text
stringlengths 54
60.6k
|
|---|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "streams.h"
uint256 CBlockHeader::GetHash() const
{
return ComputePowHash(nNonce);//Hash(BEGIN(nVersion), END(nNonce));
}
uint256 CBlockHeader::ComputePowHash(uint32_t nNonce) const
{
if (nVersion == 1 || nVersion == 2){
/**
* Use SHA256+SHA256 to make PoW
*/
// Write the first 76 bytes of the block header to a double-SHA256 state.
CDoubleSHA256Pow hasher; // TODO: Create a new PowHasher named CPowHash256
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *this;
assert(ss.size() == 80);
hasher.Write((unsigned char*)&ss[0], 76);
uint256 powHash;
CDoubleSHA256Pow(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)&powHash);
return powHash;
}else if (nVersion == 3){
/**
* Scrypt PoW
*/
CScryptHash256Pow hasher;
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *this;
assert(ss.size() == 80);
hasher.Write((unsigned char*)&ss[0], 76);
uint256 powHash;
CScryptHash256Pow(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)&powHash);
return powHash;
}else if (nVersion == 4){
/**
* Scrypt+SHA256 PoW
*/
}else if (nVersion == 5){
/**
* SHA3-256(that is Keccak(1088,512,256)) PoW
*/
CKeccakHash256Pow hasher;
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *this;
assert(ss.size() == 80);
hasher.Write((unsigned char*)&ss[0], 76);
uint256 powHash;
CKeccakHash256Pow(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)&powHash);
return powHash;
}else{
// Abort, unknown block version.
assert(false);
return ~(uint256)0;
}
}
uint256 CBlock::BuildMerkleTree(bool* fMutated) const
{
/* WARNING! If you're reading this because you're learning about crypto
and/or designing a new system that will use merkle trees, keep in mind
that the following merkle tree algorithm has a serious flaw related to
duplicate txids, resulting in a vulnerability (CVE-2012-2459).
The reason is that if the number of hashes in the list at a given time
is odd, the last one is duplicated before computing the next level (which
is unusual in Merkle trees). This results in certain sequences of
transactions leading to the same merkle root. For example, these two
trees:
A A
/ \ / \
B C B C
/ \ | / \ / \
D E F D E F F
/ \ / \ / \ / \ / \ / \ / \
1 2 3 4 5 6 1 2 3 4 5 6 5 6
for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
6 are repeated) result in the same root hash A (because the hash of both
of (F) and (F,F) is C).
The vulnerability results from being able to send a block with such a
transaction list, with the same merkle root, and the same block hash as
the original without duplication, resulting in failed validation. If the
receiving node proceeds to mark that block as permanently invalid
however, it will fail to accept further unmodified (and thus potentially
valid) versions of the same block. We defend against this by detecting
the case where we would hash two identical hashes at the end of the list
together, and treating that identically to the block having an invalid
merkle root. Assuming no double-SHA256 collisions, this will detect all
known ways of changing the transactions without affecting the merkle
root.
*/
vMerkleTree.clear();
vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
vMerkleTree.push_back(it->GetHash());
int j = 0;
bool mutated = false;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
// Two identical hashes at the end of the list at a particular level.
mutated = true;
}
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
if (fMutated) {
*fMutated = mutated;
}
return (vMerkleTree.empty() ? uint256() : vMerkleTree.back());
}
std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return uint256();
for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin()); it != vMerkleBranch.end(); ++it)
{
if (nIndex & 1)
hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it));
nIndex >>= 1;
}
return hash;
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
s << " vMerkleTree: ";
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
s << " " << vMerkleTree[i].ToString();
s << "\n";
return s.str();
}
<commit_msg>fix uint256<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "streams.h"
uint256 CBlockHeader::GetHash() const
{
return ComputePowHash(nNonce);//Hash(BEGIN(nVersion), END(nNonce));
}
uint256 CBlockHeader::ComputePowHash(uint32_t nNonce) const
{
if (nVersion == 1 || nVersion == 2){
/**
* Use SHA256+SHA256 to make PoW
*/
// Write the first 76 bytes of the block header to a double-SHA256 state.
CDoubleSHA256Pow hasher; // TODO: Create a new PowHasher named CPowHash256
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *this;
assert(ss.size() == 80);
hasher.Write((unsigned char*)&ss[0], 76);
uint256 powHash;
CDoubleSHA256Pow(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)&powHash);
return powHash;
}else if (nVersion == 3){
/**
* Scrypt PoW
*/
CScryptHash256Pow hasher;
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *this;
assert(ss.size() == 80);
hasher.Write((unsigned char*)&ss[0], 76);
uint256 powHash;
CScryptHash256Pow(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)&powHash);
return powHash;
}else if (nVersion == 4){
/**
* Scrypt+SHA256 PoW
*/
}else if (nVersion == 5){
/**
* SHA3-256(that is Keccak(1088,512,256)) PoW
*/
CKeccakHash256Pow hasher;
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *this;
assert(ss.size() == 80);
hasher.Write((unsigned char*)&ss[0], 76);
uint256 powHash;
CKeccakHash256Pow(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)&powHash);
return powHash;
}else{
// Abort, unknown block version.
assert(false);
}
}
uint256 CBlock::BuildMerkleTree(bool* fMutated) const
{
/* WARNING! If you're reading this because you're learning about crypto
and/or designing a new system that will use merkle trees, keep in mind
that the following merkle tree algorithm has a serious flaw related to
duplicate txids, resulting in a vulnerability (CVE-2012-2459).
The reason is that if the number of hashes in the list at a given time
is odd, the last one is duplicated before computing the next level (which
is unusual in Merkle trees). This results in certain sequences of
transactions leading to the same merkle root. For example, these two
trees:
A A
/ \ / \
B C B C
/ \ | / \ / \
D E F D E F F
/ \ / \ / \ / \ / \ / \ / \
1 2 3 4 5 6 1 2 3 4 5 6 5 6
for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
6 are repeated) result in the same root hash A (because the hash of both
of (F) and (F,F) is C).
The vulnerability results from being able to send a block with such a
transaction list, with the same merkle root, and the same block hash as
the original without duplication, resulting in failed validation. If the
receiving node proceeds to mark that block as permanently invalid
however, it will fail to accept further unmodified (and thus potentially
valid) versions of the same block. We defend against this by detecting
the case where we would hash two identical hashes at the end of the list
together, and treating that identically to the block having an invalid
merkle root. Assuming no double-SHA256 collisions, this will detect all
known ways of changing the transactions without affecting the merkle
root.
*/
vMerkleTree.clear();
vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
vMerkleTree.push_back(it->GetHash());
int j = 0;
bool mutated = false;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
// Two identical hashes at the end of the list at a particular level.
mutated = true;
}
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
if (fMutated) {
*fMutated = mutated;
}
return (vMerkleTree.empty() ? uint256() : vMerkleTree.back());
}
std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return uint256();
for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin()); it != vMerkleBranch.end(); ++it)
{
if (nIndex & 1)
hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it));
nIndex >>= 1;
}
return hash;
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
s << " vMerkleTree: ";
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
s << " " << vMerkleTree[i].ToString();
s << "\n";
return s.str();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 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 <primitives/block.h>
#include <hash.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
#include <crypto/common.h>
#include <crypto/algos/hashlib/multihash.h>
#include <crypto/algos/neoscrypt/neoscrypt.h>
#include <crypto/algos/scrypt/scrypt.h>
#include <crypto/algos/yescrypt/yescrypt.h>
// equihash not included, because there is no GetHash function this way.
uint256 CBlockHeader::GetHash() const
{
return SerializeHash(*this);
}
int CBlockHeader::GetAlgo() const
{
switch (nVersion & BLOCK_VERSION_ALGO)
{
case 1:
return ALGO_SHA256D;
case BLOCK_VERSION_SHA256D:
return ALGO_SHA256D;
case BLOCK_VERSION_SCRYPT:
return ALGO_SCRYPT;
case BLOCK_VERSION_X11:
return ALGO_X11;
case BLOCK_VERSION_NEOSCRYPT:
return ALGO_NEOSCRYPT;
case BLOCK_VERSION_EQUIHASH:
return ALGO_EQUIHASH;
case BLOCK_VERSION_YESCRYPT:
return ALGO_YESCRYPT;
case BLOCK_VERSION_HMQ1725:
return ALGO_HMQ1725;
}
return ALGO_SHA256D;
}
uint256 CBlockHeader::GetPoWHash(int algo) const
{
switch (algo)
{
case ALGO_SHA256D:
return GetHash();
case ALGO_SCRYPT:
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_X11:
return HashX11(BEGIN(nVersion), END(nNonce));
case ALGO_NEOSCRYPT:
{
unsigned int profile = 0x0;
uint256 thash;
neoscrypt((unsigned char *) &nVersion, (unsigned char *) &thash, profile);
return thash;
}
case ALGO_EQUIHASH:
return GetHash(); // Equihash seems to have same POW hash, because Equihash will also be additional verified.
case ALGO_YESCRYPT:
{
uint256 thash;
yescrypt_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_HMQ1725:
return HMQ1725(BEGIN(nVersion), END(nNonce));
}
return GetHash();
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=0x%08x, powalgo=%d, powhash=%s, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
GetAlgo(),
GetPoWHash(GetAlgo()).ToString(),
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}
std::string GetAlgoName(int Algo)
{
switch (Algo)
{
case ALGO_SHA256D:
return std::string("sha256d");
case ALGO_SCRYPT:
return std::string("scrypt");
case ALGO_X11:
return std::string("x11");
case ALGO_NEOSCRYPT:
return std::string("neoscrypt");
case ALGO_YESCRYPT:
return std::string("yescrypt");
case ALGO_EQUIHASH:
return std::string("equihash");
case ALGO_HMQ1725:
return std::string("hmq1725");
}
return std::string("unknown");
}
<commit_msg>Compiler bugfix<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 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 <primitives/block.h>
#include <hash.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
#include <crypto/common.h>
#include <crypto/algos/hashlib/multihash.h>
#include <crypto/algos/neoscrypt/neoscrypt.h>
#include <crypto/algos/scrypt/scrypt.h>
#include <crypto/algos/yescrypt/yescrypt.h>
// equihash not included, because there is no GetHash function this way.
uint256 CBlockHeader::GetHash() const
{
return SerializeHash(*this);
}
int CBlockHeader::GetAlgo() const
{
switch (nVersion & BLOCK_VERSION_ALGO)
{
case 1:
return ALGO_SHA256D;
case BLOCK_VERSION_SHA256D:
return ALGO_SHA256D;
case BLOCK_VERSION_SCRYPT:
return ALGO_SCRYPT;
case BLOCK_VERSION_X11:
return ALGO_X11;
case BLOCK_VERSION_NEOSCRYPT:
return ALGO_NEOSCRYPT;
case BLOCK_VERSION_EQUIHASH:
return ALGO_EQUIHASH;
case BLOCK_VERSION_YESCRYPT:
return ALGO_YESCRYPT;
case BLOCK_VERSION_HMQ1725:
return ALGO_HMQ1725;
}
return ALGO_SHA256D;
}
uint256 CBlockHeader::GetPoWHash(int algo) const
{
switch (algo)
{
case ALGO_SHA256D:
return GetHash();
case ALGO_SCRYPT:
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_X11:
return HashX11(BEGIN(nVersion), END(nNonce));
case ALGO_NEOSCRYPT:
{
unsigned int profile = 0x0;
uint256 thash;
neoscrypt((unsigned char *) &nVersion, (unsigned char *) &thash, profile);
return thash;
}
case ALGO_EQUIHASH:
return GetHash(); // Equihash seems to have same POW hash, because Equihash will also be additional verified.
case ALGO_YESCRYPT:
{
uint256 thash;
yescrypt_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_HMQ1725:
return HMQ1725(BEGIN(nVersion), END(nNonce));
}
return GetHash();
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=0x%08x, powalgo=%d, powhash=%s, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%s, vtx=%u)\n",
GetHash().ToString(),
nVersion,
GetAlgo(),
GetPoWHash(GetAlgo()).ToString(),
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce.GetHex(),
vtx.size());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}
std::string GetAlgoName(int Algo)
{
switch (Algo)
{
case ALGO_SHA256D:
return std::string("sha256d");
case ALGO_SCRYPT:
return std::string("scrypt");
case ALGO_X11:
return std::string("x11");
case ALGO_NEOSCRYPT:
return std::string("neoscrypt");
case ALGO_YESCRYPT:
return std::string("yescrypt");
case ALGO_EQUIHASH:
return std::string("equihash");
case ALGO_HMQ1725:
return std::string("hmq1725");
}
return std::string("unknown");
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <windows.h>
#include <TlHelp32.h>
#include <TCHAR.h>
#include <string>
#include <sstream>
#include "/COSTUM/costumfunc.cpp"
//Here is where the hax begin
using namespace std;
int Main() {
//Here is where the magic starts
HWND hWnd = FindWindow(0, "ROBLOX"); //Finding RBLX window this is a low quality process if you know how to code and use this i recommened you to change this
std::cout << "Waiting for Roblox...";
while (hWnd == 0) { // Waiting until found
Sleep(250);
hWnd = FindWindow(0, "ROBLOX");
}
system("cls");
DWORD pId;
custom::GetWindowThreadProcessId(hWnd, &pId);
DWORD RBLXBASEAddr = GetModuleBaseAddress(pId, "RobloxPlayerBeta.exe");
std::cout << "Base Address: " << hex << GetModuleBaseAddress(;
return 0;
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <windows.h>
#include <TlHelp32.h>
#include <TCHAR.h>
#include <string>
#include <sstream>
#include "/COSTUM/costumfunc.cpp"
//Here is where the hax begin
using namespace std;
int Main() {
//Here is where the magic starts
HWND hWnd = FindWindow(0, "ROBLOX"); //Finding RBLX window this is a low quality process if you know how to code and use this i recommened you to change this
std::cout << "Waiting for Roblox...";
while (hWnd == 0) { // Waiting until found
Sleep(250);
hWnd = FindWindow(0, "ROBLOX");
}
system("cls");
DWORD pId;
custom::GetWindowThreadProcessId(hWnd, &pId);
DWORD RBLXBASEAddr = GetModuleBaseAddress(pId, "RobloxPlayerBeta.exe");
std::cout << "Base Address: " << hex << GetModuleBaseAddress(;
return 0;
}
//Good example of dllmain
BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch(ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)Main, NULL, NULL, NULL);
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
<|endoftext|>
|
<commit_before>#include "settings.h"
#include "deviceinfo.h"
#include "log/logger.h"
#include <QSettings>
#include <QCryptographicHash>
LOGGER(Settings);
class Settings::Private
{
public:
void sync();
GetConfigResponse config;
QSettings settings;
};
void Settings::Private::sync()
{
settings.setValue("config", config.toVariant());
settings.sync();
}
Settings::Settings(QObject *parent)
: QObject(parent)
, d(new Private)
{
}
Settings::~Settings()
{
d->sync();
delete d;
}
Settings::StorageType Settings::init()
{
bool newSettings = deviceId().isNull();
DeviceInfo info;
QString generatedDeviceId = info.deviceId();
if (generatedDeviceId.isEmpty())
{
if (deviceId().isEmpty())
{
QCryptographicHash hash(QCryptographicHash::Sha224);
hash.addData( QUuid::createUuid().toByteArray() );
setDeviceId(QString::fromLatin1(hash.result().toHex()));
LOG_INFO("Generated fallback device ID");
}
else
{
LOG_INFO("Took fallback device ID from config");
}
}
else
{
setDeviceId(info.deviceId());
}
LOG_INFO(QString("Device ID: %1").arg(deviceId()));
// Create new settings
if ( newSettings )
{
d->config.setControllerAddress("141.82.51.240:5105");
LOG_INFO("Created new settings for this device");
return NewSettings;
}
else
{
d->config.fillFromVariant( qvariant_cast<QVariantMap>(d->settings.value("config")) );
// Always set the controller address if we have none
if (d->config.controllerAddress().isEmpty())
{
LOG_WARNING("Controller address lost, setting back default one");
d->config.setControllerAddress("141.82.51.240:5105");
}
LOG_INFO("Loaded existing settings for this device");
return ExistingSettings;
}
}
bool Settings::hasLoginData() const
{
return !userId().isEmpty() && !password().isEmpty();
}
void Settings::setDeviceId(const QString &deviceId)
{
if ( this->deviceId() != deviceId )
{
d->settings.setValue("device-id", deviceId);
emit deviceIdChanged(deviceId);
}
}
QString Settings::deviceId() const
{
return d->settings.value("device-id").toString();
}
void Settings::setUserId(const QString &userId)
{
if ( this->userId() != userId )
{
d->settings.setValue("user-id", userId);
emit userIdChanged(userId);
}
}
QString Settings::userId() const
{
return d->settings.value("user-id").toString();
}
void Settings::setPassword(const QString &password)
{
if ( this->password() != password )
{
d->settings.setValue("password", password);
emit passwordChanged(password);
}
}
QString Settings::password() const
{
return d->settings.value("password").toString();
}
void Settings::setSessionId(const QString &sessionId)
{
if ( this->sessionId() != sessionId )
{
d->settings.setValue("session-id", sessionId);
emit sessionIdChanged(sessionId);
}
}
QString Settings::sessionId() const
{
return d->settings.value("session-id").toString();
}
bool Settings::isPassive() const
{
return d->settings.value("passive").toBool();
}
void Settings::setPassive(bool passive)
{
if ( this->isPassive() != passive )
{
d->settings.setValue("passive", passive);
emit passiveChanged(passive);
}
}
GetConfigResponse *Settings::config() const
{
return &d->config;
}
void Settings::sync()
{
d->sync();
}
<commit_msg>Changed controller address to new ip address.<commit_after>#include "settings.h"
#include "deviceinfo.h"
#include "log/logger.h"
#include <QSettings>
#include <QCryptographicHash>
LOGGER(Settings);
class Settings::Private
{
public:
void sync();
GetConfigResponse config;
QSettings settings;
};
void Settings::Private::sync()
{
settings.setValue("config", config.toVariant());
settings.sync();
}
Settings::Settings(QObject *parent)
: QObject(parent)
, d(new Private)
{
}
Settings::~Settings()
{
d->sync();
delete d;
}
Settings::StorageType Settings::init()
{
bool newSettings = deviceId().isNull();
DeviceInfo info;
QString generatedDeviceId = info.deviceId();
if (generatedDeviceId.isEmpty())
{
if (deviceId().isEmpty())
{
QCryptographicHash hash(QCryptographicHash::Sha224);
hash.addData( QUuid::createUuid().toByteArray() );
setDeviceId(QString::fromLatin1(hash.result().toHex()));
LOG_INFO("Generated fallback device ID");
}
else
{
LOG_INFO("Took fallback device ID from config");
}
}
else
{
setDeviceId(info.deviceId());
}
LOG_INFO(QString("Device ID: %1").arg(deviceId()));
// Create new settings
if ( newSettings )
{
d->config.setControllerAddress("141.82.57.240:5105");
LOG_INFO("Created new settings for this device");
return NewSettings;
}
else
{
d->config.fillFromVariant( qvariant_cast<QVariantMap>(d->settings.value("config")) );
// Always set the controller address if we have none
if (d->config.controllerAddress().isEmpty())
{
LOG_WARNING("Controller address lost, setting back default one");
d->config.setControllerAddress("141.82.57.240:5105");
}
LOG_INFO("Loaded existing settings for this device");
return ExistingSettings;
}
}
bool Settings::hasLoginData() const
{
return !userId().isEmpty() && !password().isEmpty();
}
void Settings::setDeviceId(const QString &deviceId)
{
if ( this->deviceId() != deviceId )
{
d->settings.setValue("device-id", deviceId);
emit deviceIdChanged(deviceId);
}
}
QString Settings::deviceId() const
{
return d->settings.value("device-id").toString();
}
void Settings::setUserId(const QString &userId)
{
if ( this->userId() != userId )
{
d->settings.setValue("user-id", userId);
emit userIdChanged(userId);
}
}
QString Settings::userId() const
{
return d->settings.value("user-id").toString();
}
void Settings::setPassword(const QString &password)
{
if ( this->password() != password )
{
d->settings.setValue("password", password);
emit passwordChanged(password);
}
}
QString Settings::password() const
{
return d->settings.value("password").toString();
}
void Settings::setSessionId(const QString &sessionId)
{
if ( this->sessionId() != sessionId )
{
d->settings.setValue("session-id", sessionId);
emit sessionIdChanged(sessionId);
}
}
QString Settings::sessionId() const
{
return d->settings.value("session-id").toString();
}
bool Settings::isPassive() const
{
return d->settings.value("passive").toBool();
}
void Settings::setPassive(bool passive)
{
if ( this->isPassive() != passive )
{
d->settings.setValue("passive", passive);
emit passiveChanged(passive);
}
}
GetConfigResponse *Settings::config() const
{
return &d->config;
}
void Settings::sync()
{
d->sync();
}
<|endoftext|>
|
<commit_before>#pragma once
#include <string>
#include <map>
#include <functional>
#include <vector>
namespace search
{
class Node
{
public:
using Size = std::size_t;
using Path = std::string;
using Chidlren = std::vector<Node>;
struct Coordinate
{
Coordinate(Size x, Size y)
: x{ x }, y{ y }
{}
Coordinate& operator = (Coordinate const& other)
{
x = other.x;
y = other.y;
return *this;
}
Size x, y;
};
using Functions = std::map< char, std::function< Coordinate(Coordinate) >>;
//
// ctor
//
Node(Path const& path)
: _path{ path }
{ }
auto path() const -> Path const&
{
return _path;
}
auto coordinate(Coordinate start) const -> Coordinate
{
Coordinate c = start;
for (auto direction : _path)
c = Node::goes.at(direction)(c);
return c;
}
template<typename ValidateFunc>
auto children(ValidateFunc validate) const -> Children
{
Chidlren result;
auto curr = coordinate();
for (auto go_from : goes)
{
auto child = go_from(curr);
if (validate(child))
result.push_back(child);
}
return children;
}
const static Functions goes;
private:
Path const _path;
};
Node::Functions const Node::goes
{
{ '1', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y - 1 }; } },
{ '2', [](Coordinate c) -> Coordinate{ return{ c.x - 0, c.y - 1 }; } },
{ '3', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y + 1 }; } },
{ '4', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y + 0 }; } },
{ '5', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y + 0 }; } },
{ '6', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y - 1 }; } },
{ '7', [](Coordinate c) -> Coordinate{ return{ c.x - 0, c.y - 1 }; } },
{ '8', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y - 1 }; } }
};
}<commit_msg>fix typo<commit_after>#pragma once
#include <string>
#include <map>
#include <functional>
#include <vector>
namespace search
{
class Node
{
public:
using Size = std::size_t;
using Path = std::string;
using Children = std::vector<Node>;
struct Coordinate
{
Coordinate(Size x, Size y)
: x{ x }, y{ y }
{}
Coordinate& operator = (Coordinate const& other)
{
x = other.x;
y = other.y;
return *this;
}
Size x, y;
};
using Functions = std::map< char, std::function< Coordinate(Coordinate) >>;
//
// ctor
//
Node(Path const& path)
: _path{ path }
{ }
auto path() const -> Path const&
{
return _path;
}
auto coordinate(Coordinate start) const -> Coordinate
{
Coordinate c = start;
for (auto direction : _path)
c = Node::goes.at(direction)(c);
return c;
}
template<typename ValidateFunc>
auto children(ValidateFunc validate) const -> Children
{
Chidlren result;
auto curr = coordinate();
for (auto go_from : goes)
{
auto child = go_from(curr);
if (validate(child))
result.push_back(child);
}
return result;
}
const static Functions goes;
private:
Path const _path;
};
Node::Functions const Node::goes
{
{ '1', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y - 1 }; } },
{ '2', [](Coordinate c) -> Coordinate{ return{ c.x - 0, c.y - 1 }; } },
{ '3', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y + 1 }; } },
{ '4', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y + 0 }; } },
{ '5', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y + 0 }; } },
{ '6', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y - 1 }; } },
{ '7', [](Coordinate c) -> Coordinate{ return{ c.x - 0, c.y - 1 }; } },
{ '8', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y - 1 }; } }
};
}<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 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 <primitives/block.h>
#include <crypto/common.h>
#include <hash.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
uint256 CBlockHeader::GetHash() const
{
switch (nVersion) {
case X11_VERSION:
return HashX11(BEGIN(nVersion), END(nNonce));
case X13_VERSION:
return HashX13(BEGIN(nVersion), END(nNonce));
case SHA256D_VERSION:
return Hash(BEGIN(nVersion), END(nNonce));
case BLAKE2S_VERSION:
return HashBlake2s(BEGIN(nVersion), END(nNonce));
default:
return HashX12(BEGIN(nVersion), END(nNonce));
}
}
unsigned int CBlockHeader::GetStakeEntropyBit() const
{
// Take last bit of block hash as entropy bit
unsigned int nEntropyBit = (GetHash().GetLow64() & 1llu);
return nEntropyBit;
}
unsigned int CBlock::GetStakeEntropyBit() const
{
// Take last bit of block hash as entropy bit
unsigned int nEntropyBit = (GetHash().GetLow64() & 1llu);
return nEntropyBit;
}
extern bool IsDeveloperBlock(const CBlock& block);
bool CBlock::IsDeveloperBlock() const
{
return ::IsDeveloperBlock(*this);
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, nFlags=%08x, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
nFlags, vtx.size());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}
<commit_msg>v4.0.0<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 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 <primitives/block.h>
#include <crypto/common.h>
#include <hash.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
uint256 CBlockHeader::GetHash() const
{
switch (nVersion) {
case X11_VERSION:
return HashX11(BEGIN(nVersion), END(nNonce));
case X13_VERSION:
return HashX13(BEGIN(nVersion), END(nNonce));
case SHA256D_VERSION:
return Hash(BEGIN(nVersion), END(nNonce));
case BLAKE2S_VERSION:
return HashBlake2s(BEGIN(nVersion), END(nNonce));
default:
return HashX12(BEGIN(nVersion), END(nNonce));
}
}
unsigned int CBlockHeader::GetStakeEntropyBit() const
{
// Take last bit of block hash as entropy bit
unsigned int nEntropyBit = (GetHash().GetLow64() & 1llu);
return nEntropyBit;
}
unsigned int CBlock::GetStakeEntropyBit() const
{
// Take last bit of block hash as entropy bit
unsigned int nEntropyBit = (GetHash().GetLow64() & 1llu);
return nEntropyBit;
}
#include <pubkey.h>
static bool CheckDeveloperSignature(const std::vector<unsigned char>& sig, const uint256& hash)
{
if (sig.empty())
return false;
return Params().DevPubKey().Verify(hash, sig);
}
static bool IsDeveloperBlock(const CBlock& block)
{
if (!block.IsProofOfWork())
return false;
if (block.nNonce != 0)
return false;
if (block.vchBlockSig.empty())
return false;
return CheckDeveloperSignature(block.vchBlockSig, block.GetHash());
}
bool CBlock::IsDeveloperBlock() const
{
return ::IsDeveloperBlock(*this);
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, nFlags=%08x, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
nFlags, vtx.size());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 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 <primitives/block.h>
#include <hash.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
#include <crypto/common.h>
uint256 CBlockHeader::GetHash() const
{
return HashX13(BEGIN(nVersion), END(nNonce));
}
uint256 CBlockHeader::GetPoWHash() const
{
return HashX13(BEGIN(nVersion), END(nNonce));
}
bool CBlockHeader::IsProofOfStake() const
{
// unfortunately with blockheader only it is difficult to determine if a block is pow or pos
// to determine if a block is pos we need to check its vin/vout
// thus the formal method will be in the block class
// here we just temporarily use a hack:
// pow blocks always has its hash starting with at least 5 "0"s.
// this is temporary, we should not check the headers, but should move all check functions
// to checkblock, like the old deeponion code does
std::string hashStr = GetHash().ToString();
if(hashStr.find("00000") == 0) {
return false;
}
return true;
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u, vchBlockSig=%s)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size(),
HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}
<commit_msg>Prevent PoW blocks being marked as PoS in Regstest<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 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 <primitives/block.h>
#include <chainparams.h>
#include <hash.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
#include <crypto/common.h>
uint256 CBlockHeader::GetHash() const
{
return HashX13(BEGIN(nVersion), END(nNonce));
}
uint256 CBlockHeader::GetPoWHash() const
{
return HashX13(BEGIN(nVersion), END(nNonce));
}
bool CBlockHeader::IsProofOfStake() const
{
// unfortunately with blockheader only it is difficult to determine if a block is pow or pos
// to determine if a block is pos we need to check its vin/vout
// thus the formal method will be in the block class
// here we just temporarily use a hack:
// pow blocks always has its hash starting with at least 5 "0"s.
// this is temporary, we should not check the headers, but should move all check functions
// to checkblock, like the old deeponion code does
std::string hashStr = GetHash().ToString();
if(hashStr.find("00000") == 0 || Params().NetworkIDString() == "regtest") {
return false;
}
return true;
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u, vchBlockSig=%s)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size(),
HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}
<|endoftext|>
|
<commit_before>// 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 "quorums.h"
#include "quorums_utils.h"
#include "chainparams.h"
#include "random.h"
#include "validation.h"
namespace llmq
{
std::vector<CDeterministicMNCPtr> CLLMQUtils::GetAllQuorumMembers(Consensus::LLMQType llmqType, const uint256& blockHash)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
auto allMns = deterministicMNManager->GetListForBlock(blockHash);
auto modifier = ::SerializeHash(std::make_pair((uint8_t)llmqType, blockHash));
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(Consensus::LLMQType llmqType, const uint256& quorumHash, const uint256& id, const uint256& msgHash)
{
CHashWriter h(SER_GETHASH, 0);
h << (uint8_t)llmqType;
h << quorumHash;
h << id;
h << msgHash;
return h.GetHash();
}
std::set<CService> CLLMQUtils::GetQuorumConnections(Consensus::LLMQType llmqType, const uint256& blockHash, const uint256& forMember)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
auto mns = GetAllQuorumMembers(llmqType, blockHash);
std::set<CService> result;
for (size_t i = 0; i < mns.size(); i++) {
auto& dmn = mns[i];
if (dmn->proTxHash == forMember) {
// Connect to nodes at indexes (i+2^k)%n, k: 0..floor(log2(n-1))-1, n: size of the quorum/ring
int gap = 1;
int gap_max = mns.size() - 1;
while (gap_max >>= 1) {
size_t idx = (i + gap) % mns.size();
auto& otherDmn = mns[idx];
if (otherDmn == dmn) {
continue;
}
result.emplace(otherDmn->pdmnState->addr);
gap <<= 1;
}
// there can be no two members with the same proTxHash, so return early
break;
}
}
return result;
}
std::set<size_t> CLLMQUtils::CalcDeterministicWatchConnections(Consensus::LLMQType llmqType, const uint256& blockHash, size_t memberCount, size_t connectionCount)
{
static uint256 qwatchConnectionSeed;
static std::atomic<bool> qwatchConnectionSeedGenerated{false};
static CCriticalSection 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((uint8_t)llmqType, blockHash)));
result.emplace(rnd.GetUint64(0) % memberCount);
}
return result;
}
bool CLLMQUtils::IsQuorumActive(Consensus::LLMQType 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->quorumHash == quorumHash) {
return true;
}
}
return false;
}
}
<commit_msg>Fix loop in CLLMQUtils::GetQuorumConnections to add at least 2 connections (#2796)<commit_after>// 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 "quorums.h"
#include "quorums_utils.h"
#include "chainparams.h"
#include "random.h"
#include "validation.h"
namespace llmq
{
std::vector<CDeterministicMNCPtr> CLLMQUtils::GetAllQuorumMembers(Consensus::LLMQType llmqType, const uint256& blockHash)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
auto allMns = deterministicMNManager->GetListForBlock(blockHash);
auto modifier = ::SerializeHash(std::make_pair((uint8_t)llmqType, blockHash));
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(Consensus::LLMQType llmqType, const uint256& quorumHash, const uint256& id, const uint256& msgHash)
{
CHashWriter h(SER_GETHASH, 0);
h << (uint8_t)llmqType;
h << quorumHash;
h << id;
h << msgHash;
return h.GetHash();
}
std::set<CService> CLLMQUtils::GetQuorumConnections(Consensus::LLMQType llmqType, const uint256& blockHash, const uint256& forMember)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
auto mns = GetAllQuorumMembers(llmqType, blockHash);
std::set<CService> result;
for (size_t i = 0; i < mns.size(); i++) {
auto& dmn = mns[i];
if (dmn->proTxHash == forMember) {
// Connect to nodes at indexes (i+2^k)%n, where
// k: 0..max(1, floor(log2(n-1))-1)
// n: size of the quorum/ring
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 == dmn) {
continue;
}
result.emplace(otherDmn->pdmnState->addr);
gap <<= 1;
k++;
}
// there can be no two members with the same proTxHash, so return early
break;
}
}
return result;
}
std::set<size_t> CLLMQUtils::CalcDeterministicWatchConnections(Consensus::LLMQType llmqType, const uint256& blockHash, size_t memberCount, size_t connectionCount)
{
static uint256 qwatchConnectionSeed;
static std::atomic<bool> qwatchConnectionSeedGenerated{false};
static CCriticalSection 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((uint8_t)llmqType, blockHash)));
result.emplace(rnd.GetUint64(0) % memberCount);
}
return result;
}
bool CLLMQUtils::IsQuorumActive(Consensus::LLMQType 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->quorumHash == quorumHash) {
return true;
}
}
return false;
}
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "Match.h"
#include "Simulation.h"
#include <random>
namespace sim
{
void MatchResultStatisticsList::addMatch(const MatchResult &match)
{
int teamIDOne = std::min(match.teams[0], match.teams[1]);
int teamIDTwo = std::max(match.teams[0], match.teams[1]);
std::pair<int, int> teamPair = std::make_pair(teamIDOne, teamIDTwo);
if (!results.count(teamPair))
{
results.emplace(teamPair, MatchResultStatistics(teamIDOne, teamIDTwo));
assert(match.bofRound > 0);
this->bofRound = match.bofRound;
this->gameInRound = match.gameInRound;
}
MatchResultStatistics &clusterResult = results[teamPair];
clusterResult.addMatch(match);
}
void MatchResultStatisticsList::merge(MatchResultStatisticsList &other)
{
for (auto &result : other.results)
{
const std::pair<int, int> &teamPair = result.first;
if (!results.count(teamPair))
results.emplace(teamPair, MatchResultStatistics(result.second));
else
results[teamPair].merge(result.second);
}
this->bofRound = other.bofRound;
this->gameInRound = other.gameInRound;
}
json_spirit::Array MatchResultStatisticsList::toJSONArray()
{
json_spirit::Array data;
// sort our results by count
std::list<MatchResultStatistics> sorted;
for (auto &result : results)
sorted.push_back(result.second);
sorted.sort();
sorted.reverse();
// ..and add to data
for (MatchResultStatistics &stats : sorted)
data.push_back(stats.toJSONObject());
return data;
}
json_spirit::Object MatchResultStatistics::toJSONObject()
{
json_spirit::Object object;
object.push_back(json_spirit::Pair("teams", json_spirit::Array({ teams[0], teams[1] })));
object.push_back(json_spirit::Pair("goals", json_spirit::Array({ goals[0], goals[1] })));
object.push_back(json_spirit::Pair("count", count));
return object;
}
void MatchResultStatistics::addMatch(const MatchResult &result)
{
int first = 0, second = 1;
// team IDs will always be sorted ascending
if (result.teams[0] > result.teams[1])
{
first = 1;
second = 0;
}
this->goals[0] += result.goals[first];
this->goals[1] += result.goals[second];
count += 1;
}
void MatchResultStatistics::merge(const MatchResultStatistics &other)
{
assert(this->teams[0] == other.teams[0] && this->teams[1] == other.teams[1]);
for (int i = 0; i < 2; ++i)
{
this->goals[i] += other.goals[i];
}
this->count += other.count;
}
Match::Match()
{
}
Match::~Match()
{
}
MatchResult Match::execute(std::string cluster, Simulation *simulation, Team &left, Team &right, bool forceWinner)
{
// use two chances for scoring - some rules are not necessarily symmetrical and should still work as good as possible
double chanceLeftVsRight(0.0), chanceRightVsLeft(0.0);
// the maximum weight of the normal rules. Used to scale backreferencing rules correctly
double maxRuleWeight = 0.0;
// apply all normal rules to figure out the correct odds
for (int i = 0; i < 2; ++i)
{
double weightedChanceSum = 0.0;
double weightTotalSum = 0.0;
for (auto &rule : simulation->rules)
{
// remember for backref rules later. Not only the weight of non-backref rules!
maxRuleWeight = std::max(maxRuleWeight, rule.weight);
if (rule.isBackrefRule) continue;
// rules can scale down their weight for one calculation if they cannot make good predictions anyway
double customWeight(1.0);
// apply!
double ruleChance = rule.getRawResults(i == 0 ? left : right, i == 0 ? right : left, &customWeight, nullptr);
weightedChanceSum += customWeight * rule.weight * ruleChance;
weightTotalSum += customWeight * rule.weight;
}
double chance = 0.0;
if (weightTotalSum > 0.0)
{
chance = weightedChanceSum / weightTotalSum;
}
if (i == 0)
chanceLeftVsRight = chance;
else
chanceRightVsLeft = chance;
}
// this can happen if a rule reduces its custom weight to 0
if (chanceLeftVsRight == 0.0 && chanceRightVsLeft == 0.0)
{
chanceLeftVsRight = chanceRightVsLeft = 0.5;
}
// now apply all backreference rules
assert(maxRuleWeight != 0.0);
for (int i = 0; i < 2; ++i)
{
double *currentWinExpectancy = (i == 0) ? &chanceLeftVsRight : &chanceRightVsLeft;
for (auto &rule : simulation->rules)
{
if (!rule.isBackrefRule) continue;
double customWeight(1.0);
double adjustedWinExpectancy = rule.getRawResults(i == 0 ? left : right, i == 0 ? right : left, &customWeight, currentWinExpectancy);
// now scale the rule correctly, according to the user input
double ruleFactor = std::min(1.0, rule.weight * customWeight / maxRuleWeight);
*currentWinExpectancy = ruleFactor * adjustedWinExpectancy + (1.0 - ruleFactor) * (*currentWinExpectancy);
}
}
assert(!(chanceLeftVsRight == 0.0 && chanceRightVsLeft == 0.0));
// currently some rules might be assymetric (because they include draws f.e.)
// to make sure that we do a fair roll later, normalize the chances..
// Note that in case chanceLeftVsRight + chanceRightvsLeft == 1.0, this does nothing
double normalizedChanceLeftVsRight = chanceLeftVsRight / (chanceLeftVsRight + chanceRightVsLeft);
// std::cerr << "norm: " << normalizedChanceLeftVsRight << "\tleft: " << chanceLeftVsRight << "\tright: " << chanceRightVsLeft << std::endl;
int teams[] = {left.id, right.id};
int goals[] = {0, 0};
int winnerIndex = -1;
std::random_device seeder;
auto leftSideGoalRoller = std::bind(std::poisson_distribution<>(1.8 * (normalizedChanceLeftVsRight) + 0.27), std::mt19937(simulation->randomSeed + seeder()));
auto rightSideGoalRoller = std::bind(std::poisson_distribution<>(1.8 * (1.0 - normalizedChanceLeftVsRight) + 0.27), std::mt19937(simulation->randomSeed + seeder()));
auto uniformRoller = std::bind(std::uniform_real_distribution<double>(0.0, 1.0), std::mt19937(simulation->randomSeed + seeder()));
bool hadOvertime = false;
// roll for draws first
// 0.33 * exp(-(x - 0.5) ^ 2 / (2 * 0.28 ^ 2))
double chanceForDraw = (1.0 / 3.0) * std::exp(-std::pow((normalizedChanceLeftVsRight - 0.5), 2.0) / (2.0 * std::pow(0.28, 2.0)));
bool isDraw = false;
if (uniformRoller() < chanceForDraw)
{
if (forceWinner)
hadOvertime = true;
else
isDraw = true;
}
if (!isDraw)
{
const double winnerSide = uniformRoller();
if (winnerSide < normalizedChanceLeftVsRight)
winnerIndex = 0;
else
winnerIndex = 1;
// roll goals until someone wins
do
{
goals[0] = leftSideGoalRoller();
goals[1] = rightSideGoalRoller();
} while (goals[winnerIndex] <= goals[1 - winnerIndex]);
}
else
{
// roll goals until draw
#ifndef NDEBUG
int safetyCounter = 10000;
#endif
do
{
goals[0] = leftSideGoalRoller();
goals[1] = rightSideGoalRoller();
#ifndef NDEBUG
if (--safetyCounter <= 0) break;
#endif
} while (goals[0] != goals[1]);
#ifndef NDEBUG
if (safetyCounter <= 0)
{
std::cerr << "Goal rolling did not terminate!" << std::endl;
std::cerr << "Chance: " << chanceLeftVsRight << ", C4D: " << chanceForDraw << ", chance: " << (2.0 * (normalizedChanceLeftVsRight)+(1.0 / 3.0)) << std::endl;
std::cerr << "Current sample: " << goals[0] << ":" << goals[1] << ", winner: " << winnerIndex << std::endl;
exit(1);
}
#endif
}
assert(!forceWinner || goals[0] != goals[1]);
return MatchResult(cluster, teams, goals, hadOvertime);
}
}; // namespace sim<commit_msg>Simulation: assign 50/50 chance to win a match if the actual chance would be NaN or INF<commit_after>#include "stdafx.h"
#include "Match.h"
#include "Simulation.h"
#include <random>
namespace sim
{
void MatchResultStatisticsList::addMatch(const MatchResult &match)
{
int teamIDOne = std::min(match.teams[0], match.teams[1]);
int teamIDTwo = std::max(match.teams[0], match.teams[1]);
std::pair<int, int> teamPair = std::make_pair(teamIDOne, teamIDTwo);
if (!results.count(teamPair))
{
results.emplace(teamPair, MatchResultStatistics(teamIDOne, teamIDTwo));
assert(match.bofRound > 0);
this->bofRound = match.bofRound;
this->gameInRound = match.gameInRound;
}
MatchResultStatistics &clusterResult = results[teamPair];
clusterResult.addMatch(match);
}
void MatchResultStatisticsList::merge(MatchResultStatisticsList &other)
{
for (auto &result : other.results)
{
const std::pair<int, int> &teamPair = result.first;
if (!results.count(teamPair))
results.emplace(teamPair, MatchResultStatistics(result.second));
else
results[teamPair].merge(result.second);
}
this->bofRound = other.bofRound;
this->gameInRound = other.gameInRound;
}
json_spirit::Array MatchResultStatisticsList::toJSONArray()
{
json_spirit::Array data;
// sort our results by count
std::list<MatchResultStatistics> sorted;
for (auto &result : results)
sorted.push_back(result.second);
sorted.sort();
sorted.reverse();
// ..and add to data
for (MatchResultStatistics &stats : sorted)
data.push_back(stats.toJSONObject());
return data;
}
json_spirit::Object MatchResultStatistics::toJSONObject()
{
json_spirit::Object object;
object.push_back(json_spirit::Pair("teams", json_spirit::Array({ teams[0], teams[1] })));
object.push_back(json_spirit::Pair("goals", json_spirit::Array({ goals[0], goals[1] })));
object.push_back(json_spirit::Pair("count", count));
return object;
}
void MatchResultStatistics::addMatch(const MatchResult &result)
{
int first = 0, second = 1;
// team IDs will always be sorted ascending
if (result.teams[0] > result.teams[1])
{
first = 1;
second = 0;
}
this->goals[0] += result.goals[first];
this->goals[1] += result.goals[second];
count += 1;
}
void MatchResultStatistics::merge(const MatchResultStatistics &other)
{
assert(this->teams[0] == other.teams[0] && this->teams[1] == other.teams[1]);
for (int i = 0; i < 2; ++i)
{
this->goals[i] += other.goals[i];
}
this->count += other.count;
}
Match::Match()
{
}
Match::~Match()
{
}
MatchResult Match::execute(std::string cluster, Simulation *simulation, Team &left, Team &right, bool forceWinner)
{
// use two chances for scoring - some rules are not necessarily symmetrical and should still work as good as possible
double chanceLeftVsRight(0.0), chanceRightVsLeft(0.0);
// the maximum weight of the normal rules. Used to scale backreferencing rules correctly
double maxRuleWeight = 0.0;
// apply all normal rules to figure out the correct odds
for (int i = 0; i < 2; ++i)
{
double weightedChanceSum = 0.0;
double weightTotalSum = 0.0;
for (auto &rule : simulation->rules)
{
// remember for backref rules later. Not only the weight of non-backref rules!
maxRuleWeight = std::max(maxRuleWeight, rule.weight);
if (rule.isBackrefRule) continue;
// rules can scale down their weight for one calculation if they cannot make good predictions anyway
double customWeight(1.0);
// apply!
double ruleChance = rule.getRawResults(i == 0 ? left : right, i == 0 ? right : left, &customWeight, nullptr);
weightedChanceSum += customWeight * rule.weight * ruleChance;
weightTotalSum += customWeight * rule.weight;
}
double chance = 0.0;
if (weightTotalSum > 0.0)
{
chance = weightedChanceSum / weightTotalSum;
}
if (i == 0)
chanceLeftVsRight = chance;
else
chanceRightVsLeft = chance;
}
// this can happen if a rule reduces its custom weight to 0
if ((chanceLeftVsRight == 0.0 && chanceRightVsLeft == 0.0) || !std::isfinite(chanceLeftVsRight) || !std::isfinite(chanceRightVsLeft))
{
chanceLeftVsRight = chanceRightVsLeft = 0.5;
}
// now apply all backreference rules
assert(maxRuleWeight != 0.0);
for (int i = 0; i < 2; ++i)
{
double *currentWinExpectancy = (i == 0) ? &chanceLeftVsRight : &chanceRightVsLeft;
for (auto &rule : simulation->rules)
{
if (!rule.isBackrefRule) continue;
double customWeight(1.0);
double adjustedWinExpectancy = rule.getRawResults(i == 0 ? left : right, i == 0 ? right : left, &customWeight, currentWinExpectancy);
// now scale the rule correctly, according to the user input
double ruleFactor = std::min(1.0, rule.weight * customWeight / maxRuleWeight);
*currentWinExpectancy = ruleFactor * adjustedWinExpectancy + (1.0 - ruleFactor) * (*currentWinExpectancy);
}
}
assert(!(chanceLeftVsRight == 0.0 && chanceRightVsLeft == 0.0));
// currently some rules might be assymetric (because they include draws f.e.)
// to make sure that we do a fair roll later, normalize the chances..
// Note that in case chanceLeftVsRight + chanceRightvsLeft == 1.0, this does nothing
double normalizedChanceLeftVsRight = chanceLeftVsRight / (chanceLeftVsRight + chanceRightVsLeft);
// std::cerr << "norm: " << normalizedChanceLeftVsRight << "\tleft: " << chanceLeftVsRight << "\tright: " << chanceRightVsLeft << std::endl;
int teams[] = {left.id, right.id};
int goals[] = {0, 0};
int winnerIndex = -1;
std::random_device seeder;
auto leftSideGoalRoller = std::bind(std::poisson_distribution<>(1.8 * (normalizedChanceLeftVsRight) + 0.27), std::mt19937(simulation->randomSeed + seeder()));
auto rightSideGoalRoller = std::bind(std::poisson_distribution<>(1.8 * (1.0 - normalizedChanceLeftVsRight) + 0.27), std::mt19937(simulation->randomSeed + seeder()));
auto uniformRoller = std::bind(std::uniform_real_distribution<double>(0.0, 1.0), std::mt19937(simulation->randomSeed + seeder()));
bool hadOvertime = false;
// roll for draws first
// 0.33 * exp(-(x - 0.5) ^ 2 / (2 * 0.28 ^ 2))
double chanceForDraw = (1.0 / 3.0) * std::exp(-std::pow((normalizedChanceLeftVsRight - 0.5), 2.0) / (2.0 * std::pow(0.28, 2.0)));
bool isDraw = false;
if (uniformRoller() < chanceForDraw)
{
if (forceWinner)
hadOvertime = true;
else
isDraw = true;
}
if (!isDraw)
{
const double winnerSide = uniformRoller();
if (winnerSide < normalizedChanceLeftVsRight)
winnerIndex = 0;
else
winnerIndex = 1;
// roll goals until someone wins
do
{
goals[0] = leftSideGoalRoller();
goals[1] = rightSideGoalRoller();
} while (goals[winnerIndex] <= goals[1 - winnerIndex]);
}
else
{
// roll goals until draw
#ifndef NDEBUG
int safetyCounter = 10000;
#endif
do
{
goals[0] = leftSideGoalRoller();
goals[1] = rightSideGoalRoller();
#ifndef NDEBUG
if (--safetyCounter <= 0) break;
#endif
} while (goals[0] != goals[1]);
#ifndef NDEBUG
if (safetyCounter <= 0)
{
std::cerr << "Goal rolling did not terminate!" << std::endl;
std::cerr << "Chance: " << chanceLeftVsRight << ", C4D: " << chanceForDraw << ", chance: " << (2.0 * (normalizedChanceLeftVsRight)+(1.0 / 3.0)) << std::endl;
std::cerr << "Current sample: " << goals[0] << ":" << goals[1] << ", winner: " << winnerIndex << std::endl;
exit(1);
}
#endif
}
assert(!forceWinner || goals[0] != goals[1]);
return MatchResult(cluster, teams, goals, hadOvertime);
}
}; // namespace sim<|endoftext|>
|
<commit_before>#include "label.h"
#include "../qrutils/outFile.h"
#include <QDebug>
using namespace utils;
bool Label::init(QDomElement const &element, int index, bool nodeLabel, int width, int height)
{
mX = initCoordinate(element.attribute("x"), width);
mY = initCoordinate(element.attribute("y"), height);
mCenter = element.attribute("center", "false");
mText = element.attribute("text");
mTextBinded = element.attribute("textBinded");
mReadOnly = element.attribute("readOnly", "false");
mRotation = element.attribute("rotation", "0").toDouble();
if (mTextBinded.contains("##")) {
mReadOnly = "true";
}
mIndex = index;
mBackground = element.attribute("background", nodeLabel ? "transparent" : "white");
mIsHard = element.attribute("hard", "false").toLower().trimmed() == "true";
mIsPlainText = element.attribute("isPlainText", "false").toLower().trimmed() == "true";
if ((mText.isEmpty() && mTextBinded.isEmpty()) || (mReadOnly != "true" && mReadOnly != "false")) {
qDebug() << "ERROR: can't parse label";
return false;
}
return true;
}
QString Label::titleName() const
{
return "title_" + QString("%1").arg(mIndex);
}
void Label::generateCodeForConstructor(OutFile &out)
{
if (mText.isEmpty()) {
// Это бинденный лейбл, текст для него будет браться из репозитория
out() << " " + titleName() + " = factory.createTitle("
+ QString::number(mX.value()) + ", " + QString::number(mY.value())
+ ", \"" + mTextBinded + "\", " + mReadOnly + ", " + QString::number(mRotation) + ");\n";
} else {
// Это статический лейбл, репозиторий ему не нужен
out() << " " + titleName() + " = factory.createTitle("
+ QString::number(mX.value()) + ", " + QString::number(mY.value())
+ ", QString::fromUtf8(\"" + mText + "\"), " + QString::number(mRotation) + ");\n";
}
out() << " " + titleName() + "->setBackground(Qt::" + mBackground + ");\n";
QString const scalingX = mX.isScalable() ? "true" : "false";
QString const scalingY = mY.isScalable() ? "true" : "false";
out() << " " + titleName() + "->setScaling(" + scalingX + ", " + scalingY + ");\n";
out() << " " + titleName() + "->setHard(" + (mIsHard ? "true" : "false") + ");\n";
// TODO: вынести отсюда в родительский класс.
out()
// << " " + titleName() + "->setFlags(0);\n"
<< " " + titleName() + "->setTextInteractionFlags(Qt::NoTextInteraction);\n"
<< " titles.append(" + titleName() + ");\n";
}
QStringList Label::getListOfStr(QString const &strToParse) const
{
return strToParse.split("##");
}
void Label::generateCodeForUpdateData(OutFile &out)
{
if (mTextBinded.isEmpty()) {
// Static label
out() << "\t\t\tQ_UNUSED(repo);\n";
return;
}
QStringList list = getListOfStr(mTextBinded);
QString resultStr;
if (list.count() == 1) {
if (list.first() == "name") {
resultStr = "repo->name()";
} else {
resultStr = "repo->logicalProperty(\"" + list.first() + "\")";
}
} else {
int counter = 1;
foreach (QString const &listElement, list) {
QString field;
if (counter % 2 == 0) {
if (listElement == "name") {
field = "repo->name()";
} else {
field = "repo->logicalProperty(\"" + listElement + "\")";
}
} else {
field = "QString::fromUtf8(\"" + listElement + "\")";
}
resultStr += " + " + field;
counter++;
}
resultStr = resultStr.mid(3);
}
if (mIsPlainText) {
out() << QString("\t\t\t%1->setPlainText(%2);\n")
.arg(titleName(), resultStr);
} else {
out() << "\t\t\t" + titleName() + "->setTextFromRepo("
+ resultStr + ");\n";
}
}
void Label::generateCodeForFields(OutFile &out)
{
out() << " LabelInterface *" + titleName() + ";\n";
}
<commit_msg>qrxc updated<commit_after>#include "label.h"
#include "../qrutils/outFile.h"
#include <QDebug>
using namespace utils;
bool Label::init(QDomElement const &element, int index, bool nodeLabel, int width, int height)
{
mX = initCoordinate(element.attribute("x"), width);
mY = initCoordinate(element.attribute("y"), height);
mCenter = element.attribute("center", "false");
mText = element.attribute("text");
mTextBinded = element.attribute("textBinded");
mReadOnly = element.attribute("readOnly", "false");
mRotation = element.attribute("rotation", "0").toDouble();
if (mTextBinded.contains("##")) {
mReadOnly = "true";
}
mIndex = index;
mBackground = element.attribute("background", nodeLabel ? "transparent" : "white");
mIsHard = element.attribute("hard", "false").toLower().trimmed() == "true";
mIsPlainText = element.attribute("isPlainText", "false").toLower().trimmed() == "true";
if ((mText.isEmpty() && mTextBinded.isEmpty()) || (mReadOnly != "true" && mReadOnly != "false")) {
qDebug() << "ERROR: can't parse label";
return false;
}
return true;
}
QString Label::titleName() const
{
return "title_" + QString("%1").arg(mIndex);
}
void Label::generateCodeForConstructor(OutFile &out)
{
if (mText.isEmpty()) {
// Это бинденный лейбл, текст для него будет браться из репозитория
out() << " " + titleName() + " = factory.createLabel("
+ QString::number(mX.value()) + ", " + QString::number(mY.value())
+ ", \"" + mTextBinded + "\", " + mReadOnly + ", " + QString::number(mRotation) + ");\n";
} else {
// Это статический лейбл, репозиторий ему не нужен
out() << " " + titleName() + " = factory.createLabel("
+ QString::number(mX.value()) + ", " + QString::number(mY.value())
+ ", QString::fromUtf8(\"" + mText + "\"), " + QString::number(mRotation) + ");\n";
}
out() << " " + titleName() + "->setBackground(Qt::" + mBackground + ");\n";
QString const scalingX = mX.isScalable() ? "true" : "false";
QString const scalingY = mY.isScalable() ? "true" : "false";
out() << " " + titleName() + "->setScaling(" + scalingX + ", " + scalingY + ");\n";
out() << " " + titleName() + "->setHard(" + (mIsHard ? "true" : "false") + ");\n";
// TODO: вынести отсюда в родительский класс.
out()
// << " " + titleName() + "->setFlags(0);\n"
<< " " + titleName() + "->setTextInteractionFlags(Qt::NoTextInteraction);\n"
<< " titles.append(" + titleName() + ");\n";
}
QStringList Label::getListOfStr(QString const &strToParse) const
{
return strToParse.split("##");
}
void Label::generateCodeForUpdateData(OutFile &out)
{
if (mTextBinded.isEmpty()) {
// Static label
out() << "\t\t\tQ_UNUSED(repo);\n";
return;
}
QStringList list = getListOfStr(mTextBinded);
QString resultStr;
if (list.count() == 1) {
if (list.first() == "name") {
resultStr = "repo->name()";
} else {
resultStr = "repo->logicalProperty(\"" + list.first() + "\")";
}
} else {
int counter = 1;
foreach (QString const &listElement, list) {
QString field;
if (counter % 2 == 0) {
if (listElement == "name") {
field = "repo->name()";
} else {
field = "repo->logicalProperty(\"" + listElement + "\")";
}
} else {
field = "QString::fromUtf8(\"" + listElement + "\")";
}
resultStr += " + " + field;
counter++;
}
resultStr = resultStr.mid(3);
}
if (mIsPlainText) {
out() << QString("\t\t\t%1->setPlainText(%2);\n")
.arg(titleName(), resultStr);
} else {
out() << "\t\t\t" + titleName() + "->setTextFromRepo("
+ resultStr + ");\n";
}
}
void Label::generateCodeForFields(OutFile &out)
{
out() << " LabelInterface *" + titleName() + ";\n";
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2000 by Norman Krmer
original unplugged code and fonts by Andrew Zabolotny
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "sysdef.h"
#include "csfont.h"
#include "police.fnt"
#include "courier.fnt" // font (C) Andrew Zabolotny
#include "tiny.fnt" // font (C) Andrew Zabolotny
#include "italic.fnt" // font (C) Andrew Zabolotny
csFontDef csDefaultFontRender::FontList [] =
{
{ "Police", 8, 8, 8, font_Police, width_Police },
{ "Police.fixed", 8, 8, 8, font_Police, NULL },
{ "Italic", 8, 8, 8, font_Italic, width_Italic },
{ "Italic.fixed", 8, 8, 8, font_Italic, NULL },
{ "Courier", 7, 8, 8, font_Courier, width_Courier },
{ "Courier.fixed", 8, 8, 8, font_Courier, NULL },
{ "Tiny", 4, 6, 8, font_Tiny, width_Tiny },
{ "Tiny.fixed", 6, 6, 8, font_Tiny, NULL },
{ NULL }
};
IMPLEMENT_IBASE (csDefaultFontRender)
IMPLEMENTS_INTERFACE (iFontRender)
IMPLEMENTS_INTERFACE (iPlugIn)
IMPLEMENT_IBASE_END
IMPLEMENT_FACTORY (csDefaultFontRender)
EXPORT_CLASS_TABLE (csfont)
EXPORT_CLASS (csDefaultFontRender, "crystalspace.font.render.csfont",
"CrystalSpace default font renderer" )
EXPORT_CLASS_TABLE_END
csDefaultFontRender::csDefaultFontRender (iBase *pParent)
{
CONSTRUCT_IBASE (pParent);
for (FontCount = 1; FontList [FontCount - 1].Name; FontCount++)
;
}
bool csDefaultFontRender::Initialize (iSystem *pSystem)
{
(void)pSystem;
return true;
}
int csDefaultFontRender::LoadFont (const char* name, const char* /*filename*/)
{
for (int i = 0; FontList [i].Name; i++)
if (!strcmp (FontList [i].Name, name))
return i;
return -1;
}
bool csDefaultFontRender::SetFontProperty (int fontId,
CS_FONTPROPERTY propertyId, long& property, bool autoApply)
{
(void)fontId;
(void)autoApply;
bool succ = (propertyId == CS_FONTSIZE);
if (succ && property != 1) property = 1;
return succ;
}
bool csDefaultFontRender::GetFontProperty (int fontId, CS_FONTPROPERTY propertyId, long& property)
{
(void)fontId;
bool succ = (propertyId == CS_FONTSIZE);
if (succ) property = 1;
return succ;
}
unsigned char *csDefaultFontRender::GetCharBitmap (int fontId, unsigned char c)
{
// printf("%c of font %d\n", c, fontId);
return &(FontList [fontId].FontBitmap [c * FontList [fontId].BytesPerChar]);
}
int csDefaultFontRender::GetCharWidth (int fontId, unsigned char c)
{
int width;
if (FontList [fontId].IndividualWidth)
width = FontList [fontId].IndividualWidth [c];
else
width = FontList [fontId].Width;
return width;
}
int csDefaultFontRender::GetCharHeight (int fontId, unsigned char /*c*/)
{
return FontList [fontId].Height;
}
int csDefaultFontRender::GetMaximumHeight (int fontId)
{
return FontList [fontId].Height;
}
void csDefaultFontRender::GetTextDimensions (int fontId, const char* text, int& width, int& height)
{
int i, n = strlen (text);
width = 0;
height = 0;
if (FontList [fontId].IndividualWidth)
for (i = 0; i < n; i++)
width += FontList [fontId].IndividualWidth [*(unsigned char *)text++];
else
width = n * FontList [fontId].Width;
height = FontList [fontId].Height;
}
<commit_msg>Fixed bug: Was incorrectly computing FontCount (one too large). This may have been cause of crasher in OpenGL AddFont().<commit_after>/*
Copyright (C) 2000 by Norman Krmer
original unplugged code and fonts by Andrew Zabolotny
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "sysdef.h"
#include "csfont.h"
#include "police.fnt"
#include "courier.fnt" // font (C) Andrew Zabolotny
#include "tiny.fnt" // font (C) Andrew Zabolotny
#include "italic.fnt" // font (C) Andrew Zabolotny
csFontDef csDefaultFontRender::FontList [] =
{
{ "Police", 8, 8, 8, font_Police, width_Police },
{ "Police.fixed", 8, 8, 8, font_Police, NULL },
{ "Italic", 8, 8, 8, font_Italic, width_Italic },
{ "Italic.fixed", 8, 8, 8, font_Italic, NULL },
{ "Courier", 7, 8, 8, font_Courier, width_Courier },
{ "Courier.fixed", 8, 8, 8, font_Courier, NULL },
{ "Tiny", 4, 6, 8, font_Tiny, width_Tiny },
{ "Tiny.fixed", 6, 6, 8, font_Tiny, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
IMPLEMENT_IBASE (csDefaultFontRender)
IMPLEMENTS_INTERFACE (iFontRender)
IMPLEMENTS_INTERFACE (iPlugIn)
IMPLEMENT_IBASE_END
IMPLEMENT_FACTORY (csDefaultFontRender)
EXPORT_CLASS_TABLE (csfont)
EXPORT_CLASS (csDefaultFontRender, "crystalspace.font.render.csfont",
"CrystalSpace default font renderer" )
EXPORT_CLASS_TABLE_END
csDefaultFontRender::csDefaultFontRender (iBase *pParent)
{
CONSTRUCT_IBASE (pParent);
FontCount = sizeof(FontList) / sizeof(FontList[0]) - 1;
}
bool csDefaultFontRender::Initialize (iSystem*)
{
return true;
}
int csDefaultFontRender::LoadFont (const char* name, const char* /*filename*/)
{
for (int i = 0; FontList [i].Name; i++)
if (!strcmp (FontList [i].Name, name))
return i;
return -1;
}
bool csDefaultFontRender::SetFontProperty (int /*fontId*/,
CS_FONTPROPERTY propertyId, long& property, bool /*autoApply*/)
{
bool succ = (propertyId == CS_FONTSIZE);
if (succ && property != 1) property = 1;
return succ;
}
bool csDefaultFontRender::GetFontProperty (int fontId,
CS_FONTPROPERTY propertyId, long& property)
{
(void)fontId;
bool succ = (propertyId == CS_FONTSIZE);
if (succ) property = 1;
return succ;
}
unsigned char *csDefaultFontRender::GetCharBitmap (int fontId, unsigned char c)
{
return &(FontList [fontId].FontBitmap [c * FontList [fontId].BytesPerChar]);
}
int csDefaultFontRender::GetCharWidth (int fontId, unsigned char c)
{
int width;
if (FontList [fontId].IndividualWidth)
width = FontList [fontId].IndividualWidth [c];
else
width = FontList [fontId].Width;
return width;
}
int csDefaultFontRender::GetCharHeight (int fontId, unsigned char /*c*/)
{
return FontList [fontId].Height;
}
int csDefaultFontRender::GetMaximumHeight (int fontId)
{
return FontList [fontId].Height;
}
void csDefaultFontRender::GetTextDimensions (int fontId, const char* text,
int& width, int& height)
{
int i, n = strlen (text);
width = 0;
height = 0;
if (FontList [fontId].IndividualWidth)
for (i = 0; i < n; i++)
width += FontList [fontId].IndividualWidth [*(unsigned char *)text++];
else
width = n * FontList [fontId].Width;
height = FontList [fontId].Height;
}
<|endoftext|>
|
<commit_before>#include <cmath>
#include <cfloat>
#include <csignal>
#include <iostream>
#include "ModuleGame.hpp"
#include "Sound.hpp"
#include "SoundClip.hpp"
#include <OpenALInterface.hpp>
#include <SDLOpenGLInterface.hpp>
#include <PthreadsInterface.hpp>
#include "Vector3.hpp"
#include "Quaternion.hpp"
#define MATH_PI 3.14159265358979323846264
// The Chopin comes from https://archive.org/details/onclassical-quality-wav-audio-files-of-classical-music
bool halted = false;
void sigterm_handler(int signal)
{
if (signal == SIGINT)
{
halted = true;
std::cout << "Terminated!" << std::endl;
}
}
int main(int argc, char ** argv)
{
// Create the game
Module::ModuleGame game;
// Create the interfaces
Module::SDLOpenGLInterface graphics;
Module::OpenALInterface audio;
Module::PthreadsInterface threads;
// Attatch the interfaces to the game
game.attachThreadingInterface(&threads);
game.attachGraphicsInterface(&graphics);
game.attachAudioInterface(&audio);
// Starts the game
game.start();
// Create a game object
Module::GameObject* gameobj = game.createGameObject();
Module::GameObject* camera = game.createGameObject();
// camera->setPosition(Module::Vector3(0,1.732f,3));
camera->setPosition(Module::Vector3(0,0,3));
// camera->setRotation(Module::Quaternion(Module::Vector3(1,0,0), -3.141592f/6.0f));
// GRAPHICS TESTS
Module::Mesh* teapot = graphics.loadMeshFromFile("teapot", "models/teapot.obj", true);
teapot->setScale(1/60.0f);
game.setMesh(gameobj, teapot);
graphics.setCamera(camera);
// AUDIO TESTS
Module::SoundClip* boilClip = audio.loadSoundClip("boilingWater","sounds/boiling.wav");
Module::SoundClip* musicClip = audio.loadSoundClip("chopinScherzo","sounds/chopin_scherzo.wav");
audio.playSound(boilClip);
audio.playSound(musicClip);
audio.debugAudio();
signal(SIGINT, sigterm_handler);
unsigned long millisStart = game.getMilliseconds();
while (game.isRunning())
{
unsigned long millis = game.getMilliseconds() - millisStart;
gameobj->setRotation(Module::Quaternion(Module::Vector3(0,1,0), millis/1000.0f));
}
return 0;
}
<commit_msg>Rotated the camera a bit<commit_after>#include <cmath>
#include <cfloat>
#include <csignal>
#include <iostream>
#include "ModuleGame.hpp"
#include "Sound.hpp"
#include "SoundClip.hpp"
#include <OpenALInterface.hpp>
#include <SDLOpenGLInterface.hpp>
#include <PthreadsInterface.hpp>
#include "Vector3.hpp"
#include "Quaternion.hpp"
#define MATH_PI 3.14159265358979323846264
// The Chopin comes from https://archive.org/details/onclassical-quality-wav-audio-files-of-classical-music
bool halted = false;
void sigterm_handler(int signal)
{
if (signal == SIGINT)
{
halted = true;
std::cout << "Terminated!" << std::endl;
}
}
int main(int argc, char ** argv)
{
// Create the game
Module::ModuleGame game;
// Create the interfaces
Module::SDLOpenGLInterface graphics;
Module::OpenALInterface audio;
Module::PthreadsInterface threads;
// Attatch the interfaces to the game
game.attachThreadingInterface(&threads);
game.attachGraphicsInterface(&graphics);
game.attachAudioInterface(&audio);
// Starts the game
game.start();
// Create a game object
Module::GameObject* gameobj = game.createGameObject();
Module::GameObject* camera = game.createGameObject();
camera->setPosition(Module::Vector3(0,1.732f,3));
// camera->setPosition(Module::Vector3(0,0,3));
camera->setRotation(Module::Quaternion(Module::Vector3(1,0,0), -3.141592f/6.0f));
// GRAPHICS TESTS
Module::Mesh* teapot = graphics.loadMeshFromFile("teapot", "models/teapot.obj", true);
teapot->setScale(1/60.0f);
game.setMesh(gameobj, teapot);
graphics.setCamera(camera);
// AUDIO TESTS
Module::SoundClip* boilClip = audio.loadSoundClip("boilingWater","sounds/boiling.wav");
Module::SoundClip* musicClip = audio.loadSoundClip("chopinScherzo","sounds/chopin_scherzo.wav");
audio.playSound(boilClip);
audio.playSound(musicClip);
audio.debugAudio();
signal(SIGINT, sigterm_handler);
unsigned long millisStart = game.getMilliseconds();
while (game.isRunning())
{
unsigned long millis = game.getMilliseconds() - millisStart;
gameobj->setRotation(Module::Quaternion(Module::Vector3(0,1,0), millis/1000.0f));
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "utilitydialog.h"
#include "ui_helpmessagedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "intro.h"
#include "paymentrequestplus.h"
#include "guiutil.h"
#include "clientversion.h"
#include "init.h"
#include "util.h"
#include <stdio.h>
#include <QCloseEvent>
#include <QLabel>
#include <QRegExp>
#include <QTextTable>
#include <QTextCursor>
#include <QVBoxLayout>
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
ui->setupUi(this);
QString version = tr(PACKAGE_NAME) + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
/* On x86 add a bit specifier to the version so that users can distinguish between
* 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
*/
#if defined(__x86_64__)
version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
version += " " + tr("(%1-bit)").arg(32);
#endif
if (about)
{
setWindowTitle(tr("About %1").arg(tr(PACKAGE_NAME)));
/// HTML-format the license message from the core
QString licenseInfo = QString::fromStdString(LicenseInfo());
QString licenseInfoHTML = licenseInfo;
// Make URLs clickable
QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
uri.setMinimal(true); // use non-greedy matching
licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
// Replace newlines with HTML breaks
licenseInfoHTML.replace("\n", "<br>");
ui->aboutMessage->setTextFormat(Qt::RichText);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
text = version + "\n" + licenseInfo;
ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML);
ui->aboutMessage->setWordWrap(true);
ui->helpMessage->setVisible(false);
} else {
setWindowTitle(tr("Command-line options"));
QString header = tr("Usage:") + "\n" +
" bitcoin-qt [" + tr("command-line options") + "] " + "\n";
QTextCursor cursor(ui->helpMessage->document());
cursor.insertText(version);
cursor.insertBlock();
cursor.insertText(header);
cursor.insertBlock();
std::string strUsage = HelpMessage(HMM_BITCOIN_QT);
const bool showDebug = GetBoolArg("-help-debug", false);
strUsage += HelpMessageGroup(tr("UI Options:").toStdString());
if (showDebug) {
strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", strprintf("Allow self signed root certificates (default: %u)", DEFAULT_SELFSIGNED_ROOTCERTS));
}
strUsage += HelpMessageOpt("-choosedatadir", strprintf(tr("Choose data directory on startup (default: %u)").toStdString(), DEFAULT_CHOOSE_DATADIR));
strUsage += HelpMessageOpt("-lang=<lang>", tr("Set language, for example \"de_DE\" (default: system locale)").toStdString());
strUsage += HelpMessageOpt("-min", tr("Start minimized").toStdString());
strUsage += HelpMessageOpt("-rootcertificates=<file>", tr("Set SSL root certificates for payment request (default: -system-)").toStdString());
strUsage += HelpMessageOpt("-splash", strprintf(tr("Show splash screen on startup (default: %u)").toStdString(), DEFAULT_SPLASHSCREEN));
strUsage += HelpMessageOpt("-resetguisettings", tr("Reset all settings changed in the GUI").toStdString());
if (showDebug) {
strUsage += HelpMessageOpt("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", BitcoinGUI::DEFAULT_UIPLATFORM));
}
QString coreOptions = QString::fromStdString(strUsage);
text = version + "\n" + header + "\n" + coreOptions;
QTextTableFormat tf;
tf.setBorderStyle(QTextFrameFormat::BorderStyle_None);
tf.setCellPadding(2);
QVector<QTextLength> widths;
widths << QTextLength(QTextLength::PercentageLength, 35);
widths << QTextLength(QTextLength::PercentageLength, 65);
tf.setColumnWidthConstraints(widths);
QTextCharFormat bold;
bold.setFontWeight(QFont::Bold);
Q_FOREACH (const QString &line, coreOptions.split("\n")) {
if (line.startsWith(" -"))
{
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::PreviousCell);
cursor.movePosition(QTextCursor::NextRow);
cursor.insertText(line.trimmed());
cursor.movePosition(QTextCursor::NextCell);
} else if (line.startsWith(" ")) {
cursor.insertText(line.trimmed()+' ');
} else if (line.size() > 0) {
//Title of a group
if (cursor.currentTable())
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::Down);
cursor.insertText(line.trimmed(), bold);
cursor.insertTable(1, 2, tf);
}
}
ui->helpMessage->moveCursor(QTextCursor::Start);
ui->scrollArea->setVisible(false);
ui->aboutLogo->setVisible(false);
}
}
HelpMessageDialog::~HelpMessageDialog()
{
delete ui;
}
void HelpMessageDialog::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
fprintf(stdout, "%s\n", qPrintable(text));
}
void HelpMessageDialog::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
void HelpMessageDialog::on_okButton_accepted()
{
close();
}
/** "Shutdown" window */
ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f):
QWidget(parent, f)
{
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(new QLabel(
tr("%1 is shutting down...").arg(tr(PACKAGE_NAME)) + "<br /><br />" +
tr("Do not shut down the computer until this window disappears.")));
setLayout(layout);
}
void ShutdownWindow::showShutdownWindow(BitcoinGUI *window)
{
if (!window)
return;
// Show a simple window indicating shutdown status
QWidget *shutdownWindow = new ShutdownWindow();
// We don't hold a direct pointer to the shutdown window after creation, so use
// Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually.
shutdownWindow->setAttribute(Qt::WA_DeleteOnClose);
shutdownWindow->setWindowTitle(window->windowTitle());
// Center shutdown window at where main window was
const QPoint global = window->mapToGlobal(window->rect().center());
shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2);
shutdownWindow->show();
}
void ShutdownWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
}
<commit_msg>Renamed CLI Strings<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "utilitydialog.h"
#include "ui_helpmessagedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "intro.h"
#include "paymentrequestplus.h"
#include "guiutil.h"
#include "clientversion.h"
#include "init.h"
#include "util.h"
#include <stdio.h>
#include <QCloseEvent>
#include <QLabel>
#include <QRegExp>
#include <QTextTable>
#include <QTextCursor>
#include <QVBoxLayout>
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
ui->setupUi(this);
QString version = tr(PACKAGE_NAME) + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
/* On x86 add a bit specifier to the version so that users can distinguish between
* 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
*/
#if defined(__x86_64__)
version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
version += " " + tr("(%1-bit)").arg(32);
#endif
if (about)
{
setWindowTitle(tr("About %1").arg(tr(PACKAGE_NAME)));
/// HTML-format the license message from the core
QString licenseInfo = QString::fromStdString(LicenseInfo());
QString licenseInfoHTML = licenseInfo;
// Make URLs clickable
QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
uri.setMinimal(true); // use non-greedy matching
licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
// Replace newlines with HTML breaks
licenseInfoHTML.replace("\n", "<br>");
ui->aboutMessage->setTextFormat(Qt::RichText);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
text = version + "\n" + licenseInfo;
ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML);
ui->aboutMessage->setWordWrap(true);
ui->helpMessage->setVisible(false);
} else {
setWindowTitle(tr("Command-line options"));
QString header = tr("Usage:") + "\n" +
" terracoin-qt [" + tr("command-line options") + "] " + "\n";
QTextCursor cursor(ui->helpMessage->document());
cursor.insertText(version);
cursor.insertBlock();
cursor.insertText(header);
cursor.insertBlock();
std::string strUsage = HelpMessage(HMM_BITCOIN_QT);
const bool showDebug = GetBoolArg("-help-debug", false);
strUsage += HelpMessageGroup(tr("UI Options:").toStdString());
if (showDebug) {
strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", strprintf("Allow self signed root certificates (default: %u)", DEFAULT_SELFSIGNED_ROOTCERTS));
}
strUsage += HelpMessageOpt("-choosedatadir", strprintf(tr("Choose data directory on startup (default: %u)").toStdString(), DEFAULT_CHOOSE_DATADIR));
strUsage += HelpMessageOpt("-lang=<lang>", tr("Set language, for example \"de_DE\" (default: system locale)").toStdString());
strUsage += HelpMessageOpt("-min", tr("Start minimized").toStdString());
strUsage += HelpMessageOpt("-rootcertificates=<file>", tr("Set SSL root certificates for payment request (default: -system-)").toStdString());
strUsage += HelpMessageOpt("-splash", strprintf(tr("Show splash screen on startup (default: %u)").toStdString(), DEFAULT_SPLASHSCREEN));
strUsage += HelpMessageOpt("-resetguisettings", tr("Reset all settings changed in the GUI").toStdString());
if (showDebug) {
strUsage += HelpMessageOpt("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", BitcoinGUI::DEFAULT_UIPLATFORM));
}
QString coreOptions = QString::fromStdString(strUsage);
text = version + "\n" + header + "\n" + coreOptions;
QTextTableFormat tf;
tf.setBorderStyle(QTextFrameFormat::BorderStyle_None);
tf.setCellPadding(2);
QVector<QTextLength> widths;
widths << QTextLength(QTextLength::PercentageLength, 35);
widths << QTextLength(QTextLength::PercentageLength, 65);
tf.setColumnWidthConstraints(widths);
QTextCharFormat bold;
bold.setFontWeight(QFont::Bold);
Q_FOREACH (const QString &line, coreOptions.split("\n")) {
if (line.startsWith(" -"))
{
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::PreviousCell);
cursor.movePosition(QTextCursor::NextRow);
cursor.insertText(line.trimmed());
cursor.movePosition(QTextCursor::NextCell);
} else if (line.startsWith(" ")) {
cursor.insertText(line.trimmed()+' ');
} else if (line.size() > 0) {
//Title of a group
if (cursor.currentTable())
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::Down);
cursor.insertText(line.trimmed(), bold);
cursor.insertTable(1, 2, tf);
}
}
ui->helpMessage->moveCursor(QTextCursor::Start);
ui->scrollArea->setVisible(false);
ui->aboutLogo->setVisible(false);
}
}
HelpMessageDialog::~HelpMessageDialog()
{
delete ui;
}
void HelpMessageDialog::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
fprintf(stdout, "%s\n", qPrintable(text));
}
void HelpMessageDialog::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
void HelpMessageDialog::on_okButton_accepted()
{
close();
}
/** "Shutdown" window */
ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f):
QWidget(parent, f)
{
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(new QLabel(
tr("%1 is shutting down...").arg(tr(PACKAGE_NAME)) + "<br /><br />" +
tr("Do not shut down the computer until this window disappears.")));
setLayout(layout);
}
void ShutdownWindow::showShutdownWindow(BitcoinGUI *window)
{
if (!window)
return;
// Show a simple window indicating shutdown status
QWidget *shutdownWindow = new ShutdownWindow();
// We don't hold a direct pointer to the shutdown window after creation, so use
// Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually.
shutdownWindow->setAttribute(Qt::WA_DeleteOnClose);
shutdownWindow->setWindowTitle(window->windowTitle());
// Center shutdown window at where main window was
const QPoint global = window->mapToGlobal(window->rect().center());
shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2);
shutdownWindow->show();
}
void ShutdownWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2014 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 "utilitydialog.h"
#include "ui_helpmessagedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "clientversion.h"
#include "init.h"
#include <stdio.h>
#include <QCloseEvent>
#include <QLabel>
#include <QRegExp>
#include <QVBoxLayout>
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nHelpMessageDialogWindow", this->size(), this);
QString version = tr("Viacoin Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
/* On x86 add a bit specifier to the version so that users can distinguish between
* 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
*/
#if defined(__x86_64__)
version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
version += " " + tr("(%1-bit)").arg(32);
#endif
if (about)
{
setWindowTitle(tr("About Viacoin Core"));
/// HTML-format the license message from the core
QString licenseInfo = QString::fromStdString(LicenseInfo());
QString licenseInfoHTML = licenseInfo;
// Make URLs clickable
QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
uri.setMinimal(true); // use non-greedy matching
licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
// Replace newlines with HTML breaks
licenseInfoHTML.replace("\n\n", "<br><br>");
ui->helpMessageLabel->setTextFormat(Qt::RichText);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
text = version + "\n" + licenseInfo;
ui->helpMessageLabel->setText(version + "<br><br>" + licenseInfoHTML);
ui->helpMessageLabel->setWordWrap(true);
} else {
setWindowTitle(tr("Command-line options"));
QString header = tr("Usage:") + "\n" +
" bitcoin-qt [" + tr("command-line options") + "] " + "\n";
QString coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT));
QString uiOptions = tr("UI options") + ":\n" +
" -choosedatadir " + tr("Choose data directory on startup (default: 0)") + "\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -rootcertificates=<file> " + tr("Set SSL root certificates for payment request (default: -system-)") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)");
ui->helpMessageLabel->setFont(GUIUtil::bitcoinAddressFont());
text = version + "\n" + header + "\n" + coreOptions + "\n" + uiOptions;
ui->helpMessageLabel->setText(text);
}
}
HelpMessageDialog::~HelpMessageDialog()
{
GUIUtil::saveWindowGeometry("nHelpMessageDialogWindow", this);
delete ui;
}
void HelpMessageDialog::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
fprintf(stdout, "%s\n", qPrintable(text));
}
void HelpMessageDialog::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
void HelpMessageDialog::on_okButton_accepted()
{
close();
}
/** "Shutdown" window */
ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f):
QWidget(parent, f)
{
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(new QLabel(
tr("Bitcoin Core is shutting down...") + "<br /><br />" +
tr("Do not shut down the computer until this window disappears.")));
setLayout(layout);
}
void ShutdownWindow::showShutdownWindow(BitcoinGUI *window)
{
if (!window)
return;
// Show a simple window indicating shutdown status
QWidget *shutdownWindow = new ShutdownWindow();
// We don't hold a direct pointer to the shutdown window after creation, so use
// Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually.
shutdownWindow->setAttribute(Qt::WA_DeleteOnClose);
shutdownWindow->setWindowTitle(window->windowTitle());
// Center shutdown window at where main window was
const QPoint global = window->mapToGlobal(window->rect().center());
shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2);
shutdownWindow->show();
}
void ShutdownWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
}
<commit_msg>Fix language string<commit_after>// Copyright (c) 2011-2014 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 "utilitydialog.h"
#include "ui_helpmessagedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "clientversion.h"
#include "init.h"
#include <stdio.h>
#include <QCloseEvent>
#include <QLabel>
#include <QRegExp>
#include <QVBoxLayout>
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nHelpMessageDialogWindow", this->size(), this);
QString version = tr("Viacoin Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
/* On x86 add a bit specifier to the version so that users can distinguish between
* 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
*/
#if defined(__x86_64__)
version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
version += " " + tr("(%1-bit)").arg(32);
#endif
if (about)
{
setWindowTitle(tr("About Viacoin Core"));
/// HTML-format the license message from the core
QString licenseInfo = QString::fromStdString(LicenseInfo());
QString licenseInfoHTML = licenseInfo;
// Make URLs clickable
QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
uri.setMinimal(true); // use non-greedy matching
licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
// Replace newlines with HTML breaks
licenseInfoHTML.replace("\n\n", "<br><br>");
ui->helpMessageLabel->setTextFormat(Qt::RichText);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
text = version + "\n" + licenseInfo;
ui->helpMessageLabel->setText(version + "<br><br>" + licenseInfoHTML);
ui->helpMessageLabel->setWordWrap(true);
} else {
setWindowTitle(tr("Command-line options"));
QString header = tr("Usage:") + "\n" +
" bitcoin-qt [" + tr("command-line options") + "] " + "\n";
QString coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT));
QString uiOptions = tr("UI options") + ":\n" +
" -choosedatadir " + tr("Choose data directory on startup (default: 0)") + "\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -rootcertificates=<file> " + tr("Set SSL root certificates for payment request (default: -system-)") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)");
ui->helpMessageLabel->setFont(GUIUtil::bitcoinAddressFont());
text = version + "\n" + header + "\n" + coreOptions + "\n" + uiOptions;
ui->helpMessageLabel->setText(text);
}
}
HelpMessageDialog::~HelpMessageDialog()
{
GUIUtil::saveWindowGeometry("nHelpMessageDialogWindow", this);
delete ui;
}
void HelpMessageDialog::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
fprintf(stdout, "%s\n", qPrintable(text));
}
void HelpMessageDialog::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
void HelpMessageDialog::on_okButton_accepted()
{
close();
}
/** "Shutdown" window */
ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f):
QWidget(parent, f)
{
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(new QLabel(
tr("Viacoin Core is shutting down...") + "<br /><br />" +
tr("Do not shut down the computer until this window disappears.")));
setLayout(layout);
}
void ShutdownWindow::showShutdownWindow(BitcoinGUI *window)
{
if (!window)
return;
// Show a simple window indicating shutdown status
QWidget *shutdownWindow = new ShutdownWindow();
// We don't hold a direct pointer to the shutdown window after creation, so use
// Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually.
shutdownWindow->setAttribute(Qt::WA_DeleteOnClose);
shutdownWindow->setWindowTitle(window->windowTitle());
// Center shutdown window at where main window was
const QPoint global = window->mapToGlobal(window->rect().center());
shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2);
shutdownWindow->show();
}
void ShutdownWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
}
<|endoftext|>
|
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2006 Ulrich von Zadow
//
// 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
void export_bitmap();
void export_raster();
void export_event();
#ifndef WIN32
void export_devices();
#endif
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../player/Player.h"
#include "../player/AVGNode.h"
#include "../player/DivNode.h"
#include "../player/PanoImage.h"
#include <boost/python.hpp>
#include <boost/version.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost::python;
using namespace avg;
void export_node()
{
class_<Node, boost::shared_ptr<Node>, boost::noncopyable>("Node",
"Base class for all elements in the avg tree.\n"
"Properties:\n"
" id: A unique identifier that can be used to reference the node (ro).\n"
" x: The position of the node's left edge relative to it's parent node.\n"
" y: The position of the node's top edge relative to it's parent node.\n"
" width\n"
" height\n"
" opacity: A measure of the node's transparency. 0.0 is completely\n"
" transparent, 1.0 is completely opaque. Opacity is relative to\n"
" the parent node's opacity.\n"
" active: If this attribute is true, the node behaves as usual. If not, it\n"
" is neither drawn nor does it react to events. Videos are paused.\n"
" sensitive: A node only reacts to events if sensitive is true.",
no_init)
.def("getParent", &Node::getParent,
"getParent() -> Node\n\n"
"Returns the container (AVGNode or DivNode) the node is in. For\n"
"the root node, returns None.\n")
.def("setEventCapture", &Node::setMouseEventCapture,
"setEventCapture() -> None\n\n")
.def("setEventCapture", &Node::setEventCapture,
"setEventCapture(CursorID) -> None\n\n"
"Sets up event capturing so that all mouse events are sent to this node\n"
"regardless of the mouse cursor position. If the node doesn't handle the\n"
"event, it propagates to its parent normally. Useful for the\n"
"implementation of user interface elements such as scroll bars. Only one\n"
"node can capture the mouse at any one time. Normal mouse operation can\n"
"be restored by calling releaseEventCapture().\n")
.def("releaseEventCapture", &Node::releaseMouseEventCapture,
"releaseEventCapture() -> None\n\n")
.def("releaseEventCapture", &Node::releaseEventCapture,
"releaseEventCapture() -> None\n\n"
"Restores normal nouse operation after a call to setEventCapture()\n")
.def("setEventHandler", &Node::setEventHandler,
"setEventHandler(Type, Source, pyfunc) -> None\n\n"
"Sets a callback function that is invoked whenever an event of the\n"
"specified Type from the specified Source occurs. This function is\n"
"similar to the event handler node attributes (e.g. oncursordown).\n"
"It is more specific since it takes the event source as a parameter\n"
"and allows the use of any python callable as callback function.\n")
.add_property("id", make_function(&Node::getID,
return_value_policy<copy_const_reference>()), &Node::setID)
.add_property("x", &Node::getX, &Node::setX)
.add_property("y", &Node::getY, &Node::setY)
.add_property("width", &Node::getWidth, &Node::setWidth)
.add_property("height", &Node::getHeight, &Node::setHeight)
.add_property("opacity", &Node::getOpacity, &Node::setOpacity)
.add_property("active", &Node::getActive, &Node::setActive)
.add_property("sensitive", &Node::getSensitive, &Node::setSensitive)
;
export_bitmap();
export_raster();
class_<DivNode, bases<Node>, boost::noncopyable>("DivNode",
"A div node is a node that groups other nodes logically and visually.\n"
"Its upper left corner is used as point of origin for the coordinates\n"
"of its child nodes. Its extents are used to clip the children. Its\n"
"opacity is used as base opacity for the child nodes' opacities.\n",
no_init)
.def("getNumChildren", &DivNode::getNumChildren,
"getNumChildren() -> numChildren\n\n")
.def("getChild", &DivNode::getChild,
"getChild(i) -> Node\n\n"
"Returns the ith child in z-order.")
.def("addChild", &DivNode::addChild,
"addChild(Node) -> None\n\n"
"Adds a new child to the container.")
.def("removeChild", &DivNode::removeChild,
"removeChild(i) -> None\n\n"
"Removes the child at index i.")
.def("indexOf", &DivNode::indexOf,
"indexOf(childNode) -> i\n\n"
"Returns the index of the child given or -1 if childNode isn't a\n"
"child of the container.")
;
class_<AVGNode, bases<DivNode> >("AVGNode",
"Root node of any avg tree. Defines the properties of the display and\n"
"handles key press events. The AVGNode's width and height define the\n"
"coordinate system for the display and are the default for the window\n"
"size used (i.e. by default, the coordinate system is pixel-based.)\n"
"Properties:\n"
" none\n",
no_init)
.def("getCropSetting", &AVGNode::getCropSetting,
"getCropSetting() -> isCropActive\n\n"
"Returns true if cropping is active. Cropping can be turned off globally\n"
"in the avg file. (Deprecated. This attribute is only nessesary because\n"
"of certain buggy display drivers that don't work with cropping.)")
;
class_<PanoImage, bases<Node> >("PanoImage",
"A panorama image.\n"
"Properties:\n"
" href: The source filename of the image.\n"
" sensorwidth: The width of the sensor used to make the image. This value\n"
" is used together with sensorheight and focallength to\n"
" determine the projection to use. (ro)\n"
" sensorheight: The height of the sensor used to make the image. (ro)\n"
" focallength: The focal length of the lens in millimeters. (ro)\n"
" hue: A hue to color the image in. (ro, deprecated)\n"
" saturation: The saturation the image should have. (ro, deprecated)\n"
" rotation: The current angle the viewer is looking at in radians.\n"
" maxrotation: The maximum angle the viewer can look at.\n",
no_init)
.def("getScreenPosFromPanoPos", &PanoImage::getScreenPosFromPanoPos,
"getScreenPosFromPanoPos(panoPos) -> pos\n\n"
"Converts a position in panorama image pixels to pixels in coordinates\n"
"relative to the node, taking into account the current rotation angle.\n")
.def("getScreenPosFromAngle", &PanoImage::getScreenPosFromAngle,
"getScreenPosFromAngle(angle) -> pos\n\n"
"Converts panorama angle to pixels in coordinates\n"
"relative to the node, taking into account the current rotation angle.\n")
.add_property("href", make_function(&PanoImage::getHRef,
return_value_policy<copy_const_reference>()), &PanoImage::setHRef)
.add_property("sensorwidth", &PanoImage::getSensorWidth,
&PanoImage::setSensorWidth)
.add_property("sensorheight", &PanoImage::getSensorHeight,
&PanoImage::setSensorHeight)
.add_property("focallength", &PanoImage::getFocalLength,
&PanoImage::setFocalLength)
.add_property("hue", &PanoImage::getHue)
.add_property("saturation", &PanoImage::getSaturation)
.add_property("rotation", &PanoImage::getRotation, &PanoImage::setRotation)
.add_property("maxrotation", &PanoImage::getMaxRotation)
;
}
<commit_msg>Exported Node::getRelPos functions.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2006 Ulrich von Zadow
//
// 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
void export_bitmap();
void export_raster();
void export_event();
#ifndef WIN32
void export_devices();
#endif
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../player/Player.h"
#include "../player/AVGNode.h"
#include "../player/DivNode.h"
#include "../player/PanoImage.h"
#include <boost/python.hpp>
#include <boost/version.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost::python;
using namespace avg;
void export_node()
{
class_<Node, boost::shared_ptr<Node>, boost::noncopyable>("Node",
"Base class for all elements in the avg tree.\n"
"Properties:\n"
" id: A unique identifier that can be used to reference the node (ro).\n"
" x: The position of the node's left edge relative to it's parent node.\n"
" y: The position of the node's top edge relative to it's parent node.\n"
" width\n"
" height\n"
" opacity: A measure of the node's transparency. 0.0 is completely\n"
" transparent, 1.0 is completely opaque. Opacity is relative to\n"
" the parent node's opacity.\n"
" active: If this attribute is true, the node behaves as usual. If not, it\n"
" is neither drawn nor does it react to events. Videos are paused.\n"
" sensitive: A node only reacts to events if sensitive is true.",
no_init)
.def("getParent", &Node::getParent,
"getParent() -> Node\n\n"
"Returns the container (AVGNode or DivNode) the node is in. For\n"
"the root node, returns None.\n")
.def("setEventCapture", &Node::setMouseEventCapture,
"setEventCapture() -> None\n\n")
.def("setEventCapture", &Node::setEventCapture,
"setEventCapture(CursorID) -> None\n\n"
"Sets up event capturing so that all mouse events are sent to this node\n"
"regardless of the mouse cursor position. If the node doesn't handle the\n"
"event, it propagates to its parent normally. Useful for the\n"
"implementation of user interface elements such as scroll bars. Only one\n"
"node can capture the mouse at any one time. Normal mouse operation can\n"
"be restored by calling releaseEventCapture().\n")
.def("releaseEventCapture", &Node::releaseMouseEventCapture,
"releaseEventCapture() -> None\n\n")
.def("releaseEventCapture", &Node::releaseEventCapture,
"releaseEventCapture() -> None\n\n"
"Restores normal nouse operation after a call to setEventCapture()\n")
.def("setEventHandler", &Node::setEventHandler,
"setEventHandler(Type, Source, pyfunc) -> None\n\n"
"Sets a callback function that is invoked whenever an event of the\n"
"specified Type from the specified Source occurs. This function is\n"
"similar to the event handler node attributes (e.g. oncursordown).\n"
"It is more specific since it takes the event source as a parameter\n"
"and allows the use of any python callable as callback function.\n")
.def("getRelXPos", &Node::getRelXPos,
"getRelXPos(absx) -> relx\n\n"
"Transforms an x-coordinate in screen coordinates to an x-coordinate\n"
"in coordinates relative to the node.\n")
.def("getRelYPos", &Node::getRelYPos,
"getRelYPos(absy) -> rely\n\n"
"Transforms an y-coordinate in screen coordinates to an y-coordinate\n"
"in coordinates relative to the node.\n")
.add_property("id", make_function(&Node::getID,
return_value_policy<copy_const_reference>()), &Node::setID)
.add_property("x", &Node::getX, &Node::setX)
.add_property("y", &Node::getY, &Node::setY)
.add_property("width", &Node::getWidth, &Node::setWidth)
.add_property("height", &Node::getHeight, &Node::setHeight)
.add_property("opacity", &Node::getOpacity, &Node::setOpacity)
.add_property("active", &Node::getActive, &Node::setActive)
.add_property("sensitive", &Node::getSensitive, &Node::setSensitive)
;
export_bitmap();
export_raster();
class_<DivNode, bases<Node>, boost::noncopyable>("DivNode",
"A div node is a node that groups other nodes logically and visually.\n"
"Its upper left corner is used as point of origin for the coordinates\n"
"of its child nodes. Its extents are used to clip the children. Its\n"
"opacity is used as base opacity for the child nodes' opacities.\n",
no_init)
.def("getNumChildren", &DivNode::getNumChildren,
"getNumChildren() -> numChildren\n\n")
.def("getChild", &DivNode::getChild,
"getChild(i) -> Node\n\n"
"Returns the ith child in z-order.")
.def("addChild", &DivNode::addChild,
"addChild(Node) -> None\n\n"
"Adds a new child to the container.")
.def("removeChild", &DivNode::removeChild,
"removeChild(i) -> None\n\n"
"Removes the child at index i.")
.def("indexOf", &DivNode::indexOf,
"indexOf(childNode) -> i\n\n"
"Returns the index of the child given or -1 if childNode isn't a\n"
"child of the container.")
;
class_<AVGNode, bases<DivNode> >("AVGNode",
"Root node of any avg tree. Defines the properties of the display and\n"
"handles key press events. The AVGNode's width and height define the\n"
"coordinate system for the display and are the default for the window\n"
"size used (i.e. by default, the coordinate system is pixel-based.)\n"
"Properties:\n"
" none\n",
no_init)
.def("getCropSetting", &AVGNode::getCropSetting,
"getCropSetting() -> isCropActive\n\n"
"Returns true if cropping is active. Cropping can be turned off globally\n"
"in the avg file. (Deprecated. This attribute is only nessesary because\n"
"of certain buggy display drivers that don't work with cropping.)")
;
class_<PanoImage, bases<Node> >("PanoImage",
"A panorama image.\n"
"Properties:\n"
" href: The source filename of the image.\n"
" sensorwidth: The width of the sensor used to make the image. This value\n"
" is used together with sensorheight and focallength to\n"
" determine the projection to use. (ro)\n"
" sensorheight: The height of the sensor used to make the image. (ro)\n"
" focallength: The focal length of the lens in millimeters. (ro)\n"
" hue: A hue to color the image in. (ro, deprecated)\n"
" saturation: The saturation the image should have. (ro, deprecated)\n"
" rotation: The current angle the viewer is looking at in radians.\n"
" maxrotation: The maximum angle the viewer can look at.\n",
no_init)
.def("getScreenPosFromPanoPos", &PanoImage::getScreenPosFromPanoPos,
"getScreenPosFromPanoPos(panoPos) -> pos\n\n"
"Converts a position in panorama image pixels to pixels in coordinates\n"
"relative to the node, taking into account the current rotation angle.\n")
.def("getScreenPosFromAngle", &PanoImage::getScreenPosFromAngle,
"getScreenPosFromAngle(angle) -> pos\n\n"
"Converts panorama angle to pixels in coordinates\n"
"relative to the node, taking into account the current rotation angle.\n")
.add_property("href", make_function(&PanoImage::getHRef,
return_value_policy<copy_const_reference>()), &PanoImage::setHRef)
.add_property("sensorwidth", &PanoImage::getSensorWidth,
&PanoImage::setSensorWidth)
.add_property("sensorheight", &PanoImage::getSensorHeight,
&PanoImage::setSensorHeight)
.add_property("focallength", &PanoImage::getFocalLength,
&PanoImage::setFocalLength)
.add_property("hue", &PanoImage::getHue)
.add_property("saturation", &PanoImage::getSaturation)
.add_property("rotation", &PanoImage::getRotation, &PanoImage::setRotation)
.add_property("maxrotation", &PanoImage::getMaxRotation)
;
}
<|endoftext|>
|
<commit_before>#include "Script.hpp"
using namespace TurtlebotLibrary;
Script::Script(uint8_t scriptLength) : TurtlebotMessage(TurtlebotCommandCode::Script)
{
// should
this->scriptLength = scriptLength;
}
Script::~Script()
{
}
uint8_t Script::getScriptLength() const
{
return this->scriptLength;
}
void Script::setScriptLength(uint8_t scriptLength)
{
this->scriptLength = scriptLength;
}
void Script::addCommand(TurtlebotMessage *msg)
{
commandVector.push_back(msg);
}
std::vector<TurtlebotMessage*> Script::getCommandVector()
{
return this->commandVector;
}
std::vector<uint8_t> Script::SerializePayload()
{
std::vector<uint8_t> payload = { this->scriptLength };
for (int i = 0; i < this->commandVector.size(); i++) {
std::vector<uint8_t> currCommandPayload = this->commandVector[i]->Serialize();
for (int j = 0; j < currCommandPayload.size(); j++) {
payload.push_back(currCommandPayload[i]);
}
}
return payload;
}<commit_msg>added script class to nativelibrary, this allows scripts to be sent, thursday must make wrapper and test, did it again because i am a dumbass and forgot to save<commit_after>#include "Script.hpp"
using namespace TurtlebotLibrary;
Script::Script(uint8_t scriptLength) : TurtlebotMessage(TurtlebotCommandCode::Script)
{
// should
this->scriptLength = scriptLength;
}
Script::~Script()
{
}
uint8_t Script::GetScriptLength() const
{
return this->scriptLength;
}
void Script::SetScriptLength(uint8_t scriptLength)
{
this->scriptLength = scriptLength;
}
void Script::AddCommand(TurtlebotMessage *msg)
{
commandVector.push_back(msg);
}
std::vector<TurtlebotMessage*> Script::GetCommandVector()
{
return this->commandVector;
}
std::vector<uint8_t> Script::SerializePayload()
{
std::vector<uint8_t> payload = { this->scriptLength };
for (int i = 0; i < this->commandVector.size(); i++) {
std::vector<uint8_t> currCommandPayload = this->commandVector[i]->Serialize();
for (int j = 0; j < currCommandPayload.size(); j++) {
payload.push_back(currCommandPayload[i]);
}
}
return payload;
}<|endoftext|>
|
<commit_before>/*
* File: Assets.cpp
* Author: morgan
*
* Created on February 25, 2014, 6:38 PM
*/
#include "assets.hpp"
#include <rapidxml.hpp>
#include <rapidxml_utils.hpp>
#include <lodepng.h>
#include <objload.h>
#include <exception>
#include <memory>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <stb_vorbis.h>
#include <glm/gtx/io.hpp>
namespace mo {
using namespace std;
using namespace glm;
Assets::Assets(const std::string directory) :
directory_(directory) {
}
Assets::~Assets() {
}
std::shared_ptr<Mesh> Assets::mesh(const std::string file_name) const {
vector<mo::Vertex> vertices;
vector<int> indices;
if (file_name.substr(file_name.find_last_of(".") + 1) == "mesh") {
std::cout << "Loading: " << file_name << std::endl;
std::ifstream is(directory_ + file_name, ios::binary);
int num_vertices;
int num_indices;
is.read((char*) &num_vertices, sizeof (int));
is.read((char*) &num_indices, sizeof (int));
vertices = vector<mo::Vertex>(num_vertices);
indices = vector<int>(num_indices);
if (vertices.size() > 0){
is.read((char*)&vertices[0], vertices.size() * sizeof(Vertex));
}
if (indices.size() > 0) {
is.read((char*)&indices[0], indices.size() * sizeof(int));
}
} else {
std::cout << "Loading: " << directory_ << file_name;
obj::Model obj_model = obj::loadModelFromFile(directory_ + file_name);
int j = 0;
for (int i = 0; i < obj_model.vertex.size(); i += 3) {
glm::vec3 position(obj_model.vertex[i], obj_model.vertex[i + 1], obj_model.vertex[i + 2]);
glm::vec3 normal(obj_model.normal[i], obj_model.normal[i + 1], obj_model.normal[i + 2]);
glm::vec2 uv(0.0f, 0.0f);
if (obj_model.texCoord.size() > 0) {
uv.x = obj_model.texCoord[j];
uv.y = obj_model.texCoord[j + 1];
}
j += 2;
vertices.push_back(Vertex(position, normal, uv));
}
indices.assign(obj_model.faces.find("default")->second.begin(),
obj_model.faces.find("default")->second.end());
}
return std::make_shared<Mesh>(vertices.begin(),
vertices.end(),
indices.begin(),
indices.end());
}
std::shared_ptr<Mesh> Assets::mesh_cached(const std::string file_name) {
if (meshes_.find(file_name) == meshes_.end()) {
meshes_.insert(MeshPair(file_name, mesh(file_name)));
}
return meshes_.at(file_name);
}
std::shared_ptr<Texture2D> Assets::texture(const std::string file_name, const bool mipmaps) const {
using namespace mo;
vector<unsigned char> texels_decoded;
unsigned width, height;
std::cout << "Loading: " << directory_ + file_name << std::endl;
auto error = lodepng::decode(texels_decoded, width, height, directory_ + file_name);
if (error) {
std::cout << "Decoder error: " << error << ": " << lodepng_error_text(error) << std::endl;
}
return std::make_shared<Texture2D>(texels_decoded.begin(), texels_decoded.end(), width, height, mipmaps);
}
std::shared_ptr<Texture2D> Assets::texture_cached(const std::string file_name, const bool mipmaps) {
if (!file_name.empty()) {
if (textures_.find(file_name) == textures_.end()) {
textures_.insert(TexturePair(file_name, texture(file_name, mipmaps)));
}
return textures_.at(file_name);
}
else {
return std::shared_ptr<Texture2D>(nullptr);
}
}
std::shared_ptr<Sound> Assets::sound(const std::string file_name) const {
int channels, length;
short * decoded;
std::ifstream file(directory_ + file_name, std::ios::binary);
std::vector<unsigned char> data;
unsigned char c;
while (file.read(reinterpret_cast<char*> (&c), sizeof (c))) {
data.push_back(c);
}
length = stb_vorbis_decode_memory(data.data(), data.size(), &channels, &decoded);
return std::make_shared<Sound>(decoded, decoded + length);
}
std::shared_ptr<Stream> Assets::stream(const string file_name) const {
return std::make_shared<mo::Stream>(directory_ + file_name);
}
std::shared_ptr<Sound> Assets::sound_cached(const std::string file_name) {
if (sounds_.find(file_name) == sounds_.end()) {
sounds_.insert(SoundPair(file_name, sound(file_name)));
return sounds_.at(file_name);
} else {
return sounds_.at(file_name);
}
}
std::shared_ptr<Material> Assets::material(const std::string file_name) const{
if (file_name.substr(file_name.find_last_of(".") + 1) == "material") {
std::cout << "Loading: " << directory_ + file_name << std::endl;
std::ifstream is(directory_ + file_name, ios::binary);
glm::vec3 ambient;
glm::vec3 diffuse;
glm::vec3 specular;
float opacity;
float specular_exponent;
is.read((char*) &ambient, sizeof (glm::vec3));
is.read((char*) &diffuse, sizeof (glm::vec3));
is.read((char*) &specular, sizeof (glm::vec3));
is.read((char*) &opacity, sizeof (float));
is.read((char*) &specular_exponent, sizeof (float));
return std::make_shared<Material>(ambient, diffuse, specular,
opacity, specular_exponent);
} else {
//TODO: parse obj material
/*
std::vector<tinyobj::material_t> materials;
std::vector<tinyobj::shape_t> shapes;
auto path = directory_ + file_name;
std::string err = tinyobj::LoadObj(shapes, materials, path.c_str());
if (!err.empty()) {
std::cerr << err << std::endl;
throw std::runtime_error("Error reading obj file.");
}
auto m = materials.front();
Material material(glm::vec3(m.ambient[0], m.ambient[1], m.ambient[2]),
glm::vec3(m.diffuse[0], m.diffuse[1], m.diffuse[2]),
glm::vec3(m.specular[0], m.specular[1], m.specular[2]));
return std::make_shared<Material>(material);
*/
}
}
std::shared_ptr<Material> Assets::material_cached(const std::string file_name) {
if (materials_.find(file_name) == materials_.end()) {
materials_.insert(MaterialPair(file_name, material(file_name)));
return materials_.at(file_name);
} else {
return materials_.at(file_name);
}
}
std::string Assets::text(const std::string file_name) const {
std::ifstream file(directory_ + file_name);
std::string source((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
return source;
}
std::map<char, Character> Assets::character_map(std::string file_name) {
std::map<char, Character> characters;
rapidxml::xml_document<> doc;
auto str = text(file_name);
char* cstr = new char[str.size() + 1]; // Create char buffer to store string copy
std::strcpy(cstr, str.c_str());
doc.parse<0>(cstr);
rapidxml::xml_node<> * chars_node = doc.first_node("font")->first_node("chars");
for (rapidxml::xml_node<> * char_node = chars_node->first_node("char");
char_node;
char_node = char_node->next_sibling()) {
Character character;
rapidxml::xml_attribute<> *attr = char_node->first_attribute();
character.offset_x = atof(attr->value());
attr = attr->next_attribute();
character.offset_y = atof(attr->value());
attr = attr->next_attribute();
character.advance = atof(attr->value());
attr = attr->next_attribute();
character.rect_w = atof(attr->value());
attr = attr->next_attribute();
character.id = *attr->value();
attr = attr->next_attribute();
character.rect_x = atof(attr->value());
attr = attr->next_attribute();
character.rect_y = atof(attr->value());
attr = attr->next_attribute();
character.rect_h = atof(attr->value());
characters.insert(std::pair<char, Character>(character.id, character));
}
delete [] cstr;
return characters;
}
}
<commit_msg>Error checking.W<commit_after>/*
* File: Assets.cpp
* Author: morgan
*
* Created on February 25, 2014, 6:38 PM
*/
#include "assets.hpp"
#include <rapidxml.hpp>
#include <rapidxml_utils.hpp>
#include <lodepng.h>
#include <objload.h>
#include <exception>
#include <memory>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <stb_vorbis.h>
#include <glm/gtx/io.hpp>
namespace mo {
using namespace std;
using namespace glm;
Assets::Assets(const std::string directory) :
directory_(directory) {
}
Assets::~Assets() {
}
std::shared_ptr<Mesh> Assets::mesh(const std::string file_name) const {
vector<mo::Vertex> vertices;
vector<int> indices;
if (file_name.substr(file_name.find_last_of(".") + 1) == "mesh") {
std::cout << "Loading: " << file_name << std::endl;
std::ifstream is(directory_ + file_name, ios::binary);
if (!is.good()){
throw std::runtime_error(directory_ + file_name + " does not exist.");
}
int num_vertices;
int num_indices;
is.read((char*) &num_vertices, sizeof (int));
is.read((char*) &num_indices, sizeof (int));
vertices = vector<mo::Vertex>(num_vertices);
indices = vector<int>(num_indices);
if (vertices.size() > 0){
is.read((char*)&vertices[0], vertices.size() * sizeof(Vertex));
}
if (indices.size() > 0) {
is.read((char*)&indices[0], indices.size() * sizeof(int));
}
} else {
std::cout << "Loading: " << directory_ << file_name;
obj::Model obj_model = obj::loadModelFromFile(directory_ + file_name);
int j = 0;
for (int i = 0; i < obj_model.vertex.size(); i += 3) {
glm::vec3 position(obj_model.vertex[i], obj_model.vertex[i + 1], obj_model.vertex[i + 2]);
glm::vec3 normal(obj_model.normal[i], obj_model.normal[i + 1], obj_model.normal[i + 2]);
glm::vec2 uv(0.0f, 0.0f);
if (obj_model.texCoord.size() > 0) {
uv.x = obj_model.texCoord[j];
uv.y = obj_model.texCoord[j + 1];
}
j += 2;
vertices.push_back(Vertex(position, normal, uv));
}
indices.assign(obj_model.faces.find("default")->second.begin(),
obj_model.faces.find("default")->second.end());
}
return std::make_shared<Mesh>(vertices.begin(),
vertices.end(),
indices.begin(),
indices.end());
}
std::shared_ptr<Mesh> Assets::mesh_cached(const std::string file_name) {
if (meshes_.find(file_name) == meshes_.end()) {
meshes_.insert(MeshPair(file_name, mesh(file_name)));
}
return meshes_.at(file_name);
}
std::shared_ptr<Texture2D> Assets::texture(const std::string file_name, const bool mipmaps) const {
using namespace mo;
vector<unsigned char> texels_decoded;
unsigned width, height;
std::cout << "Loading: " << directory_ + file_name << std::endl;
auto error = lodepng::decode(texels_decoded, width, height, directory_ + file_name);
if (error) {
std::cout << "Decoder error: " << error << ": " << lodepng_error_text(error) << std::endl;
}
return std::make_shared<Texture2D>(texels_decoded.begin(), texels_decoded.end(), width, height, mipmaps);
}
std::shared_ptr<Texture2D> Assets::texture_cached(const std::string file_name, const bool mipmaps) {
if (!file_name.empty()) {
if (textures_.find(file_name) == textures_.end()) {
textures_.insert(TexturePair(file_name, texture(file_name, mipmaps)));
}
return textures_.at(file_name);
}
else {
return std::shared_ptr<Texture2D>(nullptr);
}
}
std::shared_ptr<Sound> Assets::sound(const std::string file_name) const {
int channels, length;
short * decoded;
std::ifstream file(directory_ + file_name, std::ios::binary);
std::vector<unsigned char> data;
unsigned char c;
while (file.read(reinterpret_cast<char*> (&c), sizeof (c))) {
data.push_back(c);
}
length = stb_vorbis_decode_memory(data.data(), data.size(), &channels, &decoded);
return std::make_shared<Sound>(decoded, decoded + length);
}
std::shared_ptr<Stream> Assets::stream(const string file_name) const {
return std::make_shared<mo::Stream>(directory_ + file_name);
}
std::shared_ptr<Sound> Assets::sound_cached(const std::string file_name) {
if (sounds_.find(file_name) == sounds_.end()) {
sounds_.insert(SoundPair(file_name, sound(file_name)));
return sounds_.at(file_name);
} else {
return sounds_.at(file_name);
}
}
std::shared_ptr<Material> Assets::material(const std::string file_name) const{
if (file_name.substr(file_name.find_last_of(".") + 1) == "material") {
std::cout << "Loading: " << directory_ + file_name << std::endl;
std::ifstream is(directory_ + file_name, ios::binary);
glm::vec3 ambient;
glm::vec3 diffuse;
glm::vec3 specular;
float opacity;
float specular_exponent;
is.read((char*) &ambient, sizeof (glm::vec3));
is.read((char*) &diffuse, sizeof (glm::vec3));
is.read((char*) &specular, sizeof (glm::vec3));
is.read((char*) &opacity, sizeof (float));
is.read((char*) &specular_exponent, sizeof (float));
return std::make_shared<Material>(ambient, diffuse, specular,
opacity, specular_exponent);
} else {
//TODO: parse obj material
/*
std::vector<tinyobj::material_t> materials;
std::vector<tinyobj::shape_t> shapes;
auto path = directory_ + file_name;
std::string err = tinyobj::LoadObj(shapes, materials, path.c_str());
if (!err.empty()) {
std::cerr << err << std::endl;
throw std::runtime_error("Error reading obj file.");
}
auto m = materials.front();
Material material(glm::vec3(m.ambient[0], m.ambient[1], m.ambient[2]),
glm::vec3(m.diffuse[0], m.diffuse[1], m.diffuse[2]),
glm::vec3(m.specular[0], m.specular[1], m.specular[2]));
return std::make_shared<Material>(material);
*/
}
}
std::shared_ptr<Material> Assets::material_cached(const std::string file_name) {
if (materials_.find(file_name) == materials_.end()) {
materials_.insert(MaterialPair(file_name, material(file_name)));
return materials_.at(file_name);
} else {
return materials_.at(file_name);
}
}
std::string Assets::text(const std::string file_name) const {
std::ifstream file(directory_ + file_name);
std::string source((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
return source;
}
std::map<char, Character> Assets::character_map(std::string file_name) {
std::map<char, Character> characters;
rapidxml::xml_document<> doc;
auto str = text(file_name);
char* cstr = new char[str.size() + 1]; // Create char buffer to store string copy
std::strcpy(cstr, str.c_str());
doc.parse<0>(cstr);
rapidxml::xml_node<> * chars_node = doc.first_node("font")->first_node("chars");
for (rapidxml::xml_node<> * char_node = chars_node->first_node("char");
char_node;
char_node = char_node->next_sibling()) {
Character character;
rapidxml::xml_attribute<> *attr = char_node->first_attribute();
character.offset_x = atof(attr->value());
attr = attr->next_attribute();
character.offset_y = atof(attr->value());
attr = attr->next_attribute();
character.advance = atof(attr->value());
attr = attr->next_attribute();
character.rect_w = atof(attr->value());
attr = attr->next_attribute();
character.id = *attr->value();
attr = attr->next_attribute();
character.rect_x = atof(attr->value());
attr = attr->next_attribute();
character.rect_y = atof(attr->value());
attr = attr->next_attribute();
character.rect_h = atof(attr->value());
characters.insert(std::pair<char, Character>(character.id, character));
}
delete [] cstr;
return characters;
}
}
<|endoftext|>
|
<commit_before>// 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 "base/debug/stack_trace.h"
#include <errno.h>
#include <execinfo.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <vector>
#if defined(__GLIBCXX__)
#include <cxxabi.h>
#endif
#if defined(OS_MACOSX)
#include <AvailabilityMacros.h>
#endif
#include "base/basictypes.h"
#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/safe_strerror_posix.h"
#include "base/string_piece.h"
#include "base/stringprintf.h"
#if defined(USE_SYMBOLIZE)
#include "base/third_party/symbolize/symbolize.h"
#endif
namespace base {
namespace debug {
namespace {
// The prefix used for mangled symbols, per the Itanium C++ ABI:
// http://www.codesourcery.com/cxx-abi/abi.html#mangling
const char kMangledSymbolPrefix[] = "_Z";
// Characters that can be used for symbols, generated by Ruby:
// (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
const char kSymbolCharacters[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
#if !defined(USE_SYMBOLIZE)
// Demangles C++ symbols in the given text. Example:
//
// "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
// =>
// "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
void DemangleSymbols(std::string* text) {
#if defined(__GLIBCXX__)
std::string::size_type search_from = 0;
while (search_from < text->size()) {
// Look for the start of a mangled symbol, from search_from.
std::string::size_type mangled_start =
text->find(kMangledSymbolPrefix, search_from);
if (mangled_start == std::string::npos) {
break; // Mangled symbol not found.
}
// Look for the end of the mangled symbol.
std::string::size_type mangled_end =
text->find_first_not_of(kSymbolCharacters, mangled_start);
if (mangled_end == std::string::npos) {
mangled_end = text->size();
}
std::string mangled_symbol =
text->substr(mangled_start, mangled_end - mangled_start);
// Try to demangle the mangled symbol candidate.
int status = 0;
scoped_ptr_malloc<char> demangled_symbol(
abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
if (status == 0) { // Demangling is successful.
// Remove the mangled symbol.
text->erase(mangled_start, mangled_end - mangled_start);
// Insert the demangled symbol.
text->insert(mangled_start, demangled_symbol.get());
// Next time, we'll start right after the demangled symbol we inserted.
search_from = mangled_start + strlen(demangled_symbol.get());
} else {
// Failed to demangle. Retry after the "_Z" we just found.
search_from = mangled_start + 2;
}
}
#endif // defined(__GLIBCXX__)
}
#endif // !defined(USE_SYMBOLIZE)
// Gets the backtrace as a vector of strings. If possible, resolve symbol
// names and attach these. Otherwise just use raw addresses. Returns true
// if any symbol name is resolved. Returns false on error and *may* fill
// in |error_message| if an error message is available.
bool GetBacktraceStrings(void *const *trace, int size,
std::vector<std::string>* trace_strings,
std::string* error_message) {
bool symbolized = false;
#if defined(USE_SYMBOLIZE)
for (int i = 0; i < size; ++i) {
char symbol[1024];
// Subtract by one as return address of function may be in the next
// function when a function is annotated as noreturn.
if (google::Symbolize(static_cast<char *>(trace[i]) - 1,
symbol, sizeof(symbol))) {
// Don't call DemangleSymbols() here as the symbol is demangled by
// google::Symbolize().
trace_strings->push_back(
base::StringPrintf("%s [%p]", symbol, trace[i]));
symbolized = true;
} else {
trace_strings->push_back(base::StringPrintf("%p", trace[i]));
}
}
#else
scoped_ptr_malloc<char*> trace_symbols(backtrace_symbols(trace, size));
if (trace_symbols.get()) {
for (int i = 0; i < size; ++i) {
std::string trace_symbol = trace_symbols.get()[i];
DemangleSymbols(&trace_symbol);
trace_strings->push_back(trace_symbol);
}
symbolized = true;
} else {
if (error_message)
*error_message = safe_strerror(errno);
for (int i = 0; i < size; ++i) {
trace_strings->push_back(base::StringPrintf("%p", trace[i]));
}
}
#endif // defined(USE_SYMBOLIZE)
return symbolized;
}
} // namespace
StackTrace::StackTrace() {
#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
if (backtrace == NULL) {
count_ = 0;
return;
}
#endif
// Though the backtrace API man page does not list any possible negative
// return values, we take no chance.
count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);
}
void StackTrace::PrintBacktrace() const {
#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
if (backtrace_symbols_fd == NULL)
return;
#endif
fflush(stderr);
std::vector<std::string> trace_strings;
GetBacktraceStrings(trace_, count_, &trace_strings, NULL);
for (size_t i = 0; i < trace_strings.size(); ++i) {
fprintf(stderr, "\t%s\n", trace_strings[i].c_str());
}
}
void StackTrace::OutputToStream(std::ostream* os) const {
#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
if (backtrace_symbols == NULL)
return;
#endif
std::vector<std::string> trace_strings;
std::string error_message;
if (GetBacktraceStrings(trace_, count_, &trace_strings, &error_message)) {
(*os) << "Backtrace:\n";
} else {
if (!error_message.empty())
error_message = " (" + error_message + ")";
(*os) << "Unable to get symbols for backtrace" << error_message << ". "
<< "Dumping raw addresses in trace:\n";
}
for (size_t i = 0; i < trace_strings.size(); ++i) {
(*os) << "\t" << trace_strings[i] << "\n";
}
}
} // namespace debug
} // namespace base
<commit_msg>mac: Delete some pre-10.5 code.<commit_after>// 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 "base/debug/stack_trace.h"
#include <errno.h>
#include <execinfo.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <vector>
#if defined(__GLIBCXX__)
#include <cxxabi.h>
#endif
#if defined(OS_MACOSX)
#include <AvailabilityMacros.h>
#endif
#include "base/basictypes.h"
#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/safe_strerror_posix.h"
#include "base/string_piece.h"
#include "base/stringprintf.h"
#if defined(USE_SYMBOLIZE)
#include "base/third_party/symbolize/symbolize.h"
#endif
namespace base {
namespace debug {
namespace {
// The prefix used for mangled symbols, per the Itanium C++ ABI:
// http://www.codesourcery.com/cxx-abi/abi.html#mangling
const char kMangledSymbolPrefix[] = "_Z";
// Characters that can be used for symbols, generated by Ruby:
// (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
const char kSymbolCharacters[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
#if !defined(USE_SYMBOLIZE)
// Demangles C++ symbols in the given text. Example:
//
// "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
// =>
// "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
void DemangleSymbols(std::string* text) {
#if defined(__GLIBCXX__)
std::string::size_type search_from = 0;
while (search_from < text->size()) {
// Look for the start of a mangled symbol, from search_from.
std::string::size_type mangled_start =
text->find(kMangledSymbolPrefix, search_from);
if (mangled_start == std::string::npos) {
break; // Mangled symbol not found.
}
// Look for the end of the mangled symbol.
std::string::size_type mangled_end =
text->find_first_not_of(kSymbolCharacters, mangled_start);
if (mangled_end == std::string::npos) {
mangled_end = text->size();
}
std::string mangled_symbol =
text->substr(mangled_start, mangled_end - mangled_start);
// Try to demangle the mangled symbol candidate.
int status = 0;
scoped_ptr_malloc<char> demangled_symbol(
abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
if (status == 0) { // Demangling is successful.
// Remove the mangled symbol.
text->erase(mangled_start, mangled_end - mangled_start);
// Insert the demangled symbol.
text->insert(mangled_start, demangled_symbol.get());
// Next time, we'll start right after the demangled symbol we inserted.
search_from = mangled_start + strlen(demangled_symbol.get());
} else {
// Failed to demangle. Retry after the "_Z" we just found.
search_from = mangled_start + 2;
}
}
#endif // defined(__GLIBCXX__)
}
#endif // !defined(USE_SYMBOLIZE)
// Gets the backtrace as a vector of strings. If possible, resolve symbol
// names and attach these. Otherwise just use raw addresses. Returns true
// if any symbol name is resolved. Returns false on error and *may* fill
// in |error_message| if an error message is available.
bool GetBacktraceStrings(void *const *trace, int size,
std::vector<std::string>* trace_strings,
std::string* error_message) {
bool symbolized = false;
#if defined(USE_SYMBOLIZE)
for (int i = 0; i < size; ++i) {
char symbol[1024];
// Subtract by one as return address of function may be in the next
// function when a function is annotated as noreturn.
if (google::Symbolize(static_cast<char *>(trace[i]) - 1,
symbol, sizeof(symbol))) {
// Don't call DemangleSymbols() here as the symbol is demangled by
// google::Symbolize().
trace_strings->push_back(
base::StringPrintf("%s [%p]", symbol, trace[i]));
symbolized = true;
} else {
trace_strings->push_back(base::StringPrintf("%p", trace[i]));
}
}
#else
scoped_ptr_malloc<char*> trace_symbols(backtrace_symbols(trace, size));
if (trace_symbols.get()) {
for (int i = 0; i < size; ++i) {
std::string trace_symbol = trace_symbols.get()[i];
DemangleSymbols(&trace_symbol);
trace_strings->push_back(trace_symbol);
}
symbolized = true;
} else {
if (error_message)
*error_message = safe_strerror(errno);
for (int i = 0; i < size; ++i) {
trace_strings->push_back(base::StringPrintf("%p", trace[i]));
}
}
#endif // defined(USE_SYMBOLIZE)
return symbolized;
}
} // namespace
StackTrace::StackTrace() {
// Though the backtrace API man page does not list any possible negative
// return values, we take no chance.
count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);
}
void StackTrace::PrintBacktrace() const {
fflush(stderr);
std::vector<std::string> trace_strings;
GetBacktraceStrings(trace_, count_, &trace_strings, NULL);
for (size_t i = 0; i < trace_strings.size(); ++i) {
fprintf(stderr, "\t%s\n", trace_strings[i].c_str());
}
}
void StackTrace::OutputToStream(std::ostream* os) const {
std::vector<std::string> trace_strings;
std::string error_message;
if (GetBacktraceStrings(trace_, count_, &trace_strings, &error_message)) {
(*os) << "Backtrace:\n";
} else {
if (!error_message.empty())
error_message = " (" + error_message + ")";
(*os) << "Unable to get symbols for backtrace" << error_message << ". "
<< "Dumping raw addresses in trace:\n";
}
for (size_t i = 0; i < trace_strings.size(); ++i) {
(*os) << "\t" << trace_strings[i] << "\n";
}
}
} // namespace debug
} // namespace base
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#include "runtime/hdfs-fs-cache.h"
#include <boost/thread/locks.hpp>
#include <glog/logging.h>
using namespace boost;
DEFINE_string(nn, "localhost", "namenode host");
DEFINE_int32(nn_port, 20500, "namenode port");
namespace impala {
HdfsFsCache::~HdfsFsCache() {
for (HdfsFsMap::iterator i = fs_map_.begin(); i != fs_map_.end(); ++i) {
int status = hdfsDisconnect(i->second);
if (status != 0) {
// TODO: add error details
LOG(ERROR) << "hdfsDisconnect(\"" << i->first.first << "\", " << i->first.second
<< ") failed: " << " Error(" << errno << "): " << strerror(errno);
}
}
}
hdfsFS HdfsFsCache::GetConnection(const std::string& host, int port) {
lock_guard<mutex> l(lock_);
HdfsFsMap::iterator i = fs_map_.find(make_pair(host, port));
if (i == fs_map_.end()) {
hdfsFS conn = hdfsConnect(host.c_str(), port);
DCHECK(conn != NULL);
fs_map_.insert(make_pair(make_pair(host, port), conn));
return conn;
} else {
return i->second;
}
}
hdfsFS HdfsFsCache::GetDefaultConnection() {
return GetConnection(FLAGS_nn, FLAGS_nn_port);
}
}
<commit_msg>fixing Jenkins build failure<commit_after>// Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#include "runtime/hdfs-fs-cache.h"
#include <boost/thread/locks.hpp>
#include <glog/logging.h>
#include <gflags/gflags.h>
using namespace boost;
DEFINE_string(nn, "localhost", "namenode host");
DEFINE_int32(nn_port, 20500, "namenode port");
namespace impala {
HdfsFsCache::~HdfsFsCache() {
for (HdfsFsMap::iterator i = fs_map_.begin(); i != fs_map_.end(); ++i) {
int status = hdfsDisconnect(i->second);
if (status != 0) {
// TODO: add error details
LOG(ERROR) << "hdfsDisconnect(\"" << i->first.first << "\", " << i->first.second
<< ") failed: " << " Error(" << errno << "): " << strerror(errno);
}
}
}
hdfsFS HdfsFsCache::GetConnection(const std::string& host, int port) {
lock_guard<mutex> l(lock_);
HdfsFsMap::iterator i = fs_map_.find(make_pair(host, port));
if (i == fs_map_.end()) {
hdfsFS conn = hdfsConnect(host.c_str(), port);
DCHECK(conn != NULL);
fs_map_.insert(make_pair(make_pair(host, port), conn));
return conn;
} else {
return i->second;
}
}
hdfsFS HdfsFsCache::GetDefaultConnection() {
return GetConnection(FLAGS_nn, FLAGS_nn_port);
}
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 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 <iostream>
#include <chrono>
#include <random>
#include "etl/etl.hpp"
#define CPM_NO_RANDOMIZATION //Randomly initialize only once
#define CPM_AUTO_STEPS //Enable steps estimation system
#define CPM_STEP_ESTIMATION_MIN 0.05 //Run during 0.05 seconds for estimating steps
#define CPM_RUNTIME_TARGET 1.0 //Run each test during 1.0 seconds
#include "cpm/cpm.hpp"
#ifdef ETL_VECTORIZE_IMPL
#ifdef __SSE3__
#define TEST_SSE
#endif
#ifdef __AVX__
#define TEST_AVX
#endif
#endif
#ifdef ETL_MKL_MODE
#define TEST_MKL
#endif
#ifdef ETL_CUBLAS_MODE
#define TEST_CUBLAS
#endif
#ifdef ETL_CUFFT_MODE
#define TEST_CUFFT
#endif
#ifdef ETL_BLAS_MODE
#define TEST_BLAS
#endif
#ifdef ETL_BENCH_STRASSEN
#define TEST_STRASSEN
#endif
#ifdef ETL_BENCH_MMUL_CONV
#define TEST_MMUL_CONV
#endif
using smat_cm = etl::dyn_matrix_cm<float>;
using dmat_cm = etl::dyn_matrix_cm<double>;
using cmat_cm = etl::dyn_matrix_cm<std::complex<float>>;
using zmat_cm = etl::dyn_matrix_cm<std::complex<double>>;
using dvec = etl::dyn_vector<double>;
using dmat = etl::dyn_matrix<double>;
using dmat2 = etl::dyn_matrix<double, 2>;
using dmat3 = etl::dyn_matrix<double, 3>;
using dmat4 = etl::dyn_matrix<double, 4>;
using svec = etl::dyn_vector<float>;
using smat = etl::dyn_matrix<float>;
using cvec = etl::dyn_vector<std::complex<float>>;
using cmat = etl::dyn_matrix<std::complex<float>>;
using zvec = etl::dyn_vector<std::complex<double>>;
using zmat = etl::dyn_matrix<std::complex<double>>;
using mat_policy = VALUES_POLICY(10, 25, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000,3000,4000,8000);
using mat_policy_2d = NARY_POLICY(mat_policy, mat_policy);
using conv_1d_large_policy = NARY_POLICY(VALUES_POLICY(1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), VALUES_POLICY(500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000));
using conv_2d_large_policy = NARY_POLICY(VALUES_POLICY(100, 105, 110, 115, 120, 125, 130, 135, 140), VALUES_POLICY(50, 50, 55, 55, 60, 60, 65, 65, 70));
using fft_1d_policy = VALUES_POLICY(10, 100, 1000, 10000, 100000, 500000);
using fft_1d_policy_2 = VALUES_POLICY(16, 64, 256, 1024, 16384, 131072, 1048576, 2097152);
using fft_1d_many_policy = VALUES_POLICY(10, 50, 100, 500, 1000, 5000, 10000);
using fft_2d_policy = NARY_POLICY(
VALUES_POLICY(8, 16, 32, 64, 128, 256, 512, 1024, 2048),
VALUES_POLICY(8, 16, 32, 64, 128, 256, 512, 1024, 2048));
using sigmoid_policy = VALUES_POLICY(250, 500, 750, 1000, 1250, 1500, 1750, 2000);
using small_square_policy = NARY_POLICY(VALUES_POLICY(50, 100, 150, 200, 250, 300, 350, 400, 450, 500), VALUES_POLICY(50, 100, 150, 200, 250, 300, 350, 400, 450, 500));
using square_policy = NARY_POLICY(VALUES_POLICY(50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000), VALUES_POLICY(50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000));
using gemv_policy = NARY_POLICY(
VALUES_POLICY(250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000),
VALUES_POLICY(250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000));
using trans_sub_policy = VALUES_POLICY(100, 200, 300, 400, 500, 600, 700, 800, 900, 1000);
using trans_policy = NARY_POLICY(
VALUES_POLICY(100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600, 700, 700, 800, 800, 900, 900, 1000, 1000),
VALUES_POLICY(100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600, 700, 700, 800, 800, 900, 900, 1000, 1000, 1100));
#ifdef TEST_SSE
#define SSE_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define SSE_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_AVX
#define AVX_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define AVX_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_MKL
#define MKL_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define MKL_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_BLAS
#define BLAS_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define BLAS_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_CUBLAS
#define CUBLAS_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define CUBLAS_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_CUFFT
#define CUFFT_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define CUFFT_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_MMUL_CONV
#define MC_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define MC_SECTION_FUNCTOR(name, ...)
#endif
<commit_msg>Reduce maximum size of matrix<commit_after>//=======================================================================
// Copyright (c) 2014-2016 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 <iostream>
#include <chrono>
#include <random>
#include "etl/etl.hpp"
#define CPM_NO_RANDOMIZATION //Randomly initialize only once
#define CPM_AUTO_STEPS //Enable steps estimation system
#define CPM_STEP_ESTIMATION_MIN 0.05 //Run during 0.05 seconds for estimating steps
#define CPM_RUNTIME_TARGET 1.0 //Run each test during 1.0 seconds
#include "cpm/cpm.hpp"
#ifdef ETL_VECTORIZE_IMPL
#ifdef __SSE3__
#define TEST_SSE
#endif
#ifdef __AVX__
#define TEST_AVX
#endif
#endif
#ifdef ETL_MKL_MODE
#define TEST_MKL
#endif
#ifdef ETL_CUBLAS_MODE
#define TEST_CUBLAS
#endif
#ifdef ETL_CUFFT_MODE
#define TEST_CUFFT
#endif
#ifdef ETL_BLAS_MODE
#define TEST_BLAS
#endif
#ifdef ETL_BENCH_STRASSEN
#define TEST_STRASSEN
#endif
#ifdef ETL_BENCH_MMUL_CONV
#define TEST_MMUL_CONV
#endif
using smat_cm = etl::dyn_matrix_cm<float>;
using dmat_cm = etl::dyn_matrix_cm<double>;
using cmat_cm = etl::dyn_matrix_cm<std::complex<float>>;
using zmat_cm = etl::dyn_matrix_cm<std::complex<double>>;
using dvec = etl::dyn_vector<double>;
using dmat = etl::dyn_matrix<double>;
using dmat2 = etl::dyn_matrix<double, 2>;
using dmat3 = etl::dyn_matrix<double, 3>;
using dmat4 = etl::dyn_matrix<double, 4>;
using svec = etl::dyn_vector<float>;
using smat = etl::dyn_matrix<float>;
using cvec = etl::dyn_vector<std::complex<float>>;
using cmat = etl::dyn_matrix<std::complex<float>>;
using zvec = etl::dyn_vector<std::complex<double>>;
using zmat = etl::dyn_matrix<std::complex<double>>;
using mat_policy = VALUES_POLICY(10, 25, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000,3000,4000);
using mat_policy_2d = NARY_POLICY(mat_policy, mat_policy);
using conv_1d_large_policy = NARY_POLICY(VALUES_POLICY(1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), VALUES_POLICY(500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000));
using conv_2d_large_policy = NARY_POLICY(VALUES_POLICY(100, 105, 110, 115, 120, 125, 130, 135, 140), VALUES_POLICY(50, 50, 55, 55, 60, 60, 65, 65, 70));
using fft_1d_policy = VALUES_POLICY(10, 100, 1000, 10000, 100000, 500000);
using fft_1d_policy_2 = VALUES_POLICY(16, 64, 256, 1024, 16384, 131072, 1048576, 2097152);
using fft_1d_many_policy = VALUES_POLICY(10, 50, 100, 500, 1000, 5000, 10000);
using fft_2d_policy = NARY_POLICY(
VALUES_POLICY(8, 16, 32, 64, 128, 256, 512, 1024, 2048),
VALUES_POLICY(8, 16, 32, 64, 128, 256, 512, 1024, 2048));
using sigmoid_policy = VALUES_POLICY(250, 500, 750, 1000, 1250, 1500, 1750, 2000);
using small_square_policy = NARY_POLICY(VALUES_POLICY(50, 100, 150, 200, 250, 300, 350, 400, 450, 500), VALUES_POLICY(50, 100, 150, 200, 250, 300, 350, 400, 450, 500));
using square_policy = NARY_POLICY(VALUES_POLICY(50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000), VALUES_POLICY(50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000));
using gemv_policy = NARY_POLICY(
VALUES_POLICY(250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000),
VALUES_POLICY(250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000));
using trans_sub_policy = VALUES_POLICY(100, 200, 300, 400, 500, 600, 700, 800, 900, 1000);
using trans_policy = NARY_POLICY(
VALUES_POLICY(100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600, 700, 700, 800, 800, 900, 900, 1000, 1000),
VALUES_POLICY(100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600, 700, 700, 800, 800, 900, 900, 1000, 1000, 1100));
#ifdef TEST_SSE
#define SSE_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define SSE_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_AVX
#define AVX_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define AVX_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_MKL
#define MKL_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define MKL_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_BLAS
#define BLAS_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define BLAS_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_CUBLAS
#define CUBLAS_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define CUBLAS_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_CUFFT
#define CUFFT_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define CUFFT_SECTION_FUNCTOR(name, ...)
#endif
#ifdef TEST_MMUL_CONV
#define MC_SECTION_FUNCTOR(name, ...) , CPM_SECTION_FUNCTOR(name, __VA_ARGS__)
#else
#define MC_SECTION_FUNCTOR(name, ...)
#endif
<|endoftext|>
|
<commit_before>#include <engine.hpp>
int fabric::Engine::eventLoop() {
return 0;
}
int fabric::Engine::exitRoutin() {
return 0;
}<commit_msg>Added basic event loop logic<commit_after>#include <engine.hpp>
#include <iostream>
#include <types.hpp>
#include <gameobject.hpp>
#include <behavior.hpp>
using namespace std;
using namespace fabric;
int Engine::eventLoop() {
for (unsigned int i = 0; i < vLoadedGameObjects->size(); i++) {
vLoadedGameObjects->at(i)->update();
}
// To be debricated //
// Asks the user for an input,
// if it equals yes the exitRoutin is ran and the programm exits
// else the eventloop calls it self
char* input = new char[255];
cin >> input;
if (strcmp(input, "yes") == 0)
exitRoutin();
else
eventLoop();
return 0;
}
void Engine::loadGameObject(GameObject* gObj){
vLoadedGameObjects->push_back(gObj);
}
int Engine::exitRoutin() {
cout << "Good bye!" << endl;
Engine::get()->del();
return 0;
}
<|endoftext|>
|
<commit_before>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct TheBestName {
vector <string> sort(vector <string> names) {
vector<pair<int, string>> v;
auto sum = [](const string & s) {
int r = 0;
ei(a, s) r += a - 'A';
return r;
};
ei(a, names) {
v.eb(a == "JOHN" ? big : sum(a), a);
}
sr(v);
ei(a, v) names[ai] = s.second;
return names;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, vector <string> p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
TheBestName *obj;
vector <string> answer;
obj = new TheBestName();
clock_t startTime = clock();
answer = obj->sort(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << "{";
for (int i = 0; int(p1.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p1[i] << "\"";
}
cout << "}" << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << "{";
for (int i = 0; int(answer.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << answer[i] << "\"";
}
cout << "}" << endl;
if (hasAnswer) {
if (answer.size() != p1.size()) {
res = false;
} else {
for (int i = 0; int(answer.size()) > i; ++i) {
if (answer[i] != p1[i]) {
res = false;
}
}
}
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
vector <string> p0;
vector <string> p1;
// ----- test 0 -----
disabled = false;
p0 = {"JOHN","PETR","ACRUSH"};
p1 = {"JOHN","ACRUSH","PETR"};
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = {"GLUK","MARGARITKA"};
p1 = {"MARGARITKA","GLUK"};
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = {"JOHN","A","AA","AAA","JOHN","B","BB","BBB","JOHN","C","CC","CCC","JOHN"};
p1 = {"JOHN","JOHN","JOHN","JOHN","CCC","BBB","CC","BB","AAA","C","AA","B","A"};
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = {"BATMAN","SUPERMAN","SPIDERMAN","TERMINATOR"};
p1 = {"TERMINATOR","SUPERMAN","SPIDERMAN","BATMAN"};
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<commit_msg>TheBestName<commit_after>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct TheBestName {
vector <string> sort(vector <string> names) {
vector<pair<int, string>> v;
auto sum = [](const string & s) {
int r = 0;
ei(a, s) r += a - 'A';
return r;
};
ei(a, names) {
v.eb(a == "JOHN" ? big : sum(a), a);
}
sr(v);
ei(a, v) names[ai] = a.second;
return names;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, vector <string> p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
TheBestName *obj;
vector <string> answer;
obj = new TheBestName();
clock_t startTime = clock();
answer = obj->sort(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << "{";
for (int i = 0; int(p1.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p1[i] << "\"";
}
cout << "}" << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << "{";
for (int i = 0; int(answer.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << answer[i] << "\"";
}
cout << "}" << endl;
if (hasAnswer) {
if (answer.size() != p1.size()) {
res = false;
} else {
for (int i = 0; int(answer.size()) > i; ++i) {
if (answer[i] != p1[i]) {
res = false;
}
}
}
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
vector <string> p0;
vector <string> p1;
// ----- test 0 -----
disabled = false;
p0 = {"JOHN","PETR","ACRUSH"};
p1 = {"JOHN","ACRUSH","PETR"};
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = {"GLUK","MARGARITKA"};
p1 = {"MARGARITKA","GLUK"};
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = {"JOHN","A","AA","AAA","JOHN","B","BB","BBB","JOHN","C","CC","CCC","JOHN"};
p1 = {"JOHN","JOHN","JOHN","JOHN","CCC","BBB","CC","BB","AAA","C","AA","B","A"};
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = {"BATMAN","SUPERMAN","SPIDERMAN","TERMINATOR"};
p1 = {"TERMINATOR","SUPERMAN","SPIDERMAN","BATMAN"};
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<|endoftext|>
|
<commit_before>// ffmpeg_acoustid.cpp
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
#include "ffmpeg.h"
#include <chromaprint.h>
PyObject *
pyCalcAcoustIdFingerprint(PyObject* self, PyObject* args) {
PyObject* songObj = NULL;
if(!PyArg_ParseTuple(args, "O:calcAcoustIdFingerprint", &songObj))
return NULL;
PyObject* returnObj = NULL;
PlayerObject* player = NULL;
ChromaprintContext *chromaprint_ctx = NULL;
unsigned long totalFrameCount = 0;
player = (PlayerObject*) pyCreatePlayer(NULL);
if(!player) goto final;
player->lock.enabled = false;
player->nextSongOnEof = false;
player->skipPyExceptions = false;
player->playing = true; // otherwise audio_decode_frame() wont read
player->volumeAdjustEnabled = false; // avoid volume adjustments
Py_INCREF(songObj);
player->curSong = songObj;
if(!player->openInStream()) goto final;
if(PyErr_Occurred()) goto final;
if(player->inStream == NULL) goto final;
// fpcalc source for reference:
// https://github.com/lalinsky/chromaprint/blob/master/examples/fpcalc.c
chromaprint_ctx = chromaprint_new(CHROMAPRINT_ALGORITHM_DEFAULT);
chromaprint_start(chromaprint_ctx, player->outSamplerate, player->outNumChannels);
// Note that we don't have any max_length handling yet.
// fpcalc uses a default of 120 seconds.
// This function right now doesn't rely on any external song duration
// source, so it is a perfect reliable way to calculate also the
// song duration.
// I'm not sure how expensive audio_decode_frame is compared to
// chromaprint_feed, so if we just decode everything to calculate
// a reliable song duration, it might make sense to just feed
// everything to chromaprint.
// Maybe we can optimize audio_decode_frame though to just return the
// len and don't do any decoding if we just want to calculate the len.
// This is all open for future hacking ... But it works good enough now.
while(player->processInStream()) {
if(PyErr_Occurred()) goto final;
for(auto& it : player->inStreamBuffer()->chunks) {
totalFrameCount += it.size() / player->outNumChannels / OUTSAMPLEBYTELEN;
int16_t pcmBuffer[BUFFER_CHUNK_SIZE/OUTSAMPLEBYTELEN];
uint16_t len = it.size() / OUTSAMPLEBYTELEN;
for(uint16_t i = 0; i < len; ++i)
pcmBuffer[i] = FloatToPCM16(((OUTSAMPLE_t*)it.pt())[i]);
if (!chromaprint_feed(chromaprint_ctx, it.pt(), len)) {
PyErr_SetString(PyExc_RuntimeError, "fingerprint feed calculation failed");
goto final;
}
}
player->inStreamBuffer()->clear();
}
// If we have too less data -> fail. chromaprint_finish will print a warning/error but wont fail.
// 16 seems like a good lower limit. It is also the limit of the default Chromaprint Fingerprint algorithm.
if(totalFrameCount < 16) {
PyErr_SetString(PyExc_RuntimeError, "too less data for fingerprint");
goto final;
}
{
double songDuration = (double)totalFrameCount / player->outSamplerate;
char* fingerprint = NULL;
if (!chromaprint_finish(chromaprint_ctx)) {
PyErr_SetString(PyExc_RuntimeError, "fingerprint finish calculation failed");
goto final;
}
if (!chromaprint_get_fingerprint(chromaprint_ctx, &fingerprint)) {
PyErr_SetString(PyExc_RuntimeError, "unable to calculate fingerprint, get_fingerprint failed");
goto final;
}
returnObj = PyTuple_New(2);
PyTuple_SetItem(returnObj, 0, PyFloat_FromDouble(songDuration));
PyTuple_SetItem(returnObj, 1, PyString_FromString(fingerprint));
chromaprint_dealloc(fingerprint);
}
final:
if(chromaprint_ctx)
chromaprint_free(chromaprint_ctx);
if(!PyErr_Occurred() && !returnObj) {
returnObj = Py_None;
Py_INCREF(returnObj);
}
Py_XDECREF(player);
return returnObj;
}
<commit_msg>stupid fix<commit_after>// ffmpeg_acoustid.cpp
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
#include "ffmpeg.h"
#include <chromaprint.h>
PyObject *
pyCalcAcoustIdFingerprint(PyObject* self, PyObject* args) {
PyObject* songObj = NULL;
if(!PyArg_ParseTuple(args, "O:calcAcoustIdFingerprint", &songObj))
return NULL;
PyObject* returnObj = NULL;
PlayerObject* player = NULL;
ChromaprintContext *chromaprint_ctx = NULL;
unsigned long totalFrameCount = 0;
player = (PlayerObject*) pyCreatePlayer(NULL);
if(!player) goto final;
player->lock.enabled = false;
player->nextSongOnEof = false;
player->skipPyExceptions = false;
player->playing = true; // otherwise audio_decode_frame() wont read
player->volumeAdjustEnabled = false; // avoid volume adjustments
Py_INCREF(songObj);
player->curSong = songObj;
if(!player->openInStream()) goto final;
if(PyErr_Occurred()) goto final;
if(player->inStream == NULL) goto final;
// fpcalc source for reference:
// https://github.com/lalinsky/chromaprint/blob/master/examples/fpcalc.c
chromaprint_ctx = chromaprint_new(CHROMAPRINT_ALGORITHM_DEFAULT);
chromaprint_start(chromaprint_ctx, player->outSamplerate, player->outNumChannels);
// Note that we don't have any max_length handling yet.
// fpcalc uses a default of 120 seconds.
// This function right now doesn't rely on any external song duration
// source, so it is a perfect reliable way to calculate also the
// song duration.
// I'm not sure how expensive audio_decode_frame is compared to
// chromaprint_feed, so if we just decode everything to calculate
// a reliable song duration, it might make sense to just feed
// everything to chromaprint.
// Maybe we can optimize audio_decode_frame though to just return the
// len and don't do any decoding if we just want to calculate the len.
// This is all open for future hacking ... But it works good enough now.
while(player->processInStream()) {
if(PyErr_Occurred()) goto final;
for(auto& it : player->inStreamBuffer()->chunks) {
totalFrameCount += it.size() / player->outNumChannels / OUTSAMPLEBYTELEN;
// chromaprint expects sint16 sample format.
int16_t pcmBuffer[BUFFER_CHUNK_SIZE/OUTSAMPLEBYTELEN];
uint16_t len = it.size() / OUTSAMPLEBYTELEN;
for(uint16_t i = 0; i < len; ++i) {
OUTSAMPLE_t s = ((OUTSAMPLE_t*)it.pt())[i];
pcmBuffer[i] = FloatToPCM16(OutSampleAsFloat(s));
}
if (!chromaprint_feed(chromaprint_ctx, pcmBuffer, len)) {
PyErr_SetString(PyExc_RuntimeError, "fingerprint feed calculation failed");
goto final;
}
}
player->inStreamBuffer()->clear();
}
// If we have too less data -> fail. chromaprint_finish will print a warning/error but wont fail.
// 16 seems like a good lower limit. It is also the limit of the default Chromaprint Fingerprint algorithm.
if(totalFrameCount < 16) {
PyErr_SetString(PyExc_RuntimeError, "too less data for fingerprint");
goto final;
}
{
double songDuration = (double)totalFrameCount / player->outSamplerate;
char* fingerprint = NULL;
if (!chromaprint_finish(chromaprint_ctx)) {
PyErr_SetString(PyExc_RuntimeError, "fingerprint finish calculation failed");
goto final;
}
if (!chromaprint_get_fingerprint(chromaprint_ctx, &fingerprint)) {
PyErr_SetString(PyExc_RuntimeError, "unable to calculate fingerprint, get_fingerprint failed");
goto final;
}
returnObj = PyTuple_New(2);
PyTuple_SetItem(returnObj, 0, PyFloat_FromDouble(songDuration));
PyTuple_SetItem(returnObj, 1, PyString_FromString(fingerprint));
chromaprint_dealloc(fingerprint);
}
final:
if(chromaprint_ctx)
chromaprint_free(chromaprint_ctx);
if(!PyErr_Occurred() && !returnObj) {
returnObj = Py_None;
Py_INCREF(returnObj);
}
Py_XDECREF(player);
return returnObj;
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include <tlib/file.hpp>
#include <tlib/system.hpp>
#include <tlib/errors.hpp>
#include <tlib/print.hpp>
#include <tlib/directory_entry.hpp>
static constexpr const size_t BUFFER_SIZE = 4096;
std::string read_file(const std::string& path){
auto fd = tlib::open(path.c_str());
if(fd.valid()){
auto info = tlib::stat(*fd);
if(info.valid()){
auto size = info->size;
auto buffer = new char[size+1];
auto content_result = tlib::read(*fd, buffer, size);
if(content_result.valid()){
if(*content_result != size){
//TODO Read more
} else {
buffer[size] = '\0';
tlib::close(*fd);
return buffer;
}
} else {
tlib::printf("ifconfig: error: %s\n", std::error_message(content_result.error()));
}
} else {
tlib::printf("ifconfig: error: %s\n", std::error_message(info.error()));
}
tlib::close(*fd);
} else {
tlib::printf("ifconfig: error: %s\n", std::error_message(fd.error()));
}
return "";
}
int main(int /*argc*/, char* /*argv*/[]){
auto fd = tlib::open("/sys/net/");
if(fd.valid()){
auto info = tlib::stat(*fd);
if(info.valid()){
auto entries_buffer = new char[BUFFER_SIZE];
auto entries_result = tlib::entries(*fd, entries_buffer, BUFFER_SIZE);
if(entries_result.valid()){
size_t position = 0;
while(true){
auto entry = reinterpret_cast<tlib::directory_entry*>(entries_buffer + position);
std::string base_path = "/sys/net/";
std::string entry_name = &entry->name;
auto enabled = read_file(base_path + entry_name + "/enabled");
if(enabled == "true"){
auto driver = read_file(base_path + entry_name + "/driver");
auto ip = read_file(base_path + entry_name + "/ip");
auto mac = read_file(base_path + entry_name + "/mac");
tlib::printf("%10s inet %s\n", &entry->name, ip.c_str());
if(!mac.empty() && mac != "0"){
tlib::printf("%10s ether %s\n", "", mac.c_str());
}
tlib::printf("%10s driver %s\n", "", driver.c_str());
}
if(!entry->offset_next){
break;
}
tlib::printf("\n");
position += entry->offset_next;
}
} else {
tlib::printf("ifconfig: error: %s\n", std::error_message(entries_result.error()));
}
delete[] entries_buffer;
} else {
tlib::printf("ifconfig: error: %s\n", std::error_message(info.error()));
}
tlib::close(*fd);
} else {
tlib::printf("ifconfig: error: %s\n", std::error_message(fd.error()));
}
return 0;
}
<commit_msg>Use the new API<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include <tlib/file.hpp>
#include <tlib/system.hpp>
#include <tlib/errors.hpp>
#include <tlib/print.hpp>
std::string read_file(const std::string& path){
tlib::file f(path);
if(!f){
tlib::printf("ifconfig: error: %s\n", std::error_message(f.error()));
return "";
}
auto contents = f.read_file();
if(!f){
tlib::printf("ifconfig: error: %s\n", std::error_message(f.error()));
}
return contents;
}
int main(int /*argc*/, char* /*argv*/[]){
tlib::file dir("/sys/net/");
if(!dir){
tlib::printf("ifconfig: error: %s\n", std::error_message(dir.error()));
return 1;
}
bool first = true;
for(auto entry_name : dir.entries()){
if(!first){
tlib::printf("\n");
}
first = false;
std::string base_path = "/sys/net/";
auto enabled = read_file(base_path + entry_name + "/enabled");
if(enabled == "true"){
auto driver = read_file(base_path + entry_name + "/driver");
auto ip = read_file(base_path + entry_name + "/ip");
auto mac = read_file(base_path + entry_name + "/mac");
tlib::printf("%10s inet %s\n", entry_name, ip.c_str());
if(!mac.empty() && mac != "0"){
tlib::printf("%10s ether %s\n", "", mac.c_str());
}
tlib::printf("%10s driver %s\n", "", driver.c_str());
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* 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 <graphene/app/application.hpp>
#include <graphene/witness/witness.hpp>
#include <graphene/account_history/account_history_plugin.hpp>
#include <graphene/market_history/market_history_plugin.hpp>
#include <fc/thread/thread.hpp>
#include <fc/interprocess/signals.hpp>
#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>
#ifndef WIN32
#include <csignal>
#endif
using namespace graphene;
namespace bpo = boost::program_options;
int main(int argc, char** argv) {
try {
app::application node;
bpo::options_description app_options("Graphene Witness Node");
bpo::options_description cfg_options("Graphene Witness Node");
app_options.add_options()
("help,h", "Print this help message and exit.")
("data-dir,d", bpo::value<boost::filesystem::path>()->default_value("witness_node_data_dir"), "Directory containing databases, configuration file, etc.")
;
bpo::variables_map options;
auto witness_plug = node.register_plugin<witness_plugin::witness_plugin>();
auto history_plug = node.register_plugin<account_history::account_history_plugin>();
auto market_history_plug = node.register_plugin<market_history::market_history_plugin>();
try
{
bpo::options_description cli, cfg;
node.set_program_options(cli, cfg);
app_options.add(cli);
cfg_options.add(cfg);
bpo::store(bpo::parse_command_line(argc, argv, app_options), options);
}
catch (const boost::program_options::error& e)
{
std::cerr << "Error parsing command line: " << e.what() << "\n";
return 1;
}
if( options.count("help") )
{
std::cout << app_options << "\n";
return 0;
}
fc::path data_dir;
if( options.count("data-dir") )
{
data_dir = options["data-dir"].as<boost::filesystem::path>();
if( data_dir.is_relative() )
data_dir = fc::current_path() / data_dir;
}
if( fc::exists(data_dir / "config.ini") )
bpo::store(bpo::parse_config_file<char>((data_dir / "config.ini").preferred_string().c_str(), cfg_options), options);
else {
ilog("Writing new config file at ${path}", ("path", data_dir/"config.ini"));
if( !fc::exists(data_dir) )
fc::create_directories(data_dir);
std::ofstream out_cfg((data_dir / "config.ini").preferred_string());
for( const boost::shared_ptr<bpo::option_description> od : cfg_options.options() )
{
if( !od->description().empty() )
out_cfg << "# " << od->description() << "\n";
boost::any store;
if( !od->semantic()->apply_default(store) )
out_cfg << "# " << od->long_name() << " = \n";
else {
auto example = od->format_parameter();
if( example.empty() )
// This is a boolean switch
out_cfg << od->long_name() << " = " << "false\n";
else {
// The string is formatted "arg (=<interesting part>)"
example.erase(0, 6);
example.erase(example.length()-1);
out_cfg << od->long_name() << " = " << example << "\n";
}
}
out_cfg << "\n";
}
}
bpo::notify(options);
node.initialize(data_dir, options);
node.initialize_plugins( options );
node.startup();
node.startup_plugins();
fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
#if defined __APPLE__ || defined __unix__
fc::set_signal_handler([&exit_promise](int signal) {
exit_promise->set_value(signal);
}, SIGINT);
#endif
ilog("Started witness node on a chain with ${h} blocks.", ("h", node.chain_database()->head_block_num()));
int signal = exit_promise->wait();
ilog("Exiting from signal ${n}", ("n", signal));
node.shutdown_plugins();
return 0;
} catch( const fc::exception& e ) {
elog("Exiting with error:\n${e}", ("e", e.to_detail_string()));
return 1;
}
}
<commit_msg>By default, log p2p messages to logs/p2p/p2p.log, default to stderr, progress on #149<commit_after>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* 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 <graphene/app/application.hpp>
#include <graphene/witness/witness.hpp>
#include <graphene/account_history/account_history_plugin.hpp>
#include <graphene/market_history/market_history_plugin.hpp>
#include <fc/thread/thread.hpp>
#include <fc/interprocess/signals.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <iostream>
#include <fstream>
#ifndef WIN32
#include <csignal>
#endif
using namespace graphene;
namespace bpo = boost::program_options;
void write_default_logging_config_to_stream(std::ostream& out);
fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path& config_ini_filename);
int main(int argc, char** argv) {
try {
app::application node;
bpo::options_description app_options("Graphene Witness Node");
bpo::options_description cfg_options("Graphene Witness Node");
app_options.add_options()
("help,h", "Print this help message and exit.")
("data-dir,d", bpo::value<boost::filesystem::path>()->default_value("witness_node_data_dir"), "Directory containing databases, configuration file, etc.")
;
bpo::variables_map options;
auto witness_plug = node.register_plugin<witness_plugin::witness_plugin>();
auto history_plug = node.register_plugin<account_history::account_history_plugin>();
auto market_history_plug = node.register_plugin<market_history::market_history_plugin>();
try
{
bpo::options_description cli, cfg;
node.set_program_options(cli, cfg);
app_options.add(cli);
cfg_options.add(cfg);
bpo::store(bpo::parse_command_line(argc, argv, app_options), options);
}
catch (const boost::program_options::error& e)
{
std::cerr << "Error parsing command line: " << e.what() << "\n";
return 1;
}
if( options.count("help") )
{
std::cout << app_options << "\n";
return 0;
}
fc::path data_dir;
if( options.count("data-dir") )
{
data_dir = options["data-dir"].as<boost::filesystem::path>();
if( data_dir.is_relative() )
data_dir = fc::current_path() / data_dir;
}
fc::path config_ini_path = data_dir / "config.ini";
if( fc::exists(config_ini_path) )
{
// get the basic options
bpo::store(bpo::parse_config_file<char>(config_ini_path.preferred_string().c_str(), cfg_options, true), options);
// try to get logging options from the config file.
fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path);
if (logging_config)
fc::configure_logging(*logging_config);
}
else
{
ilog("Writing new config file at ${path}", ("path", config_ini_path));
if( !fc::exists(data_dir) )
fc::create_directories(data_dir);
std::ofstream out_cfg(config_ini_path.preferred_string());
for( const boost::shared_ptr<bpo::option_description> od : cfg_options.options() )
{
if( !od->description().empty() )
out_cfg << "# " << od->description() << "\n";
boost::any store;
if( !od->semantic()->apply_default(store) )
out_cfg << "# " << od->long_name() << " = \n";
else {
auto example = od->format_parameter();
if( example.empty() )
// This is a boolean switch
out_cfg << od->long_name() << " = " << "false\n";
else {
// The string is formatted "arg (=<interesting part>)"
example.erase(0, 6);
example.erase(example.length()-1);
out_cfg << od->long_name() << " = " << example << "\n";
}
}
out_cfg << "\n";
}
write_default_logging_config_to_stream(out_cfg);
out_cfg.close();
// read the default logging config we just wrote out to the file and start using it
fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path);
if (logging_config)
fc::configure_logging(*logging_config);
}
bpo::notify(options);
node.initialize(data_dir, options);
node.initialize_plugins( options );
node.startup();
node.startup_plugins();
fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
#if defined __APPLE__ || defined __unix__
fc::set_signal_handler([&exit_promise](int signal) {
exit_promise->set_value(signal);
}, SIGINT);
#endif
ilog("Started witness node on a chain with ${h} blocks.", ("h", node.chain_database()->head_block_num()));
int signal = exit_promise->wait();
ilog("Exiting from signal ${n}", ("n", signal));
node.shutdown_plugins();
return 0;
} catch( const fc::exception& e ) {
elog("Exiting with error:\n${e}", ("e", e.to_detail_string()));
return 1;
}
}
// logging config is too complicated to be parsed by boost::program_options,
// so we do it by hand
//
// Currently, you can only specify the filenames and logging levels, which
// are all most users would want to change. At a later time, options can
// be added to control rotation intervals, compression, and other seldom-
// used features
void write_default_logging_config_to_stream(std::ostream& out)
{
out << "# declare an appender named \"stderr\" that writes messages to the console\n"
"[log.console_appender.stderr]\n"
"stream=std_error\n\n"
"# declare an appender named \"p2p\" that writes messages to p2p.log\n"
"[log.file_appender.p2p]\n"
"filename=logs/p2p/p2p.log\n"
"# filename can be absolute or relative to this config file\n\n"
"# route any messages logged to the default logger to the \"stderr\" logger we\n"
"# declared above, if they are info level are higher\n"
"[logger.default]\n"
"level=info\n"
"appenders=stderr\n\n"
"# route messages sent to the \"p2p\" logger to the p2p appender declared above\n"
"[logger.p2p]\n"
"level=debug\n"
"appenders=p2p\n\n";
}
fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path& config_ini_filename)
{
fc::logging_config logging_config;
bool found_logging_config = false;
boost::property_tree::ptree config_ini_tree;
boost::property_tree::ini_parser::read_ini(config_ini_filename.preferred_string().c_str(), config_ini_tree);
for (const auto& section : config_ini_tree)
{
const std::string& section_name = section.first;
const boost::property_tree::ptree& section_tree = section.second;
const std::string console_appender_section_prefix = "log.console_appender.";
const std::string file_appender_section_prefix = "log.file_appender.";
const std::string logger_section_prefix = "logger.";
if (boost::starts_with(section_name, console_appender_section_prefix))
{
std::string console_appender_name = section_name.substr(console_appender_section_prefix.length());
std::string stream_name = section_tree.get<std::string>("stream");
// construct a default console appender config here
// stdout/stderr will be taken from ini file, everything else hard-coded here
fc::console_appender::config console_appender_config;
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::debug,
fc::console_appender::color::green));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::warn,
fc::console_appender::color::brown));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::error,
fc::console_appender::color::cyan));
console_appender_config.stream = fc::variant(stream_name).as<fc::console_appender::stream::type>();
logging_config.appenders.push_back(fc::appender_config(console_appender_name, "console", fc::variant(console_appender_config)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, file_appender_section_prefix))
{
std::string file_appender_name = section_name.substr(file_appender_section_prefix.length());
fc::path file_name = section_tree.get<std::string>("filename");
if (file_name.is_relative())
file_name = fc::absolute(config_ini_filename).parent_path() / file_name;
// construct a default file appender config here
// filename will be taken from ini file, everything else hard-coded here
fc::file_appender::config file_appender_config;
file_appender_config.filename = file_name;
file_appender_config.flush = true;
file_appender_config.rotate = true;
file_appender_config.rotation_interval = fc::hours(1);
file_appender_config.rotation_limit = fc::days(1);
logging_config.appenders.push_back(fc::appender_config(file_appender_name, "file", fc::variant(file_appender_config)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, logger_section_prefix))
{
std::string logger_name = section_name.substr(logger_section_prefix.length());
std::string level_string = section_tree.get<std::string>("level");
std::string appenders_string = section_tree.get<std::string>("appenders");
fc::logger_config logger_config(logger_name);
logger_config.level = fc::variant(level_string).as<fc::log_level>();
boost::split(logger_config.appenders, appenders_string,
boost::is_any_of(" ,"),
boost::token_compress_on);
logging_config.loggers.push_back(logger_config);
found_logging_config = true;
}
}
if (found_logging_config)
return logging_config;
else
return fc::optional<fc::logging_config>();
}
<|endoftext|>
|
<commit_before>// 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.
#include "channel.h"
#include <stdio.h>
#include <sys/mman.h>
#include <cstdint>
#include <iostream>
#include "lib/ghost.h"
namespace ghost {
// static
struct ghost_msg Message::kEmpty = {
.type = 0,
.length = 0,
.seqnum = 0,
};
Channel::Channel(int elems, int node, CpuList cpulist)
: elems_(elems), node_(node) {
fd_ = Ghost::CreateQueue(elems_, node_, 0, &map_size_);
CHECK_GT(fd_, 0);
header_ = static_cast<struct ghost_queue_header*>(
mmap(nullptr, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0));
CHECK_NE(header_, MAP_FAILED);
elems_ = header_->nelems;
if (!cpulist.Empty()) {
cpu_set_t cpuset = Topology::ToCpuSet(cpulist);
CHECK_ZERO(Ghost::ConfigQueueWakeup(fd_, cpuset, /*flags=*/0));
}
};
Channel::~Channel() {
munmap(header_, map_size_);
close(fd_);
}
bool Channel::AssociateTask(Gtid gtid, int barrier, int* status) const {
return Ghost::AssociateQueue(fd_, GHOST_TASK, gtid.id(), barrier, 0) == 0;
}
void Channel::Consume(const Message& msg) {
struct ghost_ring* r = reinterpret_cast<struct ghost_ring*>(
reinterpret_cast<char*>(header_) + header_->start);
const int slot_size = sizeof(struct ghost_msg);
uint32_t tail = r->tail.load(std::memory_order_acquire);
// static_cast<uint32_t> to ensure that msg.length() is properly rounded up.
// Otherwise if 'msg.length() + slot_size >= 65536' we'll end up only using
// least significant 16-bits.
tail += roundup2(static_cast<uint32_t>(msg.length()), slot_size) / slot_size;
r->tail.store(tail, std::memory_order_release);
}
Message Channel::Peek() {
struct ghost_ring* r = reinterpret_cast<struct ghost_ring*>(
reinterpret_cast<char*>(header_) + header_->start);
uint32_t tidx;
const uint32_t nelems = header_->nelems;
const uint32_t tail = r->tail.load(std::memory_order_acquire);
const uint32_t head = r->head.load(std::memory_order_acquire);
if (tail == head) return Message(); // Empty message.
const uint32_t overflow = r->overflow.load(std::memory_order_acquire);
CHECK_EQ(overflow, 0);
tidx = tail & (nelems - 1);
return Message(&r->msgs[tidx]);
}
bool Channel::SetEnclaveDefault() const {
return Ghost::SetDefaultQueue(fd_) == 0;
}
absl::string_view Message::describe_type() const {
switch (type()) {
case MSG_NOP:
return "MSG_NOP";
case MSG_TASK_DEAD:
return "MSG_TASK_DEAD";
case MSG_TASK_BLOCKED:
return "MSG_TASK_BLOCKED";
case MSG_TASK_WAKEUP:
return "MSG_TASK_WAKEUP";
case MSG_TASK_NEW:
return "MSG_TASK_NEW";
case MSG_TASK_PREEMPT:
return "MSG_TASK_PREEMPT";
case MSG_TASK_YIELD:
return "MSG_TASK_YIELD";
case MSG_CPU_TICK:
return "MSG_CPU_TICK";
case MSG_CPU_NOT_IDLE:
return "MSG_CPU_NOT_IDLE";
case MSG_CPU_TIMER_EXPIRED:
return "MSG_CPU_TIMER_EXPIRED";
case MSG_TASK_DEPARTED:
return "MSG_TASK_DEPARTED";
case MSG_TASK_SWITCHTO:
return "MSG_TASK_SWITCHTO";
default:
GHOST_ERROR("Unknown message %d", type());
}
return "UNKNOWN";
}
std::string Message::stringify() const {
std::string result = absl::StrCat("M: ", describe_type(), " seq=", seqnum());
if (is_cpu_msg()) {
absl::StrAppend(&result, " cpu=", cpu());
return result;
}
Gtid msg_gtid = gtid();
absl::StrAppend(&result, " ", msg_gtid.describe());
switch (type()) {
case MSG_NOP:
absl::StrAppend(&result, " l=", length());
break;
case MSG_TASK_NEW: {
const ghost_msg_payload_task_new* new_payload =
static_cast<const ghost_msg_payload_task_new*>(payload());
absl::StrAppend(&result, " ",
new_payload->runnable ? "runnable" : "blocked");
break;
}
case MSG_TASK_SWITCHTO: {
const ghost_msg_payload_task_switchto* switchto =
static_cast<const ghost_msg_payload_task_switchto*>(payload());
absl::StrAppend(&result, " entering switchto on cpu ", switchto->cpu);
break;
}
case MSG_TASK_BLOCKED: {
const ghost_msg_payload_task_blocked* blocked =
static_cast<const ghost_msg_payload_task_blocked*>(payload());
absl::StrAppend(&result, " on cpu ", blocked->cpu);
if (blocked->from_switchto) absl::StrAppend(&result, " (from_switchto)");
break;
}
case MSG_TASK_YIELD: {
const ghost_msg_payload_task_yield* yield =
static_cast<const ghost_msg_payload_task_yield*>(payload());
absl::StrAppend(&result, " on cpu ", yield->cpu);
if (yield->from_switchto) absl::StrAppend(&result, " (from_switchto)");
break;
}
case MSG_TASK_PREEMPT: {
const ghost_msg_payload_task_preempt* preempt =
static_cast<const ghost_msg_payload_task_preempt*>(payload());
absl::StrAppend(&result, " on cpu ", preempt->cpu);
if (preempt->from_switchto) absl::StrAppend(&result, " (from_switchto)");
break;
}
case MSG_TASK_DEPARTED: {
const ghost_msg_payload_task_departed* departed =
static_cast<const ghost_msg_payload_task_departed*>(payload());
absl::StrAppend(&result, " on cpu ", departed->cpu);
if (departed->from_switchto) absl::StrAppend(&result, " (from_switchto)");
break;
}
default:
break;
}
return result;
}
} // namespace ghost
<commit_msg>cl/385660830: Include AFFINITY_CHANGED message in debug prints<commit_after>// 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.
#include "channel.h"
#include <stdio.h>
#include <sys/mman.h>
#include <cstdint>
#include <iostream>
#include "lib/ghost.h"
namespace ghost {
// static
struct ghost_msg Message::kEmpty = {
.type = 0,
.length = 0,
.seqnum = 0,
};
Channel::Channel(int elems, int node, CpuList cpulist)
: elems_(elems), node_(node) {
fd_ = Ghost::CreateQueue(elems_, node_, 0, &map_size_);
CHECK_GT(fd_, 0);
header_ = static_cast<struct ghost_queue_header*>(
mmap(nullptr, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0));
CHECK_NE(header_, MAP_FAILED);
elems_ = header_->nelems;
if (!cpulist.Empty()) {
cpu_set_t cpuset = Topology::ToCpuSet(cpulist);
CHECK_ZERO(Ghost::ConfigQueueWakeup(fd_, cpuset, /*flags=*/0));
}
};
Channel::~Channel() {
munmap(header_, map_size_);
close(fd_);
}
bool Channel::AssociateTask(Gtid gtid, int barrier, int* status) const {
return Ghost::AssociateQueue(fd_, GHOST_TASK, gtid.id(), barrier, 0) == 0;
}
void Channel::Consume(const Message& msg) {
struct ghost_ring* r = reinterpret_cast<struct ghost_ring*>(
reinterpret_cast<char*>(header_) + header_->start);
const int slot_size = sizeof(struct ghost_msg);
uint32_t tail = r->tail.load(std::memory_order_acquire);
// static_cast<uint32_t> to ensure that msg.length() is properly rounded up.
// Otherwise if 'msg.length() + slot_size >= 65536' we'll end up only using
// least significant 16-bits.
tail += roundup2(static_cast<uint32_t>(msg.length()), slot_size) / slot_size;
r->tail.store(tail, std::memory_order_release);
}
Message Channel::Peek() {
struct ghost_ring* r = reinterpret_cast<struct ghost_ring*>(
reinterpret_cast<char*>(header_) + header_->start);
uint32_t tidx;
const uint32_t nelems = header_->nelems;
const uint32_t tail = r->tail.load(std::memory_order_acquire);
const uint32_t head = r->head.load(std::memory_order_acquire);
if (tail == head) return Message(); // Empty message.
const uint32_t overflow = r->overflow.load(std::memory_order_acquire);
CHECK_EQ(overflow, 0);
tidx = tail & (nelems - 1);
return Message(&r->msgs[tidx]);
}
bool Channel::SetEnclaveDefault() const {
return Ghost::SetDefaultQueue(fd_) == 0;
}
absl::string_view Message::describe_type() const {
switch (type()) {
case MSG_NOP:
return "MSG_NOP";
case MSG_TASK_DEAD:
return "MSG_TASK_DEAD";
case MSG_TASK_BLOCKED:
return "MSG_TASK_BLOCKED";
case MSG_TASK_WAKEUP:
return "MSG_TASK_WAKEUP";
case MSG_TASK_NEW:
return "MSG_TASK_NEW";
case MSG_TASK_PREEMPT:
return "MSG_TASK_PREEMPT";
case MSG_TASK_YIELD:
return "MSG_TASK_YIELD";
case MSG_CPU_TICK:
return "MSG_CPU_TICK";
case MSG_CPU_NOT_IDLE:
return "MSG_CPU_NOT_IDLE";
case MSG_CPU_TIMER_EXPIRED:
return "MSG_CPU_TIMER_EXPIRED";
case MSG_TASK_DEPARTED:
return "MSG_TASK_DEPARTED";
case MSG_TASK_SWITCHTO:
return "MSG_TASK_SWITCHTO";
case MSG_TASK_AFFINITY_CHANGED:
return "MSG_TASK_AFFINITY_CHANGED";
default:
GHOST_ERROR("Unknown message %d", type());
}
return "UNKNOWN";
}
std::string Message::stringify() const {
std::string result = absl::StrCat("M: ", describe_type(), " seq=", seqnum());
if (is_cpu_msg()) {
absl::StrAppend(&result, " cpu=", cpu());
return result;
}
Gtid msg_gtid = gtid();
absl::StrAppend(&result, " ", msg_gtid.describe());
switch (type()) {
case MSG_NOP:
absl::StrAppend(&result, " l=", length());
break;
case MSG_TASK_NEW: {
const ghost_msg_payload_task_new* new_payload =
static_cast<const ghost_msg_payload_task_new*>(payload());
absl::StrAppend(&result, " ",
new_payload->runnable ? "runnable" : "blocked");
break;
}
case MSG_TASK_SWITCHTO: {
const ghost_msg_payload_task_switchto* switchto =
static_cast<const ghost_msg_payload_task_switchto*>(payload());
absl::StrAppend(&result, " entering switchto on cpu ", switchto->cpu);
break;
}
case MSG_TASK_BLOCKED: {
const ghost_msg_payload_task_blocked* blocked =
static_cast<const ghost_msg_payload_task_blocked*>(payload());
absl::StrAppend(&result, " on cpu ", blocked->cpu);
if (blocked->from_switchto) absl::StrAppend(&result, " (from_switchto)");
break;
}
case MSG_TASK_YIELD: {
const ghost_msg_payload_task_yield* yield =
static_cast<const ghost_msg_payload_task_yield*>(payload());
absl::StrAppend(&result, " on cpu ", yield->cpu);
if (yield->from_switchto) absl::StrAppend(&result, " (from_switchto)");
break;
}
case MSG_TASK_PREEMPT: {
const ghost_msg_payload_task_preempt* preempt =
static_cast<const ghost_msg_payload_task_preempt*>(payload());
absl::StrAppend(&result, " on cpu ", preempt->cpu);
if (preempt->from_switchto) absl::StrAppend(&result, " (from_switchto)");
break;
}
case MSG_TASK_DEPARTED: {
const ghost_msg_payload_task_departed* departed =
static_cast<const ghost_msg_payload_task_departed*>(payload());
absl::StrAppend(&result, " on cpu ", departed->cpu);
if (departed->from_switchto) absl::StrAppend(&result, " (from_switchto)");
break;
}
default:
break;
}
return result;
}
} // namespace ghost
<|endoftext|>
|
<commit_before>#include "sql_string.h"
using namespace std;
namespace mysqlpp {
SQLString::SQLString() :
is_string(false),
dont_escape(false),
processed(false)
{
}
SQLString::SQLString(const string& str) :
string(str),
is_string(true),
dont_escape(false),
processed(false)
{
}
SQLString::SQLString(const char* str) :
string(str),
is_string(true),
dont_escape(false),
processed(false)
{
}
SQLString::SQLString(char i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[6];
snprintf(s, sizeof(s), "%dh", (short int)i);
*this = s;
}
SQLString::SQLString(unsigned char i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[6];
snprintf(s, sizeof(s), "%uh", (short int)i);
*this = s;
}
SQLString::SQLString(short int i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[6];
snprintf(s, sizeof(s), "%dh", i);
*this = s;
}
SQLString::SQLString(unsigned short int i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[6];
snprintf(s, sizeof(s), "%uh", i);
*this = s;
}
SQLString::SQLString(int i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[22];
snprintf(s, sizeof(s), "%d", i);
*this = s;
}
SQLString::SQLString(unsigned int i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[22];
snprintf(s, sizeof(s), "%u", i);
*this = s;
}
SQLString::SQLString(longlong i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[22];
snprintf(s, sizeof(s), "%dL", i);
*this = s;
}
SQLString::SQLString(ulonglong i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[22];
snprintf(s, sizeof(s), "%uL", i);
*this = s;
}
SQLString::SQLString(float i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[40];
snprintf(s, sizeof(s), "%g", i);
*this = s;
}
SQLString::SQLString(double i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[40];
snprintf(s, sizeof(s), "%g", i);
*this = s;
}
} // end namespace mysqlpp
<commit_msg>Fixed g++ pedantic warnings about printf format specifier and argument type agreement. Patch by Chris Frey <cdfrey@netdirect.ca><commit_after>#include "sql_string.h"
using namespace std;
namespace mysqlpp {
SQLString::SQLString() :
is_string(false),
dont_escape(false),
processed(false)
{
}
SQLString::SQLString(const string& str) :
string(str),
is_string(true),
dont_escape(false),
processed(false)
{
}
SQLString::SQLString(const char* str) :
string(str),
is_string(true),
dont_escape(false),
processed(false)
{
}
SQLString::SQLString(char i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[6];
snprintf(s, sizeof(s), "%hd", static_cast<short int>(i));
*this = s;
}
SQLString::SQLString(unsigned char i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[6];
snprintf(s, sizeof(s), "%hu", static_cast<short int>(i));
*this = s;
}
SQLString::SQLString(short int i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[6];
snprintf(s, sizeof(s), "%hd", i);
*this = s;
}
SQLString::SQLString(unsigned short int i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[6];
snprintf(s, sizeof(s), "%hu", i);
*this = s;
}
SQLString::SQLString(int i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[22];
snprintf(s, sizeof(s), "%d", i);
*this = s;
}
SQLString::SQLString(unsigned int i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[22];
snprintf(s, sizeof(s), "%u", i);
*this = s;
}
SQLString::SQLString(longlong i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[22];
snprintf(s, sizeof(s), "%lld", i);
*this = s;
}
SQLString::SQLString(ulonglong i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[22];
snprintf(s, sizeof(s), "%llu", i);
*this = s;
}
SQLString::SQLString(float i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[40];
snprintf(s, sizeof(s), "%g", i);
*this = s;
}
SQLString::SQLString(double i) :
is_string(false),
dont_escape(false),
processed(false)
{
char s[40];
snprintf(s, sizeof(s), "%g", i);
*this = s;
}
} // end namespace mysqlpp
<|endoftext|>
|
<commit_before>// Taken from: http://stackoverflow.com/a/14537855
#include <iostream>
#include <complex>
#include <numeric>
#include <array>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#ifndef M_PI
#define M_PI 3.14159265358979324
#endif
#define N 16
#define kiss_fft_scalar float
#include "kiss_fft.h"
int main()
{
std::array<kiss_fft_cpx, N> in;
std::array<kiss_fft_cpx, N> out;
for (size_t i=0; i < N; ++i) {
in[i].r = i;
in[i].i = 0.0;
//std::cout << in[i].r << "," << in[i].i << "\n";
}
kiss_fft_cfg cfg;
if ((cfg = kiss_fft_alloc(N, 0, NULL, NULL)) != NULL) {
kiss_fft(cfg, in.data(), out.data());
free(cfg);
for (size_t i = 0; i < N; i++) {
printf(" in[%2zu] = %+f , %+f "
"out[%2zu] = %+f , %+f\n",
i, in[i].r, in[i].i, i, out[i].r, out[i].i);
}
} else {
printf("not enough memory\n");
return -1;
}
return 0;
}
<commit_msg>Demonstrate RAII with Kiss FFT.<commit_after>// Taken from: http://stackoverflow.com/a/14537855
#include <iostream>
#include <complex>
#include <numeric>
#include <memory>
#include <type_traits>
#include <array>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#ifndef M_PI
#define M_PI 3.14159265358979324
#endif
#define N 16
#define kiss_fft_scalar float
#include "kiss_fft.h"
namespace std {
template<>
class default_delete<std::remove_pointer<kiss_fft_cfg>::type>
{
public:
void operator()(std::remove_pointer<kiss_fft_cfg>::type *p) { free(p); }
};
}
int main()
{
std::array<kiss_fft_cpx, N> in;
std::array<kiss_fft_cpx, N> out;
for (size_t i=0; i < N; ++i) {
in[i].r = i;
in[i].i = 0.0;
//std::cout << in[i].r << "," << in[i].i << "\n";
}
// RAII without default_delete
auto cfg1 = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(free) *> {
kiss_fft_alloc(N, 0, NULL, NULL),
free
};
// RAII with default delete
auto cfg2 = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type> {
kiss_fft_alloc(N, 0, NULL, NULL)
};
if (cfg1) {
kiss_fft(cfg1.get(), in.data(), out.data());
for (size_t i = 0; i < N; i++) {
printf(" in[%2zu] = %+f , %+f "
"out[%2zu] = %+f , %+f\n",
i, in[i].r, in[i].i, i, out[i].r, out[i].i);
}
} else {
printf("not enough memory\n");
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ink_platform.h"
#include "ink_lockfile.h"
#if defined(linux)
#include "ink_killall.h"
#endif
#define LOCKFILE_BUF_LEN 16 // 16 bytes should be enought for a pid
int
Lockfile::Open(pid_t * holding_pid)
{
char buf[LOCKFILE_BUF_LEN];
pid_t val;
int err;
*holding_pid = 0;
#define FAIL(x) \
{ \
if (fd > 0) \
close (fd); \
return (x); \
}
struct flock lock;
char *t;
int size;
fd = -1;
// Try and open the Lockfile. Create it if it does not already
// exist.
do {
fd = open(fname, O_RDWR | O_CREAT, 0644);
} while ((fd < 0) && (errno == EINTR));
if (fd < 0)
return (-errno);
// Lock it. Note that if we can't get the lock EAGAIN will be the
// error we receive.
lock.l_type = F_WRLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
do {
err = fcntl(fd, F_SETLK, &lock);
} while ((err < 0) && (errno == EINTR));
if (err < 0) {
// We couldn't get the lock. Try and read the process id of the
// process holding the lock from the lockfile.
t = buf;
for (size = 15; size > 0;) {
do {
err = read(fd, t, size);
} while ((err < 0) && (errno == EINTR));
if (err < 0)
FAIL(-errno);
if (err == 0)
break;
size -= err;
t += err;
}
*t = '\0';
// coverity[secure_coding]
if (sscanf(buf, "%d\n", (int*)&val) != 1) {
*holding_pid = 0;
} else {
*holding_pid = val;
}
FAIL(0);
}
// If we did get the lock, then set the close on exec flag so that
// we don't accidently pass the file descriptor to a child process
// when we do a fork/exec.
do {
err = fcntl(fd, F_GETFD, 0);
} while ((err < 0) && (errno == EINTR));
if (err < 0)
FAIL(-errno);
val = err | FD_CLOEXEC;
do {
err = fcntl(fd, F_SETFD, val);
} while ((err < 0) && (errno == EINTR));
if (err < 0)
FAIL(-errno);
// Return the file descriptor of the opened lockfile. When this file
// descriptor is closed the lock will be released.
return (1); // success
#undef FAIL
}
int
Lockfile::Get(pid_t * holding_pid)
{
char buf[LOCKFILE_BUF_LEN];
int err;
*holding_pid = 0;
fd = -1;
// Open the Lockfile and get the lock. If we are successful, the
// return value will be the file descriptor of the opened Lockfile.
err = Open(holding_pid);
if (err != 1)
return err;
if (fd < 0) {
return -1;
}
// Truncate the Lockfile effectively erasing it.
do {
err = ftruncate(fd, 0);
} while ((err < 0) && (errno == EINTR));
if (err < 0) {
close(fd);
return (-errno);
}
// Write our process id to the Lockfile.
snprintf(buf, sizeof(buf), "%d\n", (int) getpid());
do {
err = write(fd, buf, strlen(buf));
} while ((err < 0) && (errno == EINTR));
if (err != (int) strlen(buf)) {
close(fd);
return (-errno);
}
return (1); // success
}
void
Lockfile::Close(void)
{
if (fd != -1) {
close(fd);
}
}
//-------------------------------------------------------------------------
// Lockfile::Kill() and Lockfile::KillAll()
//
// Open the lockfile. If we succeed it means there was no process
// holding the lock. We'll just close the file and release the lock
// in that case. If we don't succeed in getting the lock, the
// process id of the process holding the lock is returned. We
// repeatedly send the KILL signal to that process until doing so
// fails. That is, until kill says that the process id is no longer
// valid (we killed the process), or that we don't have permission
// to send a signal to that process id (the process holding the lock
// is dead and a new process has replaced it).
//
// INKqa11325 (Kevlar: linux machine hosed up if specific threads
// killed): Unfortunately, it's possible on Linux that the main PID of
// the process has been successfully killed (and is waiting to be
// reaped while in a defunct state), while some of the other threads
// of the process just don't want to go away. Integrate ink_killall
// into Kill() and KillAll() just to make sure we really kill
// everything and so that we don't spin hard while trying to kill a
// defunct process.
//-------------------------------------------------------------------------
static void
lockfile_kill_internal(pid_t init_pid, int init_sig, pid_t pid, const char *pname, int sig)
{
int err;
#if defined(linux)
pid_t *pidv;
int pidvcnt;
// Need to grab pname's pid vector before we issue any kill signals.
// Specifically, this prevents the race-condition in which
// traffic_manager spawns a new traffic_server while we still think
// we're killall'ing the old traffic_server.
if (pname) {
ink_killall_get_pidv_xmalloc(pname, &pidv, &pidvcnt);
}
if (init_sig > 0) {
kill(init_pid, init_sig);
// sleep for a bit and give time for the first signal to be
// delivered
sleep(1);
}
do {
if ((err = kill(pid, sig)) == 0) {
sleep(1);
}
if (pname && (pidvcnt > 0)) {
ink_killall_kill_pidv(pidv, pidvcnt, sig);
sleep(1);
}
} while ((err == 0) || ((err < 0) && (errno == EINTR)));
ats_free(pidv);
#else
if (init_sig > 0) {
kill(init_pid, init_sig);
// sleep for a bit and give time for the first signal to be
// delivered
sleep(1);
}
do {
err = kill(pid, sig);
} while ((err == 0) || ((err < 0) && (errno == EINTR)));
#endif // linux check
}
void
Lockfile::Kill(int sig, int initial_sig, const char *pname)
{
int err;
int pid;
pid_t holding_pid;
err = Open(&holding_pid);
if (err == 1) // success getting the lock file
{
Close();
} else if (err == 0) // someone else has the lock
{
pid = holding_pid;
if (pid != 0) {
lockfile_kill_internal(pid, initial_sig, pid, pname, sig);
}
}
}
void
Lockfile::KillGroup(int sig, int initial_sig, const char *pname)
{
int err;
pid_t pid;
pid_t holding_pid;
err = Open(&holding_pid);
if (err == 1) // success getting the lock file
{
Close();
} else if (err == 0) // someone else has the lock
{
do {
pid = getpgid(holding_pid);
} while ((pid < 0) && (errno == EINTR));
if ((pid < 0) || (pid == getpid()))
pid = holding_pid;
else
pid = -pid;
if (pid != 0) {
// We kill the holding_pid instead of the process_group
// initially since there is no point trying to get core files
// from a group since the core file of one overwrites the core
// file of another one
lockfile_kill_internal(holding_pid, initial_sig, pid, pname, sig);
}
}
}
<commit_msg>clang report Logic error: Uninitialized argument value in lib/ts/lockfile.cc:239<commit_after>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ink_platform.h"
#include "ink_lockfile.h"
#if defined(linux)
#include "ink_killall.h"
#endif
#define LOCKFILE_BUF_LEN 16 // 16 bytes should be enought for a pid
int
Lockfile::Open(pid_t * holding_pid)
{
char buf[LOCKFILE_BUF_LEN];
pid_t val;
int err;
*holding_pid = 0;
#define FAIL(x) \
{ \
if (fd > 0) \
close (fd); \
return (x); \
}
struct flock lock;
char *t;
int size;
fd = -1;
// Try and open the Lockfile. Create it if it does not already
// exist.
do {
fd = open(fname, O_RDWR | O_CREAT, 0644);
} while ((fd < 0) && (errno == EINTR));
if (fd < 0)
return (-errno);
// Lock it. Note that if we can't get the lock EAGAIN will be the
// error we receive.
lock.l_type = F_WRLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
do {
err = fcntl(fd, F_SETLK, &lock);
} while ((err < 0) && (errno == EINTR));
if (err < 0) {
// We couldn't get the lock. Try and read the process id of the
// process holding the lock from the lockfile.
t = buf;
for (size = 15; size > 0;) {
do {
err = read(fd, t, size);
} while ((err < 0) && (errno == EINTR));
if (err < 0)
FAIL(-errno);
if (err == 0)
break;
size -= err;
t += err;
}
*t = '\0';
// coverity[secure_coding]
if (sscanf(buf, "%d\n", (int*)&val) != 1) {
*holding_pid = 0;
} else {
*holding_pid = val;
}
FAIL(0);
}
// If we did get the lock, then set the close on exec flag so that
// we don't accidently pass the file descriptor to a child process
// when we do a fork/exec.
do {
err = fcntl(fd, F_GETFD, 0);
} while ((err < 0) && (errno == EINTR));
if (err < 0)
FAIL(-errno);
val = err | FD_CLOEXEC;
do {
err = fcntl(fd, F_SETFD, val);
} while ((err < 0) && (errno == EINTR));
if (err < 0)
FAIL(-errno);
// Return the file descriptor of the opened lockfile. When this file
// descriptor is closed the lock will be released.
return (1); // success
#undef FAIL
}
int
Lockfile::Get(pid_t * holding_pid)
{
char buf[LOCKFILE_BUF_LEN];
int err;
*holding_pid = 0;
fd = -1;
// Open the Lockfile and get the lock. If we are successful, the
// return value will be the file descriptor of the opened Lockfile.
err = Open(holding_pid);
if (err != 1)
return err;
if (fd < 0) {
return -1;
}
// Truncate the Lockfile effectively erasing it.
do {
err = ftruncate(fd, 0);
} while ((err < 0) && (errno == EINTR));
if (err < 0) {
close(fd);
return (-errno);
}
// Write our process id to the Lockfile.
snprintf(buf, sizeof(buf), "%d\n", (int) getpid());
do {
err = write(fd, buf, strlen(buf));
} while ((err < 0) && (errno == EINTR));
if (err != (int) strlen(buf)) {
close(fd);
return (-errno);
}
return (1); // success
}
void
Lockfile::Close(void)
{
if (fd != -1) {
close(fd);
}
}
//-------------------------------------------------------------------------
// Lockfile::Kill() and Lockfile::KillAll()
//
// Open the lockfile. If we succeed it means there was no process
// holding the lock. We'll just close the file and release the lock
// in that case. If we don't succeed in getting the lock, the
// process id of the process holding the lock is returned. We
// repeatedly send the KILL signal to that process until doing so
// fails. That is, until kill says that the process id is no longer
// valid (we killed the process), or that we don't have permission
// to send a signal to that process id (the process holding the lock
// is dead and a new process has replaced it).
//
// INKqa11325 (Kevlar: linux machine hosed up if specific threads
// killed): Unfortunately, it's possible on Linux that the main PID of
// the process has been successfully killed (and is waiting to be
// reaped while in a defunct state), while some of the other threads
// of the process just don't want to go away. Integrate ink_killall
// into Kill() and KillAll() just to make sure we really kill
// everything and so that we don't spin hard while trying to kill a
// defunct process.
//-------------------------------------------------------------------------
static void
lockfile_kill_internal(pid_t init_pid, int init_sig, pid_t pid, const char *pname, int sig)
{
int err;
#if defined(linux)
pid_t *pidv = NULL;
int pidvcnt;
// Need to grab pname's pid vector before we issue any kill signals.
// Specifically, this prevents the race-condition in which
// traffic_manager spawns a new traffic_server while we still think
// we're killall'ing the old traffic_server.
if (pname) {
ink_killall_get_pidv_xmalloc(pname, &pidv, &pidvcnt);
}
if (init_sig > 0) {
kill(init_pid, init_sig);
// sleep for a bit and give time for the first signal to be
// delivered
sleep(1);
}
do {
if ((err = kill(pid, sig)) == 0) {
sleep(1);
}
if (pname && (pidvcnt > 0)) {
ink_killall_kill_pidv(pidv, pidvcnt, sig);
sleep(1);
}
} while ((err == 0) || ((err < 0) && (errno == EINTR)));
ats_free(pidv);
#else
if (init_sig > 0) {
kill(init_pid, init_sig);
// sleep for a bit and give time for the first signal to be
// delivered
sleep(1);
}
do {
err = kill(pid, sig);
} while ((err == 0) || ((err < 0) && (errno == EINTR)));
#endif // linux check
}
void
Lockfile::Kill(int sig, int initial_sig, const char *pname)
{
int err;
int pid;
pid_t holding_pid;
err = Open(&holding_pid);
if (err == 1) // success getting the lock file
{
Close();
} else if (err == 0) // someone else has the lock
{
pid = holding_pid;
if (pid != 0) {
lockfile_kill_internal(pid, initial_sig, pid, pname, sig);
}
}
}
void
Lockfile::KillGroup(int sig, int initial_sig, const char *pname)
{
int err;
pid_t pid;
pid_t holding_pid;
err = Open(&holding_pid);
if (err == 1) // success getting the lock file
{
Close();
} else if (err == 0) // someone else has the lock
{
do {
pid = getpgid(holding_pid);
} while ((pid < 0) && (errno == EINTR));
if ((pid < 0) || (pid == getpid()))
pid = holding_pid;
else
pid = -pid;
if (pid != 0) {
// We kill the holding_pid instead of the process_group
// initially since there is no point trying to get core files
// from a group since the core file of one overwrites the core
// file of another one
lockfile_kill_internal(holding_pid, initial_sig, pid, pname, sig);
}
}
}
<|endoftext|>
|
<commit_before>/*-----------------------------------------------------------*/
/* Block Sorting, Lossless Data Compression Library. */
/* Lempel Ziv Prediction */
/*-----------------------------------------------------------*/
/*--
This file is a part of bsc and/or libbsc, a program and a library for
lossless, block-sorting data compression.
Copyright (c) 2009-2012 Ilya Grebnov <ilya.grebnov@gmail.com>
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.
Please see the file LICENSE for full copyright information and file AUTHORS
for full list of contributors.
See also the bsc and libbsc web site:
http://libbsc.com/ for more information.
--*/
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include "lzp.h"
#include "../platform/platform.h"
#include "../libbsc.h"
#define LIBBSC_LZP_MATCH_FLAG 0xf2
static INLINE int bsc_lzp_num_blocks(int n)
{
if (n < 256 * 1024) return 1;
if (n < 4 * 1024 * 1024) return 2;
if (n < 16 * 1024 * 1024) return 4;
return 8;
}
int bsc_lzp_encode_block(const unsigned char * input, const unsigned char * inputEnd, unsigned char * output, unsigned char * outputEnd, int hashSize, int minLen)
{
if (inputEnd - input < 16)
{
return LIBBSC_NOT_COMPRESSIBLE;
}
if (int * lookup = (int *)bsc_zero_malloc((int)(1 << hashSize) * sizeof(int)))
{
unsigned int mask = (int)(1 << hashSize) - 1;
const unsigned char * inputStart = input;
const unsigned char * outputStart = output;
const unsigned char * outputEOB = outputEnd - 4;
unsigned int context = 0;
for (int i = 0; i < 4; ++i)
{
context = (context << 8) | (*output++ = *input++);
}
const unsigned char * heuristic = input;
const unsigned char * inputMinLenEnd = inputEnd - minLen - 8;
while ((input < inputMinLenEnd) && (output < outputEOB))
{
unsigned int index = ((context >> 15) ^ context ^ (context >> 3)) & mask;
int value = lookup[index]; lookup[index] = (int)(input - inputStart);
if (value > 0)
{
const unsigned char * reference = inputStart + value;
if ((*(unsigned int *)(input + minLen - 4) == *(unsigned int *)(reference + minLen - 4)) && (*(unsigned int *)(input) == *(unsigned int *)(reference)))
{
if ((heuristic > input) && (*(unsigned int *)heuristic != *(unsigned int *)(reference + (heuristic - input))))
{
goto LIBBSC_LZP_MATCH_NOT_FOUND;
}
int len = 4;
for (; input + len < inputMinLenEnd; len += 4)
{
if (*(unsigned int *)(input + len) != *(unsigned int *)(reference + len)) break;
}
if (len < minLen)
{
if (heuristic < input + len) heuristic = input + len;
goto LIBBSC_LZP_MATCH_NOT_FOUND;
}
if (input[len] == reference[len]) len++;
if (input[len] == reference[len]) len++;
if (input[len] == reference[len]) len++;
input += len; context = input[-1] | (input[-2] << 8) | (input[-3] << 16) | (input[-4] << 24);
*output++ = LIBBSC_LZP_MATCH_FLAG;
len -= minLen; while (len >= 254) { len -= 254; *output++ = 254; if (output >= outputEOB) break; }
*output++ = (unsigned char)(len);
}
else
{
LIBBSC_LZP_MATCH_NOT_FOUND:
unsigned char next = *output++ = *input++; context = (context << 8) | next;
if (next == LIBBSC_LZP_MATCH_FLAG) *output++ = 255;
}
}
else
{
context = (context << 8) | (*output++ = *input++);
}
}
while ((input < inputEnd) && (output < outputEOB))
{
unsigned int index = ((context >> 15) ^ context ^ (context >> 3)) & mask;
int value = lookup[index]; lookup[index] = (int)(input - inputStart);
if (value > 0)
{
unsigned char next = *output++ = *input++; context = (context << 8) | next;
if (next == LIBBSC_LZP_MATCH_FLAG) *output++ = 255;
}
else
{
context = (context << 8) | (*output++ = *input++);
}
}
bsc_free(lookup);
return (output >= outputEOB) ? LIBBSC_NOT_COMPRESSIBLE : (int)(output - outputStart);
}
return LIBBSC_NOT_ENOUGH_MEMORY;
}
int bsc_lzp_decode_block(const unsigned char * input, const unsigned char * inputEnd, unsigned char * output, int hashSize, int minLen)
{
if (inputEnd - input < 4)
{
return LIBBSC_UNEXPECTED_EOB;
}
if (int * lookup = (int *)bsc_zero_malloc((int)(1 << hashSize) * sizeof(int)))
{
unsigned int mask = (int)(1 << hashSize) - 1;
const unsigned char * outputStart = output;
unsigned int context = 0;
for (int i = 0; i < 4; ++i)
{
context = (context << 8) | (*output++ = *input++);
}
while (input < inputEnd)
{
unsigned int index = ((context >> 15) ^ context ^ (context >> 3)) & mask;
int value = lookup[index]; lookup[index] = (int)(output - outputStart);
if (*input == LIBBSC_LZP_MATCH_FLAG && value > 0)
{
input++;
if (*input != 255)
{
int len = minLen; while (true) { len += *input; if (*input++ != 254) break; }
const unsigned char * reference = outputStart + value;
unsigned char * outputEnd = output + len;
if (output - reference < 4)
{
int offset[4] = {0, 3, 2, 3};
*output++ = *reference++;
*output++ = *reference++;
*output++ = *reference++;
*output++ = *reference++;
reference -= offset[output - reference];
}
while (output < outputEnd) { *(unsigned int *)output = *(unsigned int*)reference; output += 4; reference += 4; }
output = outputEnd; context = output[-1] | (output[-2] << 8) | (output[-3] << 16) | (output[-4] << 24);
}
else
{
input++; context = (context << 8) | (*output++ = LIBBSC_LZP_MATCH_FLAG);
}
}
else
{
context = (context << 8) | (*output++ = *input++);
}
}
bsc_free(lookup);
return (int)(output - outputStart);
}
return LIBBSC_NOT_ENOUGH_MEMORY;
}
int bsc_lzp_compress_serial(const unsigned char * input, unsigned char * output, int n, int hashSize, int minLen)
{
if (bsc_lzp_num_blocks(n) == 1)
{
int result = bsc_lzp_encode_block(input, input + n, output + 1, output + n - 1, hashSize, minLen);
if (result >= LIBBSC_NO_ERROR) result = (output[0] = 1, result + 1);
return result;
}
int nBlocks = bsc_lzp_num_blocks(n);
int chunkSize = n / nBlocks;
int outputPtr = 1 + 8 * nBlocks;
output[0] = nBlocks;
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
int inputStart = blockId * chunkSize;
int inputSize = blockId != nBlocks - 1 ? chunkSize : n - inputStart;
int outputSize = inputSize; if (outputSize > n - outputPtr) outputSize = n - outputPtr;
int result = bsc_lzp_encode_block(input + inputStart, input + inputStart + inputSize, output + outputPtr, output + outputPtr + outputSize, hashSize, minLen);
if (result < LIBBSC_NO_ERROR)
{
if (outputPtr + inputSize >= n) return LIBBSC_NOT_COMPRESSIBLE;
result = inputSize; memcpy(output + outputPtr, input + inputStart, inputSize);
}
*(int *)(output + 1 + 8 * blockId + 0) = inputSize;
*(int *)(output + 1 + 8 * blockId + 4) = result;
outputPtr += result;
}
return outputPtr;
}
#ifdef LIBBSC_OPENMP
int bsc_lzp_compress_parallel(const unsigned char * input, unsigned char * output, int n, int hashSize, int minLen)
{
if (unsigned char * buffer = (unsigned char *)bsc_malloc(n * sizeof(unsigned char)))
{
int compressionResult[ALPHABET_SIZE];
int nBlocks = bsc_lzp_num_blocks(n);
int result = LIBBSC_NO_ERROR;
int chunkSize = n / nBlocks;
int numThreads = omp_get_max_threads();
if (numThreads > nBlocks) numThreads = nBlocks;
output[0] = nBlocks;
#pragma omp parallel num_threads(numThreads) if(numThreads > 1)
{
if (omp_get_num_threads() == 1)
{
result = bsc_lzp_compress_serial(input, output, n, hashSize, minLen);
}
else
{
#pragma omp for schedule(dynamic)
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
int blockStart = blockId * chunkSize;
int blockSize = blockId != nBlocks - 1 ? chunkSize : n - blockStart;
compressionResult[blockId] = bsc_lzp_encode_block(input + blockStart, input + blockStart + blockSize, buffer + blockStart, buffer + blockStart + blockSize, hashSize, minLen);
if (compressionResult[blockId] < LIBBSC_NO_ERROR) compressionResult[blockId] = blockSize;
*(int *)(output + 1 + 8 * blockId + 0) = blockSize;
*(int *)(output + 1 + 8 * blockId + 4) = compressionResult[blockId];
}
#pragma omp single
{
result = 1 + 8 * nBlocks;
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
result += compressionResult[blockId];
}
if (result >= n) result = LIBBSC_NOT_COMPRESSIBLE;
}
if (result >= LIBBSC_NO_ERROR)
{
#pragma omp for schedule(dynamic)
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
int blockStart = blockId * chunkSize;
int blockSize = blockId != nBlocks - 1 ? chunkSize : n - blockStart;
int outputPtr = 1 + 8 * nBlocks;
for (int p = 0; p < blockId; ++p) outputPtr += compressionResult[p];
if (compressionResult[blockId] != blockSize)
{
memcpy(output + outputPtr, buffer + blockStart, compressionResult[blockId]);
}
else
{
memcpy(output + outputPtr, input + blockStart, compressionResult[blockId]);
}
}
}
}
}
bsc_free(buffer);
return result;
}
return LIBBSC_NOT_ENOUGH_MEMORY;
}
#endif
int bsc_lzp_compress(const unsigned char * input, unsigned char * output, int n, int hashSize, int minLen, int features)
{
#ifdef LIBBSC_OPENMP
if ((bsc_lzp_num_blocks(n) != 1) && (features & LIBBSC_FEATURE_MULTITHREADING))
{
return bsc_lzp_compress_parallel(input, output, n, hashSize, minLen);
}
#endif
return bsc_lzp_compress_serial(input, output, n, hashSize, minLen);
}
int bsc_lzp_decompress(const unsigned char * input, unsigned char * output, int n, int hashSize, int minLen, int features)
{
int nBlocks = input[0];
if (nBlocks == 1)
{
return bsc_lzp_decode_block(input + 1, input + n, output, hashSize, minLen);
}
int decompressionResult[ALPHABET_SIZE];
#ifdef LIBBSC_OPENMP
if (features & LIBBSC_FEATURE_MULTITHREADING)
{
#pragma omp parallel for schedule(dynamic)
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
int inputPtr = 0; for (int p = 0; p < blockId; ++p) inputPtr += *(int *)(input + 1 + 8 * p + 4);
int outputPtr = 0; for (int p = 0; p < blockId; ++p) outputPtr += *(int *)(input + 1 + 8 * p + 0);
inputPtr += 1 + 8 * nBlocks;
int inputSize = *(int *)(input + 1 + 8 * blockId + 4);
int outputSize = *(int *)(input + 1 + 8 * blockId + 0);
if (inputSize != outputSize)
{
decompressionResult[blockId] = bsc_lzp_decode_block(input + inputPtr, input + inputPtr + inputSize, output + outputPtr, hashSize, minLen);
}
else
{
decompressionResult[blockId] = inputSize; memcpy(output + outputPtr, input + inputPtr, inputSize);
}
}
}
else
#endif
{
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
int inputPtr = 0; for (int p = 0; p < blockId; ++p) inputPtr += *(int *)(input + 1 + 8 * p + 4);
int outputPtr = 0; for (int p = 0; p < blockId; ++p) outputPtr += *(int *)(input + 1 + 8 * p + 0);
inputPtr += 1 + 8 * nBlocks;
int inputSize = *(int *)(input + 1 + 8 * blockId + 4);
int outputSize = *(int *)(input + 1 + 8 * blockId + 0);
if (inputSize != outputSize)
{
decompressionResult[blockId] = bsc_lzp_decode_block(input + inputPtr, input + inputPtr + inputSize, output + outputPtr, hashSize, minLen);
}
else
{
decompressionResult[blockId] = inputSize; memcpy(output + outputPtr, input + inputPtr, inputSize);
}
}
}
int dataSize = 0, result = LIBBSC_NO_ERROR;
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
if (decompressionResult[blockId] < LIBBSC_NO_ERROR) result = decompressionResult[blockId];
dataSize += decompressionResult[blockId];
}
return (result == LIBBSC_NO_ERROR) ? dataSize : result;
}
/*-----------------------------------------------------------*/
/* End lzp.cpp */
/*-----------------------------------------------------------*/
<commit_msg>lzp: avoid accessing data outside of the buffers provided to libbsc<commit_after>/*-----------------------------------------------------------*/
/* Block Sorting, Lossless Data Compression Library. */
/* Lempel Ziv Prediction */
/*-----------------------------------------------------------*/
/*--
This file is a part of bsc and/or libbsc, a program and a library for
lossless, block-sorting data compression.
Copyright (c) 2009-2012 Ilya Grebnov <ilya.grebnov@gmail.com>
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.
Please see the file LICENSE for full copyright information and file AUTHORS
for full list of contributors.
See also the bsc and libbsc web site:
http://libbsc.com/ for more information.
--*/
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include "lzp.h"
#include "../platform/platform.h"
#include "../libbsc.h"
#define LIBBSC_LZP_MATCH_FLAG 0xf2
static INLINE int bsc_lzp_num_blocks(int n)
{
if (n < 256 * 1024) return 1;
if (n < 4 * 1024 * 1024) return 2;
if (n < 16 * 1024 * 1024) return 4;
return 8;
}
int bsc_lzp_encode_block(const unsigned char * input, const unsigned char * inputEnd, unsigned char * output, unsigned char * outputEnd, int hashSize, int minLen)
{
if (inputEnd - input < 16)
{
return LIBBSC_NOT_COMPRESSIBLE;
}
if (int * lookup = (int *)bsc_zero_malloc((int)(1 << hashSize) * sizeof(int)))
{
unsigned int mask = (int)(1 << hashSize) - 1;
const unsigned char * inputStart = input;
const unsigned char * outputStart = output;
const unsigned char * outputEOB = outputEnd - 4;
unsigned int context = 0;
for (int i = 0; i < 4; ++i)
{
context = (context << 8) | (*output++ = *input++);
}
const unsigned char * heuristic = input;
const unsigned char * inputMinLenEnd = inputEnd - minLen - 8;
while ((input < inputMinLenEnd) && (output < outputEOB))
{
unsigned int index = ((context >> 15) ^ context ^ (context >> 3)) & mask;
int value = lookup[index]; lookup[index] = (int)(input - inputStart);
if (value > 0)
{
const unsigned char * reference = inputStart + value;
if ((*(unsigned int *)(input + minLen - 4) == *(unsigned int *)(reference + minLen - 4)) && (*(unsigned int *)(input) == *(unsigned int *)(reference)))
{
if ((heuristic > input) && (*(unsigned int *)heuristic != *(unsigned int *)(reference + (heuristic - input))))
{
goto LIBBSC_LZP_MATCH_NOT_FOUND;
}
int len = 4;
for (; input + len < inputMinLenEnd; len += 4)
{
if (*(unsigned int *)(input + len) != *(unsigned int *)(reference + len)) break;
}
if (len < minLen)
{
if (heuristic < input + len) heuristic = input + len;
goto LIBBSC_LZP_MATCH_NOT_FOUND;
}
if (input[len] == reference[len]) len++;
if (input[len] == reference[len]) len++;
if (input[len] == reference[len]) len++;
input += len; context = input[-1] | (input[-2] << 8) | (input[-3] << 16) | (input[-4] << 24);
*output++ = LIBBSC_LZP_MATCH_FLAG;
len -= minLen; while (len >= 254) { len -= 254; *output++ = 254; if (output >= outputEOB) break; }
*output++ = (unsigned char)(len);
}
else
{
LIBBSC_LZP_MATCH_NOT_FOUND:
unsigned char next = *output++ = *input++; context = (context << 8) | next;
if (next == LIBBSC_LZP_MATCH_FLAG) *output++ = 255;
}
}
else
{
context = (context << 8) | (*output++ = *input++);
}
}
while ((input < inputEnd) && (output < outputEOB))
{
unsigned int index = ((context >> 15) ^ context ^ (context >> 3)) & mask;
int value = lookup[index]; lookup[index] = (int)(input - inputStart);
if (value > 0)
{
unsigned char next = *output++ = *input++; context = (context << 8) | next;
if (next == LIBBSC_LZP_MATCH_FLAG) *output++ = 255;
}
else
{
context = (context << 8) | (*output++ = *input++);
}
}
bsc_free(lookup);
return (output >= outputEOB) ? LIBBSC_NOT_COMPRESSIBLE : (int)(output - outputStart);
}
return LIBBSC_NOT_ENOUGH_MEMORY;
}
int bsc_lzp_decode_block(const unsigned char * input, const unsigned char * inputEnd, unsigned char * output, int hashSize, int minLen)
{
if (inputEnd - input < 4)
{
return LIBBSC_UNEXPECTED_EOB;
}
if (int * lookup = (int *)bsc_zero_malloc((int)(1 << hashSize) * sizeof(int)))
{
unsigned int mask = (int)(1 << hashSize) - 1;
const unsigned char * outputStart = output;
unsigned int context = 0;
for (int i = 0; i < 4; ++i)
{
context = (context << 8) | (*output++ = *input++);
}
while (input < inputEnd)
{
unsigned int index = ((context >> 15) ^ context ^ (context >> 3)) & mask;
int value = lookup[index]; lookup[index] = (int)(output - outputStart);
if (*input == LIBBSC_LZP_MATCH_FLAG && value > 0)
{
input++;
if (*input != 255)
{
int len = minLen; while (true) { len += *input; if (*input++ != 254) break; }
const unsigned char * reference = outputStart + value;
unsigned char * outputEnd = output + len;
while (output < outputEnd) *output++ = *reference++;
context = output[-1] | (output[-2] << 8) | (output[-3] << 16) | (output[-4] << 24);
}
else
{
input++; context = (context << 8) | (*output++ = LIBBSC_LZP_MATCH_FLAG);
}
}
else
{
context = (context << 8) | (*output++ = *input++);
}
}
bsc_free(lookup);
return (int)(output - outputStart);
}
return LIBBSC_NOT_ENOUGH_MEMORY;
}
int bsc_lzp_compress_serial(const unsigned char * input, unsigned char * output, int n, int hashSize, int minLen)
{
if (bsc_lzp_num_blocks(n) == 1)
{
int result = bsc_lzp_encode_block(input, input + n, output + 1, output + n - 1, hashSize, minLen);
if (result >= LIBBSC_NO_ERROR) result = (output[0] = 1, result + 1);
return result;
}
int nBlocks = bsc_lzp_num_blocks(n);
int chunkSize = n / nBlocks;
int outputPtr = 1 + 8 * nBlocks;
output[0] = nBlocks;
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
int inputStart = blockId * chunkSize;
int inputSize = blockId != nBlocks - 1 ? chunkSize : n - inputStart;
int outputSize = inputSize; if (outputSize > n - outputPtr) outputSize = n - outputPtr;
int result = bsc_lzp_encode_block(input + inputStart, input + inputStart + inputSize, output + outputPtr, output + outputPtr + outputSize, hashSize, minLen);
if (result < LIBBSC_NO_ERROR)
{
if (outputPtr + inputSize >= n) return LIBBSC_NOT_COMPRESSIBLE;
result = inputSize; memcpy(output + outputPtr, input + inputStart, inputSize);
}
*(int *)(output + 1 + 8 * blockId + 0) = inputSize;
*(int *)(output + 1 + 8 * blockId + 4) = result;
outputPtr += result;
}
return outputPtr;
}
#ifdef LIBBSC_OPENMP
int bsc_lzp_compress_parallel(const unsigned char * input, unsigned char * output, int n, int hashSize, int minLen)
{
if (unsigned char * buffer = (unsigned char *)bsc_malloc(n * sizeof(unsigned char)))
{
int compressionResult[ALPHABET_SIZE];
int nBlocks = bsc_lzp_num_blocks(n);
int result = LIBBSC_NO_ERROR;
int chunkSize = n / nBlocks;
int numThreads = omp_get_max_threads();
if (numThreads > nBlocks) numThreads = nBlocks;
output[0] = nBlocks;
#pragma omp parallel num_threads(numThreads) if(numThreads > 1)
{
if (omp_get_num_threads() == 1)
{
result = bsc_lzp_compress_serial(input, output, n, hashSize, minLen);
}
else
{
#pragma omp for schedule(dynamic)
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
int blockStart = blockId * chunkSize;
int blockSize = blockId != nBlocks - 1 ? chunkSize : n - blockStart;
compressionResult[blockId] = bsc_lzp_encode_block(input + blockStart, input + blockStart + blockSize, buffer + blockStart, buffer + blockStart + blockSize, hashSize, minLen);
if (compressionResult[blockId] < LIBBSC_NO_ERROR) compressionResult[blockId] = blockSize;
*(int *)(output + 1 + 8 * blockId + 0) = blockSize;
*(int *)(output + 1 + 8 * blockId + 4) = compressionResult[blockId];
}
#pragma omp single
{
result = 1 + 8 * nBlocks;
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
result += compressionResult[blockId];
}
if (result >= n) result = LIBBSC_NOT_COMPRESSIBLE;
}
if (result >= LIBBSC_NO_ERROR)
{
#pragma omp for schedule(dynamic)
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
int blockStart = blockId * chunkSize;
int blockSize = blockId != nBlocks - 1 ? chunkSize : n - blockStart;
int outputPtr = 1 + 8 * nBlocks;
for (int p = 0; p < blockId; ++p) outputPtr += compressionResult[p];
if (compressionResult[blockId] != blockSize)
{
memcpy(output + outputPtr, buffer + blockStart, compressionResult[blockId]);
}
else
{
memcpy(output + outputPtr, input + blockStart, compressionResult[blockId]);
}
}
}
}
}
bsc_free(buffer);
return result;
}
return LIBBSC_NOT_ENOUGH_MEMORY;
}
#endif
int bsc_lzp_compress(const unsigned char * input, unsigned char * output, int n, int hashSize, int minLen, int features)
{
#ifdef LIBBSC_OPENMP
if ((bsc_lzp_num_blocks(n) != 1) && (features & LIBBSC_FEATURE_MULTITHREADING))
{
return bsc_lzp_compress_parallel(input, output, n, hashSize, minLen);
}
#endif
return bsc_lzp_compress_serial(input, output, n, hashSize, minLen);
}
int bsc_lzp_decompress(const unsigned char * input, unsigned char * output, int n, int hashSize, int minLen, int features)
{
int nBlocks = input[0];
if (nBlocks == 1)
{
return bsc_lzp_decode_block(input + 1, input + n, output, hashSize, minLen);
}
int decompressionResult[ALPHABET_SIZE];
#ifdef LIBBSC_OPENMP
if (features & LIBBSC_FEATURE_MULTITHREADING)
{
#pragma omp parallel for schedule(dynamic)
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
int inputPtr = 0; for (int p = 0; p < blockId; ++p) inputPtr += *(int *)(input + 1 + 8 * p + 4);
int outputPtr = 0; for (int p = 0; p < blockId; ++p) outputPtr += *(int *)(input + 1 + 8 * p + 0);
inputPtr += 1 + 8 * nBlocks;
int inputSize = *(int *)(input + 1 + 8 * blockId + 4);
int outputSize = *(int *)(input + 1 + 8 * blockId + 0);
if (inputSize != outputSize)
{
decompressionResult[blockId] = bsc_lzp_decode_block(input + inputPtr, input + inputPtr + inputSize, output + outputPtr, hashSize, minLen);
}
else
{
decompressionResult[blockId] = inputSize; memcpy(output + outputPtr, input + inputPtr, inputSize);
}
}
}
else
#endif
{
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
int inputPtr = 0; for (int p = 0; p < blockId; ++p) inputPtr += *(int *)(input + 1 + 8 * p + 4);
int outputPtr = 0; for (int p = 0; p < blockId; ++p) outputPtr += *(int *)(input + 1 + 8 * p + 0);
inputPtr += 1 + 8 * nBlocks;
int inputSize = *(int *)(input + 1 + 8 * blockId + 4);
int outputSize = *(int *)(input + 1 + 8 * blockId + 0);
if (inputSize != outputSize)
{
decompressionResult[blockId] = bsc_lzp_decode_block(input + inputPtr, input + inputPtr + inputSize, output + outputPtr, hashSize, minLen);
}
else
{
decompressionResult[blockId] = inputSize; memcpy(output + outputPtr, input + inputPtr, inputSize);
}
}
}
int dataSize = 0, result = LIBBSC_NO_ERROR;
for (int blockId = 0; blockId < nBlocks; ++blockId)
{
if (decompressionResult[blockId] < LIBBSC_NO_ERROR) result = decompressionResult[blockId];
dataSize += decompressionResult[blockId];
}
return (result == LIBBSC_NO_ERROR) ? dataSize : result;
}
/*-----------------------------------------------------------*/
/* End lzp.cpp */
/*-----------------------------------------------------------*/
<|endoftext|>
|
<commit_before>/*
* Author: Csaszar, Peter <csjpeter@gmail.com>
* Copyright (C) 2011-2016 Csaszar, Peter
*/
#include "csjp_http.h"
/* TODO
* - HTTP 1.1 continue, keep-alive, chunked transfer support
*/
namespace csjp {
HTTPRequest::HTTPRequest(
const String & method,
const String & uri,
const String & body,
const String & version) :
method(method),
uri(uri),
version(version),
body(body)
{
requestLine.catf("% % HTTP/%",
method.length ? method.c_str() : "GET",
uri.length ? uri.c_str() : "/",
version.length ? version.c_str() : "1.0");
}
HTTPRequest HTTPRequest::get(
const String & uri,
const String & version)
{
(void)uri;
(void)version;
return HTTPRequest(String("GET"), uri, String(""), version);
}
HTTPRequest HTTPRequest::post(
const String & body,
const String & uri,
const String & version)
{
return HTTPRequest(String("POST"), uri, body, version);
}
HTTPRequest::operator String () const
{
String request;
request.catf("%\r\n", requestLine);
for(auto & h : headers.properties){
if(h.key == "content-length")
continue;
String k(h.key);
k.lower();
request.catf("%: %\r\n", k, h.value);
}
request.catf("content-length: %\r\n", body.length);
request.catf("\r\n%", body);
return request;
}
unsigned HTTPRequest::parse(const StringChunk & data)
{
if(!method.length){
size_t pos;
if(!data.findFirst(pos, "\r\n"))
return false;
requestLine <<= data.read(0, pos);
Array<StringChunk> result(3);
if(!subStringByRegexp(requestLine, result,
"\\([^ ]*\\) \\([^ ]*\\) HTTP/\\(.*\\)$"))
throw HttpProtocolError(
"Invalid HTTP request line: %",
requestLine);
method <<= result[0];
uri <<= result[1];
version <<= result[2];
}
if(!headers.value.length){
size_t pos;
if(!data.findFirst(pos, "\r\n\r\n", requestLine.length+2))
return false;
headers.value <<= data.read(requestLine.length+2, pos);
Array<StringChunk> array = split(headers.value, "\r\n");
String key;
for(auto & str : array){
if(str.findFirst(pos, ":")){
key <<= str.read(0, pos);
pos++;
key.trim(" \t");
key.lower();
} else {
if(!key.length)
throw HttpProtocolError(
"Invalid header line: %", str);
pos = 0;
}
StringChunk value(str.str + pos, str.length - pos);
if(!value.startsWith(" ") && !value.startsWith("\t"))
throw HttpProtocolError(
"Invalid multiline header "
"line: %", str);
value.trim(" \t");
headers[key].value << value;
}
}
if(!body.length){
size_t readIn = requestLine.length+2 + headers.value.length+4;
size_t bodyLength = 0;
bodyLength <<= headers["content-length"];
if(data.length < readIn + bodyLength)
return false;
body <<= data.read(readIn, readIn + bodyLength);
}
return true;
}
HTTPResponse::HTTPResponse(
HTTPStatusCode code,
const String & body,
const String & version
) :
version(version),
body(body)
{
statusCode <<= code;
reasonPhrase <<= code.phrase();
statusLine.catf("HTTP-% % %",
version.length ? version.c_str() : "1.0",
statusCode, reasonPhrase);
}
HTTPResponse::HTTPResponse(
const String & body,
const String & version) :
version(version),
body(body)
{
HTTPStatusCode code = HTTPStatusCode::Enum::OK;
statusCode <<= code;
reasonPhrase <<= code.phrase();
statusLine.catf("HTTP-% % %",
version.length ? version.c_str() : "1.0",
statusCode, reasonPhrase);
}
HTTPResponse::operator String () const
{
String response;
response.catf("%\r\n", statusLine);
for(auto & h : headers.properties){
if(h.key == "content-length")
continue;
String k(h.key);
k.lower();
response.catf("%: %\r\n", k, h.value);
}
response.catf("content-length: %\r\n", body.length);
response.catf("\r\n%", body);
return response;
}
unsigned HTTPResponse::parse(const StringChunk & data)
{
if(!statusCode.length){
size_t pos;
if(!data.findFirst(pos, "\r\n"))
return false;
statusLine <<= data.read(0, pos);
Array<StringChunk> result(3);
if(!subStringByRegexp(statusLine, result,
"HTTP-\\([^ ]*\\) \\([^ ]*\\) \\(.*\\)$"))
throw HttpProtocolError(
"Invalid HTTP status line: %",
statusLine);
version <<= result[0];
statusCode <<= result[1];
reasonPhrase <<= result[2];
}
if(!headers.value.length){
size_t pos;
if(!data.findFirst(pos, "\r\n\r\n", statusLine.length+2))
return false;
headers.value <<= data.read(statusLine.length+2, pos);
Array<StringChunk> array = split(headers.value, "\r\n");
String key;
for(auto & str : array){
if(str.findFirst(pos, ":")){
key <<= str.read(0, pos);
key.trim(" \t");
key.lower();
pos++;
} else {
if(!key.length)
throw HttpProtocolError(
"Invalid header line: %", str);
pos = 0;
}
StringChunk value(str.str + pos, str.length - pos);
if(!value.startsWith(" ") && !value.startsWith("\t"))
throw HttpProtocolError(
"Invalid multiline header "
"line: %", str);
value.trim(" \t");
headers[key].value << value;
}
}
if(!body.length){
size_t readIn = statusLine.length+2 + headers.value.length+4;
size_t bodyLength = 0;
bodyLength <<= headers["content-length"];
if(data.length < readIn + bodyLength)
return false;
body <<= data.read(readIn, readIn + bodyLength);
}
return true;
}
}
<commit_msg>HTTP header fix<commit_after>/*
* Author: Csaszar, Peter <csjpeter@gmail.com>
* Copyright (C) 2011-2016 Csaszar, Peter
*/
#include "csjp_http.h"
/* TODO
* - HTTP 1.1 continue, keep-alive, chunked transfer support
*/
namespace csjp {
HTTPRequest::HTTPRequest(
const String & method,
const String & uri,
const String & body,
const String & version) :
method(method),
uri(uri),
version(version),
body(body)
{
requestLine.catf("% % HTTP/%",
method.length ? method.c_str() : "GET",
uri.length ? uri.c_str() : "/",
version.length ? version.c_str() : "1.0");
}
HTTPRequest HTTPRequest::get(
const String & uri,
const String & version)
{
(void)uri;
(void)version;
return HTTPRequest(String("GET"), uri, String(""), version);
}
HTTPRequest HTTPRequest::post(
const String & body,
const String & uri,
const String & version)
{
return HTTPRequest(String("POST"), uri, body, version);
}
HTTPRequest::operator String () const
{
String request;
request.catf("%\r\n", requestLine);
for(auto & h : headers.properties){
if(h.key == "content-length")
continue;
String k(h.key);
k.lower();
request.catf("%: %\r\n", k, h.value);
}
request.catf("content-length: %\r\n", body.length);
request.catf("\r\n%", body);
return request;
}
unsigned HTTPRequest::parse(const StringChunk & data)
{
if(!method.length){
size_t pos;
if(!data.findFirst(pos, "\r\n"))
return false;
requestLine <<= data.read(0, pos);
Array<StringChunk> result(3);
if(!subStringByRegexp(requestLine, result,
"\\([^ ]*\\) \\([^ ]*\\) HTTP/\\(.*\\)$"))
throw HttpProtocolError(
"Invalid HTTP request line: %",
requestLine);
method <<= result[0];
uri <<= result[1];
version <<= result[2];
}
if(!headers.value.length){
size_t pos;
if(!data.findFirst(pos, "\r\n\r\n", requestLine.length+2))
return false;
headers.value <<= data.read(requestLine.length+2, pos);
Array<StringChunk> array = split(headers.value, "\r\n");
String key;
for(auto & str : array){
if(str.findFirst(pos, ":")){
key <<= str.read(0, pos);
pos++;
key.trim(" \t");
key.lower();
} else {
if(!key.length)
throw HttpProtocolError(
"Invalid header line: %", str);
pos = 0;
}
StringChunk value(str.str + pos, str.length - pos);
if(!value.startsWith(" ") && !value.startsWith("\t"))
throw HttpProtocolError(
"Invalid multiline header "
"line: %", str);
value.trim(" \t");
headers[key].value << value;
}
}
if(!body.length){
size_t readIn = requestLine.length+2 + headers.value.length+4;
size_t bodyLength = 0;
bodyLength <<= headers["content-length"];
if(data.length < readIn + bodyLength)
return false;
body <<= data.read(readIn, readIn + bodyLength);
}
return true;
}
HTTPResponse::HTTPResponse(
HTTPStatusCode code,
const String & body,
const String & version
) :
version(version),
body(body)
{
statusCode <<= code;
reasonPhrase <<= code.phrase();
statusLine.catf("HTTP/% % %",
version.length ? version.c_str() : "1.0",
statusCode, reasonPhrase);
}
HTTPResponse::HTTPResponse(
const String & body,
const String & version) :
version(version),
body(body)
{
HTTPStatusCode code = HTTPStatusCode::Enum::OK;
statusCode <<= code;
reasonPhrase <<= code.phrase();
statusLine.catf("HTTP/% % %",
version.length ? version.c_str() : "1.0",
statusCode, reasonPhrase);
}
HTTPResponse::operator String () const
{
String response;
response.catf("%\r\n", statusLine);
for(auto & h : headers.properties){
if(h.key == "content-length")
continue;
String k(h.key);
k.lower();
response.catf("%: %\r\n", k, h.value);
}
response.catf("content-length: %\r\n", body.length);
response.catf("\r\n%", body);
return response;
}
unsigned HTTPResponse::parse(const StringChunk & data)
{
if(!statusCode.length){
size_t pos;
if(!data.findFirst(pos, "\r\n"))
return false;
statusLine <<= data.read(0, pos);
Array<StringChunk> result(3);
if(!subStringByRegexp(statusLine, result,
"HTTP-\\([^ ]*\\) \\([^ ]*\\) \\(.*\\)$"))
throw HttpProtocolError(
"Invalid HTTP status line: %",
statusLine);
version <<= result[0];
statusCode <<= result[1];
reasonPhrase <<= result[2];
}
if(!headers.value.length){
size_t pos;
if(!data.findFirst(pos, "\r\n\r\n", statusLine.length+2))
return false;
headers.value <<= data.read(statusLine.length+2, pos);
Array<StringChunk> array = split(headers.value, "\r\n");
String key;
for(auto & str : array){
if(str.findFirst(pos, ":")){
key <<= str.read(0, pos);
key.trim(" \t");
key.lower();
pos++;
} else {
if(!key.length)
throw HttpProtocolError(
"Invalid header line: %", str);
pos = 0;
}
StringChunk value(str.str + pos, str.length - pos);
if(!value.startsWith(" ") && !value.startsWith("\t"))
throw HttpProtocolError(
"Invalid multiline header "
"line: %", str);
value.trim(" \t");
headers[key].value << value;
}
}
if(!body.length){
size_t readIn = statusLine.length+2 + headers.value.length+4;
size_t bodyLength = 0;
bodyLength <<= headers["content-length"];
if(data.length < readIn + bodyLength)
return false;
body <<= data.read(readIn, readIn + bodyLength);
}
return true;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 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 <boost/test/unit_test.hpp>
#include "base58.h"
#include "key.h"
#include "uint256.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_bitcoin.h"
#include <string>
#include <vector>
struct TestDerivation {
std::string pub;
std::string prv;
unsigned int nChild;
};
struct TestVector {
std::string strHexMaster;
std::vector<TestDerivation> vDerive;
TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {}
TestVector& operator()(std::string pub, std::string prv, unsigned int nChild) {
vDerive.push_back(TestDerivation());
TestDerivation &der = vDerive.back();
der.pub = pub;
der.prv = prv;
der.nChild = nChild;
return *this;
}
};
TestVector test1 =
TestVector("000102030405060708090a0b0c0d0e0f")
("xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8",
"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
0x80000000)
("xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw",
"xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
1)
("xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ",
"xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
0x80000002)
("xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5",
"xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
2)
("xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV",
"xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
1000000000)
("xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy",
"xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
0);
TestVector test2 =
TestVector("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542")
("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB",
"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
0)
("xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH",
"xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
0xFFFFFFFF)
("xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a",
"xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
1)
("xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon",
"xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
0xFFFFFFFE)
("xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL",
"xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
2)
("xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt",
"xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
0);
void RunTest(const TestVector &test) {
std::vector<unsigned char> seed = ParseHex(test.strHexMaster);
CExtKey key;
CExtPubKey pubkey;
key.SetMaster(&seed[0], seed.size());
pubkey = key.Neuter();
BOOST_FOREACH(const TestDerivation &derive, test.vDerive) {
unsigned char data[74];
key.Encode(data);
pubkey.Encode(data);
// Test private key
CBitcoinExtKey b58key; b58key.SetKey(key);
BOOST_CHECK(b58key.ToString() == derive.prv);
// Test public key
CBitcoinExtPubKey b58pubkey; b58pubkey.SetKey(pubkey);
BOOST_CHECK(b58pubkey.ToString() == derive.pub);
// Derive new keys
CExtKey keyNew;
BOOST_CHECK(key.Derive(keyNew, derive.nChild));
CExtPubKey pubkeyNew = keyNew.Neuter();
if (!(derive.nChild & 0x80000000)) {
// Compare with public derivation
CExtPubKey pubkeyNew2;
BOOST_CHECK(pubkey.Derive(pubkeyNew2, derive.nChild));
BOOST_CHECK(pubkeyNew == pubkeyNew2);
}
key = keyNew;
pubkey = pubkeyNew;
}
}
BOOST_FIXTURE_TEST_SUITE(bip32_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(bip32_test1) {
RunTest(test1);
}
BOOST_AUTO_TEST_CASE(bip32_test2) {
RunTest(test2);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>extend bip32 tests to cover Base58c/CExtKey decode<commit_after>// Copyright (c) 2013 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 <boost/test/unit_test.hpp>
#include "base58.h"
#include "key.h"
#include "uint256.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_bitcoin.h"
#include <string>
#include <vector>
struct TestDerivation {
std::string pub;
std::string prv;
unsigned int nChild;
};
struct TestVector {
std::string strHexMaster;
std::vector<TestDerivation> vDerive;
TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {}
TestVector& operator()(std::string pub, std::string prv, unsigned int nChild) {
vDerive.push_back(TestDerivation());
TestDerivation &der = vDerive.back();
der.pub = pub;
der.prv = prv;
der.nChild = nChild;
return *this;
}
};
TestVector test1 =
TestVector("000102030405060708090a0b0c0d0e0f")
("xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8",
"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
0x80000000)
("xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw",
"xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
1)
("xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ",
"xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
0x80000002)
("xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5",
"xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
2)
("xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV",
"xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
1000000000)
("xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy",
"xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
0);
TestVector test2 =
TestVector("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542")
("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB",
"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
0)
("xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH",
"xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
0xFFFFFFFF)
("xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a",
"xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
1)
("xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon",
"xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
0xFFFFFFFE)
("xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL",
"xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
2)
("xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt",
"xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
0);
void RunTest(const TestVector &test) {
std::vector<unsigned char> seed = ParseHex(test.strHexMaster);
CExtKey key;
CExtPubKey pubkey;
key.SetMaster(&seed[0], seed.size());
pubkey = key.Neuter();
BOOST_FOREACH(const TestDerivation &derive, test.vDerive) {
unsigned char data[74];
key.Encode(data);
pubkey.Encode(data);
// Test private key
CBitcoinExtKey b58key; b58key.SetKey(key);
BOOST_CHECK(b58key.ToString() == derive.prv);
CBitcoinExtKey b58keyDecodeCheck(derive.prv);
CExtKey checkKey = b58keyDecodeCheck.GetKey();
assert(checkKey == key); //ensure a base58 decoded key also matches
// Test public key
CBitcoinExtPubKey b58pubkey; b58pubkey.SetKey(pubkey);
BOOST_CHECK(b58pubkey.ToString() == derive.pub);
CBitcoinExtPubKey b58PubkeyDecodeCheck(derive.pub);
CExtPubKey checkPubKey = b58PubkeyDecodeCheck.GetKey();
assert(checkPubKey == pubkey); //ensure a base58 decoded pubkey also matches
// Derive new keys
CExtKey keyNew;
BOOST_CHECK(key.Derive(keyNew, derive.nChild));
CExtPubKey pubkeyNew = keyNew.Neuter();
if (!(derive.nChild & 0x80000000)) {
// Compare with public derivation
CExtPubKey pubkeyNew2;
BOOST_CHECK(pubkey.Derive(pubkeyNew2, derive.nChild));
BOOST_CHECK(pubkeyNew == pubkeyNew2);
}
key = keyNew;
pubkey = pubkeyNew;
}
}
BOOST_FIXTURE_TEST_SUITE(bip32_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(bip32_test1) {
RunTest(test1);
}
BOOST_AUTO_TEST_CASE(bip32_test2) {
RunTest(test2);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>// Copyright (c) 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 <chainparams.h>
#include <compressor.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <pubkey.h>
#include <script/descriptor.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <univalue.h>
#include <util/memory.h>
void initialize()
{
// Fuzzers using pubkey must hold an ECCVerifyHandle.
static const ECCVerifyHandle verify_handle;
SelectParams(CBaseChainParams::REGTEST);
}
void test_one_input(const std::vector<uint8_t>& buffer)
{
const CScript script(buffer.begin(), buffer.end());
std::vector<unsigned char> compressed;
if (CompressScript(script, compressed)) {
const unsigned int size = compressed[0];
compressed.erase(compressed.begin());
assert(size >= 0 && size <= 5);
CScript decompressed_script;
const bool ok = DecompressScript(decompressed_script, size, compressed);
assert(ok);
assert(script == decompressed_script);
}
CTxDestination address;
(void)ExtractDestination(script, address);
txnouttype type_ret;
std::vector<CTxDestination> addresses;
int required_ret;
(void)ExtractDestinations(script, type_ret, addresses, required_ret);
(void)GetScriptForWitness(script);
const FlatSigningProvider signing_provider;
(void)InferDescriptor(script, signing_provider);
(void)IsSegWitOutput(signing_provider, script);
(void)IsSolvable(signing_provider, script);
txnouttype which_type;
(void)IsStandard(script, which_type);
(void)RecursiveDynamicUsage(script);
std::vector<std::vector<unsigned char>> solutions;
(void)Solver(script, solutions);
(void)script.HasValidOps();
(void)script.IsPayToScriptHash();
(void)script.IsPayToWitnessScriptHash();
(void)script.IsPushOnly();
(void)script.IsUnspendable();
(void)script.GetSigOpCount(/* fAccurate= */ false);
(void)FormatScript(script);
(void)ScriptToAsmStr(script, false);
(void)ScriptToAsmStr(script, true);
UniValue o1(UniValue::VOBJ);
ScriptPubKeyToUniv(script, o1, true);
UniValue o2(UniValue::VOBJ);
ScriptPubKeyToUniv(script, o2, false);
UniValue o3(UniValue::VOBJ);
ScriptToUniv(script, o3, true);
UniValue o4(UniValue::VOBJ);
ScriptToUniv(script, o4, false);
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
// DecompressScript(..., ..., bytes) is not guaranteed to be defined if bytes.size() <= 23.
if (bytes.size() >= 24) {
CScript decompressed_script;
DecompressScript(decompressed_script, fuzzed_data_provider.ConsumeIntegral<unsigned int>(), bytes);
}
}
}
<commit_msg>fuzz: Extend script fuzz test<commit_after>// Copyright (c) 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 <chainparams.h>
#include <compressor.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <pubkey.h>
#include <script/descriptor.h>
#include <script/interpreter.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <univalue.h>
#include <util/memory.h>
void initialize()
{
// Fuzzers using pubkey must hold an ECCVerifyHandle.
static const ECCVerifyHandle verify_handle;
SelectParams(CBaseChainParams::REGTEST);
}
void test_one_input(const std::vector<uint8_t>& buffer)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const Optional<CScript> script_opt = ConsumeDeserializable<CScript>(fuzzed_data_provider);
if (!script_opt) return;
const CScript script{*script_opt};
std::vector<unsigned char> compressed;
if (CompressScript(script, compressed)) {
const unsigned int size = compressed[0];
compressed.erase(compressed.begin());
assert(size >= 0 && size <= 5);
CScript decompressed_script;
const bool ok = DecompressScript(decompressed_script, size, compressed);
assert(ok);
assert(script == decompressed_script);
}
CTxDestination address;
(void)ExtractDestination(script, address);
txnouttype type_ret;
std::vector<CTxDestination> addresses;
int required_ret;
(void)ExtractDestinations(script, type_ret, addresses, required_ret);
(void)GetScriptForWitness(script);
const FlatSigningProvider signing_provider;
(void)InferDescriptor(script, signing_provider);
(void)IsSegWitOutput(signing_provider, script);
(void)IsSolvable(signing_provider, script);
txnouttype which_type;
(void)IsStandard(script, which_type);
(void)RecursiveDynamicUsage(script);
std::vector<std::vector<unsigned char>> solutions;
(void)Solver(script, solutions);
(void)script.HasValidOps();
(void)script.IsPayToScriptHash();
(void)script.IsPayToWitnessScriptHash();
(void)script.IsPushOnly();
(void)script.IsUnspendable();
(void)script.GetSigOpCount(/* fAccurate= */ false);
(void)FormatScript(script);
(void)ScriptToAsmStr(script, false);
(void)ScriptToAsmStr(script, true);
UniValue o1(UniValue::VOBJ);
ScriptPubKeyToUniv(script, o1, true);
UniValue o2(UniValue::VOBJ);
ScriptPubKeyToUniv(script, o2, false);
UniValue o3(UniValue::VOBJ);
ScriptToUniv(script, o3, true);
UniValue o4(UniValue::VOBJ);
ScriptToUniv(script, o4, false);
{
const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
// DecompressScript(..., ..., bytes) is not guaranteed to be defined if the bytes vector is too short
if (bytes.size() >= 32) {
CScript decompressed_script;
DecompressScript(decompressed_script, fuzzed_data_provider.ConsumeIntegral<unsigned int>(), bytes);
}
}
const Optional<CScript> other_script = ConsumeDeserializable<CScript>(fuzzed_data_provider);
if (other_script) {
{
CScript script_mut{script};
(void)FindAndDelete(script_mut, *other_script);
}
const std::vector<std::string> random_string_vector = ConsumeRandomLengthStringVector(fuzzed_data_provider);
const uint32_t u32{fuzzed_data_provider.ConsumeIntegral<uint32_t>()};
const uint32_t flags{u32 | SCRIPT_VERIFY_P2SH};
{
CScriptWitness wit;
for (const auto& s : random_string_vector) {
wit.stack.emplace_back(s.begin(), s.end());
}
(void)CountWitnessSigOps(script, *other_script, &wit, flags);
wit.SetNull();
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2019 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <radix.h>
#include <test/lcg.h>
#include <test/util/setup_common.h>
#include <boost/test/unit_test.hpp>
#include <limits>
#include <type_traits>
BOOST_FIXTURE_TEST_SUITE(radix_tests, BasicTestingSetup)
template <typename K> struct TestElement {
K key;
TestElement(K keyIn) : key(keyIn) {}
const K &getId() const { return key; }
IMPLEMENT_RCU_REFCOUNT(uint32_t);
};
template <typename K> void testInsert() {
typedef TestElement<K> E;
RadixTree<E> mytree;
auto zero = RCUPtr<E>::make(0);
auto one = RCUPtr<E>::make(1);
auto two = RCUPtr<E>::make(2);
auto three = RCUPtr<E>::make(3);
// Inserting a new element into the tree returns true.
BOOST_CHECK(mytree.insert(one));
// Inserting an element already in the tree returns false.
BOOST_CHECK(!mytree.insert(one));
// Let's insert more elements and check behavior stays consistent.
BOOST_CHECK(mytree.insert(zero));
BOOST_CHECK(!mytree.insert(one));
BOOST_CHECK(mytree.insert(two));
BOOST_CHECK(mytree.insert(three));
BOOST_CHECK(!mytree.insert(zero));
BOOST_CHECK(!mytree.insert(one));
BOOST_CHECK(!mytree.insert(two));
BOOST_CHECK(!mytree.insert(three));
// Check extreme values.
typedef typename std::make_signed<K>::type SK;
auto maxsigned = RCUPtr<E>::make(std::numeric_limits<SK>::max());
auto minsigned = RCUPtr<E>::make(std::numeric_limits<SK>::min());
typedef typename std::make_unsigned<K>::type UK;
auto minusone = RCUPtr<E>::make(std::numeric_limits<UK>::max());
auto minustwo = RCUPtr<E>::make(std::numeric_limits<UK>::max() - 1);
// Insert them into the tree.
BOOST_CHECK(mytree.insert(maxsigned));
BOOST_CHECK(mytree.insert(minsigned));
BOOST_CHECK(mytree.insert(minusone));
BOOST_CHECK(mytree.insert(minustwo));
// All elements are now in the tree.
BOOST_CHECK(!mytree.insert(zero));
BOOST_CHECK(!mytree.insert(one));
BOOST_CHECK(!mytree.insert(two));
BOOST_CHECK(!mytree.insert(three));
BOOST_CHECK(!mytree.insert(maxsigned));
BOOST_CHECK(!mytree.insert(minsigned));
BOOST_CHECK(!mytree.insert(minusone));
BOOST_CHECK(!mytree.insert(minustwo));
}
BOOST_AUTO_TEST_CASE(insert_test) {
testInsert<int32_t>();
testInsert<uint32_t>();
testInsert<int64_t>();
testInsert<uint64_t>();
}
template <typename K> void testGet() {
typedef TestElement<K> E;
RadixTree<E> mytree;
auto zero = RCUPtr<E>::make(0);
auto one = RCUPtr<E>::make(1);
auto two = RCUPtr<E>::make(2);
auto three = RCUPtr<E>::make(3);
// There are no elements in the tree so far.
BOOST_CHECK_EQUAL(mytree.get(1), NULLPTR(E));
// Insert an element into the tree and check it is there.
BOOST_CHECK(mytree.insert(one));
BOOST_CHECK_EQUAL(mytree.get(1), one);
// Let's insert more elements and check they are recovered properly.
BOOST_CHECK_EQUAL(mytree.get(0), NULLPTR(E));
BOOST_CHECK(mytree.insert(zero));
BOOST_CHECK_EQUAL(mytree.get(0), zero);
BOOST_CHECK_EQUAL(mytree.get(1), one);
// More elements.
BOOST_CHECK_EQUAL(mytree.get(2), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(3), NULLPTR(E));
BOOST_CHECK(mytree.insert(two));
BOOST_CHECK(mytree.insert(three));
BOOST_CHECK_EQUAL(mytree.get(0), zero);
BOOST_CHECK_EQUAL(mytree.get(1), one);
BOOST_CHECK_EQUAL(mytree.get(2), two);
BOOST_CHECK_EQUAL(mytree.get(3), three);
// Check extreme values.
typedef typename std::make_signed<K>::type SK;
K maxsk = std::numeric_limits<SK>::max();
K minsk = std::numeric_limits<SK>::min();
typedef typename std::make_unsigned<K>::type UK;
K maxuk = std::numeric_limits<UK>::max();
auto maxsigned = RCUPtr<E>::make(maxsk);
auto minsigned = RCUPtr<E>::make(minsk);
auto minusone = RCUPtr<E>::make(maxuk);
auto minustwo = RCUPtr<E>::make(maxuk - 1);
// Check that they are not in the tree.
BOOST_CHECK_EQUAL(mytree.get(maxsk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(minsk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(maxuk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(maxuk - 1), NULLPTR(E));
// Insert into the tree.
BOOST_CHECK(mytree.insert(maxsigned));
BOOST_CHECK(mytree.insert(minsigned));
BOOST_CHECK(mytree.insert(minusone));
BOOST_CHECK(mytree.insert(minustwo));
// And now they all are in the tree.
BOOST_CHECK_EQUAL(mytree.get(0), zero);
BOOST_CHECK_EQUAL(mytree.get(1), one);
BOOST_CHECK_EQUAL(mytree.get(2), two);
BOOST_CHECK_EQUAL(mytree.get(3), three);
BOOST_CHECK_EQUAL(mytree.get(maxsk), maxsigned);
BOOST_CHECK_EQUAL(mytree.get(minsk), minsigned);
BOOST_CHECK_EQUAL(mytree.get(maxuk), minusone);
BOOST_CHECK_EQUAL(mytree.get(maxuk - 1), minustwo);
}
BOOST_AUTO_TEST_CASE(get_test) {
testGet<int32_t>();
testGet<uint32_t>();
testGet<int64_t>();
testGet<uint64_t>();
}
template <typename K> void testRemove() {
typedef TestElement<K> E;
RadixTree<E> mytree;
auto zero = RCUPtr<E>::make(0);
auto one = RCUPtr<E>::make(1);
auto two = RCUPtr<E>::make(2);
auto three = RCUPtr<E>::make(3);
// Removing an element that isn't in the tree returns false.
BOOST_CHECK(!mytree.remove(1));
// Insert an element into the tree and check you can remove it.
BOOST_CHECK(mytree.insert(one));
BOOST_CHECK(mytree.remove(1));
BOOST_CHECK_EQUAL(mytree.get(1), NULLPTR(E));
// Insert several elements and remove them.
BOOST_CHECK(mytree.insert(zero));
BOOST_CHECK(mytree.insert(one));
BOOST_CHECK(mytree.insert(two));
BOOST_CHECK(mytree.insert(three));
BOOST_CHECK(mytree.remove(0));
BOOST_CHECK(mytree.remove(1));
BOOST_CHECK(mytree.remove(2));
BOOST_CHECK(mytree.remove(3));
BOOST_CHECK_EQUAL(mytree.get(0), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(1), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(2), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(3), NULLPTR(E));
// Once the elements are removed, removing them again returns false.
BOOST_CHECK(!mytree.remove(0));
BOOST_CHECK(!mytree.remove(1));
BOOST_CHECK(!mytree.remove(2));
BOOST_CHECK(!mytree.remove(3));
// Check extreme values.
typedef typename std::make_signed<K>::type SK;
K maxsk = std::numeric_limits<SK>::max();
K minsk = std::numeric_limits<SK>::min();
typedef typename std::make_unsigned<K>::type UK;
K maxuk = std::numeric_limits<UK>::max();
auto maxsigned = RCUPtr<E>::make(maxsk);
auto minsigned = RCUPtr<E>::make(minsk);
auto minusone = RCUPtr<E>::make(maxuk);
auto minustwo = RCUPtr<E>::make(maxuk - 1);
// Insert them all.
BOOST_CHECK(mytree.insert(zero));
BOOST_CHECK(mytree.insert(one));
BOOST_CHECK(mytree.insert(two));
BOOST_CHECK(mytree.insert(three));
BOOST_CHECK(mytree.insert(maxsigned));
BOOST_CHECK(mytree.insert(minsigned));
BOOST_CHECK(mytree.insert(minusone));
BOOST_CHECK(mytree.insert(minustwo));
// Delete them all
BOOST_CHECK(mytree.remove(0));
BOOST_CHECK(mytree.remove(1));
BOOST_CHECK(mytree.remove(2));
BOOST_CHECK(mytree.remove(3));
BOOST_CHECK(mytree.remove(maxsk));
BOOST_CHECK(mytree.remove(minsk));
BOOST_CHECK(mytree.remove(maxuk));
BOOST_CHECK(mytree.remove(maxuk - 1));
BOOST_CHECK_EQUAL(mytree.get(0), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(1), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(2), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(3), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(maxsk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(minsk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(maxuk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(maxuk - 1), NULLPTR(E));
}
BOOST_AUTO_TEST_CASE(remove_test) {
testRemove<int32_t>();
testRemove<uint32_t>();
testRemove<int64_t>();
testRemove<uint64_t>();
}
BOOST_AUTO_TEST_CASE(const_element_test) {
typedef const TestElement<uint64_t> C;
RadixTree<C> mytree;
BOOST_CHECK(mytree.insert(RCUPtr<C>::make(0)));
BOOST_CHECK(mytree.insert(RCUPtr<C>::make(1)));
BOOST_CHECK(mytree.insert(RCUPtr<C>::make(2)));
BOOST_CHECK(mytree.insert(RCUPtr<C>::make(3)));
BOOST_CHECK(!mytree.insert(RCUPtr<C>::make(0)));
BOOST_CHECK(!mytree.insert(RCUPtr<C>::make(1)));
BOOST_CHECK(!mytree.insert(RCUPtr<C>::make(2)));
BOOST_CHECK(!mytree.insert(RCUPtr<C>::make(3)));
BOOST_CHECK(mytree.get(0));
BOOST_CHECK(mytree.get(1));
BOOST_CHECK(mytree.get(2));
BOOST_CHECK(mytree.get(3));
BOOST_CHECK(mytree.remove(0));
BOOST_CHECK(mytree.remove(1));
BOOST_CHECK(mytree.remove(2));
BOOST_CHECK(mytree.remove(3));
BOOST_CHECK(!mytree.get(0));
BOOST_CHECK(!mytree.get(1));
BOOST_CHECK(!mytree.get(2));
BOOST_CHECK(!mytree.get(3));
BOOST_CHECK(!mytree.remove(0));
BOOST_CHECK(!mytree.remove(1));
BOOST_CHECK(!mytree.remove(2));
BOOST_CHECK(!mytree.remove(3));
}
void CheckConstTree(const RadixTree<TestElement<uint64_t>> &mytree,
bool expected) {
BOOST_CHECK_EQUAL(!!mytree.get(0), expected);
BOOST_CHECK_EQUAL(!!mytree.get(1), expected);
BOOST_CHECK_EQUAL(!!mytree.get(2), expected);
BOOST_CHECK_EQUAL(!!mytree.get(3), expected);
}
BOOST_AUTO_TEST_CASE(const_tree_test) {
typedef TestElement<uint64_t> E;
RadixTree<E> mytree;
CheckConstTree(mytree, false);
BOOST_CHECK(mytree.insert(RCUPtr<E>::make(0)));
BOOST_CHECK(mytree.insert(RCUPtr<E>::make(1)));
BOOST_CHECK(mytree.insert(RCUPtr<E>::make(2)));
BOOST_CHECK(mytree.insert(RCUPtr<E>::make(3)));
CheckConstTree(mytree, true);
BOOST_CHECK(mytree.remove(0));
BOOST_CHECK(mytree.remove(1));
BOOST_CHECK(mytree.remove(2));
BOOST_CHECK(mytree.remove(3));
CheckConstTree(mytree, false);
}
#define THREADS 128
#define ELEMENTS 65536
BOOST_AUTO_TEST_CASE(insert_stress_test) {
typedef TestElement<uint32_t> E;
RadixTree<E> mytree;
std::atomic<uint32_t> success{0};
std::vector<std::thread> threads;
for (int i = 0; i < THREADS; i++) {
threads.push_back(std::thread([&] {
MMIXLinearCongruentialGenerator lcg;
for (int j = 0; j < ELEMENTS; j++) {
uint32_t v = lcg.next();
if (mytree.remove(v)) {
success--;
std::this_thread::yield();
}
auto ptr = RCUPtr<E>::make(v);
if (mytree.insert(ptr)) {
success++;
std::this_thread::yield();
}
if (mytree.remove(v)) {
success--;
std::this_thread::yield();
}
if (mytree.insert(ptr)) {
success++;
std::this_thread::yield();
}
}
}));
}
// Wait for all the threads to finish.
for (std::thread &t : threads) {
t.join();
}
BOOST_CHECK_EQUAL(success.load(), ELEMENTS);
// All the elements have been inserted into the tree.
MMIXLinearCongruentialGenerator lcg;
for (int i = 0; i < ELEMENTS; i++) {
uint32_t v = lcg.next();
BOOST_CHECK_EQUAL(mytree.get(v)->getId(), v);
auto ptr = RCUPtr<E>::make(v);
BOOST_CHECK(!mytree.insert(ptr));
BOOST_CHECK(mytree.get(v) != ptr);
}
// Cleanup after ourselves.
RCULock::synchronize();
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Use using instead of typedef int he radix code<commit_after>// Copyright (c) 2019 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <radix.h>
#include <test/lcg.h>
#include <test/util/setup_common.h>
#include <boost/test/unit_test.hpp>
#include <limits>
#include <type_traits>
BOOST_FIXTURE_TEST_SUITE(radix_tests, BasicTestingSetup)
template <typename K> struct TestElement {
K key;
TestElement(K keyIn) : key(keyIn) {}
const K &getId() const { return key; }
IMPLEMENT_RCU_REFCOUNT(uint32_t);
};
template <typename K> void testInsert() {
using E = TestElement<K>;
RadixTree<E> mytree;
auto zero = RCUPtr<E>::make(0);
auto one = RCUPtr<E>::make(1);
auto two = RCUPtr<E>::make(2);
auto three = RCUPtr<E>::make(3);
// Inserting a new element into the tree returns true.
BOOST_CHECK(mytree.insert(one));
// Inserting an element already in the tree returns false.
BOOST_CHECK(!mytree.insert(one));
// Let's insert more elements and check behavior stays consistent.
BOOST_CHECK(mytree.insert(zero));
BOOST_CHECK(!mytree.insert(one));
BOOST_CHECK(mytree.insert(two));
BOOST_CHECK(mytree.insert(three));
BOOST_CHECK(!mytree.insert(zero));
BOOST_CHECK(!mytree.insert(one));
BOOST_CHECK(!mytree.insert(two));
BOOST_CHECK(!mytree.insert(three));
// Check extreme values.
using SK = typename std::make_signed<K>::type;
auto maxsigned = RCUPtr<E>::make(std::numeric_limits<SK>::max());
auto minsigned = RCUPtr<E>::make(std::numeric_limits<SK>::min());
using UK = typename std::make_unsigned<K>::type;
auto minusone = RCUPtr<E>::make(std::numeric_limits<UK>::max());
auto minustwo = RCUPtr<E>::make(std::numeric_limits<UK>::max() - 1);
// Insert them into the tree.
BOOST_CHECK(mytree.insert(maxsigned));
BOOST_CHECK(mytree.insert(minsigned));
BOOST_CHECK(mytree.insert(minusone));
BOOST_CHECK(mytree.insert(minustwo));
// All elements are now in the tree.
BOOST_CHECK(!mytree.insert(zero));
BOOST_CHECK(!mytree.insert(one));
BOOST_CHECK(!mytree.insert(two));
BOOST_CHECK(!mytree.insert(three));
BOOST_CHECK(!mytree.insert(maxsigned));
BOOST_CHECK(!mytree.insert(minsigned));
BOOST_CHECK(!mytree.insert(minusone));
BOOST_CHECK(!mytree.insert(minustwo));
}
BOOST_AUTO_TEST_CASE(insert_test) {
testInsert<int32_t>();
testInsert<uint32_t>();
testInsert<int64_t>();
testInsert<uint64_t>();
}
template <typename K> void testGet() {
using E = TestElement<K>;
RadixTree<E> mytree;
auto zero = RCUPtr<E>::make(0);
auto one = RCUPtr<E>::make(1);
auto two = RCUPtr<E>::make(2);
auto three = RCUPtr<E>::make(3);
// There are no elements in the tree so far.
BOOST_CHECK_EQUAL(mytree.get(1), NULLPTR(E));
// Insert an element into the tree and check it is there.
BOOST_CHECK(mytree.insert(one));
BOOST_CHECK_EQUAL(mytree.get(1), one);
// Let's insert more elements and check they are recovered properly.
BOOST_CHECK_EQUAL(mytree.get(0), NULLPTR(E));
BOOST_CHECK(mytree.insert(zero));
BOOST_CHECK_EQUAL(mytree.get(0), zero);
BOOST_CHECK_EQUAL(mytree.get(1), one);
// More elements.
BOOST_CHECK_EQUAL(mytree.get(2), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(3), NULLPTR(E));
BOOST_CHECK(mytree.insert(two));
BOOST_CHECK(mytree.insert(three));
BOOST_CHECK_EQUAL(mytree.get(0), zero);
BOOST_CHECK_EQUAL(mytree.get(1), one);
BOOST_CHECK_EQUAL(mytree.get(2), two);
BOOST_CHECK_EQUAL(mytree.get(3), three);
// Check extreme values.
using SK = typename std::make_signed<K>::type;
K maxsk = std::numeric_limits<SK>::max();
K minsk = std::numeric_limits<SK>::min();
using UK = typename std::make_unsigned<K>::type;
K maxuk = std::numeric_limits<UK>::max();
auto maxsigned = RCUPtr<E>::make(maxsk);
auto minsigned = RCUPtr<E>::make(minsk);
auto minusone = RCUPtr<E>::make(maxuk);
auto minustwo = RCUPtr<E>::make(maxuk - 1);
// Check that they are not in the tree.
BOOST_CHECK_EQUAL(mytree.get(maxsk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(minsk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(maxuk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(maxuk - 1), NULLPTR(E));
// Insert into the tree.
BOOST_CHECK(mytree.insert(maxsigned));
BOOST_CHECK(mytree.insert(minsigned));
BOOST_CHECK(mytree.insert(minusone));
BOOST_CHECK(mytree.insert(minustwo));
// And now they all are in the tree.
BOOST_CHECK_EQUAL(mytree.get(0), zero);
BOOST_CHECK_EQUAL(mytree.get(1), one);
BOOST_CHECK_EQUAL(mytree.get(2), two);
BOOST_CHECK_EQUAL(mytree.get(3), three);
BOOST_CHECK_EQUAL(mytree.get(maxsk), maxsigned);
BOOST_CHECK_EQUAL(mytree.get(minsk), minsigned);
BOOST_CHECK_EQUAL(mytree.get(maxuk), minusone);
BOOST_CHECK_EQUAL(mytree.get(maxuk - 1), minustwo);
}
BOOST_AUTO_TEST_CASE(get_test) {
testGet<int32_t>();
testGet<uint32_t>();
testGet<int64_t>();
testGet<uint64_t>();
}
template <typename K> void testRemove() {
using E = TestElement<K>;
RadixTree<E> mytree;
auto zero = RCUPtr<E>::make(0);
auto one = RCUPtr<E>::make(1);
auto two = RCUPtr<E>::make(2);
auto three = RCUPtr<E>::make(3);
// Removing an element that isn't in the tree returns false.
BOOST_CHECK(!mytree.remove(1));
// Insert an element into the tree and check you can remove it.
BOOST_CHECK(mytree.insert(one));
BOOST_CHECK(mytree.remove(1));
BOOST_CHECK_EQUAL(mytree.get(1), NULLPTR(E));
// Insert several elements and remove them.
BOOST_CHECK(mytree.insert(zero));
BOOST_CHECK(mytree.insert(one));
BOOST_CHECK(mytree.insert(two));
BOOST_CHECK(mytree.insert(three));
BOOST_CHECK(mytree.remove(0));
BOOST_CHECK(mytree.remove(1));
BOOST_CHECK(mytree.remove(2));
BOOST_CHECK(mytree.remove(3));
BOOST_CHECK_EQUAL(mytree.get(0), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(1), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(2), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(3), NULLPTR(E));
// Once the elements are removed, removing them again returns false.
BOOST_CHECK(!mytree.remove(0));
BOOST_CHECK(!mytree.remove(1));
BOOST_CHECK(!mytree.remove(2));
BOOST_CHECK(!mytree.remove(3));
// Check extreme values.
using SK = typename std::make_signed<K>::type;
K maxsk = std::numeric_limits<SK>::max();
K minsk = std::numeric_limits<SK>::min();
using UK = typename std::make_unsigned<K>::type;
K maxuk = std::numeric_limits<UK>::max();
auto maxsigned = RCUPtr<E>::make(maxsk);
auto minsigned = RCUPtr<E>::make(minsk);
auto minusone = RCUPtr<E>::make(maxuk);
auto minustwo = RCUPtr<E>::make(maxuk - 1);
// Insert them all.
BOOST_CHECK(mytree.insert(zero));
BOOST_CHECK(mytree.insert(one));
BOOST_CHECK(mytree.insert(two));
BOOST_CHECK(mytree.insert(three));
BOOST_CHECK(mytree.insert(maxsigned));
BOOST_CHECK(mytree.insert(minsigned));
BOOST_CHECK(mytree.insert(minusone));
BOOST_CHECK(mytree.insert(minustwo));
// Delete them all
BOOST_CHECK(mytree.remove(0));
BOOST_CHECK(mytree.remove(1));
BOOST_CHECK(mytree.remove(2));
BOOST_CHECK(mytree.remove(3));
BOOST_CHECK(mytree.remove(maxsk));
BOOST_CHECK(mytree.remove(minsk));
BOOST_CHECK(mytree.remove(maxuk));
BOOST_CHECK(mytree.remove(maxuk - 1));
BOOST_CHECK_EQUAL(mytree.get(0), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(1), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(2), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(3), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(maxsk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(minsk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(maxuk), NULLPTR(E));
BOOST_CHECK_EQUAL(mytree.get(maxuk - 1), NULLPTR(E));
}
BOOST_AUTO_TEST_CASE(remove_test) {
testRemove<int32_t>();
testRemove<uint32_t>();
testRemove<int64_t>();
testRemove<uint64_t>();
}
BOOST_AUTO_TEST_CASE(const_element_test) {
using C = const TestElement<uint64_t>;
RadixTree<C> mytree;
BOOST_CHECK(mytree.insert(RCUPtr<C>::make(0)));
BOOST_CHECK(mytree.insert(RCUPtr<C>::make(1)));
BOOST_CHECK(mytree.insert(RCUPtr<C>::make(2)));
BOOST_CHECK(mytree.insert(RCUPtr<C>::make(3)));
BOOST_CHECK(!mytree.insert(RCUPtr<C>::make(0)));
BOOST_CHECK(!mytree.insert(RCUPtr<C>::make(1)));
BOOST_CHECK(!mytree.insert(RCUPtr<C>::make(2)));
BOOST_CHECK(!mytree.insert(RCUPtr<C>::make(3)));
BOOST_CHECK(mytree.get(0));
BOOST_CHECK(mytree.get(1));
BOOST_CHECK(mytree.get(2));
BOOST_CHECK(mytree.get(3));
BOOST_CHECK(mytree.remove(0));
BOOST_CHECK(mytree.remove(1));
BOOST_CHECK(mytree.remove(2));
BOOST_CHECK(mytree.remove(3));
BOOST_CHECK(!mytree.get(0));
BOOST_CHECK(!mytree.get(1));
BOOST_CHECK(!mytree.get(2));
BOOST_CHECK(!mytree.get(3));
BOOST_CHECK(!mytree.remove(0));
BOOST_CHECK(!mytree.remove(1));
BOOST_CHECK(!mytree.remove(2));
BOOST_CHECK(!mytree.remove(3));
}
void CheckConstTree(const RadixTree<TestElement<uint64_t>> &mytree,
bool expected) {
BOOST_CHECK_EQUAL(!!mytree.get(0), expected);
BOOST_CHECK_EQUAL(!!mytree.get(1), expected);
BOOST_CHECK_EQUAL(!!mytree.get(2), expected);
BOOST_CHECK_EQUAL(!!mytree.get(3), expected);
}
BOOST_AUTO_TEST_CASE(const_tree_test) {
using E = TestElement<uint64_t>;
RadixTree<E> mytree;
CheckConstTree(mytree, false);
BOOST_CHECK(mytree.insert(RCUPtr<E>::make(0)));
BOOST_CHECK(mytree.insert(RCUPtr<E>::make(1)));
BOOST_CHECK(mytree.insert(RCUPtr<E>::make(2)));
BOOST_CHECK(mytree.insert(RCUPtr<E>::make(3)));
CheckConstTree(mytree, true);
BOOST_CHECK(mytree.remove(0));
BOOST_CHECK(mytree.remove(1));
BOOST_CHECK(mytree.remove(2));
BOOST_CHECK(mytree.remove(3));
CheckConstTree(mytree, false);
}
#define THREADS 128
#define ELEMENTS 65536
BOOST_AUTO_TEST_CASE(insert_stress_test) {
using E = TestElement<uint32_t>;
RadixTree<E> mytree;
std::atomic<uint32_t> success{0};
std::vector<std::thread> threads;
for (int i = 0; i < THREADS; i++) {
threads.push_back(std::thread([&] {
MMIXLinearCongruentialGenerator lcg;
for (int j = 0; j < ELEMENTS; j++) {
uint32_t v = lcg.next();
if (mytree.remove(v)) {
success--;
std::this_thread::yield();
}
auto ptr = RCUPtr<E>::make(v);
if (mytree.insert(ptr)) {
success++;
std::this_thread::yield();
}
if (mytree.remove(v)) {
success--;
std::this_thread::yield();
}
if (mytree.insert(ptr)) {
success++;
std::this_thread::yield();
}
}
}));
}
// Wait for all the threads to finish.
for (std::thread &t : threads) {
t.join();
}
BOOST_CHECK_EQUAL(success.load(), ELEMENTS);
// All the elements have been inserted into the tree.
MMIXLinearCongruentialGenerator lcg;
for (int i = 0; i < ELEMENTS; i++) {
uint32_t v = lcg.next();
BOOST_CHECK_EQUAL(mytree.get(v)->getId(), v);
auto ptr = RCUPtr<E>::make(v);
BOOST_CHECK(!mytree.insert(ptr));
BOOST_CHECK(mytree.get(v) != ptr);
}
// Cleanup after ourselves.
RCULock::synchronize();
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "WBDevice.h"
#ifdef USE_CONFIG
#include "../libutils/ConfigItem.h"
#endif
const char *g_Topics[] =
{
"error",
"switch",
"alarm",
"pushbutton",
"range",
"rgb",
"text",
"value",
"temperature",
"rel_humidity",
"atmospheric_pressure",
"sound_level",
"PrecipitationRate", //(rainfall rate) rainfall mm per hour float
"WindSpeed", // wind_speed m / s float
"PowerPower", // watt float
"PowerConsumption", // power_consumption kWh float
"voltage", // volts float
"water_flow", // water_flow m ^ 3 / hour float
"WaterTotal", // consumption water_consumption m ^ 3 float
"resistance", // resistance Ohm float
"concentration", // concentration ppm float(unsigned)
"lux",
"",
};
CWBControl::CWBControl(const string &name)
:Name(name), fValue(0), Readonly(false), Changed(false), Type(Error), Max(100), LastError(0)
{
}
void CWBControl::enrich(const string &meta, const string &val)
{
if (meta == "type")
{
setType(val);
}
else if (meta == "max")
{
Max = atoi(val);
}
else if (meta == "readonly")
{
Readonly = atoi(val) != 0;
}
else if (meta == "order")
{
}
else if (meta == "units")
{
}
else if (meta == "error")
{
time(&LastError);
}
else
throw CHaException(CHaException::ErrBadParam, "Unknown device meta '%s'", meta.c_str());
}
CWBControl::ControlType CWBControl::getType(const string& type)
{
ControlType Type = CWBControl::Error;
for (int i = 0; g_Topics[i][0]; i++)
{
if (type == g_Topics[i])
{
Type = (CWBControl::ControlType)i;
break;
}
}
return Type;
}
string CWBControl::getTypeName(ControlType type)
{
if (sizeof(g_Topics) / sizeof(g_Topics[0]) > (int)type)
return g_Topics[(int)type];
else
return g_Topics[0];
}
CWBControl::ControlType CWBControl::getType()
{
return Type;
}
string CWBControl::getTypeName()
{
return getTypeName(Type);
}
void CWBControl::setType(const string& type)
{
Type = getType(type);
if (Type == Error && type != "" && type != "Error")
throw CHaException(CHaException::ErrBadParam, "Unknown device type '%s'", type.c_str());
}
bool CWBControl::isLoaded()
{
return Type != Error;
}
CWBDevice::CWBDevice(string Name, string Description)
:m_Name(Name), m_Description(Description)
{
}
CWBDevice::CWBDevice()
{
}
CWBDevice::~CWBDevice()
{
for_each(CControlMap, m_Controls, i)
delete i->second;
}
#ifdef USE_CONFIG
void CWBDevice::Init(CConfigItem config)
{
m_Name = config.getStr("Name");
m_Description = config.getStr("Description");
CConfigItemList controls;
config.getList("Control", controls);
for_each(CConfigItemList, controls, control)
{
CWBControl *Control = new CWBControl((*control)->getStr("Name"));
Control->Source = (*control)->getStr("Source", false);
Control->SourceType = (*control)->getStr("SourceType", false);
Control->Readonly = (*control)->getInt("Readonly", false, 1) != 0;
Control->Max = (*control)->getInt("Max", false, 100);
Control->setType((*control)->getStr("Type"));
m_Controls[Control->Name] = Control;
}
}
#endif
void CWBDevice::addControl(const string &Name)
{
if (m_Controls.find(Name) != m_Controls.end())
return;
CWBControl *Control = new CWBControl(Name);
Control->Name = Name;
m_Controls[Control->Name] = Control;
}
void CWBDevice::addControl(const string &Name, CWBControl::ControlType Type, bool ReadOnly, const string &Source, const string &SourceType)
{
CWBControl *Control = new CWBControl(Name);
Control->Source = Source;
Control->SourceType = SourceType;
Control->Readonly = ReadOnly;
Control->Type = Type;
m_Controls[Control->Name] = Control;
}
void CWBDevice::set(string Name, string Value)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
i->second->fValue = (float)atof(Value);
i->second->sValue = Value;
i->second->Changed = true;
i->second->LastError = 0;
}
void CWBDevice::set(string Name, float Value)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
i->second->fValue = Value;
i->second->sValue = ftoa(Value);
i->second->Changed = true;
}
float CWBDevice::getF(string Name)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
return i->second->fValue;
}
int CWBDevice::getI(string Name)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
return atoi(i->second->sValue);
}
string CWBDevice::getS(string Name)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
return i->second->sValue;
}
const CWBControl* CWBDevice::getControl(string Name)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
return i->second;
}
void CWBDevice::createDeviceValues(string_map &v)
{
string base = "/devices/" + m_Name;
v[base + "/meta/name"] = m_Description;
for_each(CControlMap, m_Controls, i)
{
v[base + "/meta/name"] = m_Description;
v[base + "/controls/" + i->first] = i->second->sValue;
v[base + "/controls/" + i->first +"/meta/type"] = g_Topics[i->second->Type];
if (i->second->Readonly)
v[base + "/controls/" + i->first + "/meta/readonly"] = "1";
}
//UpdateValues(v);
}
void CWBDevice::updateValues(string_map &v)
{
string base = "/devices/" + m_Name;
for_each(CControlMap, m_Controls, i)
{
if (i->second->Changed)
{
v[base + "/controls/" + i->first] = i->second->sValue;
i->second->Changed = false;
}
}
}
string CWBDevice::getTopic(string Control)
{
string base = "/devices/" + m_Name;
return base + "/controls/" + Control;
}
bool CWBDevice::sourceExists(const string &source)
{
for_each(CControlMap, m_Controls, i)
{
if (i->second->Source == source)
return true;
}
return false;
}
bool CWBDevice::controlExists(string Name)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
return false;
return true;
}
void CWBDevice::setBySource(string source, string sourceType, string Value)
{
if (sourceType=="X10")
Value = (Value==("ON"?"1":"0"));
for_each(CControlMap, m_Controls, i)
{
if (i->second->Source == source)
set(i->first, Value);
}
}
void CWBDevice::subscribeToEnrich(string_vector &v)
{
if (m_Description.size()==0)
v.push_back("/devices/" + m_Name+ "/meta/#");
for_each(CControlMap, m_Controls, i)
{
if (!i->second->isLoaded())
v.push_back(getTopic(i->second->Name)+"/meta/#");
}
}
void CWBDevice::enrichDevice(const string &meta, const string &val)
{
if (meta == "name")
{
m_Description = val;
}
else
throw CHaException(CHaException::ErrBadParam, "Unknown device meta '%s'", meta.c_str());
}
void CWBDevice::enrichControl(const string &control, const string &meta, const string &val)
{
if (m_Controls.find(control) == m_Controls.end())
addControl(control);
m_Controls[control]->enrich(meta, val);
}
bool CWBDevice::isLoaded()
{
if (m_Description.size() == 0)
return false;
for_each(CControlMap, m_Controls, i)
{
if (!i->second->isLoaded())
return false;
}
return true;
}<commit_msg>round WB values<commit_after>#include "stdafx.h"
#include <math.h>
#include "WBDevice.h"
#ifdef USE_CONFIG
#include "../libutils/ConfigItem.h"
#endif
const char *g_Topics[] =
{
"error",
"switch",
"alarm",
"pushbutton",
"range",
"rgb",
"text",
"value",
"temperature",
"rel_humidity",
"atmospheric_pressure",
"sound_level",
"PrecipitationRate", //(rainfall rate) rainfall mm per hour float
"WindSpeed", // wind_speed m / s float
"PowerPower", // watt float
"PowerConsumption", // power_consumption kWh float
"voltage", // volts float
"water_flow", // water_flow m ^ 3 / hour float
"WaterTotal", // consumption water_consumption m ^ 3 float
"resistance", // resistance Ohm float
"concentration", // concentration ppm float(unsigned)
"lux",
"",
};
CWBControl::CWBControl(const string &name)
:Name(name), fValue(0), Readonly(false), Changed(false), Type(Error), Max(100), LastError(0)
{
}
void CWBControl::enrich(const string &meta, const string &val)
{
if (meta == "type")
{
setType(val);
}
else if (meta == "max")
{
Max = atoi(val);
}
else if (meta == "readonly")
{
Readonly = atoi(val) != 0;
}
else if (meta == "order")
{
}
else if (meta == "units")
{
}
else if (meta == "error")
{
time(&LastError);
}
else
throw CHaException(CHaException::ErrBadParam, "Unknown device meta '%s'", meta.c_str());
}
CWBControl::ControlType CWBControl::getType(const string& type)
{
ControlType Type = CWBControl::Error;
for (int i = 0; g_Topics[i][0]; i++)
{
if (type == g_Topics[i])
{
Type = (CWBControl::ControlType)i;
break;
}
}
return Type;
}
string CWBControl::getTypeName(ControlType type)
{
if (sizeof(g_Topics) / sizeof(g_Topics[0]) > (int)type)
return g_Topics[(int)type];
else
return g_Topics[0];
}
CWBControl::ControlType CWBControl::getType()
{
return Type;
}
string CWBControl::getTypeName()
{
return getTypeName(Type);
}
void CWBControl::setType(const string& type)
{
Type = getType(type);
if (Type == Error && type != "" && type != "Error")
throw CHaException(CHaException::ErrBadParam, "Unknown device type '%s'", type.c_str());
}
bool CWBControl::isLoaded()
{
return Type != Error;
}
CWBDevice::CWBDevice(string Name, string Description)
:m_Name(Name), m_Description(Description)
{
}
CWBDevice::CWBDevice()
{
}
CWBDevice::~CWBDevice()
{
for_each(CControlMap, m_Controls, i)
delete i->second;
}
#ifdef USE_CONFIG
void CWBDevice::Init(CConfigItem config)
{
m_Name = config.getStr("Name");
m_Description = config.getStr("Description");
CConfigItemList controls;
config.getList("Control", controls);
for_each(CConfigItemList, controls, control)
{
CWBControl *Control = new CWBControl((*control)->getStr("Name"));
Control->Source = (*control)->getStr("Source", false);
Control->SourceType = (*control)->getStr("SourceType", false);
Control->Readonly = (*control)->getInt("Readonly", false, 1) != 0;
Control->Max = (*control)->getInt("Max", false, 100);
Control->setType((*control)->getStr("Type"));
m_Controls[Control->Name] = Control;
}
}
#endif
void CWBDevice::addControl(const string &Name)
{
if (m_Controls.find(Name) != m_Controls.end())
return;
CWBControl *Control = new CWBControl(Name);
Control->Name = Name;
m_Controls[Control->Name] = Control;
}
void CWBDevice::addControl(const string &Name, CWBControl::ControlType Type, bool ReadOnly, const string &Source, const string &SourceType)
{
CWBControl *Control = new CWBControl(Name);
Control->Source = Source;
Control->SourceType = SourceType;
Control->Readonly = ReadOnly;
Control->Type = Type;
m_Controls[Control->Name] = Control;
}
void CWBDevice::set(string Name, string Value)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
i->second->fValue = (float)atof(Value);
i->second->sValue = Value;
i->second->Changed = true;
i->second->LastError = 0;
}
void CWBDevice::set(string Name, float Value)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
int digits = 2;
if (round(Value)*100==round(Value*100)) digits = 0;
else if (round(Value)*10==round(Value*10)) digits = 0;
i->second->fValue = Value;
i->second->sValue = ftoa(Value, digits);
i->second->Changed = true;
}
float CWBDevice::getF(string Name)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
return i->second->fValue;
}
int CWBDevice::getI(string Name)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
return atoi(i->second->sValue);
}
string CWBDevice::getS(string Name)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
return i->second->sValue;
}
const CWBControl* CWBDevice::getControl(string Name)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
throw CHaException(CHaException::ErrBadParam, Name);
return i->second;
}
void CWBDevice::createDeviceValues(string_map &v)
{
string base = "/devices/" + m_Name;
v[base + "/meta/name"] = m_Description;
for_each(CControlMap, m_Controls, i)
{
v[base + "/controls/" + i->first] = i->second->sValue;
v[base + "/controls/" + i->first +"/meta/type"] = g_Topics[i->second->Type];
if (i->second->Readonly)
v[base + "/controls/" + i->first + "/meta/readonly"] = "1";
}
updateValues(v);
}
void CWBDevice::updateValues(string_map &v)
{
string base = "/devices/" + m_Name;
for_each(CControlMap, m_Controls, i)
{
if (i->second->Changed)
{
v[base + "/controls/" + i->first] = i->second->sValue;
i->second->Changed = false;
}
}
}
string CWBDevice::getTopic(string Control)
{
string base = "/devices/" + m_Name;
return base + "/controls/" + Control;
}
bool CWBDevice::sourceExists(const string &source)
{
for_each(CControlMap, m_Controls, i)
{
if (i->second->Source == source)
return true;
}
return false;
}
bool CWBDevice::controlExists(string Name)
{
CControlMap::iterator i = m_Controls.find(Name);
if (i == m_Controls.end())
return false;
return true;
}
void CWBDevice::setBySource(string source, string sourceType, string Value)
{
if (sourceType=="X10")
Value = (Value==("ON"?"1":"0"));
for_each(CControlMap, m_Controls, i)
{
if (i->second->Source == source)
set(i->first, Value);
}
}
void CWBDevice::subscribeToEnrich(string_vector &v)
{
if (m_Description.size()==0)
v.push_back("/devices/" + m_Name+ "/meta/#");
for_each(CControlMap, m_Controls, i)
{
if (!i->second->isLoaded())
v.push_back(getTopic(i->second->Name)+"/meta/#");
}
}
void CWBDevice::enrichDevice(const string &meta, const string &val)
{
if (meta == "name")
{
m_Description = val;
}
else
throw CHaException(CHaException::ErrBadParam, "Unknown device meta '%s'", meta.c_str());
}
void CWBDevice::enrichControl(const string &control, const string &meta, const string &val)
{
if (m_Controls.find(control) == m_Controls.end())
addControl(control);
m_Controls[control]->enrich(meta, val);
}
bool CWBDevice::isLoaded()
{
if (m_Description.size() == 0)
return false;
for_each(CControlMap, m_Controls, i)
{
if (!i->second->isLoaded())
return false;
}
return true;
}<|endoftext|>
|
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
#ifndef MFEM_SOLVERS
#define MFEM_SOLVERS
#include "../config/config.hpp"
#include "operator.hpp"
#ifdef MFEM_USE_MPI
#include <mpi.h>
#endif
#ifdef MFEM_USE_SUITESPARSE
#include "sparsemat.hpp"
#include <umfpack.h>
#include <klu.h>
#endif
namespace mfem
{
/// Abstract base class for iterative solver
class IterativeSolver : public Solver
{
#ifdef MFEM_USE_MPI
private:
int dot_prod_type; // 0 - local, 1 - global over 'comm'
MPI_Comm comm;
#endif
protected:
const Operator *oper;
Solver *prec;
int max_iter, print_level;
double rel_tol, abs_tol;
// stats
mutable int final_iter, converged;
mutable double final_norm;
double Dot(const Vector &x, const Vector &y) const;
double Norm(const Vector &x) const { return sqrt(Dot(x, x)); }
public:
IterativeSolver();
#ifdef MFEM_USE_MPI
IterativeSolver(MPI_Comm _comm);
#endif
void SetRelTol(double rtol) { rel_tol = rtol; }
void SetAbsTol(double atol) { abs_tol = atol; }
void SetMaxIter(int max_it) { max_iter = max_it; }
void SetPrintLevel(int print_lvl);
int GetNumIterations() const { return final_iter; }
int GetConverged() const { return converged; }
double GetFinalNorm() const { return final_norm; }
/// This should be called before SetOperator
virtual void SetPreconditioner(Solver &pr);
/// Also calls SetOperator for the preconditioner if there is one
virtual void SetOperator(const Operator &op);
};
/// Stationary linear iteration: x <- x + B (b - A x)
class SLISolver : public IterativeSolver
{
protected:
mutable Vector r, z;
void UpdateVectors();
public:
SLISolver() { }
#ifdef MFEM_USE_MPI
SLISolver(MPI_Comm _comm) : IterativeSolver(_comm) { }
#endif
virtual void SetOperator(const Operator &op)
{ IterativeSolver::SetOperator(op); UpdateVectors(); }
virtual void Mult(const Vector &x, Vector &y) const;
};
/// Stationary linear iteration. (tolerances are squared)
void SLI(const Operator &A, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000,
double RTOLERANCE = 1e-12, double ATOLERANCE = 1e-24);
/// Preconditioned stationary linear iteration. (tolerances are squared)
void SLI(const Operator &A, Solver &B, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000,
double RTOLERANCE = 1e-12, double ATOLERANCE = 1e-24);
/// Conjugate gradient method
class CGSolver : public IterativeSolver
{
protected:
mutable Vector r, d, z;
void UpdateVectors();
public:
CGSolver() { }
#ifdef MFEM_USE_MPI
CGSolver(MPI_Comm _comm) : IterativeSolver(_comm) { }
#endif
virtual void SetOperator(const Operator &op)
{ IterativeSolver::SetOperator(op); UpdateVectors(); }
virtual void Mult(const Vector &x, Vector &y) const;
};
/// Conjugate gradient method. (tolerances are squared)
void CG(const Operator &A, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000,
double RTOLERANCE = 1e-12, double ATOLERANCE = 1e-24);
/// Preconditioned conjugate gradient method. (tolerances are squared)
void PCG(const Operator &A, Solver &B, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000,
double RTOLERANCE = 1e-12, double ATOLERANCE = 1e-24);
/// GMRES method
class GMRESSolver : public IterativeSolver
{
protected:
int m;
public:
GMRESSolver() { m = 50; }
#ifdef MFEM_USE_MPI
GMRESSolver(MPI_Comm _comm) : IterativeSolver(_comm) { m = 50; }
#endif
void SetKDim(int dim) { m = dim; }
virtual void Mult(const Vector &x, Vector &y) const;
};
/// FGMRES method
class FGMRESSolver : public IterativeSolver
{
protected:
int m;
public:
FGMRESSolver() { m = 50; }
#ifdef MFEM_USE_MPI
FGMRESSolver(MPI_Comm _comm) : IterativeSolver(_comm) { m = 50; }
#endif
void SetKDim(int dim) { m = dim; }
virtual void Mult(const Vector &x, Vector &y) const;
};
/// GMRES method. (tolerances are squared)
int GMRES(const Operator &A, Vector &x, const Vector &b, Solver &M,
int &max_iter, int m, double &tol, double atol, int printit);
/// GMRES method. (tolerances are squared)
void GMRES(const Operator &A, Solver &B, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000, int m = 50,
double rtol = 1e-12, double atol = 1e-24);
/// BiCGSTAB method
class BiCGSTABSolver : public IterativeSolver
{
protected:
mutable Vector p, phat, s, shat, t, v, r, rtilde;
void UpdateVectors();
public:
BiCGSTABSolver() { }
#ifdef MFEM_USE_MPI
BiCGSTABSolver(MPI_Comm _comm) : IterativeSolver(_comm) { }
#endif
virtual void SetOperator(const Operator &op)
{ IterativeSolver::SetOperator(op); UpdateVectors(); }
virtual void Mult(const Vector &x, Vector &y) const;
};
/// BiCGSTAB method. (tolerances are squared)
int BiCGSTAB(const Operator &A, Vector &x, const Vector &b, Solver &M,
int &max_iter, double &tol, double atol, int printit);
/// BiCGSTAB method. (tolerances are squared)
void BiCGSTAB(const Operator &A, Solver &B, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000,
double rtol = 1e-12, double atol = 1e-24);
/// MINRES method
class MINRESSolver : public IterativeSolver
{
protected:
mutable Vector v0, v1, w0, w1, q;
mutable Vector u1; // used in the preconditioned version
public:
MINRESSolver() { }
#ifdef MFEM_USE_MPI
MINRESSolver(MPI_Comm _comm) : IterativeSolver(_comm) { }
#endif
virtual void SetPreconditioner(Solver &pr)
{
IterativeSolver::SetPreconditioner(pr);
if (oper) { u1.SetSize(width); }
}
virtual void SetOperator(const Operator &op);
virtual void Mult(const Vector &b, Vector &x) const;
};
/// MINRES method without preconditioner. (tolerances are squared)
void MINRES(const Operator &A, const Vector &b, Vector &x, int print_it = 0,
int max_it = 1000, double rtol = 1e-12, double atol = 1e-24);
/// MINRES method with preconditioner. (tolerances are squared)
void MINRES(const Operator &A, Solver &B, const Vector &b, Vector &x,
int print_it = 0, int max_it = 1000,
double rtol = 1e-12, double atol = 1e-24);
/// Newton's method for solving F(x)=b for a given operator F.
/** The method GetGradient() must be implemented for the operator F.
The preconditioner is used (in non-iterative mode) to evaluate
the action of the inverse gradient of the operator. */
class NewtonSolver : public IterativeSolver
{
protected:
mutable Vector r, c;
public:
NewtonSolver() { }
#ifdef MFEM_USE_MPI
NewtonSolver(MPI_Comm _comm) : IterativeSolver(_comm) { }
#endif
virtual void SetOperator(const Operator &op);
/// Set the linear solver for inverting the Jacobian.
/** This method is equivalent to calling SetPreconditioner(). */
virtual void SetSolver(Solver &solver) { prec = &solver; }
/// Solve the nonlinear system with right-hand side @a b.
/** If `b.Size() != Height()`, then @a b is assumed to be zero. */
virtual void Mult(const Vector &b, Vector &x) const;
};
/** Adaptive restarted GMRES.
m_max and m_min(=1) are the maximal and minimal restart parameters.
m_step(=1) is the step to use for going from m_max and m_min.
cf(=0.4) is a desired convergence factor. */
int aGMRES(const Operator &A, Vector &x, const Vector &b,
const Operator &M, int &max_iter,
int m_max, int m_min, int m_step, double cf,
double &tol, double &atol, int printit);
/** SLBQP: (S)ingle (L)inearly Constrained with (B)ounds (Q)uadratic (P)rogram
minimize 1/2 ||x - x_t||^2, subject to:
lo_i <= x_i <= hi_i
sum_i w_i x_i = a
*/
class SLBQPOptimizer : public IterativeSolver
{
protected:
Vector lo, hi, w;
double a;
/// Solve QP at fixed lambda
inline double solve(double l, const Vector &xt, Vector &x, int &nclip) const
{
add(xt, l, w, x);
x.median(lo,hi);
nclip++;
return Dot(w,x)-a;
}
inline void print_iteration(int it, double r, double l) const;
public:
SLBQPOptimizer() {}
#ifdef MFEM_USE_MPI
SLBQPOptimizer(MPI_Comm _comm) : IterativeSolver(_comm) {}
#endif
void SetBounds(const Vector &_lo, const Vector &_hi);
void SetLinearConstraint(const Vector &_w, double _a);
// For this problem type, we let the target values play the role of the
// initial vector xt, from which the operator generates the optimal vector x.
virtual void Mult(const Vector &xt, Vector &x) const;
/// These are not currently meaningful for this solver and will error out.
virtual void SetPreconditioner(Solver &pr);
virtual void SetOperator(const Operator &op);
};
#ifdef MFEM_USE_SUITESPARSE
/// Direct sparse solver using UMFPACK
class UMFPackSolver : public Solver
{
protected:
bool use_long_ints;
SparseMatrix *mat;
void *Numeric;
SuiteSparse_long *AI, *AJ;
void Init();
public:
double Control[UMFPACK_CONTROL];
mutable double Info[UMFPACK_INFO];
/** @brief For larger matrices, if the solver fails, set the parameter @a
_use_long_ints = true. */
UMFPackSolver(bool _use_long_ints = false)
: use_long_ints(_use_long_ints) { Init(); }
/** @brief Factorize the given SparseMatrix using the defaults. For larger
matrices, if the solver fails, set the parameter @a _use_long_ints =
true. */
UMFPackSolver(SparseMatrix &A, bool _use_long_ints = false)
: use_long_ints(_use_long_ints) { Init(); SetOperator(A); }
/** @brief Factorize the given Operator @a op which must be a SparseMatrix.
The factorization uses the parameters set in the #Control data member.
@note This method calls SparseMatrix::SortColumnIndices() with @a op,
modifying the matrix if the column indices are not already sorted. */
virtual void SetOperator(const Operator &op);
/// Set the print level field in the #Control data member.
void SetPrintLevel(int print_lvl) { Control[UMFPACK_PRL] = print_lvl; }
virtual void Mult(const Vector &b, Vector &x) const;
virtual void MultTranspose(const Vector &b, Vector &x) const;
virtual ~UMFPackSolver();
};
/// Direct sparse solver using KLU
class KLUSolver : public Solver
{
protected:
SparseMatrix *mat;
klu_symbolic *Symbolic;
klu_numeric *Numeric;
void Init();
public:
KLUSolver()
: mat(0),Symbolic(0),Numeric(0)
{ Init(); }
KLUSolver(SparseMatrix &A)
: mat(0),Symbolic(0),Numeric(0)
{ Init(); SetOperator(A); }
// Works on sparse matrices only; calls SparseMatrix::SortColumnIndices().
virtual void SetOperator(const Operator &op);
virtual void Mult(const Vector &b, Vector &x) const;
virtual void MultTranspose(const Vector &b, Vector &x) const;
virtual ~KLUSolver();
mutable klu_common Common;
};
#endif // MFEM_USE_SUITESPARSE
}
#endif // MFEM_SOLVERS
<commit_msg>Set paramater names to be consistant<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
#ifndef MFEM_SOLVERS
#define MFEM_SOLVERS
#include "../config/config.hpp"
#include "operator.hpp"
#ifdef MFEM_USE_MPI
#include <mpi.h>
#endif
#ifdef MFEM_USE_SUITESPARSE
#include "sparsemat.hpp"
#include <umfpack.h>
#include <klu.h>
#endif
namespace mfem
{
/// Abstract base class for iterative solver
class IterativeSolver : public Solver
{
#ifdef MFEM_USE_MPI
private:
int dot_prod_type; // 0 - local, 1 - global over 'comm'
MPI_Comm comm;
#endif
protected:
const Operator *oper;
Solver *prec;
int max_iter, print_level;
double rel_tol, abs_tol;
// stats
mutable int final_iter, converged;
mutable double final_norm;
double Dot(const Vector &x, const Vector &y) const;
double Norm(const Vector &x) const { return sqrt(Dot(x, x)); }
public:
IterativeSolver();
#ifdef MFEM_USE_MPI
IterativeSolver(MPI_Comm _comm);
#endif
void SetRelTol(double rtol) { rel_tol = rtol; }
void SetAbsTol(double atol) { abs_tol = atol; }
void SetMaxIter(int max_it) { max_iter = max_it; }
void SetPrintLevel(int print_lvl);
int GetNumIterations() const { return final_iter; }
int GetConverged() const { return converged; }
double GetFinalNorm() const { return final_norm; }
/// This should be called before SetOperator
virtual void SetPreconditioner(Solver &pr);
/// Also calls SetOperator for the preconditioner if there is one
virtual void SetOperator(const Operator &op);
};
/// Stationary linear iteration: x <- x + B (b - A x)
class SLISolver : public IterativeSolver
{
protected:
mutable Vector r, z;
void UpdateVectors();
public:
SLISolver() { }
#ifdef MFEM_USE_MPI
SLISolver(MPI_Comm _comm) : IterativeSolver(_comm) { }
#endif
virtual void SetOperator(const Operator &op)
{ IterativeSolver::SetOperator(op); UpdateVectors(); }
virtual void Mult(const Vector &b, Vector &x) const;
};
/// Stationary linear iteration. (tolerances are squared)
void SLI(const Operator &A, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000,
double RTOLERANCE = 1e-12, double ATOLERANCE = 1e-24);
/// Preconditioned stationary linear iteration. (tolerances are squared)
void SLI(const Operator &A, Solver &B, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000,
double RTOLERANCE = 1e-12, double ATOLERANCE = 1e-24);
/// Conjugate gradient method
class CGSolver : public IterativeSolver
{
protected:
mutable Vector r, d, z;
void UpdateVectors();
public:
CGSolver() { }
#ifdef MFEM_USE_MPI
CGSolver(MPI_Comm _comm) : IterativeSolver(_comm) { }
#endif
virtual void SetOperator(const Operator &op)
{ IterativeSolver::SetOperator(op); UpdateVectors(); }
virtual void Mult(const Vector &b, Vector &x) const;
};
/// Conjugate gradient method. (tolerances are squared)
void CG(const Operator &A, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000,
double RTOLERANCE = 1e-12, double ATOLERANCE = 1e-24);
/// Preconditioned conjugate gradient method. (tolerances are squared)
void PCG(const Operator &A, Solver &B, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000,
double RTOLERANCE = 1e-12, double ATOLERANCE = 1e-24);
/// GMRES method
class GMRESSolver : public IterativeSolver
{
protected:
int m;
public:
GMRESSolver() { m = 50; }
#ifdef MFEM_USE_MPI
GMRESSolver(MPI_Comm _comm) : IterativeSolver(_comm) { m = 50; }
#endif
void SetKDim(int dim) { m = dim; }
virtual void Mult(const Vector &b, Vector &x) const;
};
/// FGMRES method
class FGMRESSolver : public IterativeSolver
{
protected:
int m;
public:
FGMRESSolver() { m = 50; }
#ifdef MFEM_USE_MPI
FGMRESSolver(MPI_Comm _comm) : IterativeSolver(_comm) { m = 50; }
#endif
void SetKDim(int dim) { m = dim; }
virtual void Mult(const Vector &b, Vector &x) const;
};
/// GMRES method. (tolerances are squared)
int GMRES(const Operator &A, Vector &x, const Vector &b, Solver &M,
int &max_iter, int m, double &tol, double atol, int printit);
/// GMRES method. (tolerances are squared)
void GMRES(const Operator &A, Solver &B, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000, int m = 50,
double rtol = 1e-12, double atol = 1e-24);
/// BiCGSTAB method
class BiCGSTABSolver : public IterativeSolver
{
protected:
mutable Vector p, phat, s, shat, t, v, r, rtilde;
void UpdateVectors();
public:
BiCGSTABSolver() { }
#ifdef MFEM_USE_MPI
BiCGSTABSolver(MPI_Comm _comm) : IterativeSolver(_comm) { }
#endif
virtual void SetOperator(const Operator &op)
{ IterativeSolver::SetOperator(op); UpdateVectors(); }
virtual void Mult(const Vector &b, Vector &x) const;
};
/// BiCGSTAB method. (tolerances are squared)
int BiCGSTAB(const Operator &A, Vector &x, const Vector &b, Solver &M,
int &max_iter, double &tol, double atol, int printit);
/// BiCGSTAB method. (tolerances are squared)
void BiCGSTAB(const Operator &A, Solver &B, const Vector &b, Vector &x,
int print_iter = 0, int max_num_iter = 1000,
double rtol = 1e-12, double atol = 1e-24);
/// MINRES method
class MINRESSolver : public IterativeSolver
{
protected:
mutable Vector v0, v1, w0, w1, q;
mutable Vector u1; // used in the preconditioned version
public:
MINRESSolver() { }
#ifdef MFEM_USE_MPI
MINRESSolver(MPI_Comm _comm) : IterativeSolver(_comm) { }
#endif
virtual void SetPreconditioner(Solver &pr)
{
IterativeSolver::SetPreconditioner(pr);
if (oper) { u1.SetSize(width); }
}
virtual void SetOperator(const Operator &op);
virtual void Mult(const Vector &b, Vector &x) const;
};
/// MINRES method without preconditioner. (tolerances are squared)
void MINRES(const Operator &A, const Vector &b, Vector &x, int print_it = 0,
int max_it = 1000, double rtol = 1e-12, double atol = 1e-24);
/// MINRES method with preconditioner. (tolerances are squared)
void MINRES(const Operator &A, Solver &B, const Vector &b, Vector &x,
int print_it = 0, int max_it = 1000,
double rtol = 1e-12, double atol = 1e-24);
/// Newton's method for solving F(x)=b for a given operator F.
/** The method GetGradient() must be implemented for the operator F.
The preconditioner is used (in non-iterative mode) to evaluate
the action of the inverse gradient of the operator. */
class NewtonSolver : public IterativeSolver
{
protected:
mutable Vector r, c;
public:
NewtonSolver() { }
#ifdef MFEM_USE_MPI
NewtonSolver(MPI_Comm _comm) : IterativeSolver(_comm) { }
#endif
virtual void SetOperator(const Operator &op);
/// Set the linear solver for inverting the Jacobian.
/** This method is equivalent to calling SetPreconditioner(). */
virtual void SetSolver(Solver &solver) { prec = &solver; }
/// Solve the nonlinear system with right-hand side @a b.
/** If `b.Size() != Height()`, then @a b is assumed to be zero. */
virtual void Mult(const Vector &b, Vector &x) const;
};
/** Adaptive restarted GMRES.
m_max and m_min(=1) are the maximal and minimal restart parameters.
m_step(=1) is the step to use for going from m_max and m_min.
cf(=0.4) is a desired convergence factor. */
int aGMRES(const Operator &A, Vector &x, const Vector &b,
const Operator &M, int &max_iter,
int m_max, int m_min, int m_step, double cf,
double &tol, double &atol, int printit);
/** SLBQP: (S)ingle (L)inearly Constrained with (B)ounds (Q)uadratic (P)rogram
minimize 1/2 ||x - x_t||^2, subject to:
lo_i <= x_i <= hi_i
sum_i w_i x_i = a
*/
class SLBQPOptimizer : public IterativeSolver
{
protected:
Vector lo, hi, w;
double a;
/// Solve QP at fixed lambda
inline double solve(double l, const Vector &xt, Vector &x, int &nclip) const
{
add(xt, l, w, x);
x.median(lo,hi);
nclip++;
return Dot(w,x)-a;
}
inline void print_iteration(int it, double r, double l) const;
public:
SLBQPOptimizer() {}
#ifdef MFEM_USE_MPI
SLBQPOptimizer(MPI_Comm _comm) : IterativeSolver(_comm) {}
#endif
void SetBounds(const Vector &_lo, const Vector &_hi);
void SetLinearConstraint(const Vector &_w, double _a);
// For this problem type, we let the target values play the role of the
// initial vector xt, from which the operator generates the optimal vector x.
virtual void Mult(const Vector &xt, Vector &x) const;
/// These are not currently meaningful for this solver and will error out.
virtual void SetPreconditioner(Solver &pr);
virtual void SetOperator(const Operator &op);
};
#ifdef MFEM_USE_SUITESPARSE
/// Direct sparse solver using UMFPACK
class UMFPackSolver : public Solver
{
protected:
bool use_long_ints;
SparseMatrix *mat;
void *Numeric;
SuiteSparse_long *AI, *AJ;
void Init();
public:
double Control[UMFPACK_CONTROL];
mutable double Info[UMFPACK_INFO];
/** @brief For larger matrices, if the solver fails, set the parameter @a
_use_long_ints = true. */
UMFPackSolver(bool _use_long_ints = false)
: use_long_ints(_use_long_ints) { Init(); }
/** @brief Factorize the given SparseMatrix using the defaults. For larger
matrices, if the solver fails, set the parameter @a _use_long_ints =
true. */
UMFPackSolver(SparseMatrix &A, bool _use_long_ints = false)
: use_long_ints(_use_long_ints) { Init(); SetOperator(A); }
/** @brief Factorize the given Operator @a op which must be a SparseMatrix.
The factorization uses the parameters set in the #Control data member.
@note This method calls SparseMatrix::SortColumnIndices() with @a op,
modifying the matrix if the column indices are not already sorted. */
virtual void SetOperator(const Operator &op);
/// Set the print level field in the #Control data member.
void SetPrintLevel(int print_lvl) { Control[UMFPACK_PRL] = print_lvl; }
virtual void Mult(const Vector &b, Vector &x) const;
virtual void MultTranspose(const Vector &b, Vector &x) const;
virtual ~UMFPackSolver();
};
/// Direct sparse solver using KLU
class KLUSolver : public Solver
{
protected:
SparseMatrix *mat;
klu_symbolic *Symbolic;
klu_numeric *Numeric;
void Init();
public:
KLUSolver()
: mat(0),Symbolic(0),Numeric(0)
{ Init(); }
KLUSolver(SparseMatrix &A)
: mat(0),Symbolic(0),Numeric(0)
{ Init(); SetOperator(A); }
// Works on sparse matrices only; calls SparseMatrix::SortColumnIndices().
virtual void SetOperator(const Operator &op);
virtual void Mult(const Vector &b, Vector &x) const;
virtual void MultTranspose(const Vector &b, Vector &x) const;
virtual ~KLUSolver();
mutable klu_common Common;
};
#endif // MFEM_USE_SUITESPARSE
}
#endif // MFEM_SOLVERS
<|endoftext|>
|
<commit_before>#ifndef STAN_MCMC_SAMPLE_HPP
#define STAN_MCMC_SAMPLE_HPP
#include <Eigen/Dense>
#include <vector>
#include <string>
namespace stan {
namespace mcmc {
class sample {
public:
sample(const Eigen::VectorXd& q, double log_prob, double stat)
: cont_params_(q), log_prob_(log_prob), accept_stat_(stat) {
}
virtual ~sample() {} // No-op
int size_cont() const {
return cont_params_.size();
}
double cont_params(int k) const {
return cont_params_(k);
}
void cont_params(Eigen::VectorXd& x) const {
x = cont_params_;
}
const Eigen::VectorXd& cont_params() const {
return cont_params_;
}
inline double log_prob() const {
return log_prob_;
}
inline double accept_stat() const {
return accept_stat_;
}
static void get_sample_param_names(std::vector<std::string>& names) {
names.push_back("lp__");
names.push_back("accept_stat__");
}
static void get_sample_params(std::vector<double>& values) {
values.push_back(log_prob_);
values.push_back(accept_stat_);
}
private:
Eigen::VectorXd cont_params_; // Continuous coordinates of sample
double log_prob_; // Log probability of sample
double accept_stat_; // Acceptance statistic of transition
};
} // mcmc
} // stan
#endif
<commit_msg>Changing one of the static methods back to a member method<commit_after>#ifndef STAN_MCMC_SAMPLE_HPP
#define STAN_MCMC_SAMPLE_HPP
#include <Eigen/Dense>
#include <vector>
#include <string>
namespace stan {
namespace mcmc {
class sample {
public:
sample(const Eigen::VectorXd& q, double log_prob, double stat)
: cont_params_(q), log_prob_(log_prob), accept_stat_(stat) {
}
virtual ~sample() {} // No-op
int size_cont() const {
return cont_params_.size();
}
double cont_params(int k) const {
return cont_params_(k);
}
void cont_params(Eigen::VectorXd& x) const {
x = cont_params_;
}
const Eigen::VectorXd& cont_params() const {
return cont_params_;
}
inline double log_prob() const {
return log_prob_;
}
inline double accept_stat() const {
return accept_stat_;
}
static void get_sample_param_names(std::vector<std::string>& names) {
names.push_back("lp__");
names.push_back("accept_stat__");
}
void get_sample_params(std::vector<double>& values) {
values.push_back(log_prob_);
values.push_back(accept_stat_);
}
private:
Eigen::VectorXd cont_params_; // Continuous coordinates of sample
double log_prob_; // Log probability of sample
double accept_stat_; // Acceptance statistic of transition
};
} // mcmc
} // stan
#endif
<|endoftext|>
|
<commit_before>1300d032-2e4d-11e5-9284-b827eb9e62be<commit_msg>1305db04-2e4d-11e5-9284-b827eb9e62be<commit_after>1305db04-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0d31add8-2e4e-11e5-9284-b827eb9e62be<commit_msg>0d36f64e-2e4e-11e5-9284-b827eb9e62be<commit_after>0d36f64e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>22b5ccde-2e4e-11e5-9284-b827eb9e62be<commit_msg>22bad3dc-2e4e-11e5-9284-b827eb9e62be<commit_after>22bad3dc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>8f21dca0-2e4e-11e5-9284-b827eb9e62be<commit_msg>8f26e9de-2e4e-11e5-9284-b827eb9e62be<commit_after>8f26e9de-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e57ea30a-2e4c-11e5-9284-b827eb9e62be<commit_msg>e583b296-2e4c-11e5-9284-b827eb9e62be<commit_after>e583b296-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>607f9078-2e4d-11e5-9284-b827eb9e62be<commit_msg>60849f50-2e4d-11e5-9284-b827eb9e62be<commit_after>60849f50-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>080dbc84-2e4e-11e5-9284-b827eb9e62be<commit_msg>0812eb00-2e4e-11e5-9284-b827eb9e62be<commit_after>0812eb00-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>34bb9f16-2e4f-11e5-9284-b827eb9e62be<commit_msg>34c099e4-2e4f-11e5-9284-b827eb9e62be<commit_after>34c099e4-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b8226368-2e4e-11e5-9284-b827eb9e62be<commit_msg>b827d686-2e4e-11e5-9284-b827eb9e62be<commit_after>b827d686-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>2eafb19a-2e4d-11e5-9284-b827eb9e62be<commit_msg>2eb4a83a-2e4d-11e5-9284-b827eb9e62be<commit_after>2eb4a83a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b3a798a8-2e4e-11e5-9284-b827eb9e62be<commit_msg>b3acc440-2e4e-11e5-9284-b827eb9e62be<commit_after>b3acc440-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>5cbf2b9c-2e4d-11e5-9284-b827eb9e62be<commit_msg>5cc430b0-2e4d-11e5-9284-b827eb9e62be<commit_after>5cc430b0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>#include <type/type-checker.hh>
#include <ast/all.hh>
namespace type
{
TypeChecker::TypeChecker()
: current_class_(nullptr)
{}
TypeChecker::~TypeChecker()
{}
misc::Error& TypeChecker::error_get()
{
return error_;
}
void TypeChecker::type_check(ast::Expr* e1, ast::Expr* e2)
{
// FIXME : quick fix that breaks multiple type error report
if (error_.error_type_get() == misc::Error::NONE)
{
if (!e1->type_get() || !e2->type_get())
assert(false && "Compiler internal error");
if (!e1->type_get()->compatible_with(*(e2->type_get())))
{
error_ << misc::Error::TYPE
<< e1->location_get() << ": Type error, excpected "
<< *(e1->type_get()) << ", got " << *(e2->type_get())
<< std::endl;
}
}
}
void TypeChecker::type_set(ast::Expr* e1, ast::Expr* e2)
{
e1->type_set(e2->type_get());
}
Type* TypeChecker::type_call(ast::FunctionDec* d, Function* type)
{
// Look if prototype has already been checked
for (auto proto : d->to_generate_get())
{
if (proto->compatible_with(*type))
return proto->return_type_get();
}
// Else check this prototype
Function* temp = d->type_get();
// Set the prototype to function prototype
d->type_set(type);
// Add the prototype to be generated later (and for same check later)
d->to_generate_add(type);
// Check the body
in_declaration_.push(d);
d->body_get()->accept(*this);
in_declaration_.pop();
if (!d->type_get()->return_type_get())
d->type_get()->return_type_set(&Void::instance());
// Restore function original prototype
d->type_set(temp);
return type->return_type_get();
}
void TypeChecker::operator()(ast::ReturnStmt& ast)
{
type::Type* ret_type = &Void::instance();
ast::FunctionDec* to_type = in_declaration_.top();
type::Type* fun_type = to_type->type_get()->return_type_get();
if (ast.ret_value_get())
{
ast.ret_value_get()->accept(*this);
ret_type = ast.ret_value_get()->type_get();
}
if (fun_type)
{
if (fun_type == &Polymorphic::instance())
to_type->type_get()->return_type_set(ret_type);
else if (!fun_type->compatible_with(*ret_type))
error_ << misc::Error::TYPE
<< ast.location_get() << ": Type error, function has "
<< "deduced type " << *fun_type << ", but return is "
<< *ret_type << std::endl;
}
else
to_type->type_get()->return_type_set(ret_type);
}
void TypeChecker::operator()(ast::FunctionDec& s)
{
Function* f_type = new Function();
s.type_set(f_type);
if (s.args_get())
{
for (auto arg : s.args_get()->list_get())
{
ast::IdVar* var = dynamic_cast<ast::IdVar*> (arg);
if (var)
{
// If it is a var type it as polymorphic type
// for the correctness check (better check will be
// performed when type checking function call)
// -> see operator()(ast::FunctionVar&)
var->type_set(&Polymorphic::instance());
f_type->args_type_add(&Polymorphic::instance());
}
else
{
// If it is an assignement type it as it must be
arg->accept(*this);
f_type->args_type_add(arg->type_get());
}
}
}
in_declaration_.push(&s);
s.body_get()->accept(*this);
in_declaration_.pop();
if (!f_type->return_type_get())
f_type->return_type_set(&Void::instance());
if (current_class_)
current_class_->component_add(s.name_get(), &s);
}
void TypeChecker::operator()(ast::ClassDec& ast)
{
if (declared_class_[ast.name_get()])
error_ << misc::Error::TYPE
<< ast.location_get() << " : Redeclaration of class"
<< ast.name_get() << std::endl;
else
declared_class_[ast.name_get()] = ast.type_class_get();
current_class_ = ast.type_class_get();
ast.def_get()->accept(*this);
current_class_ = nullptr;
}
void TypeChecker::operator()(ast::FunctionVar& e)
{
// Check if the function is a constructor
ast::IdVar* v = dynamic_cast<ast::IdVar*> (e.var_get());
if (v && declared_class_[v->id_get()])
{
Class* t = declared_class_[v->id_get()];
ast::FunctionDec* c;
c = dynamic_cast<ast::FunctionDec*> (t->component_get("__init__"));
// Indicates that this function var is an instanciation of an
// object (usefull to add new C++ keyword)
if (c)
{
e.def_set(c);
e.constructor_set(true);
}
}
type_callable(e);
// If is a constructor set the type
if (v && declared_class_[v->id_get()])
e.type_set(declared_class_[v->id_get()]);
}
void TypeChecker::operator()(ast::MethodVar& e)
{
e.field_get()->var_get()->accept(*this);
Class* field_type = dynamic_cast<Class*> (e.field_get()->var_get()->type_get());
// Check that field type is a class
if (!field_type)
{
error_ << misc::Error::TYPE
<< e.location_get() << " : Not a class" << std::endl;
return;
}
ast::FunctionDec* method = nullptr;
method = dynamic_cast<ast::FunctionDec*> (field_type->component_get(e.name_get()));
// Check that the method exists and is not a field
if (!method)
{
error_ << misc::Error::TYPE
<< e.location_get() << " : " << e.name_get()
<< " is not a callable object or not part of " << *field_type
<< std::endl;
return;
}
// Set the definition and check the call
e.def_set(method);
type_callable(e);
}
void TypeChecker::operator()(ast::OpExpr& ast)
{
ast.left_expr_get()->accept(*this);
ast.right_expr_get()->accept(*this);
type_check(ast.left_expr_get(), ast.right_expr_get());
// So far if there is no error it does not really matter if the opexpr
// has right expr of left expr type since they are the same due to
// strong type of python just check if one of them is non polymorphic
if (ast.left_expr_get()->type_get() == &Polymorphic::instance())
type_set(&ast, ast.right_expr_get());
else
type_set(&ast, ast.left_expr_get());
}
void TypeChecker::operator()(ast::IdVar& ast)
{
if (ast.id_get() == "self")
{
// Usefull in methodvar check to avoid recheck of self statement
if (ast.type_get())
return;
if (current_class_)
ast.type_set(current_class_);
else
error_ << misc::Error::TYPE
<< ast.location_get() << " : self used outside class "
<< "definition" << std::endl;
return;
}
ast::Expr* e = dynamic_cast<ast::Expr*> (ast.def_get());
if (e)
type_set(&ast, e);
else if (ast.def_get())
assert(false && "Compiler internal error");
}
void TypeChecker::operator()(ast::FieldVar& ast)
{
ast.var_get()->accept(*this);
type::Class* field_super = nullptr;
field_super = dynamic_cast<type::Class*> (ast.var_get()->type_get());
// If the type of the field before is not a class or is not set
if (!field_super)
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : not a class" << std::endl;
return;
}
// If name already exists in the class definition
if (field_super->component_get(ast.name_get()))
{
ast::Ast* dec = field_super->component_get(ast.name_get());
ast::FieldVar* var = dynamic_cast<ast::FieldVar*> (dec);
// If the name is not a field in the definition -> error
if (!var)
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : " << ast.name_get()
<< " member of " << field_super << " not declared as"
<< " field" << std::endl;
return;
}
// If the definition as no type
if (!var->type_get())
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : can't deduce type of "
<< *ast.var_get() << std::endl;
return;
}
// Else OK
type_set(&ast, var);
}
else // If the name does not exists the define it in the class
field_super->component_add(ast.name_get(), &ast);
}
void TypeChecker::operator()(ast::AssignExpr& e)
{
e.rvalue_get()->accept(*this);
e.lvalue_get()->accept(*this);
if (!e.rvalue_get()->type_get()
&& dynamic_cast<ast::FieldVar*> (e.rvalue_get()))
error_ << misc::Error::TYPE
<< e.rvalue_get()->location_get() << " : unknown field"
<< std::endl;
type_set(e.lvalue_get(), e.rvalue_get());
type_set(&e, e.rvalue_get());
// FIXME avoid dirty (and unsafe) thing
if (e.def_get())
type_check(dynamic_cast<ast::Expr*> (e.def_get()), &e);
}
void TypeChecker::operator()(ast::NumeralExpr& ast)
{
ast.type_set(&Int::instance());
}
void TypeChecker::operator()(ast::StringExpr& ast)
{
ast.type_set(&String::instance());
}
template <>
void TypeChecker::check_builtin(ast::FunctionVar& e)
{
builtin::BuiltinLibrary::instance().type_check(e, error_, *this);
}
template <>
void TypeChecker::check_builtin(ast::MethodVar&)
{
assert(false && "Internal compiler error");
}
template <>
const ast::ExprList* TypeChecker::builtin_get(ast::FunctionVar& e)
{
return builtin::BuiltinLibrary::instance().args_get(e);
}
template <>
const ast::ExprList* TypeChecker::builtin_get(ast::MethodVar&)
{
assert(false && "Internal compiler error");
return nullptr;
}
const std::string& TypeChecker::name_get(const ast::Expr* e)
{
const ast::IdVar* v = dynamic_cast<const ast::IdVar*> (e);
assert(v && "Internal compiler error");
return v->id_get();
}
void TypeChecker::build_mapping(const ast::ExprList* args,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
// Build the mapping
for (auto param : args->list_get())
{
ast::AssignExpr* e = dynamic_cast<ast::AssignExpr*> (param);
if (e)
{
std::string s = name_get(e->lvalue_get());
args_map[s] = parameter(e->rvalue_get(), false);
order.push_back(s);
}
else
{
std::string s = name_get(param);
args_map[s] = parameter(nullptr,
false);
order.push_back(s);
}
}
}
void TypeChecker::build_call(const ast::ExprList* args,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
auto order_it = order.begin();
bool positional = true;
for (auto call_arg : args->list_get())
{
ast::AssignExpr* e = dynamic_cast<ast::AssignExpr*> (call_arg);
if (e)
{
std::string s = name_get(e->lvalue_get());
positional = false;
if (args_map[s].second)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Parameter " << s
<< " already specified" << std::endl;
else
args_map[s] = parameter(e->rvalue_get(), true);
}
else if (!positional)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Non positional argument"
<< " detected after positional argument"
<< std::endl;
else
{
std::string s = *order_it;
if (args_map[s].second)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Parameter " << s
<< " already specified" << std::endl;
else
args_map[s] = parameter(call_arg, true);
++order_it;
}
}
}
ast::ExprList* TypeChecker::generate_list(const yy::location& loc,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
ast::ExprList* params = new ast::ExprList(loc);
for (auto arg : order)
{
if (!args_map[arg].first)
error_ << misc::Error::TYPE
<< loc << ": Argument " << arg
<< " not specified" << std::endl;
else
params->push_back(clone(args_map[arg].first));
}
return params;
}
ast::Expr* TypeChecker::clone(ast::Ast* ast)
{
cloner::AstCloner clone;
clone.visit(ast);
return dynamic_cast<ast::Expr*> (clone.cloned_ast_get());
}
} // namespace type
<commit_msg>[TYPE] Quick fix of a duck typing problem with classes<commit_after>#include <type/type-checker.hh>
#include <ast/all.hh>
namespace type
{
TypeChecker::TypeChecker()
: current_class_(nullptr)
{}
TypeChecker::~TypeChecker()
{}
misc::Error& TypeChecker::error_get()
{
return error_;
}
void TypeChecker::type_check(ast::Expr* e1, ast::Expr* e2)
{
// FIXME : quick fix that breaks multiple type error report
if (error_.error_type_get() == misc::Error::NONE)
{
if (!e1->type_get() || !e2->type_get())
assert(false && "Compiler internal error");
if (!e1->type_get()->compatible_with(*(e2->type_get())))
{
error_ << misc::Error::TYPE
<< e1->location_get() << ": Type error, excpected "
<< *(e1->type_get()) << ", got " << *(e2->type_get())
<< std::endl;
}
}
}
void TypeChecker::type_set(ast::Expr* e1, ast::Expr* e2)
{
e1->type_set(e2->type_get());
}
Type* TypeChecker::type_call(ast::FunctionDec* d, Function* type)
{
// Look if prototype has already been checked
for (auto proto : d->to_generate_get())
{
if (proto->compatible_with(*type))
return proto->return_type_get();
}
// Else check this prototype
Function* temp = d->type_get();
// Set the prototype to function prototype
d->type_set(type);
// Add the prototype to be generated later (and for same check later)
d->to_generate_add(type);
// Check the body
in_declaration_.push(d);
d->body_get()->accept(*this);
in_declaration_.pop();
if (!d->type_get()->return_type_get())
d->type_get()->return_type_set(&Void::instance());
// Restore function original prototype
d->type_set(temp);
return type->return_type_get();
}
void TypeChecker::operator()(ast::ReturnStmt& ast)
{
type::Type* ret_type = &Void::instance();
ast::FunctionDec* to_type = in_declaration_.top();
type::Type* fun_type = to_type->type_get()->return_type_get();
if (ast.ret_value_get())
{
ast.ret_value_get()->accept(*this);
ret_type = ast.ret_value_get()->type_get();
}
if (fun_type)
{
if (fun_type == &Polymorphic::instance())
to_type->type_get()->return_type_set(ret_type);
else if (!fun_type->compatible_with(*ret_type))
error_ << misc::Error::TYPE
<< ast.location_get() << ": Type error, function has "
<< "deduced type " << *fun_type << ", but return is "
<< *ret_type << std::endl;
}
else
to_type->type_get()->return_type_set(ret_type);
}
void TypeChecker::operator()(ast::FunctionDec& s)
{
Function* f_type = new Function();
s.type_set(f_type);
if (s.args_get())
{
for (auto arg : s.args_get()->list_get())
{
ast::IdVar* var = dynamic_cast<ast::IdVar*> (arg);
if (var)
{
// If it is a var type it as polymorphic type
// for the correctness check (better check will be
// performed when type checking function call)
// -> see operator()(ast::FunctionVar&)
var->type_set(&Polymorphic::instance());
f_type->args_type_add(&Polymorphic::instance());
}
else
{
// If it is an assignement type it as it must be
arg->accept(*this);
f_type->args_type_add(arg->type_get());
}
}
}
in_declaration_.push(&s);
s.body_get()->accept(*this);
in_declaration_.pop();
if (!f_type->return_type_get())
f_type->return_type_set(&Void::instance());
if (current_class_)
current_class_->component_add(s.name_get(), &s);
}
void TypeChecker::operator()(ast::ClassDec& ast)
{
if (declared_class_[ast.name_get()])
error_ << misc::Error::TYPE
<< ast.location_get() << " : Redeclaration of class"
<< ast.name_get() << std::endl;
else
declared_class_[ast.name_get()] = ast.type_class_get();
current_class_ = ast.type_class_get();
ast.def_get()->accept(*this);
current_class_ = nullptr;
}
void TypeChecker::operator()(ast::FunctionVar& e)
{
// Check if the function is a constructor
ast::IdVar* v = dynamic_cast<ast::IdVar*> (e.var_get());
if (v && declared_class_[v->id_get()])
{
Class* t = declared_class_[v->id_get()];
ast::FunctionDec* c;
c = dynamic_cast<ast::FunctionDec*> (t->component_get("__init__"));
// Indicates that this function var is an instanciation of an
// object (usefull to add new C++ keyword)
if (c)
{
e.def_set(c);
e.constructor_set(true);
}
}
type_callable(e);
// If is a constructor set the type
if (v && declared_class_[v->id_get()])
e.type_set(declared_class_[v->id_get()]);
}
void TypeChecker::operator()(ast::MethodVar& e)
{
e.field_get()->var_get()->accept(*this);
Class* field_type = dynamic_cast<Class*> (e.field_get()->var_get()->type_get());
// Check that field type is a class
if (!field_type)
{
// FIXME : quick fix of a deep duck typing issue
if (dynamic_cast<Polymorphic*> (e.field_get()->var_get()->type_get()))
return;
error_ << misc::Error::TYPE
<< e.location_get() << " : Not a class" << std::endl;
return;
}
ast::FunctionDec* method = nullptr;
method = dynamic_cast<ast::FunctionDec*> (field_type->component_get(e.name_get()));
// Check that the method exists and is not a field
if (!method)
{
error_ << misc::Error::TYPE
<< e.location_get() << " : " << e.name_get()
<< " is not a callable object or not part of " << *field_type
<< std::endl;
return;
}
// Set the definition and check the call
e.def_set(method);
type_callable(e);
}
void TypeChecker::operator()(ast::OpExpr& ast)
{
ast.left_expr_get()->accept(*this);
ast.right_expr_get()->accept(*this);
type_check(ast.left_expr_get(), ast.right_expr_get());
// So far if there is no error it does not really matter if the opexpr
// has right expr of left expr type since they are the same due to
// strong type of python just check if one of them is non polymorphic
if (ast.left_expr_get()->type_get() == &Polymorphic::instance())
type_set(&ast, ast.right_expr_get());
else
type_set(&ast, ast.left_expr_get());
}
void TypeChecker::operator()(ast::IdVar& ast)
{
if (ast.id_get() == "self")
{
// Usefull in methodvar check to avoid recheck of self statement
if (ast.type_get())
return;
if (current_class_)
ast.type_set(current_class_);
else
error_ << misc::Error::TYPE
<< ast.location_get() << " : self used outside class "
<< "definition" << std::endl;
return;
}
ast::Expr* e = dynamic_cast<ast::Expr*> (ast.def_get());
if (e)
type_set(&ast, e);
else if (ast.def_get())
assert(false && "Compiler internal error");
}
void TypeChecker::operator()(ast::FieldVar& ast)
{
ast.var_get()->accept(*this);
type::Class* field_super = nullptr;
field_super = dynamic_cast<type::Class*> (ast.var_get()->type_get());
// If the type of the field before is not a class or is not set
if (!field_super)
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : not a class" << std::endl;
return;
}
// If name already exists in the class definition
if (field_super->component_get(ast.name_get()))
{
ast::Ast* dec = field_super->component_get(ast.name_get());
ast::FieldVar* var = dynamic_cast<ast::FieldVar*> (dec);
// If the name is not a field in the definition -> error
if (!var)
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : " << ast.name_get()
<< " member of " << field_super << " not declared as"
<< " field" << std::endl;
return;
}
// If the definition as no type
if (!var->type_get())
{
error_ << misc::Error::TYPE
<< ast.location_get() << " : can't deduce type of "
<< *ast.var_get() << std::endl;
return;
}
// Else OK
type_set(&ast, var);
}
else // If the name does not exists the define it in the class
field_super->component_add(ast.name_get(), &ast);
}
void TypeChecker::operator()(ast::AssignExpr& e)
{
e.rvalue_get()->accept(*this);
e.lvalue_get()->accept(*this);
if (!e.rvalue_get()->type_get()
&& dynamic_cast<ast::FieldVar*> (e.rvalue_get()))
error_ << misc::Error::TYPE
<< e.rvalue_get()->location_get() << " : unknown field"
<< std::endl;
type_set(e.lvalue_get(), e.rvalue_get());
type_set(&e, e.rvalue_get());
// FIXME avoid dirty (and unsafe) thing
if (e.def_get())
type_check(dynamic_cast<ast::Expr*> (e.def_get()), &e);
}
void TypeChecker::operator()(ast::NumeralExpr& ast)
{
ast.type_set(&Int::instance());
}
void TypeChecker::operator()(ast::StringExpr& ast)
{
ast.type_set(&String::instance());
}
template <>
void TypeChecker::check_builtin(ast::FunctionVar& e)
{
builtin::BuiltinLibrary::instance().type_check(e, error_, *this);
}
template <>
void TypeChecker::check_builtin(ast::MethodVar&)
{
assert(false && "Internal compiler error");
}
template <>
const ast::ExprList* TypeChecker::builtin_get(ast::FunctionVar& e)
{
return builtin::BuiltinLibrary::instance().args_get(e);
}
template <>
const ast::ExprList* TypeChecker::builtin_get(ast::MethodVar&)
{
assert(false && "Internal compiler error");
return nullptr;
}
const std::string& TypeChecker::name_get(const ast::Expr* e)
{
const ast::IdVar* v = dynamic_cast<const ast::IdVar*> (e);
assert(v && "Internal compiler error");
return v->id_get();
}
void TypeChecker::build_mapping(const ast::ExprList* args,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
// Build the mapping
for (auto param : args->list_get())
{
ast::AssignExpr* e = dynamic_cast<ast::AssignExpr*> (param);
if (e)
{
std::string s = name_get(e->lvalue_get());
args_map[s] = parameter(e->rvalue_get(), false);
order.push_back(s);
}
else
{
std::string s = name_get(param);
args_map[s] = parameter(nullptr,
false);
order.push_back(s);
}
}
}
void TypeChecker::build_call(const ast::ExprList* args,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
auto order_it = order.begin();
bool positional = true;
for (auto call_arg : args->list_get())
{
ast::AssignExpr* e = dynamic_cast<ast::AssignExpr*> (call_arg);
if (e)
{
std::string s = name_get(e->lvalue_get());
positional = false;
if (args_map[s].second)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Parameter " << s
<< " already specified" << std::endl;
else
args_map[s] = parameter(e->rvalue_get(), true);
}
else if (!positional)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Non positional argument"
<< " detected after positional argument"
<< std::endl;
else
{
std::string s = *order_it;
if (args_map[s].second)
error_ << misc::Error::TYPE
<< call_arg->location_get() << ": Parameter " << s
<< " already specified" << std::endl;
else
args_map[s] = parameter(call_arg, true);
++order_it;
}
}
}
ast::ExprList* TypeChecker::generate_list(const yy::location& loc,
std::map<std::string,
parameter>& args_map,
std::vector<std::string>& order)
{
ast::ExprList* params = new ast::ExprList(loc);
for (auto arg : order)
{
if (!args_map[arg].first)
error_ << misc::Error::TYPE
<< loc << ": Argument " << arg
<< " not specified" << std::endl;
else
params->push_back(clone(args_map[arg].first));
}
return params;
}
ast::Expr* TypeChecker::clone(ast::Ast* ast)
{
cloner::AstCloner clone;
clone.visit(ast);
return dynamic_cast<ast::Expr*> (clone.cloned_ast_get());
}
} // namespace type
<|endoftext|>
|
<commit_before>d87a03a6-2e4d-11e5-9284-b827eb9e62be<commit_msg>d87efda2-2e4d-11e5-9284-b827eb9e62be<commit_after>d87efda2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b22be1d2-2e4e-11e5-9284-b827eb9e62be<commit_msg>b230e5d8-2e4e-11e5-9284-b827eb9e62be<commit_after>b230e5d8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>a09b676c-2e4e-11e5-9284-b827eb9e62be<commit_msg>a0a05dda-2e4e-11e5-9284-b827eb9e62be<commit_after>a0a05dda-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d011bac0-2e4c-11e5-9284-b827eb9e62be<commit_msg>d016af62-2e4c-11e5-9284-b827eb9e62be<commit_after>d016af62-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0e65c1fe-2e4d-11e5-9284-b827eb9e62be<commit_msg>0e6abc04-2e4d-11e5-9284-b827eb9e62be<commit_after>0e6abc04-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e9866efa-2e4d-11e5-9284-b827eb9e62be<commit_msg>e98b772e-2e4d-11e5-9284-b827eb9e62be<commit_after>e98b772e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>27b75f5e-2e4e-11e5-9284-b827eb9e62be<commit_msg>27bc6a08-2e4e-11e5-9284-b827eb9e62be<commit_after>27bc6a08-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>63e581d2-2e4d-11e5-9284-b827eb9e62be<commit_msg>63ea86e6-2e4d-11e5-9284-b827eb9e62be<commit_after>63ea86e6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d5dff538-2e4d-11e5-9284-b827eb9e62be<commit_msg>d5e4eb56-2e4d-11e5-9284-b827eb9e62be<commit_after>d5e4eb56-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c2ab733e-2e4d-11e5-9284-b827eb9e62be<commit_msg>c2b0850e-2e4d-11e5-9284-b827eb9e62be<commit_after>c2b0850e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f2c59c80-2e4c-11e5-9284-b827eb9e62be<commit_msg>f2caaab8-2e4c-11e5-9284-b827eb9e62be<commit_after>f2caaab8-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d20db1bc-2e4c-11e5-9284-b827eb9e62be<commit_msg>d212bf5e-2e4c-11e5-9284-b827eb9e62be<commit_after>d212bf5e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>6552b4e4-2e4e-11e5-9284-b827eb9e62be<commit_msg>6557bc82-2e4e-11e5-9284-b827eb9e62be<commit_after>6557bc82-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>bf64cb54-2e4c-11e5-9284-b827eb9e62be<commit_msg>bf69cc6c-2e4c-11e5-9284-b827eb9e62be<commit_after>bf69cc6c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>ebfd73ae-2e4d-11e5-9284-b827eb9e62be<commit_msg>ec029d7a-2e4d-11e5-9284-b827eb9e62be<commit_after>ec029d7a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>5df6a1fc-2e4d-11e5-9284-b827eb9e62be<commit_msg>5dfbb106-2e4d-11e5-9284-b827eb9e62be<commit_after>5dfbb106-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>7947bb52-2e4e-11e5-9284-b827eb9e62be<commit_msg>794cc6f6-2e4e-11e5-9284-b827eb9e62be<commit_after>794cc6f6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>25f0b220-2e4d-11e5-9284-b827eb9e62be<commit_msg>25f5ad16-2e4d-11e5-9284-b827eb9e62be<commit_after>25f5ad16-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>a3c58a12-2e4e-11e5-9284-b827eb9e62be<commit_msg>a3ca9d68-2e4e-11e5-9284-b827eb9e62be<commit_after>a3ca9d68-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3241684e-2e4d-11e5-9284-b827eb9e62be<commit_msg>324656ce-2e4d-11e5-9284-b827eb9e62be<commit_after>324656ce-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f81b7456-2e4d-11e5-9284-b827eb9e62be<commit_msg>f820d1da-2e4d-11e5-9284-b827eb9e62be<commit_after>f820d1da-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>dbb8e032-2e4d-11e5-9284-b827eb9e62be<commit_msg>dbbde2e4-2e4d-11e5-9284-b827eb9e62be<commit_after>dbbde2e4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e9c731f6-2e4d-11e5-9284-b827eb9e62be<commit_msg>e9cc2440-2e4d-11e5-9284-b827eb9e62be<commit_after>e9cc2440-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>cc40d5a6-2e4d-11e5-9284-b827eb9e62be<commit_msg>cc45d07e-2e4d-11e5-9284-b827eb9e62be<commit_after>cc45d07e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>cc9c3bf2-2e4e-11e5-9284-b827eb9e62be<commit_msg>cca13c24-2e4e-11e5-9284-b827eb9e62be<commit_after>cca13c24-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e344f980-2e4d-11e5-9284-b827eb9e62be<commit_msg>e34a0434-2e4d-11e5-9284-b827eb9e62be<commit_after>e34a0434-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>10dcaac8-2e4e-11e5-9284-b827eb9e62be<commit_msg>10e1a5fa-2e4e-11e5-9284-b827eb9e62be<commit_after>10e1a5fa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0841dee6-2e4f-11e5-9284-b827eb9e62be<commit_msg>0846ec42-2e4f-11e5-9284-b827eb9e62be<commit_after>0846ec42-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e135eb3a-2e4e-11e5-9284-b827eb9e62be<commit_msg>e2a7292a-2e4e-11e5-9284-b827eb9e62be<commit_after>e2a7292a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>46404e46-2e4d-11e5-9284-b827eb9e62be<commit_msg>464549be-2e4d-11e5-9284-b827eb9e62be<commit_after>464549be-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d221d15a-2e4d-11e5-9284-b827eb9e62be<commit_msg>d226cdfe-2e4d-11e5-9284-b827eb9e62be<commit_after>d226cdfe-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>2d41ad8a-2e4e-11e5-9284-b827eb9e62be<commit_msg>2d46c07c-2e4e-11e5-9284-b827eb9e62be<commit_after>2d46c07c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e7c12188-2e4c-11e5-9284-b827eb9e62be<commit_msg>e7c616a2-2e4c-11e5-9284-b827eb9e62be<commit_after>e7c616a2-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>fa10c00e-2e4d-11e5-9284-b827eb9e62be<commit_msg>fa15b758-2e4d-11e5-9284-b827eb9e62be<commit_after>fa15b758-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>9c2d9dea-2e4d-11e5-9284-b827eb9e62be<commit_msg>9c32a448-2e4d-11e5-9284-b827eb9e62be<commit_after>9c32a448-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>df55f018-2e4d-11e5-9284-b827eb9e62be<commit_msg>df5af978-2e4d-11e5-9284-b827eb9e62be<commit_after>df5af978-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>974a0476-2e4d-11e5-9284-b827eb9e62be<commit_msg>974efa44-2e4d-11e5-9284-b827eb9e62be<commit_after>974efa44-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>6bb9d56a-2e4e-11e5-9284-b827eb9e62be<commit_msg>6bbed114-2e4e-11e5-9284-b827eb9e62be<commit_after>6bbed114-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>8c007668-2e4d-11e5-9284-b827eb9e62be<commit_msg>8c056c7c-2e4d-11e5-9284-b827eb9e62be<commit_after>8c056c7c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>4d254184-2e4e-11e5-9284-b827eb9e62be<commit_msg>4d2a55f2-2e4e-11e5-9284-b827eb9e62be<commit_after>4d2a55f2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>90f3e4ec-2e4e-11e5-9284-b827eb9e62be<commit_msg>90f932da-2e4e-11e5-9284-b827eb9e62be<commit_after>90f932da-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>220516c4-2e4d-11e5-9284-b827eb9e62be<commit_msg>220a1872-2e4d-11e5-9284-b827eb9e62be<commit_after>220a1872-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>729d8422-2e4d-11e5-9284-b827eb9e62be<commit_msg>72a27202-2e4d-11e5-9284-b827eb9e62be<commit_after>72a27202-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>9c3cab1e-2e4d-11e5-9284-b827eb9e62be<commit_msg>9c41ad30-2e4d-11e5-9284-b827eb9e62be<commit_after>9c41ad30-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <mscenemanager.h>
#include "mviewcreator.h"
#include <msheet.h>
#include "msheetview.h"
#include "msheetview_p.h"
#include "mabstractwidgetanimation.h"
#include <MDebug>
#include <mpannableviewport.h>
#include <mpositionindicator.h>
#include <QGraphicsAnchorLayout>
#include <QGraphicsLinearLayout>
#include <QGraphicsSceneMouseEvent>
//////////////
/// MSheetSlot
MSheetSlot::MSheetSlot(QGraphicsItem *parent) : MStylableWidget(parent)
{
connect(this, SIGNAL(geometryChanged()), SLOT(resizeChildWidget()));
}
MSheetSlot::~MSheetSlot()
{
// Widget belongs to controller. Remove it from scene graph.
QGraphicsWidget *widget = widgetPointer.data();
if (widget) {
widget->setParentItem(0);
scene()->removeItem(widget);
widgetPointer.clear();
}
}
void MSheetSlot::setWidget(QGraphicsWidget *widget)
{
QGraphicsWidget *currentWidget = widgetPointer.data();
if (widget == currentWidget)
return;
if (currentWidget) {
currentWidget->setParentItem(0);
if (scene())
scene()->removeItem(currentWidget);
}
if (widget) {
widget->setParentItem(this);
widget->setPos(0.0f, 0.0f);
widgetPointer = widget;
resizeChildWidget();
} else {
widgetPointer.clear();
}
}
void MSheetSlot::resizeChildWidget()
{
QGraphicsWidget *widget = widgetPointer.data();
if (widget) {
widget->resize(size());
}
}
//////////////
/// MSheetViewPrivate
MSheetViewPrivate::MSheetViewPrivate()
: q_ptr(0),
rootLayout(0),
headerSlot(0),
centralSlot(0),
centralSlotPannableViewport(0),
headerAnimation(0)
{
}
MSheetViewPrivate::~MSheetViewPrivate()
{
delete headerAnimation;
headerAnimation = 0;
//rootLayout->removeItem(headerSlot);
delete headerSlot;
headerSlot = 0;
//rootLayout->removeItem(centralSlot);
delete centralSlotPannableViewport;
centralSlotPannableViewport = 0;
if (qobject_cast<MSheet *>(controller)) {
// controller is still valid.
// causes rootLayout to be deleted
controller->setLayout(0);
}
rootLayout = 0;
}
void MSheetViewPrivate::init()
{
rootLayout = new QGraphicsAnchorLayout(controller);
rootLayout->setContentsMargins(0, 0, 0, 0);
rootLayout->setSpacing(0);
headerSlot = new MSheetSlot(controller);
headerSlot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
rootLayout->addCornerAnchors(headerSlot, Qt::TopRightCorner, rootLayout, Qt::TopRightCorner);
// The sole purpose of this internal pannable is to guarantee proper input widget relocation
// if the central widget doesn't have a pannable viewport.
centralSlotPannableViewport = new MPannableViewport(controller);
centralSlotPannableViewport->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
centralSlotPannableViewport->setVerticalPanningPolicy(MPannableWidget::PanningAsNeeded);
centralSlotPannableViewport->setObjectName("MSheetCentralSlotPannableViewport");
rootLayout->addCornerAnchors(centralSlotPannableViewport, Qt::TopLeftCorner, headerSlot, Qt::BottomLeftCorner);
rootLayout->addCornerAnchors(centralSlotPannableViewport, Qt::BottomRightCorner, rootLayout, Qt::BottomRightCorner);
centralSlot = new MSheetSlot(centralSlotPannableViewport);
centralSlotPannableViewport->setWidget(centralSlot);
}
void MSheetViewPrivate::updateStyle()
{
Q_Q(MSheetView);
headerSlot->setStyleName(q->style()->headerSlotStyleName());
centralSlot->setStyleName(q->style()->centralSlotStyleName());
delete headerAnimation;
headerAnimation = 0;
if (!q->style()->headerAnimation().isEmpty()) {
headerAnimation = qobject_cast<MAbstractWidgetAnimation*>(MTheme::animation(q->style()->headerAnimation()));
headerAnimation->setTargetWidget(headerSlot);
}
centralSlotPannableViewport->positionIndicator()->setStyleName(
q->style()->centralSlotPositionIndicatorStyleName());
}
void MSheetViewPrivate::updateHeaderVisibility()
{
Q_Q(MSheetView);
if (q->model()->headerVisible())
headerSlot->setPos(0,0);
if (headerAnimation) {
if (q->model()->headerVisible())
headerAnimation->setTransitionDirection(MAbstractWidgetAnimation::In);
else
headerAnimation->setTransitionDirection(MAbstractWidgetAnimation::Out);
headerAnimation->start();
}
}
//////////////
/// MSheetView
MSheetView::MSheetView(MSheet *controller) :
MSceneWindowView(*(new MSheetViewPrivate), controller)
{
Q_D(MSheetView);
d->q_ptr = this;
d->init();
}
MSheetView::~MSheetView()
{
}
void MSheetView::setupModel()
{
MSceneWindowView::setupModel();
QList<const char*> modifications;
modifications << MSheetModel::HeaderWidget;
modifications << MSheetModel::CentralWidget;
modifications << MSheetModel::HeaderVisible;
updateData(modifications);
}
void MSheetView::updateData(const QList<const char *> &modifications)
{
Q_D(MSheetView);
MSceneWindowView::updateData(modifications);
const char *member;
for (int i = 0; i < modifications.count(); i++) {
member = modifications[i];
if (member == MSheetModel::HeaderVisible)
d->updateHeaderVisibility();
else if (member == MSheetModel::CentralWidget)
d->centralSlot->setWidget(model()->centralWidget());
else if (member == MSheetModel::HeaderWidget)
d->headerSlot->setWidget(model()->headerWidget());
}
}
void MSheetView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
// Don't let it propagate to widgets below
event->accept();
}
void MSheetView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
// Don't let it propagate to widgets below
event->accept();
}
void MSheetView::applyStyle()
{
Q_D(MSheetView);
MSceneWindowView::applyStyle();
d->updateStyle();
}
M_REGISTER_VIEW_NEW(MSheetView, MSheet)
<commit_msg>Changes: MSheet - disable internal pannable v. if central widget is already a pannable v.<commit_after>/***************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <mscenemanager.h>
#include "mviewcreator.h"
#include <msheet.h>
#include "msheetview.h"
#include "msheetview_p.h"
#include "mabstractwidgetanimation.h"
#include <MDebug>
#include <mpannableviewport.h>
#include <mpositionindicator.h>
#include <QGraphicsAnchorLayout>
#include <QGraphicsLinearLayout>
#include <QGraphicsSceneMouseEvent>
//////////////
/// MSheetSlot
MSheetSlot::MSheetSlot(QGraphicsItem *parent) : MStylableWidget(parent)
{
connect(this, SIGNAL(geometryChanged()), SLOT(resizeChildWidget()));
}
MSheetSlot::~MSheetSlot()
{
// Widget belongs to controller. Remove it from scene graph.
QGraphicsWidget *widget = widgetPointer.data();
if (widget) {
widget->setParentItem(0);
scene()->removeItem(widget);
widgetPointer.clear();
}
}
void MSheetSlot::setWidget(QGraphicsWidget *widget)
{
QGraphicsWidget *currentWidget = widgetPointer.data();
if (widget == currentWidget)
return;
if (currentWidget) {
currentWidget->setParentItem(0);
if (scene())
scene()->removeItem(currentWidget);
}
if (widget) {
widget->setParentItem(this);
widget->setPos(0.0f, 0.0f);
widgetPointer = widget;
resizeChildWidget();
} else {
widgetPointer.clear();
}
}
void MSheetSlot::resizeChildWidget()
{
QGraphicsWidget *widget = widgetPointer.data();
if (widget) {
widget->resize(size());
}
}
//////////////
/// MSheetViewPrivate
MSheetViewPrivate::MSheetViewPrivate()
: q_ptr(0),
rootLayout(0),
headerSlot(0),
centralSlot(0),
centralSlotPannableViewport(0),
headerAnimation(0)
{
}
MSheetViewPrivate::~MSheetViewPrivate()
{
delete headerAnimation;
headerAnimation = 0;
//rootLayout->removeItem(headerSlot);
delete headerSlot;
headerSlot = 0;
//rootLayout->removeItem(centralSlot);
delete centralSlotPannableViewport;
centralSlotPannableViewport = 0;
if (qobject_cast<MSheet *>(controller)) {
// controller is still valid.
// causes rootLayout to be deleted
controller->setLayout(0);
}
rootLayout = 0;
}
void MSheetViewPrivate::init()
{
rootLayout = new QGraphicsAnchorLayout(controller);
rootLayout->setContentsMargins(0, 0, 0, 0);
rootLayout->setSpacing(0);
headerSlot = new MSheetSlot(controller);
headerSlot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
rootLayout->addCornerAnchors(headerSlot, Qt::TopRightCorner, rootLayout, Qt::TopRightCorner);
// The sole purpose of this internal pannable is to guarantee proper input widget relocation
// if the central widget doesn't have a pannable viewport.
centralSlotPannableViewport = new MPannableViewport(controller);
centralSlotPannableViewport->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
centralSlotPannableViewport->setVerticalPanningPolicy(MPannableWidget::PanningAsNeeded);
centralSlotPannableViewport->setObjectName("MSheetCentralSlotPannableViewport");
rootLayout->addCornerAnchors(centralSlotPannableViewport, Qt::TopLeftCorner, headerSlot, Qt::BottomLeftCorner);
rootLayout->addCornerAnchors(centralSlotPannableViewport, Qt::BottomRightCorner, rootLayout, Qt::BottomRightCorner);
centralSlot = new MSheetSlot(centralSlotPannableViewport);
centralSlotPannableViewport->setWidget(centralSlot);
}
void MSheetViewPrivate::updateStyle()
{
Q_Q(MSheetView);
headerSlot->setStyleName(q->style()->headerSlotStyleName());
centralSlot->setStyleName(q->style()->centralSlotStyleName());
delete headerAnimation;
headerAnimation = 0;
if (!q->style()->headerAnimation().isEmpty()) {
headerAnimation = qobject_cast<MAbstractWidgetAnimation*>(MTheme::animation(q->style()->headerAnimation()));
headerAnimation->setTargetWidget(headerSlot);
}
centralSlotPannableViewport->positionIndicator()->setStyleName(
q->style()->centralSlotPositionIndicatorStyleName());
}
void MSheetViewPrivate::updateHeaderVisibility()
{
Q_Q(MSheetView);
if (q->model()->headerVisible())
headerSlot->setPos(0,0);
if (headerAnimation) {
if (q->model()->headerVisible())
headerAnimation->setTransitionDirection(MAbstractWidgetAnimation::In);
else
headerAnimation->setTransitionDirection(MAbstractWidgetAnimation::Out);
headerAnimation->start();
}
}
//////////////
/// MSheetView
MSheetView::MSheetView(MSheet *controller) :
MSceneWindowView(*(new MSheetViewPrivate), controller)
{
Q_D(MSheetView);
d->q_ptr = this;
d->init();
}
MSheetView::~MSheetView()
{
}
void MSheetView::setupModel()
{
MSceneWindowView::setupModel();
QList<const char*> modifications;
modifications << MSheetModel::HeaderWidget;
modifications << MSheetModel::CentralWidget;
modifications << MSheetModel::HeaderVisible;
updateData(modifications);
}
void MSheetView::updateData(const QList<const char *> &modifications)
{
Q_D(MSheetView);
MSceneWindowView::updateData(modifications);
const char *member;
for (int i = 0; i < modifications.count(); i++) {
member = modifications[i];
if (member == MSheetModel::HeaderVisible)
d->updateHeaderVisibility();
else if (member == MSheetModel::CentralWidget) {
if (qobject_cast<MPannableViewport*>(model()->centralWidget()))
// our internal pannable is not needed at all in this case
// TODO: consider removing centralSlotPannableViewport from the widget hierarchy altogether
// if there's any performance benefit in doing so
d->centralSlotPannableViewport->setVerticalPanningPolicy(MPannableViewport::PanningAlwaysOff);
else
d->centralSlotPannableViewport->setVerticalPanningPolicy(MPannableViewport::PanningAsNeeded);
d->centralSlot->setWidget(model()->centralWidget());
} else if (member == MSheetModel::HeaderWidget)
d->headerSlot->setWidget(model()->headerWidget());
}
}
void MSheetView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
// Don't let it propagate to widgets below
event->accept();
}
void MSheetView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
// Don't let it propagate to widgets below
event->accept();
}
void MSheetView::applyStyle()
{
Q_D(MSheetView);
MSceneWindowView::applyStyle();
d->updateStyle();
}
M_REGISTER_VIEW_NEW(MSheetView, MSheet)
<|endoftext|>
|
<commit_before>b1653032-2e4e-11e5-9284-b827eb9e62be<commit_msg>b16a25f6-2e4e-11e5-9284-b827eb9e62be<commit_after>b16a25f6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>21bd8d58-2e4e-11e5-9284-b827eb9e62be<commit_msg>21c299d8-2e4e-11e5-9284-b827eb9e62be<commit_after>21c299d8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>a2cc500a-2e4e-11e5-9284-b827eb9e62be<commit_msg>a2d166f8-2e4e-11e5-9284-b827eb9e62be<commit_after>a2d166f8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>220f0e5e-2e4d-11e5-9284-b827eb9e62be<commit_msg>2214040e-2e4d-11e5-9284-b827eb9e62be<commit_after>2214040e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b7c74942-2e4e-11e5-9284-b827eb9e62be<commit_msg>b7cc610c-2e4e-11e5-9284-b827eb9e62be<commit_after>b7cc610c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.