commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
6555b4d1274f655d0ad7749ac93a9e6a5679c343
src/rpcblockchain.cpp
src/rpcblockchain.cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 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 "main.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = pindexBest; } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 30) { dDiff *= 256.0; nShift++; } while (nShift > 30) { dDiff /= 256.0; nShift--; } return dDiff; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); Array txs; BOOST_FOREACH(const CTransaction&tx, block.vtx) txs.push_back(tx.GetHash().GetHex()); result.push_back(Pair("tx", txs)); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); return result; } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the proof-of-work difficulty as a multiple of the minimum difficulty."); return GetDifficulty(); } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nTransactionFee = nAmount; return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblock <hash>\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex); return blockToJSON(block, pblockindex); } Value gettxoutsetinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "Returns statistics about the unspent transaction output set."); Object ret; CCoinsStats stats; if (pcoinsTip->GetStats(stats)) { ret.push_back(Pair("height", (boost::int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (boost::int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (boost::int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (boost::int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } return ret; } Value gettxout(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw runtime_error( "gettxout <txid> <n> [includemempool=true]\n" "Returns details about an unspent transaction output."); Object ret; std::string strHash = params[0].get_str(); uint256 hash(strHash); int n = params[1].get_int(); bool fMempool = true; if (params.size() > 2) fMempool = params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(*pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return Value::null; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return Value::null; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return Value::null; ret.push_back(Pair("bestblock", pcoinsTip->GetBestBlock()->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pcoinsTip->GetBestBlock()->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); Object o; ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 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 "main.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = pindexBest; } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); Array txs; BOOST_FOREACH(const CTransaction&tx, block.vtx) txs.push_back(tx.GetHash().GetHex()); result.push_back(Pair("tx", txs)); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); return result; } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the proof-of-work difficulty as a multiple of the minimum difficulty."); return GetDifficulty(); } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nTransactionFee = nAmount; return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblock <hash>\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex); return blockToJSON(block, pblockindex); } Value gettxoutsetinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "Returns statistics about the unspent transaction output set."); Object ret; CCoinsStats stats; if (pcoinsTip->GetStats(stats)) { ret.push_back(Pair("height", (boost::int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (boost::int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (boost::int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (boost::int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } return ret; } Value gettxout(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw runtime_error( "gettxout <txid> <n> [includemempool=true]\n" "Returns details about an unspent transaction output."); Object ret; std::string strHash = params[0].get_str(); uint256 hash(strHash); int n = params[1].get_int(); bool fMempool = true; if (params.size() > 2) fMempool = params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(*pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return Value::null; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return Value::null; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return Value::null; ret.push_back(Pair("bestblock", pcoinsTip->GetBestBlock()->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pcoinsTip->GetBestBlock()->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); Object o; ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; }
Update rpcblockchain.cpp
Update rpcblockchain.cpp
C++
mit
gjhiggins/fuguecoin,gjhiggins/fuguecoin,gjhiggins/fuguecoin,gjhiggins/fuguecoin,BlueDragon747/Blakecoin,MikuCoin/MikuCoin,BlueDragon747/Blakecoin,cinnamoncoin/Blakecoin,BlueDragon747/Blakecoin,BlueDragon747/Blakecoin,cinnamoncoin/Blakecoin,cinnamoncoin/Blakecoin,cinnamoncoin/Blakecoin,BlueDragon747/Blakecoin,cinnamoncoin/Blakecoin,MikuCoin/MikuCoin,MikuCoin/MikuCoin,MikuCoin/MikuCoin,gjhiggins/fuguecoin,MikuCoin/MikuCoin
ca40571886ab300232847230fff0d4a80ba7c58e
src/rpcblockchain.cpp
src/rpcblockchain.cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 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 "main.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = GetLastBlockIndex(pindexBest, false); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } double GetPoWMHashPS() { int nPoWInterval = 72; int64 nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30; CBlockIndex* pindex = pindexGenesisBlock; CBlockIndex* pindexPrevWork = pindexGenesisBlock; while (pindex) { if (pindex->IsProofOfWork()) { int64 nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime(); nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1); nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin); pindexPrevWork = pindex; } pindex = pindex->pnext; } return GetDifficulty() * 4294.967296 / nTargetSpacingWork; } double GetPoSKernelPS() { int nPoSInterval = 72; double dStakeKernelsTriedAvg = 0; int nStakesHandled = 0, nStakesTime = 0; CBlockIndex* pindex = pindexBest;; CBlockIndex* pindexPrevStake = NULL; while (pindex && nStakesHandled < nPoSInterval) { if (pindex->IsProofOfStake()) { dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0; nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0; pindexPrevStake = pindex; nStakesHandled++; } pindex = pindex->pprev; } return dStakeKernelsTriedAvg / nStakesTime; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint))); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": ""))); result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex())); result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit())); result.push_back(Pair("modifier", strprintf("%016"PRI64x, blockindex->nStakeModifier))); result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum))); Array txinfo; BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (fPrintTransactionDetail) { Object entry; entry.push_back(Pair("txid", tx.GetHash().GetHex())); TxToJSON(tx, 0, entry); txinfo.push_back(entry); } else txinfo.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txinfo)); result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end()))); return result; } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best block in the longest block chain."); return hashBestChain.GetHex(); } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the difficulty as a multiple of the minimum difficulty."); Object obj; obj.push_back(Pair("proof-of-work", GetDifficulty())); obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); return obj; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.01"); nTransactionFee = AmountFromValue(params[0]); nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } Value getblockbynumber(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <number> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-number."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; uint256 hash = *pblockindex->phashBlock; pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } // ppcoin: get information of sync-checkpoint Value getcheckpoint(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); Object result; CBlockIndex* pindexCheckpoint; result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str())); pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint]; result.push_back(Pair("height", pindexCheckpoint->nHeight)); result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str())); if (mapArgs.count("-checkpointkey")) result.push_back(Pair("checkpointmaster", true)); return result; }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 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 "main.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = GetLastBlockIndex(pindexBest, false); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } double GetPoWMHashPS() { int nPoWInterval = 72; int64 nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30; CBlockIndex* pindex = pindexGenesisBlock; CBlockIndex* pindexPrevWork = pindexGenesisBlock; while (pindex) { if (pindex->IsProofOfWork()) { int64 nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime(); nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1); nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin); pindexPrevWork = pindex; } pindex = pindex->pnext; } return GetDifficulty() * 4294.967296 / nTargetSpacingWork; } double GetPoSKernelPS() { int nPoSInterval = 72; double dStakeKernelsTriedAvg = 0; int nStakesHandled = 0, nStakesTime = 0; CBlockIndex* pindex = pindexBest;; CBlockIndex* pindexPrevStake = NULL; while (pindex && nStakesHandled < nPoSInterval) { if (pindex->IsProofOfStake()) { dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0; nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0; pindexPrevStake = pindex; nStakesHandled++; } pindex = pindex->pprev; } return dStakeKernelsTriedAvg / nStakesTime; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint))); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("blocktrust", blockindex->GetBlockTrust().GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": ""))); result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex())); result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit())); result.push_back(Pair("modifier", strprintf("%016"PRI64x, blockindex->nStakeModifier))); result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum))); Array txinfo; BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (fPrintTransactionDetail) { Object entry; entry.push_back(Pair("txid", tx.GetHash().GetHex())); TxToJSON(tx, 0, entry); txinfo.push_back(entry); } else txinfo.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txinfo)); result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end()))); return result; } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best block in the longest block chain."); return hashBestChain.GetHex(); } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the difficulty as a multiple of the minimum difficulty."); Object obj; obj.push_back(Pair("proof-of-work", GetDifficulty())); obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); return obj; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.01"); nTransactionFee = AmountFromValue(params[0]); nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } Value getblockbynumber(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <number> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-number."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; uint256 hash = *pblockindex->phashBlock; pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } // ppcoin: get information of sync-checkpoint Value getcheckpoint(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); Object result; CBlockIndex* pindexCheckpoint; result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str())); pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint]; result.push_back(Pair("height", pindexCheckpoint->nHeight)); result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str())); if (mapArgs.count("-checkpointkey")) result.push_back(Pair("checkpointmaster", true)); return result; }
add blocktrust field into block dump
RPC: add blocktrust field into block dump
C++
mit
Tranz5/bottlecaps,bottlecaps-foundation/bottlecaps,bottlecaps-foundation/bottlecaps,bottlecaps-foundation/bottlecaps,Tranz5/bottlecaps,bottlecaps-foundation/bottlecaps,Tranz5/bottlecaps,bottlecaps-foundation/bottlecaps,Tranz5/bottlecaps
5a061ffbc4ee5fb3550d4c1c991750089bc24329
automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-adaptor.cpp
automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-adaptor.cpp
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. * * 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 <toolkit-window.h> // Don't want to include the actual window.h which otherwise will be indirectly included by adaptor.h. #define DALI_WINDOW_H #include <dali/integration-api/adaptors/adaptor.h> #include <dali/integration-api/adaptors/scene-holder.h> #include <dali/public-api/object/base-object.h> #include <toolkit-adaptor-impl.h> #include <dali/integration-api/debug.h> #include <test-application.h> #include <test-render-surface.h> namespace Dali { namespace Internal { namespace Adaptor { bool Adaptor::mAvailable = false; Vector<CallbackBase*> Adaptor::mCallbacks = Vector<CallbackBase*>(); Dali::WindowContainer Adaptor::mWindows; Dali::Adaptor::WindowCreatedSignalType* Adaptor::mWindowCreatedSignal = nullptr; Dali::Adaptor& Adaptor::Get() { Dali::Adaptor* adaptor = new Dali::Adaptor; Adaptor::mAvailable = true; return *adaptor; } Dali::RenderSurfaceInterface& Adaptor::GetSurface() { Dali::RenderSurfaceInterface* renderSurface = reinterpret_cast <Dali::RenderSurfaceInterface*>( new Dali::TestRenderSurface( Dali::PositionSize( 0, 0, 480, 800 ) ) ); return *renderSurface; } Dali::WindowContainer Adaptor::GetWindows() { return Adaptor::mWindows; } Dali::Adaptor::AdaptorSignalType& Adaptor::AdaptorSignal() { Dali::Adaptor::AdaptorSignalType* signal = new Dali::Adaptor::AdaptorSignalType; return *signal; } Dali::Adaptor::WindowCreatedSignalType& Adaptor::WindowCreatedSignal() { if ( !Adaptor::mWindowCreatedSignal ) { Adaptor::mWindowCreatedSignal = new Dali::Adaptor::WindowCreatedSignalType; } return *Adaptor::mWindowCreatedSignal; } } // namespace Adaptor } // namespace Internal Adaptor& Adaptor::New( Window window ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Window window, Configuration::ContextLoss configuration ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Window window, const Dali::RenderSurfaceInterface& surface ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Window window, const Dali::RenderSurfaceInterface& surface, Configuration::ContextLoss configuration ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Dali::Integration::SceneHolder window ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Dali::Integration::SceneHolder window, Configuration::ContextLoss configuration ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Dali::Integration::SceneHolder window, const Dali::RenderSurfaceInterface& surface ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Dali::Integration::SceneHolder window, const Dali::RenderSurfaceInterface& surface, Configuration::ContextLoss configuration ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor::~Adaptor() { } void Adaptor::Start() { } void Adaptor::Pause() { } void Adaptor::Resume() { } void Adaptor::Stop() { } bool Adaptor::AddIdle( CallbackBase* callback, bool hasReturnValue ) { const bool isAvailable = IsAvailable(); if( isAvailable ) { Internal::Adaptor::Adaptor::mCallbacks.PushBack( callback ); } return isAvailable; } void Adaptor::RemoveIdle( CallbackBase* callback ) { const bool isAvailable = IsAvailable(); if( isAvailable ) { for( Vector<CallbackBase*>::Iterator it = Internal::Adaptor::Adaptor::mCallbacks.Begin(), endIt = Internal::Adaptor::Adaptor::mCallbacks.End(); it != endIt; ++it ) { if( callback == *it ) { Internal::Adaptor::Adaptor::mCallbacks.Remove( it ); return; } } } } void Adaptor::ReplaceSurface( Window window, Dali::RenderSurfaceInterface& surface ) { } void Adaptor::ReplaceSurface( Dali::Integration::SceneHolder window, Dali::RenderSurfaceInterface& surface ) { } Adaptor::AdaptorSignalType& Adaptor::ResizedSignal() { return Internal::Adaptor::Adaptor::AdaptorSignal(); } Adaptor::AdaptorSignalType& Adaptor::LanguageChangedSignal() { return Internal::Adaptor::Adaptor::AdaptorSignal(); } Adaptor::WindowCreatedSignalType& Adaptor::WindowCreatedSignal() { return Internal::Adaptor::Adaptor::WindowCreatedSignal(); } Dali::RenderSurfaceInterface& Adaptor::GetSurface() { return Internal::Adaptor::Adaptor::GetSurface(); } Dali::WindowContainer Adaptor::GetWindows() const { return Internal::Adaptor::Adaptor::GetWindows(); } Any Adaptor::GetNativeWindowHandle() { Any window; return window; } void Adaptor::ReleaseSurfaceLock() { } void Adaptor::SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender ) { } void Adaptor::SetUseHardwareVSync(bool useHardware) { } Adaptor& Adaptor::Get() { return Internal::Adaptor::Adaptor::Get(); } bool Adaptor::IsAvailable() { return Internal::Adaptor::Adaptor::mAvailable; } void Adaptor::NotifySceneCreated() { } void Adaptor::NotifyLanguageChanged() { } void Adaptor::FeedTouchPoint( TouchPoint& point, int timeStamp ) { } void Adaptor::FeedWheelEvent( WheelEvent& wheelEvent ) { } void Adaptor::FeedKeyEvent( KeyEvent& keyEvent ) { } void Adaptor::SceneCreated() { } class LogFactory : public LogFactoryInterface { public: virtual void InstallLogFunction() const { Dali::Integration::Log::LogFunction logFunction(&TestApplication::LogMessage); Dali::Integration::Log::InstallLogFunction(logFunction); } LogFactory() { } virtual ~LogFactory() { } }; LogFactory* gLogFactory = NULL; const LogFactoryInterface& Adaptor::GetLogFactory() { if( gLogFactory == NULL ) { gLogFactory = new LogFactory; } return *gLogFactory; } Adaptor::Adaptor() : mImpl( NULL ) { Dali::PositionSize win_size; win_size.width = 640; win_size.height = 800; Dali::Window window = Dali::Window::New( win_size, "" ); Internal::Adaptor::Adaptor::mWindows.push_back( window ); } } // namespace Dali
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. * * 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 <toolkit-window.h> // Don't want to include the actual window.h which otherwise will be indirectly included by adaptor.h. #define DALI_WINDOW_H #include <dali/integration-api/adaptors/adaptor.h> #include <dali/integration-api/adaptors/scene-holder.h> #include <dali/public-api/object/base-object.h> #include <toolkit-adaptor-impl.h> #include <dali/integration-api/debug.h> #include <test-application.h> #include <test-render-surface.h> namespace Dali { namespace Internal { namespace Adaptor { bool Adaptor::mAvailable = false; Vector<CallbackBase*> Adaptor::mCallbacks = Vector<CallbackBase*>(); Dali::WindowContainer Adaptor::mWindows; Dali::Adaptor::WindowCreatedSignalType* Adaptor::mWindowCreatedSignal = nullptr; Dali::Adaptor& Adaptor::Get() { Dali::Adaptor* adaptor = new Dali::Adaptor; Adaptor::mAvailable = true; return *adaptor; } Dali::RenderSurfaceInterface& Adaptor::GetSurface() { Dali::RenderSurfaceInterface* renderSurface = reinterpret_cast <Dali::RenderSurfaceInterface*>( new Dali::TestRenderSurface( Dali::PositionSize( 0, 0, 480, 800 ) ) ); return *renderSurface; } Dali::WindowContainer Adaptor::GetWindows() { return Adaptor::mWindows; } Dali::Adaptor::AdaptorSignalType& Adaptor::AdaptorSignal() { Dali::Adaptor::AdaptorSignalType* signal = new Dali::Adaptor::AdaptorSignalType; return *signal; } Dali::Adaptor::WindowCreatedSignalType& Adaptor::WindowCreatedSignal() { if ( !Adaptor::mWindowCreatedSignal ) { Adaptor::mWindowCreatedSignal = new Dali::Adaptor::WindowCreatedSignalType; } return *Adaptor::mWindowCreatedSignal; } } // namespace Adaptor } // namespace Internal Adaptor& Adaptor::New( Window window ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Window window, Configuration::ContextLoss configuration ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Window window, const Dali::RenderSurfaceInterface& surface ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Window window, const Dali::RenderSurfaceInterface& surface, Configuration::ContextLoss configuration ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Dali::Integration::SceneHolder window ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Dali::Integration::SceneHolder window, Configuration::ContextLoss configuration ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Dali::Integration::SceneHolder window, const Dali::RenderSurfaceInterface& surface ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor& Adaptor::New( Dali::Integration::SceneHolder window, const Dali::RenderSurfaceInterface& surface, Configuration::ContextLoss configuration ) { return Internal::Adaptor::Adaptor::Get(); } Adaptor::~Adaptor() { } void Adaptor::Start() { } void Adaptor::Pause() { } void Adaptor::Resume() { } void Adaptor::Stop() { } bool Adaptor::AddIdle( CallbackBase* callback, bool hasReturnValue ) { const bool isAvailable = IsAvailable(); if( isAvailable ) { Internal::Adaptor::Adaptor::mCallbacks.PushBack( callback ); } return isAvailable; } void Adaptor::RemoveIdle( CallbackBase* callback ) { const bool isAvailable = IsAvailable(); if( isAvailable ) { for( Vector<CallbackBase*>::Iterator it = Internal::Adaptor::Adaptor::mCallbacks.Begin(), endIt = Internal::Adaptor::Adaptor::mCallbacks.End(); it != endIt; ++it ) { if( callback == *it ) { Internal::Adaptor::Adaptor::mCallbacks.Remove( it ); return; } } } } void Adaptor::ReplaceSurface( Window window, Dali::RenderSurfaceInterface& surface ) { } void Adaptor::ReplaceSurface( Dali::Integration::SceneHolder window, Dali::RenderSurfaceInterface& surface ) { } Adaptor::AdaptorSignalType& Adaptor::ResizedSignal() { return Internal::Adaptor::Adaptor::AdaptorSignal(); } Adaptor::AdaptorSignalType& Adaptor::LanguageChangedSignal() { return Internal::Adaptor::Adaptor::AdaptorSignal(); } Adaptor::WindowCreatedSignalType& Adaptor::WindowCreatedSignal() { return Internal::Adaptor::Adaptor::WindowCreatedSignal(); } Dali::RenderSurfaceInterface& Adaptor::GetSurface() { return Internal::Adaptor::Adaptor::GetSurface(); } Dali::WindowContainer Adaptor::GetWindows() const { return Internal::Adaptor::Adaptor::GetWindows(); } Any Adaptor::GetNativeWindowHandle() { Any window; return window; } void Adaptor::ReleaseSurfaceLock() { } void Adaptor::SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender ) { } Adaptor& Adaptor::Get() { return Internal::Adaptor::Adaptor::Get(); } bool Adaptor::IsAvailable() { return Internal::Adaptor::Adaptor::mAvailable; } void Adaptor::NotifySceneCreated() { } void Adaptor::NotifyLanguageChanged() { } void Adaptor::FeedTouchPoint( TouchPoint& point, int timeStamp ) { } void Adaptor::FeedWheelEvent( WheelEvent& wheelEvent ) { } void Adaptor::FeedKeyEvent( KeyEvent& keyEvent ) { } void Adaptor::SceneCreated() { } class LogFactory : public LogFactoryInterface { public: virtual void InstallLogFunction() const { Dali::Integration::Log::LogFunction logFunction(&TestApplication::LogMessage); Dali::Integration::Log::InstallLogFunction(logFunction); } LogFactory() { } virtual ~LogFactory() { } }; LogFactory* gLogFactory = NULL; const LogFactoryInterface& Adaptor::GetLogFactory() { if( gLogFactory == NULL ) { gLogFactory = new LogFactory; } return *gLogFactory; } Adaptor::Adaptor() : mImpl( NULL ) { Dali::PositionSize win_size; win_size.width = 640; win_size.height = 800; Dali::Window window = Dali::Window::New( win_size, "" ); Internal::Adaptor::Adaptor::mWindows.push_back( window ); } } // namespace Dali
Remove vsync-monitor.
Remove vsync-monitor. Change-Id: I60d01620700cc0bb8ad49058d12e1e91fc5619cd
C++
apache-2.0
dalihub/dali-toolkit,dalihub/dali-toolkit,dalihub/dali-toolkit,dalihub/dali-toolkit
79c0919f2e7470543b975a689fd549d0a6f2156f
src/settingwindow.cpp
src/settingwindow.cpp
/* JaneClone - a text board site viewer for 2ch * Copyright (C) 2012-2014 Hiroyuki Nagata * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Contributor: * Hiroyuki Nagata <[email protected]> */ // -*- C++ -*- generated by wxGlade 0.6.5 on Tue May 21 00:18:19 2013 #include "settingwindow.hpp" // begin wxGlade: ::extracode // end wxGlade BEGIN_EVENT_TABLE(SettingDialog, wxDialog) // ボタンによるイベント EVT_BUTTON(ID_OnOkSetting, SettingDialog::OnQuit) EVT_BUTTON(ID_OnCancelSetting, SettingDialog::OnQuit) // ツリーコントロールでのウィンドウ描画切り替え EVT_TREE_SEL_CHANGED(ID_SettingPanelTree, SettingDialog::OnChangeSettingPanel) END_EVENT_TABLE() /** * 設定画面のコンストラクタ */ SettingDialog::SettingDialog(wxWindow* parent, int id, const wxString& title, const wxPoint& pos, const wxSize& size, long style): wxDialog(parent, id, title, pos, size, wxDEFAULT_DIALOG_STYLE) { // begin wxGlade: SettingDialog::SettingDialog bottomPanel = new wxPanel(this, wxID_ANY); splitterWindow = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_3D|wxSP_BORDER); // 左側のツリー部分 treePanel = new wxPanel(splitterWindow, wxID_ANY); settingTreeCtrl = new wxTreeCtrl(treePanel, ID_SettingPanelTree, wxDefaultPosition, wxDefaultSize, wxTR_HIDE_ROOT|wxTR_HAS_BUTTONS|wxTR_DEFAULT_STYLE|wxSUNKEN_BORDER); // 右側の設定画面部分 settingPanel = new wxPanel(splitterWindow, wxID_ANY); spacePanel = new wxPanel(bottomPanel, wxID_ANY); // OK,キャンセルボタン okButton = new wxButton(bottomPanel, ID_OnOkSetting, wxT("OK")); cancelButton = new wxButton(bottomPanel, ID_OnCancelSetting, wxT("キャンセル")); SetProperties(); DoLayout(); // end wxGlade // 初回は通信パネルを開く #ifndef __WXMAC__ wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new NetworkSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); #else // メインスレッドに更新してもらう SendUIUpdateEvent(); #endif this->SetTitle(wxT("設定 - 通信")); } /** * ウィンドウのプロパティを設定 */ void SettingDialog::SetProperties() { // begin wxGlade: SettingDialog::set_properties SetSize(wxSize(1160, 640)); // ツリーコントロールの表示内容を設定する settingTreeCtrl->AddRoot(wxEmptyString); wxTreeItemId item = settingTreeCtrl->AppendItem(settingTreeCtrl->GetRootItem(), wxT("基本")); settingTreeCtrl->AppendItem(item, wxT("通信")); settingTreeCtrl->AppendItem(item, wxT("パス")); settingTreeCtrl->AppendItem(item, wxT("動作")); settingTreeCtrl->AppendItem(item, wxT("操作")); settingTreeCtrl->AppendItem(item, wxT("タブ操作")); settingTreeCtrl->AppendItem(item, wxT("書き込み")); settingTreeCtrl->AppendItem(item, wxT("Doe")); settingTreeCtrl->AppendItem(item, wxT("その他1")); settingTreeCtrl->AppendItem(item, wxT("User")); item = settingTreeCtrl->AppendItem(settingTreeCtrl->GetRootItem(), wxT("機能")); settingTreeCtrl->AppendItem(item, wxT("ヒント")); settingTreeCtrl->AppendItem(item, wxT("あぼーん")); settingTreeCtrl->AppendItem(item, wxT("コマンド")); settingTreeCtrl->AppendItem(item, wxT("マウス")); settingTreeCtrl->AppendItem(item, wxT("検索・更新")); settingTreeCtrl->AppendItem(item, wxT("スレッド")); settingTreeCtrl->AppendItem(item, wxT("画像")); settingTreeCtrl->AppendItem(item, wxT("その他2")); item = settingTreeCtrl->AppendItem(settingTreeCtrl->GetRootItem(), wxT("外観")); settingTreeCtrl->AppendItem(item, wxT("スレ覧項目")); settingTreeCtrl->AppendItem(item, wxT("タブ")); settingTreeCtrl->AppendItem(item, wxT("スタイル")); settingTreeCtrl->AppendItem(item, wxT("色・フォント")); settingTreeCtrl->AppendItem(item, wxT("タブ色")); settingTreeCtrl->ExpandAll(); // end wxGlade } /** * レイアウトの設定 */ void SettingDialog::DoLayout() { // begin wxGlade: SettingDialog::do_layout wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); wxBoxSizer* bottomSizer = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* treeVbox = new wxBoxSizer(wxVERTICAL); treeVbox->Add(settingTreeCtrl, 1, wxEXPAND, 0); treePanel->SetSizer(treeVbox); splitterWindow->SplitVertically(treePanel, settingPanel, 200); vbox->Add(splitterWindow, 1, wxEXPAND, 0); bottomSizer->Add(spacePanel, 1, wxEXPAND, 0); bottomSizer->Add(okButton, 0, 0, 5); bottomSizer->Add(cancelButton, 0, 0, 5); bottomPanel->SetSizer(bottomSizer); vbox->Add(bottomPanel, 0, wxTOP|wxEXPAND, 0); SetSizer(vbox); Layout(); // end wxGlade } /** * 設定パネルの入力値 保存 */ void SettingDialog::SaveConfig(const wxString& title) { if ( title.Contains(wxT("User"))) { if ( UserSettingPanel* user = dynamic_cast<UserSettingPanel*> (wxWindow::FindWindowById(ID_UserSettingPanel, settingPanel))) { // ユーザー設定パネル user->save_properties(); } } else if (title.Contains(wxT("通信"))) { if ( NetworkSettingPanel* network = dynamic_cast<NetworkSettingPanel*> (wxWindow::FindWindowById(ID_NetworkPanel, settingPanel))) { // 設定パネル network->save_properties(); } } } /** * 設定画面のクローズ */ void SettingDialog::OnQuit(wxCommandEvent& event) { if (settingPanel) { // 設定の保存 const wxString title = this->GetTitle(); SaveConfig(title); } this->EndModal(0); } /** * ツリーコントロールでのウィンドウ描画切り替え */ void SettingDialog::OnChangeSettingPanel(wxTreeEvent& event) { // 選択されたTreeItemIdのインスタンス const wxTreeItemId pushedTree = event.GetItem(); // 板名をwxStringで取得する const wxString itemStr(settingTreeCtrl->GetItemText(pushedTree)); // 取得不可なものであればリターン if (itemStr == wxEmptyString) return; if (settingPanel) { // settingPanel内の情報を保存する const wxTreeItemId oldPushedTree = event.GetOldItem(); const wxString oldItemStr(settingTreeCtrl->GetItemText(oldPushedTree)); if (oldItemStr != wxEmptyString) { SaveConfig(oldItemStr); } // settingPanelのインスタンスが存在するならばDestroy // 子ウィンドウを殺す settingPanel->DestroyChildren(); } if (itemStr == wxT("通信")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new NetworkSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("パス")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new PathSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("動作")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new BehaviorPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("操作")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new OperationPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("タブ操作")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new TabControlSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("書き込み")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new KakikomiPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("Doe")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new DoePanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("その他1")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new OtherSettingPanelOne(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("User")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new UserSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("色・フォント")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new ColorFontSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("タブ色")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new TabColorSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("ヒント")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(wxXmlResource::Get()->LoadPanel(settingPanel, wxT("hint_panel"))); settingPanel->SetSizer(vbox); } settingPanel->GetSizer()->Fit(settingPanel); // ウィンドウのタイトルを変える this->SetTitle(wxT("設定 - ") + itemStr); }
/* JaneClone - a text board site viewer for 2ch * Copyright (C) 2012-2014 Hiroyuki Nagata * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Contributor: * Hiroyuki Nagata <[email protected]> */ // -*- C++ -*- generated by wxGlade 0.6.5 on Tue May 21 00:18:19 2013 #include "settingwindow.hpp" // begin wxGlade: ::extracode // end wxGlade BEGIN_EVENT_TABLE(SettingDialog, wxDialog) // ボタンによるイベント EVT_BUTTON(ID_OnOkSetting, SettingDialog::OnQuit) EVT_BUTTON(ID_OnCancelSetting, SettingDialog::OnQuit) // ツリーコントロールでのウィンドウ描画切り替え EVT_TREE_SEL_CHANGED(ID_SettingPanelTree, SettingDialog::OnChangeSettingPanel) END_EVENT_TABLE() /** * 設定画面のコンストラクタ */ SettingDialog::SettingDialog(wxWindow* parent, int id, const wxString& title, const wxPoint& pos, const wxSize& size, long style): wxDialog(parent, id, title, pos, size, wxDEFAULT_DIALOG_STYLE) { // begin wxGlade: SettingDialog::SettingDialog bottomPanel = new wxPanel(this, wxID_ANY); splitterWindow = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_3D|wxSP_BORDER); // 左側のツリー部分 treePanel = new wxPanel(splitterWindow, wxID_ANY); settingTreeCtrl = new wxTreeCtrl(treePanel, ID_SettingPanelTree, wxDefaultPosition, wxDefaultSize, wxTR_HIDE_ROOT|wxTR_HAS_BUTTONS|wxTR_DEFAULT_STYLE|wxSUNKEN_BORDER); // 右側の設定画面部分 settingPanel = new wxPanel(splitterWindow, wxID_ANY); spacePanel = new wxPanel(bottomPanel, wxID_ANY); // OK,キャンセルボタン okButton = new wxButton(bottomPanel, ID_OnOkSetting, wxT("OK")); cancelButton = new wxButton(bottomPanel, ID_OnCancelSetting, wxT("キャンセル")); SetProperties(); DoLayout(); // end wxGlade // 初回は通信パネルを開く #ifndef __WXMAC__ wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new NetworkSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); #else // メインスレッドに更新してもらう SendUIUpdateEvent(); #endif this->SetTitle(wxT("設定 - 通信")); } /** * ウィンドウのプロパティを設定 */ void SettingDialog::SetProperties() { // begin wxGlade: SettingDialog::set_properties SetSize(wxSize(1160, 640)); // ツリーコントロールの表示内容を設定する settingTreeCtrl->AddRoot(wxEmptyString); wxTreeItemId item = settingTreeCtrl->AppendItem(settingTreeCtrl->GetRootItem(), wxT("基本")); settingTreeCtrl->AppendItem(item, wxT("通信")); settingTreeCtrl->AppendItem(item, wxT("パス")); settingTreeCtrl->AppendItem(item, wxT("動作")); settingTreeCtrl->AppendItem(item, wxT("操作")); settingTreeCtrl->AppendItem(item, wxT("タブ操作")); settingTreeCtrl->AppendItem(item, wxT("書き込み")); settingTreeCtrl->AppendItem(item, wxT("Doe")); settingTreeCtrl->AppendItem(item, wxT("その他1")); settingTreeCtrl->AppendItem(item, wxT("User")); item = settingTreeCtrl->AppendItem(settingTreeCtrl->GetRootItem(), wxT("機能")); settingTreeCtrl->AppendItem(item, wxT("ヒント")); settingTreeCtrl->AppendItem(item, wxT("あぼーん")); settingTreeCtrl->AppendItem(item, wxT("コマンド")); settingTreeCtrl->AppendItem(item, wxT("マウス")); settingTreeCtrl->AppendItem(item, wxT("検索・更新")); settingTreeCtrl->AppendItem(item, wxT("スレッド")); settingTreeCtrl->AppendItem(item, wxT("画像")); settingTreeCtrl->AppendItem(item, wxT("その他2")); item = settingTreeCtrl->AppendItem(settingTreeCtrl->GetRootItem(), wxT("外観")); settingTreeCtrl->AppendItem(item, wxT("スレ覧項目")); settingTreeCtrl->AppendItem(item, wxT("タブ")); settingTreeCtrl->AppendItem(item, wxT("スタイル")); settingTreeCtrl->AppendItem(item, wxT("色・フォント")); settingTreeCtrl->AppendItem(item, wxT("タブ色")); settingTreeCtrl->ExpandAll(); // end wxGlade } /** * レイアウトの設定 */ void SettingDialog::DoLayout() { // begin wxGlade: SettingDialog::do_layout wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); wxBoxSizer* bottomSizer = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* treeVbox = new wxBoxSizer(wxVERTICAL); treeVbox->Add(settingTreeCtrl, 1, wxEXPAND, 0); treePanel->SetSizer(treeVbox); splitterWindow->SplitVertically(treePanel, settingPanel, 200); vbox->Add(splitterWindow, 1, wxEXPAND, 0); bottomSizer->Add(spacePanel, 1, wxEXPAND, 0); bottomSizer->Add(okButton, 0, 0, 5); bottomSizer->Add(cancelButton, 0, 0, 5); bottomPanel->SetSizer(bottomSizer); vbox->Add(bottomPanel, 0, wxTOP|wxEXPAND, 0); SetSizer(vbox); Layout(); // end wxGlade } /** * 設定パネルの入力値 保存 */ void SettingDialog::SaveConfig(const wxString& title) { if ( title.Contains(wxT("User"))) { if ( UserSettingPanel* user = dynamic_cast<UserSettingPanel*> (wxWindow::FindWindowById(ID_UserSettingPanel, settingPanel))) { // ユーザー設定パネル user->save_properties(); } } else if (title.Contains(wxT("通信"))) { if ( NetworkSettingPanel* network = dynamic_cast<NetworkSettingPanel*> (wxWindow::FindWindowById(ID_NetworkPanel, settingPanel))) { // 設定パネル network->save_properties(); } } } /** * 設定画面のクローズ */ void SettingDialog::OnQuit(wxCommandEvent& event) { if (settingPanel) { // 設定の保存 const wxString title = this->GetTitle(); SaveConfig(title); } this->EndModal(0); } /** * ツリーコントロールでのウィンドウ描画切り替え */ void SettingDialog::OnChangeSettingPanel(wxTreeEvent& event) { // 選択されたTreeItemIdのインスタンス const wxTreeItemId pushedTree = event.GetItem(); // 板名をwxStringで取得する const wxString itemStr(settingTreeCtrl->GetItemText(pushedTree)); // 取得不可なものであればリターン if (itemStr == wxEmptyString) return; if (settingPanel) { // settingPanel内の情報を保存する const wxTreeItemId oldPushedTree = event.GetOldItem(); const wxString oldItemStr(settingTreeCtrl->GetItemText(oldPushedTree)); if (oldItemStr != wxEmptyString) { SaveConfig(oldItemStr); } // settingPanelのインスタンスが存在するならばDestroy // 子ウィンドウを殺す settingPanel->DestroyChildren(); } if (itemStr == wxT("通信")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new NetworkSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("パス")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new PathSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("動作")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new BehaviorPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("操作")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new OperationPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("タブ操作")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new TabControlSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("書き込み")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new KakikomiPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("Doe")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new DoePanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("その他1")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new OtherSettingPanelOne(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("User")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new UserSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("色・フォント")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new ColorFontSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("タブ色")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(new TabColorSettingPanel(settingPanel)); settingPanel->SetSizer(vbox); } else if (itemStr == wxT("ヒント")) { wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); vbox->Add(wxXmlResource::Get()->LoadPanel(settingPanel, wxString("hint_panel"))); settingPanel->SetSizer(vbox); } settingPanel->GetSizer()->Fit(settingPanel); // ウィンドウのタイトルを変える this->SetTitle(wxT("設定 - ") + itemStr); }
Fix wx-2.8 and wx-3.0 's wxString diff.
Fix wx-2.8 and wx-3.0 's wxString diff.
C++
lgpl-2.1
Hiroyuki-Nagata/XrossBoard,Hiroyuki-Nagata/XrossBoard,Hiroyuki-Nagata/XrossBoard,Hiroyuki-Nagata/XrossBoard,Hiroyuki-Nagata/XrossBoard,Hiroyuki-Nagata/XrossBoard,Hiroyuki-Nagata/XrossBoard
73a02ac64c29c64df31f06e92de1b39b2c61ee31
plugins/rabidRabbit/rabidRabbit.cpp
plugins/rabidRabbit/rabidRabbit.cpp
// rabidRabbit.cpp : Defines the entry point for the DLL application. #include "bzfsAPI.h" #include <string> #include <vector> #include <map> #include <math.h> BZ_GET_PLUGIN_VERSION class RabidRabbitHandler : public bz_CustomMapObjectHandler { public: virtual bool handle ( bzApiString object, bz_CustomMapObjectInfo *data ); }; RabidRabbitHandler rabidrabbithandler; class RabidRabbitEventHandler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; RabidRabbitEventHandler rabidrabbiteventHandler; BZF_PLUGIN_CALL int bz_Load (const char* /*commandLineParameter*/){ bz_debugMessage(4,"rabidRabbit plugin loaded"); bz_registerCustomMapObject("RABIDRABBITZONE",&rabidrabbithandler); bz_registerCustomMapObject("RRSOUNDOFF",&rabidrabbithandler); bz_registerEvent(bz_eTickEvent,&rabidrabbiteventHandler); return 0; } BZF_PLUGIN_CALL int bz_Unload (void){ bz_removeEvent(bz_eTickEvent,&rabidrabbiteventHandler); bz_debugMessage(4,"rabidRabbit plugin unloaded"); bz_removeCustomMapObject("RABIDRABBITZONE"); bz_removeCustomMapObject("RRSOUNDOFF"); return 0; } class RRZoneInfo { public: RRZoneInfo() { currentKillZone = 0; rabbitNotifiedWrongZone = false; rabbitNotifiedWrongZoneNum = 0; soundEnabled = true; } int currentKillZone, rabbitNotifiedWrongZoneNum; bool rabbitNotifiedWrongZone, soundEnabled; }; RRZoneInfo rrzoneinfo; class RabidRabbitZone { public: RabidRabbitZone() { zonekillhunter = false; box = false; xMax = xMin = yMax = yMin = zMax = zMin = rad = 0; WW = ""; WWLifetime = 0; WWPosition[0] = 0; WWPosition[1] = 0; WWPosition[2] = 0; WWTilt = 0; WWDirection = 0; WWShotID = 0; WWDT = 0; WWRepeat = 0.5; WWFired = false; WWLastFired = 0; pi = 3.14159265358979323846; } bool zonekillhunter; bool box; float xMax,xMin,yMax,yMin,zMax,zMin; float rad; bzApiString WW; float WWLifetime, WWPosition[3], WWTilt, WWDirection, WWDT; double pi, WWLastFired, WWRepeat; bool WWFired; int WWShotID; std::string playermessage; std::string servermessage; bool pointIn ( float pos[3] ) { if ( box ) { if ( pos[0] > xMax || pos[0] < xMin ) return false; if ( pos[1] > yMax || pos[1] < yMin ) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } else { float vec[3]; vec[0] = pos[0]-xMax; vec[1] = pos[1]-yMax; vec[2] = pos[2]-zMax; float dist = sqrt(vec[0]*vec[0]+vec[1]*vec[1]); if ( dist > rad) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } return true; } }; std::vector <RabidRabbitZone> zoneList; bool RabidRabbitHandler::handle ( bzApiString object, bz_CustomMapObjectInfo *data ) { if (object == "RRSOUNDOFF") rrzoneinfo.soundEnabled = false; if (object != "RABIDRABBITZONE" || !data) return false; RabidRabbitZone newZone; // parse all the chunks for ( unsigned int i = 0; i < data->data.size(); i++ ) { std::string line = data->data.get(i).c_str(); bzAPIStringList *nubs = bz_newStringList(); nubs->tokenize(line.c_str()," ",0,true); if ( nubs->size() > 0) { std::string key = bz_toupper(nubs->get(0).c_str()); if ( key == "BBOX" && nubs->size() > 6) { newZone.box = true; newZone.xMin = (float)atof(nubs->get(1).c_str()); newZone.xMax = (float)atof(nubs->get(2).c_str()); newZone.yMin = (float)atof(nubs->get(3).c_str()); newZone.yMax = (float)atof(nubs->get(4).c_str()); newZone.zMin = (float)atof(nubs->get(5).c_str()); newZone.zMax = (float)atof(nubs->get(6).c_str()); } else if ( key == "CYLINDER" && nubs->size() > 5) { newZone.box = false; newZone.rad = (float)atof(nubs->get(5).c_str()); newZone.xMax =(float)atof(nubs->get(1).c_str()); newZone.yMax =(float)atof(nubs->get(2).c_str()); newZone.zMin =(float)atof(nubs->get(3).c_str()); newZone.zMax =(float)atof(nubs->get(4).c_str()); } else if ( key == "RRZONEWW" && nubs->size() > 10) { newZone.WW = nubs->get(1); newZone.WWLifetime = (float)atof(nubs->get(2).c_str()); newZone.WWPosition[0] = (float)atof(nubs->get(3).c_str()); newZone.WWPosition[1] = (float)atof(nubs->get(4).c_str()); newZone.WWPosition[2] = (float)atof(nubs->get(5).c_str()); newZone.WWTilt = (float)atof(nubs->get(6).c_str()); newZone.WWTilt = (newZone.WWTilt / 360) * (2 * (float)newZone.pi); newZone.WWDirection = (float)atof(nubs->get(7).c_str()); newZone.WWDirection = (newZone.WWDirection / 360) * (2 * (float)newZone.pi); newZone.WWShotID = (int)atoi(nubs->get(8).c_str()); newZone.WWDT = (float)atof(nubs->get(9).c_str()); newZone.WWRepeat = (float)atof(nubs->get(10).c_str()); } else if ( key == "SERVERMESSAGE" && nubs->size() > 1 ) { newZone.servermessage = nubs->get(1).c_str(); } else if ( key == "ZONEKILLHUNTER" ) { if (nubs->size() > 1) newZone.playermessage = nubs->get(1).c_str(); newZone.zonekillhunter = true; } } bz_deleteStringList(nubs); } zoneList.push_back(newZone); bz_setMaxWaitTime ( (float)0.1 ); return true; } void killAllHunters(std::string messagepass) { bzAPIIntList *playerList = bz_newIntList(); bz_getPlayerIndexList ( playerList ); for ( unsigned int i = 0; i < playerList->size(); i++ ){ bz_PlayerRecord *player = bz_getPlayerByIndex(playerList->operator[](i)); if (player) { if (player->team != eRabbitTeam) { bz_killPlayer(player->playerID, true, BZ_SERVER); bz_sendTextMessage (BZ_SERVER, player->playerID, messagepass.c_str()); if (rrzoneinfo.soundEnabled) bz_sendPlayCustomLocalSound(player->playerID,"flag_lost"); } if (player->team == eRabbitTeam && rrzoneinfo.soundEnabled) bz_sendPlayCustomLocalSound(player->playerID,"flag_won"); } bz_freePlayerRecord(player); } bz_deleteIntList(playerList); return; } void RabidRabbitEventHandler::process ( bz_EventData *eventData ) { if ((eventData->eventType != bz_eTickEvent) || (zoneList.size() < 2)) return; for ( unsigned int i = 0; i < zoneList.size(); i++ ) { if (!zoneList[i].WWFired && rrzoneinfo.currentKillZone == i) { bz_fireWorldWep (zoneList[i].WW.c_str(),zoneList[i].WWLifetime,BZ_SERVER,zoneList[i].WWPosition,zoneList[i].WWTilt,zoneList[i].WWDirection,zoneList[i].WWShotID,zoneList[i].WWDT); zoneList[i].WWFired = true; zoneList[i].WWLastFired = bz_getCurrentTime(); } else { if ((bz_getCurrentTime() - zoneList[i].WWLastFired) > zoneList[i].WWRepeat) zoneList[i].WWFired = false; } } bzAPIIntList *playerList = bz_newIntList(); bz_getPlayerIndexList ( playerList ); for ( unsigned int h = 0; h < playerList->size(); h++ ) { bz_PlayerRecord *player = bz_getPlayerByIndex(playerList->operator[](h)); if (player){ for ( unsigned int i = 0; i < zoneList.size(); i++ ) { if (zoneList[i].pointIn(player->pos) && player->spawned && player->team == eRabbitTeam && rrzoneinfo.currentKillZone != i && !rrzoneinfo.rabbitNotifiedWrongZone) { bz_sendTextMessage(BZ_SERVER,player->playerID,"You are not in the current Rabid Rabbit zone - try another."); rrzoneinfo.rabbitNotifiedWrongZone = true; rrzoneinfo.rabbitNotifiedWrongZoneNum = i; } if (!zoneList[i].pointIn(player->pos) && player->spawned && player->team == eRabbitTeam && rrzoneinfo.rabbitNotifiedWrongZone && rrzoneinfo.rabbitNotifiedWrongZoneNum == i) rrzoneinfo.rabbitNotifiedWrongZone = false; if (zoneList[i].pointIn(player->pos) && player->spawned && player->team == eRabbitTeam && rrzoneinfo.currentKillZone == i) { killAllHunters(zoneList[i].servermessage); rrzoneinfo.rabbitNotifiedWrongZone = true; rrzoneinfo.rabbitNotifiedWrongZoneNum = i; if (i == (zoneList.size() - 1)) rrzoneinfo.currentKillZone = 0; else rrzoneinfo.currentKillZone++; rrzoneinfo.rabbitNotifiedWrongZone = true; rrzoneinfo.rabbitNotifiedWrongZoneNum = i; } if (zoneList[i].pointIn(player->pos) && player->spawned && player->team != eRabbitTeam && zoneList[i].zonekillhunter) { bz_killPlayer(player->playerID, true, BZ_SERVER); bz_sendTextMessage (BZ_SERVER, player->playerID, zoneList[i].playermessage.c_str()); } } } bz_freePlayerRecord(player); } bz_deleteIntList(playerList); return; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
// rabidRabbit.cpp : Defines the entry point for the DLL application. #include "bzfsAPI.h" #include <string> #include <vector> #include <map> #include <math.h> BZ_GET_PLUGIN_VERSION class RabidRabbitHandler : public bz_CustomMapObjectHandler { public: virtual bool handle ( bzApiString object, bz_CustomMapObjectInfo *data ); }; RabidRabbitHandler rabidrabbithandler; class RabidRabbitEventHandler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; RabidRabbitEventHandler rabidrabbiteventHandler; class RabidRabbitDieEventHandler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; RabidRabbitDieEventHandler rabidrabbitdieeventhandler; BZF_PLUGIN_CALL int bz_Load (const char* /*commandLineParameter*/){ bz_debugMessage(4,"rabidRabbit plugin loaded"); bz_registerCustomMapObject("RABIDRABBITZONE",&rabidrabbithandler); bz_registerCustomMapObject("RRSOUNDOFF",&rabidrabbithandler); bz_registerCustomMapObject("RRCYCLEONDIE",&rabidrabbithandler); bz_registerEvent(bz_eTickEvent,&rabidrabbiteventHandler); bz_registerEvent(bz_ePlayerDieEvent ,&rabidrabbitdieeventhandler); return 0; } BZF_PLUGIN_CALL int bz_Unload (void){ bz_removeEvent(bz_eTickEvent,&rabidrabbiteventHandler); bz_removeEvent(bz_ePlayerDieEvent,&rabidrabbitdieeventhandler); bz_removeCustomMapObject("RABIDRABBITZONE"); bz_removeCustomMapObject("RRSOUNDOFF"); bz_removeCustomMapObject("RRCYCLEONDIE"); bz_debugMessage(4,"rabidRabbit plugin unloaded"); return 0; } class RRZoneInfo { public: RRZoneInfo() { currentKillZone = 0; rabbitNotifiedWrongZone = false; rabbitNotifiedWrongZoneNum = 0; soundEnabled = true; cycleOnDie = false; } int currentKillZone, rabbitNotifiedWrongZoneNum; bool rabbitNotifiedWrongZone, soundEnabled, cycleOnDie; }; RRZoneInfo rrzoneinfo; class RabidRabbitZone { public: RabidRabbitZone() { zonekillhunter = false; box = false; xMax = xMin = yMax = yMin = zMax = zMin = rad = 0; WW = ""; WWLifetime = 0; WWPosition[0] = 0; WWPosition[1] = 0; WWPosition[2] = 0; WWTilt = 0; WWDirection = 0; WWShotID = 0; WWDT = 0; WWRepeat = 0.5; WWFired = false; WWLastFired = 0; pi = 3.14159265358979323846; } bool zonekillhunter; bool box; float xMax,xMin,yMax,yMin,zMax,zMin; float rad; bzApiString WW; float WWLifetime, WWPosition[3], WWTilt, WWDirection, WWDT; double pi, WWLastFired, WWRepeat; bool WWFired; int WWShotID; std::string playermessage; std::string servermessage; bool pointIn ( float pos[3] ) { if ( box ) { if ( pos[0] > xMax || pos[0] < xMin ) return false; if ( pos[1] > yMax || pos[1] < yMin ) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } else { float vec[3]; vec[0] = pos[0]-xMax; vec[1] = pos[1]-yMax; vec[2] = pos[2]-zMax; float dist = sqrt(vec[0]*vec[0]+vec[1]*vec[1]); if ( dist > rad) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } return true; } }; std::vector <RabidRabbitZone> zoneList; bool RabidRabbitHandler::handle ( bzApiString object, bz_CustomMapObjectInfo *data ) { if (object == "RRSOUNDOFF") rrzoneinfo.soundEnabled = false; if (object == "RRCYCLEONDIE") rrzoneinfo.cycleOnDie = true; if (object != "RABIDRABBITZONE" || !data) return false; RabidRabbitZone newZone; // parse all the chunks for ( unsigned int i = 0; i < data->data.size(); i++ ) { std::string line = data->data.get(i).c_str(); bzAPIStringList *nubs = bz_newStringList(); nubs->tokenize(line.c_str()," ",0,true); if ( nubs->size() > 0) { std::string key = bz_toupper(nubs->get(0).c_str()); if ( key == "BBOX" && nubs->size() > 6) { newZone.box = true; newZone.xMin = (float)atof(nubs->get(1).c_str()); newZone.xMax = (float)atof(nubs->get(2).c_str()); newZone.yMin = (float)atof(nubs->get(3).c_str()); newZone.yMax = (float)atof(nubs->get(4).c_str()); newZone.zMin = (float)atof(nubs->get(5).c_str()); newZone.zMax = (float)atof(nubs->get(6).c_str()); } else if ( key == "CYLINDER" && nubs->size() > 5) { newZone.box = false; newZone.rad = (float)atof(nubs->get(5).c_str()); newZone.xMax =(float)atof(nubs->get(1).c_str()); newZone.yMax =(float)atof(nubs->get(2).c_str()); newZone.zMin =(float)atof(nubs->get(3).c_str()); newZone.zMax =(float)atof(nubs->get(4).c_str()); } else if ( key == "RRZONEWW" && nubs->size() > 10) { newZone.WW = nubs->get(1); newZone.WWLifetime = (float)atof(nubs->get(2).c_str()); newZone.WWPosition[0] = (float)atof(nubs->get(3).c_str()); newZone.WWPosition[1] = (float)atof(nubs->get(4).c_str()); newZone.WWPosition[2] = (float)atof(nubs->get(5).c_str()); newZone.WWTilt = (float)atof(nubs->get(6).c_str()); newZone.WWTilt = (newZone.WWTilt / 360) * (2 * (float)newZone.pi); newZone.WWDirection = (float)atof(nubs->get(7).c_str()); newZone.WWDirection = (newZone.WWDirection / 360) * (2 * (float)newZone.pi); newZone.WWShotID = (int)atoi(nubs->get(8).c_str()); newZone.WWDT = (float)atof(nubs->get(9).c_str()); newZone.WWRepeat = (float)atof(nubs->get(10).c_str()); } else if ( key == "SERVERMESSAGE" && nubs->size() > 1 ) { newZone.servermessage = nubs->get(1).c_str(); } else if ( key == "ZONEKILLHUNTER" ) { if (nubs->size() > 1) newZone.playermessage = nubs->get(1).c_str(); newZone.zonekillhunter = true; } } bz_deleteStringList(nubs); } zoneList.push_back(newZone); bz_setMaxWaitTime ( (float)0.1 ); return true; } void killAllHunters(std::string messagepass) { bzAPIIntList *playerList = bz_newIntList(); bz_getPlayerIndexList ( playerList ); for ( unsigned int i = 0; i < playerList->size(); i++ ){ bz_PlayerRecord *player = bz_getPlayerByIndex(playerList->operator[](i)); if (player) { if (player->team != eRabbitTeam) { bz_killPlayer(player->playerID, true, BZ_SERVER); bz_sendTextMessage (BZ_SERVER, player->playerID, messagepass.c_str()); if (rrzoneinfo.soundEnabled) bz_sendPlayCustomLocalSound(player->playerID,"flag_lost"); } if (player->team == eRabbitTeam && rrzoneinfo.soundEnabled && bz_getTeamCount(eHunterTeam) > 0) bz_sendPlayCustomLocalSound(player->playerID,"flag_won"); } bz_freePlayerRecord(player); } bz_deleteIntList(playerList); return; } void RabidRabbitEventHandler::process ( bz_EventData *eventData ) { if ((eventData->eventType != bz_eTickEvent) || (zoneList.size() < 2)) return; for ( unsigned int i = 0; i < zoneList.size(); i++ ) { if (!zoneList[i].WWFired && rrzoneinfo.currentKillZone == i) { bz_fireWorldWep (zoneList[i].WW.c_str(),zoneList[i].WWLifetime,BZ_SERVER,zoneList[i].WWPosition,zoneList[i].WWTilt,zoneList[i].WWDirection,zoneList[i].WWShotID,zoneList[i].WWDT); zoneList[i].WWFired = true; zoneList[i].WWLastFired = bz_getCurrentTime(); } else { if ((bz_getCurrentTime() - zoneList[i].WWLastFired) > zoneList[i].WWRepeat) zoneList[i].WWFired = false; } } bzAPIIntList *playerList = bz_newIntList(); bz_getPlayerIndexList ( playerList ); for ( unsigned int h = 0; h < playerList->size(); h++ ) { bz_PlayerRecord *player = bz_getPlayerByIndex(playerList->operator[](h)); if (player){ for ( unsigned int i = 0; i < zoneList.size(); i++ ) { if (zoneList[i].pointIn(player->pos) && player->spawned && player->team == eRabbitTeam && rrzoneinfo.currentKillZone != i && !rrzoneinfo.rabbitNotifiedWrongZone) { bz_sendTextMessage(BZ_SERVER,player->playerID,"You are not in the current Rabid Rabbit zone - try another."); rrzoneinfo.rabbitNotifiedWrongZone = true; rrzoneinfo.rabbitNotifiedWrongZoneNum = i; } if (!zoneList[i].pointIn(player->pos) && player->spawned && player->team == eRabbitTeam && rrzoneinfo.rabbitNotifiedWrongZone && rrzoneinfo.rabbitNotifiedWrongZoneNum == i) rrzoneinfo.rabbitNotifiedWrongZone = false; if (zoneList[i].pointIn(player->pos) && player->spawned && player->team == eRabbitTeam && rrzoneinfo.currentKillZone == i && bz_getTeamCount(eHunterTeam) > 0) { killAllHunters(zoneList[i].servermessage); rrzoneinfo.rabbitNotifiedWrongZone = true; rrzoneinfo.rabbitNotifiedWrongZoneNum = i; if (i == (zoneList.size() - 1)) rrzoneinfo.currentKillZone = 0; else rrzoneinfo.currentKillZone++; rrzoneinfo.rabbitNotifiedWrongZone = true; rrzoneinfo.rabbitNotifiedWrongZoneNum = i; } if (zoneList[i].pointIn(player->pos) && player->spawned && player->team != eRabbitTeam && zoneList[i].zonekillhunter) { bz_killPlayer(player->playerID, true, BZ_SERVER); bz_sendTextMessage (BZ_SERVER, player->playerID, zoneList[i].playermessage.c_str()); } } } bz_freePlayerRecord(player); } bz_deleteIntList(playerList); return; } void RabidRabbitDieEventHandler::process ( bz_EventData *eventData ) { if (eventData->eventType != bz_ePlayerDieEvent ) return; bz_PlayerDieEventData *DieData = (bz_PlayerDieEventData*)eventData; if (rrzoneinfo.cycleOnDie && DieData->team == eRabbitTeam) { int i = rrzoneinfo.currentKillZone; if (i == (zoneList.size() - 1)) rrzoneinfo.currentKillZone = 0; else rrzoneinfo.currentKillZone++; } return; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
Add new code from LouMan that changes the rabbit hole when the rabbit dies
Add new code from LouMan that changes the rabbit hole when the rabbit dies git-svn-id: c0942edff5350604e2827ab28bdfcfa5200fadee@15672 08b3d480-bf2c-0410-a26f-811ee3361c24
C++
lgpl-2.1
adamsdadakaeti/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,khonkhortisan/bzflag,adamsdadakaeti/bzflag,adamsdadakaeti/bzflag,adamsdadakaeti/bzflag,khonkhortisan/bzflag,khonkhortisan/bzflag,adamsdadakaeti/bzflag,adamsdadakaeti/bzflag,kongr45gpen/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,kongr45gpen/bzflag,kongr45gpen/bzflag,kongr45gpen/bzflag,adamsdadakaeti/bzflag
97e0f1d0d642388cc615f4a2c0977fed27164752
src/simulator.cpp
src/simulator.cpp
/* * Copyright (C) 2014-2015 Rico Antonio Felix * * 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. */ /* * @author Rico Antonio Felix <[email protected]> */ /* * Local Dependency */ #include "tv.hpp" int main(int argc, char **argv) { namespace CSP = compuSUAVE_Professional; CSP::TV bedroom; CSP::Remote::toggle_mode(bedroom); CSP::Remote::change_channel(bedroom, 40); CSP::Remote::display_settings(bedroom); return 0; }
/* * Copyright (C) 2014-2015 Rico Antonio Felix * * 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. */ /* * @author Rico Antonio Felix <[email protected]> */ /* * Local Dependency */ #include "tv.hpp" int main(int argc, char **argv) { namespace CSP = compuSUAVE_Professional; CSP::TV bedroom; CSP::Remote::toggle_mode(bedroom); CSP::Remote::change_channel(bedroom, 40); CSP::Remote::display_settings(bedroom); return 0; }
Update simulator.cpp
Update simulator.cpp
C++
apache-2.0
RicoAntonioFelix/TELEVISION-SIMULATOR
f3e00d97c5d1f197a51c3f08be2b7cc9a7019fc3
src/declarativewebpage.cpp
src/declarativewebpage.cpp
/**************************************************************************** ** ** Copyright (C) 2014 Jolla Ltd. ** Contact: Raine Makelainen <[email protected]> ** ****************************************************************************/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "declarativewebpage.h" #include "declarativewebcontainer.h" #include <QtConcurrent> #include <QStandardPaths> static const QString gFullScreenMessage("embed:fullscreenchanged"); static const QString gDomContentLoadedMessage("embed:domcontentloaded"); DeclarativeWebPage::DeclarativeWebPage(QQuickItem *parent) : QuickMozView(parent) , m_container(0) , m_tabId(0) , m_viewReady(false) , m_loaded(false) , m_userHasDraggedWhileLoading(false) , m_fullscreen(false) , m_forcedChrome(false) , m_domContentLoaded(false) , m_urlHasChanged(false) , m_backForwardNavigation(false) { connect(this, SIGNAL(viewInitialized()), this, SLOT(onViewInitialized())); connect(this, SIGNAL(recvAsyncMessage(const QString, const QVariant)), this, SLOT(onRecvAsyncMessage(const QString&, const QVariant&))); connect(&m_grabWritter, SIGNAL(finished()), this, SLOT(grabWritten())); connect(this, SIGNAL(contentHeightChanged()), this, SLOT(resetHeight())); connect(this, SIGNAL(scrollableOffsetChanged()), this, SLOT(resetHeight())); } DeclarativeWebPage::~DeclarativeWebPage() { m_grabWritter.cancel(); m_grabWritter.waitForFinished(); m_grabResult.clear(); m_thumbnailResult.clear(); } DeclarativeWebContainer *DeclarativeWebPage::container() const { return m_container; } void DeclarativeWebPage::setContainer(DeclarativeWebContainer *container) { if (m_container != container) { m_container = container; emit containerChanged(); } } int DeclarativeWebPage::tabId() const { return m_tabId; } void DeclarativeWebPage::setTabId(int tabId) { if (m_tabId != tabId) { m_tabId = tabId; emit tabIdChanged(); } } bool DeclarativeWebPage::domContentLoaded() const { return m_domContentLoaded; } bool DeclarativeWebPage::urlHasChanged() const { return m_urlHasChanged; } void DeclarativeWebPage::setUrlHasChanged(bool urlHasChanged) { m_urlHasChanged = urlHasChanged; } bool DeclarativeWebPage::backForwardNavigation() const { return m_backForwardNavigation; } void DeclarativeWebPage::setBackForwardNavigation(bool backForwardNavigation) { m_backForwardNavigation = backForwardNavigation; } bool DeclarativeWebPage::viewReady() const { return m_viewReady; } QVariant DeclarativeWebPage::resurrectedContentRect() const { return m_resurrectedContentRect; } void DeclarativeWebPage::setResurrectedContentRect(QVariant resurrectedContentRect) { if (m_resurrectedContentRect != resurrectedContentRect) { m_resurrectedContentRect = resurrectedContentRect; emit resurrectedContentRectChanged(); } } void DeclarativeWebPage::loadTab(QString newUrl, bool force) { // Always enable chrome when load is called. setChrome(true); QString oldUrl = url().toString(); if ((!newUrl.isEmpty() && oldUrl != newUrl) || force) { m_domContentLoaded = false; emit domContentLoadedChanged(); load(newUrl); } } void DeclarativeWebPage::grabToFile() { emit clearGrabResult(); m_grabResult = grabToImage(); connect(m_grabResult.data(), SIGNAL(ready()), this, SLOT(grabResultReady())); } void DeclarativeWebPage::grabThumbnail() { m_thumbnailResult = grabToImage(); connect(m_thumbnailResult.data(), SIGNAL(ready()), this, SLOT(thumbnailReady())); } void DeclarativeWebPage::forceChrome(bool forcedChrome) { // This way we don't break chromeGestureEnabled and chrome bindings. setChromeGestureEnabled(!forcedChrome); if (forcedChrome) { setChrome(forcedChrome); } // Without chrome respect content height. resetHeight(!forcedChrome); if (m_forcedChrome != forcedChrome) { m_forcedChrome = forcedChrome; emit forcedChromeChanged(); } } void DeclarativeWebPage::resetHeight(bool respectContentHeight) { if (!state().isEmpty()) { return; } // Application active if (respectContentHeight && !m_forcedChrome) { // Handle webPage height over here, BrowserPage.qml loading // reset might be redundant as we have also loaded trigger // reset. However, I'd leave it there for safety reasons. // We need to reset height always back to short height when loading starts // so that after tab change there is always initial short composited height. // Height may expand when content is moved. if (contentHeight() > (m_fullScreenHeight + m_toolbarHeight) || fullscreen()) { setHeight(m_fullScreenHeight); } else { setHeight(m_fullScreenHeight - m_toolbarHeight); } } else { setHeight(m_fullScreenHeight - m_toolbarHeight); } } void DeclarativeWebPage::componentComplete() { QuickMozView::componentComplete(); } void DeclarativeWebPage::onViewInitialized() { addMessageListener(gFullScreenMessage); addMessageListener(gDomContentLoadedMessage); } void DeclarativeWebPage::grabResultReady() { QImage image = m_grabResult->image(); m_grabResult.clear(); int size = qMin(width(), height()); QRect cropBounds(0, 0, size, size/2); m_grabWritter.setFuture(QtConcurrent::run(this, &DeclarativeWebPage::saveToFile, image, cropBounds)); } void DeclarativeWebPage::grabWritten() { QString path = m_grabWritter.result(); emit grabResult(path); } void DeclarativeWebPage::thumbnailReady() { QImage image = m_thumbnailResult->image(); m_thumbnailResult.clear(); int size = qMin(width(), height()); QRect cropBounds(0, 0, size, size); image = image.copy(cropBounds); QByteArray iconData; QBuffer buffer(&iconData); buffer.open(QIODevice::WriteOnly); if (image.save(&buffer, "jpg", 75)) { buffer.close(); emit thumbnailResult(QString(BASE64_IMAGE).arg(QString(iconData.toBase64()))); } else { emit thumbnailResult(DEFAULT_DESKTOP_BOOKMARK_ICON); } } QString DeclarativeWebPage::saveToFile(QImage image, QRect cropBounds) { if (image.isNull()) { return ""; } // 75% quality jpg produces small and good enough capture. QString path = QString("%1/tab-%2-thumb.jpg").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).arg(m_tabId); image = image.copy(cropBounds); return !allBlack(image) && image.save(path, "jpg", 75) ? path : ""; } bool DeclarativeWebPage::isBlack(QRgb rgb) const { return qRed(rgb) == 0 && qGreen(rgb) == 0 && qBlue(rgb) == 0; } bool DeclarativeWebPage::allBlack(const QImage &image) const { int h = image.height(); int w = image.width(); for (int j = 0; j < h; ++j) { const QRgb *b = (const QRgb *)image.constScanLine(j); for (int i = 0; i < w; ++i) { if (!isBlack(b[i])) return false; } } return true; } void DeclarativeWebPage::onRecvAsyncMessage(const QString& message, const QVariant& data) { if (message == gFullScreenMessage) { setFullscreen(data.toMap().value(QString("fullscreen")).toBool()); } else if (message == gDomContentLoadedMessage && data.toMap().value("rootFrame").toBool()) { m_domContentLoaded = true; emit domContentLoadedChanged(); } } bool DeclarativeWebPage::fullscreen() const { return m_fullscreen; } bool DeclarativeWebPage::forcedChrome() const { return m_forcedChrome; } void DeclarativeWebPage::setFullscreen(const bool fullscreen) { if (m_fullscreen != fullscreen) { m_fullscreen = fullscreen; resetHeight(); emit fullscreenChanged(); } } QDebug operator<<(QDebug dbg, const DeclarativeWebPage *page) { if (!page) { return dbg << "DeclarativeWebPage (this = 0x0)"; } dbg.nospace() << "DeclarativeWebPage(url = " << page->url() << ", title = " << page->title() << ", width = " << page->width() << ", height = " << page->height() << ", opacity = " << page->opacity() << ", visible = " << page->isVisible() << ", enabled = " << page->isEnabled() << ")"; return dbg.space(); }
/**************************************************************************** ** ** Copyright (C) 2014 Jolla Ltd. ** Contact: Raine Makelainen <[email protected]> ** ****************************************************************************/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "declarativewebpage.h" #include "declarativewebcontainer.h" #include <QtConcurrent> #include <QStandardPaths> static const QString gFullScreenMessage("embed:fullscreenchanged"); static const QString gDomContentLoadedMessage("embed:domcontentloaded"); DeclarativeWebPage::DeclarativeWebPage(QQuickItem *parent) : QuickMozView(parent) , m_container(0) , m_tabId(0) , m_viewReady(false) , m_loaded(false) , m_userHasDraggedWhileLoading(false) , m_fullscreen(false) , m_forcedChrome(false) , m_domContentLoaded(false) , m_urlHasChanged(false) , m_backForwardNavigation(false) { connect(this, SIGNAL(viewInitialized()), this, SLOT(onViewInitialized())); connect(this, SIGNAL(recvAsyncMessage(const QString, const QVariant)), this, SLOT(onRecvAsyncMessage(const QString&, const QVariant&))); connect(&m_grabWritter, SIGNAL(finished()), this, SLOT(grabWritten())); connect(this, SIGNAL(contentHeightChanged()), this, SLOT(resetHeight())); connect(this, SIGNAL(scrollableOffsetChanged()), this, SLOT(resetHeight())); } DeclarativeWebPage::~DeclarativeWebPage() { m_grabWritter.cancel(); m_grabWritter.waitForFinished(); m_grabResult.clear(); m_thumbnailResult.clear(); } DeclarativeWebContainer *DeclarativeWebPage::container() const { return m_container; } void DeclarativeWebPage::setContainer(DeclarativeWebContainer *container) { if (m_container != container) { m_container = container; emit containerChanged(); } } int DeclarativeWebPage::tabId() const { return m_tabId; } void DeclarativeWebPage::setTabId(int tabId) { if (m_tabId != tabId) { m_tabId = tabId; emit tabIdChanged(); } } bool DeclarativeWebPage::domContentLoaded() const { return m_domContentLoaded; } bool DeclarativeWebPage::urlHasChanged() const { return m_urlHasChanged; } void DeclarativeWebPage::setUrlHasChanged(bool urlHasChanged) { m_urlHasChanged = urlHasChanged; } bool DeclarativeWebPage::backForwardNavigation() const { return m_backForwardNavigation; } void DeclarativeWebPage::setBackForwardNavigation(bool backForwardNavigation) { m_backForwardNavigation = backForwardNavigation; } bool DeclarativeWebPage::viewReady() const { return m_viewReady; } QVariant DeclarativeWebPage::resurrectedContentRect() const { return m_resurrectedContentRect; } void DeclarativeWebPage::setResurrectedContentRect(QVariant resurrectedContentRect) { if (m_resurrectedContentRect != resurrectedContentRect) { m_resurrectedContentRect = resurrectedContentRect; emit resurrectedContentRectChanged(); } } void DeclarativeWebPage::loadTab(QString newUrl, bool force) { // Always enable chrome when load is called. setChrome(true); QString oldUrl = url().toString(); if ((!newUrl.isEmpty() && oldUrl != newUrl) || force) { m_domContentLoaded = false; emit domContentLoadedChanged(); load(newUrl); } } void DeclarativeWebPage::grabToFile() { emit clearGrabResult(); m_grabResult = grabToImage(); connect(m_grabResult.data(), SIGNAL(ready()), this, SLOT(grabResultReady())); } void DeclarativeWebPage::grabThumbnail() { m_thumbnailResult = grabToImage(); connect(m_thumbnailResult.data(), SIGNAL(ready()), this, SLOT(thumbnailReady())); } void DeclarativeWebPage::forceChrome(bool forcedChrome) { // This way we don't break chromeGestureEnabled and chrome bindings. setChromeGestureEnabled(!forcedChrome); if (forcedChrome) { setChrome(forcedChrome); } // Without chrome respect content height. resetHeight(!forcedChrome); if (m_forcedChrome != forcedChrome) { m_forcedChrome = forcedChrome; emit forcedChromeChanged(); } } void DeclarativeWebPage::resetHeight(bool respectContentHeight) { if (!state().isEmpty()) { return; } // Application active if (respectContentHeight && !m_forcedChrome) { // Handle webPage height over here, BrowserPage.qml loading // reset might be redundant as we have also loaded trigger // reset. However, I'd leave it there for safety reasons. // We need to reset height always back to short height when loading starts // so that after tab change there is always initial short composited height. // Height may expand when content is moved. if (contentHeight() > (m_fullScreenHeight + m_toolbarHeight) || fullscreen()) { setHeight(m_fullScreenHeight); } else { setHeight(m_fullScreenHeight - m_toolbarHeight); } } else { setHeight(m_fullScreenHeight - m_toolbarHeight); } } void DeclarativeWebPage::componentComplete() { QuickMozView::componentComplete(); } void DeclarativeWebPage::onViewInitialized() { addMessageListener(gFullScreenMessage); addMessageListener(gDomContentLoadedMessage); } void DeclarativeWebPage::grabResultReady() { QImage image = m_grabResult->image(); m_grabResult.clear(); int w = qMin(width(), height()); int h = qMax(width(), height()); h = qMax(h / 3, w / 2); QRect cropBounds(0, 0, w, h); m_grabWritter.setFuture(QtConcurrent::run(this, &DeclarativeWebPage::saveToFile, image, cropBounds)); } void DeclarativeWebPage::grabWritten() { QString path = m_grabWritter.result(); emit grabResult(path); } void DeclarativeWebPage::thumbnailReady() { QImage image = m_thumbnailResult->image(); m_thumbnailResult.clear(); int size = qMin(width(), height()); QRect cropBounds(0, 0, size, size); image = image.copy(cropBounds); QByteArray iconData; QBuffer buffer(&iconData); buffer.open(QIODevice::WriteOnly); if (image.save(&buffer, "jpg", 75)) { buffer.close(); emit thumbnailResult(QString(BASE64_IMAGE).arg(QString(iconData.toBase64()))); } else { emit thumbnailResult(DEFAULT_DESKTOP_BOOKMARK_ICON); } } QString DeclarativeWebPage::saveToFile(QImage image, QRect cropBounds) { if (image.isNull()) { return ""; } // 75% quality jpg produces small and good enough capture. QString path = QString("%1/tab-%2-thumb.jpg").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).arg(m_tabId); image = image.copy(cropBounds); return !allBlack(image) && image.save(path, "jpg", 75) ? path : ""; } bool DeclarativeWebPage::isBlack(QRgb rgb) const { return qRed(rgb) == 0 && qGreen(rgb) == 0 && qBlue(rgb) == 0; } bool DeclarativeWebPage::allBlack(const QImage &image) const { int h = image.height(); int w = image.width(); for (int j = 0; j < h; ++j) { const QRgb *b = (const QRgb *)image.constScanLine(j); for (int i = 0; i < w; ++i) { if (!isBlack(b[i])) return false; } } return true; } void DeclarativeWebPage::onRecvAsyncMessage(const QString& message, const QVariant& data) { if (message == gFullScreenMessage) { setFullscreen(data.toMap().value(QString("fullscreen")).toBool()); } else if (message == gDomContentLoadedMessage && data.toMap().value("rootFrame").toBool()) { m_domContentLoaded = true; emit domContentLoadedChanged(); } } bool DeclarativeWebPage::fullscreen() const { return m_fullscreen; } bool DeclarativeWebPage::forcedChrome() const { return m_forcedChrome; } void DeclarativeWebPage::setFullscreen(const bool fullscreen) { if (m_fullscreen != fullscreen) { m_fullscreen = fullscreen; resetHeight(); emit fullscreenChanged(); } } QDebug operator<<(QDebug dbg, const DeclarativeWebPage *page) { if (!page) { return dbg << "DeclarativeWebPage (this = 0x0)"; } dbg.nospace() << "DeclarativeWebPage(url = " << page->url() << ", title = " << page->title() << ", width = " << page->width() << ", height = " << page->height() << ", opacity = " << page->opacity() << ", visible = " << page->isVisible() << ", enabled = " << page->isEnabled() << ")"; return dbg.space(); }
Improve thumbnail image size for portrait and landscape orientations
Improve thumbnail image size for portrait and landscape orientations
C++
mpl-2.0
alinelena/sailfish-browser,sailfishos/sailfish-browser,sailfishos/sailfish-browser,sailfishos/sailfish-browser,rojkov/sailfish-browser,alinelena/sailfish-browser,sailfishos/sailfish-browser,alinelena/sailfish-browser,sailfishos/sailfish-browser,rojkov/sailfish-browser,alinelena/sailfish-browser,rojkov/sailfish-browser
75b19230eb970dc3b95fd61110848d393aee2af4
src/entt/entity/entity.hpp
src/entt/entity/entity.hpp
#ifndef ENTT_ENTITY_ENTITY_HPP #define ENTT_ENTITY_ENTITY_HPP #include <cstddef> #include <cstdint> #include <type_traits> #include "../config/config.h" namespace entt { /** * @brief Entity traits. * * Primary template isn't defined on purpose. All the specializations give a * compile-time error unless the template parameter is an accepted entity type. */ template<typename, typename = void> struct entt_traits; /** * @brief Entity traits for enumeration types. * @tparam Type The type to check. */ template<typename Type> struct entt_traits<Type, std::enable_if_t<std::is_enum_v<Type>>> : entt_traits<std::underlying_type_t<Type>> {}; /** * @brief Entity traits for a 16 bits entity identifier. * * A 16 bits entity identifier guarantees: * * * 12 bits for the entity number (up to 4k entities). * * 4 bit for the version (resets in [0-15]). */ template<> struct entt_traits<std::uint16_t> { /*! @brief Underlying entity type. */ using entity_type = std::uint16_t; /*! @brief Underlying version type. */ using version_type = std::uint8_t; /*! @brief Difference type. */ using difference_type = std::int32_t; /*! @brief Mask to use to get the entity number out of an identifier. */ static constexpr entity_type entity_mask = 0xFFF; /*! @brief Mask to use to get the version out of an identifier. */ static constexpr entity_type version_mask = 0xF; /*! @brief Extent of the entity number within an identifier. */ static constexpr std::size_t entity_shift = 12u; }; /** * @brief Entity traits for a 32 bits entity identifier. * * A 32 bits entity identifier guarantees: * * * 20 bits for the entity number (suitable for almost all the games). * * 12 bit for the version (resets in [0-4095]). */ template<> struct entt_traits<std::uint32_t> { /*! @brief Underlying entity type. */ using entity_type = std::uint32_t; /*! @brief Underlying version type. */ using version_type = std::uint16_t; /*! @brief Difference type. */ using difference_type = std::int64_t; /*! @brief Mask to use to get the entity number out of an identifier. */ static constexpr entity_type entity_mask = 0xFFFFF; /*! @brief Mask to use to get the version out of an identifier. */ static constexpr entity_type version_mask = 0xFFF; /*! @brief Extent of the entity number within an identifier. */ static constexpr std::size_t entity_shift = 20u; }; /** * @brief Entity traits for a 64 bits entity identifier. * * A 64 bits entity identifier guarantees: * * * 32 bits for the entity number (an indecently large number). * * 32 bit for the version (an indecently large number). */ template<> struct entt_traits<std::uint64_t> { /*! @brief Underlying entity type. */ using entity_type = std::uint64_t; /*! @brief Underlying version type. */ using version_type = std::uint32_t; /*! @brief Difference type. */ using difference_type = std::int64_t; /*! @brief Mask to use to get the entity number out of an identifier. */ static constexpr entity_type entity_mask = 0xFFFFFFFF; /*! @brief Mask to use to get the version out of an identifier. */ static constexpr entity_type version_mask = 0xFFFFFFFF; /*! @brief Extent of the entity number within an identifier. */ static constexpr std::size_t entity_shift = 32u; }; /** * @brief Converts an entity type to its underlying type. * @tparam Entity The value type. * @param entity The value to convert. * @return The integral representation of the given value. */ template<typename Entity> [[nodiscard]] constexpr auto to_integral(const Entity entity) ENTT_NOEXCEPT { return static_cast<typename entt_traits<Entity>::entity_type>(entity); } /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { struct null { template<typename Entity> [[nodiscard]] constexpr operator Entity() const ENTT_NOEXCEPT { return Entity{entt_traits<Entity>::entity_mask}; } [[nodiscard]] constexpr bool operator==(null) const ENTT_NOEXCEPT { return true; } [[nodiscard]] constexpr bool operator!=(null) const ENTT_NOEXCEPT { return false; } template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity entity) const ENTT_NOEXCEPT { return (to_integral(entity) & entt_traits<Entity>::entity_mask) == to_integral(static_cast<Entity>(*this)); } template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity entity) const ENTT_NOEXCEPT { return !(entity == *this); } }; template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity entity, null other) ENTT_NOEXCEPT { return other.operator==(entity); } template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity entity, null other) ENTT_NOEXCEPT { return !(other == entity); } } /** * Internal details not to be documented. * @endcond */ /** * @brief Compile-time constant for null entities. * * There exist implicit conversions from this variable to entity identifiers of * any allowed type. Similarly, there exist comparision operators between the * null entity and any other entity identifier. */ inline constexpr auto null = internal::null{}; } #endif
#ifndef ENTT_ENTITY_ENTITY_HPP #define ENTT_ENTITY_ENTITY_HPP #include <cstddef> #include <cstdint> #include <type_traits> #include "../config/config.h" namespace entt { /** * @brief Entity traits. * * Primary template isn't defined on purpose. All the specializations give a * compile-time error unless the template parameter is an accepted entity type. */ template<typename, typename = void> struct entt_traits; /** * @brief Entity traits for enumeration types. * @tparam Type The type to check. */ template<typename Type> struct entt_traits<Type, std::enable_if_t<std::is_enum_v<Type>>> : entt_traits<std::underlying_type_t<Type>> {}; /** * @brief Entity traits for a 16 bits entity identifier. * * A 16 bits entity identifier guarantees: * * * 12 bits for the entity number (up to 4k entities). * * 4 bit for the version (resets in [0-15]). */ template<> struct entt_traits<std::uint16_t> { /*! @brief Underlying entity type. */ using entity_type = std::uint16_t; /*! @brief Underlying version type. */ using version_type = std::uint8_t; /*! @brief Difference type. */ using difference_type = std::int32_t; /*! @brief Mask to use to get the entity number out of an identifier. */ static constexpr entity_type entity_mask = 0xFFF; /*! @brief Mask to use to get the version out of an identifier. */ static constexpr entity_type version_mask = 0xF; /*! @brief Extent of the entity number within an identifier. */ static constexpr std::size_t entity_shift = 12u; }; /** * @brief Entity traits for a 32 bits entity identifier. * * A 32 bits entity identifier guarantees: * * * 20 bits for the entity number (suitable for almost all the games). * * 12 bit for the version (resets in [0-4095]). */ template<> struct entt_traits<std::uint32_t> { /*! @brief Underlying entity type. */ using entity_type = std::uint32_t; /*! @brief Underlying version type. */ using version_type = std::uint16_t; /*! @brief Difference type. */ using difference_type = std::int64_t; /*! @brief Mask to use to get the entity number out of an identifier. */ static constexpr entity_type entity_mask = 0xFFFFF; /*! @brief Mask to use to get the version out of an identifier. */ static constexpr entity_type version_mask = 0xFFF; /*! @brief Extent of the entity number within an identifier. */ static constexpr std::size_t entity_shift = 20u; }; /** * @brief Entity traits for a 64 bits entity identifier. * * A 64 bits entity identifier guarantees: * * * 32 bits for the entity number (an indecently large number). * * 32 bit for the version (an indecently large number). */ template<> struct entt_traits<std::uint64_t> { /*! @brief Underlying entity type. */ using entity_type = std::uint64_t; /*! @brief Underlying version type. */ using version_type = std::uint32_t; /*! @brief Difference type. */ using difference_type = std::int64_t; /*! @brief Mask to use to get the entity number out of an identifier. */ static constexpr entity_type entity_mask = 0xFFFFFFFF; /*! @brief Mask to use to get the version out of an identifier. */ static constexpr entity_type version_mask = 0xFFFFFFFF; /*! @brief Extent of the entity number within an identifier. */ static constexpr std::size_t entity_shift = 32u; }; /** * @brief Converts an entity type to its underlying type. * @tparam Entity The value type. * @param entity The value to convert. * @return The integral representation of the given value. */ template<typename Entity> [[nodiscard]] constexpr auto to_integral(const Entity entity) ENTT_NOEXCEPT { return static_cast<typename entt_traits<Entity>::entity_type>(entity); } /*! @brief Null object for all entity identifiers. */ struct null_t { /** * @brief Converts the null object to identifiers of any type. * @tparam Entity Type of entity identifier. * @return The null representation for the given identifier. */ template<typename Entity> [[nodiscard]] constexpr operator Entity() const ENTT_NOEXCEPT { return Entity{entt_traits<Entity>::entity_mask}; } /** * @brief Compares two null objects. * @return True in all cases. */ [[nodiscard]] constexpr bool operator==(null_t) const ENTT_NOEXCEPT { return true; } /** * @brief Compares two null objects. * @return False in all cases. */ [[nodiscard]] constexpr bool operator!=(null_t) const ENTT_NOEXCEPT { return false; } /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @return False if the two elements differ, true otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity entity) const ENTT_NOEXCEPT { return (to_integral(entity) & entt_traits<Entity>::entity_mask) == to_integral(static_cast<Entity>(*this)); } /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @return True if the two elements differ, false otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity entity) const ENTT_NOEXCEPT { return !(entity == *this); } }; /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @param other A null object yet to be converted. * @return False if the two elements differ, true otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity entity, null_t other) ENTT_NOEXCEPT { return other.operator==(entity); } /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @param other A null object yet to be converted. * @return True if the two elements differ, false otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity entity, null_t other) ENTT_NOEXCEPT { return !(other == entity); } /** * Internal details not to be documented. * @endcond */ /** * @brief Compile-time constant for null entities. * * There exist implicit conversions from this variable to entity identifiers of * any allowed type. Similarly, there exist comparision operators between the * null entity and any other entity identifier. */ inline constexpr null_t null{}; } #endif
make null_t public
entity: make null_t public
C++
mit
skypjack/entt,skypjack/entt,skypjack/entt,skypjack/entt
46f5a4936af58b8b8bb23c136dd82641e9dfeb1e
src/fly/net/connection.cpp
src/fly/net/connection.cpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * _______ _ * * ( ____ \ ( \ |\ /| * * | ( \/ | ( ( \ / ) * * | (__ | | \ (_) / * * | __) | | \ / * * | ( | | ) ( * * | ) | (____/\ | | * * |/ (_______/ \_/ * * * * * * fly is an awesome c++11 network library. * * * * @author: lichuan * * @qq: 308831759 * * @email: [email protected] * * @github: https://github.com/lichuan/fly * * @date: 2015-06-22 18:22:00 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <unistd.h> #include <cstring> #include <netinet/in.h> #include "fly/net/connection.hpp" #include "fly/net/poller_task.hpp" #include "fly/base/logger.hpp" namespace fly { namespace net { fly::base::ID_Allocator Connection::m_id_allocator; Connection::~Connection() { while(auto *message_chunk = m_recv_msg_queue.pop()) { delete message_chunk; } while(auto *message_chunk = m_send_msg_queue.pop()) { delete message_chunk; } } Connection::Connection(int32 fd, const Addr &peer_addr) { m_fd = fd; m_peer_addr = peer_addr; } uint64 Connection::id() { return m_id; } void Connection::send(rapidjson::Document &doc) { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); send(buffer.GetString(), buffer.GetSize()); } void Connection::send(const void *data, uint32 size) { Message_Chunk *message_chunk = new Message_Chunk(size + sizeof(uint32)); uint32 *uint32_ptr = (uint32*)message_chunk->read_ptr(); *uint32_ptr = htonl(size); memcpy(message_chunk->read_ptr() + sizeof(uint32), data, size); message_chunk->write_ptr(size + sizeof(uint32)); m_send_msg_queue.push(message_chunk); m_poller_task->write_connection(shared_from_this()); } void Connection::close() { m_poller_task->close_connection(shared_from_this()); } const Addr& Connection::peer_addr() { return m_peer_addr; } void Connection::parse() { while(true) { char *msg_length_buf = (char*)(&m_cur_msg_length); uint32 remain_bytes = sizeof(uint32); if(m_cur_msg_length != 0) { goto after_parse_length; } if(m_recv_msg_queue.length() < sizeof(uint32)) { break; } while(auto *message_chunk = m_recv_msg_queue.pop()) { uint32 length = message_chunk->length(); if(length < remain_bytes) { memcpy(msg_length_buf + sizeof(uint32) - remain_bytes, message_chunk->read_ptr(), length); remain_bytes -= length; delete message_chunk; } else { memcpy(msg_length_buf + sizeof(uint32) - remain_bytes, message_chunk->read_ptr(), remain_bytes); if(length == remain_bytes) { delete message_chunk; } else { message_chunk->read_ptr(remain_bytes); m_recv_msg_queue.push_front(message_chunk); } break; } } m_cur_msg_length = ntohl(m_cur_msg_length); after_parse_length: if(m_recv_msg_queue.length() < m_cur_msg_length) { break; } const uint32 MAX_MSG_LEN = 65536; char data[MAX_MSG_LEN] = {0}; remain_bytes = m_cur_msg_length; if(m_cur_msg_length > MAX_MSG_LEN / 2) { LOG_ERROR("message length exceed half of MAX_MSG_LEN(65536)"); if(m_cur_msg_length > MAX_MSG_LEN) { LOG_FATAL("message length exceed MAX_MSG_LEN"); break; } } while(auto *message_chunk = m_recv_msg_queue.pop()) { uint32 length = message_chunk->length(); if(length < remain_bytes) { memcpy(data + m_cur_msg_length - remain_bytes, message_chunk->read_ptr(), length); remain_bytes -= length; delete message_chunk; } else { memcpy(data + m_cur_msg_length - remain_bytes, message_chunk->read_ptr(), remain_bytes); if(length == remain_bytes) { delete message_chunk; } else { message_chunk->read_ptr(remain_bytes); m_recv_msg_queue.push_front(message_chunk); } std::unique_ptr<Message> message(new Message(shared_from_this())); message->m_raw_data.assign(data, m_cur_msg_length); m_cur_msg_length = 0; rapidjson::Document &doc = message->doc(); doc.Parse(message->m_raw_data.c_str()); if(!doc.HasParseError()) { if(!doc.HasMember("msg_type")) { break; } const rapidjson::Value &msg_type = doc["msg_type"]; if(!msg_type.IsUint()) { break; } message->m_type = msg_type.GetUint(); if(!doc.HasMember("msg_cmd")) { break; } const rapidjson::Value &msg_cmd = doc["msg_cmd"]; if(!msg_cmd.IsUint()) { break; } message->m_cmd = msg_cmd.GetUint(); m_dispatch_cb(std::move(message)); } break; } } } } } }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * _______ _ * * ( ____ \ ( \ |\ /| * * | ( \/ | ( ( \ / ) * * | (__ | | \ (_) / * * | __) | | \ / * * | ( | | ) ( * * | ) | (____/\ | | * * |/ (_______/ \_/ * * * * * * fly is an awesome c++11 network library. * * * * @author: lichuan * * @qq: 308831759 * * @email: [email protected] * * @github: https://github.com/lichuan/fly * * @date: 2015-06-22 18:22:00 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <unistd.h> #include <cstring> #include <netinet/in.h> #include "fly/net/connection.hpp" #include "fly/net/poller_task.hpp" #include "fly/base/logger.hpp" namespace fly { namespace net { fly::base::ID_Allocator Connection::m_id_allocator; Connection::~Connection() { while(auto *message_chunk = m_recv_msg_queue.pop()) { delete message_chunk; } while(auto *message_chunk = m_send_msg_queue.pop()) { delete message_chunk; } } Connection::Connection(int32 fd, const Addr &peer_addr) { m_fd = fd; m_peer_addr = peer_addr; } uint64 Connection::id() { return m_id; } void Connection::send(rapidjson::Document &doc) { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); send(buffer.GetString(), buffer.GetSize()); } void Connection::send(const void *data, uint32 size) { Message_Chunk *message_chunk = new Message_Chunk(size + sizeof(uint32)); uint32 *uint32_ptr = (uint32*)message_chunk->read_ptr(); *uint32_ptr = htonl(size); memcpy(message_chunk->read_ptr() + sizeof(uint32), data, size); message_chunk->write_ptr(size + sizeof(uint32)); m_send_msg_queue.push(message_chunk); m_poller_task->write_connection(shared_from_this()); } void Connection::close() { m_poller_task->close_connection(shared_from_this()); } const Addr& Connection::peer_addr() { return m_peer_addr; } void Connection::parse() { while(true) { char *msg_length_buf = (char*)(&m_cur_msg_length); uint32 remain_bytes = sizeof(uint32); if(m_cur_msg_length != 0) { goto after_parse_length; } if(m_recv_msg_queue.length() < sizeof(uint32)) { break; } while(auto *message_chunk = m_recv_msg_queue.pop()) { uint32 length = message_chunk->length(); if(length < remain_bytes) { memcpy(msg_length_buf + sizeof(uint32) - remain_bytes, message_chunk->read_ptr(), length); remain_bytes -= length; delete message_chunk; } else { memcpy(msg_length_buf + sizeof(uint32) - remain_bytes, message_chunk->read_ptr(), remain_bytes); if(length == remain_bytes) { delete message_chunk; } else { message_chunk->read_ptr(remain_bytes); m_recv_msg_queue.push_front(message_chunk); } break; } } m_cur_msg_length = ntohl(m_cur_msg_length); after_parse_length: if(m_recv_msg_queue.length() < m_cur_msg_length) { break; } const uint32 MAX_MSG_LEN = 102400; char data[MAX_MSG_LEN] = {0}; remain_bytes = m_cur_msg_length; if(m_cur_msg_length > MAX_MSG_LEN / 2) { LOG_ERROR("message length exceed half of MAX_MSG_LEN(%d)", MAX_MSG_LEN); if(m_cur_msg_length > MAX_MSG_LEN) { LOG_FATAL("message length exceed MAX_MSG_LEN(%d)", MAX_MSG_LEN); break; } } while(auto *message_chunk = m_recv_msg_queue.pop()) { uint32 length = message_chunk->length(); if(length < remain_bytes) { memcpy(data + m_cur_msg_length - remain_bytes, message_chunk->read_ptr(), length); remain_bytes -= length; delete message_chunk; } else { memcpy(data + m_cur_msg_length - remain_bytes, message_chunk->read_ptr(), remain_bytes); if(length == remain_bytes) { delete message_chunk; } else { message_chunk->read_ptr(remain_bytes); m_recv_msg_queue.push_front(message_chunk); } std::unique_ptr<Message> message(new Message(shared_from_this())); message->m_raw_data.assign(data, m_cur_msg_length); m_cur_msg_length = 0; rapidjson::Document &doc = message->doc(); doc.Parse(message->m_raw_data.c_str()); if(!doc.HasParseError()) { if(!doc.HasMember("msg_type")) { break; } const rapidjson::Value &msg_type = doc["msg_type"]; if(!msg_type.IsUint()) { break; } message->m_type = msg_type.GetUint(); if(!doc.HasMember("msg_cmd")) { break; } const rapidjson::Value &msg_cmd = doc["msg_cmd"]; if(!msg_cmd.IsUint()) { break; } message->m_cmd = msg_cmd.GetUint(); m_dispatch_cb(std::move(message)); } break; } } } } } }
adjust max_msg_len
adjust max_msg_len
C++
apache-2.0
lichuan/fly,lichuan/fly
80234a509422ea7a264a71209c6f95df57cc8c25
src/hqn_lua_mainmemory.cpp
src/hqn_lua_mainmemory.cpp
/* * Lua functions mimicing BizHawk's mainmemory api. */ #include "hqn_lua.h" namespace hqn_lua { /// Read a signed byte from RAM int mainmemory_read_s8(lua_State *L) { int index = luaL_optint(L, 1, 0); int8_t data = (int8_t)hqn_get_nes(L)->low_mem()[index]; lua_pushinteger(L, data); return 1; } /// Read an unsigned byte from RAM int mainmemory_read_u8(lua_State *L) { // First get the index requested int index = luaL_optint(L, 1, 0); // Now get the byte at that index and return it lua_pushinteger(L, hqn_get_nes(L)->low_mem()[index]); return 1; } int mainmemory_init_(lua_State *L) { luaL_Reg functionList[] = { { "readbyte", &mainmemory_read_u8 }, { "read_s8", &mainmemory_read_s8 }, { "read_u8", &mainmemory_read_u8 }, { nullptr, nullptr } }; luaL_register(L, "mainmemory", functionList); return 0; } } // end namespace hqn_lua
/* * Lua functions mimicing BizHawk's mainmemory api. */ #include "hqn_lua.h" namespace hqn_lua { /// Read a signed byte from RAM int mainmemory_read_s8(lua_State *L) { HQN_EMULATOR(emu); int index = luaL_optint(L, 1, 0); int8_t data = (int8_t)emu->low_mem()[index]; lua_pushinteger(L, data); return 1; } /// Read an unsigned byte from RAM int mainmemory_read_u8(lua_State *L) { HQN_EMULATOR(emu); // First get the index requested int index = luaL_optint(L, 1, 0); // Now get the byte at that index and return it lua_pushinteger(L, emu->low_mem()[index]); return 1; } // Write an unsigned byte to ram int mainmemory_write_u8(lua_State *L) { HQN_EMULATOR(emu); int index = luaL_checkint(L, 1); int value = luaL_checkint(L, 2); emu->low_mem()[index] = (uint8_t)value; return 0; } int mainmemory_init_(lua_State *L) { luaL_Reg functionList[] = { { "readbyte", &mainmemory_read_u8 }, { "writebyte", &mainmemory_write_u8 }, { "read_s8", &mainmemory_read_s8 }, { "read_u8", &mainmemory_read_u8 }, { "write_u8", &mainmemory_write_u8 }, { nullptr, nullptr } }; luaL_register(L, "mainmemory", functionList); return 0; } } // end namespace hqn_lua
Add more memory functions.
Add more memory functions.
C++
mit
Bindernews/HeadlessQuickNes,Bindernews/HeadlessQuickNes,Bindernews/HeadlessQuickNes
bc1fcead0302f8229738f17ab61d063c3dbce1f2
src/aliceVision/calibration/bestImages.cpp
src/aliceVision/calibration/bestImages.cpp
// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #include "bestImages.hpp" #include <aliceVision/system/Logger.hpp> #include <limits> #include <numeric> #include <iostream> #include <assert.h> namespace aliceVision{ namespace calibration{ void precomputeCellIndexes(const std::vector<std::vector<cv::Point2f> >& imagePoints, const cv::Size& imageSize, std::size_t calibGridSize, std::vector<std::vector<std::size_t> >& cellIndexesPerImage) { float cellWidth = float(imageSize.width) / float(calibGridSize); float cellHeight = float(imageSize.height) / float(calibGridSize); for (const auto& pointbuf : imagePoints) { std::vector<std::size_t> imageCellIndexes; // Points repartition in image for (cv::Point2f point : pointbuf) { // Compute the index of the point std::size_t cellPointX = std::floor(point.x / cellWidth); std::size_t cellPointY = std::floor(point.y / cellHeight); std::size_t cellIndex = cellPointY * calibGridSize + cellPointX; imageCellIndexes.push_back(cellIndex); } cellIndexesPerImage.push_back(imageCellIndexes); } } void computeCellsWeight(const std::vector<std::size_t>& imagesIndexes, const std::vector<std::vector<std::size_t> >& cellIndexesPerImage, std::size_t calibGridSize, std::map<std::size_t, std::size_t>& cellsWeight) { //Init cell's weight to 0 for (std::size_t i = 0; i < calibGridSize * calibGridSize; ++i) cellsWeight[i] = 0; // Add weight into cells for (std::size_t i = 0; i < imagesIndexes.size(); ++i) { std::vector<std::size_t> uniqueCellIndexes = cellIndexesPerImage[imagesIndexes[i]]; std::sort(uniqueCellIndexes.begin(), uniqueCellIndexes.end()); auto last = std::unique(uniqueCellIndexes.begin(), uniqueCellIndexes.end()); uniqueCellIndexes.erase(last, uniqueCellIndexes.end()); for (std::size_t cellIndex : uniqueCellIndexes) { ++cellsWeight[cellIndex]; } } } void computeImageScores(const std::vector<std::size_t>& inputImagesIndexes, const std::vector<std::vector<std::size_t> >& cellIndexesPerImage, const std::map<std::size_t, std::size_t>& cellsWeight, std::vector<std::pair<float, std::size_t> >& imageScores) { // Compute the score of each image for (std::size_t i = 0; i < inputImagesIndexes.size(); ++i) { const std::vector<std::size_t>& imageCellIndexes = cellIndexesPerImage[inputImagesIndexes[i]]; float imageScore = 0; for (std::size_t cellIndex : imageCellIndexes) { imageScore += cellsWeight.at(cellIndex); } // Normalize by the number of checker items. // If the detector support occlusions of the checker the number of items may vary. imageScore /= float(imageCellIndexes.size()); imageScores.emplace_back(imageScore, inputImagesIndexes[i]); } } void selectBestImages(const std::vector<std::vector<cv::Point2f> >& imagePoints, const cv::Size& imageSize, std::size_t maxCalibFrames, std::size_t calibGridSize, std::vector<float>& calibImageScore, std::vector<std::size_t>& calibInputFrames, std::vector<std::vector<cv::Point2f> >& calibImagePoints, std::vector<std::size_t>& remainingImagesIndexes) { std::vector<std::vector<std::size_t> > cellIndexesPerImage; // Precompute cell indexes per image precomputeCellIndexes(imagePoints, imageSize, calibGridSize, cellIndexesPerImage); // Init with 0, 1, 2, ... remainingImagesIndexes.resize(imagePoints.size()); std::iota(remainingImagesIndexes.begin(), remainingImagesIndexes.end(), 0); std::vector<std::size_t> bestImagesIndexes; if (maxCalibFrames < imagePoints.size()) { while (bestImagesIndexes.size() < maxCalibFrames ) { std::map<std::size_t, std::size_t> cellsWeight; std::vector<std::pair<float, std::size_t> > imageScores; // Count points in each cell of the grid if (bestImagesIndexes.empty()) computeCellsWeight(remainingImagesIndexes, cellIndexesPerImage, calibGridSize, cellsWeight); else computeCellsWeight(bestImagesIndexes, cellIndexesPerImage, calibGridSize, cellsWeight); computeImageScores(remainingImagesIndexes, cellIndexesPerImage, cellsWeight, imageScores); // Find best score std::size_t bestImageIndex = std::numeric_limits<std::size_t>::max(); float bestScore = std::numeric_limits<float>::max(); for (const auto& imageScore: imageScores) { if (imageScore.first < bestScore) { bestScore = imageScore.first; bestImageIndex = imageScore.second; } } auto eraseIt = std::find(remainingImagesIndexes.begin(), remainingImagesIndexes.end(), bestImageIndex); assert(bestScore != std::numeric_limits<float>::max()); assert(eraseIt != remainingImagesIndexes.end()); remainingImagesIndexes.erase(eraseIt); bestImagesIndexes.push_back(bestImageIndex); calibImageScore.push_back(bestScore); } } else { ALICEVISION_LOG_DEBUG("Info: Less valid frames (" << imagePoints.size() << ") than specified maxCalibFrames (" << maxCalibFrames << ")."); bestImagesIndexes.resize(imagePoints.size()); std::iota(bestImagesIndexes.begin(), bestImagesIndexes.end(), 0); std::map<std::size_t, std::size_t> cellsWeight; computeCellsWeight(remainingImagesIndexes, cellIndexesPerImage, calibGridSize, cellsWeight); std::vector<std::pair<float, std::size_t> > imageScores; computeImageScores(remainingImagesIndexes, cellIndexesPerImage, cellsWeight, imageScores); for(auto imgScore: imageScores) { calibImageScore.push_back(imgScore.first); } } assert(bestImagesIndexes.size() == std::min(maxCalibFrames, imagePoints.size())); for(std::size_t i = 0; i < bestImagesIndexes.size(); ++i) { const std::size_t origI = bestImagesIndexes[i]; calibImagePoints.push_back(imagePoints[origI]); calibInputFrames.push_back(origI); } } }//namespace calibration }//namespace aliceVision
// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #include "bestImages.hpp" #include <aliceVision/system/Logger.hpp> #include <limits> #include <numeric> #include <iostream> #include <assert.h> namespace aliceVision{ namespace calibration{ void precomputeCellIndexes(const std::vector<std::vector<cv::Point2f> >& imagePoints, const cv::Size& imageSize, std::size_t calibGridSize, std::vector<std::vector<std::size_t> >& cellIndexesPerImage) { float cellWidth = float(imageSize.width) / float(calibGridSize); float cellHeight = float(imageSize.height) / float(calibGridSize); for (const auto& pointbuf : imagePoints) { std::vector<std::size_t> imageCellIndexes; // Points repartition in image for (cv::Point2f point : pointbuf) { // Compute the index of the point std::size_t cellPointX = std::floor(point.x / cellWidth); std::size_t cellPointY = std::floor(point.y / cellHeight); std::size_t cellIndex = cellPointY * calibGridSize + cellPointX; imageCellIndexes.push_back(cellIndex); } cellIndexesPerImage.push_back(imageCellIndexes); } } void computeCellsWeight(const std::vector<std::size_t>& imagesIndexes, const std::vector<std::vector<std::size_t> >& cellIndexesPerImage, std::size_t calibGridSize, std::map<std::size_t, std::size_t>& cellsWeight) { //Init cell's weight to 0 for (std::size_t i = 0; i < calibGridSize * calibGridSize; ++i) cellsWeight[i] = 0; // Add weight into cells for (const auto& imagesIndex : imagesIndexes) { std::vector<std::size_t> uniqueCellIndexes = cellIndexesPerImage[imagesIndex]; std::sort(uniqueCellIndexes.begin(), uniqueCellIndexes.end()); auto last = std::unique(uniqueCellIndexes.begin(), uniqueCellIndexes.end()); uniqueCellIndexes.erase(last, uniqueCellIndexes.end()); for (std::size_t cellIndex : uniqueCellIndexes) { ++cellsWeight[cellIndex]; } } } void computeImageScores(const std::vector<std::size_t>& inputImagesIndexes, const std::vector<std::vector<std::size_t> >& cellIndexesPerImage, const std::map<std::size_t, std::size_t>& cellsWeight, std::vector<std::pair<float, std::size_t> >& imageScores) { // Compute the score of each image for (const auto& inputImagesIndex : inputImagesIndexes) { const std::vector<std::size_t>& imageCellIndexes = cellIndexesPerImage[inputImagesIndex]; float imageScore = 0; for (std::size_t cellIndex : imageCellIndexes) { imageScore += cellsWeight.at(cellIndex); } // Normalize by the number of checker items. // If the detector support occlusions of the checker the number of items may vary. imageScore /= float(imageCellIndexes.size()); imageScores.emplace_back(imageScore, inputImagesIndex); } } void selectBestImages(const std::vector<std::vector<cv::Point2f> >& imagePoints, const cv::Size& imageSize, std::size_t maxCalibFrames, std::size_t calibGridSize, std::vector<float>& calibImageScore, std::vector<std::size_t>& calibInputFrames, std::vector<std::vector<cv::Point2f> >& calibImagePoints, std::vector<std::size_t>& remainingImagesIndexes) { std::vector<std::vector<std::size_t> > cellIndexesPerImage; // Precompute cell indexes per image precomputeCellIndexes(imagePoints, imageSize, calibGridSize, cellIndexesPerImage); // Init with 0, 1, 2, ... remainingImagesIndexes.resize(imagePoints.size()); std::iota(remainingImagesIndexes.begin(), remainingImagesIndexes.end(), 0); std::vector<std::size_t> bestImagesIndexes; if (maxCalibFrames < imagePoints.size()) { while (bestImagesIndexes.size() < maxCalibFrames ) { std::map<std::size_t, std::size_t> cellsWeight; std::vector<std::pair<float, std::size_t> > imageScores; // Count points in each cell of the grid if (bestImagesIndexes.empty()) computeCellsWeight(remainingImagesIndexes, cellIndexesPerImage, calibGridSize, cellsWeight); else computeCellsWeight(bestImagesIndexes, cellIndexesPerImage, calibGridSize, cellsWeight); computeImageScores(remainingImagesIndexes, cellIndexesPerImage, cellsWeight, imageScores); // Find best score std::size_t bestImageIndex = std::numeric_limits<std::size_t>::max(); float bestScore = std::numeric_limits<float>::max(); for (const auto& imageScore: imageScores) { if (imageScore.first < bestScore) { bestScore = imageScore.first; bestImageIndex = imageScore.second; } } auto eraseIt = std::find(remainingImagesIndexes.begin(), remainingImagesIndexes.end(), bestImageIndex); assert(bestScore != std::numeric_limits<float>::max()); assert(eraseIt != remainingImagesIndexes.end()); remainingImagesIndexes.erase(eraseIt); bestImagesIndexes.push_back(bestImageIndex); calibImageScore.push_back(bestScore); } } else { ALICEVISION_LOG_DEBUG("Info: Less valid frames (" << imagePoints.size() << ") than specified maxCalibFrames (" << maxCalibFrames << ")."); bestImagesIndexes.resize(imagePoints.size()); std::iota(bestImagesIndexes.begin(), bestImagesIndexes.end(), 0); std::map<std::size_t, std::size_t> cellsWeight; computeCellsWeight(remainingImagesIndexes, cellIndexesPerImage, calibGridSize, cellsWeight); std::vector<std::pair<float, std::size_t> > imageScores; computeImageScores(remainingImagesIndexes, cellIndexesPerImage, cellsWeight, imageScores); for(auto imgScore: imageScores) { calibImageScore.push_back(imgScore.first); } } assert(bestImagesIndexes.size() == std::min(maxCalibFrames, imagePoints.size())); for (const auto& origI : bestImagesIndexes) { calibImagePoints.push_back(imagePoints[origI]); calibInputFrames.push_back(origI); } } }//namespace calibration }//namespace aliceVision
range loop for
[calibration] range loop for
C++
mit
poparteu/openMVG,poparteu/openMVG,poparteu/openMVG,poparteu/openMVG
b9f6f562ab838fff2298b201e84b723bea325810
include/pqxx/internal/statement_parameters.hxx
include/pqxx/internal/statement_parameters.hxx
/** Common implementation for statement parameter lists. * * These are used for both prepared statements and parameterized statements. * * DO NOT INCLUDE THIS FILE DIRECTLY. Other headers include it for you. * * Copyright (c) 2000-2019, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. */ #ifndef PQXX_H_STATEMENT_PARAMETER #define PQXX_H_STATEMENT_PARAMETER #include "pqxx/compiler-public.hxx" #include "pqxx/compiler-internal-pre.hxx" #include <cstring> #include <functional> #include <iterator> #include <string> #include <vector> #include "pqxx/binarystring" #include "pqxx/strconv" #include "pqxx/util" namespace pqxx::internal { template<typename T> inline T identity(T x) { return x; } template<typename T> inline std::function<T(T)> identity_func = identity<T>; template<typename ITERATOR> inline const auto iterator_identity = identity_func<decltype(*std::declval<ITERATOR>())>; // TODO: C++20 "ranges" alternative. /// Marker type: pass a dynamically-determined number of statement parameters. /** Normally when invoking a prepared or parameterised statement, the number * of parameters is known at compile time. For instance, * @c t.exec_prepared("foo", 1, "x"); executes statement @c foo with two * parameters, an @c int and a C string. * * But sometimes you may want to pass a number of parameters known only at run * time. In those cases, a @c dynamic_params encodes a dynamically * determined number of parameters. You can mix these with regular, static * parameter lists, and you can re-use them for multiple statement invocations. * * A dynamic_params object does not store copies of its parameters, so make * sure they remain accessible until you've executed the statement. * * The ACCESSOR is an optional callable (such as a lambda). If you pass an * accessor @c a, then each parameter @c p goes into your statement as @c a(p). */ template<typename IT, typename ACCESSOR=decltype(iterator_identity<IT>)> class dynamic_params { public: /// Wrap a sequence of pointers or iterators. dynamic_params(IT begin, IT end) : m_begin(begin), m_end(end), m_accessor(iterator_identity<IT>) {} /// Wrap a sequence of pointers or iterators. /** This version takes an accessor callable. If you pass an accessor @c acc, * then any parameter @c p will go into the statement's parameter list as * @c acc(p). */ dynamic_params(IT begin, IT end, ACCESSOR &acc) : m_begin(begin), m_end(end), m_accessor(acc) {} /// Wrap a container. template<typename C> explicit dynamic_params(const C &container) : dynamic_params(std::begin(container), std::end(container)) {} /// Wrap a container. /** This version takes an accessor callable. If you pass an accessor @c acc, * then any parameter @c p will go into the statement's parameter list as * @c acc(p). */ template<typename C> explicit dynamic_params(const C &container, ACCESSOR &acc) : dynamic_params( std::begin(container), std::end(container), acc) {} IT begin() const { return m_begin; } IT end() const { return m_end; } auto access(decltype(*std::declval<IT>()) value) const -> decltype(std::declval<ACCESSOR>()(value)) { return m_accessor(value); } private: const IT m_begin, m_end; ACCESSOR m_accessor = iterator_identity<IT>; }; class PQXX_LIBEXPORT statement_parameters { protected: statement_parameters() =default; statement_parameters &operator=(const statement_parameters &) =delete; void add_param() { this->add_checked_param("", false, false); } template<typename T> void add_param(const T &v, bool nonnull) { nonnull = (nonnull && not is_null(v)); this->add_checked_param( (nonnull ? pqxx::to_string(v) : ""), nonnull, false); } void add_binary_param(const binarystring &b, bool nonnull) { this->add_checked_param(b.str(), nonnull, true); } /// Marshall parameter values into C-compatible arrays for passing to libpq. int marshall( std::vector<const char *> &values, std::vector<int> &lengths, std::vector<int> &binaries) const; private: void add_checked_param(const std::string &value, bool nonnull, bool binary); std::vector<std::string> m_values; std::vector<bool> m_nonnull; std::vector<bool> m_binary; }; /// Internal type: encode statement parameters. /** Compiles arguments for prepared statements and parameterised queries into * a format that can be passed into libpq. * * Objects of this type are meant to be short-lived. If you pass in a non-null * pointer as a parameter, it may simply use that pointer as a parameter value. */ struct params { /// Construct directly from a series of statement arguments. /** The arrays all default to zero, null, and empty strings. */ template<typename ...Args> params(Args && ... args) { strings.reserve(sizeof...(args)); lengths.reserve(sizeof...(args)); nonnulls.reserve(sizeof...(args)); binaries.reserve(sizeof...(args)); // Start recursively storing parameters. add_fields(std::forward<Args>(args)...); } /// Compose a vector of pointers to parameter string values. std::vector<const char *> get_pointers() const { const std::size_t num_fields = lengths.size(); std::size_t cur_string = 0, cur_bin_string = 0; std::vector<const char *> pointers(num_fields); for (std::size_t index = 0; index < num_fields; index++) { const char *value; if (binaries[index]) { value = bin_strings[cur_bin_string].get(); cur_bin_string++; } else if (nonnulls[index]) { value = strings[cur_string].c_str(); cur_string++; } else { value = nullptr; } pointers[index] = value; } return pointers; } /// String values, for string parameters. std::vector<std::string> strings; /// As used by libpq: lengths of non-null arguments, in bytes. std::vector<int> lengths; /// As used by libpq: boolean "is this parameter non-null?" std::vector<int> nonnulls; /// As used by libpq: boolean "is this parameter in binary format?" std::vector<int> binaries; /// Binary string values, for binary parameters. std::vector<pqxx::binarystring> bin_strings; private: /// Add a non-null string field. void add_field(std::string str) { lengths.push_back(int(str.size())); nonnulls.push_back(1); binaries.push_back(0); strings.emplace_back(std::move(str)); } /// Compile one argument (specialised for null pointer, a null value). void add_field(std::nullptr_t) { lengths.push_back(0); nonnulls.push_back(0); binaries.push_back(0); } /// Compile one argument (specialised for binarystring). void add_field(const binarystring &arg) { lengths.push_back(int(arg.size())); nonnulls.push_back(1); binaries.push_back(1); bin_strings.push_back(arg); } /// Compile one argument (default, generic implementation). /** Uses string_traits to represent the argument as a std::string. */ template<typename Arg> void add_field(const Arg &arg) { if (is_null(arg)) add_field(nullptr); else add_field(to_string(arg)); } /// Compile a dynamic_params object into a dynamic number of parameters. template<typename IT, typename ACCESSOR> void add_field(const dynamic_params<IT, ACCESSOR> &parameters) { for (auto param: parameters) add_field(parameters.access(param)); } /// Compile argument list. /** This recursively "peels off" the next remaining element, compiles its * information into its final form, and calls itself for the rest of the * list. * * @param arg Current argument to be compiled. * @param args Optional remaining arguments, to be compiled recursively. */ template<typename Arg, typename ...More> void add_fields(Arg &&arg, More && ... args) { add_field(std::forward<Arg>(arg)); // Compile remaining arguments, if any. add_fields(std::forward<More>(args)...); } /// Terminating version of add_fields, at the end of the list. /** Recursion in add_fields ends with this call. */ void add_fields() {} }; } // namespace pqxx::internal #include "pqxx/compiler-internal-post.hxx" #endif
/** Common implementation for statement parameter lists. * * These are used for both prepared statements and parameterized statements. * * DO NOT INCLUDE THIS FILE DIRECTLY. Other headers include it for you. * * Copyright (c) 2000-2019, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. */ #ifndef PQXX_H_STATEMENT_PARAMETER #define PQXX_H_STATEMENT_PARAMETER #include "pqxx/compiler-public.hxx" #include "pqxx/compiler-internal-pre.hxx" #include <cstring> #include <functional> #include <iterator> #include <string> #include <vector> #include "pqxx/binarystring" #include "pqxx/strconv" #include "pqxx/util" namespace pqxx::internal { template<typename ITERATOR> inline const auto iterator_identity = [](decltype(*std::declval<ITERATOR>()) x){ return x; }; // TODO: C++20 "ranges" alternative. /// Marker type: pass a dynamically-determined number of statement parameters. /** Normally when invoking a prepared or parameterised statement, the number * of parameters is known at compile time. For instance, * @c t.exec_prepared("foo", 1, "x"); executes statement @c foo with two * parameters, an @c int and a C string. * * But sometimes you may want to pass a number of parameters known only at run * time. In those cases, a @c dynamic_params encodes a dynamically * determined number of parameters. You can mix these with regular, static * parameter lists, and you can re-use them for multiple statement invocations. * * A dynamic_params object does not store copies of its parameters, so make * sure they remain accessible until you've executed the statement. * * The ACCESSOR is an optional callable (such as a lambda). If you pass an * accessor @c a, then each parameter @c p goes into your statement as @c a(p). */ template<typename IT, typename ACCESSOR=decltype(iterator_identity<IT>)> class dynamic_params { public: /// Wrap a sequence of pointers or iterators. dynamic_params(IT begin, IT end) : m_begin(begin), m_end(end), m_accessor(iterator_identity<IT>) {} /// Wrap a sequence of pointers or iterators. /** This version takes an accessor callable. If you pass an accessor @c acc, * then any parameter @c p will go into the statement's parameter list as * @c acc(p). */ dynamic_params(IT begin, IT end, ACCESSOR &acc) : m_begin(begin), m_end(end), m_accessor(acc) {} /// Wrap a container. template<typename C> explicit dynamic_params(const C &container) : dynamic_params(std::begin(container), std::end(container)) {} /// Wrap a container. /** This version takes an accessor callable. If you pass an accessor @c acc, * then any parameter @c p will go into the statement's parameter list as * @c acc(p). */ template<typename C> explicit dynamic_params(const C &container, ACCESSOR &acc) : dynamic_params( std::begin(container), std::end(container), acc) {} IT begin() const { return m_begin; } IT end() const { return m_end; } auto access(decltype(*std::declval<IT>()) value) const -> decltype(std::declval<ACCESSOR>()(value)) { return m_accessor(value); } private: const IT m_begin, m_end; ACCESSOR m_accessor = iterator_identity<IT>; }; class PQXX_LIBEXPORT statement_parameters { protected: statement_parameters() =default; statement_parameters &operator=(const statement_parameters &) =delete; void add_param() { this->add_checked_param("", false, false); } template<typename T> void add_param(const T &v, bool nonnull) { nonnull = (nonnull && not is_null(v)); this->add_checked_param( (nonnull ? pqxx::to_string(v) : ""), nonnull, false); } void add_binary_param(const binarystring &b, bool nonnull) { this->add_checked_param(b.str(), nonnull, true); } /// Marshall parameter values into C-compatible arrays for passing to libpq. int marshall( std::vector<const char *> &values, std::vector<int> &lengths, std::vector<int> &binaries) const; private: void add_checked_param(const std::string &value, bool nonnull, bool binary); std::vector<std::string> m_values; std::vector<bool> m_nonnull; std::vector<bool> m_binary; }; /// Internal type: encode statement parameters. /** Compiles arguments for prepared statements and parameterised queries into * a format that can be passed into libpq. * * Objects of this type are meant to be short-lived. If you pass in a non-null * pointer as a parameter, it may simply use that pointer as a parameter value. */ struct params { /// Construct directly from a series of statement arguments. /** The arrays all default to zero, null, and empty strings. */ template<typename ...Args> params(Args && ... args) { strings.reserve(sizeof...(args)); lengths.reserve(sizeof...(args)); nonnulls.reserve(sizeof...(args)); binaries.reserve(sizeof...(args)); // Start recursively storing parameters. add_fields(std::forward<Args>(args)...); } /// Compose a vector of pointers to parameter string values. std::vector<const char *> get_pointers() const { const std::size_t num_fields = lengths.size(); std::size_t cur_string = 0, cur_bin_string = 0; std::vector<const char *> pointers(num_fields); for (std::size_t index = 0; index < num_fields; index++) { const char *value; if (binaries[index]) { value = bin_strings[cur_bin_string].get(); cur_bin_string++; } else if (nonnulls[index]) { value = strings[cur_string].c_str(); cur_string++; } else { value = nullptr; } pointers[index] = value; } return pointers; } /// String values, for string parameters. std::vector<std::string> strings; /// As used by libpq: lengths of non-null arguments, in bytes. std::vector<int> lengths; /// As used by libpq: boolean "is this parameter non-null?" std::vector<int> nonnulls; /// As used by libpq: boolean "is this parameter in binary format?" std::vector<int> binaries; /// Binary string values, for binary parameters. std::vector<pqxx::binarystring> bin_strings; private: /// Add a non-null string field. void add_field(std::string str) { lengths.push_back(int(str.size())); nonnulls.push_back(1); binaries.push_back(0); strings.emplace_back(std::move(str)); } /// Compile one argument (specialised for null pointer, a null value). void add_field(std::nullptr_t) { lengths.push_back(0); nonnulls.push_back(0); binaries.push_back(0); } /// Compile one argument (specialised for binarystring). void add_field(const binarystring &arg) { lengths.push_back(int(arg.size())); nonnulls.push_back(1); binaries.push_back(1); bin_strings.push_back(arg); } /// Compile one argument (default, generic implementation). /** Uses string_traits to represent the argument as a std::string. */ template<typename Arg> void add_field(const Arg &arg) { if (is_null(arg)) add_field(nullptr); else add_field(to_string(arg)); } /// Compile a dynamic_params object into a dynamic number of parameters. template<typename IT, typename ACCESSOR> void add_field(const dynamic_params<IT, ACCESSOR> &parameters) { for (auto param: parameters) add_field(parameters.access(param)); } /// Compile argument list. /** This recursively "peels off" the next remaining element, compiles its * information into its final form, and calls itself for the rest of the * list. * * @param arg Current argument to be compiled. * @param args Optional remaining arguments, to be compiled recursively. */ template<typename Arg, typename ...More> void add_fields(Arg &&arg, More && ... args) { add_field(std::forward<Arg>(arg)); // Compile remaining arguments, if any. add_fields(std::forward<More>(args)...); } /// Terminating version of add_fields, at the end of the list. /** Recursion in add_fields ends with this call. */ void add_fields() {} }; } // namespace pqxx::internal #include "pqxx/compiler-internal-post.hxx" #endif
Simplify "identity" function.
Simplify "identity" function. Thanks @ash-j-f for reporting the problem and finding the solution! Fixes #204.
C++
bsd-3-clause
jtv/libpqxx,jtv/libpqxx,jtv/libpqxx,jtv/libpqxx
b3360332f819b2230a001712fcfdfb0e46a64b53
examples/experimental_average.cpp
examples/experimental_average.cpp
// Experimental average // Source: ./examples/experimental_average.cpp #include <iostream> #include <tuple> #include "qpp.h" int main() { using namespace qpp; ket psi = 0_ket; // same as st.z0; cmat A = gt.X; dyn_col_vect<double> evals = hevals(A); cmat evects = hevects(A); long res = 0; idx N = 10000; // number of "measurement experiments" for (idx i = 0; i < N; ++i) { auto measured = measure(psi, evects); idx m = std::get<RES>(measured); // measurement result if (evals[m] < 0) // -1 --res; else // +1 ++res; } std::cout << ">> N = " << N << " measurements\n"; std::cout << ">> The experimental average of the observable\n"; std::cout << disp(A) << '\n'; std::cout << "on the state\n"; std::cout << disp(psi) << '\n'; std::cout << "is: " << res / static_cast<double>(N) << '\n'; std::cout << ">> Theoretical average <psi | A | psi> = "; std::cout << disp((adjoint(psi) * A * psi).value()) << '\n'; }
// Experimental average // Source: ./examples/experimental_average.cpp #include <iostream> #include <tuple> #include "qpp.h" int main() { using namespace qpp; ket psi = 0_ket; // same as st.z0; cmat X = gt.X; dyn_col_vect<double> evals = hevals(X); cmat evects = hevects(X); long res = 0; idx N = 10000; // number of "measurement experiments" for (idx i = 0; i < N; ++i) { auto measured = measure(psi, evects); idx m = std::get<RES>(measured); // measurement result if (evals[m] < 0) // -1 --res; else // +1 ++res; } std::cout << ">> N = " << N << " measurements\n"; std::cout << ">> The experimental average of the observable X\n"; std::cout << disp(X) << '\n'; std::cout << "on the state psi\n"; std::cout << disp(psi) << '\n'; std::cout << "is: " << res / static_cast<double>(N) << '\n'; std::cout << ">> Theoretical average <psi | X | psi> = "; std::cout << disp((adjoint(psi) * X * psi).value()) << '\n'; }
Update experimental_average.cpp
Update experimental_average.cpp
C++
mit
vsoftco/qpp,QCT-IQC/qpp,QCT-IQC/qpp,QCT-IQC/qpp,vsoftco/qpp,vsoftco/qpp,QCT-IQC/qpp,vsoftco/qpp
53cf77cf18fa44ed60ad586fb9add661853b205a
src/sim/system.hh
src/sim/system.hh
/* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2011 Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Steve Reinhardt * Lisa Hsu * Nathan Binkert * Rick Strong */ #ifndef __SYSTEM_HH__ #define __SYSTEM_HH__ #include <string> #include <utility> #include <vector> #include "base/loader/symtab.hh" #include "base/misc.hh" #include "base/statistics.hh" #include "cpu/pc_event.hh" #include "enums/MemoryMode.hh" #include "kern/system_events.hh" #include "mem/mem_object.hh" #include "mem/port.hh" #include "mem/port_proxy.hh" #include "mem/physical.hh" #include "params/System.hh" class BaseCPU; class BaseRemoteGDB; class GDBListener; class ObjectFile; class Platform; class ThreadContext; class System : public MemObject { private: /** * Private class for the system port which is only used as a * master for debug access and for non-structural entities that do * not have a port of their own. */ class SystemPort : public MasterPort { public: /** * Create a system port with a name and an owner. */ SystemPort(const std::string &_name, MemObject *_owner) : MasterPort(_name, _owner) { } bool recvTimingResp(PacketPtr pkt) { panic("SystemPort does not receive timing!\n"); return false; } void recvRetry() { panic("SystemPort does not expect retry!\n"); } }; SystemPort _systemPort; public: /** * After all objects have been created and all ports are * connected, check that the system port is connected. */ virtual void init(); /** * Get a reference to the system port that can be used by * non-structural simulation objects like processes or threads, or * external entities like loaders and debuggers, etc, to access * the memory system. * * @return a reference to the system port we own */ MasterPort& getSystemPort() { return _systemPort; } /** * Additional function to return the Port of a memory object. */ BaseMasterPort& getMasterPort(const std::string &if_name, PortID idx = InvalidPortID); static const char *MemoryModeStrings[4]; /** @{ */ /** * Is the system in atomic mode? * * There are currently two different atomic memory modes: * 'atomic', which supports caches; and 'atomic_noncaching', which * bypasses caches. The latter is used by hardware virtualized * CPUs. SimObjects are expected to use Port::sendAtomic() and * Port::recvAtomic() when accessing memory in this mode. */ bool isAtomicMode() const { return memoryMode == Enums::atomic || memoryMode == Enums::atomic_noncaching; } /** * Is the system in timing mode? * * SimObjects are expected to use Port::sendTiming() and * Port::recvTiming() when accessing memory in this mode. */ bool isTimingMode() const { return memoryMode == Enums::timing; } /** * Should caches be bypassed? * * Some CPUs need to bypass caches to allow direct memory * accesses, which is required for hardware virtualization. */ bool bypassCaches() const { return memoryMode == Enums::atomic_noncaching; } /** @} */ /** @{ */ /** * Get the memory mode of the system. * * \warn This should only be used by the Python world. The C++ * world should use one of the query functions above * (isAtomicMode(), isTimingMode(), bypassCaches()). */ Enums::MemoryMode getMemoryMode() const { return memoryMode; } /** * Change the memory mode of the system. * * \warn This should only be called by the Python! * * @param mode Mode to change to (atomic/timing/...) */ void setMemoryMode(Enums::MemoryMode mode); /** @} */ /** * Get the cache line size of the system. */ unsigned int cacheLineSize() const { return _cacheLineSize; } #if THE_ISA != NULL_ISA PCEventQueue pcEventQueue; #endif std::vector<ThreadContext *> threadContexts; int _numContexts; ThreadContext *getThreadContext(ThreadID tid) { return threadContexts[tid]; } int numContexts() { assert(_numContexts == (int)threadContexts.size()); return _numContexts; } /** Return number of running (non-halted) thread contexts in * system. These threads could be Active or Suspended. */ int numRunningContexts(); Addr pagePtr; uint64_t init_param; /** Port to physical memory used for writing object files into ram at * boot.*/ PortProxy physProxy; /** kernel symbol table */ SymbolTable *kernelSymtab; /** Object pointer for the kernel code */ ObjectFile *kernel; /** Begining of kernel code */ Addr kernelStart; /** End of kernel code */ Addr kernelEnd; /** Entry point in the kernel to start at */ Addr kernelEntry; /** Mask that should be anded for binary/symbol loading. * This allows one two different OS requirements for the same ISA to be * handled. Some OSes are compiled for a virtual address and need to be * loaded into physical memory that starts at address 0, while other * bare metal tools generate images that start at address 0. */ Addr loadAddrMask; protected: uint64_t nextPID; public: uint64_t allocatePID() { return nextPID++; } /** Get a pointer to access the physical memory of the system */ PhysicalMemory& getPhysMem() { return physmem; } /** Amount of physical memory that is still free */ Addr freeMemSize() const; /** Amount of physical memory that exists */ Addr memSize() const; /** * Check if a physical address is within a range of a memory that * is part of the global address map. * * @param addr A physical address * @return Whether the address corresponds to a memory */ bool isMemAddr(Addr addr) const; protected: PhysicalMemory physmem; Enums::MemoryMode memoryMode; const unsigned int _cacheLineSize; uint64_t workItemsBegin; uint64_t workItemsEnd; uint32_t numWorkIds; std::vector<bool> activeCpus; /** This array is a per-sytem list of all devices capable of issuing a * memory system request and an associated string for each master id. * It's used to uniquely id any master in the system by name for things * like cache statistics. */ std::vector<std::string> masterIds; public: /** Request an id used to create a request object in the system. All objects * that intend to issues requests into the memory system must request an id * in the init() phase of startup. All master ids must be fixed by the * regStats() phase that immediately preceeds it. This allows objects in the * memory system to understand how many masters may exist and * appropriately name the bins of their per-master stats before the stats * are finalized */ MasterID getMasterId(std::string req_name); /** Get the name of an object for a given request id. */ std::string getMasterName(MasterID master_id); /** Get the number of masters registered in the system */ MasterID maxMasters() { return masterIds.size(); } virtual void regStats(); /** * Called by pseudo_inst to track the number of work items started by this * system. */ uint64_t incWorkItemsBegin() { return ++workItemsBegin; } /** * Called by pseudo_inst to track the number of work items completed by * this system. */ uint64_t incWorkItemsEnd() { return ++workItemsEnd; } /** * Called by pseudo_inst to mark the cpus actively executing work items. * Returns the total number of cpus that have executed work item begin or * ends. */ int markWorkItem(int index) { int count = 0; assert(index < activeCpus.size()); activeCpus[index] = true; for (std::vector<bool>::iterator i = activeCpus.begin(); i < activeCpus.end(); i++) { if (*i) count++; } return count; } inline void workItemBegin(uint32_t tid, uint32_t workid) { std::pair<uint32_t,uint32_t> p(tid, workid); lastWorkItemStarted[p] = curTick(); } void workItemEnd(uint32_t tid, uint32_t workid); /** * Fix up an address used to match PCs for hooking simulator * events on to target function executions. See comment in * system.cc for details. */ virtual Addr fixFuncEventAddr(Addr addr) { panic("Base fixFuncEventAddr not implemented.\n"); } /** @{ */ /** * Add a function-based event to the given function, to be looked * up in the specified symbol table. * * The ...OrPanic flavor of the method causes the simulator to * panic if the symbol can't be found. * * @param symtab Symbol table to use for look up. * @param lbl Function to hook the event to. * @param desc Description to be passed to the event. * @param args Arguments to be forwarded to the event constructor. */ template <class T, typename... Args> T *addFuncEvent(const SymbolTable *symtab, const char *lbl, const std::string &desc, Args... args) { Addr addr = 0; // initialize only to avoid compiler warning #if THE_ISA != NULL_ISA if (symtab->findAddress(lbl, addr)) { T *ev = new T(&pcEventQueue, desc, fixFuncEventAddr(addr), std::forward<Args>(args)...); return ev; } #endif return NULL; } template <class T> T *addFuncEvent(const SymbolTable *symtab, const char *lbl) { return addFuncEvent<T>(symtab, lbl, lbl); } template <class T, typename... Args> T *addFuncEventOrPanic(const SymbolTable *symtab, const char *lbl, Args... args) { T *e(addFuncEvent<T>(symtab, lbl, std::forward<Args>(args)...)); if (!e) panic("Failed to find symbol '%s'", lbl); return e; } /** @} */ /** @{ */ /** * Add a function-based event to a kernel symbol. * * These functions work like their addFuncEvent() and * addFuncEventOrPanic() counterparts. The only difference is that * they automatically use the kernel symbol table. All arguments * are forwarded to the underlying method. * * @see addFuncEvent() * @see addFuncEventOrPanic() * * @param lbl Function to hook the event to. * @param args Arguments to be passed to addFuncEvent */ template <class T, typename... Args> T *addKernelFuncEvent(const char *lbl, Args... args) { return addFuncEvent<T>(kernelSymtab, lbl, std::forward<Args>(args)...); } template <class T, typename... Args> T *addKernelFuncEventOrPanic(const char *lbl, Args... args) { T *e(addFuncEvent<T>(kernelSymtab, lbl, std::forward<Args>(args)...)); if (!e) panic("Failed to find kernel symbol '%s'", lbl); return e; } /** @} */ public: std::vector<BaseRemoteGDB *> remoteGDB; std::vector<GDBListener *> gdbListen; bool breakpoint(); public: typedef SystemParams Params; protected: Params *_params; public: System(Params *p); ~System(); void initState(); const Params *params() const { return (const Params *)_params; } public: /** * Returns the addess the kernel starts at. * @return address the kernel starts at */ Addr getKernelStart() const { return kernelStart; } /** * Returns the addess the kernel ends at. * @return address the kernel ends at */ Addr getKernelEnd() const { return kernelEnd; } /** * Returns the addess the entry point to the kernel code. * @return entry point of the kernel code */ Addr getKernelEntry() const { return kernelEntry; } /// Allocate npages contiguous unused physical pages /// @return Starting address of first page Addr allocPhysPages(int npages); int registerThreadContext(ThreadContext *tc, int assigned=-1); void replaceThreadContext(ThreadContext *tc, int context_id); void serialize(std::ostream &os); void unserialize(Checkpoint *cp, const std::string &section); unsigned int drain(DrainManager *dm); void drainResume(); public: Counter totalNumInsts; EventQueue instEventQueue; std::map<std::pair<uint32_t,uint32_t>, Tick> lastWorkItemStarted; std::map<uint32_t, Stats::Histogram*> workItemStats; //////////////////////////////////////////// // // STATIC GLOBAL SYSTEM LIST // //////////////////////////////////////////// static std::vector<System *> systemList; static int numSystemsRunning; static void printSystems(); // For futex system call std::map<uint64_t, std::list<ThreadContext *> * > futexMap; protected: /** * If needed, serialize additional symbol table entries for a * specific subclass of this sytem. Currently this is used by * Alpha and MIPS. * * @param os stream to serialize to */ virtual void serializeSymtab(std::ostream &os) {} /** * If needed, unserialize additional symbol table entries for a * specific subclass of this system. * * @param cp checkpoint to unserialize from * @param section relevant section in the checkpoint */ virtual void unserializeSymtab(Checkpoint *cp, const std::string &section) {} }; void printSystems(); #endif // __SYSTEM_HH__
/* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2011 Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Steve Reinhardt * Lisa Hsu * Nathan Binkert * Rick Strong */ #ifndef __SYSTEM_HH__ #define __SYSTEM_HH__ #include <string> #include <utility> #include <vector> #include "base/loader/symtab.hh" #include "base/misc.hh" #include "base/statistics.hh" #include "cpu/pc_event.hh" #include "enums/MemoryMode.hh" #include "kern/system_events.hh" #include "mem/mem_object.hh" #include "mem/port.hh" #include "mem/port_proxy.hh" #include "mem/physical.hh" #include "params/System.hh" class BaseCPU; class BaseRemoteGDB; class GDBListener; class ObjectFile; class Platform; class ThreadContext; class System : public MemObject { private: /** * Private class for the system port which is only used as a * master for debug access and for non-structural entities that do * not have a port of their own. */ class SystemPort : public MasterPort { public: /** * Create a system port with a name and an owner. */ SystemPort(const std::string &_name, MemObject *_owner) : MasterPort(_name, _owner) { } bool recvTimingResp(PacketPtr pkt) { panic("SystemPort does not receive timing!\n"); return false; } void recvRetry() { panic("SystemPort does not expect retry!\n"); } }; SystemPort _systemPort; public: /** * After all objects have been created and all ports are * connected, check that the system port is connected. */ virtual void init(); /** * Get a reference to the system port that can be used by * non-structural simulation objects like processes or threads, or * external entities like loaders and debuggers, etc, to access * the memory system. * * @return a reference to the system port we own */ MasterPort& getSystemPort() { return _systemPort; } /** * Additional function to return the Port of a memory object. */ BaseMasterPort& getMasterPort(const std::string &if_name, PortID idx = InvalidPortID); static const char *MemoryModeStrings[4]; /** @{ */ /** * Is the system in atomic mode? * * There are currently two different atomic memory modes: * 'atomic', which supports caches; and 'atomic_noncaching', which * bypasses caches. The latter is used by hardware virtualized * CPUs. SimObjects are expected to use Port::sendAtomic() and * Port::recvAtomic() when accessing memory in this mode. */ bool isAtomicMode() const { return memoryMode == Enums::atomic || memoryMode == Enums::atomic_noncaching; } /** * Is the system in timing mode? * * SimObjects are expected to use Port::sendTiming() and * Port::recvTiming() when accessing memory in this mode. */ bool isTimingMode() const { return memoryMode == Enums::timing; } /** * Should caches be bypassed? * * Some CPUs need to bypass caches to allow direct memory * accesses, which is required for hardware virtualization. */ bool bypassCaches() const { return memoryMode == Enums::atomic_noncaching; } /** @} */ /** @{ */ /** * Get the memory mode of the system. * * \warn This should only be used by the Python world. The C++ * world should use one of the query functions above * (isAtomicMode(), isTimingMode(), bypassCaches()). */ Enums::MemoryMode getMemoryMode() const { return memoryMode; } /** * Change the memory mode of the system. * * \warn This should only be called by the Python! * * @param mode Mode to change to (atomic/timing/...) */ void setMemoryMode(Enums::MemoryMode mode); /** @} */ /** * Get the cache line size of the system. */ unsigned int cacheLineSize() const { return _cacheLineSize; } #if THE_ISA != NULL_ISA PCEventQueue pcEventQueue; #endif std::vector<ThreadContext *> threadContexts; int _numContexts; ThreadContext *getThreadContext(ThreadID tid) { return threadContexts[tid]; } int numContexts() { assert(_numContexts == (int)threadContexts.size()); return _numContexts; } /** Return number of running (non-halted) thread contexts in * system. These threads could be Active or Suspended. */ int numRunningContexts(); Addr pagePtr; uint64_t init_param; /** Port to physical memory used for writing object files into ram at * boot.*/ PortProxy physProxy; /** kernel symbol table */ SymbolTable *kernelSymtab; /** Object pointer for the kernel code */ ObjectFile *kernel; /** Begining of kernel code */ Addr kernelStart; /** End of kernel code */ Addr kernelEnd; /** Entry point in the kernel to start at */ Addr kernelEntry; /** Mask that should be anded for binary/symbol loading. * This allows one two different OS requirements for the same ISA to be * handled. Some OSes are compiled for a virtual address and need to be * loaded into physical memory that starts at address 0, while other * bare metal tools generate images that start at address 0. */ Addr loadAddrMask; protected: uint64_t nextPID; public: uint64_t allocatePID() { return nextPID++; } /** Get a pointer to access the physical memory of the system */ PhysicalMemory& getPhysMem() { return physmem; } /** Amount of physical memory that is still free */ Addr freeMemSize() const; /** Amount of physical memory that exists */ Addr memSize() const; /** * Check if a physical address is within a range of a memory that * is part of the global address map. * * @param addr A physical address * @return Whether the address corresponds to a memory */ bool isMemAddr(Addr addr) const; protected: PhysicalMemory physmem; Enums::MemoryMode memoryMode; const unsigned int _cacheLineSize; uint64_t workItemsBegin; uint64_t workItemsEnd; uint32_t numWorkIds; std::vector<bool> activeCpus; /** This array is a per-sytem list of all devices capable of issuing a * memory system request and an associated string for each master id. * It's used to uniquely id any master in the system by name for things * like cache statistics. */ std::vector<std::string> masterIds; public: /** Request an id used to create a request object in the system. All objects * that intend to issues requests into the memory system must request an id * in the init() phase of startup. All master ids must be fixed by the * regStats() phase that immediately preceeds it. This allows objects in the * memory system to understand how many masters may exist and * appropriately name the bins of their per-master stats before the stats * are finalized */ MasterID getMasterId(std::string req_name); /** Get the name of an object for a given request id. */ std::string getMasterName(MasterID master_id); /** Get the number of masters registered in the system */ MasterID maxMasters() { return masterIds.size(); } virtual void regStats(); /** * Called by pseudo_inst to track the number of work items started by this * system. */ uint64_t incWorkItemsBegin() { return ++workItemsBegin; } /** * Called by pseudo_inst to track the number of work items completed by * this system. */ uint64_t incWorkItemsEnd() { return ++workItemsEnd; } /** * Called by pseudo_inst to mark the cpus actively executing work items. * Returns the total number of cpus that have executed work item begin or * ends. */ int markWorkItem(int index) { int count = 0; assert(index < activeCpus.size()); activeCpus[index] = true; for (std::vector<bool>::iterator i = activeCpus.begin(); i < activeCpus.end(); i++) { if (*i) count++; } return count; } inline void workItemBegin(uint32_t tid, uint32_t workid) { std::pair<uint32_t,uint32_t> p(tid, workid); lastWorkItemStarted[p] = curTick(); } void workItemEnd(uint32_t tid, uint32_t workid); /** * Fix up an address used to match PCs for hooking simulator * events on to target function executions. See comment in * system.cc for details. */ virtual Addr fixFuncEventAddr(Addr addr) { panic("Base fixFuncEventAddr not implemented.\n"); } /** @{ */ /** * Add a function-based event to the given function, to be looked * up in the specified symbol table. * * The ...OrPanic flavor of the method causes the simulator to * panic if the symbol can't be found. * * @param symtab Symbol table to use for look up. * @param lbl Function to hook the event to. * @param desc Description to be passed to the event. * @param args Arguments to be forwarded to the event constructor. */ template <class T, typename... Args> T *addFuncEvent(const SymbolTable *symtab, const char *lbl, const std::string &desc, Args... args) { Addr addr M5_VAR_USED = 0; // initialize only to avoid compiler warning #if THE_ISA != NULL_ISA if (symtab->findAddress(lbl, addr)) { T *ev = new T(&pcEventQueue, desc, fixFuncEventAddr(addr), std::forward<Args>(args)...); return ev; } #endif return NULL; } template <class T> T *addFuncEvent(const SymbolTable *symtab, const char *lbl) { return addFuncEvent<T>(symtab, lbl, lbl); } template <class T, typename... Args> T *addFuncEventOrPanic(const SymbolTable *symtab, const char *lbl, Args... args) { T *e(addFuncEvent<T>(symtab, lbl, std::forward<Args>(args)...)); if (!e) panic("Failed to find symbol '%s'", lbl); return e; } /** @} */ /** @{ */ /** * Add a function-based event to a kernel symbol. * * These functions work like their addFuncEvent() and * addFuncEventOrPanic() counterparts. The only difference is that * they automatically use the kernel symbol table. All arguments * are forwarded to the underlying method. * * @see addFuncEvent() * @see addFuncEventOrPanic() * * @param lbl Function to hook the event to. * @param args Arguments to be passed to addFuncEvent */ template <class T, typename... Args> T *addKernelFuncEvent(const char *lbl, Args... args) { return addFuncEvent<T>(kernelSymtab, lbl, std::forward<Args>(args)...); } template <class T, typename... Args> T *addKernelFuncEventOrPanic(const char *lbl, Args... args) { T *e(addFuncEvent<T>(kernelSymtab, lbl, std::forward<Args>(args)...)); if (!e) panic("Failed to find kernel symbol '%s'", lbl); return e; } /** @} */ public: std::vector<BaseRemoteGDB *> remoteGDB; std::vector<GDBListener *> gdbListen; bool breakpoint(); public: typedef SystemParams Params; protected: Params *_params; public: System(Params *p); ~System(); void initState(); const Params *params() const { return (const Params *)_params; } public: /** * Returns the addess the kernel starts at. * @return address the kernel starts at */ Addr getKernelStart() const { return kernelStart; } /** * Returns the addess the kernel ends at. * @return address the kernel ends at */ Addr getKernelEnd() const { return kernelEnd; } /** * Returns the addess the entry point to the kernel code. * @return entry point of the kernel code */ Addr getKernelEntry() const { return kernelEntry; } /// Allocate npages contiguous unused physical pages /// @return Starting address of first page Addr allocPhysPages(int npages); int registerThreadContext(ThreadContext *tc, int assigned=-1); void replaceThreadContext(ThreadContext *tc, int context_id); void serialize(std::ostream &os); void unserialize(Checkpoint *cp, const std::string &section); unsigned int drain(DrainManager *dm); void drainResume(); public: Counter totalNumInsts; EventQueue instEventQueue; std::map<std::pair<uint32_t,uint32_t>, Tick> lastWorkItemStarted; std::map<uint32_t, Stats::Histogram*> workItemStats; //////////////////////////////////////////// // // STATIC GLOBAL SYSTEM LIST // //////////////////////////////////////////// static std::vector<System *> systemList; static int numSystemsRunning; static void printSystems(); // For futex system call std::map<uint64_t, std::list<ThreadContext *> * > futexMap; protected: /** * If needed, serialize additional symbol table entries for a * specific subclass of this sytem. Currently this is used by * Alpha and MIPS. * * @param os stream to serialize to */ virtual void serializeSymtab(std::ostream &os) {} /** * If needed, unserialize additional symbol table entries for a * specific subclass of this system. * * @param cp checkpoint to unserialize from * @param section relevant section in the checkpoint */ virtual void unserializeSymtab(Checkpoint *cp, const std::string &section) {} }; void printSystems(); #endif // __SYSTEM_HH__
Fix clang warning for unused variable
sim: Fix clang warning for unused variable This patch ensures the NULL ISA can build without causing issues with an unused variable.
C++
bsd-3-clause
yb-kim/gemV,austinharris/gem5-riscv,sobercoder/gem5,gem5/gem5,rallylee/gem5,KuroeKurose/gem5,rallylee/gem5,SanchayanMaity/gem5,markoshorro/gem5,HwisooSo/gemV-update,gem5/gem5,briancoutinho0905/2dsampling,sobercoder/gem5,yb-kim/gemV,HwisooSo/gemV-update,briancoutinho0905/2dsampling,qizenguf/MLC-STT,HwisooSo/gemV-update,powerjg/gem5-ci-test,gem5/gem5,rallylee/gem5,yb-kim/gemV,powerjg/gem5-ci-test,cancro7/gem5,briancoutinho0905/2dsampling,gem5/gem5,powerjg/gem5-ci-test,gedare/gem5,aclifton/cpeg853-gem5,KuroeKurose/gem5,yb-kim/gemV,kaiyuanl/gem5,rjschof/gem5,Weil0ng/gem5,qizenguf/MLC-STT,gedare/gem5,sobercoder/gem5,cancro7/gem5,kaiyuanl/gem5,TUD-OS/gem5-dtu,cancro7/gem5,aclifton/cpeg853-gem5,HwisooSo/gemV-update,KuroeKurose/gem5,KuroeKurose/gem5,aclifton/cpeg853-gem5,Weil0ng/gem5,rjschof/gem5,rjschof/gem5,TUD-OS/gem5-dtu,sobercoder/gem5,HwisooSo/gemV-update,SanchayanMaity/gem5,zlfben/gem5,zlfben/gem5,gem5/gem5,cancro7/gem5,rjschof/gem5,zlfben/gem5,briancoutinho0905/2dsampling,TUD-OS/gem5-dtu,markoshorro/gem5,aclifton/cpeg853-gem5,Weil0ng/gem5,yb-kim/gemV,austinharris/gem5-riscv,yb-kim/gemV,qizenguf/MLC-STT,gedare/gem5,Weil0ng/gem5,KuroeKurose/gem5,gedare/gem5,powerjg/gem5-ci-test,KuroeKurose/gem5,rjschof/gem5,qizenguf/MLC-STT,HwisooSo/gemV-update,gedare/gem5,kaiyuanl/gem5,rjschof/gem5,cancro7/gem5,kaiyuanl/gem5,sobercoder/gem5,rjschof/gem5,gedare/gem5,powerjg/gem5-ci-test,markoshorro/gem5,gedare/gem5,yb-kim/gemV,kaiyuanl/gem5,rallylee/gem5,cancro7/gem5,rallylee/gem5,HwisooSo/gemV-update,powerjg/gem5-ci-test,aclifton/cpeg853-gem5,zlfben/gem5,SanchayanMaity/gem5,gem5/gem5,zlfben/gem5,sobercoder/gem5,rallylee/gem5,SanchayanMaity/gem5,markoshorro/gem5,austinharris/gem5-riscv,gem5/gem5,briancoutinho0905/2dsampling,markoshorro/gem5,markoshorro/gem5,SanchayanMaity/gem5,kaiyuanl/gem5,qizenguf/MLC-STT,austinharris/gem5-riscv,rallylee/gem5,briancoutinho0905/2dsampling,cancro7/gem5,briancoutinho0905/2dsampling,TUD-OS/gem5-dtu,austinharris/gem5-riscv,zlfben/gem5,zlfben/gem5,qizenguf/MLC-STT,aclifton/cpeg853-gem5,SanchayanMaity/gem5,markoshorro/gem5,TUD-OS/gem5-dtu,austinharris/gem5-riscv,austinharris/gem5-riscv,yb-kim/gemV,Weil0ng/gem5,qizenguf/MLC-STT,Weil0ng/gem5,aclifton/cpeg853-gem5,sobercoder/gem5,KuroeKurose/gem5,kaiyuanl/gem5,TUD-OS/gem5-dtu,SanchayanMaity/gem5,Weil0ng/gem5,powerjg/gem5-ci-test,TUD-OS/gem5-dtu
6b627be655a28aaba3b72b948a810675af02b9a9
src/lib/libkeynote_xml.cpp
src/lib/libkeynote_xml.cpp
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libkeynote project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "libkeynote_xml.h" namespace libkeynote { namespace { struct XMLException {}; } bool moveToNextNode(xmlTextReaderPtr reader) { int type = 0; do { const int ret = xmlTextReaderRead(reader); if (ret == -1) throw XMLException(); else if (ret == 0) return false; type = xmlTextReaderNodeType(reader); } while ((XML_READER_TYPE_ELEMENT != type) || (XML_READER_TYPE_END_ELEMENT != type) || (XML_READER_TYPE_TEXT != type)); return true; } void skipElement(xmlTextReaderPtr reader) { int level = 1; int ret = xmlTextReaderRead(reader); while ((1 == ret) && (0 < level)) { switch (xmlTextReaderNodeType(reader)) { case XML_READER_TYPE_ELEMENT : if (!xmlTextReaderIsEmptyElement(reader)) ++level; break; case XML_READER_TYPE_END_ELEMENT : --level; break; } ret = xmlTextReaderRead(reader); } if ((-1 == ret) || (0 != level)) throw XMLException(); } bool isElement(xmlTextReaderPtr reader) { return isStartElement(reader) || isEndElement(reader); } bool isEmptyElement(xmlTextReaderPtr reader) { return xmlTextReaderIsEmptyElement(reader); } bool isStartElement(xmlTextReaderPtr reader) { return XML_READER_TYPE_ELEMENT == xmlTextReaderNodeType(reader); } bool isEndElement(xmlTextReaderPtr reader) { return XML_READER_TYPE_END_ELEMENT == xmlTextReaderNodeType(reader); } const char *getName(xmlTextReaderPtr reader) { return reinterpret_cast<const char *>(xmlTextReaderConstLocalName(reader)); } const char *getNamespace(xmlTextReaderPtr reader) { return reinterpret_cast<const char *>(xmlTextReaderConstNamespaceUri(reader)); } const char *getText(xmlTextReaderPtr reader) { return reinterpret_cast<const char *>(xmlTextReaderConstValue(reader)); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libkeynote project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "libkeynote_xml.h" namespace libkeynote { namespace { struct XMLException {}; } bool moveToNextNode(xmlTextReaderPtr reader) { int type = 0; do { const int ret = xmlTextReaderRead(reader); if (ret == -1) throw XMLException(); else if (ret == 0) return false; type = xmlTextReaderNodeType(reader); } while (!((XML_READER_TYPE_ELEMENT == type) || (XML_READER_TYPE_END_ELEMENT == type) || (XML_READER_TYPE_TEXT == type))); return true; } void skipElement(xmlTextReaderPtr reader) { int level = 1; int ret = xmlTextReaderRead(reader); while ((1 == ret) && (0 < level)) { switch (xmlTextReaderNodeType(reader)) { case XML_READER_TYPE_ELEMENT : if (!xmlTextReaderIsEmptyElement(reader)) ++level; break; case XML_READER_TYPE_END_ELEMENT : --level; break; } ret = xmlTextReaderRead(reader); } if ((-1 == ret) || (0 != level)) throw XMLException(); } bool isElement(xmlTextReaderPtr reader) { return isStartElement(reader) || isEndElement(reader); } bool isEmptyElement(xmlTextReaderPtr reader) { return xmlTextReaderIsEmptyElement(reader); } bool isStartElement(xmlTextReaderPtr reader) { return XML_READER_TYPE_ELEMENT == xmlTextReaderNodeType(reader); } bool isEndElement(xmlTextReaderPtr reader) { return XML_READER_TYPE_END_ELEMENT == xmlTextReaderNodeType(reader); } const char *getName(xmlTextReaderPtr reader) { return reinterpret_cast<const char *>(xmlTextReaderConstLocalName(reader)); } const char *getNamespace(xmlTextReaderPtr reader) { return reinterpret_cast<const char *>(xmlTextReaderConstNamespaceUri(reader)); } const char *getText(xmlTextReaderPtr reader) { return reinterpret_cast<const char *>(xmlTextReaderConstValue(reader)); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */
fix condition
fix condition
C++
mpl-2.0
freedesktop-unofficial-mirror/libreoffice__libetonyek,freedesktop-unofficial-mirror/libreoffice__libetonyek,LibreOffice/libetonyek,LibreOffice/libetonyek,LibreOffice/libetonyek,freedesktop-unofficial-mirror/libreoffice__libetonyek
bcfa32cd8184b100e0ea9e1bac78544b814ab902
src/modules/opengl/transition_movit_overlay.cpp
src/modules/opengl/transition_movit_overlay.cpp
/* * transition_movit_overlay.cpp * Copyright (C) 2013 Dan Dennedy <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <framework/mlt.h> #include <string.h> #include <assert.h> #include "glsl_manager.h" #include <movit/init.h> #include <movit/effect_chain.h> #include <movit/util.h> #include <movit/overlay_effect.h> #include "mlt_movit_input.h" #include "mlt_flip_effect.h" static int get_image( mlt_frame a_frame, uint8_t **image, mlt_image_format *format, int *width, int *height, int writable ) { int error = 0; // Get the b frame from the stack mlt_frame b_frame = (mlt_frame) mlt_frame_pop_frame( a_frame ); // Get the transition object mlt_transition transition = (mlt_transition) mlt_frame_pop_service( a_frame ); // Get the properties of the transition mlt_properties properties = MLT_TRANSITION_PROPERTIES( transition ); // Get the properties of the a frame mlt_properties a_props = MLT_FRAME_PROPERTIES( a_frame ); // Get the movit objects mlt_service service = MLT_TRANSITION_SERVICE( transition ); mlt_service_lock( service ); EffectChain* chain = GlslManager::get_chain( service ); MltInput* a_input = GlslManager::get_input( service ); MltInput* b_input = (MltInput*) mlt_properties_get_data( properties, "movit input B", NULL ); mlt_image_format output_format = *format; if ( !chain || !a_input ) { mlt_service_unlock( service ); return 2; } // Get the frames' textures GLuint* texture_id[2] = {0, 0}; *format = mlt_image_glsl_texture; mlt_frame_get_image( a_frame, (uint8_t**) &texture_id[0], format, width, height, 0 ); a_input->useFBOInput( chain, *texture_id[0] ); *format = mlt_image_glsl_texture; mlt_frame_get_image( b_frame, (uint8_t**) &texture_id[1], format, width, height, 0 ); b_input->useFBOInput( chain, *texture_id[1] ); // Set resolution to that of the a_frame *width = mlt_properties_get_int( a_props, "width" ); *height = mlt_properties_get_int( a_props, "height" ); // Setup rendering to an FBO GlslManager* glsl = GlslManager::get_instance(); glsl_fbo fbo = glsl->get_fbo( *width, *height ); if ( output_format == mlt_image_glsl_texture ) { glsl_texture texture = glsl->get_texture( *width, *height, GL_RGBA ); glBindFramebuffer( GL_FRAMEBUFFER, fbo->fbo ); check_error(); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); GlslManager::render( service, chain, fbo->fbo, *width, *height ); glFinish(); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); *image = (uint8_t*) &texture->texture; mlt_frame_set_image( a_frame, *image, 0, NULL ); mlt_properties_set_data( properties, "movit.convert", texture, 0, (mlt_destructor) GlslManager::release_texture, NULL ); *format = output_format; } else { // Use a PBO to hold the data we read back with glReadPixels() // (Intel/DRI goes into a slow path if we don't read to PBO) GLenum gl_format = ( output_format == mlt_image_rgb24a || output_format == mlt_image_opengl )? GL_RGBA : GL_RGB; int img_size = *width * *height * ( gl_format == GL_RGB? 3 : 4 ); glsl_pbo pbo = glsl->get_pbo( img_size ); glsl_texture texture = glsl->get_texture( *width, *height, gl_format ); if ( fbo && pbo && texture ) { // Set the FBO glBindFramebuffer( GL_FRAMEBUFFER, fbo->fbo ); check_error(); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); GlslManager::render( service, chain, fbo->fbo, *width, *height ); // Read FBO into PBO glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, pbo->pbo ); check_error(); glBufferData( GL_PIXEL_PACK_BUFFER_ARB, img_size, NULL, GL_STREAM_READ ); check_error(); glReadPixels( 0, 0, *width, *height, gl_format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0) ); check_error(); // Copy from PBO uint8_t* buf = (uint8_t*) glMapBuffer( GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY ); check_error(); *format = gl_format == GL_RGBA ? mlt_image_rgb24a : mlt_image_rgb24; *image = (uint8_t*) mlt_pool_alloc( img_size ); mlt_frame_set_image( a_frame, *image, img_size, mlt_pool_release ); memcpy( *image, buf, img_size ); // Release PBO and FBO glUnmapBuffer( GL_PIXEL_PACK_BUFFER_ARB ); check_error(); glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, 0 ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); glBindTexture( GL_TEXTURE_2D, 0 ); check_error(); GlslManager::release_texture( texture ); } else { error = 1; } } if ( fbo ) GlslManager::release_fbo( fbo ); mlt_service_lock( service ); return error; } static mlt_frame process( mlt_transition transition, mlt_frame a_frame, mlt_frame b_frame ) { mlt_service service = MLT_TRANSITION_SERVICE(transition); if ( !GlslManager::init_chain( service ) ) { // Create the Movit effect chain EffectChain* chain = GlslManager::get_chain( service ); mlt_profile profile = mlt_service_profile( service ); Input* b_input = new MltInput( profile->width, profile->height ); ImageFormat output_format; output_format.color_space = COLORSPACE_sRGB; output_format.gamma_curve = GAMMA_sRGB; chain->add_input( b_input ); chain->add_output( output_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED ); chain->set_dither_bits( 8 ); Effect* effect = chain->add_effect( new OverlayEffect(), GlslManager::get_input( service ), b_input ); // Save these new input on properties for get_image mlt_properties_set_data( MLT_TRANSITION_PROPERTIES(transition), "movit input B", b_input, 0, NULL, NULL ); } // Push the transition on to the frame mlt_frame_push_service( a_frame, transition ); // Push the b_frame on to the stack mlt_frame_push_frame( a_frame, b_frame ); // Push the transition method mlt_frame_push_get_image( a_frame, get_image ); return a_frame; } extern "C" mlt_transition transition_movit_overlay_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg ) { mlt_transition transition = NULL; GlslManager* glsl = GlslManager::get_instance(); if ( glsl && ( transition = mlt_transition_new() ) ) { transition->process = process; // Inform apps and framework that this is a video only transition mlt_properties_set_int( MLT_TRANSITION_PROPERTIES( transition ), "_transition_type", 1 ); } return transition; }
/* * transition_movit_overlay.cpp * Copyright (C) 2013 Dan Dennedy <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <framework/mlt.h> #include <string.h> #include <assert.h> #include "glsl_manager.h" #include <movit/init.h> #include <movit/effect_chain.h> #include <movit/util.h> #include <movit/overlay_effect.h> #include "mlt_movit_input.h" #include "mlt_flip_effect.h" static int get_image( mlt_frame a_frame, uint8_t **image, mlt_image_format *format, int *width, int *height, int writable ) { int error = 0; // Get the b frame from the stack mlt_frame b_frame = (mlt_frame) mlt_frame_pop_frame( a_frame ); // Get the transition object mlt_transition transition = (mlt_transition) mlt_frame_pop_service( a_frame ); // Get the properties of the transition mlt_properties properties = MLT_TRANSITION_PROPERTIES( transition ); // Get the properties of the a frame mlt_properties a_props = MLT_FRAME_PROPERTIES( a_frame ); // Get the movit objects mlt_service service = MLT_TRANSITION_SERVICE( transition ); mlt_service_lock( service ); EffectChain* chain = GlslManager::get_chain( service ); MltInput* a_input = GlslManager::get_input( service ); MltInput* b_input = (MltInput*) mlt_properties_get_data( properties, "movit input B", NULL ); mlt_image_format output_format = *format; if ( !chain || !a_input ) { mlt_service_unlock( service ); return 2; } // Get the frames' textures GLuint* texture_id[2] = {0, 0}; *format = mlt_image_glsl_texture; mlt_frame_get_image( a_frame, (uint8_t**) &texture_id[0], format, width, height, 0 ); a_input->useFBOInput( chain, *texture_id[0] ); *format = mlt_image_glsl_texture; mlt_frame_get_image( b_frame, (uint8_t**) &texture_id[1], format, width, height, 0 ); b_input->useFBOInput( chain, *texture_id[1] ); // Set resolution to that of the a_frame *width = mlt_properties_get_int( a_props, "width" ); *height = mlt_properties_get_int( a_props, "height" ); // Setup rendering to an FBO GlslManager* glsl = GlslManager::get_instance(); glsl_fbo fbo = glsl->get_fbo( *width, *height ); if ( output_format == mlt_image_glsl_texture ) { glsl_texture texture = glsl->get_texture( *width, *height, GL_RGBA ); glBindFramebuffer( GL_FRAMEBUFFER, fbo->fbo ); check_error(); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); GlslManager::render( service, chain, fbo->fbo, *width, *height ); glFinish(); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); *image = (uint8_t*) &texture->texture; mlt_frame_set_image( a_frame, *image, 0, NULL ); mlt_properties_set_data( properties, "movit.convert", texture, 0, (mlt_destructor) GlslManager::release_texture, NULL ); *format = output_format; } else { // Use a PBO to hold the data we read back with glReadPixels() // (Intel/DRI goes into a slow path if we don't read to PBO) GLenum gl_format = ( output_format == mlt_image_rgb24a || output_format == mlt_image_opengl )? GL_RGBA : GL_RGB; int img_size = *width * *height * ( gl_format == GL_RGB? 3 : 4 ); glsl_pbo pbo = glsl->get_pbo( img_size ); glsl_texture texture = glsl->get_texture( *width, *height, gl_format ); if ( fbo && pbo && texture ) { // Set the FBO glBindFramebuffer( GL_FRAMEBUFFER, fbo->fbo ); check_error(); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); GlslManager::render( service, chain, fbo->fbo, *width, *height ); // Read FBO into PBO glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, pbo->pbo ); check_error(); glBufferData( GL_PIXEL_PACK_BUFFER_ARB, img_size, NULL, GL_STREAM_READ ); check_error(); glReadPixels( 0, 0, *width, *height, gl_format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0) ); check_error(); // Copy from PBO uint8_t* buf = (uint8_t*) glMapBuffer( GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY ); check_error(); *format = gl_format == GL_RGBA ? mlt_image_rgb24a : mlt_image_rgb24; *image = (uint8_t*) mlt_pool_alloc( img_size ); mlt_frame_set_image( a_frame, *image, img_size, mlt_pool_release ); memcpy( *image, buf, img_size ); // Release PBO and FBO glUnmapBuffer( GL_PIXEL_PACK_BUFFER_ARB ); check_error(); glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, 0 ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); glBindTexture( GL_TEXTURE_2D, 0 ); check_error(); GlslManager::release_texture( texture ); } else { error = 1; } } if ( fbo ) GlslManager::release_fbo( fbo ); mlt_service_unlock( service ); return error; } static mlt_frame process( mlt_transition transition, mlt_frame a_frame, mlt_frame b_frame ) { mlt_service service = MLT_TRANSITION_SERVICE(transition); if ( !GlslManager::init_chain( service ) ) { // Create the Movit effect chain EffectChain* chain = GlslManager::get_chain( service ); mlt_profile profile = mlt_service_profile( service ); Input* b_input = new MltInput( profile->width, profile->height ); ImageFormat output_format; output_format.color_space = COLORSPACE_sRGB; output_format.gamma_curve = GAMMA_sRGB; chain->add_input( b_input ); chain->add_output( output_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED ); chain->set_dither_bits( 8 ); Effect* effect = chain->add_effect( new OverlayEffect(), GlslManager::get_input( service ), b_input ); // Save these new input on properties for get_image mlt_properties_set_data( MLT_TRANSITION_PROPERTIES(transition), "movit input B", b_input, 0, NULL, NULL ); } // Push the transition on to the frame mlt_frame_push_service( a_frame, transition ); // Push the b_frame on to the stack mlt_frame_push_frame( a_frame, b_frame ); // Push the transition method mlt_frame_push_get_image( a_frame, get_image ); return a_frame; } extern "C" mlt_transition transition_movit_overlay_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg ) { mlt_transition transition = NULL; GlslManager* glsl = GlslManager::get_instance(); if ( glsl && ( transition = mlt_transition_new() ) ) { transition->process = process; // Inform apps and framework that this is a video only transition mlt_properties_set_int( MLT_TRANSITION_PROPERTIES( transition ), "_transition_type", 1 ); } return transition; }
Fix deadlock in movit.overlay transition.
Fix deadlock in movit.overlay transition. Patch by Steinar Gunderson.
C++
lgpl-2.1
mltframework/mlt,zzhhui/mlt,xzhavilla/mlt,wideioltd/mlt,mltframework/mlt,mltframework/mlt,zzhhui/mlt,zzhhui/mlt,anba8005/mlt,j-b-m/mlt,zzhhui/mlt,mltframework/mlt,siddharudh/mlt,wideioltd/mlt,siddharudh/mlt,wideioltd/mlt,j-b-m/mlt,siddharudh/mlt,xzhavilla/mlt,wideioltd/mlt,j-b-m/mlt,j-b-m/mlt,zzhhui/mlt,xzhavilla/mlt,siddharudh/mlt,anba8005/mlt,xzhavilla/mlt,zzhhui/mlt,j-b-m/mlt,xzhavilla/mlt,siddharudh/mlt,siddharudh/mlt,xzhavilla/mlt,mltframework/mlt,xzhavilla/mlt,wideioltd/mlt,siddharudh/mlt,j-b-m/mlt,siddharudh/mlt,siddharudh/mlt,anba8005/mlt,anba8005/mlt,anba8005/mlt,mltframework/mlt,anba8005/mlt,j-b-m/mlt,wideioltd/mlt,wideioltd/mlt,anba8005/mlt,mltframework/mlt,zzhhui/mlt,mltframework/mlt,j-b-m/mlt,anba8005/mlt,wideioltd/mlt,wideioltd/mlt,xzhavilla/mlt,zzhhui/mlt,mltframework/mlt,zzhhui/mlt,xzhavilla/mlt,anba8005/mlt,j-b-m/mlt,mltframework/mlt,j-b-m/mlt
bec9a518a3f189bca9579a99e7d12fc10f6bd1bc
src/libslic3r/SLAPrint.hpp
src/libslic3r/SLAPrint.hpp
#ifndef slic3r_SLAPrint_hpp_ #define slic3r_SLAPrint_hpp_ #include <mutex> #include "PrintBase.hpp" #include "PrintExport.hpp" #include "Point.hpp" #include "MTUtils.hpp" #include <iterator> namespace Slic3r { enum SLAPrintStep : unsigned int { slapsRasterize, slapsValidate, slapsCount }; enum SLAPrintObjectStep : unsigned int { slaposObjectSlice, slaposSupportPoints, slaposSupportTree, slaposBasePool, slaposSliceSupports, slaposIndexSlices, slaposCount }; class SLAPrint; class GLCanvas; using _SLAPrintObjectBase = PrintObjectBaseWithState<SLAPrint, SLAPrintObjectStep, slaposCount>; // Layers according to quantized height levels. This will be consumed by // the printer (rasterizer) in the SLAPrint class. // using coord_t = long long; enum SliceOrigin { soSupport, soModel }; class SLAPrintObject; // The public Slice record structure. It corresponds to one printable layer. class SliceRecord { public: // this will be the max limit of size_t static const size_t NONE = size_t(-1); static const SliceRecord EMPTY; private: coord_t m_print_z = 0; // Top of the layer float m_slice_z = 0.f; // Exact level of the slice float m_height = 0.f; // Height of the sliced layer size_t m_model_slices_idx = NONE; size_t m_support_slices_idx = NONE; const SLAPrintObject *m_po = nullptr; public: SliceRecord(coord_t key, float slicez, float height): m_print_z(key), m_slice_z(slicez), m_height(height) {} // The key will be the integer height level of the top of the layer. coord_t print_level() const { return m_print_z; } // Returns the exact floating point Z coordinate of the slice float slice_level() const { return m_slice_z; } // Returns the current layer height float layer_height() const { return m_height; } bool is_valid() const { return std::isnan(m_slice_z); } const SLAPrintObject* print_obj() const { return m_po; } // Methods for setting the indices into the slice vectors. void set_model_slice_idx(const SLAPrintObject &po, size_t id) { m_po = &po; m_model_slices_idx = id; } void set_support_slice_idx(const SLAPrintObject& po, size_t id) { m_po = &po; m_support_slices_idx = id; } const ExPolygons& get_slice(SliceOrigin o) const; }; class SLAPrintObject : public _SLAPrintObjectBase { private: // Prevents erroneous use by other classes. using Inherited = _SLAPrintObjectBase; public: // I refuse to grantee copying (Tamas) SLAPrintObject(const SLAPrintObject&) = delete; SLAPrintObject& operator=(const SLAPrintObject&) = delete; const SLAPrintObjectConfig& config() const { return m_config; } const Transform3d& trafo() const { return m_trafo; } struct Instance { Instance(ModelID instance_id, const Point &shift, float rotation) : instance_id(instance_id), shift(shift), rotation(rotation) {} bool operator==(const Instance &rhs) const { return this->instance_id == rhs.instance_id && this->shift == rhs.shift && this->rotation == rhs.rotation; } // ID of the corresponding ModelInstance. ModelID instance_id; // Slic3r::Point objects in scaled G-code coordinates Point shift; // Rotation along the Z axis, in radians. float rotation; }; const std::vector<Instance>& instances() const { return m_instances; } bool has_mesh(SLAPrintObjectStep step) const; TriangleMesh get_mesh(SLAPrintObjectStep step) const; // Get a support mesh centered around origin in XY, and with zero rotation around Z applied. // Support mesh is only valid if this->is_step_done(slaposSupportTree) is true. const TriangleMesh& support_mesh() const; // Get a pad mesh centered around origin in XY, and with zero rotation around Z applied. // Support mesh is only valid if this->is_step_done(slaposBasePool) is true. const TriangleMesh& pad_mesh() const; // This will return the transformed mesh which is cached const TriangleMesh& transformed_mesh() const; std::vector<sla::SupportPoint> transformed_support_points() const; // Get the needed Z elevation for the model geometry if supports should be // displayed. This Z offset should also be applied to the support // geometries. Note that this is not the same as the value stored in config // as the pad height also needs to be considered. double get_elevation() const; // This method returns the needed elevation according to the processing // status. If the supports are not ready, it is zero, if they are and the // pad is not, then without the pad, otherwise the full value is returned. double get_current_elevation() const; // This method returns the support points of this SLAPrintObject. const std::vector<sla::SupportPoint>& get_support_points() const; private: template <class T> inline static T level(const SliceRecord& sr) { static_assert(std::is_arithmetic<T>::value, "Arithmetic only!"); return std::is_integral<T>::value ? T(sr.print_level()) : T(sr.slice_level()); } template <class T> inline static SliceRecord create_slice_record(T val) { static_assert(std::is_arithmetic<T>::value, "Arithmetic only!"); return std::is_integral<T>::value ? SliceRecord{ coord_t(val), 0.f, 0.f } : SliceRecord{ 0, float(val), 0.f }; } // This is a template method for searching the slice index either by // an integer key: print_level or a floating point key: slice_level. // The eps parameter gives the max deviation in + or - direction. // // This method can be used in const or non-const contexts as well. template<class Container, class T> static auto closest_slice_record(Container& cont, T lvl, T eps) -> decltype (cont.begin()) { if(cont.empty()) return cont.end(); if(cont.size() == 1 && std::abs(level<T>(cont.front()) - lvl) > eps) return cont.end(); SliceRecord query = create_slice_record(lvl); auto it = std::lower_bound(cont.begin(), cont.end(), query, [](const SliceRecord& r1, const SliceRecord& r2) { return level<T>(r1) < level<T>(r2); }); T diff = std::abs(level<T>(*it) - lvl); if(it != cont.begin()) { auto it_prev = std::prev(it); T diff_prev = std::abs(level<T>(*it_prev) - lvl); if(diff_prev < diff) { diff = diff_prev; it = it_prev; } } if(diff > eps) it = cont.end(); return it; } public: // ///////////////////////////////////////////////////////////////////////// // // These methods should be callable on the client side (e.g. UI thread) // when the appropriate steps slaposObjectSlice and slaposSliceSupports // are ready. All the print objects are processed before slapsRasterize so // it is safe to call them during and/or after slapsRasterize. // // ///////////////////////////////////////////////////////////////////////// // Retrieve the slice index. const std::vector<SliceRecord>& get_slice_index() const; const std::vector<ExPolygons>& get_model_slices() const; const std::vector<ExPolygons>& get_support_slices() const; // Search slice index for the closest slice to given print_level. // max_epsilon gives the allowable deviation of the returned slice record's // level. const SliceRecord& closest_slice_to_print_level( coord_t print_level, coord_t max_epsilon = coord_t(SCALED_EPSILON)) const { auto it = closest_slice_record(m_slice_index, print_level, max_epsilon); if (it == m_slice_index.end()) return SliceRecord::EMPTY; return *it; } // Search slice index for the closest slice to given slice_level. // max_epsilon gives the allowable deviation of the returned slice record's // level. const SliceRecord& closest_slice_to_slice_level( float slice_level, float max_epsilon = float(EPSILON)) const { auto it = closest_slice_record(m_slice_index, slice_level, max_epsilon); if (it == m_slice_index.end()) return SliceRecord::EMPTY; return *it; } protected: // to be called from SLAPrint only. friend class SLAPrint; SLAPrintObject(SLAPrint* print, ModelObject* model_object); ~SLAPrintObject(); void config_apply(const ConfigBase &other, bool ignore_nonexistent = false) { this->m_config.apply(other, ignore_nonexistent); } void config_apply_only(const ConfigBase &other, const t_config_option_keys &keys, bool ignore_nonexistent = false) { this->m_config.apply_only(other, keys, ignore_nonexistent); } void set_trafo(const Transform3d& trafo) { m_transformed_rmesh.invalidate([this, &trafo](){ m_trafo = trafo; }); } void set_instances(const std::vector<Instance> &instances) { m_instances = instances; } // Invalidates the step, and its depending steps in SLAPrintObject and SLAPrint. bool invalidate_step(SLAPrintObjectStep step); bool invalidate_all_steps(); // Invalidate steps based on a set of parameters changed. bool invalidate_state_by_config_options(const std::vector<t_config_option_key> &opt_keys); // Which steps have to be performed. Implicitly: all // to be accessible from SLAPrint std::vector<bool> m_stepmask; private: // Object specific configuration, pulled from the configuration layer. SLAPrintObjectConfig m_config; // Translation in Z + Rotation by Y and Z + Scaling / Mirroring. Transform3d m_trafo = Transform3d::Identity(); std::vector<Instance> m_instances; // Individual 2d slice polygons from lower z to higher z levels std::vector<ExPolygons> m_model_slices; // Exact (float) height levels mapped to the slices. Each record contains // the index to the model and the support slice vectors. std::vector<SliceRecord> m_slice_index; std::vector<float> m_model_height_levels; // Caching the transformed (m_trafo) raw mesh of the object mutable CachedObject<TriangleMesh> m_transformed_rmesh; class SupportData; std::unique_ptr<SupportData> m_supportdata; }; using PrintObjects = std::vector<SLAPrintObject*>; class TriangleMesh; struct SLAPrintStatistics { SLAPrintStatistics() { clear(); } std::string estimated_print_time; double objects_used_material; double support_used_material; size_t slow_layers_count; size_t fast_layers_count; double total_cost; double total_weight; // Config with the filled in print statistics. DynamicConfig config() const; // Config with the statistics keys populated with placeholder strings. static DynamicConfig placeholders(); // Replace the print statistics placeholders in the path. std::string finalize_output_path(const std::string &path_in) const; void clear() { estimated_print_time.clear(); objects_used_material = 0.; support_used_material = 0.; slow_layers_count = 0; fast_layers_count = 0; total_cost = 0.; total_weight = 0.; } }; /** * @brief This class is the high level FSM for the SLA printing process. * * It should support the background processing framework and contain the * metadata for the support geometries and their slicing. It should also * dispatch the SLA printing configuration values to the appropriate calculation * steps. */ class SLAPrint : public PrintBaseWithState<SLAPrintStep, slapsCount> { private: // Prevents erroneous use by other classes. typedef PrintBaseWithState<SLAPrintStep, slapsCount> Inherited; public: // An aggregation of SliceRecord-s from all the print objects for each // occupied layer. Slice record levels dont have to match exactly. // They are unified if the level difference is within +/- SCALED_EPSILON struct PrintLayer { coord_t level; // The collection of slice records for the current level. std::vector<std::reference_wrapper<const SliceRecord>> slices; explicit PrintLayer(coord_t lvl) : level(lvl) {} // for being sorted in their container (see m_printer_input) bool operator<(const PrintLayer& other) const { return level < other.level; } }; SLAPrint(): m_stepmask(slapsCount, true) {} virtual ~SLAPrint() override { this->clear(); } PrinterTechnology technology() const noexcept override { return ptSLA; } void clear() override; bool empty() const override { return m_objects.empty(); } ApplyStatus apply(const Model &model, const DynamicPrintConfig &config) override; void set_task(const TaskParams &params) override; void process() override; void finalize() override; // Returns true if an object step is done on all objects and there's at least one object. bool is_step_done(SLAPrintObjectStep step) const; // Returns true if the last step was finished with success. bool finished() const override { return this->is_step_done(slaposIndexSlices) && this->Inherited::is_step_done(slapsRasterize); } template<class Fmt> void export_raster(const std::string& fname) { if(m_printer) m_printer->save<Fmt>(fname); } const PrintObjects& objects() const { return m_objects; } const SLAPrintConfig& print_config() const { return m_print_config; } const SLAPrinterConfig& printer_config() const { return m_printer_config; } const SLAMaterialConfig& material_config() const { return m_material_config; } const SLAPrintObjectConfig& default_object_config() const { return m_default_object_config; } std::string output_filename() const override; const SLAPrintStatistics& print_statistics() const { return m_print_statistics; } std::string validate() const override; // The aggregated and leveled print records from various objects. // TODO: use this structure for the preview in the future. const std::vector<PrintLayer>& print_layers() const { return m_printer_input; } private: using SLAPrinter = FilePrinter<FilePrinterFormat::SLA_PNGZIP>; using SLAPrinterPtr = std::unique_ptr<SLAPrinter>; // Invalidate steps based on a set of parameters changed. bool invalidate_state_by_config_options(const std::vector<t_config_option_key> &opt_keys); void fill_statistics(); SLAPrintConfig m_print_config; SLAPrinterConfig m_printer_config; SLAMaterialConfig m_material_config; SLAPrintObjectConfig m_default_object_config; PrintObjects m_objects; std::vector<bool> m_stepmask; // Ready-made data for rasterization. std::vector<PrintLayer> m_printer_input; // The printer itself SLAPrinterPtr m_printer; // Estimated print time, material consumed. SLAPrintStatistics m_print_statistics; friend SLAPrintObject; }; } // namespace Slic3r #endif /* slic3r_SLAPrint_hpp_ */
#ifndef slic3r_SLAPrint_hpp_ #define slic3r_SLAPrint_hpp_ #include <mutex> #include "PrintBase.hpp" #include "PrintExport.hpp" #include "Point.hpp" #include "MTUtils.hpp" #include <iterator> namespace Slic3r { enum SLAPrintStep : unsigned int { slapsRasterize, slapsValidate, slapsCount }; enum SLAPrintObjectStep : unsigned int { slaposObjectSlice, slaposSupportPoints, slaposSupportTree, slaposBasePool, slaposSliceSupports, slaposIndexSlices, slaposCount }; class SLAPrint; class GLCanvas; using _SLAPrintObjectBase = PrintObjectBaseWithState<SLAPrint, SLAPrintObjectStep, slaposCount>; // Layers according to quantized height levels. This will be consumed by // the printer (rasterizer) in the SLAPrint class. // using coord_t = long long; enum SliceOrigin { soSupport, soModel }; class SLAPrintObject : public _SLAPrintObjectBase { private: // Prevents erroneous use by other classes. using Inherited = _SLAPrintObjectBase; public: // I refuse to grantee copying (Tamas) SLAPrintObject(const SLAPrintObject&) = delete; SLAPrintObject& operator=(const SLAPrintObject&) = delete; const SLAPrintObjectConfig& config() const { return m_config; } const Transform3d& trafo() const { return m_trafo; } struct Instance { Instance(ModelID instance_id, const Point &shift, float rotation) : instance_id(instance_id), shift(shift), rotation(rotation) {} bool operator==(const Instance &rhs) const { return this->instance_id == rhs.instance_id && this->shift == rhs.shift && this->rotation == rhs.rotation; } // ID of the corresponding ModelInstance. ModelID instance_id; // Slic3r::Point objects in scaled G-code coordinates Point shift; // Rotation along the Z axis, in radians. float rotation; }; const std::vector<Instance>& instances() const { return m_instances; } bool has_mesh(SLAPrintObjectStep step) const; TriangleMesh get_mesh(SLAPrintObjectStep step) const; // Get a support mesh centered around origin in XY, and with zero rotation around Z applied. // Support mesh is only valid if this->is_step_done(slaposSupportTree) is true. const TriangleMesh& support_mesh() const; // Get a pad mesh centered around origin in XY, and with zero rotation around Z applied. // Support mesh is only valid if this->is_step_done(slaposBasePool) is true. const TriangleMesh& pad_mesh() const; // This will return the transformed mesh which is cached const TriangleMesh& transformed_mesh() const; std::vector<sla::SupportPoint> transformed_support_points() const; // Get the needed Z elevation for the model geometry if supports should be // displayed. This Z offset should also be applied to the support // geometries. Note that this is not the same as the value stored in config // as the pad height also needs to be considered. double get_elevation() const; // This method returns the needed elevation according to the processing // status. If the supports are not ready, it is zero, if they are and the // pad is not, then without the pad, otherwise the full value is returned. double get_current_elevation() const; // This method returns the support points of this SLAPrintObject. const std::vector<sla::SupportPoint>& get_support_points() const; // The public Slice record structure. It corresponds to one printable layer. class SliceRecord { public: // this will be the max limit of size_t static const size_t NONE = size_t(-1); static const SliceRecord EMPTY; private: coord_t m_print_z = 0; // Top of the layer float m_slice_z = 0.f; // Exact level of the slice float m_height = 0.f; // Height of the sliced layer size_t m_model_slices_idx = NONE; size_t m_support_slices_idx = NONE; const SLAPrintObject *m_po = nullptr; public: SliceRecord(coord_t key, float slicez, float height): m_print_z(key), m_slice_z(slicez), m_height(height) {} // The key will be the integer height level of the top of the layer. coord_t print_level() const { return m_print_z; } // Returns the exact floating point Z coordinate of the slice float slice_level() const { return m_slice_z; } // Returns the current layer height float layer_height() const { return m_height; } bool is_valid() const { return std::isnan(m_slice_z); } const SLAPrintObject* print_obj() const { return m_po; } // Methods for setting the indices into the slice vectors. void set_model_slice_idx(const SLAPrintObject &po, size_t id) { m_po = &po; m_model_slices_idx = id; } void set_support_slice_idx(const SLAPrintObject& po, size_t id) { m_po = &po; m_support_slices_idx = id; } const ExPolygons& get_slice(SliceOrigin o) const; }; private: template <class T> inline static T level(const SliceRecord& sr) { static_assert(std::is_arithmetic<T>::value, "Arithmetic only!"); return std::is_integral<T>::value ? T(sr.print_level()) : T(sr.slice_level()); } template <class T> inline static SliceRecord create_slice_record(T val) { static_assert(std::is_arithmetic<T>::value, "Arithmetic only!"); return std::is_integral<T>::value ? SliceRecord{ coord_t(val), 0.f, 0.f } : SliceRecord{ 0, float(val), 0.f }; } // This is a template method for searching the slice index either by // an integer key: print_level or a floating point key: slice_level. // The eps parameter gives the max deviation in + or - direction. // // This method can be used in const or non-const contexts as well. template<class Container, class T> static auto closest_slice_record(Container& cont, T lvl, T eps) -> decltype (cont.begin()) { if(cont.empty()) return cont.end(); if(cont.size() == 1 && std::abs(level<T>(cont.front()) - lvl) > eps) return cont.end(); SliceRecord query = create_slice_record(lvl); auto it = std::lower_bound(cont.begin(), cont.end(), query, [](const SliceRecord& r1, const SliceRecord& r2) { return level<T>(r1) < level<T>(r2); }); T diff = std::abs(level<T>(*it) - lvl); if(it != cont.begin()) { auto it_prev = std::prev(it); T diff_prev = std::abs(level<T>(*it_prev) - lvl); if(diff_prev < diff) { diff = diff_prev; it = it_prev; } } if(diff > eps) it = cont.end(); return it; } const std::vector<ExPolygons>& get_model_slices() const; const std::vector<ExPolygons>& get_support_slices() const; public: // ///////////////////////////////////////////////////////////////////////// // // These methods should be callable on the client side (e.g. UI thread) // when the appropriate steps slaposObjectSlice and slaposSliceSupports // are ready. All the print objects are processed before slapsRasterize so // it is safe to call them during and/or after slapsRasterize. // // ///////////////////////////////////////////////////////////////////////// // Retrieve the slice index. const std::vector<SliceRecord>& get_slice_index() const; // Search slice index for the closest slice to given print_level. // max_epsilon gives the allowable deviation of the returned slice record's // level. const SliceRecord& closest_slice_to_print_level( coord_t print_level, coord_t max_epsilon = coord_t(SCALED_EPSILON)) const { auto it = closest_slice_record(m_slice_index, print_level, max_epsilon); if (it == m_slice_index.end()) return SliceRecord::EMPTY; return *it; } // Search slice index for the closest slice to given slice_level. // max_epsilon gives the allowable deviation of the returned slice record's // level. const SliceRecord& closest_slice_to_slice_level( float slice_level, float max_epsilon = float(EPSILON)) const { auto it = closest_slice_record(m_slice_index, slice_level, max_epsilon); if (it == m_slice_index.end()) return SliceRecord::EMPTY; return *it; } protected: // to be called from SLAPrint only. friend class SLAPrint; SLAPrintObject(SLAPrint* print, ModelObject* model_object); ~SLAPrintObject(); void config_apply(const ConfigBase &other, bool ignore_nonexistent = false) { this->m_config.apply(other, ignore_nonexistent); } void config_apply_only(const ConfigBase &other, const t_config_option_keys &keys, bool ignore_nonexistent = false) { this->m_config.apply_only(other, keys, ignore_nonexistent); } void set_trafo(const Transform3d& trafo) { m_transformed_rmesh.invalidate([this, &trafo](){ m_trafo = trafo; }); } void set_instances(const std::vector<Instance> &instances) { m_instances = instances; } // Invalidates the step, and its depending steps in SLAPrintObject and SLAPrint. bool invalidate_step(SLAPrintObjectStep step); bool invalidate_all_steps(); // Invalidate steps based on a set of parameters changed. bool invalidate_state_by_config_options(const std::vector<t_config_option_key> &opt_keys); // Which steps have to be performed. Implicitly: all // to be accessible from SLAPrint std::vector<bool> m_stepmask; private: // Object specific configuration, pulled from the configuration layer. SLAPrintObjectConfig m_config; // Translation in Z + Rotation by Y and Z + Scaling / Mirroring. Transform3d m_trafo = Transform3d::Identity(); std::vector<Instance> m_instances; // Individual 2d slice polygons from lower z to higher z levels std::vector<ExPolygons> m_model_slices; // Exact (float) height levels mapped to the slices. Each record contains // the index to the model and the support slice vectors. std::vector<SliceRecord> m_slice_index; std::vector<float> m_model_height_levels; // Caching the transformed (m_trafo) raw mesh of the object mutable CachedObject<TriangleMesh> m_transformed_rmesh; class SupportData; std::unique_ptr<SupportData> m_supportdata; }; using PrintObjects = std::vector<SLAPrintObject*>; using SliceRecord = SLAPrintObject::SliceRecord; class TriangleMesh; struct SLAPrintStatistics { SLAPrintStatistics() { clear(); } std::string estimated_print_time; double objects_used_material; double support_used_material; size_t slow_layers_count; size_t fast_layers_count; double total_cost; double total_weight; // Config with the filled in print statistics. DynamicConfig config() const; // Config with the statistics keys populated with placeholder strings. static DynamicConfig placeholders(); // Replace the print statistics placeholders in the path. std::string finalize_output_path(const std::string &path_in) const; void clear() { estimated_print_time.clear(); objects_used_material = 0.; support_used_material = 0.; slow_layers_count = 0; fast_layers_count = 0; total_cost = 0.; total_weight = 0.; } }; /** * @brief This class is the high level FSM for the SLA printing process. * * It should support the background processing framework and contain the * metadata for the support geometries and their slicing. It should also * dispatch the SLA printing configuration values to the appropriate calculation * steps. */ class SLAPrint : public PrintBaseWithState<SLAPrintStep, slapsCount> { private: // Prevents erroneous use by other classes. typedef PrintBaseWithState<SLAPrintStep, slapsCount> Inherited; public: // An aggregation of SliceRecord-s from all the print objects for each // occupied layer. Slice record levels dont have to match exactly. // They are unified if the level difference is within +/- SCALED_EPSILON struct PrintLayer { coord_t level; // The collection of slice records for the current level. std::vector<std::reference_wrapper<const SliceRecord>> slices; explicit PrintLayer(coord_t lvl) : level(lvl) {} // for being sorted in their container (see m_printer_input) bool operator<(const PrintLayer& other) const { return level < other.level; } }; SLAPrint(): m_stepmask(slapsCount, true) {} virtual ~SLAPrint() override { this->clear(); } PrinterTechnology technology() const noexcept override { return ptSLA; } void clear() override; bool empty() const override { return m_objects.empty(); } ApplyStatus apply(const Model &model, const DynamicPrintConfig &config) override; void set_task(const TaskParams &params) override; void process() override; void finalize() override; // Returns true if an object step is done on all objects and there's at least one object. bool is_step_done(SLAPrintObjectStep step) const; // Returns true if the last step was finished with success. bool finished() const override { return this->is_step_done(slaposIndexSlices) && this->Inherited::is_step_done(slapsRasterize); } template<class Fmt> void export_raster(const std::string& fname) { if(m_printer) m_printer->save<Fmt>(fname); } const PrintObjects& objects() const { return m_objects; } const SLAPrintConfig& print_config() const { return m_print_config; } const SLAPrinterConfig& printer_config() const { return m_printer_config; } const SLAMaterialConfig& material_config() const { return m_material_config; } const SLAPrintObjectConfig& default_object_config() const { return m_default_object_config; } std::string output_filename() const override; const SLAPrintStatistics& print_statistics() const { return m_print_statistics; } std::string validate() const override; // The aggregated and leveled print records from various objects. // TODO: use this structure for the preview in the future. const std::vector<PrintLayer>& print_layers() const { return m_printer_input; } private: using SLAPrinter = FilePrinter<FilePrinterFormat::SLA_PNGZIP>; using SLAPrinterPtr = std::unique_ptr<SLAPrinter>; // Invalidate steps based on a set of parameters changed. bool invalidate_state_by_config_options(const std::vector<t_config_option_key> &opt_keys); void fill_statistics(); SLAPrintConfig m_print_config; SLAPrinterConfig m_printer_config; SLAMaterialConfig m_material_config; SLAPrintObjectConfig m_default_object_config; PrintObjects m_objects; std::vector<bool> m_stepmask; // Ready-made data for rasterization. std::vector<PrintLayer> m_printer_input; // The printer itself SLAPrinterPtr m_printer; // Estimated print time, material consumed. SLAPrintStatistics m_print_statistics; friend SLAPrintObject; }; } // namespace Slic3r #endif /* slic3r_SLAPrint_hpp_ */
Move SliceRecord into SLAPrintObject
Move SliceRecord into SLAPrintObject
C++
agpl-3.0
prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r
b0077d529919c327c59cc081e2898b8b0e62da96
src/llmq/quorums_utils.cpp
src/llmq/quorums_utils.cpp
// Copyright (c) 2018-2019 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <llmq/quorums.h> #include <llmq/quorums_utils.h> #include <chainparams.h> #include <random.h> #include <spork.h> #include <validation.h> #include <masternode/masternode-meta.h> namespace llmq { std::vector<CDeterministicMNCPtr> CLLMQUtils::GetAllQuorumMembers(uint8_t llmqType, const CBlockIndex* pindexQuorum) { auto& params = Params().GetConsensus().llmqs.at(llmqType); auto allMns = deterministicMNManager->GetListForBlock(pindexQuorum); auto modifier = ::SerializeHash(std::make_pair(llmqType, pindexQuorum->GetBlockHash())); return allMns.CalculateQuorum(params.size, modifier); } uint256 CLLMQUtils::BuildCommitmentHash(uint8_t llmqType, const uint256& blockHash, const std::vector<bool>& validMembers, const CBLSPublicKey& pubKey, const uint256& vvecHash) { CHashWriter hw(SER_NETWORK, 0); hw << llmqType; hw << blockHash; hw << DYNBITSET(validMembers); hw << pubKey; hw << vvecHash; return hw.GetHash(); } uint256 CLLMQUtils::BuildSignHash(uint8_t llmqType, const uint256& quorumHash, const uint256& id, const uint256& msgHash) { CHashWriter h(SER_GETHASH, 0); h << llmqType; h << quorumHash; h << id; h << msgHash; return h.GetHash(); } uint256 CLLMQUtils::DeterministicOutboundConnection(const uint256& proTxHash1, const uint256& proTxHash2) { // We need to deterministically select who is going to initiate the connection. The naive way would be to simply // return the min(proTxHash1, proTxHash2), but this would create a bias towards MNs with a numerically low // hash. To fix this, we return the proTxHash that has the lowest value of: // hash(min(proTxHash1, proTxHash2), max(proTxHash1, proTxHash2), proTxHashX) // where proTxHashX is the proTxHash to compare uint256 h1; uint256 h2; if (proTxHash1 < proTxHash2) { h1 = ::SerializeHash(std::make_tuple(proTxHash1, proTxHash2, proTxHash1)); h2 = ::SerializeHash(std::make_tuple(proTxHash1, proTxHash2, proTxHash2)); } else { h1 = ::SerializeHash(std::make_tuple(proTxHash2, proTxHash1, proTxHash1)); h2 = ::SerializeHash(std::make_tuple(proTxHash2, proTxHash1, proTxHash2)); } if (h1 < h2) { return proTxHash1; } return proTxHash2; } std::set<uint256> CLLMQUtils::GetQuorumConnections(uint8_t llmqType, const CBlockIndex* pindexQuorum, const uint256& forMember, bool onlyOutbound) { auto& params = Params().GetConsensus().llmqs.at(llmqType); if (sporkManager.IsSporkActive(SPORK_21_QUORUM_ALL_CONNECTED)) { auto mns = GetAllQuorumMembers(llmqType, pindexQuorum); std::set<uint256> result; for (auto& dmn : mns) { if (dmn->proTxHash == forMember) { continue; } // Determine which of the two MNs (forMember vs dmn) should initiate the outbound connection and which // one should wait for the inbound connection. We do this in a deterministic way, so that even when we // end up with both connecting to each other, we know which one to disconnect uint256 deterministicOutbound = DeterministicOutboundConnection(forMember, dmn->proTxHash); if (!onlyOutbound || deterministicOutbound == dmn->proTxHash) { result.emplace(dmn->proTxHash); } } return result; } else { return GetQuorumRelayMembers(llmqType, pindexQuorum, forMember, onlyOutbound); } } std::set<uint256> CLLMQUtils::GetQuorumRelayMembers(uint8_t llmqType, const CBlockIndex *pindexQuorum, const uint256 &forMember, bool onlyOutbound) { auto mns = GetAllQuorumMembers(llmqType, pindexQuorum); std::set<uint256> result; auto calcOutbound = [&](size_t i, const uint256 proTxHash) { // Relay to nodes at indexes (i+2^k)%n, where // k: 0..max(1, floor(log2(n-1))-1) // n: size of the quorum/ring std::set<uint256> r; int gap = 1; int gap_max = (int)mns.size() - 1; int k = 0; while ((gap_max >>= 1) || k <= 1) { size_t idx = (i + gap) % mns.size(); auto& otherDmn = mns[idx]; if (otherDmn->proTxHash == proTxHash) { continue; } r.emplace(otherDmn->proTxHash); gap <<= 1; k++; } return r; }; for (size_t i = 0; i < mns.size(); i++) { auto& dmn = mns[i]; if (dmn->proTxHash == forMember) { auto r = calcOutbound(i, dmn->proTxHash); result.insert(r.begin(), r.end()); } else if (!onlyOutbound) { auto r = calcOutbound(i, dmn->proTxHash); if (r.count(forMember)) { result.emplace(dmn->proTxHash); } } } return result; } std::set<size_t> CLLMQUtils::CalcDeterministicWatchConnections(uint8_t llmqType, const CBlockIndex* pindexQuorum, size_t memberCount, size_t connectionCount) { static uint256 qwatchConnectionSeed; static std::atomic<bool> qwatchConnectionSeedGenerated{false}; static RecursiveMutex qwatchConnectionSeedCs; if (!qwatchConnectionSeedGenerated) { LOCK(qwatchConnectionSeedCs); if (!qwatchConnectionSeedGenerated) { qwatchConnectionSeed = GetRandHash(); qwatchConnectionSeedGenerated = true; } } std::set<size_t> result; uint256 rnd = qwatchConnectionSeed; for (size_t i = 0; i < connectionCount; i++) { rnd = ::SerializeHash(std::make_pair(rnd, std::make_pair(llmqType, pindexQuorum->GetBlockHash()))); result.emplace(rnd.GetUint64(0) % memberCount); } return result; } void CLLMQUtils::EnsureQuorumConnections(uint8_t llmqType, const CBlockIndex *pindexQuorum, const uint256& myProTxHash, bool allowWatch, CConnman& connman) { auto members = GetAllQuorumMembers(llmqType, pindexQuorum); bool isMember = std::find_if(members.begin(), members.end(), [&](const CDeterministicMNCPtr& dmn) { return dmn->proTxHash == myProTxHash; }) != members.end(); if (!isMember && !allowWatch) { return; } std::set<uint256> connections; if (isMember) { connections = CLLMQUtils::GetQuorumConnections(llmqType, pindexQuorum, myProTxHash, true); } else { auto cindexes = CLLMQUtils::CalcDeterministicWatchConnections(llmqType, pindexQuorum, members.size(), 1); for (auto idx : cindexes) { connections.emplace(members[idx]->proTxHash); } } if (!connections.empty()) { if (!connman.HasMasternodeQuorumNodes(llmqType, pindexQuorum->GetBlockHash()) && LogAcceptCategory(BCLog::LLMQ)) { auto mnList = deterministicMNManager->GetListAtChainTip(); std::string debugMsg = strprintf("CLLMQUtils::%s -- adding masternodes quorum connections for quorum %s:\n", __func__, pindexQuorum->GetBlockHash().ToString()); for (auto& c : connections) { auto dmn = mnList.GetValidMN(c); if (!dmn) { debugMsg += strprintf(" %s (not in valid MN set anymore)\n", c.ToString()); } else { debugMsg += strprintf(" %s (%s)\n", c.ToString(), dmn->pdmnState->addr.ToString()); } } LogPrint(BCLog::NET, debugMsg.c_str()); } connman.SetMasternodeQuorumNodes(llmqType, pindexQuorum->GetBlockHash(), connections); } } void CLLMQUtils::AddQuorumProbeConnections(uint8_t llmqType, const CBlockIndex *pindexQuorum, const uint256 &myProTxHash, CConnman& connman) { auto members = GetAllQuorumMembers(llmqType, pindexQuorum); auto curTime = GetAdjustedTime(); std::set<uint256> probeConnections; for (auto& dmn : members) { if (dmn->proTxHash == myProTxHash) { continue; } auto lastOutbound = mmetaman.GetMetaInfo(dmn->proTxHash)->GetLastOutboundSuccess(); // re-probe after 50 minutes so that the "good connection" check in the DKG doesn't fail just because we're on // the brink of timeout if (curTime - lastOutbound > 50 * 60) { probeConnections.emplace(dmn->proTxHash); } } if (!probeConnections.empty()) { if (LogAcceptCategory(BCLog::LLMQ)) { auto mnList = deterministicMNManager->GetListAtChainTip(); std::string debugMsg = strprintf("CLLMQUtils::%s -- adding masternodes probes for quorum %s:\n", __func__, pindexQuorum->GetBlockHash().ToString()); for (auto& c : probeConnections) { auto dmn = mnList.GetValidMN(c); if (!dmn) { debugMsg += strprintf(" %s (not in valid MN set anymore)\n", c.ToString()); } else { debugMsg += strprintf(" %s (%s)\n", c.ToString(), dmn->pdmnState->addr.ToString()); } } LogPrint(BCLog::NET, debugMsg.c_str()); } connman.AddPendingProbeConnections(probeConnections); } } bool CLLMQUtils::IsQuorumActive(uint8_t llmqType, const uint256& quorumHash) { auto& params = Params().GetConsensus().llmqs.at(llmqType); // sig shares and recovered sigs are only accepted from recent/active quorums // we allow one more active quorum as specified in consensus, as otherwise there is a small window where things could // fail while we are on the brink of a new quorum auto quorums = quorumManager->ScanQuorums(llmqType, (int)params.signingActiveQuorumCount + 1); for (auto& q : quorums) { if (q->qc.quorumHash == quorumHash) { return true; } } return false; } } // namespace llmq
// Copyright (c) 2018-2019 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <llmq/quorums.h> #include <llmq/quorums_utils.h> #include <chainparams.h> #include <random.h> #include <spork.h> #include <validation.h> #include <masternode/masternode-meta.h> namespace llmq { std::vector<CDeterministicMNCPtr> CLLMQUtils::GetAllQuorumMembers(uint8_t llmqType, const CBlockIndex* pindexQuorum) { auto& params = Params().GetConsensus().llmqs.at(llmqType); auto allMns = deterministicMNManager->GetListForBlock(pindexQuorum); auto modifier = ::SerializeHash(std::make_pair(llmqType, pindexQuorum->GetBlockHash())); return allMns.CalculateQuorum(params.size, modifier); } uint256 CLLMQUtils::BuildCommitmentHash(uint8_t llmqType, const uint256& blockHash, const std::vector<bool>& validMembers, const CBLSPublicKey& pubKey, const uint256& vvecHash) { CHashWriter hw(SER_NETWORK, 0); hw << llmqType; hw << blockHash; hw << DYNBITSET(validMembers); hw << pubKey; hw << vvecHash; return hw.GetHash(); } uint256 CLLMQUtils::BuildSignHash(uint8_t llmqType, const uint256& quorumHash, const uint256& id, const uint256& msgHash) { CHashWriter h(SER_GETHASH, 0); h << llmqType; h << quorumHash; h << id; h << msgHash; return h.GetHash(); } uint256 CLLMQUtils::DeterministicOutboundConnection(const uint256& proTxHash1, const uint256& proTxHash2) { // We need to deterministically select who is going to initiate the connection. The naive way would be to simply // return the min(proTxHash1, proTxHash2), but this would create a bias towards MNs with a numerically low // hash. To fix this, we return the proTxHash that has the lowest value of: // hash(min(proTxHash1, proTxHash2), max(proTxHash1, proTxHash2), proTxHashX) // where proTxHashX is the proTxHash to compare uint256 h1; uint256 h2; if (proTxHash1 < proTxHash2) { h1 = ::SerializeHash(std::make_tuple(proTxHash1, proTxHash2, proTxHash1)); h2 = ::SerializeHash(std::make_tuple(proTxHash1, proTxHash2, proTxHash2)); } else { h1 = ::SerializeHash(std::make_tuple(proTxHash2, proTxHash1, proTxHash1)); h2 = ::SerializeHash(std::make_tuple(proTxHash2, proTxHash1, proTxHash2)); } if (h1 < h2) { return proTxHash1; } return proTxHash2; } std::set<uint256> CLLMQUtils::GetQuorumConnections(uint8_t llmqType, const CBlockIndex* pindexQuorum, const uint256& forMember, bool onlyOutbound) { auto& params = Params().GetConsensus().llmqs.at(llmqType); if (sporkManager.IsSporkActive(SPORK_21_QUORUM_ALL_CONNECTED)) { auto mns = GetAllQuorumMembers(llmqType, pindexQuorum); std::set<uint256> result; for (auto& dmn : mns) { if (dmn->proTxHash == forMember) { continue; } // Determine which of the two MNs (forMember vs dmn) should initiate the outbound connection and which // one should wait for the inbound connection. We do this in a deterministic way, so that even when we // end up with both connecting to each other, we know which one to disconnect uint256 deterministicOutbound = DeterministicOutboundConnection(forMember, dmn->proTxHash); if (!onlyOutbound || deterministicOutbound == dmn->proTxHash) { result.emplace(dmn->proTxHash); } } return result; } else { return GetQuorumRelayMembers(llmqType, pindexQuorum, forMember, onlyOutbound); } } std::set<uint256> CLLMQUtils::GetQuorumRelayMembers(uint8_t llmqType, const CBlockIndex *pindexQuorum, const uint256 &forMember, bool onlyOutbound) { auto mns = GetAllQuorumMembers(llmqType, pindexQuorum); std::set<uint256> result; auto calcOutbound = [&](size_t i, const uint256 proTxHash) { // Relay to nodes at indexes (i+2^k)%n, where // k: 0..max(1, floor(log2(n-1))-1) // n: size of the quorum/ring std::set<uint256> r; int gap = 1; int gap_max = (int)mns.size() - 1; int k = 0; while ((gap_max >>= 1) || k <= 1) { size_t idx = (i + gap) % mns.size(); auto& otherDmn = mns[idx]; if (otherDmn->proTxHash == proTxHash) { gap <<= 1; k++; continue; } r.emplace(otherDmn->proTxHash); gap <<= 1; k++; } return r; }; for (size_t i = 0; i < mns.size(); i++) { auto& dmn = mns[i]; if (dmn->proTxHash == forMember) { auto r = calcOutbound(i, dmn->proTxHash); result.insert(r.begin(), r.end()); } else if (!onlyOutbound) { auto r = calcOutbound(i, dmn->proTxHash); if (r.count(forMember)) { result.emplace(dmn->proTxHash); } } } return result; } std::set<size_t> CLLMQUtils::CalcDeterministicWatchConnections(uint8_t llmqType, const CBlockIndex* pindexQuorum, size_t memberCount, size_t connectionCount) { static uint256 qwatchConnectionSeed; static std::atomic<bool> qwatchConnectionSeedGenerated{false}; static RecursiveMutex qwatchConnectionSeedCs; if (!qwatchConnectionSeedGenerated) { LOCK(qwatchConnectionSeedCs); if (!qwatchConnectionSeedGenerated) { qwatchConnectionSeed = GetRandHash(); qwatchConnectionSeedGenerated = true; } } std::set<size_t> result; uint256 rnd = qwatchConnectionSeed; for (size_t i = 0; i < connectionCount; i++) { rnd = ::SerializeHash(std::make_pair(rnd, std::make_pair(llmqType, pindexQuorum->GetBlockHash()))); result.emplace(rnd.GetUint64(0) % memberCount); } return result; } void CLLMQUtils::EnsureQuorumConnections(uint8_t llmqType, const CBlockIndex *pindexQuorum, const uint256& myProTxHash, bool allowWatch, CConnman& connman) { auto members = GetAllQuorumMembers(llmqType, pindexQuorum); bool isMember = std::find_if(members.begin(), members.end(), [&](const CDeterministicMNCPtr& dmn) { return dmn->proTxHash == myProTxHash; }) != members.end(); if (!isMember && !allowWatch) { return; } std::set<uint256> connections; if (isMember) { connections = CLLMQUtils::GetQuorumConnections(llmqType, pindexQuorum, myProTxHash, true); } else { auto cindexes = CLLMQUtils::CalcDeterministicWatchConnections(llmqType, pindexQuorum, members.size(), 1); for (auto idx : cindexes) { connections.emplace(members[idx]->proTxHash); } } if (!connections.empty()) { if (!connman.HasMasternodeQuorumNodes(llmqType, pindexQuorum->GetBlockHash()) && LogAcceptCategory(BCLog::LLMQ)) { auto mnList = deterministicMNManager->GetListAtChainTip(); std::string debugMsg = strprintf("CLLMQUtils::%s -- adding masternodes quorum connections for quorum %s:\n", __func__, pindexQuorum->GetBlockHash().ToString()); for (auto& c : connections) { auto dmn = mnList.GetValidMN(c); if (!dmn) { debugMsg += strprintf(" %s (not in valid MN set anymore)\n", c.ToString()); } else { debugMsg += strprintf(" %s (%s)\n", c.ToString(), dmn->pdmnState->addr.ToString()); } } LogPrint(BCLog::NET, debugMsg.c_str()); } connman.SetMasternodeQuorumNodes(llmqType, pindexQuorum->GetBlockHash(), connections); } } void CLLMQUtils::AddQuorumProbeConnections(uint8_t llmqType, const CBlockIndex *pindexQuorum, const uint256 &myProTxHash, CConnman& connman) { auto members = GetAllQuorumMembers(llmqType, pindexQuorum); auto curTime = GetAdjustedTime(); std::set<uint256> probeConnections; for (auto& dmn : members) { if (dmn->proTxHash == myProTxHash) { continue; } auto lastOutbound = mmetaman.GetMetaInfo(dmn->proTxHash)->GetLastOutboundSuccess(); // re-probe after 50 minutes so that the "good connection" check in the DKG doesn't fail just because we're on // the brink of timeout if (curTime - lastOutbound > 50 * 60) { probeConnections.emplace(dmn->proTxHash); } } if (!probeConnections.empty()) { if (LogAcceptCategory(BCLog::LLMQ)) { auto mnList = deterministicMNManager->GetListAtChainTip(); std::string debugMsg = strprintf("CLLMQUtils::%s -- adding masternodes probes for quorum %s:\n", __func__, pindexQuorum->GetBlockHash().ToString()); for (auto& c : probeConnections) { auto dmn = mnList.GetValidMN(c); if (!dmn) { debugMsg += strprintf(" %s (not in valid MN set anymore)\n", c.ToString()); } else { debugMsg += strprintf(" %s (%s)\n", c.ToString(), dmn->pdmnState->addr.ToString()); } } LogPrint(BCLog::NET, debugMsg.c_str()); } connman.AddPendingProbeConnections(probeConnections); } } bool CLLMQUtils::IsQuorumActive(uint8_t llmqType, const uint256& quorumHash) { auto& params = Params().GetConsensus().llmqs.at(llmqType); // sig shares and recovered sigs are only accepted from recent/active quorums // we allow one more active quorum as specified in consensus, as otherwise there is a small window where things could // fail while we are on the brink of a new quorum auto quorums = quorumManager->ScanQuorums(llmqType, (int)params.signingActiveQuorumCount + 1); for (auto& q : quorums) { if (q->qc.quorumHash == quorumHash) { return true; } } return false; } } // namespace llmq
fix loop in GetQuorumRelayMembers
fix loop in GetQuorumRelayMembers Former-commit-id: 2f9570809638f8d155f9a973ee48edca7570be1d
C++
mit
syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin
78b54dfd3b8cdcdaa7727e6857d8e0f107375bc0
algorithms/util.cpp
algorithms/util.cpp
#include "util.h" #include <algorithm> #include <cassert> #include <cmath> #include <fstream> #include <iostream> #include <iterator> #include <stdexcept> #include <utility> using namespace std; namespace med { double euclideanDistance(const Vector& v1, const Vector& v2, bool ommitFirst) { assert(v1.size() == v2.size()); double dist = 0.0; for (int i = ommitFirst ? 1 : 0; i < v1.size(); i++) { dist += ((v1[i] - v2[i]) * (v1[i] - v2[i])); } return sqrt(dist); } double cosineSimilarity(const Vector& v1, const Vector& v2, bool ommitFirst) { assert(v1.size() == v2.size()); double ab = 0.0, a2 = 0.0, b2 = 0.0; for (int i = ommitFirst ? 1 : 0; i < v1.size(); i++) { ab += v1[i] * v2[i]; a2 += v1[i] * v1[i]; b2 += v2[i] * v2[i]; } a2 = sqrt(a2); b2 = sqrt(b2); return ab / (a2 * b2 + 0.000001); } double manhattanDistance(const Vector& v1, const Vector& v2, bool ommitFirst) { assert(v1.size() == v2.size()); double dist = 0.0; for (int i = ommitFirst ? 1 : 0; i < v1.size(); i++) { dist += abs(v1[i] - v2[i]); } return dist; } string vectorToString(const vector<double>& vector) { string result = "["; for (int i = 0; i < vector.size(); i++) { result += to_string(vector[i]); if (i != vector.size() - 1) result += ","; } result += "]"; return result; } Cluster readData(const string& filename) { ifstream input(filename); if (!input.is_open()) { throw runtime_error(string("Cannot read data file!")); } int count = 0, size = 0; input >> count; input >> size; cout << "Count= " << count << " size= " << size << endl; Cluster result; for (int i = 0; i < count; i++) { Vector vector; vector.push_back(i); for (int j = 0; j < size; j++) { double x; input >> x; //if (j != 0) { // first attribute is class vector.push_back(x); //} } result.push_back(vector); } cout << "Read data completed!" << endl; return result; } void print4dist(Cluster data, const DistFunc& distFunc, const std::string& out4distFile) { vector<double> kdistances; char progress[32]; for (int i = 0; i < data.size(); i++) { vector<double> distances; for (int j = 0; j < data.size(); j++) { if (i == j) continue; distances.push_back(distFunc(data[i], data[j], true)); } sort(distances.begin(), distances.end()); kdistances.push_back(distances[3]); sprintf(progress, "\r%3.2f%%", (double)(i)/data.size()*100); cout << progress; } sort(kdistances.begin(), kdistances.end()); double min = *(kdistances.begin()); double max = *(kdistances.end() - 1); ofstream outFile(out4distFile); for (double dist : kdistances) { outFile << dist << std::endl; } } void printClusters(const map<int, Cluster> clusters) { for (auto& cluster : clusters) { cout << "clusterId=" << cluster.first << " (size=" << cluster.second.size() << ")" << endl; // for (auto& point : cluster.second) { // cout << "\tvector: " << vectorToString(point) << endl; // } } } void printResultClusters(const map<int, Cluster> clusters, const char *resultFile) { ostream *out = &cout; if (resultFile) { ofstream *fout = new ofstream(); fout->open(resultFile, ios_base::in | ios_base::trunc); if (fout->is_open()) { out = fout; } else { cout << "Error while opening '" << resultFile << "' file, so print to stdout" << endl; } } // sort them (id, group) vector<pair<int, int>> res; for (auto& cl : clusters) { for (auto& cluster : cl.second) { res.push_back(make_pair(cluster[0], cl.first)); } } sort(res.begin(), res.end(), [](pair<int, int> p1, pair<int, int> p2) {return p1.first < p2.first;}); for (auto& r : res) { *out << r.second << endl; } if (resultFile) { try { dynamic_cast<std::ofstream&>(*out).close(); delete out; } catch (std::exception &) { } } } void print2DimVectorsForRClusters(const std::map<int, Cluster> clusters, const char *resultFile) { ostream *out = &cout; if (resultFile) { ofstream *fout = new ofstream(); fout->open(resultFile, ios_base::in | ios_base::trunc); if (fout->is_open()) { out = fout; } else { cout << "Error while opening '" << resultFile << "' file, so print to stdout" << endl; } } for (auto& cl : clusters) { // first is id of row data for (int i = 1; i < 3; ++i) { for (auto& cluster : cl.second) { assert(cluster.size() == 3); *out << cluster[i] << "\t"; } *out << std::endl; } } if (resultFile) { try { dynamic_cast<std::ofstream&>(*out).close(); delete out; } catch (std::exception &) { } } } }
#include "util.h" #include <algorithm> #include <cassert> #include <cmath> #include <fstream> #include <iostream> #include <iterator> #include <stdexcept> #include <utility> using namespace std; namespace med { double euclideanDistance(const Vector& v1, const Vector& v2, bool ommitFirst) { assert(v1.size() == v2.size()); double dist = 0.0; for (int i = ommitFirst ? 1 : 0; i < v1.size(); i++) { dist += ((v1[i] - v2[i]) * (v1[i] - v2[i])); } return sqrt(dist); } double cosineSimilarity(const Vector& v1, const Vector& v2, bool ommitFirst) { assert(v1.size() == v2.size()); double ab = 0.0, a2 = 0.0, b2 = 0.0; for (int i = ommitFirst ? 1 : 0; i < v1.size(); i++) { ab += v1[i] * v2[i]; a2 += v1[i] * v1[i]; b2 += v2[i] * v2[i]; } a2 = sqrt(a2); b2 = sqrt(b2); return 1 - ab / (a2 * b2 + 0.000001); } double manhattanDistance(const Vector& v1, const Vector& v2, bool ommitFirst) { assert(v1.size() == v2.size()); double dist = 0.0; for (int i = ommitFirst ? 1 : 0; i < v1.size(); i++) { dist += abs(v1[i] - v2[i]); } return dist; } string vectorToString(const vector<double>& vector) { string result = "["; for (int i = 0; i < vector.size(); i++) { result += to_string(vector[i]); if (i != vector.size() - 1) result += ","; } result += "]"; return result; } Cluster readData(const string& filename) { ifstream input(filename); if (!input.is_open()) { throw runtime_error(string("Cannot read data file!")); } int count = 0, size = 0; input >> count; input >> size; cout << "Count= " << count << " size= " << size << endl; Cluster result; for (int i = 0; i < count; i++) { Vector vector; vector.push_back(i); for (int j = 0; j < size; j++) { double x; input >> x; //if (j != 0) { // first attribute is class vector.push_back(x); //} } result.push_back(vector); } cout << "Read data completed!" << endl; return result; } void print4dist(Cluster data, const DistFunc& distFunc, const std::string& out4distFile) { vector<double> kdistances; char progress[32]; for (int i = 0; i < data.size(); i++) { vector<double> distances; for (int j = 0; j < data.size(); j++) { if (i == j) continue; distances.push_back(distFunc(data[i], data[j], true)); } sort(distances.begin(), distances.end()); kdistances.push_back(distances[3]); sprintf(progress, "\r%3.2f%%", (double)(i)/data.size()*100); cout << progress; } sort(kdistances.begin(), kdistances.end()); double min = *(kdistances.begin()); double max = *(kdistances.end() - 1); ofstream outFile(out4distFile); for (double dist : kdistances) { outFile << dist << std::endl; } } void printClusters(const map<int, Cluster> clusters) { for (auto& cluster : clusters) { cout << "clusterId=" << cluster.first << " (size=" << cluster.second.size() << ")" << endl; // for (auto& point : cluster.second) { // cout << "\tvector: " << vectorToString(point) << endl; // } } } void printResultClusters(const map<int, Cluster> clusters, const char *resultFile) { ostream *out = &cout; if (resultFile) { ofstream *fout = new ofstream(); fout->open(resultFile, ios_base::in | ios_base::trunc); if (fout->is_open()) { out = fout; } else { cout << "Error while opening '" << resultFile << "' file, so print to stdout" << endl; } } // sort them (id, group) vector<pair<int, int>> res; for (auto& cl : clusters) { for (auto& cluster : cl.second) { res.push_back(make_pair(cluster[0], cl.first)); } } sort(res.begin(), res.end(), [](pair<int, int> p1, pair<int, int> p2) {return p1.first < p2.first;}); for (auto& r : res) { *out << r.second << endl; } if (resultFile) { try { dynamic_cast<std::ofstream&>(*out).close(); delete out; } catch (std::exception &) { } } } void print2DimVectorsForRClusters(const std::map<int, Cluster> clusters, const char *resultFile) { ostream *out = &cout; if (resultFile) { ofstream *fout = new ofstream(); fout->open(resultFile, ios_base::in | ios_base::trunc); if (fout->is_open()) { out = fout; } else { cout << "Error while opening '" << resultFile << "' file, so print to stdout" << endl; } } for (auto& cl : clusters) { // first is id of row data for (int i = 1; i < 3; ++i) { for (auto& cluster : cl.second) { assert(cluster.size() == 3); *out << cluster[i] << "\t"; } *out << std::endl; } } if (resultFile) { try { dynamic_cast<std::ofstream&>(*out).close(); delete out; } catch (std::exception &) { } } } }
Fix of cosine distance calculation function.
Fix of cosine distance calculation function.
C++
mit
Kajo0/MED,Kajo0/MED,Kajo0/MED,Kajo0/MED
5342e22ee2b8be28ccbf437e9e777e844b9ff244
Library/Sources/Stroika/Foundation/DataExchangeFormat/ObjectVariantMapper.cpp
Library/Sources/Stroika/Foundation/DataExchangeFormat/ObjectVariantMapper.cpp
/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #include "../StroikaPreComp.h" #include "../Characters/Format.h" #include "../Containers/Tally.h" #include "../Debug/Trace.h" #include "../Time/Date.h" #include "../Time/DateRange.h" #include "../Time/DateTime.h" #include "../Time/DateTimeRange.h" #include "../Time/Duration.h" #include "../Time/DurationRange.h" #include "ObjectVariantMapper.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchangeFormat; using Time::Date; using Time::DateTime; using Time::Duration; using Time::TimeOfDay; /* ******************************************************************************** ******* DataExchangeFormat::ObjectVariantMapper::TypeMappingDetails ************ ******************************************************************************** */ ObjectVariantMapper::TypeMappingDetails::TypeMappingDetails ( const type_index& forTypeInfo, const std::function<VariantValue(const ObjectVariantMapper* mapper, const Byte* objOfType)>& toVariantMapper, const std::function<void(const ObjectVariantMapper* mapper, const VariantValue& d, Byte* into)>& fromVariantMapper ) : fForType (forTypeInfo) , fToVariantMapper (toVariantMapper) , fFromVariantMapper (fromVariantMapper) { } ObjectVariantMapper::TypeMappingDetails::TypeMappingDetails (const type_index& forTypeInfo, size_t n, const Sequence<StructureFieldInfo>& fields) : fForType (forTypeInfo) , fToVariantMapper () , fFromVariantMapper () { #if qDebug for (auto i : fields) { Require (i.fOffset < n); } { // assure each field unique Containers::Tally<size_t> t; for (auto i : fields) { t.Add (i.fOffset); } for (auto i : t) { Require (i.fCount == 1); } } #if 0 // GOOD TODO but cannot since no longer a member of the ObjectMapper class... { // Assure for each field type is registered for (auto i : fields) { Require (Lookup_ (i.fTypeInfo).fFromVariantMapper); Require (Lookup_ (i.fTypeInfo).fToVariantMapper); } } #endif #endif fToVariantMapper = [fields] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { //Debug::TraceContextBumper ctx (L"ObjectVariantMapper::TypeMappingDetails::{}::fToVariantMapper"); Mapping<String, VariantValue> m; for (auto i : fields) { //DbgTrace (L"(fieldname = %s, offset=%d", i.fSerializedFieldName.c_str (), i.fOffset); const Byte* fieldObj = fromObjOfTypeT + i.fOffset; m.Add (i.fSerializedFieldName, mapper->FromObject (i.fTypeInfo, fromObjOfTypeT + i.fOffset)); } return VariantValue (m); }; fFromVariantMapper = [fields] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { //Debug::TraceContextBumper ctx (L"ObjectVariantMapper::TypeMappingDetails::{}::fFromVariantMapper"); Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); for (auto i : fields) { //DbgTrace (L"(fieldname = %s, offset=%d", i.fSerializedFieldName.c_str (), i.fOffset); Memory::Optional<VariantValue> o = m.Lookup (i.fSerializedFieldName); if (not o.empty ()) { mapper->ToObject (i.fTypeInfo, *o, intoObjOfTypeT + i.fOffset); } } }; } /* ******************************************************************************** ****************** DataExchangeFormat::ObjectVariantMapper ********************* ******************************************************************************** */ namespace { template <typename T, typename UseVariantType> ObjectVariantMapper::TypeMappingDetails mkSerializerInfo_ () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { RequireNotNull (fromObjOfTypeT); return VariantValue (static_cast<UseVariantType> (*reinterpret_cast<const T*> (fromObjOfTypeT))); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { RequireNotNull (intoObjOfTypeT); * reinterpret_cast<T*> (intoObjOfTypeT) = static_cast<T> (d.As<UseVariantType> ()); }; return ObjectVariantMapper::TypeMappingDetails (typeid (T), toVariantMapper, fromVariantMapper); } } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<bool> () { return mkSerializerInfo_<bool, bool> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<signed char> () { return mkSerializerInfo_<signed char, signed char> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<short int> () { return mkSerializerInfo_<short int, short int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<int> () { return mkSerializerInfo_<int, int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<long int> () { return mkSerializerInfo_<long int, long int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<long long int> () { return mkSerializerInfo_<long long int, long long int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<unsigned char> () { return mkSerializerInfo_<unsigned char, unsigned char> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<unsigned short int> () { return mkSerializerInfo_<unsigned short int, unsigned short int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<unsigned int> () { return mkSerializerInfo_<unsigned int, unsigned int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<unsigned long int> () { return mkSerializerInfo_<unsigned long int, unsigned long int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<unsigned long long int> () { return mkSerializerInfo_<unsigned long long int, unsigned long long int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<float> () { return mkSerializerInfo_<float, float> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<double> () { return mkSerializerInfo_<double, double> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<long double> () { return mkSerializerInfo_<long double, long double> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Time::Date> () { return mkSerializerInfo_<Time::Date, Time::Date> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Time::DateTime> () { return mkSerializerInfo_<Time::DateTime, Time::DateTime> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Characters::String> () { return mkSerializerInfo_<Characters::String, Characters::String> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Memory::VariantValue> () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { return *(reinterpret_cast<const VariantValue*> (fromObjOfTypeT)); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { *reinterpret_cast<VariantValue*> (intoObjOfTypeT) = d; }; return (ObjectVariantMapper::TypeMappingDetails (typeid (VariantValue), toVariantMapper, fromVariantMapper)); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Time::Duration> () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { return VariantValue ((reinterpret_cast<const Duration*> (fromObjOfTypeT))->As<wstring> ()); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { *reinterpret_cast<Duration*> (intoObjOfTypeT) = Duration (d.As<String> ().As<wstring> ()); }; return (ObjectVariantMapper::TypeMappingDetails (typeid (Duration), toVariantMapper, fromVariantMapper)); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Time::TimeOfDay> () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { return VariantValue ((reinterpret_cast<const TimeOfDay*> (fromObjOfTypeT))->GetAsSecondsCount ()); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { *reinterpret_cast<TimeOfDay*> (intoObjOfTypeT) = TimeOfDay (d.As<uint32_t> ()); }; return (ObjectVariantMapper::TypeMappingDetails (typeid (TimeOfDay), toVariantMapper, fromVariantMapper)); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Containers::Mapping<Characters::String, Characters::String>> () { typedef Mapping<String, String> ACTUAL_ELEMENT_TYPE; auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Mapping<String, VariantValue> m; const ACTUAL_ELEMENT_TYPE* actualMember = reinterpret_cast<const ACTUAL_ELEMENT_TYPE*> (fromObjOfTypeT); for (auto i : *actualMember) { // really could do either way - but second more efficient //m.Add (i.first, mapper->Serialize (typeid (String), reinterpret_cast<const Byte*> (&i.second))); m.Add (i.fKey, i.fValue); } return VariantValue (m); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); ACTUAL_ELEMENT_TYPE* actualInto = reinterpret_cast<ACTUAL_ELEMENT_TYPE*> (intoObjOfTypeT); actualInto->clear (); for (auto i : m) { // really could do either way - but second more efficient //actualInto->Add (i.first, mapper->ToObject<String> (i.second)); actualInto->Add (i.fKey, i.fValue.As<String> ()); } }; return (ObjectVariantMapper::TypeMappingDetails (typeid(ACTUAL_ELEMENT_TYPE), toVariantMapper, fromVariantMapper)); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Containers::Mapping<Characters::String, Memory::VariantValue>> () { typedef Mapping<String, VariantValue> ACTUAL_ELEMENT_TYPE; auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { const ACTUAL_ELEMENT_TYPE* actualMember = reinterpret_cast<const ACTUAL_ELEMENT_TYPE*> (fromObjOfTypeT); return VariantValue (*actualMember); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { ACTUAL_ELEMENT_TYPE* actualInto = reinterpret_cast<ACTUAL_ELEMENT_TYPE*> (intoObjOfTypeT); * actualInto = d.As<Mapping<String, VariantValue>> (); }; return (ObjectVariantMapper::TypeMappingDetails (typeid(ACTUAL_ELEMENT_TYPE), toVariantMapper, fromVariantMapper)); } namespace { Set<ObjectVariantMapper::TypeMappingDetails> mkCommonSerializers_ () { Set<ObjectVariantMapper::TypeMappingDetails> result; result.Add (ObjectVariantMapper::MakeCommonSerializer<bool> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<signed char> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<short int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<long int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<long long int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<unsigned char> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<unsigned short> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<unsigned int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<unsigned long int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<unsigned long long int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<float> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<double> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<long double> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Date> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<DateTime> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<String> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<VariantValue> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Time::Duration> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Time::TimeOfDay> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Mapping<String, String>> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Mapping<String, VariantValue>> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Time::DurationRange> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Time::DateRange> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Time::DateTimeRange> ()); return result; } // Construct the default map once, so that it never needs be re-created (though it could easily get cloned when modified) Set<ObjectVariantMapper::TypeMappingDetails> GetDefaultTypeMappers_ () { static Set<ObjectVariantMapper::TypeMappingDetails> sDefaults_ = mkCommonSerializers_ (); return sDefaults_; } } ObjectVariantMapper::ObjectVariantMapper () : fSerializers_ (GetDefaultTypeMappers_ ()) { } void ObjectVariantMapper::Add (const TypeMappingDetails& s) { fSerializers_.Add (s); } void ObjectVariantMapper::Add (const Set<TypeMappingDetails>& s) { fSerializers_.AddAll (s); } void ObjectVariantMapper::ResetToDefaultTypeRegistry () { fSerializers_ = GetDefaultTypeMappers_ (); } VariantValue ObjectVariantMapper::FromObject (const type_index& forTypeInfo, const Byte* objOfType) const { Require (Lookup_ (forTypeInfo).fToVariantMapper); return Lookup_ (forTypeInfo).fToVariantMapper (this, objOfType); } void ObjectVariantMapper::ToObject (const type_index& forTypeInfo, const VariantValue& d, Byte* into) const { Require (Lookup_ (forTypeInfo).fFromVariantMapper); Lookup_ (forTypeInfo).fFromVariantMapper (this, d, into); } ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::Lookup_ (const type_index& forTypeInfo) const { Debug::TraceContextBumper ctx (SDKSTR ("ObjectVariantMapper::Lookup_")); DbgTrace ("(forTypeInfo = %s)", forTypeInfo.name ()); TypeMappingDetails foo (forTypeInfo, nullptr, nullptr); auto i = fSerializers_.Lookup (foo); Require (i.IsPresent ()); // if not present, this is a usage error - only use types which are registered return *i; }
/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #include "../StroikaPreComp.h" #include "../Characters/Format.h" #include "../Containers/Tally.h" #include "../Debug/Trace.h" #include "../Time/Date.h" #include "../Time/DateRange.h" #include "../Time/DateTime.h" #include "../Time/DateTimeRange.h" #include "../Time/Duration.h" #include "../Time/DurationRange.h" #include "ObjectVariantMapper.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchangeFormat; using Time::Date; using Time::DateTime; using Time::Duration; using Time::TimeOfDay; /* ******************************************************************************** ******* DataExchangeFormat::ObjectVariantMapper::TypeMappingDetails ************ ******************************************************************************** */ ObjectVariantMapper::TypeMappingDetails::TypeMappingDetails ( const type_index& forTypeInfo, const std::function<VariantValue(const ObjectVariantMapper* mapper, const Byte* objOfType)>& toVariantMapper, const std::function<void(const ObjectVariantMapper* mapper, const VariantValue& d, Byte* into)>& fromVariantMapper ) : fForType (forTypeInfo) , fToVariantMapper (toVariantMapper) , fFromVariantMapper (fromVariantMapper) { } ObjectVariantMapper::TypeMappingDetails::TypeMappingDetails (const type_index& forTypeInfo, size_t n, const Sequence<StructureFieldInfo>& fields) : fForType (forTypeInfo) , fToVariantMapper () , fFromVariantMapper () { #if qDebug for (auto i : fields) { Require (i.fOffset < n); } { // assure each field unique Containers::Tally<size_t> t; for (auto i : fields) { t.Add (i.fOffset); } for (auto i : t) { Require (i.fCount == 1); } } #if 0 // GOOD TODO but cannot since no longer a member of the ObjectMapper class... { // Assure for each field type is registered for (auto i : fields) { Require (Lookup_ (i.fTypeInfo).fFromVariantMapper); Require (Lookup_ (i.fTypeInfo).fToVariantMapper); } } #endif #endif fToVariantMapper = [fields] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { //Debug::TraceContextBumper ctx (L"ObjectVariantMapper::TypeMappingDetails::{}::fToVariantMapper"); Mapping<String, VariantValue> m; for (auto i : fields) { //DbgTrace (L"(fieldname = %s, offset=%d", i.fSerializedFieldName.c_str (), i.fOffset); const Byte* fieldObj = fromObjOfTypeT + i.fOffset; m.Add (i.fSerializedFieldName, mapper->FromObject (i.fTypeInfo, fromObjOfTypeT + i.fOffset)); } return VariantValue (m); }; fFromVariantMapper = [fields] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { //Debug::TraceContextBumper ctx (L"ObjectVariantMapper::TypeMappingDetails::{}::fFromVariantMapper"); Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); for (auto i : fields) { //DbgTrace (L"(fieldname = %s, offset=%d", i.fSerializedFieldName.c_str (), i.fOffset); Memory::Optional<VariantValue> o = m.Lookup (i.fSerializedFieldName); if (not o.empty ()) { mapper->ToObject (i.fTypeInfo, *o, intoObjOfTypeT + i.fOffset); } } }; } /* ******************************************************************************** ****************** DataExchangeFormat::ObjectVariantMapper ********************* ******************************************************************************** */ namespace { template <typename T, typename UseVariantType> ObjectVariantMapper::TypeMappingDetails mkSerializerInfo_ () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { RequireNotNull (fromObjOfTypeT); return VariantValue (static_cast<UseVariantType> (*reinterpret_cast<const T*> (fromObjOfTypeT))); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { RequireNotNull (intoObjOfTypeT); * reinterpret_cast<T*> (intoObjOfTypeT) = static_cast<T> (d.As<UseVariantType> ()); }; return ObjectVariantMapper::TypeMappingDetails (typeid (T), toVariantMapper, fromVariantMapper); } } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<bool> () { return mkSerializerInfo_<bool, bool> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<signed char> () { return mkSerializerInfo_<signed char, signed char> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<short int> () { return mkSerializerInfo_<short int, short int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<int> () { return mkSerializerInfo_<int, int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<long int> () { return mkSerializerInfo_<long int, long int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<long long int> () { return mkSerializerInfo_<long long int, long long int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<unsigned char> () { return mkSerializerInfo_<unsigned char, unsigned char> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<unsigned short int> () { return mkSerializerInfo_<unsigned short int, unsigned short int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<unsigned int> () { return mkSerializerInfo_<unsigned int, unsigned int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<unsigned long int> () { return mkSerializerInfo_<unsigned long int, unsigned long int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<unsigned long long int> () { return mkSerializerInfo_<unsigned long long int, unsigned long long int> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<float> () { return mkSerializerInfo_<float, float> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<double> () { return mkSerializerInfo_<double, double> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<long double> () { return mkSerializerInfo_<long double, long double> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Time::Date> () { return mkSerializerInfo_<Time::Date, Time::Date> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Time::DateTime> () { return mkSerializerInfo_<Time::DateTime, Time::DateTime> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Characters::String> () { return mkSerializerInfo_<Characters::String, Characters::String> (); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Memory::VariantValue> () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { return *(reinterpret_cast<const VariantValue*> (fromObjOfTypeT)); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { *reinterpret_cast<VariantValue*> (intoObjOfTypeT) = d; }; return (ObjectVariantMapper::TypeMappingDetails (typeid (VariantValue), toVariantMapper, fromVariantMapper)); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Time::Duration> () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { return VariantValue ((reinterpret_cast<const Duration*> (fromObjOfTypeT))->As<wstring> ()); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { *reinterpret_cast<Duration*> (intoObjOfTypeT) = Duration (d.As<String> ().As<wstring> ()); }; return (ObjectVariantMapper::TypeMappingDetails (typeid (Duration), toVariantMapper, fromVariantMapper)); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Time::TimeOfDay> () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { return VariantValue ((reinterpret_cast<const TimeOfDay*> (fromObjOfTypeT))->GetAsSecondsCount ()); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { *reinterpret_cast<TimeOfDay*> (intoObjOfTypeT) = TimeOfDay (d.As<uint32_t> ()); }; return (ObjectVariantMapper::TypeMappingDetails (typeid (TimeOfDay), toVariantMapper, fromVariantMapper)); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Containers::Mapping<Characters::String, Characters::String>> () { typedef Mapping<String, String> ACTUAL_ELEMENT_TYPE; auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Mapping<String, VariantValue> m; const ACTUAL_ELEMENT_TYPE* actualMember = reinterpret_cast<const ACTUAL_ELEMENT_TYPE*> (fromObjOfTypeT); for (auto i : *actualMember) { // really could do either way - but second more efficient //m.Add (i.first, mapper->Serialize (typeid (String), reinterpret_cast<const Byte*> (&i.second))); m.Add (i.fKey, i.fValue); } return VariantValue (m); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); ACTUAL_ELEMENT_TYPE* actualInto = reinterpret_cast<ACTUAL_ELEMENT_TYPE*> (intoObjOfTypeT); actualInto->clear (); for (auto i : m) { // really could do either way - but second more efficient //actualInto->Add (i.first, mapper->ToObject<String> (i.second)); actualInto->Add (i.fKey, i.fValue.As<String> ()); } }; return (ObjectVariantMapper::TypeMappingDetails (typeid(ACTUAL_ELEMENT_TYPE), toVariantMapper, fromVariantMapper)); } template <> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Containers::Mapping<Characters::String, Memory::VariantValue>> () { typedef Mapping<String, VariantValue> ACTUAL_ELEMENT_TYPE; auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { const ACTUAL_ELEMENT_TYPE* actualMember = reinterpret_cast<const ACTUAL_ELEMENT_TYPE*> (fromObjOfTypeT); return VariantValue (*actualMember); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { ACTUAL_ELEMENT_TYPE* actualInto = reinterpret_cast<ACTUAL_ELEMENT_TYPE*> (intoObjOfTypeT); * actualInto = d.As<Mapping<String, VariantValue>> (); }; return (ObjectVariantMapper::TypeMappingDetails (typeid(ACTUAL_ELEMENT_TYPE), toVariantMapper, fromVariantMapper)); } namespace { Set<ObjectVariantMapper::TypeMappingDetails> mkCommonSerializers_ () { Set<ObjectVariantMapper::TypeMappingDetails> result; result.Add (ObjectVariantMapper::MakeCommonSerializer<bool> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<signed char> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<short int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<long int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<long long int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<unsigned char> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<unsigned short> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<unsigned int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<unsigned long int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<unsigned long long int> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<float> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<double> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<long double> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Date> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<DateTime> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<String> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<VariantValue> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Time::Duration> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Time::TimeOfDay> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Mapping<String, String>> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Mapping<String, VariantValue>> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Time::DurationRange> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Time::DateRange> ()); result.Add (ObjectVariantMapper::MakeCommonSerializer<Time::DateTimeRange> ()); return result; } // Construct the default map once, so that it never needs be re-created (though it could easily get cloned when modified) Set<ObjectVariantMapper::TypeMappingDetails> GetDefaultTypeMappers_ () { static Set<ObjectVariantMapper::TypeMappingDetails> sDefaults_ = mkCommonSerializers_ (); return sDefaults_; } } ObjectVariantMapper::ObjectVariantMapper () : fSerializers_ (GetDefaultTypeMappers_ ()) { } void ObjectVariantMapper::Add (const TypeMappingDetails& s) { fSerializers_.Add (s); } void ObjectVariantMapper::Add (const Set<TypeMappingDetails>& s) { fSerializers_.AddAll (s); } void ObjectVariantMapper::ResetToDefaultTypeRegistry () { fSerializers_ = GetDefaultTypeMappers_ (); } VariantValue ObjectVariantMapper::FromObject (const type_index& forTypeInfo, const Byte* objOfType) const { Require (Lookup_ (forTypeInfo).fToVariantMapper); return Lookup_ (forTypeInfo).fToVariantMapper (this, objOfType); } void ObjectVariantMapper::ToObject (const type_index& forTypeInfo, const VariantValue& d, Byte* into) const { Require (Lookup_ (forTypeInfo).fFromVariantMapper); Lookup_ (forTypeInfo).fFromVariantMapper (this, d, into); } ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::Lookup_ (const type_index& forTypeInfo) const { TypeMappingDetails foo (forTypeInfo, nullptr, nullptr); auto i = fSerializers_.Lookup (foo); #if qDebug if (not i.IsPresent ()) { Debug::TraceContextBumper ctx (SDKSTR ("ObjectVariantMapper::Lookup_")); DbgTrace ("(forTypeInfo = %s) - UnRegistered Type!", forTypeInfo.name ()); } #endif Require (i.IsPresent ()); // if not present, this is a usage error - only use types which are registered return *i; }
reduce noisyness of ObjectVariantMapper::Lookup_ tracelog output
reduce noisyness of ObjectVariantMapper::Lookup_ tracelog output
C++
mit
SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika
dc70e38a5bd1a9f483e43126cba7bfa516301302
Modules/Filtering/DisplacementField/include/itkTransformToDisplacementFieldFilter.hxx
Modules/Filtering/DisplacementField/include/itkTransformToDisplacementFieldFilter.hxx
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkTransformToDisplacementFieldFilter_hxx #define itkTransformToDisplacementFieldFilter_hxx #include "itkIdentityTransform.h" #include "itkTotalProgressReporter.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkImageScanlineIterator.h" namespace itk { template <typename TOutputImage, typename TParametersValueType> TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::TransformToDisplacementFieldFilter() { this->m_OutputSpacing.Fill(1.0); this->m_OutputOrigin.Fill(0.0); this->m_OutputDirection.SetIdentity(); this->m_Size.Fill(0); this->m_OutputStartIndex.Fill(0); this->SetNumberOfRequiredInputs(1); this->SetPrimaryInputName("Transform"); // #1 "ReferenceImage" optional Self::AddOptionalInputName("ReferenceImage", 1); this->DynamicMultiThreadingOn(); } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Size: " << this->m_Size << std::endl; os << indent << "OutputStartIndex: " << this->m_OutputStartIndex << std::endl; os << indent << "OutputSpacing: " << this->m_OutputSpacing << std::endl; os << indent << "OutputOrigin: " << this->m_OutputOrigin << std::endl; os << indent << "OutputDirection: " << this->m_OutputDirection << std::endl; os << indent << "UseReferenceImage: "; if (this->m_UseReferenceImage) { os << "On" << std::endl; } else { os << "Off" << std::endl; } } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::SetOutputSpacing( const SpacePrecisionType * spacing) { this->SetOutputSpacing(SpacingType(spacing)); } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::SetOutputOrigin( const SpacePrecisionType * origin) { this->SetOutputOrigin(OriginType(origin)); } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::SetInput(const TransformInputType * input) { if (input != itkDynamicCastInDebugMode<TransformInputType *>(this->ProcessObject::GetPrimaryInput())) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast<TransformInputType *>(input)); this->Modified(); } } template <typename TOutputImage, typename TParametersValueType> auto TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::GetInput() const -> const TransformInputType * { return itkDynamicCastInDebugMode<const TransformInputType *>(this->GetPrimaryInput()); } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::GenerateOutputInformation() { OutputImageType * output = this->GetOutput(); if (!output) { return; } const ReferenceImageBaseType * referenceImage = this->GetReferenceImage(); // Set the size of the output region if (m_UseReferenceImage && referenceImage) { output->SetLargestPossibleRegion(referenceImage->GetLargestPossibleRegion()); } else { const typename TOutputImage::RegionType outputLargestPossibleRegion(m_OutputStartIndex, m_Size); output->SetLargestPossibleRegion(outputLargestPossibleRegion); } // Set spacing and origin if (m_UseReferenceImage && referenceImage) { output->SetSpacing(referenceImage->GetSpacing()); output->SetOrigin(referenceImage->GetOrigin()); output->SetDirection(referenceImage->GetDirection()); } else { output->SetSpacing(m_OutputSpacing); output->SetOrigin(m_OutputOrigin); output->SetDirection(m_OutputDirection); } } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::DynamicThreadedGenerateData( const OutputImageRegionType & outputRegionForThread) { const TransformType * transform = this->GetInput()->Get(); // Check whether we can use a fast path for resampling. Fast path // can be used if the transformation is linear. Transform respond // to the IsLinear() call. if (transform->IsLinear()) { this->LinearThreadedGenerateData(outputRegionForThread); return; } // Otherwise, we use the normal method where the transform is called // for computing the transformation of every point. this->NonlinearThreadedGenerateData(outputRegionForThread); } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::NonlinearThreadedGenerateData( const OutputImageRegionType & outputRegionForThread) { // Get the output pointer OutputImageType * output = this->GetOutput(); const TransformType * transform = this->GetInput()->Get(); // Create an iterator that will walk the output region for this thread. using OutputIteratorType = ImageScanlineIterator<TOutputImage>; OutputIteratorType outIt(output, outputRegionForThread); // Define a few variables that will be used to translate from an input pixel // to an output pixel PointType outputPoint; // Coordinates of output pixel PointType transformedPoint; // Coordinates of transformed pixel PointType displacementPoint; // the difference PixelType displacementPixel; // the difference, cast to pixel type TotalProgressReporter progress(this, output->GetRequestedRegion().GetNumberOfPixels()); // Walk the output region outIt.GoToBegin(); while (!outIt.IsAtEnd()) { while (!outIt.IsAtEndOfLine()) { // Determine the index of the current output pixel output->TransformIndexToPhysicalPoint(outIt.GetIndex(), outputPoint); // Compute corresponding input pixel position transformedPoint = transform->TransformPoint(outputPoint); displacementPoint = transformedPoint - outputPoint; // Cast PointType -> PixelType for (IndexValueType idx = 0; idx < ImageDimension; ++idx) { displacementPixel[idx] = static_cast<typename PixelType::ValueType>(displacementPoint[idx]); } outIt.Set(displacementPixel); ++outIt; } outIt.NextLine(); progress.Completed(outputRegionForThread.GetSize()[0]); } } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::LinearThreadedGenerateData( const OutputImageRegionType & outputRegionForThread) { // Get the output pointer OutputImageType * outputPtr = this->GetOutput(); const TransformType * transformPtr = this->GetInput()->Get(); const OutputImageRegionType & largestPossibleRegion = outputPtr->GetLargestPossibleRegion(); // Create an iterator that will walk the output region for this thread. using OutputIteratorType = ImageScanlineIterator<TOutputImage>; OutputIteratorType outIt(outputPtr, outputRegionForThread); // Define a few indices that will be used to translate from an input pixel // to an output pixel PointType outputPoint; // Coordinates of current output pixel PointType inputPoint; // loop over the vector image while (!outIt.IsAtEnd()) { // Compare with the ResampleImageFilter // The region may be split along the fast scan-line direction, so // the computation is done for the beginning and end of the largest // possible region to improve consistent numerics. IndexType index = outIt.GetIndex(); index[0] = largestPossibleRegion.GetIndex(0); outputPtr->TransformIndexToPhysicalPoint(index, outputPoint); inputPoint = transformPtr->TransformPoint(outputPoint); const typename PointType::VectorType startDisplacement = inputPoint - outputPoint; index[0] += largestPossibleRegion.GetSize(0); outputPtr->TransformIndexToPhysicalPoint(index, outputPoint); inputPoint = transformPtr->TransformPoint(outputPoint); const typename PointType::VectorType endDisplacement = inputPoint - outputPoint; IndexValueType scanlineIndex = outIt.GetIndex()[0]; while (!outIt.IsAtEndOfLine()) { // Perform linear interpolation between startIndex and endIndex const double alpha = (scanlineIndex - largestPossibleRegion.GetIndex(0)) / double(largestPossibleRegion.GetSize(0)); const double oneMinusAlpha = 1.0 - alpha; PixelType displacement; for (unsigned int i = 0; i < ImageDimension; ++i) { displacement[i] = oneMinusAlpha * startDisplacement[i] + alpha * endDisplacement[i]; } outIt.Set(displacement); ++outIt; ++scanlineIndex; } outIt.NextLine(); } } } // end namespace itk #endif
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkTransformToDisplacementFieldFilter_hxx #define itkTransformToDisplacementFieldFilter_hxx #include "itkIdentityTransform.h" #include "itkTotalProgressReporter.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkImageScanlineIterator.h" namespace itk { template <typename TOutputImage, typename TParametersValueType> TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::TransformToDisplacementFieldFilter() { this->m_OutputSpacing.Fill(1.0); this->m_OutputOrigin.Fill(0.0); this->m_OutputDirection.SetIdentity(); this->m_Size.Fill(0); this->m_OutputStartIndex.Fill(0); this->SetNumberOfRequiredInputs(1); this->SetPrimaryInputName("Transform"); // #1 "ReferenceImage" optional Self::AddOptionalInputName("ReferenceImage", 1); this->DynamicMultiThreadingOn(); } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Size: " << this->m_Size << std::endl; os << indent << "OutputStartIndex: " << this->m_OutputStartIndex << std::endl; os << indent << "OutputSpacing: " << this->m_OutputSpacing << std::endl; os << indent << "OutputOrigin: " << this->m_OutputOrigin << std::endl; os << indent << "OutputDirection: " << this->m_OutputDirection << std::endl; os << indent << "UseReferenceImage: "; if (this->m_UseReferenceImage) { os << "On" << std::endl; } else { os << "Off" << std::endl; } } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::SetOutputSpacing( const SpacePrecisionType * spacing) { this->SetOutputSpacing(SpacingType(spacing)); } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::SetOutputOrigin( const SpacePrecisionType * origin) { this->SetOutputOrigin(OriginType(origin)); } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::SetInput(const TransformInputType * input) { if (input != itkDynamicCastInDebugMode<TransformInputType *>(this->ProcessObject::GetPrimaryInput())) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast<TransformInputType *>(input)); this->Modified(); } } template <typename TOutputImage, typename TParametersValueType> auto TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::GetInput() const -> const TransformInputType * { return itkDynamicCastInDebugMode<const TransformInputType *>(this->GetPrimaryInput()); } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::GenerateOutputInformation() { OutputImageType * output = this->GetOutput(); if (!output) { return; } const ReferenceImageBaseType * referenceImage = this->GetReferenceImage(); // Set the size of the output region if (m_UseReferenceImage && referenceImage) { output->SetLargestPossibleRegion(referenceImage->GetLargestPossibleRegion()); } else { const typename TOutputImage::RegionType outputLargestPossibleRegion(m_OutputStartIndex, m_Size); output->SetLargestPossibleRegion(outputLargestPossibleRegion); } // Set spacing and origin if (m_UseReferenceImage && referenceImage) { output->SetSpacing(referenceImage->GetSpacing()); output->SetOrigin(referenceImage->GetOrigin()); output->SetDirection(referenceImage->GetDirection()); } else { output->SetSpacing(m_OutputSpacing); output->SetOrigin(m_OutputOrigin); output->SetDirection(m_OutputDirection); } } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::DynamicThreadedGenerateData( const OutputImageRegionType & outputRegionForThread) { const TransformType * transform = this->GetInput()->Get(); // Check whether we can use a fast path for resampling. Fast path // can be used if the transformation is linear. Transform respond // to the IsLinear() call. if (transform->IsLinear()) { this->LinearThreadedGenerateData(outputRegionForThread); return; } // Otherwise, we use the normal method where the transform is called // for computing the transformation of every point. this->NonlinearThreadedGenerateData(outputRegionForThread); } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::NonlinearThreadedGenerateData( const OutputImageRegionType & outputRegionForThread) { // Get the output pointer OutputImageType * output = this->GetOutput(); const TransformType * transform = this->GetInput()->Get(); // Create an iterator that will walk the output region for this thread. using OutputIteratorType = ImageScanlineIterator<TOutputImage>; OutputIteratorType outIt(output, outputRegionForThread); // Define a few variables that will be used to translate from an input pixel // to an output pixel PointType outputPoint; // Coordinates of output pixel PointType transformedPoint; // Coordinates of transformed pixel PixelType displacementPixel; // the difference, cast to pixel type TotalProgressReporter progress(this, output->GetRequestedRegion().GetNumberOfPixels()); // Walk the output region outIt.GoToBegin(); while (!outIt.IsAtEnd()) { while (!outIt.IsAtEndOfLine()) { // Determine the index of the current output pixel output->TransformIndexToPhysicalPoint(outIt.GetIndex(), outputPoint); // Compute corresponding input pixel position transformedPoint = transform->TransformPoint(outputPoint); const typename PointType::VectorType displacementVector = transformedPoint - outputPoint; // Cast PointType -> PixelType for (IndexValueType idx = 0; idx < ImageDimension; ++idx) { displacementPixel[idx] = static_cast<typename PixelType::ValueType>(displacementVector[idx]); } outIt.Set(displacementPixel); ++outIt; } outIt.NextLine(); progress.Completed(outputRegionForThread.GetSize()[0]); } } template <typename TOutputImage, typename TParametersValueType> void TransformToDisplacementFieldFilter<TOutputImage, TParametersValueType>::LinearThreadedGenerateData( const OutputImageRegionType & outputRegionForThread) { // Get the output pointer OutputImageType * outputPtr = this->GetOutput(); const TransformType * transformPtr = this->GetInput()->Get(); const OutputImageRegionType & largestPossibleRegion = outputPtr->GetLargestPossibleRegion(); // Create an iterator that will walk the output region for this thread. using OutputIteratorType = ImageScanlineIterator<TOutputImage>; OutputIteratorType outIt(outputPtr, outputRegionForThread); // Define a few indices that will be used to translate from an input pixel // to an output pixel PointType outputPoint; // Coordinates of current output pixel PointType inputPoint; // loop over the vector image while (!outIt.IsAtEnd()) { // Compare with the ResampleImageFilter // The region may be split along the fast scan-line direction, so // the computation is done for the beginning and end of the largest // possible region to improve consistent numerics. IndexType index = outIt.GetIndex(); index[0] = largestPossibleRegion.GetIndex(0); outputPtr->TransformIndexToPhysicalPoint(index, outputPoint); inputPoint = transformPtr->TransformPoint(outputPoint); const typename PointType::VectorType startDisplacement = inputPoint - outputPoint; index[0] += largestPossibleRegion.GetSize(0); outputPtr->TransformIndexToPhysicalPoint(index, outputPoint); inputPoint = transformPtr->TransformPoint(outputPoint); const typename PointType::VectorType endDisplacement = inputPoint - outputPoint; IndexValueType scanlineIndex = outIt.GetIndex()[0]; while (!outIt.IsAtEndOfLine()) { // Perform linear interpolation between startIndex and endIndex const double alpha = (scanlineIndex - largestPossibleRegion.GetIndex(0)) / double(largestPossibleRegion.GetSize(0)); const double oneMinusAlpha = 1.0 - alpha; PixelType displacement; for (unsigned int i = 0; i < ImageDimension; ++i) { displacement[i] = oneMinusAlpha * startDisplacement[i] + alpha * endDisplacement[i]; } outIt.Set(displacement); ++outIt; ++scanlineIndex; } outIt.NextLine(); } } } // end namespace itk #endif
Fix `TransformToDisplacementFieldFilter` displacementPoint/Vector
BUG: Fix `TransformToDisplacementFieldFilter` displacementPoint/Vector The subtraction `transformedPoint - outputPoint` yields a `Vector`, not a `Point`. Adjusted `NonlinearThreadedGenerateData` accordingly. This little flaw was found by locally (temporarily) declaring converting constructors of `Point` "explicit".
C++
apache-2.0
hjmjohnson/ITK,thewtex/ITK,hjmjohnson/ITK,Kitware/ITK,richardbeare/ITK,thewtex/ITK,thewtex/ITK,hjmjohnson/ITK,InsightSoftwareConsortium/ITK,BRAINSia/ITK,hjmjohnson/ITK,BRAINSia/ITK,thewtex/ITK,BRAINSia/ITK,richardbeare/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,BRAINSia/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,hjmjohnson/ITK,thewtex/ITK,thewtex/ITK,richardbeare/ITK,InsightSoftwareConsortium/ITK,thewtex/ITK,richardbeare/ITK,BRAINSia/ITK,BRAINSia/ITK,Kitware/ITK,richardbeare/ITK,hjmjohnson/ITK,Kitware/ITK,hjmjohnson/ITK,richardbeare/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,richardbeare/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK
5a168471be6575c2f2de656f98b966f8518ad928
src/test/test_pru.cpp
src/test/test_pru.cpp
#include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <prussdrv.h> #include <pruss_intc_mapping.h> #define PRU_BIN_NAME "./pru0.bin" #define MS_TO_CYCLE(ms) ((ms)*2000000/1000) #define DDR_BASEADDR 0x80000000 #define OFFSET_DDR 0x00001000 #define OFFSET_SHAREDRAM 2048 //equivalent with 0x00002000 #define PRUSS0_SHARED_DATARAM 4 typedef unsigned int uint32_t; struct prupwm_param{ uint32_t flag; uint32_t period; uint32_t duty[6]; }; void dump_data_duty(struct prupwm_param *pwm_param) { int i; printf("Duty FOR PRM PWM:\n"); printf("==============================================\n"); for(i=0;i<6;i++) { printf("%x08\n", pwm_param->duty[i]); } printf("==============================================\n"); } void dump_data_flag(struct prupwm_param *pwm_param) { int i; printf("switch FOR PRM PWM:\n"); printf("==============================================\n"); for(i=0;i<6;i++) { printf("PWM-%d: ", i); if(pwm_param->flag & (1 << i)) printf("ON\n"); else printf("OFF\n"); } printf("==============================================\n"); } void switch_flag(struct prupwm_param *pwm_param, int bit) { if(pwm_param->flag & (1<<bit)) { pwm_param->flag &= (~(1<<bit)); } else { pwm_param->flag |= (1<<bit); } } int main(int argc, char const *argv[]) { int ret; int i; void *sharedMem; struct prupwm_param *pwm_param; tpruss_intc_initdata pruss_intc_initdata = PRUSS_INTC_INITDATA; printf("\nINFO: Starting PRU.\r\n"); /* Initialize the PRU */ prussdrv_init (); /* Open PRU Interrupt */ ret = prussdrv_open(PRU_EVTOUT_0); if (ret) { printf("prussdrv_open open failed\n"); return -1; } /* Get the interrupt initialized */ prussdrv_pruintc_init(&pruss_intc_initdata); prussdrv_map_prumem(PRUSS0_SHARED_DATARAM, &sharedMem); pwm_param = (struct prupwm_param *)(sharedMem + OFFSET_DDR); memset(pwm_param, 0, sizeof(struct prupwm_param)); pwm_param->flag = 0xcf; pwm_param->period = MS_TO_CYCLE(20); for(i=0;i<6;i++) { pwm_param->duty[i] = MS_TO_CYCLE(1.5); } /* Execute example on PRU */ ret = prussdrv_exec_program (0, PRU_BIN_NAME); printf("\tINFO: Executing PRU. ret=%d\r\n", ret); while(1) { switch(getchar()) { case 'd': if(pwm_param->duty[0] > 100) pwm_param->duty[0] -= 100; else pwm_param->duty[0] = 0; dump_data_duty(pwm_param); break; case 'u': if(pwm_param->duty[0] < pwm_param->period) pwm_param->duty[0] += 100; else pwm_param->duty[0] = pwm_param->period; dump_data_duty(pwm_param); break; case 'q': return -1; case '0': switch_flag(pwm_param, 0); dump_data_flag(pwm_param); break; case '1': switch_flag(pwm_param, 1); dump_data_flag(pwm_param); break; case '2': switch_flag(pwm_param, 2); dump_data_flag(pwm_param); break; case '3': switch_flag(pwm_param, 3); dump_data_flag(pwm_param); break; case '4': switch_flag(pwm_param, 4); dump_data_flag(pwm_param); break; case '5': switch_flag(pwm_param, 5); dump_data_flag(pwm_param); break; default: dump_data_flag(pwm_param); dump_data_duty(pwm_param); break; } usleep(100); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <prussdrv.h> #include <pruss_intc_mapping.h> #define PRU_BIN_NAME "./pru0.bin" #define MS_TO_CYCLE(ms) ((ms)*2000000/1000) #define DDR_BASEADDR 0x80000000 #define OFFSET_DDR 0x00001000 #define OFFSET_SHAREDRAM 2048 //equivalent with 0x00002000 #define PRUSS0_SHARED_DATARAM 4 typedef unsigned int uint32_t; struct prupwm_param{ uint32_t flag; uint32_t period; uint32_t duty[6]; }; void dump_data_duty(struct prupwm_param *pwm_param) { int i; printf("Duty FOR PRM PWM:\n"); printf("==============================================\n"); for(i=0;i<6;i++) { printf("%x08\n", pwm_param->duty[i]); } printf("==============================================\n"); } void dump_data_flag(struct prupwm_param *pwm_param) { int i; printf("switch FOR PRM PWM:\n"); printf("==============================================\n"); for(i=0;i<6;i++) { printf("PWM-%d: ", i); if(pwm_param->flag & (1 << i)) printf("ON\n"); else printf("OFF\n"); } printf("==============================================\n"); } void switch_flag(struct prupwm_param *pwm_param, int bit) { if(pwm_param->flag & (1<<bit)) { pwm_param->flag &= (~(1<<bit)); } else { pwm_param->flag |= (1<<bit); } } int main(int argc, char const *argv[]) { int ret; int i; void *sharedMem; struct prupwm_param *pwm_param; tpruss_intc_initdata pruss_intc_initdata = PRUSS_INTC_INITDATA; printf("\nINFO: Starting PRU.\r\n"); /* Initialize the PRU */ prussdrv_init (); /* Open PRU Interrupt */ ret = prussdrv_open(PRU_EVTOUT_0); if (ret) { printf("prussdrv_open open failed\n"); return -1; } /* Get the interrupt initialized */ prussdrv_pruintc_init(&pruss_intc_initdata); prussdrv_map_prumem(PRUSS0_SHARED_DATARAM, &sharedMem); pwm_param = (struct prupwm_param *)(sharedMem + OFFSET_DDR); memset(pwm_param, 0, sizeof(struct prupwm_param)); pwm_param->flag = 0xcf; pwm_param->period = MS_TO_CYCLE(20); for(i=0;i<6;i++) { pwm_param->duty[i] = MS_TO_CYCLE(1.5); } /* Execute example on PRU */ ret = prussdrv_exec_program (0, PRU_BIN_NAME); printf("\tINFO: Executing PRU. ret=%d\r\n", ret); while(1) { switch(getchar()) { case 'd': if(pwm_param->duty[0] > 100) pwm_param->duty[0] -= 100; else pwm_param->duty[0] = 0; dump_data_duty(pwm_param); break; case 'u': if(pwm_param->duty[0] < pwm_param->period) pwm_param->duty[0] += 100; else pwm_param->duty[0] = pwm_param->period; dump_data_duty(pwm_param); break; case 'q': return -1; case '0': switch_flag(pwm_param, 0); dump_data_flag(pwm_param); break; case '1': switch_flag(pwm_param, 1); dump_data_flag(pwm_param); break; case '2': switch_flag(pwm_param, 2); dump_data_flag(pwm_param); break; case '3': switch_flag(pwm_param, 3); dump_data_flag(pwm_param); break; case '4': switch_flag(pwm_param, 4); dump_data_flag(pwm_param); break; case '5': switch_flag(pwm_param, 5); dump_data_flag(pwm_param); break; default: dump_data_flag(pwm_param); dump_data_duty(pwm_param); break; } usleep(100); } prussdrv_pru_disable(0); prussdrv_exit (); return 0; }
update test for pru pwm
update test for pru pwm
C++
mit
MyXingzhe/xingzhe,MyXingzhe/xingzhe,MyXingzhe/xingzhe,MyXingzhe/xingzhe
c456f7afa2a339be1aa4f3131d37420cd9129208
src/cpp/session/modules/SessionRAddins.cpp
src/cpp/session/modules/SessionRAddins.cpp
/* * SessionRAddins.cpp.in * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/Macros.hpp> #include <core/Algorithm.hpp> #include <core/Debug.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/text/DcfParser.hpp> #include <boost/regex.hpp> #include <boost/foreach.hpp> #include <boost/bind.hpp> #include <boost/range/adaptor/map.hpp> #include <boost/system/error_code.hpp> #include <r/RSexp.hpp> #include <r/RExec.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace r_addins { namespace { class AddinSpecification { public: AddinSpecification() {} AddinSpecification(const std::string& name, const std::string& package, const std::string& title, const std::string& description, const std::string& binding) : name_(name), package_(package), title_(title), description_(description), binding_(binding) { } const std::string& getName() const { return name_; } const std::string& getPackage() const { return package_; } const std::string& getTitle() const { return title_; } const std::string& getDescription() const { return description_; } const std::string& getBinding() const { return binding_; } json::Object toJson() { json::Object object; object["name"] = name_; object["package"] = package_; object["title"] = title_; object["description"] = description_; object["binding"] = binding_; return object; } private: std::string name_; std::string package_; std::string title_; std::string description_; std::string binding_; }; class AddinRegistry : boost::noncopyable { public: void add(const std::string& package, const AddinSpecification& spec) { addins_[constructKey(package, spec.getBinding())] = spec; } bool contains(const std::string& package, const std::string& name) { return addins_.count(constructKey(package, name)); } const AddinSpecification& get(const std::string& package, const std::string& name) { return addins_[constructKey(package, name)]; } json::Object toJson() { json::Object object; BOOST_FOREACH(const std::string& key, addins_ | boost::adaptors::map_keys) { object[key] = addins_[key].toJson(); } return object; } std::size_t size() const { return addins_.size(); } private: static std::string constructKey(const std::string& package, const std::string& name) { return package + "::" + name; } std::map<std::string, AddinSpecification> addins_; }; AddinRegistry& addinRegistry() { static AddinRegistry instance; return instance; } // TODO: This probably belongs in a separate module and could be exported std::vector<FilePath> getLibPaths() { std::vector<std::string> libPathsString; r::exec::RFunction rfLibPaths(".libPaths"); Error error = rfLibPaths.call(&libPathsString); if (error) LOG_ERROR(error); std::vector<FilePath> libPaths(libPathsString.size()); BOOST_FOREACH(const std::string& path, libPathsString) { libPaths.push_back(module_context::resolveAliasedPath(path)); } return libPaths; } std::map<std::string, std::string> parseAddinDcf(const std::string& contents) { // read and parse the DCF file std::map<std::string, std::string> fields; std::string errMsg; Error error = text::parseDcfFile(contents, true, &fields, &errMsg); if (error) LOG_ERROR(error); return fields; } void registerAddin(const std::string& pkgName, std::map<std::string, std::string>& fields) { addinRegistry().add(pkgName, AddinSpecification( fields["Name"], pkgName, fields["Title"], fields["Description"], fields["Binding"])); } void registerAddins(const std::string& pkgName, const FilePath& addinPath) { static const boost::regex reSeparator("\\n{2,}"); std::string contents; Error error = core::readStringFromFile(addinPath, &contents, string_utils::LineEndingPosix); if (error) { LOG_ERROR(error); return; } boost::sregex_token_iterator it(contents.begin(), contents.end(), reSeparator, -1); boost::sregex_token_iterator end; for (; it != end; ++it) { std::map<std::string, std::string> fields = parseAddinDcf(*it); registerAddin(pkgName, fields); } } class AddinIndexer : public boost::noncopyable { public: void initialize(const std::vector<FilePath>& libPaths) { std::vector<FilePath> pkgPaths; BOOST_FOREACH(const FilePath& libPath, libPaths) { if (!libPath.exists()) continue; pkgPaths.clear(); Error error = libPath.children(&pkgPaths); if (error) LOG_ERROR(error); children_.insert( children_.end(), pkgPaths.begin(), pkgPaths.end()); } n_ = children_.size(); } bool pending() { return index_ != n_; } bool work() { // std::cout << "Job " << index_ + 1 << " of " << n_ << "\n"; // ::usleep(10000); const FilePath& pkgPath = children_[index_]; FilePath addinPath = pkgPath.childPath("rstudio/addins.dcf"); if (!addinPath.exists()) { ++index_; return pending(); } std::string pkgName = pkgPath.filename(); registerAddins(pkgName, addinPath); ++index_; return pending(); } private: std::vector<FilePath> children_; std::size_t n_; std::size_t index_; }; AddinIndexer& addinIndexer() { static AddinIndexer instance; return instance; } void indexLibraryPaths(const std::vector<FilePath>& libPaths) { addinIndexer().initialize(libPaths); module_context::scheduleIncrementalWork( boost::posix_time::milliseconds(10), boost::bind(&AddinIndexer::work, &addinIndexer()), true); } void onDeferredInit(bool newSession) { indexLibraryPaths(getLibPaths()); } bool waitForGetRAddins(json::JsonRpcFunctionContinuation continuation) { if (addinIndexer().pending()) return true; json::JsonRpcResponse response; response.setResult(addinRegistry().toJson()); continuation(Success(), &response); return false; } void getRAddins(const json::JsonRpcRequest& request, const json::JsonRpcFunctionContinuation& continuation) { module_context::schedulePeriodicWork( boost::posix_time::milliseconds(20), boost::bind(waitForGetRAddins, continuation), true); } Error noSuchAddin(const ErrorLocation& errorLocation) { return systemError(boost::system::errc::invalid_argument, errorLocation); } Error executeRAddin(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string commandId; Error error; error = json::readParams(request.params, &commandId); if (error) { LOG_ERROR(error); return error; } std::vector<std::string> splat = core::algorithm::split(commandId, "::"); if (splat.size() != 2) { LOG_ERROR_MESSAGE("unexpected command id '" + commandId + "'"); return Success(); } std::string pkgName = splat[0]; std::string cmdName = splat[1]; if (!addinRegistry().contains(pkgName, cmdName)) { std::string message = "no addin with id '" + commandId + "' registered"; pResponse->setError(noSuchAddin(ERROR_LOCATION), message); return Success(); } SEXP fnSEXP = r::sexp::findFunction(cmdName, pkgName); if (fnSEXP == R_UnboundValue) { std::string message = "no function '" + cmdName + "' found in package '" + pkgName + "'"; pResponse->setError(noSuchAddin(ERROR_LOCATION), message); return Success(); } error = r::exec::RFunction(fnSEXP).call(); if (error) { LOG_ERROR(error); return error; } return Success(); } } // end anonymous namespace Error initialize() { using boost::bind; using namespace module_context; events().onDeferredInit.connect(onDeferredInit); ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionRAddins.R")) (bind(registerAsyncRpcMethod, "get_r_addins", getRAddins)) (bind(registerRpcMethod, "execute_r_addin", executeRAddin)); return initBlock.execute(); } } // namespace r_addins } // namespace modules } // namespace session } // namespace rstudio
/* * SessionRAddins.cpp.in * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/Macros.hpp> #include <core/Algorithm.hpp> #include <core/Debug.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/text/DcfParser.hpp> #include <boost/regex.hpp> #include <boost/foreach.hpp> #include <boost/bind.hpp> #include <boost/range/adaptor/map.hpp> #include <boost/system/error_code.hpp> #include <r/RSexp.hpp> #include <r/RExec.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace r_addins { namespace { class AddinSpecification { public: AddinSpecification() {} AddinSpecification(const std::string& name, const std::string& package, const std::string& title, const std::string& description, const std::string& binding) : name_(name), package_(package), title_(title), description_(description), binding_(binding) { } const std::string& getName() const { return name_; } const std::string& getPackage() const { return package_; } const std::string& getTitle() const { return title_; } const std::string& getDescription() const { return description_; } const std::string& getBinding() const { return binding_; } json::Object toJson() { json::Object object; object["name"] = name_; object["package"] = package_; object["title"] = title_; object["description"] = description_; object["binding"] = binding_; return object; } private: std::string name_; std::string package_; std::string title_; std::string description_; std::string binding_; }; class AddinRegistry : boost::noncopyable { public: void add(const std::string& package, const AddinSpecification& spec) { addins_[constructKey(package, spec.getBinding())] = spec; } bool contains(const std::string& package, const std::string& name) { return addins_.count(constructKey(package, name)); } const AddinSpecification& get(const std::string& package, const std::string& name) { return addins_[constructKey(package, name)]; } json::Object toJson() { json::Object object; BOOST_FOREACH(const std::string& key, addins_ | boost::adaptors::map_keys) { object[key] = addins_[key].toJson(); } return object; } std::size_t size() const { return addins_.size(); } private: static std::string constructKey(const std::string& package, const std::string& name) { return package + "::" + name; } std::map<std::string, AddinSpecification> addins_; }; AddinRegistry& addinRegistry() { static AddinRegistry instance; return instance; } // TODO: This probably belongs in a separate module and could be exported std::vector<FilePath> getLibPaths() { std::vector<std::string> libPathsString; r::exec::RFunction rfLibPaths(".libPaths"); Error error = rfLibPaths.call(&libPathsString); if (error) LOG_ERROR(error); std::vector<FilePath> libPaths(libPathsString.size()); BOOST_FOREACH(const std::string& path, libPathsString) { libPaths.push_back(module_context::resolveAliasedPath(path)); } return libPaths; } std::map<std::string, std::string> parseAddinDcf(const std::string& contents) { // read and parse the DCF file std::map<std::string, std::string> fields; std::string errMsg; Error error = text::parseDcfFile(contents, true, &fields, &errMsg); if (error) LOG_ERROR(error); return fields; } void registerAddin(const std::string& pkgName, std::map<std::string, std::string>& fields) { addinRegistry().add(pkgName, AddinSpecification( fields["Name"], pkgName, fields["Title"], fields["Description"], fields["Binding"])); } void registerAddins(const std::string& pkgName, const FilePath& addinPath) { static const boost::regex reSeparator("\\n{2,}"); std::string contents; Error error = core::readStringFromFile(addinPath, &contents, string_utils::LineEndingPosix); if (error) { LOG_ERROR(error); return; } boost::sregex_token_iterator it(contents.begin(), contents.end(), reSeparator, -1); boost::sregex_token_iterator end; for (; it != end; ++it) { std::map<std::string, std::string> fields = parseAddinDcf(*it); registerAddin(pkgName, fields); } } class AddinIndexer : public boost::noncopyable { public: void initialize(const std::vector<FilePath>& libPaths) { std::vector<FilePath> pkgPaths; BOOST_FOREACH(const FilePath& libPath, libPaths) { if (!libPath.exists()) continue; pkgPaths.clear(); Error error = libPath.children(&pkgPaths); if (error) LOG_ERROR(error); children_.insert( children_.end(), pkgPaths.begin(), pkgPaths.end()); } n_ = children_.size(); } bool pending() { return index_ != n_; } bool work() { // std::cout << "Job " << index_ + 1 << " of " << n_ << "\n"; // ::usleep(10000); const FilePath& pkgPath = children_[index_]; FilePath addinPath = pkgPath.childPath("rstudio/addins.dcf"); if (!addinPath.exists()) { ++index_; return pending(); } std::string pkgName = pkgPath.filename(); registerAddins(pkgName, addinPath); ++index_; return pending(); } private: std::vector<FilePath> children_; std::size_t n_; std::size_t index_; }; AddinIndexer& addinIndexer() { static AddinIndexer instance; return instance; } void indexLibraryPaths(const std::vector<FilePath>& libPaths) { addinIndexer().initialize(libPaths); module_context::scheduleIncrementalWork( boost::posix_time::milliseconds(300), boost::posix_time::milliseconds(20), boost::bind(&AddinIndexer::work, &addinIndexer()), false); } void onDeferredInit(bool newSession) { indexLibraryPaths(getLibPaths()); } bool waitForGetRAddins(json::JsonRpcFunctionContinuation continuation) { if (addinIndexer().pending()) return true; json::JsonRpcResponse response; response.setResult(addinRegistry().toJson()); continuation(Success(), &response); return false; } void getRAddins(const json::JsonRpcRequest& request, const json::JsonRpcFunctionContinuation& continuation) { module_context::schedulePeriodicWork( boost::posix_time::milliseconds(20), boost::bind(waitForGetRAddins, continuation), true); } Error noSuchAddin(const ErrorLocation& errorLocation) { return systemError(boost::system::errc::invalid_argument, errorLocation); } Error executeRAddin(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string commandId; Error error; error = json::readParams(request.params, &commandId); if (error) { LOG_ERROR(error); return error; } std::vector<std::string> splat = core::algorithm::split(commandId, "::"); if (splat.size() != 2) { LOG_ERROR_MESSAGE("unexpected command id '" + commandId + "'"); return Success(); } std::string pkgName = splat[0]; std::string cmdName = splat[1]; if (!addinRegistry().contains(pkgName, cmdName)) { std::string message = "no addin with id '" + commandId + "' registered"; pResponse->setError(noSuchAddin(ERROR_LOCATION), message); return Success(); } SEXP fnSEXP = r::sexp::findFunction(cmdName, pkgName); if (fnSEXP == R_UnboundValue) { std::string message = "no function '" + cmdName + "' found in package '" + pkgName + "'"; pResponse->setError(noSuchAddin(ERROR_LOCATION), message); return Success(); } error = r::exec::RFunction(fnSEXP).call(); if (error) { LOG_ERROR(error); return error; } return Success(); } } // end anonymous namespace Error initialize() { using boost::bind; using namespace module_context; events().onDeferredInit.connect(onDeferredInit); ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionRAddins.R")) (bind(registerAsyncRpcMethod, "get_r_addins", getRAddins)) (bind(registerRpcMethod, "execute_r_addin", executeRAddin)); return initBlock.execute(); } } // namespace r_addins } // namespace modules } // namespace session } // namespace rstudio
tweak indexer timings
tweak indexer timings
C++
agpl-3.0
jar1karp/rstudio,jar1karp/rstudio,jrnold/rstudio,JanMarvin/rstudio,piersharding/rstudio,jar1karp/rstudio,piersharding/rstudio,jar1karp/rstudio,jar1karp/rstudio,jar1karp/rstudio,piersharding/rstudio,JanMarvin/rstudio,jrnold/rstudio,JanMarvin/rstudio,piersharding/rstudio,jar1karp/rstudio,jrnold/rstudio,jrnold/rstudio,jrnold/rstudio,JanMarvin/rstudio,jrnold/rstudio,jrnold/rstudio,JanMarvin/rstudio,piersharding/rstudio,jrnold/rstudio,piersharding/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,piersharding/rstudio,JanMarvin/rstudio,jrnold/rstudio,piersharding/rstudio,jar1karp/rstudio,JanMarvin/rstudio,piersharding/rstudio,jar1karp/rstudio
d7c06f5f72acad2fa07e40c922f83dbbd692a992
src/infill/RibbedSupportVaultGenerator.cpp
src/infill/RibbedSupportVaultGenerator.cpp
//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "RibbedSupportVaultGenerator.h" #include "../sliceDataStorage.h" #include <functional> #include <memory> #include <vector> //____v // TODO: Shortest distance to polygons function, and/or write/reuse distancefield things. // Idea maybe something can be done with isolines for the distance function? // TODO: Properly implement the distance heuristic for 'closest node' (it's now just 'euclidian_sqd_distance'), this is different from the distance field! // TODO: Implement 'Simplify' ... also heuristic? Also: Should the 'sequence_smooth_func' _really_ accept a vector of Points? (Probably a better way.) // TODO: Implement 'Truncate' ... is it needed to do it within the tree as well (see note-comment in function itself). // TODO: The convert trees to lines 'algorithm' is way too simple right now (unless they're already going to be connected later). // TODO: Lots of smaller TODO's in code itself, put on list! // Implementation in Infill classes & elsewhere (not here): // TODO: Outline offset, infill-overlap & perimeter gaps. // TODO: Frontend, make sure it's enabled for 'actual' infill only (search for infill pattern). // Stretch Goals: // TODO: Check Unit Tests & Documentation. // TODO: Result lines handled by Arachne insread :-) // TODO: Also generate support instead of just infill (and enable that in frontend). // TODO: Find a way to parallelize part(s) of it?? // TODO: G2/G3 to make trees properly curved? -> Should be in Arachne, not here, but still ;-) //____^ using namespace cura; // TODO??: Move/make-settable somehow or merge completely with this class (same as next getter). RibbedVaultTreeNode::point_distance_func_t RibbedVaultTreeNode::getPointDistanceFunction() { // NOTE: The following closure is too simple compared to the paper, used during development, and will be reimplemented. return point_distance_func_t( [](const Point& a, const Point& b) { return vSize2(b - a); }); } const Point& RibbedVaultTreeNode::getLocation() const { return p; } void RibbedVaultTreeNode::setLocation(Point loc) { p = loc; } void RibbedVaultTreeNode::addChild(const Point& p) { children.push_back(std::make_shared<RibbedVaultTreeNode>(p)); } std::shared_ptr<RibbedVaultTreeNode> RibbedVaultTreeNode::findClosestNode(const Point& x, const point_distance_func_t& heuristic) { coord_t closest_distance = heuristic(p, x); std::shared_ptr<RibbedVaultTreeNode> closest_node = shared_from_this(); findClosestNodeHelper(x, heuristic, closest_distance, closest_node); return closest_node; } void RibbedVaultTreeNode::propagateToNextLayer ( std::vector<std::shared_ptr<RibbedVaultTreeNode>>& next_trees, const Polygons& next_outlines, const coord_t& prune_distance, const float& smooth_magnitude ) const { next_trees.push_back(deepCopy()); auto& result = next_trees.back(); // TODO: What is the correct order of the following operations? result->prune(prune_distance); result->smoothen(smooth_magnitude); result->realign(next_outlines, next_trees); } // NOTE: Depth-first, as currently implemented. // Skips the root (because that has no root itself), but all initial nodes will have the root point anyway. void RibbedVaultTreeNode::visitBranches(const visitor_func_t& visitor) const { for (const auto& node : children) { visitor(p, node->p); node->visitBranches(visitor); } } // Node: RibbedVaultTreeNode::RibbedVaultTreeNode(const Point& p) : p(p) {} // Root (and Trunk): RibbedVaultTreeNode::RibbedVaultTreeNode(const Point& a, const Point& b) : RibbedVaultTreeNode(a) { children.push_back(std::make_shared<RibbedVaultTreeNode>(b)); is_root = true; } void RibbedVaultTreeNode::findClosestNodeHelper(const Point& x, const point_distance_func_t& heuristic, coord_t& closest_distance, std::shared_ptr<RibbedVaultTreeNode>& closest_node) { for (const auto& node : children) { node->findClosestNodeHelper(x, heuristic, closest_distance, closest_node); const coord_t distance = heuristic(node->p, x); if (distance < closest_distance) { closest_node = node; closest_distance = distance; } } } std::shared_ptr<RibbedVaultTreeNode> RibbedVaultTreeNode::deepCopy() const { std::shared_ptr<RibbedVaultTreeNode> local_root = std::make_shared<RibbedVaultTreeNode>(p); local_root->is_root = is_root; local_root->children.reserve(children.size()); for (const auto& node : children) { local_root->children.push_back(node->deepCopy()); } return local_root; } void RibbedVaultTreeNode::realign(const Polygons& outlines, std::vector<std::shared_ptr<RibbedVaultTreeNode>>& rerooted_parts) { // NOTE: Is it neccesary to 'reroot' parts further up the tree, or can it just be done from the root onwards // and ignore any further altercations once the outline is crossed (from the outside) for the first time? // NOT IMPLEMENTED YET! (See TODO's near the top of the file.) } void RibbedVaultTreeNode::smoothen(const float& magnitude) { // NOT IMPLEMENTED YET! (See TODO's near the top of the file.) } // Prune the tree from the extremeties (leaf-nodes) until the pruning distance is reached. coord_t RibbedVaultTreeNode::prune(const coord_t& pruning_distance) { if (pruning_distance <= 0) { return 0; } coord_t distance_pruned = 0; for (auto child_it = children.begin(); child_it != children.end(); ) { auto& child = *child_it; coord_t dist_pruned_child = child->prune(pruning_distance); if (dist_pruned_child >= pruning_distance) { // pruning is finished for child; dont modify further distance_pruned = std::max(distance_pruned, dist_pruned_child); ++child_it; } else { Point a = getLocation(); Point b = child->getLocation(); Point ba = a - b; coord_t ab_len = vSize(ba); if (dist_pruned_child + ab_len <= pruning_distance) { // we're still in the process of pruning assert(child->children.empty() && "when pruning away a node all it's children must already have been pruned away"); distance_pruned = std::max(distance_pruned, dist_pruned_child + ab_len); child_it = children.erase(child_it); } else { // pruning stops in between this node and the child Point n = b + normal(ba, pruning_distance - dist_pruned_child); assert(std::abs(vSize(n - b) + dist_pruned_child - pruning_distance) < 10 && "total pruned distance must be equal to the pruning_distance"); distance_pruned = std::max(distance_pruned, pruning_distance); child->setLocation(n); ++child_it; } } } return distance_pruned; } // -- -- -- -- -- -- // -- -- -- -- -- -- RibbedVaultDistanceField::RibbedVaultDistanceField ( const coord_t& radius, const Polygons& current_outline, const Polygons& current_overhang, const std::vector<std::shared_ptr<RibbedVaultTreeNode>>& initial_trees ) { supporting_radius = radius; Polygons supporting_polylines = current_outline; for (PolygonRef poly : supporting_polylines) { if ( ! poly.empty()) { poly.add(poly[0]); // add start so that the polyline is closed } } const RibbedVaultTreeNode::visitor_func_t add_offset_branch_func = [&](const Point& parent, const Point& child) { supporting_polylines.addLine(parent, child); }; for (const auto& tree : initial_trees) { tree->visitBranches(add_offset_branch_func); } supported = supporting_polylines.offsetPolyLine(supporting_radius); unsupported = current_overhang.difference(supported); } bool RibbedVaultDistanceField::tryGetNextPoint(Point* p) const { if (unsupported.area() < 25) { return false; } *p = unsupported[0][std::rand() % unsupported[0].size()]; return true; } void RibbedVaultDistanceField::update(const Point& to_node, const Point& added_leaf) { Polygons line; line.addLine(to_node, added_leaf); supported = supported.unionPolygons(line.offset(supporting_radius)); unsupported = unsupported.difference(supported); } // -- -- -- -- -- -- // -- -- -- -- -- -- RibbedSupportVaultGenerator::RibbedSupportVaultGenerator(const coord_t& radius, const SliceMeshStorage& mesh) : radius(radius) { size_t layer_id = 0; for (const auto& layer : mesh.layers) { layer_id_by_height.insert({layer.printZ, layer_id}); ++layer_id; } generateInitialInternalOverhangs(mesh, radius); generateTrees(mesh); // NOTE: Ideally, these would not be in the constructor. TODO?: Rewrite 'Generator' as loose functions and perhaps a struct. } const RibbedVaultLayer& RibbedSupportVaultGenerator::getTreesForLayer(const size_t& layer_id) { assert(tree_roots_per_layer.count(layer_id)); return tree_roots_per_layer[layer_id]; } // Returns 'added someting'. Polygons RibbedVaultLayer::convertToLines() const { Polygons result_lines; if (tree_roots.empty()) { return result_lines; } // TODO: The convert trees to lines 'algorithm' is way too simple right now (unless they're already going to be connected later). RibbedVaultTreeNode::visitor_func_t convert_trees_to_lines = [&result_lines](const Point& node, const Point& leaf) { result_lines.addLine(node, leaf); }; for (const auto& tree : tree_roots) { tree->visitBranches(convert_trees_to_lines); } return result_lines; } // Necesary, since normally overhangs are only generated for the outside of the model, and only when support is generated. void RibbedSupportVaultGenerator::generateInitialInternalOverhangs(const SliceMeshStorage& mesh, coord_t supporting_radius) { Polygons infill_area_below; for (size_t layer_nr = 0; layer_nr < mesh.layers.size(); layer_nr++) { const SliceLayer& current_layer = mesh.layers[layer_nr]; Polygons infill_area_here; for (auto& part : current_layer.parts) { infill_area_here.add(part.getOwnInfillArea()); } Polygons overhang = infill_area_here.intersection(infill_area_below.offset(-supporting_radius)); overhang_per_layer.emplace(layer_nr, overhang); infill_area_below = std::move(infill_area_here); } } void RibbedSupportVaultGenerator::generateTrees(const SliceMeshStorage& mesh) { const auto& tree_point_dist_func = RibbedVaultTreeNode::getPointDistanceFunction(); // For-each layer from top to bottom: std::for_each(mesh.layers.rbegin(), mesh.layers.rend(), [&](const SliceLayer& current_layer) { const size_t layer_id = layer_id_by_height[current_layer.printZ]; const Polygons& current_overhang = overhang_per_layer[layer_id]; const Polygons current_outlines = current_layer.getOutlines(); // TODO: Cache current outline of layer somewhere if (tree_roots_per_layer.count(layer_id) == 0) { tree_roots_per_layer.emplace(layer_id, RibbedVaultLayer()); } std::vector<std::shared_ptr<RibbedVaultTreeNode>>& current_trees = tree_roots_per_layer[layer_id].tree_roots; // Have (next) area in need of support. RibbedVaultDistanceField distance_field(radius, current_outlines, current_overhang, current_trees); constexpr size_t debug_max_iterations = 32; size_t i_debug = 0; // Until no more points need to be added to support all: // Determine next point from tree/outline areas via distance-field Point next; while(distance_measure.tryGetNextPoint(&next) && i_debug < debug_max_iterations) { ++i_debug; // Determine & conect to connection point in tree/outline. ClosestPolygonPoint cpp = PolygonUtils::findClosest(unsupported_location, current_outlines); Point node_location = cpp.p(); std::shared_ptr<RibbedVaultTreeNode> sub_tree(nullptr); coord_t current_dist = tree_point_dist_func(node, next); for (auto& tree : current_trees) { assert(tree); auto candidate_sub_tree = tree->findClosestNode(next, tree_point_dist_func); const coord_t candidate_dist = tree_point_dist_func(candidate_sub_tree->getLocation(), next); if (candidate_dist < current_dist) { current_dist = candidate_dist; sub_tree = candidate_sub_tree; } } // Update trees & distance fields. if (! sub_tree) { current_trees.push_back(std::make_shared<RibbedVaultTreeNode>(node, next)); } else { sub_tree->addChild(next); } distance_measure.update(node, next); } // Initialize trees for next lower layer from the current one. if (layer_id == 0) { return; } const size_t lower_layer_id = layer_id - 1; if (tree_roots_per_layer.count(layer_id) == 0) { tree_roots_per_layer.emplace(lower_layer_id, RibbedVaultLayer()); } std::vector<std::shared_ptr<RibbedVaultTreeNode>>& lower_trees = tree_roots_per_layer[lower_layer_id].tree_roots; for (auto& tree : current_trees) { tree->propagateToNextLayer ( lower_trees, current_outlines, radius, 0.1 // TODO: smooth-factor should be parameter! ... or at least not a random OK seeming magic value. ); } }); }
//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "RibbedSupportVaultGenerator.h" #include "../sliceDataStorage.h" #include <functional> #include <memory> #include <vector> //____v // TODO: Shortest distance to polygons function, and/or write/reuse distancefield things. // Idea maybe something can be done with isolines for the distance function? // TODO: Properly implement the distance heuristic for 'closest node' (it's now just 'euclidian_sqd_distance'), this is different from the distance field! // TODO: Implement 'Simplify' ... also heuristic? Also: Should the 'sequence_smooth_func' _really_ accept a vector of Points? (Probably a better way.) // TODO: Implement 'Truncate' ... is it needed to do it within the tree as well (see note-comment in function itself). // TODO: The convert trees to lines 'algorithm' is way too simple right now (unless they're already going to be connected later). // TODO: Lots of smaller TODO's in code itself, put on list! // Implementation in Infill classes & elsewhere (not here): // TODO: Outline offset, infill-overlap & perimeter gaps. // TODO: Frontend, make sure it's enabled for 'actual' infill only (search for infill pattern). // Stretch Goals: // TODO: Check Unit Tests & Documentation. // TODO: Result lines handled by Arachne insread :-) // TODO: Also generate support instead of just infill (and enable that in frontend). // TODO: Find a way to parallelize part(s) of it?? // TODO: G2/G3 to make trees properly curved? -> Should be in Arachne, not here, but still ;-) //____^ using namespace cura; // TODO??: Move/make-settable somehow or merge completely with this class (same as next getter). RibbedVaultTreeNode::point_distance_func_t RibbedVaultTreeNode::getPointDistanceFunction() { // NOTE: The following closure is too simple compared to the paper, used during development, and will be reimplemented. return point_distance_func_t( [](const Point& a, const Point& b) { return vSize2(b - a); }); } const Point& RibbedVaultTreeNode::getLocation() const { return p; } void RibbedVaultTreeNode::setLocation(Point loc) { p = loc; } void RibbedVaultTreeNode::addChild(const Point& p) { children.push_back(std::make_shared<RibbedVaultTreeNode>(p)); } std::shared_ptr<RibbedVaultTreeNode> RibbedVaultTreeNode::findClosestNode(const Point& x, const point_distance_func_t& heuristic) { coord_t closest_distance = heuristic(p, x); std::shared_ptr<RibbedVaultTreeNode> closest_node = shared_from_this(); findClosestNodeHelper(x, heuristic, closest_distance, closest_node); return closest_node; } void RibbedVaultTreeNode::propagateToNextLayer ( std::vector<std::shared_ptr<RibbedVaultTreeNode>>& next_trees, const Polygons& next_outlines, const coord_t& prune_distance, const float& smooth_magnitude ) const { next_trees.push_back(deepCopy()); auto& result = next_trees.back(); // TODO: What is the correct order of the following operations? result->prune(prune_distance); result->smoothen(smooth_magnitude); result->realign(next_outlines, next_trees); } // NOTE: Depth-first, as currently implemented. // Skips the root (because that has no root itself), but all initial nodes will have the root point anyway. void RibbedVaultTreeNode::visitBranches(const visitor_func_t& visitor) const { for (const auto& node : children) { visitor(p, node->p); node->visitBranches(visitor); } } // Node: RibbedVaultTreeNode::RibbedVaultTreeNode(const Point& p) : p(p) {} // Root (and Trunk): RibbedVaultTreeNode::RibbedVaultTreeNode(const Point& a, const Point& b) : RibbedVaultTreeNode(a) { children.push_back(std::make_shared<RibbedVaultTreeNode>(b)); is_root = true; } void RibbedVaultTreeNode::findClosestNodeHelper(const Point& x, const point_distance_func_t& heuristic, coord_t& closest_distance, std::shared_ptr<RibbedVaultTreeNode>& closest_node) { for (const auto& node : children) { node->findClosestNodeHelper(x, heuristic, closest_distance, closest_node); const coord_t distance = heuristic(node->p, x); if (distance < closest_distance) { closest_node = node; closest_distance = distance; } } } std::shared_ptr<RibbedVaultTreeNode> RibbedVaultTreeNode::deepCopy() const { std::shared_ptr<RibbedVaultTreeNode> local_root = std::make_shared<RibbedVaultTreeNode>(p); local_root->is_root = is_root; local_root->children.reserve(children.size()); for (const auto& node : children) { local_root->children.push_back(node->deepCopy()); } return local_root; } void RibbedVaultTreeNode::realign(const Polygons& outlines, std::vector<std::shared_ptr<RibbedVaultTreeNode>>& rerooted_parts) { // NOTE: Is it neccesary to 'reroot' parts further up the tree, or can it just be done from the root onwards // and ignore any further altercations once the outline is crossed (from the outside) for the first time? // NOT IMPLEMENTED YET! (See TODO's near the top of the file.) } void RibbedVaultTreeNode::smoothen(const float& magnitude) { // NOT IMPLEMENTED YET! (See TODO's near the top of the file.) } // Prune the tree from the extremeties (leaf-nodes) until the pruning distance is reached. coord_t RibbedVaultTreeNode::prune(const coord_t& pruning_distance) { if (pruning_distance <= 0) { return 0; } coord_t distance_pruned = 0; for (auto child_it = children.begin(); child_it != children.end(); ) { auto& child = *child_it; coord_t dist_pruned_child = child->prune(pruning_distance); if (dist_pruned_child >= pruning_distance) { // pruning is finished for child; dont modify further distance_pruned = std::max(distance_pruned, dist_pruned_child); ++child_it; } else { Point a = getLocation(); Point b = child->getLocation(); Point ba = a - b; coord_t ab_len = vSize(ba); if (dist_pruned_child + ab_len <= pruning_distance) { // we're still in the process of pruning assert(child->children.empty() && "when pruning away a node all it's children must already have been pruned away"); distance_pruned = std::max(distance_pruned, dist_pruned_child + ab_len); child_it = children.erase(child_it); } else { // pruning stops in between this node and the child Point n = b + normal(ba, pruning_distance - dist_pruned_child); assert(std::abs(vSize(n - b) + dist_pruned_child - pruning_distance) < 10 && "total pruned distance must be equal to the pruning_distance"); distance_pruned = std::max(distance_pruned, pruning_distance); child->setLocation(n); ++child_it; } } } return distance_pruned; } // -- -- -- -- -- -- // -- -- -- -- -- -- RibbedVaultDistanceField::RibbedVaultDistanceField ( const coord_t& radius, const Polygons& current_outline, const Polygons& current_overhang, const std::vector<std::shared_ptr<RibbedVaultTreeNode>>& initial_trees ) { supporting_radius = radius; Polygons supporting_polylines = current_outline; for (PolygonRef poly : supporting_polylines) { if ( ! poly.empty()) { poly.add(poly[0]); // add start so that the polyline is closed } } const RibbedVaultTreeNode::visitor_func_t add_offset_branch_func = [&](const Point& parent, const Point& child) { supporting_polylines.addLine(parent, child); }; for (const auto& tree : initial_trees) { tree->visitBranches(add_offset_branch_func); } supported = supporting_polylines.offsetPolyLine(supporting_radius); unsupported = current_overhang.difference(supported); } bool RibbedVaultDistanceField::tryGetNextPoint(Point* p) const { if (unsupported.area() < 25) { return false; } *p = unsupported[0][std::rand() % unsupported[0].size()]; return true; } void RibbedVaultDistanceField::update(const Point& to_node, const Point& added_leaf) { Polygons line; line.addLine(to_node, added_leaf); supported = supported.unionPolygons(line.offset(supporting_radius)); unsupported = unsupported.difference(supported); } // -- -- -- -- -- -- // -- -- -- -- -- -- RibbedSupportVaultGenerator::RibbedSupportVaultGenerator(const coord_t& radius, const SliceMeshStorage& mesh) : radius(radius) { size_t layer_id = 0; for (const auto& layer : mesh.layers) { layer_id_by_height.insert({layer.printZ, layer_id}); ++layer_id; } generateInitialInternalOverhangs(mesh, radius); generateTrees(mesh); // NOTE: Ideally, these would not be in the constructor. TODO?: Rewrite 'Generator' as loose functions and perhaps a struct. } const RibbedVaultLayer& RibbedSupportVaultGenerator::getTreesForLayer(const size_t& layer_id) { assert(tree_roots_per_layer.count(layer_id)); return tree_roots_per_layer[layer_id]; } // Returns 'added someting'. Polygons RibbedVaultLayer::convertToLines() const { Polygons result_lines; if (tree_roots.empty()) { return result_lines; } // TODO: The convert trees to lines 'algorithm' is way too simple right now (unless they're already going to be connected later). RibbedVaultTreeNode::visitor_func_t convert_trees_to_lines = [&result_lines](const Point& node, const Point& leaf) { result_lines.addLine(node, leaf); }; for (const auto& tree : tree_roots) { tree->visitBranches(convert_trees_to_lines); } return result_lines; } // Necesary, since normally overhangs are only generated for the outside of the model, and only when support is generated. void RibbedSupportVaultGenerator::generateInitialInternalOverhangs(const SliceMeshStorage& mesh, coord_t supporting_radius) { Polygons infill_area_below; for (size_t layer_nr = 0; layer_nr < mesh.layers.size(); layer_nr++) { const SliceLayer& current_layer = mesh.layers[layer_nr]; Polygons infill_area_here; for (auto& part : current_layer.parts) { infill_area_here.add(part.getOwnInfillArea()); } Polygons overhang = infill_area_here.intersection(infill_area_below.offset(-supporting_radius)); overhang_per_layer.emplace(layer_nr, overhang); infill_area_below = std::move(infill_area_here); } } void RibbedSupportVaultGenerator::generateTrees(const SliceMeshStorage& mesh) { const auto& tree_point_dist_func = RibbedVaultTreeNode::getPointDistanceFunction(); // For-each layer from top to bottom: std::for_each(mesh.layers.rbegin(), mesh.layers.rend(), [&](const SliceLayer& current_layer) { const size_t layer_id = layer_id_by_height[current_layer.printZ]; const Polygons& current_overhang = overhang_per_layer[layer_id]; Polygons current_outlines; for (const auto& part : current_layer.parts) { current_outlines.add(part.getOwnInfillArea()); } if (tree_roots_per_layer.count(layer_id) == 0) { tree_roots_per_layer.emplace(layer_id, RibbedVaultLayer()); } std::vector<std::shared_ptr<RibbedVaultTreeNode>>& current_trees = tree_roots_per_layer[layer_id].tree_roots; // Have (next) area in need of support. RibbedVaultDistanceField distance_field(radius, current_outlines, current_overhang, current_trees); constexpr size_t debug_max_iterations = 32; size_t i_debug = 0; // Until no more points need to be added to support all: // Determine next point from tree/outline areas via distance-field Point next; while(distance_measure.tryGetNextPoint(&next) && i_debug < debug_max_iterations) { ++i_debug; // Determine & conect to connection point in tree/outline. ClosestPolygonPoint cpp = PolygonUtils::findClosest(unsupported_location, current_outlines); Point node_location = cpp.p(); std::shared_ptr<RibbedVaultTreeNode> sub_tree(nullptr); coord_t current_dist = tree_point_dist_func(node, next); for (auto& tree : current_trees) { assert(tree); auto candidate_sub_tree = tree->findClosestNode(next, tree_point_dist_func); const coord_t candidate_dist = tree_point_dist_func(candidate_sub_tree->getLocation(), next); if (candidate_dist < current_dist) { current_dist = candidate_dist; sub_tree = candidate_sub_tree; } } // Update trees & distance fields. if (! sub_tree) { current_trees.push_back(std::make_shared<RibbedVaultTreeNode>(node, next)); } else { sub_tree->addChild(next); } distance_measure.update(node, next); } // Initialize trees for next lower layer from the current one. if (layer_id == 0) { return; } const size_t lower_layer_id = layer_id - 1; if (tree_roots_per_layer.count(layer_id) == 0) { tree_roots_per_layer.emplace(lower_layer_id, RibbedVaultLayer()); } std::vector<std::shared_ptr<RibbedVaultTreeNode>>& lower_trees = tree_roots_per_layer[lower_layer_id].tree_roots; for (auto& tree : current_trees) { tree->propagateToNextLayer ( lower_trees, current_outlines, radius, 0.1 // TODO: smooth-factor should be parameter! ... or at least not a random OK seeming magic value. ); } }); }
use infill outlines instead of mesh outlines
fix: use infill outlines instead of mesh outlines
C++
agpl-3.0
Ultimaker/CuraEngine,Ultimaker/CuraEngine
6f81989d76f6a57da0a1e58329f3fdea0cbb7057
dlg_main.cpp
dlg_main.cpp
#include "dlg_main.h" #include "control.h" #include "hardware.h" #include <QtGui> #include <QApplication> MainDlg::MainDlg(QWidget *parent) : QWidget(parent) { ui.setupUi(this); Qt::WindowFlags flags = windowFlags(); flags |= Qt::FramelessWindowHint; setWindowFlags(flags); char buf[256]; sprintf(buf, "%i%%", control().wVelFanCoil); ui.tlVelFanCoil->setText(buf); connect(&screenUpdate, SIGNAL( timeout(void) ), this, SLOT ( updateScreen(void) )); screenUpdate.setSingleShot(false); screenUpdate.start(100); } void MainDlg::on_pbNotte_toggled(bool checked) { if (checked) { ui.pbNotte->setPalette(QPalette(QColor(255, 64, 64))); } else { ui.pbNotte->setPalette(QApplication::palette()); } QMutexLocker lock(&control().mFields); control().xRiscaldaNotte = checked; } void MainDlg::on_pbGiorno_toggled(bool checked) { if (checked) { ui.pbGiorno->setPalette(QPalette(QColor(255, 64, 64))); } else { ui.pbGiorno->setPalette(QApplication::palette()); } QMutexLocker lock(&control().mFields); control().xRiscaldaGiorno = checked; } void MainDlg::on_pbSoffitta_toggled(bool checked) { if (checked) { ui.pbSoffitta->setPalette(QPalette(QColor(255, 64, 64))); } else { ui.pbSoffitta->setPalette(QApplication::palette()); } QMutexLocker lock(&control().mFields); control().xRiscaldaSoffitta = checked; } void MainDlg::on_pbFanCoil_toggled(bool checked) { if (checked) { ui.pbFanCoil->setPalette(QPalette(QColor(255, 64, 64))); } else { ui.pbFanCoil->setPalette(QApplication::palette()); } QMutexLocker lock(&control().mFields); control().xFanCoil = checked; } void MainDlg::updateStatoRisc() { if (ui.pbRiscCaldaia->isChecked()) { ui.pbRiscCaldaia->setPalette(QPalette(QColor(255, 64, 64))); ui.pbRiscCaldaia->setText("Caldaia ON"); } else if (control().xCaldaiaInUso) { ui.pbRiscCaldaia->setPalette(QPalette(QColor(220,220,128))); ui.pbRiscCaldaia->setText("Caldaia auto ON"); } else { ui.pbRiscCaldaia->setPalette(QApplication::palette()); ui.pbRiscCaldaia->setText("Caldaia OFF"); } if (ui.pbRiscPompaCalore->isChecked()) { ui.pbRiscPompaCalore->setPalette(QPalette(QColor(64, 255, 64))); ui.pbRiscPompaCalore->setText("Pompa di calore ON"); } else if (control().xPompaCaloreInUso) { ui.pbRiscPompaCalore->setPalette(QPalette(QColor(220,220,128))); ui.pbRiscPompaCalore->setText("Pompa di calore auto ON"); } else { ui.pbRiscPompaCalore->setPalette(QApplication::palette()); ui.pbRiscPompaCalore->setText("Pompa di calore OFF"); } } void MainDlg::on_pbRiscCaldaia_toggled(bool checked) { QMutexLocker lock(&control().mFields); control().xUsaCaldaia = checked; updateStatoRisc(); } void MainDlg::on_pbRiscPompaCalore_toggled(bool checked) { QMutexLocker lock(&control().mFields); control().xUsaPompaCalore = checked; updateStatoRisc(); } void MainDlg::on_pbVelMinus_clicked() { QMutexLocker lock(&control().mFields); if (control().wVelFanCoil > 5) control().wVelFanCoil -= 5; else control().wVelFanCoil = 0; char buf[256]; sprintf(buf, "%i%%", control().wVelFanCoil); ui.tlVelFanCoil->setText(buf); } void MainDlg::on_pbVelPlus_clicked() { QMutexLocker lock(&control().mFields); if (control().wVelFanCoil < 95) control().wVelFanCoil += 5; else control().wVelFanCoil = 100; char buf[256]; sprintf(buf, "%i%%", control().wVelFanCoil); ui.tlVelFanCoil->setText(buf); } void MainDlg::on_pbTrasfAccumulo_toggled(bool checked) { if (checked) { ui.pbTrasfAccumulo->setPalette(QPalette(QColor(64, 255, 64))); } else { ui.pbTrasfAccumulo->setPalette(QApplication::palette()); } QMutexLocker lock(&control().mFields); control().xTrasfAccumulo = checked; } void MainDlg::on_pbApriCucina_clicked() { QMutexLocker lock(&control().mFields); control().xApriCucina = true; } void MainDlg::on_pbChiudiCucina_clicked() { QMutexLocker lock(&control().mFields); control().xChiudiCucina = true; } void MainDlg::updateScreen() { char buf[256]; ui.tlData->setText(QDate::currentDate().toString("dd/MM/yyyy")); ui.tlOra->setText(QTime::currentTime().toString("h:mm")); QMutexLocker lock(&control().mFields); sprintf(buf, "%.1f", control().wTemperaturaACS/10.0); ui.tlTempAcquaTop->setText(buf); sprintf(buf, "%.1f", control().wTemperaturaBoiler/10.0); ui.tlTempAcquaBot->setText(buf); sprintf(buf, "%.1f", control().wTemperaturaAccumuli/10.0); ui.tlTempAccumulo->setText(buf); if (control().xCaldaiaInUso) { ui.pbApriCucina->setPalette(QPalette(QColor(64, 255, 64))); } else { ui.pbApriCucina->setPalette(QApplication::palette()); } if (control().xApriCucina) { ui.pbApriCucina->setPalette(QPalette(QColor(64, 255, 64))); } else { ui.pbApriCucina->setPalette(QApplication::palette()); } if (control().xChiudiCucina) { ui.pbChiudiCucina->setPalette(QPalette(QColor(64, 255, 64))); } else { ui.pbChiudiCucina->setPalette(QApplication::palette()); } updateStatoRisc(); }
#include "dlg_main.h" #include "control.h" #include "hardware.h" #include <QtGui> #include <QApplication> MainDlg::MainDlg(QWidget *parent) : QWidget(parent) { ui.setupUi(this); Qt::WindowFlags flags = windowFlags(); flags |= Qt::FramelessWindowHint; setWindowFlags(flags); ui.pbRiscPompaCalore->setChecked(true); char buf[256]; sprintf(buf, "%i%%", control().wVelFanCoil); ui.tlVelFanCoil->setText(buf); connect(&screenUpdate, SIGNAL( timeout(void) ), this, SLOT ( updateScreen(void) )); screenUpdate.setSingleShot(false); screenUpdate.start(100); } void MainDlg::on_pbNotte_toggled(bool checked) { if (checked) { ui.pbNotte->setPalette(QPalette(QColor(255, 64, 64))); } else { ui.pbNotte->setPalette(QApplication::palette()); } QMutexLocker lock(&control().mFields); control().xRiscaldaNotte = checked; } void MainDlg::on_pbGiorno_toggled(bool checked) { if (checked) { ui.pbGiorno->setPalette(QPalette(QColor(255, 64, 64))); } else { ui.pbGiorno->setPalette(QApplication::palette()); } QMutexLocker lock(&control().mFields); control().xRiscaldaGiorno = checked; } void MainDlg::on_pbSoffitta_toggled(bool checked) { if (checked) { ui.pbSoffitta->setPalette(QPalette(QColor(255, 64, 64))); } else { ui.pbSoffitta->setPalette(QApplication::palette()); } QMutexLocker lock(&control().mFields); control().xRiscaldaSoffitta = checked; } void MainDlg::on_pbFanCoil_toggled(bool checked) { if (checked) { ui.pbFanCoil->setPalette(QPalette(QColor(255, 64, 64))); } else { ui.pbFanCoil->setPalette(QApplication::palette()); } QMutexLocker lock(&control().mFields); control().xFanCoil = checked; } void MainDlg::updateStatoRisc() { if (ui.pbRiscCaldaia->isChecked()) { ui.pbRiscCaldaia->setPalette(QPalette(QColor(255, 64, 64))); ui.pbRiscCaldaia->setText("Caldaia ON"); } else if (control().xCaldaiaInUso) { ui.pbRiscCaldaia->setPalette(QPalette(QColor(220,220,128))); ui.pbRiscCaldaia->setText("Caldaia auto ON"); } else { ui.pbRiscCaldaia->setPalette(QApplication::palette()); ui.pbRiscCaldaia->setText("Caldaia OFF"); } if (ui.pbRiscPompaCalore->isChecked()) { ui.pbRiscPompaCalore->setPalette(QPalette(QColor(64, 255, 64))); ui.pbRiscPompaCalore->setText("Pompa di calore ON"); } else if (control().xPompaCaloreInUso) { ui.pbRiscPompaCalore->setPalette(QPalette(QColor(220,220,128))); ui.pbRiscPompaCalore->setText("Pompa di calore auto ON"); } else { ui.pbRiscPompaCalore->setPalette(QApplication::palette()); ui.pbRiscPompaCalore->setText("Pompa di calore OFF"); } } void MainDlg::on_pbRiscCaldaia_toggled(bool checked) { QMutexLocker lock(&control().mFields); control().xUsaCaldaia = checked; updateStatoRisc(); } void MainDlg::on_pbRiscPompaCalore_toggled(bool checked) { QMutexLocker lock(&control().mFields); control().xUsaPompaCalore = checked; updateStatoRisc(); } void MainDlg::on_pbVelMinus_clicked() { QMutexLocker lock(&control().mFields); if (control().wVelFanCoil > 5) control().wVelFanCoil -= 5; else control().wVelFanCoil = 0; char buf[256]; sprintf(buf, "%i%%", control().wVelFanCoil); ui.tlVelFanCoil->setText(buf); } void MainDlg::on_pbVelPlus_clicked() { QMutexLocker lock(&control().mFields); if (control().wVelFanCoil < 95) control().wVelFanCoil += 5; else control().wVelFanCoil = 100; char buf[256]; sprintf(buf, "%i%%", control().wVelFanCoil); ui.tlVelFanCoil->setText(buf); } void MainDlg::on_pbTrasfAccumulo_toggled(bool checked) { if (checked) { ui.pbTrasfAccumulo->setPalette(QPalette(QColor(64, 255, 64))); } else { ui.pbTrasfAccumulo->setPalette(QApplication::palette()); } QMutexLocker lock(&control().mFields); control().xTrasfAccumulo = checked; } void MainDlg::on_pbApriCucina_clicked() { QMutexLocker lock(&control().mFields); control().xApriCucina = true; } void MainDlg::on_pbChiudiCucina_clicked() { QMutexLocker lock(&control().mFields); control().xChiudiCucina = true; } void MainDlg::updateScreen() { char buf[256]; ui.tlData->setText(QDate::currentDate().toString("dd/MM/yyyy")); ui.tlOra->setText(QTime::currentTime().toString("h:mm")); QMutexLocker lock(&control().mFields); sprintf(buf, "%.1f", control().wTemperaturaACS/10.0); ui.tlTempAcquaTop->setText(buf); sprintf(buf, "%.1f", control().wTemperaturaBoiler/10.0); ui.tlTempAcquaBot->setText(buf); sprintf(buf, "%.1f", control().wTemperaturaAccumuli/10.0); ui.tlTempAccumulo->setText(buf); if (control().xCaldaiaInUso) { ui.pbApriCucina->setPalette(QPalette(QColor(64, 255, 64))); } else { ui.pbApriCucina->setPalette(QApplication::palette()); } if (control().xApriCucina) { ui.pbApriCucina->setPalette(QPalette(QColor(64, 255, 64))); } else { ui.pbApriCucina->setPalette(QApplication::palette()); } if (control().xChiudiCucina) { ui.pbChiudiCucina->setPalette(QPalette(QColor(64, 255, 64))); } else { ui.pbChiudiCucina->setPalette(QApplication::palette()); } updateStatoRisc(); }
fix "pompa auto ON" all'accensione
fix "pompa auto ON" all'accensione
C++
mit
pillo79/home-control,pillo79/home-control
6b67200286d759b3b5de0c9cb2feaf53dc19a833
src/xdEngine/main.cpp
src/xdEngine/main.cpp
// 01.01.2017 Султан Xottab_DUTY Урамаев // Чем стрелы коленом ловить, гораздо интереснее отстреливать свои ноги. Продолжим. #include <GLFW/glfw3.h> #include "xdCore.hpp" #include "Console.hpp" #include "xdEngine.hpp" void InitializeConsole() { Console = new xdConsole; Console->Initialize(); } void destroyConsole() { Console->CloseLog(); delete Console; } void HelpCmdArgs() { Console->Log("\nUse parameters with values only with commas(-param \"value\")\n"\ "-param value will return \"alue\"\n"\ "-param \"value\" will return \"value\"\n\n"\ "Available parameters:\n"\ "-name - Specifies AppName, default is \"X-Day Engine\" \n"\ "-game - Specifies game library to be attached, default is \"xdGame\";\n" "-datapath - Specifies path of application data folder, default is \"*WorkingDirectory*/appdata\"\n"\ "-respath - Specifies path of resources folder, default is \"*WorkingDirectory*/res\"\n"\ "-mainconfig - Specifies path and name of main config file (path/name.extension), default is \"*DataPath*/main.config\" \n"\ "-mainlog - Specifies path and name of main log file (path/name.extension), default is \"*DataPath*/main.log\"\n"\ "-nolog - Completely disables engine log. May increase performance\n"\ "-nologflush - Disables log flushing. Useless if -nolog defined"); Console->Log("\nИспользуйте параметры только с кавычками(-параметр \"значение\")\n"\ "-параметр значение вернёт \"начени\"\n"\ "-параметр \"значение\" вернёт \"значение\"\n"\ "\nДоступные параметры:\n"\ "-name - Задаёт AppName, по умолчанию: \"X-Day Engine\" \n"\ "-game - Задаёт игровую библиотеку для подключения, по умолчанию: \"xdGame\";\n" "-datapath - Задаёт путь до папки с настройками, по умолчанию: \"*WorkingDirectory*/appdata\"\n"\ "-respath - Задаёт путь до папки с ресурсами, по умолчанию: \"*WorkingDirectory*/res\"\n"\ "-mainconfig - Задаёт путь и имя главного файла настроек (путь/имя.расширение), по умолчанию: \"*DataPath*/main.config\" \n"\ "-mainlog - Задаёт путь и имя главного лог файла (путь/имя.расширение), по умолчанию: \"*DataPath*/main.log\"\n"\ "-nolog - Полностью выключает лог движка. Может повысить производительность\n"\ "-nologflush - Выключает сброс лога в файл. Не имеет смысла если задан -nolog", false); } void Startup() { } int main(int argc, char* argv[]) { #ifdef WINDOWS system("chcp 65001"); #endif Core.Initialize("X-Day Engine", **argv); InitializeConsole(); Console->Log(Core.GetGLFWVersionString()); Console->Log(Core.GetBuildString()); Console->Log("Core.Params: " + Core.Params); Console->Log("Девиз: Чем стрелы коленом ловить, гораздо интереснее отстреливать свои ноги. Продолжим.", false); Console->Log("Slogan: It's more interesting to shoot your feet, than catch arrows by your knee. Let's continue."); HelpCmdArgs(); Startup(); destroyConsole(); system("pause"); return 0; }
// 01.01.2017 Султан Xottab_DUTY Урамаев // Чем стрелы коленом ловить, гораздо интереснее отстреливать свои ноги. Продолжим. #include <GLFW/glfw3.h> #include "xdCore.hpp" #include "Console.hpp" #include "xdEngine.hpp" void InitializeConsole() { Console = new xdConsole; Console->Initialize(); } void destroyConsole() { Console->CloseLog(); delete Console; } void HelpCmdArgs() { Console->Log("\nUse parameters with values only with commas(-param \"value\")\n"\ "-param value will return \"alue\"\n"\ "-param \"value\" will return \"value\"\n\n"\ "Available parameters:\n"\ "-name - Specifies AppName, default is \"X-Day Engine\" \n"\ "-game - Specifies game library to be attached, default is \"xdGame\";\n" "-datapath - Specifies path of application data folder, default is \"*WorkingDirectory*/appdata\"\n"\ "-respath - Specifies path of resources folder, default is \"*WorkingDirectory*/res\"\n"\ "-mainconfig - Specifies path and name of main config file (path/name.extension), default is \"*DataPath*/main.config\" \n"\ "-mainlog - Specifies path and name of main log file (path/name.extension), default is \"*DataPath*/main.log\"\n"\ "-nolog - Completely disables engine log. May increase performance\n"\ "-nologflush - Disables log flushing. Useless if -nolog defined"); Console->Log("\nИспользуйте параметры только с кавычками(-параметр \"значение\")\n"\ "-параметр значение вернёт \"начени\"\n"\ "-параметр \"значение\" вернёт \"значение\"\n"\ "\nДоступные параметры:\n"\ "-name - Задаёт AppName, по умолчанию: \"X-Day Engine\" \n"\ "-game - Задаёт игровую библиотеку для подключения, по умолчанию: \"xdGame\";\n" "-datapath - Задаёт путь до папки с настройками, по умолчанию: \"*WorkingDirectory*/appdata\"\n"\ "-respath - Задаёт путь до папки с ресурсами, по умолчанию: \"*WorkingDirectory*/res\"\n"\ "-mainconfig - Задаёт путь и имя главного файла настроек (путь/имя.расширение), по умолчанию: \"*DataPath*/main.config\" \n"\ "-mainlog - Задаёт путь и имя главного лог файла (путь/имя.расширение), по умолчанию: \"*DataPath*/main.log\"\n"\ "-nolog - Полностью выключает лог движка. Может повысить производительность\n"\ "-nologflush - Выключает сброс лога в файл. Не имеет смысла если задан -nolog", false); } void Startup() { } int main(int argc, char* argv[]) { #ifdef WINDOWS system("chcp 65001"); #endif Core.Initialize("X-Day Engine", **argv); InitializeConsole(); Console->Log(Core.GetGLFWVersionString()); Console->Log(Core.GetBuildString()); Console->Log("Core.Params: " + Core.Params); Console->Log("Девиз: Чем стрелы коленом ловить, гораздо интереснее отстреливать свои ноги. Продолжим.", false); Console->Log("Slogan: It's more interesting to shoot your feet, than catch arrows by your knee. Let's continue."); HelpCmdArgs(); glfwInit(); Console->Log("GLFW initialized."); Startup(); glfwTerminate(); Console->Log("GLFW terminated."); destroyConsole(); system("pause"); return 0; }
Add basic GLFW initialization and termination
Add basic GLFW initialization and termination
C++
mit
Xottab-DUTY/X-Day-engine
db52ca56d21d3110761fb829000d0af9aa0d3479
chrome/common/visitedlink_common.cc
chrome/common/visitedlink_common.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/visitedlink_common.h" #include "base/logging.h" #include "base/md5.h" #include "googleurl/src/gurl.h" const VisitedLinkCommon::Fingerprint VisitedLinkCommon::null_fingerprint_ = 0; const VisitedLinkCommon::Hash VisitedLinkCommon::null_hash_ = -1; VisitedLinkCommon::VisitedLinkCommon() : hash_table_(NULL), table_length_(0) { } VisitedLinkCommon::~VisitedLinkCommon() { } // FIXME: this uses linear probing, it should be replaced with quadratic // probing or something better. See VisitedLinkMaster::AddFingerprint bool VisitedLinkCommon::IsVisited(const char* canonical_url, size_t url_len) const { if (url_len == 0) return false; if (!hash_table_ || table_length_ == 0) return false; return IsVisited(ComputeURLFingerprint(canonical_url, url_len)); } bool VisitedLinkCommon::IsVisited(const GURL& url) const { return IsVisited(url.spec().data(), url.spec().size()); } bool VisitedLinkCommon::IsVisited(Fingerprint fingerprint) const { // Go through the table until we find the item or an empty spot (meaning it // wasn't found). This loop will terminate as long as the table isn't full, // which should be enforced by AddFingerprint. Hash first_hash = HashFingerprint(fingerprint); Hash cur_hash = first_hash; while (true) { Fingerprint cur_fingerprint = FingerprintAt(cur_hash); if (cur_fingerprint == null_fingerprint_) return false; // End of probe sequence found. if (cur_fingerprint == fingerprint) return true; // Found a match. // This spot was taken, but not by the item we're looking for, search in // the next position. cur_hash++; if (cur_hash == table_length_) cur_hash = 0; if (cur_hash == first_hash) { // Wrapped around and didn't find an empty space, this means we're in an // infinite loop because AddFingerprint didn't do its job resizing. NOTREACHED(); return false; } } } // Uses the top 64 bits of the MD5 sum of the canonical URL as the fingerprint, // this is as random as any other subset of the MD5SUM. // // FIXME: this uses the MD5SUM of the 16-bit character version. For systems // where wchar_t is not 16 bits (Linux uses 32 bits, I think), this will not be // compatable. We should define explicitly what should happen here across // platforms, and convert if necessary (probably to UTF-16). // static VisitedLinkCommon::Fingerprint VisitedLinkCommon::ComputeURLFingerprint( const char* canonical_url, size_t url_len, const uint8 salt[LINK_SALT_LENGTH]) { DCHECK(url_len > 0) << "Canonical URLs should not be empty"; MD5Context ctx; MD5Init(&ctx); MD5Update(&ctx, salt, sizeof(salt)); MD5Update(&ctx, canonical_url, url_len * sizeof(char)); MD5Digest digest; MD5Final(&digest, &ctx); // This is the same as "return *(Fingerprint*)&digest.a;" but if we do that // direct cast the alignment could be wrong, and we can't access a 64-bit int // on arbitrary alignment on some processors. This reinterpret_casts it // down to a char array of the same size as fingerprint, and then does the // bit cast, which amounts to a memcpy. This does not handle endian issues. return bit_cast<Fingerprint, uint8[8]>( *reinterpret_cast<uint8(*)[8]>(&digest.a)); }
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/visitedlink_common.h" #include <string.h> // for memset() #include "base/logging.h" #include "base/md5.h" #include "googleurl/src/gurl.h" const VisitedLinkCommon::Fingerprint VisitedLinkCommon::null_fingerprint_ = 0; const VisitedLinkCommon::Hash VisitedLinkCommon::null_hash_ = -1; VisitedLinkCommon::VisitedLinkCommon() : hash_table_(NULL), table_length_(0) { memset(salt_, 0, sizeof(salt_)); } VisitedLinkCommon::~VisitedLinkCommon() { } // FIXME: this uses linear probing, it should be replaced with quadratic // probing or something better. See VisitedLinkMaster::AddFingerprint bool VisitedLinkCommon::IsVisited(const char* canonical_url, size_t url_len) const { if (url_len == 0) return false; if (!hash_table_ || table_length_ == 0) return false; return IsVisited(ComputeURLFingerprint(canonical_url, url_len)); } bool VisitedLinkCommon::IsVisited(const GURL& url) const { return IsVisited(url.spec().data(), url.spec().size()); } bool VisitedLinkCommon::IsVisited(Fingerprint fingerprint) const { // Go through the table until we find the item or an empty spot (meaning it // wasn't found). This loop will terminate as long as the table isn't full, // which should be enforced by AddFingerprint. Hash first_hash = HashFingerprint(fingerprint); Hash cur_hash = first_hash; while (true) { Fingerprint cur_fingerprint = FingerprintAt(cur_hash); if (cur_fingerprint == null_fingerprint_) return false; // End of probe sequence found. if (cur_fingerprint == fingerprint) return true; // Found a match. // This spot was taken, but not by the item we're looking for, search in // the next position. cur_hash++; if (cur_hash == table_length_) cur_hash = 0; if (cur_hash == first_hash) { // Wrapped around and didn't find an empty space, this means we're in an // infinite loop because AddFingerprint didn't do its job resizing. NOTREACHED(); return false; } } } // Uses the top 64 bits of the MD5 sum of the canonical URL as the fingerprint, // this is as random as any other subset of the MD5SUM. // // FIXME: this uses the MD5SUM of the 16-bit character version. For systems // where wchar_t is not 16 bits (Linux uses 32 bits, I think), this will not be // compatable. We should define explicitly what should happen here across // platforms, and convert if necessary (probably to UTF-16). // static VisitedLinkCommon::Fingerprint VisitedLinkCommon::ComputeURLFingerprint( const char* canonical_url, size_t url_len, const uint8 salt[LINK_SALT_LENGTH]) { DCHECK(url_len > 0) << "Canonical URLs should not be empty"; MD5Context ctx; MD5Init(&ctx); MD5Update(&ctx, salt, sizeof(salt)); MD5Update(&ctx, canonical_url, url_len * sizeof(char)); MD5Digest digest; MD5Final(&digest, &ctx); // This is the same as "return *(Fingerprint*)&digest.a;" but if we do that // direct cast the alignment could be wrong, and we can't access a 64-bit int // on arbitrary alignment on some processors. This reinterpret_casts it // down to a char array of the same size as fingerprint, and then does the // bit cast, which amounts to a memcpy. This does not handle endian issues. return bit_cast<Fingerprint, uint8[8]>( *reinterpret_cast<uint8(*)[8]>(&digest.a)); }
Initialize salt_ to zero in VisitedLinkCommon.
Initialize salt_ to zero in VisitedLinkCommon. Previously, this memory would remain uninitialized until the renderer received a VisitedLink_NewTable message. This was causing valgrind errors in PhishingDOMFeatureExtractorTest when WebKit computed URL fingerprints, since the test never sends a VisitedLink_NewTable message. BUG=none TEST=no valgrind errors in PhishingDOMFeatureExtractorTest Review URL: http://codereview.chromium.org/2873081 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@54376 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
gavinp/chromium,adobe/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,ropik/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium
9401f97b821857e91d4eeada8e7ab38663f0c23d
python/dune/gdt/spaces/interface.hh
python/dune/gdt/spaces/interface.hh
// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2020) #ifndef PYTHON_DUNE_GDT_SPACES_INTERFACE_HH #define PYTHON_DUNE_GDT_SPACES_INTERFACE_HH #include <dune/pybindxi/pybind11.h> #include <dune/pybindxi/stl.h> #include <dune/gdt/spaces/interface.hh> #include <python/dune/xt/common/configuration.hh> #include <python/dune/xt/common/fvector.hh> #include <python/dune/xt/grid/grids.bindings.hh> namespace Dune { namespace GDT { namespace bindings { template <class GV, size_t r = 1, size_t rC = 1, class R = double> class SpaceInterface { using G = typename GV::Grid; static const size_t d = G::dimension; public: using type = GDT::SpaceInterface<GV, r, rC, R>; using bound_type = pybind11::class_<type>; static bound_type bind(pybind11::module& m, const std::string& class_id = "space_interface", const std::string& grid_id = XT::Grid::bindings::grid_name<G>::value(), const std::string& layer_id = "") { namespace py = pybind11; using namespace pybind11::literals; std::string class_name = class_id + "_" + grid_id; if (!layer_id.empty()) class_name += "_" + layer_id; if (r > 1) class_name += "_to_" + XT::Common::to_string(r) + "d"; if (rC > 1) class_name += "x" + XT::Common::to_string(rC) + "d"; if (!std::is_same<R, double>::value) class_name += "_" + XT::Common::Typename<R>::value(/*fail_wo_typeid=*/true); const auto ClassName = XT::Common::to_camel_case(class_name); bound_type c(m, ClassName.c_str(), ClassName.c_str()); c.def_property_readonly("dimDomain", [](type&) { return d; }); c.def_property_readonly("type", [](type& self) { std::stringstream ss; ss << self.type(); return ss.str(); }); c.def_property_readonly("num_DoFs", [](type& self) { return self.mapper().size(); }); c.def_property_readonly("min_polorder", [](type& self) { return self.min_polorder(); }); c.def_property_readonly("max_polorder", [](type& self) { return self.max_polorder(); }); c.def_property_readonly("is_lagrangian", [](type& self) { return self.is_lagrangian(); }); c.def( "continuous", [](type& self, const int diff_order) { return self.continuous(diff_order); }, "diff_order"_a = 0); c.def("pre_adapt", [](type& self) { self.pre_adapt(); }); c.def("adapt", [](type& self) { self.adapt(); }); c.def("post_adapt", [](type& self) { return self.post_adapt(); }); c.def("__repr__", [](const type& self) { std::stringstream ss; ss << self; return ss.str(); }); return c; } // ... bind(...) }; // class SpaceInterface } // namespace bindings } // namespace GDT } // namespace Dune #endif // PYTHON_DUNE_GDT_SPACES_INTERFACE_HH
// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2020) #ifndef PYTHON_DUNE_GDT_SPACES_INTERFACE_HH #define PYTHON_DUNE_GDT_SPACES_INTERFACE_HH #include <dune/pybindxi/pybind11.h> #include <dune/pybindxi/stl.h> #include <dune/gdt/spaces/interface.hh> #include <python/dune/xt/common/configuration.hh> #include <python/dune/xt/common/fvector.hh> #include <python/dune/xt/grid/grids.bindings.hh> namespace Dune { namespace GDT { namespace bindings { template <class GV, size_t r = 1, size_t rC = 1, class R = double> class SpaceInterface { using G = typename GV::Grid; static const size_t d = G::dimension; public: using type = GDT::SpaceInterface<GV, r, rC, R>; using bound_type = pybind11::class_<type>; static bound_type bind(pybind11::module& m, const std::string& class_id = "space_interface", const std::string& grid_id = XT::Grid::bindings::grid_name<G>::value(), const std::string& layer_id = "") { namespace py = pybind11; using namespace pybind11::literals; std::string class_name = class_id + "_" + grid_id; if (!layer_id.empty()) class_name += "_" + layer_id; if (r > 1) class_name += "_to_" + XT::Common::to_string(r) + "d"; if (rC > 1) class_name += "x" + XT::Common::to_string(rC) + "d"; if (!std::is_same<R, double>::value) class_name += "_" + XT::Common::Typename<R>::value(/*fail_wo_typeid=*/true); const auto ClassName = XT::Common::to_camel_case(class_name); bound_type c(m, ClassName.c_str(), ClassName.c_str()); c.def_property_readonly("dimDomain", [](type&) { return d; }); c.def_property_readonly("type", [](type& self) { std::stringstream ss; ss << self.type(); return ss.str(); }); c.def_property_readonly("num_DoFs", [](type& self) { return self.mapper().size(); }); c.def_property_readonly("min_polorder", [](type& self) { return self.min_polorder(); }); c.def_property_readonly("max_polorder", [](type& self) { return self.max_polorder(); }); c.def_property_readonly("is_lagrangian", [](type& self) { return self.is_lagrangian(); }); c.def( "continuous", [](type& self, const int diff_order) { return self.continuous(diff_order); }, "diff_order"_a = 0); c.def("pre_adapt", [](type& self) { self.pre_adapt(); }); c.def("adapt", [](type& self) { self.adapt(); }); c.def("post_adapt", [](type& self) { return self.post_adapt(); }); c.def("interpolation_points", [](type& self) { DUNE_THROW_IF(!self.is_lagrangian(), XT::Common::Exceptions::wrong_input_given, ""); const auto& global_basis = self.basis(); auto basis = global_basis.localize(); DynamicVector<size_t> global_DoF_indices(self.mapper().max_local_size()); auto points = std::make_unique<XT::LA::CommonDenseMatrix<double>>(self.mapper().size(), size_t(d), 0.); for (auto&& element : elements(self.grid_view())) { basis->bind(element); self.mapper().global_indices(element, global_DoF_indices); auto local_lagrange_points = basis->finite_element().lagrange_points(); for (size_t ii = 0; ii < basis->size(); ++ii) { auto global_point = element.geometry().global(local_lagrange_points[ii]); for (size_t jj = 0; jj < size_t(d); ++jj) points->set_entry(global_DoF_indices[ii], jj, global_point[jj]); } } return std::move(points); }, py::call_guard<py::gil_scoped_release>()); c.def("__repr__", [](const type& self) { std::stringstream ss; ss << self; return ss.str(); }); return c; } // ... bind(...) }; // class SpaceInterface } // namespace bindings } // namespace GDT } // namespace Dune #endif // PYTHON_DUNE_GDT_SPACES_INTERFACE_HH
add interpolation_points()
[python|spaces] add interpolation_points()
C++
bsd-2-clause
pymor/dune-gdt
c72b0f3d9772bee9457153aee533530299a49286
python/generate-python-bindings.cpp
python/generate-python-bindings.cpp
/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: python/generate-python-bindings.cpp * * Copyright 2016 Patrik Huber * * 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 "eos/core/LandmarkMapper.hpp" #include "eos/morphablemodel/PcaModel.hpp" #include "eos/morphablemodel/MorphableModel.hpp" #include "eos/morphablemodel/Blendshape.hpp" #include "eos/morphablemodel/EdgeTopology.hpp" #include "eos/fitting/contour_correspondence.hpp" #include "eos/fitting/fitting.hpp" #include "eos/fitting/orthographic_camera_estimation_linear.hpp" #include "eos/fitting/RenderingParameters.hpp" #include "eos/render/Mesh.hpp" #include "opencv2/core/core.hpp" #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include "pybind11_glm.hpp" #include "pybind11_opencv.hpp" #include <iostream> #include <stdexcept> #include <string> #include <algorithm> #include <cassert> namespace py = pybind11; using namespace eos; /** * Generate python bindings for the eos library using pybind11. */ PYBIND11_PLUGIN(eos) { py::module eos_module("eos", "Python bindings for the eos 3D Morphable Face Model fitting library.\n\nFor an overview of the functionality, see the documentation of the submodules. For the full documentation, see the C++ doxygen documentation."); /** * Bindings for the eos::core namespace: * - LandmarkMapper */ py::module core_module = eos_module.def_submodule("core", "Essential functions and classes to work with 3D face models and landmarks."); py::class_<core::LandmarkMapper>(core_module, "LandmarkMapper", "Represents a mapping from one kind of landmarks to a different format(e.g.model vertices).") .def(py::init<>(), "Constructs a new landmark mapper that performs an identity mapping, that is, its output is the same as the input.") .def("__init__", [](core::LandmarkMapper& instance, std::string filename) { // wrap the fs::path c'tor with std::string new (&instance) core::LandmarkMapper(filename); }, "Constructs a new landmark mapper from a file containing mappings from one set of landmark identifiers to another.") // We can't expose the convert member function yet - need std::optional (or some trick with self/this and a lambda) ; /** * Bindings for the eos::morphablemodel namespace: * - PcaModel * - MorphableModel * - load_model() */ py::module morphablemodel_module = eos_module.def_submodule("morphablemodel", "Functionality to represent a Morphable Model, its PCA models, and functions to load models and blendshapes."); py::class_<morphablemodel::PcaModel>(morphablemodel_module, "PcaModel", "Class representing a PcaModel with a mean, eigenvectors and eigenvalues, as well as a list of triangles to build a mesh.") .def("get_num_principal_components", &morphablemodel::PcaModel::get_num_principal_components, "Returns the number of principal components in the model.") .def("get_data_dimension", &morphablemodel::PcaModel::get_data_dimension, "Returns the dimension of the data, i.e. the number of shape dimensions.") .def("get_triangle_list", &morphablemodel::PcaModel::get_triangle_list, "Returns a list of triangles on how to assemble the vertices into a mesh.") .def("get_mean", &morphablemodel::PcaModel::get_mean, "Returns the mean of the model.") .def("get_mean_at_point", &morphablemodel::PcaModel::get_mean_at_point, "Return the value of the mean at a given vertex index.", py::arg("vertex_index")) .def("draw_sample", (cv::Mat (morphablemodel::PcaModel::*)(std::vector<float>) const)&morphablemodel::PcaModel::draw_sample, "Returns a sample from the model with the given PCA coefficients. The given coefficients should follow a standard normal distribution, i.e. not be scaled with their eigenvalues/variances.", py::arg("coefficients")) ; py::class_<morphablemodel::MorphableModel>(morphablemodel_module, "MorphableModel", "A class representing a 3D Morphable Model, consisting of a shape- and colour (albedo) PCA model, as well as texture (uv) coordinates.") .def("get_shape_model", [](const morphablemodel::MorphableModel& m) { return m.get_shape_model(); }, "Returns the PCA shape model of this Morphable Model.") // Not sure if that'll really be const in Python? I think Python does a copy each time this gets called? .def("get_color_model", [](const morphablemodel::MorphableModel& m) { return m.get_color_model(); }, "Returns the PCA colour (albedo) model of this Morphable Model.") ; morphablemodel_module.def("load_model", &morphablemodel::load_model, "Load a Morphable Model from a cereal::BinaryInputArchive (.bin) from the harddisk."); /** * - Blendshape * - load_blendshapes() */ py::class_<morphablemodel::Blendshape>(morphablemodel_module, "Blendshape", "A class representing a 3D blendshape.") .def_readwrite("name", &morphablemodel::Blendshape::name, "Name of the blendshape.") .def_readwrite("deformation", &morphablemodel::Blendshape::deformation, "A 3m x 1 col-vector (xyzxyz...)', where m is the number of model-vertices. Has the same format as PcaModel::mean.") ; morphablemodel_module.def("load_blendshapes", &morphablemodel::load_blendshapes, "Load a file with blendshapes from a cereal::BinaryInputArchive (.bin) from the harddisk."); /** * - EdgeTopology * - load_edge_topology() */ py::class_<morphablemodel::EdgeTopology>(morphablemodel_module, "EdgeTopology", "A struct containing a 3D shape model's edge topology."); morphablemodel_module.def("load_edge_topology", &morphablemodel::load_edge_topology, "Load a 3DMM edge topology file from a json file."); /** * Bindings for the eos::render namespace: * (Note: Defining Mesh before using it below in fitting::fit_shape_and_pose) * - Mesh */ py::module render_module = eos_module.def_submodule("render", "3D mesh and texture extraction functionality."); py::class_<render::Mesh>(render_module, "Mesh", "This class represents a 3D mesh consisting of vertices, vertex colour information and texture coordinates.") .def_readwrite("vertices", &render::Mesh::vertices, "Vertices") .def_readwrite("tvi", &render::Mesh::tvi, "Triangle vertex indices") .def_readwrite("colors", &render::Mesh::colors, "Colour data") .def_readwrite("tci", &render::Mesh::tci, "Triangle colour indices (usually the same as tvi)") .def_readwrite("texcoords", &render::Mesh::texcoords, "Texture coordinates") ; /** * Bindings for the eos::fitting namespace: * - ScaledOrthoProjectionParameters * - RenderingParameters * - estimate_orthographic_projection_linear() * - ContourLandmarks * - ModelContour * - fit_shape_and_pose() */ py::module fitting_module = eos_module.def_submodule("fitting", "Pose and shape fitting of a 3D Morphable Model."); py::class_<fitting::ScaledOrthoProjectionParameters>(fitting_module, "ScaledOrthoProjectionParameters", "Parameters of an estimated scaled orthographic projection.") .def_readwrite("R", &fitting::ScaledOrthoProjectionParameters::R, "Rotation matrix") .def_readwrite("s", &fitting::ScaledOrthoProjectionParameters::s, "Scale") .def_readwrite("tx", &fitting::ScaledOrthoProjectionParameters::tx, "x translation") .def_readwrite("ty", &fitting::ScaledOrthoProjectionParameters::ty, "y translation") ; py::class_<fitting::RenderingParameters>(fitting_module, "RenderingParameters", "Represents a set of estimated model parameters (rotation, translation) and camera parameters (viewing frustum).") .def(py::init<fitting::ScaledOrthoProjectionParameters, int, int>(), "Create a RenderingParameters object from an instance of estimated ScaledOrthoProjectionParameters.") .def("get_rotation", [](const fitting::RenderingParameters& p) { return glm::vec4(p.get_rotation().x, p.get_rotation().y, p.get_rotation().z, p.get_rotation().w); }, "Returns the rotation quaternion [x y z w].") .def("get_rotation_euler_angles", [](const fitting::RenderingParameters& p) { return glm::eulerAngles(p.get_rotation()); }, "Returns the rotation's Euler angles (in radians) as [pitch, yaw, roll].") .def("get_modelview", &fitting::RenderingParameters::get_modelview, "Returns the 4x4 model-view matrix.") .def("get_projection", &fitting::RenderingParameters::get_projection, "Returns the 4x4 projection matrix.") ; fitting_module.def("estimate_orthographic_projection_linear", [](std::vector<glm::vec2> image_points, std::vector<glm::vec4> model_points, bool is_viewport_upsidedown, int viewport_height) { // We take glm vec's (transparent conversion in python) and convert them to OpenCV vec's for now: std::vector<cv::Vec2f> image_points_cv; std::for_each(std::begin(image_points), std::end(image_points), [&image_points_cv](auto&& p) { image_points_cv.push_back({p.x, p.y}); }); std::vector<cv::Vec4f> model_points_cv; std::for_each(std::begin(model_points), std::end(model_points), [&model_points_cv](auto&& p) { model_points_cv.push_back({ p.x, p.y, p.z, p.w }); }); const boost::optional<int> viewport_height_opt = viewport_height == 0 ? boost::none : boost::optional<int>(viewport_height); return fitting::estimate_orthographic_projection_linear(image_points_cv, model_points_cv, is_viewport_upsidedown, viewport_height_opt); }, "This algorithm estimates the parameters of a scaled orthographic projection, given a set of corresponding 2D-3D points.", py::arg("image_points"), py::arg("model_points"), py::arg("is_viewport_upsidedown"), py::arg("viewport_height") = 0) ; py::class_<fitting::ContourLandmarks>(fitting_module, "ContourLandmarks", "Defines which 2D landmarks comprise the right and left face contour.") .def_static("load", &fitting::ContourLandmarks::load, "Helper method to load contour landmarks from a text file with landmark mappings, like ibug2did.txt.") ; py::class_<fitting::ModelContour>(fitting_module, "ModelContour", "Definition of the vertex indices that define the right and left model contour.") .def_static("load", &fitting::ModelContour::load, "Helper method to load a ModelContour from a json file from the hard drive.") ; fitting_module.def("fit_shape_and_pose", [](const morphablemodel::MorphableModel& morphable_model, const std::vector<morphablemodel::Blendshape>& blendshapes, const std::vector<glm::vec2>& landmarks, const std::vector<std::string>& landmark_ids, const core::LandmarkMapper& landmark_mapper, int image_width, int image_height, const morphablemodel::EdgeTopology& edge_topology, const fitting::ContourLandmarks& contour_landmarks, const fitting::ModelContour& model_contour, int num_iterations, int num_shape_coefficients_to_fit, float lambda) { assert(landmarks.size() == landmark_ids.size()); std::vector<float> pca_coeffs; std::vector<float> blendshape_coeffs; std::vector<cv::Vec2f> fitted_image_points; // We can change this to std::optional as soon as we switch to VS2017 and pybind supports std::optional const boost::optional<int> num_shape_coefficients_opt = num_shape_coefficients_to_fit == -1 ? boost::none : boost::optional<int>(num_shape_coefficients_to_fit); core::LandmarkCollection<cv::Vec2f> landmark_collection; for (int i = 0; i < landmarks.size(); ++i) { landmark_collection.push_back(core::Landmark<cv::Vec2f>{ landmark_ids[i], cv::Vec2f(landmarks[i].x, landmarks[i].y) }); } auto result = fitting::fit_shape_and_pose(morphable_model, blendshapes, landmark_collection, landmark_mapper, image_width, image_height, edge_topology, contour_landmarks, model_contour, num_iterations, num_shape_coefficients_opt, lambda, boost::none, pca_coeffs, blendshape_coeffs, fitted_image_points); return std::make_tuple(result.first, result.second, pca_coeffs, blendshape_coeffs); }, "Fit the pose (camera), shape model, and expression blendshapes to landmarks, in an iterative way. Returns a tuple (mesh, rendering_parameters, shape_coefficients, blendshape_coefficients).", py::arg("morphable_model"), py::arg("blendshapes"), py::arg("landmarks"), py::arg("landmark_ids"), py::arg("landmark_mapper"), py::arg("image_width"), py::arg("image_height"), py::arg("edge_topology"), py::arg("contour_landmarks"), py::arg("model_contour"), py::arg("num_iterations") = 5, py::arg("num_shape_coefficients_to_fit") = -1, py::arg("lambda") = 30.0f) ; return eos_module.ptr(); };
/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: python/generate-python-bindings.cpp * * Copyright 2016 Patrik Huber * * 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 "eos/core/LandmarkMapper.hpp" #include "eos/morphablemodel/PcaModel.hpp" #include "eos/morphablemodel/MorphableModel.hpp" #include "eos/morphablemodel/Blendshape.hpp" #include "eos/morphablemodel/EdgeTopology.hpp" #include "eos/fitting/contour_correspondence.hpp" #include "eos/fitting/fitting.hpp" #include "eos/fitting/orthographic_camera_estimation_linear.hpp" #include "eos/fitting/RenderingParameters.hpp" #include "eos/render/Mesh.hpp" #include "opencv2/core/core.hpp" #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include "pybind11_glm.hpp" #include "pybind11_opencv.hpp" #include <iostream> #include <stdexcept> #include <string> #include <algorithm> #include <cassert> namespace py = pybind11; using namespace eos; /** * Generate python bindings for the eos library using pybind11. */ PYBIND11_PLUGIN(eos) { py::module eos_module("eos", "Python bindings for the eos 3D Morphable Face Model fitting library.\n\nFor an overview of the functionality, see the documentation of the submodules. For the full documentation, see the C++ doxygen documentation."); /** * Bindings for the eos::core namespace: * - LandmarkMapper */ py::module core_module = eos_module.def_submodule("core", "Essential functions and classes to work with 3D face models and landmarks."); py::class_<core::LandmarkMapper>(core_module, "LandmarkMapper", "Represents a mapping from one kind of landmarks to a different format(e.g.model vertices).") .def(py::init<>(), "Constructs a new landmark mapper that performs an identity mapping, that is, its output is the same as the input.") .def("__init__", [](core::LandmarkMapper& instance, std::string filename) { // wrap the fs::path c'tor with std::string new (&instance) core::LandmarkMapper(filename); }, "Constructs a new landmark mapper from a file containing mappings from one set of landmark identifiers to another.") // We can't expose the convert member function yet - need std::optional (or some trick with self/this and a lambda) ; /** * Bindings for the eos::morphablemodel namespace: * - PcaModel * - MorphableModel * - load_model() */ py::module morphablemodel_module = eos_module.def_submodule("morphablemodel", "Functionality to represent a Morphable Model, its PCA models, and functions to load models and blendshapes."); py::class_<morphablemodel::PcaModel>(morphablemodel_module, "PcaModel", "Class representing a PcaModel with a mean, eigenvectors and eigenvalues, as well as a list of triangles to build a mesh.") .def("get_num_principal_components", &morphablemodel::PcaModel::get_num_principal_components, "Returns the number of principal components in the model.") .def("get_data_dimension", &morphablemodel::PcaModel::get_data_dimension, "Returns the dimension of the data, i.e. the number of shape dimensions.") .def("get_triangle_list", &morphablemodel::PcaModel::get_triangle_list, "Returns a list of triangles on how to assemble the vertices into a mesh.") .def("get_mean", &morphablemodel::PcaModel::get_mean, "Returns the mean of the model.") .def("get_mean_at_point", &morphablemodel::PcaModel::get_mean_at_point, "Return the value of the mean at a given vertex index.", py::arg("vertex_index")) .def("draw_sample", (cv::Mat (morphablemodel::PcaModel::*)(std::vector<float>) const)&morphablemodel::PcaModel::draw_sample, "Returns a sample from the model with the given PCA coefficients. The given coefficients should follow a standard normal distribution, i.e. not be scaled with their eigenvalues/variances.", py::arg("coefficients")) ; py::class_<morphablemodel::MorphableModel>(morphablemodel_module, "MorphableModel", "A class representing a 3D Morphable Model, consisting of a shape- and colour (albedo) PCA model, as well as texture (uv) coordinates.") .def("get_shape_model", [](const morphablemodel::MorphableModel& m) { return m.get_shape_model(); }, "Returns the PCA shape model of this Morphable Model.") // Not sure if that'll really be const in Python? I think Python does a copy each time this gets called? .def("get_color_model", [](const morphablemodel::MorphableModel& m) { return m.get_color_model(); }, "Returns the PCA colour (albedo) model of this Morphable Model.") ; morphablemodel_module.def("load_model", &morphablemodel::load_model, "Load a Morphable Model from a cereal::BinaryInputArchive (.bin) from the harddisk."); /** * - Blendshape * - load_blendshapes() */ py::class_<morphablemodel::Blendshape>(morphablemodel_module, "Blendshape", "A class representing a 3D blendshape.") .def_readwrite("name", &morphablemodel::Blendshape::name, "Name of the blendshape.") .def_readwrite("deformation", &morphablemodel::Blendshape::deformation, "A 3m x 1 col-vector (xyzxyz...)', where m is the number of model-vertices. Has the same format as PcaModel::mean.") ; morphablemodel_module.def("load_blendshapes", &morphablemodel::load_blendshapes, "Load a file with blendshapes from a cereal::BinaryInputArchive (.bin) from the harddisk."); /** * - EdgeTopology * - load_edge_topology() */ py::class_<morphablemodel::EdgeTopology>(morphablemodel_module, "EdgeTopology", "A struct containing a 3D shape model's edge topology."); morphablemodel_module.def("load_edge_topology", &morphablemodel::load_edge_topology, "Load a 3DMM edge topology file from a json file."); /** * Bindings for the eos::render namespace: * (Note: Defining Mesh before using it below in fitting::fit_shape_and_pose) * - Mesh */ py::module render_module = eos_module.def_submodule("render", "3D mesh and texture extraction functionality."); py::class_<render::Mesh>(render_module, "Mesh", "This class represents a 3D mesh consisting of vertices, vertex colour information and texture coordinates.") .def_readwrite("vertices", &render::Mesh::vertices, "Vertices") .def_readwrite("tvi", &render::Mesh::tvi, "Triangle vertex indices") .def_readwrite("colors", &render::Mesh::colors, "Colour data") .def_readwrite("tci", &render::Mesh::tci, "Triangle colour indices (usually the same as tvi)") .def_readwrite("texcoords", &render::Mesh::texcoords, "Texture coordinates") ; /** * Bindings for the eos::fitting namespace: * - ScaledOrthoProjectionParameters * - RenderingParameters * - estimate_orthographic_projection_linear() * - ContourLandmarks * - ModelContour * - fit_shape_and_pose() */ py::module fitting_module = eos_module.def_submodule("fitting", "Pose and shape fitting of a 3D Morphable Model."); py::class_<fitting::ScaledOrthoProjectionParameters>(fitting_module, "ScaledOrthoProjectionParameters", "Parameters of an estimated scaled orthographic projection.") .def_readwrite("R", &fitting::ScaledOrthoProjectionParameters::R, "Rotation matrix") .def_readwrite("s", &fitting::ScaledOrthoProjectionParameters::s, "Scale") .def_readwrite("tx", &fitting::ScaledOrthoProjectionParameters::tx, "x translation") .def_readwrite("ty", &fitting::ScaledOrthoProjectionParameters::ty, "y translation") ; py::class_<fitting::RenderingParameters>(fitting_module, "RenderingParameters", "Represents a set of estimated model parameters (rotation, translation) and camera parameters (viewing frustum).") .def(py::init<fitting::ScaledOrthoProjectionParameters, int, int>(), "Create a RenderingParameters object from an instance of estimated ScaledOrthoProjectionParameters.") .def("get_rotation", [](const fitting::RenderingParameters& p) { return glm::vec4(p.get_rotation().x, p.get_rotation().y, p.get_rotation().z, p.get_rotation().w); }, "Returns the rotation quaternion [x y z w].") .def("get_rotation_euler_angles", [](const fitting::RenderingParameters& p) { return glm::eulerAngles(p.get_rotation()); }, "Returns the rotation's Euler angles (in radians) as [pitch, yaw, roll].") .def("get_modelview", &fitting::RenderingParameters::get_modelview, "Returns the 4x4 model-view matrix.") .def("get_projection", &fitting::RenderingParameters::get_projection, "Returns the 4x4 projection matrix.") ; fitting_module.def("estimate_orthographic_projection_linear", [](std::vector<cv::Vec2f> image_points, std::vector<cv::Vec4f> model_points, bool is_viewport_upsidedown, int viewport_height) { const boost::optional<int> viewport_height_opt = viewport_height == 0 ? boost::none : boost::optional<int>(viewport_height); return fitting::estimate_orthographic_projection_linear(image_points, model_points, is_viewport_upsidedown, viewport_height_opt); }, "This algorithm estimates the parameters of a scaled orthographic projection, given a set of corresponding 2D-3D points.", py::arg("image_points"), py::arg("model_points"), py::arg("is_viewport_upsidedown"), py::arg("viewport_height") = 0) ; py::class_<fitting::ContourLandmarks>(fitting_module, "ContourLandmarks", "Defines which 2D landmarks comprise the right and left face contour.") .def_static("load", &fitting::ContourLandmarks::load, "Helper method to load contour landmarks from a text file with landmark mappings, like ibug2did.txt.") ; py::class_<fitting::ModelContour>(fitting_module, "ModelContour", "Definition of the vertex indices that define the right and left model contour.") .def_static("load", &fitting::ModelContour::load, "Helper method to load a ModelContour from a json file from the hard drive.") ; fitting_module.def("fit_shape_and_pose", [](const morphablemodel::MorphableModel& morphable_model, const std::vector<morphablemodel::Blendshape>& blendshapes, const std::vector<glm::vec2>& landmarks, const std::vector<std::string>& landmark_ids, const core::LandmarkMapper& landmark_mapper, int image_width, int image_height, const morphablemodel::EdgeTopology& edge_topology, const fitting::ContourLandmarks& contour_landmarks, const fitting::ModelContour& model_contour, int num_iterations, int num_shape_coefficients_to_fit, float lambda) { assert(landmarks.size() == landmark_ids.size()); std::vector<float> pca_coeffs; std::vector<float> blendshape_coeffs; std::vector<cv::Vec2f> fitted_image_points; // We can change this to std::optional as soon as we switch to VS2017 and pybind supports std::optional const boost::optional<int> num_shape_coefficients_opt = num_shape_coefficients_to_fit == -1 ? boost::none : boost::optional<int>(num_shape_coefficients_to_fit); core::LandmarkCollection<cv::Vec2f> landmark_collection; for (int i = 0; i < landmarks.size(); ++i) { landmark_collection.push_back(core::Landmark<cv::Vec2f>{ landmark_ids[i], cv::Vec2f(landmarks[i].x, landmarks[i].y) }); } auto result = fitting::fit_shape_and_pose(morphable_model, blendshapes, landmark_collection, landmark_mapper, image_width, image_height, edge_topology, contour_landmarks, model_contour, num_iterations, num_shape_coefficients_opt, lambda, boost::none, pca_coeffs, blendshape_coeffs, fitted_image_points); return std::make_tuple(result.first, result.second, pca_coeffs, blendshape_coeffs); }, "Fit the pose (camera), shape model, and expression blendshapes to landmarks, in an iterative way. Returns a tuple (mesh, rendering_parameters, shape_coefficients, blendshape_coefficients).", py::arg("morphable_model"), py::arg("blendshapes"), py::arg("landmarks"), py::arg("landmark_ids"), py::arg("landmark_mapper"), py::arg("image_width"), py::arg("image_height"), py::arg("edge_topology"), py::arg("contour_landmarks"), py::arg("model_contour"), py::arg("num_iterations") = 5, py::arg("num_shape_coefficients_to_fit") = -1, py::arg("lambda") = 30.0f) ; return eos_module.ptr(); };
Remove conversion to glm in estimate_orthographic_projection_linear() binding
Remove conversion to glm in estimate_orthographic_projection_linear() binding
C++
apache-2.0
patrikhuber/eos,patrikhuber/eos,icyrizard/eos,patrikhuber/eos,icyrizard/eos,icyrizard/eos
9943576fe795678f9d58e48bc93ed9a3284e8993
rclcpp/include/rclcpp/parameter.hpp
rclcpp/include/rclcpp/parameter.hpp
// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RCLCPP_RCLCPP_PARAMETER_HPP_ #define RCLCPP_RCLCPP_PARAMETER_HPP_ #include <string> #include <rmw/rmw.h> #include <rclcpp/executors.hpp> #include <rclcpp/macros.hpp> #include <rclcpp/node.hpp> #include <rcl_interfaces/GetParameters.h> #include <rcl_interfaces/GetParameterTypes.h> #include <rcl_interfaces/Parameter.h> #include <rcl_interfaces/ParameterDescriptor.h> #include <rcl_interfaces/ParameterType.h> #include <rcl_interfaces/SetParameters.h> #include <rcl_interfaces/SetParametersAtomically.h> #include <rcl_interfaces/ListParameters.h> #include <rcl_interfaces/DescribeParameters.h> namespace rclcpp { namespace parameter { enum ParameterType { PARAMETER_NOT_SET=rcl_interfaces::ParameterType::PARAMETER_NOT_SET, PARAMETER_BOOL=rcl_interfaces::ParameterType::PARAMETER_BOOL, PARAMETER_INTEGER=rcl_interfaces::ParameterType::PARAMETER_INTEGER, PARAMETER_DOUBLE=rcl_interfaces::ParameterType::PARAMETER_DOUBLE, PARAMETER_STRING=rcl_interfaces::ParameterType::PARAMETER_STRING, PARAMETER_BYTES=rcl_interfaces::ParameterType::PARAMETER_BYTES, }; // Structure to store an arbitrary parameter with templated get/set methods class ParameterVariant { public: ParameterVariant() : name_("") { value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_NOT_SET; } explicit ParameterVariant(const std::string & name, const bool bool_value) : name_(name) { value_.bool_value = bool_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_BOOL; } explicit ParameterVariant(const std::string & name, const int int_value) : name_(name) { value_.integer_value = int_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_INTEGER; } explicit ParameterVariant(const std::string & name, const int64_t int_value) : name_(name) { value_.integer_value = int_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_INTEGER; } explicit ParameterVariant(const std::string & name, const float double_value) : name_(name) { value_.double_value = double_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_DOUBLE; } explicit ParameterVariant(const std::string & name, const double double_value) : name_(name) { value_.double_value = double_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_DOUBLE; } explicit ParameterVariant(const std::string & name, const std::string & string_value) : name_(name) { value_.string_value = string_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_STRING; } explicit ParameterVariant(const std::string & name, const std::vector<int8_t> & bytes_value) : name_(name) { value_.bytes_value = bytes_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_BYTES; } /* Templated getter */ template<typename T> T get_value() const; inline ParameterType get_type() const {return static_cast<ParameterType>(value_.parameter_type); } inline std::string get_name() const & {return name_; } inline rcl_interfaces::ParameterValue get_parameter_value() const { return value_; } private: std::string name_; rcl_interfaces::ParameterValue value_; }; template<> inline int64_t ParameterVariant::get_value() const { if (value_.parameter_type != rcl_interfaces::ParameterType::PARAMETER_INTEGER) { // TODO: use custom exception throw std::runtime_error("Invalid type"); } return value_.integer_value; } template<> inline double ParameterVariant::get_value() const { if (value_.parameter_type != rcl_interfaces::ParameterType::PARAMETER_DOUBLE) { // TODO: use custom exception throw std::runtime_error("Invalid type"); } return value_.double_value; } template<> inline std::string ParameterVariant::get_value() const { if (value_.parameter_type != rcl_interfaces::ParameterType::PARAMETER_STRING) { // TODO: use custom exception throw std::runtime_error("Invalid type"); } return value_.string_value; } template<> inline bool ParameterVariant::get_value() const { if (value_.parameter_type != rcl_interfaces::ParameterType::PARAMETER_BOOL) { // TODO: use custom exception throw std::runtime_error("Invalid type"); } return value_.bool_value; } template<> inline std::vector<int8_t> ParameterVariant::get_value() const { if (value_.parameter_type != rcl_interfaces::ParameterType::PARAMETER_BYTES) { // TODO: use custom exception throw std::runtime_error("Invalid type"); } return value_.bytes_value; } class AsyncParametersClient { public: RCLCPP_MAKE_SHARED_DEFINITIONS(AsyncParametersClient); AsyncParametersClient(const rclcpp::node::Node::SharedPtr & node) : node_(node) { get_parameters_client_ = node_->create_client<rcl_interfaces::GetParameters>( "get_parameters"); get_parameter_types_client_ = node_->create_client<rcl_interfaces::GetParameterTypes>( "get_parameter_types"); set_parameters_client_ = node_->create_client<rcl_interfaces::SetParameters>( "set_parameters"); list_parameters_client_ = node_->create_client<rcl_interfaces::ListParameters>( "list_parameters"); describe_parameters_client_ = node_->create_client<rcl_interfaces::DescribeParameters>( "describe_parameters"); } std::shared_future<std::vector<ParameterVariant>> get_parameters( std::vector<std::string> names, std::function<void( std::shared_future<std::vector<ParameterVariant>>)> callback = nullptr) { std::shared_future<std::vector<ParameterVariant>> f; return f; } std::shared_future<std::vector<ParameterType>> get_parameter_types( std::vector<std::string> parameter_names, std::function<void( std::shared_future<std::vector<ParameterType>>)> callback = nullptr) { std::shared_future<std::vector<ParameterType>> f; return f; } std::shared_future<std::vector<rcl_interfaces::ParameterSetResult>> set_parameters( std::vector<ParameterVariant> parameters, std::function<void( std::shared_future<std::vector<rcl_interfaces::ParameterSetResult>>)> callback = nullptr) { std::shared_future<std::vector<rcl_interfaces::ParameterSetResult>> f; return f; } std::shared_future<rcl_interfaces::ParameterSetResult> set_parameters_atomically( std::vector<ParameterVariant> parameters, std::function<void( std::shared_future<rcl_interfaces::ParameterSetResult>)> callback = nullptr) { std::shared_future<rcl_interfaces::ParameterSetResult> f; return f; } std::shared_future<rcl_interfaces::ParameterListResult> list_parameters( std::vector<std::string> parameter_prefixes, uint64_t depth, std::function<void( std::shared_future<rcl_interfaces::ParameterListResult>)> callback = nullptr) { std::shared_future<rcl_interfaces::ParameterListResult> f; return f; } private: const rclcpp::node::Node::SharedPtr node_; rclcpp::client::Client<rcl_interfaces::GetParameters>::SharedPtr get_parameters_client_; rclcpp::client::Client<rcl_interfaces::GetParameterTypes>::SharedPtr get_parameter_types_client_; rclcpp::client::Client<rcl_interfaces::SetParameters>::SharedPtr set_parameters_client_; rclcpp::client::Client<rcl_interfaces::SetParametersAtomically>::SharedPtr set_parameters_atomically_client_; rclcpp::client::Client<rcl_interfaces::ListParameters>::SharedPtr list_parameters_client_; rclcpp::client::Client<rcl_interfaces::DescribeParameters>::SharedPtr describe_parameters_client_; }; class SyncParametersClient { friend class rclcpp::executor::Executor; public: RCLCPP_MAKE_SHARED_DEFINITIONS(SyncParametersClient); SyncParametersClient( rclcpp::node::Node::SharedPtr & node) : node_(node) { executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>(); async_parameters_client_ = std::make_shared<AsyncParametersClient>(node); } SyncParametersClient( rclcpp::executor::Executor::SharedPtr & executor, rclcpp::node::Node::SharedPtr & node) : executor_(executor), node_(node) { async_parameters_client_ = std::make_shared<AsyncParametersClient>(node); } std::vector<ParameterVariant> get_parameters(std::vector<std::string> parameter_names) { auto f = async_parameters_client_->get_parameters(parameter_names); return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get(); } std::vector<ParameterType> get_parameter_types(std::vector<std::string> parameter_names) { auto f = async_parameters_client_->get_parameter_types(parameter_names); return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get(); } std::vector<rcl_interfaces::ParameterSetResult> set_parameters(std::vector<ParameterVariant> parameters) { auto f = async_parameters_client_->set_parameters(parameters); return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get(); } rcl_interfaces::ParameterSetResult set_parameters_atomically(std::vector<ParameterVariant> parameters) { auto f = async_parameters_client_->set_parameters_atomically(parameters); return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get(); } rcl_interfaces::ParameterListResult list_parameters( std::vector<std::string> parameter_prefixes, uint64_t depth) { auto f = async_parameters_client_->list_parameters(parameter_prefixes, depth); return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get(); } private: rclcpp::executor::Executor::SharedPtr executor_; rclcpp::node::Node::SharedPtr node_; AsyncParametersClient::SharedPtr async_parameters_client_; }; } /* namespace parameter */ } /* namespace rclcpp */ #endif /* RCLCPP_RCLCPP_PARAMETER_HPP_ */
// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RCLCPP_RCLCPP_PARAMETER_HPP_ #define RCLCPP_RCLCPP_PARAMETER_HPP_ #include <string> #include <rmw/rmw.h> #include <rclcpp/executors.hpp> #include <rclcpp/macros.hpp> #include <rclcpp/node.hpp> #include <rcl_interfaces/GetParameters.h> #include <rcl_interfaces/GetParameterTypes.h> #include <rcl_interfaces/Parameter.h> #include <rcl_interfaces/ParameterDescriptor.h> #include <rcl_interfaces/ParameterType.h> #include <rcl_interfaces/SetParameters.h> #include <rcl_interfaces/SetParametersAtomically.h> #include <rcl_interfaces/ListParameters.h> #include <rcl_interfaces/DescribeParameters.h> namespace rclcpp { namespace parameter { enum ParameterType { PARAMETER_NOT_SET=rcl_interfaces::ParameterType::PARAMETER_NOT_SET, PARAMETER_BOOL=rcl_interfaces::ParameterType::PARAMETER_BOOL, PARAMETER_INTEGER=rcl_interfaces::ParameterType::PARAMETER_INTEGER, PARAMETER_DOUBLE=rcl_interfaces::ParameterType::PARAMETER_DOUBLE, PARAMETER_STRING=rcl_interfaces::ParameterType::PARAMETER_STRING, PARAMETER_BYTES=rcl_interfaces::ParameterType::PARAMETER_BYTES, }; // Structure to store an arbitrary parameter with templated get/set methods class ParameterVariant { public: ParameterVariant() : name_("") { value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_NOT_SET; } explicit ParameterVariant(const std::string & name, const bool bool_value) : name_(name) { value_.bool_value = bool_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_BOOL; } explicit ParameterVariant(const std::string & name, const int int_value) : name_(name) { value_.integer_value = int_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_INTEGER; } explicit ParameterVariant(const std::string & name, const int64_t int_value) : name_(name) { value_.integer_value = int_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_INTEGER; } explicit ParameterVariant(const std::string & name, const float double_value) : name_(name) { value_.double_value = double_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_DOUBLE; } explicit ParameterVariant(const std::string & name, const double double_value) : name_(name) { value_.double_value = double_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_DOUBLE; } explicit ParameterVariant(const std::string & name, const std::string & string_value) : name_(name) { value_.string_value = string_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_STRING; } explicit ParameterVariant(const std::string & name, const std::vector<uint8_t> & bytes_value) : name_(name) { value_.bytes_value = bytes_value; value_.parameter_type = rcl_interfaces::ParameterType::PARAMETER_BYTES; } /* Templated getter */ template<typename T> T get_value() const; inline ParameterType get_type() const {return static_cast<ParameterType>(value_.parameter_type); } inline std::string get_name() const & {return name_; } inline rcl_interfaces::ParameterValue get_parameter_value() const { return value_; } private: std::string name_; rcl_interfaces::ParameterValue value_; }; template<> inline int64_t ParameterVariant::get_value() const { if (value_.parameter_type != rcl_interfaces::ParameterType::PARAMETER_INTEGER) { // TODO: use custom exception throw std::runtime_error("Invalid type"); } return value_.integer_value; } template<> inline double ParameterVariant::get_value() const { if (value_.parameter_type != rcl_interfaces::ParameterType::PARAMETER_DOUBLE) { // TODO: use custom exception throw std::runtime_error("Invalid type"); } return value_.double_value; } template<> inline std::string ParameterVariant::get_value() const { if (value_.parameter_type != rcl_interfaces::ParameterType::PARAMETER_STRING) { // TODO: use custom exception throw std::runtime_error("Invalid type"); } return value_.string_value; } template<> inline bool ParameterVariant::get_value() const { if (value_.parameter_type != rcl_interfaces::ParameterType::PARAMETER_BOOL) { // TODO: use custom exception throw std::runtime_error("Invalid type"); } return value_.bool_value; } template<> inline std::vector<uint8_t> ParameterVariant::get_value() const { if (value_.parameter_type != rcl_interfaces::ParameterType::PARAMETER_BYTES) { // TODO: use custom exception throw std::runtime_error("Invalid type"); } return value_.bytes_value; } class AsyncParametersClient { public: RCLCPP_MAKE_SHARED_DEFINITIONS(AsyncParametersClient); AsyncParametersClient(const rclcpp::node::Node::SharedPtr & node) : node_(node) { get_parameters_client_ = node_->create_client<rcl_interfaces::GetParameters>( "get_parameters"); get_parameter_types_client_ = node_->create_client<rcl_interfaces::GetParameterTypes>( "get_parameter_types"); set_parameters_client_ = node_->create_client<rcl_interfaces::SetParameters>( "set_parameters"); list_parameters_client_ = node_->create_client<rcl_interfaces::ListParameters>( "list_parameters"); describe_parameters_client_ = node_->create_client<rcl_interfaces::DescribeParameters>( "describe_parameters"); } std::shared_future<std::vector<ParameterVariant>> get_parameters( std::vector<std::string> names, std::function<void( std::shared_future<std::vector<ParameterVariant>>)> callback = nullptr) { std::shared_future<std::vector<ParameterVariant>> f; return f; } std::shared_future<std::vector<ParameterType>> get_parameter_types( std::vector<std::string> parameter_names, std::function<void( std::shared_future<std::vector<ParameterType>>)> callback = nullptr) { std::shared_future<std::vector<ParameterType>> f; return f; } std::shared_future<std::vector<rcl_interfaces::ParameterSetResult>> set_parameters( std::vector<ParameterVariant> parameters, std::function<void( std::shared_future<std::vector<rcl_interfaces::ParameterSetResult>>)> callback = nullptr) { std::shared_future<std::vector<rcl_interfaces::ParameterSetResult>> f; return f; } std::shared_future<rcl_interfaces::ParameterSetResult> set_parameters_atomically( std::vector<ParameterVariant> parameters, std::function<void( std::shared_future<rcl_interfaces::ParameterSetResult>)> callback = nullptr) { std::shared_future<rcl_interfaces::ParameterSetResult> f; return f; } std::shared_future<rcl_interfaces::ParameterListResult> list_parameters( std::vector<std::string> parameter_prefixes, uint64_t depth, std::function<void( std::shared_future<rcl_interfaces::ParameterListResult>)> callback = nullptr) { std::shared_future<rcl_interfaces::ParameterListResult> f; return f; } private: const rclcpp::node::Node::SharedPtr node_; rclcpp::client::Client<rcl_interfaces::GetParameters>::SharedPtr get_parameters_client_; rclcpp::client::Client<rcl_interfaces::GetParameterTypes>::SharedPtr get_parameter_types_client_; rclcpp::client::Client<rcl_interfaces::SetParameters>::SharedPtr set_parameters_client_; rclcpp::client::Client<rcl_interfaces::SetParametersAtomically>::SharedPtr set_parameters_atomically_client_; rclcpp::client::Client<rcl_interfaces::ListParameters>::SharedPtr list_parameters_client_; rclcpp::client::Client<rcl_interfaces::DescribeParameters>::SharedPtr describe_parameters_client_; }; class SyncParametersClient { friend class rclcpp::executor::Executor; public: RCLCPP_MAKE_SHARED_DEFINITIONS(SyncParametersClient); SyncParametersClient( rclcpp::node::Node::SharedPtr & node) : node_(node) { executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>(); async_parameters_client_ = std::make_shared<AsyncParametersClient>(node); } SyncParametersClient( rclcpp::executor::Executor::SharedPtr & executor, rclcpp::node::Node::SharedPtr & node) : executor_(executor), node_(node) { async_parameters_client_ = std::make_shared<AsyncParametersClient>(node); } std::vector<ParameterVariant> get_parameters(std::vector<std::string> parameter_names) { auto f = async_parameters_client_->get_parameters(parameter_names); return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get(); } std::vector<ParameterType> get_parameter_types(std::vector<std::string> parameter_names) { auto f = async_parameters_client_->get_parameter_types(parameter_names); return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get(); } std::vector<rcl_interfaces::ParameterSetResult> set_parameters(std::vector<ParameterVariant> parameters) { auto f = async_parameters_client_->set_parameters(parameters); return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get(); } rcl_interfaces::ParameterSetResult set_parameters_atomically(std::vector<ParameterVariant> parameters) { auto f = async_parameters_client_->set_parameters_atomically(parameters); return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get(); } rcl_interfaces::ParameterListResult list_parameters( std::vector<std::string> parameter_prefixes, uint64_t depth) { auto f = async_parameters_client_->list_parameters(parameter_prefixes, depth); return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get(); } private: rclcpp::executor::Executor::SharedPtr executor_; rclcpp::node::Node::SharedPtr node_; AsyncParametersClient::SharedPtr async_parameters_client_; }; } /* namespace parameter */ } /* namespace rclcpp */ #endif /* RCLCPP_RCLCPP_PARAMETER_HPP_ */
Use unsigned int8 to match the byte primitive type
Use unsigned int8 to match the byte primitive type
C++
apache-2.0
ros2/rclcpp,ros2/rclcpp
34843e66f3a897cd8adb42b8e906ae356f5785d2
src/test/fs_tests.cpp
src/test/fs_tests.cpp
// Copyright (c) 2011-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // #include <fs.h> //#include <test/setup_common.h> //#include <util/system.h> #include <util.h> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(fs_tests) BOOST_AUTO_TEST_CASE(fsbridge_fstream) { fs::path tmpfolder = GetDataDir(); // tmpfile1 should be the same as tmpfile2 fs::path tmpfile1 = tmpfolder / "fs_tests_₿_🏃"; fs::path tmpfile2 = tmpfolder / "fs_tests_₿_🏃"; { fsbridge::ofstream file(tmpfile1); file << "bitcoin"; } { fsbridge::ifstream file(tmpfile2); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, "bitcoin"); } { fsbridge::ifstream file(tmpfile1, std::ios_base::in | std::ios_base::ate); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, ""); } { fsbridge::ofstream file(tmpfile2, std::ios_base::out | std::ios_base::app); file << "tests"; } { fsbridge::ifstream file(tmpfile1); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, "bitcointests"); } { fsbridge::ofstream file(tmpfile2, std::ios_base::out | std::ios_base::trunc); file << "bitcoin"; } { fsbridge::ifstream file(tmpfile1); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, "bitcoin"); } } BOOST_AUTO_TEST_SUITE_END()
// Copyright (c) 2011-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // #include <fs.h> //#include <test/setup_common.h> //#include <util/system.h> #include <util.h> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(fs_tests) BOOST_AUTO_TEST_CASE(fsbridge_fstream) { fs::path tmpfolder = GetDataDir(); // tmpfile1 should be the same as tmpfile2 fs::path tmpfile1 = tmpfolder / "fs_tests_₿_🏃"; fs::path tmpfile2 = tmpfolder / "fs_tests_₿_🏃"; { fsbridge::ofstream file(tmpfile1); file << "bitcoin"; } { fsbridge::ifstream file(tmpfile2); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, "bitcoin"); } { fsbridge::ifstream file(tmpfile1, std::ios_base::in | std::ios_base::ate); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, ""); } { fsbridge::ofstream file(tmpfile2, std::ios_base::out | std::ios_base::app); file << "tests"; } { fsbridge::ifstream file(tmpfile1); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, "bitcointests"); } { fsbridge::ofstream file(tmpfile2, std::ios_base::out | std::ios_base::trunc); file << "bitcoin"; } { fsbridge::ifstream file(tmpfile1); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, "bitcoin"); } fs::remove(tmpfile1); } BOOST_AUTO_TEST_SUITE_END()
Remove the fs_tests test file after the test
Remove the fs_tests test file after the test
C++
mit
caraka/gridcoinresearch,Git-Jiro/Gridcoin-Research,gridcoin/Gridcoin-Research,caraka/gridcoinresearch,Git-Jiro/Gridcoin-Research,gridcoin/Gridcoin-Research,caraka/gridcoinresearch,gridcoin/Gridcoin-Research,Git-Jiro/Gridcoin-Research,gridcoin/Gridcoin-Research,caraka/gridcoinresearch,caraka/gridcoinresearch,Git-Jiro/Gridcoin-Research,gridcoin/Gridcoin-Research,Git-Jiro/Gridcoin-Research,caraka/gridcoinresearch,gridcoin/Gridcoin-Research
f3b7bb520dee28cea8a3472053fabf6dbe91e8c0
remoting/protocol/session_config.cc
remoting/protocol/session_config.cc
// 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 "remoting/protocol/session_config.h" #include <algorithm> namespace remoting { namespace protocol { namespace { bool IsChannelConfigSupported(const std::list<ChannelConfig>& list, const ChannelConfig& value) { return std::find(list.begin(), list.end(), value) != list.end(); } bool SelectCommonChannelConfig(const std::list<ChannelConfig>& host_configs, const std::list<ChannelConfig>& client_configs, ChannelConfig* config) { // Usually each of these lists will contain just a few elements, so iterating // over all of them is not a problem. std::list<ChannelConfig>::const_iterator it; for (it = client_configs.begin(); it != client_configs.end(); ++it) { if (IsChannelConfigSupported(host_configs, *it)) { *config = *it; return true; } } return false; } } // namespace const int kDefaultStreamVersion = 2; const int kControlStreamVersion = 3; ChannelConfig ChannelConfig::None() { return ChannelConfig(); } ChannelConfig::ChannelConfig(TransportType transport, int version, Codec codec) : transport(transport), version(version), codec(codec) { } bool ChannelConfig::operator==(const ChannelConfig& b) const { // If the transport field is set to NONE then all other fields are irrelevant. if (transport == ChannelConfig::TRANSPORT_NONE) return transport == b.transport; return transport == b.transport && version == b.version && codec == b.codec; } // static scoped_ptr<SessionConfig> SessionConfig::SelectCommon( const CandidateSessionConfig* client_config, const CandidateSessionConfig* host_config) { scoped_ptr<SessionConfig> result(new SessionConfig()); ChannelConfig control_config; ChannelConfig event_config; ChannelConfig video_config; ChannelConfig audio_config; result->standard_ice_ = host_config->standard_ice() && client_config->standard_ice(); if (!SelectCommonChannelConfig(host_config->control_configs(), client_config->control_configs(), &result->control_config_) || !SelectCommonChannelConfig(host_config->event_configs(), client_config->event_configs(), &result->event_config_) || !SelectCommonChannelConfig(host_config->video_configs(), client_config->video_configs(), &result->video_config_) || !SelectCommonChannelConfig(host_config->audio_configs(), client_config->audio_configs(), &result->audio_config_)) { return nullptr; } return result; } // static scoped_ptr<SessionConfig> SessionConfig::GetFinalConfig( const CandidateSessionConfig* candidate_config) { if (candidate_config->control_configs().size() != 1 || candidate_config->event_configs().size() != 1 || candidate_config->video_configs().size() != 1 || candidate_config->audio_configs().size() != 1) { return nullptr; } scoped_ptr<SessionConfig> result(new SessionConfig()); result->standard_ice_ = candidate_config->standard_ice(); result->control_config_ = candidate_config->control_configs().front(); result->event_config_ = candidate_config->event_configs().front(); result->video_config_ = candidate_config->video_configs().front(); result->audio_config_ = candidate_config->audio_configs().front(); return result.Pass(); } // static scoped_ptr<SessionConfig> SessionConfig::ForTest() { scoped_ptr<SessionConfig> result(new SessionConfig()); result->standard_ice_ = true; result->control_config_ = ChannelConfig(ChannelConfig::TRANSPORT_MUX_STREAM, kControlStreamVersion, ChannelConfig::CODEC_UNDEFINED); result->event_config_ = ChannelConfig(ChannelConfig::TRANSPORT_MUX_STREAM, kDefaultStreamVersion, ChannelConfig::CODEC_UNDEFINED); result->video_config_ = ChannelConfig(ChannelConfig::TRANSPORT_STREAM, kDefaultStreamVersion, ChannelConfig::CODEC_VP8); result->audio_config_ = ChannelConfig(ChannelConfig::TRANSPORT_NONE, kDefaultStreamVersion, ChannelConfig::CODEC_UNDEFINED); return result.Pass(); } // static scoped_ptr<SessionConfig> SessionConfig::WithLegacyIceForTest() { scoped_ptr<SessionConfig> result = ForTest(); result->standard_ice_ = false; return result.Pass(); } SessionConfig::SessionConfig() { } CandidateSessionConfig::CandidateSessionConfig() { } CandidateSessionConfig::CandidateSessionConfig( const CandidateSessionConfig& config) : standard_ice_(true), control_configs_(config.control_configs_), event_configs_(config.event_configs_), video_configs_(config.video_configs_), audio_configs_(config.audio_configs_) { } CandidateSessionConfig::~CandidateSessionConfig() { } bool CandidateSessionConfig::IsSupported( const SessionConfig& config) const { return IsChannelConfigSupported(control_configs_, config.control_config()) && IsChannelConfigSupported(event_configs_, config.event_config()) && IsChannelConfigSupported(video_configs_, config.video_config()) && IsChannelConfigSupported(audio_configs_, config.audio_config()); } scoped_ptr<CandidateSessionConfig> CandidateSessionConfig::Clone() const { return make_scoped_ptr(new CandidateSessionConfig(*this)); } // static scoped_ptr<CandidateSessionConfig> CandidateSessionConfig::CreateEmpty() { return make_scoped_ptr(new CandidateSessionConfig()); } // static scoped_ptr<CandidateSessionConfig> CandidateSessionConfig::CreateFrom( const SessionConfig& config) { scoped_ptr<CandidateSessionConfig> result = CreateEmpty(); result->set_standard_ice(config.standard_ice()); result->mutable_control_configs()->push_back(config.control_config()); result->mutable_event_configs()->push_back(config.event_config()); result->mutable_video_configs()->push_back(config.video_config()); result->mutable_audio_configs()->push_back(config.audio_config()); return result.Pass(); } // static scoped_ptr<CandidateSessionConfig> CandidateSessionConfig::CreateDefault() { scoped_ptr<CandidateSessionConfig> result = CreateEmpty(); result->set_standard_ice(true); // Control channel. result->mutable_control_configs()->push_back( ChannelConfig(ChannelConfig::TRANSPORT_MUX_STREAM, kControlStreamVersion, ChannelConfig::CODEC_UNDEFINED)); // Event channel. result->mutable_event_configs()->push_back( ChannelConfig(ChannelConfig::TRANSPORT_MUX_STREAM, kDefaultStreamVersion, ChannelConfig::CODEC_UNDEFINED)); // Video channel. result->mutable_video_configs()->push_back( ChannelConfig(ChannelConfig::TRANSPORT_STREAM, kDefaultStreamVersion, ChannelConfig::CODEC_VP8)); // Audio channel. result->mutable_audio_configs()->push_back( ChannelConfig(ChannelConfig::TRANSPORT_MUX_STREAM, kDefaultStreamVersion, ChannelConfig::CODEC_OPUS)); result->mutable_audio_configs()->push_back(ChannelConfig::None()); return result.Pass(); } void CandidateSessionConfig::DisableAudioChannel() { mutable_audio_configs()->clear(); mutable_audio_configs()->push_back(ChannelConfig()); } void CandidateSessionConfig::EnableVideoCodec(ChannelConfig::Codec codec) { mutable_video_configs()->push_front( ChannelConfig(ChannelConfig::TRANSPORT_STREAM, kDefaultStreamVersion, codec)); } } // namespace protocol } // namespace remoting
// 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 "remoting/protocol/session_config.h" #include <algorithm> namespace remoting { namespace protocol { namespace { bool IsChannelConfigSupported(const std::list<ChannelConfig>& list, const ChannelConfig& value) { return std::find(list.begin(), list.end(), value) != list.end(); } bool SelectCommonChannelConfig(const std::list<ChannelConfig>& host_configs, const std::list<ChannelConfig>& client_configs, ChannelConfig* config) { // Usually each of these lists will contain just a few elements, so iterating // over all of them is not a problem. std::list<ChannelConfig>::const_iterator it; for (it = client_configs.begin(); it != client_configs.end(); ++it) { if (IsChannelConfigSupported(host_configs, *it)) { *config = *it; return true; } } return false; } } // namespace const int kDefaultStreamVersion = 2; const int kControlStreamVersion = 3; ChannelConfig ChannelConfig::None() { return ChannelConfig(); } ChannelConfig::ChannelConfig(TransportType transport, int version, Codec codec) : transport(transport), version(version), codec(codec) { } bool ChannelConfig::operator==(const ChannelConfig& b) const { // If the transport field is set to NONE then all other fields are irrelevant. if (transport == ChannelConfig::TRANSPORT_NONE) return transport == b.transport; return transport == b.transport && version == b.version && codec == b.codec; } // static scoped_ptr<SessionConfig> SessionConfig::SelectCommon( const CandidateSessionConfig* client_config, const CandidateSessionConfig* host_config) { scoped_ptr<SessionConfig> result(new SessionConfig()); ChannelConfig control_config; ChannelConfig event_config; ChannelConfig video_config; ChannelConfig audio_config; result->standard_ice_ = host_config->standard_ice() && client_config->standard_ice(); if (!SelectCommonChannelConfig(host_config->control_configs(), client_config->control_configs(), &result->control_config_) || !SelectCommonChannelConfig(host_config->event_configs(), client_config->event_configs(), &result->event_config_) || !SelectCommonChannelConfig(host_config->video_configs(), client_config->video_configs(), &result->video_config_) || !SelectCommonChannelConfig(host_config->audio_configs(), client_config->audio_configs(), &result->audio_config_)) { return nullptr; } return result; } // static scoped_ptr<SessionConfig> SessionConfig::GetFinalConfig( const CandidateSessionConfig* candidate_config) { if (candidate_config->control_configs().size() != 1 || candidate_config->event_configs().size() != 1 || candidate_config->video_configs().size() != 1 || candidate_config->audio_configs().size() != 1) { return nullptr; } scoped_ptr<SessionConfig> result(new SessionConfig()); result->standard_ice_ = candidate_config->standard_ice(); result->control_config_ = candidate_config->control_configs().front(); result->event_config_ = candidate_config->event_configs().front(); result->video_config_ = candidate_config->video_configs().front(); result->audio_config_ = candidate_config->audio_configs().front(); return result.Pass(); } // static scoped_ptr<SessionConfig> SessionConfig::ForTest() { scoped_ptr<SessionConfig> result(new SessionConfig()); result->standard_ice_ = true; result->control_config_ = ChannelConfig(ChannelConfig::TRANSPORT_MUX_STREAM, kControlStreamVersion, ChannelConfig::CODEC_UNDEFINED); result->event_config_ = ChannelConfig(ChannelConfig::TRANSPORT_MUX_STREAM, kDefaultStreamVersion, ChannelConfig::CODEC_UNDEFINED); result->video_config_ = ChannelConfig(ChannelConfig::TRANSPORT_STREAM, kDefaultStreamVersion, ChannelConfig::CODEC_VP8); result->audio_config_ = ChannelConfig(ChannelConfig::TRANSPORT_NONE, kDefaultStreamVersion, ChannelConfig::CODEC_UNDEFINED); return result.Pass(); } // static scoped_ptr<SessionConfig> SessionConfig::WithLegacyIceForTest() { scoped_ptr<SessionConfig> result = ForTest(); result->standard_ice_ = false; return result.Pass(); } SessionConfig::SessionConfig() { } CandidateSessionConfig::CandidateSessionConfig() { } CandidateSessionConfig::CandidateSessionConfig( const CandidateSessionConfig& config) = default; CandidateSessionConfig::~CandidateSessionConfig() { } bool CandidateSessionConfig::IsSupported( const SessionConfig& config) const { return IsChannelConfigSupported(control_configs_, config.control_config()) && IsChannelConfigSupported(event_configs_, config.event_config()) && IsChannelConfigSupported(video_configs_, config.video_config()) && IsChannelConfigSupported(audio_configs_, config.audio_config()); } scoped_ptr<CandidateSessionConfig> CandidateSessionConfig::Clone() const { return make_scoped_ptr(new CandidateSessionConfig(*this)); } // static scoped_ptr<CandidateSessionConfig> CandidateSessionConfig::CreateEmpty() { return make_scoped_ptr(new CandidateSessionConfig()); } // static scoped_ptr<CandidateSessionConfig> CandidateSessionConfig::CreateFrom( const SessionConfig& config) { scoped_ptr<CandidateSessionConfig> result = CreateEmpty(); result->set_standard_ice(config.standard_ice()); result->mutable_control_configs()->push_back(config.control_config()); result->mutable_event_configs()->push_back(config.event_config()); result->mutable_video_configs()->push_back(config.video_config()); result->mutable_audio_configs()->push_back(config.audio_config()); return result.Pass(); } // static scoped_ptr<CandidateSessionConfig> CandidateSessionConfig::CreateDefault() { scoped_ptr<CandidateSessionConfig> result = CreateEmpty(); result->set_standard_ice(true); // Control channel. result->mutable_control_configs()->push_back( ChannelConfig(ChannelConfig::TRANSPORT_MUX_STREAM, kControlStreamVersion, ChannelConfig::CODEC_UNDEFINED)); // Event channel. result->mutable_event_configs()->push_back( ChannelConfig(ChannelConfig::TRANSPORT_MUX_STREAM, kDefaultStreamVersion, ChannelConfig::CODEC_UNDEFINED)); // Video channel. result->mutable_video_configs()->push_back( ChannelConfig(ChannelConfig::TRANSPORT_STREAM, kDefaultStreamVersion, ChannelConfig::CODEC_VP8)); // Audio channel. result->mutable_audio_configs()->push_back( ChannelConfig(ChannelConfig::TRANSPORT_MUX_STREAM, kDefaultStreamVersion, ChannelConfig::CODEC_OPUS)); result->mutable_audio_configs()->push_back(ChannelConfig::None()); return result.Pass(); } void CandidateSessionConfig::DisableAudioChannel() { mutable_audio_configs()->clear(); mutable_audio_configs()->push_back(ChannelConfig()); } void CandidateSessionConfig::EnableVideoCodec(ChannelConfig::Codec codec) { mutable_video_configs()->push_front( ChannelConfig(ChannelConfig::TRANSPORT_STREAM, kDefaultStreamVersion, codec)); } } // namespace protocol } // namespace remoting
Fix CandidateSessionConfig copy constructor to copy all fields.
Fix CandidateSessionConfig copy constructor to copy all fields. The constructor wasn't copying standard_ice field which breaks the case when older client connects to newer host. BUG=483325 Review URL: https://codereview.chromium.org/1125213003 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#328631}
C++
bsd-3-clause
Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk
f65d60e9dc8363c4247a2cbfa148b1f5763821a7
src/tool/exchange.cpp
src/tool/exchange.cpp
// Copyright 2016 Peter Georg // // 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 "exchange.hpp" #include <algorithm> #include <sstream> #include <vector> extern "C" { #include <omp.h> } #include "../allreduce.hpp" #include "../communicator.hpp" #include "../config.hpp" #include "../connection.hpp" #include "../misc/allocator.hpp" #include "../misc/random.hpp" #include "../misc/time.hpp" #include "../recvwindow.hpp" #include "../sendwindow.hpp" #include "mpi.hpp" #include "parameter.hpp" void runExchange(int argc, char **argv) { // Default options int dim = {1}; std::vector<int> geom; std::vector<int> periodic; std::uint64_t maxIter = {10000}; std::uint64_t overallSize = {1024 * 1024 * 1024}; std::uint32_t minMsgSize = {0}; std::uint32_t maxMsgSize = {128 * 1024}; std::uint32_t deltaMsgSize = 100; std::uint32_t minDeltaMsgSize = {4}; std::uint32_t maxDeltaMsgSize = {4 * 1024}; bool bufferedSend = {false}; bool bufferedRecv = {false}; int threads = {1}; bool verify = {false}; // Get additional parameter options parameterOption(argv, argv + argc, "--dim", dim); geom.resize(dim, 0); periodic.resize(dim, 1); parameterOption(argv, argv + argc, "--geom", geom); parameterOption(argv, argv + argc, "--periodic", periodic); parameterOption<std::uint64_t>(argv, argv + argc, "--maxIter", maxIter); parameterOption<std::uint64_t>( argv, argv + argc, "--overallSize", overallSize); parameterOption<std::uint32_t>( argv, argv + argc, "--minMsgSize", minMsgSize); parameterOption<std::uint32_t>( argv, argv + argc, "--maxMsgSize", maxMsgSize); parameterOption<std::uint32_t>( argv, argv + argc, "--deltaMsgSize", deltaMsgSize); parameterOption<std::uint32_t>( argv, argv + argc, "--minDeltaMsgSize", minDeltaMsgSize); parameterOption<std::uint32_t>( argv, argv + argc, "--maxDeltaMsgSize", maxDeltaMsgSize); if(minDeltaMsgSize > maxDeltaMsgSize) { printUsage(); } if(parameterExists(argv, argv + argc, "--bufferedSend")) { bufferedSend = {true}; } if(parameterExists(argv, argv + argc, "--bufferedRecv")) { bufferedRecv = {true}; } if(parameterExists(argv, argv + argc, "--threaded")) { if(pMR::cThreadLevel < pMR::ThreadLevel::Multiple) { throw std::runtime_error( "pMR has not been configured for threaded communication."); } threads = omp_get_max_threads(); } if(parameterExists(argv, argv + argc, "--verify")) { verify = {true}; } // Prepare benchmark environment pMR::Communicator communicator(MPI_COMM_WORLD, geom, periodic); // Establish connections std::vector<pMR::Connection> connections; for(auto n = decltype(communicator.dimensions()){0}; n != communicator.dimensions(); ++n) { pMR::Target lNeighbor = communicator.getNeighbor(n, -1); pMR::Target rNeighbor = communicator.getNeighbor(n, +1); if(communicator.coordinate(n) % 2 == 1) { if(lNeighbor.isRemote()) { connections.emplace_back(lNeighbor); } if(rNeighbor.isRemote()) { connections.emplace_back(rNeighbor); } } else { if(rNeighbor.isRemote()) { connections.emplace_back(rNeighbor); } if(lNeighbor.isRemote()) { connections.emplace(connections.end() - 1, lNeighbor); } } } if(connections.size() == 0) { finalize(); } // Print Benchmark Information printMaster("Benchmark: Exchange"); printMaster("Processes: ", communicator.size()); printMaster("Dimensions: ", static_cast<int>(connections.size() / 2), "/", communicator.dimensions()); printMaster("Topology: ", communicator.topology()); printMaster("Periodic: ", communicator.periodic()); printMaster("BufferedSend:", bufferedSend); printMaster("BufferedRecv:", bufferedRecv); printMaster("Threads: ", threads); printMaster("Verify: ", verify); printMaster(); printMaster(" MPIRank Size[By] Iteration Time/It[s]"); // Loop Message Sizes auto msgSize = minMsgSize; while(msgSize <= maxMsgSize) { std::vector<std::vector<unsigned char, pMR::Allocator<unsigned char>>> vBuffers, sendBuffers, recvBuffers; std::vector<pMR::SendWindow<unsigned char>> sendWindows; std::vector<pMR::RecvWindow<unsigned char>> recvWindows; // Create Buffers and Windows for(decltype(connections.size()) c = 0; c != connections.size(); ++c) { if(verify) { vBuffers.emplace_back(msgSize + pMR::cacheLineSize()); sendBuffers.emplace_back(msgSize + pMR::cacheLineSize()); recvBuffers.emplace_back(msgSize + pMR::cacheLineSize()); std::generate_n(vBuffers.back().begin(), msgSize, pMR::getRandomNumber<std::uint8_t>); std::fill_n(vBuffers.back().rbegin(), pMR::cacheLineSize(), 0); std::copy(vBuffers.back().begin(), vBuffers.back().end(), sendBuffers.back().begin()); std::fill( recvBuffers.back().begin(), recvBuffers.back().end(), 0); } else { sendBuffers.emplace_back(msgSize); recvBuffers.emplace_back(msgSize); } if(bufferedSend) { sendWindows.emplace_back(connections[c], msgSize); } else { sendWindows.emplace_back( connections[c], sendBuffers.back().data(), msgSize); } if(bufferedRecv) { recvWindows.emplace_back(connections[c], msgSize); } else { recvWindows.emplace_back( connections[c], recvBuffers.back().data(), msgSize); } } // Calculate iterations count auto iter = maxIter; if(msgSize) { iter = std::min(iter, overallSize / msgSize / static_cast<std::uint64_t>(sendWindows.size())); } auto size = sendWindows.size(); auto s = decltype(size){0}; threads = std::min(threads, static_cast<int>(size)); double time = -pMR::getTimeInSeconds(); #pragma omp parallel num_threads(threads) for(auto i = decltype(iter){0}; i != iter; ++i) { #pragma omp for for(s = 0; s < size; ++s) { recvWindows[s].init(); sendWindows[s].init(); } if(bufferedSend) { #pragma omp for for(s = 0; s < size; ++s) { sendWindows[s].insert(sendBuffers[s].cbegin()); } } #pragma omp for for(s = 0; s < size; ++s) { sendWindows[s].post(); recvWindows[s].post(); } #pragma omp for for(s = 0; s < size; ++s) { sendWindows[s].wait(); recvWindows[s].wait(); } if(bufferedRecv) { #pragma omp for for(s = 0; s < size; ++s) { recvWindows[s].extract(recvBuffers[s].begin()); } } if(verify) { if(i % 2 == 1) { #pragma omp for for(s = 0; s < size; ++s) { if(recvBuffers[s] != vBuffers[s]) { throw std::runtime_error( "Verification check failed!"); } } } #pragma omp for for(s = 0; s < size; ++s) { std::copy(recvBuffers[s].begin(), recvBuffers[s].end(), sendBuffers[s].begin()); std::fill(recvBuffers[s].begin(), recvBuffers[s].end(), 0); } } } time += pMR::getTimeInSeconds(); std::ostringstream oss; oss << std::setw(8) << getRank(MPI_COMM_WORLD) << " " << std::setw(8) << msgSize << " " << std::setw(8) << iter << " " << std::scientific << time / iter << std::endl; std::cout << oss.str(); // Increment msgSize for next loop auto tmpSize = (msgSize * (100 + deltaMsgSize)) / 100; tmpSize -= tmpSize % minDeltaMsgSize; if(tmpSize - msgSize < minDeltaMsgSize) { tmpSize = msgSize + minDeltaMsgSize; } if(tmpSize - msgSize > maxDeltaMsgSize) { tmpSize = msgSize + maxDeltaMsgSize; } msgSize = tmpSize; } finalize(); }
// Copyright 2016 Peter Georg // // 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 "exchange.hpp" #include <algorithm> #include <sstream> #include <vector> extern "C" { #include <omp.h> } #include "../allreduce.hpp" #include "../communicator.hpp" #include "../config.hpp" #include "../connection.hpp" #include "../misc/allocator.hpp" #include "../misc/random.hpp" #include "../misc/time.hpp" #include "../recvwindow.hpp" #include "../sendwindow.hpp" #include "mpi.hpp" #include "parameter.hpp" void runExchange(int argc, char **argv) { // Default options int dim = {1}; std::vector<int> geom; std::vector<int> periodic; std::uint64_t maxIter = {10000}; std::uint64_t overallSize = {1024 * 1024 * 1024}; std::uint32_t minMsgSize = {0}; std::uint32_t maxMsgSize = {128 * 1024}; std::uint32_t deltaMsgSize = 100; std::uint32_t minDeltaMsgSize = {4}; std::uint32_t maxDeltaMsgSize = {4 * 1024}; bool bufferedSend = {false}; bool bufferedRecv = {false}; int threads = {1}; bool verify = {false}; // Get additional parameter options parameterOption(argv, argv + argc, "--dim", dim); geom.resize(dim, 0); periodic.resize(dim, 1); parameterOption(argv, argv + argc, "--geom", geom); parameterOption(argv, argv + argc, "--periodic", periodic); parameterOption<std::uint64_t>(argv, argv + argc, "--maxIter", maxIter); parameterOption<std::uint64_t>( argv, argv + argc, "--overallSize", overallSize); parameterOption<std::uint32_t>( argv, argv + argc, "--minMsgSize", minMsgSize); parameterOption<std::uint32_t>( argv, argv + argc, "--maxMsgSize", maxMsgSize); parameterOption<std::uint32_t>( argv, argv + argc, "--deltaMsgSize", deltaMsgSize); parameterOption<std::uint32_t>( argv, argv + argc, "--minDeltaMsgSize", minDeltaMsgSize); parameterOption<std::uint32_t>( argv, argv + argc, "--maxDeltaMsgSize", maxDeltaMsgSize); if(minDeltaMsgSize > maxDeltaMsgSize) { printUsage(); } if(parameterExists(argv, argv + argc, "--bufferedSend")) { bufferedSend = {true}; } if(parameterExists(argv, argv + argc, "--bufferedRecv")) { bufferedRecv = {true}; } if(parameterExists(argv, argv + argc, "--threaded")) { if(pMR::cThreadLevel < pMR::ThreadLevel::Multiple) { throw std::runtime_error( "pMR has not been configured for threaded communication."); } threads = omp_get_max_threads(); } if(parameterExists(argv, argv + argc, "--verify")) { verify = {true}; } // Prepare benchmark environment pMR::Communicator communicator(MPI_COMM_WORLD, geom, periodic); // Establish connections std::vector<pMR::Connection> connections; for(auto n = decltype(communicator.dimensions()){0}; n != communicator.dimensions(); ++n) { pMR::Target lNeighbor = communicator.getNeighbor(n, -1); pMR::Target rNeighbor = communicator.getNeighbor(n, +1); if(communicator.coordinate(n) % 2 == 1) { if(lNeighbor.isRemote()) { connections.emplace_back(lNeighbor); } if(rNeighbor.isRemote()) { connections.emplace_back(rNeighbor); } } else { if(rNeighbor.isRemote()) { connections.emplace_back(rNeighbor); } if(lNeighbor.isRemote()) { connections.emplace(connections.end() - 1, lNeighbor); } } } if(connections.size() == 0) { finalize(); } threads = std::min(threads, static_cast<int>(connections.size())); // Print Benchmark Information printMaster("Benchmark: Exchange"); printMaster("Processes: ", communicator.size()); printMaster("Dimensions: ", static_cast<int>(connections.size() / 2), "/", communicator.dimensions()); printMaster("Topology: ", communicator.topology()); printMaster("Periodic: ", communicator.periodic()); printMaster("BufferedSend:", bufferedSend); printMaster("BufferedRecv:", bufferedRecv); printMaster("Threads: ", threads); printMaster("Verify: ", verify); printMaster(); printMaster(" MPIRank Size[By] Iteration Time/It[s]"); // Loop Message Sizes auto msgSize = minMsgSize; while(msgSize <= maxMsgSize) { std::vector<std::vector<unsigned char, pMR::Allocator<unsigned char>>> vBuffers, sendBuffers, recvBuffers; std::vector<pMR::SendWindow<unsigned char>> sendWindows; std::vector<pMR::RecvWindow<unsigned char>> recvWindows; // Create Buffers and Windows for(decltype(connections.size()) c = 0; c != connections.size(); ++c) { if(verify) { vBuffers.emplace_back(msgSize + pMR::cacheLineSize()); sendBuffers.emplace_back(msgSize + pMR::cacheLineSize()); recvBuffers.emplace_back(msgSize + pMR::cacheLineSize()); std::generate_n(vBuffers.back().begin(), msgSize, pMR::getRandomNumber<std::uint8_t>); std::fill_n(vBuffers.back().rbegin(), pMR::cacheLineSize(), 0); std::copy(vBuffers.back().begin(), vBuffers.back().end(), sendBuffers.back().begin()); std::fill( recvBuffers.back().begin(), recvBuffers.back().end(), 0); } else { sendBuffers.emplace_back(msgSize); recvBuffers.emplace_back(msgSize); } if(bufferedSend) { sendWindows.emplace_back(connections[c], msgSize); } else { sendWindows.emplace_back( connections[c], sendBuffers.back().data(), msgSize); } if(bufferedRecv) { recvWindows.emplace_back(connections[c], msgSize); } else { recvWindows.emplace_back( connections[c], recvBuffers.back().data(), msgSize); } } // Calculate iterations count auto iter = maxIter; if(msgSize) { iter = std::min(iter, overallSize / msgSize / static_cast<std::uint64_t>(sendWindows.size())); } auto size = sendWindows.size(); auto s = decltype(size){0}; double time = -pMR::getTimeInSeconds(); #pragma omp parallel num_threads(threads) for(auto i = decltype(iter){0}; i != iter; ++i) { #pragma omp for for(s = 0; s < size; ++s) { recvWindows[s].init(); sendWindows[s].init(); } if(bufferedSend) { #pragma omp for for(s = 0; s < size; ++s) { sendWindows[s].insert(sendBuffers[s].cbegin()); } } #pragma omp for for(s = 0; s < size; ++s) { sendWindows[s].post(); recvWindows[s].post(); } #pragma omp for for(s = 0; s < size; ++s) { sendWindows[s].wait(); recvWindows[s].wait(); } if(bufferedRecv) { #pragma omp for for(s = 0; s < size; ++s) { recvWindows[s].extract(recvBuffers[s].begin()); } } if(verify) { if(i % 2 == 1) { #pragma omp for for(s = 0; s < size; ++s) { if(recvBuffers[s] != vBuffers[s]) { throw std::runtime_error( "Verification check failed!"); } } } #pragma omp for for(s = 0; s < size; ++s) { std::copy(recvBuffers[s].begin(), recvBuffers[s].end(), sendBuffers[s].begin()); std::fill(recvBuffers[s].begin(), recvBuffers[s].end(), 0); } } } time += pMR::getTimeInSeconds(); std::ostringstream oss; oss << std::setw(8) << getRank(MPI_COMM_WORLD) << " " << std::setw(8) << msgSize << " " << std::setw(8) << iter << " " << std::scientific << time / iter << std::endl; std::cout << oss.str(); // Increment msgSize for next loop auto tmpSize = (msgSize * (100 + deltaMsgSize)) / 100; tmpSize -= tmpSize % minDeltaMsgSize; if(tmpSize - msgSize < minDeltaMsgSize) { tmpSize = msgSize + minDeltaMsgSize; } if(tmpSize - msgSize > maxDeltaMsgSize) { tmpSize = msgSize + maxDeltaMsgSize; } msgSize = tmpSize; } finalize(); }
Correct num threads output
Correct num threads output
C++
apache-2.0
pjgeorg/pMR,pjgeorg/pMR,pjgeorg/pMR
2b309aa07b31f0ec27a8f6e6db46ec0b859402b2
highwayhash/data_parallel_benchmark.cc
highwayhash/data_parallel_benchmark.cc
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cmath> #include <cstdio> #include <future> //NOLINT #include <set> #include "testing/base/public/gunit.h" #include "third_party/absl/time/clock.h" #include "highwayhash/arch_specific.h" #include "highwayhash/data_parallel.h" #include "thread/threadpool.h" namespace highwayhash { namespace { constexpr int kBenchmarkTasks = 1000000; // Returns elapsed time [nanoseconds] for std::async. double BenchmarkAsync(uint64_t* total) { const base::Time t0 = absl::Now(); std::atomic<uint64_t> sum1{0}; std::atomic<uint64_t> sum2{0}; std::vector<std::future<void>> futures; futures.reserve(kBenchmarkTasks); for (int i = 0; i < kBenchmarkTasks; ++i) { futures.push_back(std::async( [&sum1, &sum2](const int i) { sum1.fetch_add(i); sum2.fetch_add(1); }, i)); } for (auto& future : futures) { future.get(); } const base::Time t1 = absl::Now(); *total = sum1.load() + sum2.load(); return base::ToDoubleNanoseconds(t1 - t0); } // Returns elapsed time [nanoseconds] for (atomic) ThreadPool. double BenchmarkPoolA(uint64_t* total) { const base::Time t0 = absl::Now(); std::atomic<uint64_t> sum1{0}; std::atomic<uint64_t> sum2{0}; ThreadPool pool; pool.Run(0, kBenchmarkTasks, [&sum1, &sum2](const int i) { sum1.fetch_add(i); sum2.fetch_add(1); }); const base::Time t1 = absl::Now(); *total = sum1.load() + sum2.load(); return base::ToDoubleNanoseconds(t1 - t0); } // Returns elapsed time [nanoseconds] for ::ThreadPool. double BenchmarkPoolG(uint64_t* total) { const base::Time t0 = absl::Now(); std::atomic<uint64_t> sum1{0}; std::atomic<uint64_t> sum2{0}; { ::ThreadPool pool(std::thread::hardware_concurrency()); pool.StartWorkers(); for (int i = 0; i < kBenchmarkTasks; ++i) { pool.Schedule([&sum1, &sum2, i]() { sum1.fetch_add(i); sum2.fetch_add(1); }); } } const base::Time t1 = absl::Now(); *total = sum1.load() + sum2.load(); return base::ToDoubleNanoseconds(t1 - t0); } // Compares ThreadPool speed to std::async and ::ThreadPool. TEST(DataParallelTest, Benchmarks) { uint64_t sum1, sum2, sum3; const double async_ns = BenchmarkAsync(&sum1); const double poolA_ns = BenchmarkPoolA(&sum2); const double poolG_ns = BenchmarkPoolG(&sum3); printf("Async %11.0f ns\nPoolA %11.0f ns\nPoolG %11.0f ns\n", async_ns, poolA_ns, poolG_ns); // baseline 20x, 10x with asan or msan, 5x with tsan EXPECT_GT(async_ns, poolA_ns * 4); // baseline 200x, 180x with asan, 70x with msan, 50x with tsan. EXPECT_GT(poolG_ns, poolA_ns * 20); // Should reach same result. EXPECT_EQ(sum1, sum2); EXPECT_EQ(sum2, sum3); } // Ensures multiple hardware threads are used (decided by the OS scheduler). TEST(DataParallelTest, TestApicIds) { for (int num_threads = 1; num_threads <= std::thread::hardware_concurrency(); ++num_threads) { ThreadPool pool(num_threads); std::mutex mutex; std::set<unsigned> ids; double total = 0.0; pool.Run(0, 2 * num_threads, [&mutex, &ids, &total](const int i) { // Useless computations to keep the processor busy so that threads // can't just reuse the same processor. double sum = 0.0; for (int rep = 0; rep < 900 * (i + 30); ++rep) { sum += pow(rep, 0.5); } mutex.lock(); ids.insert(ApicId()); total += sum; mutex.unlock(); }); // No core ID / APIC ID available if (num_threads > 1 && ids.size() == 1) { EXPECT_EQ(0, *ids.begin()); } else { // (The Linux scheduler doesn't use all available HTs, but the // computations should at least keep most cores busy.) EXPECT_GT(ids.size() + 2, num_threads / 4); } // (Ensure the busy-work is not elided.) EXPECT_GT(total, 1E4); } } } // namespace } // namespace highwayhash
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cmath> #include <cstdio> #include <future> //NOLINT #include <set> #include "testing/base/public/gunit.h" #include "third_party/absl/time/clock.h" #include "third_party/absl/time/time.h" #include "highwayhash/arch_specific.h" #include "highwayhash/data_parallel.h" #include "thread/threadpool.h" namespace highwayhash { namespace { constexpr int kBenchmarkTasks = 1000000; // Returns elapsed time [nanoseconds] for std::async. double BenchmarkAsync(uint64_t* total) { const absl::Time t0 = absl::Now(); std::atomic<uint64_t> sum1{0}; std::atomic<uint64_t> sum2{0}; std::vector<std::future<void>> futures; futures.reserve(kBenchmarkTasks); for (int i = 0; i < kBenchmarkTasks; ++i) { futures.push_back(std::async( [&sum1, &sum2](const int i) { sum1.fetch_add(i); sum2.fetch_add(1); }, i)); } for (auto& future : futures) { future.get(); } const absl::Time t1 = absl::Now(); *total = sum1.load() + sum2.load(); return absl::ToDoubleNanoseconds(t1 - t0); } // Returns elapsed time [nanoseconds] for (atomic) ThreadPool. double BenchmarkPoolA(uint64_t* total) { const absl::Time t0 = absl::Now(); std::atomic<uint64_t> sum1{0}; std::atomic<uint64_t> sum2{0}; ThreadPool pool; pool.Run(0, kBenchmarkTasks, [&sum1, &sum2](const int i) { sum1.fetch_add(i); sum2.fetch_add(1); }); const absl::Time t1 = absl::Now(); *total = sum1.load() + sum2.load(); return absl::ToDoubleNanoseconds(t1 - t0); } // Returns elapsed time [nanoseconds] for ::ThreadPool. double BenchmarkPoolG(uint64_t* total) { const absl::Time t0 = absl::Now(); std::atomic<uint64_t> sum1{0}; std::atomic<uint64_t> sum2{0}; { ::ThreadPool pool(std::thread::hardware_concurrency()); pool.StartWorkers(); for (int i = 0; i < kBenchmarkTasks; ++i) { pool.Schedule([&sum1, &sum2, i]() { sum1.fetch_add(i); sum2.fetch_add(1); }); } } const absl::Time t1 = absl::Now(); *total = sum1.load() + sum2.load(); return absl::ToDoubleNanoseconds(t1 - t0); } // Compares ThreadPool speed to std::async and ::ThreadPool. TEST(DataParallelTest, Benchmarks) { uint64_t sum1, sum2, sum3; const double async_ns = BenchmarkAsync(&sum1); const double poolA_ns = BenchmarkPoolA(&sum2); const double poolG_ns = BenchmarkPoolG(&sum3); printf("Async %11.0f ns\nPoolA %11.0f ns\nPoolG %11.0f ns\n", async_ns, poolA_ns, poolG_ns); // baseline 20x, 10x with asan or msan, 5x with tsan EXPECT_GT(async_ns, poolA_ns * 4); // baseline 200x, 180x with asan, 70x with msan, 50x with tsan. EXPECT_GT(poolG_ns, poolA_ns * 20); // Should reach same result. EXPECT_EQ(sum1, sum2); EXPECT_EQ(sum2, sum3); } // Ensures multiple hardware threads are used (decided by the OS scheduler). TEST(DataParallelTest, TestApicIds) { for (int num_threads = 1; num_threads <= std::thread::hardware_concurrency(); ++num_threads) { ThreadPool pool(num_threads); std::mutex mutex; std::set<unsigned> ids; double total = 0.0; pool.Run(0, 2 * num_threads, [&mutex, &ids, &total](const int i) { // Useless computations to keep the processor busy so that threads // can't just reuse the same processor. double sum = 0.0; for (int rep = 0; rep < 900 * (i + 30); ++rep) { sum += pow(rep, 0.5); } mutex.lock(); ids.insert(ApicId()); total += sum; mutex.unlock(); }); // No core ID / APIC ID available if (num_threads > 1 && ids.size() == 1) { EXPECT_EQ(0, *ids.begin()); } else { // (The Linux scheduler doesn't use all available HTs, but the // computations should at least keep most cores busy.) EXPECT_GT(ids.size() + 2, num_threads / 4); } // (Ensure the busy-work is not elided.) EXPECT_GT(total, 1E4); } } } // namespace } // namespace highwayhash
Update timer to absl
Update timer to absl
C++
apache-2.0
google/highwayhash,google/highwayhash,google/highwayhash,google/highwayhash
a3fefe42ce338077a894f3095324ac41da6ef8e4
himan-plugins/source/hybrid_height.cpp
himan-plugins/source/hybrid_height.cpp
/** * @file hybrid_height.cpp * * @date Apr 5, 2013 * @author peramaki */ #include "hybrid_height.h" #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #include <boost/thread.hpp> #define HIMAN_AUXILIARY_INCLUDE #include "neons.h" #include "radon.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace std; using namespace himan::plugin; const string itsName("hybrid_height"); const himan::param ZParam("Z-M2S2"); const himan::params GPParam { himan::param("LNSP-N") , himan::param("P-PA") }; const himan::param PParam("P-HPA"); const himan::param TParam("T-K"); const himan::param TGParam("TG-K"); hybrid_height::hybrid_height() { itsClearTextFormula = "HEIGHT = prevH + (287/9.81) * (T+prevT)/2 * log(prevP / P)"; itsLogger = logger_factory::Instance()->GetLog(itsName); } void hybrid_height::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * For hybrid height we must go through the levels backwards. */ itsInfo->LevelOrder(kBottomToTop); HPDatabaseType dbtype = conf->DatabaseType(); if (dbtype == kNeons || dbtype == kNeonsAndRadon) { auto n = GET_PLUGIN(neons); itsBottomLevel = boost::lexical_cast<int> (n->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "last hybrid level number")); } if ((dbtype == kRadon || dbtype == kNeonsAndRadon) && itsBottomLevel == kHPMissingInt) { auto r = GET_PLUGIN(radon); itsBottomLevel = boost::lexical_cast<int> (r->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "last hybrid level number")); } itsUseGeopotential = (itsConfiguration->SourceProducer().Id() == 1 || itsConfiguration->SourceProducer().Id() == 199); PrimaryDimension(kTimeDimension); SetParams({param("HL-M", 3, 0, 3, 6)}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void hybrid_height::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { auto myThreadedLogger = logger_factory::Instance()->GetLog(itsName + "Thread #" + boost::lexical_cast<string> (threadIndex)); myThreadedLogger->Info("Calculating time " + static_cast<string>(myTargetInfo->Time().ValidDateTime()) + " level " + static_cast<string> (myTargetInfo->Level())); if (itsUseGeopotential) { bool ret = WithGeopotential(myTargetInfo); if (!ret) { myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + static_cast<string> (myTargetInfo->Level())); return; } } else { bool ret = WithIteration(myTargetInfo); if (!ret) { myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + static_cast<string> (myTargetInfo->Level())); return; } } string deviceType = "CPU"; myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data().Size())); } bool hybrid_height::WithGeopotential(info_t& myTargetInfo) { himan::level H0(himan::kHeight, 0); if ( itsConfiguration->SourceProducer().Id() == 131) { H0 = level(himan::kHybrid, 1, "LNSP"); } auto GPInfo = Fetch(myTargetInfo->Time(), myTargetInfo->Level(), ZParam, myTargetInfo->ForecastType(), false); auto zeroGPInfo = Fetch(myTargetInfo->Time(), H0, ZParam, myTargetInfo->ForecastType(), false); if (!GPInfo || !zeroGPInfo) { return false; } SetAB(myTargetInfo, GPInfo); LOCKSTEP(myTargetInfo, GPInfo, zeroGPInfo) { double GP = GPInfo->Value(); double zeroGP = zeroGPInfo->Value(); if (GP == kFloatMissing || zeroGP == kFloatMissing) { continue; } double height = (GP - zeroGP) * himan::constants::kIg; myTargetInfo->Value(height); } return true; } bool hybrid_height::WithIteration(info_t& myTargetInfo) { himan::level H0(himan::kHeight, 0); himan::level H2(himan::kHeight, 2); if ( itsConfiguration->SourceProducer().Id() == 131) { H2 = level(himan::kHybrid, 137, "GROUND"); H0 = level(himan::kHybrid, 1, "LNSP"); } const auto forecastTime = myTargetInfo->Time(); const auto forecastType = myTargetInfo->ForecastType(); level prevLevel; bool firstLevel = false; if (myTargetInfo->Level().Value() == itsBottomLevel) { firstLevel = true; } else { prevLevel = level(myTargetInfo->Level()); prevLevel.Value(myTargetInfo->Level().Value() + 1); prevLevel.Index(prevLevel.Index() + 1); } info_t prevTInfo, prevPInfo, prevHInfo; if (!firstLevel) { prevTInfo = Fetch(forecastTime, prevLevel, TParam, forecastType, false); prevPInfo = Fetch(forecastTime, prevLevel, PParam, forecastType, false); prevHInfo = Fetch(forecastTime, prevLevel, param("HL-M"), forecastType, false); } else { if ( itsConfiguration->SourceProducer().Id() == 131 ) { prevPInfo = Fetch(forecastTime, H0, GPParam, forecastType, false); prevTInfo = Fetch(forecastTime, H2, TParam, forecastType, false); } else { prevPInfo = Fetch(forecastTime, H0, GPParam, forecastType, false); prevTInfo = Fetch(forecastTime, H2, TGParam, forecastType, false); } } auto PInfo = Fetch(forecastTime, myTargetInfo->Level(), PParam, forecastType, false); auto TInfo = Fetch(forecastTime, myTargetInfo->Level(), TParam, forecastType, false); if (!prevTInfo || !prevPInfo || ( !prevHInfo && !firstLevel ) || !PInfo || !TInfo) { return false; } SetAB(myTargetInfo, TInfo); if (!firstLevel) { prevHInfo->ResetLocation(); assert(prevLevel.Value() > myTargetInfo->Level().Value()); } LOCKSTEP(myTargetInfo, PInfo, prevPInfo, TInfo, prevTInfo) { double T = TInfo->Value(); double P = PInfo->Value(); double prevT = prevTInfo->Value(); double prevP = prevPInfo->Value(); double prevH = kFloatMissing; if (!firstLevel) { prevHInfo->NextLocation(); prevH = prevHInfo->Value(); } else { prevH = 0; } if (prevT == kFloatMissing || prevP == kFloatMissing || T == kFloatMissing || P == kFloatMissing || prevH == kFloatMissing) { continue; } if (firstLevel) { if ( itsConfiguration->SourceProducer().Id() == 131 ) { // LNSP to regular pressure prevP = exp (prevP) * 0.01f; } else { prevP *= 0.01f; } } double deltaZ = 14.628 * (prevT + T) * log(prevP/P); double totalHeight = prevH + deltaZ; myTargetInfo->Value(totalHeight); } return true; }
/** * @file hybrid_height.cpp * * @date Apr 5, 2013 * @author peramaki */ #include "hybrid_height.h" #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #include <boost/thread.hpp> #define HIMAN_AUXILIARY_INCLUDE #include "neons.h" #include "radon.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace std; using namespace himan::plugin; const string itsName("hybrid_height"); const himan::param ZParam("Z-M2S2"); const himan::params GPParam { himan::param("LNSP-N") , himan::param("P-PA") }; const himan::param PParam("P-HPA"); const himan::param TParam("T-K"); const himan::param TGParam("TG-K"); hybrid_height::hybrid_height() : itsBottomLevel(kHPMissingInt) { itsClearTextFormula = "HEIGHT = prevH + (287/9.81) * (T+prevT)/2 * log(prevP / P)"; itsLogger = logger_factory::Instance()->GetLog(itsName); } void hybrid_height::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * For hybrid height we must go through the levels backwards. */ itsInfo->LevelOrder(kBottomToTop); HPDatabaseType dbtype = conf->DatabaseType(); if (dbtype == kNeons || dbtype == kNeonsAndRadon) { auto n = GET_PLUGIN(neons); itsBottomLevel = boost::lexical_cast<int> (n->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "last hybrid level number")); } if ((dbtype == kRadon || dbtype == kNeonsAndRadon) && itsBottomLevel == kHPMissingInt) { auto r = GET_PLUGIN(radon); itsBottomLevel = boost::lexical_cast<int> (r->ProducerMetaData(itsConfiguration->SourceProducer().Id(), "last hybrid level number")); } itsUseGeopotential = (itsConfiguration->SourceProducer().Id() == 1 || itsConfiguration->SourceProducer().Id() == 199); PrimaryDimension(kTimeDimension); SetParams({param("HL-M", 3, 0, 3, 6)}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void hybrid_height::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { auto myThreadedLogger = logger_factory::Instance()->GetLog(itsName + "Thread #" + boost::lexical_cast<string> (threadIndex)); myThreadedLogger->Info("Calculating time " + static_cast<string>(myTargetInfo->Time().ValidDateTime()) + " level " + static_cast<string> (myTargetInfo->Level())); if (itsUseGeopotential) { bool ret = WithGeopotential(myTargetInfo); if (!ret) { myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + static_cast<string> (myTargetInfo->Level())); return; } } else { bool ret = WithIteration(myTargetInfo); if (!ret) { myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + static_cast<string> (myTargetInfo->Level())); return; } } string deviceType = "CPU"; myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data().Size())); } bool hybrid_height::WithGeopotential(info_t& myTargetInfo) { himan::level H0(himan::kHeight, 0); if ( itsConfiguration->SourceProducer().Id() == 131) { H0 = level(himan::kHybrid, 1, "LNSP"); } auto GPInfo = Fetch(myTargetInfo->Time(), myTargetInfo->Level(), ZParam, myTargetInfo->ForecastType(), false); auto zeroGPInfo = Fetch(myTargetInfo->Time(), H0, ZParam, myTargetInfo->ForecastType(), false); if (!GPInfo || !zeroGPInfo) { return false; } SetAB(myTargetInfo, GPInfo); LOCKSTEP(myTargetInfo, GPInfo, zeroGPInfo) { double GP = GPInfo->Value(); double zeroGP = zeroGPInfo->Value(); if (GP == kFloatMissing || zeroGP == kFloatMissing) { continue; } double height = (GP - zeroGP) * himan::constants::kIg; myTargetInfo->Value(height); } return true; } bool hybrid_height::WithIteration(info_t& myTargetInfo) { himan::level H0(himan::kHeight, 0); himan::level H2(himan::kHeight, 2); if ( itsConfiguration->SourceProducer().Id() == 131) { H2 = level(himan::kHybrid, 137, "GROUND"); H0 = level(himan::kHybrid, 1, "LNSP"); } const auto forecastTime = myTargetInfo->Time(); const auto forecastType = myTargetInfo->ForecastType(); level prevLevel; bool firstLevel = false; if (myTargetInfo->Level().Value() == itsBottomLevel) { firstLevel = true; } else { prevLevel = level(myTargetInfo->Level()); prevLevel.Value(myTargetInfo->Level().Value() + 1); prevLevel.Index(prevLevel.Index() + 1); } info_t prevTInfo, prevPInfo, prevHInfo; if (!firstLevel) { prevTInfo = Fetch(forecastTime, prevLevel, TParam, forecastType, false); prevPInfo = Fetch(forecastTime, prevLevel, PParam, forecastType, false); prevHInfo = Fetch(forecastTime, prevLevel, param("HL-M"), forecastType, false); } else { if ( itsConfiguration->SourceProducer().Id() == 131 ) { prevPInfo = Fetch(forecastTime, H0, GPParam, forecastType, false); prevTInfo = Fetch(forecastTime, H2, TParam, forecastType, false); } else { prevPInfo = Fetch(forecastTime, H0, GPParam, forecastType, false); prevTInfo = Fetch(forecastTime, H2, TGParam, forecastType, false); } } auto PInfo = Fetch(forecastTime, myTargetInfo->Level(), PParam, forecastType, false); auto TInfo = Fetch(forecastTime, myTargetInfo->Level(), TParam, forecastType, false); if (!prevTInfo || !prevPInfo || ( !prevHInfo && !firstLevel ) || !PInfo || !TInfo) { return false; } SetAB(myTargetInfo, TInfo); if (!firstLevel) { prevHInfo->ResetLocation(); assert(prevLevel.Value() > myTargetInfo->Level().Value()); } LOCKSTEP(myTargetInfo, PInfo, prevPInfo, TInfo, prevTInfo) { double T = TInfo->Value(); double P = PInfo->Value(); double prevT = prevTInfo->Value(); double prevP = prevPInfo->Value(); double prevH = kFloatMissing; if (!firstLevel) { prevHInfo->NextLocation(); prevH = prevHInfo->Value(); } else { prevH = 0; } if (prevT == kFloatMissing || prevP == kFloatMissing || T == kFloatMissing || P == kFloatMissing || prevH == kFloatMissing) { continue; } if (firstLevel) { if ( itsConfiguration->SourceProducer().Id() == 131 ) { // LNSP to regular pressure prevP = exp (prevP) * 0.01f; } else { prevP *= 0.01f; } } double deltaZ = 14.628 * (prevT + T) * log(prevP/P); double totalHeight = prevH + deltaZ; myTargetInfo->Value(totalHeight); } return true; }
initialize variable itsBottomLevel
initialize variable itsBottomLevel
C++
mit
fmidev/himan,fmidev/himan,fmidev/himan
8e40489e8b5558d7bfecfc8f62445f626dfbe26e
himan-plugins/source/monin_obukhov.cpp
himan-plugins/source/monin_obukhov.cpp
/** * @file monin_obukhov.cpp * * Claculates the inverse of the Monin-Obukhov length. * */ #include <boost/lexical_cast.hpp> #include "forecast_time.h" #include "level.h" #include "logger_factory.h" #include "monin_obukhov.h" using namespace std; using namespace himan::plugin; monin_obukhov::monin_obukhov() { itsClearTextFormula = "1/L = -(k*g*Q)/(rho*cp*u*^3*T)"; itsLogger = logger_factory::Instance()->GetLog("monin_obukhov"); } void monin_obukhov::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter properties * - name PARM_NAME, this name is found from neons. For example: T-K * - univ_id UNIV_ID, newbase-id, ie code table 204 * - grib1 id must be in database * - grib2 descriptor X'Y'Z, http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table4-2.shtml * */ param theRequestedParam("MOL-M", 1204); // If this param is also used as a source param for other calculations SetParams({theRequestedParam}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void monin_obukhov::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { /* * Required source parameters * * eg. param PParam("P-Pa"); for pressure in pascals * */ const param TParam("T-K"); // ground Temperature const param SHFParam("FLSEN-JM2"); // accumulated surface sensible heat flux const param LHFParam("FLLAT-JM2"); // accumulated surface latent heat flux const param U_SParam("FRVEL-MS"); // friction velocity const param PParam("P-PA"); // ---- auto myThreadedLogger = logger_factory::Instance()->GetLog("monin_obukhov Thread #" + boost::lexical_cast<string>(threadIndex)); // Prev/current time and level int paramStep = 1; // myTargetInfo->Param().Aggregation().TimeResolutionValue(); HPTimeResolution timeResolution = myTargetInfo->Time().StepResolution(); forecast_time forecastTime = myTargetInfo->Time(); forecast_time forecastTimePrev = myTargetInfo->Time(); forecastTimePrev.ValidDateTime().Adjust(timeResolution, -paramStep); forecast_type forecastType = myTargetInfo->ForecastType(); level forecastLevel = level(himan::kHeight, 0, "Height"); myThreadedLogger->Debug("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " + static_cast<string>(forecastLevel)); info_t TInfo = Fetch(forecastTime, forecastLevel, TParam, forecastType, false); info_t SHFInfo = Fetch(forecastTime, forecastLevel, SHFParam, forecastType, false); info_t PrevSHFInfo = Fetch(forecastTimePrev, forecastLevel, SHFParam, forecastType, false); info_t LHFInfo = Fetch(forecastTime, forecastLevel, LHFParam, forecastType, false); info_t PrevLHFInfo = Fetch(forecastTimePrev, forecastLevel, LHFParam, forecastType, false); info_t U_SInfo = Fetch(forecastTime, forecastLevel, U_SParam, forecastType, false); info_t PInfo = Fetch(forecastTime, forecastLevel, PParam, forecastType, false); // determine length of forecast step to calculate surface heat flux in W/m2 double forecastStepSize; if (itsConfiguration->SourceProducer().Id() != 199) { forecastStepSize = itsConfiguration->ForecastStep() * 3600; // step size in seconds } else { forecastStepSize = itsConfiguration->ForecastStep() * 60; // step size in seconds } if (!TInfo || !SHFInfo || !U_SInfo || !PInfo || !PrevSHFInfo || !LHFInfo || !PrevLHFInfo) { myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string>(forecastTime.Step()) + ", level " + static_cast<string>(forecastLevel)); return; } string deviceType = "CPU"; LOCKSTEP(myTargetInfo, TInfo, SHFInfo, PrevSHFInfo, LHFInfo, PrevLHFInfo, U_SInfo, PInfo) { double T = TInfo->Value(); double SHF = SHFInfo->Value() - PrevSHFInfo->Value(); double LHF = LHFInfo->Value() - PrevLHFInfo->Value(); double U_S = U_SInfo->Value(); double P = PInfo->Value(); double T_C = T - constants::kKelvin; // Convert Temperature to Celvins double mol(kFloatMissing); if (T == kFloatMissing || SHF == kFloatMissing || LHF == kFloatMissing || U_S == kFloatMissing || P == kFloatMissing) { continue; } SHF /= forecastStepSize; // divide by time step to obtain Watts/m2 LHF /= forecastStepSize; // divide by time step to obtain Watts/m2 /* Calculation of the inverse of Monin-Obukhov length to avoid division by 0 */ if (U_S != 0.0) { double rho = P / (constants::kRd * T); // Calculate density double cp = 1.0056e3 + 0.017766 * T_C + 4.0501e-4 * pow(T_C, 2) - 1.017e-6 * pow(T_C, 3) + 1.4715e-8 * pow(T_C, 4) - 7.4022e-11 * pow(T_C, 5) + 1.2521e-13 * pow(T_C, 6); // Calculate specific heat capacity mol = -constants::kG * constants::kK * (SHF + 0.07 * LHF) / (rho * cp * U_S * U_S * U_S * T); } myTargetInfo->Value(mol); } myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string>(myTargetInfo->Data().Size())); }
/** * @file monin_obukhov.cpp * * Claculates the inverse of the Monin-Obukhov length. * */ #include <boost/lexical_cast.hpp> #include "forecast_time.h" #include "level.h" #include "logger_factory.h" #include "monin_obukhov.h" #include "metutil.h" using namespace std; using namespace himan::plugin; monin_obukhov::monin_obukhov() { itsClearTextFormula = "1/L = -(k*g*Q)/(rho*cp*u*^3*T)"; itsLogger = logger_factory::Instance()->GetLog("monin_obukhov"); } void monin_obukhov::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter properties * - name PARM_NAME, this name is found from neons. For example: T-K * - univ_id UNIV_ID, newbase-id, ie code table 204 * - grib1 id must be in database * - grib2 descriptor X'Y'Z, http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table4-2.shtml * */ param theRequestedParam("MOL-M", 1204); // If this param is also used as a source param for other calculations SetParams({theRequestedParam}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void monin_obukhov::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { /* * Required source parameters * * eg. param PParam("P-Pa"); for pressure in pascals * */ const param TParam("T-K"); // ground Temperature const param SHFParam("FLSEN-JM2"); // accumulated surface sensible heat flux const param LHFParam("FLLAT-JM2"); // accumulated surface latent heat flux const param U_SParam("FRVEL-MS"); // friction velocity const param PParam("P-PA"); // ---- auto myThreadedLogger = logger_factory::Instance()->GetLog("monin_obukhov Thread #" + boost::lexical_cast<string>(threadIndex)); // Prev/current time and level int paramStep = 1; // myTargetInfo->Param().Aggregation().TimeResolutionValue(); HPTimeResolution timeResolution = myTargetInfo->Time().StepResolution(); forecast_time forecastTime = myTargetInfo->Time(); forecast_time forecastTimePrev = myTargetInfo->Time(); forecastTimePrev.ValidDateTime().Adjust(timeResolution, -paramStep); forecast_type forecastType = myTargetInfo->ForecastType(); level forecastLevel = level(himan::kHeight, 0, "Height"); myThreadedLogger->Debug("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " + static_cast<string>(forecastLevel)); info_t TInfo = Fetch(forecastTime, forecastLevel, TParam, forecastType, false); info_t SHFInfo = Fetch(forecastTime, forecastLevel, SHFParam, forecastType, false); info_t PrevSHFInfo = Fetch(forecastTimePrev, forecastLevel, SHFParam, forecastType, false); info_t LHFInfo = Fetch(forecastTime, forecastLevel, LHFParam, forecastType, false); info_t PrevLHFInfo = Fetch(forecastTimePrev, forecastLevel, LHFParam, forecastType, false); info_t U_SInfo = Fetch(forecastTime, forecastLevel, U_SParam, forecastType, false); info_t PInfo = Fetch(forecastTime, forecastLevel, PParam, forecastType, false); // determine length of forecast step to calculate surface heat flux in W/m2 double forecastStepSize; if (itsConfiguration->SourceProducer().Id() != 199) { forecastStepSize = itsConfiguration->ForecastStep() * 3600; // step size in seconds } else { forecastStepSize = itsConfiguration->ForecastStep() * 60; // step size in seconds } if (!TInfo || !SHFInfo || !U_SInfo || !PInfo || !PrevSHFInfo || !LHFInfo || !PrevLHFInfo) { myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string>(forecastTime.Step()) + ", level " + static_cast<string>(forecastLevel)); return; } string deviceType = "CPU"; LOCKSTEP(myTargetInfo, TInfo, SHFInfo, PrevSHFInfo, LHFInfo, PrevLHFInfo, U_SInfo, PInfo) { double T = TInfo->Value(); double SHF = SHFInfo->Value() - PrevSHFInfo->Value(); double LHF = LHFInfo->Value() - PrevLHFInfo->Value(); double U_S = U_SInfo->Value(); double P = PInfo->Value(); double T_C = T - constants::kKelvin; // Convert Temperature to Celvins double mol(kFloatMissing); if (T == kFloatMissing || SHF == kFloatMissing || LHF == kFloatMissing || U_S == kFloatMissing || P == kFloatMissing) { continue; } SHF /= forecastStepSize; // divide by time step to obtain Watts/m2 LHF /= forecastStepSize; // divide by time step to obtain Watts/m2 /* Calculation of the inverse of Monin-Obukhov length to avoid division by 0 */ if (U_S != 0.0) { double rho = P / (constants::kRd * T); // Calculate density double cp = 1.0056e3 + 0.017766 * T_C + 4.0501e-4 * pow(T_C, 2) - 1.017e-6 * pow(T_C, 3) + 1.4715e-8 * pow(T_C, 4) - 7.4022e-11 * pow(T_C, 5) + 1.2521e-13 * pow(T_C, 6); // Calculate specific heat capacity double L = 2500800.0 - 2360.0 * T_C + 1.6 * pow(T_C, 2) - 0.06 * pow(T_C, 3); // Calculate specific latent heat of condensation of water mol = -constants::kG * constants::kK * (SHF + 0.61 * cp * T / L * LHF) / (rho * cp * U_S * U_S * U_S * himan::metutil::VirtualTemperature_(T,P)); } myTargetInfo->Value(mol); } myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string>(myTargetInfo->Data().Size())); }
fix temperature in MOL to virtual temperature, and clarify calculation of 0.007 factor for LHF.
fix temperature in MOL to virtual temperature, and clarify calculation of 0.007 factor for LHF.
C++
mit
fmidev/himan,fmidev/himan,fmidev/himan
6f16d41c5a901fcef140e19f872c8f9b1ef3b0d4
modules/perception/obstacle/radar/modest/object_builder.cc
modules/perception/obstacle/radar/modest/object_builder.cc
/****************************************************************************** * Copyright 2017 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/perception/obstacle/radar/modest/object_builder.h" #include <cmath> #include <map> #include "modules/common/log.h" #include "modules/perception/obstacle/radar/modest/conti_radar_util.h" #include "modules/perception/obstacle/radar/modest/radar_util.h" namespace apollo { namespace perception { void ObjectBuilder::Build(const ContiRadar &raw_obstacles, const Eigen::Matrix4d &radar_pose, const Eigen::Vector2d &main_velocity, SensorObjects *radar_objects) { if (radar_objects == nullptr) { AERROR << "radar objects is nullptr."; return; } std::map<int, int> current_con_ids; auto objects = &(radar_objects->objects); for (int i = 0; i < raw_obstacles.contiobs_size(); i++) { ObjectPtr object_ptr = ObjectPtr(new Object()); int obstacle_id = raw_obstacles.contiobs(i).obstacle_id(); std::map<int, int>::iterator continuous_id_it = continuous_ids_.find(obstacle_id); if (continuous_id_it != continuous_ids_.end()) { current_con_ids[obstacle_id] = continuous_id_it->second + 1; } else { current_con_ids[obstacle_id] = 1; } if (current_con_ids[obstacle_id] <= delay_frames_) { object_ptr->is_background = true; } int tracking_times = current_con_ids[obstacle_id]; if (use_fp_filter_ && ContiRadarUtil::IsFp(raw_obstacles.contiobs(i), conti_params_, delay_frames_, tracking_times)) { object_ptr->is_background = true; } object_ptr->track_id = obstacle_id; Eigen::Matrix<double, 4, 1> location_r; Eigen::Matrix<double, 4, 1> location_w; location_r << raw_obstacles.contiobs(i).longitude_dist(), raw_obstacles.contiobs(i).lateral_dist(), 0.0, 1.0; location_w = radar_pose * location_r; Eigen::Vector3d point; point = location_w.topLeftCorner(3, 1); object_ptr->center = point; object_ptr->anchor_point = object_ptr->center; Eigen::Matrix<double, 3, 1> velocity_r; Eigen::Matrix<double, 3, 1> velocity_w; velocity_r << raw_obstacles.contiobs(i).longitude_vel(), raw_obstacles.contiobs(i).lateral_vel(), 0.0; velocity_w = radar_pose.topLeftCorner(3, 3) * velocity_r; Eigen::Vector3f ref_velocity(main_velocity(0), main_velocity(1), 0.0); if (ContiRadarUtil::IsConflict(ref_velocity, velocity_w.cast<float>())) { object_ptr->is_background = true; } // calculate the absolute velodity object_ptr->velocity(0) = velocity_w[0] + main_velocity(0); object_ptr->velocity(1) = velocity_w[1] + main_velocity(1); object_ptr->velocity(2) = 0; object_ptr->length = 1.0; object_ptr->width = 1.0; object_ptr->height = 1.0; object_ptr->type = UNKNOWN; Eigen::Matrix3d dist_rms; Eigen::Matrix3d vel_rms; vel_rms.setZero(); dist_rms.setZero(); dist_rms(0, 0) = raw_obstacles.contiobs(i).longitude_dist_rms(); dist_rms(1, 1) = raw_obstacles.contiobs(i).lateral_dist_rms(); vel_rms(0, 0) = raw_obstacles.contiobs(i).longitude_vel_rms(); vel_rms(1, 1) = raw_obstacles.contiobs(i).lateral_vel_rms(); object_ptr->position_uncertainty = radar_pose.topLeftCorner(3, 3) * dist_rms * dist_rms.transpose() * radar_pose.topLeftCorner(3, 3).transpose(); object_ptr->velocity_uncertainty = radar_pose.topLeftCorner(3, 3) * vel_rms * vel_rms.transpose() * radar_pose.topLeftCorner(3, 3).transpose(); double local_theta = raw_obstacles.contiobs(i).oritation_angle() / 180.0 * M_PI; Eigen::Vector3f direction = Eigen::Vector3f(cos(local_theta), sin(local_theta), 0); direction = radar_pose.topLeftCorner(3, 3).cast<float>() * direction; object_ptr->direction = direction.cast<double>(); // the avg time diff is from manual object_ptr->tracking_time = current_con_ids[obstacle_id] * 0.074; double theta = std::atan2(direction(1), direction(0)); object_ptr->theta = theta; // For radar obstacle , the polygon is supposed to have // four mock point: around obstacle center. RadarUtil::MockRadarPolygon(point, object_ptr->length, object_ptr->width, theta, &(object_ptr->polygon)); if (object_ptr->radar_supplement == nullptr) { object_ptr->radar_supplement.reset(new RadarSupplement()); } object_ptr->radar_supplement->range = std::sqrt( location_r[0] * location_r[0] + location_r[1] * location_r[1]); object_ptr->radar_supplement->angle = 0; objects->push_back(object_ptr); } continuous_ids_ = current_con_ids; } } // namespace perception } // namespace apollo
/****************************************************************************** * Copyright 2017 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/perception/obstacle/radar/modest/object_builder.h" #include <cmath> #include <map> #include "modules/common/log.h" #include "modules/perception/obstacle/radar/modest/conti_radar_util.h" #include "modules/perception/obstacle/radar/modest/radar_util.h" namespace apollo { namespace perception { void ObjectBuilder::Build(const ContiRadar &raw_obstacles, const Eigen::Matrix4d &radar_pose, const Eigen::Vector2d &main_velocity, SensorObjects *radar_objects) { if (radar_objects == nullptr) { AERROR << "radar objects is nullptr."; return; } std::map<int, int> current_con_ids; auto objects = &(radar_objects->objects); for (int i = 0; i < raw_obstacles.contiobs_size(); i++) { ObjectPtr object_ptr = ObjectPtr(new Object()); int obstacle_id = raw_obstacles.contiobs(i).obstacle_id(); std::map<int, int>::iterator continuous_id_it = continuous_ids_.find(obstacle_id); if (continuous_id_it != continuous_ids_.end()) { current_con_ids[obstacle_id] = continuous_id_it->second + 1; } else { current_con_ids[obstacle_id] = 1; } if (current_con_ids[obstacle_id] <= delay_frames_) { object_ptr->is_background = true; } int tracking_times = current_con_ids[obstacle_id]; if (use_fp_filter_ && ContiRadarUtil::IsFp(raw_obstacles.contiobs(i), conti_params_, delay_frames_, tracking_times)) { object_ptr->is_background = true; } object_ptr->track_id = obstacle_id; Eigen::Matrix<double, 4, 1> location_r; Eigen::Matrix<double, 4, 1> location_w; location_r << raw_obstacles.contiobs(i).longitude_dist(), raw_obstacles.contiobs(i).lateral_dist(), 0.0, 1.0; location_w = radar_pose * location_r; Eigen::Vector3d point; point = location_w.topLeftCorner(3, 1); object_ptr->center = point; object_ptr->anchor_point = object_ptr->center; Eigen::Matrix<double, 3, 1> velocity_r; Eigen::Matrix<double, 3, 1> velocity_w; velocity_r << raw_obstacles.contiobs(i).longitude_vel(), raw_obstacles.contiobs(i).lateral_vel(), 0.0; velocity_w = radar_pose.topLeftCorner(3, 3) * velocity_r; // calculate the absolute velodity object_ptr->velocity(0) = velocity_w[0] + main_velocity(0); object_ptr->velocity(1) = velocity_w[1] + main_velocity(1); object_ptr->velocity(2) = 0; Eigen::Vector3f ref_velocity(main_velocity(0), main_velocity(1), 0.0); if (ContiRadarUtil::IsConflict(ref_velocity, object_ptr->velocity.cast<float>())) { object_ptr->is_background = true; } object_ptr->length = 1.0; object_ptr->width = 1.0; object_ptr->height = 1.0; object_ptr->type = UNKNOWN; Eigen::Matrix3d dist_rms; Eigen::Matrix3d vel_rms; vel_rms.setZero(); dist_rms.setZero(); dist_rms(0, 0) = raw_obstacles.contiobs(i).longitude_dist_rms(); dist_rms(1, 1) = raw_obstacles.contiobs(i).lateral_dist_rms(); vel_rms(0, 0) = raw_obstacles.contiobs(i).longitude_vel_rms(); vel_rms(1, 1) = raw_obstacles.contiobs(i).lateral_vel_rms(); object_ptr->position_uncertainty = radar_pose.topLeftCorner(3, 3) * dist_rms * dist_rms.transpose() * radar_pose.topLeftCorner(3, 3).transpose(); object_ptr->velocity_uncertainty = radar_pose.topLeftCorner(3, 3) * vel_rms * vel_rms.transpose() * radar_pose.topLeftCorner(3, 3).transpose(); double local_theta = raw_obstacles.contiobs(i).oritation_angle() / 180.0 * M_PI; Eigen::Vector3f direction = Eigen::Vector3f(cos(local_theta), sin(local_theta), 0); direction = radar_pose.topLeftCorner(3, 3).cast<float>() * direction; object_ptr->direction = direction.cast<double>(); // the avg time diff is from manual object_ptr->tracking_time = current_con_ids[obstacle_id] * 0.074; double theta = std::atan2(direction(1), direction(0)); object_ptr->theta = theta; // For radar obstacle , the polygon is supposed to have // four mock point: around obstacle center. RadarUtil::MockRadarPolygon(point, object_ptr->length, object_ptr->width, theta, &(object_ptr->polygon)); if (object_ptr->radar_supplement == nullptr) { object_ptr->radar_supplement.reset(new RadarSupplement()); } object_ptr->radar_supplement->range = std::sqrt( location_r[0] * location_r[0] + location_r[1] * location_r[1]); object_ptr->radar_supplement->angle = 0; objects->push_back(object_ptr); } continuous_ids_ = current_con_ids; } } // namespace perception } // namespace apollo
use absolute velocity
perception: use absolute velocity
C++
apache-2.0
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
efd9e0ce45b4b41066b6d934e50afb46bc842e84
modules/planning/optimizer/dp_poly_path/trajectory_cost.cc
modules/planning/optimizer/dp_poly_path/trajectory_cost.cc
/****************************************************************************** * Copyright 2017 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. *****************************************************************************/ /** * @file trjactory_cost.h **/ #include "modules/planning/optimizer/dp_poly_path/trajectory_cost.h" #include <algorithm> #include <cmath> #include "modules/common/math/vec2d.h" #include "modules/common/proto/pnc_point.pb.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using Box2d = ::apollo::common::math::Box2d; using Vec2d = ::apollo::common::math::Vec2d; using TrajectoryPoint = ::apollo::common::TrajectoryPoint; TrajectoryCost::TrajectoryCost(const DpPolyPathConfig &config, const ReferenceLine &reference_line, const common::VehicleParam &vehicle_param, const SpeedData &heuristic_speed_data) : config_(config), reference_line_(&reference_line), vehicle_param_(vehicle_param), heuristic_speed_data_(heuristic_speed_data) { const double total_time = std::min(heuristic_speed_data_.total_time(), FLAGS_prediction_total_time); num_of_time_stamps_ = static_cast<uint32_t>( std::floor(total_time / config.eval_time_interval())); } double TrajectoryCost::calculate(const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s) const { double total_cost = 0.0; // path_cost double path_s = 0.0; while (path_s < (end_s - start_s)) { double l = std::fabs(curve.evaluate(0, path_s)); total_cost += l; double dl = std::fabs(curve.evaluate(1, path_s)); total_cost += dl; path_s += config_.path_resolution(); } // obstacle cost return total_cost; } } // namespace planning } // namespace apollo
/****************************************************************************** * Copyright 2017 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. *****************************************************************************/ /** * @file trjactory_cost.h **/ #include "modules/planning/optimizer/dp_poly_path/trajectory_cost.h" #include <algorithm> #include <cmath> #include "modules/common/math/vec2d.h" #include "modules/common/proto/pnc_point.pb.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using Box2d = ::apollo::common::math::Box2d; using Vec2d = ::apollo::common::math::Vec2d; using TrajectoryPoint = ::apollo::common::TrajectoryPoint; TrajectoryCost::TrajectoryCost(const DpPolyPathConfig &config, const ReferenceLine &reference_line, const common::VehicleParam &vehicle_param, const SpeedData &heuristic_speed_data) : config_(config), reference_line_(&reference_line), vehicle_param_(vehicle_param), heuristic_speed_data_(heuristic_speed_data) { const double total_time = std::min(heuristic_speed_data_.total_time(), FLAGS_prediction_total_time); num_of_time_stamps_ = static_cast<uint32_t>( std::floor(total_time / config.eval_time_interval())); } double TrajectoryCost::calculate(const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s) const { double total_cost = 0.0; // path_cost double path_s = 0.0; while (path_s < (end_s - start_s)) { double l = std::fabs(curve.evaluate(0, path_s)); total_cost += l; double dl = std::fabs(curve.evaluate(1, path_s)); total_cost += dl; // TODO(all): add the 5.0 as a parameter into config path_s += config_.path_resolution() / 5.0; } // obstacle cost return total_cost; } } // namespace planning } // namespace apollo
modify the increment pf path_s for more points to compute trajectory cost
modify the increment pf path_s for more points to compute trajectory cost
C++
apache-2.0
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
74b7afc9c8f4614423591169b263dfb35e43eaae
examples/test.cc
examples/test.cc
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #include <cassert> #include <cinttypes> #include <cstdint> #include <cstdio> #include <vector> #include "mp4parse.h" void test_context() { mp4parse_state *context = mp4parse_new(); assert(context != nullptr); mp4parse_free(context); } void test_arg_validation(mp4parse_state *context) { int32_t rv; rv = mp4parse_read(nullptr, nullptr, 0); assert(rv == MP4PARSE_ERROR_BADARG); rv = mp4parse_read(context, nullptr, 0); assert(rv == MP4PARSE_ERROR_BADARG); size_t len = 4097; rv = mp4parse_read(context, nullptr, len); assert(rv == MP4PARSE_ERROR_BADARG); std::vector<uint8_t> buf; rv = mp4parse_read(context, buf.data(), buf.size()); assert(rv == MP4PARSE_ERROR_BADARG); buf.resize(len); rv = mp4parse_read(context, buf.data(), buf.size()); if (context) { // This fails with UNSUPPORTED because buf contains zeroes, so the first // box read is zero (unknown) length, which the parser doesn't currently // support. assert(rv == MP4PARSE_ERROR_UNSUPPORTED); } else { assert(rv == MP4PARSE_ERROR_BADARG); } } void test_arg_validation() { test_arg_validation(nullptr); mp4parse_state *context = mp4parse_new(); assert(context != nullptr); test_arg_validation(context); mp4parse_free(context); } const char * tracktype2str(uint32_t type) { switch (type) { case MP4PARSE_TRACK_TYPE_VIDEO: return "video"; case MP4PARSE_TRACK_TYPE_AUDIO: return "audio"; } return "unknown"; } const char * errorstring(int32_t error) { switch (error) { case MP4PARSE_OK: return "Ok"; case MP4PARSE_ERROR_BADARG: return "Invalid argument"; case MP4PARSE_ERROR_INVALID: return "Invalid data"; case MP4PARSE_ERROR_UNSUPPORTED: return "Feature unsupported"; case MP4PARSE_ERROR_EOF: return "Unexpected end-of-file"; case MP4PARSE_ERROR_IO: return "I/O error"; } return "Unknown error"; } int32_t read_file(const char* filename) { FILE* f = fopen(filename, "rb"); assert(f != nullptr); size_t len = 4096*16; std::vector<uint8_t> buf(len); size_t read = fread(buf.data(), sizeof(decltype(buf)::value_type), buf.size(), f); buf.resize(read); fclose(f); mp4parse_state *context = mp4parse_new(); assert(context != nullptr); fprintf(stderr, "Parsing %lu byte buffer.\n", (unsigned long)read); int32_t rv = mp4parse_read(context, buf.data(), buf.size()); if (rv != MP4PARSE_OK) { fprintf(stderr, "Parsing failed: %s\n", errorstring(rv)); return rv; } uint32_t tracks = mp4parse_get_track_count(context); fprintf(stderr, "%u tracks returned to C code.\n", tracks); for (uint32_t i = 0; i < tracks; ++i) { mp4parse_track_info track_info; int32_t rv2 = mp4parse_get_track_info(context, i, &track_info); assert(rv2 == MP4PARSE_OK); fprintf(stderr, "Track %d: type=%s duration=%" PRId64 " media_time=%" PRId64 " track_id=%d\n", i, tracktype2str(track_info.track_type), track_info.duration, track_info.media_time, track_info.track_id); } mp4parse_free(context); return MP4PARSE_OK; } int main(int argc, char* argv[]) { test_context(); test_arg_validation(); for (auto i = 1; i < argc; ++i) { read_file(argv[i]); } return 0; }
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #include <cassert> #include <cinttypes> #include <cstdint> #include <cstdio> #include <vector> #include "mp4parse.h" void test_context() { mp4parse_state *context = mp4parse_new(); assert(context != nullptr); mp4parse_free(context); } void test_arg_validation(mp4parse_state *context) { int32_t rv; rv = mp4parse_read(nullptr, nullptr, 0); assert(rv == MP4PARSE_ERROR_BADARG); rv = mp4parse_read(context, nullptr, 0); assert(rv == MP4PARSE_ERROR_BADARG); size_t len = 4097; rv = mp4parse_read(context, nullptr, len); assert(rv == MP4PARSE_ERROR_BADARG); std::vector<uint8_t> buf; rv = mp4parse_read(context, buf.data(), buf.size()); assert(rv == MP4PARSE_ERROR_BADARG); buf.resize(len); rv = mp4parse_read(context, buf.data(), buf.size()); if (context) { // This fails with UNSUPPORTED because buf contains zeroes, so the first // box read is zero (unknown) length, which the parser doesn't currently // support. assert(rv == MP4PARSE_ERROR_UNSUPPORTED); } else { assert(rv == MP4PARSE_ERROR_BADARG); } } void test_arg_validation() { test_arg_validation(nullptr); mp4parse_state *context = mp4parse_new(); assert(context != nullptr); test_arg_validation(context); mp4parse_free(context); } const char * tracktype2str(mp4parse_track_type type) { switch (type) { case MP4PARSE_TRACK_TYPE_VIDEO: return "video"; case MP4PARSE_TRACK_TYPE_AUDIO: return "audio"; } return "unknown"; } const char * errorstring(mp4parse_error error) { switch (error) { case MP4PARSE_OK: return "Ok"; case MP4PARSE_ERROR_BADARG: return "Invalid argument"; case MP4PARSE_ERROR_INVALID: return "Invalid data"; case MP4PARSE_ERROR_UNSUPPORTED: return "Feature unsupported"; case MP4PARSE_ERROR_EOF: return "Unexpected end-of-file"; case MP4PARSE_ERROR_ASSERT: return "Caught assert or panic"; case MP4PARSE_ERROR_IO: return "I/O error"; } return "Unknown error"; } int32_t read_file(const char* filename) { FILE* f = fopen(filename, "rb"); assert(f != nullptr); size_t len = 4096*16; std::vector<uint8_t> buf(len); size_t read = fread(buf.data(), sizeof(decltype(buf)::value_type), buf.size(), f); buf.resize(read); fclose(f); mp4parse_state *context = mp4parse_new(); assert(context != nullptr); fprintf(stderr, "Parsing %lu byte buffer.\n", (unsigned long)read); mp4parse_error rv = mp4parse_read(context, buf.data(), buf.size()); if (rv != MP4PARSE_OK) { fprintf(stderr, "Parsing failed: %s\n", errorstring(rv)); return rv; } uint32_t tracks = mp4parse_get_track_count(context); fprintf(stderr, "%u tracks returned to C code.\n", tracks); for (uint32_t i = 0; i < tracks; ++i) { mp4parse_track_info track_info; int32_t rv2 = mp4parse_get_track_info(context, i, &track_info); assert(rv2 == MP4PARSE_OK); fprintf(stderr, "Track %d: type=%s duration=%" PRId64 " media_time=%" PRId64 " track_id=%d\n", i, tracktype2str(track_info.track_type), track_info.duration, track_info.media_time, track_info.track_id); } mp4parse_free(context); return MP4PARSE_OK; } int main(int argc, char* argv[]) { test_context(); test_arg_validation(); for (auto i = 1; i < argc; ++i) { read_file(argv[i]); } return 0; }
Use enums rather than ints in test.cc.
Use enums rather than ints in test.cc.
C++
mpl-2.0
kinetiknz/mp4parse-rust,mozilla/mp4parse-rust,kinetiknz/mp4parse-rust
31355b0538e57e91a3a0d92e7c5bafbf6272e3ba
test/std/strings/char.traits/char.traits.specializations/char.traits.specializations.char8_t/length.pass.cpp
test/std/strings/char.traits/char.traits.specializations/char.traits.specializations.char8_t/length.pass.cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // <string> // template<> struct char_traits<char8_t> // static constexpr size_t length(const char_type* s); #include <string> #include <cassert> #include "test_macros.h" constexpr bool test_constexpr() { return std::char_traits<char8_t>::length(u8"") == 0 && std::char_traits<char8_t>::length(u8"abcd") == 4; } int main() { #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L assert(std::char_traits<char8_t>::length(u8"") == 0); assert(std::char_traits<char8_t>::length(u8"a") == 1); assert(std::char_traits<char8_t>::length(u8"aa") == 2); assert(std::char_traits<char8_t>::length(u8"aaa") == 3); assert(std::char_traits<char8_t>::length(u8"aaaa") == 4); static_assert(test_constexpr(), ""); #endif }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // <string> // template<> struct char_traits<char8_t> // static constexpr size_t length(const char_type* s); #include <string> #include <cassert> #include "test_macros.h" #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L constexpr bool test_constexpr() { return std::char_traits<char8_t>::length(u8"") == 0 && std::char_traits<char8_t>::length(u8"abcd") == 4; } int main() { assert(std::char_traits<char8_t>::length(u8"") == 0); assert(std::char_traits<char8_t>::length(u8"a") == 1); assert(std::char_traits<char8_t>::length(u8"aa") == 2); assert(std::char_traits<char8_t>::length(u8"aaa") == 3); assert(std::char_traits<char8_t>::length(u8"aaaa") == 4); static_assert(test_constexpr(), ""); } #else int main() { } #endif
Fix test on compilers that do not support char8_t yet
[libcxx] Fix test on compilers that do not support char8_t yet git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@348846 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
2f6fa4cee4073264369a056d3e72b654a52176d7
backup-unit/browserunit.cpp
backup-unit/browserunit.cpp
#include "logging.h" #include <vault/unit.h> #include <QProcess> #include <QCoreApplication> #include <QVariantList> #include <QVariantMap> #include <QDebug> #include <QLoggingCategory> #include <sys/types.h> #include <signal.h> #include <set> #include <unistd.h> #include <stdexcept> void stop_browser() { qCDebug(lcBackupLog) << "Terminating browser"; QProcess ps; auto get_browser_pids = [&ps]() { std::set<int> res; ps.execute("pgrep", {"-f", "sailfish-browser"}); if (ps.exitStatus() == QProcess::CrashExit) { qCDebug(lcBackupLog) << "pgrep failed"; return res; } auto data = QString(ps.readAllStandardOutput()).split("\n"); for (auto const &line : data) { if (!line.length()) continue; bool ok = false; auto pid = line.toInt(&ok); if (ok) res.insert(pid); } return res; }; auto const sec0_1 = 100000; auto sig = SIGINT; auto counter = 31; auto pids = get_browser_pids(); for (; pids.size(); pids = get_browser_pids()) { bool is_running_left = false; for (auto const &pid : pids) { if (!kill(pid, sig)) { qCDebug(lcBackupLog) << "Sent" << sig << "to" << pid; is_running_left = true; } } if (!is_running_left) break; usleep(sec0_1); if (!--counter) throw std::runtime_error("Can't interrupt sailfish-browser"); else if (counter < 6) sig = SIGKILL; else if (counter < 15) sig = SIGTERM; } } namespace { const QString browser_dir = ".local/share/org.sailfishos/browser"; const QString moz_dir = browser_dir + "/.mozilla"; // thumbs const QString cache_dir = ".cache/org.sailfishos/browser"; const QVariantMap info = { {"home", QVariantMap({ {"data", QVariantList({ browser_dir + "/bookmarks.json" })} , {"bin", QVariantList({ moz_dir + "/key3.db" , browser_dir + "/sailfish-browser.sqlite" , cache_dir , moz_dir + "/signons.sqlite" }) }})} , {"options", QVariantMap({{"overwrite", true}})} }; } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); try { stop_browser(); } catch (std::exception const &e) { qCDebug(lcBackupLog) << e.what(); return 1; } return vault::unit::execute(info); }
#include "logging.h" #include <vault/unit.h> #include <QProcess> #include <QCoreApplication> #include <QVariantList> #include <QVariantMap> #include <QDebug> #include <QLoggingCategory> #include <QFileInfo> #include <QDir> #include <sys/types.h> #include <signal.h> #include <set> #include <unistd.h> #include <stdexcept> void stop_browser() { qCDebug(lcBackupLog) << "Terminating browser"; QProcess ps; auto get_browser_pids = [&ps]() { std::set<int> res; ps.execute("pgrep", {"-f", "sailfish-browser"}); if (ps.exitStatus() == QProcess::CrashExit) { qCDebug(lcBackupLog) << "pgrep failed"; return res; } auto data = QString(ps.readAllStandardOutput()).split("\n"); for (auto const &line : data) { if (!line.length()) continue; bool ok = false; auto pid = line.toInt(&ok); if (ok) res.insert(pid); } return res; }; auto const sec0_1 = 100000; auto sig = SIGINT; auto counter = 31; auto pids = get_browser_pids(); for (; pids.size(); pids = get_browser_pids()) { bool is_running_left = false; for (auto const &pid : pids) { if (!kill(pid, sig)) { qCDebug(lcBackupLog) << "Sent" << sig << "to" << pid; is_running_left = true; } } if (!is_running_left) break; usleep(sec0_1); if (!--counter) throw std::runtime_error("Can't interrupt sailfish-browser"); else if (counter < 6) sig = SIGKILL; else if (counter < 15) sig = SIGTERM; } } namespace { const QString browser_dir = ".local/share/org.sailfishos/browser"; const QString moz_dir = browser_dir + "/.mozilla"; // thumbs const QString cache_dir = ".cache/org.sailfishos/browser"; // files const QString bookmarks = "/bookmarks.json"; const QString database = "/sailfish-browser.sqlite"; const QString keys = "/key3.db"; const QString signons = "/signons.sqlite"; const QVariantMap info = { {"home", QVariantMap({ {"data", QVariantList({ browser_dir + bookmarks })} , {"bin", QVariantList({ moz_dir + keys , browser_dir + database , cache_dir , moz_dir + signons }) }})} , {"options", QVariantMap({{"overwrite", true}})} }; // old paths const QString old_browser_dir = ".local/share/org.sailfishos/sailfish-browser"; const QString old_moz_dir = ".mozilla/mozembed"; const QString old_cache_dir = ".cache/org.sailfishos/sailfish-browser"; } void fix(QString common, QString file, QString oldPath, QString newPath) { const auto pathTemplate = QStringLiteral("%1/%3/%2").arg(common).arg(file); QFileInfo source(pathTemplate.arg(oldPath)); if (source.exists()) { QFileInfo dest(pathTemplate.arg(newPath)); dest.dir().mkpath("."); if (!source.dir().rename(source.fileName(), dest.absoluteFilePath())) { qCWarning(lcBackupLog) << "Moving" << source.filePath() << "to" << dest.absoluteFilePath() << "failed"; } } } void fix_dir(QString common, QString oldPath, QString newPath) { if (QFileInfo(common + "/" + oldPath).exists()) { if (!QDir(common).rename(oldPath, newPath)) { qCWarning(lcBackupLog) << "Moving" << oldPath << "to" << newPath << "failed"; } } } void fix_import() { // Check for old style backup and convert to current structure if needed fix(vault::unit::optValue("dir"), bookmarks, old_browser_dir, browser_dir); auto blobDir = vault::unit::optValue("bin-dir"); fix(blobDir, database, old_browser_dir, browser_dir); fix(blobDir, keys, old_moz_dir, moz_dir); fix(blobDir, signons, old_moz_dir, moz_dir); fix_dir(blobDir, old_cache_dir, cache_dir); } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); try { stop_browser(); } catch (std::exception const &e) { qCDebug(lcBackupLog) << e.what(); return 1; } if (vault::unit::optValue("action") == "import") { fix_import(); } return vault::unit::execute(info); }
Fix restoring old backups. Fixes JB#52318
[sailfish-browser] Fix restoring old backups. Fixes JB#52318 This moves the files around in the in memory copy of the archive before restoring it. This doesn't modify the archive itself because it is mounted with nosave option. Signed-off-by: Tomi Leppänen <[email protected]>
C++
mpl-2.0
sailfishos/sailfish-browser,sailfishos/sailfish-browser,sailfishos/sailfish-browser,sailfishos/sailfish-browser,sailfishos/sailfish-browser
75e7c0e6de686b386286be7aa3b60465d50e98a2
Modules/Automatic/libs/Automatic.cpp
Modules/Automatic/libs/Automatic.cpp
#include "Automatic.h" #define PI 3.141592653589 #define Kland 1 #define THRE 0.15 #define DRATE_MIN 0.1 #define DRATE_MAX 0.4 #define VMAX 1.5 #define TMAX 2 #define TMIN 0.5 #define PLATFORM_OFFSET 0.1 Eigen::Quaterniond getQuatFromYaw(double yaw){ Eigen::Quaterniond quaterniond; quaterniond.w() = cos(yaw/2); quaterniond.x() = 0; quaterniond.y() = 0; quaterniond.z() = sin(yaw/2); return quaterniond; } Automatic::Automatic() {} MavState Automatic::getState() { return _state; } exec::task Automatic::getTask() { return _actualTask; } void Automatic::setState(MavState rState) { _state = rState; } void Automatic::setTask(exec::task rTask) { _actualTask.x=rTask.x; _actualTask.y=rTask.y; _actualTask.z=rTask.z; _actualTask.yaw=rTask.yaw; _actualTask.action=rTask.action; _actualTask.params[0]=rTask.params[0]; _actualTask.params[1]=rTask.params[1]; _actualTask.params[2]=rTask.params[2]; _actualTask.params[3]=rTask.params[3]; } void Automatic::rotate() { _comm.setType(MavState::type::POSITION); double angleValid = _actualTask.params[0]; double yawSP = _actualTask.yaw; double yawComm; if(angleValid==0){ double x_target = _actualTask.x; double y_target = _actualTask.y; yawSP = atan2(y_target - _state.getY(),x_target - _state.getX()); } //calculateYawInterm(_state.getYawFromQuat(),yawSP,yawComm); yawComm = yawSP; _comm.setYaw(yawComm); Eigen::Quaterniond q_interm = yawToQuaternion(yawComm); _comm.setOrientation(q_interm); } void Automatic::calculateYawInterm(float heading, double yawTarget, double &yawComm){ double yawSp_h = yawTarget - heading; _comm.setType(MavState::type::POSITION); /* DISABLE ALGORITHM FOR BUG FIXING if (fabs(yawSp_h) <= PI/10) yawComm = yawTarget; else if(fabs(yawSp_h) > PI - PI/18){ //Increase yaw yawComm = heading + PI / 10 ; if (yawComm > PI){ yawComm = yawComm - 2*PI; } } else{ if (yawSp_h > 0){ //Increase yaw yawComm = heading + PI / 10 ; if (yawComm > PI){ yawComm = yawComm - 2*PI; } } else{ //decrease yaw yawComm = heading - PI / 10 ; if (yawComm < -PI){ yawComm = yawComm + 2*PI; } } } */ } double calculateDescendRate(double dz,double drate_max,double drate_min, double tmax, double tmin){ //Calculate the descend rate profile (linear) through y = mx + q //where x is vertical distance between robot and platform if(dz > tmax) return drate_max; else if(dz < tmin) return drate_min; else{ double m = (drate_max - drate_min) / (tmax - tmin); double q = drate_min - m * tmin; return m * dz + q; } } void Automatic::takeOff() { _comm.setType(MavState::type::POSITION); double height = _actualTask.params[0]; _comm.setX((float)_actualTask.x); _comm.setY((float)_actualTask.y); _comm.setZ((float)height); Eigen::Quaterniond q = getQuatFromYaw(_actualTask.yaw); _comm.setOrientation((float)q.w(),(float)q.x(),(float)q.y(),(float)q.z()); } void Automatic::move() { _comm.setType(MavState::type::POSITION); double alpha = _actualTask.params[0]; calculatePositionInterm(alpha,_actualTask,_state,_comm); } void Automatic::calculatePositionInterm(const double alpha, const exec::task target, const MavState state, MavState &comm) { _comm.setType(MavState::type::POSITION); double positionError[3] = {target.x - state.getX() ,target.y - state.getY() , target.z - state.getZ()}; double dist = sqrt(pow(positionError[0],2) + pow(positionError[1],2) + pow(positionError[2],2)); //Publish if(fabs(dist) <= alpha) { comm.setX((float)target.x); comm.setY((float)target.y); comm.setZ((float)target.z); } else if(fabs(dist) > alpha) { double incrementVect[3]; //Normalize positionError[0] = positionError[0] / dist; positionError[1] = positionError[1] / dist; positionError[2] = positionError[2] / dist; //Calculate relative motion to actual position incrementVect[0] = positionError[0] * alpha; incrementVect[1] = positionError[1] * alpha; incrementVect[2] = positionError[2] * alpha; comm.setX(state.getX() + (float)incrementVect[0]); comm.setY(state.getY() + (float)incrementVect[1]); comm.setZ(state.getZ() + (float)incrementVect[2]); } } void Automatic::land1(float x_target, float y_target, float h) { //Calculate difference double dx = - _state.getX() + x_target; double dy = - _state.getY() + y_target; double dz = - _state.getZ() + h; //_state.z is negative due to inversion, // that is why we don't use the minus sign // Be sure that we are on top of the target double x_target_v = Kland * (dx); double y_target_v = Kland * (dy); //Normalize Eigen::Vector2d v(x_target_v,y_target_v); if(v.norm() > VMAX){ v.normalize(); v = v * VMAX; } _comm.setVx(v(0) * 2); _comm.setVy(v(1) * 2); //TODO: add security checks on vz if(fabs(dx) <= THRE && fabs(dy) <= THRE){ //Descending is safe, is it? double desc = calculateDescendRate(fabs(dz), DRATE_MAX, DRATE_MIN, TMAX, TMIN); desc = 0.2; _comm.setVz(-desc); /* if (fabs(dz) < 0.05){ _comm.setVx(0); _comm.setVy(0); _comm.setVz(-10); } */ } //else if (fabs(dx) <= THRE * 10 && fabs(dy) <= THRE * 10) _comm.setVz(DRATE_MAX); //Is it correct? Don't think so else _comm.setVz(0); _comm.setType(MavState::type::VELOCITY); } void Automatic::land2(MavState platPose, double kp, double ki, double kd) { //Calculate difference double dx = - _state.getX() + platPose.getX(); double dy = - _state.getY() + platPose.getY(); double dz = - _state.getZ() + platPose.getZ() + PLATFORM_OFFSET; // Be sure that we are on top of the target double x_target_v = Kland * (dx); double y_target_v = Kland * (dy); //Normalize Eigen::Vector2d v(x_target_v,y_target_v); if(v.norm() > VMAX){ v.normalize(); v = v * VMAX; } _comm.setVx(v(0)); _comm.setVy(v(1)); //TODO: add security checks on vz if(fabs(dx) <= THRE && fabs(dy) <= THRE){ //Descending is safe, is it?< double desc = calculateDescendRate(dz, DRATE_MAX, DRATE_MIN, TMAX, TMIN); double z_target_v = platPose.getVz() - desc; //if(z_target_v <= -DRATE) z_target_v = -DRATE; //could be useful double err_v = z_target_v - _state.getVz(); z_target_v += ki*(err_v); // Proportional term std::cout << "Actua: " <<-_state.getVz() + platPose.getVz()<< std::endl; std::cout << "Desir: " << desc << std::endl; std::cout << "ErrVe: " << err_v << std::endl; std::cout << "ErrDe: " << desc - (-_state.getVz() + platPose.getVz())<< std::endl; _comm.setVz(z_target_v); }else if(fabs(dx) <= THRE*8 && fabs(dy) <= THRE*8){ _comm.setVz(DRATE_MAX*1.5); }else { _comm.setVz(0); } //Is it correct? _comm.setType(MavState::type::VELOCITY); }
#include "Automatic.h" #define PI 3.141592653589 #define Kland 1 #define THRE 0.15 #define DRATE_MIN 0.1 #define DRATE_MAX 0.4 #define VMAX 1.5 #define TMAX 2 #define TMIN 0.5 #define PLATFORM_OFFSET 0.1 Eigen::Quaterniond getQuatFromYaw(double yaw){ Eigen::Quaterniond quaterniond; quaterniond.w() = cos(yaw/2); quaterniond.x() = 0; quaterniond.y() = 0; quaterniond.z() = sin(yaw/2); return quaterniond; } Automatic::Automatic() {} MavState Automatic::getState() { return _state; } exec::task Automatic::getTask() { return _actualTask; } void Automatic::setState(MavState rState) { _state = rState; } void Automatic::setTask(exec::task rTask) { _actualTask.x=rTask.x; _actualTask.y=rTask.y; _actualTask.z=rTask.z; _actualTask.yaw=rTask.yaw; _actualTask.action=rTask.action; _actualTask.params[0]=rTask.params[0]; _actualTask.params[1]=rTask.params[1]; _actualTask.params[2]=rTask.params[2]; _actualTask.params[3]=rTask.params[3]; } void Automatic::rotate() { _comm.setType(MavState::type::POSITION); double angleValid = _actualTask.params[0]; double yawSP = _actualTask.yaw; double yawComm; if(angleValid==0){ double x_target = _actualTask.x; double y_target = _actualTask.y; yawSP = atan2(y_target - _state.getY(),x_target - _state.getX()); } //calculateYawInterm(_state.getYawFromQuat(),yawSP,yawComm); yawComm = yawSP; _comm.setYaw(yawComm); Eigen::Quaterniond q_interm = yawToQuaternion(yawComm); _comm.setOrientation(q_interm); } void Automatic::calculateYawInterm(float heading, double yawTarget, double &yawComm){ double yawSp_h = yawTarget - heading; _comm.setType(MavState::type::POSITION); /* DISABLE ALGORITHM FOR BUG FIXING if (fabs(yawSp_h) <= PI/10) yawComm = yawTarget; else if(fabs(yawSp_h) > PI - PI/18){ //Increase yaw yawComm = heading + PI / 10 ; if (yawComm > PI){ yawComm = yawComm - 2*PI; } } else{ if (yawSp_h > 0){ //Increase yaw yawComm = heading + PI / 10 ; if (yawComm > PI){ yawComm = yawComm - 2*PI; } } else{ //decrease yaw yawComm = heading - PI / 10 ; if (yawComm < -PI){ yawComm = yawComm + 2*PI; } } } */ } double calculateDescendRate(double dz,double drate_max,double drate_min, double tmax, double tmin){ //Calculate the descend rate profile (linear) through y = mx + q //where x is vertical distance between robot and platform if(dz > tmax) return drate_max; else if(dz < tmin) return drate_min; else{ double m = (drate_max - drate_min) / (tmax - tmin); double q = drate_min - m * tmin; return m * dz + q; } } void Automatic::takeOff() { _comm.setType(MavState::type::POSITION); double height = _actualTask.params[0]; _comm.setX((float)_actualTask.x); _comm.setY((float)_actualTask.y); _comm.setZ((float)height); Eigen::Quaterniond q = getQuatFromYaw(_actualTask.yaw); _comm.setOrientation((float)q.w(),(float)q.x(),(float)q.y(),(float)q.z()); } void Automatic::move() { _comm.setType(MavState::type::POSITION); double alpha = _actualTask.params[0]; calculatePositionInterm(alpha,_actualTask,_state,_comm); } void Automatic::calculatePositionInterm(const double alpha, const exec::task target, const MavState state, MavState &comm) { _comm.setType(MavState::type::POSITION); double positionError[3] = {target.x - state.getX() ,target.y - state.getY() , target.z - state.getZ()}; double dist = sqrt(pow(positionError[0],2) + pow(positionError[1],2) + pow(positionError[2],2)); //Publish if(fabs(dist) <= alpha) { comm.setX((float)target.x); comm.setY((float)target.y); comm.setZ((float)target.z); } else if(fabs(dist) > alpha) { double incrementVect[3]; //Normalize positionError[0] = positionError[0] / dist; positionError[1] = positionError[1] / dist; positionError[2] = positionError[2] / dist; //Calculate relative motion to actual position incrementVect[0] = positionError[0] * alpha; incrementVect[1] = positionError[1] * alpha; incrementVect[2] = positionError[2] * alpha; comm.setX(state.getX() + (float)incrementVect[0]); comm.setY(state.getY() + (float)incrementVect[1]); comm.setZ(state.getZ() + (float)incrementVect[2]); } } void Automatic::land1(float x_target, float y_target, float h) { //Calculate difference double dx = - _state.getX() + x_target; double dy = - _state.getY() + y_target; double dz = - _state.getZ() + h; // Be sure that we are on top of the target double x_target_v = Kland * (dx); double y_target_v = Kland * (dy); //Normalize Eigen::Vector2d v(x_target_v,y_target_v); if(v.norm() > VMAX){ v.normalize(); v = v * VMAX; } _comm.setVx(v(0) * 2); _comm.setVy(v(1) * 2); //TODO: add security checks on vz if(fabs(dx) <= THRE && fabs(dy) <= THRE){ //Descending is safe, is it? double desc = calculateDescendRate(fabs(dz), DRATE_MAX, DRATE_MIN, TMAX, TMIN); _comm.setVz(-desc); /* if (fabs(dz) < 0.05){ _comm.setVx(0); _comm.setVy(0); _comm.setVz(-10); } */ } //else if (fabs(dx) <= THRE * 10 && fabs(dy) <= THRE * 10) _comm.setVz(DRATE_MAX); //Is it correct? Don't think so else _comm.setVz(0); _comm.setType(MavState::type::VELOCITY); } void Automatic::land2(MavState platPose, double kp, double ki, double kd) { //Calculate difference double dx = - _state.getX() + platPose.getX(); double dy = - _state.getY() + platPose.getY(); double dz = - _state.getZ() + platPose.getZ() + PLATFORM_OFFSET; // Be sure that we are on top of the target double x_target_v = Kland * (dx); double y_target_v = Kland * (dy); //Normalize Eigen::Vector2d v(x_target_v,y_target_v); if(v.norm() > VMAX){ v.normalize(); v = v * VMAX; } _comm.setVx(v(0)); _comm.setVy(v(1)); //TODO: add security checks on vz if(fabs(dx) <= THRE && fabs(dy) <= THRE){ //Descending is safe, is it?< double desc = calculateDescendRate(dz, DRATE_MAX, DRATE_MIN, TMAX, TMIN); double z_target_v = platPose.getVz() - desc; //if(z_target_v <= -DRATE) z_target_v = -DRATE; //could be useful double err_v = z_target_v - _state.getVz(); z_target_v += ki*(err_v); // Proportional term std::cout << "Actua: " <<-_state.getVz() + platPose.getVz()<< std::endl; std::cout << "Desir: " << desc << std::endl; std::cout << "ErrVe: " << err_v << std::endl; std::cout << "ErrDe: " << desc - (-_state.getVz() + platPose.getVz())<< std::endl; _comm.setVz(z_target_v); }else if(fabs(dx) <= THRE*8 && fabs(dy) <= THRE*8){ _comm.setVz(DRATE_MAX*1.5); }else { _comm.setVz(0); } //Is it correct? _comm.setType(MavState::type::VELOCITY); }
remove fixed descend rate
remove fixed descend rate
C++
mit
EmaroLab/mocap2mav,EmaroLab/mocap2mav
69f914be7fbafd96531846cbabb365bc33544dac
graphics/meshes/spritemesh.cpp
graphics/meshes/spritemesh.cpp
#include "spritemesh.h" using namespace GluonGraphics; class SpriteMesh::SpriteMeshPrivate { public: QSizeF size; }; SpriteMesh::SpriteMesh(QObject * parent) :Mesh(parent) { d = new SpriteMeshPrivate; setSize(QSizeF(1.0f, 1.0f)); } SpriteMesh::SpriteMesh(const QSizeF& rect, QObject * parent) :Mesh(parent) { d = new SpriteMeshPrivate; setSize(rect); } SpriteMesh::~SpriteMesh() { delete d; } void SpriteMesh::setSize(const QSizeF &size) { d->size = size; float halfw = size.width() / 2.0f; float halfh = size.height() / 2.0f; if(vertexCount() < 4) { for(int i = 0; i < 4; ++i) { addVertex(QVector2D()); } } Vertex *vertex = vertexAt(0); vertex->setX(-halfw); vertex->setY(-halfh); vertex = vertexAt(1); vertex->setX(-halfw); vertex->setY(halfh); vertex = vertexAt(2); vertex->setX(halfw); vertex->setY(halfh); vertex = vertexAt(3); vertex->setX(halfw); vertex->setY(-halfh); } QSizeF GluonGraphics::SpriteMesh::size() const { return d->size; }
#include "spritemesh.h" using namespace GluonGraphics; class SpriteMesh::SpriteMeshPrivate { public: QSizeF size; }; SpriteMesh::SpriteMesh(QObject * parent) :Mesh(parent) { d = new SpriteMeshPrivate; setSize(QSizeF(1.0f, 1.0f)); } SpriteMesh::SpriteMesh(const QSizeF& rect, QObject * parent) :Mesh(parent) { d = new SpriteMeshPrivate; setSize(rect); } SpriteMesh::~SpriteMesh() { delete d; } void SpriteMesh::setSize(const QSizeF &size) { d->size = size; float halfw = size.width() / 2.0f; float halfh = size.height() / 2.0f; if(vertexCount() < 4) { for(int i = 0; i < 4; ++i) { addVertex(QVector2D()); } } Vertex *vertex = vertexAt(0); vertex->setX(-halfw); vertex->setY(-halfh); vertex->setTex(QVector2D(0, 1)); vertex->setColor(Qt::white); vertex = vertexAt(1); vertex->setX(-halfw); vertex->setY(halfh); vertex->setTex(QVector2D(0, 0)); vertex->setColor(Qt::white); vertex = vertexAt(2); vertex->setX(halfw); vertex->setY(halfh); vertex->setTex(QVector2D(1, 0)); vertex->setColor(Qt::white); vertex = vertexAt(3); vertex->setX(halfw); vertex->setY(-halfh); vertex->setTex(QVector2D(1, 1)); vertex->setColor(Qt::white); } QSizeF GluonGraphics::SpriteMesh::size() const { return d->size; }
Add some texture coordinates. Fixes texture problems.
Add some texture coordinates. Fixes texture problems.
C++
lgpl-2.1
cgaebel/gluon,cgaebel/gluon,KDE/gluon,pranavrc/example-gluon,pranavrc/example-gluon,cgaebel/gluon,pranavrc/example-gluon,KDE/gluon,KDE/gluon,cgaebel/gluon,pranavrc/example-gluon,KDE/gluon
1c97e606618a35973f4c608d150e384c5c526263
include/blackhole/detail/sink/file.hpp
include/blackhole/detail/sink/file.hpp
#pragma once #include "blackhole/sink/file.hpp" #include <fstream> #include <limits> #include <map> #include "blackhole/cpp17/string_view.hpp" namespace blackhole { namespace sink { namespace file { struct backend_t { std::size_t counter; std::size_t interval; std::unique_ptr<std::ofstream> stream; backend_t(const std::string& filename, std::size_t interval) : counter(0), interval(interval), stream(new std::ofstream(filename)) { BOOST_ASSERT(interval > 0); } backend_t(const backend_t& other) = delete; backend_t(backend_t&& other) = default; virtual ~backend_t() {} auto operator=(const backend_t& other) -> backend_t& = delete; auto operator=(backend_t&& other) -> backend_t& = default; virtual auto write(const string_view& message) -> void { stream->write(message.data(), static_cast<std::streamsize>(message.size())); stream->put('\n'); counter = (counter + 1) % interval; if (counter == 0) { flush(); } } virtual auto flush() -> void { stream->flush(); } }; class inner_t { struct { std::string filename; std::size_t interval; std::map<std::string, backend_t> backends; } data; public: inner_t(std::string filename, std::size_t interval) { data.filename = std::move(filename); data.interval = interval > 0 ? interval : std::numeric_limits<std::size_t>::max(); } virtual ~inner_t() {} auto interval() const noexcept -> std::size_t { return data.interval; } virtual auto filename(const record_t&) const -> std::string { // TODO: Generate path from tokens, for now just return static path. return {data.filename}; } virtual auto backend(const std::string& filename) -> backend_t& { const auto it = data.backends.find(filename); if (it == data.backends.end()) { return data.backends.insert(it, std::make_pair(filename, backend_t(filename, interval())))->second; } return it->second; } }; } // namespace file } // namespace sink } // namespace blackhole
#pragma once #include "blackhole/sink/file.hpp" #include <fstream> #include <limits> #include <map> #include <boost/assert.hpp> #include "blackhole/cpp17/string_view.hpp" namespace blackhole { namespace sink { namespace file { struct backend_t { std::size_t counter; std::size_t interval; std::unique_ptr<std::ofstream> stream; backend_t(const std::string& filename, std::size_t interval) : counter(0), interval(interval), stream(new std::ofstream(filename)) { BOOST_ASSERT(interval > 0); } backend_t(const backend_t& other) = delete; backend_t(backend_t&& other) = default; virtual ~backend_t() {} auto operator=(const backend_t& other) -> backend_t& = delete; auto operator=(backend_t&& other) -> backend_t& = default; virtual auto write(const string_view& message) -> void { stream->write(message.data(), static_cast<std::streamsize>(message.size())); stream->put('\n'); counter = (counter + 1) % interval; if (counter == 0) { flush(); } } virtual auto flush() -> void { stream->flush(); } }; class inner_t { struct { std::string filename; std::size_t interval; std::map<std::string, backend_t> backends; } data; public: inner_t(std::string filename, std::size_t interval) { data.filename = std::move(filename); data.interval = interval > 0 ? interval : std::numeric_limits<std::size_t>::max(); } virtual ~inner_t() {} auto interval() const noexcept -> std::size_t { return data.interval; } virtual auto filename(const record_t&) const -> std::string { // TODO: Generate path from tokens, for now just return static path. return {data.filename}; } virtual auto backend(const std::string& filename) -> backend_t& { const auto it = data.backends.find(filename); if (it == data.backends.end()) { return data.backends.insert(it, std::make_pair(filename, backend_t(filename, interval())))->second; } return it->second; } }; } // namespace file } // namespace sink } // namespace blackhole
add another forgotten include
fix(sink/file): add another forgotten include
C++
mit
noxiouz/blackhole,3Hren/blackhole
47fbf32c62cabdb4adce86e72d046cb66998ecda
src/videorenderer.cpp
src/videorenderer.cpp
/**************************************************************************** * Copyright (C) 2012-2013 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "videorenderer.h" #include <QtCore/QDebug> #include <QtCore/QMutex> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <semaphore.h> #include <errno.h> // #include <linux/time.h> #include <time.h> #ifndef CLOCK_REALTIME #define CLOCK_REALTIME 0 #endif #include <QtCore/QTimer> ///Shared memory object struct SHMHeader{ sem_t notification; sem_t mutex; unsigned m_BufferGen; int m_BufferSize; /* The header will be aligned on 16-byte boundaries */ char padding[8]; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-pedantic" char m_Data[]; #pragma GCC diagnostic pop }; ///Constructor VideoRenderer::VideoRenderer(QString shmPath, Resolution res): QObject(nullptr), m_Width(res.width()), m_Height(res.height()), m_ShmPath(shmPath), fd(-1), m_pShmArea((SHMHeader*)MAP_FAILED), m_ShmAreaLen(0), m_BufferGen(0), m_isRendering(false),m_pTimer(nullptr),m_Res(res),m_pMutex(new QMutex()) { } ///Destructor VideoRenderer::~VideoRenderer() { stopShm(); //delete m_pShmArea; } ///Get the data from shared memory and transform it into a QByteArray QByteArray VideoRenderer::renderToBitmap(QByteArray& data,bool& ok) { if (!m_isRendering) { return QByteArray(); } if (!shmLock()) { ok = false; return QByteArray(); } // wait for a new buffer while (m_BufferGen == m_pShmArea->m_BufferGen) { shmUnlock(); const struct timespec timeout = createTimeout(); int err = sem_timedwait(&m_pShmArea->notification, &timeout); // Useful for debugging // switch (errno ) { // case EINTR: // qDebug() << "Unlock failed: Interrupted function call (POSIX.1); see signal(7)"; // ok = false; // return QByteArray(); // break; // case EINVAL: // qDebug() << "Unlock failed: Invalid argument (POSIX.1)"; // ok = false; // return QByteArray(); // break; // case EAGAIN: // qDebug() << "Unlock failed: Resource temporarily unavailable (may be the same value as EWOULDBLOCK) (POSIX.1)"; // ok = false; // return QByteArray(); // break; // case ETIMEDOUT: // qDebug() << "Unlock failed: Connection timed out (POSIX.1)"; // ok = false; // return QByteArray(); // break; // } if (err < 0) { ok = false; return QByteArray(); } if (!shmLock()) { ok = false; return QByteArray(); } } if (!resizeShm()) { qDebug() << "Could not resize shared memory"; ok = false; return QByteArray(); } if (data.size() != m_pShmArea->m_BufferSize) data.resize(m_pShmArea->m_BufferSize); memcpy(data.data(),m_pShmArea->m_Data,m_pShmArea->m_BufferSize); m_BufferGen = m_pShmArea->m_BufferGen; shmUnlock(); return data; } ///Connect to the shared memory bool VideoRenderer::startShm() { if (fd != -1) { qDebug() << "fd must be -1"; return false; } fd = shm_open(m_ShmPath.toAscii(), O_RDWR, 0); if (fd < 0) { qDebug() << "could not open shm area \"%s\", shm_open failed:%s" << m_ShmPath << strerror(errno); return false; } m_ShmAreaLen = sizeof(SHMHeader); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" m_pShmArea = (SHMHeader*) mmap(NULL, m_ShmAreaLen, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); #pragma GCC diagnostic pop if (m_pShmArea == MAP_FAILED) { qDebug() << "Could not map shm area, mmap failed"; return false; } return true; } ///Disconnect from the shared memory void VideoRenderer::stopShm() { if (fd >= 0) close(fd); fd = -1; if (m_pShmArea != MAP_FAILED) munmap(m_pShmArea, m_ShmAreaLen); m_ShmAreaLen = 0; m_pShmArea = (SHMHeader*) MAP_FAILED; } ///Resize the shared memory bool VideoRenderer::resizeShm() { while (( (unsigned int) sizeof(SHMHeader) + (unsigned int) m_pShmArea->m_BufferSize) > (unsigned int) m_ShmAreaLen) { const size_t new_size = sizeof(SHMHeader) + m_pShmArea->m_BufferSize; shmUnlock(); if (munmap(m_pShmArea, m_ShmAreaLen)) { qDebug() << "Could not unmap shared area:%s" << strerror(errno); return false; } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" m_pShmArea = (SHMHeader*) mmap(NULL, new_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); #pragma GCC diagnostic pop m_ShmAreaLen = new_size; if (!m_pShmArea) { m_pShmArea = nullptr; qDebug() << "Could not remap shared area"; return false; } m_ShmAreaLen = new_size; if (!shmLock()) return false; } return true; } ///Lock the memory while the copy is being made bool VideoRenderer::shmLock() { const timespec timeout = createTimeout(); /* We need an upper limit on how long we'll wait to avoid locking the whole GUI */ if (sem_timedwait(&m_pShmArea->mutex, &timeout) == ETIMEDOUT) { qDebug() << "Timed out before shm lock was acquired"; return false; } return true; } ///Remove the lock, allow a new frame to be drawn void VideoRenderer::shmUnlock() { sem_post(&m_pShmArea->mutex); } ///Create a SHM timeout timespec VideoRenderer::createTimeout() { timespec timeout = {0, 0}; if (clock_gettime(CLOCK_REALTIME, &timeout) == -1) qDebug() << "clock_gettime"; timeout.tv_sec += TIMEOUT_SEC; return timeout; } /***************************************************************************** * * * Slots * * * ****************************************************************************/ ///Update the buffer void VideoRenderer::timedEvents() { bool ok = true; // m_pMutex->lock(); renderToBitmap(m_Frame,ok); // m_pMutex->unlock(); if (ok == true) { emit frameUpdated(); } else { qDebug() << "Frame dropped"; usleep(rand()%1000); //Be sure it can come back in sync } } ///Start the rendering loop void VideoRenderer::startRendering() { startShm(); if (!m_pTimer) { m_pTimer = new QTimer(this); connect(m_pTimer,SIGNAL(timeout()),this,SLOT(timedEvents())); m_pTimer->setInterval(42); } m_pTimer->start(); m_isRendering = true; } ///Stop the rendering loop void VideoRenderer::stopRendering() { m_isRendering = false; stopShm(); //qDebug() << "Video stopped for call" << id; //emit videoStopped(); if (m_pTimer) m_pTimer->stop(); } /***************************************************************************** * * * Getters * * * ****************************************************************************/ ///Get the raw bytes directly from the SHM, not recommended, but optimal const char* VideoRenderer::rawData() { return m_pShmArea->m_Data; } ///Is this redenrer active bool VideoRenderer::isRendering() { return m_isRendering; } ///Return the current framerate QByteArray VideoRenderer::currentFrame() { return m_Frame; } ///Return the current resolution Resolution VideoRenderer::activeResolution() { return m_Res; } ///Get mutex, in case renderer and views are not in the same thread QMutex* VideoRenderer::mutex() { return m_pMutex; } /***************************************************************************** * * * Setters * * * ****************************************************************************/ void VideoRenderer::setResolution(QSize size) { m_Res = size; m_Width = size.width(); m_Height = size.height(); } void VideoRenderer::setShmPath(QString path) { m_ShmPath = path; }
/**************************************************************************** * Copyright (C) 2012-2013 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "videorenderer.h" #include <QtCore/QDebug> #include <QtCore/QMutex> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <semaphore.h> #include <errno.h> // #include <linux/time.h> #include <time.h> #ifndef CLOCK_REALTIME #define CLOCK_REALTIME 0 #endif #include <QtCore/QTimer> ///Shared memory object struct SHMHeader{ sem_t notification; sem_t mutex; unsigned m_BufferGen; int m_BufferSize; /* The header will be aligned on 16-byte boundaries */ char padding[8]; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-pedantic" char m_Data[]; #pragma GCC diagnostic pop }; ///Constructor VideoRenderer::VideoRenderer(QString shmPath, Resolution res): QObject(nullptr), m_Width(res.width()), m_Height(res.height()), m_ShmPath(shmPath), fd(-1), m_pShmArea((SHMHeader*)MAP_FAILED), m_ShmAreaLen(0), m_BufferGen(0), m_isRendering(false),m_pTimer(nullptr),m_Res(res),m_pMutex(new QMutex()) { } ///Destructor VideoRenderer::~VideoRenderer() { stopShm(); //delete m_pShmArea; } ///Get the data from shared memory and transform it into a QByteArray QByteArray VideoRenderer::renderToBitmap(QByteArray& data,bool& ok) { if (!m_isRendering) { return QByteArray(); } if (!shmLock()) { ok = false; return QByteArray(); } // wait for a new buffer while (m_BufferGen == m_pShmArea->m_BufferGen) { shmUnlock(); const struct timespec timeout = createTimeout(); int err = sem_timedwait(&m_pShmArea->notification, &timeout); // Useful for debugging // switch (errno ) { // case EINTR: // qDebug() << "Unlock failed: Interrupted function call (POSIX.1); see signal(7)"; // ok = false; // return QByteArray(); // break; // case EINVAL: // qDebug() << "Unlock failed: Invalid argument (POSIX.1)"; // ok = false; // return QByteArray(); // break; // case EAGAIN: // qDebug() << "Unlock failed: Resource temporarily unavailable (may be the same value as EWOULDBLOCK) (POSIX.1)"; // ok = false; // return QByteArray(); // break; // case ETIMEDOUT: // qDebug() << "Unlock failed: Connection timed out (POSIX.1)"; // ok = false; // return QByteArray(); // break; // } if (err < 0) { ok = false; return QByteArray(); } if (!shmLock()) { ok = false; return QByteArray(); } } if (!resizeShm()) { qDebug() << "Could not resize shared memory"; ok = false; return QByteArray(); } if (data.size() != m_pShmArea->m_BufferSize) data.resize(m_pShmArea->m_BufferSize); memcpy(data.data(),m_pShmArea->m_Data,m_pShmArea->m_BufferSize); m_BufferGen = m_pShmArea->m_BufferGen; shmUnlock(); return data; } ///Connect to the shared memory bool VideoRenderer::startShm() { if (fd != -1) { qDebug() << "fd must be -1"; return false; } fd = shm_open(m_ShmPath.toAscii(), O_RDWR, 0); if (fd < 0) { qDebug() << "could not open shm area \"%s\", shm_open failed:%s" << m_ShmPath << strerror(errno); return false; } m_ShmAreaLen = sizeof(SHMHeader); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" m_pShmArea = (SHMHeader*) mmap(NULL, m_ShmAreaLen, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); #pragma GCC diagnostic pop if (m_pShmArea == MAP_FAILED) { qDebug() << "Could not map shm area, mmap failed"; return false; } return true; } ///Disconnect from the shared memory void VideoRenderer::stopShm() { if (fd >= 0) close(fd); fd = -1; if (m_pShmArea != MAP_FAILED) munmap(m_pShmArea, m_ShmAreaLen); m_ShmAreaLen = 0; m_pShmArea = (SHMHeader*) MAP_FAILED; } ///Resize the shared memory bool VideoRenderer::resizeShm() { while (( (unsigned int) sizeof(SHMHeader) + (unsigned int) m_pShmArea->m_BufferSize) > (unsigned int) m_ShmAreaLen) { const size_t new_size = sizeof(SHMHeader) + m_pShmArea->m_BufferSize; shmUnlock(); if (munmap(m_pShmArea, m_ShmAreaLen)) { qDebug() << "Could not unmap shared area:%s" << strerror(errno); return false; } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" m_pShmArea = (SHMHeader*) mmap(NULL, new_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); #pragma GCC diagnostic pop m_ShmAreaLen = new_size; if (!m_pShmArea) { m_pShmArea = nullptr; qDebug() << "Could not remap shared area"; return false; } m_ShmAreaLen = new_size; if (!shmLock()) return false; } return true; } ///Lock the memory while the copy is being made bool VideoRenderer::shmLock() { const timespec timeout = createTimeout(); /* We need an upper limit on how long we'll wait to avoid locking the whole GUI */ if (sem_timedwait(&m_pShmArea->mutex, &timeout) == ETIMEDOUT) { qDebug() << "Timed out before shm lock was acquired"; return false; } return true; } ///Remove the lock, allow a new frame to be drawn void VideoRenderer::shmUnlock() { sem_post(&m_pShmArea->mutex); } ///Create a SHM timeout timespec VideoRenderer::createTimeout() { timespec timeout = {0, 0}; if (clock_gettime(CLOCK_REALTIME, &timeout) == -1) qDebug() << "clock_gettime"; timeout.tv_sec += TIMEOUT_SEC; return timeout; } /***************************************************************************** * * * Slots * * * ****************************************************************************/ ///Update the buffer void VideoRenderer::timedEvents() { bool ok = true; // m_pMutex->lock(); renderToBitmap(m_Frame,ok); // m_pMutex->unlock(); if (ok == true) { emit frameUpdated(); } else { qDebug() << "Frame dropped"; usleep(rand()%1000); //Be sure it can come back in sync } } ///Start the rendering loop void VideoRenderer::startRendering() { startShm(); if (!m_pTimer) { m_pTimer = new QTimer(this); connect(m_pTimer,SIGNAL(timeout()),this,SLOT(timedEvents())); m_pTimer->setInterval(42); } m_pTimer->start(); m_isRendering = true; } ///Stop the rendering loop void VideoRenderer::stopRendering() { m_isRendering = false; stopShm(); //qDebug() << "Video stopped for call" << id; //emit videoStopped(); if (m_pTimer) m_pTimer->stop(); } /***************************************************************************** * * * Getters * * * ****************************************************************************/ ///Get the raw bytes directly from the SHM, not recommended, but optimal const char* VideoRenderer::rawData() { return m_isRendering?m_pShmArea->m_Data:nullptr; } ///Is this redenrer active bool VideoRenderer::isRendering() { return m_isRendering; } ///Return the current framerate QByteArray VideoRenderer::currentFrame() { return m_Frame; } ///Return the current resolution Resolution VideoRenderer::activeResolution() { return m_Res; } ///Get mutex, in case renderer and views are not in the same thread QMutex* VideoRenderer::mutex() { return m_pMutex; } /***************************************************************************** * * * Setters * * * ****************************************************************************/ void VideoRenderer::setResolution(QSize size) { m_Res = size; m_Width = size.width(); m_Height = size.height(); } void VideoRenderer::setShmPath(QString path) { m_ShmPath = path; }
Add #include <KLocale> where necessary
Add #include <KLocale> where necessary
C++
lgpl-2.1
KDE/libringclient,savoirfairelinux/ring-lrc,KDE/libringclient,savoirfairelinux/ring-lrc,savoirfairelinux/ring-lrc,savoirfairelinux/ring-lrc,savoirfairelinux/ring-lrc,KDE/libringclient
25f2158b482553c947ce77414aaf40db9876b6cb
host/commands/wifirouter/router.cc
host/commands/wifirouter/router.cc
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cerrno> #include <map> #include <memory> #include <set> #include <gflags/gflags.h> #include <glog/logging.h> #include <netlink/genl/ctrl.h> #include <netlink/genl/family.h> #include <netlink/genl/genl.h> #include <netlink/netlink.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> DEFINE_string(socket_name, "cvd-wifirouter", "Name of the unix-domain socket providing access for routing. " "Socket will be created in abstract namespace."); namespace { using MacHash = uint64_t; using MacToClientsTable = std::multimap<MacHash, int>; using ClientsTable = std::set<int>; // Copied out of mac80211_hwsim.h header. constexpr int HWSIM_CMD_REGISTER = 1; constexpr int HWSIM_ATTR_ADDR_TRANSMITTER = 2; constexpr int HWSIM_ATTR_MAX = 19; // Name of the WIFI SIM Netlink Family. constexpr char kWifiSimFamilyName[] = "MAC80211_HWSIM"; const int kMaxSupportedPacketSize = getpagesize(); constexpr uint16_t kWifiRouterType = ('W' << 8 | 'R'); enum { WIFIROUTER_ATTR_MAC, // Keep this last. WIFIROUTER_ATTR_MAX }; // Get hash for mac address serialized to 6 bytes of data starting at specified // location. // We don't care about byte ordering as much as we do about having all bytes // there. Byte order does not matter, we want to use it as a key in our map. uint64_t GetMacHash(const void* macaddr) { auto typed = reinterpret_cast<const uint16_t*>(macaddr); return (1ull * typed[0] << 32) | (typed[1] << 16) | typed[2]; } // Enable asynchronous notifications from MAC80211_HWSIM. // - `sock` is a valid netlink socket connected to NETLINK_GENERIC, // - `family` is MAC80211_HWSIM genl family number. // // Upon failure, this function will terminate execution of the program. void RegisterForHWSimNotifications(nl_sock* sock, int family) { std::unique_ptr<nl_msg, void (*)(nl_msg*)> msg( nlmsg_alloc(), [](nl_msg* m) { nlmsg_free(m); }); genlmsg_put(msg.get(), NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_REQUEST, HWSIM_CMD_REGISTER, 0); nl_send_auto(sock, msg.get()); auto res = nl_wait_for_ack(sock); LOG_IF(FATAL, res < 0) << "Could not register for notifications: " << nl_geterror(res); } // Create and configure WIFI Router server socket. // This function is guaranteed to success. If at any point an error is detected, // the function will terminate execution of the program. int CreateWifiRouterServerSocket() { auto fd = socket(AF_UNIX, SOCK_SEQPACKET, 0); LOG_IF(FATAL, fd <= 0) << "Could not create unix socket: " << strerror(-fd); sockaddr_un addr{}; addr.sun_family = AF_UNIX; strncpy(addr.sun_path + 1, FLAGS_socket_name.c_str(), sizeof(addr.sun_path) - 2); auto res = bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)); LOG_IF(FATAL, res < 0) << "Could not bind unix socket: " << strerror(-res); listen(fd, 4); return fd; } // Accept new WIFI Router client. When successful, client will be placed in // clients table. void AcceptNewClient(int server_fd, ClientsTable* clients) { auto client = accept(server_fd, nullptr, nullptr); LOG_IF(ERROR, client < 0) << "Could not accept client: " << strerror(errno); if (client > 0) clients->insert(client); } // Disconnect and remove client from list of registered clients and recipients // of WLAN traffic. void RemoveClient(int client, ClientsTable* clients, MacToClientsTable* targets) { close(client); clients->erase(client); for (auto iter = targets->begin(); iter != targets->end();) { if (iter->second == client) { iter = targets->erase(iter); } else { ++iter; } } } // Read MAC80211HWSIM packet, find the originating MAC address and redirect it // to proper sink. void RouteWIFIPacket(nl_sock* nl, int simfamily, ClientsTable* clients, MacToClientsTable* targets) { sockaddr_nl tmp; uint8_t* buf; const auto len = nl_recv(nl, &tmp, &buf, nullptr); if (len < 0) { LOG(ERROR) << "Could not read from netlink: " << nl_geterror(len); return; } std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(buf), [](nlmsghdr* m) { free(m); }); // Discard messages that originate from anything else than MAC80211_HWSIM. if (msg->nlmsg_type != simfamily) return; // Note, this is generic netlink message, and uses different parsing // technique. nlattr* attrs[HWSIM_ATTR_MAX + 1]; if (genlmsg_parse(msg.get(), 0, attrs, HWSIM_ATTR_MAX, nullptr)) return; std::set<int> pending_removals; if (attrs[HWSIM_ATTR_ADDR_TRANSMITTER] != nullptr) { auto key = GetMacHash(nla_data(attrs[HWSIM_ATTR_ADDR_TRANSMITTER])); VLOG(2) << "Received netlink packet from " << std::hex << key; for (auto it = targets->find(key); it != targets->end() && it->first == key; ++it) { auto num_written = write(it->second, buf, len); if (num_written != len) pending_removals.insert(it->second); } for (auto client : pending_removals) { RemoveClient(client, clients, targets); } } } void HandleClientMessage(int client, ClientsTable* clients, MacToClientsTable* targets) { std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(malloc(kMaxSupportedPacketSize)), [](nlmsghdr* h) { free(h); }); auto size = read(client, msg.get(), kMaxSupportedPacketSize); // Invalid message or no data -> client invalid or disconnected. if (size == 0 || size != msg->nlmsg_len || size < sizeof(nlmsghdr)) { RemoveClient(client, clients, targets); return; } // Accept message, but ignore it. if (msg->nlmsg_type != kWifiRouterType) return; nlattr* attrs[WIFIROUTER_ATTR_MAX]; if (!nlmsg_parse(msg.get(), 0, attrs, WIFIROUTER_ATTR_MAX - 1, nullptr)) { RemoveClient(client, clients, targets); return; } if (attrs[WIFIROUTER_ATTR_MAC] != nullptr) { targets->emplace(GetMacHash(nla_data(attrs[WIFIROUTER_ATTR_MAC])), client); } } // Process incoming requests from netlink, server or clients. void ServerLoop(int server_fd, nl_sock* netlink_sock, int family) { ClientsTable clients; MacToClientsTable targets; int netlink_fd = nl_socket_get_fd(netlink_sock); while (true) { auto max_fd = server_fd; fd_set reads{}; auto fdset = [&max_fd, &reads](int fd) { FD_SET(fd, &reads); max_fd = std::max(max_fd, fd); }; fdset(server_fd); fdset(netlink_fd); for (int client : clients) fdset(client); if (select(max_fd + 1, &reads, nullptr, nullptr, nullptr) <= 0) continue; if (FD_ISSET(server_fd, &reads)) AcceptNewClient(server_fd, &clients); if (FD_ISSET(netlink_fd, &reads)) RouteWIFIPacket(netlink_sock, family, &clients, &targets); for (int client : clients) { if (FD_ISSET(client, &reads)) { HandleClientMessage(client, &clients, &targets); } } } } } // namespace int main(int argc, char* argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); std::unique_ptr<nl_sock, void (*)(nl_sock*)> sock(nl_socket_alloc(), nl_socket_free); auto res = nl_connect(sock.get(), NETLINK_GENERIC); LOG_IF(FATAL, res < 0) << "Could not connect to netlink generic: " << nl_geterror(res); auto mac80211_family = genl_ctrl_resolve(sock.get(), kWifiSimFamilyName); LOG_IF(FATAL, mac80211_family <= 0) << "Could not find MAC80211 HWSIM. Please make sure module " << "'mac80211_hwsim' is loaded on your system."; RegisterForHWSimNotifications(sock.get(), mac80211_family); auto server_fd = CreateWifiRouterServerSocket(); ServerLoop(server_fd, sock.get(), mac80211_family); }
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cerrno> #include <cstddef> #include <map> #include <memory> #include <set> #include <gflags/gflags.h> #include <glog/logging.h> #include <netlink/genl/ctrl.h> #include <netlink/genl/family.h> #include <netlink/genl/genl.h> #include <netlink/netlink.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> DEFINE_string(socket_name, "cvd-wifirouter", "Name of the unix-domain socket providing access for routing. " "Socket will be created in abstract namespace."); namespace { using MacHash = uint64_t; using MacToClientsTable = std::multimap<MacHash, int>; using ClientsTable = std::set<int>; // Copied out of mac80211_hwsim.h header. constexpr int HWSIM_CMD_REGISTER = 1; constexpr int HWSIM_ATTR_ADDR_TRANSMITTER = 2; constexpr int HWSIM_ATTR_MAX = 19; // Name of the WIFI SIM Netlink Family. constexpr char kWifiSimFamilyName[] = "MAC80211_HWSIM"; const int kMaxSupportedPacketSize = getpagesize(); constexpr uint16_t kWifiRouterType = ('W' << 8 | 'R'); enum { WIFIROUTER_ATTR_MAC, // Keep this last. WIFIROUTER_ATTR_MAX }; // Get hash for mac address serialized to 6 bytes of data starting at specified // location. // We don't care about byte ordering as much as we do about having all bytes // there. Byte order does not matter, we want to use it as a key in our map. uint64_t GetMacHash(const void* macaddr) { auto typed = reinterpret_cast<const uint16_t*>(macaddr); return (1ull * typed[0] << 32) | (typed[1] << 16) | typed[2]; } // Enable asynchronous notifications from MAC80211_HWSIM. // - `sock` is a valid netlink socket connected to NETLINK_GENERIC, // - `family` is MAC80211_HWSIM genl family number. // // Upon failure, this function will terminate execution of the program. void RegisterForHWSimNotifications(nl_sock* sock, int family) { std::unique_ptr<nl_msg, void (*)(nl_msg*)> msg( nlmsg_alloc(), [](nl_msg* m) { nlmsg_free(m); }); genlmsg_put(msg.get(), NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_REQUEST, HWSIM_CMD_REGISTER, 0); nl_send_auto(sock, msg.get()); auto res = nl_wait_for_ack(sock); LOG_IF(FATAL, res < 0) << "Could not register for notifications: " << nl_geterror(res); } // Create and configure WIFI Router server socket. // This function is guaranteed to success. If at any point an error is detected, // the function will terminate execution of the program. int CreateWifiRouterServerSocket() { auto fd = socket(AF_UNIX, SOCK_SEQPACKET, 0); LOG_IF(FATAL, fd <= 0) << "Could not create unix socket: " << strerror(-fd); sockaddr_un addr{}; addr.sun_family = AF_UNIX; auto len = std::min(sizeof(addr.sun_path) - 2, FLAGS_socket_name.size()); strncpy(&addr.sun_path[1], FLAGS_socket_name.c_str(), len); len += offsetof(sockaddr_un, sun_path) + 1; // include heading \0 byte. auto res = bind(fd, reinterpret_cast<sockaddr*>(&addr), len); LOG_IF(FATAL, res < 0) << "Could not bind unix socket: " << strerror(-res); listen(fd, 4); return fd; } // Accept new WIFI Router client. When successful, client will be placed in // clients table. void AcceptNewClient(int server_fd, ClientsTable* clients) { auto client = accept(server_fd, nullptr, nullptr); LOG_IF(ERROR, client < 0) << "Could not accept client: " << strerror(errno); if (client > 0) clients->insert(client); } // Disconnect and remove client from list of registered clients and recipients // of WLAN traffic. void RemoveClient(int client, ClientsTable* clients, MacToClientsTable* targets) { close(client); clients->erase(client); for (auto iter = targets->begin(); iter != targets->end();) { if (iter->second == client) { iter = targets->erase(iter); } else { ++iter; } } } // Read MAC80211HWSIM packet, find the originating MAC address and redirect it // to proper sink. void RouteWIFIPacket(nl_sock* nl, int simfamily, ClientsTable* clients, MacToClientsTable* targets) { sockaddr_nl tmp; uint8_t* buf; const auto len = nl_recv(nl, &tmp, &buf, nullptr); if (len < 0) { LOG(ERROR) << "Could not read from netlink: " << nl_geterror(len); return; } std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(buf), [](nlmsghdr* m) { free(m); }); // Discard messages that originate from anything else than MAC80211_HWSIM. if (msg->nlmsg_type != simfamily) return; // Note, this is generic netlink message, and uses different parsing // technique. nlattr* attrs[HWSIM_ATTR_MAX + 1]; if (genlmsg_parse(msg.get(), 0, attrs, HWSIM_ATTR_MAX, nullptr)) return; std::set<int> pending_removals; if (attrs[HWSIM_ATTR_ADDR_TRANSMITTER] != nullptr) { auto key = GetMacHash(nla_data(attrs[HWSIM_ATTR_ADDR_TRANSMITTER])); VLOG(2) << "Received netlink packet from " << std::hex << key; for (auto it = targets->find(key); it != targets->end() && it->first == key; ++it) { auto num_written = write(it->second, buf, len); if (num_written != len) pending_removals.insert(it->second); } for (auto client : pending_removals) { RemoveClient(client, clients, targets); } } } void HandleClientMessage(int client, ClientsTable* clients, MacToClientsTable* targets) { std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(malloc(kMaxSupportedPacketSize)), [](nlmsghdr* h) { free(h); }); auto size = read(client, msg.get(), kMaxSupportedPacketSize); // Invalid message or no data -> client invalid or disconnected. if (size == 0 || size != msg->nlmsg_len || size < sizeof(nlmsghdr)) { RemoveClient(client, clients, targets); return; } // Accept message, but ignore it. if (msg->nlmsg_type != kWifiRouterType) return; nlattr* attrs[WIFIROUTER_ATTR_MAX]; if (!nlmsg_parse(msg.get(), 0, attrs, WIFIROUTER_ATTR_MAX - 1, nullptr)) { RemoveClient(client, clients, targets); return; } if (attrs[WIFIROUTER_ATTR_MAC] != nullptr) { targets->emplace(GetMacHash(nla_data(attrs[WIFIROUTER_ATTR_MAC])), client); } } // Process incoming requests from netlink, server or clients. void ServerLoop(int server_fd, nl_sock* netlink_sock, int family) { ClientsTable clients; MacToClientsTable targets; int netlink_fd = nl_socket_get_fd(netlink_sock); while (true) { auto max_fd = server_fd; fd_set reads{}; auto fdset = [&max_fd, &reads](int fd) { FD_SET(fd, &reads); max_fd = std::max(max_fd, fd); }; fdset(server_fd); fdset(netlink_fd); for (int client : clients) fdset(client); if (select(max_fd + 1, &reads, nullptr, nullptr, nullptr) <= 0) continue; if (FD_ISSET(server_fd, &reads)) AcceptNewClient(server_fd, &clients); if (FD_ISSET(netlink_fd, &reads)) RouteWIFIPacket(netlink_sock, family, &clients, &targets); for (int client : clients) { if (FD_ISSET(client, &reads)) { HandleClientMessage(client, &clients, &targets); } } } } } // namespace int main(int argc, char* argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); std::unique_ptr<nl_sock, void (*)(nl_sock*)> sock(nl_socket_alloc(), nl_socket_free); auto res = nl_connect(sock.get(), NETLINK_GENERIC); LOG_IF(FATAL, res < 0) << "Could not connect to netlink generic: " << nl_geterror(res); auto mac80211_family = genl_ctrl_resolve(sock.get(), kWifiSimFamilyName); LOG_IF(FATAL, mac80211_family <= 0) << "Could not find MAC80211 HWSIM. Please make sure module " << "'mac80211_hwsim' is loaded on your system."; RegisterForHWSimNotifications(sock.get(), mac80211_family); auto server_fd = CreateWifiRouterServerSocket(); ServerLoop(server_fd, sock.get(), mac80211_family); }
trim unix socket path length.
trim unix socket path length. This change fixes unix socket path: @cvd-wifirouter@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@... to @cvd-wifirouter Change-Id: Ib49d5248c4eb39b9678f61450bd51da4918f7b7f
C++
apache-2.0
google/android-cuttlefish,google/android-cuttlefish,google/android-cuttlefish,google/android-cuttlefish,google/android-cuttlefish,google/android-cuttlefish,google/android-cuttlefish
21674ab156c0a01b7b9ad8efa01ecb33ca5248f8
iRODS/lib/api/include/fileOpen.hpp
iRODS/lib/api/include/fileOpen.hpp
/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* fileOpen.h - This file may be generated by a program or script */ #ifndef FILE_OPEN_HPP #define FILE_OPEN_HPP /* This is a low level file type API call */ #include "rods.hpp" #include "rcMisc.hpp" #include "procApiRequest.hpp" #include "apiNumber.hpp" #include "initServer.hpp" /* definition for otherFlags */ #define NO_CHK_PERM_FLAG 0x1 // JMC - backport 4758 #define UNIQUE_REM_COMM_FLAG 0x2 #define FORCE_FLAG 0x4 typedef struct { char resc_name_[MAX_NAME_LEN]; char resc_hier_[MAX_NAME_LEN]; char objPath[MAX_NAME_LEN]; int otherFlags; /* for chkPerm, uniqueRemoteConn */ rodsHostAddr_t addr; char fileName[MAX_NAME_LEN]; int flags; int mode; rodsLong_t dataSize; keyValPair_t condInput; char in_pdmo[MAX_NAME_LEN]; } fileOpenInp_t; #define fileOpenInp_PI "str resc_name_[MAX_NAME_LEN]; str resc_hier_[MAX_NAME_LEN]; str objPath[MAX_NAME_LEN]; int otherFlags; struct RHostAddr_PI; str fileName[MAX_NAME_LEN]; int flags; int mode; double dataSize; struct KeyValPair_PI; str in_pdmo[MAX_NAME_LEN];" #if defined(RODS_SERVER) #define RS_FILE_OPEN rsFileOpen /* prototype for the server handler */ int rsFileOpen( rsComm_t *rsComm, fileOpenInp_t *fileOpenInp ); int rsFileOpenByHost( rsComm_t *rsComm, fileOpenInp_t *fileOpenInp, rodsServerHost_t *rodsServerHost ); int _rsFileOpen( rsComm_t *rsComm, fileOpenInp_t *fileOpenInp ); int remoteFileOpen( rsComm_t *rsComm, fileOpenInp_t *fileOpenInp, rodsServerHost_t *rodsServerHost ); #else #define RS_FILE_OPEN NULL #endif /* prototype for the client call */ #ifdef __cplusplus extern "C" { #endif int rcFileOpen( rcComm_t *conn, fileOpenInp_t *fileOpenInp ); #ifdef __cplusplus } #endif #endif /* FILE_OPEN_H */
/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* fileOpen.h - This file may be generated by a program or script */ #ifndef FILE_OPEN_HPP #define FILE_OPEN_HPP /* This is a low level file type API call */ #include "rods.hpp" #include "rcMisc.hpp" #include "procApiRequest.hpp" #include "apiNumber.hpp" #include "initServer.hpp" /* definition for otherFlags */ #define NO_CHK_PERM_FLAG 0x1 // JMC - backport 4758 #define UNIQUE_REM_COMM_FLAG 0x2 #define FORCE_FLAG 0x4 typedef struct { char resc_name_[MAX_NAME_LEN]; char resc_hier_[MAX_NAME_LEN]; char objPath[MAX_NAME_LEN]; int otherFlags; /* for chkPerm, uniqueRemoteConn */ rodsHostAddr_t addr; char fileName[MAX_NAME_LEN]; int flags; int mode; keyValPair_t condInput; char in_pdmo[MAX_NAME_LEN]; rodsLong_t dataSize; } fileOpenInp_t; #define fileOpenInp_PI "str resc_name_[MAX_NAME_LEN]; str resc_hier_[MAX_NAME_LEN]; str objPath[MAX_NAME_LEN]; int otherFlags; struct RHostAddr_PI; str fileName[MAX_NAME_LEN]; int flags; int mode; struct KeyValPair_PI; str in_pdmo[MAX_NAME_LEN]; double dataSize;" #if defined(RODS_SERVER) #define RS_FILE_OPEN rsFileOpen /* prototype for the server handler */ int rsFileOpen( rsComm_t *rsComm, fileOpenInp_t *fileOpenInp ); int rsFileOpenByHost( rsComm_t *rsComm, fileOpenInp_t *fileOpenInp, rodsServerHost_t *rodsServerHost ); int _rsFileOpen( rsComm_t *rsComm, fileOpenInp_t *fileOpenInp ); int remoteFileOpen( rsComm_t *rsComm, fileOpenInp_t *fileOpenInp, rodsServerHost_t *rodsServerHost ); #else #define RS_FILE_OPEN NULL #endif /* prototype for the client call */ #ifdef __cplusplus extern "C" { #endif int rcFileOpen( rcComm_t *conn, fileOpenInp_t *fileOpenInp ); #ifdef __cplusplus } #endif #endif /* FILE_OPEN_H */
move rodsLong_t to end of packing instruction for safety
[#2248] move rodsLong_t to end of packing instruction for safety
C++
bsd-3-clause
PaulVanSchayck/irods,PaulVanSchayck/irods,janiheikkinen/irods,PaulVanSchayck/irods,janiheikkinen/irods,janiheikkinen/irods,PaulVanSchayck/irods,janiheikkinen/irods,janiheikkinen/irods,PaulVanSchayck/irods,janiheikkinen/irods,PaulVanSchayck/irods,PaulVanSchayck/irods,janiheikkinen/irods,janiheikkinen/irods,janiheikkinen/irods,PaulVanSchayck/irods,PaulVanSchayck/irods
24bc5c3a40af99115ecbcf6a83bd3be66a93b95b
gui/apitrace.cpp
gui/apitrace.cpp
#include "apitrace.h" #include "traceloader.h" #include "saverthread.h" #include <QDebug> #include <QDir> #include <QThread> ApiTrace::ApiTrace() : m_needsSaving(false) { m_loader = new TraceLoader(); connect(this, SIGNAL(loadTrace(QString)), m_loader, SLOT(loadTrace(QString))); connect(this, SIGNAL(requestFrame(ApiTraceFrame*)), m_loader, SLOT(loadFrame(ApiTraceFrame*))); connect(m_loader, SIGNAL(framesLoaded(const QList<ApiTraceFrame*>)), this, SLOT(addFrames(const QList<ApiTraceFrame*>))); connect(m_loader, SIGNAL(frameContentsLoaded(ApiTraceFrame*,QVector<ApiTraceCall*>, QVector<ApiTraceCall*>,quint64)), this, SLOT(loaderFrameLoaded(ApiTraceFrame*,QVector<ApiTraceCall*>,QVector<ApiTraceCall*>,quint64))); connect(m_loader, SIGNAL(guessedApi(int)), this, SLOT(guessedApi(int))); connect(this, SIGNAL(loaderSearch(ApiTrace::SearchRequest)), m_loader, SLOT(search(ApiTrace::SearchRequest))); connect(m_loader, SIGNAL(searchResult(ApiTrace::SearchRequest,ApiTrace::SearchResult,ApiTraceCall*)), this, SLOT(loaderSearchResult(ApiTrace::SearchRequest,ApiTrace::SearchResult,ApiTraceCall*))); connect(this, SIGNAL(loaderFindFrameStart(ApiTraceFrame*)), m_loader, SLOT(findFrameStart(ApiTraceFrame*))); connect(this, SIGNAL(loaderFindFrameEnd(ApiTraceFrame*)), m_loader, SLOT(findFrameEnd(ApiTraceFrame*))); connect(m_loader, SIGNAL(foundFrameStart(ApiTraceFrame*)), this, SIGNAL(foundFrameStart(ApiTraceFrame*))); connect(m_loader, SIGNAL(foundFrameEnd(ApiTraceFrame*)), this, SIGNAL(foundFrameEnd(ApiTraceFrame*))); connect(this, SIGNAL(loaderFindCallIndex(int)), m_loader, SLOT(findCallIndex(int))); connect(m_loader, SIGNAL(foundCallIndex(ApiTraceCall*)), this, SIGNAL(foundCallIndex(ApiTraceCall*))); connect(m_loader, SIGNAL(startedParsing()), this, SIGNAL(startedLoadingTrace())); connect(m_loader, SIGNAL(parsed(int)), this, SIGNAL(loaded(int))); connect(m_loader, SIGNAL(finishedParsing()), this, SIGNAL(finishedLoadingTrace())); m_saver = new SaverThread(this); connect(m_saver, SIGNAL(traceSaved()), this, SLOT(slotSaved())); connect(m_saver, SIGNAL(traceSaved()), this, SIGNAL(saved())); m_loaderThread = new QThread(); m_loader->moveToThread(m_loaderThread); m_loaderThread->start(); } ApiTrace::~ApiTrace() { m_loaderThread->quit(); m_loaderThread->deleteLater(); qDeleteAll(m_frames); delete m_loader; delete m_saver; } bool ApiTrace::isEmpty() const { return m_frames.isEmpty(); } QString ApiTrace::fileName() const { if (edited()) { return m_tempFileName; } return m_fileName; } const QList<ApiTraceFrame*> & ApiTrace::frames() const { return m_frames; } ApiTraceFrame * ApiTrace::frameAt(int idx) const { return m_frames.value(idx); } int ApiTrace::numFrames() const { return m_frames.count(); } int ApiTrace::numCallsInFrame(int idx) const { const ApiTraceFrame *frame = frameAt(idx); if (frame) { return frame->numTotalCalls(); } else { return 0; } } void ApiTrace::setFileName(const QString &name) { if (m_fileName != name) { m_fileName = name; m_tempFileName = QString(); m_frames.clear(); m_errors.clear(); m_editedCalls.clear(); m_queuedErrors.clear(); m_needsSaving = false; emit invalidated(); emit loadTrace(m_fileName); } } void ApiTrace::addFrames(const QList<ApiTraceFrame*> &frames) { int currentFrames = m_frames.count(); int numNewFrames = frames.count(); emit beginAddingFrames(currentFrames, numNewFrames); m_frames += frames; foreach(ApiTraceFrame *frame, frames) { frame->setParentTrace(this); } emit endAddingFrames(); } ApiTraceCall * ApiTrace::callWithIndex(int idx) const { for (int i = 0; i < m_frames.count(); ++i) { ApiTraceCall *call = m_frames[i]->callWithIndex(idx); if (call) { return call; } } return NULL; } ApiTraceState ApiTrace::defaultState() const { ApiTraceFrame *frame = frameAt(0); if (!frame || !frame->isLoaded() || frame->isEmpty()) { return ApiTraceState(); } ApiTraceCall *firstCall = frame->calls().first(); if (!firstCall->hasState()) { return ApiTraceState(); } return *firstCall->state(); } void ApiTrace::callEdited(ApiTraceCall *call) { if (!m_editedCalls.contains(call)) { //lets generate a temp filename QString tempPath = QDir::tempPath(); m_tempFileName = QString::fromLatin1("%1/%2.edited") .arg(tempPath) .arg(m_fileName); } m_editedCalls.insert(call); m_needsSaving = true; emit changed(call); } void ApiTrace::callReverted(ApiTraceCall *call) { m_editedCalls.remove(call); if (m_editedCalls.isEmpty()) { m_needsSaving = false; } emit changed(call); } bool ApiTrace::edited() const { return !m_editedCalls.isEmpty(); } bool ApiTrace::needsSaving() const { return m_needsSaving; } void ApiTrace::save() { QFileInfo fi(m_tempFileName); QDir dir; emit startedSaving(); dir.mkpath(fi.absolutePath()); m_saver->saveFile(m_tempFileName, m_fileName, m_editedCalls); } void ApiTrace::slotSaved() { m_needsSaving = false; } bool ApiTrace::isSaving() const { return m_saver->isRunning(); } bool ApiTrace::hasErrors() const { return !m_errors.isEmpty() || !m_queuedErrors.isEmpty(); } void ApiTrace::loadFrame(ApiTraceFrame *frame) { if (!isFrameLoading(frame)) { Q_ASSERT(!frame->isLoaded()); m_loadingFrames.insert(frame); emit requestFrame(frame); } } void ApiTrace::guessedApi(int api) { m_api = static_cast<trace::API>(api); } trace::API ApiTrace::api() const { return m_api; } void ApiTrace::finishedParsing() { if (!m_frames.isEmpty()) { ApiTraceFrame *firstFrame = m_frames[0]; if (firstFrame && !firstFrame->isLoaded()) { loadFrame(firstFrame); } } } void ApiTrace::loaderFrameLoaded(ApiTraceFrame *frame, const QVector<ApiTraceCall*> &topLevelItems, const QVector<ApiTraceCall*> &calls, quint64 binaryDataSize) { Q_ASSERT(frame->numChildrenToLoad() >= calls.size()); if (!frame->isLoaded()) { emit beginLoadingFrame(frame, calls.size()); frame->setCalls(topLevelItems, calls, binaryDataSize); emit endLoadingFrame(frame); m_loadingFrames.remove(frame); } if (!m_queuedErrors.isEmpty()) { QList< QPair<ApiTraceFrame*, ApiTraceError> >::iterator itr; for (itr = m_queuedErrors.begin(); itr != m_queuedErrors.end(); ++itr) { const ApiTraceError &error = (*itr).second; if ((*itr).first == frame) { ApiTraceCall *call = frame->callWithIndex(error.callIndex); if (!call) { continue; } call->setError(error.message); m_queuedErrors.erase(itr); if (call->hasError()) { m_errors.insert(call); } else { m_errors.remove(call); } emit changed(call); } } } } void ApiTrace::findNext(ApiTraceFrame *frame, ApiTraceCall *from, const QString &str, Qt::CaseSensitivity sensitivity) { ApiTraceCall *foundCall = 0; int frameIdx = m_frames.indexOf(frame); SearchRequest request(SearchRequest::Next, frame, from, str, sensitivity); if (frame->isLoaded()) { foundCall = frame->findNextCall(from, str, sensitivity); if (foundCall) { emit findResult(request, SearchResult_Found, foundCall); return; } //if the frame is loaded we already searched it above // so skip it frameIdx += 1; } //for the rest of the frames we search from beginning request.from = 0; for (int i = frameIdx; i < m_frames.count(); ++i) { ApiTraceFrame *frame = m_frames[i]; request.frame = frame; if (!frame->isLoaded()) { emit loaderSearch(request); return; } else { ApiTraceCall *call = frame->findNextCall(0, str, sensitivity); if (call) { emit findResult(request, SearchResult_Found, call); return; } } } emit findResult(request, SearchResult_Wrapped, 0); } void ApiTrace::findPrev(ApiTraceFrame *frame, ApiTraceCall *from, const QString &str, Qt::CaseSensitivity sensitivity) { ApiTraceCall *foundCall = 0; int frameIdx = m_frames.indexOf(frame); SearchRequest request(SearchRequest::Prev, frame, from, str, sensitivity); if (frame->isLoaded()) { foundCall = frame->findPrevCall(from, str, sensitivity); if (foundCall) { emit findResult(request, SearchResult_Found, foundCall); return; } //if the frame is loaded we already searched it above // so skip it frameIdx -= 1; } request.from = 0; for (int i = frameIdx; i >= 0; --i) { ApiTraceFrame *frame = m_frames[i]; request.frame = frame; if (!frame->isLoaded()) { emit loaderSearch(request); return; } else { ApiTraceCall *call = frame->findPrevCall(0, str, sensitivity); if (call) { emit findResult(request, SearchResult_Found, call); return; } } } emit findResult(request, SearchResult_Wrapped, 0); } void ApiTrace::loaderSearchResult(const ApiTrace::SearchRequest &request, ApiTrace::SearchResult result, ApiTraceCall *call) { //qDebug()<<"Search result = "<<result // <<", call is = "<<call; emit findResult(request, result, call); } void ApiTrace::findFrameStart(ApiTraceFrame *frame) { if (!frame) return; if (frame->isLoaded()) { emit foundFrameStart(frame); } else { emit loaderFindFrameStart(frame); } } void ApiTrace::findFrameEnd(ApiTraceFrame *frame) { if (!frame) return; if (frame->isLoaded()) { emit foundFrameEnd(frame); } else { emit loaderFindFrameEnd(frame); } } void ApiTrace::findCallIndex(int index) { int frameIdx = callInFrame(index); ApiTraceFrame *frame = 0; if (frameIdx < 0) { emit foundCallIndex(0); return; } frame = m_frames[frameIdx]; if (frame) { if (frame->isLoaded()) { ApiTraceCall *call = frame->callWithIndex(index); emit foundCallIndex(call); } else { emit loaderFindCallIndex(index); } } } int ApiTrace::callInFrame(int callIdx) const { unsigned numCalls = 0; for (int frameIdx = 0; frameIdx < m_frames.size(); ++frameIdx) { const ApiTraceFrame *frame = m_frames[frameIdx]; unsigned numCallsInFrame = frame->isLoaded() ? frame->numTotalCalls() : frame->numChildrenToLoad(); unsigned firstCall = numCalls; unsigned endCall = numCalls + numCallsInFrame; if (firstCall <= callIdx && endCall > callIdx) { return frameIdx; } numCalls = endCall; } return -1; } void ApiTrace::setCallError(const ApiTraceError &error) { int frameIdx = callInFrame(error.callIndex); ApiTraceFrame *frame = 0; if (frameIdx < 0) { return; } frame = m_frames[frameIdx]; if (frame->isLoaded()) { ApiTraceCall *call = frame->callWithIndex(error.callIndex); call->setError(error.message); if (call->hasError()) { m_errors.insert(call); } else { m_errors.remove(call); } emit changed(call); } else { loadFrame(frame); m_queuedErrors.append(qMakePair(frame, error)); } } bool ApiTrace::isFrameLoading(ApiTraceFrame *frame) const { return m_loadingFrames.contains(frame); } void ApiTrace::bindThumbnailsToFrames(const QList<QImage> &thumbnails) { QList<ApiTraceFrame *> frames = m_frames; QList<QImage>::const_iterator thumbnail = thumbnails.begin(); foreach (ApiTraceFrame *frame, frames) { if (thumbnail != thumbnails.end()) { frame->setThumbnail(*thumbnail); ++thumbnail; emit changed(frame); } } } #include "apitrace.moc"
#include "apitrace.h" #include "traceloader.h" #include "saverthread.h" #include <QDebug> #include <QFileInfo> #include <QDir> #include <QThread> ApiTrace::ApiTrace() : m_needsSaving(false) { m_loader = new TraceLoader(); connect(this, SIGNAL(loadTrace(QString)), m_loader, SLOT(loadTrace(QString))); connect(this, SIGNAL(requestFrame(ApiTraceFrame*)), m_loader, SLOT(loadFrame(ApiTraceFrame*))); connect(m_loader, SIGNAL(framesLoaded(const QList<ApiTraceFrame*>)), this, SLOT(addFrames(const QList<ApiTraceFrame*>))); connect(m_loader, SIGNAL(frameContentsLoaded(ApiTraceFrame*,QVector<ApiTraceCall*>, QVector<ApiTraceCall*>,quint64)), this, SLOT(loaderFrameLoaded(ApiTraceFrame*,QVector<ApiTraceCall*>,QVector<ApiTraceCall*>,quint64))); connect(m_loader, SIGNAL(guessedApi(int)), this, SLOT(guessedApi(int))); connect(this, SIGNAL(loaderSearch(ApiTrace::SearchRequest)), m_loader, SLOT(search(ApiTrace::SearchRequest))); connect(m_loader, SIGNAL(searchResult(ApiTrace::SearchRequest,ApiTrace::SearchResult,ApiTraceCall*)), this, SLOT(loaderSearchResult(ApiTrace::SearchRequest,ApiTrace::SearchResult,ApiTraceCall*))); connect(this, SIGNAL(loaderFindFrameStart(ApiTraceFrame*)), m_loader, SLOT(findFrameStart(ApiTraceFrame*))); connect(this, SIGNAL(loaderFindFrameEnd(ApiTraceFrame*)), m_loader, SLOT(findFrameEnd(ApiTraceFrame*))); connect(m_loader, SIGNAL(foundFrameStart(ApiTraceFrame*)), this, SIGNAL(foundFrameStart(ApiTraceFrame*))); connect(m_loader, SIGNAL(foundFrameEnd(ApiTraceFrame*)), this, SIGNAL(foundFrameEnd(ApiTraceFrame*))); connect(this, SIGNAL(loaderFindCallIndex(int)), m_loader, SLOT(findCallIndex(int))); connect(m_loader, SIGNAL(foundCallIndex(ApiTraceCall*)), this, SIGNAL(foundCallIndex(ApiTraceCall*))); connect(m_loader, SIGNAL(startedParsing()), this, SIGNAL(startedLoadingTrace())); connect(m_loader, SIGNAL(parsed(int)), this, SIGNAL(loaded(int))); connect(m_loader, SIGNAL(finishedParsing()), this, SIGNAL(finishedLoadingTrace())); m_saver = new SaverThread(this); connect(m_saver, SIGNAL(traceSaved()), this, SLOT(slotSaved())); connect(m_saver, SIGNAL(traceSaved()), this, SIGNAL(saved())); m_loaderThread = new QThread(); m_loader->moveToThread(m_loaderThread); m_loaderThread->start(); } ApiTrace::~ApiTrace() { m_loaderThread->quit(); m_loaderThread->deleteLater(); qDeleteAll(m_frames); delete m_loader; delete m_saver; } bool ApiTrace::isEmpty() const { return m_frames.isEmpty(); } QString ApiTrace::fileName() const { if (edited()) { return m_tempFileName; } return m_fileName; } const QList<ApiTraceFrame*> & ApiTrace::frames() const { return m_frames; } ApiTraceFrame * ApiTrace::frameAt(int idx) const { return m_frames.value(idx); } int ApiTrace::numFrames() const { return m_frames.count(); } int ApiTrace::numCallsInFrame(int idx) const { const ApiTraceFrame *frame = frameAt(idx); if (frame) { return frame->numTotalCalls(); } else { return 0; } } void ApiTrace::setFileName(const QString &name) { if (m_fileName != name) { m_fileName = name; m_tempFileName = QString(); m_frames.clear(); m_errors.clear(); m_editedCalls.clear(); m_queuedErrors.clear(); m_needsSaving = false; emit invalidated(); emit loadTrace(m_fileName); } } void ApiTrace::addFrames(const QList<ApiTraceFrame*> &frames) { int currentFrames = m_frames.count(); int numNewFrames = frames.count(); emit beginAddingFrames(currentFrames, numNewFrames); m_frames += frames; foreach(ApiTraceFrame *frame, frames) { frame->setParentTrace(this); } emit endAddingFrames(); } ApiTraceCall * ApiTrace::callWithIndex(int idx) const { for (int i = 0; i < m_frames.count(); ++i) { ApiTraceCall *call = m_frames[i]->callWithIndex(idx); if (call) { return call; } } return NULL; } ApiTraceState ApiTrace::defaultState() const { ApiTraceFrame *frame = frameAt(0); if (!frame || !frame->isLoaded() || frame->isEmpty()) { return ApiTraceState(); } ApiTraceCall *firstCall = frame->calls().first(); if (!firstCall->hasState()) { return ApiTraceState(); } return *firstCall->state(); } void ApiTrace::callEdited(ApiTraceCall *call) { if (!m_editedCalls.contains(call)) { // Lets generate a temp filename QFileInfo fileInfo(m_fileName); QString tempPath = QDir::tempPath(); m_tempFileName = QDir::tempPath(); m_tempFileName += QDir::separator(); m_tempFileName += fileInfo.fileName(); m_tempFileName += QString::fromLatin1(".edited"); } m_editedCalls.insert(call); m_needsSaving = true; emit changed(call); } void ApiTrace::callReverted(ApiTraceCall *call) { m_editedCalls.remove(call); if (m_editedCalls.isEmpty()) { m_needsSaving = false; } emit changed(call); } bool ApiTrace::edited() const { return !m_editedCalls.isEmpty(); } bool ApiTrace::needsSaving() const { return m_needsSaving; } void ApiTrace::save() { QFileInfo fi(m_tempFileName); QDir dir; emit startedSaving(); dir.mkpath(fi.absolutePath()); m_saver->saveFile(m_tempFileName, m_fileName, m_editedCalls); } void ApiTrace::slotSaved() { m_needsSaving = false; } bool ApiTrace::isSaving() const { return m_saver->isRunning(); } bool ApiTrace::hasErrors() const { return !m_errors.isEmpty() || !m_queuedErrors.isEmpty(); } void ApiTrace::loadFrame(ApiTraceFrame *frame) { if (!isFrameLoading(frame)) { Q_ASSERT(!frame->isLoaded()); m_loadingFrames.insert(frame); emit requestFrame(frame); } } void ApiTrace::guessedApi(int api) { m_api = static_cast<trace::API>(api); } trace::API ApiTrace::api() const { return m_api; } void ApiTrace::finishedParsing() { if (!m_frames.isEmpty()) { ApiTraceFrame *firstFrame = m_frames[0]; if (firstFrame && !firstFrame->isLoaded()) { loadFrame(firstFrame); } } } void ApiTrace::loaderFrameLoaded(ApiTraceFrame *frame, const QVector<ApiTraceCall*> &topLevelItems, const QVector<ApiTraceCall*> &calls, quint64 binaryDataSize) { Q_ASSERT(frame->numChildrenToLoad() >= calls.size()); if (!frame->isLoaded()) { emit beginLoadingFrame(frame, calls.size()); frame->setCalls(topLevelItems, calls, binaryDataSize); emit endLoadingFrame(frame); m_loadingFrames.remove(frame); } if (!m_queuedErrors.isEmpty()) { QList< QPair<ApiTraceFrame*, ApiTraceError> >::iterator itr; for (itr = m_queuedErrors.begin(); itr != m_queuedErrors.end(); ++itr) { const ApiTraceError &error = (*itr).second; if ((*itr).first == frame) { ApiTraceCall *call = frame->callWithIndex(error.callIndex); if (!call) { continue; } call->setError(error.message); m_queuedErrors.erase(itr); if (call->hasError()) { m_errors.insert(call); } else { m_errors.remove(call); } emit changed(call); } } } } void ApiTrace::findNext(ApiTraceFrame *frame, ApiTraceCall *from, const QString &str, Qt::CaseSensitivity sensitivity) { ApiTraceCall *foundCall = 0; int frameIdx = m_frames.indexOf(frame); SearchRequest request(SearchRequest::Next, frame, from, str, sensitivity); if (frame->isLoaded()) { foundCall = frame->findNextCall(from, str, sensitivity); if (foundCall) { emit findResult(request, SearchResult_Found, foundCall); return; } //if the frame is loaded we already searched it above // so skip it frameIdx += 1; } //for the rest of the frames we search from beginning request.from = 0; for (int i = frameIdx; i < m_frames.count(); ++i) { ApiTraceFrame *frame = m_frames[i]; request.frame = frame; if (!frame->isLoaded()) { emit loaderSearch(request); return; } else { ApiTraceCall *call = frame->findNextCall(0, str, sensitivity); if (call) { emit findResult(request, SearchResult_Found, call); return; } } } emit findResult(request, SearchResult_Wrapped, 0); } void ApiTrace::findPrev(ApiTraceFrame *frame, ApiTraceCall *from, const QString &str, Qt::CaseSensitivity sensitivity) { ApiTraceCall *foundCall = 0; int frameIdx = m_frames.indexOf(frame); SearchRequest request(SearchRequest::Prev, frame, from, str, sensitivity); if (frame->isLoaded()) { foundCall = frame->findPrevCall(from, str, sensitivity); if (foundCall) { emit findResult(request, SearchResult_Found, foundCall); return; } //if the frame is loaded we already searched it above // so skip it frameIdx -= 1; } request.from = 0; for (int i = frameIdx; i >= 0; --i) { ApiTraceFrame *frame = m_frames[i]; request.frame = frame; if (!frame->isLoaded()) { emit loaderSearch(request); return; } else { ApiTraceCall *call = frame->findPrevCall(0, str, sensitivity); if (call) { emit findResult(request, SearchResult_Found, call); return; } } } emit findResult(request, SearchResult_Wrapped, 0); } void ApiTrace::loaderSearchResult(const ApiTrace::SearchRequest &request, ApiTrace::SearchResult result, ApiTraceCall *call) { //qDebug()<<"Search result = "<<result // <<", call is = "<<call; emit findResult(request, result, call); } void ApiTrace::findFrameStart(ApiTraceFrame *frame) { if (!frame) return; if (frame->isLoaded()) { emit foundFrameStart(frame); } else { emit loaderFindFrameStart(frame); } } void ApiTrace::findFrameEnd(ApiTraceFrame *frame) { if (!frame) return; if (frame->isLoaded()) { emit foundFrameEnd(frame); } else { emit loaderFindFrameEnd(frame); } } void ApiTrace::findCallIndex(int index) { int frameIdx = callInFrame(index); ApiTraceFrame *frame = 0; if (frameIdx < 0) { emit foundCallIndex(0); return; } frame = m_frames[frameIdx]; if (frame) { if (frame->isLoaded()) { ApiTraceCall *call = frame->callWithIndex(index); emit foundCallIndex(call); } else { emit loaderFindCallIndex(index); } } } int ApiTrace::callInFrame(int callIdx) const { unsigned numCalls = 0; for (int frameIdx = 0; frameIdx < m_frames.size(); ++frameIdx) { const ApiTraceFrame *frame = m_frames[frameIdx]; unsigned numCallsInFrame = frame->isLoaded() ? frame->numTotalCalls() : frame->numChildrenToLoad(); unsigned firstCall = numCalls; unsigned endCall = numCalls + numCallsInFrame; if (firstCall <= callIdx && endCall > callIdx) { return frameIdx; } numCalls = endCall; } return -1; } void ApiTrace::setCallError(const ApiTraceError &error) { int frameIdx = callInFrame(error.callIndex); ApiTraceFrame *frame = 0; if (frameIdx < 0) { return; } frame = m_frames[frameIdx]; if (frame->isLoaded()) { ApiTraceCall *call = frame->callWithIndex(error.callIndex); call->setError(error.message); if (call->hasError()) { m_errors.insert(call); } else { m_errors.remove(call); } emit changed(call); } else { loadFrame(frame); m_queuedErrors.append(qMakePair(frame, error)); } } bool ApiTrace::isFrameLoading(ApiTraceFrame *frame) const { return m_loadingFrames.contains(frame); } void ApiTrace::bindThumbnailsToFrames(const QList<QImage> &thumbnails) { QList<ApiTraceFrame *> frames = m_frames; QList<QImage>::const_iterator thumbnail = thumbnails.begin(); foreach (ApiTraceFrame *frame, frames) { if (thumbnail != thumbnails.end()) { frame->setThumbnail(*thumbnail); ++thumbnail; emit changed(frame); } } } #include "apitrace.moc"
Use only the file name portion for the temporary edited trace.
gui: Use only the file name portion for the temporary edited trace.
C++
mit
trtt/apitrace,tuanthng/apitrace,apitrace/apitrace,apitrace/apitrace,surround-io/apitrace,joshua5201/apitrace,joshua5201/apitrace,tuanthng/apitrace,schulmar/apitrace,EoD/apitrace,surround-io/apitrace,apitrace/apitrace,swq0553/apitrace,trtt/apitrace,swq0553/apitrace,swq0553/apitrace,joshua5201/apitrace,surround-io/apitrace,trtt/apitrace,surround-io/apitrace,joshua5201/apitrace,joshua5201/apitrace,EoD/apitrace,schulmar/apitrace,schulmar/apitrace,schulmar/apitrace,EoD/apitrace,swq0553/apitrace,schulmar/apitrace,apitrace/apitrace,swq0553/apitrace,trtt/apitrace,surround-io/apitrace,trtt/apitrace,tuanthng/apitrace,tuanthng/apitrace,EoD/apitrace,tuanthng/apitrace,EoD/apitrace
d9a73568b0a26c57d0fac8ee97550d0989b9c321
gui/retracer.cpp
gui/retracer.cpp
#include "retracer.h" #include "apitracecall.h" #include "thumbnail.h" #include "image.hpp" #include "trace_profiler.hpp" #include <QDebug> #include <QVariant> #include <QList> #include <QImage> #include <qjson/parser.h> /** * Wrapper around a QProcess which enforces IO to block . * * Several QIODevice users (notably QJSON) expect blocking semantics, e.g., * they expect that QIODevice::read() will blocked until the requested ammount * of bytes is read or end of file is reached. But by default QProcess, does * not block. And passing QIODevice::Unbuffered mitigates but does not fully * address the problem either. * * This class wraps around QProcess, providing QIODevice interface, while * ensuring that all reads block. * * This class also works around a bug in QProcess::atEnd() implementation. * * See also: * - http://qt-project.org/wiki/Simple_Crypt_IO_Device * - http://qt-project.org/wiki/Custom_IO_Device */ class BlockingIODevice : public QIODevice { /* We don't use the Q_OBJECT in this class given we don't declare any * signals and slots or use any other services provided by Qt's meta-object * system. */ public: BlockingIODevice(QProcess * io); bool isSequential() const; bool atEnd() const; bool waitForReadyRead(int msecs = -1); protected: qint64 readData(char * data, qint64 maxSize); qint64 writeData(const char * data, qint64 maxSize); private: QProcess *m_device; }; BlockingIODevice::BlockingIODevice(QProcess * io) : m_device(io) { /* * We pass QIODevice::Unbuffered to prevent the base QIODevice class to do * its own buffering on top of the overridden readData() method. * * The only buffering used will be to satisfy QIODevice::peek() and * QIODevice::ungetChar(). */ setOpenMode(ReadOnly | Unbuffered); } bool BlockingIODevice::isSequential() const { return true; } bool BlockingIODevice::atEnd() const { /* * XXX: QProcess::atEnd() documentation is wrong -- it will return true * even when the process is running --, so we try to workaround that here. */ if (m_device->atEnd()) { if (m_device->state() == QProcess::Running) { if (!m_device->waitForReadyRead(-1)) { return true; } } } return false; } bool BlockingIODevice::waitForReadyRead(int msecs) { Q_UNUSED(msecs); return true; } qint64 BlockingIODevice::readData(char * data, qint64 maxSize) { qint64 bytesToRead = maxSize; qint64 readSoFar = 0; do { qint64 chunkSize = m_device->read(data + readSoFar, bytesToRead); if (chunkSize < 0) { if (readSoFar) { return readSoFar; } else { return chunkSize; } } Q_ASSERT(chunkSize <= bytesToRead); bytesToRead -= chunkSize; readSoFar += chunkSize; if (bytesToRead) { if (!m_device->waitForReadyRead(-1)) { qDebug() << "waitForReadyRead failed\n"; break; } } } while(bytesToRead); return readSoFar; } qint64 BlockingIODevice::writeData(const char * data, qint64 maxSize) { Q_ASSERT(false); return -1; } Q_DECLARE_METATYPE(QList<ApiTraceError>); Retracer::Retracer(QObject *parent) : QThread(parent), m_benchmarking(false), m_doubleBuffered(true), m_captureState(false), m_captureCall(0), m_profileGpu(false), m_profileCpu(false), m_profilePixels(false) { qRegisterMetaType<QList<ApiTraceError> >(); #ifdef Q_OS_WIN QString format = QLatin1String("%1;"); #else QString format = QLatin1String("%1:"); #endif QString buildPath = format.arg(APITRACE_BINARY_DIR); m_processEnvironment = QProcessEnvironment::systemEnvironment(); m_processEnvironment.insert("PATH", buildPath + m_processEnvironment.value("PATH")); qputenv("PATH", m_processEnvironment.value("PATH").toLatin1()); } QString Retracer::fileName() const { return m_fileName; } void Retracer::setFileName(const QString &name) { m_fileName = name; } void Retracer::setAPI(trace::API api) { m_api = api; } bool Retracer::isBenchmarking() const { return m_benchmarking; } void Retracer::setBenchmarking(bool bench) { m_benchmarking = bench; } bool Retracer::isDoubleBuffered() const { return m_doubleBuffered; } void Retracer::setDoubleBuffered(bool db) { m_doubleBuffered = db; } bool Retracer::isProfilingGpu() const { return m_profileGpu; } bool Retracer::isProfilingCpu() const { return m_profileCpu; } bool Retracer::isProfilingPixels() const { return m_profilePixels; } bool Retracer::isProfiling() const { return m_profileGpu || m_profileCpu || m_profilePixels; } void Retracer::setProfiling(bool gpu, bool cpu, bool pixels) { m_profileGpu = gpu; m_profileCpu = cpu; m_profilePixels = pixels; } void Retracer::setCaptureAtCallNumber(qlonglong num) { m_captureCall = num; } qlonglong Retracer::captureAtCallNumber() const { return m_captureCall; } bool Retracer::captureState() const { return m_captureState; } void Retracer::setCaptureState(bool enable) { m_captureState = enable; } bool Retracer::captureThumbnails() const { return m_captureThumbnails; } void Retracer::setCaptureThumbnails(bool enable) { m_captureThumbnails = enable; } /** * Starting point for the retracing thread. * * Overrides QThread::run(). */ void Retracer::run() { QString msg = QLatin1String("Replay finished!"); /* * Construct command line */ QString prog; QStringList arguments; switch (m_api) { case trace::API_GL: prog = QLatin1String("glretrace"); break; case trace::API_EGL: prog = QLatin1String("eglretrace"); break; case trace::API_DX: case trace::API_D3D7: case trace::API_D3D8: case trace::API_D3D9: case trace::API_D3D10: case trace::API_D3D10_1: case trace::API_D3D11: #ifdef Q_OS_WIN prog = QLatin1String("d3dretrace"); #else prog = QLatin1String("wine"); arguments << QLatin1String("d3dretrace.exe"); #endif break; default: emit finished(QLatin1String("Unsupported API")); return; } if (m_captureState) { arguments << QLatin1String("-D"); arguments << QString::number(m_captureCall); } else if (m_captureThumbnails) { arguments << QLatin1String("-s"); // emit snapshots arguments << QLatin1String("-"); // emit to stdout } else if (isProfiling()) { if (m_profileGpu) { arguments << QLatin1String("-pgpu"); } if (m_profileCpu) { arguments << QLatin1String("-pcpu"); } if (m_profilePixels) { arguments << QLatin1String("-ppd"); } } else { if (m_doubleBuffered) { arguments << QLatin1String("-db"); } else { arguments << QLatin1String("-sb"); } if (m_benchmarking) { arguments << QLatin1String("-b"); } } arguments << m_fileName; /* * Start the process. */ QProcess process; process.start(prog, arguments, QIODevice::ReadOnly); if (!process.waitForStarted(-1)) { emit finished(QLatin1String("Could not start process")); return; } /* * Process standard output */ QList<QImage> thumbnails; QVariantMap parsedJson; trace::Profile* profile = NULL; process.setReadChannel(QProcess::StandardOutput); if (process.waitForReadyRead(-1)) { BlockingIODevice io(&process); if (m_captureState) { /* * Parse JSON from the output. * * XXX: QJSON's scanner is inneficient as it abuses single * character QIODevice::peek (not cheap), instead of maintaining a * lookahead character on its own. */ bool ok = false; QJson::Parser jsonParser; #if 0 parsedJson = jsonParser.parse(&io, &ok).toMap(); #else /* * XXX: QJSON expects blocking IO, and it looks like * BlockingIODevice does not work reliably in all cases. */ process.waitForFinished(-1); parsedJson = jsonParser.parse(&process, &ok).toMap(); #endif if (!ok) { msg = QLatin1String("failed to parse JSON"); } } else if (m_captureThumbnails) { /* * Parse concatenated PNM images from output. */ while (!io.atEnd()) { unsigned channels = 0; unsigned width = 0; unsigned height = 0; char header[512]; qint64 headerSize = 0; int headerLines = 3; // assume no optional comment line for (int headerLine = 0; headerLine < headerLines; ++headerLine) { qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize); // if header actually contains optional comment line, ... if (headerLine == 1 && header[headerSize] == '#') { ++headerLines; } headerSize += headerRead; } const char *headerEnd = image::readPNMHeader(header, headerSize, &channels, &width, &height); // if invalid PNM header was encountered, ... if (header == headerEnd) { qDebug() << "error: invalid snapshot stream encountered"; break; } // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height"; QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888); int rowBytes = channels * width; for (int y = 0; y < height; ++y) { unsigned char *scanLine = snapshot.scanLine(y); qint64 readBytes = io.read((char *) scanLine, rowBytes); Q_ASSERT(readBytes == rowBytes); } QImage thumb = thumbnail(snapshot); thumbnails.append(thumb); } Q_ASSERT(process.state() != QProcess::Running); } else if (isProfiling()) { profile = new trace::Profile(); process.waitForFinished(-1); while (!io.atEnd()) { char line[256]; qint64 lineLength; lineLength = io.readLine(line, 256); if (lineLength == -1) break; trace::Profiler::parseLine(line, profile); } } else { QByteArray output; output = process.readAllStandardOutput(); if (output.length() < 80) { msg = QString::fromUtf8(output); } } } /* * Wait for process termination */ process.waitForFinished(-1); if (process.exitStatus() != QProcess::NormalExit) { msg = QLatin1String("Process crashed"); } else if (process.exitCode() != 0) { msg = QLatin1String("Process exited with non zero exit code"); } /* * Parse errors. */ QList<ApiTraceError> errors; process.setReadChannel(QProcess::StandardError); QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$"); while (!process.atEnd()) { QString line = process.readLine(); if (regexp.indexIn(line) != -1) { ApiTraceError error; error.callIndex = regexp.cap(1).toInt(); error.type = regexp.cap(2); error.message = regexp.cap(3); errors.append(error); } else if (!errors.isEmpty()) { // Probably a multiligne message ApiTraceError &previous = errors.last(); if (line.endsWith("\n")) { line.chop(1); } previous.message.append('\n'); previous.message.append(line); } } /* * Emit signals */ if (m_captureState) { ApiTraceState *state = new ApiTraceState(parsedJson); emit foundState(state); msg = QLatin1String("State fetched."); } if (m_captureThumbnails && !thumbnails.isEmpty()) { emit foundThumbnails(thumbnails); } if (isProfiling() && profile) { emit foundProfile(profile); } if (!errors.isEmpty()) { emit retraceErrors(errors); } emit finished(msg); } #include "retracer.moc"
#include "retracer.h" #include "apitracecall.h" #include "thumbnail.h" #include "image.hpp" #include "trace_profiler.hpp" #include <QDebug> #include <QVariant> #include <QList> #include <QImage> #include <qjson/parser.h> /** * Wrapper around a QProcess which enforces IO to block . * * Several QIODevice users (notably QJSON) expect blocking semantics, e.g., * they expect that QIODevice::read() will blocked until the requested ammount * of bytes is read or end of file is reached. But by default QProcess, does * not block. And passing QIODevice::Unbuffered mitigates but does not fully * address the problem either. * * This class wraps around QProcess, providing QIODevice interface, while * ensuring that all reads block. * * This class also works around a bug in QProcess::atEnd() implementation. * * See also: * - http://qt-project.org/wiki/Simple_Crypt_IO_Device * - http://qt-project.org/wiki/Custom_IO_Device */ class BlockingIODevice : public QIODevice { /* We don't use the Q_OBJECT in this class given we don't declare any * signals and slots or use any other services provided by Qt's meta-object * system. */ public: BlockingIODevice(QProcess * io); bool isSequential() const; bool atEnd() const; bool waitForReadyRead(int msecs = -1); protected: qint64 readData(char * data, qint64 maxSize); qint64 writeData(const char * data, qint64 maxSize); private: QProcess *m_device; }; BlockingIODevice::BlockingIODevice(QProcess * io) : m_device(io) { /* * We pass QIODevice::Unbuffered to prevent the base QIODevice class to do * its own buffering on top of the overridden readData() method. * * The only buffering used will be to satisfy QIODevice::peek() and * QIODevice::ungetChar(). */ setOpenMode(ReadOnly | Unbuffered); } bool BlockingIODevice::isSequential() const { return true; } bool BlockingIODevice::atEnd() const { /* * XXX: QProcess::atEnd() documentation is wrong -- it will return true * even when the process is running --, so we try to workaround that here. */ if (m_device->atEnd()) { if (m_device->state() == QProcess::Running) { if (!m_device->waitForReadyRead(-1)) { return true; } } } return false; } bool BlockingIODevice::waitForReadyRead(int msecs) { Q_UNUSED(msecs); return true; } qint64 BlockingIODevice::readData(char * data, qint64 maxSize) { qint64 bytesToRead = maxSize; qint64 readSoFar = 0; do { qint64 chunkSize = m_device->read(data + readSoFar, bytesToRead); if (chunkSize < 0) { if (readSoFar) { return readSoFar; } else { return chunkSize; } } Q_ASSERT(chunkSize <= bytesToRead); bytesToRead -= chunkSize; readSoFar += chunkSize; if (bytesToRead) { if (!m_device->waitForReadyRead(-1)) { qDebug() << "waitForReadyRead failed\n"; break; } } } while(bytesToRead); return readSoFar; } qint64 BlockingIODevice::writeData(const char * data, qint64 maxSize) { Q_ASSERT(false); return -1; } Q_DECLARE_METATYPE(QList<ApiTraceError>); Retracer::Retracer(QObject *parent) : QThread(parent), m_benchmarking(false), m_doubleBuffered(true), m_captureState(false), m_captureCall(0), m_profileGpu(false), m_profileCpu(false), m_profilePixels(false) { qRegisterMetaType<QList<ApiTraceError> >(); #ifdef Q_OS_WIN QString format = QLatin1String("%1;"); #else QString format = QLatin1String("%1:"); #endif QString buildPath = format.arg(APITRACE_BINARY_DIR); m_processEnvironment = QProcessEnvironment::systemEnvironment(); m_processEnvironment.insert("PATH", buildPath + m_processEnvironment.value("PATH")); qputenv("PATH", m_processEnvironment.value("PATH").toLatin1()); } QString Retracer::fileName() const { return m_fileName; } void Retracer::setFileName(const QString &name) { m_fileName = name; } void Retracer::setAPI(trace::API api) { m_api = api; } bool Retracer::isBenchmarking() const { return m_benchmarking; } void Retracer::setBenchmarking(bool bench) { m_benchmarking = bench; } bool Retracer::isDoubleBuffered() const { return m_doubleBuffered; } void Retracer::setDoubleBuffered(bool db) { m_doubleBuffered = db; } bool Retracer::isProfilingGpu() const { return m_profileGpu; } bool Retracer::isProfilingCpu() const { return m_profileCpu; } bool Retracer::isProfilingPixels() const { return m_profilePixels; } bool Retracer::isProfiling() const { return m_profileGpu || m_profileCpu || m_profilePixels; } void Retracer::setProfiling(bool gpu, bool cpu, bool pixels) { m_profileGpu = gpu; m_profileCpu = cpu; m_profilePixels = pixels; } void Retracer::setCaptureAtCallNumber(qlonglong num) { m_captureCall = num; } qlonglong Retracer::captureAtCallNumber() const { return m_captureCall; } bool Retracer::captureState() const { return m_captureState; } void Retracer::setCaptureState(bool enable) { m_captureState = enable; } bool Retracer::captureThumbnails() const { return m_captureThumbnails; } void Retracer::setCaptureThumbnails(bool enable) { m_captureThumbnails = enable; } /** * Starting point for the retracing thread. * * Overrides QThread::run(). */ void Retracer::run() { QString msg = QLatin1String("Replay finished!"); /* * Construct command line */ QString prog; QStringList arguments; switch (m_api) { case trace::API_GL: prog = QLatin1String("glretrace"); break; case trace::API_EGL: prog = QLatin1String("eglretrace"); break; case trace::API_DX: case trace::API_D3D7: case trace::API_D3D8: case trace::API_D3D9: case trace::API_D3D10: case trace::API_D3D10_1: case trace::API_D3D11: #ifdef Q_OS_WIN prog = QLatin1String("d3dretrace"); #else prog = QLatin1String("wine"); arguments << QLatin1String("d3dretrace.exe"); #endif break; default: emit finished(QLatin1String("Unsupported API")); return; } if (m_captureState) { arguments << QLatin1String("-D"); arguments << QString::number(m_captureCall); } else if (m_captureThumbnails) { arguments << QLatin1String("-s"); // emit snapshots arguments << QLatin1String("-"); // emit to stdout } else if (isProfiling()) { if (m_profileGpu) { arguments << QLatin1String("-pgpu"); } if (m_profileCpu) { arguments << QLatin1String("-pcpu"); } if (m_profilePixels) { arguments << QLatin1String("-ppd"); } } else { if (m_doubleBuffered) { arguments << QLatin1String("-db"); } else { arguments << QLatin1String("-sb"); } if (m_benchmarking) { arguments << QLatin1String("-b"); } } arguments << m_fileName; /* * Start the process. */ QProcess process; process.start(prog, arguments, QIODevice::ReadOnly); if (!process.waitForStarted(-1)) { emit finished(QLatin1String("Could not start process")); return; } /* * Process standard output */ QList<QImage> thumbnails; QVariantMap parsedJson; trace::Profile* profile = NULL; process.setReadChannel(QProcess::StandardOutput); if (process.waitForReadyRead(-1)) { BlockingIODevice io(&process); if (m_captureState) { /* * Parse JSON from the output. * * XXX: QJSON's scanner is inneficient as it abuses single * character QIODevice::peek (not cheap), instead of maintaining a * lookahead character on its own. */ bool ok = false; QJson::Parser jsonParser; #if 0 parsedJson = jsonParser.parse(&io, &ok).toMap(); #else /* * XXX: QJSON expects blocking IO, and it looks like * BlockingIODevice does not work reliably in all cases. */ process.waitForFinished(-1); parsedJson = jsonParser.parse(&process, &ok).toMap(); #endif if (!ok) { msg = QLatin1String("failed to parse JSON"); } } else if (m_captureThumbnails) { /* * Parse concatenated PNM images from output. */ while (!io.atEnd()) { unsigned channels = 0; unsigned width = 0; unsigned height = 0; char header[512]; qint64 headerSize = 0; int headerLines = 3; // assume no optional comment line for (int headerLine = 0; headerLine < headerLines; ++headerLine) { qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize); // if header actually contains optional comment line, ... if (headerLine == 1 && header[headerSize] == '#') { ++headerLines; } headerSize += headerRead; } const char *headerEnd = image::readPNMHeader(header, headerSize, &channels, &width, &height); // if invalid PNM header was encountered, ... if (header == headerEnd) { qDebug() << "error: invalid snapshot stream encountered"; break; } // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height"; QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888); int rowBytes = channels * width; for (int y = 0; y < height; ++y) { unsigned char *scanLine = snapshot.scanLine(y); qint64 readBytes = io.read((char *) scanLine, rowBytes); Q_ASSERT(readBytes == rowBytes); } QImage thumb = thumbnail(snapshot); thumbnails.append(thumb); } Q_ASSERT(process.state() != QProcess::Running); } else if (isProfiling()) { profile = new trace::Profile(); while (!io.atEnd()) { char line[256]; qint64 lineLength; lineLength = io.readLine(line, 256); if (lineLength == -1) break; trace::Profiler::parseLine(line, profile); } } else { QByteArray output; output = process.readAllStandardOutput(); if (output.length() < 80) { msg = QString::fromUtf8(output); } } } /* * Wait for process termination */ process.waitForFinished(-1); if (process.exitStatus() != QProcess::NormalExit) { msg = QLatin1String("Process crashed"); } else if (process.exitCode() != 0) { msg = QLatin1String("Process exited with non zero exit code"); } /* * Parse errors. */ QList<ApiTraceError> errors; process.setReadChannel(QProcess::StandardError); QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$"); while (!process.atEnd()) { QString line = process.readLine(); if (regexp.indexIn(line) != -1) { ApiTraceError error; error.callIndex = regexp.cap(1).toInt(); error.type = regexp.cap(2); error.message = regexp.cap(3); errors.append(error); } else if (!errors.isEmpty()) { // Probably a multiligne message ApiTraceError &previous = errors.last(); if (line.endsWith("\n")) { line.chop(1); } previous.message.append('\n'); previous.message.append(line); } } /* * Emit signals */ if (m_captureState) { ApiTraceState *state = new ApiTraceState(parsedJson); emit foundState(state); msg = QLatin1String("State fetched."); } if (m_captureThumbnails && !thumbnails.isEmpty()) { emit foundThumbnails(thumbnails); } if (isProfiling() && profile) { emit foundProfile(profile); } if (!errors.isEmpty()) { emit retraceErrors(errors); } emit finished(msg); } #include "retracer.moc"
Allow BlockingIO read of profiling results.
Allow BlockingIO read of profiling results.
C++
mit
tuanthng/apitrace,apitrace/apitrace,apitrace/apitrace,apitrace/apitrace,swq0553/apitrace,tuanthng/apitrace,PeterLValve/apitrace,trtt/apitrace,EoD/apitrace,joshua5201/apitrace,EoD/apitrace,EoD/apitrace,tuanthng/apitrace,schulmar/apitrace,EoD/apitrace,swq0553/apitrace,surround-io/apitrace,swq0553/apitrace,swq0553/apitrace,joshua5201/apitrace,PeterLValve/apitrace,surround-io/apitrace,trtt/apitrace,schulmar/apitrace,tuanthng/apitrace,schulmar/apitrace,schulmar/apitrace,trtt/apitrace,EoD/apitrace,surround-io/apitrace,PeterLValve/apitrace,joshua5201/apitrace,trtt/apitrace,swq0553/apitrace,apitrace/apitrace,joshua5201/apitrace,PeterLValve/apitrace,tuanthng/apitrace,surround-io/apitrace,surround-io/apitrace,trtt/apitrace,schulmar/apitrace,joshua5201/apitrace
4cffb1eae71680ecf55832821950f81b4a067508
hal/avr32/serial_usb_avr32.cpp
hal/avr32/serial_usb_avr32.cpp
/******************************************************************************* * Copyright (c) 2009-2014, MAV'RIC Development Team * 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. ******************************************************************************/ /******************************************************************************* * \file serial_usb_avr32.cpp * * \author MAV'RIC Team * * \brief Implementation of serial over USB for avr32 * * \details Incomplete implementation (TODO) * - Implemented: * * buffered, blocking writing * - NOT implemented: * * Read functions * * Receive interrupt callback * * buffered input * ******************************************************************************/ #include "serial_usb_avr32.hpp" extern "C" { #include <stdint.h> #include "stdio_usb.h" #include "udi_cdc.h" } //------------------------------------------------------------------------------ // PUBLIC FUNCTIONS IMPLEMENTATION //------------------------------------------------------------------------------ Serial_usb_avr32::Serial_usb_avr32(serial_usb_avr32_conf_t config) { // Store config config_ = config; } bool Serial_usb_avr32::init(void) { // Init usb hardware stdio_usb_init(NULL); stdio_usb_enable(); return true; } uint32_t Serial_usb_avr32::readable(void) { // Not implemented return 0; } uint32_t Serial_usb_avr32::writeable(void) { return tx_buffer_.writeable(); } void Serial_usb_avr32::flush(void) { uint8_t byte = 0; // Block until everything is sent while( !tx_buffer_.empty() ) { if( udi_cdc_is_tx_ready() ) { // Get one byte tx_buffer_.get(byte); // Write byte stdio_usb_putchar(NULL, (int)byte); } } } bool Serial_usb_avr32::attach(serial_interrupt_callback_t func) { // Not implemented return false; } bool Serial_usb_avr32::write(const uint8_t* bytes, const uint32_t size) { bool ret = false; // Queue bytes if( writeable() >= size ) { for( uint32_t i = 0; i < size; ++i ) { tx_buffer_.put(bytes[i]); } ret = true; } // Try to flush "softly": do not block if fails more than size times for( uint8_t i=0; i<size; i++ ) { while( udi_cdc_is_tx_ready() && (!tx_buffer_.empty()) ) { uint8_t byte = 0; tx_buffer_.get(byte); stdio_usb_putchar(NULL, (int)byte); } } // If buffer is almost full, flush if( writeable() < 80 ) { flush(); } return ret; } bool Serial_usb_avr32::read(uint8_t* bytes, const uint32_t size) { // Not implemented return false; }
/******************************************************************************* * Copyright (c) 2009-2014, MAV'RIC Development Team * 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. ******************************************************************************/ /******************************************************************************* * \file serial_usb_avr32.cpp * * \author MAV'RIC Team * * \brief Implementation of serial over USB for avr32 * * \details Incomplete implementation (TODO) * - Implemented: * * buffered, blocking writing * - NOT implemented: * * Read functions * * Receive interrupt callback * * buffered input * ******************************************************************************/ #include "serial_usb_avr32.hpp" extern "C" { #include <stdint.h> #include "stdio_usb.h" #include "udi_cdc.h" } //------------------------------------------------------------------------------ // PUBLIC FUNCTIONS IMPLEMENTATION //------------------------------------------------------------------------------ Serial_usb_avr32::Serial_usb_avr32(serial_usb_avr32_conf_t config) { // Store config config_ = config; } bool Serial_usb_avr32::init(void) { // Init usb hardware stdio_usb_init(NULL); stdio_usb_enable(); return true; } uint32_t Serial_usb_avr32::readable(void) { // Not implemented return 0; } uint32_t Serial_usb_avr32::writeable(void) { return tx_buffer_.writeable(); } void Serial_usb_avr32::flush(void) { uint8_t byte = 0; // Block until everything is sent while( !tx_buffer_.empty() ) { if( udi_cdc_is_tx_ready() ) { // Get one byte tx_buffer_.get(byte); // Write byte stdio_usb_putchar(NULL, (int)byte); } } } bool Serial_usb_avr32::attach(serial_interrupt_callback_t func) { // Not implemented return false; } bool Serial_usb_avr32::write(const uint8_t* bytes, const uint32_t size) { bool ret = false; // Queue bytes if( writeable() >= size ) { for( uint32_t i = 0; i < size; ++i ) { tx_buffer_.put(bytes[i]); } ret = true; } // Try to flush "softly": do not block if fails more than size times for( uint8_t i=0; i<size; i++ ) { while( udi_cdc_is_tx_ready() && (!tx_buffer_.empty()) ) { uint8_t byte = 0; tx_buffer_.get(byte); stdio_usb_putchar(NULL, (int)byte); } } // If buffer is almost full, flush // if( writeable() < 80 ) // { // flush(); // } return ret; } bool Serial_usb_avr32::read(uint8_t* bytes, const uint32_t size) { // Not implemented return false; }
Fix bug with usb on avr32, flush waits forever if not plugged
Fix bug with usb on avr32, flush waits forever if not plugged
C++
bsd-3-clause
lis-epfl/MAVRIC_Library,lis-epfl/MAVRIC_Library,lis-epfl/MAVRIC_Library
493e29bc3df0c6e4507537a580e0b4687705e0b1
handler/win/loader_lock_dll.cc
handler/win/loader_lock_dll.cc
// Copyright 2016 The Crashpad 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 <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <windows.h> namespace { // This custom logging function is to avoid taking a dependency on base in this // standalone DLL. Don’t call this directly, use the LOG_FATAL() and // PLOG_FATAL() macros below. __declspec(noreturn) void LogFatal(const char* file, int line, bool get_last_error, const char* format, ...) { DWORD last_error = ERROR_SUCCESS; if (get_last_error) { last_error = GetLastError(); } char fname[_MAX_FNAME]; char ext[_MAX_EXT]; if (_splitpath_s(file, nullptr, 0, nullptr, 0, fname, sizeof(fname), ext, sizeof(ext)) == 0) { fprintf(stderr, "%s%s", fname, ext); } else { fputs(file, stderr); } fprintf(stderr, ":%d: ", line); va_list va; va_start(va, format); vfprintf(stderr, format, va); va_end(va); if (get_last_error) { fprintf(stderr, ": error %u", last_error); } fputs("\n", stderr); fflush(stderr); TerminateProcess(GetCurrentProcess(), 1); __fastfail(FAST_FAIL_FATAL_APP_EXIT); } #define LOG_FATAL(...) \ do { \ LogFatal(__FILE__, __LINE__, false, __VA_ARGS__); \ } while (false) #define PLOG_FATAL(...) \ do { \ LogFatal(__FILE__, __LINE__, true, __VA_ARGS__); \ } while (false) } // namespace // This program intentionally blocks in DllMain which is executed with the // loader lock locked. This allows us to test that // CrashpadClient::DumpAndCrashTargetProcess() can still dump the target in this // case. BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) { switch (reason) { case DLL_PROCESS_DETACH: case DLL_THREAD_DETACH: { // Recover the event handle stashed by the main executable. static constexpr size_t kEventStringSize = 19; wchar_t event_string[kEventStringSize]; SetLastError(ERROR_SUCCESS); DWORD size = GetEnvironmentVariable( L"CRASHPAD_TEST_DLL_EVENT", event_string, kEventStringSize); if (size == 0 && GetLastError() != ERROR_SUCCESS) { PLOG_FATAL("GetEnvironmentVariable"); } if (size == 0 || size >= kEventStringSize) { LOG_FATAL("GetEnvironmentVariable: size %u", size); } HANDLE event; int converted = swscanf(event_string, L"%p", &event); if (converted != 1) { LOG_FATAL("swscanf: converted %d", converted); } // Let the main thread know that the loader lock is and will remain held. if (!SetEvent(event)) { PLOG_FATAL("SetEvent"); } Sleep(INFINITE); break; } } return TRUE; }
// Copyright 2016 The Crashpad 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 <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <windows.h> namespace { // This custom logging function is to avoid taking a dependency on base in this // standalone DLL. Don’t call this directly, use the LOG_FATAL() and // PLOG_FATAL() macros below. __declspec(noreturn) void LogFatal(const char* file, int line, bool get_last_error, const char* format, ...) { DWORD last_error = ERROR_SUCCESS; if (get_last_error) { last_error = GetLastError(); } char fname[_MAX_FNAME]; char ext[_MAX_EXT]; if (_splitpath_s(file, nullptr, 0, nullptr, 0, fname, sizeof(fname), ext, sizeof(ext)) == 0) { fprintf(stderr, "%s%s", fname, ext); } else { fputs(file, stderr); } fprintf(stderr, ":%d: ", line); va_list va; va_start(va, format); vfprintf(stderr, format, va); va_end(va); if (get_last_error) { fprintf(stderr, ": error %lu", last_error); } fputs("\n", stderr); fflush(stderr); TerminateProcess(GetCurrentProcess(), 1); __fastfail(FAST_FAIL_FATAL_APP_EXIT); } #define LOG_FATAL(...) \ do { \ LogFatal(__FILE__, __LINE__, false, __VA_ARGS__); \ } while (false) #define PLOG_FATAL(...) \ do { \ LogFatal(__FILE__, __LINE__, true, __VA_ARGS__); \ } while (false) } // namespace // This program intentionally blocks in DllMain which is executed with the // loader lock locked. This allows us to test that // CrashpadClient::DumpAndCrashTargetProcess() can still dump the target in this // case. BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) { switch (reason) { case DLL_PROCESS_DETACH: case DLL_THREAD_DETACH: { // Recover the event handle stashed by the main executable. static constexpr size_t kEventStringSize = 19; wchar_t event_string[kEventStringSize]; SetLastError(ERROR_SUCCESS); DWORD size = GetEnvironmentVariable( L"CRASHPAD_TEST_DLL_EVENT", event_string, kEventStringSize); if (size == 0 && GetLastError() != ERROR_SUCCESS) { PLOG_FATAL("GetEnvironmentVariable"); } if (size == 0 || size >= kEventStringSize) { LOG_FATAL("GetEnvironmentVariable: size %u", size); } HANDLE event; int converted = swscanf(event_string, L"%p", &event); if (converted != 1) { LOG_FATAL("swscanf: converted %d", converted); } // Let the main thread know that the loader lock is and will remain held. if (!SetEvent(event)) { PLOG_FATAL("SetEvent"); } Sleep(INFINITE); break; } } return TRUE; }
Use correct format specifier
win: Use correct format specifier This caused an error with clang, but not msvc. At first I thought this might be a discrepancy between the warning levels used, but it appears msvc was okay with this because ints are the same size as longs. Change-Id: I798284fef9aa70b1bfda73308b9babe1779e8f4b Reviewed-on: https://chromium-review.googlesource.com/941723 Reviewed-by: Mark Mentovai <[email protected]> Commit-Queue: Joshua Peraza <[email protected]>
C++
apache-2.0
chromium/crashpad,chromium/crashpad,chromium/crashpad
adb9e4a145054eefe7dbe96bb7998504ff9047c7
src/yubikeyfinder.cpp
src/yubikeyfinder.cpp
/* Copyright (C) 2011-2013 Yubico AB. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE 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 "yubikeyfinder.h" #include <ykcore.h> #include <ykdef.h> #include <QTimer> #include <QApplication> YubiKeyFinder* YubiKeyFinder::_instance = 0; // first version is inclusive, second is exclusive const unsigned int YubiKeyFinder::FEATURE_MATRIX[][2] = { { YK_VERSION(2,0,0), 0 }, //Feature_MultipleConfigurations { YK_VERSION(2,0,0), 0 }, //Feature_ProtectConfiguration2 { YK_VERSION(1,3,0), 0 }, //Feature_StaticPassword { YK_VERSION(2,0,0), 0 }, //Feature_ScanCodeMode { YK_VERSION(2,0,0), 0 }, //Feature_ShortTicket { YK_VERSION(2,0,0), 0 }, //Feature_StrongPwd { YK_VERSION(2,1,0), 0 }, //Feature_OathHotp { YK_VERSION(2,2,0), 0 }, //Feature_ChallengeResponse { YK_VERSION(2,1,4), 0 }, //Feature_SerialNumber { YK_VERSION(2,1,7), 0 }, //Feature_MovingFactor { YK_VERSION(2,3,0), 0 }, //Feature_ChallengeResponseFixed { YK_VERSION(2,3,0), 0 }, //Feature_Updatable { YK_VERSION(2,1,4), 0 }, //Feature_Ndef { YK_VERSION(2,4,0), 0 }, //Feature_LedInvert }; // when a featureset should be excluded from versions (NEO, I'm looking at you.) const unsigned int YubiKeyFinder::FEATURE_MATRIX_EXCLUDE[][2] = { { YK_VERSION(2,1,4), YK_VERSION(2,2,0) }, //Feature_MultipleConfigurations { YK_VERSION(2,1,4), YK_VERSION(2,2,0) }, //Feature_ProtectConfiguration2 { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_StaticPassword { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_ScanCodeMode { 0, 0 }, //Feature_ShortTicket { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_StrongPwd { 0, 0 }, //Feature_OathHotp { 0, 0 }, //Feature_ChallengeResponse { 0, 0 }, //Feature_SerialNumber { 0, 0 }, //Feature_MovingFactor { 0, 0 }, //Feature_ChallengeResponseFixed { 0, 0 }, //Feature_Updatable { YK_VERSION(2,2,0), YK_VERSION(3,0,0) }, //Feature_Ndef { YK_VERSION(3,0,0), YK_VERSION(3,1,0) }, //Feature_LedInvert }; YubiKeyFinder::YubiKeyFinder() { // init the ykpers library yk_init(); //Initialize fields init(); //Create timer m_timer = new QTimer( this ); connect(m_timer, SIGNAL(timeout()), this, SLOT(findKey())); } YubiKeyFinder::~YubiKeyFinder() { yk_release(); if(m_timer != 0) { delete m_timer; m_timer = 0; } if(_instance) { delete _instance; } if(m_ykds) { ykds_free(m_ykds); } } YubiKeyFinder* YubiKeyFinder::getInstance() { if(_instance == NULL) { _instance = new YubiKeyFinder(); } return _instance; } QString YubiKeyFinder::versionStr() { if(m_version > 0) { return tr("%1.%2.%3"). arg(m_versionMajor). arg(m_versionMinor). arg(m_versionBuild); } return ""; } bool YubiKeyFinder::checkFeatureSupport(Feature feature) { if(m_version > 0 && (unsigned int) feature < sizeof(FEATURE_MATRIX)/sizeof(FEATURE_MATRIX[0])) { bool supported = ( m_version >= FEATURE_MATRIX[feature][0] && (FEATURE_MATRIX[feature][1] == 0 || m_version < FEATURE_MATRIX[feature][1]) ); if(supported) if(FEATURE_MATRIX_EXCLUDE[feature][0] != 0) if(m_version >= FEATURE_MATRIX_EXCLUDE[feature][0]) if(m_version < FEATURE_MATRIX_EXCLUDE[feature][1]) return false; return supported; } return false; } void YubiKeyFinder::init() { m_state = State_Absent; m_yk = 0; m_version = 0; m_versionMajor = 0; m_versionMinor = 0; m_versionBuild = 0; m_serial = 0; m_ykds = ykds_alloc(); } void YubiKeyFinder::start() { //Start timer init(); if(m_timer && !m_timer->isActive()) { m_timer->start(TIMEOUT_FINDER); } } void YubiKeyFinder::stop() { //Stop timer if(m_timer && m_timer->isActive()) { m_timer->stop(); // doing closeKey() here might look out of place and may cause findKey() // to fail unexpectedly, but it's needed to not leak file descriptors // when writing the key. closeKey(); } } bool YubiKeyFinder::openKey() { bool flag = true; if (!(m_yk = yk_open_first_key())) { flag = false; } return flag; } bool YubiKeyFinder::closeKey() { bool flag = true; if(m_yk != 0) { if (!yk_close_key(m_yk)) { flag = false; } m_yk = 0; } return flag; } void YubiKeyFinder::findKey() { if(QApplication::activeWindow() == 0) { //No focus, avoid locking the YubiKey. m_state = State_NoFocus; return; } bool error = false; //qDebug() << "-------------------------"; //qDebug() << "Starting key search"; //qDebug() << "-------------------------"; try { if(m_yk == 0 && !openKey()) { throw 0; } if (!yk_get_status(m_yk, m_ykds)) { throw 0; } //qDebug() << "Key found"; //Check pervious state if(m_state == State_Absent || m_state == State_NoFocus) { m_state = State_Present; //Get version m_versionMajor = ykds_version_major(m_ykds); m_versionMinor = ykds_version_minor(m_ykds); m_versionBuild = ykds_version_build(m_ykds); m_version = YK_VERSION(m_versionMajor, m_versionMinor, m_versionBuild); m_touchLevel = ykds_touch_level(m_ykds); //Get serial number if(checkFeatureSupport(Feature_SerialNumber)) { if (!yk_get_serial(m_yk, 0, 0, &m_serial)) { qDebug() << "Failed to read serial number (serial-api-visible disabled?)."; } else { qDebug() << "Serial number: " << m_serial; } } //Get supported features size_t featuresCount = sizeof(FEATURE_MATRIX)/sizeof(FEATURE_MATRIX[0]); bool featuresMatrix[featuresCount]; for(size_t i = 0; i < featuresCount; i++) { featuresMatrix[i] = checkFeatureSupport((Feature)i); } int error = ERR_NOERROR; if(!yk_check_firmware_version2(m_ykds)) { error = ERR_UNKNOWN_FIRMWARE; } emit keyFound(true, featuresMatrix, error); emit diagnostics(QString("Found key with version %1, serial %2 and touch %3.") .arg(versionStr(), QString::number(m_serial), QString::number(m_touchLevel))); } } catch(...) { error = true; } closeKey(); if(error) { init(); m_state = State_Absent; int error = ERR_OTHER; if(yk_errno == YK_EMORETHANONE) { error = ERR_MORETHANONE; } else if(yk_errno == YK_ENOKEY) { error = ERR_NOKEY; } else if(yk_errno == YK_EUSBERR) { emit diagnostics(QString("USB Error: %1").arg(yk_usb_strerror())); } else if(yk_errno) { emit diagnostics(yk_strerror(yk_errno)); } yk_errno = 0; ykp_errno = 0; emit keyFound(false, NULL, error); } //qDebug() << "-------------------------"; //qDebug() << "Stopping key search"; //qDebug() << "-------------------------"; }
/* Copyright (C) 2011-2013 Yubico AB. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE 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 "yubikeyfinder.h" #include <ykcore.h> #include <ykdef.h> #include <QTimer> #include <QApplication> YubiKeyFinder* YubiKeyFinder::_instance = 0; // first version is inclusive, second is exclusive const unsigned int YubiKeyFinder::FEATURE_MATRIX[][2] = { { YK_VERSION(2,0,0), 0 }, //Feature_MultipleConfigurations { YK_VERSION(2,0,0), 0 }, //Feature_ProtectConfiguration2 { YK_VERSION(1,3,0), 0 }, //Feature_StaticPassword { YK_VERSION(2,0,0), 0 }, //Feature_ScanCodeMode { YK_VERSION(2,0,0), 0 }, //Feature_ShortTicket { YK_VERSION(2,0,0), 0 }, //Feature_StrongPwd { YK_VERSION(2,1,0), 0 }, //Feature_OathHotp { YK_VERSION(2,2,0), 0 }, //Feature_ChallengeResponse { YK_VERSION(2,1,4), 0 }, //Feature_SerialNumber { YK_VERSION(2,1,7), 0 }, //Feature_MovingFactor { YK_VERSION(2,3,0), 0 }, //Feature_ChallengeResponseFixed { YK_VERSION(2,3,0), 0 }, //Feature_Updatable { YK_VERSION(2,1,4), 0 }, //Feature_Ndef { YK_VERSION(2,4,0), 0 }, //Feature_LedInvert }; // when a featureset should be excluded from versions (NEO, I'm looking at you.) const unsigned int YubiKeyFinder::FEATURE_MATRIX_EXCLUDE[][2] = { { YK_VERSION(2,1,4), YK_VERSION(2,2,0) }, //Feature_MultipleConfigurations { YK_VERSION(2,1,4), YK_VERSION(2,2,0) }, //Feature_ProtectConfiguration2 { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_StaticPassword { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_ScanCodeMode { 0, 0 }, //Feature_ShortTicket { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_StrongPwd { 0, 0 }, //Feature_OathHotp { 0, 0 }, //Feature_ChallengeResponse { 0, 0 }, //Feature_SerialNumber { 0, 0 }, //Feature_MovingFactor { 0, 0 }, //Feature_ChallengeResponseFixed { 0, 0 }, //Feature_Updatable { YK_VERSION(2,2,0), YK_VERSION(3,0,0) }, //Feature_Ndef { YK_VERSION(3,0,0), YK_VERSION(3,1,0) }, //Feature_LedInvert }; YubiKeyFinder::YubiKeyFinder() { // init the ykpers library yk_init(); //Initialize fields init(); //Create timer m_timer = new QTimer( this ); connect(m_timer, SIGNAL(timeout()), this, SLOT(findKey())); } YubiKeyFinder::~YubiKeyFinder() { yk_release(); if(m_timer != 0) { delete m_timer; m_timer = 0; } if(_instance) { delete _instance; } if(m_ykds) { ykds_free(m_ykds); } } YubiKeyFinder* YubiKeyFinder::getInstance() { if(_instance == NULL) { _instance = new YubiKeyFinder(); } return _instance; } QString YubiKeyFinder::versionStr() { if(m_version > 0) { return tr("%1.%2.%3"). arg(m_versionMajor). arg(m_versionMinor). arg(m_versionBuild); } return ""; } bool YubiKeyFinder::checkFeatureSupport(Feature feature) { if(m_version > 0 && (unsigned int) feature < sizeof(FEATURE_MATRIX)/sizeof(FEATURE_MATRIX[0])) { bool supported = ( m_version >= FEATURE_MATRIX[feature][0] && (FEATURE_MATRIX[feature][1] == 0 || m_version < FEATURE_MATRIX[feature][1]) ); if(supported) if(FEATURE_MATRIX_EXCLUDE[feature][0] != 0) if(m_version >= FEATURE_MATRIX_EXCLUDE[feature][0]) if(m_version < FEATURE_MATRIX_EXCLUDE[feature][1]) return false; return supported; } return false; } void YubiKeyFinder::init() { m_state = State_Absent; m_yk = 0; m_version = 0; m_versionMajor = 0; m_versionMinor = 0; m_versionBuild = 0; m_serial = 0; m_touchLevel = 0; m_ykds = ykds_alloc(); } void YubiKeyFinder::start() { //Start timer init(); if(m_timer && !m_timer->isActive()) { m_timer->start(TIMEOUT_FINDER); } } void YubiKeyFinder::stop() { //Stop timer if(m_timer && m_timer->isActive()) { m_timer->stop(); // doing closeKey() here might look out of place and may cause findKey() // to fail unexpectedly, but it's needed to not leak file descriptors // when writing the key. closeKey(); } } bool YubiKeyFinder::openKey() { bool flag = true; if (!(m_yk = yk_open_first_key())) { flag = false; } return flag; } bool YubiKeyFinder::closeKey() { bool flag = true; if(m_yk != 0) { if (!yk_close_key(m_yk)) { flag = false; } m_yk = 0; } return flag; } void YubiKeyFinder::findKey() { if(QApplication::activeWindow() == 0) { //No focus, avoid locking the YubiKey. m_state = State_NoFocus; return; } bool error = false; //qDebug() << "-------------------------"; //qDebug() << "Starting key search"; //qDebug() << "-------------------------"; try { if(m_yk == 0 && !openKey()) { throw 0; } if (!yk_get_status(m_yk, m_ykds)) { throw 0; } //qDebug() << "Key found"; //Check pervious state if(m_state == State_Absent || m_state == State_NoFocus) { m_state = State_Present; //Get version m_versionMajor = ykds_version_major(m_ykds); m_versionMinor = ykds_version_minor(m_ykds); m_versionBuild = ykds_version_build(m_ykds); m_version = YK_VERSION(m_versionMajor, m_versionMinor, m_versionBuild); m_touchLevel = ykds_touch_level(m_ykds); //Get serial number if(checkFeatureSupport(Feature_SerialNumber)) { if (!yk_get_serial(m_yk, 0, 0, &m_serial)) { qDebug() << "Failed to read serial number (serial-api-visible disabled?)."; } else { qDebug() << "Serial number: " << m_serial; } } //Get supported features size_t featuresCount = sizeof(FEATURE_MATRIX)/sizeof(FEATURE_MATRIX[0]); bool featuresMatrix[featuresCount]; for(size_t i = 0; i < featuresCount; i++) { featuresMatrix[i] = checkFeatureSupport((Feature)i); } int error = ERR_NOERROR; if(!yk_check_firmware_version2(m_ykds)) { error = ERR_UNKNOWN_FIRMWARE; } emit keyFound(true, featuresMatrix, error); emit diagnostics(QString("Found key with version %1, serial %2 and touch %3.") .arg(versionStr(), QString::number(m_serial), QString::number(m_touchLevel))); } } catch(...) { error = true; } closeKey(); if(error) { init(); m_state = State_Absent; int error = ERR_OTHER; if(yk_errno == YK_EMORETHANONE) { error = ERR_MORETHANONE; } else if(yk_errno == YK_ENOKEY) { error = ERR_NOKEY; } else if(yk_errno == YK_EUSBERR) { emit diagnostics(QString("USB Error: %1").arg(yk_usb_strerror())); } else if(yk_errno) { emit diagnostics(yk_strerror(yk_errno)); } yk_errno = 0; ykp_errno = 0; emit keyFound(false, NULL, error); } //qDebug() << "-------------------------"; //qDebug() << "Stopping key search"; //qDebug() << "-------------------------"; }
clear touchLevel when initing
clear touchLevel when initing
C++
bsd-2-clause
eworm-de/yubikey-personalization-gui,eworm-de/yubikey-personalization-gui,Yubico/yubikey-personalization-gui,eworm-de/yubikey-personalization-gui,Yubico/yubikey-personalization-gui,Yubico/yubikey-personalization-gui
760204bc776ec519a95793837d2e47a8d888f9cd
include/date.hpp
include/date.hpp
//======================================================================= // Copyright (c) 2013-2014 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DATE_HPP #define DATE_HPP #include <ctime> #include "utils.hpp" namespace budget { using date_type = unsigned short; class date_exception: public std::exception { protected: std::string _message; public: date_exception(std::string message) : _message(message){} /*! * Return the error message. * \return The error message. */ const std::string& message() const { return _message; } virtual const char* what() const throw() { return _message.c_str(); } }; struct day { date_type value; day(date_type value) : value(value) {} operator date_type() const { return value; } }; struct month { date_type value; month(date_type value) : value(value) {} operator date_type() const { return value; } std::string as_short_string() const { static constexpr const char* months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; return months[value-1]; } std::string as_long_string() const { static constexpr const char* months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; return months[value-1]; } }; struct year { date_type value; year(date_type value) : value(value) {} operator date_type() const { return value; } }; struct days { date_type value; explicit days(date_type value) : value(value) {} operator date_type() const { return value; } }; struct months { date_type value; explicit months(date_type value) : value(value) {} operator date_type() const { return value; } }; struct years { date_type value; explicit years(date_type value) : value(value) {} operator date_type() const { return value; } }; struct date { date_type _year; date_type _month; date_type _day; explicit date(){} date(date_type year, date_type month, date_type day) : _year(year), _month(month), _day(day){ if(year < 1400){ throw date_exception("Year not in the valid range"); } if(month == 0 || month > 12){ throw date_exception("Invalid month"); } if(day == 0 || day > days_month(year, month)){ throw date_exception("Invalid day"); } } date(const date& d) : _year(d._year), _month(d._month), _day(d._day) { //Nothing else } year year() const { return _year; } month month() const { return _month; } day day() const { return _day; } static date_type days_month(date_type year, date_type month){ static constexpr const date_type month_days[12] = {31,0,31,30,31,30,31,31,30,31,30,31}; if(month == 2){ return is_leap(year) ? 29 : 28; } else { return month_days[month - 1]; } } static bool is_leap(date_type year){ return ((year % 4 == 0) && year % 100 != 0) || year % 400 == 0; } bool is_leap() const { return is_leap(_year); } date end_of_month(){ return {_year, _month, days_month(_year, _month)}; } date& operator+=(years years){ if(_year + years < _year){ throw date_exception("Year too high"); } _year += years; return *this; } date& operator+=(months months){ _month += months; if(_month > 12){ *this += years(_month / 12); _month %= 12; } _day = std::min(_day, days_month(_year, _month)); return *this; } date& operator+=(days d){ while(d > 0){ ++_day; if(_day > days_month(_year, _month)){ _day = 1; ++_month; if(_month > 12){ _month = 1; ++_year; } } d = days(d - 1); } return *this; } date& operator-=(years years){ if(_year < years){ throw date_exception("Year too low"); } _year -= years; return *this; } date& operator-=(months months){ if(_month < months){ *this -= years(months / 12); _month -= months % 12; } else { _month -= months; } _day = std::min(_day, days_month(_year, _month)); return *this; } date& operator-=(days d){ while(d > 0){ --_day; if(_day == 0){ --_month; if(_month == 0){ --_year; _month = 12; } _day = days_month(_year, _month); } d = days(d - 1); } return *this; } date operator+(years years) const { date d(*this); d += years; return d; } date operator+(months months) const { date d(*this); d += months; return d; } date operator+(days days) const { date d(*this); d += days; return d; } date operator-(years years) const { date d(*this); d -= years; return d; } date operator-(months months) const { date d(*this); d -= months; return d; } date operator-(days days) const { date d(*this); d -= days; return d; } bool operator==(const date& rhs) const { return _year == rhs._year && _month == rhs._month && _day == rhs._day; } bool operator!=(const date& rhs) const { return !(*this == rhs); } bool operator<(const date& rhs) const { if(_year < rhs._year){ return true; } else if(_year == rhs._year){ if(_month < rhs._month){ return true; } else if(_month == rhs._month){ return _day < rhs._day; } } return false; } bool operator>(const date& rhs) const { if(_year > rhs._year){ return true; } else if(_year == rhs._year){ if(_month > rhs._month){ return true; } else if(_month == rhs._month){ return _day > rhs._day; } } return false; } }; std::ostream& operator<<(std::ostream& stream, const month& month); std::ostream& operator<<(std::ostream& stream, const date& date); date local_day(); date from_string(const std::string& str); date from_iso_string(const std::string& str); std::string date_to_string(date date); template<> inline std::string to_string(budget::date date){ return date_to_string(date); } unsigned short start_year(); unsigned short start_month(budget::year year); } //end of namespace budget #endif
//======================================================================= // Copyright (c) 2013-2014 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DATE_HPP #define DATE_HPP #include <ctime> #include "utils.hpp" namespace budget { using date_type = unsigned short; class date_exception: public std::exception { protected: std::string _message; public: date_exception(std::string message) : _message(message){} /*! * Return the error message. * \return The error message. */ const std::string& message() const { return _message; } virtual const char* what() const throw() { return _message.c_str(); } }; struct day { date_type value; day(date_type value) : value(value) {} operator date_type() const { return value; } }; struct month { date_type value; month(date_type value) : value(value) {} operator date_type() const { return value; } std::string as_short_string() const { static constexpr const char* months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; return months[value-1]; } std::string as_long_string() const { static constexpr const char* months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; return months[value-1]; } }; struct year { date_type value; year(date_type value) : value(value) {} operator date_type() const { return value; } }; struct days { date_type value; explicit days(date_type value) : value(value) {} operator date_type() const { return value; } }; struct months { date_type value; explicit months(date_type value) : value(value) {} operator date_type() const { return value; } }; struct years { date_type value; explicit years(date_type value) : value(value) {} operator date_type() const { return value; } }; struct date { date_type _year; date_type _month; date_type _day; explicit date(){} date(date_type year, date_type month, date_type day) : _year(year), _month(month), _day(day){ if(year < 1400){ throw date_exception("Year not in the valid range"); } if(month == 0 || month > 12){ throw date_exception("Invalid month"); } if(day == 0 || day > days_month(year, month)){ throw date_exception("Invalid day"); } } date(const date& d) : _year(d._year), _month(d._month), _day(d._day) { //Nothing else } year year() const { return _year; } month month() const { return _month; } day day() const { return _day; } static date_type days_month(date_type year, date_type month){ static constexpr const date_type month_days[12] = {31,0,31,30,31,30,31,31,30,31,30,31}; if(month == 2){ return is_leap(year) ? 29 : 28; } else { return month_days[month - 1]; } } static bool is_leap(date_type year){ return ((year % 4 == 0) && year % 100 != 0) || year % 400 == 0; } bool is_leap() const { return is_leap(_year); } date end_of_month(){ return {_year, _month, days_month(_year, _month)}; } date& operator+=(years years){ if(_year + years < _year){ throw date_exception("Year too high"); } _year += years; return *this; } date& operator+=(months months){ _month += months; if(_month > 12){ *this += years(_month / 12); _month %= 12; } _day = std::min(_day, days_month(_year, _month)); return *this; } date& operator+=(days d){ while(d > 0){ ++_day; if(_day > days_month(_year, _month)){ _day = 1; ++_month; if(_month > 12){ _month = 1; ++_year; } } d = days(d - 1); } return *this; } date& operator-=(years years){ if(_year < years){ throw date_exception("Year too low"); } _year -= years; return *this; } date& operator-=(months months){ if(_month == months){ *this -= years(1); _month = 12; } else if(_month < months){ *this -= years(months / 12); _month -= months % 12; } else { _month -= months; } _day = std::min(_day, days_month(_year, _month)); return *this; } date& operator-=(days d){ while(d > 0){ --_day; if(_day == 0){ --_month; if(_month == 0){ --_year; _month = 12; } _day = days_month(_year, _month); } d = days(d - 1); } return *this; } date operator+(years years) const { date d(*this); d += years; return d; } date operator+(months months) const { date d(*this); d += months; return d; } date operator+(days days) const { date d(*this); d += days; return d; } date operator-(years years) const { date d(*this); d -= years; return d; } date operator-(months months) const { date d(*this); d -= months; return d; } date operator-(days days) const { date d(*this); d -= days; return d; } bool operator==(const date& rhs) const { return _year == rhs._year && _month == rhs._month && _day == rhs._day; } bool operator!=(const date& rhs) const { return !(*this == rhs); } bool operator<(const date& rhs) const { if(_year < rhs._year){ return true; } else if(_year == rhs._year){ if(_month < rhs._month){ return true; } else if(_month == rhs._month){ return _day < rhs._day; } } return false; } bool operator>(const date& rhs) const { if(_year > rhs._year){ return true; } else if(_year == rhs._year){ if(_month > rhs._month){ return true; } else if(_month == rhs._month){ return _day > rhs._day; } } return false; } }; std::ostream& operator<<(std::ostream& stream, const month& month); std::ostream& operator<<(std::ostream& stream, const date& date); date local_day(); date from_string(const std::string& str); date from_iso_string(const std::string& str); std::string date_to_string(date date); template<> inline std::string to_string(budget::date date){ return date_to_string(date); } unsigned short start_year(); unsigned short start_month(budget::year year); } //end of namespace budget #endif
Fix bug in date
Fix bug in date
C++
mit
wichtounet/budgetwarrior,wichtounet/budgetwarrior,wichtounet/budgetwarrior
dd5873868519eba553b3cacc810c045a02960948
test/ProtocolTest.cpp
test/ProtocolTest.cpp
/** * 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 <wdt/Wdt.h> #include <wdt/util/SerializationUtil.h> #include <glog/logging.h> #include <gtest/gtest.h> namespace facebook { namespace wdt { using std::string; using facebook::wdt::encodeString; void testHeader() { BlockDetails bd; bd.fileName = "abcdef"; bd.seqId = 3; bd.dataSize = 3; bd.offset = 4; bd.fileSize = 10; bd.allocationStatus = EXISTS_CORRECT_SIZE; char buf[128]; int64_t off = 0; Protocol::encodeHeader(Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, off, sizeof(buf), bd); EXPECT_EQ(off, bd.fileName.size() + 1 + 1 + 1 + 1 + 1 + 1); // 1 byte variant for seqId, len, size, offset and filesize BlockDetails nbd; int64_t noff = 0; bool success = Protocol::decodeHeader(Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, noff, sizeof(buf), nbd); EXPECT_TRUE(success); EXPECT_EQ(noff, off); EXPECT_EQ(nbd.fileName, bd.fileName); EXPECT_EQ(nbd.seqId, bd.seqId); EXPECT_EQ(nbd.fileSize, bd.fileSize); EXPECT_EQ(nbd.offset, bd.offset); EXPECT_EQ(nbd.dataSize, nbd.dataSize); EXPECT_EQ(nbd.allocationStatus, bd.allocationStatus); noff = 0; // exact size: success = Protocol::decodeHeader( Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, noff, off, nbd); EXPECT_TRUE(success); WLOG(INFO) << "error tests, expect errors"; // too short noff = 0; success = Protocol::decodeHeader( Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, noff, off - 1, nbd); EXPECT_FALSE(success); // Long size: bd.dataSize = (int64_t)100 * 1024 * 1024 * 1024; // 100Gb bd.fileName.assign("different"); bd.seqId = 5; bd.offset = 3; bd.fileSize = 128; bd.allocationStatus = EXISTS_TOO_SMALL; bd.prevSeqId = 10; off = 0; Protocol::encodeHeader(Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, off, sizeof(buf), bd); EXPECT_EQ(off, bd.fileName.size() + 1 + 1 + 6 + 1 + 2 + 1 + 1); // 1 byte variant for id len and size noff = 0; success = Protocol::decodeHeader(Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, noff, sizeof(buf), nbd); EXPECT_TRUE(success); EXPECT_EQ(noff, off); EXPECT_EQ(nbd.fileName, bd.fileName); EXPECT_EQ(nbd.seqId, bd.seqId); EXPECT_EQ(nbd.fileSize, bd.fileSize); EXPECT_EQ(nbd.offset, bd.offset); EXPECT_EQ(nbd.dataSize, nbd.dataSize); EXPECT_EQ(nbd.allocationStatus, bd.allocationStatus); EXPECT_EQ(nbd.prevSeqId, bd.prevSeqId); WLOG(INFO) << "got size of " << nbd.dataSize; // too short for size encoding: noff = 0; success = Protocol::decodeHeader( Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, noff, off - 2, nbd); EXPECT_FALSE(success); } void testFileChunksInfo() { FileChunksInfo fileChunksInfo; fileChunksInfo.setSeqId(10); fileChunksInfo.setFileName("abc"); fileChunksInfo.setFileSize(128); fileChunksInfo.addChunk(Interval(1, 10)); fileChunksInfo.addChunk(Interval(20, 30)); char buf[128]; int64_t off = 0; Protocol::encodeFileChunksInfo(buf, off, sizeof(buf), fileChunksInfo); FileChunksInfo nFileChunksInfo; folly::ByteRange br((uint8_t *)buf, sizeof(buf)); bool success = Protocol::decodeFileChunksInfo(br, nFileChunksInfo); EXPECT_TRUE(success); int64_t noff = br.start() - (uint8_t *)buf; EXPECT_EQ(noff, off); EXPECT_EQ(nFileChunksInfo, fileChunksInfo); // test with smaller buffer; exact size: br.reset((uint8_t *)buf, off); success = Protocol::decodeFileChunksInfo(br, nFileChunksInfo); EXPECT_TRUE(success); // 1 byte missing : br.reset((uint8_t *)buf, off - 1); success = Protocol::decodeFileChunksInfo(br, nFileChunksInfo); EXPECT_FALSE(success); } void testSettings() { Settings settings; int senderProtocolVersion = Protocol::SETTINGS_FLAG_VERSION; settings.readTimeoutMillis = 501; settings.writeTimeoutMillis = 503; settings.transferId = "abc"; settings.enableChecksum = true; settings.sendFileChunks = false; settings.blockModeDisabled = true; char buf[128]; int64_t off = 0; EXPECT_TRUE(Protocol::encodeSettings(senderProtocolVersion, buf, off, sizeof(buf), settings)); int nsenderProtocolVersion; Settings nsettings; int64_t noff = 0; bool success = Protocol::decodeVersion(buf, noff, off, nsenderProtocolVersion); EXPECT_TRUE(success); EXPECT_EQ(nsenderProtocolVersion, senderProtocolVersion); success = Protocol::decodeSettings(Protocol::SETTINGS_FLAG_VERSION, buf, noff, off, nsettings); EXPECT_TRUE(success); EXPECT_EQ(noff, off); EXPECT_EQ(nsettings.readTimeoutMillis, settings.readTimeoutMillis); EXPECT_EQ(nsettings.writeTimeoutMillis, settings.writeTimeoutMillis); EXPECT_EQ(nsettings.transferId, settings.transferId); EXPECT_EQ(nsettings.enableChecksum, settings.enableChecksum); EXPECT_EQ(nsettings.sendFileChunks, settings.sendFileChunks); EXPECT_EQ(nsettings.blockModeDisabled, settings.blockModeDisabled); } TEST(Protocol, EncodeString) { string inp1("abc"); char buf[10]; folly::ByteRange br((const u_int8_t *)buf, sizeof(buf)); int64_t off = 0; EXPECT_TRUE(encodeString(buf, sizeof(buf), off, inp1)); EXPECT_EQ(off, inp1.size() + 1); string inp2("de"); EXPECT_TRUE(encodeString(buf, sizeof(buf), off, inp2)); EXPECT_EQ(off, inp1.size() + inp2.size() + 2); string d1; EXPECT_TRUE(decodeString(br, d1)); EXPECT_EQ(d1, inp1); string d2; EXPECT_TRUE(decodeString(br, d2)); EXPECT_EQ(d2, inp2); } TEST(Protocol, DecodeInt32) { string buf; EXPECT_TRUE(encodeVarI64(buf, 501)); EXPECT_TRUE(encodeVarI64(buf, 502)); EXPECT_TRUE(encodeVarI64(buf, 1L << 32)); EXPECT_TRUE(encodeVarI64(buf, -7)); EXPECT_EQ(buf.size(), 2 + 2 + 5 + 1); folly::ByteRange br((uint8_t *)buf.data(), buf.size()); int32_t v = -1; EXPECT_TRUE(decodeInt32(br, v)); EXPECT_EQ(501, v); EXPECT_TRUE(decodeInt32(br, v)); EXPECT_EQ(502, v); // this should log an error about overflow: EXPECT_FALSE(decodeInt32(br, v)); EXPECT_EQ(502, v); // v unchanged on error int64_t lv = -1; EXPECT_TRUE(decodeInt64(br, lv)); EXPECT_EQ(lv, 1L << 32); EXPECT_TRUE(decodeInt32(br, v)); EXPECT_EQ(v, -7); } TEST(Protocol, encodeVarI64C) { char buf[5]; int64_t pos = 0; // Negative values crash the compatible (compact) version of encodeVarI64C EXPECT_DEATH(encodeVarI64C(buf, sizeof(buf), pos, -3), "Check failed: v >= 0"); } TEST(Protocol, Simple_Header) { testHeader(); } TEST(Protocol, Simple_Settings) { testSettings(); } TEST(Protocol, FileChunksInfo) { testFileChunksInfo(); } } } // namespaces int main(int argc, char *argv[]) { FLAGS_logtostderr = true; testing::InitGoogleTest(&argc, argv); google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); facebook::wdt::Wdt::initializeWdt("wdt"); int ret = RUN_ALL_TESTS(); return ret; }
/** * 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 <wdt/Wdt.h> #include <wdt/util/SerializationUtil.h> #include <glog/logging.h> #include <gtest/gtest.h> namespace facebook { namespace wdt { using std::string; using facebook::wdt::encodeString; void testHeader() { BlockDetails bd; bd.fileName = "abcdef"; bd.seqId = 3; bd.dataSize = 3; bd.offset = 4; bd.fileSize = 10; bd.allocationStatus = EXISTS_CORRECT_SIZE; char buf[128]; int64_t off = 0; Protocol::encodeHeader(Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, off, sizeof(buf), bd); EXPECT_EQ(off, bd.fileName.size() + 1 + 1 + 1 + 1 + 1 + 1); // 1 byte variant for seqId, len, size, offset and filesize BlockDetails nbd; int64_t noff = 0; bool success = Protocol::decodeHeader(Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, noff, sizeof(buf), nbd); EXPECT_TRUE(success); EXPECT_EQ(noff, off); EXPECT_EQ(nbd.fileName, bd.fileName); EXPECT_EQ(nbd.seqId, bd.seqId); EXPECT_EQ(nbd.fileSize, bd.fileSize); EXPECT_EQ(nbd.offset, bd.offset); EXPECT_EQ(nbd.dataSize, bd.dataSize); EXPECT_EQ(nbd.allocationStatus, bd.allocationStatus); noff = 0; // exact size: success = Protocol::decodeHeader( Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, noff, off, nbd); EXPECT_TRUE(success); WLOG(INFO) << "error tests, expect errors"; // too short noff = 0; success = Protocol::decodeHeader( Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, noff, off - 1, nbd); EXPECT_FALSE(success); // Long size: bd.dataSize = (int64_t)100 * 1024 * 1024 * 1024; // 100Gb bd.fileName.assign("different"); bd.seqId = 5; bd.offset = 3; bd.fileSize = 128; bd.allocationStatus = EXISTS_TOO_SMALL; bd.prevSeqId = 10; off = 0; Protocol::encodeHeader(Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, off, sizeof(buf), bd); EXPECT_EQ(off, bd.fileName.size() + 1 + 1 + 6 + 1 + 2 + 1 + 1); // 1 byte variant for id len and size noff = 0; success = Protocol::decodeHeader(Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, noff, sizeof(buf), nbd); EXPECT_TRUE(success); EXPECT_EQ(noff, off); EXPECT_EQ(nbd.fileName, bd.fileName); EXPECT_EQ(nbd.seqId, bd.seqId); EXPECT_EQ(nbd.fileSize, bd.fileSize); EXPECT_EQ(nbd.offset, bd.offset); EXPECT_EQ(nbd.dataSize, bd.dataSize); EXPECT_EQ(nbd.allocationStatus, bd.allocationStatus); EXPECT_EQ(nbd.prevSeqId, bd.prevSeqId); WLOG(INFO) << "got size of " << nbd.dataSize; // too short for size encoding: noff = 0; success = Protocol::decodeHeader( Protocol::HEADER_FLAG_AND_PREV_SEQ_ID_VERSION, buf, noff, off - 2, nbd); EXPECT_FALSE(success); } void testFileChunksInfo() { FileChunksInfo fileChunksInfo; fileChunksInfo.setSeqId(10); fileChunksInfo.setFileName("abc"); fileChunksInfo.setFileSize(128); fileChunksInfo.addChunk(Interval(1, 10)); fileChunksInfo.addChunk(Interval(20, 30)); char buf[128]; int64_t off = 0; Protocol::encodeFileChunksInfo(buf, off, sizeof(buf), fileChunksInfo); FileChunksInfo nFileChunksInfo; folly::ByteRange br((uint8_t *)buf, sizeof(buf)); bool success = Protocol::decodeFileChunksInfo(br, nFileChunksInfo); EXPECT_TRUE(success); int64_t noff = br.start() - (uint8_t *)buf; EXPECT_EQ(noff, off); EXPECT_EQ(nFileChunksInfo, fileChunksInfo); // test with smaller buffer; exact size: br.reset((uint8_t *)buf, off); success = Protocol::decodeFileChunksInfo(br, nFileChunksInfo); EXPECT_TRUE(success); // 1 byte missing : br.reset((uint8_t *)buf, off - 1); success = Protocol::decodeFileChunksInfo(br, nFileChunksInfo); EXPECT_FALSE(success); } void testSettings() { Settings settings; int senderProtocolVersion = Protocol::SETTINGS_FLAG_VERSION; settings.readTimeoutMillis = 501; settings.writeTimeoutMillis = 503; settings.transferId = "abc"; settings.enableChecksum = true; settings.sendFileChunks = false; settings.blockModeDisabled = true; char buf[128]; int64_t off = 0; EXPECT_TRUE(Protocol::encodeSettings(senderProtocolVersion, buf, off, sizeof(buf), settings)); int nsenderProtocolVersion; Settings nsettings; int64_t noff = 0; bool success = Protocol::decodeVersion(buf, noff, off, nsenderProtocolVersion); EXPECT_TRUE(success); EXPECT_EQ(nsenderProtocolVersion, senderProtocolVersion); success = Protocol::decodeSettings(Protocol::SETTINGS_FLAG_VERSION, buf, noff, off, nsettings); EXPECT_TRUE(success); EXPECT_EQ(noff, off); EXPECT_EQ(nsettings.readTimeoutMillis, settings.readTimeoutMillis); EXPECT_EQ(nsettings.writeTimeoutMillis, settings.writeTimeoutMillis); EXPECT_EQ(nsettings.transferId, settings.transferId); EXPECT_EQ(nsettings.enableChecksum, settings.enableChecksum); EXPECT_EQ(nsettings.sendFileChunks, settings.sendFileChunks); EXPECT_EQ(nsettings.blockModeDisabled, settings.blockModeDisabled); } TEST(Protocol, EncodeString) { string inp1("abc"); char buf[10]; folly::ByteRange br((const u_int8_t *)buf, sizeof(buf)); int64_t off = 0; EXPECT_TRUE(encodeString(buf, sizeof(buf), off, inp1)); EXPECT_EQ(off, inp1.size() + 1); string inp2("de"); EXPECT_TRUE(encodeString(buf, sizeof(buf), off, inp2)); EXPECT_EQ(off, inp1.size() + inp2.size() + 2); string d1; EXPECT_TRUE(decodeString(br, d1)); EXPECT_EQ(d1, inp1); string d2; EXPECT_TRUE(decodeString(br, d2)); EXPECT_EQ(d2, inp2); } TEST(Protocol, DecodeInt32) { string buf; EXPECT_TRUE(encodeVarI64(buf, 501)); EXPECT_TRUE(encodeVarI64(buf, 502)); EXPECT_TRUE(encodeVarI64(buf, 1L << 32)); EXPECT_TRUE(encodeVarI64(buf, -7)); EXPECT_EQ(buf.size(), 2 + 2 + 5 + 1); folly::ByteRange br((uint8_t *)buf.data(), buf.size()); int32_t v = -1; EXPECT_TRUE(decodeInt32(br, v)); EXPECT_EQ(501, v); EXPECT_TRUE(decodeInt32(br, v)); EXPECT_EQ(502, v); // this should log an error about overflow: EXPECT_FALSE(decodeInt32(br, v)); EXPECT_EQ(502, v); // v unchanged on error int64_t lv = -1; EXPECT_TRUE(decodeInt64(br, lv)); EXPECT_EQ(lv, 1L << 32); EXPECT_TRUE(decodeInt32(br, v)); EXPECT_EQ(v, -7); } TEST(Protocol, encodeVarI64C) { char buf[5]; int64_t pos = 0; // Negative values crash the compatible (compact) version of encodeVarI64C EXPECT_DEATH(encodeVarI64C(buf, sizeof(buf), pos, -3), "Check failed: v >= 0"); } TEST(Protocol, Simple_Header) { testHeader(); } TEST(Protocol, Simple_Settings) { testSettings(); } TEST(Protocol, FileChunksInfo) { testFileChunksInfo(); } } } // namespaces int main(int argc, char *argv[]) { FLAGS_logtostderr = true; testing::InitGoogleTest(&argc, argv); google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); facebook::wdt::Wdt::initializeWdt("wdt"); int ret = RUN_ALL_TESTS(); return ret; }
fix two typos
wdt/test/ProtocolTest.cpp: fix two typos Summary: Fix two typos. Not only is nbd.dataSize always going to be equal to itself, but from context, it is clear that the RHS should use "bd", not "nbd": EXPECT_EQ(nbd.fileSize, bd.fileSize); EXPECT_EQ(nbd.offset, bd.offset); EXPECT_EQ(nbd.dataSize, nbd.dataSize); ^ Reviewed By: uddipta Differential Revision: D4457563 fbshipit-source-id: 0191867eaa32755b65db5575f88814236c873614
C++
bsd-3-clause
ldemailly/wdt,ldemailly/wdt,ldemailly/wdt,ldemailly/wdt,luluandleilei/wdt,luluandleilei/wdt,luluandleilei/wdt,luluandleilei/wdt
9b312d51aafbe8578d87486613cbed50d30d3529
include/bulk/partitioned_array.hpp
include/bulk/partitioned_array.hpp
/** * A partitioned array is a co-array with a special structure. Locally it * behaves like a nD array, indexable using `local`. It also knows about the * global structure through its associated partitioning. * - The data is stored linearly. * - A partitioning is defined in a general way, and contains functions for owner * and local index lookup, as well as flattening of multi-indices. * - convenient indexing features * * Examples of partitionings include: * - Block partitioning * - Cyclic partitioning * - A binary tree of splits, giving a binary (space) partitioning. * - A set of slices ((2,2,1,1), (3,2,1)), see * http://dask.pydata.org/en/latest/array-creation.html * - Custom partitionings, for example cartesian distributions using different * functions for each axis * * Some design decisions that have to be made have to do with inheritence and * overload functions. * * Also, we want to support multi-indices, but dont want to resort to `arrays` * for everything. Using parameter packs we can do this nicely for the user, but * internally we still resort to arrays. This leads to duplicated implementations * in the partitioning objects and should be fixed. * * As it is, this is probably over-engineered and will see major revisions. */ #include <array> #include "partitioning.hpp" #include "coarray.hpp" #include "future.hpp" #include "util/meta_helpers.hpp" namespace bulk { template <int D, typename... Ts> using check_dim = typename std::enable_if<count_of_type<D, int, Ts...>::value>::type; /** * A partitioned array is a distributed array with an associated partitioning. * * It is used to retain the notion of a 'global index' without refering * specifically to a partitioning. * * TODO: think about template argument storage class (coarray by default) * TODO: this about specializing for 'rectangular partitionings' */ template <typename T, int D, typename World> class partitioned_array { public: /** Construct a partitioned array from a given partitioning. */ partitioned_array(World& world, partitioning<D, D>& part) : world_(world), part_(part), data_(world, part_.local_element_count(world.processor_id())) { multi_id_ = unflatten<D>(part_.grid(), world.processor_id()); } /** Obtain an image to a (possibly remote) element using a global index. */ template <typename... Ts, typename = check_dim<D, Ts...>> auto global(Ts... index) { auto owner = part_.owner({index...}); auto idx = flatten<D>(part_.local_extent(owner), part_.local_index({index...})); return data_(flatten<D>(part_.grid(), part_.owner({index...})))[idx]; } /** Obtain an element using its local index. */ template <typename... Ts, typename = check_dim<D, Ts...>> T& local(Ts... index) { return data_[flatten<D>(part_.local_extent(multi_id_), {index...})]; } private: std::array<int, D> multi_id_; // world in which this array resides World& world_; // underlying partitioning partitioning<D, D>& part_; // linear storage bulk::coarray<T, World> data_; }; } // namespace bulk
/** * A partitioned array is a co-array with a special structure. Locally it * behaves like a nD array, indexable using `local`. It also knows about the * global structure through its associated partitioning. * - The data is stored linearly. * - A partitioning is defined in a general way, and contains functions for owner * and local index lookup, as well as flattening of multi-indices. * - convenient indexing features * * Examples of partitionings include: * - Block partitioning * - Cyclic partitioning * - A binary tree of splits, giving a binary (space) partitioning. * - A set of slices ((2,2,1,1), (3,2,1)), see * http://dask.pydata.org/en/latest/array-creation.html * - Custom partitionings, for example cartesian distributions using different * functions for each axis * * Some design decisions that have to be made have to do with inheritence and * overload functions. * * Also, we want to support multi-indices, but dont want to resort to `arrays` * for everything. Using parameter packs we can do this nicely for the user, but * internally we still resort to arrays. This leads to duplicated implementations * in the partitioning objects and should be fixed. * * As it is, this is probably over-engineered and will see major revisions. */ #include <array> #include "partitioning.hpp" #include "coarray.hpp" #include "future.hpp" #include "util/meta_helpers.hpp" namespace bulk { template <int D, typename... Ts> using check_dim = typename std::enable_if<count_of_type<D, int, Ts...>::value>::type; /** * A partitioned array is a distributed array with an associated partitioning. * * It is used to retain the notion of a 'global index' without refering * specifically to a partitioning. * * TODO: think about template argument storage class (coarray by default) * TODO: this about specializing for 'rectangular partitionings' */ template <typename T, int D, typename World> class partitioned_array { public: /** Construct a partitioned array from a given partitioning. */ partitioned_array(World& world, partitioning<D, D>& part) : world_(world), part_(part), data_(world, part_.local_element_count(world.processor_id())) { multi_id_ = unflatten<D>(part_.grid(), world.processor_id()); } /** Obtain an image to a (possibly remote) element using a global index. */ template <typename... Ts, typename = check_dim<D, Ts...>> auto global(Ts... index) { auto owner = part_.owner({index...}); auto idx = flatten<D>(part_.local_extent(owner), part_.local_index({index...})); return data_(flatten<D>(part_.grid(), part_.owner({index...})))[idx]; } /** Obtain an element using its local index. */ template <typename... Ts, typename = check_dim<D, Ts...>> T& local(Ts... index) { return data_[flatten<D>(part_.local_extent(multi_id_), {index...})]; } /// ditto template <typename... Ts, typename = check_dim<D, Ts...>> const T& local(Ts... index) const { return data_[flatten<D>(part_.local_extent(multi_id_), {index...})]; } /** Obtain a reference to the world. */ auto world() const { return world_ ; } private: std::array<int, D> multi_id_; // world in which this array resides World& world_; // underlying partitioning partitioning<D, D>& part_; // linear storage bulk::coarray<T, World> data_; }; } // namespace bulk
Extend partitioned array interface
Extend partitioned array interface
C++
mit
jwbuurlage/Bulk
a67cdd126b125632202566bd21228073b31c2832
src/rpc/mailbox/mailbox.cc
src/rpc/mailbox/mailbox.cc
// Copyright 2010-2012 RethinkDB, all rights reserved. #define __STDC_LIMIT_MACROS #define __STDC_FORMAT_MACROS #include "rpc/mailbox/mailbox.hpp" #include <stdint.h> #include "errors.hpp" #include <boost/bind.hpp> #include "containers/archive/archive.hpp" #include "containers/archive/vector_stream.hpp" #include "concurrency/pmap.hpp" #include "logger.hpp" /* raw_mailbox_t */ const int raw_mailbox_t::address_t::ANY_THREAD = -1; raw_mailbox_t::address_t::address_t() : peer(peer_id_t()), thread(ANY_THREAD), mailbox_id(0) { } raw_mailbox_t::address_t::address_t(const address_t &a) : peer(a.peer), thread(a.thread), mailbox_id(a.mailbox_id) { } bool raw_mailbox_t::address_t::is_nil() const { return peer.is_nil(); } peer_id_t raw_mailbox_t::address_t::get_peer() const { guarantee(!is_nil(), "A nil address has no peer"); return peer; } std::string raw_mailbox_t::address_t::human_readable() const { return strprintf("%s:%d:%" PRIu64, uuid_to_str(peer.get_uuid()).c_str(), thread, mailbox_id); } raw_mailbox_t::raw_mailbox_t(mailbox_manager_t *m, mailbox_read_callback_t *_callback) : manager(m), mailbox_id(manager->register_mailbox(this)), callback(_callback) { // Do nothing } raw_mailbox_t::~raw_mailbox_t() { assert_thread(); manager->unregister_mailbox(mailbox_id); } raw_mailbox_t::address_t raw_mailbox_t::get_address() const { address_t a; a.peer = manager->get_connectivity_service()->get_me(); a.thread = home_thread().threadnum; a.mailbox_id = mailbox_id; return a; } class raw_mailbox_writer_t : public send_message_write_callback_t { public: raw_mailbox_writer_t(int32_t _dest_thread, raw_mailbox_t::id_t _dest_mailbox_id, mailbox_write_callback_t *_subwriter) : dest_thread(_dest_thread), dest_mailbox_id(_dest_mailbox_id), subwriter(_subwriter) { } virtual ~raw_mailbox_writer_t() { } void write(write_stream_t *stream) { write_message_t msg; msg << dest_thread; msg << dest_mailbox_id; uint64_t prefix_length = static_cast<uint64_t>(msg.size()); subwriter->write(&msg); // Prepend the message length // TODO: It would be more efficient if we could make this part of `msg`. // e.g. with a `prepend()` method on write_message_t. write_message_t length_msg; length_msg << (static_cast<uint64_t>(msg.size()) - prefix_length); int res = send_write_message(stream, &length_msg); if (res) { throw fake_archive_exc_t(); } res = send_write_message(stream, &msg); if (res) { throw fake_archive_exc_t(); } } private: int32_t dest_thread; raw_mailbox_t::id_t dest_mailbox_id; mailbox_write_callback_t *subwriter; }; void send(mailbox_manager_t *src, raw_mailbox_t::address_t dest, mailbox_write_callback_t *callback) { guarantee(src); guarantee(!dest.is_nil()); raw_mailbox_writer_t writer(dest.thread, dest.mailbox_id, callback); src->message_service->send_message(dest.peer, &writer); } mailbox_manager_t::mailbox_manager_t(message_service_t *ms) : message_service(ms) { } mailbox_manager_t::mailbox_table_t::mailbox_table_t() { next_mailbox_id = (UINT64_MAX / get_num_threads()) * get_thread_id().threadnum; } mailbox_manager_t::mailbox_table_t::~mailbox_table_t() { guarantee(mailboxes.empty(), "Please destroy all mailboxes before destroying the cluster"); } raw_mailbox_t *mailbox_manager_t::mailbox_table_t::find_mailbox(raw_mailbox_t::id_t id) { std::map<raw_mailbox_t::id_t, raw_mailbox_t *>::iterator it = mailboxes.find(id); if (it == mailboxes.end()) { return NULL; } else { return it->second; } } void mailbox_manager_t::on_message(peer_id_t source_peer, read_stream_t *stream) { int32_t dest_thread; uint64_t data_length = 0; raw_mailbox_t::id_t dest_mailbox_id; { archive_result_t res = deserialize(stream, &data_length); if (res != 0 || data_length > std::numeric_limits<size_t>::max()) { throw fake_archive_exc_t(); } res = deserialize(stream, &dest_thread); if (res != 0) { throw fake_archive_exc_t(); } res = deserialize(stream, &dest_mailbox_id); if (res != 0) { throw fake_archive_exc_t(); } } // Read the data from the read stream, so it can be deallocated before we continue // in a coroutine std::vector<char> stream_data; int64_t stream_data_offset = 0; // Special case for `vector_read_stream_t`s to avoid copying. // `connectivity_cluster_t` gives us a `vector_read_stream_t` if the message is // delivered locally. vector_read_stream_t *vector_stream = dynamic_cast<vector_read_stream_t *>(stream); if (vector_stream != NULL) { // Avoid copying the data vector_stream->swap(&stream_data, &stream_data_offset); if(stream_data.size() - stream_data_offset != data_length) { // Either we go a vector_read_stream_t that contained more data // than just ours (which shouldn't happen), or we got a wrong data_length // from the network. throw fake_archive_exc_t(); } } else { stream_data.resize(data_length); int64_t bytes_read = force_read(stream, stream_data.data(), data_length); if (bytes_read != static_cast<int64_t>(data_length)) { throw fake_archive_exc_t(); } } if (dest_thread == raw_mailbox_t::address_t::ANY_THREAD) { // TODO: this will just run the callback on the current thread, maybe do some load balancing, instead dest_thread = get_thread_id().threadnum; } // We use `spawn_now_dangerously()` to avoid having to heap-allocate `stream_data`. // Instead we pass in a pointer to our local automatically allocated object // and `mailbox_read_coroutine()` moves the data out of it before it yields. coro_t::spawn_now_dangerously(boost::bind(&mailbox_manager_t::mailbox_read_coroutine, this, source_peer, threadnum_t(dest_thread), dest_mailbox_id, &stream_data, stream_data_offset)); } void mailbox_manager_t::mailbox_read_coroutine(peer_id_t source_peer, threadnum_t dest_thread, raw_mailbox_t::id_t dest_mailbox_id, std::vector<char> *stream_data, int64_t stream_data_offset) { // Construct a new stream to use vector_read_stream_t stream(std::move(*stream_data), stream_data_offset); stream_data = NULL; // <- It is not safe to use `stream_data` anymore once we // switch the thread bool archive_exception = false; { on_thread_t rethreader(dest_thread); try { raw_mailbox_t *mbox = mailbox_tables.get()->find_mailbox(dest_mailbox_id); if (mbox != NULL) { mbox->callback->read(&stream); } } catch (const fake_archive_exc_t &e) { // Set a flag and handle the exception later. // This is to avoid doing thread switches and other coroutine things // while being in the exception handler. Just a precaution... archive_exception = true; } } if (archive_exception) { logWRN("Received an invalid cluster message from a peer. Disconnecting."); message_service->kill_connection(source_peer); } } raw_mailbox_t::id_t mailbox_manager_t::generate_mailbox_id() { raw_mailbox_t::id_t id = ++mailbox_tables.get()->next_mailbox_id; return id; } raw_mailbox_t::id_t mailbox_manager_t::register_mailbox(raw_mailbox_t *mb) { raw_mailbox_t::id_t id = generate_mailbox_id(); std::map<raw_mailbox_t::id_t, raw_mailbox_t *> *mailboxes = &mailbox_tables.get()->mailboxes; std::pair<std::map<raw_mailbox_t::id_t, raw_mailbox_t *>::iterator, bool> res = mailboxes->insert(std::make_pair(id, mb)); guarantee(res.second); // Assert a new element was inserted. return id; } void mailbox_manager_t::unregister_mailbox(raw_mailbox_t::id_t id) { size_t num_elements_erased = mailbox_tables.get()->mailboxes.erase(id); guarantee(num_elements_erased == 1); }
// Copyright 2010-2012 RethinkDB, all rights reserved. #define __STDC_LIMIT_MACROS #define __STDC_FORMAT_MACROS #include "rpc/mailbox/mailbox.hpp" #include <stdint.h> #include "errors.hpp" #include <boost/bind.hpp> #include "containers/archive/archive.hpp" #include "containers/archive/vector_stream.hpp" #include "concurrency/pmap.hpp" #include "logger.hpp" /* raw_mailbox_t */ const int raw_mailbox_t::address_t::ANY_THREAD = -1; raw_mailbox_t::address_t::address_t() : peer(peer_id_t()), thread(ANY_THREAD), mailbox_id(0) { } raw_mailbox_t::address_t::address_t(const address_t &a) : peer(a.peer), thread(a.thread), mailbox_id(a.mailbox_id) { } bool raw_mailbox_t::address_t::is_nil() const { return peer.is_nil(); } peer_id_t raw_mailbox_t::address_t::get_peer() const { guarantee(!is_nil(), "A nil address has no peer"); return peer; } std::string raw_mailbox_t::address_t::human_readable() const { return strprintf("%s:%d:%" PRIu64, uuid_to_str(peer.get_uuid()).c_str(), thread, mailbox_id); } raw_mailbox_t::raw_mailbox_t(mailbox_manager_t *m, mailbox_read_callback_t *_callback) : manager(m), mailbox_id(manager->register_mailbox(this)), callback(_callback) { // Do nothing } raw_mailbox_t::~raw_mailbox_t() { assert_thread(); manager->unregister_mailbox(mailbox_id); } raw_mailbox_t::address_t raw_mailbox_t::get_address() const { address_t a; a.peer = manager->get_connectivity_service()->get_me(); a.thread = home_thread().threadnum; a.mailbox_id = mailbox_id; return a; } class raw_mailbox_writer_t : public send_message_write_callback_t { public: raw_mailbox_writer_t(int32_t _dest_thread, raw_mailbox_t::id_t _dest_mailbox_id, mailbox_write_callback_t *_subwriter) : dest_thread(_dest_thread), dest_mailbox_id(_dest_mailbox_id), subwriter(_subwriter) { } virtual ~raw_mailbox_writer_t() { } void write(write_stream_t *stream) { write_message_t msg; msg << dest_thread; msg << dest_mailbox_id; uint64_t prefix_length = static_cast<uint64_t>(msg.size()); subwriter->write(&msg); // Prepend the message length // TODO: It would be more efficient if we could make this part of `msg`. // e.g. with a `prepend()` method on write_message_t. write_message_t length_msg; length_msg << (static_cast<uint64_t>(msg.size()) - prefix_length); int res = send_write_message(stream, &length_msg); if (res) { throw fake_archive_exc_t(); } res = send_write_message(stream, &msg); if (res) { throw fake_archive_exc_t(); } } private: int32_t dest_thread; raw_mailbox_t::id_t dest_mailbox_id; mailbox_write_callback_t *subwriter; }; void send(mailbox_manager_t *src, raw_mailbox_t::address_t dest, mailbox_write_callback_t *callback) { guarantee(src); guarantee(!dest.is_nil()); raw_mailbox_writer_t writer(dest.thread, dest.mailbox_id, callback); src->message_service->send_message(dest.peer, &writer); } mailbox_manager_t::mailbox_manager_t(message_service_t *ms) : message_service(ms) { } mailbox_manager_t::mailbox_table_t::mailbox_table_t() { next_mailbox_id = (UINT64_MAX / get_num_threads()) * get_thread_id().threadnum; } mailbox_manager_t::mailbox_table_t::~mailbox_table_t() { guarantee(mailboxes.empty(), "Please destroy all mailboxes before destroying the cluster"); } raw_mailbox_t *mailbox_manager_t::mailbox_table_t::find_mailbox(raw_mailbox_t::id_t id) { std::map<raw_mailbox_t::id_t, raw_mailbox_t *>::iterator it = mailboxes.find(id); if (it == mailboxes.end()) { return NULL; } else { return it->second; } } void mailbox_manager_t::on_message(peer_id_t source_peer, read_stream_t *stream) { int32_t dest_thread; uint64_t data_length = 0; raw_mailbox_t::id_t dest_mailbox_id; { archive_result_t res = deserialize(stream, &data_length); if (res != ARCHIVE_SUCCESS || data_length > std::numeric_limits<size_t>::max() || data_length > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { throw fake_archive_exc_t(); } res = deserialize(stream, &dest_thread); if (res != 0) { throw fake_archive_exc_t(); } res = deserialize(stream, &dest_mailbox_id); if (res != 0) { throw fake_archive_exc_t(); } } // Read the data from the read stream, so it can be deallocated before we continue // in a coroutine std::vector<char> stream_data; int64_t stream_data_offset = 0; // Special case for `vector_read_stream_t`s to avoid copying. // `connectivity_cluster_t` gives us a `vector_read_stream_t` if the message is // delivered locally. vector_read_stream_t *vector_stream = dynamic_cast<vector_read_stream_t *>(stream); if (vector_stream != NULL) { // Avoid copying the data vector_stream->swap(&stream_data, &stream_data_offset); if(stream_data.size() - static_cast<uint64_t>(stream_data_offset) != data_length) { // Either we go a vector_read_stream_t that contained more data // than just ours (which shouldn't happen), or we got a wrong data_length // from the network. throw fake_archive_exc_t(); } } else { stream_data.resize(data_length); int64_t bytes_read = force_read(stream, stream_data.data(), data_length); if (bytes_read != static_cast<int64_t>(data_length)) { throw fake_archive_exc_t(); } } if (dest_thread == raw_mailbox_t::address_t::ANY_THREAD) { // TODO: this will just run the callback on the current thread, maybe do some load balancing, instead dest_thread = get_thread_id().threadnum; } // We use `spawn_now_dangerously()` to avoid having to heap-allocate `stream_data`. // Instead we pass in a pointer to our local automatically allocated object // and `mailbox_read_coroutine()` moves the data out of it before it yields. coro_t::spawn_now_dangerously(boost::bind(&mailbox_manager_t::mailbox_read_coroutine, this, source_peer, threadnum_t(dest_thread), dest_mailbox_id, &stream_data, stream_data_offset)); } void mailbox_manager_t::mailbox_read_coroutine(peer_id_t source_peer, threadnum_t dest_thread, raw_mailbox_t::id_t dest_mailbox_id, std::vector<char> *stream_data, int64_t stream_data_offset) { // Construct a new stream to use vector_read_stream_t stream(std::move(*stream_data), stream_data_offset); stream_data = NULL; // <- It is not safe to use `stream_data` anymore once we // switch the thread bool archive_exception = false; { on_thread_t rethreader(dest_thread); try { raw_mailbox_t *mbox = mailbox_tables.get()->find_mailbox(dest_mailbox_id); if (mbox != NULL) { mbox->callback->read(&stream); } } catch (const fake_archive_exc_t &e) { // Set a flag and handle the exception later. // This is to avoid doing thread switches and other coroutine things // while being in the exception handler. Just a precaution... archive_exception = true; } } if (archive_exception) { logWRN("Received an invalid cluster message from a peer. Disconnecting."); message_service->kill_connection(source_peer); } } raw_mailbox_t::id_t mailbox_manager_t::generate_mailbox_id() { raw_mailbox_t::id_t id = ++mailbox_tables.get()->next_mailbox_id; return id; } raw_mailbox_t::id_t mailbox_manager_t::register_mailbox(raw_mailbox_t *mb) { raw_mailbox_t::id_t id = generate_mailbox_id(); std::map<raw_mailbox_t::id_t, raw_mailbox_t *> *mailboxes = &mailbox_tables.get()->mailboxes; std::pair<std::map<raw_mailbox_t::id_t, raw_mailbox_t *>::iterator, bool> res = mailboxes->insert(std::make_pair(id, mb)); guarantee(res.second); // Assert a new element was inserted. return id; } void mailbox_manager_t::unregister_mailbox(raw_mailbox_t::id_t id) { size_t num_elements_erased = mailbox_tables.get()->mailboxes.erase(id); guarantee(num_elements_erased == 1); }
Fix signed and unsigned integer comparison. Closes #1929.
Fix signed and unsigned integer comparison. Closes #1929.
C++
apache-2.0
gavioto/rethinkdb,robertjpayne/rethinkdb,matthaywardwebdesign/rethinkdb,gdi2290/rethinkdb,mquandalle/rethinkdb,rrampage/rethinkdb,sebadiaz/rethinkdb,eliangidoni/rethinkdb,gavioto/rethinkdb,bchavez/rethinkdb,sontek/rethinkdb,losywee/rethinkdb,niieani/rethinkdb,mbroadst/rethinkdb,Qinusty/rethinkdb,KSanthanam/rethinkdb,wojons/rethinkdb,marshall007/rethinkdb,tempbottle/rethinkdb,wojons/rethinkdb,Wilbeibi/rethinkdb,tempbottle/rethinkdb,gdi2290/rethinkdb,captainpete/rethinkdb,yaolinz/rethinkdb,ayumilong/rethinkdb,robertjpayne/rethinkdb,jmptrader/rethinkdb,marshall007/rethinkdb,Qinusty/rethinkdb,pap/rethinkdb,alash3al/rethinkdb,4talesa/rethinkdb,scripni/rethinkdb,sebadiaz/rethinkdb,dparnell/rethinkdb,ayumilong/rethinkdb,niieani/rethinkdb,gavioto/rethinkdb,yaolinz/rethinkdb,elkingtonmcb/rethinkdb,marshall007/rethinkdb,urandu/rethinkdb,mcanthony/rethinkdb,spblightadv/rethinkdb,bpradipt/rethinkdb,urandu/rethinkdb,niieani/rethinkdb,spblightadv/rethinkdb,robertjpayne/rethinkdb,captainpete/rethinkdb,ayumilong/rethinkdb,KSanthanam/rethinkdb,mcanthony/rethinkdb,pap/rethinkdb,ayumilong/rethinkdb,ajose01/rethinkdb,mquandalle/rethinkdb,eliangidoni/rethinkdb,Qinusty/rethinkdb,eliangidoni/rethinkdb,ayumilong/rethinkdb,wkennington/rethinkdb,eliangidoni/rethinkdb,jesseditson/rethinkdb,yaolinz/rethinkdb,losywee/rethinkdb,mcanthony/rethinkdb,wujf/rethinkdb,tempbottle/rethinkdb,AntouanK/rethinkdb,jmptrader/rethinkdb,robertjpayne/rethinkdb,Qinusty/rethinkdb,catroot/rethinkdb,matthaywardwebdesign/rethinkdb,urandu/rethinkdb,losywee/rethinkdb,elkingtonmcb/rethinkdb,matthaywardwebdesign/rethinkdb,catroot/rethinkdb,Wilbeibi/rethinkdb,matthaywardwebdesign/rethinkdb,JackieXie168/rethinkdb,robertjpayne/rethinkdb,scripni/rethinkdb,captainpete/rethinkdb,RubenKelevra/rethinkdb,niieani/rethinkdb,matthaywardwebdesign/rethinkdb,sontek/rethinkdb,yaolinz/rethinkdb,mquandalle/rethinkdb,victorbriz/rethinkdb,niieani/rethinkdb,catroot/rethinkdb,spblightadv/rethinkdb,spblightadv/rethinkdb,bpradipt/rethinkdb,rrampage/rethinkdb,greyhwndz/rethinkdb,captainpete/rethinkdb,matthaywardwebdesign/rethinkdb,sontek/rethinkdb,greyhwndz/rethinkdb,alash3al/rethinkdb,jesseditson/rethinkdb,scripni/rethinkdb,captainpete/rethinkdb,niieani/rethinkdb,jmptrader/rethinkdb,bchavez/rethinkdb,Qinusty/rethinkdb,gdi2290/rethinkdb,elkingtonmcb/rethinkdb,scripni/rethinkdb,pap/rethinkdb,urandu/rethinkdb,mcanthony/rethinkdb,greyhwndz/rethinkdb,KSanthanam/rethinkdb,sebadiaz/rethinkdb,JackieXie168/rethinkdb,yakovenkodenis/rethinkdb,jmptrader/rethinkdb,wujf/rethinkdb,spblightadv/rethinkdb,wujf/rethinkdb,bpradipt/rethinkdb,bpradipt/rethinkdb,gdi2290/rethinkdb,marshall007/rethinkdb,robertjpayne/rethinkdb,tempbottle/rethinkdb,eliangidoni/rethinkdb,grandquista/rethinkdb,lenstr/rethinkdb,captainpete/rethinkdb,gavioto/rethinkdb,ajose01/rethinkdb,mquandalle/rethinkdb,jesseditson/rethinkdb,yakovenkodenis/rethinkdb,Qinusty/rethinkdb,RubenKelevra/rethinkdb,wojons/rethinkdb,Qinusty/rethinkdb,Qinusty/rethinkdb,JackieXie168/rethinkdb,ayumilong/rethinkdb,grandquista/rethinkdb,captainpete/rethinkdb,mbroadst/rethinkdb,rrampage/rethinkdb,rrampage/rethinkdb,mquandalle/rethinkdb,KSanthanam/rethinkdb,4talesa/rethinkdb,catroot/rethinkdb,tempbottle/rethinkdb,Qinusty/rethinkdb,grandquista/rethinkdb,niieani/rethinkdb,jmptrader/rethinkdb,KSanthanam/rethinkdb,greyhwndz/rethinkdb,wojons/rethinkdb,catroot/rethinkdb,lenstr/rethinkdb,mbroadst/rethinkdb,bpradipt/rethinkdb,Wilbeibi/rethinkdb,JackieXie168/rethinkdb,grandquista/rethinkdb,mbroadst/rethinkdb,Wilbeibi/rethinkdb,dparnell/rethinkdb,wkennington/rethinkdb,jesseditson/rethinkdb,RubenKelevra/rethinkdb,AntouanK/rethinkdb,KSanthanam/rethinkdb,bpradipt/rethinkdb,wkennington/rethinkdb,eliangidoni/rethinkdb,yaolinz/rethinkdb,wujf/rethinkdb,rrampage/rethinkdb,matthaywardwebdesign/rethinkdb,bchavez/rethinkdb,4talesa/rethinkdb,marshall007/rethinkdb,rrampage/rethinkdb,KSanthanam/rethinkdb,sbusso/rethinkdb,grandquista/rethinkdb,alash3al/rethinkdb,mcanthony/rethinkdb,losywee/rethinkdb,ayumilong/rethinkdb,RubenKelevra/rethinkdb,lenstr/rethinkdb,victorbriz/rethinkdb,robertjpayne/rethinkdb,bchavez/rethinkdb,mcanthony/rethinkdb,losywee/rethinkdb,pap/rethinkdb,spblightadv/rethinkdb,gavioto/rethinkdb,sontek/rethinkdb,wojons/rethinkdb,gavioto/rethinkdb,wkennington/rethinkdb,RubenKelevra/rethinkdb,greyhwndz/rethinkdb,bpradipt/rethinkdb,ajose01/rethinkdb,marshall007/rethinkdb,4talesa/rethinkdb,spblightadv/rethinkdb,ajose01/rethinkdb,sebadiaz/rethinkdb,Wilbeibi/rethinkdb,losywee/rethinkdb,dparnell/rethinkdb,JackieXie168/rethinkdb,tempbottle/rethinkdb,wkennington/rethinkdb,mbroadst/rethinkdb,lenstr/rethinkdb,JackieXie168/rethinkdb,gdi2290/rethinkdb,mcanthony/rethinkdb,AntouanK/rethinkdb,yakovenkodenis/rethinkdb,jmptrader/rethinkdb,gdi2290/rethinkdb,ajose01/rethinkdb,sbusso/rethinkdb,RubenKelevra/rethinkdb,yakovenkodenis/rethinkdb,RubenKelevra/rethinkdb,dparnell/rethinkdb,dparnell/rethinkdb,victorbriz/rethinkdb,elkingtonmcb/rethinkdb,grandquista/rethinkdb,Wilbeibi/rethinkdb,ajose01/rethinkdb,jmptrader/rethinkdb,urandu/rethinkdb,ajose01/rethinkdb,scripni/rethinkdb,alash3al/rethinkdb,losywee/rethinkdb,JackieXie168/rethinkdb,lenstr/rethinkdb,dparnell/rethinkdb,eliangidoni/rethinkdb,rrampage/rethinkdb,alash3al/rethinkdb,yaolinz/rethinkdb,wkennington/rethinkdb,sebadiaz/rethinkdb,urandu/rethinkdb,dparnell/rethinkdb,pap/rethinkdb,elkingtonmcb/rethinkdb,sontek/rethinkdb,lenstr/rethinkdb,tempbottle/rethinkdb,greyhwndz/rethinkdb,AntouanK/rethinkdb,bpradipt/rethinkdb,AntouanK/rethinkdb,scripni/rethinkdb,pap/rethinkdb,urandu/rethinkdb,scripni/rethinkdb,alash3al/rethinkdb,yakovenkodenis/rethinkdb,pap/rethinkdb,wojons/rethinkdb,bchavez/rethinkdb,AntouanK/rethinkdb,captainpete/rethinkdb,alash3al/rethinkdb,urandu/rethinkdb,sebadiaz/rethinkdb,4talesa/rethinkdb,wujf/rethinkdb,tempbottle/rethinkdb,ayumilong/rethinkdb,bchavez/rethinkdb,sontek/rethinkdb,eliangidoni/rethinkdb,sbusso/rethinkdb,robertjpayne/rethinkdb,bchavez/rethinkdb,gavioto/rethinkdb,yakovenkodenis/rethinkdb,mcanthony/rethinkdb,gdi2290/rethinkdb,elkingtonmcb/rethinkdb,niieani/rethinkdb,KSanthanam/rethinkdb,yakovenkodenis/rethinkdb,bchavez/rethinkdb,yakovenkodenis/rethinkdb,victorbriz/rethinkdb,jesseditson/rethinkdb,dparnell/rethinkdb,victorbriz/rethinkdb,ajose01/rethinkdb,wujf/rethinkdb,catroot/rethinkdb,4talesa/rethinkdb,JackieXie168/rethinkdb,sbusso/rethinkdb,victorbriz/rethinkdb,matthaywardwebdesign/rethinkdb,sbusso/rethinkdb,mquandalle/rethinkdb,wkennington/rethinkdb,rrampage/rethinkdb,Wilbeibi/rethinkdb,dparnell/rethinkdb,elkingtonmcb/rethinkdb,yaolinz/rethinkdb,wujf/rethinkdb,sbusso/rethinkdb,catroot/rethinkdb,wojons/rethinkdb,victorbriz/rethinkdb,losywee/rethinkdb,scripni/rethinkdb,mbroadst/rethinkdb,gavioto/rethinkdb,alash3al/rethinkdb,jesseditson/rethinkdb,sontek/rethinkdb,wojons/rethinkdb,marshall007/rethinkdb,grandquista/rethinkdb,marshall007/rethinkdb,sontek/rethinkdb,greyhwndz/rethinkdb,spblightadv/rethinkdb,eliangidoni/rethinkdb,grandquista/rethinkdb,lenstr/rethinkdb,grandquista/rethinkdb,wkennington/rethinkdb,Wilbeibi/rethinkdb,mquandalle/rethinkdb,victorbriz/rethinkdb,sebadiaz/rethinkdb,AntouanK/rethinkdb,mbroadst/rethinkdb,lenstr/rethinkdb,JackieXie168/rethinkdb,jmptrader/rethinkdb,robertjpayne/rethinkdb,elkingtonmcb/rethinkdb,mbroadst/rethinkdb,RubenKelevra/rethinkdb,4talesa/rethinkdb,bchavez/rethinkdb,AntouanK/rethinkdb,bpradipt/rethinkdb,catroot/rethinkdb,jesseditson/rethinkdb,4talesa/rethinkdb,mbroadst/rethinkdb,greyhwndz/rethinkdb,pap/rethinkdb,sbusso/rethinkdb,mquandalle/rethinkdb,jesseditson/rethinkdb,yaolinz/rethinkdb,sebadiaz/rethinkdb,sbusso/rethinkdb
a18927a0b1a00c5fe3a8ccec069eec55d112634a
include/mapnik/wkt/wkt_factory.hpp
include/mapnik/wkt/wkt_factory.hpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_WKT_FACTORY_HPP #define MAPNIK_WKT_FACTORY_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/geometry.hpp> // boost #include <boost/utility.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <boost/scoped_ptr.hpp> // stl #include <string> namespace mapnik { namespace wkt { template <typename Iterator> struct wkt_collection_grammar; } MAPNIK_DECL bool from_wkt(std::string const& wkt, boost::ptr_vector<geometry_type> & paths); #if BOOST_VERSION >= 104700 class wkt_parser : boost::noncopyable { typedef std::string::const_iterator iterator_type; public: wkt_parser(); bool parse(std::string const& wkt, boost::ptr_vector<geometry_type> & paths); private: boost::scoped_ptr<mapnik::wkt::wkt_collection_grammar<iterator_type> > grammar_; }; #endif } #endif // MAPNIK_WKT_FACTORY_HPP
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_WKT_FACTORY_HPP #define MAPNIK_WKT_FACTORY_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/geometry.hpp> // boost #include <boost/utility.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <boost/scoped_ptr.hpp> #include <boost/version.hpp> // stl #include <string> namespace mapnik { namespace wkt { template <typename Iterator> struct wkt_collection_grammar; } MAPNIK_DECL bool from_wkt(std::string const& wkt, boost::ptr_vector<geometry_type> & paths); #if BOOST_VERSION >= 104700 class wkt_parser : boost::noncopyable { typedef std::string::const_iterator iterator_type; public: wkt_parser(); bool parse(std::string const& wkt, boost::ptr_vector<geometry_type> & paths); private: boost::scoped_ptr<mapnik::wkt::wkt_collection_grammar<iterator_type> > grammar_; }; #endif } #endif // MAPNIK_WKT_FACTORY_HPP
Add include
Add include
C++
lgpl-2.1
qianwenming/mapnik,cjmayo/mapnik,zerebubuth/mapnik,mapnik/python-mapnik,CartoDB/mapnik,mbrukman/mapnik,rouault/mapnik,kapouer/mapnik,mapycz/mapnik,strk/mapnik,sebastic/python-mapnik,mapycz/mapnik,naturalatlas/mapnik,mbrukman/mapnik,strk/mapnik,Uli1/mapnik,naturalatlas/mapnik,cjmayo/mapnik,mapycz/python-mapnik,Uli1/mapnik,whuaegeanse/mapnik,stefanklug/mapnik,rouault/mapnik,kapouer/mapnik,stefanklug/mapnik,mapnik/mapnik,pramsey/mapnik,manz/python-mapnik,yohanboniface/python-mapnik,tomhughes/mapnik,jwomeara/mapnik,mapnik/python-mapnik,mbrukman/mapnik,zerebubuth/mapnik,jwomeara/mapnik,Airphrame/mapnik,pramsey/mapnik,tomhughes/mapnik,tomhughes/python-mapnik,cjmayo/mapnik,stefanklug/mapnik,Mappy/mapnik,pnorman/mapnik,pramsey/mapnik,rouault/mapnik,lightmare/mapnik,lightmare/mapnik,garnertb/python-mapnik,Mappy/mapnik,stefanklug/mapnik,qianwenming/mapnik,pnorman/mapnik,whuaegeanse/mapnik,yohanboniface/python-mapnik,Airphrame/mapnik,whuaegeanse/mapnik,rouault/mapnik,kapouer/mapnik,sebastic/python-mapnik,yiqingj/work,sebastic/python-mapnik,davenquinn/python-mapnik,lightmare/mapnik,strk/mapnik,Mappy/mapnik,CartoDB/mapnik,qianwenming/mapnik,yiqingj/work,Uli1/mapnik,yiqingj/work,kapouer/mapnik,yohanboniface/python-mapnik,mapnik/mapnik,Airphrame/mapnik,mbrukman/mapnik,garnertb/python-mapnik,jwomeara/mapnik,pnorman/mapnik,pnorman/mapnik,qianwenming/mapnik,manz/python-mapnik,Uli1/mapnik,lightmare/mapnik,mapycz/python-mapnik,tomhughes/python-mapnik,tomhughes/python-mapnik,Airphrame/mapnik,jwomeara/mapnik,mapycz/mapnik,CartoDB/mapnik,davenquinn/python-mapnik,tomhughes/mapnik,cjmayo/mapnik,manz/python-mapnik,mapnik/mapnik,zerebubuth/mapnik,Mappy/mapnik,naturalatlas/mapnik,mapnik/mapnik,pramsey/mapnik,whuaegeanse/mapnik,yiqingj/work,davenquinn/python-mapnik,mapnik/python-mapnik,naturalatlas/mapnik,strk/mapnik,garnertb/python-mapnik,qianwenming/mapnik,tomhughes/mapnik
7b1b084af768c7fe076f520e2329019b26928598
include/pajlada/settings/types.hpp
include/pajlada/settings/types.hpp
#pragma once namespace pajlada { namespace Settings { // Custom "JSON Object {}" type struct Object { }; // Custom "JSON Array []" type struct Array { }; } // namespace Settings } // namespace pajlada
#pragma once namespace pajlada { namespace Settings { // Custom "JSON Object {}" type struct Object { bool operator==(const Object &rhs) { return false; } }; // Custom "JSON Array []" type struct Array { bool operator==(const Array &rhs) { return false; } }; } // namespace Settings } // namespace pajlada
Create two dummy ==operators for Object/Array
Create two dummy ==operators for Object/Array
C++
mit
pajlada/settings,pajlada/settings
79f1583f32784ce0bd37d0a7e213df7b09c1cf62
lib/sanitizer_common/sanitizer_tls_get_addr.cc
lib/sanitizer_common/sanitizer_tls_get_addr.cc
//===-- sanitizer_tls_get_addr.cc -----------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Handle the __tls_get_addr call. // //===----------------------------------------------------------------------===// #include "sanitizer_tls_get_addr.h" #include "sanitizer_flags.h" #include "sanitizer_platform_interceptors.h" namespace __sanitizer { #if SANITIZER_INTERCEPT_TLS_GET_ADDR // The actual parameter that comes to __tls_get_addr // is a pointer to a struct with two words in it: struct TlsGetAddrParam { uptr dso_id; uptr offset; }; // Glibc starting from 2.19 allocates tls using __signal_safe_memalign, // which has such header. struct Glibc_2_19_tls_header { uptr size; uptr start; }; // This must be static TLS __attribute__((tls_model("initial-exec"))) static __thread DTLS dtls; // Make sure we properly destroy the DTLS objects: // this counter should never get too large. static atomic_uintptr_t number_of_live_dtls; static const uptr kDestroyedThread = -1; static inline void DTLS_Deallocate(DTLS::DTV *dtv, uptr size) { if (!size) return; VPrintf(2, "__tls_get_addr: DTLS_Deallocate %p %zd\n", dtv, size); UnmapOrDie(dtv, size * sizeof(DTLS::DTV)); atomic_fetch_sub(&number_of_live_dtls, 1, memory_order_relaxed); } static inline void DTLS_Resize(uptr new_size) { if (dtls.dtv_size >= new_size) return; new_size = RoundUpToPowerOfTwo(new_size); new_size = Max(new_size, 4096UL / sizeof(DTLS::DTV)); DTLS::DTV *new_dtv = (DTLS::DTV *)MmapOrDie(new_size * sizeof(DTLS::DTV), "DTLS_Resize"); uptr num_live_dtls = atomic_fetch_add(&number_of_live_dtls, 1, memory_order_relaxed); VPrintf(2, "__tls_get_addr: DTLS_Resize %p %zd\n", &dtls, num_live_dtls); CHECK_LT(num_live_dtls, 1 << 20); uptr old_dtv_size = dtls.dtv_size; DTLS::DTV *old_dtv = dtls.dtv; if (old_dtv_size) internal_memcpy(new_dtv, dtls.dtv, dtls.dtv_size * sizeof(DTLS::DTV)); dtls.dtv = new_dtv; dtls.dtv_size = new_size; if (old_dtv_size) DTLS_Deallocate(old_dtv, old_dtv_size); } void DTLS_Destroy() { if (!common_flags()->intercept_tls_get_addr) return; VPrintf(2, "__tls_get_addr: DTLS_Destroy %p %zd\n", &dtls, dtls.dtv_size); uptr s = dtls.dtv_size; dtls.dtv_size = kDestroyedThread; // Do this before unmap for AS-safety. DTLS_Deallocate(dtls.dtv, s); } #if defined(__powerpc64__) // This is glibc's TLS_DTV_OFFSET: // "Dynamic thread vector pointers point 0x8000 past the start of each // TLS block." static const uptr kDtvOffset = 0x8000; #else static const uptr kDtvOffset = 0; #endif DTLS::DTV *DTLS_on_tls_get_addr(void *arg_void, void *res, uptr static_tls_begin, uptr static_tls_end) { if (!common_flags()->intercept_tls_get_addr) return 0; TlsGetAddrParam *arg = reinterpret_cast<TlsGetAddrParam *>(arg_void); uptr dso_id = arg->dso_id; if (dtls.dtv_size == kDestroyedThread) return 0; DTLS_Resize(dso_id + 1); if (dtls.dtv[dso_id].beg) return 0; uptr tls_size = 0; uptr tls_beg = reinterpret_cast<uptr>(res) - arg->offset - kDtvOffset; VPrintf(2, "__tls_get_addr: %p {%p,%p} => %p; tls_beg: %p; sp: %p " "num_live_dtls %zd\n", arg, arg->dso_id, arg->offset, res, tls_beg, &tls_beg, atomic_load(&number_of_live_dtls, memory_order_relaxed)); if (dtls.last_memalign_ptr == tls_beg) { tls_size = dtls.last_memalign_size; VPrintf(2, "__tls_get_addr: glibc <=2.18 suspected; tls={%p,%p}\n", tls_beg, tls_size); } else if (tls_beg >= static_tls_begin && tls_beg < static_tls_end) { // This is the static TLS block which was initialized / unpoisoned at thread // creation. VPrintf(2, "__tls_get_addr: static tls: %p\n", tls_beg); tls_size = 0; } else if ((tls_beg % 4096) == sizeof(Glibc_2_19_tls_header)) { // We may want to check gnu_get_libc_version(). Glibc_2_19_tls_header *header = (Glibc_2_19_tls_header *)tls_beg - 1; tls_size = header->size; tls_beg = header->start; VPrintf(2, "__tls_get_addr: glibc >=2.19 suspected; tls={%p %p}\n", tls_beg, tls_size); } else { VPrintf(2, "__tls_get_addr: Can't guess glibc version\n"); // This may happen inside the DTOR of main thread, so just ignore it. tls_size = 0; } dtls.dtv[dso_id].beg = tls_beg; dtls.dtv[dso_id].size = tls_size; return dtls.dtv + dso_id; } void DTLS_on_libc_memalign(void *ptr, uptr size) { if (!common_flags()->intercept_tls_get_addr) return; VPrintf(2, "DTLS_on_libc_memalign: %p %p\n", ptr, size); dtls.last_memalign_ptr = reinterpret_cast<uptr>(ptr); dtls.last_memalign_size = size; } DTLS *DTLS_Get() { return &dtls; } #else void DTLS_on_libc_memalign(void *ptr, uptr size) {} DTLS::DTV *DTLS_on_tls_get_addr(void *arg, void *res) { return 0; } DTLS *DTLS_Get() { return 0; } void DTLS_Destroy() {} #endif // SANITIZER_INTERCEPT_TLS_GET_ADDR } // namespace __sanitizer
//===-- sanitizer_tls_get_addr.cc -----------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Handle the __tls_get_addr call. // //===----------------------------------------------------------------------===// #include "sanitizer_tls_get_addr.h" #include "sanitizer_flags.h" #include "sanitizer_platform_interceptors.h" namespace __sanitizer { #if SANITIZER_INTERCEPT_TLS_GET_ADDR // The actual parameter that comes to __tls_get_addr // is a pointer to a struct with two words in it: struct TlsGetAddrParam { uptr dso_id; uptr offset; }; // Glibc starting from 2.19 allocates tls using __signal_safe_memalign, // which has such header. struct Glibc_2_19_tls_header { uptr size; uptr start; }; // This must be static TLS __attribute__((tls_model("initial-exec"))) static __thread DTLS dtls; // Make sure we properly destroy the DTLS objects: // this counter should never get too large. static atomic_uintptr_t number_of_live_dtls; static const uptr kDestroyedThread = -1; static inline void DTLS_Deallocate(DTLS::DTV *dtv, uptr size) { if (!size) return; VPrintf(2, "__tls_get_addr: DTLS_Deallocate %p %zd\n", dtv, size); UnmapOrDie(dtv, size * sizeof(DTLS::DTV)); atomic_fetch_sub(&number_of_live_dtls, 1, memory_order_relaxed); } static inline void DTLS_Resize(uptr new_size) { if (dtls.dtv_size >= new_size) return; new_size = RoundUpToPowerOfTwo(new_size); new_size = Max(new_size, 4096UL / sizeof(DTLS::DTV)); DTLS::DTV *new_dtv = (DTLS::DTV *)MmapOrDie(new_size * sizeof(DTLS::DTV), "DTLS_Resize"); uptr num_live_dtls = atomic_fetch_add(&number_of_live_dtls, 1, memory_order_relaxed); VPrintf(2, "__tls_get_addr: DTLS_Resize %p %zd\n", &dtls, num_live_dtls); CHECK_LT(num_live_dtls, 1 << 20); uptr old_dtv_size = dtls.dtv_size; DTLS::DTV *old_dtv = dtls.dtv; if (old_dtv_size) internal_memcpy(new_dtv, dtls.dtv, dtls.dtv_size * sizeof(DTLS::DTV)); dtls.dtv = new_dtv; dtls.dtv_size = new_size; if (old_dtv_size) DTLS_Deallocate(old_dtv, old_dtv_size); } void DTLS_Destroy() { if (!common_flags()->intercept_tls_get_addr) return; VPrintf(2, "__tls_get_addr: DTLS_Destroy %p %zd\n", &dtls, dtls.dtv_size); uptr s = dtls.dtv_size; dtls.dtv_size = kDestroyedThread; // Do this before unmap for AS-safety. DTLS_Deallocate(dtls.dtv, s); } #if defined(__powerpc64__) || defined(__mips__) // This is glibc's TLS_DTV_OFFSET: // "Dynamic thread vector pointers point 0x8000 past the start of each // TLS block." static const uptr kDtvOffset = 0x8000; #else static const uptr kDtvOffset = 0; #endif DTLS::DTV *DTLS_on_tls_get_addr(void *arg_void, void *res, uptr static_tls_begin, uptr static_tls_end) { if (!common_flags()->intercept_tls_get_addr) return 0; TlsGetAddrParam *arg = reinterpret_cast<TlsGetAddrParam *>(arg_void); uptr dso_id = arg->dso_id; if (dtls.dtv_size == kDestroyedThread) return 0; DTLS_Resize(dso_id + 1); if (dtls.dtv[dso_id].beg) return 0; uptr tls_size = 0; uptr tls_beg = reinterpret_cast<uptr>(res) - arg->offset - kDtvOffset; VPrintf(2, "__tls_get_addr: %p {%p,%p} => %p; tls_beg: %p; sp: %p " "num_live_dtls %zd\n", arg, arg->dso_id, arg->offset, res, tls_beg, &tls_beg, atomic_load(&number_of_live_dtls, memory_order_relaxed)); if (dtls.last_memalign_ptr == tls_beg) { tls_size = dtls.last_memalign_size; VPrintf(2, "__tls_get_addr: glibc <=2.18 suspected; tls={%p,%p}\n", tls_beg, tls_size); } else if (tls_beg >= static_tls_begin && tls_beg < static_tls_end) { // This is the static TLS block which was initialized / unpoisoned at thread // creation. VPrintf(2, "__tls_get_addr: static tls: %p\n", tls_beg); tls_size = 0; } else if ((tls_beg % 4096) == sizeof(Glibc_2_19_tls_header)) { // We may want to check gnu_get_libc_version(). Glibc_2_19_tls_header *header = (Glibc_2_19_tls_header *)tls_beg - 1; tls_size = header->size; tls_beg = header->start; VPrintf(2, "__tls_get_addr: glibc >=2.19 suspected; tls={%p %p}\n", tls_beg, tls_size); } else { VPrintf(2, "__tls_get_addr: Can't guess glibc version\n"); // This may happen inside the DTOR of main thread, so just ignore it. tls_size = 0; } dtls.dtv[dso_id].beg = tls_beg; dtls.dtv[dso_id].size = tls_size; return dtls.dtv + dso_id; } void DTLS_on_libc_memalign(void *ptr, uptr size) { if (!common_flags()->intercept_tls_get_addr) return; VPrintf(2, "DTLS_on_libc_memalign: %p %p\n", ptr, size); dtls.last_memalign_ptr = reinterpret_cast<uptr>(ptr); dtls.last_memalign_size = size; } DTLS *DTLS_Get() { return &dtls; } #else void DTLS_on_libc_memalign(void *ptr, uptr size) {} DTLS::DTV *DTLS_on_tls_get_addr(void *arg, void *res) { return 0; } DTLS *DTLS_Get() { return 0; } void DTLS_Destroy() {} #endif // SANITIZER_INTERCEPT_TLS_GET_ADDR } // namespace __sanitizer
Correct Dynamic Thread Vector offset for MIPS
[Compiler-rt][MIPS] Correct Dynamic Thread Vector offset for MIPS Reviewers: samsonov Subscribers: dsanders, jaydeep, sagar, llvm-commits Differential Revision: http://reviews.llvm.org/D17703 git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@262303 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
9e3a7626fc5c86e09822806e84c5342d332867f7
include/Nazara/Graphics/Sprite.inl
include/Nazara/Graphics/Sprite.inl
// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Error.hpp> #include <memory> #include <Nazara/Renderer/Debug.hpp> namespace Nz { /*! * \brief Constructs a Sprite object by default */ inline Sprite::Sprite() : m_color(Color::White), m_origin(Nz::Vector3f::Zero()), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_size(64.f, 64.f) { SetDefaultMaterial(); } /*! * \brief Constructs a Sprite object with a reference to a material * * \param material Reference to a material */ inline Sprite::Sprite(MaterialRef material) : m_color(Color::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_size(64.f, 64.f) { SetMaterial(std::move(material), true); } /*! * \brief Constructs a Sprite object with a pointer to a texture * * \param texture Pointer to a texture */ inline Sprite::Sprite(Texture* texture) : m_color(Color::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_size(64.f, 64.f) { SetTexture(texture, true); } /*! * \brief Constructs a Sprite object by assignation * * \param sprite Sprite to copy into this */ inline Sprite::Sprite(const Sprite& sprite) : InstancedRenderable(sprite), m_color(sprite.m_color), m_material(sprite.m_material), m_textureCoords(sprite.m_textureCoords), m_size(sprite.m_size) { } /*! * \brief Gets the color of the sprite * \return Current color */ inline const Color& Sprite::GetColor() const { return m_color; } /*! * \brief Gets the material of the sprite * \return Current material */ inline const MaterialRef& Sprite::GetMaterial() const { return m_material; } /*! * \brief Gets the origin of the sprite * * \return Current material * * \see SetOrigin */ inline const Vector3f & Sprite::GetOrigin() const { return m_origin; } /*! * \brief Gets the size of the sprite * \return Current size */ inline const Vector2f& Sprite::GetSize() const { return m_size; } /*! * \brief Gets the texture coordinates of the sprite * \return Current texture coordinates */ inline const Rectf& Sprite::GetTextureCoords() const { return m_textureCoords; } /*! * \brief Sets the color of the billboard * * \param color Color for the billboard */ inline void Sprite::SetColor(const Color& color) { m_color = color; InvalidateVertices(); } /*! * \brief Sets the default material of the sprite (just default material) */ inline void Sprite::SetDefaultMaterial() { MaterialRef material = Material::New(); material->EnableFaceCulling(false); SetMaterial(std::move(material)); } /*! * \brief Sets the material of the sprite * * \param material Material for the sprite * \param resizeSprite Should sprite be resized to the material size (diffuse map) */ inline void Sprite::SetMaterial(MaterialRef material, bool resizeSprite) { m_material = std::move(material); if (m_material && resizeSprite) { Texture* diffuseMap = m_material->GetDiffuseMap(); if (diffuseMap && diffuseMap->IsValid()) SetSize(Vector2f(Vector2ui(diffuseMap->GetSize()))); } } /*! * \brief Sets the origin of the sprite * * The origin is the center of translation/rotation/scaling of the sprite. * * \param origin New origin for the sprite * * \see GetOrigin */ inline void Sprite::SetOrigin(const Vector3f& origin) { m_origin = origin; // On invalide la bounding box InvalidateBoundingVolume(); InvalidateVertices(); } /*! * \brief Sets the size of the sprite * * \param size Size for the sprite */ inline void Sprite::SetSize(const Vector2f& size) { m_size = size; // On invalide la bounding box InvalidateBoundingVolume(); InvalidateVertices(); } /*! * \brief Sets the size of the sprite * * \param sizeX Size in X for the sprite * \param sizeY Size in Y for the sprite */ inline void Sprite::SetSize(float sizeX, float sizeY) { SetSize(Vector2f(sizeX, sizeY)); } /*! * \brief Sets the texture of the sprite * * \param texture Texture for the sprite * \param resizeSprite Should sprite be resized to the texture size */ inline void Sprite::SetTexture(TextureRef texture, bool resizeSprite) { if (!m_material) SetDefaultMaterial(); else if (m_material->GetReferenceCount() > 1) m_material = Material::New(*m_material); // Copie if (resizeSprite && texture && texture->IsValid()) SetSize(Vector2f(Vector2ui(texture->GetSize()))); m_material->SetDiffuseMap(std::move(texture)); } /*! * \brief Sets the texture coordinates of the sprite * * \param coords Texture coordinates */ inline void Sprite::SetTextureCoords(const Rectf& coords) { m_textureCoords = coords; InvalidateVertices(); } /*! * \brief Sets the texture rectangle of the sprite * * \param rect Rectangles symbolizing the size of the texture * * \remark Produces a NazaraAssert if material is invalid * \remark Produces a NazaraAssert if material has no diffuse map */ inline void Sprite::SetTextureRect(const Rectui& rect) { NazaraAssert(m_material, "Sprite has no material"); NazaraAssert(m_material->HasDiffuseMap(), "Sprite material has no diffuse map"); Texture* diffuseMap = m_material->GetDiffuseMap(); float invWidth = 1.f / diffuseMap->GetWidth(); float invHeight = 1.f / diffuseMap->GetHeight(); SetTextureCoords(Rectf(invWidth * rect.x, invHeight * rect.y, invWidth * rect.width, invHeight * rect.height)); } /*! * \brief Sets the current sprite with the content of the other one * \return A reference to this * * \param sprite The other Sprite */ inline Sprite& Sprite::operator=(const Sprite& sprite) { InstancedRenderable::operator=(sprite); m_color = sprite.m_color; m_material = sprite.m_material; m_textureCoords = sprite.m_textureCoords; m_size = sprite.m_size; // We do not copy final vertices because it's highly probable that our parameters are modified and they must be regenerated InvalidateBoundingVolume(); InvalidateVertices(); return *this; } /*! * \brief Invalidates the vertices */ inline void Sprite::InvalidateVertices() { InvalidateInstanceData(0); } /*! * \brief Creates a new sprite from the arguments * \return A reference to the newly created sprite * * \param args Arguments for the sprite */ template<typename... Args> SpriteRef Sprite::New(Args&&... args) { std::unique_ptr<Sprite> object(new Sprite(std::forward<Args>(args)...)); object->SetPersistent(false); return object.release(); } } #include <Nazara/Renderer/DebugOff.hpp> #include "Sprite.hpp"
// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Error.hpp> #include <memory> #include <Nazara/Renderer/Debug.hpp> namespace Nz { /*! * \brief Constructs a Sprite object by default */ inline Sprite::Sprite() : m_color(Color::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_size(64.f, 64.f), m_origin(Nz::Vector3f::Zero()) { SetDefaultMaterial(); } /*! * \brief Constructs a Sprite object with a reference to a material * * \param material Reference to a material */ inline Sprite::Sprite(MaterialRef material) : Sprite() { SetMaterial(std::move(material), true); } /*! * \brief Constructs a Sprite object with a pointer to a texture * * \param texture Pointer to a texture */ inline Sprite::Sprite(Texture* texture) : Sprite() { SetTexture(texture, true); } /*! * \brief Constructs a Sprite object by assignation * * \param sprite Sprite to copy into this */ inline Sprite::Sprite(const Sprite& sprite) : InstancedRenderable(sprite), m_color(sprite.m_color), m_material(sprite.m_material), m_textureCoords(sprite.m_textureCoords), m_size(sprite.m_size), m_origin(sprite.m_origin) { } /*! * \brief Gets the color of the sprite * \return Current color */ inline const Color& Sprite::GetColor() const { return m_color; } /*! * \brief Gets the material of the sprite * \return Current material */ inline const MaterialRef& Sprite::GetMaterial() const { return m_material; } /*! * \brief Gets the origin of the sprite * * \return Current material * * \see SetOrigin */ inline const Vector3f & Sprite::GetOrigin() const { return m_origin; } /*! * \brief Gets the size of the sprite * \return Current size */ inline const Vector2f& Sprite::GetSize() const { return m_size; } /*! * \brief Gets the texture coordinates of the sprite * \return Current texture coordinates */ inline const Rectf& Sprite::GetTextureCoords() const { return m_textureCoords; } /*! * \brief Sets the color of the billboard * * \param color Color for the billboard */ inline void Sprite::SetColor(const Color& color) { m_color = color; InvalidateVertices(); } /*! * \brief Sets the default material of the sprite (just default material) */ inline void Sprite::SetDefaultMaterial() { MaterialRef material = Material::New(); material->EnableFaceCulling(false); SetMaterial(std::move(material)); } /*! * \brief Sets the material of the sprite * * \param material Material for the sprite * \param resizeSprite Should sprite be resized to the material size (diffuse map) */ inline void Sprite::SetMaterial(MaterialRef material, bool resizeSprite) { m_material = std::move(material); if (m_material && resizeSprite) { Texture* diffuseMap = m_material->GetDiffuseMap(); if (diffuseMap && diffuseMap->IsValid()) SetSize(Vector2f(Vector2ui(diffuseMap->GetSize()))); } } /*! * \brief Sets the origin of the sprite * * The origin is the center of translation/rotation/scaling of the sprite. * * \param origin New origin for the sprite * * \see GetOrigin */ inline void Sprite::SetOrigin(const Vector3f& origin) { m_origin = origin; // On invalide la bounding box InvalidateBoundingVolume(); InvalidateVertices(); } /*! * \brief Sets the size of the sprite * * \param size Size for the sprite */ inline void Sprite::SetSize(const Vector2f& size) { m_size = size; // On invalide la bounding box InvalidateBoundingVolume(); InvalidateVertices(); } /*! * \brief Sets the size of the sprite * * \param sizeX Size in X for the sprite * \param sizeY Size in Y for the sprite */ inline void Sprite::SetSize(float sizeX, float sizeY) { SetSize(Vector2f(sizeX, sizeY)); } /*! * \brief Sets the texture of the sprite * * \param texture Texture for the sprite * \param resizeSprite Should sprite be resized to the texture size */ inline void Sprite::SetTexture(TextureRef texture, bool resizeSprite) { if (!m_material) SetDefaultMaterial(); else if (m_material->GetReferenceCount() > 1) m_material = Material::New(*m_material); // Copie if (resizeSprite && texture && texture->IsValid()) SetSize(Vector2f(Vector2ui(texture->GetSize()))); m_material->SetDiffuseMap(std::move(texture)); } /*! * \brief Sets the texture coordinates of the sprite * * \param coords Texture coordinates */ inline void Sprite::SetTextureCoords(const Rectf& coords) { m_textureCoords = coords; InvalidateVertices(); } /*! * \brief Sets the texture rectangle of the sprite * * \param rect Rectangles symbolizing the size of the texture * * \remark Produces a NazaraAssert if material is invalid * \remark Produces a NazaraAssert if material has no diffuse map */ inline void Sprite::SetTextureRect(const Rectui& rect) { NazaraAssert(m_material, "Sprite has no material"); NazaraAssert(m_material->HasDiffuseMap(), "Sprite material has no diffuse map"); Texture* diffuseMap = m_material->GetDiffuseMap(); float invWidth = 1.f / diffuseMap->GetWidth(); float invHeight = 1.f / diffuseMap->GetHeight(); SetTextureCoords(Rectf(invWidth * rect.x, invHeight * rect.y, invWidth * rect.width, invHeight * rect.height)); } /*! * \brief Sets the current sprite with the content of the other one * \return A reference to this * * \param sprite The other Sprite */ inline Sprite& Sprite::operator=(const Sprite& sprite) { InstancedRenderable::operator=(sprite); m_color = sprite.m_color; m_material = sprite.m_material; m_origin = sprite.m_origin; m_textureCoords = sprite.m_textureCoords; m_size = sprite.m_size; // We do not copy final vertices because it's highly probable that our parameters are modified and they must be regenerated InvalidateBoundingVolume(); InvalidateVertices(); return *this; } /*! * \brief Invalidates the vertices */ inline void Sprite::InvalidateVertices() { InvalidateInstanceData(0); } /*! * \brief Creates a new sprite from the arguments * \return A reference to the newly created sprite * * \param args Arguments for the sprite */ template<typename... Args> SpriteRef Sprite::New(Args&&... args) { std::unique_ptr<Sprite> object(new Sprite(std::forward<Args>(args)...)); object->SetPersistent(false); return object.release(); } } #include <Nazara/Renderer/DebugOff.hpp> #include "Sprite.hpp"
Fix origin not being initialized/copied
Graphics/Sprite: Fix origin not being initialized/copied Former-commit-id: 790b49278d8cf7c1800f559cf0d29d65d0834b08 [formerly 93b247cc3433a5ac7c0f5a5ef48b0cf7a0c0f9dc] [formerly 9d6210ac2449aa5dc0d74d9a3cb256480e095008 [formerly 4ccda8249177b9ba5daa5406fd57f17b483cd81c]] Former-commit-id: 22dcc8245a3ec0774c1723f88682c585a43ff3c7 [formerly 94bbee0ec1e3fb904d83258da52b8f90634f4c8a] Former-commit-id: a8326b7bec2c16837b1340de8edd5c731ec837ec
C++
mit
DigitalPulseSoftware/NazaraEngine
cad9eb846657a4c03b623368b9a0a79236613f7b
test/handler_mock.hpp
test/handler_mock.hpp
// Copyright 2021 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. #pragma once #include "handler.hpp" #include <cstddef> #include <cstdint> #include <string> #include <tuple> #include <gmock/gmock.h> namespace google { namespace ipmi { class HandlerMock : public HandlerInterface { public: ~HandlerMock() = default; MOCK_CONST_METHOD1(getEthDetails, std::tuple<std::uint8_t, std::string>(std::string)); MOCK_CONST_METHOD1(getRxPackets, std::int64_t(const std::string&)); MOCK_CONST_METHOD1(getCpldVersion, std::tuple<std::uint8_t, std::uint8_t, std::uint8_t, std::uint8_t>(unsigned int)); MOCK_CONST_METHOD1(psuResetDelay, void(std::uint32_t)); MOCK_CONST_METHOD0(psuResetOnShutdown, void()); MOCK_METHOD0(getFlashSize, uint32_t()); MOCK_METHOD2(getEntityName, std::string(std::uint8_t, std::uint8_t)); MOCK_METHOD0(getMachineName, std::string()); MOCK_METHOD0(buildI2cPcieMapping, void()); MOCK_CONST_METHOD0(getI2cPcieMappingSize, size_t()); MOCK_CONST_METHOD1(getI2cEntry, std::tuple<std::uint32_t, std::string>(unsigned int)); MOCK_CONST_METHOD1(hostPowerOffDelay, void(std::uint32_t)); }; } // namespace ipmi } // namespace google
// Copyright 2021 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. #pragma once #include "handler.hpp" #include <cstddef> #include <cstdint> #include <string> #include <tuple> #include <gmock/gmock.h> namespace google { namespace ipmi { class HandlerMock : public HandlerInterface { public: ~HandlerMock() = default; MOCK_METHOD((std::tuple<std::uint8_t, std::string>), getEthDetails, (std::string), (const, override)); MOCK_METHOD(std::int64_t, getRxPackets, (const std::string&), (const, override)); MOCK_METHOD( (std::tuple<std::uint8_t, std::uint8_t, std::uint8_t, std::uint8_t>), getCpldVersion, (unsigned int), (const, override)); MOCK_METHOD(void, psuResetDelay, (std::uint32_t), (const, override)); MOCK_METHOD(void, psuResetOnShutdown, (), (const, override)); MOCK_METHOD(std::uint32_t, getFlashSize, (), (override)); MOCK_METHOD(std::string, getEntityName, (std::uint8_t, std::uint8_t), (override)); MOCK_METHOD(std::string, getMachineName, (), (override)); MOCK_METHOD(void, buildI2cPcieMapping, (), (override)); MOCK_METHOD(size_t, getI2cPcieMappingSize, (), (const, override)); MOCK_METHOD((std::tuple<std::uint32_t, std::string>), getI2cEntry, (unsigned int), (const, override)); MOCK_METHOD(void, hostPowerOffDelay, (std::uint32_t), (const, override)); }; } // namespace ipmi } // namespace google
Replace the C++ MOCK_METHOD<n> macros with the new MOCK_METHOD
test: Replace the C++ MOCK_METHOD<n> macros with the new MOCK_METHOD Change-Id: If9d29d7a4706204dfda6b698388f72e442ab2d98 Signed-off-by: Willy Tu <[email protected]>
C++
apache-2.0
openbmc/google-ipmi-sys
5dc5b2c48f708d7dde4eaddf2313112894e8a284
include/ResourceManager/Logger.hpp
include/ResourceManager/Logger.hpp
//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014 stevehalliwell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // //////////////////////////////////////////////////////////// //////jjhkjhjhkjhjkh///// #ifndef LOGGER_HPP #define LOGGER_HPP #include <iostream> #include <string> #include <fstream> //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// namespace rm { class Logger { public: //////////////////////////////////////////////////////////// /// \brief Prints a single value of unknown type to both the /// console and to a log file if it exists /// /// \param data The data to print. data must be compatible /// with std streams /// //////////////////////////////////////////////////////////// template<typename Arg> static void logMessage(const Arg& data); //////////////////////////////////////////////////////////// /// \brief Prints multiple values of unknown types to both the /// console and to a log file if it exists /// /// \param data The data to print. data must be compatible /// with std streams /// /// \param other The remaining data to print. /// //////////////////////////////////////////////////////////// template<typename Arg1, typename... OtherArgs> static void logMessage(const Arg1& data, const OtherArgs&... other); //////////////////////////////////////////////////////////// /// \brief Sets the location of the file that the logger prints /// to /// /// \param path The path of the file /// //////////////////////////////////////////////////////////// static void setFileLocation(const std::string& path); private: static std::fstream file; static bool doesPrintOut; }; #include <ResourceManager/Logger.inl> } #endif //LOGGER_HPP
//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014 stevehalliwell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // //////////////////////////////////////////////////////////// #ifndef LOGGER_HPP #define LOGGER_HPP #include <iostream> #include <string> #include <fstream> //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// namespace rm { class Logger { public: //////////////////////////////////////////////////////////// /// \brief Prints a single value of unknown type to both the /// console and to a log file if it exists /// /// \param data The data to print. data must be compatible /// with std streams /// //////////////////////////////////////////////////////////// template<typename Arg> static void logMessage(const Arg& data); //////////////////////////////////////////////////////////// /// \brief Prints multiple values of unknown types to both the /// console and to a log file if it exists /// /// \param data The data to print. data must be compatible /// with std streams /// /// \param other The remaining data to print. /// //////////////////////////////////////////////////////////// template<typename Arg1, typename... OtherArgs> static void logMessage(const Arg1& data, const OtherArgs&... other); //////////////////////////////////////////////////////////// /// \brief Sets the location of the file that the logger prints /// to /// /// \param path The path of the file /// //////////////////////////////////////////////////////////// static void setFileLocation(const std::string& path); private: static std::fstream file; static bool doesPrintOut; }; #include <ResourceManager/Logger.inl> } #endif //LOGGER_HPP
test 2
test 2
C++
mit
stevehalliwell/sfml-resman
f367495e314cf46ecc72f77203d52d3caa3b6957
include/chemfiles/files/NcFile.hpp
include/chemfiles/files/NcFile.hpp
/* Chemfiles, an efficient IO library for chemistry file_ formats * Copyright (C) 2015 Guillaume Fraux * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file_, You can obtain one at http://mozilla.org/MPL/2.0/ */ #include "chemfiles/config.hpp" #if HAVE_NETCDF #ifndef CHEMFILES_NCFILE_HPP #define CHEMFILES_NCFILE_HPP #include <vector> #include <string> #include <cassert> #include <netcdf.h> #include "chemfiles/File.hpp" namespace chemfiles { class NcFile; namespace nc { //! Maximum lenght for strings in variables const size_t STRING_MAXLEN = 10; //! NetCDF id type definition using netcdf_id_t = int; //! Count for variable stride and starting point using count_t = std::vector<size_t>; //! Get the number of elements in a NetCDF hyperslab with `count` elements. size_t hyperslab_size(const count_t& count); //! Check for netcdf return `status`. This will throw a `FileError` with the //! given `message` in case of error. void check(int status, const std::string& message); //! Enable a member function at compile-time if T and U are the same types template<class T, class U> using enable_if_same = typename std::enable_if<std::is_same<T, U>::value>::type; /*! * @class NcVariable NcFile.hpp NcFile.cpp * @brief RAII wrapper around NetCDF variable * * This class is manually instanciated for float and char types, which are the * only ones needed by chemfiles. */ template <typename NcType> class NcVariable { public: //! Create a new variable from `file` with id `var`. NcVariable(NcFile& file, netcdf_id_t var); //! Get the attribute `name`. std::string attribute(const std::string& name); //! Add an attribute with the given `value` and `name`. void add_attribute(const std::string& name, const std::string& value); //! Get `count` values starting at `start` from this variable template<typename T = NcType, typename unused = enable_if_same<T, float>> std::vector<float> get(count_t start, count_t count) const; //! Add `cout` values from `data` starting at `start` in this variable template<typename T = NcType, typename unused = enable_if_same<T, float>> void add(count_t start, count_t count, std::vector<float> data); //! Put a single string of data in this variable template<typename T = NcType, typename unused = enable_if_same<T, char>> void add(std::string data); //! Put multiple strings of data in this variable template<typename T = NcType, typename unused = enable_if_same<T, char>> void add(std::vector<const char*> data); //! Get the dimensions size for this variable std::vector<size_t> dimmensions() const; private: NcFile& file_; netcdf_id_t var_id_; }; //! Mapping between C++ and NetCDF data types template<typename NcType> struct nc_type {}; template<> struct nc_type<float> {static constexpr auto value = NC_FLOAT;}; template<> struct nc_type<char> {static constexpr auto value = NC_CHAR;}; } // namespace nc /*! * @class NcFile NcFile.hpp NcFile.cpp * @brief RAII wrapper around NetCDF 3 binary files * * This interface only provide basic functionalities needed by the Amber NetCDF * format. All the operation are guaranteed to return a valid value or throw an * error. * * The template functions are manually specialized for float and char data types. */ class NcFile final: public BinaryFile { public: NcFile(const std::string& filename, File::Mode mode); ~NcFile() noexcept; //! Possible file mode. By default, files are in the DATA mode. enum NcMode { //! Files in DEFINE mode can have there attributes, dimmensions and variables //! modified, but no data can be read or written using NcVariable. DEFINE, //! Files in data mode acces read and write access to NcVariables. DATA, }; //! Set the file mode for this file void set_nc_mode(NcMode mode); //! Get the file mode for this file NcMode nc_mode() const; //! Get the NetCDF id of this file. nc::netcdf_id_t netcdf_id() const { return file_id_; } //! Get a global string attribut from the file std::string global_attribute(const std::string& name) const; //! Create a global attribut in the file_ void add_global_attribute(const std::string& name, const std::string& value); //! Get the value of a specific dimmension size_t dimension(const std::string& name) const; //! Get the value of an optional dimmension, or the default `value` if the //! dimmension is not in the file size_t optional_dimension(const std::string& name, size_t value) const; //! Create a dimmension with the specified value. If `value == NC_UNLIMITED`, //! then the dimension is infinite. void add_dimension(const std::string& name, size_t value = NC_UNLIMITED); //! Check if a variable exists bool variable_exists(const std::string& name) const; //! Get a NetCDF variable template <typename NcType> nc::NcVariable<NcType> variable(const std::string& name) { auto var_id = nc::netcdf_id_t(-1); auto status = nc_inq_varid(file_id_, name.c_str(), &var_id); nc::check(status, "Can not read variable '" + name + "'"); return nc::NcVariable<NcType>(*this, var_id); } //! Create a new variable of type `NcType` with name `name` along the dimensions in //! `dims`. `dims` must be string or string-like values. template <typename NcType, typename ...Dims> nc::NcVariable<NcType> add_variable(const std::string& name, Dims... dims) { assert(nc_mode() == DEFINE && "File must be in define mode to add variable"); auto dim_ids = get_dimmensions(dims...); auto var_id = nc::netcdf_id_t(-1); auto status = nc_def_var( // Variable file and name file_id_, name.c_str(), // Variable type nc::nc_type<NcType>::value, // Variable dimmensions sizeof...(dims), dim_ids.data(), &var_id ); nc::check(status, "Can not add variable '" + name + "'"); return nc::NcVariable<NcType>(*this, var_id); } // A NcFile will always be in a consistent mode bool is_open() override {return true;} private: template <typename ...Dims> std::vector<nc::netcdf_id_t> get_dimmensions(Dims... dims) { std::vector<std::string> dimmensions = {dims...}; std::vector<nc::netcdf_id_t> dim_ids; for (auto& name: dimmensions) { auto dim_id = nc::netcdf_id_t(-1); auto status = nc_inq_dimid(file_id_, name.c_str(), &dim_id); nc::check(status, "Can not get dimmension '" + name + "'"); dim_ids.push_back(dim_id); } return dim_ids; } nc::netcdf_id_t file_id_ = -1; NcMode nc_mode_; }; namespace nc { template <typename NcType> NcVariable<NcType>::NcVariable(NcFile& file, netcdf_id_t var): file_(file), var_id_(var) {} template <typename NcType> std::string NcVariable<NcType>::attribute(const std::string& name) { size_t size = 0; int status = nc_inq_attlen(file_.netcdf_id(), var_id_, name.c_str(), &size); nc::check(status, "Can not read attribute id '" + name + "'"); std::string value(size, ' '); status = nc_get_att_text(file_.netcdf_id(), var_id_, name.c_str(), &value[0]); nc::check(status, "Can not read attribute text '" + name + "'"); return value; } template <typename NcType> void NcVariable<NcType>::add_attribute(const std::string& name, const std::string& value) { assert(file_.nc_mode() == NcFile::DEFINE && "File must be in define mode to add attribute"); int status = nc_put_att_text(file_.netcdf_id(), var_id_, name.c_str(), value.size(), value.c_str()); nc::check(status, "Can not set attribute'" + name + "'"); } template<> template<typename T, typename U> std::vector<float> NcVariable<float>::get(count_t start, count_t count) const { auto size = hyperslab_size(count); auto result = std::vector<float>(size, 0.0); int status = nc_get_vara_float( file_.netcdf_id(), var_id_, start.data(), count.data(), result.data() ); nc::check(status, "Could not read variable"); return result; } template<> template<typename T, typename U> void NcVariable<float>::add(count_t start, count_t count, std::vector<float> data) { assert(data.size() == hyperslab_size(count)); int status = nc_put_vara_float( file_.netcdf_id(), var_id_, start.data(), count.data(), data.data() ); nc::check(status, "Could not put data in variable"); } template<> template<typename T, typename U> void NcVariable<char>::add(std::string data) { int status = nc_put_var_text(file_.netcdf_id(), var_id_, data.c_str()); nc::check(status, "Could not put text data in variable"); } template<> template<typename T, typename U> void NcVariable<char>::add(std::vector<const char*> data) { size_t i = 0; for (auto string: data) { size_t start[] = {i, 0}; size_t count[] = {1, STRING_MAXLEN}; int status = nc_put_vara_text( file_.netcdf_id(), var_id_, start, count, string ); nc::check(status, "Could not put vector text data in variable"); i++; } } template<typename NcType> std::vector<size_t> NcVariable<NcType>::dimmensions() const { int size = 0; int status = nc_inq_varndims(file_.netcdf_id(), var_id_, &size); nc::check(status, "Could not get the number of dimmensions"); auto dim_ids = std::vector<netcdf_id_t>(static_cast<size_t>(size), 0); status = nc_inq_vardimid(file_.netcdf_id(), var_id_, dim_ids.data()); nc::check(status, "Could not get the dimmensions id"); std::vector<size_t> result; for (auto dim_id: dim_ids) { size_t length = 0; status = nc_inq_dimlen(file_.netcdf_id(), dim_id, &length); check(status, "Could not get the dimmensions size"); result.push_back(length); } return result; } } // namespace nc } // namespace chemfiles #endif #endif // HAVE_NETCDF
/* Chemfiles, an efficient IO library for chemistry file_ formats * Copyright (C) 2015 Guillaume Fraux * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file_, You can obtain one at http://mozilla.org/MPL/2.0/ */ #include "chemfiles/config.hpp" #if HAVE_NETCDF #ifndef CHEMFILES_NCFILE_HPP #define CHEMFILES_NCFILE_HPP #include <vector> #include <string> #include <cassert> #include <netcdf.h> #include "chemfiles/File.hpp" namespace chemfiles { class NcFile; namespace nc { //! Maximum lenght for strings in variables const size_t STRING_MAXLEN = 10; //! NetCDF id type definition using netcdf_id_t = int; //! Count for variable stride and starting point using count_t = std::vector<size_t>; //! Get the number of elements in a NetCDF hyperslab with `count` elements. size_t hyperslab_size(const count_t& count); //! Check for netcdf return `status`. This will throw a `FileError` with the //! given `message` in case of error. void check(int status, const std::string& message); //! Enable a member function at compile-time if T and U are the same types template<class T, class U> using enable_if_same = typename std::enable_if<std::is_same<T, U>::value>::type; /*! * @class NcVariable NcFile.hpp NcFile.cpp * @brief RAII wrapper around NetCDF variable * * This class is manually instanciated for float and char types, which are the * only ones needed by chemfiles. */ template <typename NcType> class NcVariable { public: //! Create a new variable from `file` with id `var`. NcVariable(NcFile& file, netcdf_id_t var); //! Get the attribute `name`. std::string attribute(const std::string& name); //! Add an attribute with the given `value` and `name`. void add_attribute(const std::string& name, const std::string& value); //! Get `count` values starting at `start` from this variable template<typename T = NcType, typename unused = enable_if_same<T, float>> std::vector<float> get(count_t start, count_t count) const; //! Add `cout` values from `data` starting at `start` in this variable template<typename T = NcType, typename unused = enable_if_same<T, float>> void add(count_t start, count_t count, std::vector<float> data); //! Put a single string of data in this variable template<typename T = NcType, typename unused = enable_if_same<T, char>> void add(std::string data); //! Put multiple strings of data in this variable template<typename T = NcType, typename unused = enable_if_same<T, char>> void add(std::vector<std::string> data); //! Get the dimensions size for this variable std::vector<size_t> dimmensions() const; private: NcFile& file_; netcdf_id_t var_id_; }; //! Mapping between C++ and NetCDF data types template<typename NcType> struct nc_type {}; template<> struct nc_type<float> {static constexpr auto value = NC_FLOAT;}; template<> struct nc_type<char> {static constexpr auto value = NC_CHAR;}; } // namespace nc /*! * @class NcFile NcFile.hpp NcFile.cpp * @brief RAII wrapper around NetCDF 3 binary files * * This interface only provide basic functionalities needed by the Amber NetCDF * format. All the operation are guaranteed to return a valid value or throw an * error. * * The template functions are manually specialized for float and char data types. */ class NcFile final: public BinaryFile { public: NcFile(const std::string& filename, File::Mode mode); ~NcFile() noexcept; //! Possible file mode. By default, files are in the DATA mode. enum NcMode { //! Files in DEFINE mode can have there attributes, dimmensions and variables //! modified, but no data can be read or written using NcVariable. DEFINE, //! Files in data mode acces read and write access to NcVariables. DATA, }; //! Set the file mode for this file void set_nc_mode(NcMode mode); //! Get the file mode for this file NcMode nc_mode() const; //! Get the NetCDF id of this file. nc::netcdf_id_t netcdf_id() const { return file_id_; } //! Get a global string attribut from the file std::string global_attribute(const std::string& name) const; //! Create a global attribut in the file_ void add_global_attribute(const std::string& name, const std::string& value); //! Get the value of a specific dimmension size_t dimension(const std::string& name) const; //! Get the value of an optional dimmension, or the default `value` if the //! dimmension is not in the file size_t optional_dimension(const std::string& name, size_t value) const; //! Create a dimmension with the specified value. If `value == NC_UNLIMITED`, //! then the dimension is infinite. void add_dimension(const std::string& name, size_t value = NC_UNLIMITED); //! Check if a variable exists bool variable_exists(const std::string& name) const; //! Get a NetCDF variable template <typename NcType> nc::NcVariable<NcType> variable(const std::string& name) { auto var_id = nc::netcdf_id_t(-1); auto status = nc_inq_varid(file_id_, name.c_str(), &var_id); nc::check(status, "Can not read variable '" + name + "'"); return nc::NcVariable<NcType>(*this, var_id); } //! Create a new variable of type `NcType` with name `name` along the dimensions in //! `dims`. `dims` must be string or string-like values. template <typename NcType, typename ...Dims> nc::NcVariable<NcType> add_variable(const std::string& name, Dims... dims) { assert(nc_mode() == DEFINE && "File must be in define mode to add variable"); auto dim_ids = get_dimmensions(dims...); auto var_id = nc::netcdf_id_t(-1); auto status = nc_def_var( // Variable file and name file_id_, name.c_str(), // Variable type nc::nc_type<NcType>::value, // Variable dimmensions sizeof...(dims), dim_ids.data(), &var_id ); nc::check(status, "Can not add variable '" + name + "'"); return nc::NcVariable<NcType>(*this, var_id); } // A NcFile will always be in a consistent mode bool is_open() override {return true;} private: template <typename ...Dims> std::vector<nc::netcdf_id_t> get_dimmensions(Dims... dims) { std::vector<std::string> dimmensions = {dims...}; std::vector<nc::netcdf_id_t> dim_ids; for (auto& name: dimmensions) { auto dim_id = nc::netcdf_id_t(-1); auto status = nc_inq_dimid(file_id_, name.c_str(), &dim_id); nc::check(status, "Can not get dimmension '" + name + "'"); dim_ids.push_back(dim_id); } return dim_ids; } nc::netcdf_id_t file_id_ = -1; NcMode nc_mode_; }; namespace nc { template <typename NcType> NcVariable<NcType>::NcVariable(NcFile& file, netcdf_id_t var): file_(file), var_id_(var) {} template <typename NcType> std::string NcVariable<NcType>::attribute(const std::string& name) { size_t size = 0; int status = nc_inq_attlen(file_.netcdf_id(), var_id_, name.c_str(), &size); nc::check(status, "Can not read attribute id '" + name + "'"); std::string value(size, ' '); status = nc_get_att_text(file_.netcdf_id(), var_id_, name.c_str(), &value[0]); nc::check(status, "Can not read attribute text '" + name + "'"); return value; } template <typename NcType> void NcVariable<NcType>::add_attribute(const std::string& name, const std::string& value) { assert(file_.nc_mode() == NcFile::DEFINE && "File must be in define mode to add attribute"); int status = nc_put_att_text(file_.netcdf_id(), var_id_, name.c_str(), value.size(), value.c_str()); nc::check(status, "Can not set attribute'" + name + "'"); } template<> template<typename T, typename U> std::vector<float> NcVariable<float>::get(count_t start, count_t count) const { auto size = hyperslab_size(count); auto result = std::vector<float>(size, 0.0); int status = nc_get_vara_float( file_.netcdf_id(), var_id_, start.data(), count.data(), result.data() ); nc::check(status, "Could not read variable"); return result; } template<> template<typename T, typename U> void NcVariable<float>::add(count_t start, count_t count, std::vector<float> data) { assert(data.size() == hyperslab_size(count)); int status = nc_put_vara_float( file_.netcdf_id(), var_id_, start.data(), count.data(), data.data() ); nc::check(status, "Could not put data in variable"); } template<> template<typename T, typename U> void NcVariable<char>::add(std::string data) { int status = nc_put_var_text(file_.netcdf_id(), var_id_, data.c_str()); nc::check(status, "Could not put text data in variable"); } template<> template<typename T, typename U> void NcVariable<char>::add(std::vector<std::string> data) { size_t i = 0; for (auto string: data) { string.resize(STRING_MAXLEN, '\0'); size_t start[] = {i, 0}; size_t count[] = {1, STRING_MAXLEN}; int status = nc_put_vara_text( file_.netcdf_id(), var_id_, start, count, string.c_str() ); nc::check(status, "Could not put vector text data in variable"); i++; } } template<typename NcType> std::vector<size_t> NcVariable<NcType>::dimmensions() const { int size = 0; int status = nc_inq_varndims(file_.netcdf_id(), var_id_, &size); nc::check(status, "Could not get the number of dimmensions"); auto dim_ids = std::vector<netcdf_id_t>(static_cast<size_t>(size), 0); status = nc_inq_vardimid(file_.netcdf_id(), var_id_, dim_ids.data()); nc::check(status, "Could not get the dimmensions id"); std::vector<size_t> result; for (auto dim_id: dim_ids) { size_t length = 0; status = nc_inq_dimlen(file_.netcdf_id(), dim_id, &length); check(status, "Could not get the dimmensions size"); result.push_back(length); } return result; } } // namespace nc } // namespace chemfiles #endif #endif // HAVE_NETCDF
Fix a buffer overflow reading static memory
Fix a buffer overflow reading static memory
C++
bsd-3-clause
chemfiles/chemfiles,lscalfi/chemfiles,Luthaf/Chemharp,chemfiles/chemfiles,chemfiles/chemfiles,lscalfi/chemfiles,Luthaf/Chemharp,chemfiles/chemfiles,lscalfi/chemfiles,lscalfi/chemfiles,Luthaf/Chemharp
6ed37ba1b5e4dff62548f41abd7c6fa5f6dd6905
test/fuzzers/audio_processing_configs_fuzzer.cc
test/fuzzers/audio_processing_configs_fuzzer.cc
/* * Copyright (c) 2017 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 <bitset> #include <string> #include "absl/memory/memory.h" #include "api/audio/echo_canceller3_factory.h" #include "modules/audio_processing/aec_dump/mock_aec_dump.h" #include "modules/audio_processing/include/audio_processing.h" #include "rtc_base/arraysize.h" #include "rtc_base/numerics/safe_minmax.h" #include "system_wrappers/include/field_trial.h" #include "test/fuzzers/audio_processing_fuzzer_helper.h" #include "test/fuzzers/fuzz_data_helper.h" namespace webrtc { namespace { const std::string kFieldTrialNames[] = { "WebRTC-Aec3AdaptErleOnLowRenderKillSwitch", "WebRTC-Aec3AgcGainChangeResponseKillSwitch", "WebRTC-Aec3BoundedNearendKillSwitch", "WebRTC-Aec3EarlyShadowFilterJumpstartKillSwitch", "WebRTC-Aec3EnableAdaptiveEchoReverbEstimation", "WebRTC-Aec3EnableLegacyDominantNearend", "WebRTC-Aec3EnableUnityInitialRampupGain", "WebRTC-Aec3EnableUnityNonZeroRampupGain", "WebRTC-Aec3EnforceSkewHysteresis1", "WebRTC-Aec3EnforceSkewHysteresis2", "WebRTC-Aec3FilterAnalyzerPreprocessorKillSwitch", "WebRTC-Aec3MisadjustmentEstimatorKillSwitch", "WebRTC-Aec3NewFilterParamsKillSwitch", "WebRTC-Aec3OverrideEchoPathGainKillSwitch", "WebRTC-Aec3RapidAgcGainRecoveryKillSwitch", "WebRTC-Aec3ResetErleAtGainChangesKillSwitch", "WebRTC-Aec3ReverbBasedOnRenderKillSwitch", "WebRTC-Aec3ReverbModellingKillSwitch", "WebRTC-Aec3ShadowFilterBoostedJumpstartKillSwitch", "WebRTC-Aec3ShadowFilterJumpstartKillSwitch", "WebRTC-Aec3ShortReverbKillSwitch", "WebRTC-Aec3SmoothSignalTransitionsKillSwitch", "WebRTC-Aec3SmoothUpdatesTailFreqRespKillSwitch", "WebRTC-Aec3SoftTransparentModeKillSwitch", "WebRTC-Aec3StandardNonlinearReverbModelKillSwitch", "WebRTC-Aec3StrictDivergenceCheckKillSwitch", "WebRTC-Aec3UseLegacyNormalSuppressorTuning", "WebRTC-Aec3UseOffsetBlocks", "WebRTC-Aec3UseShortDelayEstimatorWindow", "WebRTC-Aec3UseStationarityPropertiesKillSwitch", "WebRTC-Aec3UtilizeShadowFilterOutputKillSwitch", "WebRTC-Aec3ZeroExternalDelayHeadroomKillSwitch", }; std::unique_ptr<AudioProcessing> CreateApm(test::FuzzDataHelper* fuzz_data, std::string* field_trial_string) { // Parse boolean values for optionally enabling different // configurable public components of APM. bool exp_agc = fuzz_data->ReadOrDefaultValue(true); bool exp_ns = fuzz_data->ReadOrDefaultValue(true); static_cast<void>(fuzz_data->ReadOrDefaultValue(true)); bool ef = fuzz_data->ReadOrDefaultValue(true); bool raf = fuzz_data->ReadOrDefaultValue(true); static_cast<void>(fuzz_data->ReadOrDefaultValue(true)); static_cast<void>(fuzz_data->ReadOrDefaultValue(true)); bool red = fuzz_data->ReadOrDefaultValue(true); bool hpf = fuzz_data->ReadOrDefaultValue(true); bool aec3 = fuzz_data->ReadOrDefaultValue(true); bool use_aec = fuzz_data->ReadOrDefaultValue(true); bool use_aecm = fuzz_data->ReadOrDefaultValue(true); bool use_agc = fuzz_data->ReadOrDefaultValue(true); bool use_ns = fuzz_data->ReadOrDefaultValue(true); bool use_le = fuzz_data->ReadOrDefaultValue(true); bool use_vad = fuzz_data->ReadOrDefaultValue(true); bool use_agc_limiter = fuzz_data->ReadOrDefaultValue(true); bool use_agc2_limiter = fuzz_data->ReadOrDefaultValue(true); // Read an int8 value, but don't let it be too large or small. const float gain_controller2_gain_db = rtc::SafeClamp<int>(fuzz_data->ReadOrDefaultValue<int8_t>(0), -50, 50); constexpr size_t kNumFieldTrials = arraysize(kFieldTrialNames); // Verify that the read data type has enough bits to fuzz the field trials. using FieldTrialBitmaskType = uint32_t; RTC_DCHECK_LE(kNumFieldTrials, sizeof(FieldTrialBitmaskType) * 8); std::bitset<kNumFieldTrials> field_trial_bitmask( fuzz_data->ReadOrDefaultValue<FieldTrialBitmaskType>(0)); for (size_t i = 0; i < kNumFieldTrials; ++i) { if (field_trial_bitmask[i]) { *field_trial_string += kFieldTrialNames[i] + "/Enabled/"; } } field_trial::InitFieldTrialsFromString(field_trial_string->c_str()); // Ignore a few bytes. Bytes from this segment will be used for // future config flag changes. We assume 40 bytes is enough for // configuring the APM. constexpr size_t kSizeOfConfigSegment = 40; RTC_DCHECK(kSizeOfConfigSegment >= fuzz_data->BytesRead()); static_cast<void>( fuzz_data->ReadByteArray(kSizeOfConfigSegment - fuzz_data->BytesRead())); // Filter out incompatible settings that lead to CHECK failures. if ((use_aecm && use_aec) || // These settings cause CHECK failure. (use_aecm && aec3 && use_ns) // These settings trigger webrtc:9489. ) { return nullptr; } // Components can be enabled through webrtc::Config and // webrtc::AudioProcessingConfig. Config config; std::unique_ptr<EchoControlFactory> echo_control_factory; if (aec3) { echo_control_factory.reset(new EchoCanceller3Factory()); } config.Set<ExperimentalAgc>(new ExperimentalAgc(exp_agc)); config.Set<ExperimentalNs>(new ExperimentalNs(exp_ns)); config.Set<ExtendedFilter>(new ExtendedFilter(ef)); config.Set<RefinedAdaptiveFilter>(new RefinedAdaptiveFilter(raf)); config.Set<DelayAgnostic>(new DelayAgnostic(true)); std::unique_ptr<AudioProcessing> apm( AudioProcessingBuilder() .SetEchoControlFactory(std::move(echo_control_factory)) .Create(config)); apm->AttachAecDump( absl::make_unique<testing::NiceMock<webrtc::test::MockAecDump>>()); webrtc::AudioProcessing::Config apm_config; apm_config.echo_canceller.enabled = use_aec || use_aecm; apm_config.echo_canceller.mobile_mode = use_aecm; apm_config.residual_echo_detector.enabled = red; apm_config.high_pass_filter.enabled = hpf; apm_config.gain_controller2.enabled = use_agc2_limiter; apm_config.gain_controller2.fixed_gain_db = gain_controller2_gain_db; apm->ApplyConfig(apm_config); apm->gain_control()->Enable(use_agc); apm->noise_suppression()->Enable(use_ns); apm->level_estimator()->Enable(use_le); apm->voice_detection()->Enable(use_vad); apm->gain_control()->enable_limiter(use_agc_limiter); return apm; } } // namespace void FuzzOneInput(const uint8_t* data, size_t size) { test::FuzzDataHelper fuzz_data(rtc::ArrayView<const uint8_t>(data, size)); // This string must be in scope during execution, according to documentation // for field_trial.h. Hence it's created here and not in CreateApm. std::string field_trial_string = ""; auto apm = CreateApm(&fuzz_data, &field_trial_string); if (apm) { FuzzAudioProcessing(&fuzz_data, std::move(apm)); } } } // namespace webrtc
/* * Copyright (c) 2017 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 <bitset> #include <string> #include "absl/memory/memory.h" #include "api/audio/echo_canceller3_factory.h" #include "modules/audio_processing/aec_dump/mock_aec_dump.h" #include "modules/audio_processing/include/audio_processing.h" #include "rtc_base/arraysize.h" #include "rtc_base/numerics/safe_minmax.h" #include "system_wrappers/include/field_trial.h" #include "test/fuzzers/audio_processing_fuzzer_helper.h" #include "test/fuzzers/fuzz_data_helper.h" namespace webrtc { namespace { const std::string kFieldTrialNames[] = { "WebRTC-Aec3AdaptErleOnLowRenderKillSwitch", "WebRTC-Aec3AgcGainChangeResponseKillSwitch", "WebRTC-Aec3BoundedNearendKillSwitch", "WebRTC-Aec3EarlyShadowFilterJumpstartKillSwitch", "WebRTC-Aec3EnableAdaptiveEchoReverbEstimation", "WebRTC-Aec3EnableLegacyDominantNearend", "WebRTC-Aec3EnableUnityInitialRampupGain", "WebRTC-Aec3EnableUnityNonZeroRampupGain", "WebRTC-Aec3EnforceSkewHysteresis1", "WebRTC-Aec3EnforceSkewHysteresis2", "WebRTC-Aec3FilterAnalyzerPreprocessorKillSwitch", "WebRTC-Aec3MisadjustmentEstimatorKillSwitch", "WebRTC-Aec3NewFilterParamsKillSwitch", "WebRTC-Aec3NewRenderBufferingKillSwitch", "WebRTC-Aec3OverrideEchoPathGainKillSwitch", "WebRTC-Aec3RapidAgcGainRecoveryKillSwitch", "WebRTC-Aec3ResetErleAtGainChangesKillSwitch", "WebRTC-Aec3ReverbBasedOnRenderKillSwitch", "WebRTC-Aec3ReverbModellingKillSwitch", "WebRTC-Aec3ShadowFilterBoostedJumpstartKillSwitch", "WebRTC-Aec3ShadowFilterJumpstartKillSwitch", "WebRTC-Aec3ShortReverbKillSwitch", "WebRTC-Aec3SmoothSignalTransitionsKillSwitch", "WebRTC-Aec3SmoothUpdatesTailFreqRespKillSwitch", "WebRTC-Aec3SoftTransparentModeKillSwitch", "WebRTC-Aec3StandardNonlinearReverbModelKillSwitch", "WebRTC-Aec3StrictDivergenceCheckKillSwitch", "WebRTC-Aec3UseLegacyNormalSuppressorTuning", "WebRTC-Aec3UseOffsetBlocks", "WebRTC-Aec3UseShortDelayEstimatorWindow", "WebRTC-Aec3UseStationarityPropertiesKillSwitch", "WebRTC-Aec3UtilizeShadowFilterOutputKillSwitch", "WebRTC-Aec3ZeroExternalDelayHeadroomKillSwitch", }; std::unique_ptr<AudioProcessing> CreateApm(test::FuzzDataHelper* fuzz_data, std::string* field_trial_string) { // Parse boolean values for optionally enabling different // configurable public components of APM. bool exp_agc = fuzz_data->ReadOrDefaultValue(true); bool exp_ns = fuzz_data->ReadOrDefaultValue(true); static_cast<void>(fuzz_data->ReadOrDefaultValue(true)); bool ef = fuzz_data->ReadOrDefaultValue(true); bool raf = fuzz_data->ReadOrDefaultValue(true); static_cast<void>(fuzz_data->ReadOrDefaultValue(true)); static_cast<void>(fuzz_data->ReadOrDefaultValue(true)); bool red = fuzz_data->ReadOrDefaultValue(true); bool hpf = fuzz_data->ReadOrDefaultValue(true); bool aec3 = fuzz_data->ReadOrDefaultValue(true); bool use_aec = fuzz_data->ReadOrDefaultValue(true); bool use_aecm = fuzz_data->ReadOrDefaultValue(true); bool use_agc = fuzz_data->ReadOrDefaultValue(true); bool use_ns = fuzz_data->ReadOrDefaultValue(true); bool use_le = fuzz_data->ReadOrDefaultValue(true); bool use_vad = fuzz_data->ReadOrDefaultValue(true); bool use_agc_limiter = fuzz_data->ReadOrDefaultValue(true); bool use_agc2_limiter = fuzz_data->ReadOrDefaultValue(true); // Read an int8 value, but don't let it be too large or small. const float gain_controller2_gain_db = rtc::SafeClamp<int>(fuzz_data->ReadOrDefaultValue<int8_t>(0), -50, 50); constexpr size_t kNumFieldTrials = arraysize(kFieldTrialNames); // Verify that the read data type has enough bits to fuzz the field trials. using FieldTrialBitmaskType = uint32_t; RTC_DCHECK_LE(kNumFieldTrials, sizeof(FieldTrialBitmaskType) * 8); std::bitset<kNumFieldTrials> field_trial_bitmask( fuzz_data->ReadOrDefaultValue<FieldTrialBitmaskType>(0)); for (size_t i = 0; i < kNumFieldTrials; ++i) { if (field_trial_bitmask[i]) { *field_trial_string += kFieldTrialNames[i] + "/Enabled/"; } } field_trial::InitFieldTrialsFromString(field_trial_string->c_str()); // Ignore a few bytes. Bytes from this segment will be used for // future config flag changes. We assume 40 bytes is enough for // configuring the APM. constexpr size_t kSizeOfConfigSegment = 40; RTC_DCHECK(kSizeOfConfigSegment >= fuzz_data->BytesRead()); static_cast<void>( fuzz_data->ReadByteArray(kSizeOfConfigSegment - fuzz_data->BytesRead())); // Filter out incompatible settings that lead to CHECK failures. if ((use_aecm && use_aec) || // These settings cause CHECK failure. (use_aecm && aec3 && use_ns) // These settings trigger webrtc:9489. ) { return nullptr; } // Components can be enabled through webrtc::Config and // webrtc::AudioProcessingConfig. Config config; std::unique_ptr<EchoControlFactory> echo_control_factory; if (aec3) { echo_control_factory.reset(new EchoCanceller3Factory()); } config.Set<ExperimentalAgc>(new ExperimentalAgc(exp_agc)); config.Set<ExperimentalNs>(new ExperimentalNs(exp_ns)); config.Set<ExtendedFilter>(new ExtendedFilter(ef)); config.Set<RefinedAdaptiveFilter>(new RefinedAdaptiveFilter(raf)); config.Set<DelayAgnostic>(new DelayAgnostic(true)); std::unique_ptr<AudioProcessing> apm( AudioProcessingBuilder() .SetEchoControlFactory(std::move(echo_control_factory)) .Create(config)); apm->AttachAecDump( absl::make_unique<testing::NiceMock<webrtc::test::MockAecDump>>()); webrtc::AudioProcessing::Config apm_config; apm_config.echo_canceller.enabled = use_aec || use_aecm; apm_config.echo_canceller.mobile_mode = use_aecm; apm_config.residual_echo_detector.enabled = red; apm_config.high_pass_filter.enabled = hpf; apm_config.gain_controller2.enabled = use_agc2_limiter; apm_config.gain_controller2.fixed_gain_db = gain_controller2_gain_db; apm->ApplyConfig(apm_config); apm->gain_control()->Enable(use_agc); apm->noise_suppression()->Enable(use_ns); apm->level_estimator()->Enable(use_le); apm->voice_detection()->Enable(use_vad); apm->gain_control()->enable_limiter(use_agc_limiter); return apm; } } // namespace void FuzzOneInput(const uint8_t* data, size_t size) { test::FuzzDataHelper fuzz_data(rtc::ArrayView<const uint8_t>(data, size)); // This string must be in scope during execution, according to documentation // for field_trial.h. Hence it's created here and not in CreateApm. std::string field_trial_string = ""; auto apm = CreateApm(&fuzz_data, &field_trial_string); if (apm) { FuzzAudioProcessing(&fuzz_data, std::move(apm)); } } } // namespace webrtc
Enable fuzzer testing of old render buffering code.
AEC3: Enable fuzzer testing of old render buffering code. The old render buffering code has been replaced, but can still be activated by a killswitch. This change enables fuzzer testing of the old code path. Bug: webrtc:9726 Change-Id: I6e91cd4b4a95388cc63d1a65dade21b3c44be71b Reviewed-on: https://webrtc-review.googlesource.com/c/107562 Reviewed-by: Henrik Lundin <[email protected]> Commit-Queue: Gustaf Ullberg <[email protected]> Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#25303}
C++
bsd-3-clause
TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc
d48ed1df2890524e4218329750ab1beecde7c5ed
mcrouter/test/cpp_unit_tests/MemcacheLocal.cpp
mcrouter/test/cpp_unit_tests/MemcacheLocal.cpp
#include "MemcacheLocal.h" #include <vector> #include "folly/FileUtil.h" #include "folly/Memory.h" #include "mcrouter/config.h" using namespace folly; using namespace std; namespace facebook { namespace memcache { namespace test { // constants const std::string MemcacheLocal::kHostName = "localhost"; const int MemcacheLocal::kPortSearchOut = 20; const int MemcacheLocal::kPortRangeBegin = 40000; const int MemcacheLocal::kPortRangeEnd = 50000; const int MemcacheLocal::kTimeout = 10; const std::string MemcacheLocal::kMemcachedPath = MCROUTER_INSTALL_PATH "mcrouter/lib/network/mock_mc_server"; const std::string MemcacheLocal::kMemcachedBin = "mock_mc_server"; const std::string kConfig = "mcrouter/test/cpp_unit_tests/files/memcache_local_config.json"; MemcacheLocal::MemcacheLocal(const int port) : random_(time(nullptr)) { //initialize random process_ = nullptr; if (port == 0) { // find an open port and start memcache for our test. // blocks until server ready port_ = startMemcachedServer(kPortRangeBegin, kPortRangeEnd); } else { port_ = port; if (!startMemcachedOnPort(kMemcachedPath, kMemcachedBin, port_)) { throw std::runtime_error("Failed to start memcached on port " + to_string(port_)); } } } MemcacheLocal::~MemcacheLocal() { // stop the server. blocks until server exited stopMemcachedServer(port_); } int MemcacheLocal::startMemcachedOnPort(const string& path, const string& bin, const int port) { //memcache prints some lines. redirect output to file / silence output. int fd1; //open the output file fd1 = open("/dev/null", O_CREAT | O_RDWR); /** * options: redirect stdout and stderr of the subprocess to fd1 (/dev/null) * also send the subprocess a SIGTERM (terminate) signal when parent dies */ Subprocess::Options options; options.stdout(fd1).stderr(fd1).parentDeathSignal(SIGTERM); process_ = folly::make_unique<Subprocess>( vector<string> { bin, "-P", to_string(port) }, options, path.c_str(), nullptr); int i, socket_descriptor; // premature exit? sleep(1); ProcessReturnCode prc = process_->poll(); if (prc.exited() || prc.killed()) { return 0; } // busy wait and test if we can connect to the server for (i = 0; i < kTimeout; i++) { // try kTimeOut times to connect socket_descriptor = connectTcpServer(kHostName, port); if (socket_descriptor != -1) { break; } sleep(1); } if (i == kTimeout) { // could not start memcached server process_->kill(); // kill suprocess process_->wait(); // reap subprocess return 0; } // otherwise, socket_descriptor is a valid, connected socket // close the socket close(socket_descriptor); return 1; // could start memcached server, and connect to it } void MemcacheLocal::stopMemcachedServer(const int port) const { int socket_descriptor; socket_descriptor = connectTcpServer(kHostName, port); if (socket_descriptor != -1) { // Mr. Memcached server, please shutdown sendMessage(socket_descriptor, "shutdown\r\n"); close(socket_descriptor); // close the socket process_->wait(); // yes, he is finished } else { // how come we can't connect to server? throw std::runtime_error("No transport to memcached server"); } } // assumes an established socket int MemcacheLocal::sendMessage(const int sockfd, const string& message) const { int nchar; const char *msg = message.c_str(); nchar = send(sockfd, msg, strlen(msg), 0); if (nchar == -1) { throw std::runtime_error("Can not send command through socket"); } return nchar; } void * MemcacheLocal::getSocketAddress(struct sockaddr *sa) const { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*) sa)->sin_addr); } return &(((struct sockaddr_in6*) sa)->sin6_addr); } int MemcacheLocal::connectTcpServer(const string& hostname, const int port) const { int sockfd; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; string port_string = to_string(port); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(hostname.c_str(), port_string.c_str(), &hints, &servinfo)) != 0) { // we can not get address info. network problem throw std::runtime_error("getaddrinfo fails"); } // loop through all the results and connect to the first we can for (p = servinfo; p != nullptr; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); continue; } break; } if (p == nullptr) { return -1; // failed to connect } inet_ntop(p->ai_family, getSocketAddress((struct sockaddr *)p->ai_addr), s, sizeof s); // connecting freeaddrinfo(servinfo); // all done with this structure return sockfd; } int MemcacheLocal::generateRandomPort(const int start_port, const int stop_port) { int half_range = (stop_port - start_port) >> 1; // half the range std::uniform_int_distribution<int> dist(0, half_range - 1); int half_port = dist(random_); // generate URN [0, half_range) return (half_port << 1) + start_port; // ensures the generated port is even } int MemcacheLocal::startMemcachedServer(const int start_port, const int stop_port) { /* find an open port */ int port; int i; if (start_port > stop_port) throw std::runtime_error("Port limit misconfiguration. Begin > End !"); for (i = 0; i < kPortSearchOut; i++) { port = generateRandomPort(start_port, stop_port); // if memcached started successfully, return. Otherwise, keep begging. if (startMemcachedOnPort(kMemcachedPath, kMemcachedBin, port)) { break; } } if (i == kPortSearchOut) { // so many futile search for an open port!! // something must be wrong throw std::runtime_error("Can not find an open port to bind memcached"); } return port; } std::string MemcacheLocal::generateMcrouterConfigString() { std::string config; if (!folly::readFile(kConfig.data(), config)) { throw std::runtime_error("Can not read " + kConfig); } config.replace(config.find("PORT"), 4, std::to_string(port_)); return config; } } } } // !namespace facebook::memcache::test
#include "MemcacheLocal.h" #include <vector> #include "folly/FileUtil.h" #include "folly/Memory.h" #include "mcrouter/config.h" using namespace folly; using namespace std; namespace facebook { namespace memcache { namespace test { // constants const std::string MemcacheLocal::kHostName = "localhost"; const int MemcacheLocal::kPortSearchOut = 20; const int MemcacheLocal::kPortRangeBegin = 40000; const int MemcacheLocal::kPortRangeEnd = 50000; const int MemcacheLocal::kTimeout = 10; const std::string MemcacheLocal::kMemcachedPath = MCROUTER_INSTALL_PATH "mcrouter/lib/network/mock_mc_server"; const std::string MemcacheLocal::kMemcachedBin = "mock_mc_server"; const std::string kConfig = "mcrouter/test/cpp_unit_tests/files/memcache_local_config.json"; MemcacheLocal::MemcacheLocal(const int port) : random_(time(nullptr)) { //initialize random process_ = nullptr; if (port == 0) { // find an open port and start memcache for our test. // blocks until server ready port_ = startMemcachedServer(kPortRangeBegin, kPortRangeEnd); } else { port_ = port; if (!startMemcachedOnPort(kMemcachedPath, kMemcachedBin, port_)) { throw std::runtime_error("Failed to start memcached on port " + to_string(port_)); } } } MemcacheLocal::~MemcacheLocal() { // stop the server. blocks until server exited stopMemcachedServer(port_); } int MemcacheLocal::startMemcachedOnPort(const string& path, const string& bin, const int port) { //memcache prints some lines. redirect output to file / silence output. int fd1; //open the output file fd1 = open("/dev/null", O_RDWR); /** * options: redirect stdout and stderr of the subprocess to fd1 (/dev/null) * also send the subprocess a SIGTERM (terminate) signal when parent dies */ Subprocess::Options options; options.stdout(fd1).stderr(fd1).parentDeathSignal(SIGTERM); process_ = folly::make_unique<Subprocess>( vector<string> { bin, "-P", to_string(port) }, options, path.c_str(), nullptr); int i, socket_descriptor; // premature exit? sleep(1); ProcessReturnCode prc = process_->poll(); if (prc.exited() || prc.killed()) { return 0; } // busy wait and test if we can connect to the server for (i = 0; i < kTimeout; i++) { // try kTimeOut times to connect socket_descriptor = connectTcpServer(kHostName, port); if (socket_descriptor != -1) { break; } sleep(1); } if (i == kTimeout) { // could not start memcached server process_->kill(); // kill suprocess process_->wait(); // reap subprocess return 0; } // otherwise, socket_descriptor is a valid, connected socket // close the socket close(socket_descriptor); return 1; // could start memcached server, and connect to it } void MemcacheLocal::stopMemcachedServer(const int port) const { int socket_descriptor; socket_descriptor = connectTcpServer(kHostName, port); if (socket_descriptor != -1) { // Mr. Memcached server, please shutdown sendMessage(socket_descriptor, "shutdown\r\n"); close(socket_descriptor); // close the socket process_->wait(); // yes, he is finished } else { // how come we can't connect to server? throw std::runtime_error("No transport to memcached server"); } } // assumes an established socket int MemcacheLocal::sendMessage(const int sockfd, const string& message) const { int nchar; const char *msg = message.c_str(); nchar = send(sockfd, msg, strlen(msg), 0); if (nchar == -1) { throw std::runtime_error("Can not send command through socket"); } return nchar; } void * MemcacheLocal::getSocketAddress(struct sockaddr *sa) const { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*) sa)->sin_addr); } return &(((struct sockaddr_in6*) sa)->sin6_addr); } int MemcacheLocal::connectTcpServer(const string& hostname, const int port) const { int sockfd; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; string port_string = to_string(port); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(hostname.c_str(), port_string.c_str(), &hints, &servinfo)) != 0) { // we can not get address info. network problem throw std::runtime_error("getaddrinfo fails"); } // loop through all the results and connect to the first we can for (p = servinfo; p != nullptr; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); continue; } break; } if (p == nullptr) { return -1; // failed to connect } inet_ntop(p->ai_family, getSocketAddress((struct sockaddr *)p->ai_addr), s, sizeof s); // connecting freeaddrinfo(servinfo); // all done with this structure return sockfd; } int MemcacheLocal::generateRandomPort(const int start_port, const int stop_port) { int half_range = (stop_port - start_port) >> 1; // half the range std::uniform_int_distribution<int> dist(0, half_range - 1); int half_port = dist(random_); // generate URN [0, half_range) return (half_port << 1) + start_port; // ensures the generated port is even } int MemcacheLocal::startMemcachedServer(const int start_port, const int stop_port) { /* find an open port */ int port; int i; if (start_port > stop_port) throw std::runtime_error("Port limit misconfiguration. Begin > End !"); for (i = 0; i < kPortSearchOut; i++) { port = generateRandomPort(start_port, stop_port); // if memcached started successfully, return. Otherwise, keep begging. if (startMemcachedOnPort(kMemcachedPath, kMemcachedBin, port)) { break; } } if (i == kPortSearchOut) { // so many futile search for an open port!! // something must be wrong throw std::runtime_error("Can not find an open port to bind memcached"); } return port; } std::string MemcacheLocal::generateMcrouterConfigString() { std::string config; if (!folly::readFile(kConfig.data(), config)) { throw std::runtime_error("Can not read " + kConfig); } config.replace(config.find("PORT"), 4, std::to_string(port_)); return config; } } } } // !namespace facebook::memcache::test
Fix open source build
Fix open source build Summary: O_CREAT needs third argument, mode Test Plan: build mcrouter Reviewed By: [email protected] FB internal diff: D1407061
C++
bsd-3-clause
leitao/mcrouter,yqzhang/mcrouter,apinski-cavium/mcrouter,nvaller/mcrouter,tempbottle/mcrouter,is00hcw/mcrouter,facebook/mcrouter,reddit/mcrouter,reddit/mcrouter,leitao/mcrouter,yqzhang/mcrouter,reddit/mcrouter,apinski-cavium/mcrouter,seem-sky/mcrouter,easyfmxu/mcrouter,facebook/mcrouter,tempbottle/mcrouter,evertrue/mcrouter,synecdoche/mcrouter,zhlong73/mcrouter,easyfmxu/mcrouter,seem-sky/mcrouter,apinski-cavium/mcrouter,synecdoche/mcrouter,is00hcw/mcrouter,glensc/mcrouter,seem-sky/mcrouter,zhlong73/mcrouter,reddit/mcrouter,is00hcw/mcrouter,seem-sky/mcrouter,glensc/mcrouter,zhlong73/mcrouter,nvaller/mcrouter,synecdoche/mcrouter,evertrue/mcrouter,nvaller/mcrouter,facebook/mcrouter,yqzhang/mcrouter,evertrue/mcrouter,yqzhang/mcrouter,easyfmxu/mcrouter,facebook/mcrouter,zhlong73/mcrouter,nvaller/mcrouter,apinski-cavium/mcrouter,leitao/mcrouter,glensc/mcrouter,leitao/mcrouter,is00hcw/mcrouter,tempbottle/mcrouter,glensc/mcrouter,tempbottle/mcrouter,easyfmxu/mcrouter,evertrue/mcrouter,synecdoche/mcrouter
6c937e2082afc000a2d39384baaf189219b39a59
include/tudocomp/io/BitIStream.hpp
include/tudocomp/io/BitIStream.hpp
#ifndef _INCLUDED_BIT_ISTREAM_HPP #define _INCLUDED_BIT_ISTREAM_HPP #include <climits> #include <cstdint> #include <iostream> namespace tudocomp { namespace io { /// Wrapper over an istream that can be used to read single bits. /// /// Read bytes are buffered on the inside until all bits of them had been read. class BitIStream { std::istream& inp; uint8_t next = 0; int c; bool* done; inline void readNext() { const int MSB = 7; char tmp; // TODO: Error reporting *done |= !inp.get(tmp); next = tmp; c = MSB; } public: /// Create a new BitIstream. /// /// \param inp_ The istream to read bits from. inline BitIStream(std::istream& inp_, bool& done_): inp(inp_), done(&done_) { c = -1; } /// Read a single bit, and return it as a byte of either the value 0 or 1. inline uint8_t readBit() { if (c < 0) { readNext(); } uint8_t bit = (next >> c) & 0b1; c--; return bit; } /// Read a number of bits, and accumulate them in the return value /// with the last bit read at least significant position of the integer. template<class T> T readBits(size_t amount = sizeof(T) * CHAR_BIT) { T value = 0; for(size_t i = 0; i < amount; i++) { value <<= 1; value |= readBit(); } return value; } /// Read a compressed integer from the input. /// /// \param b The block width in bits (default is 7 bits). template<typename T> inline T read_compressed_int(size_t b = 7) { assert(b > 0); uint64_t value = 0; size_t i = 0; bool has_next; do { has_next = readBit(); value |= (readBits<size_t>(b) << (b * (i++))); } while(has_next); return T(value); } }; }} #endif
#ifndef _INCLUDED_BIT_ISTREAM_HPP #define _INCLUDED_BIT_ISTREAM_HPP #include <climits> #include <cstdint> #include <iostream> namespace tudocomp { namespace io { /// Wrapper over an istream that can be used to read single bits. /// /// Read bytes are buffered on the inside until all bits of them had been read. class BitIStream { std::istream& inp; uint8_t next = 0; int c; bool* done; inline void readNext() { const int MSB = 7; char tmp; // TODO: Error reporting *done |= !inp.get(tmp); next = tmp; c = MSB; } public: /// Create a new BitIstream. /// /// \param inp_ The istream to read bits from. inline BitIStream(std::istream& inp_, bool& done_): inp(inp_), done(&done_) { c = -1; } /// Read a single bit, and return it as a byte of either the value 0 or 1. inline uint8_t readBit() { if (c < 0) { readNext(); } uint8_t bit = (next >> c) & 0b1; c--; return bit; } /// Read a number of bits, and accumulate them in the return value /// with the last bit read at least significant position of the integer. template<class T> T readBits(size_t amount = sizeof(T) * CHAR_BIT) { T value = 0; for(size_t i = 0; i < amount; i++) { value <<= 1; value |= readBit(); } return value; } /// Read a compressed integer from the input. /// /// \param b The block width in bits (default is 7 bits). template<typename T = size_t> inline T read_compressed_int(size_t b = 7) { assert(b > 0); uint64_t value = 0; size_t i = 0; bool has_next; do { has_next = readBit(); value |= (readBits<size_t>(b) << (b * (i++))); } while(has_next); return T(value); } }; }} #endif
Use size_t as default type for read_compressed_int<T>
Use size_t as default type for read_compressed_int<T>
C++
apache-2.0
tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp
446e4acfb6b801b29f437595ca564a66cb63f4e9
src/shared-application.cpp
src/shared-application.cpp
#include "shared-application.h" #include <QtGlobal> #ifdef Q_OS_WIN32 #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #ifndef __MSVCRT__ #define __MSVCRT__ #endif #include <process.h> #else #include <pthread.h> #endif #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) #include <event2/event.h> #include <event2/event_compat.h> #include <event2/event_struct.h> #else #include <event.h> #endif extern "C" { #include <searpc-client.h> #include <ccnet.h> #include <searpc.h> #include <seafile/seafile.h> #include <seafile/seafile-object.h> } #include "utils/utils.h" namespace { const char *kAppletCommandsMQ = "applet.commands"; const int kWaitResponseSeconds = 6; bool isActivate = false; struct UserData { struct event_base *ev_base; _CcnetClient *ccnet_client; }; void readCallback(int sock, short what, void* data) { UserData *user_data = static_cast<UserData*>(data); if (ccnet_client_read_input(user_data->ccnet_client) <= 0) { // fatal error event_base_loopbreak(user_data->ev_base); } } void messageCallback(CcnetMessage *message, void *data) { isActivate = g_strcmp0(message->body, "ack_activate") == 0; if (isActivate) { // time to leave struct event_base *ev_base = static_cast<struct event_base*>(data); event_base_loopbreak(ev_base); } } #ifndef Q_OS_WIN32 void *askActivateSynchronically(void * /*arg*/) { #else unsigned __stdcall askActivateSynchronically(void * /*arg*/) { #endif _CcnetClient* async_client = ccnet_client_new(); _CcnetClient *sync_client = ccnet_client_new(); const QString ccnet_dir = defaultCcnetDir(); if (ccnet_client_load_confdir(async_client, toCStr(ccnet_dir)) < 0) { g_object_unref(sync_client); g_object_unref(async_client); return 0; } if (ccnet_client_connect_daemon(async_client, CCNET_CLIENT_ASYNC) < 0) { g_object_unref(sync_client); g_object_unref(async_client); return 0; } if (ccnet_client_load_confdir(sync_client, toCStr(ccnet_dir)) < 0) { g_object_unref(sync_client); g_object_unref(async_client); return 0; } if (ccnet_client_connect_daemon(sync_client, CCNET_CLIENT_SYNC) < 0) { g_object_unref(sync_client); g_object_unref(async_client); return 0; } // // send message synchronously // CcnetMessage *syn_message; syn_message = ccnet_message_new(sync_client->base.id, sync_client->base.id, kAppletCommandsMQ, "syn_activate", 0); // blocking io, but cancellable from pthread_cancel if (ccnet_client_send_message(sync_client, syn_message) < 0) { ccnet_message_free(syn_message); g_object_unref(sync_client); g_object_unref(async_client); return 0; } ccnet_message_free(syn_message); // // receive message asynchronously // struct event_base* ev_base = event_base_new(); struct timeval timeout; timeout.tv_sec = kWaitResponseSeconds - 1; timeout.tv_usec = 0; // set timeout event_base_loopexit(ev_base, &timeout); UserData user_data; user_data.ev_base = ev_base; user_data.ccnet_client = async_client; struct event *read_event = event_new(ev_base, async_client->connfd, EV_READ | EV_PERSIST, readCallback, &user_data); event_add(read_event, NULL); // set message read callback _CcnetMqclientProc *mqclient_proc = (CcnetMqclientProc *) ccnet_proc_factory_create_master_processor (async_client->proc_factory, "mq-client"); ccnet_mqclient_proc_set_message_got_cb(mqclient_proc, messageCallback, ev_base); const char *topics[] = { kAppletCommandsMQ, }; if (ccnet_processor_start((CcnetProcessor *)mqclient_proc, G_N_ELEMENTS(topics), (char **)topics) < 0) { event_base_free(ev_base); g_object_unref(sync_client); g_object_unref(async_client); return 0; } event_base_dispatch(ev_base); event_base_free(ev_base); g_object_unref(sync_client); g_object_unref(async_client); return 0; } } // anonymous namespace bool SharedApplication::activate() { #ifndef Q_OS_WIN32 // saddly, this don't work for windows pthread_t thread; // do it in a background thread if (pthread_create(&thread, NULL, askActivateSynchronically, NULL) != 0) { return false; } // keep wait for timeout or thread quiting int waiting_count = kWaitResponseSeconds * 10; // pthread_kill: currently only a value of 0 is supported on mingw while (pthread_kill(thread, 0) == 0 && --waiting_count > 0) { msleep(100); } if (waiting_count == 0) { // saddly, pthread_cancel don't work properly on mingw pthread_cancel(thread); } #else // _beginthreadex as the document says // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682453%28v=vs.85%29.aspx HANDLE thread = (HANDLE)_beginthreadex(NULL, 0, askActivateSynchronically, NULL, 0, NULL); if (!thread) return false; // keep wait for timeout or thread quiting if (WaitForSingleObject(thread, kWaitResponseSeconds * 1000) == WAIT_TIMEOUT) { TerminateThread(thread, 128); } CloseHandle(thread); #endif return isActivate; }
#include "shared-application.h" #include <QtGlobal> #ifdef Q_OS_WIN32 #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #ifndef __MSVCRT__ #define __MSVCRT__ #endif #include <process.h> #else #include <pthread.h> #endif #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) #include <event2/event.h> #include <event2/event_compat.h> #include <event2/event_struct.h> #else #include <event.h> #endif extern "C" { #include <searpc-client.h> #include <ccnet.h> #include <searpc.h> #include <seafile/seafile.h> #include <seafile/seafile-object.h> } #include "utils/utils.h" namespace { const char *kAppletCommandsMQ = "applet.commands"; const int kWaitResponseSeconds = 6; bool isActivate = false; struct UserData { struct event_base *ev_base; _CcnetClient *ccnet_client; }; // // send message synchronously // void sendOnceCallback(int sock, short what, void* data) { UserData *user_data = static_cast<UserData*>(data); _CcnetClient *sync_client = user_data->ccnet_client; CcnetMessage *syn_message; syn_message = ccnet_message_new(sync_client->base.id, sync_client->base.id, kAppletCommandsMQ, "syn_activate", 0); // blocking io, but cancellable from pthread_cancel if (ccnet_client_send_message(sync_client, syn_message) < 0) { ccnet_message_free(syn_message); // fatal error event_base_loopbreak(user_data->ev_base); } ccnet_message_free(syn_message); } void readCallback(int sock, short what, void* data) { UserData *user_data = static_cast<UserData*>(data); if (ccnet_client_read_input(user_data->ccnet_client) <= 0) { // fatal error event_base_loopbreak(user_data->ev_base); } } void messageCallback(CcnetMessage *message, void *data) { isActivate = g_strcmp0(message->body, "ack_activate") == 0; if (isActivate) { // time to leave struct event_base *ev_base = static_cast<struct event_base*>(data); event_base_loopbreak(ev_base); } } #ifndef Q_OS_WIN32 void *askActivateSynchronically(void * /*arg*/) { #else unsigned __stdcall askActivateSynchronically(void * /*arg*/) { #endif _CcnetClient* async_client = ccnet_client_new(); _CcnetClient *sync_client = ccnet_client_new(); const QString ccnet_dir = defaultCcnetDir(); if (ccnet_client_load_confdir(async_client, toCStr(ccnet_dir)) < 0) { g_object_unref(sync_client); g_object_unref(async_client); return 0; } if (ccnet_client_connect_daemon(async_client, CCNET_CLIENT_ASYNC) < 0) { g_object_unref(sync_client); g_object_unref(async_client); return 0; } if (ccnet_client_load_confdir(sync_client, toCStr(ccnet_dir)) < 0) { g_object_unref(sync_client); g_object_unref(async_client); return 0; } if (ccnet_client_connect_daemon(sync_client, CCNET_CLIENT_SYNC) < 0) { g_object_unref(sync_client); g_object_unref(async_client); return 0; } // // receive message asynchronously // struct event_base* ev_base = event_base_new(); struct timeval timeout; timeout.tv_sec = kWaitResponseSeconds - 1; timeout.tv_usec = 0; // set timeout event_base_loopexit(ev_base, &timeout); UserData read_data; read_data.ev_base = ev_base; read_data.ccnet_client = async_client; struct event *read_event = event_new(ev_base, async_client->connfd, EV_READ | EV_PERSIST, readCallback, &read_data); event_add(read_event, NULL); UserData sendonce_data; sendonce_data.ev_base = ev_base; sendonce_data.ccnet_client = sync_client; struct event *sendonce_event = event_new(ev_base, sync_client->connfd, EV_WRITE, sendOnceCallback, &sendonce_data); event_add(sendonce_event, NULL); // set message read callback _CcnetMqclientProc *mqclient_proc = (CcnetMqclientProc *) ccnet_proc_factory_create_master_processor (async_client->proc_factory, "mq-client"); ccnet_mqclient_proc_set_message_got_cb(mqclient_proc, messageCallback, ev_base); const char *topics[] = { kAppletCommandsMQ, }; if (ccnet_processor_start((CcnetProcessor *)mqclient_proc, G_N_ELEMENTS(topics), (char **)topics) < 0) { event_base_free(ev_base); g_object_unref(sync_client); g_object_unref(async_client); return 0; } event_base_dispatch(ev_base); event_base_free(ev_base); g_object_unref(sync_client); g_object_unref(async_client); return 0; } } // anonymous namespace bool SharedApplication::activate() { #ifndef Q_OS_WIN32 // saddly, this don't work for windows pthread_t thread; // do it in a background thread if (pthread_create(&thread, NULL, askActivateSynchronically, NULL) != 0) { return false; } // keep wait for timeout or thread quiting int waiting_count = kWaitResponseSeconds * 10; // pthread_kill: currently only a value of 0 is supported on mingw while (pthread_kill(thread, 0) == 0 && --waiting_count > 0) { msleep(100); } if (waiting_count == 0) { // saddly, pthread_cancel don't work properly on mingw pthread_cancel(thread); } #else // _beginthreadex as the document says // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682453%28v=vs.85%29.aspx HANDLE thread = (HANDLE)_beginthreadex(NULL, 0, askActivateSynchronically, NULL, 0, NULL); if (!thread) return false; // keep wait for timeout or thread quiting if (WaitForSingleObject(thread, kWaitResponseSeconds * 1000) == WAIT_TIMEOUT) { TerminateThread(thread, 128); } CloseHandle(thread); #endif return isActivate; }
fix shared application issue on windows
fix shared application issue on windows
C++
apache-2.0
daodaoliang/seafile-client,lucius-feng/seafile-client,haiwen/seafile-client,wgaalves/seafile-client,lucius-feng/seafile-client,lucius-feng/seafile-client,haiwen/seafile-client,lucius-feng/seafile-client,daodaoliang/seafile-client,daodaoliang/seafile-client,losingle/seafile-client,wgaalves/seafile-client,losingle/seafile-client,haiwen/seafile-client,haiwen/seafile-client,wgaalves/seafile-client,wgaalves/seafile-client,losingle/seafile-client,losingle/seafile-client,daodaoliang/seafile-client
a9a537ab28f6c5ad06dd286a3213adf5a10d7586
lib/Trace/TraceThreadListener.cpp
lib/Trace/TraceThreadListener.cpp
//===- lib/Trace/TraceThreadListener.cpp ----------------------------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #define _POSIX_C_SOURCE 199506L #include "seec/Trace/TraceFormat.hpp" #include "seec/Trace/TraceThreadListener.hpp" #include "seec/Util/SynchronizedExit.hpp" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #if (defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))) #include <unistd.h> #include <signal.h> #endif namespace seec { namespace trace { //------------------------------------------------------------------------------ // Helper methods //------------------------------------------------------------------------------ void TraceThreadListener::synchronizeProcessTime() { auto RealProcessTime = ProcessListener.getTime(); if (RealProcessTime != ProcessTime) { ProcessTime = RealProcessTime; EventsOut.write<EventType::NewProcessTime>(ProcessTime); } } void TraceThreadListener::checkSignals() { // This function polls for blocked signals. #if defined(__APPLE__) // Apple don't have sigtimedwait(), so we have to use a messy workaround. static std::mutex CheckSignalsMutex; int Success = 0; int Caught = 0; sigset_t Empty; sigset_t Pending; Success = sigemptyset(&Empty); assert(Success == 0 && "sigemptyset() failed."); { std::lock_guard<std::mutex> Lock (CheckSignalsMutex); Success = sigpending(&Pending); assert(Success == 0 && "sigpending() failed."); if (memcmp(&Empty, &Pending, sizeof(sigset_t)) == 0) return; // There is a pending signal. Success = sigwait(&Pending, &Caught); assert(Success == 0 && "sigwait() failed."); } #elif defined(_POSIX_REALTIME_SIGNALS) // Use sigtimedwait() if we possibly can. sigset_t FullSet; auto const FillResult = sigfillset(&FullSet); assert(FillResult == 0 && "sigfillset() failed."); siginfo_t Information; struct timespec WaitTime = (struct timespec){.tv_sec = 0, .tv_nsec = 0}; int const Caught = sigtimedwait(&FullSet, &Information, &WaitTime); // If no signal is found then sigtimedwait() returns an error (-1). if (Caught == -1) return; // Caught > 0 indicates the signal number of the caught signal. #else // All other platforms - no implementation currently. return; #endif // TODO: Write the signal into the trace. // Describe signal using strsignal(). // Perform a coordinated exit (traces will be finalized during destruction). getSupportSynchronizedExit().getSynchronizedExit().exit(EXIT_FAILURE); } //------------------------------------------------------------------------------ // Dynamic memory //------------------------------------------------------------------------------ void TraceThreadListener::recordMalloc(uintptr_t Address, std::size_t Size) { ProcessTime = getCIProcessTime(); auto Offset = EventsOut.write<EventType::Malloc>(Size, ProcessTime); // update dynamic allocation lookup ProcessListener.setCurrentDynamicMemoryAllocation(Address, ThreadID, Offset, Size); } DynamicAllocation TraceThreadListener::recordFree(uintptr_t Address) { auto MaybeMalloc = ProcessListener.getCurrentDynamicMemoryAllocation(Address); // If the allocation didn't exist it should have been caught in preCfree. assert(MaybeMalloc.assigned() && "recordFree with unassigned address."); auto Malloc = MaybeMalloc.get<0>(); // Get new process time and update this thread's view of process time. ProcessTime = getCIProcessTime(); // Write Free event. EventsOut.write<EventType::Free>(Malloc.thread(), Malloc.offset(), ProcessTime); // Update dynamic allocation lookup. ProcessListener.removeCurrentDynamicMemoryAllocation(Address); return Malloc; } void TraceThreadListener::recordFreeAndClear(uintptr_t Address) { auto Malloc = recordFree(Address); // Clear the state of the freed area. recordStateClear(Malloc.address(), Malloc.size()); } //------------------------------------------------------------------------------ // Memory states //------------------------------------------------------------------------------ void TraceThreadListener::writeStateOverwritten(OverwrittenMemoryInfo const &Info) { for (auto const &Overwrite : Info.overwrites()) { auto &Event = Overwrite.getStateEvent(); auto &OldArea = Overwrite.getOldArea(); auto &NewArea = Overwrite.getNewArea(); switch (Overwrite.getType()) { case StateOverwrite::OverwriteType::ReplaceState: EventsOut.write<EventType::StateOverwrite> (Event.getThreadID(), Event.getOffset()); break; case StateOverwrite::OverwriteType::ReplaceFragment: EventsOut.write<EventType::StateOverwriteFragment> (Event.getThreadID(), Event.getOffset(), NewArea.address(), NewArea.length()); break; case StateOverwrite::OverwriteType::TrimFragmentRight: EventsOut.write<EventType::StateOverwriteFragmentTrimmedRight> (OldArea.address(), OldArea.end() - NewArea.start()); break; case StateOverwrite::OverwriteType::TrimFragmentLeft: EventsOut.write<EventType::StateOverwriteFragmentTrimmedLeft> (NewArea.end(), OldArea.start()); break; case StateOverwrite::OverwriteType::SplitFragment: EventsOut.write<EventType::StateOverwriteFragmentSplit> (OldArea.address(), NewArea.end()); break; } } } void TraceThreadListener::recordUntypedState(char const *Data, std::size_t Size) { assert(GlobalMemoryLock.owns_lock() && "Global memory is not locked."); uintptr_t Address = reinterpret_cast<uintptr_t>(Data); ProcessTime = getCIProcessTime(); // Update the process' memory trace with the new state, and find the states // that were overwritten. auto MemoryState = ProcessListener.getTraceMemoryStateAccessor(); auto OverwrittenInfo = MemoryState->add(Address, Size, ThreadID, EventsOut.offset(), ProcessTime); if (Size <= EventRecord<EventType::StateUntypedSmall>::sizeofData()) { EventRecord<EventType::StateUntypedSmall>::typeofData DataStore; char *DataStorePtr = reinterpret_cast<char *>(&DataStore); memcpy(DataStorePtr, Data, Size); // Write the state information to the trace. EventsOut.write<EventType::StateUntypedSmall>( static_cast<uint8_t>(Size), static_cast<uint32_t>(OverwrittenInfo.overwrites().size()), Address, ProcessTime, DataStore); } else { auto DataOffset = ProcessListener.recordData(Data, Size); // Write the state information to the trace. EventsOut.write<EventType::StateUntyped>( static_cast<uint32_t>(OverwrittenInfo.overwrites().size()), Address, ProcessTime, DataOffset, Size); } writeStateOverwritten(OverwrittenInfo); // TODO: add non-local change records for all appropriate functions } void TraceThreadListener::recordTypedState(void const *Data, std::size_t Size, offset_uint Value){ recordUntypedState(reinterpret_cast<char const *>(Data), Size); } void TraceThreadListener::recordStateClear(uintptr_t Address, std::size_t Size) { assert(GlobalMemoryLock.owns_lock() && "Global memory is not locked."); ProcessTime = getCIProcessTime(); auto MemoryState = ProcessListener.getTraceMemoryStateAccessor(); auto OverwrittenInfo = MemoryState->clear(Address, Size); EventsOut.write<EventType::StateClear>( static_cast<uint32_t>(OverwrittenInfo.overwrites().size()), Address, ProcessTime, Size); writeStateOverwritten(OverwrittenInfo); } void TraceThreadListener::recordMemset() { llvm_unreachable("recordMemset unimplemented"); } void TraceThreadListener::recordMemmove(uintptr_t Source, uintptr_t Destination, std::size_t Size) { assert(GlobalMemoryLock.owns_lock() && "Global memory is not locked."); ProcessTime = getCIProcessTime(); auto const MemoryState = ProcessListener.getTraceMemoryStateAccessor(); auto const MoveInfo = MemoryState->memmove(Source, Destination, Size, EventLocation(ThreadID, EventsOut.offset()), ProcessTime); auto const &OverwrittenInfo = MoveInfo.first; auto const OverwrittenCount = static_cast<uint32_t>(OverwrittenInfo.overwrites().size()); EventsOut.write<EventType::StateMemmove>(OverwrittenCount, ProcessTime, Source, Destination, Size); // Write events describing the overwritten states. writeStateOverwritten(OverwrittenInfo); // Write events describing the copied states. for (auto const &Copy : MoveInfo.second) { EventsOut.write<EventType::StateCopied>(Copy.getEvent().getThreadID(), Copy.getEvent().getOffset(), Copy.getArea().start(), Copy.getArea().length()); } } void TraceThreadListener::addKnownMemoryRegion(uintptr_t Address, std::size_t Length, seec::MemoryPermission Access) { assert(GlobalMemoryLock.owns_lock() && "Global memory is not locked."); ProcessListener.addKnownMemoryRegion(Address, Length, Access); auto const Readable = (Access == seec::MemoryPermission::ReadOnly) || (Access == seec::MemoryPermission::ReadWrite); auto const Writable = (Access == seec::MemoryPermission::WriteOnly) || (Access == seec::MemoryPermission::ReadWrite); EventsOut.write<EventType::KnownRegionAdd> (Address, Length, Readable, Writable); } bool TraceThreadListener::removeKnownMemoryRegion(uintptr_t Address) { assert(GlobalMemoryLock.owns_lock() && "Global memory is not locked."); auto const &KnownMemory = ProcessListener.getKnownMemory(); auto const It = KnownMemory.find(Address); if (It == KnownMemory.end()) return false; auto const KeyAddress = It->Begin; auto const Length = (It->End - It->Begin) + 1; // Range is inclusive. auto const Access = It->Value; auto const Result = ProcessListener.removeKnownMemoryRegion(Address); if (!Result) return false; auto const Readable = (Access == seec::MemoryPermission::ReadOnly) || (Access == seec::MemoryPermission::ReadWrite); auto const Writable = (Access == seec::MemoryPermission::WriteOnly) || (Access == seec::MemoryPermission::ReadWrite); EventsOut.write<EventType::KnownRegionRemove> (KeyAddress, Length, Readable, Writable); return Result; } //------------------------------------------------------------------------------ // Constructor and destructor. //------------------------------------------------------------------------------ TraceThreadListener::TraceThreadListener(TraceProcessListener &ProcessListener, OutputStreamAllocator &StreamAllocator) : seec::trace::CallDetector<TraceThreadListener> (ProcessListener.getDetectCallsLookup()), ProcessListener(ProcessListener), SupportSyncExit(ProcessListener.syncExit()), ThreadID(ProcessListener.registerThreadListener(this)), StreamAllocator(StreamAllocator), OutputEnabled(false), EventsOut(), Time(0), ProcessTime(0), RecordedFunctions(), RecordedTopLevelFunctions(), FunctionStack(), FunctionStackMutex(), ActiveFunction(nullptr), GlobalMemoryLock(), DynamicMemoryLock(), StreamsLock() { traceOpen(); #if (defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))) // Setup signal handling for this thread. int Success = 0; sigset_t BlockedSignals; Success |= sigfillset(&BlockedSignals); // Remove signals that cause undefined behaviour when blocked. Success |= sigdelset(&BlockedSignals, SIGBUS); Success |= sigdelset(&BlockedSignals, SIGFPE); Success |= sigdelset(&BlockedSignals, SIGILL); Success |= sigdelset(&BlockedSignals, SIGSEGV); Success |= sigprocmask(SIG_BLOCK, &BlockedSignals, NULL); assert(Success == 0 && "Failed to setup signal blocking."); #endif } TraceThreadListener::~TraceThreadListener() { traceWrite(); traceFlush(); traceClose(); ProcessListener.deregisterThreadListener(ThreadID); } //------------------------------------------------------------------------------ // Trace writing control. //------------------------------------------------------------------------------ void TraceThreadListener::traceWrite() { if (!OutputEnabled) return; // Terminate the event stream. EventsOut.write<EventType::TraceEnd>(0); // Write the trace information. auto TraceOut = StreamAllocator.getThreadStream(ThreadID, ThreadSegment::Trace); assert(TraceOut && "Couldn't get thread trace stream."); offset_uint Written = 0; // Calculate the offset position of the first (top-level functions) list. offset_uint ListOffset = getNewFunctionRecordOffset(); // Write offset of top-level function list. Written += writeBinary(*TraceOut, ListOffset); // Calculate offset of the next function list. ListOffset += getWriteBinarySize(RecordedTopLevelFunctions); // Write function information. for (auto const &Function: RecordedFunctions) { Written += writeBinary(*TraceOut, Function->getIndex()); Written += writeBinary(*TraceOut, Function->getEventOffsetStart()); Written += writeBinary(*TraceOut, Function->getEventOffsetEnd()); Written += writeBinary(*TraceOut, Function->getThreadTimeEntered()); Written += writeBinary(*TraceOut, Function->getThreadTimeExited()); // Write offset of the child function list. Written += writeBinary(*TraceOut, ListOffset); // Calculate offset of the next function list. ListOffset += getWriteBinarySize(Function->getChildren()); } // Write the top-level function list. Written += writeBinary(*TraceOut, RecordedTopLevelFunctions); // Write the child lists. for (auto const &Function: RecordedFunctions) { Written += writeBinary(*TraceOut, Function->getChildren()); } } void TraceThreadListener::traceFlush() { EventsOut.flush(); } void TraceThreadListener::traceClose() { EventsOut.close(); } void TraceThreadListener::traceOpen() { EventsOut.open( StreamAllocator.getThreadStream(ThreadID, ThreadSegment::Events, llvm::raw_fd_ostream::F_Append)); OutputEnabled = true; } //------------------------------------------------------------------------------ // Mutators //------------------------------------------------------------------------------ static void writeError(EventWriter &EventsOut, seec::runtime_errors::RunError const &Error, bool IsTopLevel) { uint16_t Type = static_cast<uint16_t>(Error.type()); auto const &Args = Error.args(); auto const &Additional = Error.additional(); EventsOut.write<EventType::RuntimeError> (Type, static_cast<uint8_t>(Args.size()), static_cast<uint8_t>(Additional.size()), static_cast<uint8_t>(IsTopLevel)); for (auto const &Argument : Args) { EventsOut.write<EventType::RuntimeErrorArgument>( static_cast<uint8_t>(Argument->type()), Argument->data()); } for (auto const &AdditionalError : Additional) { writeError(EventsOut, *AdditionalError, false); } } void TraceThreadListener ::handleRunError(seec::runtime_errors::RunError const &Error, RunErrorSeverity Severity, seec::Maybe<uint32_t> PreInstructionIndex) { // PreInstruction event precedes the RuntimeError if (PreInstructionIndex.assigned()) { EventsOut.write<EventType::PreInstruction>(PreInstructionIndex.get<0>(), ++Time); } writeError(EventsOut, Error, true); switch (Severity) { case RunErrorSeverity::Warning: break; case RunErrorSeverity::Fatal: llvm::errs() << "\nSeeC: Fatal runtime error detected!" " Replay trace for more details.\n"; // Shut down the tracing. SupportSyncExit.getSynchronizedExit().exit(EXIT_FAILURE); break; } } } // namespace trace (in seec) } // namespace seec
//===- lib/Trace/TraceThreadListener.cpp ----------------------------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #define _POSIX_C_SOURCE 199506L #include "seec/Trace/TraceFormat.hpp" #include "seec/Trace/TraceThreadListener.hpp" #include "seec/Util/SynchronizedExit.hpp" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #if (defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))) #include <unistd.h> #include <signal.h> #endif namespace seec { namespace trace { //------------------------------------------------------------------------------ // Helper methods //------------------------------------------------------------------------------ void TraceThreadListener::synchronizeProcessTime() { auto RealProcessTime = ProcessListener.getTime(); if (RealProcessTime != ProcessTime) { ProcessTime = RealProcessTime; EventsOut.write<EventType::NewProcessTime>(ProcessTime); } } void TraceThreadListener::checkSignals() { // This function polls for blocked signals. #if defined(__APPLE__) // Apple don't have sigtimedwait(), so we have to use a messy workaround. static std::mutex CheckSignalsMutex; int Success = 0; int Caught = 0; sigset_t Empty; sigset_t Pending; Success = sigemptyset(&Empty); assert(Success == 0 && "sigemptyset() failed."); { std::lock_guard<std::mutex> Lock (CheckSignalsMutex); Success = sigpending(&Pending); assert(Success == 0 && "sigpending() failed."); if (memcmp(&Empty, &Pending, sizeof(sigset_t)) == 0) return; // There is a pending signal. Success = sigwait(&Pending, &Caught); assert(Success == 0 && "sigwait() failed."); } #elif defined(_POSIX_VERSION) && _POSIX_VERSION >= 199309L // Use sigtimedwait() if we possibly can. sigset_t FullSet; auto const FillResult = sigfillset(&FullSet); assert(FillResult == 0 && "sigfillset() failed."); siginfo_t Information; struct timespec WaitTime = (struct timespec){.tv_sec = 0, .tv_nsec = 0}; int const Caught = sigtimedwait(&FullSet, &Information, &WaitTime); // If no signal is found then sigtimedwait() returns an error (-1). if (Caught == -1) return; // Caught > 0 indicates the signal number of the caught signal. #else // All other platforms - no implementation currently. return; #endif // TODO: Write the signal into the trace. // Describe signal using strsignal(). // Perform a coordinated exit (traces will be finalized during destruction). getSupportSynchronizedExit().getSynchronizedExit().exit(EXIT_FAILURE); } //------------------------------------------------------------------------------ // Dynamic memory //------------------------------------------------------------------------------ void TraceThreadListener::recordMalloc(uintptr_t Address, std::size_t Size) { ProcessTime = getCIProcessTime(); auto Offset = EventsOut.write<EventType::Malloc>(Size, ProcessTime); // update dynamic allocation lookup ProcessListener.setCurrentDynamicMemoryAllocation(Address, ThreadID, Offset, Size); } DynamicAllocation TraceThreadListener::recordFree(uintptr_t Address) { auto MaybeMalloc = ProcessListener.getCurrentDynamicMemoryAllocation(Address); // If the allocation didn't exist it should have been caught in preCfree. assert(MaybeMalloc.assigned() && "recordFree with unassigned address."); auto Malloc = MaybeMalloc.get<0>(); // Get new process time and update this thread's view of process time. ProcessTime = getCIProcessTime(); // Write Free event. EventsOut.write<EventType::Free>(Malloc.thread(), Malloc.offset(), ProcessTime); // Update dynamic allocation lookup. ProcessListener.removeCurrentDynamicMemoryAllocation(Address); return Malloc; } void TraceThreadListener::recordFreeAndClear(uintptr_t Address) { auto Malloc = recordFree(Address); // Clear the state of the freed area. recordStateClear(Malloc.address(), Malloc.size()); } //------------------------------------------------------------------------------ // Memory states //------------------------------------------------------------------------------ void TraceThreadListener::writeStateOverwritten(OverwrittenMemoryInfo const &Info) { for (auto const &Overwrite : Info.overwrites()) { auto &Event = Overwrite.getStateEvent(); auto &OldArea = Overwrite.getOldArea(); auto &NewArea = Overwrite.getNewArea(); switch (Overwrite.getType()) { case StateOverwrite::OverwriteType::ReplaceState: EventsOut.write<EventType::StateOverwrite> (Event.getThreadID(), Event.getOffset()); break; case StateOverwrite::OverwriteType::ReplaceFragment: EventsOut.write<EventType::StateOverwriteFragment> (Event.getThreadID(), Event.getOffset(), NewArea.address(), NewArea.length()); break; case StateOverwrite::OverwriteType::TrimFragmentRight: EventsOut.write<EventType::StateOverwriteFragmentTrimmedRight> (OldArea.address(), OldArea.end() - NewArea.start()); break; case StateOverwrite::OverwriteType::TrimFragmentLeft: EventsOut.write<EventType::StateOverwriteFragmentTrimmedLeft> (NewArea.end(), OldArea.start()); break; case StateOverwrite::OverwriteType::SplitFragment: EventsOut.write<EventType::StateOverwriteFragmentSplit> (OldArea.address(), NewArea.end()); break; } } } void TraceThreadListener::recordUntypedState(char const *Data, std::size_t Size) { assert(GlobalMemoryLock.owns_lock() && "Global memory is not locked."); uintptr_t Address = reinterpret_cast<uintptr_t>(Data); ProcessTime = getCIProcessTime(); // Update the process' memory trace with the new state, and find the states // that were overwritten. auto MemoryState = ProcessListener.getTraceMemoryStateAccessor(); auto OverwrittenInfo = MemoryState->add(Address, Size, ThreadID, EventsOut.offset(), ProcessTime); if (Size <= EventRecord<EventType::StateUntypedSmall>::sizeofData()) { EventRecord<EventType::StateUntypedSmall>::typeofData DataStore; char *DataStorePtr = reinterpret_cast<char *>(&DataStore); memcpy(DataStorePtr, Data, Size); // Write the state information to the trace. EventsOut.write<EventType::StateUntypedSmall>( static_cast<uint8_t>(Size), static_cast<uint32_t>(OverwrittenInfo.overwrites().size()), Address, ProcessTime, DataStore); } else { auto DataOffset = ProcessListener.recordData(Data, Size); // Write the state information to the trace. EventsOut.write<EventType::StateUntyped>( static_cast<uint32_t>(OverwrittenInfo.overwrites().size()), Address, ProcessTime, DataOffset, Size); } writeStateOverwritten(OverwrittenInfo); // TODO: add non-local change records for all appropriate functions } void TraceThreadListener::recordTypedState(void const *Data, std::size_t Size, offset_uint Value){ recordUntypedState(reinterpret_cast<char const *>(Data), Size); } void TraceThreadListener::recordStateClear(uintptr_t Address, std::size_t Size) { assert(GlobalMemoryLock.owns_lock() && "Global memory is not locked."); ProcessTime = getCIProcessTime(); auto MemoryState = ProcessListener.getTraceMemoryStateAccessor(); auto OverwrittenInfo = MemoryState->clear(Address, Size); EventsOut.write<EventType::StateClear>( static_cast<uint32_t>(OverwrittenInfo.overwrites().size()), Address, ProcessTime, Size); writeStateOverwritten(OverwrittenInfo); } void TraceThreadListener::recordMemset() { llvm_unreachable("recordMemset unimplemented"); } void TraceThreadListener::recordMemmove(uintptr_t Source, uintptr_t Destination, std::size_t Size) { assert(GlobalMemoryLock.owns_lock() && "Global memory is not locked."); ProcessTime = getCIProcessTime(); auto const MemoryState = ProcessListener.getTraceMemoryStateAccessor(); auto const MoveInfo = MemoryState->memmove(Source, Destination, Size, EventLocation(ThreadID, EventsOut.offset()), ProcessTime); auto const &OverwrittenInfo = MoveInfo.first; auto const OverwrittenCount = static_cast<uint32_t>(OverwrittenInfo.overwrites().size()); EventsOut.write<EventType::StateMemmove>(OverwrittenCount, ProcessTime, Source, Destination, Size); // Write events describing the overwritten states. writeStateOverwritten(OverwrittenInfo); // Write events describing the copied states. for (auto const &Copy : MoveInfo.second) { EventsOut.write<EventType::StateCopied>(Copy.getEvent().getThreadID(), Copy.getEvent().getOffset(), Copy.getArea().start(), Copy.getArea().length()); } } void TraceThreadListener::addKnownMemoryRegion(uintptr_t Address, std::size_t Length, seec::MemoryPermission Access) { assert(GlobalMemoryLock.owns_lock() && "Global memory is not locked."); ProcessListener.addKnownMemoryRegion(Address, Length, Access); auto const Readable = (Access == seec::MemoryPermission::ReadOnly) || (Access == seec::MemoryPermission::ReadWrite); auto const Writable = (Access == seec::MemoryPermission::WriteOnly) || (Access == seec::MemoryPermission::ReadWrite); EventsOut.write<EventType::KnownRegionAdd> (Address, Length, Readable, Writable); } bool TraceThreadListener::removeKnownMemoryRegion(uintptr_t Address) { assert(GlobalMemoryLock.owns_lock() && "Global memory is not locked."); auto const &KnownMemory = ProcessListener.getKnownMemory(); auto const It = KnownMemory.find(Address); if (It == KnownMemory.end()) return false; auto const KeyAddress = It->Begin; auto const Length = (It->End - It->Begin) + 1; // Range is inclusive. auto const Access = It->Value; auto const Result = ProcessListener.removeKnownMemoryRegion(Address); if (!Result) return false; auto const Readable = (Access == seec::MemoryPermission::ReadOnly) || (Access == seec::MemoryPermission::ReadWrite); auto const Writable = (Access == seec::MemoryPermission::WriteOnly) || (Access == seec::MemoryPermission::ReadWrite); EventsOut.write<EventType::KnownRegionRemove> (KeyAddress, Length, Readable, Writable); return Result; } //------------------------------------------------------------------------------ // Constructor and destructor. //------------------------------------------------------------------------------ TraceThreadListener::TraceThreadListener(TraceProcessListener &ProcessListener, OutputStreamAllocator &StreamAllocator) : seec::trace::CallDetector<TraceThreadListener> (ProcessListener.getDetectCallsLookup()), ProcessListener(ProcessListener), SupportSyncExit(ProcessListener.syncExit()), ThreadID(ProcessListener.registerThreadListener(this)), StreamAllocator(StreamAllocator), OutputEnabled(false), EventsOut(), Time(0), ProcessTime(0), RecordedFunctions(), RecordedTopLevelFunctions(), FunctionStack(), FunctionStackMutex(), ActiveFunction(nullptr), GlobalMemoryLock(), DynamicMemoryLock(), StreamsLock() { traceOpen(); #if (defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))) // Setup signal handling for this thread. int Success = 0; sigset_t BlockedSignals; Success |= sigfillset(&BlockedSignals); // Remove signals that cause undefined behaviour when blocked. Success |= sigdelset(&BlockedSignals, SIGBUS); Success |= sigdelset(&BlockedSignals, SIGFPE); Success |= sigdelset(&BlockedSignals, SIGILL); Success |= sigdelset(&BlockedSignals, SIGSEGV); Success |= sigprocmask(SIG_BLOCK, &BlockedSignals, NULL); assert(Success == 0 && "Failed to setup signal blocking."); #endif } TraceThreadListener::~TraceThreadListener() { traceWrite(); traceFlush(); traceClose(); ProcessListener.deregisterThreadListener(ThreadID); } //------------------------------------------------------------------------------ // Trace writing control. //------------------------------------------------------------------------------ void TraceThreadListener::traceWrite() { if (!OutputEnabled) return; // Terminate the event stream. EventsOut.write<EventType::TraceEnd>(0); // Write the trace information. auto TraceOut = StreamAllocator.getThreadStream(ThreadID, ThreadSegment::Trace); assert(TraceOut && "Couldn't get thread trace stream."); offset_uint Written = 0; // Calculate the offset position of the first (top-level functions) list. offset_uint ListOffset = getNewFunctionRecordOffset(); // Write offset of top-level function list. Written += writeBinary(*TraceOut, ListOffset); // Calculate offset of the next function list. ListOffset += getWriteBinarySize(RecordedTopLevelFunctions); // Write function information. for (auto const &Function: RecordedFunctions) { Written += writeBinary(*TraceOut, Function->getIndex()); Written += writeBinary(*TraceOut, Function->getEventOffsetStart()); Written += writeBinary(*TraceOut, Function->getEventOffsetEnd()); Written += writeBinary(*TraceOut, Function->getThreadTimeEntered()); Written += writeBinary(*TraceOut, Function->getThreadTimeExited()); // Write offset of the child function list. Written += writeBinary(*TraceOut, ListOffset); // Calculate offset of the next function list. ListOffset += getWriteBinarySize(Function->getChildren()); } // Write the top-level function list. Written += writeBinary(*TraceOut, RecordedTopLevelFunctions); // Write the child lists. for (auto const &Function: RecordedFunctions) { Written += writeBinary(*TraceOut, Function->getChildren()); } } void TraceThreadListener::traceFlush() { EventsOut.flush(); } void TraceThreadListener::traceClose() { EventsOut.close(); } void TraceThreadListener::traceOpen() { EventsOut.open( StreamAllocator.getThreadStream(ThreadID, ThreadSegment::Events, llvm::raw_fd_ostream::F_Append)); OutputEnabled = true; } //------------------------------------------------------------------------------ // Mutators //------------------------------------------------------------------------------ static void writeError(EventWriter &EventsOut, seec::runtime_errors::RunError const &Error, bool IsTopLevel) { uint16_t Type = static_cast<uint16_t>(Error.type()); auto const &Args = Error.args(); auto const &Additional = Error.additional(); EventsOut.write<EventType::RuntimeError> (Type, static_cast<uint8_t>(Args.size()), static_cast<uint8_t>(Additional.size()), static_cast<uint8_t>(IsTopLevel)); for (auto const &Argument : Args) { EventsOut.write<EventType::RuntimeErrorArgument>( static_cast<uint8_t>(Argument->type()), Argument->data()); } for (auto const &AdditionalError : Additional) { writeError(EventsOut, *AdditionalError, false); } } void TraceThreadListener ::handleRunError(seec::runtime_errors::RunError const &Error, RunErrorSeverity Severity, seec::Maybe<uint32_t> PreInstructionIndex) { // PreInstruction event precedes the RuntimeError if (PreInstructionIndex.assigned()) { EventsOut.write<EventType::PreInstruction>(PreInstructionIndex.get<0>(), ++Time); } writeError(EventsOut, Error, true); switch (Severity) { case RunErrorSeverity::Warning: break; case RunErrorSeverity::Fatal: llvm::errs() << "\nSeeC: Fatal runtime error detected!" " Replay trace for more details.\n"; // Shut down the tracing. SupportSyncExit.getSynchronizedExit().exit(EXIT_FAILURE); break; } } } // namespace trace (in seec) } // namespace seec
Fix macro check for existence of sigtimedwait() on non-apple platforms.
Fix macro check for existence of sigtimedwait() on non-apple platforms.
C++
mit
mheinsen/seec,seec-team/seec,mheinsen/seec,mheinsen/seec,seec-team/seec,mheinsen/seec,seec-team/seec,seec-team/seec,mheinsen/seec,seec-team/seec
3429bcf8f33487f52b31136be6c294798e2afdca
src/lib/xmlParse/xmlRegisterContextResponse.cpp
src/lib/xmlParse/xmlRegisterContextResponse.cpp
/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Ken Zangelin */ #include <stdio.h> #include <string> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "common/globals.h" #include "ngsi/ContextRegistrationAttribute.h" #include "ngsi/EntityId.h" #include "ngsi9/RegisterContextResponse.h" #include "xmlParse/XmlNode.h" #include "xmlParse/xmlParse.h" #include "xmlParse/xmlRegisterContextResponse.h" /* **************************************************************************** * * duration - */ static int duration(xml_node<>* node, ParseData* reqData) { LM_T(LmtParse, ("Got a duration: '%s'", node->value())); reqData->rcrs.res.duration.set(node->value()); return 0; } /* **************************************************************************** * * registrationId - */ static int registrationId(xml_node<>* node, ParseData* reqData) { LM_T(LmtParse, ("Got a registration id: '%s'", node->value())); reqData->rcrs.res.registrationId.set(node->value()); return 0; } /* **************************************************************************** * * errorCodeCode - */ static int errorCodeCode(xml_node<>* node, ParseData* reqData) { LM_T(LmtParse, ("Got a errorCode code: '%s'", node->value())); reqData->rcrs.res.errorCode.code = (HttpStatusCode) atoi(node->value()); return 0; } /* **************************************************************************** * * errorCodeReasonPhrase - */ static int errorCodeReasonPhrase(xml_node<>* node, ParseData* reqData) { LM_T(LmtParse, ("Got an errorCode reason phrase: '%s'", node->value())); reqData->rcrs.res.errorCode.reasonPhrase = node->value(); // OK - parsing step return 0; } /* **************************************************************************** * * errorCodeDetails - */ static int errorCodeDetails(xml_node<>* node, ParseData* reqData) { LM_T(LmtParse, ("Got an errorCode details string: '%s'", node->value())); reqData->rcrs.res.errorCode.details = node->value(); return 0; } /* **************************************************************************** * * registerContextResponseParseVector - */ XmlNode rcrsParseVector[] = { { "/registerContextResponse", nullTreat }, { "/registerContextResponse/duration", duration }, { "/registerContextResponse/registrationId", registrationId }, { "/registerContextResponse/errorCode", nullTreat }, { "/registerContextResponse/errorCode/code", errorCodeCode }, { "/registerContextResponse/errorCode/reasonPhrase", errorCodeReasonPhrase }, { "/registerContextResponse/errorCode/details", errorCodeDetails }, { "LAST", NULL } }; /* **************************************************************************** * * rcrsInit - */ void rcrsInit(ParseData* reqData) { reqData->errorString = ""; } /* **************************************************************************** * * rcrsRelease - */ void rcrsRelease(ParseData* reqData) { } /* **************************************************************************** * * rcrsCheck - */ std::string rcrsCheck(ParseData* reqData, ConnectionInfo* ciP) { return reqData->rcrs.res.check(RegisterContext, ciP->outFormat, "", reqData->errorString, 0); } /* **************************************************************************** * * rcrsPresent - */ void rcrsPresent(ParseData* reqData) { if (!lmTraceIsSet(LmtDump)) return; PRINTF("\n\n"); reqData->rcrs.res.duration.present(""); reqData->rcrs.res.registrationId.present(""); reqData->rcrs.res.errorCode.present(""); }
/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Ken Zangelin */ #include <stdio.h> #include <string> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "common/globals.h" #include "ngsi/ContextRegistrationAttribute.h" #include "ngsi/EntityId.h" #include "ngsi9/RegisterContextResponse.h" #include "xmlParse/XmlNode.h" #include "xmlParse/xmlParse.h" #include "xmlParse/xmlRegisterContextResponse.h" /* **************************************************************************** * * duration - */ static int duration(xml_node<>* node, ParseData* reqData) { LM_T(LmtParse, ("Got a duration: '%s'", node->value())); reqData->rcrs.res.duration.set(node->value()); return 0; } /* **************************************************************************** * * registrationId - */ static int registrationId(xml_node<>* node, ParseData* reqData) { LM_T(LmtParse, ("Got a registration id: '%s'", node->value())); reqData->rcrs.res.registrationId.set(node->value()); return 0; } /* **************************************************************************** * * errorCodeCode - */ static int errorCodeCode(xml_node<>* node, ParseData* reqData) { LM_T(LmtParse, ("Got a errorCode code: '%s'", node->value())); reqData->rcrs.res.errorCode.code = (HttpStatusCode) atoi(node->value()); return 0; } /* **************************************************************************** * * errorCodeReasonPhrase - */ static int errorCodeReasonPhrase(xml_node<>* node, ParseData* reqData) { LM_T(LmtParse, ("Got an errorCode reason phrase: '%s'", node->value())); reqData->rcrs.res.errorCode.reasonPhrase = node->value(); // OK - parsing step return 0; } /* **************************************************************************** * * errorCodeDetails - */ static int errorCodeDetails(xml_node<>* node, ParseData* reqData) { LM_T(LmtParse, ("Got an errorCode details string: '%s'", node->value())); reqData->rcrs.res.errorCode.details = node->value(); return 0; } /* **************************************************************************** * * registerContextResponseParseVector - */ XmlNode rcrsParseVector[] = { { "/registerContextResponse", nullTreat }, { "/registerContextResponse/duration", duration }, { "/registerContextResponse/registrationId", registrationId }, { "/registerContextResponse/errorCode", nullTreat }, { "/registerContextResponse/errorCode/code", errorCodeCode }, { "/registerContextResponse/errorCode/reasonPhrase", errorCodeReasonPhrase }, { "/registerContextResponse/errorCode/details", errorCodeDetails }, { "LAST", NULL } }; /* **************************************************************************** * * rcrsInit - */ void rcrsInit(ParseData* reqData) { reqData->errorString = ""; } /* **************************************************************************** * * rcrsRelease - */ void rcrsRelease(ParseData* reqData) { } /* **************************************************************************** * * rcrsCheck - */ std::string rcrsCheck(ParseData* reqData, ConnectionInfo* ciP) { return reqData->rcrs.res.check(RegisterContext, ciP->outFormat, "", reqData->errorString, 0); } /* **************************************************************************** * * rcrsPresent - */ void rcrsPresent(ParseData* reqData) { if (!lmTraceIsSet(LmtDump)) return; LM_F(("\n\n")); reqData->rcrs.res.duration.present(""); reqData->rcrs.res.registrationId.present(""); reqData->rcrs.res.errorCode.present(""); }
Remove PRINTF macro
Remove PRINTF macro
C++
agpl-3.0
Fiware/data.Orion,jmcanterafonseca/fiware-orion,Fiware/context.Orion,j1fig/fiware-orion,McMutton/fiware-orion,yalp/fiware-orion,McMutton/fiware-orion,pacificIT/fiware-orion,McMutton/fiware-orion,guerrerocarlos/fiware-orion,gavioto/fiware-orion,fiwareulpgcmirror/fiware-orion,gavioto/fiware-orion,telefonicaid/fiware-orion,j1fig/fiware-orion,McMutton/fiware-orion,telefonicaid/fiware-orion,j1fig/fiware-orion,guerrerocarlos/fiware-orion,fiwareulpgcmirror/fiware-orion,fiwareulpgcmirror/fiware-orion,telefonicaid/fiware-orion,telefonicaid/fiware-orion,Fiware/data.Orion,fortizc/fiware-orion,yalp/fiware-orion,pacificIT/fiware-orion,Fiware/context.Orion,pacificIT/fiware-orion,fiwareulpgcmirror/fiware-orion,fortizc/fiware-orion,telefonicaid/fiware-orion,j1fig/fiware-orion,guerrerocarlos/fiware-orion,jmcanterafonseca/fiware-orion,Fiware/context.Orion,McMutton/fiware-orion,pacificIT/fiware-orion,jmcanterafonseca/fiware-orion,telefonicaid/fiware-orion,Fiware/data.Orion,jmcanterafonseca/fiware-orion,fiwareulpgcmirror/fiware-orion,yalp/fiware-orion,Fiware/data.Orion,j1fig/fiware-orion,guerrerocarlos/fiware-orion,Fiware/data.Orion,fortizc/fiware-orion,pacificIT/fiware-orion,fortizc/fiware-orion,gavioto/fiware-orion,gavioto/fiware-orion,fiwareulpgcmirror/fiware-orion,jmcanterafonseca/fiware-orion,McMutton/fiware-orion,yalp/fiware-orion,guerrerocarlos/fiware-orion,Fiware/context.Orion,fortizc/fiware-orion,McMutton/fiware-orion,jmcanterafonseca/fiware-orion,Fiware/context.Orion,fortizc/fiware-orion,Fiware/data.Orion,Fiware/context.Orion,yalp/fiware-orion,gavioto/fiware-orion
f2b5605c0e2701e90e1139c3e6b947754f0149a0
vespalog/src/vespa/log/log.cpp
vespalog/src/vespa/log/log.cpp
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "log.h" LOG_SETUP_INDIRECT(".log", "$Id$"); #undef LOG #define LOG LOG_INDIRECT #include "lock.h" #include "log-target.h" #include "internal.h" #include "control-file.h" #include "bufferedlogger.h" #include <vespa/defaults.h> #include <cassert> #include <cstdarg> #include <unistd.h> #include <sys/time.h> namespace ns_log { uint64_t Timer::getTimestamp() const { struct timeval tv; gettimeofday(&tv, nullptr); uint64_t timestamp = tv.tv_sec; timestamp *= 1000000; timestamp += tv.tv_usec; return timestamp; } LogTarget *Logger::_target = 0; int Logger::_numInstances = 0; bool Logger::fakePid = false; char Logger::_prefix[64] = { '\0' }; const char Logger::_hexdigit[17] = "0123456789abcdef"; char Logger::_controlName[1024] = { '\0' }; char Logger::_hostname[1024] = { '\0'}; char Logger::_serviceName[1024] = {'\0' }; ControlFile *Logger::_controlFile = 0; static inline unsigned long gettid(const void *tid) { return reinterpret_cast<uint64_t>(tid) >> 3; } static inline unsigned long gettid(unsigned long tid) { return tid; } void Logger::ensureControlName() { if (_controlName[0] == '\0') { if (!ControlFile::makeName(_serviceName, _controlName, sizeof _controlName)) { LOG(spam, "Neither $VESPA_LOG_CONTROL_FILE nor " "$VESPA_LOG_CONTROL_DIR + $VESPA_SERVICE_NAME are set, " "runtime log-control is therefore disabled."); strcpy(_controlName, "///undefined///"); } } } void Logger::ensureServiceName() { if (_serviceName[0] == '\0') { const char *name = getenv("VESPA_SERVICE_NAME"); snprintf(_serviceName, sizeof _serviceName, "%s", name ? name : "-"); } } void Logger::setTarget() { try { char *name = getenv("VESPA_LOG_TARGET"); if (name) { LogTarget *target = LogTarget::makeTarget(name); delete _target; _target = target; } else { LOG(spam, "$VESPA_LOG_TARGET is not set, logging to stderr"); } } catch (InvalidLogException& x) { LOG(error, "Log target problem: %s. Logging to stderr. " "($VESPA_LOG_TARGET=\"%s\")", x.what(), getenv("VESPA_LOG_TARGET")); } } void Logger::ensurePrefix(const char *name) { const char *start = name; if (name[0] != '\0' && name[0] != '.') { const char *end = strchr(name, '.'); int len = end ? end - name : strlen(name); start += len; if (_prefix[0]) { // Make sure the prefix already set is identical to this one if ((len != int(strlen(_prefix))) || memcmp(name, _prefix, len) != 0) { LOG(error, "Fatal: Tried to set log component name '%s' which " "conflicts with existing root component '%s'. ABORTING", name, _prefix); throwInvalid("Bad config component name '%s' conflicts " "with existing name '%s'", name, _prefix); } } else { // No one has set the prefix yet, so we do it snprintf(_prefix, sizeof _prefix, "%.*s", len, name); LOG(debug, "prefix was set to '%s'", _prefix); } } } void Logger::ensureHostname() { if (_hostname[0] == '\0') { snprintf(_hostname, sizeof _hostname, "%s", vespa::Defaults::vespaHostname()); } } Logger::Logger(const char *name, const char *rcsId) : _logLevels(ControlFile::defaultLevels()), _timer(new Timer()) { _numInstances++; memset(_rcsId, 0, sizeof(_rcsId)); memset(_appendix, 0, sizeof(_appendix)); const char *app(strchr(name, '.') ? strchr(name, '.') : ""); assert(strlen(app) < sizeof(_appendix)); strcpy(_appendix, app); if (!_target) { // Set up stderr first as a target so we can log even if target // cannot be found _target = LogTarget::defaultTarget(); setTarget(); } ensureServiceName(); if (rcsId) { setRcsId(rcsId); } ensureControlName(); ensurePrefix(name); ensureHostname(); // Only read log levels from a file if we are using a file! if (strcmp(_controlName, "///undefined///") != 0) { try { if (!_controlFile) { _controlFile = new ControlFile(_controlName, ControlFile::CREATE); } _logLevels = _controlFile->getLevels(_appendix); _controlFile->setPrefix(_prefix); } catch (InvalidLogException& x) { LOG(error, "Problems initialising logging: %s.", x.what()); LOG(warning, "Log control disabled, using default levels."); } } } Logger::~Logger() { _numInstances--; if (_numInstances == 1) { if (logger != nullptr) { logger->~Logger(); free(logger); logger = nullptr; } } else if (_numInstances == 0) { delete _controlFile; logInitialised = false; delete _target; _target = nullptr; } } int Logger::setRcsId(const char *id) { const char *start = strchr(id, ','); if (start) { start += std::min((size_t)3, strlen(start)); // Skip 3 chars } else { start = id; } int len = strlen(start); const char *end = strchr(start, ' '); if (!end) { end = start + len; } assert(size_t(len + 8) < sizeof(_rcsId)); sprintf(_rcsId, "(%.*s): ", (int)(end - start), start); LOG(spam, "rcs id was set to '%s'", _rcsId); return 0; } int Logger::tryLog(int sizeofPayload, LogLevel level, const char *file, int line, const char *fmt, va_list args) { char * payload(new char[sizeofPayload]); const int actualSize = vsnprintf(payload, sizeofPayload, fmt, args); if (actualSize < sizeofPayload) { uint64_t timestamp = _timer->getTimestamp(); doLogCore(timestamp, level, file, line, payload, actualSize); } delete[] payload; return actualSize; } void Logger::doLog(LogLevel level, const char *file, int line, const char *fmt, ...) { int sizeofPayload(0x400); int actualSize(sizeofPayload-1); do { sizeofPayload = actualSize+1; va_list args; va_start(args, fmt); actualSize = tryLog(sizeofPayload, level, file, line, fmt, args); va_end(args); } while (sizeofPayload < actualSize); ns_log::BufferedLogger::logger.trimCache(); } void Logger::doLogCore(uint64_t timestamp, LogLevel level, const char *file, int line, const char *msg, size_t msgSize) { const size_t sizeofEscapedPayload(msgSize*4+1); const size_t sizeofTotalMessage(sizeofEscapedPayload + 1000); auto escapedPayload = std::make_unique<char[]>(sizeofEscapedPayload); auto totalMessage = std::make_unique<char[]>(sizeofTotalMessage); char *dst = escapedPayload.get(); for (size_t i(0); (i < msgSize) && msg[i]; i++) { unsigned char c = static_cast<unsigned char>(msg[i]); if ((c >= 32) && (c != '\\') && (c != 127)) { *dst++ = static_cast<char>(c); } else { *dst++ = '\\'; if (c == '\\') { *dst++ = '\\'; } else if (c == '\r') { *dst++ = 'r'; } else if (c == '\n') { *dst++ = 'n'; } else if (c == '\t') { *dst++ = 't'; } else { *dst++ = 'x'; *dst++ = _hexdigit[c >> 4]; *dst++ = _hexdigit[c & 0xf]; } } } *dst = 0; // The only point of tracking thread id is to be able to distinguish log // from multiple threads from each other. As one aren't using that many // threads, only showing the least significant bits will hopefully // distinguish between all threads in your application. Alter later if // found to be too inaccurate. int32_t tid = (fakePid ? -1 : gettid(pthread_self()) % 0xffff); if (_target->makeHumanReadable()) { time_t secs = static_cast<time_t>(timestamp / 1000000); struct tm tmbuf; localtime_r(&secs, &tmbuf); char timebuf[100]; strftime(timebuf, 100, "%Y-%m-%d %H:%M:%S", &tmbuf); snprintf(totalMessage.get(), sizeofTotalMessage, "[%s.%06u] %d/%d (%s%s) %s: %s\n", timebuf, static_cast<unsigned int>(timestamp % 1000000), fakePid ? -1 : getpid(), tid, _prefix, _appendix, levelName(level), msg); } else if (level == debug || level == spam) { snprintf(totalMessage.get(), sizeofTotalMessage, "%u.%06u\t%s\t%d/%d\t%s\t%s%s\t%s\t%s:%d %s%s\n", static_cast<unsigned int>(timestamp / 1000000), static_cast<unsigned int>(timestamp % 1000000), _hostname, fakePid ? -1 : getpid(), tid, _serviceName, _prefix, _appendix, levelName(level), file, line, _rcsId, escapedPayload.get()); } else { snprintf(totalMessage.get(), sizeofTotalMessage, "%u.%06u\t%s\t%d/%d\t%s\t%s%s\t%s\t%s\n", static_cast<unsigned int>(timestamp / 1000000), static_cast<unsigned int>(timestamp % 1000000), _hostname, fakePid ? -1 : getpid(), tid, _serviceName, _prefix, _appendix, levelName(level), escapedPayload.get()); } _target->write(totalMessage.get(), strlen(totalMessage.get())); } const char * Logger::levelName(LogLevel level) { switch (level) { case fatal: return "fatal"; // Deprecated, remove this later. case error: return "error"; case warning: return "warning"; case event: return "event"; case config: return "config"; case info: return "info"; case debug: return "debug"; case spam: return "spam"; case NUM_LOGLEVELS: break; } return "--unknown--"; } void Logger::doEventStarting(const char *name) { doLog(event, "", 0, "starting/1 name=\"%s\"", name); } void Logger::doEventStopping(const char *name, const char *why) { doLog(event, "", 0, "stopping/1 name=\"%s\" why=\"%s\"", name, why); } void Logger::doEventStarted(const char *name) { doLog(event, "", 0, "started/1 name=\"%s\"", name); } void Logger::doEventStopped(const char *name, pid_t pid, int exitCode) { doLog(event, "", 0, "stopped/1 name=\"%s\" pid=%d exitcode=%d", name, static_cast<int>(pid), exitCode); } void Logger::doEventReloading(const char *name) { doLog(event, "", 0, "reloading/1 name=\"%s\"", name); } void Logger::doEventReloaded(const char *name) { doLog(event, "", 0, "reloaded/1 name=\"%s\"", name); } void Logger::doEventCrash(const char *name, pid_t pid, int signal) { doLog(event, "", 0, "crash/1 name=\"%s\" pid=%d signal=\"%s\"", name, pid, strsignal(signal)); } void Logger::doEventProgress(const char *name, double value, double total) { if (total > 0) { doLog(event, "", 0, "progress/1 name=\"%s\" value=%.18g total=%.18g", name, value, total); } else { doLog(event, "", 0, "progress/1 name=\"%s\" value=%.18g", name, value); } } void Logger::doEventCount(const char *name, uint64_t value) { doLog(event, "", 0, "count/1 name=\"%s\" value=%" PRIu64, name, value); } void Logger::doEventValue(const char *name, double value) { doLog(event, "", 0, "value/1 name=\"%s\" value=%.18g", name, value); } void Logger::doEventState(const char *name, const char *value) { doLog(event, "", 0, "state/1 name=\"%s\" value=\"%s\"", name, value); } } // end namespace ns_log
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "log.h" LOG_SETUP_INDIRECT(".log", "$Id$"); #undef LOG #define LOG LOG_INDIRECT #include "lock.h" #include "log-target.h" #include "internal.h" #include "control-file.h" #include "bufferedlogger.h" #include <vespa/defaults.h> #include <cassert> #include <cstdarg> #include <unistd.h> #include <sys/time.h> namespace ns_log { uint64_t Timer::getTimestamp() const { struct timeval tv; gettimeofday(&tv, nullptr); uint64_t timestamp = tv.tv_sec; timestamp *= 1000000; timestamp += tv.tv_usec; return timestamp; } LogTarget *Logger::_target = 0; int Logger::_numInstances = 0; bool Logger::fakePid = false; char Logger::_prefix[64] = { '\0' }; const char Logger::_hexdigit[17] = "0123456789abcdef"; char Logger::_controlName[1024] = { '\0' }; char Logger::_hostname[1024] = { '\0'}; char Logger::_serviceName[1024] = {'\0' }; ControlFile *Logger::_controlFile = 0; namespace { class GetTid { public: unsigned long operator()(const void *tid) const { return reinterpret_cast<uint64_t>(tid) >> 3; } unsigned long operator()(unsigned long tid) const { return tid; } }; GetTid gettid; } void Logger::ensureControlName() { if (_controlName[0] == '\0') { if (!ControlFile::makeName(_serviceName, _controlName, sizeof _controlName)) { LOG(spam, "Neither $VESPA_LOG_CONTROL_FILE nor " "$VESPA_LOG_CONTROL_DIR + $VESPA_SERVICE_NAME are set, " "runtime log-control is therefore disabled."); strcpy(_controlName, "///undefined///"); } } } void Logger::ensureServiceName() { if (_serviceName[0] == '\0') { const char *name = getenv("VESPA_SERVICE_NAME"); snprintf(_serviceName, sizeof _serviceName, "%s", name ? name : "-"); } } void Logger::setTarget() { try { char *name = getenv("VESPA_LOG_TARGET"); if (name) { LogTarget *target = LogTarget::makeTarget(name); delete _target; _target = target; } else { LOG(spam, "$VESPA_LOG_TARGET is not set, logging to stderr"); } } catch (InvalidLogException& x) { LOG(error, "Log target problem: %s. Logging to stderr. " "($VESPA_LOG_TARGET=\"%s\")", x.what(), getenv("VESPA_LOG_TARGET")); } } void Logger::ensurePrefix(const char *name) { const char *start = name; if (name[0] != '\0' && name[0] != '.') { const char *end = strchr(name, '.'); int len = end ? end - name : strlen(name); start += len; if (_prefix[0]) { // Make sure the prefix already set is identical to this one if ((len != int(strlen(_prefix))) || memcmp(name, _prefix, len) != 0) { LOG(error, "Fatal: Tried to set log component name '%s' which " "conflicts with existing root component '%s'. ABORTING", name, _prefix); throwInvalid("Bad config component name '%s' conflicts " "with existing name '%s'", name, _prefix); } } else { // No one has set the prefix yet, so we do it snprintf(_prefix, sizeof _prefix, "%.*s", len, name); LOG(debug, "prefix was set to '%s'", _prefix); } } } void Logger::ensureHostname() { if (_hostname[0] == '\0') { snprintf(_hostname, sizeof _hostname, "%s", vespa::Defaults::vespaHostname()); } } Logger::Logger(const char *name, const char *rcsId) : _logLevels(ControlFile::defaultLevels()), _timer(new Timer()) { _numInstances++; memset(_rcsId, 0, sizeof(_rcsId)); memset(_appendix, 0, sizeof(_appendix)); const char *app(strchr(name, '.') ? strchr(name, '.') : ""); assert(strlen(app) < sizeof(_appendix)); strcpy(_appendix, app); if (!_target) { // Set up stderr first as a target so we can log even if target // cannot be found _target = LogTarget::defaultTarget(); setTarget(); } ensureServiceName(); if (rcsId) { setRcsId(rcsId); } ensureControlName(); ensurePrefix(name); ensureHostname(); // Only read log levels from a file if we are using a file! if (strcmp(_controlName, "///undefined///") != 0) { try { if (!_controlFile) { _controlFile = new ControlFile(_controlName, ControlFile::CREATE); } _logLevels = _controlFile->getLevels(_appendix); _controlFile->setPrefix(_prefix); } catch (InvalidLogException& x) { LOG(error, "Problems initialising logging: %s.", x.what()); LOG(warning, "Log control disabled, using default levels."); } } } Logger::~Logger() { _numInstances--; if (_numInstances == 1) { if (logger != nullptr) { logger->~Logger(); free(logger); logger = nullptr; } } else if (_numInstances == 0) { delete _controlFile; logInitialised = false; delete _target; _target = nullptr; } } int Logger::setRcsId(const char *id) { const char *start = strchr(id, ','); if (start) { start += std::min((size_t)3, strlen(start)); // Skip 3 chars } else { start = id; } int len = strlen(start); const char *end = strchr(start, ' '); if (!end) { end = start + len; } assert(size_t(len + 8) < sizeof(_rcsId)); sprintf(_rcsId, "(%.*s): ", (int)(end - start), start); LOG(spam, "rcs id was set to '%s'", _rcsId); return 0; } int Logger::tryLog(int sizeofPayload, LogLevel level, const char *file, int line, const char *fmt, va_list args) { char * payload(new char[sizeofPayload]); const int actualSize = vsnprintf(payload, sizeofPayload, fmt, args); if (actualSize < sizeofPayload) { uint64_t timestamp = _timer->getTimestamp(); doLogCore(timestamp, level, file, line, payload, actualSize); } delete[] payload; return actualSize; } void Logger::doLog(LogLevel level, const char *file, int line, const char *fmt, ...) { int sizeofPayload(0x400); int actualSize(sizeofPayload-1); do { sizeofPayload = actualSize+1; va_list args; va_start(args, fmt); actualSize = tryLog(sizeofPayload, level, file, line, fmt, args); va_end(args); } while (sizeofPayload < actualSize); ns_log::BufferedLogger::logger.trimCache(); } void Logger::doLogCore(uint64_t timestamp, LogLevel level, const char *file, int line, const char *msg, size_t msgSize) { const size_t sizeofEscapedPayload(msgSize*4+1); const size_t sizeofTotalMessage(sizeofEscapedPayload + 1000); auto escapedPayload = std::make_unique<char[]>(sizeofEscapedPayload); auto totalMessage = std::make_unique<char[]>(sizeofTotalMessage); char *dst = escapedPayload.get(); for (size_t i(0); (i < msgSize) && msg[i]; i++) { unsigned char c = static_cast<unsigned char>(msg[i]); if ((c >= 32) && (c != '\\') && (c != 127)) { *dst++ = static_cast<char>(c); } else { *dst++ = '\\'; if (c == '\\') { *dst++ = '\\'; } else if (c == '\r') { *dst++ = 'r'; } else if (c == '\n') { *dst++ = 'n'; } else if (c == '\t') { *dst++ = 't'; } else { *dst++ = 'x'; *dst++ = _hexdigit[c >> 4]; *dst++ = _hexdigit[c & 0xf]; } } } *dst = 0; // The only point of tracking thread id is to be able to distinguish log // from multiple threads from each other. As one aren't using that many // threads, only showing the least significant bits will hopefully // distinguish between all threads in your application. Alter later if // found to be too inaccurate. int32_t tid = (fakePid ? -1 : gettid(pthread_self()) % 0xffff); if (_target->makeHumanReadable()) { time_t secs = static_cast<time_t>(timestamp / 1000000); struct tm tmbuf; localtime_r(&secs, &tmbuf); char timebuf[100]; strftime(timebuf, 100, "%Y-%m-%d %H:%M:%S", &tmbuf); snprintf(totalMessage.get(), sizeofTotalMessage, "[%s.%06u] %d/%d (%s%s) %s: %s\n", timebuf, static_cast<unsigned int>(timestamp % 1000000), fakePid ? -1 : getpid(), tid, _prefix, _appendix, levelName(level), msg); } else if (level == debug || level == spam) { snprintf(totalMessage.get(), sizeofTotalMessage, "%u.%06u\t%s\t%d/%d\t%s\t%s%s\t%s\t%s:%d %s%s\n", static_cast<unsigned int>(timestamp / 1000000), static_cast<unsigned int>(timestamp % 1000000), _hostname, fakePid ? -1 : getpid(), tid, _serviceName, _prefix, _appendix, levelName(level), file, line, _rcsId, escapedPayload.get()); } else { snprintf(totalMessage.get(), sizeofTotalMessage, "%u.%06u\t%s\t%d/%d\t%s\t%s%s\t%s\t%s\n", static_cast<unsigned int>(timestamp / 1000000), static_cast<unsigned int>(timestamp % 1000000), _hostname, fakePid ? -1 : getpid(), tid, _serviceName, _prefix, _appendix, levelName(level), escapedPayload.get()); } _target->write(totalMessage.get(), strlen(totalMessage.get())); } const char * Logger::levelName(LogLevel level) { switch (level) { case fatal: return "fatal"; // Deprecated, remove this later. case error: return "error"; case warning: return "warning"; case event: return "event"; case config: return "config"; case info: return "info"; case debug: return "debug"; case spam: return "spam"; case NUM_LOGLEVELS: break; } return "--unknown--"; } void Logger::doEventStarting(const char *name) { doLog(event, "", 0, "starting/1 name=\"%s\"", name); } void Logger::doEventStopping(const char *name, const char *why) { doLog(event, "", 0, "stopping/1 name=\"%s\" why=\"%s\"", name, why); } void Logger::doEventStarted(const char *name) { doLog(event, "", 0, "started/1 name=\"%s\"", name); } void Logger::doEventStopped(const char *name, pid_t pid, int exitCode) { doLog(event, "", 0, "stopped/1 name=\"%s\" pid=%d exitcode=%d", name, static_cast<int>(pid), exitCode); } void Logger::doEventReloading(const char *name) { doLog(event, "", 0, "reloading/1 name=\"%s\"", name); } void Logger::doEventReloaded(const char *name) { doLog(event, "", 0, "reloaded/1 name=\"%s\"", name); } void Logger::doEventCrash(const char *name, pid_t pid, int signal) { doLog(event, "", 0, "crash/1 name=\"%s\" pid=%d signal=\"%s\"", name, pid, strsignal(signal)); } void Logger::doEventProgress(const char *name, double value, double total) { if (total > 0) { doLog(event, "", 0, "progress/1 name=\"%s\" value=%.18g total=%.18g", name, value, total); } else { doLog(event, "", 0, "progress/1 name=\"%s\" value=%.18g", name, value); } } void Logger::doEventCount(const char *name, uint64_t value) { doLog(event, "", 0, "count/1 name=\"%s\" value=%" PRIu64, name, value); } void Logger::doEventValue(const char *name, double value) { doLog(event, "", 0, "value/1 name=\"%s\" value=%.18g", name, value); } void Logger::doEventState(const char *name, const char *value) { doLog(event, "", 0, "state/1 name=\"%s\" value=\"%s\"", name, value); } } // end namespace ns_log
Use functor with overloaded methods instead of overloaded functions to avoid warning about unused function.
Use functor with overloaded methods instead of overloaded functions to avoid warning about unused function.
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
322db895a6756924f969f48fc9ce6853464e5c88
veuilib/include/vscloading.hpp
veuilib/include/vscloading.hpp
#ifndef __VSC_LOADING_HPP__ #define __VSC_LOADING_HPP__ #include <QDialog> #include <QTimer> #include <QLabel> #include <QMovie> #include <QThread> #include "factory.hpp" #include "utility.hpp" #include "debug.hpp" using namespace UtilityLib; class VE_LIBRARY_API VSCLoading : public QWidget { Q_OBJECT public: VSCLoading(QWidget *parent); ~VSCLoading(); private: QLabel * m_label; QMovie * m_movie; }; #endif // __VSC_LOADING_HPP__
#ifndef __VSC_LOADING_HPP__ #define __VSC_LOADING_HPP__ #include <QDialog> #include <QTimer> #include <QLabel> #include <QMovie> #include <QThread> #include "factory.hpp" #include "utility.hpp" #include "debug.hpp" using namespace UtilityLib; class VE_LIBRARY_API VSCLoading : public QWidget { Q_OBJECT public: VSCLoading(QWidget *parent); ~VSCLoading(); public: void Processing(int cnt); private: QLabel * m_label; QMovie * m_movie; }; #endif // __VSC_LOADING_HPP__
add processing for loading
add processing for loading
C++
mit
veyesys/opencvr,xsmart/opencvr,telecamera/opencvr,telecamera/opencvr,xiaojuntong/opencvr,xiaojuntong/opencvr,xiaojuntong/opencvr,xiaojuntong/opencvr,herocodemaster/opencvr,xsmart/opencvr,veyesys/opencvr,telecamera/opencvr,herocodemaster/opencvr,veyesys/opencvr,xsmart/opencvr,xsmart/opencvr,veyesys/opencvr,veyesys/opencvr,xsmart/opencvr,herocodemaster/opencvr,telecamera/opencvr,herocodemaster/opencvr
50f252cc13df6962dbde592079fceabcf4076d23
src/BinaryTree.hpp
src/BinaryTree.hpp
#pragma once #ifndef BinaryTree_disabled #ifndef BinaryTree_defined // ReSharper disable CppUnusedIncludeDirective #include <memory> #include <functional> #include <stack> /** * \brief 遍历方式 */ enum class Order{ PreOrder, InOrder, PostOrder, }; /** * \brief 二叉树的节点类型 * \tparam T 数据类型 */ template<typename T, template<class...> class P> struct BinaryTree{ BinaryTree(P<BinaryTree<T, P>>&& l, P<BinaryTree<T, P>>&& r, T&& d) :data(std::forward<T>(d)), left(std::forward<P<BinaryTree<T, P>>>(l)), right(std::forward<P<BinaryTree<T, P>>>(r)) {} explicit BinaryTree(T&& d) :data(std::forward<T>(d)){} T data; P<BinaryTree<T, P>> left; P<BinaryTree<T, P>> right; /** * \brief 二叉树递归遍历 * \tparam O 遍历方式 * \tparam F 操作函数类型 * \param f 操作函数 */ template<Order O, typename F> void TreeTraversalRecursive(F&& f); /** * \brief 二叉树先序遍历 * \tparam O == Order::PreOrder * \tparam F 操作函数类型 * \param f 操作函数 * \return void */ template<Order O, typename F> typename std::enable_if<O == Order::PreOrder, void>::type TreeTraversalIterative(F&& f){ std::stack<BinaryTree<T, P>*> s; s.push(this); while (!s.empty()) { auto cur = s.top(); std::invoke(std::forward<F&&>(f), cur->data); s.pop(); if (cur->right)s.emplace(cur->right.get()); if (cur->left)s.emplace(cur->left.get()); } } /** * \brief 二叉树中序遍历 * \tparam O == Order::InOrder * \tparam F 操作函数类型 * \param f 操作函数 * \return void */ template<Order O, typename F> typename std::enable_if<O == Order::InOrder, void>::type TreeTraversalIterative(F&& f){ std::stack<BinaryTree<T, P>*> s; auto cur = this; while (!s.empty() || cur) { if (cur) { s.push(cur); cur = cur->left.get(); } else { cur = s.top(); s.pop(); std::invoke(std::forward<F&&>(f), cur->data); cur = cur->right.get(); } } } /** * \brief 二叉树后序遍历 * \tparam O == Order::PostOrder * \tparam F 操作函数类型 * \param f 操作函数 * \return void */ template<Order O, typename F> typename std::enable_if<O == Order::PostOrder, void>::type TreeTraversalIterative(F&& f){ std::stack<BinaryTree<T, P>*> trv; std::stack<BinaryTree<T, P>*> out; trv.push(this); while (!trv.empty()) { auto cur = trv.top(); trv.pop(); if (cur->left)trv.push(cur->left.get()); if (cur->right)trv.push(cur->right.get()); out.push(cur); } while (!out.empty()) { std::invoke(std::forward<F&&>(f), out.top()->data); out.pop(); } } template<Order O, int I, typename F> typename std::enable_if <(I == 0 && O == Order::PreOrder) || (I == 1 && O == Order::InOrder) || (I == 2 && O == Order::PostOrder), void>::type TreeTraversalRecursiveImpl(F&& f){ std::invoke(std::forward<F&&>(f), data); } template<Order O, int I, typename F> typename std::enable_if <(I == 1 && O == Order::PreOrder) || (I == 0 && O == Order::InOrder) || (I == 0 && O == Order::PostOrder), void>::type TreeTraversalRecursiveImpl(F&& f){ if(left)left->template TreeTraversalRecursive<O>(std::forward<F&&>(f)); } template<Order O, int I, typename F> typename std::enable_if <(I == 2 && O == Order::PreOrder) || (I == 2 && O == Order::InOrder) || (I == 1 && O == Order::PostOrder), void>::type TreeTraversalRecursiveImpl(F&& f){ if(right)right->template TreeTraversalRecursive<O>(std::forward<F&&>(f)); } }; template<typename T, template<class...> class P> template<Order O, typename F> void BinaryTree<T, P>::TreeTraversalRecursive(F&& f){ TreeTraversalRecursiveImpl<O, 0>(std::forward<F&&>(f)); TreeTraversalRecursiveImpl<O, 1>(std::forward<F&&>(f)); TreeTraversalRecursiveImpl<O, 2>(std::forward<F&&>(f)); } template<typename T> std::shared_ptr<BinaryTree<T, std::shared_ptr>> MakeTree(std::shared_ptr<BinaryTree<T, std::shared_ptr>>&& left, std::shared_ptr<BinaryTree<T, std::shared_ptr>>&& right, T&& t) { return std::make_shared<BinaryTree<T, std::shared_ptr>>(std::forward<std::shared_ptr<BinaryTree<T, std::shared_ptr>>>(left), std::forward<std::shared_ptr<BinaryTree<T, std::shared_ptr>>>(right), std::forward<T>(t)); } template<typename T> std::unique_ptr<BinaryTree<T, std::unique_ptr>> MakeTree(std::unique_ptr<BinaryTree<T, std::unique_ptr>>&& left, std::unique_ptr<BinaryTree<T, std::unique_ptr>>&& right, T&& t) { return std::make_unique<BinaryTree<T, std::unique_ptr>>(std::forward<std::unique_ptr<BinaryTree<T, std::unique_ptr>>>(left), std::forward<std::unique_ptr<BinaryTree<T, std::unique_ptr>>>(right), std::forward<T>(t)); } template<template<class...> class P, typename T> P<BinaryTree<T, P>> MakeTree(P<BinaryTree<T, P>>&& left, P<BinaryTree<T, P>>&& right, T&& t) { return P<BinaryTree<T, P>>(new BinaryTree<T, P>(std::forward<P<BinaryTree<T, P>>>(left), std::forward<P<BinaryTree<T, P>>>(right), std::forward<T>(t))); } template<template<class...> class P, typename T> auto MakeTree(T&& t) -> typename std::enable_if< !std::is_same<P<int>, std::unique_ptr<int>>::value && !std::is_same<P<int>, std::shared_ptr<int>>::value , P<BinaryTree<T, P>> >::type { return P<BinaryTree<T, P>>(new BinaryTree<T, P>(std::forward<T>(t))); } template<template<class...> class P, typename T> auto MakeTree(T&& t) -> typename std::enable_if< std::is_same<P<T>, std::unique_ptr<T>>::value , P<BinaryTree<T, P>> >::type { return std::make_unique<BinaryTree<T, P>>(std::forward<T>(t)); } template<template<class...> class P = std::shared_ptr, typename T> auto MakeTree(T&& t) -> typename std::enable_if< std::is_same<P<T>, std::shared_ptr<T>>::value , P<BinaryTree<T, P>> >::type { return std::make_shared<BinaryTree<T, P>>(std::forward<T>(t)); } #define BinaryTree_defined #endif #endif
#pragma once #ifndef BinaryTree_disabled #ifndef BinaryTree_defined // ReSharper disable CppUnusedIncludeDirective #include <memory> #include <functional> #include <stack> /** * \brief 遍历方式 */ enum class Order{ PreOrder, InOrder, PostOrder, }; /** * \brief 二叉树的节点类型 * \tparam T 数据类型 */ template<typename T, template<class...> class P> class BinaryTree{ public: BinaryTree(P<BinaryTree<T, P>>&& l, P<BinaryTree<T, P>>&& r, T&& d) :data(std::forward<T>(d)), left(std::forward<P<BinaryTree<T, P>>>(l)), right(std::forward<P<BinaryTree<T, P>>>(r)) {} explicit BinaryTree(T&& d) :data(std::forward<T>(d)){} T data; P<BinaryTree<T, P>> left; P<BinaryTree<T, P>> right; /** * \brief 二叉树递归遍历 * \tparam O 遍历方式 * \tparam F 操作函数类型 * \param f 操作函数 */ template<Order O, typename F> void TreeTraversalRecursive(F&& f); /** * \brief 二叉树先序遍历 * \tparam O == Order::PreOrder * \tparam F 操作函数类型 * \param f 操作函数 * \return void */ template<Order O, typename F> typename std::enable_if<O == Order::PreOrder, void>::type TreeTraversalIterative(F&& f){ std::stack<BinaryTree<T, P>*> s; s.push(this); while (!s.empty()) { auto cur = s.top(); std::invoke(std::forward<F&&>(f), cur->data); s.pop(); if (cur->right)s.emplace(cur->right.get()); if (cur->left)s.emplace(cur->left.get()); } } /** * \brief 二叉树中序遍历 * \tparam O == Order::InOrder * \tparam F 操作函数类型 * \param f 操作函数 * \return void */ template<Order O, typename F> typename std::enable_if<O == Order::InOrder, void>::type TreeTraversalIterative(F&& f){ std::stack<BinaryTree<T, P>*> s; auto cur = this; while (!s.empty() || cur) { if (cur) { s.push(cur); cur = cur->left.get(); } else { cur = s.top(); s.pop(); std::invoke(std::forward<F&&>(f), cur->data); cur = cur->right.get(); } } } /** * \brief 二叉树后序遍历 * \tparam O == Order::PostOrder * \tparam F 操作函数类型 * \param f 操作函数 * \return void */ template<Order O, typename F> typename std::enable_if<O == Order::PostOrder, void>::type TreeTraversalIterative(F&& f){ std::stack<BinaryTree<T, P>*> trv; std::stack<BinaryTree<T, P>*> out; trv.push(this); while (!trv.empty()) { auto cur = trv.top(); trv.pop(); if (cur->left)trv.push(cur->left.get()); if (cur->right)trv.push(cur->right.get()); out.push(cur); } while (!out.empty()) { std::invoke(std::forward<F&&>(f), out.top()->data); out.pop(); } } private: template<Order O, int I, typename F> typename std::enable_if <(I == 0 && O == Order::PreOrder) || (I == 1 && O == Order::InOrder) || (I == 2 && O == Order::PostOrder), void>::type TreeTraversalRecursiveImpl(F&& f){ std::invoke(std::forward<F&&>(f), data); } template<Order O, int I, typename F> typename std::enable_if <(I == 1 && O == Order::PreOrder) || (I == 0 && O == Order::InOrder) || (I == 0 && O == Order::PostOrder), void>::type TreeTraversalRecursiveImpl(F&& f){ if(left)left->template TreeTraversalRecursive<O>(std::forward<F&&>(f)); } template<Order O, int I, typename F> typename std::enable_if <(I == 2 && O == Order::PreOrder) || (I == 2 && O == Order::InOrder) || (I == 1 && O == Order::PostOrder), void>::type TreeTraversalRecursiveImpl(F&& f){ if(right)right->template TreeTraversalRecursive<O>(std::forward<F&&>(f)); } }; template<typename T, template<class...> class P> template<Order O, typename F> void BinaryTree<T, P>::TreeTraversalRecursive(F&& f){ TreeTraversalRecursiveImpl<O, 0>(std::forward<F&&>(f)); TreeTraversalRecursiveImpl<O, 1>(std::forward<F&&>(f)); TreeTraversalRecursiveImpl<O, 2>(std::forward<F&&>(f)); } template<typename T> std::shared_ptr<BinaryTree<T, std::shared_ptr>> MakeTree(std::shared_ptr<BinaryTree<T, std::shared_ptr>>&& left, std::shared_ptr<BinaryTree<T, std::shared_ptr>>&& right, T&& t) { return std::make_shared<BinaryTree<T, std::shared_ptr>>(std::forward<std::shared_ptr<BinaryTree<T, std::shared_ptr>>>(left), std::forward<std::shared_ptr<BinaryTree<T, std::shared_ptr>>>(right), std::forward<T>(t)); } template<typename T> std::unique_ptr<BinaryTree<T, std::unique_ptr>> MakeTree(std::unique_ptr<BinaryTree<T, std::unique_ptr>>&& left, std::unique_ptr<BinaryTree<T, std::unique_ptr>>&& right, T&& t) { return std::make_unique<BinaryTree<T, std::unique_ptr>>(std::forward<std::unique_ptr<BinaryTree<T, std::unique_ptr>>>(left), std::forward<std::unique_ptr<BinaryTree<T, std::unique_ptr>>>(right), std::forward<T>(t)); } template<template<class...> class P, typename T> P<BinaryTree<T, P>> MakeTree(P<BinaryTree<T, P>>&& left, P<BinaryTree<T, P>>&& right, T&& t) { return P<BinaryTree<T, P>>(new BinaryTree<T, P>(std::forward<P<BinaryTree<T, P>>>(left), std::forward<P<BinaryTree<T, P>>>(right), std::forward<T>(t))); } template<template<class...> class P, typename T> auto MakeTree(T&& t) -> typename std::enable_if< !std::is_same<P<int>, std::unique_ptr<int>>::value && !std::is_same<P<int>, std::shared_ptr<int>>::value , P<BinaryTree<T, P>> >::type { return P<BinaryTree<T, P>>(new BinaryTree<T, P>(std::forward<T>(t))); } template<template<class...> class P, typename T> auto MakeTree(T&& t) -> typename std::enable_if< std::is_same<P<T>, std::unique_ptr<T>>::value , P<BinaryTree<T, P>> >::type { return std::make_unique<BinaryTree<T, P>>(std::forward<T>(t)); } template<template<class...> class P = std::shared_ptr, typename T> auto MakeTree(T&& t) -> typename std::enable_if< std::is_same<P<T>, std::shared_ptr<T>>::value , P<BinaryTree<T, P>> >::type { return std::make_shared<BinaryTree<T, P>>(std::forward<T>(t)); } #define BinaryTree_defined #endif #endif
UPDATE use class for BinaryTree
UPDATE use class for BinaryTree
C++
mit
Librazy/DataStructureExps
dda0491dc1af245bce3c5fb28ccbf0235131dffc
src/MQTT433gateway.cpp
src/MQTT433gateway.cpp
/** MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight Project home: https://github.com/puuu/MQTT433gateway/ The MIT License (MIT) Copyright (c) 2016 Puuu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <ESP8266httpUpdate.h> #include <ESP8266mDNS.h> #include <FS.h> #include <ArduinoSimpleLogging.h> #include <WiFiManager.h> #include <ConfigWebServer.h> #include <MqttClient.h> #include <RfHandler.h> #include <Settings.h> #include <StatusLED.h> #include <SyslogLogTarget.h> #include <SystemHeap.h> #include <SystemLoad.h> WiFiClient wifi; Settings settings; ConfigWebServer *webServer = nullptr; MqttClient *mqttClient = nullptr; RfHandler *rf = nullptr; SyslogLogTarget *syslogLog = nullptr; StatusLED *statusLED = nullptr; SystemLoad *systemLoad = nullptr; SystemHeap *systemHeap = nullptr; void setupMqtt(const Settings &) { if (mqttClient != nullptr) { delete mqttClient; mqttClient = nullptr; Logger.debug.println(F("MQTT instance removed.")); } if (!settings.hasValidPassword()) { Logger.warning.println( F("No valid config password set - do not connect to MQTT!")); return; } if (settings.mqttBroker.length() <= 0) { Logger.warning.println(F("No MQTT broker configured yet")); return; } mqttClient = new MqttClient(settings, wifi); mqttClient->registerRfDataHandler( [](const String &protocol, const String &data) { if (rf) rf->transmitCode(protocol, data); }); mqttClient->begin(); Logger.info.println(F("MQTT instance created.")); } void setupRf(const Settings &) { if (rf) { delete rf; rf = nullptr; Logger.debug.println(F("Rf instance removed.")); } if (!settings.hasValidPassword()) { Logger.warning.println( F("No valid config password set - do not start RF handler!")); return; } rf = new RfHandler(settings); rf->registerReceiveHandler([](const String &protocol, const String &data) { if (mqttClient) { mqttClient->publishCode(protocol, data); } }); rf->begin(); Logger.info.println(F("RfHandler Instance created.")); } void setupWebLog() { if (webServer) { if (settings.webLogLevel.length() > 0) { Logger.addHandler(Logger.stringToLevel(settings.webLogLevel), webServer->logTarget()); } else { Logger.removeHandler(webServer->logTarget()); } } } void setupWebServer() { webServer = new ConfigWebServer(settings); webServer->registerSystemCommandHandler(F("restart"), []() { Logger.info.println(F("Restart device.")); delay(100); ESP.restart(); }); webServer->registerSystemCommandHandler(F("reset_wifi"), []() { Logger.info.println(F("Reset wifi and restart device.")); WiFi.disconnect(true); delay(100); ESP.restart(); }); webServer->registerSystemCommandHandler(F("reset_config"), []() { Logger.info.println(F("Reset configuration and restart device.")); settings.reset(); delay(100); ESP.restart(); }); webServer->registerProtocolProvider([]() { if (rf) { return rf->availableProtocols(); } return String(F("[]")); }); webServer->registerOtaHook([]() { Logger.debug.println(F("Prepare for oat update.")); if (statusLED) statusLED->setState(StatusLED::ota); if (rf) { delete rf; rf = nullptr; } if (mqttClient) { delete mqttClient; mqttClient = nullptr; } WiFiUDP::stopAll(); }); webServer->registerDebugFlagHandler( F("protocolRaw"), []() { return rf && rf->isRawModeEnabled(); }, [](bool state) { if (rf) rf->setRawMode(state); }); webServer->registerDebugFlagHandler( F("systemLoad"), []() { return systemLoad != nullptr; }, [](bool state) { if (state) { systemLoad = new SystemLoad(Logger.debug); } else if (systemLoad) { delete systemLoad; systemLoad = nullptr; } }); webServer->registerDebugFlagHandler( F("freeHeap"), []() { return systemHeap != nullptr; }, [](bool state) { if (state) { systemHeap = new SystemHeap(Logger.debug); } else if (systemHeap) { delete systemHeap; systemHeap = nullptr; } }); webServer->begin(); Logger.info.println(F("WebServer instance created.")); setupWebLog(); } void setupMdns() { if (0 == settings.deviceName.length()) { return; } if (!MDNS.begin(settings.deviceName.c_str())) { Logger.error.println(F("Error setting up MDNS responder")); } MDNS.addService("http", "tcp", 80); Logger.info.println(F("MDNS service registered.")); } void setupStatusLED(const Settings &s) { delete statusLED; statusLED = new StatusLED(s.ledPin, s.ledActiveHigh); Logger.debug.print("Change status LED config: pin="); Logger.debug.print(s.ledPin); Logger.debug.print(" activeHigh="); Logger.debug.println(s.ledActiveHigh); } void setupWifi() { WiFiManager wifiManager; wifiManager.setConfigPortalTimeout(180); wifiManager.setAPCallback([](WiFiManager *) { Logger.info.println(F("Start wifimanager config portal.")); if (statusLED) statusLED->setState(StatusLED::wifimanager); }); // Restart after we had the portal running wifiManager.setSaveConfigCallback([]() { Logger.info.println(F("Wifi config changed. Restart.")); delay(100); ESP.restart(); }); if (!wifiManager.autoConnect(settings.deviceName.c_str(), settings.configPassword.c_str())) { Logger.warning.println(F("Try connecting again after reboot")); ESP.restart(); } } void setup() { Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY); Logger.addHandler(Logger.DEBUG, Serial); if (!SPIFFS.begin()) { Logger.error.println(F("Initializing of SPIFFS failed!")); } settings.registerChangeHandler(STATUSLED, setupStatusLED); settings.registerChangeHandler(MQTT, setupMqtt); settings.registerChangeHandler(RF_ECHO, [](const Settings &s) { Logger.debug.println(F("Configure rfEchoMessages.")); if (rf) { rf->setEchoEnabled(s.rfEchoMessages); } else { Logger.warning.println(F("No Rf instance available")); } }); settings.registerChangeHandler(RF_PROTOCOL, [](const Settings &s) { Logger.debug.println(F("Configure rfProtocols.")); if (rf) { rf->filterProtocols(s.rfProtocols); } else { Logger.warning.println(F("No Rf instance available")); } }); settings.registerChangeHandler(WEB_CONFIG, [](const Settings &s) { Logger.debug.println(F("Configure WebServer.")); if (!webServer) { setupWebServer(); } }); settings.registerChangeHandler(SYSLOG, [](const Settings &s) { if (syslogLog) { Logger.removeHandler(*syslogLog); delete syslogLog; syslogLog = nullptr; Logger.debug.println(F("Syslog instance removed.")); } if (s.syslogLevel.length() > 0 && s.syslogHost.length() > 0 && s.syslogPort != 0) { syslogLog = new SyslogLogTarget(); syslogLog->begin(s.deviceName, s.syslogHost, s.syslogPort); Logger.debug.println(F("Syslog instance created.")); Logger.addHandler(Logger.stringToLevel(s.syslogLevel), *syslogLog); } }); settings.registerChangeHandler(RF_CONFIG, setupRf); settings.registerChangeHandler(LOGGING, [](const Settings &s) { Logger.debug.println(F("Configure logging.")); if (s.serialLogLevel.length() > 0) { Logger.addHandler(Logger.stringToLevel(settings.serialLogLevel), Serial); } else { Logger.removeHandler(Serial); } setupWebLog(); }); Logger.info.println(F("Load Settings...")); settings.load(); setupStatusLED(settings); if (statusLED) statusLED->setState(StatusLED::wifiConnect); setupWifi(); // Notify all setting listeners settings.notifyAll(); if (statusLED) statusLED->setState(StatusLED::startup); Logger.debug.println(F("Current configuration:")); settings.serialize(Logger.debug, true, false); Logger.debug.println(); setupMdns(); Logger.info.print(F("Listen on IP: ")); Logger.info.println(WiFi.localIP()); } void loop() { if (rf && mqttClient && mqttClient->isConnected()) { if (statusLED) statusLED->setState(StatusLED::normalOperation); } else { if (statusLED) statusLED->setState(StatusLED::requireConfiguration); } if (statusLED) { statusLED->loop(); } if (webServer) { webServer->loop(); } if (mqttClient) { mqttClient->loop(); } if (rf) { rf->loop(); } if (systemLoad) { systemLoad->loop(); } if (systemHeap) { systemHeap->loop(); } }
/** MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight Project home: https://github.com/puuu/MQTT433gateway/ The MIT License (MIT) Copyright (c) 2016 Puuu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <ESP8266httpUpdate.h> #include <ESP8266mDNS.h> #include <FS.h> #include <ArduinoSimpleLogging.h> #include <WiFiManager.h> #include <ConfigWebServer.h> #include <MqttClient.h> #include <RfHandler.h> #include <Settings.h> #include <StatusLED.h> #include <SyslogLogTarget.h> #include <SystemHeap.h> #include <SystemLoad.h> WiFiClient wifi; Settings settings; ConfigWebServer *webServer = nullptr; MqttClient *mqttClient = nullptr; RfHandler *rf = nullptr; SyslogLogTarget *syslogLog = nullptr; StatusLED *statusLED = nullptr; SystemLoad *systemLoad = nullptr; SystemHeap *systemHeap = nullptr; void setupMqtt(const Settings &) { if (mqttClient != nullptr) { delete mqttClient; mqttClient = nullptr; Logger.debug.println(F("MQTT instance removed.")); } if (!settings.hasValidPassword()) { Logger.warning.println( F("No valid config password set - do not connect to MQTT!")); return; } if (settings.mqttBroker.length() <= 0) { Logger.warning.println(F("No MQTT broker configured yet")); return; } mqttClient = new MqttClient(settings, wifi); mqttClient->registerRfDataHandler( [](const String &protocol, const String &data) { if (rf) rf->transmitCode(protocol, data); }); mqttClient->begin(); Logger.info.println(F("MQTT instance created.")); } void setupRf(const Settings &) { if (rf) { delete rf; rf = nullptr; Logger.debug.println(F("Rf instance removed.")); } if (!settings.hasValidPassword()) { Logger.warning.println( F("No valid config password set - do not start RF handler!")); return; } rf = new RfHandler(settings); rf->registerReceiveHandler([](const String &protocol, const String &data) { if (mqttClient) { mqttClient->publishCode(protocol, data); } }); rf->begin(); Logger.info.println(F("RfHandler Instance created.")); } void setupWebLog() { if (webServer) { if (settings.webLogLevel.length() > 0) { Logger.addHandler(Logger.stringToLevel(settings.webLogLevel), webServer->logTarget()); } else { Logger.removeHandler(webServer->logTarget()); } } } void setupWebServer() { webServer = new ConfigWebServer(settings); webServer->registerSystemCommandHandler(F("restart"), []() { Logger.info.println(F("Restart device.")); delay(100); ESP.restart(); }); webServer->registerSystemCommandHandler(F("reset_wifi"), []() { Logger.info.println(F("Reset wifi and restart device.")); WiFi.disconnect(true); delay(100); ESP.restart(); }); webServer->registerSystemCommandHandler(F("reset_config"), []() { Logger.info.println(F("Reset configuration and restart device.")); settings.reset(); delay(100); ESP.restart(); }); webServer->registerProtocolProvider([]() { if (rf) { return rf->availableProtocols(); } return String(F("[]")); }); webServer->registerOtaHook([]() { Logger.debug.println(F("Prepare for oat update.")); if (statusLED) statusLED->setState(StatusLED::ota); if (rf) { delete rf; rf = nullptr; } if (mqttClient) { delete mqttClient; mqttClient = nullptr; } WiFiUDP::stopAll(); }); webServer->registerDebugFlagHandler( F("protocolRaw"), []() { return rf && rf->isRawModeEnabled(); }, [](bool state) { if (rf) rf->setRawMode(state); }); webServer->registerDebugFlagHandler( F("systemLoad"), []() { return systemLoad != nullptr; }, [](bool state) { if (state) { systemLoad = new SystemLoad(Logger.debug); } else if (systemLoad) { delete systemLoad; systemLoad = nullptr; } }); webServer->registerDebugFlagHandler( F("freeHeap"), []() { return systemHeap != nullptr; }, [](bool state) { if (state) { systemHeap = new SystemHeap(Logger.debug); } else if (systemHeap) { delete systemHeap; systemHeap = nullptr; } }); webServer->begin(); Logger.info.println(F("WebServer instance created.")); setupWebLog(); } void setupMdns() { if (0 == settings.deviceName.length()) { return; } if (!MDNS.begin(settings.deviceName.c_str())) { Logger.error.println(F("Error setting up MDNS responder")); return; } MDNS.addService("http", "tcp", 80); Logger.info.println(F("MDNS service registered.")); } void setupStatusLED(const Settings &s) { delete statusLED; statusLED = new StatusLED(s.ledPin, s.ledActiveHigh); Logger.debug.print("Change status LED config: pin="); Logger.debug.print(s.ledPin); Logger.debug.print(" activeHigh="); Logger.debug.println(s.ledActiveHigh); } void setupWifi() { WiFiManager wifiManager; wifiManager.setConfigPortalTimeout(180); wifiManager.setAPCallback([](WiFiManager *) { Logger.info.println(F("Start wifimanager config portal.")); if (statusLED) statusLED->setState(StatusLED::wifimanager); }); // Restart after we had the portal running wifiManager.setSaveConfigCallback([]() { Logger.info.println(F("Wifi config changed. Restart.")); delay(100); ESP.restart(); }); if (!wifiManager.autoConnect(settings.deviceName.c_str(), settings.configPassword.c_str())) { Logger.warning.println(F("Try connecting again after reboot")); ESP.restart(); } } void setup() { Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY); Logger.addHandler(Logger.DEBUG, Serial); if (!SPIFFS.begin()) { Logger.error.println(F("Initializing of SPIFFS failed!")); } settings.registerChangeHandler(STATUSLED, setupStatusLED); settings.registerChangeHandler(MQTT, setupMqtt); settings.registerChangeHandler(RF_ECHO, [](const Settings &s) { Logger.debug.println(F("Configure rfEchoMessages.")); if (rf) { rf->setEchoEnabled(s.rfEchoMessages); } else { Logger.warning.println(F("No Rf instance available")); } }); settings.registerChangeHandler(RF_PROTOCOL, [](const Settings &s) { Logger.debug.println(F("Configure rfProtocols.")); if (rf) { rf->filterProtocols(s.rfProtocols); } else { Logger.warning.println(F("No Rf instance available")); } }); settings.registerChangeHandler(WEB_CONFIG, [](const Settings &s) { Logger.debug.println(F("Configure WebServer.")); if (!webServer) { setupWebServer(); } }); settings.registerChangeHandler(SYSLOG, [](const Settings &s) { if (syslogLog) { Logger.removeHandler(*syslogLog); delete syslogLog; syslogLog = nullptr; Logger.debug.println(F("Syslog instance removed.")); } if (s.syslogLevel.length() > 0 && s.syslogHost.length() > 0 && s.syslogPort != 0) { syslogLog = new SyslogLogTarget(); syslogLog->begin(s.deviceName, s.syslogHost, s.syslogPort); Logger.debug.println(F("Syslog instance created.")); Logger.addHandler(Logger.stringToLevel(s.syslogLevel), *syslogLog); } }); settings.registerChangeHandler(RF_CONFIG, setupRf); settings.registerChangeHandler(LOGGING, [](const Settings &s) { Logger.debug.println(F("Configure logging.")); if (s.serialLogLevel.length() > 0) { Logger.addHandler(Logger.stringToLevel(settings.serialLogLevel), Serial); } else { Logger.removeHandler(Serial); } setupWebLog(); }); Logger.info.println(F("Load Settings...")); settings.load(); setupStatusLED(settings); if (statusLED) statusLED->setState(StatusLED::wifiConnect); setupWifi(); // Notify all setting listeners settings.notifyAll(); if (statusLED) statusLED->setState(StatusLED::startup); Logger.debug.println(F("Current configuration:")); settings.serialize(Logger.debug, true, false); Logger.debug.println(); setupMdns(); Logger.info.print(F("Listen on IP: ")); Logger.info.println(WiFi.localIP()); } void loop() { if (rf && mqttClient && mqttClient->isConnected()) { if (statusLED) statusLED->setState(StatusLED::normalOperation); } else { if (statusLED) statusLED->setState(StatusLED::requireConfiguration); } if (statusLED) { statusLED->loop(); } if (webServer) { webServer->loop(); } if (mqttClient) { mqttClient->loop(); } if (rf) { rf->loop(); } if (systemLoad) { systemLoad->loop(); } if (systemHeap) { systemHeap->loop(); } }
add missing return in setupMdns()
MQTT433gateway: add missing return in setupMdns()
C++
mit
puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway
9a8fd60a42714940b2936d67e5d87e5ed9fca57f
src/sn_Thread/rwspin_lock.hpp
src/sn_Thread/rwspin_lock.hpp
#ifndef SN_THREAD_RWSPIN_LOCK_H #define SN_THREAD_RWSPIN_LOCK_H #include <atomic> #include <memory> #include <thread> #if defined(__GNUC__) #define likely(x) __builtin_expect ((x), 1) #define unlikely(x) __builtin_expect ((x), 0) #else #define likely(x) x #define unlikely(x) x #endif namespace sn_Thread { // ref: https://www.zhihu.com/question/67990738 namespace rwspin_lock { class RWSpinLock { std::atomic<size_t> m_cnt{0}; std::atomic<bool> m_need_write{false}; friend class RWReadGuard; friend class RWWriteGuard; }; class RWReadGuard { private: RWSpinLock* m_lock{}; public: RWLockReadGuard() noexcept = default; explicit RWReadGuard(RWSpinLock * lock) noexcept : m_lock{lock} { while (true) { if (unlikely(lock->m_need_write.load(std::memory_order_acquire))) { std::this_thread::yield(); continue; } lock->m_cnt.fetch_add(1); if (unlikely(lock->m_need_write.load(std::memory_order_acquire))) { lock->m_cnt.fetch_sub(1); continue; } } } // @TODO RWReadGuard(RWReadGuard && another) = delete; // @TODO RWReadGuard & operator=(RWReadGuard && another) = delete; ~RWReadGuard() noexcept { if (m_lock) { m_lock->m_cnt.fetch_sub(1); } } public: RWLockReadGuard(const RWLockReadGuard &) noexcept = delete; void operator=(const RWLockReadGuard &) noexcept = delete; }; class RWWriteGuard { private: RWSpinLock* m_lock{}; public: RWWriteGuard() noexcept = default; explicit RWWriteGuard(RWSpinLock * lock) noexcept : m_lock{lock} { while (true) { if (unlikely(lock->m_need_write.load(std::memory_order_acquire))) { std::this_thread::yield(); continue; } bool e = false; if (unlikely(lock->m_need_write.compare_exchange_strong(e, true))) { break; } } } RWLockWriteGuard(RWLockWriteGuard && another) = delete; RWLockWriteGuard & operator=(RWLockWriteGuard && another) = delete; ~RWLockWriteGuard() noexcept { if (m_lock) { m_lock->m_need_write.store(false, std::memory_order_release); } } public: RWLockWriteGuard(const RWLockWriteGuard &) noexcept = delete; void operator=(const RWLockWriteGuard &) noexcept = delete; }; } } #endif
#ifndef SN_THREAD_RWSPIN_LOCK_H #define SN_THREAD_RWSPIN_LOCK_H #include <atomic> #include <memory> #include <thread> #if defined(__GNUC__) #define likely(x) __builtin_expect ((x), 1) #define unlikely(x) __builtin_expect ((x), 0) #else #define likely(x) x #define unlikely(x) x #endif namespace sn_Thread { // @ref: https://stackoverflow.com/questions/41193648/c-shared-mutex-implementation class atomic_shared_mutex { atomic<uint32_t> m_refcnt{0}; constexpr const static uint32_t STATE_WRITE = 1U << (sizeof(uint32_t) * 8 - 1); public: void lock() { uint32_t val; do { val = 0; } while (!m_refcnt.compare_exchange_weak( val, STATE_WRITE, memory_order_acquire )); } void unlock() { m_refcnt.store(0, memory_order_release); } void lock_shared() { uint32_t val; do { while (val == STATE_WRITE) { val = m_refcnt.load(memory_order_relaxed); } } while(!m_refcnt.compare_exchange_weak( val, val + 1, memory_order_acquire )); } void unlock_shared() { m_refcnt.fetch_sub(1, memory_order_release); } }; // @ref: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/shared_mutex class shared_mutex { mutex m_mtx; // block when STATE_WRITE set or MAX_READER condition_variable m_blk_wt; // block when reader is non-zero condition_variable m_blk_rd; uint32_t m_cnt{0}; constexpr const static uint32_t STATE_WRITE = 1U << (sizeof(uint32_t) * 8 - 1); constexpr const static uint32_t MAX_READER = ~STATE_WRITE; bool is_on_write() const { return m_cnt & STATE_WRITE; } bool num_reader() const { return m_cnt & MAX_READER; } public: void lock() { unique_lock<mutex> lk{m_mtx}; // wait until getting writer lk m_blk_wt.wait(lk, [=]{ return !is_on_write(); }); m_cnt |= STATE_WRITE; // wait until reader exits m_blk_rd.wait(lk, [=]{ return !num_reader(); }); } void unlock() { lock_guard<mutex> lk{m_mtx}; m_cnt = 0; m_blk_wt.notify_all(); } void lock_shared() { unique_lock<mutex> lk{m_mtx}; m_blk_wt.wait(lk, [=]{ return m_cnt < MAX_READER; }); ++m_cnt; } void unlock_shared() { lock_guard<mutex> lk{m_mtx}; auto prev = m_cnt--; if (is_on_write()) { // Wake on writer if no more reader if (!num_reader()) { m_blk_rd.notify_one(); } } else { // Wake on reader overflow if (prev == MAX_READER) { m_blk_wt.notify_one(); } } } }; // @ref: https://code.woboq.org/llvm/libcxx/include/shared_mutex.html template <typename Mtx> class shared_lock { Mtx* m_mtx; bool is_own; public: explicit shared_lock(Mtx& mtx) noexcept : m_mtx(addressof(mtx)), is_own(true) { m_mtx->lock_shared(); } shared_lock(const shared_lock&) = delete; shared_lock& operator=(const shared_lock&) = delete; shared_lock(shared_lock&& u) noexcept : m_mtx{u.m_mtx}, is_own{u.is_own} { { u.m_mtx = nullptr; u.is_own = false; } shared_lock& operator=(shared_lock&& u) noexcept { if (is_own) { m_mtx->unlock_shared(); } m_mtx = u.m_mtx; is_own = u.is_own; u.m_mtx = nullptr; u.is_own = false; return *this; } ~shared_lock() { if (is_own) { m_mtx->unlock_shared(); } } }; // ref: https://www.zhihu.com/question/67990738 namespace rwspin_lock { class RWSpinLock { std::atomic<size_t> m_cnt{0}; std::atomic<bool> m_need_write{false}; friend class RWReadGuard; friend class RWWriteGuard; }; class RWReadGuard { private: RWSpinLock* m_lock{}; public: RWLockReadGuard() noexcept = default; explicit RWReadGuard(RWSpinLock * lock) noexcept : m_lock{lock} { while (true) { if (unlikely(lock->m_need_write.load(std::memory_order_acquire))) { std::this_thread::yield(); continue; } lock->m_cnt.fetch_add(1); if (unlikely(lock->m_need_write.load(std::memory_order_acquire))) { lock->m_cnt.fetch_sub(1); continue; } } } // @TODO RWReadGuard(RWReadGuard && another) = delete; // @TODO RWReadGuard & operator=(RWReadGuard && another) = delete; ~RWReadGuard() noexcept { if (m_lock) { m_lock->m_cnt.fetch_sub(1); } } public: RWLockReadGuard(const RWLockReadGuard &) noexcept = delete; void operator=(const RWLockReadGuard &) noexcept = delete; }; class RWWriteGuard { private: RWSpinLock* m_lock{}; public: RWWriteGuard() noexcept = default; explicit RWWriteGuard(RWSpinLock * lock) noexcept : m_lock{lock} { while (true) { if (unlikely(lock->m_need_write.load(std::memory_order_acquire))) { std::this_thread::yield(); continue; } bool e = false; if (unlikely(lock->m_need_write.compare_exchange_strong(e, true))) { break; } } } RWLockWriteGuard(RWLockWriteGuard && another) = delete; RWLockWriteGuard & operator=(RWLockWriteGuard && another) = delete; ~RWLockWriteGuard() noexcept { if (m_lock) { m_lock->m_need_write.store(false, std::memory_order_release); } } public: RWLockWriteGuard(const RWLockWriteGuard &) noexcept = delete; void operator=(const RWLockWriteGuard &) noexcept = delete; }; } } #endif
Update shared_lock
Update shared_lock
C++
mit
Airtnp/SuperNaiveCppLib
313627a80b1853f90e42bed080f573efb33f6223
src/Network/Server.cpp
src/Network/Server.cpp
#include <fstream> #include "Server.hpp" #include "NetworkEvents.hpp" namespace DrawAttack { Server::Server(unsigned short port, std::string wordFilename) : m_port(port) , m_running(false) , m_wordFilename(wordFilename) , m_mode(Wait) , m_currentDrawer(nullptr) { std::ifstream wordFile(wordFilename); std::string line; if (wordFile.is_open()) { while (std::getline(wordFile, line)) { m_wordList.push_back(line); } wordFile.close(); } else { cpp3ds::err() << "Failed to open word file: " << wordFilename << std::endl; } clearDrawData(); } Server::~Server() { for (auto& socket : m_sockets) { socket->disconnect(); delete socket; } m_listener.close(); } void Server::run() { if (m_wordList.size() == 0) return; cpp3ds::Clock pingClock; if (m_listener.listen(m_port) == cpp3ds::Socket::Done) { m_selector.add(m_listener); std::cout << "Started DrawAttack server on port " << m_port << "..." << std::endl; m_running = true; while (m_running) { // Make the selector wait for data on any socket if (m_selector.wait(cpp3ds::milliseconds(1000))) { if (m_selector.isReady(m_listener)) { cpp3ds::TcpSocket* socket = new cpp3ds::TcpSocket; if (m_listener.accept(*socket) == cpp3ds::Socket::Done) { std::cout << "client connected" << std::endl; // Add the new client to the clients list sendPlayerData(socket); socket->send(m_drawDataPacket); m_pingResponses[socket] = true; m_sockets.emplace_back(socket); m_selector.add(*socket); } else { delete socket; } } else { for (auto& socket : m_sockets) { if (m_selector.isReady(*socket)) { processSocket(socket); } } } } // Ping clients and check for previous response if (pingClock.getElapsedTime() >= cpp3ds::seconds(PING_TIMEOUT)) { cpp3ds::Packet packet; packet << NetworkEvent::Ping; for (auto& socket : m_sockets) { if (m_pingResponses[socket]) { socket->send(packet); m_pingResponses[socket] = false; } else { // Timed out socket std::cout << "A socket timed out." << std::endl; removeSocket(socket); } } pingClock.restart(); } if (m_mode == Play) { if (m_roundClock.getElapsedTime() >= cpp3ds::seconds(ROUND_DURATION)) { // Round time ended, nobody won cpp3ds::Packet packet; packet << NetworkEvent::RoundWord << m_currentWord << NetworkEvent::RoundFail; sendToAllSockets(packet); m_roundClock.restart(); m_mode = Wait; } if (m_roundTimeoutClock.getElapsedTime() >= cpp3ds::seconds(ROUND_TIMEOUT)) { // Drawer hasn't been active, so end round cpp3ds::Packet packet; packet << NetworkEvent::RoundWord << m_currentWord << NetworkEvent::RoundTimeout; sendToAllSockets(packet); m_roundClock.restart(); m_mode = Wait; } } else if (m_mode == Wait) { if (m_players.size() >= MIN_PLAYERS) { if (m_roundClock.getElapsedTime() >= cpp3ds::seconds(ROUND_INTERMISSION)) { Player drawer = getNextDrawer(); startRound(drawer, getNextWord(), ROUND_DURATION); } } } } } else { cpp3ds::err() << "Failed to listen on port " << m_port << std::endl; } } void Server::exit(std::string reason) { cpp3ds::Packet packet; if (reason.empty()) reason = "Shutdown by admin"; packet << NetworkEvent::ServerShutdown << reason; sendToAllSockets(packet); m_running = false; } void Server::sendToAllSockets(cpp3ds::Packet &packet) { for (auto& socket : m_sockets) { socket->send(packet); } } void Server::sendToAllPlayers(cpp3ds::Packet &packet) { for (auto& player : m_players) { player.first->send(packet); } } void Server::sendPlayerData(cpp3ds::TcpSocket* socket) { cpp3ds::Packet packet; packet << NetworkEvent::PlayerData; packet << static_cast<cpp3ds::Uint8>(m_players.size()); for (const auto& player : m_players) { packet << player.second.getName(); packet << player.second.getScore(); } socket->send(packet); } void Server::processSocket(cpp3ds::TcpSocket* socket) { cpp3ds::Packet packet; cpp3ds::Socket::Status status = socket->receive(packet); if (status == cpp3ds::Socket::Done) { cpp3ds::Packet packetSend; NetworkEvent event; while (NetworkEvent::packetToEvent(packet, event)) { if (!validateEvent(socket, event)) continue; switch(event.type) { case NetworkEvent::Version: if (event.server.message.compare(SERVER_VERSION) != 0) { packet.clear(); std::string message = _("Incompatible client version %s (needs %s)", event.server.message.c_str(), SERVER_VERSION); packet << NetworkEvent::ServerShutdown << message; socket->send(packet); removeSocket(socket); } break; case NetworkEvent::PlayerConnected: { std::cout << event.player.name << " connected." << std::endl; bool collision = false; for (auto& player : m_players) { if (event.player.name.compare(player.second.getName()) == 0) { collision = true; break; } } if (collision) { cpp3ds::Packet packet; packet << NetworkEvent::PlayerNameCollision << event.player.name; socket->send(packet); break; } Player player(event.player.name); m_players.emplace(socket, player); NetworkEvent::eventToPacket(event, packetSend); sendToAllSockets(packetSend); packetSend.clear(); if (m_players.size() < MIN_PLAYERS) { sendWaitForPlayers(socket, MIN_PLAYERS); } break; } case NetworkEvent::Text: { NetworkEvent::eventToPacket(event, packetSend); if (m_mode != Play) break; std::string word = event.text.value.toAnsiString(); std::transform(word.begin(), word.end(), word.begin(), ::tolower); if (word.compare(m_currentWord) == 0) { std::cout << event.text.name << " won!" << std::endl; packetSend << NetworkEvent::RoundWord << word << NetworkEvent::RoundWin << event.text.name; for (auto& player : m_players) { if (player.second.getName().compare(event.text.name) == 0) player.second.incrementScore(); if (player.first == m_currentDrawer) player.second.incrementScore(); } m_roundClock.restart(); m_mode = Wait; } break; } case NetworkEvent::DrawMove: case NetworkEvent::DrawEndline: m_drawDataPacket << event.type << event.draw.x << event.draw.y; NetworkEvent::eventToPacket(event, packetSend); m_roundTimeoutClock.restart(); break; case NetworkEvent::DrawClear: clearDrawData(); NetworkEvent::eventToPacket(event, packetSend); m_roundTimeoutClock.restart(); break; case NetworkEvent::DrawUndo: { m_drawDataPacket << event.type; NetworkEvent::eventToPacket(event, packetSend); m_roundTimeoutClock.restart(); break; } case NetworkEvent::RoundPass: packetSend << NetworkEvent::RoundWord << m_currentWord; NetworkEvent::eventToPacket(event, packetSend); m_roundClock.restart(); m_mode = Wait; break; case NetworkEvent::Ping: m_pingResponses[socket] = true; break; default: break; } } if (!packetSend.endOfPacket()) sendToAllSockets(packetSend); } else if (status == cpp3ds::Socket::Disconnected || status == cpp3ds::Socket::Error) { removeSocket(socket); } } bool Server::validateEvent(cpp3ds::TcpSocket* socket, const NetworkEvent &event) { switch (event.type) { case NetworkEvent::PlayerConnected: break; case NetworkEvent::RoundPass: case NetworkEvent::DrawMove: case NetworkEvent::DrawEndline: case NetworkEvent::DrawUndo: case NetworkEvent::DrawClear: if (m_currentDrawer != socket || m_mode == Wait) return false; break; default: break; } // Assume it's good if none of the above checks failed return true; } void Server::startRound(Player &drawer, std::string word, float duration) { std::cout << "Starting round. Drawer: " << drawer.getName() << " Word: " << word << std::endl; m_roundDuration = duration; m_currentWord = word; m_mode = Play; cpp3ds::Packet packet; packet << NetworkEvent::RoundStart << drawer.getName() << duration; sendToAllSockets(packet); // Send word to the drawer packet.clear(); packet << NetworkEvent::RoundWord << word; m_currentDrawer->send(packet); m_roundClock.restart(); m_roundTimeoutClock.restart(); clearDrawData(); } void Server::sendDrawData(cpp3ds::TcpSocket *socket) { } void Server::clearDrawData() { m_drawDataPacket.clear(); m_drawDataPacket << NetworkEvent::DrawData; } void Server::removeSocket(cpp3ds::TcpSocket *socket) { cpp3ds::Packet packet; std::string name; m_selector.remove(*socket); for (std::map<cpp3ds::TcpSocket*, Player>::iterator i = m_players.begin(); i != m_players.end(); i++) if (i->first == socket) { name = i->second.getName(); m_players.erase(i); break; } for (std::vector<cpp3ds::TcpSocket*>::iterator i = m_sockets.begin(); i != m_sockets.end(); i++) if (*i == socket) { m_sockets.erase(i); break; } delete socket; // If name is empty, it was just an idle (spectating) socket if (!name.empty()) { std::cout << "Player disconnected: " << name << std::endl; packet << NetworkEvent::PlayerDisconnected << name; if (m_players.size() < MIN_PLAYERS) { m_mode = Wait; packet << NetworkEvent::WaitForPlayers << MIN_PLAYERS; } sendToAllSockets(packet); } } void Server::sendWaitForPlayers(cpp3ds::TcpSocket *socket, float playersNeeded) { cpp3ds::Packet packet; packet << NetworkEvent::WaitForPlayers << playersNeeded; socket->send(packet); } const Player& Server::getNextDrawer() { if (m_currentDrawer) { bool found = false; for (auto& player : m_players) { if (found) { m_currentDrawer = player.first; return player.second; } if (player.first == m_currentDrawer) found = true; } } m_currentDrawer = m_players.begin()->first; return m_players.begin()->second; } std::string Server::getNextWord() { if (m_wordList.empty()) { if (m_wordListUsed.empty()) return "Error: No word list"; m_wordList = m_wordListUsed; m_wordListUsed.clear(); } auto iterator = m_wordList.begin(); std::advance(iterator, std::rand() % m_wordList.size()); std::string nextWord = *iterator; m_wordListUsed.push_back(nextWord); m_wordList.erase(iterator); return nextWord; } } // namespace DrawAttack
#include <fstream> #include "Server.hpp" #include "NetworkEvents.hpp" namespace DrawAttack { Server::Server(unsigned short port, std::string wordFilename) : m_port(port) , m_running(false) , m_wordFilename(wordFilename) , m_mode(Wait) , m_currentDrawer(nullptr) { std::ifstream wordFile(wordFilename); std::string line; if (wordFile.is_open()) { while (std::getline(wordFile, line)) { std::transform(line.begin(), line.end(), line.begin(), ::tolower); m_wordList.push_back(line); } wordFile.close(); } else { cpp3ds::err() << "Failed to open word file: " << wordFilename << std::endl; } clearDrawData(); } Server::~Server() { for (auto& socket : m_sockets) { socket->disconnect(); delete socket; } m_listener.close(); } void Server::run() { if (m_wordList.size() == 0) return; cpp3ds::Clock pingClock; if (m_listener.listen(m_port) == cpp3ds::Socket::Done) { m_selector.add(m_listener); std::cout << "Started DrawAttack server on port " << m_port << "..." << std::endl; m_running = true; while (m_running) { // Make the selector wait for data on any socket if (m_selector.wait(cpp3ds::milliseconds(1000))) { if (m_selector.isReady(m_listener)) { cpp3ds::TcpSocket* socket = new cpp3ds::TcpSocket; if (m_listener.accept(*socket) == cpp3ds::Socket::Done) { std::cout << "client connected" << std::endl; // Add the new client to the clients list sendPlayerData(socket); socket->send(m_drawDataPacket); m_pingResponses[socket] = true; m_sockets.emplace_back(socket); m_selector.add(*socket); } else { delete socket; } } else { for (auto& socket : m_sockets) { if (m_selector.isReady(*socket)) { processSocket(socket); } } } } // Ping clients and check for previous response if (pingClock.getElapsedTime() >= cpp3ds::seconds(PING_TIMEOUT)) { cpp3ds::Packet packet; packet << NetworkEvent::Ping; for (auto i = m_sockets.begin(); i != m_sockets.end();) { if (m_pingResponses[*i]) { (*i)->send(packet); m_pingResponses[*i] = false; i++; } else { // Timed out socket std::cout << "A socket timed out." << std::endl; removeSocket(*i); } } pingClock.restart(); } if (m_mode == Play) { if (m_roundClock.getElapsedTime() >= cpp3ds::seconds(ROUND_DURATION)) { // Round time ended, nobody won cpp3ds::Packet packet; packet << NetworkEvent::RoundWord << m_currentWord << NetworkEvent::RoundFail; sendToAllSockets(packet); m_roundClock.restart(); m_mode = Wait; } if (m_roundTimeoutClock.getElapsedTime() >= cpp3ds::seconds(ROUND_TIMEOUT)) { // Drawer hasn't been active, so end round cpp3ds::Packet packet; packet << NetworkEvent::RoundWord << m_currentWord << NetworkEvent::RoundTimeout; sendToAllSockets(packet); m_roundClock.restart(); m_mode = Wait; } } else if (m_mode == Wait) { if (m_players.size() >= MIN_PLAYERS) { if (m_roundClock.getElapsedTime() >= cpp3ds::seconds(ROUND_INTERMISSION)) { Player drawer = getNextDrawer(); startRound(drawer, getNextWord(), ROUND_DURATION); } } } } } else { cpp3ds::err() << "Failed to listen on port " << m_port << std::endl; } } void Server::exit(std::string reason) { cpp3ds::Packet packet; if (reason.empty()) reason = "Shutdown by admin"; packet << NetworkEvent::ServerShutdown << reason; sendToAllSockets(packet); m_running = false; } void Server::sendToAllSockets(cpp3ds::Packet &packet) { for (auto& socket : m_sockets) { socket->send(packet); } } void Server::sendToAllPlayers(cpp3ds::Packet &packet) { for (auto& player : m_players) { player.first->send(packet); } } void Server::sendPlayerData(cpp3ds::TcpSocket* socket) { cpp3ds::Packet packet; packet << NetworkEvent::PlayerData; packet << static_cast<cpp3ds::Uint8>(m_players.size()); for (const auto& player : m_players) { packet << player.second.getName(); packet << player.second.getScore(); } socket->send(packet); } void Server::processSocket(cpp3ds::TcpSocket* socket) { cpp3ds::Packet packet; cpp3ds::Socket::Status status = socket->receive(packet); if (status == cpp3ds::Socket::Done) { cpp3ds::Packet packetSend; NetworkEvent event; while (NetworkEvent::packetToEvent(packet, event)) { if (!validateEvent(socket, event)) continue; switch(event.type) { case NetworkEvent::Version: if (event.server.message.compare(SERVER_VERSION) != 0) { packet.clear(); std::string message = _("Incompatible client version %s (needs %s)", event.server.message.c_str(), SERVER_VERSION); packet << NetworkEvent::ServerShutdown << message; socket->send(packet); removeSocket(socket); } break; case NetworkEvent::PlayerConnected: { std::cout << event.player.name << " connected." << std::endl; bool collision = false; for (auto& player : m_players) { if (event.player.name.compare(player.second.getName()) == 0) { collision = true; break; } } if (collision) { cpp3ds::Packet packet; packet << NetworkEvent::PlayerNameCollision << event.player.name; socket->send(packet); break; } Player player(event.player.name); m_players.emplace(socket, player); NetworkEvent::eventToPacket(event, packetSend); sendToAllSockets(packetSend); packetSend.clear(); if (m_players.size() < MIN_PLAYERS) { sendWaitForPlayers(socket, MIN_PLAYERS); } break; } case NetworkEvent::Text: { NetworkEvent::eventToPacket(event, packetSend); if (m_mode != Play) break; std::string word = event.text.value.toAnsiString(); std::transform(word.begin(), word.end(), word.begin(), ::tolower); if (word.compare(m_currentWord) == 0) { std::cout << event.text.name << " won!" << std::endl; packetSend << NetworkEvent::RoundWord << word << NetworkEvent::RoundWin << event.text.name; for (auto& player : m_players) { if (player.second.getName().compare(event.text.name) == 0) player.second.incrementScore(); if (player.first == m_currentDrawer) player.second.incrementScore(); } m_roundClock.restart(); m_mode = Wait; } break; } case NetworkEvent::DrawMove: case NetworkEvent::DrawEndline: m_drawDataPacket << event.type << event.draw.x << event.draw.y; NetworkEvent::eventToPacket(event, packetSend); m_roundTimeoutClock.restart(); break; case NetworkEvent::DrawClear: clearDrawData(); NetworkEvent::eventToPacket(event, packetSend); m_roundTimeoutClock.restart(); break; case NetworkEvent::DrawUndo: { m_drawDataPacket << event.type; NetworkEvent::eventToPacket(event, packetSend); m_roundTimeoutClock.restart(); break; } case NetworkEvent::RoundPass: packetSend << NetworkEvent::RoundWord << m_currentWord; NetworkEvent::eventToPacket(event, packetSend); m_roundClock.restart(); m_mode = Wait; break; case NetworkEvent::Ping: m_pingResponses[socket] = true; break; default: break; } } if (!packetSend.endOfPacket()) sendToAllSockets(packetSend); } else if (status == cpp3ds::Socket::Disconnected || status == cpp3ds::Socket::Error) { removeSocket(socket); } } bool Server::validateEvent(cpp3ds::TcpSocket* socket, const NetworkEvent &event) { switch (event.type) { case NetworkEvent::PlayerConnected: break; case NetworkEvent::RoundPass: case NetworkEvent::DrawMove: case NetworkEvent::DrawEndline: case NetworkEvent::DrawUndo: case NetworkEvent::DrawClear: if (m_currentDrawer != socket || m_mode == Wait) return false; break; default: break; } // Assume it's good if none of the above checks failed return true; } void Server::startRound(Player &drawer, std::string word, float duration) { std::cout << "Starting round. Drawer: " << drawer.getName() << " Word: " << word << std::endl; m_roundDuration = duration; m_currentWord = word; m_mode = Play; cpp3ds::Packet packet; packet << NetworkEvent::RoundStart << drawer.getName() << duration; sendToAllSockets(packet); // Send word to the drawer packet.clear(); packet << NetworkEvent::RoundWord << word; m_currentDrawer->send(packet); m_roundClock.restart(); m_roundTimeoutClock.restart(); clearDrawData(); } void Server::sendDrawData(cpp3ds::TcpSocket *socket) { } void Server::clearDrawData() { m_drawDataPacket.clear(); m_drawDataPacket << NetworkEvent::DrawData; } void Server::removeSocket(cpp3ds::TcpSocket *socket) { cpp3ds::Packet packet; std::string name; m_selector.remove(*socket); for (auto i = m_players.begin(); i != m_players.end(); i++) if (i->first == socket) { name = i->second.getName(); m_players.erase(i); break; } for (auto i = m_sockets.begin(); i != m_sockets.end(); i++) if (*i == socket) { m_sockets.erase(i); break; } delete socket; // If name is empty, it was just an idle (spectating) socket if (!name.empty()) { std::cout << "Player disconnected: " << name << std::endl; packet << NetworkEvent::PlayerDisconnected << name; if (m_players.size() < MIN_PLAYERS) { m_mode = Wait; packet << NetworkEvent::WaitForPlayers << MIN_PLAYERS; } sendToAllSockets(packet); } } void Server::sendWaitForPlayers(cpp3ds::TcpSocket *socket, float playersNeeded) { cpp3ds::Packet packet; packet << NetworkEvent::WaitForPlayers << playersNeeded; socket->send(packet); } const Player& Server::getNextDrawer() { if (m_currentDrawer) { bool found = false; for (auto& player : m_players) { if (found) { m_currentDrawer = player.first; return player.second; } if (player.first == m_currentDrawer) found = true; } } m_currentDrawer = m_players.begin()->first; return m_players.begin()->second; } std::string Server::getNextWord() { if (m_wordList.empty()) { if (m_wordListUsed.empty()) return "Error: No word list"; m_wordList = m_wordListUsed; m_wordListUsed.clear(); } auto iterator = m_wordList.begin(); std::advance(iterator, std::rand() % m_wordList.size()); std::string nextWord = *iterator; m_wordListUsed.push_back(nextWord); m_wordList.erase(iterator); return nextWord; } } // namespace DrawAttack
Fix iteration bug causing seg fault
Fix iteration bug causing seg fault
C++
mit
Cruel/DrawAttack,cpp3ds/Pictionary3DS
dd9af2f18bda561ab8c2565687be161c33539c5a
deal.II/base/source/parsed_function.cc
deal.II/base/source/parsed_function.cc
//--------------------------------------------------------------------------- // $Id: function_parser.h 14594 2007-03-22 20:17:41Z bangerth $ // Version: $Name$ // // Copyright (C) 2007 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <base/parsed_function.h> #include <base/utilities.h> DEAL_II_NAMESPACE_OPEN namespace Functions { template <int dim> ParsedFunction<dim>::ParsedFunction (const unsigned int n_components, const double h) : AutoDerivativeFunction<dim>(h, n_components), function_object(n_components) {} template <int dim> void ParsedFunction<dim>::declare_parameters(ParameterHandler &prm, const unsigned int n_components) { Assert(n_components > 0, ExcZero()); std::string vnames; switch (dim) { case 1: vnames = "x,t"; break; case 2: vnames = "x,y,t"; break; case 3: vnames = "x,y,z,t"; break; default: AssertThrow(false, ExcNotImplemented()); break; } prm.declare_entry("Variable names", vnames, Patterns::Anything(), "The name of the variables as they will be used in the " "function, separated by ','."); // The expression of the function std::string expr = "0"; for (unsigned int i=1; i<n_components; ++i) expr += "; 0"; prm.declare_entry("Function expression", expr, Patterns::Anything(), "Separate vector valued expressions by ';' as ',' " "is used internally by the function parser."); prm.declare_entry("Function constants", "", Patterns::Anything(), "Any constant used inside the function which is not " "a variable name."); } template <int dim> void ParsedFunction<dim>::parse_parameters(ParameterHandler &prm) { std::string vnames = prm.get("Variable names"); std::string expression = prm.get("Function expression"); std::string constants_list = prm.get("Function constants"); std::vector<std::string> const_list = Utilities::split_string_list(constants_list, ','); std::map<std::string, double> constants; for(unsigned int i = 0; i < const_list.size(); ++i) { std::vector<std::string> this_c = Utilities::split_string_list(const_list[i], '='); AssertThrow(this_c.size() == 2, ExcMessage("Invalid format")); double tmp; AssertThrow( sscanf(this_c[1].c_str(), "%lf", &tmp), ExcMessage("Double number?")); constants[this_c[0]] = tmp; } constants["pi"] = numbers::PI; constants["Pi"] = numbers::PI; unsigned int nn = (Utilities::split_string_list(vnames)).size(); switch (nn) { case dim: // Time independent function function_object.initialize(vnames, expression, constants); break; case dim+1: // Time dependent function function_object.initialize(vnames, expression, constants, true); break; default: AssertThrow(false, ExcMessage("Not the correct size. Check your code.")); } } template <int dim> void ParsedFunction<dim>::vector_value (const Point<dim> &p, Vector<double> &values) const { function_object.vector_value(p, values); } template <int dim> double ParsedFunction<dim>::value (const Point<dim> &p, unsigned int comp) const { return function_object.value(p, comp); } template <int dim> void ParsedFunction<dim>::set_time (const double newtime) { function_object.set_time(newtime); AutoDerivativeFunction<dim>::set_time(newtime); } // Explicit instantiations template class ParsedFunction<1>; template class ParsedFunction<2>; template class ParsedFunction<3>; } DEAL_II_NAMESPACE_CLOSE
//--------------------------------------------------------------------------- // $Id: function_parser.h 14594 2007-03-22 20:17:41Z bangerth $ // Version: $Name$ // // Copyright (C) 2007, 2008 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <base/parsed_function.h> #include <base/utilities.h> #include <cstdio> DEAL_II_NAMESPACE_OPEN namespace Functions { template <int dim> ParsedFunction<dim>::ParsedFunction (const unsigned int n_components, const double h) : AutoDerivativeFunction<dim>(h, n_components), function_object(n_components) {} template <int dim> void ParsedFunction<dim>::declare_parameters(ParameterHandler &prm, const unsigned int n_components) { Assert(n_components > 0, ExcZero()); std::string vnames; switch (dim) { case 1: vnames = "x,t"; break; case 2: vnames = "x,y,t"; break; case 3: vnames = "x,y,z,t"; break; default: AssertThrow(false, ExcNotImplemented()); break; } prm.declare_entry("Variable names", vnames, Patterns::Anything(), "The name of the variables as they will be used in the " "function, separated by ','."); // The expression of the function std::string expr = "0"; for (unsigned int i=1; i<n_components; ++i) expr += "; 0"; prm.declare_entry("Function expression", expr, Patterns::Anything(), "Separate vector valued expressions by ';' as ',' " "is used internally by the function parser."); prm.declare_entry("Function constants", "", Patterns::Anything(), "Any constant used inside the function which is not " "a variable name."); } template <int dim> void ParsedFunction<dim>::parse_parameters(ParameterHandler &prm) { std::string vnames = prm.get("Variable names"); std::string expression = prm.get("Function expression"); std::string constants_list = prm.get("Function constants"); std::vector<std::string> const_list = Utilities::split_string_list(constants_list, ','); std::map<std::string, double> constants; for(unsigned int i = 0; i < const_list.size(); ++i) { std::vector<std::string> this_c = Utilities::split_string_list(const_list[i], '='); AssertThrow(this_c.size() == 2, ExcMessage("Invalid format")); double tmp; AssertThrow( sscanf(this_c[1].c_str(), "%lf", &tmp), ExcMessage("Double number?")); constants[this_c[0]] = tmp; } constants["pi"] = numbers::PI; constants["Pi"] = numbers::PI; unsigned int nn = (Utilities::split_string_list(vnames)).size(); switch (nn) { case dim: // Time independent function function_object.initialize(vnames, expression, constants); break; case dim+1: // Time dependent function function_object.initialize(vnames, expression, constants, true); break; default: AssertThrow(false, ExcMessage("Not the correct size. Check your code.")); } } template <int dim> void ParsedFunction<dim>::vector_value (const Point<dim> &p, Vector<double> &values) const { function_object.vector_value(p, values); } template <int dim> double ParsedFunction<dim>::value (const Point<dim> &p, unsigned int comp) const { return function_object.value(p, comp); } template <int dim> void ParsedFunction<dim>::set_time (const double newtime) { function_object.set_time(newtime); AutoDerivativeFunction<dim>::set_time(newtime); } // Explicit instantiations template class ParsedFunction<1>; template class ParsedFunction<2>; template class ParsedFunction<3>; } DEAL_II_NAMESPACE_CLOSE
Patch by Dima Sorkin: Include cstdio for sscanf.
Patch by Dima Sorkin: Include cstdio for sscanf. git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@16757 0785d39b-7218-0410-832d-ea1e28bc413d
C++
lgpl-2.1
JaeryunYim/dealii,sriharisundar/dealii,YongYang86/dealii,danshapero/dealii,EGP-CIG-REU/dealii,sairajat/dealii,lue/dealii,shakirbsm/dealii,lue/dealii,johntfoster/dealii,andreamola/dealii,flow123d/dealii,lue/dealii,kalj/dealii,mac-a/dealii,pesser/dealii,ibkim11/dealii,adamkosik/dealii,danshapero/dealii,jperryhouts/dealii,mac-a/dealii,danshapero/dealii,lue/dealii,mac-a/dealii,naliboff/dealii,shakirbsm/dealii,ESeNonFossiIo/dealii,flow123d/dealii,rrgrove6/dealii,andreamola/dealii,pesser/dealii,lpolster/dealii,naliboff/dealii,mac-a/dealii,lpolster/dealii,YongYang86/dealii,Arezou-gh/dealii,shakirbsm/dealii,JaeryunYim/dealii,Arezou-gh/dealii,flow123d/dealii,maieneuro/dealii,shakirbsm/dealii,naliboff/dealii,sairajat/dealii,pesser/dealii,angelrca/dealii,gpitton/dealii,natashasharma/dealii,jperryhouts/dealii,lpolster/dealii,nicolacavallini/dealii,natashasharma/dealii,andreamola/dealii,pesser/dealii,adamkosik/dealii,gpitton/dealii,sriharisundar/dealii,ESeNonFossiIo/dealii,YongYang86/dealii,mac-a/dealii,EGP-CIG-REU/dealii,Arezou-gh/dealii,johntfoster/dealii,spco/dealii,kalj/dealii,nicolacavallini/dealii,msteigemann/dealii,sairajat/dealii,msteigemann/dealii,EGP-CIG-REU/dealii,danshapero/dealii,flow123d/dealii,natashasharma/dealii,spco/dealii,andreamola/dealii,nicolacavallini/dealii,nicolacavallini/dealii,ibkim11/dealii,johntfoster/dealii,maieneuro/dealii,YongYang86/dealii,Arezou-gh/dealii,johntfoster/dealii,msteigemann/dealii,danshapero/dealii,mtezzele/dealii,angelrca/dealii,danshapero/dealii,kalj/dealii,shakirbsm/dealii,spco/dealii,sairajat/dealii,lue/dealii,EGP-CIG-REU/dealii,YongYang86/dealii,gpitton/dealii,rrgrove6/dealii,jperryhouts/dealii,spco/dealii,danshapero/dealii,sriharisundar/dealii,naliboff/dealii,maieneuro/dealii,mac-a/dealii,ibkim11/dealii,JaeryunYim/dealii,msteigemann/dealii,spco/dealii,gpitton/dealii,msteigemann/dealii,ibkim11/dealii,mtezzele/dealii,adamkosik/dealii,rrgrove6/dealii,kalj/dealii,msteigemann/dealii,spco/dealii,shakirbsm/dealii,ibkim11/dealii,lpolster/dealii,natashasharma/dealii,mtezzele/dealii,maieneuro/dealii,gpitton/dealii,YongYang86/dealii,rrgrove6/dealii,angelrca/dealii,flow123d/dealii,kalj/dealii,jperryhouts/dealii,mtezzele/dealii,mtezzele/dealii,ESeNonFossiIo/dealii,mtezzele/dealii,mac-a/dealii,spco/dealii,ibkim11/dealii,nicolacavallini/dealii,nicolacavallini/dealii,ESeNonFossiIo/dealii,rrgrove6/dealii,Arezou-gh/dealii,maieneuro/dealii,ibkim11/dealii,msteigemann/dealii,rrgrove6/dealii,adamkosik/dealii,sriharisundar/dealii,andreamola/dealii,sriharisundar/dealii,mtezzele/dealii,sriharisundar/dealii,maieneuro/dealii,EGP-CIG-REU/dealii,shakirbsm/dealii,rrgrove6/dealii,johntfoster/dealii,angelrca/dealii,andreamola/dealii,adamkosik/dealii,angelrca/dealii,flow123d/dealii,jperryhouts/dealii,JaeryunYim/dealii,naliboff/dealii,ESeNonFossiIo/dealii,johntfoster/dealii,naliboff/dealii,sriharisundar/dealii,kalj/dealii,sairajat/dealii,naliboff/dealii,ESeNonFossiIo/dealii,adamkosik/dealii,natashasharma/dealii,lue/dealii,ESeNonFossiIo/dealii,lpolster/dealii,jperryhouts/dealii,adamkosik/dealii,maieneuro/dealii,pesser/dealii,lpolster/dealii,EGP-CIG-REU/dealii,flow123d/dealii,EGP-CIG-REU/dealii,gpitton/dealii,JaeryunYim/dealii,sairajat/dealii,kalj/dealii,angelrca/dealii,angelrca/dealii,pesser/dealii,lpolster/dealii,natashasharma/dealii,nicolacavallini/dealii,natashasharma/dealii,lue/dealii,Arezou-gh/dealii,jperryhouts/dealii,YongYang86/dealii,Arezou-gh/dealii,sairajat/dealii,andreamola/dealii,JaeryunYim/dealii,JaeryunYim/dealii,pesser/dealii,gpitton/dealii,johntfoster/dealii
0088a9b823bd82b3e8c4999661cdf31435f5e6e5
src/Plugins/stocks.cpp
src/Plugins/stocks.cpp
#include "./include/http.hpp" #include "./include/json.hpp" namespace Stocks { std::string get_stock_summary(const std::string& q) { std::string response = ""; if ( MyHTTP::get("https://www.google.com/finance/info?q=" + q.substr(0, q.find(" ")), response) ) { response.erase(0, 5); // erase first five characters. response.erase(response.length()-2); // and last two characters. nlohmann::json data = nlohmann::json::parse(response); return data["t"].get<std::string>() + " on " + data["e"].get<std::string>() + " was last at: $" + data["l"].get<std::string>() + ". Percent Day Change: " + data["cp"].get<std::string>(); } return "Failed to look up: " + q; } }
#include "./include/http.hpp" #include "./include/json.hpp" #include <stdexcept> namespace Stocks { std::string get_stock_summary(const std::string& q) { std::string response = ""; try { if ( MyHTTP::get("https://www.google.com/finance/info?q=" + MyHTTP::uri_encode(q.substr(0, q.find(" ")) ), response) ) { response.erase(0, 5); // erase first five characters. response.erase(response.length()-2); // and last two characters. nlohmann::json data = nlohmann::json::parse(response); return data["t"].get<std::string>() + " on " + data["e"].get<std::string>() + " was last at: $" + data["l"].get<std::string>() + ". Percent Day Change: " + data["cp"].get<std::string>(); } } catch (std::exception& e) { std::cerr << "Failed in get_stock_summary(): " << e.what() << '\n'; } return "Failed to look up: " + q; } }
add exception handling to stocks plugin
add exception handling to stocks plugin
C++
mit
c650/irc-bot-framework,c650/irc-bot-framework
66e7a979996b89918f7a7c1641c275b0a84b7938
unittests/MC/AsmStreamerTest.cpp
unittests/MC/AsmStreamerTest.cpp
//===- AsmStreamerTest.cpp - Triple unit tests ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCValue.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { // Helper class. class StringAsmStreamer { std::string Str; raw_string_ostream OS; MCContext Context; MCStreamer *Streamer; public: StringAsmStreamer() : OS(Str), Streamer(createAsmStreamer(Context, OS)) {} ~StringAsmStreamer() { delete Streamer; } MCContext &getContext() { return Context; } MCStreamer &getStreamer() { return *Streamer; } const std::string &getString() { Streamer->Finish(); return Str; } }; TEST(AsmStreamer, EmptyOutput) { StringAsmStreamer S; EXPECT_EQ("", S.getString()); } TEST(AsmStreamer, Sections) { StringAsmStreamer S; MCSection *Sec0 = S.getContext().GetSection("foo"); S.getStreamer().SwitchSection(Sec0); EXPECT_EQ(".section foo\n", S.getString()); } TEST(AsmStreamer, Values) { StringAsmStreamer S; MCSection *Sec0 = S.getContext().GetSection("foo"); MCSymbol *A = S.getContext().CreateSymbol("a"); MCSymbol *B = S.getContext().CreateSymbol("b"); S.getStreamer().SwitchSection(Sec0); S.getStreamer().EmitLabel(A); S.getStreamer().EmitLabel(B); S.getStreamer().EmitValue(MCValue::get(A, B, 10), 1); S.getStreamer().EmitValue(MCValue::get(A, B, 10), 2); S.getStreamer().EmitValue(MCValue::get(A, B, 10), 4); S.getStreamer().EmitValue(MCValue::get(A, B, 10), 8); EXPECT_EQ(".section foo\n\ a:\n\ b:\n\ .byte a - b + 10\n\ .short a - b + 10\n\ .long a - b + 10\n\ .quad a - b + 10\n", S.getString()); } TEST(AsmStreamer, Align) { StringAsmStreamer S; MCSection *Sec0 = S.getContext().GetSection("foo"); S.getStreamer().SwitchSection(Sec0); S.getStreamer().EmitValueToAlignment(4); S.getStreamer().EmitValueToAlignment(4, /*Value=*/12, /*ValueSize=*/2); S.getStreamer().EmitValueToAlignment(8, /*Value=*/12, /*ValueSize=*/4, /*MaxBytesToEmit=*/24); EXPECT_EQ(".section foo\n\ .p2align 2, 0\n\ .p2alignw 2, 12\n\ .p2alignl 3, 12, 24\n", S.getString()); } TEST(AsmStreamer, Org) { StringAsmStreamer S; MCSection *Sec0 = S.getContext().GetSection("foo"); S.getStreamer().SwitchSection(Sec0); MCSymbol *A = S.getContext().CreateSymbol("a"); S.getStreamer().EmitLabel(A); S.getStreamer().EmitValueToOffset(MCValue::get(A, 0, 4), 32); EXPECT_EQ(".section foo\n\ a:\n\ .org a + 4, 32\n", S.getString()); } }
//===- AsmStreamerTest.cpp - Triple unit tests ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCValue.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { // Helper class. class StringAsmStreamer { std::string Str; raw_string_ostream OS; MCContext Context; MCStreamer *Streamer; public: StringAsmStreamer() : OS(Str), Streamer(createAsmStreamer(Context, OS)) {} ~StringAsmStreamer() { delete Streamer; } MCContext &getContext() { return Context; } MCStreamer &getStreamer() { return *Streamer; } const std::string &getString() { Streamer->Finish(); return Str; } }; TEST(AsmStreamer, EmptyOutput) { StringAsmStreamer S; EXPECT_EQ("", S.getString()); } TEST(AsmStreamer, Sections) { StringAsmStreamer S; MCSection *Sec0 = MCSection::Create("foo", S.getContext()); S.getStreamer().SwitchSection(Sec0); EXPECT_EQ(".section foo\n", S.getString()); } TEST(AsmStreamer, Values) { StringAsmStreamer S; MCSection *Sec0 = MCSection::Create("foo", S.getContext()); MCSymbol *A = S.getContext().CreateSymbol("a"); MCSymbol *B = S.getContext().CreateSymbol("b"); S.getStreamer().SwitchSection(Sec0); S.getStreamer().EmitLabel(A); S.getStreamer().EmitLabel(B); S.getStreamer().EmitValue(MCValue::get(A, B, 10), 1); S.getStreamer().EmitValue(MCValue::get(A, B, 10), 2); S.getStreamer().EmitValue(MCValue::get(A, B, 10), 4); S.getStreamer().EmitValue(MCValue::get(A, B, 10), 8); EXPECT_EQ(".section foo\n\ a:\n\ b:\n\ .byte a - b + 10\n\ .short a - b + 10\n\ .long a - b + 10\n\ .quad a - b + 10\n", S.getString()); } TEST(AsmStreamer, Align) { StringAsmStreamer S; MCSection *Sec0 = MCSection::Create("foo", S.getContext()); S.getStreamer().SwitchSection(Sec0); S.getStreamer().EmitValueToAlignment(4); S.getStreamer().EmitValueToAlignment(4, /*Value=*/12, /*ValueSize=*/2); S.getStreamer().EmitValueToAlignment(8, /*Value=*/12, /*ValueSize=*/4, /*MaxBytesToEmit=*/24); EXPECT_EQ(".section foo\n\ .p2align 2, 0\n\ .p2alignw 2, 12\n\ .p2alignl 3, 12, 24\n", S.getString()); } TEST(AsmStreamer, Org) { StringAsmStreamer S; MCSection *Sec0 = MCSection::Create("foo", S.getContext()); S.getStreamer().SwitchSection(Sec0); MCSymbol *A = S.getContext().CreateSymbol("a"); S.getStreamer().EmitLabel(A); S.getStreamer().EmitValueToOffset(MCValue::get(A, 0, 4), 32); EXPECT_EQ(".section foo\n\ a:\n\ .org a + 4, 32\n", S.getString()); } }
Adjust unit test for the MCSection changes.
Adjust unit test for the MCSection changes. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@77714 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm
78b331766ab66827165549fdd6b62db87305c750
src/TestimonySource.cc
src/TestimonySource.cc
// See the file in the main distribution directory for copyright. #include <zeek/zeek-config.h> #include "TestimonySource.h" #include <zeek/iosource/Packet.h> #include <zeek/iosource/BPF_Program.h> #include <unistd.h> #include <zeek/Event.h> using namespace ZEEK_IOSOURCE_NS::testimony; TestimonySource::~TestimonySource() { Close(); } void TestimonySource::Open() { OpenLive(); } void TestimonySource::Close() { //temporary_queue_writer will be deleted automatically by thread manager testimony_close(td); Closed(); } void TestimonySource::OpenLive() { int res; const char *fanout_str = getenv("TESTIMONY_FANOUT_ID"); uint32_t fanout_id; res = testimony_connect(&td, props.path.c_str()); if ( res < 0 ) { Error("testimony_connect: " + std::string(strerror(-res))); return; } if ( fanout_str ) { sscanf(fanout_str, "%u", &fanout_id); testimony_conn(td)->fanout_index = fanout_id; } res = testimony_init(td); if ( res < 0 ) { Error("testimony_init: " + std::string(testimony_error(td)) + strerror(-res)); return; } testimony_iter_init(&td_iter); props.selectable_fd = -1; props.link_type = DLT_EN10MB; props.is_live = true; Opened(props); } bool TestimonySource::ExtractNextPacket(Packet* pkt) { const u_char *data; struct timeval tmp_timeval; const tpacket3_hdr *packet; while (true) { if ( (packet = testimony_iter_next(td_iter)) == NULL ) { testimony_return_block(td, block); int res = testimony_get_block(td, 0, &block); if ( res == 0 && !block ) { // Timeout continue; } if ( res < 0 ) { //Error("testimony_get_block:" + std::string(testimony_error(td)) + strerror(-res)); return false; Close(); } testimony_iter_reset(td_iter, block); } else { // Queue the packet tmp_timeval.tv_sec = packet->tp_sec; tmp_timeval.tv_usec = packet->tp_nsec / 1000; data = (u_char *) packet + packet->tp_mac; pkt->Init(props.link_type, &tmp_timeval, packet->tp_snaplen, packet->tp_len, data); if(packet->tp_snaplen == 0 || packet->tp_len == 0) { Error("empty packet header"); return false; } return true; ++stats.received; stats.bytes_received += packet->tp_len; } } return false; } void TestimonySource::DoneWithPacket() { } bool TestimonySource::PrecompileFilter(int index, const std::string& filter) { // Nothing to do. Packet filters are configured on // testimony daemon side return true; } bool TestimonySource::SetFilter(int index) { return true; } void TestimonySource::Statistics(Stats* s) { s->received = stats.received; s->bytes_received = stats.bytes_received; // TODO: get this information from the daemon s->link = stats.received; s->dropped = 0; } ZEEK_IOSOURCE_NS::PktSrc* TestimonySource::Instantiate(const std::string& path, bool is_live) { return new TestimonySource(path, is_live); }
// See the file in the main distribution directory for copyright. #include <zeek/zeek-config.h> #include "TestimonySource.h" #include <zeek/iosource/Packet.h> #include <zeek/iosource/BPF_Program.h> #include <unistd.h> #include <zeek/Event.h> using namespace ZEEK_IOSOURCE_NS::testimony; TestimonySource::~TestimonySource() { Close(); } void TestimonySource::Open() { OpenLive(); } void TestimonySource::Close() { //temporary_queue_writer will be deleted automatically by thread manager testimony_close(td); Closed(); } void TestimonySource::OpenLive() { int res; const char *fanout_str = getenv("TESTIMONY_FANOUT_ID"); uint32_t fanout_id; res = testimony_connect(&td, props.path.c_str()); if ( res < 0 ) { Error("testimony_connect: " + std::string(strerror(-res))); return; } if ( fanout_str ) { sscanf(fanout_str, "%u", &fanout_id); testimony_conn(td)->fanout_index = fanout_id; } res = testimony_init(td); if ( res < 0 ) { Error("testimony_init: " + std::string(testimony_error(td)) + strerror(-res)); return; } testimony_iter_init(&td_iter); props.selectable_fd = -1; props.link_type = DLT_EN10MB; props.is_live = true; Opened(props); } bool TestimonySource::ExtractNextPacket(Packet* pkt) { const u_char *data; struct timeval tmp_timeval; const tpacket3_hdr *packet; while (true) { if ( (packet = testimony_iter_next(td_iter)) == NULL ) { testimony_return_block(td, block); int res = testimony_get_block(td, 0, &block); if ( res == 0 && !block ) { // Timeout continue; } if ( res < 0 ) { //Error("testimony_get_block:" + std::string(testimony_error(td)) + strerror(-res)); return false; Close(); } testimony_iter_reset(td_iter, block); } else { // Queue the packet tmp_timeval.tv_sec = packet->tp_sec; tmp_timeval.tv_usec = packet->tp_nsec / 1000; data = (u_char *) packet + packet->tp_mac; pkt->Init(props.link_type, &tmp_timeval, packet->tp_snaplen, packet->tp_len, data); if(packet->tp_snaplen == 0 || packet->tp_len == 0) { Error("empty packet header"); return false; } ++stats.received; stats.bytes_received += packet->tp_len; return true; } } return false; } void TestimonySource::DoneWithPacket() { } bool TestimonySource::PrecompileFilter(int index, const std::string& filter) { // Nothing to do. Packet filters are configured on // testimony daemon side return true; } bool TestimonySource::SetFilter(int index) { return true; } void TestimonySource::Statistics(Stats* s) { s->received = stats.received; s->bytes_received = stats.bytes_received; // TODO: get this information from the daemon s->link = stats.received; s->dropped = 0; } ZEEK_IOSOURCE_NS::PktSrc* TestimonySource::Instantiate(const std::string& path, bool is_live) { return new TestimonySource(path, is_live); }
Fix broken stats reporting
Fix broken stats reporting Since the function was returning before setting the stats, pkts_proc and bytes_recv are always 0. Moving the return to after setting the stats results in the values being shown in stats.log
C++
bsd-2-clause
MalakhatkoVadym/zeek-testimony-plugin,MalakhatkoVadym/zeek-testimony-plugin
355e4ba60640724c4325f248e19982ec4e8bf4f4
generators/utilities/src/main/resources/csrc/emulator.cc
generators/utilities/src/main/resources/csrc/emulator.cc
// See LICENSE.SiFive for license details. // See LICENSE.Berkeley for license details. #if VM_TRACE #include <memory> #if CY_FST_TRACE #include "verilated_fst_c.h" #else #include "verilated.h" #include "verilated_vcd_c.h" #endif // CY_FST_TRACE #endif // VM_TRACE #include <fesvr/dtm.h> #include <fesvr/tsi.h> #include "remote_bitbang.h" #include <iostream> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> // For option parsing, which is split across this file, Verilog, and // FESVR's HTIF, a few external files must be pulled in. The list of // files and what they provide is enumerated: // // $RISCV/include/fesvr/htif.h: // defines: // - HTIF_USAGE_OPTIONS // - HTIF_LONG_OPTIONS_OPTIND // - HTIF_LONG_OPTIONS // $(ROCKETCHIP_DIR)/generated-src(-debug)?/$(CONFIG).plusArgs: // defines: // - PLUSARG_USAGE_OPTIONS // variables: // - static const char * verilog_plusargs extern tsi_t* tsi; extern dtm_t* dtm; extern remote_bitbang_t * jtag; static uint64_t trace_count = 0; bool verbose = false; bool done_reset = false; void handle_sigterm(int sig) { dtm->stop(); } double sc_time_stamp() { return trace_count; } static void usage(const char * program_name) { printf("Usage: %s [EMULATOR OPTION]... [VERILOG PLUSARG]... [HOST OPTION]... BINARY [TARGET OPTION]...\n", program_name); fputs("\ Run a BINARY on the Rocket Chip emulator.\n\ \n\ Mandatory arguments to long options are mandatory for short options too.\n\ \n\ EMULATOR OPTIONS\n\ -c, --cycle-count Print the cycle count before exiting\n\ +cycle-count\n\ -h, --help Display this help and exit\n\ -m, --max-cycles=CYCLES Kill the emulation after CYCLES\n\ +max-cycles=CYCLES\n\ -s, --seed=SEED Use random number seed SEED\n\ -r, --rbb-port=PORT Use PORT for remote bit bang (with OpenOCD and GDB) \n\ If not specified, a random port will be chosen\n\ automatically.\n\ -V, --verbose Enable all Chisel printfs (cycle-by-cycle info)\n\ +verbose\n\ ", stdout); #if VM_TRACE == 0 fputs("\ \n\ EMULATOR DEBUG OPTIONS (only supported in debug build -- try `make debug`)\n", stdout); #endif fputs("\ -v, --vcd=FILE, Write vcd trace to FILE (or '-' for stdout)\n\ -x, --dump-start=CYCLE Start VCD tracing at CYCLE\n\ +dump-start\n\ ", stdout); fputs("\n" PLUSARG_USAGE_OPTIONS, stdout); fputs("\n" HTIF_USAGE_OPTIONS, stdout); printf("\n" "EXAMPLES\n" " - run a bare metal test:\n" " %s $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add\n" " - run a bare metal test showing cycle-by-cycle information:\n" " %s +verbose $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add 2>&1 | spike-dasm\n" #if VM_TRACE " - run a bare metal test to generate a VCD waveform:\n" " %s -v rv64ui-p-add.vcd $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add\n" #endif " - run an ELF (you wrote, called 'hello') using the proxy kernel:\n" " %s pk hello\n", program_name, program_name, program_name #if VM_TRACE , program_name #endif ); } int main(int argc, char** argv) { unsigned random_seed = (unsigned)time(NULL) ^ (unsigned)getpid(); uint64_t max_cycles = -1; int ret = 0; bool print_cycles = false; // Port numbers are 16 bit unsigned integers. uint16_t rbb_port = 0; #if VM_TRACE const char* vcdfile_name = NULL; FILE * vcdfile = NULL; uint64_t start = 0; #endif int verilog_plusargs_legal = 1; opterr = 1; while (1) { static struct option long_options[] = { {"cycle-count", no_argument, 0, 'c' }, {"help", no_argument, 0, 'h' }, {"max-cycles", required_argument, 0, 'm' }, {"seed", required_argument, 0, 's' }, {"rbb-port", required_argument, 0, 'r' }, {"verbose", no_argument, 0, 'V' }, {"permissive", no_argument, 0, 'p' }, {"permissive-off", no_argument, 0, 'o' }, #if VM_TRACE {"vcd", required_argument, 0, 'v' }, {"dump-start", required_argument, 0, 'x' }, #endif HTIF_LONG_OPTIONS }; int option_index = 0; #if VM_TRACE int c = getopt_long(argc, argv, "-chm:s:r:v:Vx:po", long_options, &option_index); #else int c = getopt_long(argc, argv, "-chm:s:r:Vpo", long_options, &option_index); #endif if (c == -1) break; retry: switch (c) { // Process long and short EMULATOR options case '?': usage(argv[0]); return 1; case 'c': print_cycles = true; break; case 'h': usage(argv[0]); return 0; case 'm': max_cycles = atoll(optarg); break; case 's': random_seed = atoi(optarg); break; case 'r': rbb_port = atoi(optarg); break; case 'V': verbose = true; break; case 'p': opterr = 0; break; case 'o': opterr = 1; break; #if VM_TRACE case 'v': { vcdfile_name = optarg; vcdfile = strcmp(optarg, "-") == 0 ? stdout : fopen(optarg, "w"); if (!vcdfile) { std::cerr << "Unable to open " << optarg << " for VCD write\n"; return 1; } break; } case 'x': start = atoll(optarg); break; #endif // Process legacy '+' EMULATOR arguments by replacing them with // their getopt equivalents case 1: { std::string arg = optarg; if (arg.substr(0, 1) != "+") { optind--; goto done_processing; } if (arg == "+verbose") c = 'V'; else if (arg.substr(0, 12) == "+max-cycles=") { c = 'm'; optarg = optarg+12; } #if VM_TRACE else if (arg.substr(0, 12) == "+dump-start=") { c = 'x'; optarg = optarg+12; } #endif else if (arg.substr(0, 12) == "+cycle-count") c = 'c'; else if (arg == "+permissive") c = 'p'; else if (arg == "+permissive-off") c = 'o'; // If we don't find a legacy '+' EMULATOR argument, it still could be // a VERILOG_PLUSARG and not an error. else if (verilog_plusargs_legal) { const char ** plusarg = &verilog_plusargs[0]; int legal_verilog_plusarg = 0; while (*plusarg && (legal_verilog_plusarg == 0)){ if (arg.substr(1, strlen(*plusarg)) == *plusarg) { legal_verilog_plusarg = 1; } plusarg ++; } if (!legal_verilog_plusarg) { verilog_plusargs_legal = 0; } else { c = 'P'; } goto retry; } // If we STILL don't find a legacy '+' argument, it still could be // an HTIF (HOST) argument and not an error. If this is the case, then // we're done processing EMULATOR and VERILOG arguments. else { static struct option htif_long_options [] = { HTIF_LONG_OPTIONS }; struct option * htif_option = &htif_long_options[0]; while (htif_option->name) { if (arg.substr(1, strlen(htif_option->name)) == htif_option->name) { optind--; goto done_processing; } htif_option++; } if(opterr) { std::cerr << argv[0] << ": invalid plus-arg (Verilog or HTIF) \"" << arg << "\"\n"; c = '?'; } else { c = 'p'; } } goto retry; } case 'P': break; // Nothing to do here, Verilog PlusArg // Realize that we've hit HTIF (HOST) arguments or error out default: if (c >= HTIF_LONG_OPTIONS_OPTIND) { optind--; goto done_processing; } c = '?'; goto retry; } } done_processing: if (optind == argc) { std::cerr << "No binary specified for emulator\n"; usage(argv[0]); return 1; } int htif_argc = 1 + argc - optind; char** htif_argv = (char **) malloc((htif_argc) * sizeof (char *)); htif_argv[0] = argv[0]; for (int i = 1; optind < argc;) htif_argv[i++] = argv[optind++]; if (verbose) fprintf(stderr, "using random seed %u\n", random_seed); srand(random_seed); srand48(random_seed); Verilated::randReset(2); Verilated::commandArgs(htif_argc, htif_argv); TEST_HARNESS *tile = new TEST_HARNESS; #if VM_TRACE Verilated::traceEverOn(true); // Verilator must compute traced signals #if CY_FST_TRACE std::unique_ptr<VerilatedFstC> tfp(new VerilatedFstC); #else std::unique_ptr<VerilatedVcdFILE> vcdfd(new VerilatedVcdFILE(vcdfile)); std::unique_ptr<VerilatedVcdC> tfp(new VerilatedVcdC(vcdfd.get())); #endif // CY_FST_TRACE if (vcdfile_name) { tile->trace(tfp.get(), 99); // Trace 99 levels of hierarchy tfp->open(vcdfile_name); } #endif // VM_TRACE // RocketChip currently only supports RBB port 0, so this needs to stay here jtag = new remote_bitbang_t(rbb_port); signal(SIGTERM, handle_sigterm); bool dump; // start reset off low so a rising edge triggers async reset tile->reset = 0; tile->clock = 0; tile->eval(); // reset for several cycles to handle pipelined reset for (int i = 0; i < 100; i++) { tile->reset = 1; tile->clock = 0; tile->eval(); #if VM_TRACE dump = tfp && trace_count >= start; if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2)); #endif tile->clock = 1; tile->eval(); #if VM_TRACE if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2 + 1)); #endif trace_count ++; } tile->reset = 0; done_reset = true; do { tile->clock = 0; tile->eval(); #if VM_TRACE dump = tfp && trace_count >= start; if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2)); #endif tile->clock = 1; tile->eval(); #if VM_TRACE if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2 + 1)); #endif trace_count++; } // for verilator multithreading. need to do 1 loop before checking if // tsi exists, since tsi is created by verilated thread on the first // serial_tick. while ((!dtm || !dtm->done()) && (!jtag || !jtag->done()) && (!tsi || !tsi->done()) && !tile->io_success && trace_count < max_cycles); #if VM_TRACE if (tfp) tfp->close(); if (vcdfile) fclose(vcdfile); #endif if (dtm && dtm->exit_code()) { fprintf(stderr, "*** FAILED *** via dtm (code = %d, seed %d) after %ld cycles\n", dtm->exit_code(), random_seed, trace_count); ret = dtm->exit_code(); } else if (tsi && tsi->exit_code()) { fprintf(stderr, "*** FAILED *** (code = %d, seed %d) after %ld cycles\n", tsi->exit_code(), random_seed, trace_count); ret = tsi->exit_code(); } else if (jtag && jtag->exit_code()) { fprintf(stderr, "*** FAILED *** via jtag (code = %d, seed %d) after %ld cycles\n", jtag->exit_code(), random_seed, trace_count); ret = jtag->exit_code(); } else if (trace_count == max_cycles) { fprintf(stderr, "*** FAILED *** via trace_count (timeout, seed %d) after %ld cycles\n", random_seed, trace_count); ret = 2; } else if (verbose || print_cycles) { fprintf(stderr, "*** PASSED *** Completed after %ld cycles\n", trace_count); } if (dtm) delete dtm; if (tsi) delete tsi; if (jtag) delete jtag; if (tile) delete tile; if (htif_argv) free(htif_argv); return ret; }
// See LICENSE.SiFive for license details. // See LICENSE.Berkeley for license details. #if VM_TRACE #include <memory> #if CY_FST_TRACE #include "verilated_fst_c.h" #else #include "verilated.h" #include "verilated_vcd_c.h" #endif // CY_FST_TRACE #endif // VM_TRACE #include <fesvr/dtm.h> #include <fesvr/tsi.h> #include "remote_bitbang.h" #include <iostream> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> // For option parsing, which is split across this file, Verilog, and // FESVR's HTIF, a few external files must be pulled in. The list of // files and what they provide is enumerated: // // $RISCV/include/fesvr/htif.h: // defines: // - HTIF_USAGE_OPTIONS // - HTIF_LONG_OPTIONS_OPTIND // - HTIF_LONG_OPTIONS // $(ROCKETCHIP_DIR)/generated-src(-debug)?/$(CONFIG).plusArgs: // defines: // - PLUSARG_USAGE_OPTIONS // variables: // - static const char * verilog_plusargs extern tsi_t* tsi; extern dtm_t* dtm; extern remote_bitbang_t * jtag; static uint64_t trace_count = 0; bool verbose = false; bool done_reset = false; void handle_sigterm(int sig) { dtm->stop(); } double sc_time_stamp() { return trace_count; } static void usage(const char * program_name) { printf("Usage: %s [EMULATOR OPTION]... [VERILOG PLUSARG]... [HOST OPTION]... BINARY [TARGET OPTION]...\n", program_name); fputs("\ Run a BINARY on the Rocket Chip emulator.\n\ \n\ Mandatory arguments to long options are mandatory for short options too.\n\ \n\ EMULATOR OPTIONS\n\ -c, --cycle-count Print the cycle count before exiting\n\ +cycle-count\n\ -h, --help Display this help and exit\n\ -m, --max-cycles=CYCLES Kill the emulation after CYCLES\n\ +max-cycles=CYCLES\n\ -s, --seed=SEED Use random number seed SEED\n\ -r, --rbb-port=PORT Use PORT for remote bit bang (with OpenOCD and GDB) \n\ If not specified, a random port will be chosen\n\ automatically.\n\ -V, --verbose Enable all Chisel printfs (cycle-by-cycle info)\n\ +verbose\n\ ", stdout); #if VM_TRACE == 0 fputs("\ \n\ EMULATOR DEBUG OPTIONS (only supported in debug build -- try `make debug`)\n", stdout); #endif fputs("\ -v, --vcd=FILE, Write vcd trace to FILE (or '-' for stdout)\n\ -x, --dump-start=CYCLE Start VCD tracing at CYCLE\n\ +dump-start\n\ ", stdout); fputs("\n" PLUSARG_USAGE_OPTIONS, stdout); fputs("\n" HTIF_USAGE_OPTIONS, stdout); printf("\n" "EXAMPLES\n" " - run a bare metal test:\n" " %s $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add\n" " - run a bare metal test showing cycle-by-cycle information:\n" " %s +verbose $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add 2>&1 | spike-dasm\n" #if VM_TRACE " - run a bare metal test to generate a VCD waveform:\n" " %s -v rv64ui-p-add.vcd $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add\n" #endif " - run an ELF (you wrote, called 'hello') using the proxy kernel:\n" " %s pk hello\n", program_name, program_name, program_name #if VM_TRACE , program_name #endif ); } int main(int argc, char** argv) { unsigned random_seed = (unsigned)time(NULL) ^ (unsigned)getpid(); uint64_t max_cycles = -1; int ret = 0; bool print_cycles = false; // Port numbers are 16 bit unsigned integers. uint16_t rbb_port = 0; #if VM_TRACE const char* vcdfile_name = NULL; FILE * vcdfile = NULL; uint64_t start = 0; #endif int verilog_plusargs_legal = 1; opterr = 1; while (1) { static struct option long_options[] = { {"cycle-count", no_argument, 0, 'c' }, {"help", no_argument, 0, 'h' }, {"max-cycles", required_argument, 0, 'm' }, {"seed", required_argument, 0, 's' }, {"rbb-port", required_argument, 0, 'r' }, {"verbose", no_argument, 0, 'V' }, {"permissive", no_argument, 0, 'p' }, {"permissive-off", no_argument, 0, 'o' }, #if VM_TRACE {"vcd", required_argument, 0, 'v' }, {"dump-start", required_argument, 0, 'x' }, #endif HTIF_LONG_OPTIONS }; int option_index = 0; #if VM_TRACE int c = getopt_long(argc, argv, "-chm:s:r:v:Vx:po", long_options, &option_index); #else int c = getopt_long(argc, argv, "-chm:s:r:Vpo", long_options, &option_index); #endif if (c == -1) break; retry: switch (c) { // Process long and short EMULATOR options case '?': usage(argv[0]); return 1; case 'c': print_cycles = true; break; case 'h': usage(argv[0]); return 0; case 'm': max_cycles = atoll(optarg); break; case 's': random_seed = atoi(optarg); break; case 'r': rbb_port = atoi(optarg); break; case 'V': verbose = true; break; case 'p': opterr = 0; break; case 'o': opterr = 1; break; #if VM_TRACE case 'v': { vcdfile_name = optarg; vcdfile = strcmp(optarg, "-") == 0 ? stdout : fopen(optarg, "w"); if (!vcdfile) { std::cerr << "Unable to open " << optarg << " for VCD write\n"; return 1; } break; } case 'x': start = atoll(optarg); break; #endif // Process legacy '+' EMULATOR arguments by replacing them with // their getopt equivalents case 1: { std::string arg = optarg; if (arg.substr(0, 1) != "+") { optind--; goto done_processing; } if (arg == "+verbose") c = 'V'; else if (arg.substr(0, 12) == "+max-cycles=") { c = 'm'; optarg = optarg+12; } #if VM_TRACE else if (arg.substr(0, 12) == "+dump-start=") { c = 'x'; optarg = optarg+12; } #endif else if (arg.substr(0, 12) == "+cycle-count") c = 'c'; else if (arg == "+permissive") c = 'p'; else if (arg == "+permissive-off") c = 'o'; // If we don't find a legacy '+' EMULATOR argument, it still could be // a VERILOG_PLUSARG and not an error. else if (verilog_plusargs_legal) { const char ** plusarg = &verilog_plusargs[0]; int legal_verilog_plusarg = 0; while (*plusarg && (legal_verilog_plusarg == 0)){ if (arg.substr(1, strlen(*plusarg)) == *plusarg) { legal_verilog_plusarg = 1; } plusarg ++; } if (!legal_verilog_plusarg) { verilog_plusargs_legal = 0; } else { c = 'P'; } goto retry; } // If we STILL don't find a legacy '+' argument, it still could be // an HTIF (HOST) argument and not an error. If this is the case, then // we're done processing EMULATOR and VERILOG arguments. else { static struct option htif_long_options [] = { HTIF_LONG_OPTIONS }; struct option * htif_option = &htif_long_options[0]; while (htif_option->name) { if (arg.substr(1, strlen(htif_option->name)) == htif_option->name) { optind--; goto done_processing; } htif_option++; } if(opterr) { std::cerr << argv[0] << ": invalid plus-arg (Verilog or HTIF) \"" << arg << "\"\n"; c = '?'; } else { c = 'p'; } } goto retry; } case 'P': break; // Nothing to do here, Verilog PlusArg // Realize that we've hit HTIF (HOST) arguments or error out default: if (c >= HTIF_LONG_OPTIONS_OPTIND) { optind--; goto done_processing; } c = '?'; goto retry; } } done_processing: if (optind == argc) { std::cerr << "No binary specified for emulator\n"; usage(argv[0]); return 1; } int htif_argc = 1; char** htif_argv = new char*[argc]; htif_argv[0] = argv[0]; for (int i = 1; i < argc; i++) if (argv[i][0] != '-') htif_argv[htif_argc++] = argv[i]; if (verbose) fprintf(stderr, "using random seed %u\n", random_seed); srand(random_seed); srand48(random_seed); Verilated::randReset(2); Verilated::commandArgs(htif_argc, htif_argv); TEST_HARNESS *tile = new TEST_HARNESS; #if VM_TRACE Verilated::traceEverOn(true); // Verilator must compute traced signals #if CY_FST_TRACE std::unique_ptr<VerilatedFstC> tfp(new VerilatedFstC); #else std::unique_ptr<VerilatedVcdFILE> vcdfd(new VerilatedVcdFILE(vcdfile)); std::unique_ptr<VerilatedVcdC> tfp(new VerilatedVcdC(vcdfd.get())); #endif // CY_FST_TRACE if (vcdfile_name) { tile->trace(tfp.get(), 99); // Trace 99 levels of hierarchy tfp->open(vcdfile_name); } #endif // VM_TRACE // RocketChip currently only supports RBB port 0, so this needs to stay here jtag = new remote_bitbang_t(rbb_port); signal(SIGTERM, handle_sigterm); bool dump; // start reset off low so a rising edge triggers async reset tile->reset = 0; tile->clock = 0; tile->eval(); // reset for several cycles to handle pipelined reset for (int i = 0; i < 100; i++) { tile->reset = 1; tile->clock = 0; tile->eval(); #if VM_TRACE dump = tfp && trace_count >= start; if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2)); #endif tile->clock = 1; tile->eval(); #if VM_TRACE if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2 + 1)); #endif trace_count ++; } tile->reset = 0; done_reset = true; do { tile->clock = 0; tile->eval(); #if VM_TRACE dump = tfp && trace_count >= start; if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2)); #endif tile->clock = 1; tile->eval(); #if VM_TRACE if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2 + 1)); #endif trace_count++; } // for verilator multithreading. need to do 1 loop before checking if // tsi exists, since tsi is created by verilated thread on the first // serial_tick. while ((!dtm || !dtm->done()) && (!jtag || !jtag->done()) && (!tsi || !tsi->done()) && !tile->io_success && trace_count < max_cycles); #if VM_TRACE if (tfp) tfp->close(); if (vcdfile) fclose(vcdfile); #endif if (dtm && dtm->exit_code()) { fprintf(stderr, "*** FAILED *** via dtm (code = %d, seed %d) after %ld cycles\n", dtm->exit_code(), random_seed, trace_count); ret = dtm->exit_code(); } else if (tsi && tsi->exit_code()) { fprintf(stderr, "*** FAILED *** (code = %d, seed %d) after %ld cycles\n", tsi->exit_code(), random_seed, trace_count); ret = tsi->exit_code(); } else if (jtag && jtag->exit_code()) { fprintf(stderr, "*** FAILED *** via jtag (code = %d, seed %d) after %ld cycles\n", jtag->exit_code(), random_seed, trace_count); ret = jtag->exit_code(); } else if (trace_count == max_cycles) { fprintf(stderr, "*** FAILED *** via trace_count (timeout, seed %d) after %ld cycles\n", random_seed, trace_count); ret = 2; } else if (verbose || print_cycles) { fprintf(stderr, "*** PASSED *** Completed after %ld cycles\n", trace_count); } if (dtm) delete dtm; if (tsi) delete tsi; if (jtag) delete jtag; if (tile) delete tile; if (htif_argv) delete[] htif_argv; return ret; }
Change to filter all arguments that begin with a '-'
Change to filter all arguments that begin with a '-'
C++
bsd-3-clause
ucb-bar/chipyard,ucb-bar/chipyard,ucb-bar/chipyard,ucb-bar/chipyard
2be73c65f9af9294fe4b76a7bfd4d2b449227cdb
Interpret/SmartView/PropertiesStruct.cpp
Interpret/SmartView/PropertiesStruct.cpp
#include <StdAfx.h> #include <Interpret/SmartView/PropertiesStruct.h> #include <Interpret/InterpretProp.h> #include <Interpret/SmartView/SmartView.h> namespace smartview { void PropertiesStruct::Parse() { // For consistancy with previous parsings, we'll refuse to parse if asked to parse more than _MaxEntriesSmall // However, we may want to reconsider this choice. if (m_MaxEntries > _MaxEntriesSmall) return; DWORD dwPropCount = 0; // If we have a non-default max, it was computed elsewhere and we do expect to have that many entries. So we can reserve. if (m_MaxEntries != _MaxEntriesSmall) { m_Props.reserve(m_MaxEntries); } for (;;) { if (dwPropCount >= m_MaxEntries) break; m_Props.push_back(BinToSPropValueStruct()); if (!m_Parser.RemainingBytes()) break; dwPropCount++; } } void PropertiesStruct::ParseBlocks() { auto i = 0; for (auto prop : m_Props) { if (i != 0) { addBlankLine(); } addHeader(L"Property[%1!d!]\r\n", i++); addBlock(prop.ulPropTag, L"Property = 0x%1!08X!", prop.ulPropTag.getData()); auto propTagNames = interpretprop::PropTagToPropName(prop.ulPropTag, false); if (!propTagNames.bestGuess.empty()) { terminateBlock(); addBlock(prop.ulPropTag, L"Name: %1!ws!", propTagNames.bestGuess.c_str()); } if (!propTagNames.otherMatches.empty()) { terminateBlock(); addBlock(prop.ulPropTag, L"Other Matches: %1!ws!", propTagNames.otherMatches.c_str()); } // TODO: get proper blocks here terminateBlock(); addHeader(L"PropString = %1!ws! ", prop.PropString().c_str()); addHeader(L"AltPropString = %1!ws!", prop.AltPropString().c_str()); auto sProp = prop.getData(); auto szSmartView = InterpretPropSmartView(&sProp, nullptr, nullptr, nullptr, false, false); if (!szSmartView.empty()) { // TODO: proper blocks here terminateBlock(); addHeader(L"Smart View: %1!ws!", szSmartView.c_str()); } } } _Check_return_ SPropValueStruct PropertiesStruct::BinToSPropValueStruct() { const auto ulCurrOffset = m_Parser.GetCurrentOffset(); auto prop = SPropValueStruct{}; prop.PropType = m_Parser.Get<WORD>(); prop.PropID = m_Parser.Get<WORD>(); prop.ulPropTag = PROP_TAG(prop.PropType, prop.PropID); prop.ulPropTag.setSize(prop.PropType.getSize() + prop.PropID.getSize()); prop.ulPropTag.setOffset(prop.PropType.getOffset()); prop.dwAlignPad = 0; if (m_NickName) (void) m_Parser.Get<DWORD>(); // reserved switch (prop.PropType) { case PT_I2: // TODO: Insert proper property struct parsing here if (m_NickName) prop.Value.i = m_Parser.Get<WORD>(); if (m_NickName) m_Parser.Get<WORD>(); if (m_NickName) m_Parser.Get<DWORD>(); break; case PT_LONG: prop.Value.l = m_Parser.Get<DWORD>(); if (m_NickName) m_Parser.Get<DWORD>(); break; case PT_ERROR: prop.Value.err = m_Parser.Get<DWORD>(); if (m_NickName) m_Parser.Get<DWORD>(); break; case PT_R4: prop.Value.flt = m_Parser.Get<float>(); if (m_NickName) m_Parser.Get<DWORD>(); break; case PT_DOUBLE: prop.Value.dbl = m_Parser.Get<double>(); break; case PT_BOOLEAN: if (m_RuleCondition) { prop.Value.b = m_Parser.Get<BYTE>(); } else { prop.Value.b = m_Parser.Get<WORD>(); } if (m_NickName) m_Parser.Get<WORD>(); if (m_NickName) m_Parser.Get<DWORD>(); break; case PT_I8: prop.Value.li = m_Parser.Get<LARGE_INTEGER>(); break; case PT_SYSTIME: prop.Value.ft.dwHighDateTime = m_Parser.Get<DWORD>(); prop.Value.ft.dwLowDateTime = m_Parser.Get<DWORD>(); break; case PT_STRING8: if (m_RuleCondition) { prop.Value.lpszA.str = m_Parser.GetStringA(); prop.Value.lpszA.cb = static_cast<ULONG>(prop.Value.lpszA.str.length()); } else { if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.lpszA.cb = m_Parser.Get<DWORD>(); } else { prop.Value.lpszA.cb = m_Parser.Get<WORD>(); } prop.Value.lpszA.str = m_Parser.GetStringA(prop.Value.lpszA.cb); } break; case PT_BINARY: if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union } if (m_RuleCondition || m_NickName) { prop.Value.bin.cb = m_Parser.Get<DWORD>(); } else { prop.Value.bin.cb = m_Parser.Get<WORD>(); } // Note that we're not placing a restriction on how large a binary property we can parse. May need to revisit this. prop.Value.bin.lpb = m_Parser.GetBYTES(prop.Value.bin.cb); break; case PT_UNICODE: if (m_RuleCondition) { prop.Value.lpszW.str = m_Parser.GetStringW(); prop.Value.lpszW.cb = static_cast<ULONG>(prop.Value.lpszW.str.length()); } else { if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.lpszW.cb = m_Parser.Get<DWORD>(); } else { prop.Value.lpszW.cb = m_Parser.Get<WORD>(); } prop.Value.lpszW.str = m_Parser.GetStringW(prop.Value.lpszW.cb / sizeof(WCHAR)); } break; case PT_CLSID: if (m_NickName) (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.lpguid = m_Parser.Get<GUID>(); break; case PT_MV_STRING8: if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.MVszA.cValues = m_Parser.Get<DWORD>(); } else { prop.Value.MVszA.cValues = m_Parser.Get<WORD>(); } if (prop.Value.MVszA.cValues) //if (prop.Value.MVszA.cValues && prop.Value.MVszA.cValues < _MaxEntriesLarge) { prop.Value.MVszA.lppszA.reserve(prop.Value.MVszA.cValues); for (ULONG j = 0; j < prop.Value.MVszA.cValues; j++) { prop.Value.MVszA.lppszA.push_back(m_Parser.GetStringA()); } } break; case PT_MV_UNICODE: if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.MVszW.cValues = m_Parser.Get<DWORD>(); } else { prop.Value.MVszW.cValues = m_Parser.Get<WORD>(); } if (prop.Value.MVszW.cValues) //if (prop.Value.MVszW.cValues && prop.Value.MVszW.cValues < _MaxEntriesLarge) { prop.Value.MVszW.lppszW.reserve(prop.Value.MVszW.cValues); for (ULONG j = 0; j < prop.Value.MVszW.cValues; j++) { prop.Value.MVszW.lppszW.emplace_back(m_Parser.GetStringW()); } } break; case PT_MV_BINARY: if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.MVbin.cValues = m_Parser.Get<DWORD>(); } else { prop.Value.MVbin.cValues = m_Parser.Get<WORD>(); } if (prop.Value.MVbin.cValues && prop.Value.MVbin.cValues < _MaxEntriesLarge) { for (ULONG j = 0; j < prop.Value.MVbin.cValues; j++) { auto bin = SBinaryBlock{}; bin.cb = m_Parser.Get<DWORD>(); // Note that we're not placing a restriction on how large a multivalued binary property we can parse. May need to revisit this. bin.lpb = m_Parser.GetBYTES(bin.cb); prop.Value.MVbin.lpbin.push_back(bin); } } break; default: break; } if (ulCurrOffset == m_Parser.GetCurrentOffset()) { // We didn't advance at all - we should return nothing. return {}; } return prop; } } // namespace smartview
#include <StdAfx.h> #include <Interpret/SmartView/PropertiesStruct.h> #include <Interpret/InterpretProp.h> #include <Interpret/SmartView/SmartView.h> namespace smartview { void PropertiesStruct::Parse() { // For consistancy with previous parsings, we'll refuse to parse if asked to parse more than _MaxEntriesSmall // However, we may want to reconsider this choice. if (m_MaxEntries > _MaxEntriesSmall) return; DWORD dwPropCount = 0; // If we have a non-default max, it was computed elsewhere and we do expect to have that many entries. So we can reserve. if (m_MaxEntries != _MaxEntriesSmall) { m_Props.reserve(m_MaxEntries); } for (;;) { if (dwPropCount >= m_MaxEntries) break; m_Props.push_back(BinToSPropValueStruct()); if (!m_Parser.RemainingBytes()) break; dwPropCount++; } } void PropertiesStruct::ParseBlocks() { auto i = 0; for (auto prop : m_Props) { if (i != 0) { terminateBlock(); } auto propBlock = block(); propBlock.setText(L"Property[%1!d!]\r\n", i++); propBlock.addBlock(prop.ulPropTag, L"Property = 0x%1!08X!", prop.ulPropTag.getData()); auto propTagNames = interpretprop::PropTagToPropName(prop.ulPropTag, false); if (!propTagNames.bestGuess.empty()) { propBlock.terminateBlock(); propBlock.addBlock(prop.ulPropTag, L"Name: %1!ws!", propTagNames.bestGuess.c_str()); } if (!propTagNames.otherMatches.empty()) { propBlock.terminateBlock(); propBlock.addBlock(prop.ulPropTag, L"Other Matches: %1!ws!", propTagNames.otherMatches.c_str()); } // TODO: get proper blocks here propBlock.terminateBlock(); propBlock.addHeader(L"PropString = %1!ws! ", prop.PropString().c_str()); propBlock.addHeader(L"AltPropString = %1!ws!", prop.AltPropString().c_str()); auto sProp = prop.getData(); auto szSmartView = InterpretPropSmartView(&sProp, nullptr, nullptr, nullptr, false, false); if (!szSmartView.empty()) { // TODO: proper blocks here propBlock.terminateBlock(); propBlock.addHeader(L"Smart View: %1!ws!", szSmartView.c_str()); } addBlock(propBlock); } } _Check_return_ SPropValueStruct PropertiesStruct::BinToSPropValueStruct() { const auto ulCurrOffset = m_Parser.GetCurrentOffset(); auto prop = SPropValueStruct{}; prop.PropType = m_Parser.Get<WORD>(); prop.PropID = m_Parser.Get<WORD>(); prop.ulPropTag = PROP_TAG(prop.PropType, prop.PropID); prop.ulPropTag.setSize(prop.PropType.getSize() + prop.PropID.getSize()); prop.ulPropTag.setOffset(prop.PropType.getOffset()); prop.dwAlignPad = 0; if (m_NickName) (void) m_Parser.Get<DWORD>(); // reserved switch (prop.PropType) { case PT_I2: // TODO: Insert proper property struct parsing here if (m_NickName) prop.Value.i = m_Parser.Get<WORD>(); if (m_NickName) m_Parser.Get<WORD>(); if (m_NickName) m_Parser.Get<DWORD>(); break; case PT_LONG: prop.Value.l = m_Parser.Get<DWORD>(); if (m_NickName) m_Parser.Get<DWORD>(); break; case PT_ERROR: prop.Value.err = m_Parser.Get<DWORD>(); if (m_NickName) m_Parser.Get<DWORD>(); break; case PT_R4: prop.Value.flt = m_Parser.Get<float>(); if (m_NickName) m_Parser.Get<DWORD>(); break; case PT_DOUBLE: prop.Value.dbl = m_Parser.Get<double>(); break; case PT_BOOLEAN: if (m_RuleCondition) { prop.Value.b = m_Parser.Get<BYTE>(); } else { prop.Value.b = m_Parser.Get<WORD>(); } if (m_NickName) m_Parser.Get<WORD>(); if (m_NickName) m_Parser.Get<DWORD>(); break; case PT_I8: prop.Value.li = m_Parser.Get<LARGE_INTEGER>(); break; case PT_SYSTIME: prop.Value.ft.dwHighDateTime = m_Parser.Get<DWORD>(); prop.Value.ft.dwLowDateTime = m_Parser.Get<DWORD>(); break; case PT_STRING8: if (m_RuleCondition) { prop.Value.lpszA.str = m_Parser.GetStringA(); prop.Value.lpszA.cb = static_cast<ULONG>(prop.Value.lpszA.str.length()); } else { if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.lpszA.cb = m_Parser.Get<DWORD>(); } else { prop.Value.lpszA.cb = m_Parser.Get<WORD>(); } prop.Value.lpszA.str = m_Parser.GetStringA(prop.Value.lpszA.cb); } break; case PT_BINARY: if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union } if (m_RuleCondition || m_NickName) { prop.Value.bin.cb = m_Parser.Get<DWORD>(); } else { prop.Value.bin.cb = m_Parser.Get<WORD>(); } // Note that we're not placing a restriction on how large a binary property we can parse. May need to revisit this. prop.Value.bin.lpb = m_Parser.GetBYTES(prop.Value.bin.cb); break; case PT_UNICODE: if (m_RuleCondition) { prop.Value.lpszW.str = m_Parser.GetStringW(); prop.Value.lpszW.cb = static_cast<ULONG>(prop.Value.lpszW.str.length()); } else { if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.lpszW.cb = m_Parser.Get<DWORD>(); } else { prop.Value.lpszW.cb = m_Parser.Get<WORD>(); } prop.Value.lpszW.str = m_Parser.GetStringW(prop.Value.lpszW.cb / sizeof(WCHAR)); } break; case PT_CLSID: if (m_NickName) (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.lpguid = m_Parser.Get<GUID>(); break; case PT_MV_STRING8: if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.MVszA.cValues = m_Parser.Get<DWORD>(); } else { prop.Value.MVszA.cValues = m_Parser.Get<WORD>(); } if (prop.Value.MVszA.cValues) //if (prop.Value.MVszA.cValues && prop.Value.MVszA.cValues < _MaxEntriesLarge) { prop.Value.MVszA.lppszA.reserve(prop.Value.MVszA.cValues); for (ULONG j = 0; j < prop.Value.MVszA.cValues; j++) { prop.Value.MVszA.lppszA.push_back(m_Parser.GetStringA()); } } break; case PT_MV_UNICODE: if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.MVszW.cValues = m_Parser.Get<DWORD>(); } else { prop.Value.MVszW.cValues = m_Parser.Get<WORD>(); } if (prop.Value.MVszW.cValues) //if (prop.Value.MVszW.cValues && prop.Value.MVszW.cValues < _MaxEntriesLarge) { prop.Value.MVszW.lppszW.reserve(prop.Value.MVszW.cValues); for (ULONG j = 0; j < prop.Value.MVszW.cValues; j++) { prop.Value.MVszW.lppszW.emplace_back(m_Parser.GetStringW()); } } break; case PT_MV_BINARY: if (m_NickName) { (void) m_Parser.Get<LARGE_INTEGER>(); // union prop.Value.MVbin.cValues = m_Parser.Get<DWORD>(); } else { prop.Value.MVbin.cValues = m_Parser.Get<WORD>(); } if (prop.Value.MVbin.cValues && prop.Value.MVbin.cValues < _MaxEntriesLarge) { for (ULONG j = 0; j < prop.Value.MVbin.cValues; j++) { auto bin = SBinaryBlock{}; bin.cb = m_Parser.Get<DWORD>(); // Note that we're not placing a restriction on how large a multivalued binary property we can parse. May need to revisit this. bin.lpb = m_Parser.GetBYTES(bin.cb); prop.Value.MVbin.lpbin.push_back(bin); } } break; default: break; } if (ulCurrOffset == m_Parser.GetCurrentOffset()) { // We didn't advance at all - we should return nothing. return {}; } return prop; } } // namespace smartview
build properties under a node
build properties under a node
C++
mit
stephenegriffin/mfcmapi,stephenegriffin/mfcmapi,stephenegriffin/mfcmapi
a2cd00a32ceabbec2ff4fbc1acf11238f103ab4f
Modules/Learning/Supervised/include/otbKNearestNeighborsMachineLearningModel.hxx
Modules/Learning/Supervised/include/otbKNearestNeighborsMachineLearningModel.hxx
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbKNearestNeighborsMachineLearningModel_hxx #define otbKNearestNeighborsMachineLearningModel_hxx #include "otb_boost_lexicalcast_header.h" #include "otbKNearestNeighborsMachineLearningModel.h" #include "otbOpenCVUtils.h" #include <fstream> #include <set> #include "itkMacro.h" namespace otb { template <class TInputValue, class TTargetValue> KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::KNearestNeighborsMachineLearningModel() : m_KNearestModel(cv::ml::KNearest::create()), m_K(32), m_DecisionRule(KNN_VOTING) { this->m_ConfidenceIndex = true; this->m_IsRegressionSupported = true; } /** Train the machine learning model */ template <class TInputValue, class TTargetValue> void KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::Train() { // convert listsample to opencv matrix cv::Mat samples; otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples); cv::Mat labels; otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(), labels); // update decision rule if needed if (this->m_RegressionMode) { if (this->m_DecisionRule == KNN_VOTING) { this->SetDecisionRule(KNN_MEAN); } } else { if (this->m_DecisionRule != KNN_VOTING) { this->SetDecisionRule(KNN_VOTING); } } m_KNearestModel->setDefaultK(m_K); // would be nice to expose KDTree mode ( maybe in a different classifier) m_KNearestModel->setAlgorithmType(cv::ml::KNearest::BRUTE_FORCE); m_KNearestModel->setIsClassifier(!this->m_RegressionMode); // setEmax() ? m_KNearestModel->train(cv::ml::TrainData::create(samples, cv::ml::ROW_SAMPLE, labels)); } template <class TInputValue, class TTargetValue> typename KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::TargetSampleType KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::DoPredict(const InputSampleType& input, ConfidenceValueType* quality, ProbaSampleType* proba) const { TargetSampleType target; // convert listsample to Mat cv::Mat sample; otb::SampleToMat<InputSampleType>(input, sample); float result; cv::Mat nearest(1, m_K, CV_32FC1); result = m_KNearestModel->findNearest(sample, m_K, cv::noArray(), nearest, cv::noArray()); // compute quality if asked (only happens in classification mode) if (quality != nullptr) { assert(!this->m_RegressionMode); unsigned int accuracy = 0; for (int k = 0; k < m_K; ++k) { if (nearest.at<float>(0, k) == result) { accuracy++; } } (*quality) = static_cast<ConfidenceValueType>(accuracy); } if (proba != nullptr && !this->m_ProbaIndex) itkExceptionMacro("Probability per class not available for this classifier !"); // Decision rule : // VOTING is OpenCV default behaviour for classification // MEAN is OpenCV default behaviour for regression // MEDIAN : only case that must be handled here if (this->m_DecisionRule == KNN_MEDIAN) { std::multiset<float> values; for (int k = 0; k < m_K; ++k) { values.insert(nearest.at<float>(0, k)); } std::multiset<float>::iterator median = values.begin(); int pos = (m_K >> 1); for (int k = 0; k < pos; ++k, ++median) { } result = *median; } target[0] = static_cast<TTargetValue>(result); return target; } template <class TInputValue, class TTargetValue> void KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::Save(const std::string& filename, const std::string& name) { cv::FileStorage fs(filename, cv::FileStorage::WRITE); fs << (name.empty() ? m_KNearestModel->getDefaultName() : cv::String(name)) << "{"; m_KNearestModel->write(fs); fs << "DecisionRule" << m_DecisionRule; fs << "}"; fs.release(); } template <class TInputValue, class TTargetValue> void KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::Load(const std::string& filename, const std::string& itkNotUsed(name)) { std::ifstream ifs(filename); if (!ifs) { itkExceptionMacro(<< "Could not read file " << filename); } // try to load with the 3.x syntax bool isKNNv3 = false; while (!ifs.eof()) { std::string line; std::getline(ifs, line); if (line.find(m_KNearestModel->getDefaultName()) != std::string::npos) { isKNNv3 = true; break; } } ifs.close(); if (isKNNv3) { cv::FileStorage fs(filename, cv::FileStorage::READ); m_KNearestModel->read(fs.getFirstTopLevelNode()); m_DecisionRule = (int)(fs.getFirstTopLevelNode()["DecisionRule"]); return; } ifs.open(filename); // there is no m_KNearestModel->load(filename.c_str(), name.c_str()); // first line is the K parameter of this algorithm. std::string line; std::getline(ifs, line); std::istringstream iss(line); if (line.find("K") == std::string::npos) { itkExceptionMacro(<< "Could not read file " << filename); } std::string::size_type pos = line.find_first_of("=", 0); std::string::size_type nextpos = line.find_first_of(" \n\r", pos + 1); this->SetK(boost::lexical_cast<int>(line.substr(pos + 1, nextpos - pos - 1))); // second line is the IsRegression parameter std::getline(ifs, line); if (line.find("IsRegression") == std::string::npos) { itkExceptionMacro(<< "Could not read file " << filename); } pos = line.find_first_of("=", 0); nextpos = line.find_first_of(" \n\r", pos + 1); this->SetRegressionMode(boost::lexical_cast<bool>(line.substr(pos + 1, nextpos - pos - 1))); // third line is the DecisionRule parameter (only for regression) if (this->m_RegressionMode) { std::getline(ifs, line); pos = line.find_first_of("=", 0); nextpos = line.find_first_of(" \n\r", pos + 1); this->SetDecisionRule(boost::lexical_cast<int>(line.substr(pos + 1, nextpos - pos - 1))); } // Clear previous listSample (if any) typename InputListSampleType::Pointer samples = InputListSampleType::New(); typename TargetListSampleType::Pointer labels = TargetListSampleType::New(); // Read a txt file. First column is the label, other columns are the sample data. unsigned int nbFeatures = 0; while (!ifs.eof()) { std::getline(ifs, line); if (nbFeatures == 0) { nbFeatures = std::count(line.begin(), line.end(), ' '); } if (line.size() > 1) { // Parse label pos = line.find_first_of(" ", 0); TargetSampleType label; label[0] = static_cast<TargetValueType>(boost::lexical_cast<unsigned int>(line.substr(0, pos))); // Parse sample features InputSampleType sample(nbFeatures); sample.Fill(0); unsigned int id = 0; nextpos = line.find_first_of(" ", pos + 1); while (nextpos != std::string::npos) { nextpos = line.find_first_of(" \n\r", pos + 1); std::string subline = line.substr(pos + 1, nextpos - pos - 1); // sample[id] = static_cast<InputValueType>(boost::lexical_cast<float>(subline)); sample[id] = atof(subline.c_str()); pos = nextpos; id++; } samples->SetMeasurementVectorSize(itk::NumericTraits<InputSampleType>::GetLength(sample)); samples->PushBack(sample); labels->PushBack(label); } } ifs.close(); this->SetInputListSample(samples); this->SetTargetListSample(labels); this->Train(); } template <class TInputValue, class TTargetValue> bool KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::CanReadFile(const std::string& file) { try { this->Load(file); } catch (...) { return false; } return true; } template <class TInputValue, class TTargetValue> bool KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::CanWriteFile(const std::string& itkNotUsed(file)) { return false; } template <class TInputValue, class TTargetValue> void KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::PrintSelf(std::ostream& os, itk::Indent indent) const { // Call superclass implementation Superclass::PrintSelf(os, indent); } } // end namespace otb #endif
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbKNearestNeighborsMachineLearningModel_hxx #define otbKNearestNeighborsMachineLearningModel_hxx #include "otb_boost_lexicalcast_header.h" #include "otbKNearestNeighborsMachineLearningModel.h" #include "otbOpenCVUtils.h" #include <fstream> #include <set> #include "itkMacro.h" namespace otb { template <class TInputValue, class TTargetValue> KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::KNearestNeighborsMachineLearningModel() : m_KNearestModel(cv::ml::KNearest::create()), m_K(32), m_DecisionRule(KNN_VOTING) { this->m_ConfidenceIndex = true; this->m_IsRegressionSupported = true; } /** Train the machine learning model */ template <class TInputValue, class TTargetValue> void KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::Train() { // convert listsample to opencv matrix cv::Mat samples; otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples); cv::Mat labels; otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(), labels); // update decision rule if needed if (this->m_RegressionMode) { if (this->m_DecisionRule == KNN_VOTING) { this->SetDecisionRule(KNN_MEAN); } } else { if (this->m_DecisionRule != KNN_VOTING) { this->SetDecisionRule(KNN_VOTING); } } m_KNearestModel->setDefaultK(m_K); // would be nice to expose KDTree mode ( maybe in a different classifier) m_KNearestModel->setAlgorithmType(cv::ml::KNearest::BRUTE_FORCE); m_KNearestModel->setIsClassifier(!this->m_RegressionMode); // setEmax() ? m_KNearestModel->train(cv::ml::TrainData::create(samples, cv::ml::ROW_SAMPLE, labels)); } template <class TInputValue, class TTargetValue> typename KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::TargetSampleType KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::DoPredict(const InputSampleType& input, ConfidenceValueType* quality, ProbaSampleType* proba) const { TargetSampleType target; // convert listsample to Mat cv::Mat sample; otb::SampleToMat<InputSampleType>(input, sample); float result; cv::Mat nearest(1, m_K, CV_32FC1); result = m_KNearestModel->findNearest(sample, m_K, cv::noArray(), nearest, cv::noArray()); // compute quality if asked (only happens in classification mode) if (quality != nullptr) { assert(!this->m_RegressionMode); unsigned int accuracy = 0; for (int k = 0; k < m_K; ++k) { if (nearest.at<float>(0, k) == result) { accuracy++; } } (*quality) = static_cast<ConfidenceValueType>(accuracy); } if (proba != nullptr && !this->m_ProbaIndex) itkExceptionMacro("Probability per class not available for this classifier !"); // Decision rule : // VOTING is OpenCV default behaviour for classification // MEAN is OpenCV default behaviour for regression // MEDIAN : only case that must be handled here if (this->m_DecisionRule == KNN_MEDIAN) { std::multiset<float> values; for (int k = 0; k < m_K; ++k) { values.insert(nearest.at<float>(0, k)); } std::multiset<float>::iterator median = values.begin(); int pos = (m_K >> 1); for (int k = 0; k < pos; ++k, ++median) { } result = *median; } target[0] = static_cast<TTargetValue>(result); return target; } template <class TInputValue, class TTargetValue> void KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::Save(const std::string& filename, const std::string& name) { cv::FileStorage fs(filename, cv::FileStorage::WRITE); fs << (name.empty() ? m_KNearestModel->getDefaultName() : cv::String(name)) << "{"; m_KNearestModel->write(fs); fs << "DecisionRule" << m_DecisionRule; fs << "}"; fs.release(); } template <class TInputValue, class TTargetValue> void KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::Load(const std::string& filename, const std::string& itkNotUsed(name)) { std::ifstream ifs(filename); if (!ifs) { itkExceptionMacro(<< "Could not read file " << filename); } // try to load with the 3.x syntax bool isKNNv3 = false; while (!ifs.eof()) { std::string line; std::getline(ifs, line); if (line.find(m_KNearestModel->getDefaultName()) != std::string::npos) { isKNNv3 = true; break; } } ifs.close(); if (isKNNv3) { cv::FileStorage fs(filename, cv::FileStorage::READ); m_KNearestModel->read(fs.getFirstTopLevelNode()); m_DecisionRule = (int)(fs.getFirstTopLevelNode()["DecisionRule"]); m_K = m_KNearestModel->getDefaultK(); return; } ifs.open(filename); // there is no m_KNearestModel->load(filename.c_str(), name.c_str()); // first line is the K parameter of this algorithm. std::string line; std::getline(ifs, line); std::istringstream iss(line); if (line.find("K") == std::string::npos) { itkExceptionMacro(<< "Could not read file " << filename); } std::string::size_type pos = line.find_first_of("=", 0); std::string::size_type nextpos = line.find_first_of(" \n\r", pos + 1); this->SetK(boost::lexical_cast<int>(line.substr(pos + 1, nextpos - pos - 1))); // second line is the IsRegression parameter std::getline(ifs, line); if (line.find("IsRegression") == std::string::npos) { itkExceptionMacro(<< "Could not read file " << filename); } pos = line.find_first_of("=", 0); nextpos = line.find_first_of(" \n\r", pos + 1); this->SetRegressionMode(boost::lexical_cast<bool>(line.substr(pos + 1, nextpos - pos - 1))); // third line is the DecisionRule parameter (only for regression) if (this->m_RegressionMode) { std::getline(ifs, line); pos = line.find_first_of("=", 0); nextpos = line.find_first_of(" \n\r", pos + 1); this->SetDecisionRule(boost::lexical_cast<int>(line.substr(pos + 1, nextpos - pos - 1))); } // Clear previous listSample (if any) typename InputListSampleType::Pointer samples = InputListSampleType::New(); typename TargetListSampleType::Pointer labels = TargetListSampleType::New(); // Read a txt file. First column is the label, other columns are the sample data. unsigned int nbFeatures = 0; while (!ifs.eof()) { std::getline(ifs, line); if (nbFeatures == 0) { nbFeatures = std::count(line.begin(), line.end(), ' '); } if (line.size() > 1) { // Parse label pos = line.find_first_of(" ", 0); TargetSampleType label; label[0] = static_cast<TargetValueType>(boost::lexical_cast<unsigned int>(line.substr(0, pos))); // Parse sample features InputSampleType sample(nbFeatures); sample.Fill(0); unsigned int id = 0; nextpos = line.find_first_of(" ", pos + 1); while (nextpos != std::string::npos) { nextpos = line.find_first_of(" \n\r", pos + 1); std::string subline = line.substr(pos + 1, nextpos - pos - 1); // sample[id] = static_cast<InputValueType>(boost::lexical_cast<float>(subline)); sample[id] = atof(subline.c_str()); pos = nextpos; id++; } samples->SetMeasurementVectorSize(itk::NumericTraits<InputSampleType>::GetLength(sample)); samples->PushBack(sample); labels->PushBack(label); } } ifs.close(); this->SetInputListSample(samples); this->SetTargetListSample(labels); this->Train(); } template <class TInputValue, class TTargetValue> bool KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::CanReadFile(const std::string& file) { try { this->Load(file); } catch (...) { return false; } return true; } template <class TInputValue, class TTargetValue> bool KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::CanWriteFile(const std::string& itkNotUsed(file)) { return false; } template <class TInputValue, class TTargetValue> void KNearestNeighborsMachineLearningModel<TInputValue, TTargetValue>::PrintSelf(std::ostream& os, itk::Indent indent) const { // Call superclass implementation Superclass::PrintSelf(os, indent); } } // end namespace otb #endif
read the number of neighbor when using OpenCV >= 3 in KNearestNeighborsMachineLearningModel instead of using the default constructed value
BUG: read the number of neighbor when using OpenCV >= 3 in KNearestNeighborsMachineLearningModel instead of using the default constructed value
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
1ac7d3dccb66375e59847a4c4310d7c2aa74c601
include/dll/neural/batch_normalization_2d_layer_impl.hpp
include/dll/neural/batch_normalization_2d_layer_impl.hpp
//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "dll/neural_layer.hpp" namespace dll { /*! * \brief Batch Normalization layer */ template <typename Desc> struct batch_normalization_2d_layer_impl : neural_layer<batch_normalization_2d_layer_impl<Desc>, Desc> { using desc = Desc; ///< The descriptor type using base_type = neural_layer<batch_normalization_2d_layer_impl<Desc>, Desc>; ///< The base type using weight = typename desc::weight; ///< The data type of the layer using this_type = batch_normalization_2d_layer_impl<Desc>; ///< The type of this layer using layer_t = this_type; ///< This layer's type using dyn_layer_t = typename desc::dyn_layer_t; ///< The dynamic version of this layer static constexpr size_t Input = desc::Input; ///< The input size static constexpr weight e = 1e-8; ///< Epsilon for numerical stability using input_one_t = etl::fast_dyn_matrix<weight, Input>; ///< The type of one input using output_one_t = etl::fast_dyn_matrix<weight, Input>; ///< The type of one output using input_t = std::vector<input_one_t>; ///< The type of the input using output_t = std::vector<output_one_t>; ///< The type of the output etl::fast_matrix<weight, Input> gamma; etl::fast_matrix<weight, Input> beta; etl::fast_matrix<weight, Input> mean; etl::fast_matrix<weight, Input> var; etl::fast_matrix<weight, Input> last_mean; etl::fast_matrix<weight, Input> last_var; etl::fast_matrix<weight, Input> inv_var; etl::dyn_matrix<weight, 2> input_pre; /// B x Input weight momentum = 0.9; //Backup gamma and beta std::unique_ptr<etl::fast_matrix<weight, Input>> bak_gamma; ///< Backup gamma std::unique_ptr<etl::fast_matrix<weight, Input>> bak_beta; ///< Backup beta batch_normalization_2d_layer_impl() : base_type() { gamma = 1.0; beta = 0.0; } /*! * \brief Returns a string representation of the layer */ static std::string to_short_string(std::string pre = "") { cpp_unused(pre); return "batch_norm"; } /*! * \brief Return the number of trainable parameters of this network. * \return The the number of trainable parameters of this network. */ static constexpr size_t parameters() noexcept { return 4 * Input; } /*! * \brief Return the size of the input of this layer * \return The size of the input of this layer */ static constexpr size_t input_size() noexcept { return Input; } /*! * \brief Return the size of the output of this layer * \return The size of the output of this layer */ static constexpr size_t output_size() noexcept { return Input; } using base_type::test_forward_batch; using base_type::train_forward_batch; /*! * \brief Apply the layer to the batch of input * \param output The batch of output * \param input The batch of input to apply the layer to */ template <typename Input, typename Output> void forward_batch(Output& output, const Input& input) const { test_forward_batch(output, input); } /*! * \brief Apply the layer to the batch of input * \param output The batch of output * \param input The batch of input to apply the layer to */ template <typename Input, typename Output> void test_forward_batch(Output& output, const Input& input) const { dll::auto_timer timer("bn:2d:test:forward"); const auto B = etl::dim<0>(input); auto inv_var = etl::force_temporary(1.0 / etl::sqrt(var + e)); for(size_t b = 0; b < B; ++b){ output(b) = (gamma >> ((input(b) - mean) >> inv_var)) + beta; } } /*! * \brief Apply the layer to the batch of input * \param output The batch of output * \param input The batch of input to apply the layer to */ template <typename Input, typename Output> void train_forward_batch(Output& output, const Input& input) { dll::auto_timer timer("bn:2d:train:forward"); const auto B = etl::dim<0>(input); last_mean = etl::mean_l(input); auto last_mean_rep = etl::rep_l(last_mean, B); last_var = etl::mean_l((input - last_mean_rep) >> (input - last_mean_rep)); inv_var = 1.0 / etl::sqrt(last_var + e); input_pre.inherit_if_null(input); for(size_t b = 0; b < B; ++b){ input_pre(b) = (input(b) - last_mean) >> inv_var; output(b) = (gamma >> input_pre(b)) + beta; } // Update the current mean and variance mean = momentum * mean + (1.0 - momentum) * last_mean; var = momentum * var + (1.0 - momentum) * (B / (B - 1) * last_var); } /*! * \brief Adapt the errors, called before backpropagation of the errors. * * This must be used by layers that have both an activation fnction and a non-linearity. * * \param context the training context */ template<typename C> void adapt_errors(C& context) const { cpp_unused(context); } /*! * \brief Backpropagate the errors to the previous layers * \param output The ETL expression into which write the output * \param context The training context */ template<typename H, typename C> void backward_batch(H&& output, C& context) const { dll::auto_timer timer("bn:2d:backward"); const auto B = etl::dim<0>(context.input); auto dxhat = etl::force_temporary(context.errors >> etl::rep_l(gamma, B)); auto dxhat_l = etl::force_temporary(etl::sum_l(dxhat)); auto dxhat_xhat_l = etl::force_temporary(etl::sum_l(dxhat >> input_pre)); for(size_t b = 0; b < B; ++b){ output(b) = (1.0 / B) >> inv_var >> (B * dxhat(b) - dxhat_l - (input_pre(b) >> dxhat_xhat_l)); } } /*! * \brief Compute the gradients for this layer, if any * \param context The trainng context */ template<typename C> void compute_gradients(C& context) const { dll::auto_timer timer("bn:2d:gradients"); // Gradients of gamma std::get<0>(context.up.context)->grad = etl::sum_l(input_pre >> context.errors); // Gradients of beta std::get<1>(context.up.context)->grad = etl::sum_l(context.errors); } /*! * \brief Prepare one empty output for this layer * \return an empty ETL matrix suitable to store one output of this layer * * \tparam Input The type of one Input */ template <typename InputType> output_one_t prepare_one_output() const { return {}; } /*! * \brief Prepare a set of empty outputs for this layer * \param samples The number of samples to prepare the output for * \return a container containing empty ETL matrices suitable to store samples output of this layer * \tparam Input The type of one input */ template <typename InputType> static output_t prepare_output(size_t samples) { return output_t{samples}; } /*! * \brief Initialize the dynamic version of the layer from the fast version of the layer * \param dyn Reference to the dynamic version of the layer that needs to be initialized */ template<typename DLayer> static void dyn_init(DLayer& dyn){ dyn.init_layer(Input); } /*! * \brief Returns the trainable variables of this layer. * \return a tuple containing references to the variables of this layer */ decltype(auto) trainable_parameters(){ return std::make_tuple(std::ref(gamma), std::ref(beta)); } /*! * \brief Returns the trainable variables of this layer. * \return a tuple containing references to the variables of this layer */ decltype(auto) trainable_parameters() const { return std::make_tuple(std::cref(gamma), std::cref(beta)); } /*! * \brief Backup the weights in the secondary weights matrix */ void backup_weights() { unique_safe_get(bak_gamma) = gamma; unique_safe_get(bak_beta) = beta; } /*! * \brief Restore the weights from the secondary weights matrix */ void restore_weights() { gamma = *bak_gamma; beta = *bak_beta; } }; // Declare the traits for the layer template<typename Desc> struct layer_base_traits<batch_normalization_2d_layer_impl<Desc>> { static constexpr bool is_neural = true; ///< Indicates if the layer is a neural layer static constexpr bool is_dense = false; ///< Indicates if the layer is dense static constexpr bool is_conv = false; ///< Indicates if the layer is convolutional static constexpr bool is_deconv = false; ///< Indicates if the layer is deconvolutional static constexpr bool is_standard = false; ///< Indicates if the layer is standard static constexpr bool is_rbm = false; ///< Indicates if the layer is RBM static constexpr bool is_pooling = false; ///< Indicates if the layer is a pooling layer static constexpr bool is_unpooling = false; ///< Indicates if the layer is an unpooling laye static constexpr bool is_transform = false; ///< Indicates if the layer is a transform layer static constexpr bool is_dynamic = false; ///< Indicates if the layer is dynamic static constexpr bool pretrain_last = false; ///< Indicates if the layer is dynamic static constexpr bool sgd_supported = true; ///< Indicates if the layer is supported by SGD }; /*! * \brief Specialization of sgd_context for batch_normalization_2d_layer_impl */ template <typename DBN, typename Desc, size_t L> struct sgd_context<DBN, batch_normalization_2d_layer_impl<Desc>, L> { using layer_t = batch_normalization_2d_layer_impl<Desc>; ///< The current layer type using weight = typename layer_t::weight; ///< The data type for this layer static constexpr auto batch_size = DBN::batch_size; etl::fast_matrix<weight, batch_size, Desc::Input> input; ///< A batch of input etl::fast_matrix<weight, batch_size, Desc::Input> output; ///< A batch of output etl::fast_matrix<weight, batch_size, Desc::Input> errors; ///< A batch of errors sgd_context(const layer_t& /*layer*/){} }; } //end of dll namespace
//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "dll/neural_layer.hpp" namespace dll { /*! * \brief Batch Normalization layer */ template <typename Desc> struct batch_normalization_2d_layer_impl : neural_layer<batch_normalization_2d_layer_impl<Desc>, Desc> { using desc = Desc; ///< The descriptor type using base_type = neural_layer<batch_normalization_2d_layer_impl<Desc>, Desc>; ///< The base type using weight = typename desc::weight; ///< The data type of the layer using this_type = batch_normalization_2d_layer_impl<Desc>; ///< The type of this layer using layer_t = this_type; ///< This layer's type using dyn_layer_t = typename desc::dyn_layer_t; ///< The dynamic version of this layer static constexpr size_t Input = desc::Input; ///< The input size static constexpr weight e = 1e-8; ///< Epsilon for numerical stability using input_one_t = etl::fast_dyn_matrix<weight, Input>; ///< The type of one input using output_one_t = etl::fast_dyn_matrix<weight, Input>; ///< The type of one output using input_t = std::vector<input_one_t>; ///< The type of the input using output_t = std::vector<output_one_t>; ///< The type of the output etl::fast_matrix<weight, Input> gamma; etl::fast_matrix<weight, Input> beta; etl::fast_matrix<weight, Input> mean; etl::fast_matrix<weight, Input> var; etl::fast_matrix<weight, Input> last_mean; etl::fast_matrix<weight, Input> last_var; etl::fast_matrix<weight, Input> inv_var; etl::dyn_matrix<weight, 2> input_pre; /// B x Input weight momentum = 0.9; //Backup gamma and beta std::unique_ptr<etl::fast_matrix<weight, Input>> bak_gamma; ///< Backup gamma std::unique_ptr<etl::fast_matrix<weight, Input>> bak_beta; ///< Backup beta batch_normalization_2d_layer_impl() : base_type() { gamma = 1.0; beta = 0.0; } /*! * \brief Returns a string representation of the layer */ static std::string to_short_string(std::string pre = "") { cpp_unused(pre); return "batch_norm"; } /*! * \brief Return the number of trainable parameters of this network. * \return The the number of trainable parameters of this network. */ static constexpr size_t parameters() noexcept { return 4 * Input; } /*! * \brief Return the size of the input of this layer * \return The size of the input of this layer */ static constexpr size_t input_size() noexcept { return Input; } /*! * \brief Return the size of the output of this layer * \return The size of the output of this layer */ static constexpr size_t output_size() noexcept { return Input; } using base_type::test_forward_batch; using base_type::train_forward_batch; /*! * \brief Apply the layer to the batch of input * \param output The batch of output * \param input The batch of input to apply the layer to */ template <typename Input, typename Output> void forward_batch(Output& output, const Input& input) const { test_forward_batch(output, input); } /*! * \brief Apply the layer to the batch of input * \param output The batch of output * \param input The batch of input to apply the layer to */ template <typename Input, typename Output> void test_forward_batch(Output& output, const Input& input) const { dll::auto_timer timer("bn:2d:test:forward"); const auto B = etl::dim<0>(input); auto inv_var = etl::force_temporary(1.0 / etl::sqrt(var + e)); for(size_t b = 0; b < B; ++b){ output(b) = (gamma >> ((input(b) - mean) >> inv_var)) + beta; } } /*! * \brief Apply the layer to the batch of input * \param output The batch of output * \param input The batch of input to apply the layer to */ template <typename Input, typename Output> void train_forward_batch(Output& output, const Input& input) { dll::auto_timer timer("bn:2d:train:forward"); const auto B = etl::dim<0>(input); last_mean = etl::bias_batch_mean_2d(input); last_var = etl::bias_batch_var_2d(input, last_mean); inv_var = 1.0 / etl::sqrt(last_var + e); input_pre.inherit_if_null(input); for(size_t b = 0; b < B; ++b){ input_pre(b) = (input(b) - last_mean) >> inv_var; output(b) = (input_pre(b) >> gamma) + beta; } // Update the current mean and variance mean = momentum * mean + (1.0 - momentum) * last_mean; var = momentum * var + (1.0 - momentum) * (B / (B - 1) * last_var); } /*! * \brief Adapt the errors, called before backpropagation of the errors. * * This must be used by layers that have both an activation fnction and a non-linearity. * * \param context the training context */ template<typename C> void adapt_errors(C& context) const { cpp_unused(context); } /*! * \brief Backpropagate the errors to the previous layers * \param output The ETL expression into which write the output * \param context The training context */ template<typename H, typename C> void backward_batch(H&& output, C& context) const { dll::auto_timer timer("bn:2d:backward"); const auto B = etl::dim<0>(context.input); auto& dgamma = std::get<0>(context.up.context)->grad; auto& dbeta = std::get<1>(context.up.context)->grad; dbeta = bias_batch_sum_2d(context.errors); dgamma = bias_batch_sum_2d(input_pre >> context.errors); for(size_t b = 0; b < B; ++b){ output(b) = (1.0 / B) >> inv_var >> gamma >> ((B >> context.errors(b)) - (input_pre(b) >> dgamma) - dbeta); } } /*! * \brief Compute the gradients for this layer, if any * \param context The trainng context */ template<typename C> void compute_gradients(C& context) const { // If the layer is not the first one, the gradients already have been computed if (!C::layer) { dll::auto_timer timer("bn:2d:gradients"); // Gradients of gamma std::get<0>(context.up.context)->grad = bias_batch_sum_2d(input_pre >> context.errors); // Gradients of beta std::get<1>(context.up.context)->grad = bias_batch_sum_2d(context.errors); } } /*! * \brief Prepare one empty output for this layer * \return an empty ETL matrix suitable to store one output of this layer * * \tparam Input The type of one Input */ template <typename InputType> output_one_t prepare_one_output() const { return {}; } /*! * \brief Prepare a set of empty outputs for this layer * \param samples The number of samples to prepare the output for * \return a container containing empty ETL matrices suitable to store samples output of this layer * \tparam Input The type of one input */ template <typename InputType> static output_t prepare_output(size_t samples) { return output_t{samples}; } /*! * \brief Initialize the dynamic version of the layer from the fast version of the layer * \param dyn Reference to the dynamic version of the layer that needs to be initialized */ template<typename DLayer> static void dyn_init(DLayer& dyn){ dyn.init_layer(Input); } /*! * \brief Returns the trainable variables of this layer. * \return a tuple containing references to the variables of this layer */ decltype(auto) trainable_parameters(){ return std::make_tuple(std::ref(gamma), std::ref(beta)); } /*! * \brief Returns the trainable variables of this layer. * \return a tuple containing references to the variables of this layer */ decltype(auto) trainable_parameters() const { return std::make_tuple(std::cref(gamma), std::cref(beta)); } /*! * \brief Backup the weights in the secondary weights matrix */ void backup_weights() { unique_safe_get(bak_gamma) = gamma; unique_safe_get(bak_beta) = beta; } /*! * \brief Restore the weights from the secondary weights matrix */ void restore_weights() { gamma = *bak_gamma; beta = *bak_beta; } }; // Declare the traits for the layer template<typename Desc> struct layer_base_traits<batch_normalization_2d_layer_impl<Desc>> { static constexpr bool is_neural = true; ///< Indicates if the layer is a neural layer static constexpr bool is_dense = false; ///< Indicates if the layer is dense static constexpr bool is_conv = false; ///< Indicates if the layer is convolutional static constexpr bool is_deconv = false; ///< Indicates if the layer is deconvolutional static constexpr bool is_standard = false; ///< Indicates if the layer is standard static constexpr bool is_rbm = false; ///< Indicates if the layer is RBM static constexpr bool is_pooling = false; ///< Indicates if the layer is a pooling layer static constexpr bool is_unpooling = false; ///< Indicates if the layer is an unpooling laye static constexpr bool is_transform = false; ///< Indicates if the layer is a transform layer static constexpr bool is_dynamic = false; ///< Indicates if the layer is dynamic static constexpr bool pretrain_last = false; ///< Indicates if the layer is dynamic static constexpr bool sgd_supported = true; ///< Indicates if the layer is supported by SGD }; /*! * \brief Specialization of sgd_context for batch_normalization_2d_layer_impl */ template <typename DBN, typename Desc, size_t L> struct sgd_context<DBN, batch_normalization_2d_layer_impl<Desc>, L> { using layer_t = batch_normalization_2d_layer_impl<Desc>; ///< The current layer type using weight = typename layer_t::weight; ///< The data type for this layer static constexpr auto batch_size = DBN::batch_size; ///< The batch size of the network static constexpr auto layer = L; ///> The layer's index etl::fast_matrix<weight, batch_size, Desc::Input> input; ///< A batch of input etl::fast_matrix<weight, batch_size, Desc::Input> output; ///< A batch of output etl::fast_matrix<weight, batch_size, Desc::Input> errors; ///< A batch of errors sgd_context(const layer_t& /*layer*/){} }; } //end of dll namespace
Make BN fast for static layer
Make BN fast for static layer
C++
mit
wichtounet/dll,wichtounet/dll,wichtounet/dll
fbff189e556bcb7c8fd5770b8aa4656d63d690c1
src/clustering/immediate_consistency/branch/backfiller.cc
src/clustering/immediate_consistency/branch/backfiller.cc
#include "clustering/immediate_consistency/branch/backfiller.hpp" #include "btree/parallel_traversal.hpp" #include "clustering/immediate_consistency/branch/history.hpp" #include "clustering/immediate_consistency/branch/multistore.hpp" #include "concurrency/fifo_enforcer.hpp" #include "concurrency/semaphore.hpp" #include "rpc/semilattice/view.hpp" #include "stl_utils.hpp" #define MAX_CHUNKS_OUT 5000 inline state_timestamp_t get_earliest_timestamp_of_version_range(const version_range_t &vr) { return vr.earliest.timestamp; } template <class protocol_t> backfiller_t<protocol_t>::backfiller_t(mailbox_manager_t *mm, branch_history_manager_t<protocol_t> *bhm, multistore_ptr_t<protocol_t> *_svs) : mailbox_manager(mm), branch_history_manager(bhm), svs(_svs), backfill_mailbox(mailbox_manager, boost::bind(&backfiller_t::on_backfill, this, _1, _2, _3, _4, _5, _6, _7, auto_drainer_t::lock_t(&drainer))), cancel_backfill_mailbox(mailbox_manager, boost::bind(&backfiller_t::on_cancel_backfill, this, _1, auto_drainer_t::lock_t(&drainer))), request_progress_mailbox(mailbox_manager, boost::bind(&backfiller_t::request_backfill_progress, this, _1, _2, auto_drainer_t::lock_t(&drainer))) { } template <class protocol_t> backfiller_business_card_t<protocol_t> backfiller_t<protocol_t>::get_business_card() { return backfiller_business_card_t<protocol_t>(backfill_mailbox.get_address(), cancel_backfill_mailbox.get_address(), request_progress_mailbox.get_address() ); } template <class protocol_t> bool backfiller_t<protocol_t>::confirm_and_send_metainfo(typename store_view_t<protocol_t>::metainfo_t metainfo, DEBUG_VAR region_map_t<protocol_t, version_range_t> start_point, mailbox_addr_t<void(region_map_t<protocol_t, version_range_t>, branch_history_t<protocol_t>)> end_point_cont) { rassert(metainfo.get_domain() == start_point.get_domain()); region_map_t<protocol_t, version_range_t> end_point = region_map_transform<protocol_t, binary_blob_t, version_range_t>(metainfo, &binary_blob_t::get<version_range_t> ); #ifndef NDEBUG // TODO: Should the rassert calls in this block of code be return // false statements instead of assertions? Tim doesn't know. // Figure this out. /* Confirm that `start_point` is a point in our past */ typedef region_map_t<protocol_t, version_range_t> version_map_t; for (typename version_map_t::const_iterator it = start_point.begin(); it != start_point.end(); ++it) { for (typename version_map_t::const_iterator jt = end_point.begin(); jt != end_point.end(); ++jt) { typename protocol_t::region_t ixn = region_intersection(it->first, jt->first); if (!region_is_empty(ixn)) { version_t start = it->second.latest; version_t end = jt->second.earliest; rassert(start.timestamp <= end.timestamp); rassert(version_is_ancestor(branch_history_manager, start, end, ixn)); } } } #endif /* Package a subset of the branch history graph that includes every branch that `end_point` mentions and all their ancestors recursively */ branch_history_t<protocol_t> branch_history; branch_history_manager->export_branch_history(end_point, &branch_history); /* Transmit `end_point` to the backfillee */ send(mailbox_manager, end_point_cont, end_point, branch_history); return true; } template <class protocol_t> void do_send_chunk(mailbox_manager_t *mbox_manager, mailbox_addr_t<void(typename protocol_t::backfill_chunk_t, fifo_enforcer_write_token_t)> chunk_addr, const typename protocol_t::backfill_chunk_t &chunk, fifo_enforcer_source_t *fifo_src, semaphore_t *chunk_semaphore) { chunk_semaphore->co_lock(); send(mbox_manager, chunk_addr, chunk, fifo_src->enter_write()); } template <class protocol_t> class backfiller_send_backfill_callback_t : public send_backfill_callback_t<protocol_t> { public: backfiller_send_backfill_callback_t(const region_map_t<protocol_t, version_range_t> *start_point, mailbox_addr_t<void(region_map_t<protocol_t, version_range_t>, branch_history_t<protocol_t>)> end_point_cont, mailbox_manager_t *mailbox_manager, mailbox_addr_t<void(typename protocol_t::backfill_chunk_t, fifo_enforcer_write_token_t)> chunk_cont, fifo_enforcer_source_t *fifo_src, semaphore_t *chunk_semaphore, backfiller_t<protocol_t> *backfiller) : start_point_(start_point), end_point_cont_(end_point_cont), mailbox_manager_(mailbox_manager), chunk_cont_(chunk_cont), fifo_src_(fifo_src), chunk_semaphore_(chunk_semaphore), backfiller_(backfiller) { } bool should_backfill_impl(const typename store_view_t<protocol_t>::metainfo_t &metainfo) { return backfiller_->confirm_and_send_metainfo(metainfo, *start_point_, end_point_cont_); } void send_chunk(const typename protocol_t::backfill_chunk_t &chunk) { do_send_chunk<protocol_t>(mailbox_manager_, chunk_cont_, chunk, fifo_src_, chunk_semaphore_); } private: const region_map_t<protocol_t, version_range_t> *start_point_; mailbox_addr_t<void(region_map_t<protocol_t, version_range_t>, branch_history_t<protocol_t>)> end_point_cont_; mailbox_manager_t *mailbox_manager_; mailbox_addr_t<void(typename protocol_t::backfill_chunk_t, fifo_enforcer_write_token_t)> chunk_cont_; fifo_enforcer_source_t *fifo_src_; semaphore_t *chunk_semaphore_; backfiller_t<protocol_t> *backfiller_; DISABLE_COPYING(backfiller_send_backfill_callback_t); }; template <class protocol_t> void backfiller_t<protocol_t>::on_backfill(backfill_session_id_t session_id, const region_map_t<protocol_t, version_range_t> &start_point, const branch_history_t<protocol_t> &start_point_associated_branch_history, mailbox_addr_t<void(region_map_t<protocol_t, version_range_t>, branch_history_t<protocol_t>)> end_point_cont, mailbox_addr_t<void(typename protocol_t::backfill_chunk_t, fifo_enforcer_write_token_t)> chunk_cont, mailbox_addr_t<void(fifo_enforcer_write_token_t)> done_cont, mailbox_addr_t<void(mailbox_addr_t<void(int)>)> allocation_registration_box, auto_drainer_t::lock_t keepalive) { assert_thread(); rassert(region_is_superset(svs->get_multistore_joined_region(), start_point.get_domain())); /* Set up a local interruptor cond and put it in the map so that this session can be interrupted if the backfillee decides to abort */ cond_t local_interruptor; map_insertion_sentry_t<backfill_session_id_t, cond_t *> be_interruptible(&local_interruptors, session_id, &local_interruptor); /* Set up a local progress monitor so people can query us for progress. */ traversal_progress_combiner_t local_progress; map_insertion_sentry_t<backfill_session_id_t, traversal_progress_combiner_t *> display_progress(&local_backfill_progress, session_id, &local_progress); /* Set up a cond that gets pulsed if we're interrupted by either the backfillee stopping or the backfiller destructor being called, but don't wait on that cond yet. */ wait_any_t interrupted(&local_interruptor, keepalive.get_drain_signal()); semaphore_t chunk_semaphore(MAX_CHUNKS_OUT); mailbox_t<void(int)> receive_allocations_mbox(mailbox_manager, boost::bind(&semaphore_t::unlock, &chunk_semaphore, _1), mailbox_callback_mode_inline); send(mailbox_manager, allocation_registration_box, receive_allocations_mbox.get_address()); try { branch_history_manager->import_branch_history(start_point_associated_branch_history, keepalive.get_drain_signal()); // TODO: Describe this fifo source's purpose a bit. It's for ordering backfill operations, right? fifo_enforcer_source_t fifo_src; scoped_ptr_t<fifo_enforcer_sink_t::exit_read_t> send_backfill_token; svs->new_read_token(&send_backfill_token); backfiller_send_backfill_callback_t<protocol_t> send_backfill_cb(&start_point, end_point_cont, mailbox_manager, chunk_cont, &fifo_src, &chunk_semaphore, this); /* Actually perform the backfill */ svs->send_multistore_backfill( region_map_transform<protocol_t, version_range_t, state_timestamp_t>( start_point, &get_earliest_timestamp_of_version_range ), &send_backfill_cb, local_backfill_progress[session_id], &send_backfill_token, &interrupted ); /* Send a confirmation */ send(mailbox_manager, done_cont, fifo_src.enter_write()); } catch (interrupted_exc_t) { /* Ignore. If we were interrupted by the backfillee, then it already knows the backfill is cancelled. If we were interrupted by the backfiller shutting down, it will know when it sees we deconstructed our `resource_advertisement_t`. */ } } template <class protocol_t> void backfiller_t<protocol_t>::on_cancel_backfill(backfill_session_id_t session_id, UNUSED auto_drainer_t::lock_t) { assert_thread(); typename std::map<backfill_session_id_t, cond_t *>::iterator it = local_interruptors.find(session_id); if (it != local_interruptors.end()) { (*it).second->pulse(); } else { /* The backfill ended on its own right as we were trying to cancel it. Since the backfill was over, we removed the local interruptor from the map, but the cancel message was already in flight. Since there is no backfill to cancel, we just ignore the cancel message. */ } } template <class protocol_t> void backfiller_t<protocol_t>::request_backfill_progress(backfill_session_id_t session_id, mailbox_addr_t<void(std::pair<int, int>)> response_mbox, auto_drainer_t::lock_t) { if (std_contains(local_backfill_progress, session_id) && local_backfill_progress[session_id]) { progress_completion_fraction_t fraction = local_backfill_progress[session_id]->guess_completion(); std::pair<int, int> pair_fraction = std::make_pair(fraction.estimate_of_released_nodes, fraction.estimate_of_total_nodes); send(mailbox_manager, response_mbox, pair_fraction); } else { send(mailbox_manager, response_mbox, std::make_pair(-1, -1)); } //TODO indicate an error has occurred } #include "memcached/protocol.hpp" #include "mock/dummy_protocol.hpp" #include "rdb_protocol/protocol.hpp" template class backfiller_t<mock::dummy_protocol_t>; template class backfiller_t<memcached_protocol_t>; template class backfiller_t<rdb_protocol_t>;
#include "clustering/immediate_consistency/branch/backfiller.hpp" #include "btree/parallel_traversal.hpp" #include "clustering/immediate_consistency/branch/history.hpp" #include "clustering/immediate_consistency/branch/multistore.hpp" #include "concurrency/fifo_enforcer.hpp" #include "concurrency/semaphore.hpp" #include "rpc/semilattice/view.hpp" #include "stl_utils.hpp" #define MAX_CHUNKS_OUT 5000 inline state_timestamp_t get_earliest_timestamp_of_version_range(const version_range_t &vr) { return vr.earliest.timestamp; } template <class protocol_t> backfiller_t<protocol_t>::backfiller_t(mailbox_manager_t *mm, branch_history_manager_t<protocol_t> *bhm, multistore_ptr_t<protocol_t> *_svs) : mailbox_manager(mm), branch_history_manager(bhm), svs(_svs), backfill_mailbox(mailbox_manager, boost::bind(&backfiller_t::on_backfill, this, _1, _2, _3, _4, _5, _6, _7, auto_drainer_t::lock_t(&drainer))), cancel_backfill_mailbox(mailbox_manager, boost::bind(&backfiller_t::on_cancel_backfill, this, _1, auto_drainer_t::lock_t(&drainer))), request_progress_mailbox(mailbox_manager, boost::bind(&backfiller_t::request_backfill_progress, this, _1, _2, auto_drainer_t::lock_t(&drainer))) { } template <class protocol_t> backfiller_business_card_t<protocol_t> backfiller_t<protocol_t>::get_business_card() { return backfiller_business_card_t<protocol_t>(backfill_mailbox.get_address(), cancel_backfill_mailbox.get_address(), request_progress_mailbox.get_address() ); } template <class protocol_t> bool backfiller_t<protocol_t>::confirm_and_send_metainfo(typename store_view_t<protocol_t>::metainfo_t metainfo, DEBUG_VAR region_map_t<protocol_t, version_range_t> start_point, mailbox_addr_t<void(region_map_t<protocol_t, version_range_t>, branch_history_t<protocol_t>)> end_point_cont) { rassert(metainfo.get_domain() == start_point.get_domain()); region_map_t<protocol_t, version_range_t> end_point = region_map_transform<protocol_t, binary_blob_t, version_range_t>(metainfo, &binary_blob_t::get<version_range_t> ); #ifndef NDEBUG // TODO: Should the rassert calls in this block of code be return // false statements instead of assertions? Tim doesn't know. // Figure this out. /* Confirm that `start_point` is a point in our past */ typedef region_map_t<protocol_t, version_range_t> version_map_t; for (typename version_map_t::const_iterator it = start_point.begin(); it != start_point.end(); ++it) { for (typename version_map_t::const_iterator jt = end_point.begin(); jt != end_point.end(); ++jt) { typename protocol_t::region_t ixn = region_intersection(it->first, jt->first); if (!region_is_empty(ixn)) { version_t start = it->second.latest; version_t end = jt->second.earliest; rassert(start.timestamp <= end.timestamp); rassert(version_is_ancestor(branch_history_manager, start, end, ixn)); } } } #endif /* Package a subset of the branch history graph that includes every branch that `end_point` mentions and all their ancestors recursively */ branch_history_t<protocol_t> branch_history; branch_history_manager->export_branch_history(end_point, &branch_history); /* Transmit `end_point` to the backfillee */ send(mailbox_manager, end_point_cont, end_point, branch_history); return true; } template <class protocol_t> void do_send_chunk(mailbox_manager_t *mbox_manager, mailbox_addr_t<void(typename protocol_t::backfill_chunk_t, fifo_enforcer_write_token_t)> chunk_addr, const typename protocol_t::backfill_chunk_t &chunk, fifo_enforcer_source_t *fifo_src, semaphore_t *chunk_semaphore) { chunk_semaphore->co_lock(); send(mbox_manager, chunk_addr, chunk, fifo_src->enter_write()); } template <class protocol_t> class backfiller_send_backfill_callback_t : public send_backfill_callback_t<protocol_t> { public: backfiller_send_backfill_callback_t(const region_map_t<protocol_t, version_range_t> *start_point, mailbox_addr_t<void(region_map_t<protocol_t, version_range_t>, branch_history_t<protocol_t>)> end_point_cont, mailbox_manager_t *mailbox_manager, mailbox_addr_t<void(typename protocol_t::backfill_chunk_t, fifo_enforcer_write_token_t)> chunk_cont, fifo_enforcer_source_t *fifo_src, semaphore_t *chunk_semaphore, backfiller_t<protocol_t> *backfiller) : start_point_(start_point), end_point_cont_(end_point_cont), mailbox_manager_(mailbox_manager), chunk_cont_(chunk_cont), fifo_src_(fifo_src), chunk_semaphore_(chunk_semaphore), backfiller_(backfiller) { } bool should_backfill_impl(const typename store_view_t<protocol_t>::metainfo_t &metainfo) { return backfiller_->confirm_and_send_metainfo(metainfo, *start_point_, end_point_cont_); } void send_chunk(const typename protocol_t::backfill_chunk_t &chunk) { do_send_chunk<protocol_t>(mailbox_manager_, chunk_cont_, chunk, fifo_src_, chunk_semaphore_); } private: const region_map_t<protocol_t, version_range_t> *start_point_; mailbox_addr_t<void(region_map_t<protocol_t, version_range_t>, branch_history_t<protocol_t>)> end_point_cont_; mailbox_manager_t *mailbox_manager_; mailbox_addr_t<void(typename protocol_t::backfill_chunk_t, fifo_enforcer_write_token_t)> chunk_cont_; fifo_enforcer_source_t *fifo_src_; semaphore_t *chunk_semaphore_; backfiller_t<protocol_t> *backfiller_; DISABLE_COPYING(backfiller_send_backfill_callback_t); }; template <class protocol_t> void backfiller_t<protocol_t>::on_backfill(backfill_session_id_t session_id, const region_map_t<protocol_t, version_range_t> &start_point, const branch_history_t<protocol_t> &start_point_associated_branch_history, mailbox_addr_t<void(region_map_t<protocol_t, version_range_t>, branch_history_t<protocol_t>)> end_point_cont, mailbox_addr_t<void(typename protocol_t::backfill_chunk_t, fifo_enforcer_write_token_t)> chunk_cont, mailbox_addr_t<void(fifo_enforcer_write_token_t)> done_cont, mailbox_addr_t<void(mailbox_addr_t<void(int)>)> allocation_registration_box, auto_drainer_t::lock_t keepalive) { assert_thread(); rassert(region_is_superset(svs->get_multistore_joined_region(), start_point.get_domain())); /* Set up a local interruptor cond and put it in the map so that this session can be interrupted if the backfillee decides to abort */ cond_t local_interruptor; map_insertion_sentry_t<backfill_session_id_t, cond_t *> be_interruptible(&local_interruptors, session_id, &local_interruptor); /* Set up a local progress monitor so people can query us for progress. */ traversal_progress_combiner_t local_progress; map_insertion_sentry_t<backfill_session_id_t, traversal_progress_combiner_t *> display_progress(&local_backfill_progress, session_id, &local_progress); /* Set up a cond that gets pulsed if we're interrupted by either the backfillee stopping or the backfiller destructor being called, but don't wait on that cond yet. */ wait_any_t interrupted(&local_interruptor, keepalive.get_drain_signal()); semaphore_t chunk_semaphore(MAX_CHUNKS_OUT); mailbox_t<void(int)> receive_allocations_mbox(mailbox_manager, boost::bind(&semaphore_t::unlock, &chunk_semaphore, _1), mailbox_callback_mode_inline); send(mailbox_manager, allocation_registration_box, receive_allocations_mbox.get_address()); try { branch_history_manager->import_branch_history(start_point_associated_branch_history, keepalive.get_drain_signal()); // TODO: Describe this fifo source's purpose a bit. It's for ordering backfill operations, right? fifo_enforcer_source_t fifo_src; scoped_ptr_t<fifo_enforcer_sink_t::exit_read_t> send_backfill_token; svs->new_read_token(&send_backfill_token); backfiller_send_backfill_callback_t<protocol_t> send_backfill_cb(&start_point, end_point_cont, mailbox_manager, chunk_cont, &fifo_src, &chunk_semaphore, this); /* Actually perform the backfill */ svs->send_multistore_backfill( region_map_transform<protocol_t, version_range_t, state_timestamp_t>( start_point, &get_earliest_timestamp_of_version_range ), &send_backfill_cb, local_backfill_progress[session_id], &send_backfill_token, &interrupted ); /* Send a confirmation */ send(mailbox_manager, done_cont, fifo_src.enter_write()); } catch (interrupted_exc_t) { /* Ignore. If we were interrupted by the backfillee, then it already knows the backfill is cancelled. If we were interrupted by the backfiller shutting down, the backfillee will find out via the directory. */ } } template <class protocol_t> void backfiller_t<protocol_t>::on_cancel_backfill(backfill_session_id_t session_id, UNUSED auto_drainer_t::lock_t) { assert_thread(); typename std::map<backfill_session_id_t, cond_t *>::iterator it = local_interruptors.find(session_id); if (it != local_interruptors.end()) { (*it).second->pulse(); } else { /* The backfill ended on its own right as we were trying to cancel it. Since the backfill was over, we removed the local interruptor from the map, but the cancel message was already in flight. Since there is no backfill to cancel, we just ignore the cancel message. */ } } template <class protocol_t> void backfiller_t<protocol_t>::request_backfill_progress(backfill_session_id_t session_id, mailbox_addr_t<void(std::pair<int, int>)> response_mbox, auto_drainer_t::lock_t) { if (std_contains(local_backfill_progress, session_id) && local_backfill_progress[session_id]) { progress_completion_fraction_t fraction = local_backfill_progress[session_id]->guess_completion(); std::pair<int, int> pair_fraction = std::make_pair(fraction.estimate_of_released_nodes, fraction.estimate_of_total_nodes); send(mailbox_manager, response_mbox, pair_fraction); } else { send(mailbox_manager, response_mbox, std::make_pair(-1, -1)); } //TODO indicate an error has occurred } #include "memcached/protocol.hpp" #include "mock/dummy_protocol.hpp" #include "rdb_protocol/protocol.hpp" template class backfiller_t<mock::dummy_protocol_t>; template class backfiller_t<memcached_protocol_t>; template class backfiller_t<rdb_protocol_t>;
Improve comment.
Improve comment.
C++
agpl-3.0
rrampage/rethinkdb,AtnNn/rethinkdb,pap/rethinkdb,niieani/rethinkdb,greyhwndz/rethinkdb,mquandalle/rethinkdb,grandquista/rethinkdb,gavioto/rethinkdb,elkingtonmcb/rethinkdb,catroot/rethinkdb,wojons/rethinkdb,niieani/rethinkdb,victorbriz/rethinkdb,Qinusty/rethinkdb,losywee/rethinkdb,tempbottle/rethinkdb,eliangidoni/rethinkdb,4talesa/rethinkdb,mcanthony/rethinkdb,grandquista/rethinkdb,jfriedly/rethinkdb,Qinusty/rethinkdb,niieani/rethinkdb,ayumilong/rethinkdb,rrampage/rethinkdb,alash3al/rethinkdb,4talesa/rethinkdb,JackieXie168/rethinkdb,4talesa/rethinkdb,mquandalle/rethinkdb,RubenKelevra/rethinkdb,marshall007/rethinkdb,wojons/rethinkdb,JackieXie168/rethinkdb,wojons/rethinkdb,yakovenkodenis/rethinkdb,pap/rethinkdb,eliangidoni/rethinkdb,wkennington/rethinkdb,bchavez/rethinkdb,jfriedly/rethinkdb,mbroadst/rethinkdb,robertjpayne/rethinkdb,niieani/rethinkdb,bchavez/rethinkdb,Wilbeibi/rethinkdb,alash3al/rethinkdb,ayumilong/rethinkdb,elkingtonmcb/rethinkdb,yaolinz/rethinkdb,tempbottle/rethinkdb,KSanthanam/rethinkdb,rrampage/rethinkdb,ayumilong/rethinkdb,bchavez/rethinkdb,JackieXie168/rethinkdb,Wilbeibi/rethinkdb,spblightadv/rethinkdb,Wilbeibi/rethinkdb,sebadiaz/rethinkdb,matthaywardwebdesign/rethinkdb,RubenKelevra/rethinkdb,marshall007/rethinkdb,nviennot/rethinkdb,AtnNn/rethinkdb,jesseditson/rethinkdb,sontek/rethinkdb,wojons/rethinkdb,gdi2290/rethinkdb,matthaywardwebdesign/rethinkdb,4talesa/rethinkdb,grandquista/rethinkdb,jesseditson/rethinkdb,ayumilong/rethinkdb,AntouanK/rethinkdb,gavioto/rethinkdb,wojons/rethinkdb,AtnNn/rethinkdb,captainpete/rethinkdb,wkennington/rethinkdb,sontek/rethinkdb,mquandalle/rethinkdb,alash3al/rethinkdb,sbusso/rethinkdb,mquandalle/rethinkdb,catroot/rethinkdb,eliangidoni/rethinkdb,mquandalle/rethinkdb,RubenKelevra/rethinkdb,nviennot/rethinkdb,wujf/rethinkdb,grandquista/rethinkdb,wujf/rethinkdb,losywee/rethinkdb,gavioto/rethinkdb,KSanthanam/rethinkdb,lenstr/rethinkdb,greyhwndz/rethinkdb,eliangidoni/rethinkdb,gdi2290/rethinkdb,scripni/rethinkdb,dparnell/rethinkdb,marshall007/rethinkdb,sbusso/rethinkdb,yaolinz/rethinkdb,wujf/rethinkdb,matthaywardwebdesign/rethinkdb,sebadiaz/rethinkdb,bchavez/rethinkdb,matthaywardwebdesign/rethinkdb,eliangidoni/rethinkdb,tempbottle/rethinkdb,gdi2290/rethinkdb,rrampage/rethinkdb,ajose01/rethinkdb,dparnell/rethinkdb,nviennot/rethinkdb,4talesa/rethinkdb,mbroadst/rethinkdb,robertjpayne/rethinkdb,niieani/rethinkdb,robertjpayne/rethinkdb,bpradipt/rethinkdb,victorbriz/rethinkdb,jesseditson/rethinkdb,jmptrader/rethinkdb,grandquista/rethinkdb,elkingtonmcb/rethinkdb,JackieXie168/rethinkdb,bpradipt/rethinkdb,urandu/rethinkdb,mcanthony/rethinkdb,jmptrader/rethinkdb,sbusso/rethinkdb,captainpete/rethinkdb,Wilbeibi/rethinkdb,bpradipt/rethinkdb,bchavez/rethinkdb,nviennot/rethinkdb,gavioto/rethinkdb,gavioto/rethinkdb,KSanthanam/rethinkdb,RubenKelevra/rethinkdb,JackieXie168/rethinkdb,bpradipt/rethinkdb,eliangidoni/rethinkdb,AntouanK/rethinkdb,sontek/rethinkdb,sontek/rethinkdb,spblightadv/rethinkdb,sebadiaz/rethinkdb,pap/rethinkdb,losywee/rethinkdb,tempbottle/rethinkdb,jfriedly/rethinkdb,mbroadst/rethinkdb,dparnell/rethinkdb,4talesa/rethinkdb,bpradipt/rethinkdb,bpradipt/rethinkdb,urandu/rethinkdb,Qinusty/rethinkdb,catroot/rethinkdb,captainpete/rethinkdb,RubenKelevra/rethinkdb,yakovenkodenis/rethinkdb,jesseditson/rethinkdb,pap/rethinkdb,Qinusty/rethinkdb,ajose01/rethinkdb,AtnNn/rethinkdb,robertjpayne/rethinkdb,spblightadv/rethinkdb,losywee/rethinkdb,RubenKelevra/rethinkdb,wojons/rethinkdb,yaolinz/rethinkdb,spblightadv/rethinkdb,greyhwndz/rethinkdb,AtnNn/rethinkdb,yaolinz/rethinkdb,gdi2290/rethinkdb,scripni/rethinkdb,mcanthony/rethinkdb,urandu/rethinkdb,jmptrader/rethinkdb,dparnell/rethinkdb,ayumilong/rethinkdb,mcanthony/rethinkdb,spblightadv/rethinkdb,jesseditson/rethinkdb,jmptrader/rethinkdb,sebadiaz/rethinkdb,alash3al/rethinkdb,gavioto/rethinkdb,greyhwndz/rethinkdb,catroot/rethinkdb,bpradipt/rethinkdb,dparnell/rethinkdb,niieani/rethinkdb,wujf/rethinkdb,mbroadst/rethinkdb,sebadiaz/rethinkdb,KSanthanam/rethinkdb,jmptrader/rethinkdb,AntouanK/rethinkdb,JackieXie168/rethinkdb,RubenKelevra/rethinkdb,Qinusty/rethinkdb,robertjpayne/rethinkdb,wkennington/rethinkdb,matthaywardwebdesign/rethinkdb,scripni/rethinkdb,greyhwndz/rethinkdb,marshall007/rethinkdb,wkennington/rethinkdb,Qinusty/rethinkdb,RubenKelevra/rethinkdb,ajose01/rethinkdb,rrampage/rethinkdb,grandquista/rethinkdb,alash3al/rethinkdb,KSanthanam/rethinkdb,yakovenkodenis/rethinkdb,scripni/rethinkdb,KSanthanam/rethinkdb,losywee/rethinkdb,AntouanK/rethinkdb,gdi2290/rethinkdb,urandu/rethinkdb,scripni/rethinkdb,wujf/rethinkdb,4talesa/rethinkdb,lenstr/rethinkdb,greyhwndz/rethinkdb,mcanthony/rethinkdb,spblightadv/rethinkdb,sebadiaz/rethinkdb,AtnNn/rethinkdb,sbusso/rethinkdb,tempbottle/rethinkdb,lenstr/rethinkdb,scripni/rethinkdb,bchavez/rethinkdb,sbusso/rethinkdb,ayumilong/rethinkdb,Qinusty/rethinkdb,Wilbeibi/rethinkdb,jfriedly/rethinkdb,sontek/rethinkdb,captainpete/rethinkdb,marshall007/rethinkdb,ajose01/rethinkdb,jesseditson/rethinkdb,AntouanK/rethinkdb,Wilbeibi/rethinkdb,nviennot/rethinkdb,jfriedly/rethinkdb,marshall007/rethinkdb,losywee/rethinkdb,dparnell/rethinkdb,urandu/rethinkdb,victorbriz/rethinkdb,bchavez/rethinkdb,sebadiaz/rethinkdb,ayumilong/rethinkdb,mquandalle/rethinkdb,marshall007/rethinkdb,urandu/rethinkdb,yakovenkodenis/rethinkdb,yakovenkodenis/rethinkdb,pap/rethinkdb,AntouanK/rethinkdb,Qinusty/rethinkdb,rrampage/rethinkdb,tempbottle/rethinkdb,yaolinz/rethinkdb,lenstr/rethinkdb,gavioto/rethinkdb,losywee/rethinkdb,sbusso/rethinkdb,robertjpayne/rethinkdb,captainpete/rethinkdb,dparnell/rethinkdb,Wilbeibi/rethinkdb,captainpete/rethinkdb,catroot/rethinkdb,elkingtonmcb/rethinkdb,jesseditson/rethinkdb,spblightadv/rethinkdb,wkennington/rethinkdb,yaolinz/rethinkdb,wkennington/rethinkdb,victorbriz/rethinkdb,gdi2290/rethinkdb,yakovenkodenis/rethinkdb,JackieXie168/rethinkdb,KSanthanam/rethinkdb,grandquista/rethinkdb,robertjpayne/rethinkdb,jesseditson/rethinkdb,lenstr/rethinkdb,mquandalle/rethinkdb,sebadiaz/rethinkdb,nviennot/rethinkdb,niieani/rethinkdb,jmptrader/rethinkdb,matthaywardwebdesign/rethinkdb,gavioto/rethinkdb,alash3al/rethinkdb,ajose01/rethinkdb,JackieXie168/rethinkdb,4talesa/rethinkdb,wujf/rethinkdb,greyhwndz/rethinkdb,catroot/rethinkdb,wujf/rethinkdb,mbroadst/rethinkdb,jfriedly/rethinkdb,sontek/rethinkdb,spblightadv/rethinkdb,dparnell/rethinkdb,lenstr/rethinkdb,robertjpayne/rethinkdb,losywee/rethinkdb,eliangidoni/rethinkdb,marshall007/rethinkdb,catroot/rethinkdb,pap/rethinkdb,KSanthanam/rethinkdb,sbusso/rethinkdb,rrampage/rethinkdb,mcanthony/rethinkdb,yaolinz/rethinkdb,alash3al/rethinkdb,urandu/rethinkdb,mbroadst/rethinkdb,victorbriz/rethinkdb,elkingtonmcb/rethinkdb,robertjpayne/rethinkdb,victorbriz/rethinkdb,captainpete/rethinkdb,yakovenkodenis/rethinkdb,mquandalle/rethinkdb,bpradipt/rethinkdb,ayumilong/rethinkdb,scripni/rethinkdb,urandu/rethinkdb,pap/rethinkdb,AtnNn/rethinkdb,sontek/rethinkdb,AntouanK/rethinkdb,mcanthony/rethinkdb,tempbottle/rethinkdb,scripni/rethinkdb,mbroadst/rethinkdb,jfriedly/rethinkdb,elkingtonmcb/rethinkdb,eliangidoni/rethinkdb,matthaywardwebdesign/rethinkdb,mcanthony/rethinkdb,niieani/rethinkdb,yakovenkodenis/rethinkdb,yaolinz/rethinkdb,catroot/rethinkdb,jfriedly/rethinkdb,pap/rethinkdb,lenstr/rethinkdb,sbusso/rethinkdb,victorbriz/rethinkdb,bchavez/rethinkdb,wojons/rethinkdb,dparnell/rethinkdb,matthaywardwebdesign/rethinkdb,gdi2290/rethinkdb,wkennington/rethinkdb,eliangidoni/rethinkdb,grandquista/rethinkdb,lenstr/rethinkdb,bpradipt/rethinkdb,mbroadst/rethinkdb,AtnNn/rethinkdb,mbroadst/rethinkdb,alash3al/rethinkdb,nviennot/rethinkdb,ajose01/rethinkdb,jmptrader/rethinkdb,ajose01/rethinkdb,AntouanK/rethinkdb,elkingtonmcb/rethinkdb,jmptrader/rethinkdb,nviennot/rethinkdb,victorbriz/rethinkdb,captainpete/rethinkdb,bchavez/rethinkdb,elkingtonmcb/rethinkdb,sontek/rethinkdb,rrampage/rethinkdb,wkennington/rethinkdb,Wilbeibi/rethinkdb,grandquista/rethinkdb,ajose01/rethinkdb,wojons/rethinkdb,JackieXie168/rethinkdb,greyhwndz/rethinkdb,tempbottle/rethinkdb,Qinusty/rethinkdb
2afc1302537b0ddb94677f72d73bee8a7844d7bf
preferences.cpp
preferences.cpp
/* * Copyright (C) 2007-2010 Sebastian Schuberth <sschuberth_AT_gmail_DOT_com> * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <shlobj.h> #include "component.h" #include "resource.h" #include <foobar2000/helpers/win32_dialog.h> #define DEFAULT_CAD_START true #define DEFAULT_CAD_PATH get_registry_string(HKEY_CURRENT_USER,_T("Software\\CD Art Display")) #define DEFAULT_WRITE_RATING false // Returns a registry key's default value in UTF-8. static char const* get_registry_string(HKEY key,LPCTSTR subkey) { TCHAR path[MAX_PATH]; LONG size=MAX_PATH; if (RegQueryValue(key,subkey,path,&size)!=ERROR_SUCCESS) { return NULL; } pfc::stringcvt::string_utf8_from_wide path_utf8; path_utf8.convert(path); return path_utf8; } // {7cef938b-1b5f-4fe5-a8ca-a1711f6de31c} static GUID const cfg_cad_start_guid= { 0x7cef938b, 0x1b5f, 0x4fe5, { 0xa8, 0xca, 0xa1, 0x71, 0x1f, 0x6d, 0xe3, 0x1c } }; cfg_bool cfg_cad_start(cfg_cad_start_guid,DEFAULT_CAD_START); // {33b397c7-8e79-4302-b5af-058a269d0e4d} static GUID const cfg_cad_path_guid= { 0x33b397c7, 0x8e79, 0x4302, { 0xb5, 0xaf, 0x05, 0x8a, 0x26, 0x9d, 0x0e, 0x4d } }; cfg_string cfg_cad_path(cfg_cad_path_guid,DEFAULT_CAD_PATH); // {453c4714-7147-42a2-bae2-da0a6935a707} static GUID const cfg_write_rating_guid= { 0x453c4714, 0x7147, 0x42a2, { 0xba, 0xe2, 0xda, 0x0a, 0x69, 0x35, 0xa7, 0x07 } }; cfg_bool cfg_write_rating(cfg_write_rating_guid,DEFAULT_WRITE_RATING); class CDArtDisplayPreferences:public preferences_page { public: HWND create(HWND p_parent) { return uCreateDialog(IDD_CONFIG,p_parent,WindowProc); } char const* get_name() { static char const* name="CD Art Display Interface"; return name; } GUID get_guid() { // {8ae21164-7867-4fc0-9545-f5fe97dfe896} static GUID const guid= { 0x8ae21164, 0x7867, 0x4fc0, { 0x95, 0x45, 0xf5, 0xfe, 0x97, 0xdf, 0xe8, 0x96 } }; return guid; } GUID get_parent_guid() { return guid_tools; } bool reset_query() { return true; } void reset() { cfg_cad_start=DEFAULT_CAD_START; cfg_cad_path=DEFAULT_CAD_PATH; cfg_write_rating=DEFAULT_WRITE_RATING; } bool get_help_url(pfc::string_base& p_out) { p_out="http://www.cdartdisplay.com/forum/"; return true; } private: static int CALLBACK WindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: { // Set the check box state according to the stored configuration. uSendDlgItemMessage(hWnd,IDC_CAD_START,BM_SETCHECK,cfg_cad_start,0); EnableWindow(GetDlgItem(hWnd,IDC_CAD_PATH),cfg_cad_start); // Get the foobar2000 configuration strings and convert them to // the OS' format. pfc::stringcvt::string_os_from_utf8 path2os; path2os.convert(cfg_cad_path); uSendDlgItemMessage(hWnd,IDC_CAD_PATH,WM_SETTEXT,0,reinterpret_cast<LPARAM>(path2os.get_ptr())); // Set the stored configuration for writing the rating to tags. uSendDlgItemMessage(hWnd,IDC_WRITE_RATING,BM_SETCHECK,cfg_write_rating,0); return TRUE; } case WM_COMMAND: { // Get all edit control string in the OS' format and convert them // to UTF-8 for foobar2000. pfc::stringcvt::string_utf8_from_os path2utf8; TCHAR path[MAX_PATH]; LRESULT result; switch (LOWORD(wParam)) { case IDC_CAD_START: { // Get the check box state and toggle the edit control accordingly. cfg_cad_start=uSendDlgItemMessage(hWnd,IDC_CAD_START,BM_GETCHECK,0,0)!=0; EnableWindow(GetDlgItem(hWnd,IDC_CAD_PATH),cfg_cad_start); break; } case IDC_CAD_PATH: { if (HIWORD(wParam)==EN_CHANGE) { result=uSendDlgItemMessage(hWnd,IDC_CAD_PATH,WM_GETTEXT,MAX_PATH,reinterpret_cast<LPARAM>(path)); if (result==0) { cfg_cad_path.reset(); } else if (result>0) { path2utf8.convert(path); cfg_cad_path=path2utf8; } } break; } case IDC_WRITE_RATING: { // Get the check box state and toggle the edit control accordingly. cfg_write_rating=uSendDlgItemMessage(hWnd,IDC_WRITE_RATING,BM_GETCHECK,0,0)!=0; break; } default: { return 1; } } return 0; } } return DefWindowProc(hWnd,uMsg,wParam,lParam); } }; static preferences_page_factory_t<CDArtDisplayPreferences> foo_preferences;
/* * Copyright (C) 2007-2010 Sebastian Schuberth <sschuberth_AT_gmail_DOT_com> * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <shlobj.h> #include "component.h" #include "resource.h" #include <foobar2000/helpers/win32_dialog.h> #define DEFAULT_CAD_START true #define DEFAULT_CAD_PATH get_registry_string(HKEY_CURRENT_USER,_T("Software\\CD Art Display")) #define DEFAULT_WRITE_RATING false // Returns a registry key's default value in UTF-8. static char const* get_registry_string(HKEY key,LPCTSTR subkey) { TCHAR path[MAX_PATH]; LONG size=sizeof(path); if (RegQueryValue(key,subkey,path,&size)!=ERROR_SUCCESS) { return NULL; } pfc::stringcvt::string_utf8_from_wide path_utf8; path_utf8.convert(path); return path_utf8; } // {7cef938b-1b5f-4fe5-a8ca-a1711f6de31c} static GUID const cfg_cad_start_guid= { 0x7cef938b, 0x1b5f, 0x4fe5, { 0xa8, 0xca, 0xa1, 0x71, 0x1f, 0x6d, 0xe3, 0x1c } }; cfg_bool cfg_cad_start(cfg_cad_start_guid,DEFAULT_CAD_START); // {33b397c7-8e79-4302-b5af-058a269d0e4d} static GUID const cfg_cad_path_guid= { 0x33b397c7, 0x8e79, 0x4302, { 0xb5, 0xaf, 0x05, 0x8a, 0x26, 0x9d, 0x0e, 0x4d } }; cfg_string cfg_cad_path(cfg_cad_path_guid,DEFAULT_CAD_PATH); // {453c4714-7147-42a2-bae2-da0a6935a707} static GUID const cfg_write_rating_guid= { 0x453c4714, 0x7147, 0x42a2, { 0xba, 0xe2, 0xda, 0x0a, 0x69, 0x35, 0xa7, 0x07 } }; cfg_bool cfg_write_rating(cfg_write_rating_guid,DEFAULT_WRITE_RATING); class CDArtDisplayPreferences:public preferences_page { public: HWND create(HWND p_parent) { return uCreateDialog(IDD_CONFIG,p_parent,WindowProc); } char const* get_name() { static char const* name="CD Art Display Interface"; return name; } GUID get_guid() { // {8ae21164-7867-4fc0-9545-f5fe97dfe896} static GUID const guid= { 0x8ae21164, 0x7867, 0x4fc0, { 0x95, 0x45, 0xf5, 0xfe, 0x97, 0xdf, 0xe8, 0x96 } }; return guid; } GUID get_parent_guid() { return guid_tools; } bool reset_query() { return true; } void reset() { cfg_cad_start=DEFAULT_CAD_START; cfg_cad_path=DEFAULT_CAD_PATH; cfg_write_rating=DEFAULT_WRITE_RATING; } bool get_help_url(pfc::string_base& p_out) { p_out="http://www.cdartdisplay.com/forum/"; return true; } private: static int CALLBACK WindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: { // Set the check box state according to the stored configuration. uSendDlgItemMessage(hWnd,IDC_CAD_START,BM_SETCHECK,cfg_cad_start,0); EnableWindow(GetDlgItem(hWnd,IDC_CAD_PATH),cfg_cad_start); // Get the foobar2000 configuration strings and convert them to // the OS' format. pfc::stringcvt::string_os_from_utf8 path2os; path2os.convert(cfg_cad_path); uSendDlgItemMessage(hWnd,IDC_CAD_PATH,WM_SETTEXT,0,reinterpret_cast<LPARAM>(path2os.get_ptr())); // Set the stored configuration for writing the rating to tags. uSendDlgItemMessage(hWnd,IDC_WRITE_RATING,BM_SETCHECK,cfg_write_rating,0); return TRUE; } case WM_COMMAND: { // Get all edit control string in the OS' format and convert them // to UTF-8 for foobar2000. pfc::stringcvt::string_utf8_from_os path2utf8; TCHAR path[MAX_PATH]; LRESULT result; switch (LOWORD(wParam)) { case IDC_CAD_START: { // Get the check box state and toggle the edit control accordingly. cfg_cad_start=uSendDlgItemMessage(hWnd,IDC_CAD_START,BM_GETCHECK,0,0)!=0; EnableWindow(GetDlgItem(hWnd,IDC_CAD_PATH),cfg_cad_start); break; } case IDC_CAD_PATH: { if (HIWORD(wParam)==EN_CHANGE) { result=uSendDlgItemMessage(hWnd,IDC_CAD_PATH,WM_GETTEXT,MAX_PATH,reinterpret_cast<LPARAM>(path)); if (result==0) { cfg_cad_path.reset(); } else if (result>0) { path2utf8.convert(path); cfg_cad_path=path2utf8; } } break; } case IDC_WRITE_RATING: { // Get the check box state and toggle the edit control accordingly. cfg_write_rating=uSendDlgItemMessage(hWnd,IDC_WRITE_RATING,BM_GETCHECK,0,0)!=0; break; } default: { return 1; } } return 0; } } return DefWindowProc(hWnd,uMsg,wParam,lParam); } }; static preferences_page_factory_t<CDArtDisplayPreferences> foo_preferences;
Fix registry buffer size argument, which needs to be specified in bytes, not characters.
Fix registry buffer size argument, which needs to be specified in bytes, not characters.
C++
lgpl-2.1
sschuberth/foo-cdartdisplay,sschuberth/foo-cdartdisplay,sschuberth/foo-cdartdisplay
32323b84722273a57b89201c88a4ae3b26bd4fb1
chrome/browser/crash_recovery_browsertest.cc
chrome/browser/crash_recovery_browsertest.cc
// Copyright (c) 2010 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/file_path.h" #include "chrome/browser/browser.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/notification_type.h" #include "chrome/common/page_transition_types.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace { void SimulateRendererCrash(Browser* browser) { browser->OpenURL(GURL(chrome::kAboutCrashURL), GURL(), CURRENT_TAB, PageTransition::TYPED); ui_test_utils::WaitForNotification( NotificationType::TAB_CONTENTS_DISCONNECTED); } } // namespace class CrashRecoveryBrowserTest : public InProcessBrowserTest { }; // http://crbug.com/29331 - Causes an OS crash dialog in release mode, needs to // be fixed before it can be enabled to not cause the bots issues. #if defined(OS_MACOSX) #define MAYBE_Reload DISABLED_Reload #endif // Test that reload works after a crash. IN_PROC_BROWSER_TEST_F(CrashRecoveryBrowserTest, MAYBE_Reload) { // The title of the active tab should change each time this URL is loaded. GURL url( "data:text/html,<script>document.title=new Date().valueOf()</script>"); ui_test_utils::NavigateToURL(browser(), url); string16 title_before_crash; string16 title_after_crash; ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title_before_crash)); SimulateRendererCrash(browser()); browser()->Reload(CURRENT_TAB); ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser())); ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title_after_crash)); EXPECT_NE(title_before_crash, title_after_crash); } // Tests that loading a crashed page in a new tab correctly updates the title. // There was an earlier bug (1270510) in process-per-site in which the max page // ID of the RenderProcessHost was stale, so the NavigationEntry in the new tab // was not committed. This prevents regression of that bug. // http://crbug.com/57158 - Times out sometimes on all platforms. IN_PROC_BROWSER_TEST_F(CrashRecoveryBrowserTest, DISABLED_LoadInNewTab) { const FilePath::CharType* kTitle2File = FILE_PATH_LITERAL("title2.html"); ui_test_utils::NavigateToURL(browser(), ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory), FilePath(kTitle2File))); string16 title_before_crash; string16 title_after_crash; ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title_before_crash)); SimulateRendererCrash(browser()); browser()->Reload(CURRENT_TAB); ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser())); ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title_after_crash)); EXPECT_EQ(title_before_crash, title_after_crash); }
// Copyright (c) 2010 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/file_path.h" #include "chrome/browser/browser.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/notification_type.h" #include "chrome/common/page_transition_types.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace { void SimulateRendererCrash(Browser* browser) { browser->OpenURL(GURL(chrome::kAboutCrashURL), GURL(), CURRENT_TAB, PageTransition::TYPED); ui_test_utils::WaitForNotification( NotificationType::TAB_CONTENTS_DISCONNECTED); } } // namespace class CrashRecoveryBrowserTest : public InProcessBrowserTest { }; // http://crbug.com/29331 - Causes an OS crash dialog in release mode, needs to // be fixed before it can be enabled to not cause the bots issues. #if defined(OS_MACOSX) #define MAYBE_Reload DISABLED_Reload #endif // Test that reload works after a crash. // Times out on all platforms after WebKit roll 70722:70770. // http://crbug.com/61097 IN_PROC_BROWSER_TEST_F(CrashRecoveryBrowserTest, DISABLED_Reload) { // The title of the active tab should change each time this URL is loaded. GURL url( "data:text/html,<script>document.title=new Date().valueOf()</script>"); ui_test_utils::NavigateToURL(browser(), url); string16 title_before_crash; string16 title_after_crash; ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title_before_crash)); SimulateRendererCrash(browser()); browser()->Reload(CURRENT_TAB); ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser())); ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title_after_crash)); EXPECT_NE(title_before_crash, title_after_crash); } // Tests that loading a crashed page in a new tab correctly updates the title. // There was an earlier bug (1270510) in process-per-site in which the max page // ID of the RenderProcessHost was stale, so the NavigationEntry in the new tab // was not committed. This prevents regression of that bug. // http://crbug.com/57158 - Times out sometimes on all platforms. IN_PROC_BROWSER_TEST_F(CrashRecoveryBrowserTest, DISABLED_LoadInNewTab) { const FilePath::CharType* kTitle2File = FILE_PATH_LITERAL("title2.html"); ui_test_utils::NavigateToURL(browser(), ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory), FilePath(kTitle2File))); string16 title_before_crash; string16 title_after_crash; ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title_before_crash)); SimulateRendererCrash(browser()); browser()->Reload(CURRENT_TAB); ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser())); ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title_after_crash)); EXPECT_EQ(title_before_crash, title_after_crash); }
Disable CrashRecoveryBrowserTest.Reload for timing out.
Disable CrashRecoveryBrowserTest.Reload for timing out. [email protected] BUG=61097 TEST=none Review URL: http://codereview.chromium.org/4184005 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@64255 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
robclark/chromium,axinging/chromium-crosswalk,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,Chilledheart/chromium,nacl-webkit/chrome_deps,ltilve/chromium,timopulkkinen/BubbleFish,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,Just-D/chromium-1,robclark/chromium,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,M4sse/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,littlstar/chromium.src,jaruba/chromium.src,M4sse/chromium.src,hujiajie/pa-chromium,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,Just-D/chromium-1,jaruba/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,timopulkkinen/BubbleFish,hujiajie/pa-chromium,ltilve/chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,markYoungH/chromium.src,ltilve/chromium,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,jaruba/chromium.src,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,rogerwang/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,littlstar/chromium.src,robclark/chromium,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,robclark/chromium,M4sse/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,keishi/chromium,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,keishi/chromium,anirudhSK/chromium,mogoweb/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,robclark/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,robclark/chromium,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,hujiajie/pa-chromium,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,patrickm/chromium.src,littlstar/chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,ondra-novak/chromium.src,dushu1203/chromium.src,keishi/chromium,M4sse/chromium.src,nacl-webkit/chrome_deps,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,keishi/chromium,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,robclark/chromium,rogerwang/chromium,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,littlstar/chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,anirudhSK/chromium,nacl-webkit/chrome_deps,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,dushu1203/chromium.src,hujiajie/pa-chromium,patrickm/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,robclark/chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,dushu1203/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,rogerwang/chromium,littlstar/chromium.src,dednal/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,rogerwang/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,bright-sparks/chromium-spacewalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,axinging/chromium-crosswalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,keishi/chromium,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,rogerwang/chromium,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,robclark/chromium,hgl888/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,mogoweb/chromium-crosswalk,patrickm/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,nacl-webkit/chrome_deps,hujiajie/pa-chromium,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,ltilve/chromium,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,rogerwang/chromium,rogerwang/chromium,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,ltilve/chromium,M4sse/chromium.src,keishi/chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,rogerwang/chromium,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,junmin-zhu/chromium-rivertrail
7a856a21dec78a5429ecf523c1fc7096eaa05a53
chrome/browser/importer/importer_messages.cc
chrome/browser/importer/importer_messages.cc
// Copyright (c) 2010 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/values.h" #define IPC_MESSAGE_IMPL #include "chrome/browser/importer/importer_messages.h"
// Copyright (c) 2010 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/values.h" #define IPC_MESSAGE_IMPL #include "chrome/browser/importer/importer_messages.h"
Add missing new line
Add missing new line git-svn-id: http://src.chromium.org/svn/trunk/src@68669 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: d5e9727bb025e6c322d3efd7c6ca6c9b552a6853
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
9df8a0ddd328ddc440286360bf9a4bfeecce50e9
chrome/browser/prefs/session_startup_pref.cc
chrome/browser/prefs/session_startup_pref.cc
// 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 "chrome/browser/prefs/session_startup_pref.h" #include <string> #include "base/metrics/histogram.h" #include "base/prefs/pref_service.h" #include "base/prefs/scoped_user_pref_update.h" #include "base/time/time.h" #include "base/values.h" #include "base/version.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/net/url_fixer_upper.h" #include "chrome/common/pref_names.h" #include "components/user_prefs/pref_registry_syncable.h" #if defined(OS_MACOSX) #include "chrome/browser/ui/cocoa/window_restore_utils.h" #endif namespace { enum StartupURLsMigrationMetrics { STARTUP_URLS_MIGRATION_METRICS_PERFORMED, STARTUP_URLS_MIGRATION_METRICS_NOT_PRESENT, STARTUP_URLS_MIGRATION_METRICS_RESET, STARTUP_URLS_MIGRATION_METRICS_MAX, }; // Converts a SessionStartupPref::Type to an integer written to prefs. int TypeToPrefValue(SessionStartupPref::Type type) { switch (type) { case SessionStartupPref::LAST: return SessionStartupPref::kPrefValueLast; case SessionStartupPref::URLS: return SessionStartupPref::kPrefValueURLs; default: return SessionStartupPref::kPrefValueNewTab; } } void SetNewURLList(PrefService* prefs) { if (prefs->IsUserModifiablePreference(prefs::kURLsToRestoreOnStartup)) { base::ListValue new_url_pref_list; base::StringValue* home_page = new base::StringValue(prefs->GetString(prefs::kHomePage)); new_url_pref_list.Append(home_page); prefs->Set(prefs::kURLsToRestoreOnStartup, new_url_pref_list); } } void URLListToPref(const base::ListValue* url_list, SessionStartupPref* pref) { pref->urls.clear(); for (size_t i = 0; i < url_list->GetSize(); ++i) { std::string url_text; if (url_list->GetString(i, &url_text)) { GURL fixed_url = URLFixerUpper::FixupURL(url_text, std::string()); pref->urls.push_back(fixed_url); } } } } // namespace // static void SessionStartupPref::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterIntegerPref( prefs::kRestoreOnStartup, TypeToPrefValue(GetDefaultStartupType()), user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); registry->RegisterListPref(prefs::kURLsToRestoreOnStartup, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); registry->RegisterListPref(prefs::kURLsToRestoreOnStartupOld, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterBooleanPref( prefs::kRestoreOnStartupMigrated, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterInt64Pref( prefs::kRestoreStartupURLsMigrationTime, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); } // static SessionStartupPref::Type SessionStartupPref::GetDefaultStartupType() { #if defined(OS_CHROMEOS) return SessionStartupPref::LAST; #else return SessionStartupPref::DEFAULT; #endif } // static void SessionStartupPref::SetStartupPref( Profile* profile, const SessionStartupPref& pref) { DCHECK(profile); SetStartupPref(profile->GetPrefs(), pref); } // static void SessionStartupPref::SetStartupPref(PrefService* prefs, const SessionStartupPref& pref) { DCHECK(prefs); if (!SessionStartupPref::TypeIsManaged(prefs)) prefs->SetInteger(prefs::kRestoreOnStartup, TypeToPrefValue(pref.type)); if (!SessionStartupPref::URLsAreManaged(prefs)) { // Always save the URLs, that way the UI can remain consistent even if the // user changes the startup type pref. // Ownership of the ListValue retains with the pref service. ListPrefUpdate update(prefs, prefs::kURLsToRestoreOnStartup); ListValue* url_pref_list = update.Get(); DCHECK(url_pref_list); url_pref_list->Clear(); for (size_t i = 0; i < pref.urls.size(); ++i) { url_pref_list->Set(static_cast<int>(i), new StringValue(pref.urls[i].spec())); } } } // static SessionStartupPref SessionStartupPref::GetStartupPref(Profile* profile) { DCHECK(profile); return GetStartupPref(profile->GetPrefs()); } // static SessionStartupPref SessionStartupPref::GetStartupPref(PrefService* prefs) { DCHECK(prefs); MigrateIfNecessary(prefs); MigrateMacDefaultPrefIfNecessary(prefs); SessionStartupPref pref( PrefValueToType(prefs->GetInteger(prefs::kRestoreOnStartup))); // Always load the urls, even if the pref type isn't URLS. This way the // preferences panels can show the user their last choice. const ListValue* url_list = prefs->GetList(prefs::kURLsToRestoreOnStartup); URLListToPref(url_list, &pref); return pref; } // static void SessionStartupPref::MigrateIfNecessary(PrefService* prefs) { DCHECK(prefs); // Check if we need to migrate the old version of the startup URLs preference // to the new name, and also send metrics about the migration. StartupURLsMigrationMetrics metrics_result = STARTUP_URLS_MIGRATION_METRICS_MAX; const base::ListValue* old_startup_urls = prefs->GetList(prefs::kURLsToRestoreOnStartupOld); if (!prefs->GetUserPrefValue(prefs::kRestoreStartupURLsMigrationTime)) { // Record the absence of the migration timestamp, this will get overwritten // below if migration occurs now. metrics_result = STARTUP_URLS_MIGRATION_METRICS_NOT_PRESENT; // Seems like we never migrated, do it if necessary. if (!prefs->GetUserPrefValue(prefs::kURLsToRestoreOnStartup)) { if (old_startup_urls && !old_startup_urls->empty()) { prefs->Set(prefs::kURLsToRestoreOnStartup, *old_startup_urls); prefs->ClearPref(prefs::kURLsToRestoreOnStartupOld); } metrics_result = STARTUP_URLS_MIGRATION_METRICS_PERFORMED; } prefs->SetInt64(prefs::kRestoreStartupURLsMigrationTime, base::Time::Now().ToInternalValue()); } else if (old_startup_urls && !old_startup_urls->empty()) { // Migration needs to be reset. prefs->ClearPref(prefs::kURLsToRestoreOnStartupOld); base::Time last_migration_time = base::Time::FromInternalValue( prefs->GetInt64(prefs::kRestoreStartupURLsMigrationTime)); base::Time now = base::Time::Now(); prefs->SetInt64(prefs::kRestoreStartupURLsMigrationTime, now.ToInternalValue()); if (now < last_migration_time) last_migration_time = now; HISTOGRAM_CUSTOM_TIMES("Settings.StartupURLsResetTime", now - last_migration_time, base::TimeDelta::FromDays(0), base::TimeDelta::FromDays(7), 50); metrics_result = STARTUP_URLS_MIGRATION_METRICS_RESET; } // Record a metric migration event if something interesting happened. if (metrics_result != STARTUP_URLS_MIGRATION_METRICS_MAX) { UMA_HISTOGRAM_ENUMERATION( "Settings.StartupURLsMigration", metrics_result, STARTUP_URLS_MIGRATION_METRICS_MAX); } if (!prefs->GetBoolean(prefs::kRestoreOnStartupMigrated)) { // Read existing values. const base::Value* homepage_is_new_tab_page_value = prefs->GetUserPrefValue(prefs::kHomePageIsNewTabPage); bool homepage_is_new_tab_page = true; if (homepage_is_new_tab_page_value) { if (!homepage_is_new_tab_page_value->GetAsBoolean( &homepage_is_new_tab_page)) NOTREACHED(); } const base::Value* restore_on_startup_value = prefs->GetUserPrefValue(prefs::kRestoreOnStartup); int restore_on_startup = -1; if (restore_on_startup_value) { if (!restore_on_startup_value->GetAsInteger(&restore_on_startup)) NOTREACHED(); } // If restore_on_startup has the deprecated value kPrefValueHomePage, // migrate it to open the homepage on startup. If 'homepage is NTP' is set, // that means just opening the NTP. If not, it means opening a one-item URL // list containing the homepage. if (restore_on_startup == kPrefValueHomePage) { if (homepage_is_new_tab_page) { prefs->SetInteger(prefs::kRestoreOnStartup, kPrefValueNewTab); } else { prefs->SetInteger(prefs::kRestoreOnStartup, kPrefValueURLs); SetNewURLList(prefs); } } else if (!restore_on_startup_value && !homepage_is_new_tab_page && GetDefaultStartupType() == DEFAULT) { // kRestoreOnStartup was never set by the user, but the homepage was set. // Migrate to the list of URLs. (If restore_on_startup was never set, // and homepage_is_new_tab_page is true, no action is needed. The new // default value is "open the new tab page" which is what we want.) prefs->SetInteger(prefs::kRestoreOnStartup, kPrefValueURLs); SetNewURLList(prefs); } prefs->SetBoolean(prefs::kRestoreOnStartupMigrated, true); } } // static void SessionStartupPref::MigrateMacDefaultPrefIfNecessary(PrefService* prefs) { #if defined(OS_MACOSX) DCHECK(prefs); if (!restore_utils::IsWindowRestoreEnabled()) return; // The default startup pref used to be LAST, now it is DEFAULT. Don't change // the setting for existing profiles (even if the user has never changed it), // but make new profiles default to DEFAULT. bool old_profile_version = !prefs->FindPreference( prefs::kProfileCreatedByVersion)->IsDefaultValue() && Version(prefs->GetString(prefs::kProfileCreatedByVersion)).IsOlderThan( "21.0.1180.0"); if (old_profile_version && TypeIsDefault(prefs)) prefs->SetInteger(prefs::kRestoreOnStartup, kPrefValueLast); #endif } // static bool SessionStartupPref::TypeIsManaged(PrefService* prefs) { DCHECK(prefs); const PrefService::Preference* pref_restore = prefs->FindPreference(prefs::kRestoreOnStartup); DCHECK(pref_restore); return pref_restore->IsManaged(); } // static bool SessionStartupPref::URLsAreManaged(PrefService* prefs) { DCHECK(prefs); const PrefService::Preference* pref_urls = prefs->FindPreference(prefs::kURLsToRestoreOnStartup); DCHECK(pref_urls); return pref_urls->IsManaged(); } // static bool SessionStartupPref::TypeIsDefault(PrefService* prefs) { DCHECK(prefs); const PrefService::Preference* pref_restore = prefs->FindPreference(prefs::kRestoreOnStartup); DCHECK(pref_restore); return pref_restore->IsDefaultValue(); } // static SessionStartupPref::Type SessionStartupPref::PrefValueToType(int pref_value) { switch (pref_value) { case kPrefValueLast: return SessionStartupPref::LAST; case kPrefValueURLs: return SessionStartupPref::URLS; case kPrefValueHomePage: return SessionStartupPref::HOMEPAGE; default: return SessionStartupPref::DEFAULT; } } SessionStartupPref::SessionStartupPref(Type type) : type(type) {} SessionStartupPref::~SessionStartupPref() {}
// 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 "chrome/browser/prefs/session_startup_pref.h" #include <string> #include "base/metrics/histogram.h" #include "base/prefs/pref_service.h" #include "base/prefs/scoped_user_pref_update.h" #include "base/time/time.h" #include "base/values.h" #include "base/version.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/net/url_fixer_upper.h" #include "chrome/common/pref_names.h" #include "components/user_prefs/pref_registry_syncable.h" #if defined(OS_MACOSX) #include "chrome/browser/ui/cocoa/window_restore_utils.h" #endif namespace { enum StartupURLsMigrationMetrics { STARTUP_URLS_MIGRATION_METRICS_PERFORMED, STARTUP_URLS_MIGRATION_METRICS_NOT_PRESENT, STARTUP_URLS_MIGRATION_METRICS_RESET, STARTUP_URLS_MIGRATION_METRICS_MAX, }; // Converts a SessionStartupPref::Type to an integer written to prefs. int TypeToPrefValue(SessionStartupPref::Type type) { switch (type) { case SessionStartupPref::LAST: return SessionStartupPref::kPrefValueLast; case SessionStartupPref::URLS: return SessionStartupPref::kPrefValueURLs; default: return SessionStartupPref::kPrefValueNewTab; } } void SetNewURLList(PrefService* prefs) { if (prefs->IsUserModifiablePreference(prefs::kURLsToRestoreOnStartup)) { base::ListValue new_url_pref_list; base::StringValue* home_page = new base::StringValue(prefs->GetString(prefs::kHomePage)); new_url_pref_list.Append(home_page); prefs->Set(prefs::kURLsToRestoreOnStartup, new_url_pref_list); } } void URLListToPref(const base::ListValue* url_list, SessionStartupPref* pref) { pref->urls.clear(); for (size_t i = 0; i < url_list->GetSize(); ++i) { std::string url_text; if (url_list->GetString(i, &url_text)) { GURL fixed_url = URLFixerUpper::FixupURL(url_text, std::string()); pref->urls.push_back(fixed_url); } } } } // namespace // static void SessionStartupPref::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterIntegerPref( prefs::kRestoreOnStartup, TypeToPrefValue(GetDefaultStartupType()), user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); registry->RegisterListPref(prefs::kURLsToRestoreOnStartup, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); registry->RegisterListPref(prefs::kURLsToRestoreOnStartupOld, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterBooleanPref( prefs::kRestoreOnStartupMigrated, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterInt64Pref( prefs::kRestoreStartupURLsMigrationTime, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); } // static SessionStartupPref::Type SessionStartupPref::GetDefaultStartupType() { #if defined(OS_CHROMEOS) return SessionStartupPref::LAST; #else return SessionStartupPref::DEFAULT; #endif } // static void SessionStartupPref::SetStartupPref( Profile* profile, const SessionStartupPref& pref) { DCHECK(profile); SetStartupPref(profile->GetPrefs(), pref); } // static void SessionStartupPref::SetStartupPref(PrefService* prefs, const SessionStartupPref& pref) { DCHECK(prefs); if (!SessionStartupPref::TypeIsManaged(prefs)) prefs->SetInteger(prefs::kRestoreOnStartup, TypeToPrefValue(pref.type)); if (!SessionStartupPref::URLsAreManaged(prefs)) { // Always save the URLs, that way the UI can remain consistent even if the // user changes the startup type pref. // Ownership of the ListValue retains with the pref service. ListPrefUpdate update(prefs, prefs::kURLsToRestoreOnStartup); ListValue* url_pref_list = update.Get(); DCHECK(url_pref_list); url_pref_list->Clear(); for (size_t i = 0; i < pref.urls.size(); ++i) { url_pref_list->Set(static_cast<int>(i), new StringValue(pref.urls[i].spec())); } } } // static SessionStartupPref SessionStartupPref::GetStartupPref(Profile* profile) { DCHECK(profile); return GetStartupPref(profile->GetPrefs()); } // static SessionStartupPref SessionStartupPref::GetStartupPref(PrefService* prefs) { DCHECK(prefs); MigrateIfNecessary(prefs); MigrateMacDefaultPrefIfNecessary(prefs); SessionStartupPref pref( PrefValueToType(prefs->GetInteger(prefs::kRestoreOnStartup))); // Always load the urls, even if the pref type isn't URLS. This way the // preferences panels can show the user their last choice. const ListValue* url_list = prefs->GetList(prefs::kURLsToRestoreOnStartup); URLListToPref(url_list, &pref); return pref; } // static void SessionStartupPref::MigrateIfNecessary(PrefService* prefs) { DCHECK(prefs); // Check if we need to migrate the old version of the startup URLs preference // to the new name, and also send metrics about the migration. StartupURLsMigrationMetrics metrics_result = STARTUP_URLS_MIGRATION_METRICS_MAX; const base::ListValue* old_startup_urls = prefs->GetList(prefs::kURLsToRestoreOnStartupOld); if (!prefs->GetUserPrefValue(prefs::kRestoreStartupURLsMigrationTime)) { // Record the absence of the migration timestamp, this will get overwritten // below if migration occurs now. metrics_result = STARTUP_URLS_MIGRATION_METRICS_NOT_PRESENT; // Seems like we never migrated, do it if necessary. if (!prefs->GetUserPrefValue(prefs::kURLsToRestoreOnStartup)) { if (old_startup_urls && !old_startup_urls->empty()) { prefs->Set(prefs::kURLsToRestoreOnStartup, *old_startup_urls); prefs->ClearPref(prefs::kURLsToRestoreOnStartupOld); } metrics_result = STARTUP_URLS_MIGRATION_METRICS_PERFORMED; } prefs->SetInt64(prefs::kRestoreStartupURLsMigrationTime, base::Time::Now().ToInternalValue()); } else if (old_startup_urls && !old_startup_urls->empty()) { // Migration needs to be reset. prefs->ClearPref(prefs::kURLsToRestoreOnStartupOld); base::Time last_migration_time = base::Time::FromInternalValue( prefs->GetInt64(prefs::kRestoreStartupURLsMigrationTime)); base::Time now = base::Time::Now(); prefs->SetInt64(prefs::kRestoreStartupURLsMigrationTime, now.ToInternalValue()); if (now < last_migration_time) last_migration_time = now; UMA_HISTOGRAM_CUSTOM_TIMES("Settings.StartupURLsResetTime", now - last_migration_time, base::TimeDelta::FromDays(0), base::TimeDelta::FromDays(7), 50); metrics_result = STARTUP_URLS_MIGRATION_METRICS_RESET; } // Record a metric migration event if something interesting happened. if (metrics_result != STARTUP_URLS_MIGRATION_METRICS_MAX) { UMA_HISTOGRAM_ENUMERATION( "Settings.StartupURLsMigration", metrics_result, STARTUP_URLS_MIGRATION_METRICS_MAX); } if (!prefs->GetBoolean(prefs::kRestoreOnStartupMigrated)) { // Read existing values. const base::Value* homepage_is_new_tab_page_value = prefs->GetUserPrefValue(prefs::kHomePageIsNewTabPage); bool homepage_is_new_tab_page = true; if (homepage_is_new_tab_page_value) { if (!homepage_is_new_tab_page_value->GetAsBoolean( &homepage_is_new_tab_page)) NOTREACHED(); } const base::Value* restore_on_startup_value = prefs->GetUserPrefValue(prefs::kRestoreOnStartup); int restore_on_startup = -1; if (restore_on_startup_value) { if (!restore_on_startup_value->GetAsInteger(&restore_on_startup)) NOTREACHED(); } // If restore_on_startup has the deprecated value kPrefValueHomePage, // migrate it to open the homepage on startup. If 'homepage is NTP' is set, // that means just opening the NTP. If not, it means opening a one-item URL // list containing the homepage. if (restore_on_startup == kPrefValueHomePage) { if (homepage_is_new_tab_page) { prefs->SetInteger(prefs::kRestoreOnStartup, kPrefValueNewTab); } else { prefs->SetInteger(prefs::kRestoreOnStartup, kPrefValueURLs); SetNewURLList(prefs); } } else if (!restore_on_startup_value && !homepage_is_new_tab_page && GetDefaultStartupType() == DEFAULT) { // kRestoreOnStartup was never set by the user, but the homepage was set. // Migrate to the list of URLs. (If restore_on_startup was never set, // and homepage_is_new_tab_page is true, no action is needed. The new // default value is "open the new tab page" which is what we want.) prefs->SetInteger(prefs::kRestoreOnStartup, kPrefValueURLs); SetNewURLList(prefs); } prefs->SetBoolean(prefs::kRestoreOnStartupMigrated, true); } } // static void SessionStartupPref::MigrateMacDefaultPrefIfNecessary(PrefService* prefs) { #if defined(OS_MACOSX) DCHECK(prefs); if (!restore_utils::IsWindowRestoreEnabled()) return; // The default startup pref used to be LAST, now it is DEFAULT. Don't change // the setting for existing profiles (even if the user has never changed it), // but make new profiles default to DEFAULT. bool old_profile_version = !prefs->FindPreference( prefs::kProfileCreatedByVersion)->IsDefaultValue() && Version(prefs->GetString(prefs::kProfileCreatedByVersion)).IsOlderThan( "21.0.1180.0"); if (old_profile_version && TypeIsDefault(prefs)) prefs->SetInteger(prefs::kRestoreOnStartup, kPrefValueLast); #endif } // static bool SessionStartupPref::TypeIsManaged(PrefService* prefs) { DCHECK(prefs); const PrefService::Preference* pref_restore = prefs->FindPreference(prefs::kRestoreOnStartup); DCHECK(pref_restore); return pref_restore->IsManaged(); } // static bool SessionStartupPref::URLsAreManaged(PrefService* prefs) { DCHECK(prefs); const PrefService::Preference* pref_urls = prefs->FindPreference(prefs::kURLsToRestoreOnStartup); DCHECK(pref_urls); return pref_urls->IsManaged(); } // static bool SessionStartupPref::TypeIsDefault(PrefService* prefs) { DCHECK(prefs); const PrefService::Preference* pref_restore = prefs->FindPreference(prefs::kRestoreOnStartup); DCHECK(pref_restore); return pref_restore->IsDefaultValue(); } // static SessionStartupPref::Type SessionStartupPref::PrefValueToType(int pref_value) { switch (pref_value) { case kPrefValueLast: return SessionStartupPref::LAST; case kPrefValueURLs: return SessionStartupPref::URLS; case kPrefValueHomePage: return SessionStartupPref::HOMEPAGE; default: return SessionStartupPref::DEFAULT; } } SessionStartupPref::SessionStartupPref(Type type) : type(type) {} SessionStartupPref::~SessionStartupPref() {}
Use correct UMA histogram macro for Settings.StartupURLsResetTime.
Use correct UMA histogram macro for Settings.StartupURLsResetTime. BUG=299290 TEST=NONE Review URL: https://codereview.chromium.org/41733003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@232196 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,jaruba/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,jaruba/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,littlstar/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,littlstar/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,littlstar/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,ltilve/chromium,ltilve/chromium,M4sse/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,patrickm/chromium.src,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,bright-sparks/chromium-spacewalk,anirudhSK/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,littlstar/chromium.src,markYoungH/chromium.src,Just-D/chromium-1,M4sse/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,markYoungH/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,dednal/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,dushu1203/chromium.src,M4sse/chromium.src,dednal/chromium.src,anirudhSK/chromium,dednal/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,littlstar/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,dednal/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,patrickm/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,anirudhSK/chromium,dednal/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk
f78f20b0864f635b3e45c6abc8ab86878ab85af6
chrome/browser/ui/extensions/shell_window.cc
chrome/browser/ui/extensions/shell_window.cc
// 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 "chrome/browser/ui/extensions/shell_window.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_process_manager.h" #include "chrome/browser/extensions/extension_tabs_module_constants.h" #include "chrome/browser/extensions/extension_window_controller.h" #include "chrome/browser/extensions/shell_window_registry.h" #include "chrome/browser/file_select_helper.h" #include "chrome/browser/intents/web_intents_util.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_id.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/intents/web_intent_picker_controller.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/view_type_utils.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_messages.h" #include "content/public/browser/invalidate_type.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_intents_dispatcher.h" #include "content/public/common/renderer_preferences.h" using content::SiteInstance; using content::WebContents; namespace { static const int kDefaultWidth = 512; static const int kDefaultHeight = 384; } // namespace namespace internal { class ShellWindowController : public ExtensionWindowController { public: ShellWindowController(ShellWindow* shell_window, Profile* profile); // Overriden from ExtensionWindowController virtual int GetWindowId() const OVERRIDE; virtual std::string GetWindowTypeText() const OVERRIDE; virtual base::DictionaryValue* CreateWindowValueWithTabs() const OVERRIDE; virtual bool CanClose(Reason* reason) const OVERRIDE; virtual void SetFullscreenMode(bool is_fullscreen, const GURL& extension_url) const OVERRIDE; virtual bool IsVisibleToExtension( const extensions::Extension* extension) const OVERRIDE; private: ShellWindow* shell_window_; DISALLOW_COPY_AND_ASSIGN(ShellWindowController); }; ShellWindowController::ShellWindowController( ShellWindow* shell_window, Profile* profile) : ExtensionWindowController(shell_window, profile), shell_window_(shell_window) { } int ShellWindowController::GetWindowId() const { return static_cast<int>(shell_window_->session_id().id()); } std::string ShellWindowController::GetWindowTypeText() const { return extension_tabs_module_constants::kWindowTypeValueShell; } base::DictionaryValue* ShellWindowController::CreateWindowValueWithTabs() const { return CreateWindowValue(); } bool ShellWindowController::CanClose(Reason* reason) const { return true; } void ShellWindowController::SetFullscreenMode(bool is_fullscreen, const GURL& extension_url) const { // TODO(mihaip): implement } bool ShellWindowController::IsVisibleToExtension( const extensions::Extension* extension) const { return shell_window_->extension() == extension; } } // namespace internal ShellWindow::CreateParams::CreateParams() : frame(ShellWindow::CreateParams::FRAME_CUSTOM), bounds(10, 10, kDefaultWidth, kDefaultHeight) { } ShellWindow* ShellWindow::Create(Profile* profile, const extensions::Extension* extension, const GURL& url, const ShellWindow::CreateParams params) { // This object will delete itself when the window is closed. return ShellWindow::CreateImpl(profile, extension, url, params); } ShellWindow::ShellWindow(Profile* profile, const extensions::Extension* extension, const GURL& url) : profile_(profile), extension_(extension), ALLOW_THIS_IN_INITIALIZER_LIST( extension_function_dispatcher_(profile, this)) { web_contents_ = WebContents::Create( profile, SiteInstance::CreateForURL(profile, url), MSG_ROUTING_NONE, NULL, NULL); contents_wrapper_.reset(new TabContentsWrapper(web_contents_)); content::WebContentsObserver::Observe(web_contents_); web_contents_->SetDelegate(this); chrome::SetViewType(web_contents_, chrome::VIEW_TYPE_APP_SHELL); web_contents_->GetMutableRendererPrefs()-> browser_handles_all_top_level_requests = true; web_contents_->GetRenderViewHost()->SyncRendererPrefs(); web_contents_->GetController().LoadURL( url, content::Referrer(), content::PAGE_TRANSITION_LINK, std::string()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, content::Source<Profile>(profile_)); // Close when the browser is exiting. // TODO(mihaip): we probably don't want this in the long run (when platform // apps are no longer tied to the browser process). registrar_.Add(this, content::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); // Prevent the browser process from shutting down while this window is open. browser::StartKeepAlive(); // Make this window available to the extension API. extension_window_controller_.reset( new internal::ShellWindowController(this, profile_)); ShellWindowRegistry::Get(profile_)->AddShellWindow(this); } ShellWindow::~ShellWindow() { // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the // last window open. registrar_.RemoveAll(); ShellWindowRegistry::Get(profile_)->RemoveShellWindow(this); // Remove shutdown prevention. browser::EndKeepAlive(); } string16 ShellWindow::GetTitle() const { // WebContents::GetTitle() will return the page's URL if there's no <title> // specified. However, we'd prefer to show the name of the extension in that // case, so we directly inspect the NavigationEntry's title. if (web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) return UTF8ToUTF16(extension()->name()); return web_contents()->GetTitle(); } bool ShellWindow::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ShellWindow, message) IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void ShellWindow::CloseContents(WebContents* contents) { Close(); } bool ShellWindow::ShouldSuppressDialogs() { return true; } void ShellWindow::WebIntentDispatch( content::WebContents* web_contents, content::WebIntentsDispatcher* intents_dispatcher) { if (!web_intents::IsWebIntentsEnabledForProfile(profile_)) return; contents_wrapper_->web_intent_picker_controller()->SetIntentsDispatcher( intents_dispatcher); contents_wrapper_->web_intent_picker_controller()->ShowDialog( intents_dispatcher->GetIntent().action, intents_dispatcher->GetIntent().type); } void ShellWindow::RunFileChooser(WebContents* tab, const content::FileChooserParams& params) { FileSelectHelper::RunFileChooser(tab, params); } bool ShellWindow::IsPopupOrPanel(const WebContents* source) const { DCHECK(source == web_contents_); return true; } void ShellWindow::MoveContents(WebContents* source, const gfx::Rect& pos) { DCHECK(source == web_contents_); extension_window_controller_->window()->SetBounds(pos); } void ShellWindow::NavigationStateChanged( const content::WebContents* source, unsigned changed_flags) { DCHECK(source == web_contents_); if (changed_flags & content::INVALIDATE_TYPE_TITLE) UpdateWindowTitle(); } void ShellWindow::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSION_UNLOADED: { const extensions::Extension* unloaded_extension = content::Details<extensions::UnloadedExtensionInfo>( details)->extension; if (extension_ == unloaded_extension) Close(); break; } case content::NOTIFICATION_APP_TERMINATING: Close(); break; default: NOTREACHED() << "Received unexpected notification"; } } ExtensionWindowController* ShellWindow::GetExtensionWindowController() const { return extension_window_controller_.get(); } void ShellWindow::OnRequest(const ExtensionHostMsg_Request_Params& params) { extension_function_dispatcher_.Dispatch(params, web_contents_->GetRenderViewHost()); }
// 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 "chrome/browser/ui/extensions/shell_window.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_process_manager.h" #include "chrome/browser/extensions/extension_tabs_module_constants.h" #include "chrome/browser/extensions/extension_window_controller.h" #include "chrome/browser/extensions/shell_window_registry.h" #include "chrome/browser/file_select_helper.h" #include "chrome/browser/intents/web_intents_util.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_id.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/intents/web_intent_picker_controller.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/view_type_utils.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_messages.h" #include "content/public/browser/invalidate_type.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_intents_dispatcher.h" #include "content/public/common/renderer_preferences.h" using content::SiteInstance; using content::WebContents; namespace { static const int kDefaultWidth = 512; static const int kDefaultHeight = 384; } // namespace namespace internal { class ShellWindowController : public ExtensionWindowController { public: ShellWindowController(ShellWindow* shell_window, Profile* profile); // Overriden from ExtensionWindowController virtual int GetWindowId() const OVERRIDE; virtual std::string GetWindowTypeText() const OVERRIDE; virtual base::DictionaryValue* CreateWindowValueWithTabs() const OVERRIDE; virtual bool CanClose(Reason* reason) const OVERRIDE; virtual void SetFullscreenMode(bool is_fullscreen, const GURL& extension_url) const OVERRIDE; virtual bool IsVisibleToExtension( const extensions::Extension* extension) const OVERRIDE; private: ShellWindow* shell_window_; DISALLOW_COPY_AND_ASSIGN(ShellWindowController); }; ShellWindowController::ShellWindowController( ShellWindow* shell_window, Profile* profile) : ExtensionWindowController(shell_window, profile), shell_window_(shell_window) { } int ShellWindowController::GetWindowId() const { return static_cast<int>(shell_window_->session_id().id()); } std::string ShellWindowController::GetWindowTypeText() const { return extension_tabs_module_constants::kWindowTypeValueShell; } base::DictionaryValue* ShellWindowController::CreateWindowValueWithTabs() const { return CreateWindowValue(); } bool ShellWindowController::CanClose(Reason* reason) const { return true; } void ShellWindowController::SetFullscreenMode(bool is_fullscreen, const GURL& extension_url) const { // TODO(mihaip): implement } bool ShellWindowController::IsVisibleToExtension( const extensions::Extension* extension) const { return shell_window_->extension() == extension; } } // namespace internal ShellWindow::CreateParams::CreateParams() : frame(ShellWindow::CreateParams::FRAME_CHROME), bounds(10, 10, kDefaultWidth, kDefaultHeight) { } ShellWindow* ShellWindow::Create(Profile* profile, const extensions::Extension* extension, const GURL& url, const ShellWindow::CreateParams params) { // This object will delete itself when the window is closed. return ShellWindow::CreateImpl(profile, extension, url, params); } ShellWindow::ShellWindow(Profile* profile, const extensions::Extension* extension, const GURL& url) : profile_(profile), extension_(extension), ALLOW_THIS_IN_INITIALIZER_LIST( extension_function_dispatcher_(profile, this)) { web_contents_ = WebContents::Create( profile, SiteInstance::CreateForURL(profile, url), MSG_ROUTING_NONE, NULL, NULL); contents_wrapper_.reset(new TabContentsWrapper(web_contents_)); content::WebContentsObserver::Observe(web_contents_); web_contents_->SetDelegate(this); chrome::SetViewType(web_contents_, chrome::VIEW_TYPE_APP_SHELL); web_contents_->GetMutableRendererPrefs()-> browser_handles_all_top_level_requests = true; web_contents_->GetRenderViewHost()->SyncRendererPrefs(); web_contents_->GetController().LoadURL( url, content::Referrer(), content::PAGE_TRANSITION_LINK, std::string()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, content::Source<Profile>(profile_)); // Close when the browser is exiting. // TODO(mihaip): we probably don't want this in the long run (when platform // apps are no longer tied to the browser process). registrar_.Add(this, content::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); // Prevent the browser process from shutting down while this window is open. browser::StartKeepAlive(); // Make this window available to the extension API. extension_window_controller_.reset( new internal::ShellWindowController(this, profile_)); ShellWindowRegistry::Get(profile_)->AddShellWindow(this); } ShellWindow::~ShellWindow() { // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the // last window open. registrar_.RemoveAll(); ShellWindowRegistry::Get(profile_)->RemoveShellWindow(this); // Remove shutdown prevention. browser::EndKeepAlive(); } string16 ShellWindow::GetTitle() const { // WebContents::GetTitle() will return the page's URL if there's no <title> // specified. However, we'd prefer to show the name of the extension in that // case, so we directly inspect the NavigationEntry's title. if (web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) return UTF8ToUTF16(extension()->name()); return web_contents()->GetTitle(); } bool ShellWindow::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ShellWindow, message) IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void ShellWindow::CloseContents(WebContents* contents) { Close(); } bool ShellWindow::ShouldSuppressDialogs() { return true; } void ShellWindow::WebIntentDispatch( content::WebContents* web_contents, content::WebIntentsDispatcher* intents_dispatcher) { if (!web_intents::IsWebIntentsEnabledForProfile(profile_)) return; contents_wrapper_->web_intent_picker_controller()->SetIntentsDispatcher( intents_dispatcher); contents_wrapper_->web_intent_picker_controller()->ShowDialog( intents_dispatcher->GetIntent().action, intents_dispatcher->GetIntent().type); } void ShellWindow::RunFileChooser(WebContents* tab, const content::FileChooserParams& params) { FileSelectHelper::RunFileChooser(tab, params); } bool ShellWindow::IsPopupOrPanel(const WebContents* source) const { DCHECK(source == web_contents_); return true; } void ShellWindow::MoveContents(WebContents* source, const gfx::Rect& pos) { DCHECK(source == web_contents_); extension_window_controller_->window()->SetBounds(pos); } void ShellWindow::NavigationStateChanged( const content::WebContents* source, unsigned changed_flags) { DCHECK(source == web_contents_); if (changed_flags & content::INVALIDATE_TYPE_TITLE) UpdateWindowTitle(); } void ShellWindow::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSION_UNLOADED: { const extensions::Extension* unloaded_extension = content::Details<extensions::UnloadedExtensionInfo>( details)->extension; if (extension_ == unloaded_extension) Close(); break; } case content::NOTIFICATION_APP_TERMINATING: Close(); break; default: NOTREACHED() << "Received unexpected notification"; } } ExtensionWindowController* ShellWindow::GetExtensionWindowController() const { return extension_window_controller_.get(); } void ShellWindow::OnRequest(const ExtensionHostMsg_Request_Params& params) { extension_function_dispatcher_.Dispatch(params, web_contents_->GetRenderViewHost()); }
Make the default window frame be 'chrome', like app_window.idl says it is
Make the default window frame be 'chrome', like app_window.idl says it is [email protected] Review URL: https://chromiumcodereview.appspot.com/10546017 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@140681 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,Jonekee/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,bright-sparks/chromium-spacewalk,anirudhSK/chromium,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,jaruba/chromium.src,ltilve/chromium,hujiajie/pa-chromium,dednal/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,timopulkkinen/BubbleFish,dushu1203/chromium.src,littlstar/chromium.src,mogoweb/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,keishi/chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,hujiajie/pa-chromium,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,keishi/chromium,nacl-webkit/chrome_deps,Chilledheart/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,dednal/chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,keishi/chromium,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,hujiajie/pa-chromium,M4sse/chromium.src,ltilve/chromium,nacl-webkit/chrome_deps,hujiajie/pa-chromium,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,patrickm/chromium.src,ltilve/chromium,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,M4sse/chromium.src,littlstar/chromium.src,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,keishi/chromium,zcbenz/cefode-chromium,dushu1203/chromium.src,anirudhSK/chromium,jaruba/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,jaruba/chromium.src,dednal/chromium.src,keishi/chromium,hgl888/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,M4sse/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,jaruba/chromium.src,keishi/chromium,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,patrickm/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,ChromiumWebApps/chromium,anirudhSK/chromium,dushu1203/chromium.src,Chilledheart/chromium,dednal/chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,anirudhSK/chromium,M4sse/chromium.src,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,ltilve/chromium,keishi/chromium,keishi/chromium,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,keishi/chromium,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,keishi/chromium,dushu1203/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,patrickm/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,keishi/chromium,hujiajie/pa-chromium,axinging/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,littlstar/chromium.src,zcbenz/cefode-chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,zcbenz/cefode-chromium,ChromiumWebApps/chromium,Chilledheart/chromium,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk
301dd005fb3211cd337a443a7bb792771ef016f4
modules/pacing/packet_router.cc
modules/pacing/packet_router.cc
/* * Copyright (c) 2015 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/modules/pacing/packet_router.h" #include "webrtc/base/atomicops.h" #include "webrtc/base/checks.h" #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp.h" #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h" namespace webrtc { namespace { void AddModule(RtpRtcp* rtp_module, std::list<RtpRtcp*>* rtp_modules) { RTC_DCHECK(std::find(rtp_modules->begin(), rtp_modules->end(), rtp_module) == rtp_modules->end()); rtp_modules->push_back(rtp_module); } void RemoveModule(RtpRtcp* rtp_module, std::list<RtpRtcp*>* rtp_modules) { RTC_DCHECK(std::find(rtp_modules->begin(), rtp_modules->end(), rtp_module) != rtp_modules->end()); rtp_modules->remove(rtp_module); } bool SendFeedback(rtcp::TransportFeedback* packet, std::list<RtpRtcp*>* rtp_modules) { for (auto* rtp_module : *rtp_modules) { packet->WithPacketSenderSsrc(rtp_module->SSRC()); if (rtp_module->SendFeedbackPacket(*packet)) return true; } return false; } } // namespace PacketRouter::PacketRouter() : transport_seq_(0) { pacer_thread_checker_.DetachFromThread(); } PacketRouter::~PacketRouter() { RTC_DCHECK(send_rtp_modules_.empty()); RTC_DCHECK(recv_rtp_modules_.empty()); } void PacketRouter::AddRtpModule(RtpRtcp* rtp_module, bool sender) { rtc::CritScope cs(&modules_crit_); if (sender) { AddModule(rtp_module, &send_rtp_modules_); } else { AddModule(rtp_module, &recv_rtp_modules_); } } void PacketRouter::RemoveRtpModule(RtpRtcp* rtp_module, bool sender) { rtc::CritScope cs(&modules_crit_); if (sender) { RemoveModule(rtp_module, &send_rtp_modules_); } else { RemoveModule(rtp_module, &recv_rtp_modules_); } } bool PacketRouter::TimeToSendPacket(uint32_t ssrc, uint16_t sequence_number, int64_t capture_timestamp, bool retransmission) { RTC_DCHECK(pacer_thread_checker_.CalledOnValidThread()); rtc::CritScope cs(&modules_crit_); for (auto* rtp_module : send_rtp_modules_) { if (rtp_module->SendingMedia() && ssrc == rtp_module->SSRC()) { return rtp_module->TimeToSendPacket(ssrc, sequence_number, capture_timestamp, retransmission); } } return true; } size_t PacketRouter::TimeToSendPadding(size_t bytes_to_send) { RTC_DCHECK(pacer_thread_checker_.CalledOnValidThread()); size_t total_bytes_sent = 0; rtc::CritScope cs(&modules_crit_); for (RtpRtcp* module : send_rtp_modules_) { if (module->SendingMedia()) { size_t bytes_sent = module->TimeToSendPadding(bytes_to_send - total_bytes_sent); total_bytes_sent += bytes_sent; if (total_bytes_sent >= bytes_to_send) break; } } return total_bytes_sent; } void PacketRouter::SetTransportWideSequenceNumber(uint16_t sequence_number) { rtc::AtomicOps::ReleaseStore(&transport_seq_, sequence_number); } uint16_t PacketRouter::AllocateSequenceNumber() { int prev_seq = rtc::AtomicOps::AcquireLoad(&transport_seq_); int desired_prev_seq; int new_seq; do { desired_prev_seq = prev_seq; new_seq = (desired_prev_seq + 1) & 0xFFFF; // Note: CompareAndSwap returns the actual value of transport_seq at the // time the CAS operation was executed. Thus, if prev_seq is returned, the // operation was successful - otherwise we need to retry. Saving the // return value saves us a load on retry. prev_seq = rtc::AtomicOps::CompareAndSwap(&transport_seq_, desired_prev_seq, new_seq); } while (prev_seq != desired_prev_seq); return new_seq; } bool PacketRouter::SendFeedback(rtcp::TransportFeedback* packet) { RTC_DCHECK(pacer_thread_checker_.CalledOnValidThread()); rtc::CritScope cs(&modules_crit_); if (::webrtc::SendFeedback(packet, &recv_rtp_modules_)) return true; if (::webrtc::SendFeedback(packet, &send_rtp_modules_)) return true; return false; } } // namespace webrtc
/* * Copyright (c) 2015 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/modules/pacing/packet_router.h" #include "webrtc/base/atomicops.h" #include "webrtc/base/checks.h" #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp.h" #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h" namespace webrtc { namespace { void AddModule(RtpRtcp* rtp_module, std::list<RtpRtcp*>* rtp_modules) { RTC_DCHECK(std::find(rtp_modules->begin(), rtp_modules->end(), rtp_module) == rtp_modules->end()); rtp_modules->push_back(rtp_module); } void RemoveModule(RtpRtcp* rtp_module, std::list<RtpRtcp*>* rtp_modules) { RTC_DCHECK(std::find(rtp_modules->begin(), rtp_modules->end(), rtp_module) != rtp_modules->end()); rtp_modules->remove(rtp_module); } bool SendFeedback(rtcp::TransportFeedback* packet, std::list<RtpRtcp*>* rtp_modules) { for (auto* rtp_module : *rtp_modules) { packet->WithPacketSenderSsrc(rtp_module->SSRC()); if (rtp_module->SendFeedbackPacket(*packet)) return true; } return false; } } // namespace PacketRouter::PacketRouter() : transport_seq_(0) { pacer_thread_checker_.DetachFromThread(); } PacketRouter::~PacketRouter() { RTC_DCHECK(send_rtp_modules_.empty()); RTC_DCHECK(recv_rtp_modules_.empty()); } void PacketRouter::AddRtpModule(RtpRtcp* rtp_module, bool sender) { rtc::CritScope cs(&modules_crit_); if (sender) { AddModule(rtp_module, &send_rtp_modules_); } else { AddModule(rtp_module, &recv_rtp_modules_); } } void PacketRouter::RemoveRtpModule(RtpRtcp* rtp_module, bool sender) { rtc::CritScope cs(&modules_crit_); if (sender) { RemoveModule(rtp_module, &send_rtp_modules_); } else { RemoveModule(rtp_module, &recv_rtp_modules_); } } bool PacketRouter::TimeToSendPacket(uint32_t ssrc, uint16_t sequence_number, int64_t capture_timestamp, bool retransmission) { RTC_DCHECK(pacer_thread_checker_.CalledOnValidThread()); rtc::CritScope cs(&modules_crit_); for (auto* rtp_module : send_rtp_modules_) { if (rtp_module->SendingMedia() && ssrc == rtp_module->SSRC()) { return rtp_module->TimeToSendPacket(ssrc, sequence_number, capture_timestamp, retransmission); } } return true; } size_t PacketRouter::TimeToSendPadding(size_t bytes_to_send) { RTC_DCHECK(pacer_thread_checker_.CalledOnValidThread()); size_t total_bytes_sent = 0; rtc::CritScope cs(&modules_crit_); for (RtpRtcp* module : send_rtp_modules_) { if (module->SendingMedia()) { size_t bytes_sent = module->TimeToSendPadding(bytes_to_send - total_bytes_sent); total_bytes_sent += bytes_sent; if (total_bytes_sent >= bytes_to_send) break; } } return total_bytes_sent; } void PacketRouter::SetTransportWideSequenceNumber(uint16_t sequence_number) { rtc::AtomicOps::ReleaseStore(&transport_seq_, sequence_number); } uint16_t PacketRouter::AllocateSequenceNumber() { int prev_seq = rtc::AtomicOps::AcquireLoad(&transport_seq_); int desired_prev_seq; int new_seq; do { desired_prev_seq = prev_seq; new_seq = (desired_prev_seq + 1) & 0xFFFF; // Note: CompareAndSwap returns the actual value of transport_seq at the // time the CAS operation was executed. Thus, if prev_seq is returned, the // operation was successful - otherwise we need to retry. Saving the // return value saves us a load on retry. prev_seq = rtc::AtomicOps::CompareAndSwap(&transport_seq_, desired_prev_seq, new_seq); } while (prev_seq != desired_prev_seq); return new_seq; } bool PacketRouter::SendFeedback(rtcp::TransportFeedback* packet) { rtc::CritScope cs(&modules_crit_); if (::webrtc::SendFeedback(packet, &recv_rtp_modules_)) return true; if (::webrtc::SendFeedback(packet, &send_rtp_modules_)) return true; return false; } } // namespace webrtc
Remove thread check from PacketRouter::SendFeedback.
Remove thread check from PacketRouter::SendFeedback. [email protected] Review URL: https://codereview.webrtc.org/1732923004 . Cr-Original-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#11759} Cr-Mirrored-From: https://chromium.googlesource.com/external/webrtc Cr-Mirrored-Commit: bf66ae6d80c5639234a08edbbdd99ec33f694023
C++
bsd-3-clause
jchavanton/webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,jchavanton/webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,jchavanton/webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,jchavanton/webrtc
b6fe6c650280aaa31149ba116c188c16c88d3eeb
mainwindow.cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "model.h" #include "model_io.h" #include "figurepainter.h" #include "build_info.h" #include <fstream> #include <QFileDialog> #include <QInputDialog> #include <QMessageBox> #include <QShortcut> #include <QScreen> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), modelWidget(nullptr), redoExtraShortcut(QKeySequence("Ctrl+Shift+Z"), this), zoomInExtraShortcut(QKeySequence("Ctrl+="), this) { ui->setupUi(this); connect(&redoExtraShortcut , &QShortcut::activated, ui->actionRedo , &QAction::trigger); connect(&zoomInExtraShortcut, &QShortcut::activated, ui->actionZoomIn, &QAction::trigger); setModelWidget(new Ui::ModelWidget()); setWindowIcon(QIcon(":/icon.ico")); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionNew_triggered() { setModelWidget(new Ui::ModelWidget()); currentFileName = QString(); } void MainWindow::setModelWidget(Ui::ModelWidget *newWidget) { if (this->modelWidget) { ui->wrapperFrame->layout()->removeWidget(this->modelWidget); delete this->modelWidget; } this->modelWidget = newWidget; ui->wrapperFrame->layout()->addWidget(this->modelWidget); ui->actionSaveAs->setEnabled(true); ui->actionUndo->setEnabled(modelWidget->canUndo()); connect(modelWidget, &Ui::ModelWidget::canUndoChanged, [this]() { ui->actionUndo->setEnabled(modelWidget->canUndo()); }); ui->actionRedo->setEnabled(modelWidget->canRedo()); connect(modelWidget, &Ui::ModelWidget::canRedoChanged, [this]() { ui->actionRedo->setEnabled(modelWidget->canRedo()); }); connect(modelWidget, &Ui::ModelWidget::scaleFactorChanged, [this]() { ui->actionZoomOut->setEnabled(modelWidget->scaleFactor() > SCALE_FACTOR_STEP + 1e-8); }); modelWidget->setGridStep(ui->actionShowGrid->isChecked() ? defaultGridStep : 0); QScreen *screen = QApplication::screens().at(0); modelWidget->setScaleFactor(screen->logicalDotsPerInch() / 96.0); } void MainWindow::on_actionOpen_triggered() { QString filename = QFileDialog::getOpenFileName( this, "Select file with a model", QDir::currentPath(), "Models (*.model)" ); if (filename == "") { return; } std::unique_ptr<Ui::ModelWidget> modelWidget(new Ui::ModelWidget()); std::ifstream file(filename.toStdString()); try { Model model; file >> model; modelWidget->setModel(std::move(model)); } catch (model_format_error &e) { QMessageBox::critical(this, "Error while opening model", e.what()); return; } setModelWidget(modelWidget.release()); currentFileName = filename; } void MainWindow::on_actionSave_triggered() { if (currentFileName == QString()) { ui->actionSaveAs->trigger(); return; } Model &model = this->modelWidget->getModel(); std::ofstream file(currentFileName.toStdString()); file << model; } QString forceFileExtension(QString filename, QString selectedFilter) { QString extension = selectedFilter.mid(selectedFilter.indexOf("(*.") + 3); extension.chop(1); // chop trailing ) extension = ("." + extension).toLower(); if (!filename.endsWith(extension)) { filename += extension; } return filename; } void MainWindow::on_actionSaveAs_triggered() { QString selectedFilter; QString filename = QFileDialog::getSaveFileName( this, "Select file to save in", QDir::currentPath(), "Models (*.model);;SVG (*.svg);;PNG (*.png)", &selectedFilter ); if (filename == "") { return; } filename = forceFileExtension(filename, selectedFilter); Model &model = this->modelWidget->getModel(); std::ofstream file(filename.toStdString()); if (filename.toLower().endsWith(".svg")) { exportModelToSvg(model, file); } else if (filename.toLower().endsWith(".png")) { file.close(); exportModelToImageFile(model, filename); } else { file << model; currentFileName = filename; } } void MainWindow::on_actionUndo_triggered() { // Extra check is added for symmetry with actionRedo if (!modelWidget->canUndo()) { return; } modelWidget->undo(); } void MainWindow::on_actionRedo_triggered() { // Extra check is added because there is extra shortcut if (!modelWidget->canRedo()) { return; } modelWidget->redo(); } void MainWindow::on_actionShowGrid_triggered() { if (ui->actionShowGrid->isChecked()) { defaultGridStep = QInputDialog::getInt(this, "Grid step", "Specify grid step in pixels", defaultGridStep, 1, int(1e9)); } modelWidget->setGridStep(ui->actionShowGrid->isChecked() ? defaultGridStep : 0); } void MainWindow::on_actionZoomIn_triggered() { modelWidget->setScaleFactor(modelWidget->scaleFactor() + SCALE_FACTOR_STEP); } void MainWindow::on_actionZoomOut_triggered() { modelWidget->setScaleFactor(modelWidget->scaleFactor() - SCALE_FACTOR_STEP); } void MainWindow::on_actionExit_triggered() { QApplication::exit(); } void MainWindow::on_actionAbout_triggered() { QMessageBox::about(this, "About Manugram", QString() + "Git commit hash: " + GIT_LAST_SHA1 + "\n" + "Git commit date: " + GIT_LAST_TIME ); }
#include "mainwindow.h" #include "ui_mainwindow.h" #include "model.h" #include "model_io.h" #include "figurepainter.h" #include "build_info.h" #include <fstream> #include <QFileDialog> #include <QInputDialog> #include <QMessageBox> #include <QShortcut> #include <QScreen> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), modelWidget(nullptr), redoExtraShortcut(QKeySequence("Ctrl+Shift+Z"), this), zoomInExtraShortcut(QKeySequence("Ctrl+="), this) { ui->setupUi(this); connect(&redoExtraShortcut , &QShortcut::activated, ui->actionRedo , &QAction::trigger); connect(&zoomInExtraShortcut, &QShortcut::activated, ui->actionZoomIn, &QAction::trigger); setModelWidget(new Ui::ModelWidget()); setWindowIcon(QIcon(":/icon.ico")); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionNew_triggered() { setModelWidget(new Ui::ModelWidget()); currentFileName = QString(); } void MainWindow::setModelWidget(Ui::ModelWidget *newWidget) { if (this->modelWidget) { ui->wrapperFrame->layout()->removeWidget(this->modelWidget); delete this->modelWidget; } this->modelWidget = newWidget; ui->wrapperFrame->layout()->addWidget(this->modelWidget); ui->actionSaveAs->setEnabled(true); ui->actionUndo->setEnabled(modelWidget->canUndo()); connect(modelWidget, &Ui::ModelWidget::canUndoChanged, [this]() { ui->actionUndo->setEnabled(modelWidget->canUndo()); }); ui->actionRedo->setEnabled(modelWidget->canRedo()); connect(modelWidget, &Ui::ModelWidget::canRedoChanged, [this]() { ui->actionRedo->setEnabled(modelWidget->canRedo()); }); connect(modelWidget, &Ui::ModelWidget::scaleFactorChanged, [this]() { ui->actionZoomOut->setEnabled(modelWidget->scaleFactor() > SCALE_FACTOR_STEP + 1e-8); }); modelWidget->setGridStep(ui->actionShowGrid->isChecked() ? defaultGridStep : 0); QScreen *screen = QApplication::screens().at(0); modelWidget->setScaleFactor(screen->logicalDotsPerInch() / 96.0); } void MainWindow::on_actionOpen_triggered() { QString filename = QFileDialog::getOpenFileName( this, "Select file with a model", QDir::currentPath(), "Models (*.model)" ); if (filename == "") { return; } std::unique_ptr<Ui::ModelWidget> modelWidget(new Ui::ModelWidget()); std::ifstream file(filename.toStdString()); try { Model model; file >> model; modelWidget->setModel(std::move(model)); } catch (model_format_error &e) { QMessageBox::critical(this, "Error while opening model", e.what()); return; } setModelWidget(modelWidget.release()); currentFileName = filename; } void MainWindow::on_actionSave_triggered() { if (currentFileName == QString()) { ui->actionSaveAs->trigger(); return; } Model &model = this->modelWidget->getModel(); std::ofstream file(currentFileName.toStdString()); file << model; } QString forceFileExtension(QString filename, QString selectedFilter) { QString extension = selectedFilter.mid(selectedFilter.indexOf("(*.") + 3); extension.chop(1); // chop trailing ) extension = ("." + extension).toLower(); if (!filename.endsWith(extension)) { filename += extension; } return filename; } void MainWindow::on_actionSaveAs_triggered() { QString selectedFilter; QString filename = QFileDialog::getSaveFileName( this, "Select file to save in", QDir::currentPath(), "Models (*.model);;SVG (*.svg);;PNG (*.png)", &selectedFilter ); if (filename == "") { return; } filename = forceFileExtension(filename, selectedFilter); Model &model = this->modelWidget->getModel(); std::ofstream file(filename.toStdString()); if (filename.toLower().endsWith(".svg")) { exportModelToSvg(model, file); } else if (filename.toLower().endsWith(".png")) { file.close(); exportModelToImageFile(model, filename); } else { file << model; currentFileName = filename; } } void MainWindow::on_actionUndo_triggered() { // Extra check is added for symmetry with actionRedo if (!modelWidget->canUndo()) { return; } modelWidget->undo(); } void MainWindow::on_actionRedo_triggered() { // Extra check is added because there is extra shortcut if (!modelWidget->canRedo()) { return; } modelWidget->redo(); } void MainWindow::on_actionShowGrid_triggered() { if (ui->actionShowGrid->isChecked()) { defaultGridStep = QInputDialog::getInt(this, "Grid step", "Specify grid step in pixels", defaultGridStep, 1, int(1e9)); } modelWidget->setGridStep(ui->actionShowGrid->isChecked() ? defaultGridStep : 0); } void MainWindow::on_actionZoomIn_triggered() { modelWidget->setScaleFactor(modelWidget->scaleFactor() + SCALE_FACTOR_STEP); } void MainWindow::on_actionZoomOut_triggered() { modelWidget->setScaleFactor(modelWidget->scaleFactor() - SCALE_FACTOR_STEP); } void MainWindow::on_actionExit_triggered() { QApplication::exit(); } void MainWindow::on_actionAbout_triggered() { QMessageBox::about(this, "About Manugram", QString() + "Git commit hash: " + GIT_LAST_SHA1 + "\n" + "Git commit date: " + GIT_LAST_TIME + "\n" + "Build time: " + BUILD_TIME ); }
build time was added (#62)
mainwindow.about: build time was added (#62)
C++
mit
cscenter/manugram,cscenter/manugram,cscenter/manugram
cdb7753939f6c5193253b06f8267718854249044
mainwindow.cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowTitle("CRC Calculator ver " + QString::number(MAJOR_VERSION) + '.' + QString::number(MINOR_VERSION)); ui->CRC_Res_Bin_groupBox->setLayout(bit_set.layout()); Prepare_CRC_Param_comboBox(); CRC_Param_to_GUI(); //Signal/Slots for Wrap word checkBox QObject::connect(ui->Hex_tab_WrapWord_checkBox, SIGNAL(stateChanged(int)), this, SLOT(Hex_tab_WrapWord_checkBox_stateChanged(int)) ); QObject::connect(ui->Text_tab_WrapWord_checkBox, SIGNAL(stateChanged(int)), this, SLOT(Text_tab_WrapWord_checkBox_stateChanged(int)) ); QObject::connect(ui->CRC_Param_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selected_index_CRC_in_comboBox(int)) ); QObject::connect(&qucrc, SIGNAL(index_changed(uint32_t)), this, SLOT(set_index_CRC_in_comboBox(uint32_t)) ); } MainWindow::~MainWindow() { delete ui; } void MainWindow::Hex_tab_WrapWord_checkBox_stateChanged(int state) { if( state ) ui->Hex_tab_plainTextEdit->setLineWrapMode(QPlainTextEdit::WidgetWidth); else ui->Hex_tab_plainTextEdit->setLineWrapMode(QPlainTextEdit::NoWrap); } void MainWindow::Text_tab_WrapWord_checkBox_stateChanged(int state) { if( state ) ui->Text_tab_plainTextEdit->setLineWrapMode(QPlainTextEdit::WidgetWidth); else ui->Text_tab_plainTextEdit->setLineWrapMode(QPlainTextEdit::NoWrap); } void MainWindow::selected_index_CRC_in_comboBox(int new_index) { if( new_index == 0 ) return; // for Custom no action qucrc.set_index(new_index); CRC_Param_to_GUI(); } void MainWindow::set_index_CRC_in_comboBox(uint32_t new_index) { ui->CRC_Param_comboBox->setCurrentIndex(new_index); } void MainWindow::CRC_Param_to_GUI() { ui->CRC_Bits_spinBox->setValue(qucrc.get_bits()); ui->CRC_Poly_lineEdit->setText( QString::number(qucrc.get_poly(), 16) ); ui->CRC_Init_lineEdit->setText( QString::number(qucrc.get_init(), 16) ); ui->CRC_XorOut_lineEdit->setText( QString::number(qucrc.get_xor_out(), 16) ); ui->CRC_Check_lineEdit->setText( QString::number(qucrc.get_check(), 16) ); ui->CRC_RefIn_checkBox->setChecked(qucrc.get_ref_in()); ui->CRC_RefOut_checkBox->setChecked(qucrc.get_ref_out()); } void MainWindow::Prepare_CRC_Param_comboBox() { ui->CRC_Param_comboBox->clear(); for( size_t i = 0; i < QuCRC_t::CRC_List.size(); i++) { QString item; CRC_Param_Info crc_info = QuCRC_t::CRC_List[i]; item = crc_info.name; // item += " Bits: " + QString::number(crc_info.bits); // item += " Poly: 0x" + QString::number(crc_info.poly, 16); // item += " Init: 0x" + QString::number(crc_info.init, 16); // item += " RefIn: " + QString::number(crc_info.ref_in); // item += " RefOut: " + QString::number(crc_info.ref_out); // item += " XorOut: 0x" + QString::number(crc_info.xor_out, 16); ui->CRC_Param_comboBox->addItem(item); } ui->CRC_Param_comboBox->setCurrentIndex( qucrc.get_index() ); }
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowTitle("CRC Calculator ver " + QString::number(MAJOR_VERSION) + '.' + QString::number(MINOR_VERSION)); ui->CRC_Res_Bin_groupBox->setLayout(bit_set.layout()); Prepare_CRC_Param_comboBox(); CRC_Param_to_GUI(); //Signal/Slots for Wrap word checkBox QObject::connect(ui->Hex_tab_WrapWord_checkBox, SIGNAL(stateChanged(int)), this, SLOT(Hex_tab_WrapWord_checkBox_stateChanged(int)) ); QObject::connect(ui->Text_tab_WrapWord_checkBox, SIGNAL(stateChanged(int)), this, SLOT(Text_tab_WrapWord_checkBox_stateChanged(int)) ); QObject::connect(ui->CRC_Param_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selected_index_CRC_in_comboBox(int)) ); QObject::connect(&qucrc, SIGNAL(index_changed(uint32_t)), this, SLOT(set_index_CRC_in_comboBox(uint32_t)) ); } MainWindow::~MainWindow() { delete ui; } void MainWindow::Hex_tab_WrapWord_checkBox_stateChanged(int state) { if( state ) ui->Hex_tab_plainTextEdit->setLineWrapMode(QPlainTextEdit::WidgetWidth); else ui->Hex_tab_plainTextEdit->setLineWrapMode(QPlainTextEdit::NoWrap); } void MainWindow::Text_tab_WrapWord_checkBox_stateChanged(int state) { if( state ) ui->Text_tab_plainTextEdit->setLineWrapMode(QPlainTextEdit::WidgetWidth); else ui->Text_tab_plainTextEdit->setLineWrapMode(QPlainTextEdit::NoWrap); } void MainWindow::selected_index_CRC_in_comboBox(int new_index) { if( new_index == 0 ) return; // for Custom no action qucrc.set_index(new_index); CRC_Param_to_GUI(); } void MainWindow::set_index_CRC_in_comboBox(uint32_t new_index) { ui->CRC_Param_comboBox->setCurrentIndex(new_index); } void MainWindow::CRC_Param_to_GUI() { ui->CRC_Bits_spinBox->setValue(qucrc.get_bits()); ui->CRC_Poly_lineEdit->setText( "0x" + QString::number(qucrc.get_poly(), 16).toUpper() ); ui->CRC_Init_lineEdit->setText( "0x" + QString::number(qucrc.get_init(), 16).toUpper() ); ui->CRC_XorOut_lineEdit->setText("0x" + QString::number(qucrc.get_xor_out(), 16).toUpper() ); ui->CRC_Check_lineEdit->setText( "0x" + QString::number(qucrc.get_check(), 16).toUpper() ); ui->CRC_RefIn_checkBox->setChecked(qucrc.get_ref_in()); ui->CRC_RefOut_checkBox->setChecked(qucrc.get_ref_out()); } void MainWindow::Prepare_CRC_Param_comboBox() { ui->CRC_Param_comboBox->clear(); for( size_t i = 0; i < QuCRC_t::CRC_List.size(); i++) { QString item; CRC_Param_Info crc_info = QuCRC_t::CRC_List[i]; item = crc_info.name; // item += " Bits: " + QString::number(crc_info.bits); // item += " Poly: 0x" + QString::number(crc_info.poly, 16); // item += " Init: 0x" + QString::number(crc_info.init, 16); // item += " RefIn: " + QString::number(crc_info.ref_in); // item += " RefOut: " + QString::number(crc_info.ref_out); // item += " XorOut: 0x" + QString::number(crc_info.xor_out, 16); ui->CRC_Param_comboBox->addItem(item); } ui->CRC_Param_comboBox->setCurrentIndex( qucrc.get_index() ); }
Add 0x prefix + toUpper for Hex param
Add 0x prefix + toUpper for Hex param
C++
bsd-3-clause
KoynovStas/QCRC_Calc
413e93b03fca7447f003f37f00f0771dea515a45
mainwindow.cpp
mainwindow.cpp
#include <QtWidgets> #include "mainwindow.h" #include <fts_fuzzy_match.h> #include <glob.h> #include <string> #include <map> #include <database.h> Window::Window(QWidget *parent) : QMainWindow(parent) { // Initalise database db.setDatabaseName("recipes.db"); // Initialise widgets searchBox = new SearchBox(); searchBox->setPlaceholderText("Search for recipes"); recipeBox = new QComboBox(); QStringList recipeCategories; recipeCategories << "All Recipes" << "Beef" << "Chicken" << "Dessert" << "Lamb" << "Pork" << "Seafood" << "Turkey" << "Veggie"; recipeBox->addItems(recipeCategories); createRecipeList(); numResults = new QLabel(); // Set layout centralWidget = new QWidget(); QGridLayout *mainLayout = new QGridLayout(centralWidget); mainLayout->addWidget(searchBox, 0, 0, 1, 6); mainLayout->addWidget(numResults, 0, 6, 1, 1); mainLayout->addWidget(recipeBox, 0, 7, 1, 1); mainLayout->addWidget(recipeList, 1, 0, 1, 8); centralWidget->setLayout(mainLayout); centralWidget->show(); setCentralWidget(centralWidget); // Create menus optionsMenu = new QMenu("Options"); updateDb = new QAction("Update database", this); connect(updateDb, &QAction::triggered, this, &Window::updateDatabase); cleanDb = new QAction("Clean database", this); connect(cleanDb, &QAction::triggered, this, &Window::cleanDatabase); optionsMenu->addAction(updateDb); optionsMenu->addAction(cleanDb); menuBar()->addMenu(optionsMenu); // Set window paramters setWindowTitle(tr("Find Recipes")); setMinimumSize(600, 400); // Set signals connect(recipeList, &QListWidget::itemDoubleClicked, this, &Window::openFile); connect(searchBox, SIGNAL(inputText(QString)), this, SLOT(updateRecipesDiplay(QString))); connect(searchBox, SIGNAL(returnPressed()), recipeList, SLOT(setFocus())); connect(recipeBox, SIGNAL(currentTextChanged(QString)), searchBox, SLOT(recipeFiterChanged(QString))); // Populate list on start up updateRecipesDiplay(""); } // Get list of files according to glob patternn QStringList globVector(const std::string& pattern){ glob_t glob_result; glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result); QStringList files; for(unsigned int i=0; i<glob_result.gl_pathc; ++i){ files << QString(glob_result.gl_pathv[i]); } globfree(&glob_result); return files; } void SearchBox::recipeFiterChanged(QString newFilter){ // When the recipe filter changes, emit this signal to call updateRecipeDisplay emit inputText(text()); } void SearchBox::keyPressEvent(QKeyEvent *evt){ QLineEdit::keyPressEvent(evt); // When the search changes, emit this signal to call updateRecipeDisplay emit inputText(text()); } void Window::updateRecipesDiplay(QString searchText){ recipeList->clear(); QList<QListWidgetItem*> recipes = getRecipeList(searchText); for (int i=0; i<recipes.size(); ++i){ recipeList->addItem(recipes[i]); } if(searchText.isEmpty()){ recipeList->sortItems(); } QString text = QString("%1 recipes").arg(recipes.size()); if (recipes.size() == 1){ text = "1 recipe"; } numResults->setText(text); } QList<QListWidgetItem*> Window::getRecipeList(QString searchText){ QList<QListWidgetItem*> recipes; if (searchText.isEmpty()) { recipes = getAllRecipes(); }else{ recipes = getMatchingRecipes(searchText); } return recipes; } QList<QListWidgetItem*> Window::getAllRecipes(){ QList<QListWidgetItem*> recipes; // Open database and execute query db.open(); // Prepare query based on filter QSqlQuery query = QSqlQuery(); if(recipeBox->currentText() != "All Recipes"){ QString category = recipeBox->currentText(); query.prepare("select TITLE, IMG_PATH, FILE_PATH from RECIPES where CATEGORY = :category"); query.bindValue(":category", category); query.setForwardOnly(true); }else{ query.prepare("select TITLE, IMG_PATH, FILE_PATH from RECIPES"); query.setForwardOnly(true); } // Execute query query.exec(); while(query.next()){ // Extract info from query results QString title = query.value(0).toString(); QString img_path = query.value(1).toString(); QString file_path = query.value(2).toString(); // Create QListWidgetItems QListWidgetItem *recipe = new QListWidgetItem; recipe->setText(title); recipe->setData(Qt::UserRole, file_path); QImage *img = new QImage(); bool loaded = img->load(img_path); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); }else{ // If image doesn't exist, use placeholder image bool loaded = img->load("./Images/Placeholder.jpg"); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); } } recipes.append(recipe); } db.close(); return recipes; } QList<QListWidgetItem*> Window::getMatchingRecipes(QString searchText){ QList<QListWidgetItem*> recipes; // Get matching recipes and their scores. The QStringList contains title, img_path, file_path in order. std::map<double, QStringList> matchingRecipes = findMatches(searchText); // Build QListWidgetItems and add to QList // By default the map should be in ascending order, so use reverse iterator to get highest matches first for (auto iter = matchingRecipes.rbegin(); iter != matchingRecipes.rend(); ++iter){ QString title = iter->second[0]; QString img_path = iter->second[1]; QString file_path = iter->second[2]; QListWidgetItem *recipe = new QListWidgetItem; recipe->setText(title); recipe->setData(Qt::UserRole, file_path); QImage *img = new QImage(); bool loaded = img->load(img_path); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); }else{ // If image doesn't exist, use placeholder image bool loaded = img->load("./Images/Placeholder.jpg"); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); } } recipes.append(recipe); } return recipes; } std::map<double, QStringList> Window::findMatches(QString text) { // Open database db.open(); // Prepare query based on filter QSqlQuery query = QSqlQuery(); if(recipeBox->currentText() != "All Recipes"){ QString category = recipeBox->currentText(); query.prepare("select TITLE, IMG_PATH, FILE_PATH from RECIPES where CATEGORY = :category"); query.bindValue(":category", category); query.setForwardOnly(true); }else{ query.prepare("select TITLE, IMG_PATH, FILE_PATH from RECIPES"); query.setForwardOnly(true); } // Execute query query.exec(); // Get matching files and their scores std::map<double, QStringList> matchingFiles; std::string txtstr = text.toStdString(); while(query.next()){ int score; QString title = query.value(0).toString(); QString img_path = query.value(1).toString(); QString file_path = query.value(2).toString(); std::string titlestr = title.toStdString(); if (fts::fuzzy_match_score(txtstr.c_str(), titlestr.c_str(), score)){ // If a map entry already has the current score, increase score by 0.01. double dbscore = (double)score; if (matchingFiles.count(dbscore) > 0){ dbscore += 0.01; } matchingFiles[dbscore] = QStringList() << title << img_path << file_path; } } return matchingFiles; } void Window::createRecipeList() { recipeList = new QListWidget(); recipeList->setViewMode(QListView::IconMode); recipeList->setIconSize(QSize(267, 150)); recipeList->setGridSize(QSize(280, 185)); recipeList->setWordWrap(true); recipeList->setTextElideMode(Qt::ElideNone); } void Window::openFile(QListWidgetItem *recipe) { // Read hidden data to find full file path QString path = recipe->data(Qt::UserRole).toString(); QDesktopServices::openUrl(QUrl::fromLocalFile(currentDir.absoluteFilePath(path))); } void Window::updateDatabase(){ db_ops::update_database(&db); } void Window::cleanDatabase(){ db_ops::clean_database(&db); } void Window::resizeEvent(QResizeEvent *event){ int iconWidth, iconHeight, gridWidth, gridHeight, columns; double gridRatio = 280.0/185.0; double iconRatio = 267.0/150.0; QSize recipeListSize = recipeList->size(); if(recipeListSize.width()<=587){ // Set defaults for minimum size columns = 2; iconWidth = 267; iconHeight = 150; gridWidth = 280; gridHeight = 185; }else{ // Icons should never go larger than default, so set number of columns to round up columns = ceil(recipeListSize.width()/280.0); // Width of grid is widget_width/columns, with extra width removed to allow for scrollbar gridWidth = int(recipeListSize.width()/columns) - ceil(18.0/columns); // Calculate other parameters based on ratios of default values. gridHeight = int(gridWidth/gridRatio); iconWidth = gridWidth - 13; iconHeight = int(iconWidth/iconRatio); } recipeList->setIconSize(QSize(iconWidth, iconHeight)); recipeList->setGridSize(QSize(gridWidth, gridHeight)); }
#include <QtWidgets> #include "mainwindow.h" #include <fts_fuzzy_match.h> #include <glob.h> #include <string> #include <map> #include <database.h> Window::Window(QWidget *parent) : QMainWindow(parent) { // Initalise database db.setDatabaseName("recipes.db"); // Initialise widgets searchBox = new SearchBox(); searchBox->setPlaceholderText("Search for recipes"); recipeBox = new QComboBox(); QStringList recipeCategories; recipeCategories << "All Recipes" << "Beef" << "Chicken" << "Dessert" << "Lamb" << "Pork" << "Seafood" << "Turkey" << "Veggie"; recipeBox->addItems(recipeCategories); createRecipeList(); numResults = new QLabel(); // Set layout centralWidget = new QWidget(); QGridLayout *mainLayout = new QGridLayout(centralWidget); mainLayout->addWidget(searchBox, 0, 0, 1, 6); mainLayout->addWidget(numResults, 0, 6, 1, 1); mainLayout->addWidget(recipeBox, 0, 7, 1, 1); mainLayout->addWidget(recipeList, 1, 0, 1, 8); centralWidget->setLayout(mainLayout); centralWidget->show(); setCentralWidget(centralWidget); // Create menus optionsMenu = new QMenu("Options"); updateDb = new QAction("Update database", this); connect(updateDb, &QAction::triggered, this, &Window::updateDatabase); cleanDb = new QAction("Clean database", this); connect(cleanDb, &QAction::triggered, this, &Window::cleanDatabase); optionsMenu->addAction(updateDb); optionsMenu->addAction(cleanDb); menuBar()->addMenu(optionsMenu); // Set window paramters setWindowTitle(tr("Find Recipes")); setMinimumSize(600, 400); // Set signals connect(recipeList, &QListWidget::itemDoubleClicked, this, &Window::openFile); connect(searchBox, SIGNAL(inputText(QString)), this, SLOT(updateRecipesDiplay(QString))); connect(searchBox, SIGNAL(returnPressed()), recipeList, SLOT(setFocus())); connect(recipeBox, SIGNAL(currentTextChanged(QString)), searchBox, SLOT(recipeFiterChanged(QString))); // Populate list on start up updateRecipesDiplay(""); } // Get list of files according to glob patternn QStringList globVector(const std::string& pattern){ glob_t glob_result; glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result); QStringList files; for(unsigned int i=0; i<glob_result.gl_pathc; ++i){ files << QString(glob_result.gl_pathv[i]); } globfree(&glob_result); return files; } void SearchBox::recipeFiterChanged(QString newFilter){ // When the recipe filter changes, emit this signal to call updateRecipeDisplay emit inputText(text()); } void SearchBox::keyPressEvent(QKeyEvent *evt){ QLineEdit::keyPressEvent(evt); // When the search changes, emit this signal to call updateRecipeDisplay emit inputText(text()); } void Window::updateRecipesDiplay(QString searchText){ recipeList->clear(); QList<QListWidgetItem*> recipes = getRecipeList(searchText); for (int i=0; i<recipes.size(); ++i){ recipeList->addItem(recipes[i]); } if(searchText.isEmpty()){ recipeList->sortItems(); } QString text = QString("%1 recipes").arg(recipes.size()); if (recipes.size() == 1){ text = "1 recipe"; } numResults->setText(text); } QList<QListWidgetItem*> Window::getRecipeList(QString searchText){ QList<QListWidgetItem*> recipes; if (searchText.isEmpty()) { recipes = getAllRecipes(); }else{ recipes = getMatchingRecipes(searchText); } return recipes; } QList<QListWidgetItem*> Window::getAllRecipes(){ QList<QListWidgetItem*> recipes; // Open database and execute query db.open(); // Prepare query based on filter QSqlQuery query = QSqlQuery(); if(recipeBox->currentText() != "All Recipes"){ QString category = recipeBox->currentText(); query.prepare("select TITLE, IMG_PATH, FILE_PATH from RECIPES where CATEGORY = :category"); query.bindValue(":category", category); query.setForwardOnly(true); }else{ query.prepare("select TITLE, IMG_PATH, FILE_PATH from RECIPES"); query.setForwardOnly(true); } // Execute query query.exec(); while(query.next()){ // Extract info from query results QString title = query.value(0).toString(); QString img_path = query.value(1).toString(); QString file_path = query.value(2).toString(); // Create QListWidgetItems QListWidgetItem *recipe = new QListWidgetItem; recipe->setText(title); recipe->setData(Qt::UserRole, file_path); QImage *img = new QImage(); bool loaded = img->load(img_path); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); }else{ // If image doesn't exist, use placeholder image bool loaded = img->load("./Images/Placeholder.jpg"); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); } } recipes.append(recipe); } db.close(); return recipes; } QList<QListWidgetItem*> Window::getMatchingRecipes(QString searchText){ QList<QListWidgetItem*> recipes; // Get matching recipes and their scores. The QStringList contains title, img_path, file_path in order. std::map<double, QStringList> matchingRecipes = findMatches(searchText); // Build QListWidgetItems and add to QList // By default the map should be in ascending order, so use reverse iterator to get highest matches first for (auto iter = matchingRecipes.rbegin(); iter != matchingRecipes.rend(); ++iter){ QString title = iter->second[0]; QString img_path = iter->second[1]; QString file_path = iter->second[2]; QListWidgetItem *recipe = new QListWidgetItem; recipe->setText(title); recipe->setData(Qt::UserRole, file_path); QImage *img = new QImage(); bool loaded = img->load(img_path); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); }else{ // If image doesn't exist, use placeholder image bool loaded = img->load("./Images/Placeholder.jpg"); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); } } recipes.append(recipe); } return recipes; } std::map<double, QStringList> Window::findMatches(QString text) { // Open database db.open(); // Prepare query based on filter QSqlQuery query = QSqlQuery(); if(recipeBox->currentText() != "All Recipes"){ QString category = recipeBox->currentText(); query.prepare("select TITLE, IMG_PATH, FILE_PATH from RECIPES where CATEGORY = :category"); query.bindValue(":category", category); query.setForwardOnly(true); }else{ query.prepare("select TITLE, IMG_PATH, FILE_PATH from RECIPES"); query.setForwardOnly(true); } // Execute query query.exec(); // Get matching files and their scores std::map<double, QStringList> matchingFiles; std::string txtstr = text.toStdString(); while(query.next()){ int score; QString title = query.value(0).toString(); QString img_path = query.value(1).toString(); QString file_path = query.value(2).toString(); std::string titlestr = title.toStdString(); if (fts::fuzzy_match_score(txtstr.c_str(), titlestr.c_str(), score)){ // If a map entry already has the current score, increase score by 0.01. double dbscore = (double)score; if (matchingFiles.count(dbscore) > 0){ dbscore += 0.01; } matchingFiles[dbscore] = QStringList() << title << img_path << file_path; } } db.close(); return matchingFiles; } void Window::createRecipeList() { recipeList = new QListWidget(); recipeList->setViewMode(QListView::IconMode); recipeList->setIconSize(QSize(267, 150)); recipeList->setGridSize(QSize(280, 185)); recipeList->setWordWrap(true); recipeList->setTextElideMode(Qt::ElideNone); } void Window::openFile(QListWidgetItem *recipe) { // Read hidden data to find full file path QString path = recipe->data(Qt::UserRole).toString(); QDesktopServices::openUrl(QUrl::fromLocalFile(currentDir.absoluteFilePath(path))); } void Window::updateDatabase(){ db_ops::update_database(&db); // Repopulate list updateRecipesDiplay(""); } void Window::cleanDatabase(){ db_ops::clean_database(&db); } void Window::resizeEvent(QResizeEvent *event){ int iconWidth, iconHeight, gridWidth, gridHeight, columns; double gridRatio = 280.0/185.0; double iconRatio = 267.0/150.0; QSize recipeListSize = recipeList->size(); if(recipeListSize.width()<=587){ // Set defaults for minimum size columns = 2; iconWidth = 267; iconHeight = 150; gridWidth = 280; gridHeight = 185; }else{ // Icons should never go larger than default, so set number of columns to round up columns = ceil(recipeListSize.width()/280.0); // Width of grid is widget_width/columns, with extra width removed to allow for scrollbar gridWidth = int(recipeListSize.width()/columns) - ceil(18.0/columns); // Calculate other parameters based on ratios of default values. gridHeight = int(gridWidth/gridRatio); iconWidth = gridWidth - 13; iconHeight = int(iconWidth/iconRatio); } recipeList->setIconSize(QSize(iconWidth, iconHeight)); recipeList->setGridSize(QSize(gridWidth, gridHeight)); }
Refresh display after updating database
Refresh display after updating database
C++
mit
strangetom/RecipeFinder
83f4c981491580d3c3efc82e8d251424ab49d98a
mainwindow.cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; }
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowTitle("CRC Calculator ver " + QString::number(MAJOR_VERSION) + '.' + QString::number(MINOR_VERSION)); } MainWindow::~MainWindow() { delete ui; }
Add Main Window Title + version
Add Main Window Title + version
C++
bsd-3-clause
KoynovStas/QCRC_Calc
623dbc6e99fe9097f366f2f1c20053b241870142
src/HexagonOffload.cpp
src/HexagonOffload.cpp
#include <iostream> #include <fstream> #include <memory> #include "HexagonOffload.h" #include "IRMutator.h" #include "Substitute.h" #include "Closure.h" #include "Param.h" #include "Image.h" #include "LLVM_Output.h" #include "RemoveTrivialForLoops.h" namespace Halide { namespace Internal { using std::string; using std::vector; namespace { // Replace the parameter objects of loads/stores witha new parameter // object. class ReplaceParams : public IRMutator { const std::map<std::string, Parameter> &replacements; using IRMutator::visit; void visit(const Load *op) { auto i = replacements.find(op->name); if (i != replacements.end()) { expr = Load::make(op->type, op->name, mutate(op->index), op->image, i->second); } else { IRMutator::visit(op); } } void visit(const Store *op) { auto i = replacements.find(op->name); if (i != replacements.end()) { stmt = Store::make(op->name, mutate(op->value), mutate(op->index), i->second); } else { IRMutator::visit(op); } } public: ReplaceParams(const std::map<std::string, Parameter> &replacements) : replacements(replacements) {} }; Stmt replace_params(Stmt s, const std::map<std::string, Parameter> &replacements) { return ReplaceParams(replacements).mutate(s); } class InjectHexagonRpc : public IRMutator { std::map<std::string, Expr> state_vars; Module device_code; /** Alignment info for Int(32) variables in scope, so we don't * lose the information when creating Hexagon kernels. */ Scope<ModulusRemainder> alignment_info; Expr state_var(const std::string& name, Type type) { Expr& var = state_vars[name]; if (!var.defined()) { Buffer storage(type, {}, nullptr, name + "_buf"); *(void **)storage.host_ptr() = nullptr; var = Load::make(type_of<void*>(), name + "_buf", 0, storage, Parameter()); } return var; } Expr state_var_ptr(const std::string& name, Type type) { Expr var = state_var(name, type); return Call::make(Handle(), Call::address_of, {var}, Call::Intrinsic); } Expr module_state() { return state_var("hexagon_module_state", type_of<void*>()); } Expr module_state_ptr() { return state_var_ptr("hexagon_module_state", type_of<void*>()); } // Create a Buffer containing the given buffer/size, and return an // expression for a pointer to the first element. Expr buffer_ptr(const uint8_t* buffer, size_t size, const char* name) { Buffer code(type_of<uint8_t>(), {(int)size}, nullptr, name); memcpy(code.host_ptr(), buffer, (int)size); Expr ptr_0 = Load::make(type_of<uint8_t>(), name, 0, code, Parameter()); return Call::make(Handle(), Call::address_of, {ptr_0}, Call::Intrinsic); } Stmt call_extern_and_assert(const std::string& name, const std::vector<Expr>& args) { Expr call = Call::make(Int(32), name, args, Call::Extern); string call_result_name = unique_name(name + "_result"); Expr call_result_var = Variable::make(Int(32), call_result_name); return LetStmt::make(call_result_name, call, AssertStmt::make(EQ::make(call_result_var, 0), call_result_var)); } using IRMutator::visit; void visit(const For *loop) { if (loop->device_api == DeviceAPI::Hexagon) { // Unrolling or loop partitioning might generate multiple // loops with the same name, so we need to unique them. std::string hex_name = "hex_" + loop->name; // After moving this to Hexagon, it doesn't need to be // marked Hexagon anymore. Stmt body = For::make(loop->name, loop->min, loop->extent, loop->for_type, DeviceAPI::None, loop->body); body = remove_trivial_for_loops(body); // Build a closure for the device code. // TODO: Should this move the body of the loop to Hexagon, // or the loop itself? Currently, this moves the loop itself. Closure c(body); // Make an argument list, and generate a function in the // device_code module. The hexagon runtime code expects // the arguments to appear in the order of (input buffers, // output buffers, input scalars). There's a huge hack // here, in that the scalars must be last for the scalar // arguments to shadow the symbols of the buffer. std::vector<LoweredArgument> input_buffers, output_buffers; std::map<std::string, Parameter> replacement_params; for (const auto& i : c.buffers) { if (i.second.write) { Argument::Kind kind = Argument::OutputBuffer; output_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions)); } else { Argument::Kind kind = Argument::InputBuffer; input_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions)); } // Build a parameter to replace. Parameter p(i.second.type, true, i.second.dimensions); // Assert that buffers are aligned to one HVX // vector. Generally, they should be page aligned ION // buffers, so this should be a reasonable // requirement. const int alignment = 128; p.set_host_alignment(alignment); // The other parameter constraints are already // accounted for by the closure grabbing those // arguments, so we only need to provide the host // alignment. replacement_params[i.first] = p; // Add an assert to the body that validates the // alignment of the buffer. if (!device_code.target().has_feature(Target::NoAsserts)) { Expr host_ptr = reinterpret<uint64_t>(Variable::make(Handle(), i.first + ".host")); Expr error = Call::make(Int(32), "halide_error_unaligned_host_ptr", {i.first, alignment}, Call::Extern); body = Block::make(AssertStmt::make(host_ptr % alignment == 0, error), body); } } body = replace_params(body, replacement_params); std::vector<LoweredArgument> args; args.insert(args.end(), input_buffers.begin(), input_buffers.end()); args.insert(args.end(), output_buffers.begin(), output_buffers.end()); for (const auto& i : c.vars) { LoweredArgument arg(i.first, Argument::InputScalar, i.second, 0); if (alignment_info.contains(i.first)) { arg.alignment = alignment_info.get(i.first); } args.push_back(arg); } device_code.append(LoweredFunc(hex_name, args, body, LoweredFunc::External)); // Generate a call to hexagon_device_run. std::vector<Expr> arg_sizes; std::vector<Expr> arg_ptrs; std::vector<Expr> arg_flags; for (const auto& i : c.buffers) { arg_sizes.push_back(Expr((uint64_t) sizeof(buffer_t*))); arg_ptrs.push_back(Variable::make(type_of<buffer_t *>(), i.first + ".buffer")); int flags = 0; if (i.second.read) flags |= 0x1; if (i.second.write) flags |= 0x2; arg_flags.push_back(flags); } for (const auto& i : c.vars) { Expr arg = Variable::make(i.second, i.first); Expr arg_ptr = Call::make(type_of<void *>(), Call::make_struct, {arg}, Call::Intrinsic); // sizeof(scalar-type) will always fit into int32 arg_sizes.push_back(Expr((uint64_t) i.second.bytes())); arg_ptrs.push_back(arg_ptr); arg_flags.push_back(0x0); } // The argument list is terminated with an argument of size 0. arg_sizes.push_back(Expr((uint64_t) 0)); std::string pipeline_name = hex_name + "_argv"; std::vector<Expr> params; params.push_back(module_state()); params.push_back(pipeline_name); params.push_back(state_var_ptr(hex_name, type_of<int>())); params.push_back(Call::make(type_of<size_t*>(), Call::make_struct, arg_sizes, Call::Intrinsic)); params.push_back(Call::make(type_of<void**>(), Call::make_struct, arg_ptrs, Call::Intrinsic)); params.push_back(Call::make(type_of<int*>(), Call::make_struct, arg_flags, Call::Intrinsic)); stmt = call_extern_and_assert("halide_hexagon_run", params); } else { IRMutator::visit(loop); } } void visit(const Let *op) { if (op->value.type() == Int(32)) { alignment_info.push(op->name, modulus_remainder(op->value, alignment_info)); } IRMutator::visit(op); if (op->value.type() == Int(32)) { alignment_info.pop(op->name); } } void visit(const LetStmt *op) { if (op->value.type() == Int(32)) { alignment_info.push(op->name, modulus_remainder(op->value, alignment_info)); } IRMutator::visit(op); if (op->value.type() == Int(32)) { alignment_info.pop(op->name); } } public: InjectHexagonRpc(const Target &target) : device_code("hexagon", target) {} Stmt inject(Stmt s) { s = mutate(s); // Skip if there are no device kernels. if (device_code.functions().empty()) { return s; } // Compile the device code. std::vector<uint8_t> object; #if 0 compile_module_to_shared_object(device_code, object); //compile_module_to_shared_object(device_code, "/tmp/hex.so"); #else debug(1) << "Hexagon device code module: " << device_code << "\n"; device_code.compile(Outputs().bitcode("hex.bc")); string hex_command = "${HL_HEXAGON_TOOLS}/bin/hexagon-clang hex.bc -fPIC -O3 -Wno-override-module -shared -o hex.so"; if (device_code.target().has_feature(Target::HVX_v62)) { hex_command += " -mv62"; } if (device_code.target().has_feature(Target::HVX_128)) { hex_command += " -mhvx-double"; } int result = system(hex_command.c_str()); internal_assert(result == 0) << "hexagon-clang failed\n"; std::ifstream so("hex.so", std::ios::binary | std::ios::ate); object.resize(so.tellg()); so.seekg(0, std::ios::beg); so.read(reinterpret_cast<char*>(&object[0]), object.size()); #endif // Put the compiled object into a buffer. size_t code_size = object.size(); Expr code_ptr = buffer_ptr(&object[0], code_size, "hexagon_code"); // Wrap the statement in calls to halide_initialize_kernels. Stmt init_kernels = call_extern_and_assert("halide_hexagon_initialize_kernels", {module_state_ptr(), code_ptr, Expr((uint64_t) code_size)}); s = Block::make(init_kernels, s); return s; } }; } Stmt inject_hexagon_rpc(Stmt s, const Target &host_target) { Target target(Target::NoOS, Target::Hexagon, 32); for (Target::Feature i : {Target::Debug, Target::NoAsserts, Target::HVX_64, Target::HVX_128, Target::HVX_v62}) { if (host_target.has_feature(i)) { target = target.with_feature(i); } } InjectHexagonRpc injector(target); s = injector.inject(s); return s; } } // namespace Internal } // namespace Halide
#include <iostream> #include <fstream> #include <memory> #include "HexagonOffload.h" #include "IRMutator.h" #include "Substitute.h" #include "Closure.h" #include "Param.h" #include "Image.h" #include "LLVM_Output.h" #include "RemoveTrivialForLoops.h" namespace Halide { namespace Internal { using std::string; using std::vector; namespace { // Replace the parameter objects of loads/stores witha new parameter // object. class ReplaceParams : public IRMutator { const std::map<std::string, Parameter> &replacements; using IRMutator::visit; void visit(const Load *op) { auto i = replacements.find(op->name); if (i != replacements.end()) { expr = Load::make(op->type, op->name, mutate(op->index), op->image, i->second); } else { IRMutator::visit(op); } } void visit(const Store *op) { auto i = replacements.find(op->name); if (i != replacements.end()) { stmt = Store::make(op->name, mutate(op->value), mutate(op->index), i->second); } else { IRMutator::visit(op); } } public: ReplaceParams(const std::map<std::string, Parameter> &replacements) : replacements(replacements) {} }; Stmt replace_params(Stmt s, const std::map<std::string, Parameter> &replacements) { return ReplaceParams(replacements).mutate(s); } class InjectHexagonRpc : public IRMutator { std::map<std::string, Expr> state_vars; Module device_code; /** Alignment info for Int(32) variables in scope, so we don't * lose the information when creating Hexagon kernels. */ Scope<ModulusRemainder> alignment_info; Expr state_var(const std::string& name, Type type) { Expr& var = state_vars[name]; if (!var.defined()) { Buffer storage(type, {}, nullptr, name + "_buf"); *(void **)storage.host_ptr() = nullptr; var = Load::make(type_of<void*>(), name + "_buf", 0, storage, Parameter()); } return var; } Expr state_var_ptr(const std::string& name, Type type) { Expr var = state_var(name, type); return Call::make(Handle(), Call::address_of, {var}, Call::Intrinsic); } Expr module_state() { return state_var("hexagon_module_state", type_of<void*>()); } Expr module_state_ptr() { return state_var_ptr("hexagon_module_state", type_of<void*>()); } // Create a Buffer containing the given buffer/size, and return an // expression for a pointer to the first element. Expr buffer_ptr(const uint8_t* buffer, size_t size, const char* name) { Buffer code(type_of<uint8_t>(), {(int)size}, nullptr, name); memcpy(code.host_ptr(), buffer, (int)size); Expr ptr_0 = Load::make(type_of<uint8_t>(), name, 0, code, Parameter()); return Call::make(Handle(), Call::address_of, {ptr_0}, Call::Intrinsic); } Stmt call_extern_and_assert(const std::string& name, const std::vector<Expr>& args) { Expr call = Call::make(Int(32), name, args, Call::Extern); string call_result_name = unique_name(name + "_result"); Expr call_result_var = Variable::make(Int(32), call_result_name); return LetStmt::make(call_result_name, call, AssertStmt::make(EQ::make(call_result_var, 0), call_result_var)); } using IRMutator::visit; void visit(const For *loop) { if (loop->device_api == DeviceAPI::Hexagon) { // Unrolling or loop partitioning might generate multiple // loops with the same name, so we need to unique them. std::string hex_name = "hex_" + loop->name; // After moving this to Hexagon, it doesn't need to be // marked Hexagon anymore. Stmt body = For::make(loop->name, loop->min, loop->extent, loop->for_type, DeviceAPI::None, loop->body); body = remove_trivial_for_loops(body); // Build a closure for the device code. // TODO: Should this move the body of the loop to Hexagon, // or the loop itself? Currently, this moves the loop itself. Closure c(body); // Make an argument list, and generate a function in the // device_code module. The hexagon runtime code expects // the arguments to appear in the order of (input buffers, // output buffers, input scalars). There's a huge hack // here, in that the scalars must be last for the scalar // arguments to shadow the symbols of the buffer. std::vector<LoweredArgument> input_buffers, output_buffers; std::map<std::string, Parameter> replacement_params; for (const auto& i : c.buffers) { if (i.second.write) { Argument::Kind kind = Argument::OutputBuffer; output_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions)); } else { Argument::Kind kind = Argument::InputBuffer; input_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions)); } // Build a parameter to replace. Parameter p(i.second.type, true, i.second.dimensions); // Assert that buffers are aligned to one HVX // vector. Generally, they should be page aligned ION // buffers, so this should be a reasonable // requirement. const int alignment = 128; p.set_host_alignment(alignment); // The other parameter constraints are already // accounted for by the closure grabbing those // arguments, so we only need to provide the host // alignment. replacement_params[i.first] = p; // Add an assert to the body that validates the // alignment of the buffer. if (!device_code.target().has_feature(Target::NoAsserts)) { Expr host_ptr = reinterpret<uint64_t>(Variable::make(Handle(), i.first + ".host")); Expr error = Call::make(Int(32), "halide_error_unaligned_host_ptr", {i.first, alignment}, Call::Extern); body = Block::make(AssertStmt::make(host_ptr % alignment == 0, error), body); } } body = replace_params(body, replacement_params); std::vector<LoweredArgument> args; args.insert(args.end(), input_buffers.begin(), input_buffers.end()); args.insert(args.end(), output_buffers.begin(), output_buffers.end()); for (const auto& i : c.vars) { LoweredArgument arg(i.first, Argument::InputScalar, i.second, 0); if (alignment_info.contains(i.first)) { arg.alignment = alignment_info.get(i.first); } args.push_back(arg); } device_code.append(LoweredFunc(hex_name, args, body, LoweredFunc::External)); // Generate a call to hexagon_device_run. std::vector<Expr> arg_sizes; std::vector<Expr> arg_ptrs; std::vector<Expr> arg_flags; for (const auto& i : c.buffers) { arg_sizes.push_back(Expr((uint64_t) sizeof(buffer_t*))); arg_ptrs.push_back(Variable::make(type_of<buffer_t *>(), i.first + ".buffer")); int flags = 0; if (i.second.read) flags |= 0x1; if (i.second.write) flags |= 0x2; arg_flags.push_back(flags); } for (const auto& i : c.vars) { Expr arg = Variable::make(i.second, i.first); Expr arg_ptr = Call::make(type_of<void *>(), Call::make_struct, {arg}, Call::Intrinsic); // sizeof(scalar-type) will always fit into int32 arg_sizes.push_back(Expr((uint64_t) i.second.bytes())); arg_ptrs.push_back(arg_ptr); arg_flags.push_back(0x0); } // The argument list is terminated with an argument of size 0. arg_sizes.push_back(Expr((uint64_t) 0)); std::string pipeline_name = hex_name + "_argv"; std::vector<Expr> params; params.push_back(module_state()); params.push_back(pipeline_name); params.push_back(state_var_ptr(hex_name, type_of<int>())); params.push_back(Call::make(type_of<size_t*>(), Call::make_struct, arg_sizes, Call::Intrinsic)); params.push_back(Call::make(type_of<void**>(), Call::make_struct, arg_ptrs, Call::Intrinsic)); params.push_back(Call::make(type_of<int*>(), Call::make_struct, arg_flags, Call::Intrinsic)); stmt = call_extern_and_assert("halide_hexagon_run", params); } else { IRMutator::visit(loop); } } void visit(const Let *op) { if (op->value.type() == Int(32)) { alignment_info.push(op->name, modulus_remainder(op->value, alignment_info)); } IRMutator::visit(op); if (op->value.type() == Int(32)) { alignment_info.pop(op->name); } } void visit(const LetStmt *op) { if (op->value.type() == Int(32)) { alignment_info.push(op->name, modulus_remainder(op->value, alignment_info)); } IRMutator::visit(op); if (op->value.type() == Int(32)) { alignment_info.pop(op->name); } } public: InjectHexagonRpc(const Target &target) : device_code("hexagon", target) {} Stmt inject(Stmt s) { s = mutate(s); // Skip if there are no device kernels. if (device_code.functions().empty()) { return s; } // Compile the device code. std::vector<uint8_t> object; #if 0 compile_module_to_shared_object(device_code, object); //compile_module_to_shared_object(device_code, "/tmp/hex.so"); #else TemporaryFile tmp_bitcode("hex", ".bc"); TemporaryFile tmp_shared_object("hex", ".so"); debug(1) << "Hexagon device code module: " << device_code << "\n"; device_code.compile(Outputs().bitcode(tmp_bitcode.pathname())); string hex_command = "${HL_HEXAGON_TOOLS}/bin/hexagon-clang "; hex_command += tmp_bitcode.pathname(); hex_command += " -fPIC -O3 -Wno-override-module -shared "; if (device_code.target().has_feature(Target::HVX_v62)) { hex_command += " -mv62"; } if (device_code.target().has_feature(Target::HVX_128)) { hex_command += " -mhvx-double"; } hex_command += " -o " + tmp_shared_object.pathname(); int result = system(hex_command.c_str()); internal_assert(result == 0) << "hexagon-clang failed\n"; std::ifstream so(tmp_shared_object.pathname(), std::ios::binary | std::ios::ate); object.resize(so.tellg()); so.seekg(0, std::ios::beg); so.read(reinterpret_cast<char*>(&object[0]), object.size()); #endif // Put the compiled object into a buffer. size_t code_size = object.size(); Expr code_ptr = buffer_ptr(&object[0], code_size, "hexagon_code"); // Wrap the statement in calls to halide_initialize_kernels. Stmt init_kernels = call_extern_and_assert("halide_hexagon_initialize_kernels", {module_state_ptr(), code_ptr, Expr((uint64_t) code_size)}); s = Block::make(init_kernels, s); return s; } }; } Stmt inject_hexagon_rpc(Stmt s, const Target &host_target) { Target target(Target::NoOS, Target::Hexagon, 32); for (Target::Feature i : {Target::Debug, Target::NoAsserts, Target::HVX_64, Target::HVX_128, Target::HVX_v62}) { if (host_target.has_feature(i)) { target = target.with_feature(i); } } InjectHexagonRpc injector(target); s = injector.inject(s); return s; } } // namespace Internal } // namespace Halide
Use proper temporary files for intermediates.
Use proper temporary files for intermediates.
C++
mit
ronen/Halide,ronen/Halide,kgnk/Halide,ronen/Halide,jiawen/Halide,kgnk/Halide,psuriana/Halide,kgnk/Halide,jiawen/Halide,ronen/Halide,ronen/Halide,psuriana/Halide,jiawen/Halide,kgnk/Halide,psuriana/Halide,jiawen/Halide,ronen/Halide,psuriana/Halide,psuriana/Halide,kgnk/Halide,ronen/Halide,ronen/Halide,psuriana/Halide,jiawen/Halide,kgnk/Halide,kgnk/Halide,jiawen/Halide,psuriana/Halide,jiawen/Halide,kgnk/Halide
68572219d56533d35e012e1fbbde049c454ed15e
src/IO/CommandLine.cpp
src/IO/CommandLine.cpp
#include "CommandLine.h" #include "FrameBuffer.h" #include "Keyboard.h" using namespace std; CommandLine::CommandLine(table_type table):_table(table){ //builtin commands here _table.insert(make_pair("echo",[](CommandLine*,const vector<string>& args){ for(auto s : args){ printf("%s ",s.c_str()); } fb.printf("\n"); })); _table.insert(make_pair("help",[](CommandLine*,const vector<string>&){ printf( "Help of Super OS (tm) : \n" "Builtin Commands :\n" " echo <arg> : print argument <arg>\n" ); })); _table.insert(make_pair("ls",[](CommandLine*cl ,const vector<string>&){ if(!cl->pwd) { printf("fatal error : no pwd set\n"); return; } auto v = cl->pwd->getFilesName(); for(auto f : v) printf("%s ",f.c_str()); printf("\n"); })); _table.insert(make_pair("cd",[](CommandLine*cl ,const vector<string>&args ){ if(!cl->pwd) { printf("fatal error : no pwd set\n"); return; } if(args.empty()) return; File* f = (*cl->pwd)[args[0]]; if(f == nullptr) { printf("%s doesn't exist in current directory\n",args[0].c_str()); return; } Directory * d = f->dir(); if(d == nullptr){ printf("%s is not a directory\n",args[0].c_str()); return; } cl->pwd = d; })); } void CommandLine::run(){ while(true) { printf("$ "); auto input = readCommand(); if(input.size() == 0) continue; auto it = _table.find(input[0]); if(it == _table.end()){ printf("Command %s not found\n",input[0].c_str()); continue; } input.erase(input.begin()); it->second(this,input); } } std::string CommandLine::readCommandText(){ std::string res; //fb.printf("hey ! \n"); while(true) { Keycode kc = kbd.poll(); //fb.printf("Reading Command"); if(!kc.isRelease && kc.symbol > 0) { if(kc.symbol == '\b') { if(!res.empty()) { fb.puts("\b \b"); } } else { fb.putc(kc.symbol); } } else continue; if(kc.symbol == '\n') break; if(kc.symbol == '\b'){ if(!res.empty()) { res.pop_back(); } continue; } if (kc.symbol != -1) res.push_back(kc.symbol); } //fb.printf("Command : %s",res.c_str()); return res; } std::vector<std::string> CommandLine::readCommand(){ return split(readCommandText(),' ',false); // may be more complicated later. } void CommandLine::add(std::string name,command_func func){ _table[name] = func; }
#include "CommandLine.h" #include "FrameBuffer.h" #include "Keyboard.h" using namespace std; CommandLine::CommandLine(table_type table):_table(table){ //builtin commands here _table.insert(make_pair("echo", [](CommandLine*, const vector<string>& args) { for(auto s : args) { printf("%s ", s.c_str()); } fb.printf("\n"); })); _table.insert(make_pair("help",[](CommandLine*, const vector<string>&) { printf( "Help of Super OS (tm) : \n" "Builtin Commands :\n" " echo <arg> : print argument <arg>\n" ); })); _table.insert(make_pair("ls", [](CommandLine* cl, const vector<string>&) { if(!cl->pwd) { printf("fatal error : no pwd set\n"); return; } auto v = cl->pwd->getFilesName(); for(auto f : v) printf("%s ",f.c_str()); printf("\n"); })); _table.insert(make_pair("cd", [](CommandLine* cl, const vector<string>& args) { if(!cl->pwd) { printf("fatal error : no pwd set\n"); return; } if(args.empty()) return; File* f = (*cl->pwd)[args[0]]; if(f == nullptr) { printf("%s doesn't exist in current directory\n",args[0].c_str()); return; } Directory* d = f->dir(); if(d == nullptr) { printf("%s is not a directory\n",args[0].c_str()); return; } cl->pwd = d; })); _table.insert(make_pair("cat", [](CommandLine* cl, const vector<string>& args) { if(!cl->pwd) { printf("fatal error : no pwd set\n"); return; } if(args.empty()) return; for(const string& file : args) { File* f = (*cl->pwd)[file]; if(f == nullptr) { printf("cat: %s: No such file or directory\n", file.c_str()); continue; } if(f->getType() == FileType::Directory) { printf("cat: %s: Is a directory\n", file.c_str()); continue; } char buffer[1025]; size_t size = f->getSize(); for(size_t i = 0; i < size; i += 1024) { size_t count = min((size_t)1024, size-i); f->readaddr(i, buffer, count); buffer[count] = 0; printf("%s", buffer); } printf("\n"); } })); } void CommandLine::run(){ while(true) { printf("$ "); auto input = readCommand(); if(input.size() == 0) continue; auto it = _table.find(input[0]); if(it == _table.end()){ printf("Command %s not found\n",input[0].c_str()); continue; } input.erase(input.begin()); it->second(this,input); } } std::string CommandLine::readCommandText(){ std::string res; //fb.printf("hey ! \n"); while(true) { Keycode kc = kbd.poll(); //fb.printf("Reading Command"); if(!kc.isRelease && kc.symbol > 0) { if(kc.symbol == '\b') { if(!res.empty()) { fb.puts("\b \b"); } } else { fb.putc(kc.symbol); } } else continue; if(kc.symbol == '\n') break; if(kc.symbol == '\b'){ if(!res.empty()) { res.pop_back(); } continue; } if (kc.symbol != -1) res.push_back(kc.symbol); } //fb.printf("Command : %s",res.c_str()); return res; } std::vector<std::string> CommandLine::readCommand(){ return split(readCommandText(),' ',false); // may be more complicated later. } void CommandLine::add(std::string name,command_func func){ _table[name] = func; }
Add `cat`
Add `cat`
C++
mit
TWal/ENS_sysres,TWal/ENS_sysres,TWal/ENS_sysres,TWal/ENS_sysres
6d497d7fdc546210bfa790817bcf698411385030
interpreter/cling/lib/Interpreter/AutoloadCallback.cpp
interpreter/cling/lib/Interpreter/AutoloadCallback.cpp
//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Path.h" #include "clang/Sema/Sema.h" #include "clang/Basic/Diagnostic.h" #include "clang/AST/AST.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/AutoloadCallback.h" #include "cling/Interpreter/Transaction.h" using namespace clang; namespace cling { void AutoloadCallback::report(clang::SourceLocation l,std::string name,std::string header) { Sema& sema= m_Interpreter->getSema(); unsigned id = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning, "Note: '%0' can be found in %1"); /* unsigned idn //TODO: To be enabled after we have a way to get the full path = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note, "Type : %0 , Full Path: %1")*/; sema.Diags.Report(l, id) << name << header; } bool AutoloadCallback::LookupObject (TagDecl *t) { if (t->hasAttr<AnnotateAttr>()) report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation()); return false; } class DefaultArgVisitor: public RecursiveASTVisitor<DefaultArgVisitor> { private: bool m_IsStoringState; AutoloadCallback::FwdDeclsMap* m_Map; clang::Preprocessor* m_PP; private: void InsertIntoAutoloadingState (Decl* decl, std::string annotation) { assert(annotation != "" && "Empty annotation!"); assert(m_PP); const FileEntry* FE = 0; SourceLocation fileNameLoc; bool isAngled = false; const DirectoryLookup* LookupFrom = 0; const DirectoryLookup* CurDir = 0; FE = m_PP->LookupFile(fileNameLoc, annotation, isAngled, LookupFrom, CurDir, /*SearchPath*/0, /*RelativePath*/ 0, /*suggestedModule*/0, /*SkipCache*/false, /*OpenFile*/ false, /*CacheFail*/ false); assert(FE && "Must have a valid FileEntry"); if (m_Map->find(FE) == m_Map->end()) (*m_Map)[FE] = std::vector<Decl*>(); (*m_Map)[FE].push_back(decl); } public: DefaultArgVisitor() : m_IsStoringState(false), m_Map(0) {} void RemoveDefaultArgsOf(Decl* D) { //D = D->getMostRecentDecl(); TraverseDecl(D); //while ((D = D->getPreviousDecl())) // TraverseDecl(D); } void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map, Preprocessor& PP) { m_IsStoringState = true; m_Map = &map; m_PP = &PP; TraverseDecl(D); m_PP = 0; m_Map = 0; m_IsStoringState = false; } bool shouldVisitTemplateInstantiations() { return true; } bool TraverseTemplateTypeParmDecl(TemplateTypeParmDecl* D) { if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitDecl(Decl* D) { if (m_IsStoringState) return true; if (!D->hasAttr<AnnotateAttr>()) return false; AnnotateAttr* attr = D->getAttr<AnnotateAttr>(); if (!attr) return true; switch (D->getKind()) { default: InsertIntoAutoloadingState(D, attr->getAnnotation()); break; case Decl::Enum: // EnumDecls have extra information 2 chars after the filename used // for extra fixups. InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2)); break; } return true; } bool TraverseTemplateDecl(TemplateDecl* D) { if (!D->getTemplatedDecl()->hasAttr<AnnotateAttr>()) return false; for(auto P: D->getTemplateParameters()->asArray()) TraverseDecl(P); return true; } bool TraverseNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) { if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool TraverseParmVarDecl(ParmVarDecl* D) { if (D->hasDefaultArg()) D->setDefaultArg(nullptr); return true; } }; void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, const clang::FileEntry *File, llvm::StringRef SearchPath, llvm::StringRef RelativePath, const clang::Module *Imported) { assert(File && "Must have a valid File"); auto found = m_Map.find(File); if (found == m_Map.end()) return; // nothing to do, file not referred in any annotation DefaultArgVisitor defaultArgsCleaner; for (auto D : found->second) { defaultArgsCleaner.RemoveDefaultArgsOf(D); } // Don't need to keep track of cleaned up decls from file. m_Map.erase(found); } AutoloadCallback::AutoloadCallback(Interpreter* interp) : InterpreterCallbacks(interp,true,false,true), m_Interpreter(interp){ //#ifdef _POSIX_C_SOURCE // //Workaround for differnt expansion of macros to typedefs // m_Interpreter->parse("#include <sys/types.h>"); //#endif } AutoloadCallback::~AutoloadCallback() { } void AutoloadCallback::TransactionCommitted(const Transaction &T) { if (T.decls_begin() == T.decls_end()) return; if (T.decls_begin()->m_DGR.isNull()) return; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { DefaultArgVisitor defaultArgsStateCollector; Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor(); for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; // if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl) // continue; if (DCI.m_DGR.isNull()) continue; for (DeclGroupRef::iterator J = DCI.m_DGR.begin(), JE = DCI.m_DGR.end(); J != JE; ++J) { defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP); } } } } } //end namespace cling
//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Path.h" #include "clang/Sema/Sema.h" #include "clang/Basic/Diagnostic.h" #include "clang/AST/AST.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/AutoloadCallback.h" #include "cling/Interpreter/Transaction.h" using namespace clang; namespace cling { void AutoloadCallback::report(clang::SourceLocation l,std::string name,std::string header) { Sema& sema= m_Interpreter->getSema(); unsigned id = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning, "Note: '%0' can be found in %1"); /* unsigned idn //TODO: To be enabled after we have a way to get the full path = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note, "Type : %0 , Full Path: %1")*/; sema.Diags.Report(l, id) << name << header; } bool AutoloadCallback::LookupObject (TagDecl *t) { if (t->hasAttr<AnnotateAttr>()) report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation()); return false; } class DefaultArgVisitor: public RecursiveASTVisitor<DefaultArgVisitor> { private: bool m_IsStoringState; AutoloadCallback::FwdDeclsMap* m_Map; clang::Preprocessor* m_PP; private: void InsertIntoAutoloadingState (Decl* decl, std::string annotation) { assert(annotation != "" && "Empty annotation!"); assert(m_PP); const FileEntry* FE = 0; SourceLocation fileNameLoc; bool isAngled = false; const DirectoryLookup* LookupFrom = 0; const DirectoryLookup* CurDir = 0; FE = m_PP->LookupFile(fileNameLoc, annotation, isAngled, LookupFrom, CurDir, /*SearchPath*/0, /*RelativePath*/ 0, /*suggestedModule*/0, /*SkipCache*/false, /*OpenFile*/ false, /*CacheFail*/ false); assert(FE && "Must have a valid FileEntry"); if (m_Map->find(FE) == m_Map->end()) (*m_Map)[FE] = std::vector<Decl*>(); (*m_Map)[FE].push_back(decl); } public: DefaultArgVisitor() : m_IsStoringState(false), m_Map(0) {} void RemoveDefaultArgsOf(Decl* D) { //D = D->getMostRecentDecl(); TraverseDecl(D); //while ((D = D->getPreviousDecl())) // TraverseDecl(D); } void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map, Preprocessor& PP) { m_IsStoringState = true; m_Map = &map; m_PP = &PP; TraverseDecl(D); m_PP = 0; m_Map = 0; m_IsStoringState = false; } bool shouldVisitTemplateInstantiations() { return true; } bool TraverseTemplateTypeParmDecl(TemplateTypeParmDecl* D) { if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitDecl(Decl* D) { if (!m_IsStoringState) return true; if (!D->hasAttr<AnnotateAttr>()) return false; AnnotateAttr* attr = D->getAttr<AnnotateAttr>(); if (!attr) return true; switch (D->getKind()) { default: InsertIntoAutoloadingState(D, attr->getAnnotation()); break; case Decl::Enum: // EnumDecls have extra information 2 chars after the filename used // for extra fixups. InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2)); break; } return true; } bool TraverseTemplateDecl(TemplateDecl* D) { if (!D->getTemplatedDecl()->hasAttr<AnnotateAttr>()) return false; for(auto P: D->getTemplateParameters()->asArray()) TraverseDecl(P); return true; } bool TraverseNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) { if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool TraverseParmVarDecl(ParmVarDecl* D) { if (D->hasDefaultArg()) D->setDefaultArg(nullptr); return true; } }; void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, const clang::FileEntry *File, llvm::StringRef SearchPath, llvm::StringRef RelativePath, const clang::Module *Imported) { assert(File && "Must have a valid File"); auto found = m_Map.find(File); if (found == m_Map.end()) return; // nothing to do, file not referred in any annotation DefaultArgVisitor defaultArgsCleaner; for (auto D : found->second) { defaultArgsCleaner.RemoveDefaultArgsOf(D); } // Don't need to keep track of cleaned up decls from file. m_Map.erase(found); } AutoloadCallback::AutoloadCallback(Interpreter* interp) : InterpreterCallbacks(interp,true,false,true), m_Interpreter(interp){ //#ifdef _POSIX_C_SOURCE // //Workaround for differnt expansion of macros to typedefs // m_Interpreter->parse("#include <sys/types.h>"); //#endif } AutoloadCallback::~AutoloadCallback() { } void AutoloadCallback::TransactionCommitted(const Transaction &T) { if (T.decls_begin() == T.decls_end()) return; if (T.decls_begin()->m_DGR.isNull()) return; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { DefaultArgVisitor defaultArgsStateCollector; Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor(); for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; // if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl) // continue; if (DCI.m_DGR.isNull()) continue; for (DeclGroupRef::iterator J = DCI.m_DGR.begin(), JE = DCI.m_DGR.end(); J != JE; ++J) { defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP); } } } } } //end namespace cling
Use the correct condition.
Use the correct condition.
C++
lgpl-2.1
perovic/root,0x0all/ROOT,thomaskeck/root,omazapa/root,esakellari/my_root_for_test,nilqed/root,nilqed/root,esakellari/my_root_for_test,georgtroska/root,simonpf/root,bbockelm/root,gbitzes/root,vukasinmilosevic/root,krafczyk/root,sawenzel/root,jrtomps/root,sawenzel/root,sbinet/cxx-root,gganis/root,davidlt/root,sirinath/root,gganis/root,lgiommi/root,olifre/root,krafczyk/root,mattkretz/root,thomaskeck/root,BerserkerTroll/root,vukasinmilosevic/root,krafczyk/root,olifre/root,esakellari/my_root_for_test,simonpf/root,thomaskeck/root,jrtomps/root,olifre/root,mkret2/root,bbockelm/root,mattkretz/root,lgiommi/root,root-mirror/root,root-mirror/root,CristinaCristescu/root,omazapa/root-old,davidlt/root,satyarth934/root,krafczyk/root,CristinaCristescu/root,sirinath/root,abhinavmoudgil95/root,sawenzel/root,vukasinmilosevic/root,satyarth934/root,mattkretz/root,root-mirror/root,thomaskeck/root,abhinavmoudgil95/root,sbinet/cxx-root,pspe/root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,dfunke/root,gbitzes/root,davidlt/root,agarciamontoro/root,CristinaCristescu/root,lgiommi/root,esakellari/my_root_for_test,Duraznos/root,abhinavmoudgil95/root,omazapa/root,evgeny-boger/root,BerserkerTroll/root,arch1tect0r/root,veprbl/root,CristinaCristescu/root,esakellari/root,sbinet/cxx-root,sawenzel/root,sbinet/cxx-root,root-mirror/root,lgiommi/root,buuck/root,simonpf/root,pspe/root,root-mirror/root,abhinavmoudgil95/root,zzxuanyuan/root,dfunke/root,davidlt/root,jrtomps/root,zzxuanyuan/root,sbinet/cxx-root,omazapa/root,simonpf/root,arch1tect0r/root,Y--/root,zzxuanyuan/root,thomaskeck/root,georgtroska/root,jrtomps/root,abhinavmoudgil95/root,abhinavmoudgil95/root,davidlt/root,krafczyk/root,gganis/root,sawenzel/root,veprbl/root,mattkretz/root,davidlt/root,satyarth934/root,dfunke/root,vukasinmilosevic/root,sawenzel/root,pspe/root,Duraznos/root,BerserkerTroll/root,perovic/root,arch1tect0r/root,krafczyk/root,gganis/root,agarciamontoro/root,esakellari/root,omazapa/root,buuck/root,omazapa/root-old,evgeny-boger/root,mkret2/root,mhuwiler/rootauto,jrtomps/root,0x0all/ROOT,CristinaCristescu/root,mhuwiler/rootauto,jrtomps/root,Y--/root,omazapa/root,mhuwiler/rootauto,olifre/root,arch1tect0r/root,buuck/root,nilqed/root,zzxuanyuan/root,georgtroska/root,omazapa/root-old,veprbl/root,omazapa/root-old,pspe/root,beniz/root,zzxuanyuan/root-compressor-dummy,gganis/root,davidlt/root,0x0all/ROOT,vukasinmilosevic/root,gganis/root,nilqed/root,simonpf/root,esakellari/my_root_for_test,sirinath/root,esakellari/root,agarciamontoro/root,arch1tect0r/root,davidlt/root,mattkretz/root,perovic/root,olifre/root,BerserkerTroll/root,omazapa/root,simonpf/root,vukasinmilosevic/root,simonpf/root,arch1tect0r/root,lgiommi/root,Y--/root,jrtomps/root,sirinath/root,krafczyk/root,lgiommi/root,mhuwiler/rootauto,veprbl/root,karies/root,buuck/root,beniz/root,BerserkerTroll/root,omazapa/root,thomaskeck/root,krafczyk/root,gganis/root,sirinath/root,satyarth934/root,dfunke/root,nilqed/root,bbockelm/root,veprbl/root,perovic/root,satyarth934/root,CristinaCristescu/root,BerserkerTroll/root,olifre/root,simonpf/root,mkret2/root,krafczyk/root,dfunke/root,sbinet/cxx-root,thomaskeck/root,zzxuanyuan/root,mattkretz/root,gbitzes/root,evgeny-boger/root,dfunke/root,Y--/root,esakellari/root,esakellari/root,beniz/root,omazapa/root-old,olifre/root,gganis/root,mkret2/root,vukasinmilosevic/root,BerserkerTroll/root,omazapa/root-old,CristinaCristescu/root,vukasinmilosevic/root,pspe/root,buuck/root,dfunke/root,perovic/root,mkret2/root,evgeny-boger/root,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,sbinet/cxx-root,bbockelm/root,agarciamontoro/root,abhinavmoudgil95/root,Y--/root,vukasinmilosevic/root,CristinaCristescu/root,perovic/root,0x0all/ROOT,gbitzes/root,zzxuanyuan/root,Duraznos/root,zzxuanyuan/root-compressor-dummy,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,beniz/root,davidlt/root,satyarth934/root,arch1tect0r/root,nilqed/root,omazapa/root-old,georgtroska/root,mattkretz/root,veprbl/root,dfunke/root,bbockelm/root,omazapa/root,Duraznos/root,satyarth934/root,agarciamontoro/root,davidlt/root,vukasinmilosevic/root,jrtomps/root,buuck/root,karies/root,beniz/root,mkret2/root,sirinath/root,pspe/root,gbitzes/root,evgeny-boger/root,karies/root,buuck/root,satyarth934/root,zzxuanyuan/root,0x0all/ROOT,bbockelm/root,BerserkerTroll/root,beniz/root,Y--/root,evgeny-boger/root,mattkretz/root,BerserkerTroll/root,omazapa/root-old,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,dfunke/root,pspe/root,CristinaCristescu/root,veprbl/root,agarciamontoro/root,georgtroska/root,gganis/root,mattkretz/root,davidlt/root,zzxuanyuan/root-compressor-dummy,nilqed/root,zzxuanyuan/root-compressor-dummy,dfunke/root,olifre/root,sbinet/cxx-root,nilqed/root,Duraznos/root,mkret2/root,sirinath/root,georgtroska/root,CristinaCristescu/root,evgeny-boger/root,0x0all/ROOT,omazapa/root-old,BerserkerTroll/root,root-mirror/root,evgeny-boger/root,abhinavmoudgil95/root,Y--/root,gbitzes/root,zzxuanyuan/root,mhuwiler/rootauto,0x0all/ROOT,Duraznos/root,Y--/root,dfunke/root,bbockelm/root,gbitzes/root,beniz/root,gbitzes/root,veprbl/root,beniz/root,omazapa/root-old,buuck/root,bbockelm/root,simonpf/root,georgtroska/root,karies/root,agarciamontoro/root,karies/root,perovic/root,veprbl/root,esakellari/my_root_for_test,mhuwiler/rootauto,mkret2/root,gbitzes/root,bbockelm/root,perovic/root,simonpf/root,satyarth934/root,veprbl/root,Duraznos/root,beniz/root,vukasinmilosevic/root,pspe/root,abhinavmoudgil95/root,georgtroska/root,olifre/root,Duraznos/root,satyarth934/root,esakellari/root,zzxuanyuan/root,evgeny-boger/root,lgiommi/root,esakellari/root,esakellari/my_root_for_test,karies/root,agarciamontoro/root,buuck/root,gganis/root,omazapa/root,esakellari/root,mattkretz/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,georgtroska/root,omazapa/root-old,omazapa/root,pspe/root,perovic/root,root-mirror/root,root-mirror/root,jrtomps/root,Duraznos/root,jrtomps/root,Duraznos/root,Y--/root,bbockelm/root,buuck/root,olifre/root,sawenzel/root,karies/root,pspe/root,nilqed/root,karies/root,lgiommi/root,mkret2/root,mkret2/root,esakellari/root,CristinaCristescu/root,nilqed/root,gganis/root,sawenzel/root,lgiommi/root,karies/root,sawenzel/root,olifre/root,esakellari/my_root_for_test,omazapa/root,sirinath/root,evgeny-boger/root,krafczyk/root,beniz/root,lgiommi/root,mhuwiler/rootauto,simonpf/root,thomaskeck/root,esakellari/root,zzxuanyuan/root,0x0all/ROOT,zzxuanyuan/root,sawenzel/root,gbitzes/root,zzxuanyuan/root,karies/root,esakellari/my_root_for_test,sawenzel/root,Duraznos/root,lgiommi/root,beniz/root,thomaskeck/root,arch1tect0r/root,abhinavmoudgil95/root,nilqed/root,arch1tect0r/root,sirinath/root,perovic/root,agarciamontoro/root,veprbl/root,root-mirror/root,root-mirror/root,thomaskeck/root,pspe/root,Y--/root,jrtomps/root,sbinet/cxx-root,bbockelm/root,satyarth934/root,esakellari/my_root_for_test,mhuwiler/rootauto,arch1tect0r/root,mkret2/root,georgtroska/root,zzxuanyuan/root-compressor-dummy,karies/root,gbitzes/root,buuck/root,agarciamontoro/root,esakellari/root,root-mirror/root,mhuwiler/rootauto,BerserkerTroll/root,abhinavmoudgil95/root,sirinath/root,krafczyk/root,mattkretz/root,zzxuanyuan/root-compressor-dummy,evgeny-boger/root,mhuwiler/rootauto,perovic/root,sirinath/root,0x0all/ROOT,arch1tect0r/root,Y--/root
0faba3d8f11ee466b9a3c1ec8466e5827fffe308
cpp/MaximumGap.cc
cpp/MaximumGap.cc
// https://oj.leetcode.com/problems/maximum-gap/ class Solution { public: int maximumGap(vector<int> &num) { if (num.size() < 2) return 0; set<int> S; for (int i = 0; i < num.size(); i++) { S.insert(num[i]); } set<int>::iterator it = S.begin(); int prev = *it; it++; int maxGap = 0; for (; it != S.end(); it++) { int cur = *it; maxGap = max(maxGap, cur - prev); prev = cur; } return maxGap; } };
// https://oj.leetcode.com/problems/maximum-gap/ class Solution { public: int maximumGap(vector<int> &num) { if (num.size() < 2) return 0; set<int> S; for (int i = 0; i < num.size(); i++) { S.insert(num[i]); } set<int>::iterator it = S.begin(); int prev = *it; it++; int maxGap = 0; for (; it != S.end(); it++) { int cur = *it; maxGap = max(maxGap, cur - prev); prev = cur; } return maxGap; } }; // official bucket based solution class Solution { public: int maximumGap(vector<int> &num) { if (num.size() < 2) return 0; int minValue = INT_MAX; int maxValue = 0; for (int i = 0; i < num.size(); i++) { minValue = min(minValue, num[i]); maxValue = max(maxValue, num[i]); } // note, the "double" & "ceil" is very important!!! int bucketRange = ceil(((double)(maxValue - minValue) / (num.size() - 1))); int bucketNum = (maxValue - minValue) / bucketRange + 1; vector<int> lowers(bucketNum, -1); // -1 means it's empty vector<int> uppers(bucketNum, -1); for (int i = 0; i < num.size(); i++) { int bucketPos = (num[i] - minValue) / bucketRange; if (lowers[bucketPos] == -1) { lowers[bucketPos] = num[i]; uppers[bucketPos] = num[i]; } else { lowers[bucketPos] = min(lowers[bucketPos], num[i]); uppers[bucketPos] = max(uppers[bucketPos], num[i]); } } // iterate the buckets to get the max gap assert(uppers[0] != -1 && lowers[bucketNum - 1] != -1); int maxGap = 0; int prevUpper = uppers[0]; for (int i = 1; i < bucketNum; i++) { if (lowers[i] == -1) continue; maxGap = max(maxGap, lowers[i] - prevUpper); prevUpper = uppers[i]; } return maxGap; } };
Update MaximumGap.cc
Update MaximumGap.cc
C++
bsd-3-clause
speedfirst/leetcode,speedfirst/leetcode
37ba42a6a28868857e31926b723904f0e88a2b15
cpp/problem_5.hpp
cpp/problem_5.hpp
/* * 2520 is the smallest number that can be divided by each * of the numbers from 1 to 10 without any remainder. * * What is the smallest positive number that is evenly * divisible by all of the numbers from 1 to 20? * * Answer: 232792560 */ #include<numeric> #include<vector> namespace problem_5 { template<class T> T gcd(T a, T b) { while(b != 0) { T temp = a % b; a = b; b = temp; } return a; } template<class T> T lcm(const T &a, const T &b) { return (a * b) / gcd<T>(a, b); } // TODO: abstract from vector template<class T> T lcmm(const std::vector<T> &a) { return std::accumulate(++a.begin(), a.end(), a.front(), lcm<T>); } template<class T> std::vector<T> range(const T &lo, const T &hi) { std::vector<T> v(hi - lo + 1); std::iota(v.begin(), v.end(), lo); return v; } template<class T> T problem_4(const T &lo, const T &hi) { return lcmm(range<T>(lo, hi)); } }
/* * 2520 is the smallest number that can be divided by each * of the numbers from 1 to 10 without any remainder. * * What is the smallest positive number that is evenly * divisible by all of the numbers from 1 to 20? * * Answer: 232792560 */ #include<numeric> #include<vector> namespace problem_5 { template<class T> T gcd(T a, T b) { while(b != 0) { T temp = a % b; a = b; b = temp; } return a; } template<class T> T lcm(const T &a, const T &b) { return (a * b) / gcd<T>(a, b); } // TODO: abstract from vector template<class T> T lcmm(const std::vector<T> &a) { return std::accumulate(++a.begin(), a.end(), a.front(), lcm<T>); } template<class T> std::vector<T> range(const T &lo, const T &hi) { std::vector<T> v(hi - lo + 1); std::iota(v.begin(), v.end(), lo); return v; } template<class T> T problem_5(const T &lo, const T &hi) { return lcmm(range<T>(lo, hi)); } }
Update problem_5.hpp
Update problem_5.hpp
C++
mit
ptwales/Project-Euler,ptwales/Project-Euler
a854409dba72a4edc4719afb121a904f310e4b11
libraries/plugins/elasticsearch/elasticsearch_plugin.cpp
libraries/plugins/elasticsearch/elasticsearch_plugin.cpp
/* * Copyright (c) 2017 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/elasticsearch/elasticsearch_plugin.hpp> #include <graphene/app/impacted.hpp> #include <graphene/chain/account_evaluator.hpp> #include <graphene/chain/account_object.hpp> #include <graphene/chain/config.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/evaluator.hpp> #include <graphene/chain/operation_history_object.hpp> #include <graphene/chain/transaction_evaluation_state.hpp> #include <fc/smart_ref_impl.hpp> #include <fc/thread/thread.hpp> #include <curl/curl.h> #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/find.hpp> #include <regex> namespace graphene { namespace elasticsearch { CURL *curl; // global curl handler vector <string> bulk; // global vector of op lines namespace detail { class elasticsearch_plugin_impl { public: elasticsearch_plugin_impl(elasticsearch_plugin& _plugin) : _self( _plugin ) { } virtual ~elasticsearch_plugin_impl(); void update_account_histories( const signed_block& b ); graphene::chain::database& database() { return _self.database(); } elasticsearch_plugin& _self; primary_index< simple_index< operation_history_object > >* _oho_index; std::string _elasticsearch_node_url = "http://localhost:9200/"; uint32_t _elasticsearch_bulk_replay = 10000; uint32_t _elasticsearch_bulk_sync = 100; bool _elasticsearch_logs = true; bool _elasticsearch_visitor = false; private: void add_elasticsearch( const account_id_type account_id, const optional<operation_history_object>& oho, const signed_block& b ); void createBulkLine(account_transaction_history_object ath, operation_history_struct os, int op_type, block_struct bs, visitor_struct vs); void sendBulk(std::string _elasticsearch_node_url, bool _elasticsearch_logs); }; elasticsearch_plugin_impl::~elasticsearch_plugin_impl() { return; } void elasticsearch_plugin_impl::update_account_histories( const signed_block& b ) { graphene::chain::database& db = database(); const vector<optional< operation_history_object > >& hist = db.get_applied_operations(); for( const optional< operation_history_object >& o_op : hist ) { optional <operation_history_object> oho; auto create_oho = [&]() { return optional<operation_history_object>( db.create<operation_history_object>([&](operation_history_object &h) { if (o_op.valid()) h = *o_op; })); }; if( !o_op.valid() ) { _oho_index->use_next_id(); continue; } oho = create_oho(); const operation_history_object& op = *o_op; // get the set of accounts this operation applies to flat_set<account_id_type> impacted; vector<authority> other; operation_get_required_authorities( op.op, impacted, impacted, other ); // fee_payer is added here if( op.op.which() == operation::tag< account_create_operation >::value ) impacted.insert( op.result.get<object_id_type>() ); else graphene::app::operation_get_impacted_accounts( op.op, impacted ); for( auto& a : other ) for( auto& item : a.account_auths ) impacted.insert( item.first ); for( auto& account_id : impacted ) { add_elasticsearch( account_id, oho, b ); } } } void elasticsearch_plugin_impl::add_elasticsearch( const account_id_type account_id, const optional <operation_history_object>& oho, const signed_block& b) { graphene::chain::database& db = database(); const auto &stats_obj = account_id(db).statistics(db); // add new entry const auto &ath = db.create<account_transaction_history_object>([&](account_transaction_history_object &obj) { obj.operation_id = oho->id; obj.account = account_id; obj.sequence = stats_obj.total_ops + 1; obj.next = stats_obj.most_recent_op; }); // keep stats growing as no op will be removed db.modify(stats_obj, [&](account_statistics_object &obj) { obj.most_recent_op = ath.id; obj.total_ops = ath.sequence; }); // operation_type int op_type = -1; if (!oho->id.is_null()) op_type = oho->op.which(); // operation history data operation_history_struct os; os.trx_in_block = oho->trx_in_block; os.op_in_trx = oho->op_in_trx; os.operation_result = fc::json::to_string(oho->result); os.virtual_op = oho->virtual_op; os.op = fc::json::to_string(oho->op); // visitor data visitor_struct vs; if(_elasticsearch_visitor) { operation_visitor o_v; oho->op.visit(o_v); vs.fee_data.asset = o_v.fee_asset; vs.fee_data.amount = o_v.fee_amount; vs.transfer_data.asset = o_v.transfer_asset_id; vs.transfer_data.amount = o_v.transfer_amount; vs.transfer_data.from = o_v.transfer_from; vs.transfer_data.to = o_v.transfer_to; } // block data std::string trx_id = ""; if(!b.transactions.empty() && oho->trx_in_block < b.transactions.size()) { trx_id = b.transactions[oho->trx_in_block].id().str(); } block_struct bs; bs.block_num = b.block_num(); bs.block_time = b.timestamp; bs.trx_id = trx_id; // check if we are in replay or in sync and change number of bulk documents accordingly uint32_t limit_documents = 0; if((fc::time_point::now() - b.timestamp) < fc::seconds(30)) limit_documents = _elasticsearch_bulk_sync; else limit_documents = _elasticsearch_bulk_replay; if(bulk.size() < limit_documents) { // we have everything, creating bulk array createBulkLine(ath, os, op_type, bs, vs); } if (curl && bulk.size() >= limit_documents) { // we are in bulk time, ready to add data to elasticsearech sendBulk(_elasticsearch_node_url, _elasticsearch_logs); } else { // wdump(("no curl!")); } // remove everything expect this from ath const auto &his_idx = db.get_index_type<account_transaction_history_index>(); const auto &by_seq_idx = his_idx.indices().get<by_seq>(); auto itr = by_seq_idx.lower_bound(boost::make_tuple(account_id, 0)); if (itr != by_seq_idx.end() && itr->account == account_id && itr->id != ath.id) { // if found, remove the entry, and adjust account stats object const auto remove_op_id = itr->operation_id; const auto itr_remove = itr; ++itr; db.remove( *itr_remove ); // modify previous node's next pointer // this should be always true, but just have a check here if( itr != by_seq_idx.end() && itr->account == account_id ) { db.modify( *itr, [&]( account_transaction_history_object& obj ){ obj.next = account_transaction_history_id_type(); }); } // do the same on oho const auto &by_opid_idx = his_idx.indices().get<by_opid>(); if (by_opid_idx.find(remove_op_id) == by_opid_idx.end()) { db.remove(remove_op_id(db)); } } } void elasticsearch_plugin_impl::createBulkLine(account_transaction_history_object ath, operation_history_struct os, int op_type, block_struct bs, visitor_struct vs) { bulk_struct bulks; bulks.account_history = ath; bulks.operation_history = os; bulks.operation_type = op_type; bulks.block_data = bs; bulks.additional_data = vs; std::string alltogether = fc::json::to_string(bulks); // bulk header before each line, op_type = create to avoid dups, index id will be ath id(2.9.X). std::string _id = fc::json::to_string(ath.id); bulk.push_back("{ \"index\" : { \"_index\" : \"graphene\", \"_type\" : \"data\", \"op_type\" : \"create\", \"_id\" : "+_id+" } }"); // header bulk.push_back(alltogether); } void elasticsearch_plugin_impl::sendBulk(std::string _elasticsearch_node_url, bool _elasticsearch_logs) { // curl buffers to read std::string readBuffer; std::string readBuffer_logs; std::string bulking = ""; bulking = boost::algorithm::join(bulk, "\n"); bulking = bulking + "\n"; bulk.clear(); //wlog((bulking)); struct curl_slist *headers = NULL; curl_slist_append(headers, "Content-Type: application/json"); std::string url = _elasticsearch_node_url + "_bulk"; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_POST, true); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, bulking.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&readBuffer); curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1"); //curl_easy_setopt(curl, CURLOPT_VERBOSE, true); curl_easy_perform(curl); long http_code = 0; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code); if(http_code == 200) { // all good, do nothing } else if(http_code == 429) { // repeat request? } else { // exit everything ? } if(_elasticsearch_logs) { auto logs = readBuffer; // do logs std::string url_logs = _elasticsearch_node_url + "logs/data/"; curl_easy_setopt(curl, CURLOPT_URL, url_logs.c_str()); curl_easy_setopt(curl, CURLOPT_POST, true); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, logs.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &readBuffer_logs); curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1"); //curl_easy_setopt(curl, CURLOPT_VERBOSE, true); //ilog("log here curl: ${output}", ("output", readBuffer_logs)); curl_easy_perform(curl); http_code = 0; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code); if(http_code == 200) { // all good, do nothing } else if(http_code == 429) { // repeat request? } else { // exit everything ? } } } } // end namespace detail elasticsearch_plugin::elasticsearch_plugin() : my( new detail::elasticsearch_plugin_impl(*this) ) { curl = curl_easy_init(); } elasticsearch_plugin::~elasticsearch_plugin() { } std::string elasticsearch_plugin::plugin_name()const { return "elasticsearch"; } void elasticsearch_plugin::plugin_set_program_options( boost::program_options::options_description& cli, boost::program_options::options_description& cfg ) { cli.add_options() ("elasticsearch-node-url", boost::program_options::value<std::string>(), "Elastic Search database node url") ("elasticsearch-bulk-replay", boost::program_options::value<uint32_t>(), "Number of bulk documents to index on replay(5000)") ("elasticsearch-bulk-sync", boost::program_options::value<uint32_t>(), "Number of bulk documents to index on a syncronied chain(10)") ("elasticsearch-logs", boost::program_options::value<bool>(), "Log bulk events to database") ("elasticsearch-visitor", boost::program_options::value<bool>(), "Use visitor to index additional data(slows down the replay)") ; cfg.add(cli); } void elasticsearch_plugin::plugin_initialize(const boost::program_options::variables_map& options) { database().applied_block.connect( [&]( const signed_block& b){ my->update_account_histories(b); } ); my->_oho_index = database().add_index< primary_index< simple_index< operation_history_object > > >(); database().add_index< primary_index< account_transaction_history_index > >(); if (options.count("elasticsearch-node-url")) { my->_elasticsearch_node_url = options["elasticsearch-node-url"].as<std::string>(); } if (options.count("elasticsearch-bulk-replay")) { my->_elasticsearch_bulk_replay = options["elasticsearch-bulk-replay"].as<uint32_t>(); } if (options.count("elasticsearch-bulk-sync")) { my->_elasticsearch_bulk_sync = options["elasticsearch-bulk-sync"].as<uint32_t>(); } if (options.count("elasticsearch-logs")) { my->_elasticsearch_logs = options["elasticsearch-logs"].as<bool>(); } if (options.count("elasticsearch-visitor")) { my->_elasticsearch_visitor = options["elasticsearch-visitor"].as<bool>(); } } void elasticsearch_plugin::plugin_startup() { } } }
/* * Copyright (c) 2017 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/elasticsearch/elasticsearch_plugin.hpp> #include <graphene/app/impacted.hpp> #include <graphene/chain/account_evaluator.hpp> #include <graphene/chain/account_object.hpp> #include <graphene/chain/config.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/evaluator.hpp> #include <graphene/chain/operation_history_object.hpp> #include <graphene/chain/transaction_evaluation_state.hpp> #include <fc/smart_ref_impl.hpp> #include <fc/thread/thread.hpp> #include <curl/curl.h> #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/find.hpp> #include <regex> namespace graphene { namespace elasticsearch { CURL *curl; // global curl handler vector <string> bulk; // global vector of op lines namespace detail { class elasticsearch_plugin_impl { public: elasticsearch_plugin_impl(elasticsearch_plugin& _plugin) : _self( _plugin ) { } virtual ~elasticsearch_plugin_impl(); void update_account_histories( const signed_block& b ); graphene::chain::database& database() { return _self.database(); } elasticsearch_plugin& _self; primary_index< simple_index< operation_history_object > >* _oho_index; std::string _elasticsearch_node_url = "http://localhost:9200/"; uint32_t _elasticsearch_bulk_replay = 10000; uint32_t _elasticsearch_bulk_sync = 100; bool _elasticsearch_logs = true; bool _elasticsearch_visitor = false; private: void add_elasticsearch( const account_id_type account_id, const optional<operation_history_object>& oho, const signed_block& b ); void createBulkLine(account_transaction_history_object ath, operation_history_struct os, int op_type, block_struct bs, visitor_struct vs); void sendBulk(std::string _elasticsearch_node_url, bool _elasticsearch_logs); }; elasticsearch_plugin_impl::~elasticsearch_plugin_impl() { return; } void elasticsearch_plugin_impl::update_account_histories( const signed_block& b ) { graphene::chain::database& db = database(); const vector<optional< operation_history_object > >& hist = db.get_applied_operations(); for( const optional< operation_history_object >& o_op : hist ) { optional <operation_history_object> oho; auto create_oho = [&]() { return optional<operation_history_object>( db.create<operation_history_object>([&](operation_history_object &h) { if (o_op.valid()) h = *o_op; })); }; if( !o_op.valid() ) { _oho_index->use_next_id(); continue; } oho = create_oho(); const operation_history_object& op = *o_op; // get the set of accounts this operation applies to flat_set<account_id_type> impacted; vector<authority> other; operation_get_required_authorities( op.op, impacted, impacted, other ); // fee_payer is added here if( op.op.which() == operation::tag< account_create_operation >::value ) impacted.insert( op.result.get<object_id_type>() ); else graphene::app::operation_get_impacted_accounts( op.op, impacted ); for( auto& a : other ) for( auto& item : a.account_auths ) impacted.insert( item.first ); for( auto& account_id : impacted ) { add_elasticsearch( account_id, oho, b ); } } } void elasticsearch_plugin_impl::add_elasticsearch( const account_id_type account_id, const optional <operation_history_object>& oho, const signed_block& b) { graphene::chain::database& db = database(); const auto &stats_obj = account_id(db).statistics(db); // add new entry const auto &ath = db.create<account_transaction_history_object>([&](account_transaction_history_object &obj) { obj.operation_id = oho->id; obj.account = account_id; obj.sequence = stats_obj.total_ops + 1; obj.next = stats_obj.most_recent_op; }); // keep stats growing as no op will be removed db.modify(stats_obj, [&](account_statistics_object &obj) { obj.most_recent_op = ath.id; obj.total_ops = ath.sequence; }); // operation_type int op_type = -1; if (!oho->id.is_null()) op_type = oho->op.which(); // operation history data operation_history_struct os; os.trx_in_block = oho->trx_in_block; os.op_in_trx = oho->op_in_trx; os.operation_result = fc::json::to_string(oho->result); os.virtual_op = oho->virtual_op; os.op = fc::json::to_string(oho->op); // visitor data visitor_struct vs; if(_elasticsearch_visitor) { operation_visitor o_v; oho->op.visit(o_v); vs.fee_data.asset = o_v.fee_asset; vs.fee_data.amount = o_v.fee_amount; vs.transfer_data.asset = o_v.transfer_asset_id; vs.transfer_data.amount = o_v.transfer_amount; vs.transfer_data.from = o_v.transfer_from; vs.transfer_data.to = o_v.transfer_to; } // block data std::string trx_id = ""; if(!b.transactions.empty() && oho->trx_in_block < b.transactions.size()) { trx_id = b.transactions[oho->trx_in_block].id().str(); } block_struct bs; bs.block_num = b.block_num(); bs.block_time = b.timestamp; bs.trx_id = trx_id; // check if we are in replay or in sync and change number of bulk documents accordingly uint32_t limit_documents = 0; if((fc::time_point::now() - b.timestamp) < fc::seconds(30)) limit_documents = _elasticsearch_bulk_sync; else limit_documents = _elasticsearch_bulk_replay; createBulkLine(ath, os, op_type, bs, vs); // we have everything, creating bulk line if (curl && bulk.size() >= limit_documents) { // we are in bulk time, ready to add data to elasticsearech sendBulk(_elasticsearch_node_url, _elasticsearch_logs); } // remove everything except current object from ath const auto &his_idx = db.get_index_type<account_transaction_history_index>(); const auto &by_seq_idx = his_idx.indices().get<by_seq>(); auto itr = by_seq_idx.lower_bound(boost::make_tuple(account_id, 0)); if (itr != by_seq_idx.end() && itr->account == account_id && itr->id != ath.id) { // if found, remove the entry const auto remove_op_id = itr->operation_id; const auto itr_remove = itr; ++itr; db.remove( *itr_remove ); // modify previous node's next pointer // this should be always true, but just have a check here if( itr != by_seq_idx.end() && itr->account == account_id ) { db.modify( *itr, [&]( account_transaction_history_object& obj ){ obj.next = account_transaction_history_id_type(); }); } // do the same on oho const auto &by_opid_idx = his_idx.indices().get<by_opid>(); if (by_opid_idx.find(remove_op_id) == by_opid_idx.end()) { db.remove(remove_op_id(db)); } } } void elasticsearch_plugin_impl::createBulkLine(account_transaction_history_object ath, operation_history_struct os, int op_type, block_struct bs, visitor_struct vs) { bulk_struct bulks; bulks.account_history = ath; bulks.operation_history = os; bulks.operation_type = op_type; bulks.block_data = bs; bulks.additional_data = vs; std::string alltogether = fc::json::to_string(bulks); // bulk header before each line, op_type = create to avoid dups, index id will be ath id(2.9.X). std::string _id = fc::json::to_string(ath.id); bulk.push_back("{ \"index\" : { \"_index\" : \"graphene\", \"_type\" : \"data\", \"op_type\" : \"create\", \"_id\" : "+_id+" } }"); // header bulk.push_back(alltogether); } void elasticsearch_plugin_impl::sendBulk(std::string _elasticsearch_node_url, bool _elasticsearch_logs) { // curl buffers to read std::string readBuffer; std::string readBuffer_logs; std::string bulking = ""; bulking = boost::algorithm::join(bulk, "\n"); bulking = bulking + "\n"; bulk.clear(); //wlog((bulking)); struct curl_slist *headers = NULL; curl_slist_append(headers, "Content-Type: application/json"); std::string url = _elasticsearch_node_url + "_bulk"; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_POST, true); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, bulking.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&readBuffer); curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1"); //curl_easy_setopt(curl, CURLOPT_VERBOSE, true); curl_easy_perform(curl); long http_code = 0; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code); if(http_code == 200) { // all good, do nothing } else if(http_code == 429) { // repeat request? } else { // exit everything ? } if(_elasticsearch_logs) { auto logs = readBuffer; // do logs std::string url_logs = _elasticsearch_node_url + "logs/data/"; curl_easy_setopt(curl, CURLOPT_URL, url_logs.c_str()); curl_easy_setopt(curl, CURLOPT_POST, true); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, logs.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &readBuffer_logs); curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1"); //curl_easy_setopt(curl, CURLOPT_VERBOSE, true); //ilog("log here curl: ${output}", ("output", readBuffer_logs)); curl_easy_perform(curl); http_code = 0; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code); if(http_code == 200) { // all good, do nothing } else if(http_code == 429) { // repeat request? } else { // exit everything ? } } } } // end namespace detail elasticsearch_plugin::elasticsearch_plugin() : my( new detail::elasticsearch_plugin_impl(*this) ) { curl = curl_easy_init(); } elasticsearch_plugin::~elasticsearch_plugin() { } std::string elasticsearch_plugin::plugin_name()const { return "elasticsearch"; } void elasticsearch_plugin::plugin_set_program_options( boost::program_options::options_description& cli, boost::program_options::options_description& cfg ) { cli.add_options() ("elasticsearch-node-url", boost::program_options::value<std::string>(), "Elastic Search database node url") ("elasticsearch-bulk-replay", boost::program_options::value<uint32_t>(), "Number of bulk documents to index on replay(5000)") ("elasticsearch-bulk-sync", boost::program_options::value<uint32_t>(), "Number of bulk documents to index on a syncronied chain(10)") ("elasticsearch-logs", boost::program_options::value<bool>(), "Log bulk events to database") ("elasticsearch-visitor", boost::program_options::value<bool>(), "Use visitor to index additional data(slows down the replay)") ; cfg.add(cli); } void elasticsearch_plugin::plugin_initialize(const boost::program_options::variables_map& options) { database().applied_block.connect( [&]( const signed_block& b){ my->update_account_histories(b); } ); my->_oho_index = database().add_index< primary_index< simple_index< operation_history_object > > >(); database().add_index< primary_index< account_transaction_history_index > >(); if (options.count("elasticsearch-node-url")) { my->_elasticsearch_node_url = options["elasticsearch-node-url"].as<std::string>(); } if (options.count("elasticsearch-bulk-replay")) { my->_elasticsearch_bulk_replay = options["elasticsearch-bulk-replay"].as<uint32_t>(); } if (options.count("elasticsearch-bulk-sync")) { my->_elasticsearch_bulk_sync = options["elasticsearch-bulk-sync"].as<uint32_t>(); } if (options.count("elasticsearch-logs")) { my->_elasticsearch_logs = options["elasticsearch-logs"].as<bool>(); } if (options.count("elasticsearch-visitor")) { my->_elasticsearch_visitor = options["elasticsearch-visitor"].as<bool>(); } } void elasticsearch_plugin::plugin_startup() { } } }
remove check that can cause loss of data
remove check that can cause loss of data
C++
mit
bitshares/bitshares-2,bitshares/bitshares-2,bitshares/bitshares-2,bitshares/bitshares-2