commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
6e3d8c7b66bf0185fa50c3868eb4677a84c6f6d7
src/skaffari.cpp
src/skaffari.cpp
/* * Skaffari - a mail account administration web interface based on Cutelyst * Copyright (C) 2017 Matthias Fehring <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "skaffari.h" #include <Cutelyst/Application> #include <Cutelyst/Plugins/StaticSimple/StaticSimple> #include <Cutelyst/Plugins/View/Grantlee/grantleeview.h> #include <Cutelyst/Plugins/Session/Session> #include <Cutelyst/Plugins/Authentication/authentication.h> #include <Cutelyst/Plugins/Authentication/credentialpassword.h> #include <Cutelyst/Plugins/Authentication/authenticationrealm.h> #include <Cutelyst/Plugins/Utils/Sql> #include <Cutelyst/Plugins/StatusMessage> #include <Cutelyst/Engine> #include <grantlee5/grantlee/metatype.h> #include <grantlee5/grantlee/engine.h> #include <QSqlDatabase> #include <QSqlError> #include <QDir> #include <QMetaType> #include <QCoreApplication> #include "objects/domain.h" #include "objects/simpleadmin.h" #include "objects/simpledomain.h" #include "objects/adminaccount.h" #include "objects/account.h" #include "objects/folder.h" #include "utils/language.h" #include "../common/config.h" #include "root.h" #include "authstoresql.h" #include "login.h" #include "logout.h" #include "domaineditor.h" #include "accounteditor.h" #include "skaffariengine.h" #include "admineditor.h" #include "myaccount.h" Q_LOGGING_CATEGORY(SK_CORE, "skaffari.core") using namespace Cutelyst; Skaffari::Skaffari(QObject *parent) : Application(parent) { } Skaffari::~Skaffari() { } bool Skaffari::init() { QCoreApplication::setApplicationName(QStringLiteral("Skaffari")); qRegisterMetaType<Folder>(); qRegisterMetaType<Domain>(); qRegisterMetaType<SimpleAdmin>(); qRegisterMetaType<SimpleDomain>(); qRegisterMetaType<AdminAccount>(); qRegisterMetaType<Language>(); qRegisterMetaType<Account>(); Grantlee::registerMetaType<Folder>(); Grantlee::registerMetaType<Domain>(); Grantlee::registerMetaType<SimpleAdmin>(); Grantlee::registerMetaType<SimpleDomain>(); Grantlee::registerMetaType<AdminAccount>(); Grantlee::registerMetaType<Language>(); Grantlee::registerMetaType<Account>(); QString tmplBasePath = QStringLiteral(SKAFFARI_TMPLDIR) + QLatin1Char('/') + config(QStringLiteral("template"), QStringLiteral("default")).toString(); QString sitePath = tmplBasePath + QLatin1String("/site"); auto view = new GrantleeView(this); view->setTemplateExtension(QStringLiteral(".html")); view->setWrapper(QStringLiteral("wrapper.html")); view->setCache(false); view->setIncludePaths({sitePath}); view->engine()->addDefaultLibrary(QStringLiteral("grantlee_i18ntags")); new Root(this); new Login(this); new Logout(this); new DomainEditor(this); new AccountEditor(this); new AdminEditor(this); new MyAccount(this); auto staticSimple = new StaticSimple(this); QString staticPath = tmplBasePath + QLatin1String("/static"); staticSimple->setIncludePaths({staticPath}); new Session(this); new StatusMessage(this); auto auth = new Authentication(this); auto credential = new CredentialPassword(auth); credential->setPasswordType(CredentialPassword::Hashed); auto store = new AuthStoreSql(this); auto realm = new AuthenticationRealm(store, credential, auth); store->setParent(realm); auth->addRealm(store, credential); defaultHeaders().setHeader(QStringLiteral("X-Frame-Options"), QStringLiteral("DENY")); defaultHeaders().setHeader(QStringLiteral("X-Content-Type-Options"), QStringLiteral("nosniff")); defaultHeaders().setHeader(QStringLiteral("X-XSS-Protection"), QStringLiteral("1; mode=block")); defaultHeaders().setHeader(QStringLiteral("Content-Security-Policy"), QStringLiteral("default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; connect-src 'self';")); return true; } bool Skaffari::postFork() { const QVariantMap dbconfig = this->engine()->config(QStringLiteral("Database")); const QString dbtype = dbconfig.value(QStringLiteral("type")).toString(); const QString dbname = dbconfig.value(QStringLiteral("name")).toString(); const QString dbuser = dbconfig.value(QStringLiteral("user")).toString(); const QString dbpass = dbconfig.value(QStringLiteral("password")).toString(); const QString dbhost = dbconfig.value(QStringLiteral("host"), QStringLiteral("localhost")).toString(); const int dbport = dbconfig.value(QStringLiteral("port"), QStringLiteral("3306")).toInt(); QSqlDatabase db; if (dbtype == QLatin1String("QMYSQL")) { if (dbname.isEmpty()) { qCCritical(SK_CORE) << "No database name set!"; return false; } if (dbuser.isEmpty()) { qCCritical(SK_CORE) << "No database user set!"; return false; } if (dbpass.isEmpty()) { qCCritical(SK_CORE) << "No database password set!"; return false; } db = QSqlDatabase::addDatabase(dbtype, Sql::databaseNameThread()); db.setDatabaseName(dbname); db.setUserName(dbuser); db.setPassword(dbpass); if (dbhost[0] == QLatin1Char('/')) { db.setConnectOptions(QStringLiteral("UNIX_SOCKET=%1").arg(dbhost)); } else { db.setHostName(dbhost); db.setPort(dbport); } } else { qCCritical(SK_CORE) << dbtype << "is not a supported database type."; return false; } if (!db.open()) { qCCritical(SK_CORE) << "Failed to establish database connection:" << db.lastError().text(); return false; } auto engine = new SkaffariEngine(this); if (!engine->init(this->engine()->config(QStringLiteral("Admins")), this->engine()->config(QStringLiteral("Defaults")), this->engine()->config(QStringLiteral("Accounts")), this->engine()->config(QStringLiteral("IMAP")))) { return false; } const QVector<Controller*> constControllers = controllers(); for (Controller *c : constControllers) { auto sengine = dynamic_cast<SEngine*>(c); if (sengine) { sengine->engine = engine; } } return true; } #include "moc_skaffari.cpp"
/* * Skaffari - a mail account administration web interface based on Cutelyst * Copyright (C) 2017 Matthias Fehring <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "skaffari.h" #include <Cutelyst/Application> #include <Cutelyst/Plugins/StaticSimple/StaticSimple> #include <Cutelyst/Plugins/View/Grantlee/grantleeview.h> #include <Cutelyst/Plugins/Session/Session> #include <Cutelyst/Plugins/Authentication/authentication.h> #include <Cutelyst/Plugins/Authentication/credentialpassword.h> #include <Cutelyst/Plugins/Authentication/authenticationrealm.h> #include <Cutelyst/Plugins/Utils/Sql> #include <Cutelyst/Plugins/StatusMessage> #include <Cutelyst/Engine> #include <grantlee5/grantlee/metatype.h> #include <grantlee5/grantlee/engine.h> #include <QSqlDatabase> #include <QSqlError> #include <QDir> #include <QMetaType> #include <QCoreApplication> #include "objects/domain.h" #include "objects/simpleadmin.h" #include "objects/simpledomain.h" #include "objects/adminaccount.h" #include "objects/account.h" #include "objects/folder.h" #include "utils/language.h" #include "../common/config.h" #include "root.h" #include "authstoresql.h" #include "login.h" #include "logout.h" #include "domaineditor.h" #include "accounteditor.h" #include "skaffariengine.h" #include "admineditor.h" #include "myaccount.h" Q_LOGGING_CATEGORY(SK_CORE, "skaffari.core") using namespace Cutelyst; Skaffari::Skaffari(QObject *parent) : Application(parent) { } Skaffari::~Skaffari() { } bool Skaffari::init() { QCoreApplication::setApplicationName(QStringLiteral("Skaffari")); QCoreApplication::setApplicationVersion(QStringLiteral(SKAFFARI_VERSION)); qRegisterMetaType<Folder>(); qRegisterMetaType<Domain>(); qRegisterMetaType<SimpleAdmin>(); qRegisterMetaType<SimpleDomain>(); qRegisterMetaType<AdminAccount>(); qRegisterMetaType<Language>(); qRegisterMetaType<Account>(); Grantlee::registerMetaType<Folder>(); Grantlee::registerMetaType<Domain>(); Grantlee::registerMetaType<SimpleAdmin>(); Grantlee::registerMetaType<SimpleDomain>(); Grantlee::registerMetaType<AdminAccount>(); Grantlee::registerMetaType<Language>(); Grantlee::registerMetaType<Account>(); QString tmplBasePath = QStringLiteral(SKAFFARI_TMPLDIR) + QLatin1Char('/') + config(QStringLiteral("template"), QStringLiteral("default")).toString(); QString sitePath = tmplBasePath + QLatin1String("/site"); auto view = new GrantleeView(this); view->setTemplateExtension(QStringLiteral(".html")); view->setWrapper(QStringLiteral("wrapper.html")); view->setCache(false); view->setIncludePaths({sitePath}); view->engine()->addDefaultLibrary(QStringLiteral("grantlee_i18ntags")); new Root(this); new Login(this); new Logout(this); new DomainEditor(this); new AccountEditor(this); new AdminEditor(this); new MyAccount(this); auto staticSimple = new StaticSimple(this); QString staticPath = tmplBasePath + QLatin1String("/static"); staticSimple->setIncludePaths({staticPath}); new Session(this); new StatusMessage(this); auto auth = new Authentication(this); auto credential = new CredentialPassword(auth); credential->setPasswordType(CredentialPassword::Hashed); auto store = new AuthStoreSql(this); auto realm = new AuthenticationRealm(store, credential, auth); store->setParent(realm); auth->addRealm(store, credential); defaultHeaders().setHeader(QStringLiteral("X-Frame-Options"), QStringLiteral("DENY")); defaultHeaders().setHeader(QStringLiteral("X-Content-Type-Options"), QStringLiteral("nosniff")); defaultHeaders().setHeader(QStringLiteral("X-XSS-Protection"), QStringLiteral("1; mode=block")); defaultHeaders().setHeader(QStringLiteral("Content-Security-Policy"), QStringLiteral("default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; connect-src 'self';")); return true; } bool Skaffari::postFork() { const QVariantMap dbconfig = this->engine()->config(QStringLiteral("Database")); const QString dbtype = dbconfig.value(QStringLiteral("type")).toString(); const QString dbname = dbconfig.value(QStringLiteral("name")).toString(); const QString dbuser = dbconfig.value(QStringLiteral("user")).toString(); const QString dbpass = dbconfig.value(QStringLiteral("password")).toString(); const QString dbhost = dbconfig.value(QStringLiteral("host"), QStringLiteral("localhost")).toString(); const int dbport = dbconfig.value(QStringLiteral("port"), QStringLiteral("3306")).toInt(); QSqlDatabase db; if (dbtype == QLatin1String("QMYSQL")) { if (dbname.isEmpty()) { qCCritical(SK_CORE) << "No database name set!"; return false; } if (dbuser.isEmpty()) { qCCritical(SK_CORE) << "No database user set!"; return false; } if (dbpass.isEmpty()) { qCCritical(SK_CORE) << "No database password set!"; return false; } db = QSqlDatabase::addDatabase(dbtype, Sql::databaseNameThread()); db.setDatabaseName(dbname); db.setUserName(dbuser); db.setPassword(dbpass); if (dbhost[0] == QLatin1Char('/')) { db.setConnectOptions(QStringLiteral("UNIX_SOCKET=%1").arg(dbhost)); } else { db.setHostName(dbhost); db.setPort(dbport); } } else { qCCritical(SK_CORE) << dbtype << "is not a supported database type."; return false; } if (!db.open()) { qCCritical(SK_CORE) << "Failed to establish database connection:" << db.lastError().text(); return false; } auto engine = new SkaffariEngine(this); if (!engine->init(this->engine()->config(QStringLiteral("Admins")), this->engine()->config(QStringLiteral("Defaults")), this->engine()->config(QStringLiteral("Accounts")), this->engine()->config(QStringLiteral("IMAP")))) { return false; } const QVector<Controller*> constControllers = controllers(); for (Controller *c : constControllers) { auto sengine = dynamic_cast<SEngine*>(c); if (sengine) { sengine->engine = engine; } } return true; } #include "moc_skaffari.cpp"
Add application version
Add application version
C++
agpl-3.0
Buschtrommel/Skaffari,Buschtrommel/Skaffari,Buschtrommel/Skaffari,Buschtrommel/Skaffari,Huessenbergnetz/Skaffari,Huessenbergnetz/Skaffari,Buschtrommel/Skaffari,Huessenbergnetz/Skaffari,Huessenbergnetz/Skaffari,Huessenbergnetz/Skaffari,Huessenbergnetz/Skaffari
023109d30f04e54ecc6bb225f587c41603d9684b
header/CThreadPool_Ret.hpp
header/CThreadPool_Ret.hpp
#ifndef CTHREADPOOL_RET #define CTHREADPOOL_RET #include<thread> //thread::hardware_concurrency #include<type_traits> //result_of_t #include<unordered_map> #include<utility> //forward, move #include"../../lib/header/thread/CThreadRingBuf.hpp" #include"CThreadPoolItem_Ret.hpp" namespace nThread { //1. a fixed-sized threadpool //2. can return value template<class Ret> class CThreadPool_Ret { public: using size_type=std::result_of_t<decltype(std::thread::hardware_concurrency)&()>; using thread_id=IThreadPoolItemBase::id; private: CThreadRingBuf<CThreadPoolItem_Ret<Ret>*> waiting_buf_; std::unordered_map<thread_id,CThreadPoolItem_Ret<Ret>> thr_; public: //CThreadPool_Ret::CThreadPool_Ret() // :CThreadPool_Ret(std::thread::hardware_concurrency()){} CThreadPool_Ret() :CThreadPool_Ret{std::thread::hardware_concurrency()}{} //1. determine the total of usable threads //2. the value you pass will always equal to CThreadPool_Ret::size explicit CThreadPool_Ret(size_type size) :waiting_buf_{size},thr_{size} { while(size--) { CThreadPoolItem_Ret<Ret> item{&waiting_buf_}; const auto id{item.get_id()}; waiting_buf_.write(&thr_.emplace(id,std::move(item)).first->second); } } //of course, why do you need to copy or move CThreadPool_Ret? CThreadPool_Ret(const CThreadPool_Ret &)=delete; //1. block until CThreadPool_Ret::available is not zero and execute the func //2. after returning from add, CThreadPool_Ret::available will reduce 1 //3. after returning from add, CThreadPool_Ret::valid(thread_id) will return true //4. //you must call CThreadPool_Ret::get after returning from add at some moment //otherwise, CThreadPool_Ret::available cannot increase 1 template<class Func,class ... Args> thread_id add(Func &&func,Args &&...args) { auto temp{waiting_buf_.read()}; temp->assign(std::forward<Func>(func),std::forward<Args>(args)...); return temp->get_id(); } //1. return the total of usable threads at that moment //2. reduce 1 after returning from CThreadPool_Ret::add //3. increase 1 after returning from CThreadPool_Ret::get //4. non-block inline size_type available() const noexcept { return static_cast<size_type>(waiting_buf_.size()); } //1. block until the thread_id completes the func //2. after returning from get, CThreadPool_Ret::valid(thread_id) will return false //3. if the thread_id is not valid, do not get the thread_id inline Ret get(const thread_id id) { return thr_.at(id).get(); } //1. return the total of usable threads //2. is fixed after constructing //3. non-block inline size_type size() const noexcept { return static_cast<size_type>(thr_.size()); } //1. return whether the thread_id has been get yet //2. return true for the thread_id which was returned by CThreadPool_Ret::add //3. return false for the thread_id which was used by CThreadPool_Ret::get //4. non-block inline bool valid(const thread_id id) const noexcept { return thr_.at(id).is_running(); } //block until the thread_id completes the func inline void wait(const thread_id id) const { thr_.at(id).wait(); } void wait_all() const { for(const auto &val:thr_) if(valid(val.first)) wait(val.first); } //of course, why do you need to copy or move CThreadPool_Ret? CThreadPool_Ret& operator=(const CThreadPool_Ret &)=delete; //get all the threads in destructor }; } #endif
#ifndef CTHREADPOOL_RET #define CTHREADPOOL_RET #include<thread> //thread::hardware_concurrency #include<type_traits> //result_of_t #include<unordered_map> #include<utility> //forward, move #include"../../lib/header/thread/CThreadRingBuf.hpp" #include"CThreadPoolItem_Ret.hpp" namespace nThread { //1. a fixed-sized threadpool //2. can return value template<class Ret> class CThreadPool_Ret { public: using size_type=std::result_of_t<decltype(std::thread::hardware_concurrency)&()>; using thread_id=IThreadPoolItemBase::id; private: CThreadRingBuf<CThreadPoolItem_Ret<Ret>*> waiting_buf_; std::unordered_map<thread_id,CThreadPoolItem_Ret<Ret>> thr_; public: CThreadPool_Ret() :CThreadPool_Ret{std::thread::hardware_concurrency()}{} //1. determine the total of usable threads //2. the value you pass will always equal to CThreadPool_Ret::size explicit CThreadPool_Ret(size_type size) :waiting_buf_{size},thr_{size} { while(size--) { CThreadPoolItem_Ret<Ret> item{&waiting_buf_}; const auto id{item.get_id()}; waiting_buf_.write(&thr_.emplace(id,std::move(item)).first->second); } } //of course, why do you need to copy or move CThreadPool_Ret? CThreadPool_Ret(const CThreadPool_Ret &)=delete; //1. block until CThreadPool_Ret::available is not zero and execute the func //2. after returning from add, CThreadPool_Ret::available will reduce 1 //3. after returning from add, CThreadPool_Ret::valid(thread_id) will return true //4. //you must call CThreadPool_Ret::get after returning from add at some moment //otherwise, CThreadPool_Ret::available cannot increase 1 template<class Func,class ... Args> thread_id add(Func &&func,Args &&...args) { auto temp{waiting_buf_.read()}; temp->assign(std::forward<Func>(func),std::forward<Args>(args)...); return temp->get_id(); } //1. return the total of usable threads at that moment //2. reduce 1 after returning from CThreadPool_Ret::add //3. increase 1 after returning from CThreadPool_Ret::get //4. non-block inline size_type available() const noexcept { return static_cast<size_type>(waiting_buf_.size()); } //1. block until the thread_id completes the func //2. after returning from get, CThreadPool_Ret::valid(thread_id) will return false //3. if the thread_id is not valid, do not get the thread_id inline Ret get(const thread_id id) { return thr_.at(id).get(); } //1. return the total of usable threads //2. is fixed after constructing //3. non-block inline size_type size() const noexcept { return static_cast<size_type>(thr_.size()); } //1. return whether the thread_id has been get yet //2. return true for the thread_id which was returned by CThreadPool_Ret::add //3. return false for the thread_id which was used by CThreadPool_Ret::get //4. non-block inline bool valid(const thread_id id) const noexcept { return thr_.at(id).is_running(); } //block until the thread_id completes the func inline void wait(const thread_id id) const { thr_.at(id).wait(); } void wait_all() const { for(const auto &val:thr_) if(valid(val.first)) wait(val.first); } //of course, why do you need to copy or move CThreadPool_Ret? CThreadPool_Ret& operator=(const CThreadPool_Ret &)=delete; //get all the threads in destructor }; } #endif
remove comment
remove comment
C++
mit
Fdhvdu/ThreadPool
3c54c721f6519dcb3c0d6b1f177a03bcb2d5dc26
prototype2/tools/ReaderPcap.cpp
prototype2/tools/ReaderPcap.cpp
/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <algorithm> #include <arpa/inet.h> #include <cassert> #include <cinttypes> #include <cstring> #include <tools/ReaderPcap.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <fmt/format.h> // GCOVR_EXCL_START // Protocol identifiers const int ETHERTYPE_ARP = 0x0806; const int ETHERTYPE_IPV4 = 0x0800; const int IPPROTO_UDP = 17; // Header and data location specifications const int ETHERTYPE_OFFSET = 12; const int ETHERNET_HEADER_SIZE = 14; #define IP_HEADR_OFFSET 14 #define IP_HEADER_SIZE 20 #define UDP_HEADER_OFFSET 34 #define UDP_HEADER_SIZE 8 #define UDP_DATA_OFFSET 42 ReaderPcap::ReaderPcap(std::string filename) : FileName(filename) { memset(&Stats, 0, sizeof(struct stats_t)); } ReaderPcap::~ReaderPcap() { if (PcapHandle != NULL ) { pcap_close(PcapHandle); } } int ReaderPcap::open() { char errbuff[PCAP_ERRBUF_SIZE]; PcapHandle = pcap_open_offline(FileName.c_str(), errbuff); if (PcapHandle == NULL) { return -1; } return 0; } int ReaderPcap::validatePacket(pcap_pkthdr *header, const unsigned char *data) { Stats.PacketsTotal++; /**< total packets in pcap file */ Stats.BytesTotal += header->len; if (header->len != header->caplen) { Stats.PacketsTruncated++; return 0; } uint16_t type = ntohs(*(uint16_t *)&data[ETHERTYPE_OFFSET]); // printf("packet header len %d, type %x\n", header->len, type); if (type == ETHERTYPE_ARP) { Stats.EtherTypeArp++; } else if (type == ETHERTYPE_IPV4) { Stats.EtherTypeIpv4++; } else { Stats.EtherTypeUnknown++; } if (type != ETHERTYPE_IPV4) { // must be ipv4 return 0; } ip *ip = (ip *)&data[IP_HEADR_OFFSET]; // IPv4 header length must be 20, ip version 4, ipproto must be UDP if ((ip->ip_hl != 5) or (ip->ip_v != 4) or (ip->ip_p != IPPROTO_UDP)) { Stats.IpProtoUnknown++; return 0; } Stats.IpProtoUDP++; assert(header->len > ETHERNET_HEADER_SIZE + IP_HEADER_SIZE + UDP_HEADER_SIZE); assert(Stats.PacketsTotal == Stats.EtherTypeIpv4 + Stats.EtherTypeArp + Stats.EtherTypeUnknown); assert(Stats.EtherTypeIpv4 == Stats.IpProtoUDP + Stats.IpProtoUnknown); udphdr *udp = (udphdr *)&data[UDP_HEADER_OFFSET]; #ifndef __FAVOR_BSD // Why is __FAVOR_BSD not defined here? uint16_t UdpLen = htons(udp->len); #else uint16_t UdpLen = htons(udp->uh_ulen); #endif assert(UdpLen >= UDP_HEADER_SIZE); #if 0 printf("UDP Payload, Packet %" PRIu64 ", time: %d:%d seconds, size: %d bytes\n", Stats.PacketsTotal, (int)header->ts.tv_sec, (int)header->ts.tv_usec, (int)header->len); printf("ip src->dest: 0x%08x:%d ->0x%08x:%d\n", ntohl(*(uint32_t*)&ip->ip_src), ntohs(udp->uh_sport), ntohl(*(uint32_t*)&ip->ip_dst), ntohs(udp->uh_dport)); #endif return UdpLen; } int ReaderPcap::read(char *buffer, size_t bufferlen) { if (PcapHandle == nullptr) { return -1; } pcap_pkthdr *Header; const unsigned char *Data; int ret = pcap_next_ex(PcapHandle, &Header, &Data); if (ret < 0) { return -1; } int UdpDataLength; if ((UdpDataLength = validatePacket(Header, Data)) <= 0) { return UdpDataLength; } auto DataLength = std::min((size_t)(UdpDataLength - UDP_HEADER_SIZE), bufferlen); std::memcpy(buffer, &Data[UDP_DATA_OFFSET], DataLength); return DataLength; } int ReaderPcap::getStats() { if (PcapHandle == NULL) { return -1; } while (true) { int RetVal; struct pcap_pkthdr *Header; const unsigned char *Data; if ((RetVal = pcap_next_ex(PcapHandle, &Header, &Data)) < 0) { break; } validatePacket(Header, Data); } return 0; } void ReaderPcap::printPacket(unsigned char *data, size_t len) { for (unsigned int i = 0; i < len; i++) { if ((i % 16) == 0 && i != 0) { printf("\n"); } printf("%.2x ", data[i]); } printf("\n"); } void ReaderPcap::printStats() { printf("Total packets %" PRIu64 "\n", Stats.PacketsTotal); printf("Truncated packets %" PRIu64 "\n", Stats.PacketsTruncated); printf("Ethertype IPv4 %" PRIu64 "\n", Stats.EtherTypeIpv4); printf(" ipproto UDP %" PRIu64 "\n", Stats.IpProtoUDP); printf(" ipproto other %" PRIu64 "\n", Stats.IpProtoUnknown); printf("Ethertype unknown %" PRIu64 "\n", Stats.EtherTypeUnknown); printf("Ethertype ARP %" PRIu64 "\n", Stats.EtherTypeArp); printf("Total bytes %" PRIu64 "\n", Stats.BytesTotal); } // GCOVR_EXCL_STOP
/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <algorithm> #include <arpa/inet.h> #include <cassert> #include <cinttypes> #include <cstring> #include <tools/ReaderPcap.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <fmt/format.h> // GCOVR_EXCL_START // Protocol identifiers const int ETHERTYPE_ARP = 0x0806; const int ETHERTYPE_IPV4 = 0x0800; const int IPPROTO_UDP = 17; // Header and data location specifications const int ETHERTYPE_OFFSET = 12; const int ETHERNET_HEADER_SIZE = 14; #define IP_HEADR_OFFSET 14 #define IP_HEADER_SIZE 20 #define UDP_HEADER_OFFSET 34 #define UDP_HEADER_SIZE 8 #define UDP_DATA_OFFSET 42 ReaderPcap::ReaderPcap(std::string filename) : FileName(filename) { memset(&Stats, 0, sizeof(struct stats_t)); } ReaderPcap::~ReaderPcap() { if (PcapHandle != NULL ) { pcap_close(PcapHandle); } } int ReaderPcap::open() { char errbuff[PCAP_ERRBUF_SIZE]; PcapHandle = pcap_open_offline(FileName.c_str(), errbuff); if (PcapHandle == NULL) { return -1; } return 0; } int ReaderPcap::validatePacket(pcap_pkthdr *header, const unsigned char *data) { Stats.PacketsTotal++; /**< total packets in pcap file */ Stats.BytesTotal += header->len; if (header->len != header->caplen) { Stats.PacketsTruncated++; return 0; } uint16_t type = ntohs(*(uint16_t *)&data[ETHERTYPE_OFFSET]); // printf("packet header len %d, type %x\n", header->len, type); if (type == ETHERTYPE_ARP) { Stats.EtherTypeArp++; } else if (type == ETHERTYPE_IPV4) { Stats.EtherTypeIpv4++; } else { Stats.EtherTypeUnknown++; } if (type != ETHERTYPE_IPV4) { // must be ipv4 return 0; } ip *ip = (ip *)&data[IP_HEADR_OFFSET]; // IPv4 header length must be 20, ip version 4, ipproto must be UDP if ((ip->ip_hl != 5) or (ip->ip_v != 4) or (ip->ip_p != IPPROTO_UDP)) { Stats.IpProtoUnknown++; return 0; } Stats.IpProtoUDP++; assert(header->len > ETHERNET_HEADER_SIZE + IP_HEADER_SIZE + UDP_HEADER_SIZE); assert(Stats.PacketsTotal == Stats.EtherTypeIpv4 + Stats.EtherTypeArp + Stats.EtherTypeUnknown); assert(Stats.EtherTypeIpv4 == Stats.IpProtoUDP + Stats.IpProtoUnknown); udphdr *udp = (udphdr *)&data[UDP_HEADER_OFFSET]; #ifndef __FAVOR_BSD // Why is __FAVOR_BSD not defined here? uint16_t UdpLen = htons(udp->len); #else uint16_t UdpLen = htons(udp->uh_ulen); #endif assert(UdpLen >= UDP_HEADER_SIZE); #if 0 printf("UDP Payload, Packet %" PRIu64 ", time: %d:%d seconds, size: %d bytes\n", Stats.PacketsTotal, (int)header->ts.tv_sec, (int)header->ts.tv_usec, (int)header->len); printf("ip src->dest: 0x%08x:%d ->0x%08x:%d\n", ntohl(*(uint32_t*)&ip->ip_src), ntohs(udp->uh_sport), ntohl(*(uint32_t*)&ip->ip_dst), ntohs(udp->uh_dport)); #endif return UdpLen; } int ReaderPcap::read(char *buffer, size_t bufferlen) { if (PcapHandle == nullptr) { return -1; } pcap_pkthdr *Header; const unsigned char *Data; int ret = pcap_next_ex(PcapHandle, &Header, &Data); if (ret < 0) { return -1; } int UdpDataLength; if ((UdpDataLength = validatePacket(Header, Data)) <= 0) { return UdpDataLength; } auto DataLength = std::min((size_t)(UdpDataLength - UDP_HEADER_SIZE), bufferlen); std::memcpy(buffer, &Data[UDP_DATA_OFFSET], DataLength); return DataLength; } int ReaderPcap::getStats() { if (PcapHandle == NULL) { return -1; } while (true) { int RetVal; pcap_pkthdr *Header; const unsigned char *Data; if ((RetVal = pcap_next_ex(PcapHandle, &Header, &Data)) < 0) { break; } validatePacket(Header, Data); } return 0; } void ReaderPcap::printPacket(unsigned char *data, size_t len) { for (unsigned int i = 0; i < len; i++) { if ((i % 16) == 0 && i != 0) { printf("\n"); } printf("%.2x ", data[i]); } printf("\n"); } void ReaderPcap::printStats() { printf("Total packets %" PRIu64 "\n", Stats.PacketsTotal); printf("Truncated packets %" PRIu64 "\n", Stats.PacketsTruncated); printf("Ethertype IPv4 %" PRIu64 "\n", Stats.EtherTypeIpv4); printf(" ipproto UDP %" PRIu64 "\n", Stats.IpProtoUDP); printf(" ipproto other %" PRIu64 "\n", Stats.IpProtoUnknown); printf("Ethertype unknown %" PRIu64 "\n", Stats.EtherTypeUnknown); printf("Ethertype ARP %" PRIu64 "\n", Stats.EtherTypeArp); printf("Total bytes %" PRIu64 "\n", Stats.BytesTotal); } // GCOVR_EXCL_STOP
Update prototype2/tools/ReaderPcap.cpp
Update prototype2/tools/ReaderPcap.cpp Co-Authored-By: Jonas Nilsson <[email protected]>
C++
bsd-2-clause
ess-dmsc/event-formation-unit,ess-dmsc/event-formation-unit,ess-dmsc/event-formation-unit,ess-dmsc/event-formation-unit
08c1897fb747639e353cc56f39ae3c8c516543e9
src/commands/base/sign.cxx
src/commands/base/sign.cxx
/** * Copyright (C) 2015 Virgil Security Inc. * * Lead Maintainer: Virgil Security Inc. <[email protected]> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * (1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * (3) Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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 <fstream> #include <iostream> #include <iterator> #include <stdexcept> #include <string> #include <tclap/CmdLine.h> #include <virgil/crypto/VirgilByteArray.h> #include <virgil/crypto/VirgilStreamSigner.h> #include <virgil/crypto/stream/VirgilStreamDataSource.h> #include <cli/version.h> #include <cli/util.h> namespace vcrypto = virgil::crypto; namespace vcli = virgil::cli; #ifdef SPLIT_CLI #define MAIN main #else #define MAIN sign_main #endif int MAIN(int argc, char** argv) { try { std::string description = "Sign data with given user's Private Key.\n"; std::vector<std::string> examples; examples.push_back("virgil sign -i plain.txt -o plain.txt.sign -k alice/private.key\n"); examples.push_back("virgil sign -i plain.txt -o plain.txt.sign -k alice/private.key -p STRONGPASS\n"); std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples); // Parse arguments. TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version()); TCLAP::ValueArg<std::string> inArg("i", "in", "Data to be signed. If omitted, stdin is used.", false, "", "file"); TCLAP::ValueArg<std::string> outArg("o", "out", "Digest sign. If omitted, stdout is used.", false, "", "file"); TCLAP::ValueArg<std::string> privateKeyArg("k", "key", "Signer's Private Key.", true, "", "file"); TCLAP::ValueArg<std::string> privateKeyPasswordArg( "p", "private-key-password", "Password to be used for Private Key encryption.", false, "", "arg"); TCLAP::SwitchArg verboseArg("V", "VERBOSE", "Show detailed information", false); cmd.add(verboseArg); cmd.add(privateKeyPasswordArg); cmd.add(privateKeyArg); cmd.add(outArg); cmd.add(inArg); cmd.parse(argc, argv); // Prepare input std::istream* inStream; std::ifstream inFile; if (inArg.getValue().empty() || inArg.getValue() == "-") { inStream = &std::cin; } else { inFile.open(inArg.getValue(), std::ios::in | std::ios::binary); if (!inFile) { throw std::invalid_argument("cannot read file: " + inArg.getValue()); } inStream = &inFile; } // Read private key vcrypto::VirgilByteArray privateKey = vcli::readPrivateKey(privateKeyArg.getValue()); vcrypto::VirgilByteArray privateKeyPassword; if (privateKeyPasswordArg.isSet()) { privateKeyPassword = vcrypto::str2bytes(privateKeyPasswordArg.getValue()); } else { privateKeyPassword = vcli::setPrivateKeyPass(privateKey); } // Create signer vcrypto::VirgilStreamSigner signer; // Sign data vcrypto::stream::VirgilStreamDataSource dataSource(*inStream); vcrypto::VirgilByteArray sign = signer.sign(dataSource, privateKey, privateKeyPassword); // Prepare output. Write sign to the output. vcli::writeBytes(outArg.getValue(), sign); if (verboseArg.isSet()) { std::cout << "File signing" << std::endl; } } catch (TCLAP::ArgException& exception) { std::cerr << "sing. Error: " << exception.error() << " for arg " << exception.argId() << std::endl; return EXIT_FAILURE; } catch (std::exception& exception) { std::cerr << "sign. Error: " << exception.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
/** * Copyright (C) 2015 Virgil Security Inc. * * Lead Maintainer: Virgil Security Inc. <[email protected]> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * (1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * (3) Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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 <fstream> #include <iostream> #include <iterator> #include <stdexcept> #include <string> #include <tclap/CmdLine.h> #include <virgil/crypto/VirgilByteArray.h> #include <virgil/crypto/VirgilStreamSigner.h> #include <virgil/crypto/stream/VirgilStreamDataSource.h> #include <cli/version.h> #include <cli/util.h> namespace vcrypto = virgil::crypto; namespace vcli = virgil::cli; #ifdef SPLIT_CLI #define MAIN main #else #define MAIN sign_main #endif int MAIN(int argc, char** argv) { try { std::string description = "Sign data with given user's Private Key.\n"; std::vector<std::string> examples; examples.push_back("virgil sign -i plain.txt -o plain.txt.sign -k alice/private.key\n"); examples.push_back("virgil sign -i plain.txt -o plain.txt.sign -k alice/private.key -p STRONGPASS\n"); std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples); // Parse arguments. TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version()); TCLAP::ValueArg<std::string> inArg("i", "in", "Data to be signed. If omitted, stdin is used.", false, "", "file"); TCLAP::ValueArg<std::string> outArg("o", "out", "Digest sign. If omitted, stdout is used.", false, "", "file"); TCLAP::ValueArg<std::string> privateKeyArg("k", "key", "Signer's Private Key.", true, "", "file"); TCLAP::ValueArg<std::string> privateKeyPasswordArg( "p", "private-key-password", "Password to be used for Private Key encryption.", false, "", "arg"); TCLAP::SwitchArg verboseArg("V", "VERBOSE", "Show detailed information", false); cmd.add(verboseArg); cmd.add(privateKeyPasswordArg); cmd.add(privateKeyArg); cmd.add(outArg); cmd.add(inArg); cmd.parse(argc, argv); // Prepare input std::istream* inStream; std::ifstream inFile; if (inArg.getValue().empty() || inArg.getValue() == "-") { inStream = &std::cin; } else { inFile.open(inArg.getValue(), std::ios::in | std::ios::binary); if (!inFile) { throw std::invalid_argument("cannot read file: " + inArg.getValue()); } inStream = &inFile; } // Read private key vcrypto::VirgilByteArray privateKey = vcli::readPrivateKey(privateKeyArg.getValue()); vcrypto::VirgilByteArray privateKeyPassword; if (privateKeyPasswordArg.isSet()) { privateKeyPassword = vcrypto::str2bytes(privateKeyPasswordArg.getValue()); } else { privateKeyPassword = vcli::setPrivateKeyPass(privateKey); } // Create signer vcrypto::VirgilStreamSigner signer; // Sign data vcrypto::stream::VirgilStreamDataSource dataSource(*inStream); vcrypto::VirgilByteArray sign = signer.sign(dataSource, privateKey, privateKeyPassword); // Prepare output. Write sign to the output. vcli::writeBytes(outArg.getValue(), sign); if (verboseArg.isSet()) { std::cout << "File signed" << std::endl; } } catch (TCLAP::ArgException& exception) { std::cerr << "sing. Error: " << exception.error() << " for arg " << exception.argId() << std::endl; return EXIT_FAILURE; } catch (std::exception& exception) { std::cerr << "sign. Error: " << exception.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Change message for 'verbose' info in sign.cxx
Change message for 'verbose' info in sign.cxx
C++
bsd-3-clause
VirgilSecurity/virgil-cli
ad230110f2fdb4cf977b97afc35a4f2eebaf0f0b
content/browser/renderer_host/resource_dispatcher_host_uitest.cc
content/browser/renderer_host/resource_dispatcher_host_uitest.cc
// Copyright (c) 2011 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 <sstream> #include <string> #include "base/command_line.h" #include "base/file_path.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/test/test_timeouts.h" #include "chrome/browser/net/url_request_failed_dns_job.h" #include "chrome/browser/net/url_request_mock_http_job.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" namespace { class ResourceDispatcherTest : public UITest { public: void CheckTitleTest(const std::string& file, const std::string& expected_title, int expected_navigations) { NavigateToURLBlockUntilNavigationsComplete( URLRequestMockHTTPJob::GetMockUrl(FilePath().AppendASCII(file)), expected_navigations); EXPECT_EQ(expected_title, WideToASCII(GetActiveTabTitle())); } protected: ResourceDispatcherTest() : UITest() { dom_automation_enabled_ = true; } }; TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) { CheckTitleTest("content-sniffer-test0.html", "Content Sniffer Test 0", 1); } TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) { CheckTitleTest("nosniff-test.html", "mock.http/nosniff-test.html", 1); } TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) { CheckTitleTest("content-sniffer-test1.html", "mock.http/content-sniffer-test1.html", 1); } TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) { CheckTitleTest("content-sniffer-test2.html", "mock.http/content-sniffer-test2.html", 1); } TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) { CheckTitleTest("content-sniffer-test3.html", "Content Sniffer Test 3", 1); EXPECT_EQ(1, GetTabCount()); // Make sure the download shelf is not showing. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); bool visible = false; ASSERT_TRUE(browser->IsShelfVisible(&visible)); EXPECT_FALSE(visible); } TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) { CheckTitleTest("content-disposition-empty.html", "success", 1); } TEST_F(ResourceDispatcherTest, ContentDispositionInline) { CheckTitleTest("content-disposition-inline.html", "success", 1); } // Test for bug #1091358. // Flaky: http://crbug.com/62595 TEST_F(ResourceDispatcherTest, FLAKY_SyncXMLHttpRequest) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(test_server.Start()); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_server.GetURL( "files/sync_xmlhttprequest.html"))); // Let's check the XMLHttpRequest ran successfully. bool success = false; EXPECT_TRUE(tab->ExecuteAndExtractBool(L"", L"window.domAutomationController.send(DidSyncRequestSucceed());", &success)); EXPECT_TRUE(success); } // http://code.google.com/p/chromium/issues/detail?id=62776 TEST_F(ResourceDispatcherTest, FLAKY_SyncXMLHttpRequest_Disallowed) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(test_server.Start()); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_server.GetURL( "files/sync_xmlhttprequest_disallowed.html"))); // Let's check the XMLHttpRequest ran successfully. bool success = false; EXPECT_TRUE(tab->ExecuteAndExtractBool(L"", L"window.domAutomationController.send(DidSucceed());", &success)); EXPECT_TRUE(success); } // Test for bug #1159553 -- A synchronous xhr (whose content-type is // downloadable) would trigger download and hang the renderer process, // if executed while navigating to a new page. // Disabled -- http://code.google.com/p/chromium/issues/detail?id=56264 TEST_F(ResourceDispatcherTest, DISABLED_SyncXMLHttpRequest_DuringUnload) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(test_server.Start()); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_server.GetURL( "files/sync_xmlhttprequest_during_unload.html"))); // Confirm that the page has loaded (since it changes its title during load). std::wstring tab_title; EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"sync xhr on unload", tab_title); // Navigate to a new page, to dispatch unload event and trigger xhr. // (the bug would make this step hang the renderer). ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_server.GetURL("files/title2.html"))); // Check that the new page got loaded, and that no download was triggered. EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"Title Of Awesomeness", tab_title); bool shelf_is_visible = false; scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible)); EXPECT_FALSE(shelf_is_visible); } // Tests that onunload is run for cross-site requests. (Bug 1114994) TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(test_server.Start()); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); GURL url(test_server.GetURL("files/onunload_cookie.html")); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url)); // Confirm that the page has loaded (since it changes its title during load). std::wstring tab_title; EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"set cookie on unload", tab_title); // Navigate to a new cross-site page, to dispatch unload event and set the // cookie. CheckTitleTest("content-sniffer-test0.html", "Content Sniffer Test 0", 1); // Check that the cookie was set. std::string value_result; ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result)); ASSERT_FALSE(value_result.empty()); ASSERT_STREQ("foo", value_result.c_str()); } #if !defined(OS_MACOSX) // Tests that the onbeforeunload and onunload logic is shortcutted if the old // renderer is gone. In that case, we don't want to wait for the old renderer // to run the handlers. // We need to disable this on Mac because the crash causes the OS CrashReporter // process to kick in to analyze the poor dead renderer. Unfortunately, if the // app isn't stripped of debug symbols, this takes about five minutes to // complete and isn't conducive to quick turnarounds. As we don't currently // strip the app on the build bots, this is bad times. TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) { // This test only works in multi-process mode if (ProxyLauncher::in_process_renderer()) return; scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); // Cause the renderer to crash. #if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD) expected_crashes_ = 1; #endif ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL))); // Wait for browser to notice the renderer crash. base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms()); // Navigate to a new cross-site page. The browser should not wait around for // the old renderer's on{before}unload handlers to run. CheckTitleTest("content-sniffer-test0.html", "Content Sniffer Test 0", 1); } #endif // !defined(OS_MACOSX) // Tests that cross-site navigations work when the new page does not go through // the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872) TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) { scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); // Start with an HTTP page. CheckTitleTest("content-sniffer-test0.html", "Content Sniffer Test 0", 1); // Now load a file:// page, which does not use the BufferedEventHandler. // Make sure that the page loads and displays a title, and doesn't get stuck. FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("title2.html"); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(net::FilePathToFileURL(test_file))); EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle()); } // Tests that a cross-site navigation to an error page (resulting in the link // doctor page) still runs the onunload handler and can support navigations // away from the link doctor page. (Bug 1235537) TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(test_server.Start()); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); GURL url(test_server.GetURL("files/onunload_cookie.html")); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url)); // Confirm that the page has loaded (since it changes its title during load). std::wstring tab_title; EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"set cookie on unload", tab_title); // Navigate to a new cross-site URL that results in an error page. // TODO(creis): If this causes crashes or hangs, it might be for the same // reason as ErrorPageTest::DNSError. See bug 1199491 and // http://crbug.com/22877. ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURLBlockUntilNavigationsComplete( GURL(URLRequestFailedDnsJob::kTestUrl), 2)); EXPECT_NE(L"set cookie on unload", GetActiveTabTitle()); // Check that the cookie was set, meaning that the onunload handler ran. std::string value_result; EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result)); EXPECT_FALSE(value_result.empty()); EXPECT_STREQ("foo", value_result.c_str()); // Check that renderer-initiated navigations still work. In a previous bug, // the ResourceDispatcherHost would think that such navigations were // cross-site, because we didn't clean up from the previous request. Since // TabContents was in the NORMAL state, it would ignore the attempt to run // the onunload handler, and the navigation would fail. // (Test by redirecting to javascript:window.location='someURL'.) GURL test_url(test_server.GetURL("files/title2.html")); std::string redirect_url = "javascript:window.location='" + test_url.possibly_invalid_spec() + "'"; ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(GURL(redirect_url))); EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"Title Of Awesomeness", tab_title); } TEST_F(ResourceDispatcherTest, CrossOriginRedirectBlocked) { // We expect the following URL requests from this test: // 1- http://mock.http/cross-origin-redirect-blocked.html // 2- http://mock.http/redirect-to-title2.html // 3- http://mock.http/title2.html // // If the redirect in #2 were not blocked, we'd also see a request // for http://mock.http:4000/title2.html, and the title would be different. CheckTitleTest("cross-origin-redirect-blocked.html", "Title Of More Awesomeness", 2); } // Tests that ResourceDispatcherHostRequestInfo is updated correctly on failed // requests, to prevent calling Read on a request that has already failed. // See bug 40250. TEST_F(ResourceDispatcherTest, CrossSiteFailedRequest) { scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); // Visit another URL first to trigger a cross-site navigation. GURL url(chrome::kChromeUINewTabURL); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url)); // Visit a URL that fails without calling ResourceDispatcherHost::Read. GURL broken_url("chrome://theme"); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(broken_url)); // Make sure the navigation finishes. std::wstring tab_title; EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"chrome://theme/ is not available", tab_title); } } // namespace
// Copyright (c) 2011 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 <sstream> #include <string> #include "base/command_line.h" #include "base/file_path.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/test/test_timeouts.h" #include "chrome/browser/net/url_request_failed_dns_job.h" #include "chrome/browser/net/url_request_mock_http_job.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" namespace { class ResourceDispatcherTest : public UITest { public: void CheckTitleTest(const std::string& file, const std::string& expected_title, int expected_navigations) { NavigateToURLBlockUntilNavigationsComplete( URLRequestMockHTTPJob::GetMockUrl(FilePath().AppendASCII(file)), expected_navigations); EXPECT_EQ(expected_title, WideToASCII(GetActiveTabTitle())); } protected: ResourceDispatcherTest() : UITest() { dom_automation_enabled_ = true; } }; TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) { CheckTitleTest("content-sniffer-test0.html", "Content Sniffer Test 0", 1); } TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) { CheckTitleTest("nosniff-test.html", "mock.http/nosniff-test.html", 1); } TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) { CheckTitleTest("content-sniffer-test1.html", "mock.http/content-sniffer-test1.html", 1); } TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) { CheckTitleTest("content-sniffer-test2.html", "mock.http/content-sniffer-test2.html", 1); } TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) { CheckTitleTest("content-sniffer-test3.html", "Content Sniffer Test 3", 1); EXPECT_EQ(1, GetTabCount()); // Make sure the download shelf is not showing. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); bool visible = false; ASSERT_TRUE(browser->IsShelfVisible(&visible)); EXPECT_FALSE(visible); } TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) { CheckTitleTest("content-disposition-empty.html", "success", 1); } TEST_F(ResourceDispatcherTest, ContentDispositionInline) { CheckTitleTest("content-disposition-inline.html", "success", 1); } // Test for bug #1091358. // Flaky: http://crbug.com/62595 TEST_F(ResourceDispatcherTest, FLAKY_SyncXMLHttpRequest) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(test_server.Start()); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_server.GetURL( "files/sync_xmlhttprequest.html"))); // Let's check the XMLHttpRequest ran successfully. bool success = false; EXPECT_TRUE(tab->ExecuteAndExtractBool(L"", L"window.domAutomationController.send(DidSyncRequestSucceed());", &success)); EXPECT_TRUE(success); } // http://code.google.com/p/chromium/issues/detail?id=62776 TEST_F(ResourceDispatcherTest, FLAKY_SyncXMLHttpRequest_Disallowed) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(test_server.Start()); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_server.GetURL( "files/sync_xmlhttprequest_disallowed.html"))); // Let's check the XMLHttpRequest ran successfully. bool success = false; EXPECT_TRUE(tab->ExecuteAndExtractBool(L"", L"window.domAutomationController.send(DidSucceed());", &success)); EXPECT_TRUE(success); } // Test for bug #1159553 -- A synchronous xhr (whose content-type is // downloadable) would trigger download and hang the renderer process, // if executed while navigating to a new page. // Disabled -- http://code.google.com/p/chromium/issues/detail?id=56264 TEST_F(ResourceDispatcherTest, DISABLED_SyncXMLHttpRequest_DuringUnload) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(test_server.Start()); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_server.GetURL( "files/sync_xmlhttprequest_during_unload.html"))); // Confirm that the page has loaded (since it changes its title during load). std::wstring tab_title; EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"sync xhr on unload", tab_title); // Navigate to a new page, to dispatch unload event and trigger xhr. // (the bug would make this step hang the renderer). ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_server.GetURL("files/title2.html"))); // Check that the new page got loaded, and that no download was triggered. EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"Title Of Awesomeness", tab_title); bool shelf_is_visible = false; scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible)); EXPECT_FALSE(shelf_is_visible); } // Tests that onunload is run for cross-site requests. (Bug 1114994) TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(test_server.Start()); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); GURL url(test_server.GetURL("files/onunload_cookie.html")); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url)); // Confirm that the page has loaded (since it changes its title during load). std::wstring tab_title; EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"set cookie on unload", tab_title); // Navigate to a new cross-site page, to dispatch unload event and set theq // cookie. CheckTitleTest("content-sniffer-test0.html", "Content Sniffer Test 0", 1); // Check that the cookie was set. std::string value_result; ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result)); ASSERT_FALSE(value_result.empty()); ASSERT_STREQ("foo", value_result.c_str()); } #if !defined(OS_MACOSX) // Tests that the onbeforeunload and onunload logic is shortcutted if the old // renderer is gone. In that case, we don't want to wait for the old renderer // to run the handlers. // We need to disable this on Mac because the crash causes the OS CrashReporter // process to kick in to analyze the poor dead renderer. Unfortunately, if the // app isn't stripped of debug symbols, this takes about five minutes to // complete and isn't conducive to quick turnarounds. As we don't currently // strip the app on the build bots, this is bad times. TEST_F(ResourceDispatcherTest, FAILS_CrossSiteAfterCrash) { // This test only works in multi-process mode if (ProxyLauncher::in_process_renderer()) return; scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); // Cause the renderer to crash. #if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD) expected_crashes_ = 1; #endif ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL))); // Wait for browser to notice the renderer crash. base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms()); // Navigate to a new cross-site page. The browser should not wait around for // the old renderer's on{before}unload handlers to run. CheckTitleTest("content-sniffer-test0.html", "Content Sniffer Test 0", 1); } #endif // !defined(OS_MACOSX) // Tests that cross-site navigations work when the new page does not go through // the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872) TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) { scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); // Start with an HTTP page. CheckTitleTest("content-sniffer-test0.html", "Content Sniffer Test 0", 1); // Now load a file:// page, which does not use the BufferedEventHandler. // Make sure that the page loads and displays a title, and doesn't get stuck. FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("title2.html"); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(net::FilePathToFileURL(test_file))); EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle()); } // Tests that a cross-site navigation to an error page (resulting in the link // doctor page) still runs the onunload handler and can support navigations // away from the link doctor page. (Bug 1235537) TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(test_server.Start()); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); GURL url(test_server.GetURL("files/onunload_cookie.html")); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url)); // Confirm that the page has loaded (since it changes its title during load). std::wstring tab_title; EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"set cookie on unload", tab_title); // Navigate to a new cross-site URL that results in an error page. // TODO(creis): If this causes crashes or hangs, it might be for the same // reason as ErrorPageTest::DNSError. See bug 1199491 and // http://crbug.com/22877. ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURLBlockUntilNavigationsComplete( GURL(URLRequestFailedDnsJob::kTestUrl), 2)); EXPECT_NE(L"set cookie on unload", GetActiveTabTitle()); // Check that the cookie was set, meaning that the onunload handler ran. std::string value_result; EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result)); EXPECT_FALSE(value_result.empty()); EXPECT_STREQ("foo", value_result.c_str()); // Check that renderer-initiated navigations still work. In a previous bug, // the ResourceDispatcherHost would think that such navigations were // cross-site, because we didn't clean up from the previous request. Since // TabContents was in the NORMAL state, it would ignore the attempt to run // the onunload handler, and the navigation would fail. // (Test by redirecting to javascript:window.location='someURL'.) GURL test_url(test_server.GetURL("files/title2.html")); std::string redirect_url = "javascript:window.location='" + test_url.possibly_invalid_spec() + "'"; ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(GURL(redirect_url))); EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"Title Of Awesomeness", tab_title); } TEST_F(ResourceDispatcherTest, CrossOriginRedirectBlocked) { // We expect the following URL requests from this test: // 1- http://mock.http/cross-origin-redirect-blocked.html // 2- http://mock.http/redirect-to-title2.html // 3- http://mock.http/title2.html // // If the redirect in #2 were not blocked, we'd also see a request // for http://mock.http:4000/title2.html, and the title would be different. CheckTitleTest("cross-origin-redirect-blocked.html", "Title Of More Awesomeness", 2); } // Tests that ResourceDispatcherHostRequestInfo is updated correctly on failed // requests, to prevent calling Read on a request that has already failed. // See bug 40250. TEST_F(ResourceDispatcherTest, CrossSiteFailedRequest) { scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab()); ASSERT_TRUE(tab.get()); // Visit another URL first to trigger a cross-site navigation. GURL url(chrome::kChromeUINewTabURL); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url)); // Visit a URL that fails without calling ResourceDispatcherHost::Read. GURL broken_url("chrome://theme"); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(broken_url)); // Make sure the navigation finishes. std::wstring tab_title; EXPECT_TRUE(tab->GetTabTitle(&tab_title)); EXPECT_EQ(L"chrome://theme/ is not available", tab_title); } } // namespace
Disable ResourceDispatcherTest.CrossSiteAfterCrash test
Disable ResourceDispatcherTest.CrossSiteAfterCrash test BUG=76399 TEST=none TBR=ericu Review URL: http://codereview.chromium.org/6665037 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@78388 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
e56d4b92cd1a701bbff74b7241eb0e838bbddbb9
src/compiler/change-lowering.cc
src/compiler/change-lowering.cc
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/change-lowering.h" #include "src/compiler/js-graph.h" #include "src/compiler/linkage.h" #include "src/compiler/machine-operator.h" namespace v8 { namespace internal { namespace compiler { ChangeLowering::~ChangeLowering() {} Reduction ChangeLowering::Reduce(Node* node) { Node* control = graph()->start(); switch (node->opcode()) { case IrOpcode::kChangeBitToBool: return ChangeBitToBool(node->InputAt(0), control); case IrOpcode::kChangeBoolToBit: return ChangeBoolToBit(node->InputAt(0)); case IrOpcode::kChangeFloat64ToTagged: return ChangeFloat64ToTagged(node->InputAt(0), control); case IrOpcode::kChangeInt32ToTagged: return ChangeInt32ToTagged(node->InputAt(0), control); case IrOpcode::kChangeTaggedToFloat64: return ChangeTaggedToFloat64(node->InputAt(0), control); case IrOpcode::kChangeTaggedToInt32: return ChangeTaggedToUI32(node->InputAt(0), control, kSigned); case IrOpcode::kChangeTaggedToUint32: return ChangeTaggedToUI32(node->InputAt(0), control, kUnsigned); case IrOpcode::kChangeUint32ToTagged: return ChangeUint32ToTagged(node->InputAt(0), control); default: return NoChange(); } UNREACHABLE(); return NoChange(); } Node* ChangeLowering::HeapNumberValueIndexConstant() { STATIC_ASSERT(HeapNumber::kValueOffset % kPointerSize == 0); const int heap_number_value_offset = ((HeapNumber::kValueOffset / kPointerSize) * (machine()->Is64() ? 8 : 4)); return jsgraph()->IntPtrConstant(heap_number_value_offset - kHeapObjectTag); } Node* ChangeLowering::SmiMaxValueConstant() { const int smi_value_size = machine()->Is32() ? SmiTagging<4>::SmiValueSize() : SmiTagging<8>::SmiValueSize(); return jsgraph()->Int32Constant( -(static_cast<int>(0xffffffffu << (smi_value_size - 1)) + 1)); } Node* ChangeLowering::SmiShiftBitsConstant() { const int smi_shift_size = machine()->Is32() ? SmiTagging<4>::SmiShiftSize() : SmiTagging<8>::SmiShiftSize(); return jsgraph()->IntPtrConstant(smi_shift_size + kSmiTagSize); } Node* ChangeLowering::AllocateHeapNumberWithValue(Node* value, Node* control) { // The AllocateHeapNumber() runtime function does not use the context, so we // can safely pass in Smi zero here. Node* context = jsgraph()->ZeroConstant(); Node* effect = graph()->NewNode(common()->ValueEffect(1), value); const Runtime::Function* function = Runtime::FunctionForId(Runtime::kAllocateHeapNumber); DCHECK_EQ(0, function->nargs); CallDescriptor* desc = linkage()->GetRuntimeCallDescriptor( function->function_id, 0, Operator::kNoProperties); Node* heap_number = graph()->NewNode( common()->Call(desc), jsgraph()->CEntryStubConstant(), jsgraph()->ExternalConstant(ExternalReference(function, isolate())), jsgraph()->Int32Constant(function->nargs), context, effect, control); Node* store = graph()->NewNode( machine()->Store(StoreRepresentation(kMachFloat64, kNoWriteBarrier)), heap_number, HeapNumberValueIndexConstant(), value, heap_number, control); return graph()->NewNode(common()->Finish(1), heap_number, store); } Node* ChangeLowering::ChangeSmiToInt32(Node* value) { value = graph()->NewNode(machine()->WordSar(), value, SmiShiftBitsConstant()); if (machine()->Is64()) { value = graph()->NewNode(machine()->TruncateInt64ToInt32(), value); } return value; } Node* ChangeLowering::LoadHeapNumberValue(Node* value, Node* control) { return graph()->NewNode(machine()->Load(kMachFloat64), value, HeapNumberValueIndexConstant(), graph()->start(), control); } Reduction ChangeLowering::ChangeBitToBool(Node* val, Node* control) { Node* branch = graph()->NewNode(common()->Branch(), val, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* true_value = jsgraph()->TrueConstant(); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* false_value = jsgraph()->FalseConstant(); Node* merge = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* phi = graph()->NewNode( common()->Phi(static_cast<MachineType>(kTypeBool | kRepTagged), 2), true_value, false_value, merge); return Replace(phi); } Reduction ChangeLowering::ChangeBoolToBit(Node* val) { return Replace( graph()->NewNode(machine()->WordEqual(), val, jsgraph()->TrueConstant())); } Reduction ChangeLowering::ChangeFloat64ToTagged(Node* val, Node* control) { return Replace(AllocateHeapNumberWithValue(val, control)); } Reduction ChangeLowering::ChangeInt32ToTagged(Node* val, Node* control) { if (machine()->Is64()) { return Replace( graph()->NewNode(machine()->Word64Shl(), graph()->NewNode(machine()->ChangeInt32ToInt64(), val), SmiShiftBitsConstant())); } Node* add = graph()->NewNode(machine()->Int32AddWithOverflow(), val, val); Node* ovf = graph()->NewNode(common()->Projection(1), add); Node* branch = graph()->NewNode(common()->Branch(BranchHint::kTrue), ovf, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* heap_number = AllocateHeapNumberWithValue( graph()->NewNode(machine()->ChangeInt32ToFloat64(), val), if_true); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* smi = graph()->NewNode(common()->Projection(0), add); Node* merge = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* phi = graph()->NewNode(common()->Phi(kMachAnyTagged, 2), heap_number, smi, merge); return Replace(phi); } Reduction ChangeLowering::ChangeTaggedToUI32(Node* val, Node* control, Signedness signedness) { STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagMask == 1); Node* tag = graph()->NewNode(machine()->WordAnd(), val, jsgraph()->IntPtrConstant(kSmiTagMask)); Node* branch = graph()->NewNode(common()->Branch(), tag, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); const Operator* op = (signedness == kSigned) ? machine()->ChangeFloat64ToInt32() : machine()->ChangeFloat64ToUint32(); Node* change = graph()->NewNode(op, LoadHeapNumberValue(val, if_true)); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* number = ChangeSmiToInt32(val); Node* merge = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* phi = graph()->NewNode( common()->Phi((signedness == kSigned) ? kMachInt32 : kMachUint32, 2), change, number, merge); return Replace(phi); } Reduction ChangeLowering::ChangeTaggedToFloat64(Node* val, Node* control) { STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagMask == 1); Node* tag = graph()->NewNode(machine()->WordAnd(), val, jsgraph()->IntPtrConstant(kSmiTagMask)); Node* branch = graph()->NewNode(common()->Branch(), tag, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* load = LoadHeapNumberValue(val, if_true); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* number = graph()->NewNode(machine()->ChangeInt32ToFloat64(), ChangeSmiToInt32(val)); Node* merge = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* phi = graph()->NewNode(common()->Phi(kMachFloat64, 2), load, number, merge); return Replace(phi); } Reduction ChangeLowering::ChangeUint32ToTagged(Node* val, Node* control) { STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagMask == 1); Node* cmp = graph()->NewNode(machine()->Uint32LessThanOrEqual(), val, SmiMaxValueConstant()); Node* branch = graph()->NewNode(common()->Branch(BranchHint::kTrue), cmp, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* smi = graph()->NewNode( machine()->WordShl(), machine()->Is64() ? graph()->NewNode(machine()->ChangeUint32ToUint64(), val) : val, SmiShiftBitsConstant()); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* heap_number = AllocateHeapNumberWithValue( graph()->NewNode(machine()->ChangeUint32ToFloat64(), val), if_false); Node* merge = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* phi = graph()->NewNode(common()->Phi(kMachAnyTagged, 2), smi, heap_number, merge); return Replace(phi); } Isolate* ChangeLowering::isolate() const { return jsgraph()->isolate(); } Graph* ChangeLowering::graph() const { return jsgraph()->graph(); } CommonOperatorBuilder* ChangeLowering::common() const { return jsgraph()->common(); } MachineOperatorBuilder* ChangeLowering::machine() const { return jsgraph()->machine(); } } // namespace compiler } // namespace internal } // namespace v8
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/change-lowering.h" #include "src/compiler/js-graph.h" #include "src/compiler/linkage.h" #include "src/compiler/machine-operator.h" namespace v8 { namespace internal { namespace compiler { ChangeLowering::~ChangeLowering() {} Reduction ChangeLowering::Reduce(Node* node) { Node* control = graph()->start(); switch (node->opcode()) { case IrOpcode::kChangeBitToBool: return ChangeBitToBool(node->InputAt(0), control); case IrOpcode::kChangeBoolToBit: return ChangeBoolToBit(node->InputAt(0)); case IrOpcode::kChangeFloat64ToTagged: return ChangeFloat64ToTagged(node->InputAt(0), control); case IrOpcode::kChangeInt32ToTagged: return ChangeInt32ToTagged(node->InputAt(0), control); case IrOpcode::kChangeTaggedToFloat64: return ChangeTaggedToFloat64(node->InputAt(0), control); case IrOpcode::kChangeTaggedToInt32: return ChangeTaggedToUI32(node->InputAt(0), control, kSigned); case IrOpcode::kChangeTaggedToUint32: return ChangeTaggedToUI32(node->InputAt(0), control, kUnsigned); case IrOpcode::kChangeUint32ToTagged: return ChangeUint32ToTagged(node->InputAt(0), control); default: return NoChange(); } UNREACHABLE(); return NoChange(); } Node* ChangeLowering::HeapNumberValueIndexConstant() { STATIC_ASSERT(HeapNumber::kValueOffset % kPointerSize == 0); const int heap_number_value_offset = ((HeapNumber::kValueOffset / kPointerSize) * (machine()->Is64() ? 8 : 4)); return jsgraph()->IntPtrConstant(heap_number_value_offset - kHeapObjectTag); } Node* ChangeLowering::SmiMaxValueConstant() { const int smi_value_size = machine()->Is32() ? SmiTagging<4>::SmiValueSize() : SmiTagging<8>::SmiValueSize(); return jsgraph()->Int32Constant( -(static_cast<int>(0xffffffffu << (smi_value_size - 1)) + 1)); } Node* ChangeLowering::SmiShiftBitsConstant() { const int smi_shift_size = machine()->Is32() ? SmiTagging<4>::SmiShiftSize() : SmiTagging<8>::SmiShiftSize(); return jsgraph()->IntPtrConstant(smi_shift_size + kSmiTagSize); } Node* ChangeLowering::AllocateHeapNumberWithValue(Node* value, Node* control) { // The AllocateHeapNumber() runtime function does not use the context, so we // can safely pass in Smi zero here. Node* context = jsgraph()->ZeroConstant(); Node* effect = graph()->NewNode(common()->ValueEffect(1), value); const Runtime::Function* function = Runtime::FunctionForId(Runtime::kAllocateHeapNumber); DCHECK_EQ(0, function->nargs); CallDescriptor* desc = linkage()->GetRuntimeCallDescriptor( function->function_id, 0, Operator::kNoProperties); Node* heap_number = graph()->NewNode( common()->Call(desc), jsgraph()->CEntryStubConstant(), jsgraph()->ExternalConstant(ExternalReference(function, isolate())), jsgraph()->Int32Constant(function->nargs), context, effect, control); Node* store = graph()->NewNode( machine()->Store(StoreRepresentation(kMachFloat64, kNoWriteBarrier)), heap_number, HeapNumberValueIndexConstant(), value, heap_number, control); return graph()->NewNode(common()->Finish(1), heap_number, store); } Node* ChangeLowering::ChangeSmiToInt32(Node* value) { value = graph()->NewNode(machine()->WordSar(), value, SmiShiftBitsConstant()); if (machine()->Is64()) { value = graph()->NewNode(machine()->TruncateInt64ToInt32(), value); } return value; } Node* ChangeLowering::LoadHeapNumberValue(Node* value, Node* control) { return graph()->NewNode(machine()->Load(kMachFloat64), value, HeapNumberValueIndexConstant(), graph()->start(), control); } Reduction ChangeLowering::ChangeBitToBool(Node* val, Node* control) { Node* branch = graph()->NewNode(common()->Branch(), val, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* true_value = jsgraph()->TrueConstant(); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* false_value = jsgraph()->FalseConstant(); Node* merge = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* phi = graph()->NewNode( common()->Phi(static_cast<MachineType>(kTypeBool | kRepTagged), 2), true_value, false_value, merge); return Replace(phi); } Reduction ChangeLowering::ChangeBoolToBit(Node* val) { return Replace( graph()->NewNode(machine()->WordEqual(), val, jsgraph()->TrueConstant())); } Reduction ChangeLowering::ChangeFloat64ToTagged(Node* val, Node* control) { return Replace(AllocateHeapNumberWithValue(val, control)); } Reduction ChangeLowering::ChangeInt32ToTagged(Node* val, Node* control) { if (machine()->Is64()) { return Replace( graph()->NewNode(machine()->Word64Shl(), graph()->NewNode(machine()->ChangeInt32ToInt64(), val), SmiShiftBitsConstant())); } Node* add = graph()->NewNode(machine()->Int32AddWithOverflow(), val, val); Node* ovf = graph()->NewNode(common()->Projection(1), add); Node* branch = graph()->NewNode(common()->Branch(BranchHint::kFalse), ovf, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* heap_number = AllocateHeapNumberWithValue( graph()->NewNode(machine()->ChangeInt32ToFloat64(), val), if_true); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* smi = graph()->NewNode(common()->Projection(0), add); Node* merge = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* phi = graph()->NewNode(common()->Phi(kMachAnyTagged, 2), heap_number, smi, merge); return Replace(phi); } Reduction ChangeLowering::ChangeTaggedToUI32(Node* val, Node* control, Signedness signedness) { STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagMask == 1); Node* tag = graph()->NewNode(machine()->WordAnd(), val, jsgraph()->IntPtrConstant(kSmiTagMask)); Node* branch = graph()->NewNode(common()->Branch(BranchHint::kFalse), tag, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); const Operator* op = (signedness == kSigned) ? machine()->ChangeFloat64ToInt32() : machine()->ChangeFloat64ToUint32(); Node* change = graph()->NewNode(op, LoadHeapNumberValue(val, if_true)); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* number = ChangeSmiToInt32(val); Node* merge = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* phi = graph()->NewNode( common()->Phi((signedness == kSigned) ? kMachInt32 : kMachUint32, 2), change, number, merge); return Replace(phi); } Reduction ChangeLowering::ChangeTaggedToFloat64(Node* val, Node* control) { STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagMask == 1); Node* tag = graph()->NewNode(machine()->WordAnd(), val, jsgraph()->IntPtrConstant(kSmiTagMask)); Node* branch = graph()->NewNode(common()->Branch(), tag, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* load = LoadHeapNumberValue(val, if_true); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* number = graph()->NewNode(machine()->ChangeInt32ToFloat64(), ChangeSmiToInt32(val)); Node* merge = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* phi = graph()->NewNode(common()->Phi(kMachFloat64, 2), load, number, merge); return Replace(phi); } Reduction ChangeLowering::ChangeUint32ToTagged(Node* val, Node* control) { STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagMask == 1); Node* cmp = graph()->NewNode(machine()->Uint32LessThanOrEqual(), val, SmiMaxValueConstant()); Node* branch = graph()->NewNode(common()->Branch(BranchHint::kTrue), cmp, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* smi = graph()->NewNode( machine()->WordShl(), machine()->Is64() ? graph()->NewNode(machine()->ChangeUint32ToUint64(), val) : val, SmiShiftBitsConstant()); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* heap_number = AllocateHeapNumberWithValue( graph()->NewNode(machine()->ChangeUint32ToFloat64(), val), if_false); Node* merge = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* phi = graph()->NewNode(common()->Phi(kMachAnyTagged, 2), smi, heap_number, merge); return Replace(phi); } Isolate* ChangeLowering::isolate() const { return jsgraph()->isolate(); } Graph* ChangeLowering::graph() const { return jsgraph()->graph(); } CommonOperatorBuilder* ChangeLowering::common() const { return jsgraph()->common(); } MachineOperatorBuilder* ChangeLowering::machine() const { return jsgraph()->machine(); } } // namespace compiler } // namespace internal } // namespace v8
Fix branch hints for ChangeInt32ToTagged and ChangeTaggedToUI32.
[turbofan] Fix branch hints for ChangeInt32ToTagged and ChangeTaggedToUI32. [email protected] Review URL: https://codereview.chromium.org/694353006 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#25106} git-svn-id: f98b9d40cb02301bc76fa9e1b46ee668158567fd@25106 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
C++
mit
UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh
3e630ff673034c30a0cdd63b690dcc601fdcd7c7
src/core/seqcombinator.hpp
src/core/seqcombinator.hpp
#ifndef SEQCOMBINATOR_HPP_ #define SEQCOMBINATOR_HPP_ #include <vector> #include <initializer_list> #include <core/animation.hpp> template <typename State> class SeqCombinator: public Animation<State> { public: // TODO(#86): check if there are no animations SeqCombinator(std::vector<AnimationPtr<State>> &&animations): m_animations(std::move(animations)), m_currentAnimation(0) {} virtual State nextState(const int32_t deltaTime) override { if (!isFinished()) { if (!m_animations[m_currentAnimation]->isFinished()) { return m_animations[m_currentAnimation]->nextState(deltaTime); } else { const State previousState = m_animations[m_currentAnimation]->getCurrentState(); m_currentAnimation++; if (!isFinished()) { m_animations[m_currentAnimation]->reset(previousState); return m_animations[m_currentAnimation]->getCurrentState(); } } } return m_animations.back()->getCurrentState(); } virtual State getCurrentState() const override { if (isFinished()) { return m_animations.back()->getCurrentState(); } else { return m_animations[m_currentAnimation]->getCurrentState(); } } virtual bool isFinished() const override { return m_currentAnimation >= m_animations.size(); } virtual void reset(const State &state) override { m_currentAnimation = 0; m_animations[m_currentAnimation]->reset(state); } private: std::vector<AnimationPtr<State>> m_animations; size_t m_currentAnimation; }; #endif // SEQCOMBINATOR_HPP_
#ifndef SEQCOMBINATOR_HPP_ #define SEQCOMBINATOR_HPP_ #include <vector> #include <initializer_list> #include <core/animation.hpp> template <typename State> class SeqCombinator: public Animation<State> { public: // TODO: check for nullptr animations in the sequence SeqCombinator(std::vector<AnimationPtr<State>> &&animations): m_animations(std::move(animations)), m_currentAnimation(0) {} virtual State nextState(const int32_t deltaTime) override { if (m_animations.empty()) { return m_emptyPlaceholder; } if (!isFinished()) { if (!m_animations[m_currentAnimation]->isFinished()) { return m_animations[m_currentAnimation]->nextState(deltaTime); } else { const State previousState = m_animations[m_currentAnimation]->getCurrentState(); m_currentAnimation++; if (!isFinished()) { m_animations[m_currentAnimation]->reset(previousState); return m_animations[m_currentAnimation]->getCurrentState(); } } } return m_animations.back()->getCurrentState(); } virtual State getCurrentState() const override { if (m_animations.empty()) { return m_emptyPlaceholder; } else if (isFinished()) { return m_animations.back()->getCurrentState(); } else { return m_animations[m_currentAnimation]->getCurrentState(); } } virtual bool isFinished() const override { return m_currentAnimation >= m_animations.size(); } virtual void reset(const State &state) override { if (m_animations.empty()) { m_emptyPlaceholder = state; } else { m_currentAnimation = 0; m_animations[m_currentAnimation]->reset(state); } } private: std::vector<AnimationPtr<State>> m_animations; size_t m_currentAnimation; State m_emptyPlaceholder; }; #endif // SEQCOMBINATOR_HPP_
Introduce empty placeholder for SeqCombinator
Introduce empty placeholder for SeqCombinator (#86)
C++
mit
rexim/beatwave
67b40e3b92a8475c6e73f58aa980ba1ad05626b6
server/ServerMethods.cpp
server/ServerMethods.cpp
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include <gst/gst.h> #include <ServerMethods.hpp> #include <types/MediaPipelineImpl.hpp> #include <common/MediaSet.hpp> #include <string> #include <EventHandler.hpp> #include <KurentoException.hpp> #include "utils/utils.hpp" #include <JsonRpcUtils.hpp> #define GST_CAT_DEFAULT kurento_server_methods GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoServerMethods" #define SESSION_ID "SessionId" #define OBJECT "object" #define SUBSCRIPTION "subscription" namespace kurento { ServerMethods::ServerMethods() { handler.addMethod ("create", std::bind (&ServerMethods::create, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("invoke", std::bind (&ServerMethods::invoke, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("subscribe", std::bind (&ServerMethods::subscribe, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("unsubscribe", std::bind (&ServerMethods::unsubscribe, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("release", std::bind (&ServerMethods::release, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("unref", std::bind (&ServerMethods::unref, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("keepAlive", std::bind (&ServerMethods::keepAlive, this, std::placeholders::_1, std::placeholders::_2) ); } static void requireParams (const Json::Value &params) { if (params == Json::Value::null) { throw JsonRpc::CallException (JsonRpc::ErrorCode::SERVER_ERROR_INIT, "'params' is requiered"); } } void ServerMethods::process (const std::string &request, std::string &response) { handler.process (request, response); } void ServerMethods::keepAlive (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string sessionId; requireParams (params); JsonRpc::getValue (params, SESSION_ID, sessionId); try { MediaSet::getMediaSet().keepAliveSession (sessionId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::release (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string objectId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); try { MediaSet::getMediaSet().release (objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::unref (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string objectId; std::string sessionId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); JsonRpc::getValue (params, OBJECT, sessionId); try { MediaSet::getMediaSet().unref (sessionId, objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::unsubscribe (const Json::Value &params, Json::Value &response) { std::string subscription; requireParams (params); JsonRpc::getValue (params, SUBSCRIPTION, subscription); eventHandlers.erase (subscription); } void ServerMethods::subscribe (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string eventType; std::string ip; int port; std::string handlerId; std::string sessionId; std::string objectId; requireParams (params); JsonRpc::getValue (params, "type", eventType); JsonRpc::getValue (params, "ip", ip); JsonRpc::getValue (params, "port", port); JsonRpc::getValue (params, OBJECT, objectId); try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { generateUUID (sessionId); } try { std::shared_ptr<EventHandler> handler (new EventHandler (ip, port) ); obj = MediaSet::getMediaSet().getMediaObject (sessionId, objectId); handlerId = obj->connect (eventType, handler); if (handlerId == "") { KurentoException e ("event not found"); throw e; } eventHandlers[handlerId] = handler; } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } response["sessionId"] = sessionId; response["value"] = handlerId; } void ServerMethods::invoke (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string sessionId; std::string operation; Json::Value operationParams; std::string objectId; requireParams (params); JsonRpc::getValue (params, "operation", operation); JsonRpc::getValue (params, OBJECT, objectId); try { JsonRpc::getValue (params, "operationParams", operationParams); } catch (JsonRpc::CallException e) { /* operationParams is optional at this point */ } try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { generateUUID (sessionId); } try { Json::Value value; obj = MediaSet::getMediaSet().getMediaObject (sessionId, objectId); if (!obj) { throw KurentoException ("Object not found"); } obj->getInvoker().invoke (obj, operation, operationParams, value); response["value"] = value; response["sessionId"] = sessionId; } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::create (const Json::Value &params, Json::Value &response) { std::string type; std::shared_ptr<Factory> factory; std::string sessionId; requireParams (params); JsonRpc::getValue (params, "type", type); try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { generateUUID (sessionId); } if (!objectRegistrar) { KurentoException e ("Class '" + type + "' does not exist"); throw e; } factory = objectRegistrar->getFactory (type); if (factory) { try { std::shared_ptr <MediaObjectImpl> object; object = std::dynamic_pointer_cast<MediaObjectImpl> ( factory->createObject (params["constructorParams"]) ); MediaSet::getMediaSet().ref (sessionId, object); try { object->getMediaPipeline(); } catch (...) { GST_ERROR ("Error getting pipeline"); } MediaSet::getMediaSet().ref (sessionId, object); response["value"] = object->getIdStr(); response["sessionId"] = sessionId; } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } else { JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, "Class '" + type + "' does not exist"); // TODO: Define error data and code throw e; } } ServerMethods::StaticConstructor ServerMethods::staticConstructor; ServerMethods::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include <gst/gst.h> #include <ServerMethods.hpp> #include <types/MediaPipelineImpl.hpp> #include <common/MediaSet.hpp> #include <string> #include <EventHandler.hpp> #include <KurentoException.hpp> #include "utils/utils.hpp" #include <JsonRpcUtils.hpp> #define GST_CAT_DEFAULT kurento_server_methods GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoServerMethods" #define SESSION_ID "sessionId" #define OBJECT "object" #define SUBSCRIPTION "subscription" namespace kurento { ServerMethods::ServerMethods() { handler.addMethod ("create", std::bind (&ServerMethods::create, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("invoke", std::bind (&ServerMethods::invoke, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("subscribe", std::bind (&ServerMethods::subscribe, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("unsubscribe", std::bind (&ServerMethods::unsubscribe, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("release", std::bind (&ServerMethods::release, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("unref", std::bind (&ServerMethods::unref, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("keepAlive", std::bind (&ServerMethods::keepAlive, this, std::placeholders::_1, std::placeholders::_2) ); } static void requireParams (const Json::Value &params) { if (params == Json::Value::null) { throw JsonRpc::CallException (JsonRpc::ErrorCode::SERVER_ERROR_INIT, "'params' is requiered"); } } void ServerMethods::process (const std::string &request, std::string &response) { handler.process (request, response); } void ServerMethods::keepAlive (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string sessionId; requireParams (params); JsonRpc::getValue (params, SESSION_ID, sessionId); try { MediaSet::getMediaSet().keepAliveSession (sessionId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::release (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string objectId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); try { MediaSet::getMediaSet().release (objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::unref (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string objectId; std::string sessionId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); JsonRpc::getValue (params, OBJECT, sessionId); try { MediaSet::getMediaSet().unref (sessionId, objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::unsubscribe (const Json::Value &params, Json::Value &response) { std::string subscription; requireParams (params); JsonRpc::getValue (params, SUBSCRIPTION, subscription); eventHandlers.erase (subscription); } void ServerMethods::subscribe (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string eventType; std::string ip; int port; std::string handlerId; std::string sessionId; std::string objectId; requireParams (params); JsonRpc::getValue (params, "type", eventType); JsonRpc::getValue (params, "ip", ip); JsonRpc::getValue (params, "port", port); JsonRpc::getValue (params, OBJECT, objectId); try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { generateUUID (sessionId); } try { std::shared_ptr<EventHandler> handler (new EventHandler (ip, port) ); obj = MediaSet::getMediaSet().getMediaObject (sessionId, objectId); handlerId = obj->connect (eventType, handler); if (handlerId == "") { KurentoException e ("event not found"); throw e; } eventHandlers[handlerId] = handler; } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } response["sessionId"] = sessionId; response["value"] = handlerId; } void ServerMethods::invoke (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string sessionId; std::string operation; Json::Value operationParams; std::string objectId; requireParams (params); JsonRpc::getValue (params, "operation", operation); JsonRpc::getValue (params, OBJECT, objectId); try { JsonRpc::getValue (params, "operationParams", operationParams); } catch (JsonRpc::CallException e) { /* operationParams is optional at this point */ } try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { generateUUID (sessionId); } try { Json::Value value; obj = MediaSet::getMediaSet().getMediaObject (sessionId, objectId); if (!obj) { throw KurentoException ("Object not found"); } obj->getInvoker().invoke (obj, operation, operationParams, value); response["value"] = value; response["sessionId"] = sessionId; } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::create (const Json::Value &params, Json::Value &response) { std::string type; std::shared_ptr<Factory> factory; std::string sessionId; requireParams (params); JsonRpc::getValue (params, "type", type); try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { generateUUID (sessionId); } if (!objectRegistrar) { KurentoException e ("Class '" + type + "' does not exist"); throw e; } factory = objectRegistrar->getFactory (type); if (factory) { try { std::shared_ptr <MediaObjectImpl> object; object = std::dynamic_pointer_cast<MediaObjectImpl> ( factory->createObject (params["constructorParams"]) ); MediaSet::getMediaSet().ref (sessionId, object); try { object->getMediaPipeline(); } catch (...) { GST_ERROR ("Error getting pipeline"); } MediaSet::getMediaSet().ref (sessionId, object); response["value"] = object->getIdStr(); response["sessionId"] = sessionId; } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } else { JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, "Class '" + type + "' does not exist"); // TODO: Define error data and code throw e; } } ServerMethods::StaticConstructor ServerMethods::staticConstructor; ServerMethods::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */
Fix sessionId parameter name
ServerMethods: Fix sessionId parameter name Change-Id: I1434a4f27c768b9e24642d8d35e5d41560ba8861
C++
lgpl-2.1
lulufei/kurento-media-server,mparis/kurento-media-server,Kurento/kurento-media-server,TribeMedia/kurento-media-server,TribeMedia/kurento-media-server,todotobe1/kurento-media-server,mparis/kurento-media-server,shelsonjava/kurento-media-server,todotobe1/kurento-media-server,lulufei/kurento-media-server,shelsonjava/kurento-media-server,Kurento/kurento-media-server
2bbb7699376d60432be6253f291f11628adf43bc
libproxy/modules/config_gnome.cpp
libproxy/modules/config_gnome.cpp
/******************************************************************************* * libproxy - A library for proxy configuration * Copyright (C) 2006 Nathaniel McCallum <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ #include <cstdio> // For fileno(), fread(), pclose(), popen(), sscanf() #include <sys/select.h> // For select() #include <fcntl.h> // For fcntl() #include <errno.h> // For errno stuff #include <unistd.h> // For pipe(), close(), vfork(), dup(), execl(), _exit() #include <signal.h> // For kill() #include "../extension_config.hpp" using namespace libproxy; #define BUFFERSIZE 10240 static const char *all_keys[] = { "/system/proxy/mode", "/system/proxy/autoconfig_url", "/system/http_proxy/host", "/system/http_proxy/port", "/system/proxy/secure_host", "/system/proxy/secure_port", "/system/proxy/ftp_host", "/system/proxy/ftp_port", "/system/proxy/socks_host", "/system/proxy/socks_port", "/system/http_proxy/ignore_hosts", "/system/http_proxy/use_authentication", "/system/http_proxy/authentication_user", "/system/http_proxy/authentication_password", NULL }; static int popen2(const char *program, FILE** read, FILE** write, pid_t* pid) { if (!read || !write || !pid || !program || !*program) return EINVAL; *read = NULL; *write = NULL; *pid = 0; // Open the pipes int rpipe[2]; int wpipe[2]; if (pipe(rpipe) < 0) return errno; if (pipe(wpipe) < 0) { close(rpipe[0]); close(rpipe[1]); return errno; } switch (*pid = vfork()) { case -1: // Error close(rpipe[0]); close(rpipe[1]); close(wpipe[0]); close(wpipe[1]); return errno; case 0: // Child close(STDIN_FILENO); // Close stdin close(STDOUT_FILENO); // Close stdout // Dup the read end of the write pipe to stdin // Dup the write end of the read pipe to stdout if (dup2(wpipe[0], STDIN_FILENO) != STDIN_FILENO) _exit(1); if (dup2(rpipe[1], STDOUT_FILENO) != STDOUT_FILENO) _exit(2); // Close unneeded fds close(rpipe[0]); close(rpipe[1]); close(wpipe[0]); close(wpipe[1]); // Exec execl("/bin/sh", "sh", "-c", program, (char*) NULL); _exit(127); // Whatever we do, don't return default: // Parent close(rpipe[1]); close(wpipe[0]); *read = fdopen(rpipe[0], "r"); *write = fdopen(wpipe[1], "w"); if (*read == NULL || *write == NULL) { if (*read != NULL) fclose(*read); if (*write != NULL) fclose(*write); return errno; } return 0; } } class gnome_config_extension : public config_extension { public: gnome_config_extension() { // Build the command int count; string cmd = LIBEXECDIR "/pxgconf"; for (count=0 ; all_keys[count] ; count++) cmd += string(" ", 1) + all_keys[count]; // Get our pipes if (popen2(cmd.c_str(), &this->read, &this->write, &this->pid) != 0) throw runtime_error("Unable to open gconf helper!"); // Read in our initial data this->read_data(count); // Set the read pipe to non-blocking if (fcntl(fileno(this->read), F_SETFL, FNONBLOCK) == -1) { fclose(this->read); fclose(this->write); kill(this->pid, SIGTERM); throw runtime_error("Unable to set pipe to non-blocking!"); } } ~gnome_config_extension() { fclose(this->read); fclose(this->write); kill(this->pid, SIGTERM); } url get_config(url dest) throw (runtime_error) { // Check for changes in the config fd_set rfds; struct timeval timeout = { 0, 0 }; FD_ZERO(&rfds); FD_SET(fileno(this->read), &rfds); if (select(fileno(this->read)+1, &rfds, NULL, NULL, &timeout) > 0) this->read_data(); // Mode is wpad:// or pac+http://... if (this->data["/system/proxy/mode"] == "auto") { string pac = this->data["/system/proxy/autoconfig_url"]; return url::is_valid(pac) ? url(string("pac+") + pac) : url("wpad://"); } // Mode is http://... or socks://... else if (this->data["/system/proxy/mode"] == "manual") { string type = "http", host, port; bool auth = this->data["/system/http_proxy/use_authentication"] == "true"; string username = this->data["/system/http_proxy/authentication_user"]; string password = this->data["/system/http_proxy/authentication_password"]; uint16_t p = 0; // Get the per-scheme proxy settings if (dest.get_scheme() == "https") { host = this->data["/system/proxy/secure_host"]; port = this->data["/system/proxy/secure_port"]; if (sscanf(port.c_str(), "%hu", &p) != 1) p = 0; } else if (dest.get_scheme() == "ftp") { host = this->data["/system/proxy/ftp_host"]; port = this->data["/system/proxy/ftp_port"]; if (sscanf(port.c_str(), "%hu", &p) != 1) p = 0; } if (host == "" || p == 0) { host = this->data["/system/http_proxy/host"]; port = this->data["/system/http_proxy/port"]; if (sscanf(port.c_str(), "%hu", &p) != 1) p = 0; } // If http(s)/ftp proxy is not set, try socks if (host == "" || p == 0) { host = this->data["/system/proxy/socks_host"]; port = this->data["/system/proxy/socks_port"]; if (sscanf(port.c_str(), "%hu", &p) != 1) p = 0; } // If host and port were found, build config url if (host != "" && p != 0) { string tmp = type + "://"; if (auth) tmp += username + ":" + password + "@"; tmp += host + ":" + port; return url(tmp); } } // Mode is direct:// return url("direct://"); } string get_ignore(url) { return this->data["/system/http_proxy/ignore_hosts"]; } bool set_creds(url /*proxy*/, string username, string password) { string auth = "/system/http_proxy/use_authentication\ttrue\n"; string user = string("/system/http_proxy/authentication_user\t") + username + "\n"; string pass = string("/system/http_proxy/authentication_password\t") + password + "\n"; return (fwrite(auth.c_str(), 1, auth.size(), this->write) == auth.size() && fwrite(user.c_str(), 1, user.size(), this->write) == user.size() && fwrite(pass.c_str(), 1, pass.size(), this->write) == pass.size()); } private: FILE* read; FILE* write; pid_t pid; map<string, string> data; bool read_data(int num=-1) { if (num == 0) return true; if (!this->read) return false; // We need the pipe to be open for (char l[BUFFERSIZE] ; num != 0 && fgets(l, BUFFERSIZE, this->read) != NULL ; ) { string line = l; line = line.substr(0, line.rfind('\n')); string key = line.substr(0, line.find("\t")); string val = line.substr(line.find("\t")+1); this->data[key] = val; if (num > 0) num--; } return (num <= 0); } }; static base_extension** gnome_config_extension_init() { base_extension** retval = new base_extension*[2]; retval[1] = NULL; try { retval[0] = new gnome_config_extension(); return retval; } catch (runtime_error) { delete retval; return NULL; } } MM_MODULE_INIT(gnome_config_extension, gnome_config_extension_init); MM_MODULE_TEST_EZ(gnome_config_extension, ( getenv("GNOME_DESKTOP_SESSION_ID") || (getenv("DESKTOP_SESSION") && string(getenv("DESKTOP_SESSION")) == "gnome") ) );
/******************************************************************************* * libproxy - A library for proxy configuration * Copyright (C) 2006 Nathaniel McCallum <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ #include <cstdio> // For fileno(), fread(), pclose(), popen(), sscanf() #include <sys/select.h> // For select() #include <fcntl.h> // For fcntl() #include <errno.h> // For errno stuff #include <unistd.h> // For pipe(), close(), vfork(), dup(), execl(), _exit() #include <signal.h> // For kill() #include "../extension_config.hpp" using namespace libproxy; #define BUFFERSIZE 10240 static const char *all_keys[] = { "/system/proxy/mode", "/system/proxy/autoconfig_url", "/system/http_proxy/host", "/system/http_proxy/port", "/system/proxy/secure_host", "/system/proxy/secure_port", "/system/proxy/ftp_host", "/system/proxy/ftp_port", "/system/proxy/socks_host", "/system/proxy/socks_port", "/system/http_proxy/ignore_hosts", "/system/http_proxy/use_authentication", "/system/http_proxy/authentication_user", "/system/http_proxy/authentication_password", NULL }; static int popen2(const char *program, FILE** read, FILE** write, pid_t* pid) { if (!read || !write || !pid || !program || !*program) return EINVAL; *read = NULL; *write = NULL; *pid = 0; // Open the pipes int rpipe[2]; int wpipe[2]; if (pipe(rpipe) < 0) return errno; if (pipe(wpipe) < 0) { close(rpipe[0]); close(rpipe[1]); return errno; } switch (*pid = vfork()) { case -1: // Error close(rpipe[0]); close(rpipe[1]); close(wpipe[0]); close(wpipe[1]); return errno; case 0: // Child close(STDIN_FILENO); // Close stdin close(STDOUT_FILENO); // Close stdout // Dup the read end of the write pipe to stdin // Dup the write end of the read pipe to stdout if (dup2(wpipe[0], STDIN_FILENO) != STDIN_FILENO) _exit(1); if (dup2(rpipe[1], STDOUT_FILENO) != STDOUT_FILENO) _exit(2); // Close unneeded fds close(rpipe[0]); close(rpipe[1]); close(wpipe[0]); close(wpipe[1]); // Exec execl("/bin/sh", "sh", "-c", program, (char*) NULL); _exit(127); // Whatever we do, don't return default: // Parent close(rpipe[1]); close(wpipe[0]); *read = fdopen(rpipe[0], "r"); *write = fdopen(wpipe[1], "w"); if (*read == NULL || *write == NULL) { if (*read != NULL) fclose(*read); if (*write != NULL) fclose(*write); return errno; } return 0; } } class gnome_config_extension : public config_extension { public: gnome_config_extension() { // Build the command int count; string cmd = LIBEXECDIR "/pxgconf"; for (count=0 ; all_keys[count] ; count++) cmd += string(" ", 1) + all_keys[count]; // Get our pipes if (popen2(cmd.c_str(), &this->read, &this->write, &this->pid) != 0) throw runtime_error("Unable to open gconf helper!"); // Read in our initial data this->read_data(count); // Set the read pipe to non-blocking if (fcntl(fileno(this->read), F_SETFL, O_NONBLOCK) == -1) { fclose(this->read); fclose(this->write); kill(this->pid, SIGTERM); throw runtime_error("Unable to set pipe to non-blocking!"); } } ~gnome_config_extension() { fclose(this->read); fclose(this->write); kill(this->pid, SIGTERM); } url get_config(url dest) throw (runtime_error) { // Check for changes in the config fd_set rfds; struct timeval timeout = { 0, 0 }; FD_ZERO(&rfds); FD_SET(fileno(this->read), &rfds); if (select(fileno(this->read)+1, &rfds, NULL, NULL, &timeout) > 0) this->read_data(); // Mode is wpad:// or pac+http://... if (this->data["/system/proxy/mode"] == "auto") { string pac = this->data["/system/proxy/autoconfig_url"]; return url::is_valid(pac) ? url(string("pac+") + pac) : url("wpad://"); } // Mode is http://... or socks://... else if (this->data["/system/proxy/mode"] == "manual") { string type = "http", host, port; bool auth = this->data["/system/http_proxy/use_authentication"] == "true"; string username = this->data["/system/http_proxy/authentication_user"]; string password = this->data["/system/http_proxy/authentication_password"]; uint16_t p = 0; // Get the per-scheme proxy settings if (dest.get_scheme() == "https") { host = this->data["/system/proxy/secure_host"]; port = this->data["/system/proxy/secure_port"]; if (sscanf(port.c_str(), "%hu", &p) != 1) p = 0; } else if (dest.get_scheme() == "ftp") { host = this->data["/system/proxy/ftp_host"]; port = this->data["/system/proxy/ftp_port"]; if (sscanf(port.c_str(), "%hu", &p) != 1) p = 0; } if (host == "" || p == 0) { host = this->data["/system/http_proxy/host"]; port = this->data["/system/http_proxy/port"]; if (sscanf(port.c_str(), "%hu", &p) != 1) p = 0; } // If http(s)/ftp proxy is not set, try socks if (host == "" || p == 0) { host = this->data["/system/proxy/socks_host"]; port = this->data["/system/proxy/socks_port"]; if (sscanf(port.c_str(), "%hu", &p) != 1) p = 0; } // If host and port were found, build config url if (host != "" && p != 0) { string tmp = type + "://"; if (auth) tmp += username + ":" + password + "@"; tmp += host + ":" + port; return url(tmp); } } // Mode is direct:// return url("direct://"); } string get_ignore(url) { return this->data["/system/http_proxy/ignore_hosts"]; } bool set_creds(url /*proxy*/, string username, string password) { string auth = "/system/http_proxy/use_authentication\ttrue\n"; string user = string("/system/http_proxy/authentication_user\t") + username + "\n"; string pass = string("/system/http_proxy/authentication_password\t") + password + "\n"; return (fwrite(auth.c_str(), 1, auth.size(), this->write) == auth.size() && fwrite(user.c_str(), 1, user.size(), this->write) == user.size() && fwrite(pass.c_str(), 1, pass.size(), this->write) == pass.size()); } private: FILE* read; FILE* write; pid_t pid; map<string, string> data; bool read_data(int num=-1) { if (num == 0) return true; if (!this->read) return false; // We need the pipe to be open for (char l[BUFFERSIZE] ; num != 0 && fgets(l, BUFFERSIZE, this->read) != NULL ; ) { string line = l; line = line.substr(0, line.rfind('\n')); string key = line.substr(0, line.find("\t")); string val = line.substr(line.find("\t")+1); this->data[key] = val; if (num > 0) num--; } return (num <= 0); } }; static base_extension** gnome_config_extension_init() { base_extension** retval = new base_extension*[2]; retval[1] = NULL; try { retval[0] = new gnome_config_extension(); return retval; } catch (runtime_error) { delete retval; return NULL; } } MM_MODULE_INIT(gnome_config_extension, gnome_config_extension_init); MM_MODULE_TEST_EZ(gnome_config_extension, ( getenv("GNOME_DESKTOP_SESSION_ID") || (getenv("DESKTOP_SESSION") && string(getenv("DESKTOP_SESSION")) == "gnome") ) );
Make config_gnome use O_NONBLOCK instead of FNONBLOCK; patch by raimue
Make config_gnome use O_NONBLOCK instead of FNONBLOCK; patch by raimue
C++
lgpl-2.1
binarycrusader/libproxy,cicku/libproxy,binarycrusader/libproxy,horar/libproxy,markcox/libproxy,cicku/libproxy,codegooglecom/libproxy,maxinbjohn/libproxy,horar/libproxy,anonymous2ch/libproxy,maxinbjohn/libproxy,markcox/libproxy,maxinbjohn/libproxy,horar/libproxy,codegooglecom/libproxy,libproxy/libproxy,libproxy/libproxy,markcox/libproxy,anonymous2ch/libproxy,cicku/libproxy,cicku/libproxy,horar/libproxy,cicku/libproxy,anonymous2ch/libproxy,libproxy/libproxy,binarycrusader/libproxy,markcox/libproxy,markcox/libproxy,maxinbjohn/libproxy,binarycrusader/libproxy,markcox/libproxy,codegooglecom/libproxy,anonymous2ch/libproxy,libproxy/libproxy,binarycrusader/libproxy,cicku/libproxy,horar/libproxy,anonymous2ch/libproxy,anonymous2ch/libproxy,markcox/libproxy,maxinbjohn/libproxy,codegooglecom/libproxy,markcox/libproxy,codegooglecom/libproxy,cicku/libproxy,libproxy/libproxy,binarycrusader/libproxy,anonymous2ch/libproxy,binarycrusader/libproxy,libproxy/libproxy,maxinbjohn/libproxy,binarycrusader/libproxy,horar/libproxy,horar/libproxy,libproxy/libproxy,codegooglecom/libproxy,maxinbjohn/libproxy,codegooglecom/libproxy
4375e1acbb4462618e2a17c8377647b7feeac390
webrtc/tools/frame_analyzer/video_quality_analysis.cc
webrtc/tools/frame_analyzer/video_quality_analysis.cc
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/tools/frame_analyzer/video_quality_analysis.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string> #define STATS_LINE_LENGTH 32 #define Y4M_FILE_HEADER_MAX_SIZE 200 #define Y4M_FRAME_DELIMITER "FRAME" #define Y4M_FRAME_HEADER_SIZE 6 namespace webrtc { namespace test { using std::string; int GetI420FrameSize(int width, int height) { int half_width = (width + 1) >> 1; int half_height = (height + 1) >> 1; int y_plane = width * height; // I420 Y plane. int u_plane = half_width * half_height; // I420 U plane. int v_plane = half_width * half_height; // I420 V plane. return y_plane + u_plane + v_plane; } int ExtractFrameSequenceNumber(std::string line) { size_t space_position = line.find(' '); if (space_position == string::npos) { return -1; } std::string frame = line.substr(0, space_position); size_t underscore_position = frame.find('_'); if (underscore_position == string::npos) { return -1; } std::string frame_number = frame.substr(underscore_position + 1); return strtol(frame_number.c_str(), NULL, 10); } int ExtractDecodedFrameNumber(std::string line) { size_t space_position = line.find(' '); if (space_position == string::npos) { return -1; } std::string decoded_number = line.substr(space_position + 1); return strtol(decoded_number.c_str(), NULL, 10); } bool IsThereBarcodeError(std::string line) { size_t barcode_error_position = line.find("Barcode error"); if (barcode_error_position != string::npos) { return true; } return false; } bool GetNextStatsLine(FILE* stats_file, char* line) { int chars = 0; char buf = 0; while (buf != '\n') { size_t chars_read = fread(&buf, 1, 1, stats_file); if (chars_read != 1 || feof(stats_file)) { return false; } line[chars] = buf; ++chars; } line[chars-1] = '\0'; // Strip the trailing \n and put end of string. return true; } bool ExtractFrameFromYuvFile(const char* i420_file_name, int width, int height, int frame_number, uint8* result_frame) { int frame_size = GetI420FrameSize(width, height); int offset = frame_number * frame_size; // Calculate offset for the frame. bool errors = false; FILE* input_file = fopen(i420_file_name, "rb"); if (input_file == NULL) { fprintf(stderr, "Couldn't open input file for reading: %s\n", i420_file_name); return false; } // Change stream pointer to new offset. fseek(input_file, offset, SEEK_SET); size_t bytes_read = fread(result_frame, 1, frame_size, input_file); if (bytes_read != static_cast<size_t>(frame_size) && ferror(input_file)) { fprintf(stdout, "Error while reading frame no %d from file %s\n", frame_number, i420_file_name); errors = true; } fclose(input_file); return !errors; } bool ExtractFrameFromY4mFile(const char* y4m_file_name, int width, int height, int frame_number, uint8* result_frame) { int frame_size = GetI420FrameSize(width, height); int frame_offset = frame_number * frame_size bool errors = false; FILE* input_file = fopen(y4m_file_name, "rb"); if (input_file == NULL) { fprintf(stderr, "Couldn't open input file for reading: %s\n", y4m_file_name); return false; } // YUV4MPEG2, a.k.a. Y4M File format has a file header and a frame header. The // file header has the aspect: "YUV4MPEG2 C420 W640 H360 Ip F30:1 A1:1". // Skip the header if this is the first frame of the file. if (frame_number == 0) { char frame_header[Y4M_FILE_HEADER_MAX_SIZE]; size_t bytes_read = fread(frame_header, 1, Y4M_FILE_HEADER_MAX_SIZE, input_file); if (bytes_read != static_cast<size_t>(frame_size) && ferror(input_file)) { fprintf(stdout, "Error while reading first frame from file %s\n", y4m_file_name); fclose(input_file); return false; } std::string header_contents(frame_header); std::size_t found = header_contents.find(Y4M_FRAME_DELIMITER); if (found == std::string::npos) { fprintf(stdout, "Corrupted Y4M header, could not find \"FRAME\" in %s\n", header_contents.c_str()); fclose(input_file); return false; } frame_offset = static_cast<int>(found); } // Change stream pointer to new offset, skipping the frame header as well. fseek(input_file, frame_offset + Y4M_FRAME_HEADER_SIZE, SEEK_SET); size_t bytes_read = fread(result_frame, 1, frame_size, input_file); if (bytes_read != static_cast<size_t>(frame_size) && ferror(input_file)) { fprintf(stdout, "Error while reading frame no %d from file %s\n", frame_number, y4m_file_name); errors = true; } fclose(input_file); return !errors; } double CalculateMetrics(VideoAnalysisMetricsType video_metrics_type, const uint8* ref_frame, const uint8* test_frame, int width, int height) { if (!ref_frame || !test_frame) return -1; else if (height < 0 || width < 0) return -1; int half_width = (width + 1) >> 1; int half_height = (height + 1) >> 1; const uint8* src_y_a = ref_frame; const uint8* src_u_a = src_y_a + width * height; const uint8* src_v_a = src_u_a + half_width * half_height; const uint8* src_y_b = test_frame; const uint8* src_u_b = src_y_b + width * height; const uint8* src_v_b = src_u_b + half_width * half_height; int stride_y = width; int stride_uv = half_width; double result = 0.0; switch (video_metrics_type) { case kPSNR: // In the following: stride is determined by width. result = libyuv::I420Psnr(src_y_a, width, src_u_a, half_width, src_v_a, half_width, src_y_b, width, src_u_b, half_width, src_v_b, half_width, width, height); // LibYuv sets the max psnr value to 128, we restrict it to 48. // In case of 0 mse in one frame, 128 can skew the results significantly. result = (result > 48.0) ? 48.0 : result; break; case kSSIM: result = libyuv::I420Ssim(src_y_a, stride_y, src_u_a, stride_uv, src_v_a, stride_uv, src_y_b, stride_y, src_u_b, stride_uv, src_v_b, stride_uv, width, height); break; default: assert(false); } return result; } void RunAnalysis(const char* reference_file_name, const char* test_file_name, const char* stats_file_name, int width, int height, ResultsContainer* results) { // Check if the reference_file_name ends with "y4m". bool y4m_mode = false; if (std::string(reference_file_name).find("y4m") != std::string::npos){ y4m_mode = true; } int size = GetI420FrameSize(width, height); FILE* stats_file = fopen(stats_file_name, "r"); // String buffer for the lines in the stats file. char line[STATS_LINE_LENGTH]; // Allocate buffers for test and reference frames. uint8* test_frame = new uint8[size]; uint8* reference_frame = new uint8[size]; int previous_frame_number = -1; // While there are entries in the stats file. while (GetNextStatsLine(stats_file, line)) { int extracted_test_frame = ExtractFrameSequenceNumber(line); int decoded_frame_number = ExtractDecodedFrameNumber(line); // If there was problem decoding the barcode in this frame or the frame has // been duplicated, continue. if (IsThereBarcodeError(line) || decoded_frame_number == previous_frame_number) { continue; } assert(extracted_test_frame != -1); assert(decoded_frame_number != -1); ExtractFrameFromYuvFile(test_file_name, width, height, extracted_test_frame, test_frame); if (y4m_mode) { ExtractFrameFromY4mFile(reference_file_name, width, height, decoded_frame_number, reference_frame); } else { ExtractFrameFromYuvFile(reference_file_name, width, height, decoded_frame_number, reference_frame); } // Calculate the PSNR and SSIM. double result_psnr = CalculateMetrics(kPSNR, reference_frame, test_frame, width, height); double result_ssim = CalculateMetrics(kSSIM, reference_frame, test_frame, width, height); previous_frame_number = decoded_frame_number; // Fill in the result struct. AnalysisResult result; result.frame_number = decoded_frame_number; result.psnr_value = result_psnr; result.ssim_value = result_ssim; results->frames.push_back(result); } // Cleanup. fclose(stats_file); delete[] test_frame; delete[] reference_frame; } void PrintMaxRepeatedAndSkippedFrames(const std::string& label, const std::string& stats_file_name) { PrintMaxRepeatedAndSkippedFrames(stdout, label, stats_file_name); } void PrintMaxRepeatedAndSkippedFrames(FILE* output, const std::string& label, const std::string& stats_file_name) { FILE* stats_file = fopen(stats_file_name.c_str(), "r"); if (stats_file == NULL) { fprintf(stderr, "Couldn't open stats file for reading: %s\n", stats_file_name.c_str()); return; } char line[STATS_LINE_LENGTH]; int repeated_frames = 1; int max_repeated_frames = 1; int max_skipped_frames = 1; int previous_frame_number = -1; while (GetNextStatsLine(stats_file, line)) { int decoded_frame_number = ExtractDecodedFrameNumber(line); if (decoded_frame_number == -1) { continue; } // Calculate how many frames a cluster of repeated frames contains. if (decoded_frame_number == previous_frame_number) { ++repeated_frames; if (repeated_frames > max_repeated_frames) { max_repeated_frames = repeated_frames; } } else { repeated_frames = 1; } // Calculate how much frames have been skipped. if (decoded_frame_number != 0 && previous_frame_number != -1) { int skipped_frames = decoded_frame_number - previous_frame_number - 1; if (skipped_frames > max_skipped_frames) { max_skipped_frames = skipped_frames; } } previous_frame_number = decoded_frame_number; } fprintf(output, "RESULT Max_repeated: %s= %d\n", label.c_str(), max_repeated_frames); fprintf(output, "RESULT Max_skipped: %s= %d\n", label.c_str(), max_skipped_frames); fclose(stats_file); } void PrintAnalysisResults(const std::string& label, ResultsContainer* results) { PrintAnalysisResults(stdout, label, results); } void PrintAnalysisResults(FILE* output, const std::string& label, ResultsContainer* results) { std::vector<AnalysisResult>::iterator iter; fprintf(output, "RESULT Unique_frames_count: %s= %u\n", label.c_str(), static_cast<unsigned int>(results->frames.size())); if (results->frames.size() > 0u) { fprintf(output, "RESULT PSNR: %s= [", label.c_str()); for (iter = results->frames.begin(); iter != results->frames.end() - 1; ++iter) { fprintf(output, "%f,", iter->psnr_value); } fprintf(output, "%f] dB\n", iter->psnr_value); fprintf(output, "RESULT SSIM: %s= [", label.c_str()); for (iter = results->frames.begin(); iter != results->frames.end() - 1; ++iter) { fprintf(output, "%f,", iter->ssim_value); } fprintf(output, "%f]\n", iter->ssim_value); } } } // namespace test } // namespace webrtc
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/tools/frame_analyzer/video_quality_analysis.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string> #define STATS_LINE_LENGTH 32 #define Y4M_FILE_HEADER_MAX_SIZE 200 #define Y4M_FRAME_DELIMITER "FRAME" #define Y4M_FRAME_HEADER_SIZE 6 namespace webrtc { namespace test { using std::string; int GetI420FrameSize(int width, int height) { int half_width = (width + 1) >> 1; int half_height = (height + 1) >> 1; int y_plane = width * height; // I420 Y plane. int u_plane = half_width * half_height; // I420 U plane. int v_plane = half_width * half_height; // I420 V plane. return y_plane + u_plane + v_plane; } int ExtractFrameSequenceNumber(std::string line) { size_t space_position = line.find(' '); if (space_position == string::npos) { return -1; } std::string frame = line.substr(0, space_position); size_t underscore_position = frame.find('_'); if (underscore_position == string::npos) { return -1; } std::string frame_number = frame.substr(underscore_position + 1); return strtol(frame_number.c_str(), NULL, 10); } int ExtractDecodedFrameNumber(std::string line) { size_t space_position = line.find(' '); if (space_position == string::npos) { return -1; } std::string decoded_number = line.substr(space_position + 1); return strtol(decoded_number.c_str(), NULL, 10); } bool IsThereBarcodeError(std::string line) { size_t barcode_error_position = line.find("Barcode error"); if (barcode_error_position != string::npos) { return true; } return false; } bool GetNextStatsLine(FILE* stats_file, char* line) { int chars = 0; char buf = 0; while (buf != '\n') { size_t chars_read = fread(&buf, 1, 1, stats_file); if (chars_read != 1 || feof(stats_file)) { return false; } line[chars] = buf; ++chars; } line[chars-1] = '\0'; // Strip the trailing \n and put end of string. return true; } bool ExtractFrameFromYuvFile(const char* i420_file_name, int width, int height, int frame_number, uint8* result_frame) { int frame_size = GetI420FrameSize(width, height); int offset = frame_number * frame_size; // Calculate offset for the frame. bool errors = false; FILE* input_file = fopen(i420_file_name, "rb"); if (input_file == NULL) { fprintf(stderr, "Couldn't open input file for reading: %s\n", i420_file_name); return false; } // Change stream pointer to new offset. fseek(input_file, offset, SEEK_SET); size_t bytes_read = fread(result_frame, 1, frame_size, input_file); if (bytes_read != static_cast<size_t>(frame_size) && ferror(input_file)) { fprintf(stdout, "Error while reading frame no %d from file %s\n", frame_number, i420_file_name); errors = true; } fclose(input_file); return !errors; } bool ExtractFrameFromY4mFile(const char* y4m_file_name, int width, int height, int frame_number, uint8* result_frame) { int frame_size = GetI420FrameSize(width, height); int frame_offset = frame_number * frame_size; bool errors = false; FILE* input_file = fopen(y4m_file_name, "rb"); if (input_file == NULL) { fprintf(stderr, "Couldn't open input file for reading: %s\n", y4m_file_name); return false; } // YUV4MPEG2, a.k.a. Y4M File format has a file header and a frame header. The // file header has the aspect: "YUV4MPEG2 C420 W640 H360 Ip F30:1 A1:1". // Skip the header if this is the first frame of the file. if (frame_number == 0) { char frame_header[Y4M_FILE_HEADER_MAX_SIZE]; size_t bytes_read = fread(frame_header, 1, Y4M_FILE_HEADER_MAX_SIZE, input_file); if (bytes_read != static_cast<size_t>(frame_size) && ferror(input_file)) { fprintf(stdout, "Error while reading first frame from file %s\n", y4m_file_name); fclose(input_file); return false; } std::string header_contents(frame_header); std::size_t found = header_contents.find(Y4M_FRAME_DELIMITER); if (found == std::string::npos) { fprintf(stdout, "Corrupted Y4M header, could not find \"FRAME\" in %s\n", header_contents.c_str()); fclose(input_file); return false; } frame_offset = static_cast<int>(found); } // Change stream pointer to new offset, skipping the frame header as well. fseek(input_file, frame_offset + Y4M_FRAME_HEADER_SIZE, SEEK_SET); size_t bytes_read = fread(result_frame, 1, frame_size, input_file); if (bytes_read != static_cast<size_t>(frame_size) && ferror(input_file)) { fprintf(stdout, "Error while reading frame no %d from file %s\n", frame_number, y4m_file_name); errors = true; } fclose(input_file); return !errors; } double CalculateMetrics(VideoAnalysisMetricsType video_metrics_type, const uint8* ref_frame, const uint8* test_frame, int width, int height) { if (!ref_frame || !test_frame) return -1; else if (height < 0 || width < 0) return -1; int half_width = (width + 1) >> 1; int half_height = (height + 1) >> 1; const uint8* src_y_a = ref_frame; const uint8* src_u_a = src_y_a + width * height; const uint8* src_v_a = src_u_a + half_width * half_height; const uint8* src_y_b = test_frame; const uint8* src_u_b = src_y_b + width * height; const uint8* src_v_b = src_u_b + half_width * half_height; int stride_y = width; int stride_uv = half_width; double result = 0.0; switch (video_metrics_type) { case kPSNR: // In the following: stride is determined by width. result = libyuv::I420Psnr(src_y_a, width, src_u_a, half_width, src_v_a, half_width, src_y_b, width, src_u_b, half_width, src_v_b, half_width, width, height); // LibYuv sets the max psnr value to 128, we restrict it to 48. // In case of 0 mse in one frame, 128 can skew the results significantly. result = (result > 48.0) ? 48.0 : result; break; case kSSIM: result = libyuv::I420Ssim(src_y_a, stride_y, src_u_a, stride_uv, src_v_a, stride_uv, src_y_b, stride_y, src_u_b, stride_uv, src_v_b, stride_uv, width, height); break; default: assert(false); } return result; } void RunAnalysis(const char* reference_file_name, const char* test_file_name, const char* stats_file_name, int width, int height, ResultsContainer* results) { // Check if the reference_file_name ends with "y4m". bool y4m_mode = false; if (std::string(reference_file_name).find("y4m") != std::string::npos){ y4m_mode = true; } int size = GetI420FrameSize(width, height); FILE* stats_file = fopen(stats_file_name, "r"); // String buffer for the lines in the stats file. char line[STATS_LINE_LENGTH]; // Allocate buffers for test and reference frames. uint8* test_frame = new uint8[size]; uint8* reference_frame = new uint8[size]; int previous_frame_number = -1; // While there are entries in the stats file. while (GetNextStatsLine(stats_file, line)) { int extracted_test_frame = ExtractFrameSequenceNumber(line); int decoded_frame_number = ExtractDecodedFrameNumber(line); // If there was problem decoding the barcode in this frame or the frame has // been duplicated, continue. if (IsThereBarcodeError(line) || decoded_frame_number == previous_frame_number) { continue; } assert(extracted_test_frame != -1); assert(decoded_frame_number != -1); ExtractFrameFromYuvFile(test_file_name, width, height, extracted_test_frame, test_frame); if (y4m_mode) { ExtractFrameFromY4mFile(reference_file_name, width, height, decoded_frame_number, reference_frame); } else { ExtractFrameFromYuvFile(reference_file_name, width, height, decoded_frame_number, reference_frame); } // Calculate the PSNR and SSIM. double result_psnr = CalculateMetrics(kPSNR, reference_frame, test_frame, width, height); double result_ssim = CalculateMetrics(kSSIM, reference_frame, test_frame, width, height); previous_frame_number = decoded_frame_number; // Fill in the result struct. AnalysisResult result; result.frame_number = decoded_frame_number; result.psnr_value = result_psnr; result.ssim_value = result_ssim; results->frames.push_back(result); } // Cleanup. fclose(stats_file); delete[] test_frame; delete[] reference_frame; } void PrintMaxRepeatedAndSkippedFrames(const std::string& label, const std::string& stats_file_name) { PrintMaxRepeatedAndSkippedFrames(stdout, label, stats_file_name); } void PrintMaxRepeatedAndSkippedFrames(FILE* output, const std::string& label, const std::string& stats_file_name) { FILE* stats_file = fopen(stats_file_name.c_str(), "r"); if (stats_file == NULL) { fprintf(stderr, "Couldn't open stats file for reading: %s\n", stats_file_name.c_str()); return; } char line[STATS_LINE_LENGTH]; int repeated_frames = 1; int max_repeated_frames = 1; int max_skipped_frames = 1; int previous_frame_number = -1; while (GetNextStatsLine(stats_file, line)) { int decoded_frame_number = ExtractDecodedFrameNumber(line); if (decoded_frame_number == -1) { continue; } // Calculate how many frames a cluster of repeated frames contains. if (decoded_frame_number == previous_frame_number) { ++repeated_frames; if (repeated_frames > max_repeated_frames) { max_repeated_frames = repeated_frames; } } else { repeated_frames = 1; } // Calculate how much frames have been skipped. if (decoded_frame_number != 0 && previous_frame_number != -1) { int skipped_frames = decoded_frame_number - previous_frame_number - 1; if (skipped_frames > max_skipped_frames) { max_skipped_frames = skipped_frames; } } previous_frame_number = decoded_frame_number; } fprintf(output, "RESULT Max_repeated: %s= %d\n", label.c_str(), max_repeated_frames); fprintf(output, "RESULT Max_skipped: %s= %d\n", label.c_str(), max_skipped_frames); fclose(stats_file); } void PrintAnalysisResults(const std::string& label, ResultsContainer* results) { PrintAnalysisResults(stdout, label, results); } void PrintAnalysisResults(FILE* output, const std::string& label, ResultsContainer* results) { std::vector<AnalysisResult>::iterator iter; fprintf(output, "RESULT Unique_frames_count: %s= %u\n", label.c_str(), static_cast<unsigned int>(results->frames.size())); if (results->frames.size() > 0u) { fprintf(output, "RESULT PSNR: %s= [", label.c_str()); for (iter = results->frames.begin(); iter != results->frames.end() - 1; ++iter) { fprintf(output, "%f,", iter->psnr_value); } fprintf(output, "%f] dB\n", iter->psnr_value); fprintf(output, "RESULT SSIM: %s= [", label.c_str()); for (iter = results->frames.begin(); iter != results->frames.end() - 1; ++iter) { fprintf(output, "%f,", iter->ssim_value); } fprintf(output, "%f]\n", iter->ssim_value); } } } // namespace test } // namespace webrtc
Add support for YUV4MPEG file reading to tools files. (Minor fix).
Add support for YUV4MPEG file reading to tools files. (Minor fix). git-svn-id: 917f5d3ca488f358c4d40eaec14422cf392ccec9@5703 4adac7df-926f-26a2-2b94-8c16560cd09d
C++
bsd-3-clause
TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,mwgoldsmith/ilbc,mwgoldsmith/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,mwgoldsmith/ilbc,TimothyGu/libilbc,mwgoldsmith/libilbc,ShiftMediaProject/libilbc,mwgoldsmith/libilbc,mwgoldsmith/libilbc,ShiftMediaProject/libilbc,mwgoldsmith/ilbc,ShiftMediaProject/libilbc,mwgoldsmith/ilbc,TimothyGu/libilbc
4c0d07ddb9857bf36d26bdda5c112be0f896484a
llbc/src/core/utils/Util_Text.cpp
llbc/src/core/utils/Util_Text.cpp
/** * @file Util_Text.cpp * @author Longwei Lai<[email protected]> * @date 2013/02/09 * @version 1.0 * * @brief LLBC library text processing APIs encapsulation. */ //! First, include export header file. #include "llbc/common/Export.h" #include "llbc/common/BeforeIncl.h" #include "llbc/common/Common.h" #include "llbc/core/utils/Util_Algorithm.h" #include "llbc/core/utils/Util_Text.h" #if LLBC_TARGET_PLATFORM_WIN32 #pragma warning(disable:4996) #endif #if LLBC_TARGET_PLATFORM_NON_WIN32 int lstrlenA(LPCSTR lpString) { return ::strlen(lpString); } int lstrlenW(LPCWSTR lpString) { if (UNLIKELY(!lpString)) { return 0; } int i = 0; for (; lpString[i] != LLBC_WTEXT('\0'); i ++); return i; } LPSTR lstrcatA(LPSTR lpString1, LPCSTR lpString2) { return ::strcat(lpString1, lpString2); } LPWSTR lstrcatW(LPWSTR lpString1, LPCWSTR lpString2) { if (UNLIKELY(!lpString2)) { return lpString1; } int str1Len = ::lstrlenW(lpString1); int str2Len = ::lstrlenW(lpString2); memcpy(lpString1 + str1Len, lpString2, str2Len * sizeof(LLBC_NS wchar)); return lpString1; } int lstrcmpA(LPCSTR lpString1, LPCSTR lpString2) { return ::strcmp(lpString1, lpString2); } int lstrcmpW(LPCWSTR lpString1, LPCWSTR lpString2) { int str1Len = ::lstrlenW(lpString1); int str2Len = ::lstrlenW(lpString2); int len = MIN(str1Len, str2Len); for (register int i = 0; i < len; i ++) { if (lpString1[i] < lpString2[i]) { return -1; } else if (lpString1[i] == lpString2[i]) { return 1; } } return (str1Len < str2Len ? -1 : (str1Len == str2Len ? 0 : 1)); } int lstrcmpiA(LPCSTR lpString1, LPCSTR lpString2) { return ::lstrcmpA(lpString1,lpString2); } int lstrcmpiW(LPCWSTR lpString1, LPCWSTR lpString2) { return ::lstrcmpW(lpString1, lpString2); } LPSTR lstrcpyA(LPSTR lpString1, LPCSTR lpString2) { return strcpy(lpString1, lpString2); } LPWSTR lstrcpyW(LPWSTR lpString1, LPCWSTR lpString2) { int str2Len = ::lstrlenW(lpString2); memcpy(lpString1, lpString2, str2Len * sizeof(LLBC_NS wchar)); lpString1[str2Len] = LLBC_WTEXT('\0'); return lpString1; } #endif // LLBC_TARGET_PLATFORM_NON_WIN32 __LLBC_NS_BEGIN void LLBC_SplitString(const LLBC_String &str, const LLBC_String &separator, std::vector<LLBC_String> &destStrList, bool justSplitFirst, char escapeChar) { if (UNLIKELY(str.empty())) { return; } if (UNLIKELY(separator.empty())) { destStrList.push_back(str); } LLBC_String::size_type curPos = 0; LLBC_String::size_type prevPos = 0; LLBC_String strInternal = str; while ((curPos = strInternal.find(separator, curPos)) != LLBC_String::npos) { if (curPos != 0 && strInternal[curPos - 1] == escapeChar) { strInternal.erase(-- curPos, 1); curPos += separator.size(); continue; } LLBC_String temp = strInternal.substr(prevPos, curPos - prevPos); destStrList.push_back(temp); if (justSplitFirst) { destStrList.push_back(strInternal.substr(curPos + separator.size())); return; } curPos += separator.size(); prevPos = curPos; } LLBC_String temp = strInternal.substr(prevPos); if (!temp.empty()) { destStrList.push_back(temp); } } LLBC_String LLBC_FilterOutString(const LLBC_String &str, const LLBC_String &filterStr) { std::vector<LLBC_String> strings; LLBC_SplitString(str, filterStr, strings); LLBC_String retStr; for (size_t i = 0; i < strings.size(); i ++) { retStr += strings[i]; } return retStr; } LLBC_String LLBC_ToUpper(const char *str) { LLBC_String convertedStr(str); char ch = '\0'; const LLBC_String::size_type length = convertedStr.size(); for (register LLBC_String::size_type i = 0; i < length; i ++) { ch = convertedStr[i]; if (ch >= 'a' && ch <= 'z') { convertedStr[i] -= 32; } } return convertedStr; } LLBC_String LLBC_ToLower(const char *str) { LLBC_String convertedStr(str); char ch = '\0'; const LLBC_String::size_type length = convertedStr.size(); for (register LLBC_String::size_type i = 0; i < length; i ++) { ch = convertedStr[i]; if (ch >= 'A' && ch <= 'Z') { convertedStr[i] += 32; } } return convertedStr; } LLBC_String LLBC_Trim(const LLBC_String &str) { if (UNLIKELY(str.empty())) { return LLBC_String(); } return LLBC_TrimRight(LLBC_TrimLeft(str)); } LLBC_String LLBC_Trim(const LLBC_String &str, char target) { if (UNLIKELY(str.empty())) { return LLBC_String(); } return LLBC_TrimRight(LLBC_TrimLeft(str, target), target); } LLBC_String LLBC_Trim(const LLBC_String &str, const char *targets) { if (UNLIKELY(str.empty())) { return LLBC_String(); } return LLBC_TrimRight(LLBC_TrimLeft(str, targets), targets); } LLBC_String LLBC_TrimLeft(const LLBC_String &str) { return LLBC_TrimLeft(str, "\t "); } LLBC_String LLBC_TrimLeft(const LLBC_String &str, char target) { if (UNLIKELY(str.empty())) { return LLBC_String(); } const LLBC_String::size_type length = str.size(); register LLBC_String::size_type leftPos = 0; for (; str[leftPos] == target && leftPos < length; leftPos ++); if (leftPos >= length) { return LLBC_String(); } return str.substr(leftPos, LLBC_String::npos); } LLBC_String LLBC_TrimLeft(const LLBC_String &str, const char *targets) { if (UNLIKELY(!targets)) { return str; } LLBC_String retStr = str; const uint32 len = LLBC_StrLenA(targets); for (register uint32 i = 0; i < len; i ++) { retStr = LLBC_TrimLeft(retStr, targets[i]); } return retStr; } LLBC_String LLBC_TrimRight(const LLBC_String &str) { return LLBC_TrimRight(str, "\t "); } LLBC_String LLBC_TrimRight(const LLBC_String &str, char target) { if (UNLIKELY(str.empty())) { return LLBC_String(); } const LLBC_String::size_type length = str.size(); register LLBC_String::size_type rightPos = length - 1; for (; str[rightPos] == target && rightPos != 0; rightPos --); return str.substr(0, rightPos + 1); } LLBC_String LLBC_TrimRight(const LLBC_String &str, const char *targets) { if (UNLIKELY(!targets)) { return str; } LLBC_String retStr = str; const uint32 len = LLBC_StrLenA(targets); for (register uint32 i = 0; i < len; i ++) { retStr = LLBC_TrimRight(retStr, targets[i]); } return retStr; } LLBC_String LLBC_DirName(const LLBC_String &path) { if (UNLIKELY(path.empty())) { return LLBC_String(); } #if LLBC_TARGET_PLATFORM_NON_WIN32 char *buf = reinterpret_cast<char *>(::malloc(path.size() + 1)); ::memcpy(buf, path.data(), path.size()); buf[path.size()] = '\0'; ::dirname(buf); LLBC_String dirName = buf; ::free(buf); return dirName; #else if (path[path.length() - 1] == ':') { return path; } LLBC_String::size_type slashPos = path.rfind(LLBC_SLASH_A); LLBC_String::size_type backlashPos = path.rfind(LLBC_BACKLASH_A); if (slashPos == LLBC_String::npos) { if (backlashPos == LLBC_String::npos) { return LLBC_String(); } return path.substr(0, backlashPos); } else { if (backlashPos == LLBC_String::npos) { return path.substr(0, slashPos); } } return path.substr(0, MAX(slashPos, backlashPos)); #endif } LLBC_String LLBC_BaseName(const LLBC_String &path, bool incExtension) { if (UNLIKELY(path.empty())) { return LLBC_String(); } LLBC_String baseName; #if LLBC_TARGET_PLATFORM_NON_WIN32 baseName = ::basename(const_cast<char *>(path.c_str())); #else LLBC_String::size_type slashPos = path.rfind(LLBC_SLASH_A); LLBC_String::size_type backlashPos = path.rfind(LLBC_BACKLASH_A); if (slashPos == LLBC_String::npos) { if (backlashPos == LLBC_String::npos) { baseName = path; } else { baseName = path.substr(backlashPos + 1); } } else { if (backlashPos == LLBC_String::npos) { baseName = path.substr(slashPos + 1); } else { baseName = path.substr(MAX(slashPos, backlashPos) + 1); } } #endif if (!incExtension) { LLBC_String::size_type dotPos = baseName.rfind('.'); if (dotPos != LLBC_String::npos && dotPos != 0) { baseName.erase(dotPos); } } return baseName; } LLBC_String LLBC_ExtensionName(const LLBC_String &path) { LLBC_String basename = LLBC_BaseName(path); if (UNLIKELY(basename.empty())) { return LLBC_String(); } LLBC_String::size_type pos = basename.rfind("."); if (pos == LLBC_String::npos) { return LLBC_String(); } return basename.substr(pos + 1); } sint32 LLBC_Str2Int32(const char *str) { return ::atoi(str); } uint32 LLBC_Str2UInt32(const char *str) { return static_cast<uint32>(LLBC_Str2Int32(str)); } long LLBC_Str2Long(const char *str) { return ::atol(str); } ulong LLBC_Str2ULong(const char *str) { return static_cast<ulong>(LLBC_Str2Long(str)); } sint64 LLBC_Str2Int64(const char *str) { #if LLBC_TARGET_PLATFORM_NON_WIN32 return ::atoll(str); #else return ::_atoi64(str); #endif } uint64 LLBC_Str2UInt64(const char *str) { return static_cast<uint64>(LLBC_Str2Int64(str)); } void *LLBC_Str2Ptr(const char *str) { if (UNLIKELY(!str)) { LLBC_SetLastError(LLBC_ERROR_ARG); return NULL; } LLBC_SetLastError(LLBC_ERROR_SUCCESS); bool hexFormat = false; LLBC_String lowerStr = LLBC_ToLower(str); lowerStr = LLBC_Trim(lowerStr); if (lowerStr.size() >= 2 && (lowerStr[0] == '0' && lowerStr[1] == 'x')) { hexFormat = true; lowerStr = lowerStr.substr(2); } if (lowerStr.empty()) { return NULL; } for (LLBC_String::size_type i = 0; i < lowerStr.size(); i ++) { if (hexFormat) { if (!((lowerStr[i] >= '0' && lowerStr[i] <= '9') || (lowerStr[i] >= 'a' && lowerStr[i] <= 'f'))) { LLBC_SetLastError(LLBC_ERROR_ARG); return NULL; } } else { if (lowerStr[i] < '0' || lowerStr[i] > '9') { LLBC_SetLastError(LLBC_ERROR_ARG); return NULL; } } } ulong ptrVal = 0; ulong baseVal = hexFormat ? 16 : 10; for (LLBC_String::size_type i = 0; i < lowerStr.size(); i ++) { ptrVal *= baseVal; if (lowerStr[i] >= '0' && lowerStr[i] <= '9') { ptrVal += (uint8)(lowerStr[i] - '0'); } else { ptrVal += (uint8)(lowerStr[i] - 'a' + (char)10); } } return reinterpret_cast<void *>(ptrVal); } double LLBC_Str2Double(const char *str) { #if LLBC_TARGET_PLATFORM_NON_WIN32 return ::atof(str); #else return ::atof(str); #endif } #if LLBC_TARGET_PLATFORM_WIN32 #pragma warning(default:4996) #endif __LLBC_NS_END #include "llbc/common/AfterIncl.h"
/** * @file Util_Text.cpp * @author Longwei Lai<[email protected]> * @date 2013/02/09 * @version 1.0 * * @brief LLBC library text processing APIs encapsulation. */ //! First, include export header file. #include "llbc/common/Export.h" #include "llbc/common/BeforeIncl.h" #include "llbc/common/Common.h" #include "llbc/core/utils/Util_Text.h" #if LLBC_TARGET_PLATFORM_WIN32 #pragma warning(disable:4996) #endif #if LLBC_TARGET_PLATFORM_NON_WIN32 int lstrlenA(LPCSTR lpString) { return ::strlen(lpString); } int lstrlenW(LPCWSTR lpString) { if (UNLIKELY(!lpString)) { return 0; } int i = 0; for (; lpString[i] != LLBC_WTEXT('\0'); i ++); return i; } LPSTR lstrcatA(LPSTR lpString1, LPCSTR lpString2) { return ::strcat(lpString1, lpString2); } LPWSTR lstrcatW(LPWSTR lpString1, LPCWSTR lpString2) { if (UNLIKELY(!lpString2)) { return lpString1; } int str1Len = ::lstrlenW(lpString1); int str2Len = ::lstrlenW(lpString2); memcpy(lpString1 + str1Len, lpString2, str2Len * sizeof(LLBC_NS wchar)); return lpString1; } int lstrcmpA(LPCSTR lpString1, LPCSTR lpString2) { return ::strcmp(lpString1, lpString2); } int lstrcmpW(LPCWSTR lpString1, LPCWSTR lpString2) { int str1Len = ::lstrlenW(lpString1); int str2Len = ::lstrlenW(lpString2); int len = MIN(str1Len, str2Len); for (register int i = 0; i < len; i ++) { if (lpString1[i] < lpString2[i]) { return -1; } else if (lpString1[i] == lpString2[i]) { return 1; } } return (str1Len < str2Len ? -1 : (str1Len == str2Len ? 0 : 1)); } int lstrcmpiA(LPCSTR lpString1, LPCSTR lpString2) { return ::lstrcmpA(lpString1,lpString2); } int lstrcmpiW(LPCWSTR lpString1, LPCWSTR lpString2) { return ::lstrcmpW(lpString1, lpString2); } LPSTR lstrcpyA(LPSTR lpString1, LPCSTR lpString2) { return strcpy(lpString1, lpString2); } LPWSTR lstrcpyW(LPWSTR lpString1, LPCWSTR lpString2) { int str2Len = ::lstrlenW(lpString2); memcpy(lpString1, lpString2, str2Len * sizeof(LLBC_NS wchar)); lpString1[str2Len] = LLBC_WTEXT('\0'); return lpString1; } #endif // LLBC_TARGET_PLATFORM_NON_WIN32 __LLBC_NS_BEGIN void LLBC_SplitString(const LLBC_String &str, const LLBC_String &separator, std::vector<LLBC_String> &destStrList, bool justSplitFirst, char escapeChar) { if (UNLIKELY(str.empty())) { return; } if (UNLIKELY(separator.empty())) { destStrList.push_back(str); } LLBC_String::size_type curPos = 0; LLBC_String::size_type prevPos = 0; LLBC_String strInternal = str; while ((curPos = strInternal.find(separator, curPos)) != LLBC_String::npos) { if (curPos != 0 && strInternal[curPos - 1] == escapeChar) { strInternal.erase(-- curPos, 1); curPos += separator.size(); continue; } LLBC_String temp = strInternal.substr(prevPos, curPos - prevPos); destStrList.push_back(temp); if (justSplitFirst) { destStrList.push_back(strInternal.substr(curPos + separator.size())); return; } curPos += separator.size(); prevPos = curPos; } LLBC_String temp = strInternal.substr(prevPos); if (!temp.empty()) { destStrList.push_back(temp); } } LLBC_String LLBC_FilterOutString(const LLBC_String &str, const LLBC_String &filterStr) { std::vector<LLBC_String> strings; LLBC_SplitString(str, filterStr, strings); LLBC_String retStr; for (size_t i = 0; i < strings.size(); i ++) { retStr += strings[i]; } return retStr; } LLBC_String LLBC_ToUpper(const char *str) { LLBC_String convertedStr(str); char ch = '\0'; const LLBC_String::size_type length = convertedStr.size(); for (register LLBC_String::size_type i = 0; i < length; i ++) { ch = convertedStr[i]; if (ch >= 'a' && ch <= 'z') { convertedStr[i] -= 32; } } return convertedStr; } LLBC_String LLBC_ToLower(const char *str) { LLBC_String convertedStr(str); char ch = '\0'; const LLBC_String::size_type length = convertedStr.size(); for (register LLBC_String::size_type i = 0; i < length; i ++) { ch = convertedStr[i]; if (ch >= 'A' && ch <= 'Z') { convertedStr[i] += 32; } } return convertedStr; } LLBC_String LLBC_Trim(const LLBC_String &str) { if (UNLIKELY(str.empty())) { return LLBC_String(); } return LLBC_TrimRight(LLBC_TrimLeft(str)); } LLBC_String LLBC_Trim(const LLBC_String &str, char target) { if (UNLIKELY(str.empty())) { return LLBC_String(); } return LLBC_TrimRight(LLBC_TrimLeft(str, target), target); } LLBC_String LLBC_Trim(const LLBC_String &str, const char *targets) { if (UNLIKELY(str.empty())) { return LLBC_String(); } return LLBC_TrimRight(LLBC_TrimLeft(str, targets), targets); } LLBC_String LLBC_TrimLeft(const LLBC_String &str) { return LLBC_TrimLeft(str, "\t "); } LLBC_String LLBC_TrimLeft(const LLBC_String &str, char target) { if (UNLIKELY(str.empty())) { return LLBC_String(); } const LLBC_String::size_type length = str.size(); register LLBC_String::size_type leftPos = 0; for (; str[leftPos] == target && leftPos < length; leftPos ++); if (leftPos >= length) { return LLBC_String(); } return str.substr(leftPos, LLBC_String::npos); } LLBC_String LLBC_TrimLeft(const LLBC_String &str, const char *targets) { if (UNLIKELY(!targets)) { return str; } LLBC_String retStr = str; const uint32 len = LLBC_StrLenA(targets); for (register uint32 i = 0; i < len; i ++) { retStr = LLBC_TrimLeft(retStr, targets[i]); } return retStr; } LLBC_String LLBC_TrimRight(const LLBC_String &str) { return LLBC_TrimRight(str, "\t "); } LLBC_String LLBC_TrimRight(const LLBC_String &str, char target) { if (UNLIKELY(str.empty())) { return LLBC_String(); } const LLBC_String::size_type length = str.size(); register LLBC_String::size_type rightPos = length - 1; for (; str[rightPos] == target && rightPos != 0; rightPos --); return str.substr(0, rightPos + 1); } LLBC_String LLBC_TrimRight(const LLBC_String &str, const char *targets) { if (UNLIKELY(!targets)) { return str; } LLBC_String retStr = str; const uint32 len = LLBC_StrLenA(targets); for (register uint32 i = 0; i < len; i ++) { retStr = LLBC_TrimRight(retStr, targets[i]); } return retStr; } LLBC_String LLBC_DirName(const LLBC_String &path) { if (UNLIKELY(path.empty())) { return LLBC_String(); } #if LLBC_TARGET_PLATFORM_NON_WIN32 char *buf = reinterpret_cast<char *>(::malloc(path.size() + 1)); ::memcpy(buf, path.data(), path.size()); buf[path.size()] = '\0'; ::dirname(buf); LLBC_String dirName = buf; ::free(buf); return dirName; #else if (path[path.length() - 1] == ':') { return path; } LLBC_String::size_type slashPos = path.rfind(LLBC_SLASH_A); LLBC_String::size_type backlashPos = path.rfind(LLBC_BACKLASH_A); if (slashPos == LLBC_String::npos) { if (backlashPos == LLBC_String::npos) { return LLBC_String(); } return path.substr(0, backlashPos); } else { if (backlashPos == LLBC_String::npos) { return path.substr(0, slashPos); } } return path.substr(0, MAX(slashPos, backlashPos)); #endif } LLBC_String LLBC_BaseName(const LLBC_String &path, bool incExtension) { if (UNLIKELY(path.empty())) { return LLBC_String(); } LLBC_String baseName; #if LLBC_TARGET_PLATFORM_NON_WIN32 baseName = ::basename(const_cast<char *>(path.c_str())); #else LLBC_String::size_type slashPos = path.rfind(LLBC_SLASH_A); LLBC_String::size_type backlashPos = path.rfind(LLBC_BACKLASH_A); if (slashPos == LLBC_String::npos) { if (backlashPos == LLBC_String::npos) { baseName = path; } else { baseName = path.substr(backlashPos + 1); } } else { if (backlashPos == LLBC_String::npos) { baseName = path.substr(slashPos + 1); } else { baseName = path.substr(MAX(slashPos, backlashPos) + 1); } } #endif if (!incExtension) { LLBC_String::size_type dotPos = baseName.rfind('.'); if (dotPos != LLBC_String::npos && dotPos != 0) { baseName.erase(dotPos); } } return baseName; } LLBC_String LLBC_ExtensionName(const LLBC_String &path) { LLBC_String basename = LLBC_BaseName(path); if (UNLIKELY(basename.empty())) { return LLBC_String(); } LLBC_String::size_type pos = basename.rfind("."); if (pos == LLBC_String::npos) { return LLBC_String(); } return basename.substr(pos + 1); } sint32 LLBC_Str2Int32(const char *str) { return ::atoi(str); } uint32 LLBC_Str2UInt32(const char *str) { return static_cast<uint32>(LLBC_Str2Int32(str)); } long LLBC_Str2Long(const char *str) { return ::atol(str); } ulong LLBC_Str2ULong(const char *str) { return static_cast<ulong>(LLBC_Str2Long(str)); } sint64 LLBC_Str2Int64(const char *str) { #if LLBC_TARGET_PLATFORM_NON_WIN32 return ::atoll(str); #else return ::_atoi64(str); #endif } uint64 LLBC_Str2UInt64(const char *str) { return static_cast<uint64>(LLBC_Str2Int64(str)); } void *LLBC_Str2Ptr(const char *str) { if (UNLIKELY(!str)) { LLBC_SetLastError(LLBC_ERROR_ARG); return NULL; } LLBC_SetLastError(LLBC_ERROR_SUCCESS); bool hexFormat = false; LLBC_String lowerStr = LLBC_ToLower(str); lowerStr = LLBC_Trim(lowerStr); if (lowerStr.size() >= 2 && (lowerStr[0] == '0' && lowerStr[1] == 'x')) { hexFormat = true; lowerStr = lowerStr.substr(2); } if (lowerStr.empty()) { return NULL; } for (LLBC_String::size_type i = 0; i < lowerStr.size(); i ++) { if (hexFormat) { if (!((lowerStr[i] >= '0' && lowerStr[i] <= '9') || (lowerStr[i] >= 'a' && lowerStr[i] <= 'f'))) { LLBC_SetLastError(LLBC_ERROR_ARG); return NULL; } } else { if (lowerStr[i] < '0' || lowerStr[i] > '9') { LLBC_SetLastError(LLBC_ERROR_ARG); return NULL; } } } ulong ptrVal = 0; ulong baseVal = hexFormat ? 16 : 10; for (LLBC_String::size_type i = 0; i < lowerStr.size(); i ++) { ptrVal *= baseVal; if (lowerStr[i] >= '0' && lowerStr[i] <= '9') { ptrVal += (uint8)(lowerStr[i] - '0'); } else { ptrVal += (uint8)(lowerStr[i] - 'a' + (char)10); } } return reinterpret_cast<void *>(ptrVal); } double LLBC_Str2Double(const char *str) { #if LLBC_TARGET_PLATFORM_NON_WIN32 return ::atof(str); #else return ::atof(str); #endif } #if LLBC_TARGET_PLATFORM_WIN32 #pragma warning(default:4996) #endif __LLBC_NS_END #include "llbc/common/AfterIncl.h"
Delete don't need include header file:Util_Algorithm.h
Delete don't need include header file:Util_Algorithm.h
C++
mit
lailongwei/llbc,lailongwei/llbc,lailongwei/llbc,lailongwei/llbc,lailongwei/llbc
1c7c5f7648d99878ed9eb7166fd5757f24ba5732
src/examples/HelloSPTP.cpp
src/examples/HelloSPTP.cpp
/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013-2015, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ #include <algorithm> // std::generate #include <cmath> // pow #include <ctime> // std::time #include <iostream> #include <vector> #include "nupic/algorithms/Cells4.hpp" //TODO use TM instead #include "nupic/algorithms/SpatialPooler.hpp" #include "nupic/os/Timer.hpp" #include "nupic/utils/VectorHelpers.hpp" #include "nupic/utils/Random.hpp" namespace examples { using namespace std; using namespace nupic; using namespace nupic::utils; using nupic::algorithms::spatial_pooler::SpatialPooler; using nupic::algorithms::Cells4::Cells4; // work-load void run() { const UInt COLS = 2048; // number of columns in SP, TP const UInt DIM_INPUT = 10000; const UInt CELLS = 10; // cells per column in TP const UInt EPOCHS = (UInt)pow(10, 3); // number of iterations (calls to SP/TP compute() ) std::cout << "starting test. DIM_INPUT=" << DIM_INPUT << ", DIM=" << COLS << ", CELLS=" << CELLS << std::endl; std::cout << "EPOCHS = " << EPOCHS << std::endl; // generate random input vector<UInt> input(DIM_INPUT); vector<UInt> outSP(COLS); // active array, output of SP/TP // initialize SP, TP SpatialPooler sp(vector<UInt>{DIM_INPUT}, vector<UInt>{COLS}); Cells4 tp(COLS, CELLS, 12, 8, 15, 5, .5f, .8f, 1.0f, .1f, .1f, 0.0f, false, 42, true, false); vector<UInt> outTP(tp.nCells()); vector<Real> rIn(COLS); // input for TP (must be Reals) vector<Real> rOut(tp.nCells()); Random rnd; // Start a stopwatch timer printf("starting: %d iterations.", EPOCHS); Timer stopwatch(true); //run for (UInt e = 0; e < EPOCHS; e++) { generate(input.begin(), input.end(), [&] () { return rnd.getUInt32(2); }); fill(outSP.begin(), outSP.end(), 0); sp.compute(input.data(), true, outSP.data()); sp.stripUnlearnedColumns(outSP.data()); rIn = VectorHelpers::castVectorType<UInt, Real>(outSP); tp.compute(rIn.data(), rOut.data(), true, true); outTP = VectorHelpers::castVectorType<Real, UInt>(rOut); // print if (e == EPOCHS - 1) { cout << "Epoch = " << e << endl; VectorHelpers::print_vector(VectorHelpers::binaryToSparse<UInt>(outSP), ",", "SP= "); VectorHelpers::print_vector(VectorHelpers::binaryToSparse<UInt>(VectorHelpers::cellsToColumns(outTP, CELLS)), ",", "TP= "); NTA_CHECK(outSP[69] == 0) << "A value in SP computed incorrectly"; NTA_CHECK(outTP[42] == 0) << "Incorrect value in TP"; } } stopwatch.stop(); const size_t timeTotal = stopwatch.getElapsed(); const size_t CI_avg_time = 45; //sec cout << "Total elapsed time = " << timeTotal << " seconds" << endl; NTA_CHECK(timeTotal <= CI_avg_time) << //we'll see how stable the time result in CI is, if usable "HelloSPTP test slower than expected! (" << timeTotal << ",should be "<< CI_avg_time; } } //-ns
/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013-2015, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ #include <algorithm> // std::generate #include <cmath> // pow #include <ctime> // std::time #include <iostream> #include <vector> #include "nupic/algorithms/Anomaly.hpp" #include "nupic/algorithms/Cells4.hpp" //TODO use TM instead #include "nupic/algorithms/SpatialPooler.hpp" #include "nupic/os/Timer.hpp" #include "nupic/utils/VectorHelpers.hpp" #include "nupic/utils/Random.hpp" namespace examples { using namespace std; using namespace nupic; using namespace nupic::utils; using nupic::algorithms::spatial_pooler::SpatialPooler; using nupic::algorithms::Cells4::Cells4; using nupic::algorithms::anomaly::Anomaly; using nupic::algorithms::anomaly::AnomalyMode; // work-load void run() { const UInt COLS = 2048; // number of columns in SP, TP const UInt DIM_INPUT = 10000; const UInt CELLS = 10; // cells per column in TP const UInt EPOCHS = (UInt)pow(10, 3); // number of iterations (calls to SP/TP compute() ) std::cout << "starting test. DIM_INPUT=" << DIM_INPUT << ", DIM=" << COLS << ", CELLS=" << CELLS << std::endl; std::cout << "EPOCHS = " << EPOCHS << std::endl; // initialize SP, TP, Anomaly, AnomalyLikelihood SpatialPooler sp(vector<UInt>{DIM_INPUT}, vector<UInt>{COLS}); Cells4 tp(COLS, CELLS, 12, 8, 15, 5, .5f, .8f, 1.0f, .1f, .1f, 0.0f, false, 42, true, false); Anomaly an(5, AnomalyMode::LIKELIHOOD); // data for processing input vector<UInt> input(DIM_INPUT); vector<UInt> outSP(COLS); // active array, output of SP/TP vector<UInt> outTP(tp.nCells()); vector<Real> rIn(COLS); // input for TP (must be Reals) vector<Real> rOut(tp.nCells()); Real res = 0.0; //for anomaly: vector<UInt> prevPred_(outSP.size()); Random rnd; // Start a stopwatch timer printf("starting: %d iterations.", EPOCHS); Timer stopwatch(true); //run for (UInt e = 0; e < EPOCHS; e++) { generate(input.begin(), input.end(), [&] () { return rnd.getUInt32(2); }); fill(outSP.begin(), outSP.end(), 0); sp.compute(input.data(), true, outSP.data()); sp.stripUnlearnedColumns(outSP.data()); rIn = VectorHelpers::castVectorType<UInt, Real>(outSP); tp.compute(rIn.data(), rOut.data(), true, true); outTP = VectorHelpers::castVectorType<Real, UInt>(rOut); res = an.compute(outSP /*active*/, prevPred_ /*prev predicted*/); prevPred_ = outTP; //to be used as predicted T-1 cout << res << " "; // print if (e == EPOCHS - 1) { cout << "Epoch = " << e << endl; VectorHelpers::print_vector(VectorHelpers::binaryToSparse<UInt>(outSP), ",", "SP= "); VectorHelpers::print_vector(VectorHelpers::binaryToSparse<UInt>(VectorHelpers::cellsToColumns(outTP, CELLS)), ",", "TP= "); NTA_CHECK(outSP[69] == 0) << "A value in SP computed incorrectly"; NTA_CHECK(outTP[42] == 0) << "Incorrect value in TP"; } } stopwatch.stop(); const size_t timeTotal = stopwatch.getElapsed(); const size_t CI_avg_time = 45; //sec cout << "Total elapsed time = " << timeTotal << " seconds" << endl; NTA_CHECK(timeTotal <= CI_avg_time) << //we'll see how stable the time result in CI is, if usable "HelloSPTP test slower than expected! (" << timeTotal << ",should be "<< CI_avg_time; } } //-ns
add Anomaly (w likelihood) to pipeline
Hotgym: add Anomaly (w likelihood) to pipeline
C++
agpl-3.0
breznak/nupic.core,breznak/nupic.core,breznak/nupic.core,breznak/nupic.core
2d59d2f9c5ad642f1b81dc53fa2077c70f341c4d
src/gpu/GrTextureMaker.cpp
src/gpu/GrTextureMaker.cpp
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrTextureMaker.h" #include "GrColorSpaceXform.h" #include "GrContext.h" #include "GrGpu.h" #include "GrResourceProvider.h" sk_sp<GrTextureProxy> GrTextureMaker::refTextureProxyForParams(const GrSamplerState& params, SkColorSpace* dstColorSpace, sk_sp<SkColorSpace>* texColorSpace, SkScalar scaleAdjust[2]) { CopyParams copyParams; bool willBeMipped = params.filter() == GrSamplerState::Filter::kMipMap; if (!fContext->caps()->mipMapSupport()) { willBeMipped = false; } if (texColorSpace) { *texColorSpace = this->getColorSpace(dstColorSpace); } sk_sp<GrTextureProxy> original(this->refOriginalTextureProxy(willBeMipped, dstColorSpace, AllowedTexGenType::kCheap)); if (original) { if (!fContext->getGpu()->isACopyNeededForTextureParams(original.get(), params, &copyParams, scaleAdjust)) { return original; } } else { if (!fContext->getGpu()->isACopyNeededForTextureParams(this->width(), this->height(), params, &copyParams, scaleAdjust)) { return this->refOriginalTextureProxy(willBeMipped, dstColorSpace, AllowedTexGenType::kAny); } } GrSurfaceOrigin origOrigin; GrUniqueKey copyKey; this->makeCopyKey(copyParams, &copyKey, dstColorSpace); if (copyKey.isValid()) { if (original) { origOrigin = original->origin(); } else { origOrigin = kTopLeft_GrSurfaceOrigin; } sk_sp<GrTextureProxy> result(fContext->resourceProvider()->findOrCreateProxyByUniqueKey( copyKey, origOrigin)); if (result) { return result; } } sk_sp<GrTextureProxy> result; if (original) { result = CopyOnGpu(fContext, std::move(original), nullptr, copyParams, willBeMipped); } else { result = this->generateTextureProxyForParams(copyParams, willBeMipped, dstColorSpace); } if (!result) { return nullptr; } if (copyKey.isValid()) { SkASSERT(result->origin() == origOrigin); fContext->resourceProvider()->assignUniqueKeyToProxy(copyKey, result.get()); this->didCacheCopy(copyKey); } return result; } std::unique_ptr<GrFragmentProcessor> GrTextureMaker::createFragmentProcessor( const SkMatrix& textureMatrix, const SkRect& constraintRect, FilterConstraint filterConstraint, bool coordsLimitedToConstraintRect, const GrSamplerState::Filter* filterOrNullForBicubic, SkColorSpace* dstColorSpace) { const GrSamplerState::Filter* fmForDetermineDomain = filterOrNullForBicubic; if (filterOrNullForBicubic && GrSamplerState::Filter::kMipMap == *filterOrNullForBicubic && kYes_FilterConstraint == filterConstraint) { // TODo: Here we should force a copy restricted to the constraintRect since MIP maps will // read outside the constraint rect. However, as in the adjuster case, we aren't currently // doing that. // We instead we compute the domain as though were bilerping which is only correct if we // only sample level 0. static const GrSamplerState::Filter kBilerp = GrSamplerState::Filter::kBilerp; fmForDetermineDomain = &kBilerp; } GrSamplerState samplerState; if (filterOrNullForBicubic) { samplerState = GrSamplerState(GrSamplerState::WrapMode::kClamp, *filterOrNullForBicubic); } else { // Bicubic doesn't use filtering for it's texture accesses. samplerState = GrSamplerState::ClampNearest(); } sk_sp<SkColorSpace> texColorSpace; SkScalar scaleAdjust[2] = { 1.0f, 1.0f }; sk_sp<GrTextureProxy> proxy(this->refTextureProxyForParams(samplerState, dstColorSpace, &texColorSpace, scaleAdjust)); if (!proxy) { return nullptr; } SkMatrix adjustedMatrix = textureMatrix; adjustedMatrix.postScale(scaleAdjust[0], scaleAdjust[1]); SkRect domain; DomainMode domainMode = DetermineDomainMode(constraintRect, filterConstraint, coordsLimitedToConstraintRect, proxy.get(), nullptr, fmForDetermineDomain, &domain); SkASSERT(kTightCopy_DomainMode != domainMode); GrPixelConfig config = proxy->config(); auto fp = CreateFragmentProcessorForDomainAndFilter(std::move(proxy), adjustedMatrix, domainMode, domain, filterOrNullForBicubic); return GrColorSpaceXformEffect::Make(std::move(fp), texColorSpace.get(), config, dstColorSpace); } sk_sp<GrTextureProxy> GrTextureMaker::generateTextureProxyForParams(const CopyParams& copyParams, bool willBeMipped, SkColorSpace* dstColorSpace) { sk_sp<GrTextureProxy> original(this->refOriginalTextureProxy(willBeMipped, dstColorSpace, AllowedTexGenType::kAny)); if (!original) { return nullptr; } return CopyOnGpu(fContext, std::move(original), nullptr, copyParams, willBeMipped); }
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrTextureMaker.h" #include "GrColorSpaceXform.h" #include "GrContext.h" #include "GrGpu.h" #include "GrResourceProvider.h" sk_sp<GrTextureProxy> GrTextureMaker::refTextureProxyForParams(const GrSamplerState& params, SkColorSpace* dstColorSpace, sk_sp<SkColorSpace>* texColorSpace, SkScalar scaleAdjust[2]) { CopyParams copyParams; bool willBeMipped = params.filter() == GrSamplerState::Filter::kMipMap; if (!fContext->caps()->mipMapSupport()) { willBeMipped = false; } if (texColorSpace) { *texColorSpace = this->getColorSpace(dstColorSpace); } sk_sp<GrTextureProxy> original(this->refOriginalTextureProxy(willBeMipped, dstColorSpace, AllowedTexGenType::kCheap)); if (original) { if (!fContext->getGpu()->isACopyNeededForTextureParams(original.get(), params, &copyParams, scaleAdjust)) { return original; } } else { if (!fContext->getGpu()->isACopyNeededForTextureParams(this->width(), this->height(), params, &copyParams, scaleAdjust)) { return this->refOriginalTextureProxy(willBeMipped, dstColorSpace, AllowedTexGenType::kAny); } } GrSurfaceOrigin origOrigin; GrUniqueKey copyKey; this->makeCopyKey(copyParams, &copyKey, dstColorSpace); sk_sp<GrTextureProxy> cachedProxy; if (copyKey.isValid()) { if (original) { origOrigin = original->origin(); } else { origOrigin = kTopLeft_GrSurfaceOrigin; } cachedProxy = fContext->resourceProvider()->findOrCreateProxyByUniqueKey(copyKey, origOrigin); if (cachedProxy && (!willBeMipped || GrMipMapped::kYes == cachedProxy->mipMapped())) { return cachedProxy; } } sk_sp<GrTextureProxy> result; if (original) { result = std::move(original); } else if (cachedProxy) { result = cachedProxy; } else { // Since we will be copying this texture there is no reason to make it mipped result = this->refOriginalTextureProxy(false, dstColorSpace, AllowedTexGenType::kAny); } if (!result) { return nullptr; } result = CopyOnGpu(fContext, std::move(result), nullptr, copyParams, willBeMipped); if (!result) { return nullptr; } if (copyKey.isValid()) { SkASSERT(result->origin() == origOrigin); if (cachedProxy) { SkASSERT(GrMipMapped::kYes == result->mipMapped() && GrMipMapped::kNo == cachedProxy->mipMapped()); // If we had a cachedProxy, that means there already is a proxy in the cache which // matches the key, but it does not have mip levels and we require them. Thus we must // remove the unique key from that proxy. fContext->resourceProvider()->removeUniqueKeyFromProxy(copyKey, cachedProxy.get()); } fContext->resourceProvider()->assignUniqueKeyToProxy(copyKey, result.get()); this->didCacheCopy(copyKey); } return result; } std::unique_ptr<GrFragmentProcessor> GrTextureMaker::createFragmentProcessor( const SkMatrix& textureMatrix, const SkRect& constraintRect, FilterConstraint filterConstraint, bool coordsLimitedToConstraintRect, const GrSamplerState::Filter* filterOrNullForBicubic, SkColorSpace* dstColorSpace) { const GrSamplerState::Filter* fmForDetermineDomain = filterOrNullForBicubic; if (filterOrNullForBicubic && GrSamplerState::Filter::kMipMap == *filterOrNullForBicubic && kYes_FilterConstraint == filterConstraint) { // TODo: Here we should force a copy restricted to the constraintRect since MIP maps will // read outside the constraint rect. However, as in the adjuster case, we aren't currently // doing that. // We instead we compute the domain as though were bilerping which is only correct if we // only sample level 0. static const GrSamplerState::Filter kBilerp = GrSamplerState::Filter::kBilerp; fmForDetermineDomain = &kBilerp; } GrSamplerState samplerState; if (filterOrNullForBicubic) { samplerState = GrSamplerState(GrSamplerState::WrapMode::kClamp, *filterOrNullForBicubic); } else { // Bicubic doesn't use filtering for it's texture accesses. samplerState = GrSamplerState::ClampNearest(); } sk_sp<SkColorSpace> texColorSpace; SkScalar scaleAdjust[2] = { 1.0f, 1.0f }; sk_sp<GrTextureProxy> proxy(this->refTextureProxyForParams(samplerState, dstColorSpace, &texColorSpace, scaleAdjust)); if (!proxy) { return nullptr; } SkMatrix adjustedMatrix = textureMatrix; adjustedMatrix.postScale(scaleAdjust[0], scaleAdjust[1]); SkRect domain; DomainMode domainMode = DetermineDomainMode(constraintRect, filterConstraint, coordsLimitedToConstraintRect, proxy.get(), nullptr, fmForDetermineDomain, &domain); SkASSERT(kTightCopy_DomainMode != domainMode); GrPixelConfig config = proxy->config(); auto fp = CreateFragmentProcessorForDomainAndFilter(std::move(proxy), adjustedMatrix, domainMode, domain, filterOrNullForBicubic); return GrColorSpaceXformEffect::Make(std::move(fp), texColorSpace.get(), config, dstColorSpace); } sk_sp<GrTextureProxy> GrTextureMaker::generateTextureProxyForParams(const CopyParams& copyParams, bool willBeMipped, SkColorSpace* dstColorSpace) { sk_sp<GrTextureProxy> original(this->refOriginalTextureProxy(willBeMipped, dstColorSpace, AllowedTexGenType::kAny)); if (!original) { return nullptr; } return CopyOnGpu(fContext, std::move(original), nullptr, copyParams, willBeMipped); }
Update GrTextureMaker to handle mips when copying for npot
Update GrTextureMaker to handle mips when copying for npot Bug: skia: Change-Id: I4b5ea3b8fadf207aef521404c4e9205df23ef3c8 Reviewed-on: https://skia-review.googlesource.com/65900 Reviewed-by: Brian Salomon <[email protected]> Commit-Queue: Greg Daniel <[email protected]>
C++
bsd-3-clause
HalCanary/skia-hc,HalCanary/skia-hc,google/skia,google/skia,google/skia,aosp-mirror/platform_external_skia,rubenvb/skia,google/skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,google/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,rubenvb/skia,rubenvb/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,google/skia,HalCanary/skia-hc,google/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,rubenvb/skia,HalCanary/skia-hc,HalCanary/skia-hc,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,HalCanary/skia-hc,google/skia,rubenvb/skia,aosp-mirror/platform_external_skia
06158a6556bcfbb4cb45dfdf7349cadedbe6b897
src/graphics/ha_buffer.cpp
src/graphics/ha_buffer.cpp
#include "./ha_buffer.h" #include <iostream> #include <algorithm> #include "./shader_program.h" #include "./quad.h" namespace Graphics { HABuffer::HABuffer(Eigen::Vector2i size) : size(size) { } void HABuffer::initialize(Gl *gl) { this->gl = gl; quad = std::make_shared<Quad>(); quad->skipSettingUniforms = true; quad->initialize(gl); initializeShadersHash(); initializeBufferHash(); } void HABuffer::initializeShadersHash() { printf("initShaders %d %d\n", size(0), size(1)); buildShader = std::make_shared<ShaderProgram>( gl, ":shader/buildHABuffer.vert", ":shader/buildHABuffer.frag"); renderShader = std::make_shared<ShaderProgram>( gl, ":shader/renderHABuffer.vert", ":shader/renderHABuffer.frag"); clearShader = std::make_shared<ShaderProgram>( gl, ":shader/clearHABuffer.vert", ":shader/clearHABuffer.frag"); } void HABuffer::initializeBufferHash() { habufferScreenSize = std::max(size[0], size[1]); uint num_records = habufferScreenSize * habufferScreenSize * 8; habufferTableSize = std::max(habufferScreenSize, static_cast<uint>(ceil(sqrt(static_cast<float>(num_records))))); habufferNumRecords = habufferTableSize * habufferTableSize; habufferCountsSize = habufferScreenSize * habufferScreenSize + 1; printf("HA-Buffer: Screen size: %d %d\n" " # records: %d (%d x %d)\n", size.x(), size.y(), habufferNumRecords, habufferTableSize, habufferTableSize); // HA-Buffer records if (!RecordsBuffer.isInitialized()) RecordsBuffer.initialize(gl, habufferNumRecords * sizeof(uint) * 2); else RecordsBuffer.resize(habufferNumRecords * sizeof(uint) * 2); if (!CountsBuffer.isInitialized()) CountsBuffer.initialize(gl, habufferCountsSize * sizeof(uint)); else CountsBuffer.resize(habufferCountsSize * sizeof(uint)); if (!FragmentDataBuffer.isInitialized()) FragmentDataBuffer.initialize(gl, habufferNumRecords * sizeof(FragmentData)); else FragmentDataBuffer.resize(habufferNumRecords * sizeof(FragmentData)); // clear counts CountsBuffer.clear(0); gl->glMemoryBarrier(GL_ALL_BARRIER_BITS); printf("[HABuffer] Memory usage: %.2fMB", ((habufferNumRecords * sizeof(uint) * 2 + habufferNumRecords * sizeof(FragmentData) + (habufferScreenSize * habufferScreenSize + 1) * sizeof(uint)) / 1024) / 1024.0f); } void HABuffer::begin(const RenderData &renderData) { buildShader->bind(); buildShader->setUniform("u_Projection", renderData.projectionMatrix); buildShader->setUniform("u_View", renderData.viewMatrix); buildShader->setUniform("u_NumRecords", habufferNumRecords); buildShader->setUniform("u_ScreenSz", habufferScreenSize); buildShader->setUniform("u_HashSz", habufferTableSize); buildShader->setUniformAsVec2Array("u_Offsets", offsets, 512); buildShader->setUniform("u_ZNear", habufferZNear); buildShader->setUniform("u_ZFar", habufferZFar); buildShader->setUniform("Opacity", habufferOpacity); buildShader->setUniform("u_Records", RecordsBuffer); buildShader->setUniform("u_Counts", CountsBuffer); buildShader->setUniform("u_FragmentData", FragmentDataBuffer); #if !USE_TEXTURE Eigen::Matrix4f modelViewMatrixIT = modelViewMatrix.inverse().transpose(); buildShader->setUniform("u_ModelView_IT", modelViewMatrixIT); #endif glAssert(gl->glDisable(GL_CULL_FACE)); glAssert(gl->glDisable(GL_DEPTH_TEST)); } bool HABuffer::end() { #if 1 glAssert(gl->glMemoryBarrier(GL_ALL_BARRIER_BITS)); #endif glAssert(gl->glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT)); uint numInserted = 1; CountsBuffer.getData(&numInserted, sizeof(uint), CountsBuffer.getSize() - sizeof(uint)); bool overflow = false; if (numInserted >= habufferNumRecords) { overflow = true; printf("Frame was interrupted: %u\n", numInserted); } else if (numInserted > habufferNumRecords * 0.8) { printf("inserted %u / %u\n", numInserted, habufferNumRecords); } displayStatistics("after render"); return overflow; } void HABuffer::render() { renderShader->bind(); Eigen::Matrix4f identity = Eigen::Matrix4f::Identity(); renderShader->setUniform("u_Projection", identity); renderShader->setUniform("u_View", identity); renderShader->setUniform("u_Model", identity); renderShader->setUniform("u_ScreenSz", habufferScreenSize); renderShader->setUniform("u_HashSz", habufferTableSize); renderShader->setUniformAsVec2Array("u_Offsets", offsets, 512); renderShader->setUniform("u_Records", RecordsBuffer); renderShader->setUniform("u_Counts", CountsBuffer); renderShader->setUniform("u_FragmentData", FragmentDataBuffer); // Ensure that all global memory write are done before resolving glAssert(gl->glMemoryBarrier(GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV)); glAssert(gl->glDepthMask(GL_FALSE)); glAssert(gl->glDisable(GL_DEPTH_TEST)); quad->setShaderProgram(renderShader); quad->render(gl, RenderData()); glAssert(gl->glDepthMask(GL_TRUE)); glAssert(gl->glEnable(GL_DEPTH_TEST)); // TODO(SIRK): print timing /* float tm_threshold = TIMING_THRESHOLD; float cleartime = g_TmClear.waitResult(); float buildtime = g_TmBuild.waitResult(); float rendertime = g_TmRender.waitResult(); if (cleartime > tm_threshold || buildtime > tm_threshold || rendertime > tm_threshold) { printf("Clear time %lf ms\n", cleartime); printf("Build time %lf ms\n", buildtime); printf("Render time %lf ms\n", rendertime); } */ } void HABuffer::clear() { for (int i = 0; i < 512; i++) { offsets[i] = rand() ^ (rand() << 8) ^ (rand() << 16); offsets[i] = offsets[i] % habufferTableSize; } clearShader->bind(); clearShader->setUniform("u_NumRecords", habufferNumRecords); clearShader->setUniform("u_ScreenSz", habufferScreenSize); clearShader->setUniform("u_Records", RecordsBuffer); clearShader->setUniform("u_Counts", CountsBuffer); // Render the full screen quad quad->setShaderProgram(clearShader); quad->render(gl, RenderData()); // Ensure that all global memory write are done before starting to render glAssert(gl->glMemoryBarrier(GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV)); } void HABuffer::displayStatistics(const char *label) { uint *lcounts = new uint[habufferCountsSize]; CountsBuffer.getData(lcounts, CountsBuffer.getSize()); int avgdepth = 0; int num = 0; for (uint c = 0; c < habufferCountsSize - 1; c++) { if (lcounts[c] > 0) { num++; avgdepth += lcounts[c]; } } if (num == 0) num = 1; double rec_percentage = lcounts[habufferCountsSize - 1] / static_cast<double>(habufferNumRecords) * 100.0; if (rec_percentage > 80.0) { std::cerr << label << " habufferCountsSize:" << habufferCountsSize << "<avg:" << avgdepth / static_cast<float>(num) << " max: " << lcounts[habufferCountsSize - 1] << "/" << habufferNumRecords << "(" << rec_percentage << "% " << '>' << std::endl; } delete[] lcounts; } } // namespace Graphics
#include "./ha_buffer.h" #include <iostream> #include <algorithm> #include "./shader_program.h" #include "./quad.h" namespace Graphics { HABuffer::HABuffer(Eigen::Vector2i size) : size(size) { } void HABuffer::initialize(Gl *gl) { this->gl = gl; quad = std::make_shared<Quad>(); quad->skipSettingUniforms = true; quad->initialize(gl); initializeShadersHash(); initializeBufferHash(); } void HABuffer::initializeShadersHash() { printf("initShaders %d %d\n", size(0), size(1)); buildShader = std::make_shared<ShaderProgram>( gl, ":shader/buildHABuffer.vert", ":shader/buildHABuffer.frag"); renderShader = std::make_shared<ShaderProgram>( gl, ":shader/renderHABuffer.vert", ":shader/renderHABuffer.frag"); clearShader = std::make_shared<ShaderProgram>( gl, ":shader/clearHABuffer.vert", ":shader/clearHABuffer.frag"); } void HABuffer::initializeBufferHash() { habufferScreenSize = std::max(size[0], size[1]); uint num_records = habufferScreenSize * habufferScreenSize * 8; habufferTableSize = std::max(habufferScreenSize, static_cast<uint>(ceil(sqrt(static_cast<float>(num_records))))); habufferNumRecords = habufferTableSize * habufferTableSize; habufferCountsSize = habufferScreenSize * habufferScreenSize + 1; printf("HA-Buffer: Screen size: %d %d\n" " # records: %d (%d x %d)\n", size.x(), size.y(), habufferNumRecords, habufferTableSize, habufferTableSize); // HA-Buffer records if (!RecordsBuffer.isInitialized()) RecordsBuffer.initialize(gl, habufferNumRecords * sizeof(uint) * 2); else RecordsBuffer.resize(habufferNumRecords * sizeof(uint) * 2); if (!CountsBuffer.isInitialized()) CountsBuffer.initialize(gl, habufferCountsSize * sizeof(uint)); else CountsBuffer.resize(habufferCountsSize * sizeof(uint)); if (!FragmentDataBuffer.isInitialized()) FragmentDataBuffer.initialize(gl, habufferNumRecords * sizeof(FragmentData)); else FragmentDataBuffer.resize(habufferNumRecords * sizeof(FragmentData)); // clear counts CountsBuffer.clear(0); gl->glMemoryBarrier(GL_ALL_BARRIER_BITS); printf("[HABuffer] Memory usage: %.2fMB", ((habufferNumRecords * sizeof(uint) * 2 + habufferNumRecords * sizeof(FragmentData) + (habufferScreenSize * habufferScreenSize + 1) * sizeof(uint)) / 1024) / 1024.0f); } void HABuffer::begin(const RenderData &renderData) { buildShader->bind(); buildShader->setUniform("u_Projection", renderData.projectionMatrix); buildShader->setUniform("u_View", renderData.viewMatrix); buildShader->setUniform("u_NumRecords", habufferNumRecords); buildShader->setUniform("u_ScreenSz", habufferScreenSize); buildShader->setUniform("u_HashSz", habufferTableSize); buildShader->setUniformAsVec2Array("u_Offsets", offsets, 512); buildShader->setUniform("u_ZNear", habufferZNear); buildShader->setUniform("u_ZFar", habufferZFar); buildShader->setUniform("Opacity", habufferOpacity); buildShader->setUniform("u_Records", RecordsBuffer); buildShader->setUniform("u_Counts", CountsBuffer); buildShader->setUniform("u_FragmentData", FragmentDataBuffer); glAssert(gl->glDisable(GL_CULL_FACE)); glAssert(gl->glDisable(GL_DEPTH_TEST)); } bool HABuffer::end() { #if 1 glAssert(gl->glMemoryBarrier(GL_ALL_BARRIER_BITS)); #endif glAssert(gl->glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT)); uint numInserted = 1; CountsBuffer.getData(&numInserted, sizeof(uint), CountsBuffer.getSize() - sizeof(uint)); bool overflow = false; if (numInserted >= habufferNumRecords) { overflow = true; printf("Frame was interrupted: %u\n", numInserted); } else if (numInserted > habufferNumRecords * 0.8) { printf("inserted %u / %u\n", numInserted, habufferNumRecords); } displayStatistics("after render"); return overflow; } void HABuffer::render() { renderShader->bind(); Eigen::Matrix4f identity = Eigen::Matrix4f::Identity(); renderShader->setUniform("u_Projection", identity); renderShader->setUniform("u_View", identity); renderShader->setUniform("u_Model", identity); renderShader->setUniform("u_ScreenSz", habufferScreenSize); renderShader->setUniform("u_HashSz", habufferTableSize); renderShader->setUniformAsVec2Array("u_Offsets", offsets, 512); renderShader->setUniform("u_Records", RecordsBuffer); renderShader->setUniform("u_Counts", CountsBuffer); renderShader->setUniform("u_FragmentData", FragmentDataBuffer); // Ensure that all global memory write are done before resolving glAssert(gl->glMemoryBarrier(GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV)); glAssert(gl->glDepthMask(GL_FALSE)); glAssert(gl->glDisable(GL_DEPTH_TEST)); quad->setShaderProgram(renderShader); quad->render(gl, RenderData()); glAssert(gl->glDepthMask(GL_TRUE)); glAssert(gl->glEnable(GL_DEPTH_TEST)); // TODO(SIRK): print timing /* float tm_threshold = TIMING_THRESHOLD; float cleartime = g_TmClear.waitResult(); float buildtime = g_TmBuild.waitResult(); float rendertime = g_TmRender.waitResult(); if (cleartime > tm_threshold || buildtime > tm_threshold || rendertime > tm_threshold) { printf("Clear time %lf ms\n", cleartime); printf("Build time %lf ms\n", buildtime); printf("Render time %lf ms\n", rendertime); } */ } void HABuffer::clear() { for (int i = 0; i < 512; i++) { offsets[i] = rand() ^ (rand() << 8) ^ (rand() << 16); offsets[i] = offsets[i] % habufferTableSize; } clearShader->bind(); clearShader->setUniform("u_NumRecords", habufferNumRecords); clearShader->setUniform("u_ScreenSz", habufferScreenSize); clearShader->setUniform("u_Records", RecordsBuffer); clearShader->setUniform("u_Counts", CountsBuffer); // Render the full screen quad quad->setShaderProgram(clearShader); quad->render(gl, RenderData()); // Ensure that all global memory write are done before starting to render glAssert(gl->glMemoryBarrier(GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV)); } void HABuffer::displayStatistics(const char *label) { uint *lcounts = new uint[habufferCountsSize]; CountsBuffer.getData(lcounts, CountsBuffer.getSize()); int avgdepth = 0; int num = 0; for (uint c = 0; c < habufferCountsSize - 1; c++) { if (lcounts[c] > 0) { num++; avgdepth += lcounts[c]; } } if (num == 0) num = 1; double rec_percentage = lcounts[habufferCountsSize - 1] / static_cast<double>(habufferNumRecords) * 100.0; if (rec_percentage > 80.0) { std::cerr << label << " habufferCountsSize:" << habufferCountsSize << "<avg:" << avgdepth / static_cast<float>(num) << " max: " << lcounts[habufferCountsSize - 1] << "/" << habufferNumRecords << "(" << rec_percentage << "% " << '>' << std::endl; } delete[] lcounts; } } // namespace Graphics
Remove unused code.
Remove unused code.
C++
mit
Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller
48226b4b6c3629d4ff8d4a67ff926076942b5c80
src/hdf5/DimensionHDF5.cpp
src/hdf5/DimensionHDF5.cpp
// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix/util/util.hpp> #include <nix/hdf5/DimensionHDF5.hpp> #include <nix/hdf5/DataSet.hpp> using namespace std; namespace nix { namespace hdf5 { DimensionType dimensionTypeFromStr(const string &str) { if (str == "set") { return DimensionType::Set; } else if (str == "range") { return DimensionType::Range; } else if (str == "sample") { return DimensionType::Sample; } else { throw runtime_error("Not a valid dimension name"); } } std::string dimensionTypeToStr(DimensionType dim) { //The way this switch + string.empty() checking is // done here might seem a bit convoluted, but the // idea behind it is: // a) have no default case in the switch to get a // compile warning in case a new element is // added to the enum // b) still be safe and throw an exception in case // not all enum cases are handled properly std::string dimType; switch (dim) { case DimensionType::Set: dimType = "set"; break; case DimensionType::Range: dimType = "range"; break; case DimensionType::Sample: dimType = "sample"; break; } if (dimType.empty()) { throw runtime_error("Not a valid dimension type"); } return dimType; } // Implementation of Dimension DimensionHDF5::DimensionHDF5(Group group, size_t id) : group(group), dim_id(id) { } DimensionHDF5::DimensionHDF5(const DimensionHDF5 &other) : group(other.group), dim_id(other.dim_id) { } void DimensionHDF5::setType() { group.setAttr("dimension_type", dimensionTypeToStr(dimensionType())); } void DimensionHDF5::swap(DimensionHDF5 &other) { using std::swap; swap(group, other.group); swap(dim_id, other.dim_id); } bool DimensionHDF5::operator==(const DimensionHDF5 &other) const { return group == other.group; } bool DimensionHDF5::operator!=(const DimensionHDF5 &other) const { return !(*this == other); } DimensionHDF5::~DimensionHDF5() {} //-------------------------------------------------------------- // Implementation of SampledDimension //-------------------------------------------------------------- SampledDimensionHDF5::SampledDimensionHDF5(Group group, size_t id, double _samplingInterval) : DimensionHDF5(group, id) { setType(); samplingInterval(_samplingInterval); } SampledDimensionHDF5::SampledDimensionHDF5(const SampledDimensionHDF5 &other) : DimensionHDF5(other.group, other.dim_id) { setType(); samplingInterval(other.samplingInterval()); } DimensionType SampledDimensionHDF5::dimensionType() const { return DimensionType::Sample; } boost::optional<std::string> SampledDimensionHDF5::label() const { boost::optional<std::string> ret; string label; bool have_attr = group.getAttr("label", label); if (have_attr) { ret = label; } return ret; } void SampledDimensionHDF5::label(const string &label) { if(label.empty()) { throw EmptyString("label"); } else { group.setAttr("label", label); // NOTE: forceUpdatedAt() not possible since not reachable from here } } void SampledDimensionHDF5::label(const none_t t) { if(group.hasAttr("label")) { group.removeAttr("label"); } // NOTE: forceUpdatedAt() not possible since not reachable from here } boost::optional<std::string> SampledDimensionHDF5::unit() const { boost::optional<std::string> ret; string unit; bool have_attr = group.getAttr("unit", unit); if (have_attr) { ret = unit; } return ret; } void SampledDimensionHDF5::unit(const string &unit) { if(unit.empty()) { throw EmptyString("unit"); } else { group.setAttr("unit", unit); // NOTE: forceUpdatedAt() not possible since not reachable from here } } void SampledDimensionHDF5::unit(const none_t t) { if(group.hasAttr("unit")) { group.removeAttr("unit"); } // NOTE: forceUpdatedAt() not possible since not reachable from here } double SampledDimensionHDF5::samplingInterval() const { double sampling_interval; if(group.hasAttr("sampling_interval")) { group.getAttr("sampling_interval", sampling_interval); return sampling_interval; } else { throw MissingAttr("sampling_interval"); } } void SampledDimensionHDF5::samplingInterval(double sampling_interval) { group.setAttr("sampling_interval", sampling_interval); } boost::optional<double> SampledDimensionHDF5::offset() const { boost::optional<double> ret; double offset = 0; if(group.getAttr("offset", offset)) { ret = offset; } return ret; } void SampledDimensionHDF5::offset(double offset) { group.setAttr("offset", offset); } void SampledDimensionHDF5::offset(const none_t t) { if(group.hasAttr("offset")) { group.removeAttr("offset"); } } SampledDimensionHDF5& SampledDimensionHDF5::operator=(const SampledDimensionHDF5 &other) { SampledDimensionHDF5 tmp(other); swap(tmp); return *this; } SampledDimensionHDF5::~SampledDimensionHDF5() {} //-------------------------------------------------------------- // Implementation of SetDimensionHDF5 //-------------------------------------------------------------- SetDimensionHDF5::SetDimensionHDF5(Group group, size_t id) : DimensionHDF5(group, id) { setType(); } SetDimensionHDF5::SetDimensionHDF5(const SetDimensionHDF5 &other) : DimensionHDF5(other.group, other.dim_id) { setType(); } DimensionType SetDimensionHDF5::dimensionType() const { return DimensionType::Set; } vector<string> SetDimensionHDF5::labels() const { vector<string> labels; group.getData("labels", labels); return labels; } void SetDimensionHDF5::labels(const vector<string> &labels) { group.setData("labels", labels); } void SetDimensionHDF5::labels(const none_t t) { if(group.hasAttr("offset")) { group.removeAttr("offset"); } } SetDimensionHDF5& SetDimensionHDF5::operator=(const SetDimensionHDF5 &other) { SetDimensionHDF5 tmp(other); swap(tmp); return *this; } SetDimensionHDF5::~SetDimensionHDF5() {} //-------------------------------------------------------------- // Implementation of RangeDimensionHDF5 //-------------------------------------------------------------- RangeDimensionHDF5::RangeDimensionHDF5(Group group, size_t id, vector<double> _ticks) : DimensionHDF5(group, id) { setType(); ticks(_ticks); } RangeDimensionHDF5::RangeDimensionHDF5(const RangeDimensionHDF5 &other) : DimensionHDF5(other.group, other.dim_id) { setType(); ticks(other.ticks()); } DimensionType RangeDimensionHDF5::dimensionType() const { return DimensionType::Range; } boost::optional<std::string> RangeDimensionHDF5::label() const { boost::optional<std::string> ret; string label; group.getAttr("label", label); ret = label; return ret; } void RangeDimensionHDF5::label(const string &label) { if(label.empty()) { throw EmptyString("label"); } else { group.setAttr("label", label); // NOTE: forceUpdatedAt() not possible since not reachable from here } } void RangeDimensionHDF5::label(const none_t t) { if(group.hasAttr("label")) { group.removeAttr("label"); } // NOTE: forceUpdatedAt() not possible since not reachable from here } boost::optional<std::string> RangeDimensionHDF5::unit() const { boost::optional<std::string> ret; string unit; bool have_attr = group.getAttr("unit", unit); if (have_attr) { ret = unit; } return ret; } void RangeDimensionHDF5::unit(const string &unit) { if(unit.empty()) { throw EmptyString("unit"); } else { group.setAttr("unit", unit); // NOTE: forceUpdatedAt() not possible since not reachable from here } } void RangeDimensionHDF5::unit(const none_t t) { if(group.hasAttr("unit")) { group.removeAttr("unit"); } // NOTE: forceUpdatedAt() not possible since not reachable from here } RangeDimensionHDF5& RangeDimensionHDF5::operator=(const RangeDimensionHDF5 &other) { RangeDimensionHDF5 tmp(other); swap(tmp); return *this; } vector<double> RangeDimensionHDF5::ticks() const { vector<double> ticks; if(group.hasData("ticks")) { group.getData("ticks", ticks); return ticks; } else { throw MissingAttr("ticks"); } } void RangeDimensionHDF5::ticks(const vector<double> &ticks) { group.setData("ticks", ticks); } RangeDimensionHDF5::~RangeDimensionHDF5() {} } // namespace hdf5 } // namespace nix
// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix/util/util.hpp> #include <nix/hdf5/DimensionHDF5.hpp> #include <nix/hdf5/DataSet.hpp> using namespace std; namespace nix { namespace hdf5 { DimensionType dimensionTypeFromStr(const string &str) { if (str == "set") { return DimensionType::Set; } else if (str == "range") { return DimensionType::Range; } else if (str == "sample") { return DimensionType::Sample; } else { throw runtime_error("Not a valid dimension name"); } } std::string dimensionTypeToStr(DimensionType dim) { //The way this switch + string.empty() checking is // done here might seem a bit convoluted, but the // idea behind it is: // a) have no default case in the switch to get a // compile warning in case a new element is // added to the enum // b) still be safe and throw an exception in case // not all enum cases are handled properly std::string dimType; switch (dim) { case DimensionType::Set: dimType = "set"; break; case DimensionType::Range: dimType = "range"; break; case DimensionType::Sample: dimType = "sample"; break; } if (dimType.empty()) { throw runtime_error("Not a valid dimension type"); } return dimType; } // Implementation of Dimension DimensionHDF5::DimensionHDF5(Group group, size_t id) : group(group), dim_id(id) { } DimensionHDF5::DimensionHDF5(const DimensionHDF5 &other) : group(other.group), dim_id(other.dim_id) { } void DimensionHDF5::setType() { group.setAttr("dimension_type", dimensionTypeToStr(dimensionType())); } void DimensionHDF5::swap(DimensionHDF5 &other) { using std::swap; swap(group, other.group); swap(dim_id, other.dim_id); } bool DimensionHDF5::operator==(const DimensionHDF5 &other) const { return group == other.group; } bool DimensionHDF5::operator!=(const DimensionHDF5 &other) const { return !(*this == other); } DimensionHDF5::~DimensionHDF5() {} //-------------------------------------------------------------- // Implementation of SampledDimension //-------------------------------------------------------------- SampledDimensionHDF5::SampledDimensionHDF5(Group group, size_t id, double _samplingInterval) : DimensionHDF5(group, id) { setType(); samplingInterval(_samplingInterval); } SampledDimensionHDF5::SampledDimensionHDF5(const SampledDimensionHDF5 &other) : DimensionHDF5(other.group, other.dim_id) { setType(); samplingInterval(other.samplingInterval()); } DimensionType SampledDimensionHDF5::dimensionType() const { return DimensionType::Sample; } boost::optional<std::string> SampledDimensionHDF5::label() const { boost::optional<std::string> ret; string label; bool have_attr = group.getAttr("label", label); if (have_attr) { ret = label; } return ret; } void SampledDimensionHDF5::label(const string &label) { if(label.empty()) { throw EmptyString("label"); } else { group.setAttr("label", label); // NOTE: forceUpdatedAt() not possible since not reachable from here } } void SampledDimensionHDF5::label(const none_t t) { if(group.hasAttr("label")) { group.removeAttr("label"); } // NOTE: forceUpdatedAt() not possible since not reachable from here } boost::optional<std::string> SampledDimensionHDF5::unit() const { boost::optional<std::string> ret; string unit; bool have_attr = group.getAttr("unit", unit); if (have_attr) { ret = unit; } return ret; } void SampledDimensionHDF5::unit(const string &unit) { if(unit.empty()) { throw EmptyString("unit"); } else { group.setAttr("unit", unit); // NOTE: forceUpdatedAt() not possible since not reachable from here } } void SampledDimensionHDF5::unit(const none_t t) { if(group.hasAttr("unit")) { group.removeAttr("unit"); } // NOTE: forceUpdatedAt() not possible since not reachable from here } double SampledDimensionHDF5::samplingInterval() const { double sampling_interval; if(group.hasAttr("sampling_interval")) { group.getAttr("sampling_interval", sampling_interval); return sampling_interval; } else { throw MissingAttr("sampling_interval"); } } void SampledDimensionHDF5::samplingInterval(double sampling_interval) { group.setAttr("sampling_interval", sampling_interval); } boost::optional<double> SampledDimensionHDF5::offset() const { boost::optional<double> ret; double offset = 0; if(group.getAttr("offset", offset)) { ret = offset; } return ret; } void SampledDimensionHDF5::offset(double offset) { group.setAttr("offset", offset); } void SampledDimensionHDF5::offset(const none_t t) { if(group.hasAttr("offset")) { group.removeAttr("offset"); } } SampledDimensionHDF5& SampledDimensionHDF5::operator=(const SampledDimensionHDF5 &other) { SampledDimensionHDF5 tmp(other); swap(tmp); return *this; } SampledDimensionHDF5::~SampledDimensionHDF5() {} //-------------------------------------------------------------- // Implementation of SetDimensionHDF5 //-------------------------------------------------------------- SetDimensionHDF5::SetDimensionHDF5(Group group, size_t id) : DimensionHDF5(group, id) { setType(); } SetDimensionHDF5::SetDimensionHDF5(const SetDimensionHDF5 &other) : DimensionHDF5(other.group, other.dim_id) { setType(); } DimensionType SetDimensionHDF5::dimensionType() const { return DimensionType::Set; } vector<string> SetDimensionHDF5::labels() const { vector<string> labels; group.getData("labels", labels); return labels; } void SetDimensionHDF5::labels(const vector<string> &labels) { group.setData("labels", labels); } void SetDimensionHDF5::labels(const none_t t) { if(group.hasAttr("offset")) { group.removeAttr("offset"); } } SetDimensionHDF5& SetDimensionHDF5::operator=(const SetDimensionHDF5 &other) { SetDimensionHDF5 tmp(other); swap(tmp); return *this; } SetDimensionHDF5::~SetDimensionHDF5() {} //-------------------------------------------------------------- // Implementation of RangeDimensionHDF5 //-------------------------------------------------------------- RangeDimensionHDF5::RangeDimensionHDF5(Group group, size_t id, vector<double> _ticks) : DimensionHDF5(group, id) { setType(); ticks(_ticks); } RangeDimensionHDF5::RangeDimensionHDF5(const RangeDimensionHDF5 &other) : DimensionHDF5(other.group, other.dim_id) { setType(); ticks(other.ticks()); } DimensionType RangeDimensionHDF5::dimensionType() const { return DimensionType::Range; } boost::optional<std::string> RangeDimensionHDF5::label() const { boost::optional<std::string> ret; string label; bool have_attr = group.getAttr("label", label); if (have_attr) { ret = label; } return ret; } void RangeDimensionHDF5::label(const string &label) { if(label.empty()) { throw EmptyString("label"); } else { group.setAttr("label", label); // NOTE: forceUpdatedAt() not possible since not reachable from here } } void RangeDimensionHDF5::label(const none_t t) { if(group.hasAttr("label")) { group.removeAttr("label"); } // NOTE: forceUpdatedAt() not possible since not reachable from here } boost::optional<std::string> RangeDimensionHDF5::unit() const { boost::optional<std::string> ret; string unit; bool have_attr = group.getAttr("unit", unit); if (have_attr) { ret = unit; } return ret; } void RangeDimensionHDF5::unit(const string &unit) { if(unit.empty()) { throw EmptyString("unit"); } else { group.setAttr("unit", unit); // NOTE: forceUpdatedAt() not possible since not reachable from here } } void RangeDimensionHDF5::unit(const none_t t) { if(group.hasAttr("unit")) { group.removeAttr("unit"); } // NOTE: forceUpdatedAt() not possible since not reachable from here } RangeDimensionHDF5& RangeDimensionHDF5::operator=(const RangeDimensionHDF5 &other) { RangeDimensionHDF5 tmp(other); swap(tmp); return *this; } vector<double> RangeDimensionHDF5::ticks() const { vector<double> ticks; if(group.hasData("ticks")) { group.getData("ticks", ticks); return ticks; } else { throw MissingAttr("ticks"); } } void RangeDimensionHDF5::ticks(const vector<double> &ticks) { group.setData("ticks", ticks); } RangeDimensionHDF5::~RangeDimensionHDF5() {} } // namespace hdf5 } // namespace nix
fix returning none if it is not there
[h5] RangeDimension::label: fix returning none if it is not there
C++
bsd-3-clause
stoewer/nix
733fb02e602b0a6cf2b94caf225ab7cf5e46babe
src/http/messageheader.cpp
src/http/messageheader.cpp
/* * Copyright (C) 2009 by Marc Boris Duerner, Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cxxtools/http/messageheader.h> #include <cxxtools/clock.h> #include <cxxtools/log.h> #include <cctype> #include <sstream> #include <stdio.h> #include <string.h> log_define("cxxtools.http.messageheader") namespace cxxtools { namespace http { namespace { int compareIgnoreCase(const char* s1, const char* s2) { const char* it1 = s1; const char* it2 = s2; while (*it1 && *it2) { if (*it1 != *it2) { char c1 = std::toupper(*it1); char c2 = std::toupper(*it2); if (c1 < c2) return -1; else if (c2 < c1) return 1; } ++it1; ++it2; } return *it1 ? 1 : *it2 ? -1 : 0; } } const char* MessageHeader::getHeader(const char* key) const { for (const_iterator it = begin(); it != end(); ++it) { if (compareIgnoreCase(key, it->first) == 0) return it->second; } return 0; } bool MessageHeader::isHeaderValue(const char* key, const char* value) const { const char* h = getHeader(key); if (h == 0) return false; return compareIgnoreCase(h, value) == 0; } void MessageHeader::clear() { _rawdata[0] = _rawdata[1] = '\0'; _endOffset = 0; _httpVersionMajor = 1; _httpVersionMinor = 1; } void MessageHeader::setHeader(const char* key, const char* value, bool replace) { log_debug("setHeader(\"" << key << "\", \"" << value << "\", " << replace << ')'); if (!*key) throw std::runtime_error("empty key not allowed in messageheader"); if (replace) removeHeader(key); char* p = eptr(); size_t lk = strlen(key); // length of key size_t lv = strlen(value); // length of value if (p - _rawdata + lk + lv + 2 > MAXHEADERSIZE) throw std::runtime_error("message header too big"); std::strcpy(p, key); // copy key p += lk + 1; std::strcpy(p, value); // copy value p[lv + 1] = '\0'; // put new message end marker in place _endOffset = (p + lv + 1) - _rawdata; } void MessageHeader::removeHeader(const char* key) { if (!*key) throw std::runtime_error("empty key not allowed in messageheader"); char* p = eptr(); const_iterator it = begin(); while (it != end()) { if (compareIgnoreCase(key, it->first) == 0) { unsigned slen = it->second - it->first + std::strlen(it->second) + 1; std::memcpy( const_cast<char*>(it->first), it->first + slen, p - it->first + slen); p -= slen; it.fixup(); } else ++it; } _endOffset = p - _rawdata; } bool MessageHeader::chunkedTransferEncoding() const { return isHeaderValue("Transfer-Encoding", "chunked"); } std::size_t MessageHeader::contentLength() const { const char* s = getHeader("Content-Length"); if (s == 0) return 0; std::size_t size = 0; while (*s >= '0' && *s <= '9') size = size * 10 + (*s++ - '0'); return size; } bool MessageHeader::keepAlive() const { const char* ch = getHeader("Connection"); if (ch == 0) return httpVersionMajor() == 1 && httpVersionMinor() >= 1; else return compareIgnoreCase(ch, "keep-alive") == 0; } char* MessageHeader::htdateCurrent(char* buffer) { int year = 0; unsigned month = 0; unsigned day = 0; unsigned hour = 0; unsigned min = 0; unsigned sec = 0; unsigned msec = 0; DateTime dt = Clock::getSystemTime(); dt.get(year, month, day, hour, min, sec, msec); unsigned dayOfWeek = dt.date().dayOfWeek(); static const char* wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; static const char* monthn[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; sprintf(buffer, "%s, %02d %s %d %02d:%02d:%02d GMT", wday[dayOfWeek], day, monthn[month-1], year, hour, min, sec); return buffer; } } // namespace http } // namespace cxxtools
/* * Copyright (C) 2009 by Marc Boris Duerner, Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cxxtools/http/messageheader.h> #include <cxxtools/clock.h> #include <cxxtools/log.h> #include <cctype> #include <sstream> #include <stdio.h> #include <string.h> log_define("cxxtools.http.messageheader") namespace cxxtools { namespace http { namespace { int compareIgnoreCase(const char* s1, const char* s2) { const char* it1 = s1; const char* it2 = s2; while (*it1 && *it2) { if (*it1 != *it2) { char c1 = std::toupper(*it1); char c2 = std::toupper(*it2); if (c1 < c2) return -1; else if (c2 < c1) return 1; } ++it1; ++it2; } return *it1 ? 1 : *it2 ? -1 : 0; } } const char* MessageHeader::getHeader(const char* key) const { for (const_iterator it = begin(); it != end(); ++it) { if (compareIgnoreCase(key, it->first) == 0) return it->second; } return 0; } bool MessageHeader::isHeaderValue(const char* key, const char* value) const { const char* h = getHeader(key); if (h == 0) return false; return compareIgnoreCase(h, value) == 0; } void MessageHeader::clear() { _rawdata[0] = _rawdata[1] = '\0'; _endOffset = 0; _httpVersionMajor = 1; _httpVersionMinor = 1; } void MessageHeader::setHeader(const char* key, const char* value, bool replace) { log_debug("setHeader(\"" << key << "\", \"" << value << "\", " << replace << ')'); if (!*key) throw std::runtime_error("empty key not allowed in messageheader"); if (replace) removeHeader(key); char* p = eptr(); size_t lk = strlen(key); // length of key size_t lv = strlen(value); // length of value if (p - _rawdata + lk + lv + 2 > MAXHEADERSIZE) throw std::runtime_error("message header too big"); std::strcpy(p, key); // copy key p += lk + 1; std::strcpy(p, value); // copy value p[lv + 1] = '\0'; // put new message end marker in place _endOffset = (p + lv + 1) - _rawdata; } void MessageHeader::removeHeader(const char* key) { if (!*key) throw std::runtime_error("empty key not allowed in messageheader"); char* p = eptr(); const_iterator it = begin(); while (it != end()) { if (compareIgnoreCase(key, it->first) == 0) { unsigned slen = it->second - it->first + std::strlen(it->second) + 1; std::memmove( const_cast<char*>(it->first), it->first + slen, p - it->first + slen); p -= slen; it.fixup(); } else ++it; } _endOffset = p - _rawdata; } bool MessageHeader::chunkedTransferEncoding() const { return isHeaderValue("Transfer-Encoding", "chunked"); } std::size_t MessageHeader::contentLength() const { const char* s = getHeader("Content-Length"); if (s == 0) return 0; std::size_t size = 0; while (*s >= '0' && *s <= '9') size = size * 10 + (*s++ - '0'); return size; } bool MessageHeader::keepAlive() const { const char* ch = getHeader("Connection"); if (ch == 0) return httpVersionMajor() == 1 && httpVersionMinor() >= 1; else return compareIgnoreCase(ch, "keep-alive") == 0; } char* MessageHeader::htdateCurrent(char* buffer) { int year = 0; unsigned month = 0; unsigned day = 0; unsigned hour = 0; unsigned min = 0; unsigned sec = 0; unsigned msec = 0; DateTime dt = Clock::getSystemTime(); dt.get(year, month, day, hour, min, sec, msec); unsigned dayOfWeek = dt.date().dayOfWeek(); static const char* wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; static const char* monthn[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; sprintf(buffer, "%s, %02d %s %d %02d:%02d:%02d GMT", wday[dayOfWeek], day, monthn[month-1], year, hour, min, sec); return buffer; } } // namespace http } // namespace cxxtools
use memmove instead of memcpy when removing message header since the areas may overlap
use memmove instead of memcpy when removing message header since the areas may overlap
C++
lgpl-2.1
maekitalo/cxxtools,maekitalo/cxxtools,maekitalo/cxxtools,OlafRadicke/cxxtools,maekitalo/cxxtools,OlafRadicke/cxxtools,OlafRadicke/cxxtools,OlafRadicke/cxxtools
005c6fa43fdc1b27fb72ba6c2a58465af300d98d
src/input/psp/joystick.cpp
src/input/psp/joystick.cpp
#ifdef MINPSPW #include "joystick.h" void PSPJoystick::poll(){ sceCtrlPeekBufferPositive(&joystick, 1); } JoystickInput PSPJoystick::readAll(){ JoystickInput input; if(joystick.Buttons != 0){ // WIIMOTE for now, we can add in nunchuck and classic later if(joystick.Buttons & PSP_CTRL_START){ //input.button7 = true; } else if(joystick.Buttons & PSP_CTRL_SELECT){ //input.button8 = true; } else if(joystick.Buttons & PSP_CTRL_SQUARE){ input.button1 = true; } else if(joystick.Buttons & PSP_CTRL_CROSS){ input.button2 = true; } else if(joystick.Buttons & PSP_CTRL_TRIANGLE){ input.button3 = true; } else if(joystick.Buttons & PSP_CTRL_CIRCLE){ input.button4 = true; } else if(joystick.Buttons & PSP_CTRL_RTRIGGER){ } else if(joystick.Buttons & PSP_CTRL_LTRIGGER){ } else if(joystick.Buttons & PSP_CTRL_LEFT){ input.left = true; } else if(joystick.Buttons & PSP_CTRL_RIGHT){ input.right = true; } else if(joystick.Buttons & PSP_CTRL_DOWN){ input.down = true; } else if(joystick.Buttons & PSP_CTRL_UP){ input.up = true; } } return input; } PSPJoystick::~PSPJoystick(){ // no cleanup required } PSPJoystick::PSPJoystick(){ sceCtrlSetSamplingCycle(0); sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG); } #endif
#ifdef MINPSPW #include "joystick.h" void PSPJoystick::poll(){ sceCtrlPeekBufferPositive(&joystick, 1); } JoystickInput PSPJoystick::readAll(){ JoystickInput input; if(joystick.Buttons != 0){ if(joystick.Buttons & PSP_CTRL_START){ //input.button7 = true; } else if(joystick.Buttons & PSP_CTRL_SELECT){ //input.button8 = true; } else if(joystick.Buttons & PSP_CTRL_SQUARE){ input.button1 = true; } else if(joystick.Buttons & PSP_CTRL_CROSS){ input.button2 = true; } else if(joystick.Buttons & PSP_CTRL_TRIANGLE){ input.button3 = true; } else if(joystick.Buttons & PSP_CTRL_CIRCLE){ input.button4 = true; } else if(joystick.Buttons & PSP_CTRL_RTRIGGER){ } else if(joystick.Buttons & PSP_CTRL_LTRIGGER){ } else if(joystick.Buttons & PSP_CTRL_LEFT){ input.left = true; } else if(joystick.Buttons & PSP_CTRL_RIGHT){ input.right = true; } else if(joystick.Buttons & PSP_CTRL_DOWN){ input.down = true; } else if(joystick.Buttons & PSP_CTRL_UP){ input.up = true; } } return input; } PSPJoystick::~PSPJoystick(){ // no cleanup required } PSPJoystick::PSPJoystick(){ sceCtrlSetSamplingCycle(0); sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG); } #endif
Remove comment.
Remove comment.
C++
bsd-3-clause
scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown
8f4476b893b498684fa236ce2727f56319dc8ae9
paddle/operators/fetch_op.cc
paddle/operators/fetch_op.cc
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/framework/feed_fetch_type.h" #include "paddle/framework/op_registry.h" namespace paddle { namespace operators { class FetchOp : public framework::OperatorBase { public: FetchOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorBase(type, inputs, outputs, attrs) {} void Run(const framework::Scope &scope, const platform::DeviceContext &dev_ctx) const override { auto fetch_var_name = Input("X"); auto *fetch_var = scope.FindVar(fetch_var_name); PADDLE_ENFORCE(fetch_var != nullptr, "Cannot find fetch variable in scope, fetch_var_name is %s", fetch_var_name); auto out_name = this->Output("Out"); auto *out_var = scope.FindVar(out_name); PADDLE_ENFORCE(out_var != nullptr, "Cannot find out_var in scope, out_var_name is %s", out_name); auto col = static_cast<size_t>(Attr<int>("col")); auto *fetch_list = out_var->GetMutable<framework::FeedFetchList>(); auto &src_item = fetch_var->Get<framework::FeedFetchType>(); if (col >= fetch_list->size()) { fetch_list->resize(col + 1); } auto &dst_item = fetch_list->at(col); // FIXME(yuyang18): Should we assume the fetch operator always generate // CPU outputs? dst_item.CopyFrom(src_item, platform::CPUPlace(), dev_ctx); dst_item.set_lod(src_item.lod()); VLOG(3) << "Fetch variable " << fetch_var_name << " to " << out_name; } }; class FetchOpInfoMaker : public framework::OpProtoAndCheckerMaker { public: FetchOpInfoMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("X", "The input of fetch op"); AddOutput("Out", "The output of fetch op"); AddComment("fetch op, it should not be configured by users directly"); AddAttr<int>("col", "column of fetch"); } }; } // namespace operators } // namespace paddle REGISTER_OPERATOR(fetch, paddle::operators::FetchOp, paddle::framework::EmptyGradOpMaker, paddle::operators::FetchOpInfoMaker);
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/framework/feed_fetch_type.h" #include "paddle/framework/op_registry.h" namespace paddle { namespace operators { class FetchOp : public framework::OperatorBase { public: FetchOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorBase(type, inputs, outputs, attrs) {} void Run(const framework::Scope &scope, const platform::DeviceContext &dev_ctx) const override { auto fetch_var_name = Input("X"); auto *fetch_var = scope.FindVar(fetch_var_name); PADDLE_ENFORCE(fetch_var != nullptr, "Cannot find fetch variable in scope, fetch_var_name is %s", fetch_var_name); auto out_name = this->Output("Out"); auto *out_var = scope.FindVar(out_name); PADDLE_ENFORCE(out_var != nullptr, "Cannot find out_var in scope, out_var_name is %s", out_name); auto col = static_cast<size_t>(Attr<int>("col")); auto *fetch_list = out_var->GetMutable<framework::FeedFetchList>(); auto &src_item = fetch_var->Get<framework::FeedFetchType>(); if (col >= fetch_list->size()) { fetch_list->resize(col + 1); } auto &dst_item = fetch_list->at(col); // FIXME(yuyang18): Should we assume the fetch operator always generate // CPU outputs? dst_item.CopyFrom(src_item, platform::CPUPlace(), dev_ctx); dev_ctx.Wait(); dst_item.set_lod(src_item.lod()); VLOG(3) << "Fetch variable " << fetch_var_name << " to " << out_name; } }; class FetchOpInfoMaker : public framework::OpProtoAndCheckerMaker { public: FetchOpInfoMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("X", "The input of fetch op"); AddOutput("Out", "The output of fetch op"); AddComment("fetch op, it should not be configured by users directly"); AddAttr<int>("col", "column of fetch"); } }; } // namespace operators } // namespace paddle REGISTER_OPERATOR(fetch, paddle::operators::FetchOp, paddle::framework::EmptyGradOpMaker, paddle::operators::FetchOpInfoMaker);
Add device.Wait() in fetch_op (#5141)
Add device.Wait() in fetch_op (#5141)
C++
apache-2.0
QiJune/Paddle,jacquesqiao/Paddle,pengli09/Paddle,tensor-tang/Paddle,putcn/Paddle,pkuyym/Paddle,lcy-seso/Paddle,pkuyym/Paddle,PaddlePaddle/Paddle,Canpio/Paddle,jacquesqiao/Paddle,lcy-seso/Paddle,reyoung/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,chengduoZH/Paddle,pengli09/Paddle,pkuyym/Paddle,putcn/Paddle,pkuyym/Paddle,Canpio/Paddle,chengduoZH/Paddle,putcn/Paddle,baidu/Paddle,pkuyym/Paddle,Canpio/Paddle,pengli09/Paddle,chengduoZH/Paddle,luotao1/Paddle,tensor-tang/Paddle,Canpio/Paddle,tensor-tang/Paddle,QiJune/Paddle,QiJune/Paddle,reyoung/Paddle,jacquesqiao/Paddle,Canpio/Paddle,baidu/Paddle,luotao1/Paddle,lcy-seso/Paddle,QiJune/Paddle,Canpio/Paddle,reyoung/Paddle,Canpio/Paddle,jacquesqiao/Paddle,luotao1/Paddle,tensor-tang/Paddle,pengli09/Paddle,PaddlePaddle/Paddle,jacquesqiao/Paddle,tensor-tang/Paddle,pkuyym/Paddle,baidu/Paddle,reyoung/Paddle,reyoung/Paddle,reyoung/Paddle,chengduoZH/Paddle,pengli09/Paddle,chengduoZH/Paddle,luotao1/Paddle,Canpio/Paddle,pengli09/Paddle,jacquesqiao/Paddle,baidu/Paddle,lcy-seso/Paddle,QiJune/Paddle,luotao1/Paddle,baidu/Paddle,putcn/Paddle,lcy-seso/Paddle,putcn/Paddle,pengli09/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,putcn/Paddle,QiJune/Paddle,pengli09/Paddle,lcy-seso/Paddle
720f5bc85339a3e920d4232151409d2cb778e4fb
examples/fit-model.cpp
examples/fit-model.cpp
/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: examples/fit-model.cpp * * Copyright 2016 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "eos/core/Image.hpp" #include "eos/core/Image_opencv_interop.hpp" #include "eos/core/Landmark.hpp" #include "eos/core/LandmarkMapper.hpp" #include "eos/core/read_pts_landmarks.hpp" #include "eos/fitting/fitting.hpp" #include "eos/morphablemodel/Blendshape.hpp" #include "eos/morphablemodel/MorphableModel.hpp" #include "eos/render/draw_utils.hpp" #include "eos/render/texture_extraction.hpp" #include "eos/cpp17/optional.hpp" #include "Eigen/Core" #include "boost/filesystem.hpp" #include "boost/program_options.hpp" #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <string> #include <vector> using namespace eos; namespace po = boost::program_options; namespace fs = boost::filesystem; using eos::core::Landmark; using eos::core::LandmarkCollection; using cv::Mat; using std::cout; using std::endl; using std::string; using std::vector; /** * This app demonstrates estimation of the camera and fitting of the shape * model of a 3D Morphable Model from an ibug LFPW image with its landmarks. * In addition to fit-model-simple, this example uses blendshapes, contour- * fitting, and can iterate the fitting. * * 68 ibug landmarks are loaded from the .pts file and converted * to vertex indices using the LandmarkMapper. */ int main(int argc, char* argv[]) { string modelfile, isomapfile, imagefile, landmarksfile, mappingsfile, contourfile, edgetopologyfile, blendshapesfile, outputbasename; try { po::options_description desc("Allowed options"); // clang-format off desc.add_options() ("help,h", "display the help message") ("model,m", po::value<string>(&modelfile)->required()->default_value("../share/sfm_shape_3448.bin"), "a Morphable Model stored as cereal BinaryArchive") ("image,i", po::value<string>(&imagefile)->required()->default_value("data/image_0010.png"), "an input image") ("landmarks,l", po::value<string>(&landmarksfile)->required()->default_value("data/image_0010.pts"), "2D landmarks for the image, in ibug .pts format") ("mapping,p", po::value<string>(&mappingsfile)->required()->default_value("../share/ibug_to_sfm.txt"), "landmark identifier to model vertex number mapping") ("model-contour,c", po::value<string>(&contourfile)->required()->default_value("../share/sfm_model_contours.json"), "file with model contour indices") ("edge-topology,e", po::value<string>(&edgetopologyfile)->required()->default_value("../share/sfm_3448_edge_topology.json"), "file with model's precomputed edge topology") ("blendshapes,b", po::value<string>(&blendshapesfile)->required()->default_value("../share/expression_blendshapes_3448.bin"), "file with blendshapes") ("output,o", po::value<string>(&outputbasename)->required()->default_value("out"), "basename for the output rendering and obj files"); // clang-format on po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); if (vm.count("help")) { cout << "Usage: fit-model [options]" << endl; cout << desc; return EXIT_SUCCESS; } po::notify(vm); } catch (const po::error& e) { cout << "Error while parsing command-line arguments: " << e.what() << endl; cout << "Use --help to display a list of options." << endl; return EXIT_FAILURE; } // Load the image, landmarks, LandmarkMapper and the Morphable Model: Mat image = cv::imread(imagefile); LandmarkCollection<Eigen::Vector2f> landmarks; try { landmarks = core::read_pts_landmarks(landmarksfile); } catch (const std::runtime_error& e) { cout << "Error reading the landmarks: " << e.what() << endl; return EXIT_FAILURE; } morphablemodel::MorphableModel morphable_model; try { morphable_model = morphablemodel::load_model(modelfile); } catch (const std::runtime_error& e) { cout << "Error loading the Morphable Model: " << e.what() << endl; return EXIT_FAILURE; } // The landmark mapper is used to map 2D landmark points (e.g. from the ibug scheme) to vertex ids: core::LandmarkMapper landmark_mapper; try { landmark_mapper = core::LandmarkMapper(mappingsfile); } catch (const std::exception& e) { cout << "Error loading the landmark mappings: " << e.what() << endl; return EXIT_FAILURE; } // The expression blendshapes: const vector<morphablemodel::Blendshape> blendshapes = morphablemodel::load_blendshapes(blendshapesfile); morphablemodel::MorphableModel morphable_model_with_expressions(morphable_model.get_shape_model(), blendshapes, morphable_model.get_color_model(), morphable_model.get_texture_coordinates()); // These two are used to fit the front-facing contour to the ibug contour landmarks: const fitting::ModelContour model_contour = contourfile.empty() ? fitting::ModelContour() : fitting::ModelContour::load(contourfile); const fitting::ContourLandmarks ibug_contour = fitting::ContourLandmarks::load(mappingsfile); // The edge topology is used to speed up computation of the occluding face contour fitting: const morphablemodel::EdgeTopology edge_topology = morphablemodel::load_edge_topology(edgetopologyfile); // Draw the loaded landmarks: Mat outimg = image.clone(); for (auto&& lm : landmarks) { cv::rectangle(outimg, cv::Point2f(lm.coordinates[0] - 2.0f, lm.coordinates[1] - 2.0f), cv::Point2f(lm.coordinates[0] + 2.0f, lm.coordinates[1] + 2.0f), {255, 0, 0}); } // Fit the model, get back a mesh and the pose: core::Mesh mesh; fitting::RenderingParameters rendering_params; std::tie(mesh, rendering_params) = fitting::fit_shape_and_pose( morphable_model_with_expressions, landmarks, landmark_mapper, image.cols, image.rows, edge_topology, ibug_contour, model_contour, 5, cpp17::nullopt, 30.0f); // The 3D head pose can be recovered as follows: float yaw_angle = glm::degrees(glm::yaw(rendering_params.get_rotation())); // and similarly for pitch and roll. // Extract the texture from the image using given mesh and camera parameters: const Eigen::Matrix<float, 3, 4> affine_from_ortho = fitting::get_3x4_affine_camera_matrix(rendering_params, image.cols, image.rows); const core::Image4u isomap = render::extract_texture(mesh, affine_from_ortho, core::from_mat(image), true); // Draw the fitted mesh as wireframe, and save the image: render::draw_wireframe(outimg, mesh, rendering_params.get_modelview(), rendering_params.get_projection(), fitting::get_opencv_viewport(image.cols, image.rows)); fs::path outputfile = outputbasename + ".png"; cv::imwrite(outputfile.string(), outimg); // Save the mesh as textured obj: outputfile.replace_extension(".obj"); core::write_textured_obj(mesh, outputfile.string()); // And save the isomap: outputfile.replace_extension(".isomap.png"); cv::imwrite(outputfile.string(), core::to_mat(isomap)); cout << "Finished fitting and wrote result mesh and isomap to files with basename " << outputfile.stem().stem() << "." << endl; return EXIT_SUCCESS; }
/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: examples/fit-model.cpp * * Copyright 2016 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "eos/core/Image.hpp" #include "eos/core/Image_opencv_interop.hpp" #include "eos/core/Landmark.hpp" #include "eos/core/LandmarkMapper.hpp" #include "eos/core/read_pts_landmarks.hpp" #include "eos/fitting/fitting.hpp" #include "eos/morphablemodel/Blendshape.hpp" #include "eos/morphablemodel/MorphableModel.hpp" #include "eos/render/draw_utils.hpp" #include "eos/render/texture_extraction.hpp" #include "eos/cpp17/optional.hpp" #include "Eigen/Core" #include "boost/filesystem.hpp" #include "boost/program_options.hpp" #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <string> #include <vector> using namespace eos; namespace po = boost::program_options; namespace fs = boost::filesystem; using eos::core::Landmark; using eos::core::LandmarkCollection; using cv::Mat; using std::cout; using std::endl; using std::string; using std::vector; /** * This app demonstrates estimation of the camera and fitting of the shape * model of a 3D Morphable Model from an ibug LFPW image with its landmarks. * In addition to fit-model-simple, this example uses blendshapes, contour- * fitting, and can iterate the fitting. * * 68 ibug landmarks are loaded from the .pts file and converted * to vertex indices using the LandmarkMapper. */ int main(int argc, char* argv[]) { string modelfile, isomapfile, imagefile, landmarksfile, mappingsfile, contourfile, edgetopologyfile, blendshapesfile, outputbasename; try { po::options_description desc("Allowed options"); // clang-format off desc.add_options() ("help,h", "display the help message") ("model,m", po::value<string>(&modelfile)->required()->default_value("../share/sfm_shape_3448.bin"), "a Morphable Model stored as cereal BinaryArchive") ("image,i", po::value<string>(&imagefile)->required()->default_value("data/image_0010.png"), "an input image") ("landmarks,l", po::value<string>(&landmarksfile)->required()->default_value("data/image_0010.pts"), "2D landmarks for the image, in ibug .pts format") ("mapping,p", po::value<string>(&mappingsfile)->required()->default_value("../share/ibug_to_sfm.txt"), "landmark identifier to model vertex number mapping") ("model-contour,c", po::value<string>(&contourfile)->required()->default_value("../share/sfm_model_contours.json"), "file with model contour indices") ("edge-topology,e", po::value<string>(&edgetopologyfile)->required()->default_value("../share/sfm_3448_edge_topology.json"), "file with model's precomputed edge topology") ("blendshapes,b", po::value<string>(&blendshapesfile)->required()->default_value("../share/expression_blendshapes_3448.bin"), "file with blendshapes") ("output,o", po::value<string>(&outputbasename)->required()->default_value("out"), "basename for the output rendering and obj files"); // clang-format on po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); if (vm.count("help")) { cout << "Usage: fit-model [options]" << endl; cout << desc; return EXIT_SUCCESS; } po::notify(vm); } catch (const po::error& e) { cout << "Error while parsing command-line arguments: " << e.what() << endl; cout << "Use --help to display a list of options." << endl; return EXIT_FAILURE; } // Load the image, landmarks, LandmarkMapper and the Morphable Model: Mat image = cv::imread(imagefile); LandmarkCollection<Eigen::Vector2f> landmarks; try { landmarks = core::read_pts_landmarks(landmarksfile); } catch (const std::runtime_error& e) { cout << "Error reading the landmarks: " << e.what() << endl; return EXIT_FAILURE; } morphablemodel::MorphableModel morphable_model; try { morphable_model = morphablemodel::load_model(modelfile); } catch (const std::runtime_error& e) { cout << "Error loading the Morphable Model: " << e.what() << endl; return EXIT_FAILURE; } // The landmark mapper is used to map 2D landmark points (e.g. from the ibug scheme) to vertex ids: core::LandmarkMapper landmark_mapper; try { landmark_mapper = core::LandmarkMapper(mappingsfile); } catch (const std::exception& e) { cout << "Error loading the landmark mappings: " << e.what() << endl; return EXIT_FAILURE; } // The expression blendshapes: const vector<morphablemodel::Blendshape> blendshapes = morphablemodel::load_blendshapes(blendshapesfile); morphablemodel::MorphableModel morphable_model_with_expressions( morphable_model.get_shape_model(), blendshapes, morphable_model.get_color_model(), cpp17::nullopt, morphable_model.get_texture_coordinates()); // These two are used to fit the front-facing contour to the ibug contour landmarks: const fitting::ModelContour model_contour = contourfile.empty() ? fitting::ModelContour() : fitting::ModelContour::load(contourfile); const fitting::ContourLandmarks ibug_contour = fitting::ContourLandmarks::load(mappingsfile); // The edge topology is used to speed up computation of the occluding face contour fitting: const morphablemodel::EdgeTopology edge_topology = morphablemodel::load_edge_topology(edgetopologyfile); // Draw the loaded landmarks: Mat outimg = image.clone(); for (auto&& lm : landmarks) { cv::rectangle(outimg, cv::Point2f(lm.coordinates[0] - 2.0f, lm.coordinates[1] - 2.0f), cv::Point2f(lm.coordinates[0] + 2.0f, lm.coordinates[1] + 2.0f), {255, 0, 0}); } // Fit the model, get back a mesh and the pose: core::Mesh mesh; fitting::RenderingParameters rendering_params; std::tie(mesh, rendering_params) = fitting::fit_shape_and_pose( morphable_model_with_expressions, landmarks, landmark_mapper, image.cols, image.rows, edge_topology, ibug_contour, model_contour, 5, cpp17::nullopt, 30.0f); // The 3D head pose can be recovered as follows: float yaw_angle = glm::degrees(glm::yaw(rendering_params.get_rotation())); // and similarly for pitch and roll. // Extract the texture from the image using given mesh and camera parameters: const Eigen::Matrix<float, 3, 4> affine_from_ortho = fitting::get_3x4_affine_camera_matrix(rendering_params, image.cols, image.rows); const core::Image4u isomap = render::extract_texture(mesh, affine_from_ortho, core::from_mat(image), true); // Draw the fitted mesh as wireframe, and save the image: render::draw_wireframe(outimg, mesh, rendering_params.get_modelview(), rendering_params.get_projection(), fitting::get_opencv_viewport(image.cols, image.rows)); fs::path outputfile = outputbasename + ".png"; cv::imwrite(outputfile.string(), outimg); // Save the mesh as textured obj: outputfile.replace_extension(".obj"); core::write_textured_obj(mesh, outputfile.string()); // And save the isomap: outputfile.replace_extension(".isomap.png"); cv::imwrite(outputfile.string(), core::to_mat(isomap)); cout << "Finished fitting and wrote result mesh and isomap to files with basename " << outputfile.stem().stem() << "." << endl; return EXIT_SUCCESS; }
Add nullopt for landmark_definitions to fix compile error in fit-model
Add nullopt for landmark_definitions to fix compile error in fit-model
C++
apache-2.0
patrikhuber/eos,patrikhuber/eos,patrikhuber/eos
524cc8efc4083151682bcd219537473cc330f067
devel/filestore.C
devel/filestore.C
#define BLOCKSIZE 16384 // supports files up to (BLOCKSIZE-260)/20 * BLOCKSIZE/20 * BLOCKSIZE // currently: 10815307776 bytes #include <chord.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <stdio.h> #include <dhash.h> #include <dhash_common.h> #include <dhashclient.h> dhashclient *dhash; int inflight = 0; FILE *outfile; // utility functions ---------------------------------- chordID compute_hash(char *buf, int len) { char hashbytes[sha1::hashsize]; chordID ID; sha1_hash (hashbytes, buf, len); mpz_set_rawmag_be (&ID, hashbytes, sizeof (hashbytes)); // For big endian return ID; } void insert_cb(dhash_stat s, ptr<insert_info>) { if(s != DHASH_OK) warn << "bad store\n"; inflight--; if(inflight == 0) exit(0); } chordID write_block(char *buf, int len) { chordID ID = compute_hash(buf, len); dhash->insert (ID, buf, len, wrap(&insert_cb)); inflight++; return ID; } // indirect block ----------------------------------- struct indirect { vec<chordID> hs; indirect *parent; void add_hash(chordID h) { hs.push_back(h); if(full()) { // write out indirect block write_out(); } } virtual void print(char *buf, int l) { if(len() > l) { warnx << len() << "\n"; fatal("buf too small\n"); } for(unsigned int i=0; i<hs.size(); i++) { mpz_get_raw (buf, sha1::hashsize, &hs[i]); buf += sha1::hashsize; } } chordID write_out(void) { chordID ID; char buf[BLOCKSIZE]; if(len() == 0) return 0; // xxx bug for max-sized file? print(buf, BLOCKSIZE); warnx << "len " << len() << "\n"; ID = write_block(buf, len()); clear(); if(parent) { warnx << "p\n"; parent->add_hash(ID); } return ID; } void clear(void) { hs.clear(); } virtual int len(void) { return hs.size() * sha1::hashsize; } bool full(void) { return (len() + sha1::hashsize) > BLOCKSIZE; } indirect(indirect *p) : parent(p) {} virtual ~indirect() {} }; // inode block ------------------------------------- struct inode : indirect { char filename[256]; int filelen; static const int extralen = sizeof(inode::filename) + sizeof(inode::filelen); inode(char *aname, int alen) : indirect(NULL) { strncpy(filename, aname, sizeof(filename)); filelen = alen; } int len(void) { return indirect::len() + extralen; } void print(char *buf, int l) { if(len() > l) { warnx << len() << "\n"; fatal("buf too small\n"); } memcpy(buf, filename, sizeof(filename)); buf += sizeof(filename); memcpy(buf, &filelen, sizeof(filelen)); buf += sizeof(filelen); indirect::print(buf, l - extralen); } void write_out(void) { warnx << indirect::write_out() << "\n"; } }; // callback for printing out inode info -------------------------- void list_cb(dhash_stat st, ptr<dhash_block> bl, vec<chordID> vc) { if(st != DHASH_OK) fatal("lost inode\n"); str fns(bl->data, 256); char filename[256]; strcpy(filename, fns); int filelen; memcpy(&filelen, bl->data+256, sizeof(filelen)); warnx << filename << ": " << filelen << " bytes\n"; exit(0); } // a chain of callbacks for retrieving indirect and file data blocks, // to retrieve the file ---------------------------------------------- void gotblock_cb(int len, dhash_stat st, ptr<dhash_block> bl, vec<chordID> vc) { if(st != DHASH_OK) { warnx << "at " << len; fatal(" lost block\n"); } if(fseek(outfile, len, SEEK_SET) != 0) fatal("fseek failure\n"); if(fwrite(bl->data, 1, bl->len, outfile) != bl->len) fatal("write failure\n"); inflight--; if(inflight == 0) exit(0); } void gotindirect_cb(int len, dhash_stat st, ptr<dhash_block> bl, vec<chordID> vc) { if(st != DHASH_OK) { warnx << "at " << len; fatal(" lost indirect\n"); } char *buf = bl->data; chordID ID; for(unsigned int i=0; i<bl->len; i+=20) { mpz_set_rawmag_be (&ID, buf+i, sha1::hashsize); // For big endian dhash->retrieve(ID, wrap(&gotblock_cb, len+BLOCKSIZE*i/20)); warnx << "retrieve " << ID << "\n"; inflight++; } } void gotinode_cb(dhash_stat st, ptr<dhash_block> bl, vec<chordID> vc) { if(st != DHASH_OK) fatal("lost inode\n"); str fns(bl->data, 256); char filename[256]; strcpy(filename, fns); int filelen; memcpy(&filelen, bl->data+256, sizeof(filelen)); outfile = fopen(filename, "w"); if(outfile == NULL) fatal("can't open file for writing\n"); char *buf = bl->data+inode::extralen; chordID ID; for(unsigned int i=0; i<(bl->len-inode::extralen); i+=20) { mpz_set_rawmag_be(&ID, buf+i, sha1::hashsize); // For big endian dhash->retrieve(ID, wrap(&gotindirect_cb, (BLOCKSIZE/20)*BLOCKSIZE*i/20)); warnx << "retrieve " << ID << "\n"; } } void store(char *name) { struct stat st; if(stat(name, &st) == -1) fatal("couldn't stat file\n"); inode n(name, st.st_size); FILE *f = fopen(name, "r"); if(f == NULL) fatal("couldn't open file\n"); char buf[BLOCKSIZE]; int len; indirect in(&n); chordID ID; do { len = fread(buf, 1, BLOCKSIZE, f); warnx << "len " << len << "\n"; ID = write_block(buf, len); in.add_hash(ID); } while(len == BLOCKSIZE); in.write_out(); n.write_out(); } int main(int argc, char *argv[]) { if(argc != 4) fatal("filestore [sockname] -[fls] [filename/hash]\n"); dhash = New dhashclient(argv[1]); chordID ID; char *cmd = argv[2]; char *name = argv[3]; if(!strcmp(cmd, "-s")) { // store store(name); } else if(!strcmp(cmd, "-l")) { // list str2chordID(name, ID); dhash->retrieve(ID, wrap(&list_cb)); } else if(!strcmp(cmd, "-f")) { // retrieve str2chordID(name, ID); dhash->retrieve(ID, wrap(&gotinode_cb)); warnx << "retrieve " << ID << "\n"; } else { fatal("filestore [sockname] -[fls] [filename/hash]\n"); } amain(); return 0; }
#define BLOCKSIZE 16384 // supports files up to (BLOCKSIZE-260)/20 * BLOCKSIZE/20 * BLOCKSIZE // currently: 10815307776 bytes #include <chord.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <stdio.h> #include <dhash.h> #include <dhash_common.h> #include <dhashclient.h> dhashclient *dhash; int inflight = 0; FILE *outfile; // utility functions ---------------------------------- chordID compute_hash(char *buf, int len) { char hashbytes[sha1::hashsize]; chordID ID; sha1_hash (hashbytes, buf, len); mpz_set_rawmag_be (&ID, hashbytes, sizeof (hashbytes)); // For big endian return ID; } void insert_cb(dhash_stat s, ptr<insert_info>) { if(s != DHASH_OK) warn << "bad store\n"; inflight--; if(inflight == 0) exit(0); } chordID write_block(char *buf, int len) { chordID ID = compute_hash(buf, len); dhash->insert (ID, buf, len, wrap(&insert_cb)); inflight++; return ID; } // indirect block ----------------------------------- struct indirect { vec<chordID> hs; indirect *parent; void add_hash(chordID h) { hs.push_back(h); if(full()) { // write out indirect block write_out(); } } virtual void print(char *buf, int l) { if(len() > l) { warnx << len() << "\n"; fatal("buf too small\n"); } for(unsigned int i=0; i<hs.size(); i++) { mpz_get_raw (buf, sha1::hashsize, &hs[i]); buf += sha1::hashsize; } } chordID write_out(void) { chordID ID; char buf[BLOCKSIZE]; if(len() == 0) return 0; // xxx bug for max-sized file? print(buf, BLOCKSIZE); warnx << "len " << len() << "\n"; ID = write_block(buf, len()); clear(); if(parent) { warnx << "p\n"; parent->add_hash(ID); } return ID; } void clear(void) { hs.clear(); } virtual int len(void) { return hs.size() * sha1::hashsize; } bool full(void) { return (len() + sha1::hashsize) > BLOCKSIZE; } indirect(indirect *p) : parent(p) {} virtual ~indirect() {} }; // inode block ------------------------------------- struct inode : indirect { char filename[256]; int filelen; int extralen; inode(char *aname, int alen) : indirect(NULL) { strncpy(filename, aname, sizeof(filename)); filelen = alen; extralen = sizeof(filename) + sizeof(filelen); } int len(void) { return indirect::len() + extralen; } void print(char *buf, int l) { if(len() > l) { warnx << len() << "\n"; fatal("buf too small\n"); } memcpy(buf, filename, sizeof(filename)); buf += sizeof(filename); memcpy(buf, &filelen, sizeof(filelen)); buf += sizeof(filelen); indirect::print(buf, l - extralen); } void write_out(void) { warnx << indirect::write_out() << "\n"; } }; // callback for printing out inode info -------------------------- void list_cb(dhash_stat st, ptr<dhash_block> bl, vec<chordID> vc) { if(st != DHASH_OK) fatal("lost inode\n"); str fns(bl->data, 256); char filename[256]; strcpy(filename, fns); int filelen; memcpy(&filelen, bl->data+256, sizeof(filelen)); warnx << filename << ": " << filelen << " bytes\n"; exit(0); } // a chain of callbacks for retrieving indirect and file data blocks, // to retrieve the file ---------------------------------------------- void gotblock_cb(int len, dhash_stat st, ptr<dhash_block> bl, vec<chordID> vc) { if(st != DHASH_OK) { warnx << "at " << len; fatal(" lost block\n"); } if(fseek(outfile, len, SEEK_SET) != 0) fatal("fseek failure\n"); if(fwrite(bl->data, 1, bl->len, outfile) != bl->len) fatal("write failure\n"); inflight--; if(inflight == 0) exit(0); } void gotindirect_cb(int len, dhash_stat st, ptr<dhash_block> bl, vec<chordID> vc) { if(st != DHASH_OK) { warnx << "at " << len; fatal(" lost indirect\n"); } char *buf = bl->data; chordID ID; for(unsigned int i=0; i<bl->len; i+=20) { mpz_set_rawmag_be (&ID, buf+i, sha1::hashsize); // For big endian dhash->retrieve(ID, wrap(&gotblock_cb, len+BLOCKSIZE*i/20)); warnx << "retrieve " << ID << "\n"; inflight++; } } void gotinode_cb(dhash_stat st, ptr<dhash_block> bl, vec<chordID> vc) { if(st != DHASH_OK) fatal("lost inode\n"); str fns(bl->data, 256); char filename[256]; strcpy(filename, fns); int filelen; memcpy(&filelen, bl->data+256, sizeof(filelen)); outfile = fopen(filename, "w"); if(outfile == NULL) fatal("can't open file for writing\n"); char *buf = bl->data+260; chordID ID; for(unsigned int i=0; i<(bl->len-260); i+=20) { mpz_set_rawmag_be(&ID, buf+i, sha1::hashsize); // For big endian dhash->retrieve(ID, wrap(&gotindirect_cb, (BLOCKSIZE/20)*BLOCKSIZE*i/20)); warnx << "retrieve " << ID << "\n"; } } void store(char *name) { struct stat st; if(stat(name, &st) == -1) fatal("couldn't stat file\n"); inode n(name, st.st_size); FILE *f = fopen(name, "r"); if(f == NULL) fatal("couldn't open file\n"); char buf[BLOCKSIZE]; int len; indirect in(&n); chordID ID; do { len = fread(buf, 1, BLOCKSIZE, f); warnx << "len " << len << "\n"; ID = write_block(buf, len); in.add_hash(ID); } while(len == BLOCKSIZE); in.write_out(); n.write_out(); } int main(int argc, char *argv[]) { if(argc != 4) fatal("filestore [sockname] -[fls] [filename/hash]\n"); dhash = New dhashclient(argv[1]); chordID ID; char *cmd = argv[2]; char *name = argv[3]; if(!strcmp(cmd, "-s")) { // store store(name); } else if(!strcmp(cmd, "-l")) { // list str2chordID(name, ID); dhash->retrieve(ID, wrap(&list_cb)); } else if(!strcmp(cmd, "-f")) { // retrieve str2chordID(name, ID); dhash->retrieve(ID, wrap(&gotinode_cb)); warnx << "retrieve " << ID << "\n"; } else { fatal("filestore [sockname] -[fls] [filename/hash]\n"); } amain(); return 0; }
fix to build with newer gcc
fix to build with newer gcc
C++
mit
sit/dht,weidezhang/dht,weidezhang/dht,sit/dht,weidezhang/dht,sit/dht,sit/dht,weidezhang/dht,weidezhang/dht,sit/dht
0b22203c77c4d9d4482a858367b35129b7455674
src/backend/catalog/manager.cpp
src/backend/catalog/manager.cpp
//===----------------------------------------------------------------------===// // // PelotonDB // // manager.cpp // // Identification: src/backend/catalog/manager.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cassert> #include "backend/catalog/manager.h" #include "backend/storage/database.h" #include "backend/storage/data_table.h" namespace peloton { namespace catalog { Manager &Manager::GetInstance() { static Manager manager; return manager; } //===--------------------------------------------------------------------===// // OBJECT MAP //===--------------------------------------------------------------------===// void Manager::SetTileGroup(const oid_t oid, storage::TileGroup *location) { { std::lock_guard<std::mutex> lock(locator_mutex); locator.insert(std::pair<oid_t, storage::TileGroup *>(oid, location)); } } storage::TileGroup *Manager::GetTileGroup(const oid_t oid) { storage::TileGroup *location = nullptr; { std::lock_guard<std::mutex> lock(locator_mutex); location = locator.at(oid); } return location; } //used for logging test void Manager::ClearTileGroup(){ { std::lock_guard<std::mutex> lock(locator_mutex); locator.clear(); } } //===--------------------------------------------------------------------===// // DATABASE //===--------------------------------------------------------------------===// void Manager::AddDatabase(storage::Database *database) { { std::lock_guard<std::mutex> lock(catalog_mutex); databases.push_back(database); } } storage::Database *Manager::GetDatabaseWithOid(const oid_t database_oid) const { for (auto database : databases) if (database->GetOid() == database_oid) return database; return nullptr; } void Manager::DropDatabaseWithOid(const oid_t database_oid) { { std::lock_guard<std::mutex> lock(catalog_mutex); oid_t database_offset = 0; for (auto database : databases) { if (database->GetOid() == database_oid) { delete database; break; } database_offset++; } assert(database_offset < databases.size()); // Drop the database databases.erase(databases.begin() + database_offset); } } storage::Database *Manager::GetDatabase(const oid_t database_offset) const { assert(database_offset < databases.size()); auto database = databases.at(database_offset); return database; } oid_t Manager::GetDatabaseCount() const { return databases.size(); } //===--------------------------------------------------------------------===// // CONVENIENCE WRAPPERS //===--------------------------------------------------------------------===// storage::DataTable *Manager::GetTableWithOid(const oid_t database_oid, const oid_t table_oid) const { // Lookup DB auto database = GetDatabaseWithOid(database_oid); // Lookup table if (database != nullptr) { auto table = database->GetTableWithOid(table_oid); return table; } return nullptr; } storage::DataTable *Manager::GetTableWithName( const oid_t database_oid, const std::string table_name) const { // Lookup DB auto database = GetDatabaseWithOid(database_oid); // Lookup table if (database != nullptr) { auto table = database->GetTableWithName(table_name); return table; } return nullptr; } index::Index *Manager::GetIndexWithOid(const oid_t database_oid, const oid_t table_oid, const oid_t index_oid) const { // Lookup table auto table = GetTableWithOid(database_oid, table_oid); // Lookup index if (table != nullptr) { auto index = table->GetIndexWithOid(index_oid); return index; } return nullptr; } } // End catalog namespace } // End peloton namespace
//===----------------------------------------------------------------------===// // // PelotonDB // // manager.cpp // // Identification: src/backend/catalog/manager.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cassert> #include "backend/catalog/manager.h" #include "backend/storage/database.h" #include "backend/storage/data_table.h" namespace peloton { namespace catalog { Manager &Manager::GetInstance() { static Manager manager; return manager; } //===--------------------------------------------------------------------===// // OBJECT MAP //===--------------------------------------------------------------------===// void Manager::SetTileGroup(const oid_t oid, storage::TileGroup *location) { { std::lock_guard<std::mutex> lock(locator_mutex); locator.insert(std::pair<oid_t, storage::TileGroup *>(oid, location)); } } storage::TileGroup *Manager::GetTileGroup(const oid_t oid) { storage::TileGroup *location = nullptr; { std::lock_guard<std::mutex> lock(locator_mutex); if (locator.find(oid) != locator.end()) location = locator.at(oid); } return location; } //used for logging test void Manager::ClearTileGroup(){ { std::lock_guard<std::mutex> lock(locator_mutex); locator.clear(); } } //===--------------------------------------------------------------------===// // DATABASE //===--------------------------------------------------------------------===// void Manager::AddDatabase(storage::Database *database) { { std::lock_guard<std::mutex> lock(catalog_mutex); databases.push_back(database); } } storage::Database *Manager::GetDatabaseWithOid(const oid_t database_oid) const { for (auto database : databases) if (database->GetOid() == database_oid) return database; return nullptr; } void Manager::DropDatabaseWithOid(const oid_t database_oid) { { std::lock_guard<std::mutex> lock(catalog_mutex); oid_t database_offset = 0; for (auto database : databases) { if (database->GetOid() == database_oid) { delete database; break; } database_offset++; } assert(database_offset < databases.size()); // Drop the database databases.erase(databases.begin() + database_offset); } } storage::Database *Manager::GetDatabase(const oid_t database_offset) const { assert(database_offset < databases.size()); auto database = databases.at(database_offset); return database; } oid_t Manager::GetDatabaseCount() const { return databases.size(); } //===--------------------------------------------------------------------===// // CONVENIENCE WRAPPERS //===--------------------------------------------------------------------===// storage::DataTable *Manager::GetTableWithOid(const oid_t database_oid, const oid_t table_oid) const { // Lookup DB auto database = GetDatabaseWithOid(database_oid); // Lookup table if (database != nullptr) { auto table = database->GetTableWithOid(table_oid); return table; } return nullptr; } storage::DataTable *Manager::GetTableWithName( const oid_t database_oid, const std::string table_name) const { // Lookup DB auto database = GetDatabaseWithOid(database_oid); // Lookup table if (database != nullptr) { auto table = database->GetTableWithName(table_name); return table; } return nullptr; } index::Index *Manager::GetIndexWithOid(const oid_t database_oid, const oid_t table_oid, const oid_t index_oid) const { // Lookup table auto table = GetTableWithOid(database_oid, table_oid); // Lookup index if (table != nullptr) { auto index = table->GetIndexWithOid(index_oid); return index; } return nullptr; } } // End catalog namespace } // End peloton namespace
Fix GetTileGroup bug. Should return nullptr when group not exist.
Fix GetTileGroup bug. Should return nullptr when group not exist.
C++
apache-2.0
Ghatage/peloton,Ghatage/peloton,Ghatage/peloton,amaliujia/peloton,Ghatage/peloton,Ghatage/peloton,amaliujia/peloton,amaliujia/peloton,Ghatage/peloton,amaliujia/peloton,amaliujia/peloton,amaliujia/peloton,Ghatage/peloton,amaliujia/peloton
94bf686fb9bfceddd3936c3cb58647735102a06d
gui/events/xcb.c++
gui/events/xcb.c++
/** * The MIT License (MIT) * * Copyright © 2017-2018 Ruben Van Boxem * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #include "gui/events/xcb.h++" #include "gui/native_window/xcb.h++" #include "gui/window.h++" #include <core/debug.h++> namespace skui { namespace gui { namespace events { xcb::xcb(gui::window& window) : base{window} { auto native_xcb_window = dynamic_cast<native_window::xcb*>(&window.get_native_window()); if(!native_xcb_window) core::debug_print("events::xcb requires a native_window::xcb or native_window::xlib.\n"); connection = native_xcb_window->get_connection(); xcb_window = native_xcb_window->get_window(); // The magic incantation to receive and be able to check for the "window was closed" event xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, true, 12, "WM_PROTOCOLS"); core::unique_free_ptr<xcb_intern_atom_reply_t> reply(xcb_intern_atom_reply(connection, cookie, nullptr)); xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, false, 16, "WM_DELETE_WINDOW"); wm_delete_window.reset(xcb_intern_atom_reply(connection, cookie2, nullptr)); xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, reply->atom, 4, 32, 1, &wm_delete_window->atom); // end magic xcb_flush(connection); } xcb::~xcb() = default; void xcb::exec() { bool running = true; while(running) { core::unique_free_ptr<xcb_generic_event_t> event_ptr(xcb_wait_for_event(connection)); if(!event_ptr) { core::debug_print("Call to xcb_wait_for_event failed. Most likely an I/O error.\n"); running = false; break; } switch(event_ptr->response_type & ~0x80) { case XCB_EXPOSE: { auto expose = reinterpret_cast<xcb_expose_event_t*>(event_ptr.get()); if(expose->count>0) continue; window.repaint(); break; } case XCB_UNMAP_NOTIFY: { //auto unmap = reinterpret_cast<xcb_unmap_notify_event_t*>(event_ptr.get()); break; } case XCB_BUTTON_PRESS: { auto button_press = reinterpret_cast<xcb_button_press_event_t*>(event_ptr.get()); switch (button_press->state) { case XCB_BUTTON_MASK_1: core::debug_print("Primary mouse button pressed."); break; } switch (button_press->detail) { case 4: // Wheel button up break; case 5: // wheel button down break; default: core::debug_print("Button ", button_press->detail, " pressed in window ", button_press->event, ", at coordinates (", button_press->event_x, ",", button_press->event, ").\n"); break; } break; } case XCB_BUTTON_RELEASE: { //auto button_release = reinterpret_cast<xcb_button_release_event_t*>(event_ptr.get()); //implementation::print_modifiers(button_release->state); break; } case XCB_MOTION_NOTIFY: { //auto motion = reinterpret_cast<xcb_motion_notify_event_t*>(event_ptr.get()); break; } case XCB_ENTER_NOTIFY: { //auto enter = reinterpret_cast<xcb_enter_notify_event_t*>(event_ptr.get()); break; } case XCB_LEAVE_NOTIFY: { //auto leave = reinterpret_cast<xcb_leave_notify_event_t*>(event_ptr.get()); break; } case XCB_KEY_PRESS: { //auto key_press = reinterpret_cast<xcb_key_press_event_t*>(event_ptr.get()); //implementation::print_modifiers(key_press->state); break; } case XCB_KEY_RELEASE: { //auto key_release = reinterpret_cast<xcb_key_release_event_t*>(event_ptr.get()); //implementation::print_modifiers(key_release->state); break; } case XCB_CONFIGURE_NOTIFY: { // We send out an event here so when maximizing or minimizing a window, it gets repainted properly const auto& configure_notify = *reinterpret_cast<xcb_configure_notify_event_t*>(event_ptr.get()); // xcb_send_event is hardcoded to read 32 bytes regardless the event type, so give it 32 bytes. core::unique_free_ptr<xcb_expose_event_t> event(reinterpret_cast<xcb_expose_event_t*>(std::calloc(1, 32))); event->response_type = XCB_EXPOSE; event->window = xcb_window; event->x = static_cast<std::uint16_t>(configure_notify.x); event->y = static_cast<std::uint16_t>(configure_notify.y); event->width = configure_notify.width; event->height = configure_notify.height; xcb_send_event(connection, false, xcb_window, XCB_EVENT_MASK_EXPOSURE, reinterpret_cast<char*>(event.get())); xcb_flush(connection); break; } case XCB_CLIENT_MESSAGE: { auto client_message = reinterpret_cast<xcb_client_message_event_t*>(event_ptr.get()); if(client_message->data.data32[0] == wm_delete_window->atom) { core::debug_print("WM_DELETE_WINDOW received.\n"); window.close(); } break; } case XCB_DESTROY_NOTIFY: { running = false; break; } default: core::debug_print("Unknown event: ", event_ptr->response_type & ~0x80, ".\n"); break; } } } } } }
/** * The MIT License (MIT) * * Copyright © 2017-2018 Ruben Van Boxem * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #include "gui/events/xcb.h++" #include "gui/native_window/xcb.h++" #include "gui/window.h++" #include <core/debug.h++> namespace { std::uint8_t mask_send_event_bit(std::uint8_t response_type) { return response_type & 0b0111'1111; } } namespace skui { namespace gui { namespace events { xcb::xcb(gui::window& window) : base{window} { auto native_xcb_window = dynamic_cast<native_window::xcb*>(&window.get_native_window()); if(!native_xcb_window) core::debug_print("events::xcb requires a native_window::xcb or native_window::xlib.\n"); connection = native_xcb_window->get_connection(); xcb_window = native_xcb_window->get_window(); // The magic incantation to receive and be able to check for the "window was closed" event xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, true, 12, "WM_PROTOCOLS"); core::unique_free_ptr<xcb_intern_atom_reply_t> reply(xcb_intern_atom_reply(connection, cookie, nullptr)); xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, false, 16, "WM_DELETE_WINDOW"); wm_delete_window.reset(xcb_intern_atom_reply(connection, cookie2, nullptr)); xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, reply->atom, 4, 32, 1, &wm_delete_window->atom); // end magic xcb_flush(connection); } xcb::~xcb() = default; void xcb::exec() { bool running = true; while(running) { core::unique_free_ptr<xcb_generic_event_t> event_ptr(xcb_wait_for_event(connection)); if(!event_ptr) { core::debug_print("Call to xcb_wait_for_event failed. Most likely an I/O error.\n"); running = false; break; } switch(mask_send_event_bit(event_ptr->response_type)) { case XCB_EXPOSE: { auto expose = reinterpret_cast<xcb_expose_event_t*>(event_ptr.get()); if(expose->count>0) continue; window.repaint(); break; } case XCB_UNMAP_NOTIFY: { //auto unmap = reinterpret_cast<xcb_unmap_notify_event_t*>(event_ptr.get()); break; } case XCB_BUTTON_PRESS: { auto button_press = reinterpret_cast<xcb_button_press_event_t*>(event_ptr.get()); switch (button_press->state) { case XCB_BUTTON_MASK_1: core::debug_print("Primary mouse button pressed."); break; } switch (button_press->detail) { case 4: // Wheel button up break; case 5: // wheel button down break; default: core::debug_print("Button ", button_press->detail, " pressed in window ", button_press->event, ", at coordinates (", button_press->event_x, ",", button_press->event, ").\n"); break; } break; } case XCB_BUTTON_RELEASE: { //auto button_release = reinterpret_cast<xcb_button_release_event_t*>(event_ptr.get()); //implementation::print_modifiers(button_release->state); break; } case XCB_MOTION_NOTIFY: { //auto motion = reinterpret_cast<xcb_motion_notify_event_t*>(event_ptr.get()); break; } case XCB_ENTER_NOTIFY: { //auto enter = reinterpret_cast<xcb_enter_notify_event_t*>(event_ptr.get()); break; } case XCB_LEAVE_NOTIFY: { //auto leave = reinterpret_cast<xcb_leave_notify_event_t*>(event_ptr.get()); break; } case XCB_KEY_PRESS: { //auto key_press = reinterpret_cast<xcb_key_press_event_t*>(event_ptr.get()); //implementation::print_modifiers(key_press->state); break; } case XCB_KEY_RELEASE: { //auto key_release = reinterpret_cast<xcb_key_release_event_t*>(event_ptr.get()); //implementation::print_modifiers(key_release->state); break; } case XCB_CONFIGURE_NOTIFY: { // We send out an event here so when maximizing or minimizing a window, it gets repainted properly const auto& configure_notify = *reinterpret_cast<xcb_configure_notify_event_t*>(event_ptr.get()); // xcb_send_event is hardcoded to read 32 bytes regardless the event type, so give it 32 bytes. core::unique_free_ptr<xcb_expose_event_t> event(reinterpret_cast<xcb_expose_event_t*>(std::calloc(1, 32))); event->response_type = XCB_EXPOSE; event->window = xcb_window; event->x = static_cast<std::uint16_t>(configure_notify.x); event->y = static_cast<std::uint16_t>(configure_notify.y); event->width = configure_notify.width; event->height = configure_notify.height; xcb_send_event(connection, false, xcb_window, XCB_EVENT_MASK_EXPOSURE, reinterpret_cast<char*>(event.get())); xcb_flush(connection); break; } case XCB_CLIENT_MESSAGE: { auto client_message = reinterpret_cast<xcb_client_message_event_t*>(event_ptr.get()); if(client_message->data.data32[0] == wm_delete_window->atom) { core::debug_print("WM_DELETE_WINDOW received.\n"); window.close(); } break; } case XCB_DESTROY_NOTIFY: { running = false; break; } default: core::debug_print("Unknown event: ", (int)mask_send_event_bit(event_ptr->response_type), ".\n"); break; } } } } } }
Use a vocabulary function to mask the send_event bit.
Use a vocabulary function to mask the send_event bit.
C++
mit
rubenvb/skui,skui-org/skui,rubenvb/skui,skui-org/skui
b1b8de0e3e80646c907fc6d5f8d0067ad76313ed
src/cbang/os/Win32Utilities.cpp
src/cbang/os/Win32Utilities.cpp
/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2015, Cauldron Development LLC Copyright (c) 2003-2015, Stanford University All rights reserved. The C! library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland [email protected] \******************************************************************************/ #ifdef _WIN32 #include "Win32Utilities.h" #include "SysError.h" #include <cbang/Exception.h> #include <windows.h> #include <io.h> using namespace cb; namespace cb { namespace Win32Utilities { void setInherit(int fd, bool inherit) { setInherit(_get_osfhandle(fd), inherit); } void setInherit(void *handle, bool inherit) { if (handle == INVALID_HANDLE_VALUE) THROW("Invalid handle"); DWORD flags = inherit ? HANDLE_FLAG_INHERIT : 0; if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) THROWS("Failed to clear pipe inherit flag: " << SysError()); } unsigned priorityToClass(ProcessPriority priority) { switch (priority) { case ProcessPriority::PRIORITY_INHERIT: return 0; case ProcessPriority::PRIORITY_NORMAL: return NORMAL_PRIORITY_CLASS; case ProcessPriority::PRIORITY_IDLE: return IDLE_PRIORITY_CLASS; case ProcessPriority::PRIORITY_LOW: return BELOW_NORMAL_PRIORITY_CLASS; case ProcessPriority::PRIORITY_HIGH: return ABOVE_NORMAL_PRIORITY_CLASS; case ProcessPriority::PRIORITY_REALTIME: return REALTIME_PRIORITY_CLASS; default: THROWS("Invalid priority: " << priority); } } }; }; #endif // _WIN32
/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2015, Cauldron Development LLC Copyright (c) 2003-2015, Stanford University All rights reserved. The C! library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland [email protected] \******************************************************************************/ #ifdef _WIN32 #include "Win32Utilities.h" #include "SysError.h" #include <cbang/Exception.h> #include <windows.h> #include <io.h> using namespace cb; namespace cb { namespace Win32Utilities { void setInherit(int fd, bool inherit) { setInherit((void *)_get_osfhandle(fd), inherit); } void setInherit(void *handle, bool inherit) { if (handle == INVALID_HANDLE_VALUE) THROW("Invalid handle"); DWORD flags = inherit ? HANDLE_FLAG_INHERIT : 0; if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) THROWS("Failed to clear pipe inherit flag: " << SysError()); } unsigned priorityToClass(ProcessPriority priority) { switch (priority) { case ProcessPriority::PRIORITY_INHERIT: return 0; case ProcessPriority::PRIORITY_NORMAL: return NORMAL_PRIORITY_CLASS; case ProcessPriority::PRIORITY_IDLE: return IDLE_PRIORITY_CLASS; case ProcessPriority::PRIORITY_LOW: return BELOW_NORMAL_PRIORITY_CLASS; case ProcessPriority::PRIORITY_HIGH: return ABOVE_NORMAL_PRIORITY_CLASS; case ProcessPriority::PRIORITY_REALTIME: return REALTIME_PRIORITY_CLASS; default: THROWS("Invalid priority: " << priority); } } }; }; #endif // _WIN32
Fix clang infinite recursion compiler error
Fix clang infinite recursion compiler error
C++
lgpl-2.1
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
f6500312f954eff1cb42b93297a69ba9eddb85b5
WebCore/platform/graphics/cairo/ImageCairo.cpp
WebCore/platform/graphics/cairo/ImageCairo.cpp
/* * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved. * Copyright (C) 2007 Alp Toker <[email protected]> * Copyright (C) 2009 Dirk Schulze <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "BitmapImage.h" #if PLATFORM(CAIRO) #include "AffineTransform.h" #include "Color.h" #include "FloatRect.h" #include "GraphicsContext.h" #include "ImageBuffer.h" #include "ImageObserver.h" #include <cairo.h> #include <math.h> #include <wtf/OwnPtr.h> namespace WebCore { bool FrameData::clear(bool clearMetadata) { if (clearMetadata) m_haveMetadata = false; if (m_frame) { cairo_surface_destroy(m_frame); m_frame = 0; return true; } return false; } BitmapImage::BitmapImage(cairo_surface_t* surface, ImageObserver* observer) : Image(observer) , m_currentFrame(0) , m_frames(0) , m_frameTimer(0) , m_repetitionCount(cAnimationNone) , m_repetitionCountStatus(Unknown) , m_repetitionsComplete(0) , m_isSolidColor(false) , m_checkedForSolidColor(false) , m_animationFinished(true) , m_allDataReceived(true) , m_haveSize(true) , m_sizeAvailable(true) , m_decodedSize(0) , m_haveFrameCount(true) , m_frameCount(1) { initPlatformData(); // TODO: check to be sure this is an image surface int width = cairo_image_surface_get_width(surface); int height = cairo_image_surface_get_height(surface); m_decodedSize = width * height * 4; m_size = IntSize(width, height); m_frames.grow(1); m_frames[0].m_frame = surface; m_frames[0].m_hasAlpha = cairo_surface_get_content(surface) != CAIRO_CONTENT_COLOR; m_frames[0].m_haveMetadata = true; checkForSolidColor(); } void BitmapImage::draw(GraphicsContext* context, const FloatRect& dst, const FloatRect& src, ColorSpace styleColorSpace, CompositeOperator op) { FloatRect srcRect(src); FloatRect dstRect(dst); if (dstRect.width() == 0.0f || dstRect.height() == 0.0f || srcRect.width() == 0.0f || srcRect.height() == 0.0f) return; startAnimation(); cairo_surface_t* image = frameAtIndex(m_currentFrame); if (!image) // If it's too early we won't have an image yet. return; if (mayFillWithSolidColor()) { fillWithSolidColor(context, dstRect, solidColor(), styleColorSpace, op); return; } IntSize selfSize = size(); cairo_t* cr = context->platformContext(); context->save(); // Set the compositing operation. if (op == CompositeSourceOver && !frameHasAlphaAtIndex(m_currentFrame)) context->setCompositeOperation(CompositeCopy); else context->setCompositeOperation(op); // If we're drawing a sub portion of the image or scaling then create // a pattern transformation on the image and draw the transformed pattern. // Test using example site at http://www.meyerweb.com/eric/css/edge/complexspiral/demo.html cairo_pattern_t* pattern = cairo_pattern_create_for_surface(image); cairo_pattern_set_extend(pattern, CAIRO_EXTEND_PAD); float scaleX = srcRect.width() / dstRect.width(); float scaleY = srcRect.height() / dstRect.height(); cairo_matrix_t matrix = { scaleX, 0, 0, scaleY, srcRect.x(), srcRect.y() }; cairo_pattern_set_matrix(pattern, &matrix); // Draw the shadow #if ENABLE(FILTERS) FloatSize shadowSize; float shadowBlur; Color shadowColor; if (context->getShadow(shadowSize, shadowBlur, shadowColor)) { IntSize shadowBufferSize; FloatRect shadowRect; float kernelSize (0.0); GraphicsContext::calculateShadowBufferDimensions(shadowBufferSize, shadowRect, kernelSize, dstRect, shadowSize, shadowBlur); shadowColor = colorWithOverrideAlpha(shadowColor.rgb(), (shadowColor.alpha() * context->getAlpha()) / 255.f); //draw shadow into a new ImageBuffer OwnPtr<ImageBuffer> shadowBuffer = ImageBuffer::create(shadowBufferSize); cairo_t* shadowContext = shadowBuffer->context()->platformContext(); cairo_set_source(shadowContext, pattern); cairo_translate(shadowContext, -dstRect.x(), -dstRect.y()); cairo_rectangle(shadowContext, 0, 0, dstRect.width(), dstRect.height()); cairo_fill(shadowContext); context->createPlatformShadow(shadowBuffer.release(), shadowColor, shadowRect, kernelSize); } #endif // Draw the image. cairo_translate(cr, dstRect.x(), dstRect.y()); cairo_set_source(cr, pattern); cairo_pattern_destroy(pattern); cairo_rectangle(cr, 0, 0, dstRect.width(), dstRect.height()); cairo_clip(cr); cairo_paint_with_alpha(cr, context->getAlpha()); context->restore(); if (imageObserver()) imageObserver()->didDraw(this); } void Image::drawPattern(GraphicsContext* context, const FloatRect& tileRect, const AffineTransform& patternTransform, const FloatPoint& phase, ColorSpace, CompositeOperator op, const FloatRect& destRect) { cairo_surface_t* image = nativeImageForCurrentFrame(); if (!image) // If it's too early we won't have an image yet. return; // Avoid NaN if (!isfinite(phase.x()) || !isfinite(phase.y())) return; cairo_t* cr = context->platformContext(); context->save(); IntRect imageSize = enclosingIntRect(tileRect); OwnPtr<ImageBuffer> imageSurface = ImageBuffer::create(imageSize.size()); if (!imageSurface) return; if (tileRect.size() != size()) { cairo_t* clippedImageContext = imageSurface->context()->platformContext(); cairo_set_source_surface(clippedImageContext, image, -tileRect.x(), -tileRect.y()); cairo_paint(clippedImageContext); image = imageSurface->image()->nativeImageForCurrentFrame(); } cairo_pattern_t* pattern = cairo_pattern_create_for_surface(image); cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT); cairo_matrix_t pattern_matrix = cairo_matrix_t(patternTransform); cairo_matrix_t phase_matrix = {1, 0, 0, 1, phase.x() + tileRect.x() * patternTransform.a(), phase.y() + tileRect.y() * patternTransform.d()}; cairo_matrix_t combined; cairo_matrix_multiply(&combined, &pattern_matrix, &phase_matrix); cairo_matrix_invert(&combined); cairo_pattern_set_matrix(pattern, &combined); context->setCompositeOperation(op); cairo_set_source(cr, pattern); cairo_pattern_destroy(pattern); cairo_rectangle(cr, destRect.x(), destRect.y(), destRect.width(), destRect.height()); cairo_fill(cr); context->restore(); if (imageObserver()) imageObserver()->didDraw(this); } void BitmapImage::checkForSolidColor() { m_isSolidColor = false; m_checkedForSolidColor = true; if (frameCount() > 1) return; cairo_surface_t* frameSurface = frameAtIndex(0); if (!frameSurface) return; ASSERT(cairo_surface_get_type(frameSurface) == CAIRO_SURFACE_TYPE_IMAGE); int width = cairo_image_surface_get_width(frameSurface); int height = cairo_image_surface_get_height(frameSurface); if (width != 1 || height != 1) return; unsigned* pixelColor = reinterpret_cast<unsigned*>(cairo_image_surface_get_data(frameSurface)); m_solidColor = colorFromPremultipliedARGB(*pixelColor); m_isSolidColor = true; } } #endif // PLATFORM(CAIRO)
/* * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved. * Copyright (C) 2007 Alp Toker <[email protected]> * Copyright (C) 2009 Dirk Schulze <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "BitmapImage.h" #if PLATFORM(CAIRO) #include "AffineTransform.h" #include "Color.h" #include "FloatRect.h" #include "GraphicsContext.h" #include "ImageBuffer.h" #include "ImageObserver.h" #include <cairo.h> #include <math.h> #include <wtf/OwnPtr.h> namespace WebCore { bool FrameData::clear(bool clearMetadata) { if (clearMetadata) m_haveMetadata = false; if (m_frame) { cairo_surface_destroy(m_frame); m_frame = 0; return true; } return false; } BitmapImage::BitmapImage(cairo_surface_t* surface, ImageObserver* observer) : Image(observer) , m_currentFrame(0) , m_frames(0) , m_frameTimer(0) , m_repetitionCount(cAnimationNone) , m_repetitionCountStatus(Unknown) , m_repetitionsComplete(0) , m_isSolidColor(false) , m_checkedForSolidColor(false) , m_animationFinished(true) , m_allDataReceived(true) , m_haveSize(true) , m_sizeAvailable(true) , m_decodedSize(0) , m_haveFrameCount(true) , m_frameCount(1) { initPlatformData(); // TODO: check to be sure this is an image surface int width = cairo_image_surface_get_width(surface); int height = cairo_image_surface_get_height(surface); m_decodedSize = width * height * 4; m_size = IntSize(width, height); m_frames.grow(1); m_frames[0].m_frame = surface; m_frames[0].m_hasAlpha = cairo_surface_get_content(surface) != CAIRO_CONTENT_COLOR; m_frames[0].m_haveMetadata = true; checkForSolidColor(); } void BitmapImage::draw(GraphicsContext* context, const FloatRect& dst, const FloatRect& src, ColorSpace styleColorSpace, CompositeOperator op) { FloatRect srcRect(src); FloatRect dstRect(dst); if (dstRect.width() == 0.0f || dstRect.height() == 0.0f || srcRect.width() == 0.0f || srcRect.height() == 0.0f) return; startAnimation(); cairo_surface_t* image = frameAtIndex(m_currentFrame); if (!image) // If it's too early we won't have an image yet. return; if (mayFillWithSolidColor()) { fillWithSolidColor(context, dstRect, solidColor(), styleColorSpace, op); return; } IntSize selfSize = size(); cairo_t* cr = context->platformContext(); context->save(); // Set the compositing operation. if (op == CompositeSourceOver && !frameHasAlphaAtIndex(m_currentFrame)) context->setCompositeOperation(CompositeCopy); else context->setCompositeOperation(op); // If we're drawing a sub portion of the image or scaling then create // a pattern transformation on the image and draw the transformed pattern. // Test using example site at http://www.meyerweb.com/eric/css/edge/complexspiral/demo.html cairo_pattern_t* pattern = cairo_pattern_create_for_surface(image); cairo_pattern_set_extend(pattern, CAIRO_EXTEND_PAD); float scaleX = srcRect.width() / dstRect.width(); float scaleY = srcRect.height() / dstRect.height(); cairo_matrix_t matrix = { scaleX, 0, 0, scaleY, srcRect.x(), srcRect.y() }; cairo_pattern_set_matrix(pattern, &matrix); // Draw the shadow #if ENABLE(FILTERS) FloatSize shadowSize; float shadowBlur; Color shadowColor; if (context->getShadow(shadowSize, shadowBlur, shadowColor)) { IntSize shadowBufferSize; FloatRect shadowRect; float kernelSize (0.0); GraphicsContext::calculateShadowBufferDimensions(shadowBufferSize, shadowRect, kernelSize, dstRect, shadowSize, shadowBlur); shadowColor = colorWithOverrideAlpha(shadowColor.rgb(), (shadowColor.alpha() * context->getAlpha()) / 255.f); //draw shadow into a new ImageBuffer OwnPtr<ImageBuffer> shadowBuffer = ImageBuffer::create(shadowBufferSize); cairo_t* shadowContext = shadowBuffer->context()->platformContext(); cairo_set_source(shadowContext, pattern); cairo_translate(shadowContext, -dstRect.x(), -dstRect.y()); cairo_rectangle(shadowContext, 0, 0, dstRect.width(), dstRect.height()); cairo_fill(shadowContext); context->createPlatformShadow(shadowBuffer.release(), shadowColor, shadowRect, kernelSize); } #endif // Draw the image. cairo_translate(cr, dstRect.x(), dstRect.y()); cairo_set_source(cr, pattern); cairo_pattern_destroy(pattern); cairo_rectangle(cr, 0, 0, dstRect.width(), dstRect.height()); cairo_clip(cr); cairo_paint_with_alpha(cr, context->getAlpha()); context->restore(); if (imageObserver()) imageObserver()->didDraw(this); } void Image::drawPattern(GraphicsContext* context, const FloatRect& tileRect, const AffineTransform& patternTransform, const FloatPoint& phase, ColorSpace, CompositeOperator op, const FloatRect& destRect) { cairo_surface_t* image = nativeImageForCurrentFrame(); if (!image) // If it's too early we won't have an image yet. return; // Avoid NaN if (!isfinite(phase.x()) || !isfinite(phase.y())) return; cairo_t* cr = context->platformContext(); context->save(); IntRect imageSize = enclosingIntRect(tileRect); OwnPtr<ImageBuffer> imageSurface = ImageBuffer::create(imageSize.size()); if (!imageSurface) return; if (tileRect.size() != size()) { cairo_t* clippedImageContext = imageSurface->context()->platformContext(); cairo_set_source_surface(clippedImageContext, image, -tileRect.x(), -tileRect.y()); cairo_paint(clippedImageContext); RefPtr<Image> copiedImage = imageSurface->copyImage(); // FIXME: Copying here is wasteful. image = copiedImage->nativeImageForCurrentFrame(); } cairo_pattern_t* pattern = cairo_pattern_create_for_surface(image); cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT); cairo_matrix_t pattern_matrix = cairo_matrix_t(patternTransform); cairo_matrix_t phase_matrix = {1, 0, 0, 1, phase.x() + tileRect.x() * patternTransform.a(), phase.y() + tileRect.y() * patternTransform.d()}; cairo_matrix_t combined; cairo_matrix_multiply(&combined, &pattern_matrix, &phase_matrix); cairo_matrix_invert(&combined); cairo_pattern_set_matrix(pattern, &combined); context->setCompositeOperation(op); cairo_set_source(cr, pattern); cairo_pattern_destroy(pattern); cairo_rectangle(cr, destRect.x(), destRect.y(), destRect.width(), destRect.height()); cairo_fill(cr); context->restore(); if (imageObserver()) imageObserver()->didDraw(this); } void BitmapImage::checkForSolidColor() { m_isSolidColor = false; m_checkedForSolidColor = true; if (frameCount() > 1) return; cairo_surface_t* frameSurface = frameAtIndex(0); if (!frameSurface) return; ASSERT(cairo_surface_get_type(frameSurface) == CAIRO_SURFACE_TYPE_IMAGE); int width = cairo_image_surface_get_width(frameSurface); int height = cairo_image_surface_get_height(frameSurface); if (width != 1 || height != 1) return; unsigned* pixelColor = reinterpret_cast<unsigned*>(cairo_image_surface_get_data(frameSurface)); m_solidColor = colorFromPremultipliedARGB(*pixelColor); m_isSolidColor = true; } } #endif // PLATFORM(CAIRO)
Fix GTK build bustage.
Fix GTK build bustage. git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@65454 bbb929c8-8fbe-4397-9dbb-9b2b20218538
C++
bsd-3-clause
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
8ec9c6b9a39d598f34e5274e5c00d63c58537ebb
httpserver/ConnHandler.cpp
httpserver/ConnHandler.cpp
/* * ConnHandler.cpp * * Created on: Sep 2, 2012 * Author: ondra */ #include "ConnHandler.h" #include "lightspeed/base/containers/autoArray.tcc" #include <string.h> #include "lightspeed/base/text/textParser.tcc" #include "lightspeed/base/text/textFormat.tcc" #include "HttpReqImpl.h" #include "lightspeed/base/debug/dbglog.h" #include "lightspeed/base/streams/netio.tcc" namespace BredyHttpSrv { static atomic contextCounter = 0; ConnHandler::Command ConnHandler::onDataReady(const PNetworkStream &stream, ITCPServerContext *context) throw() { try { Synchronized<Semaphore> _(busySemaphore); stream->setWaitHandler(this); ConnContext *ctx = static_cast<ConnContext *>(context); DbgLog::setThreadName(ctx->ctxName,false); if (ctx->nstream == nil) { ctx->nstream = Constructor1<NStream,PNetworkStream>(stream.getMT()); } ConnHandler::Command cmd = ctx->onData(ctx->nstream); while (cmd == ConnHandler::cmdWaitRead && ctx->nstream->dataReady() > 0) { cmd = ctx->onData(ctx->nstream); } if (cmd == ITCPServerConnHandler::cmdWaitUserWakeup) { LogObject(THISLOCATION).debug("Request uses detach feature"); } return cmd; } catch (std::exception &e) { LogObject(THISLOCATION).note("Uncaught exception: %1") << e.what(); return cmdRemove; } } natural ConnHandler::wait(const INetworkResource *res, natural waitFor, natural timeout) const { natural k = INetworkResource::WaitHandler::wait(res,waitFor,0); if (k == 0 && timeout != 0) { SyncReleased<Semaphore> _(busySemaphore); k = INetworkResource::WaitHandler::wait(res,waitFor,timeout); } return k; } ConnHandler::Command ConnHandler::onWriteReady(const PNetworkStream &stream, ITCPServerContext *context) throw() { //because handler can't wait for both reading or writing, it is always known, what expected //so we can route onWriteReady through onDataReady return onDataReady(stream,context); } ConnHandler::Command ConnHandler::onTimeout(const PNetworkStream &, ITCPServerContext *context) throw () { //when timeout - remove connection return cmdRemove; } void ConnHandler::onDisconnectByPeer(ITCPServerContext *context) throw () { //while stream is disconnected, we need to close all contexts //before rest part of object becomes invalud //contexts can be accessed from other threads //so it is responsibility of they creators to use proper synchronization //and perform any cleanup before contexts are destroyed ConnContext *ctx = static_cast<ConnContext *>(context); ctx->prepareToDisconnect(); } ITCPServerContext *ConnHandler::onIncome(const NetworkAddress &addr) throw() { DbgLog::setThreadName("server",false); ConnContext* x = new ConnContext(*this,addr); x->setStaticObj(); return x; } ConnHandler::Command ConnHandler::onAccept(ITCPServerConnControl *controlObject, ITCPServerContext *context) { controlObject->setDataReadyTimeout(120000); controlObject->setWriteReadyTimeout(120000); ConnContext *ctx = static_cast<ConnContext *>(context); ctx->setControlObject(controlObject); return cmdWaitRead; } void ConnHandler::addSite(ConstStrA path, IHttpHandler* handler) { pathMap.addHandler(path,handler); } void ConnHandler::removeSite(ConstStrA path) { pathMap.removeHandler(path); } class DurationMeasure { public: DurationMeasure(ConnHandler *target):target(target), begin(SysTime::now()) {} ~DurationMeasure() { try { SysTime end = SysTime::now(); target->recordRequestDuration((end - begin).msecs()); } catch (...) { } } protected: ConnHandler *target; SysTime begin; }; natural ConnContext::callHandler(IHttpRequest &request, ConstStrA path, IHttpHandler **h) { DurationMeasure _(&owner); PathMapper::MappingIter iter = owner.pathMap.findPathMapping(path); while (iter.hasItems()) { const PathMapper::Record &rc = iter.getNext(); ConstStrA vpath = path.offset(rc.key.length()); natural res = rc.value->onRequest(request,vpath); if (request.headersSent() || res != 0) { if (h) *h = rc.value; return res; } } if (h) *h = 0; return 404; } ConnContext::ConnContext(ConnHandler &owner, const NetworkAddress &addr) :HttpReqImpl(owner.baseUrl,owner.serverIdent, owner.busySemaphore), owner(owner) { natural contextId = lockInc(contextCounter); peerAddr = addr; TextFormatBuff<char, StaticAlloc<100> > fmt; fmt("Http:%1") << contextId; ctxName = fmt.write(); (LogObject(THISLOCATION).info("New connection %1 ") << ctxName ) ; } ConnContext::~ConnContext() { prepareToDisconnect(); DbgLog::setThreadName("",true); LogObject(THISLOCATION).info("Connection closed %1") << ctxName ; } void* ConnContext::proxyInterface(IInterfaceRequest& p) { if (p.getType() == TypeInfo(typeid(ITCPServerConnControl))) { return controlObject.get(); } void *r = HttpReqImpl::proxyInterface(p); if (r == 0) r = owner.proxyInterface(p); return r; } const void* ConnContext::proxyInterface(const IInterfaceRequest& p) const { if (p.getType() == TypeInfo(typeid(ITCPServerConnControl))) { return controlObject.get(); } const void *r = HttpReqImpl::proxyInterface(p); if (r == 0) r = owner.proxyInterface(p); return r; } void* ConnHandler::proxyInterface(IInterfaceRequest& p) { return IHttpMapper::proxyInterface(p); } const void* ConnHandler::proxyInterface(const IInterfaceRequest& p) const { return IHttpMapper::proxyInterface(p); } ConnHandler::Command ConnHandler::onUserWakeup( const PNetworkStream &stream, ITCPServerContext *context ) throw() { try { Synchronized<Semaphore> _(busySemaphore); ConnContext *ctx = static_cast<ConnContext *>(context); DbgLog::setThreadName(ctx->ctxName,false); //we need context otherwise close connection if (ctx == 0) return cmdRemove; return ctx->onUserWakeup(); } catch (std::exception &e) { LogObject(THISLOCATION).note("Uncaught exception: %1") << e.what(); return cmdRemove; } } ConstStrA trimSpaces(ConstStrA what) { if (what.empty()) return what; if (isspace(what[0])) return trimSpaces(what.crop(1,0)); if (isspace(what[what.length() - 1])) return trimSpaces(what.crop(0,1)); return what; } ConstStrA ConnHandler::getRealAddr(ConstStrA ip, ConstStrA proxies) { natural sep = proxies.findLast(','); while (sep != naturalNull) { ConstStrA first = trimSpaces(proxies.offset(sep + 1)); proxies = proxies.head(sep); if (first.empty()) continue; if (isPeerTrustedProxy(ip)) { ip = first; } else { return ip; } sep = proxies.findLast(','); } ConstStrA last = trimSpaces(proxies); if (isPeerTrustedProxy(ip)) { return last; } else { return ip; } } ConstStrA ConnContext::getPeerAddrStr() const { if (peerAddrStr.empty()) peerAddrStr = peerAddr.asString(false); return peerAddrStr; } natural ConnContext::getSourceId() const { return controlObject->getSourceId(); } void ConnContext::setControlObject(Pointer<ITCPServerConnControl> controlObject) { this->controlObject = controlObject; } void ConnContext::prepareToDisconnect() { //destroy context, because there still can be other thread accessing it setRequestContext(0); //destroy context, because there still can be other thread accessing it setConnectionContext(0); } void ConnContext::clear() { HttpReqImpl::clear(); peerRealAddrStr.clear(); } LightSpeed::ConstStrA ConnContext::getPeerRealAddr() const { if (peerRealAddrStr.empty()) { StringA ipport = getPeerAddrStr(); natural sep = ipport.findLast(':'); ConstStrA ip = ipport.head(sep); HeaderValue proxies = getHeaderField(fldXForwardedFor); if (proxies.defined) peerRealAddrStr = owner.getRealAddr(ip, proxies); else peerRealAddrStr = ip; } return peerRealAddrStr; } }
/* * ConnHandler.cpp * * Created on: Sep 2, 2012 * Author: ondra */ #include "ConnHandler.h" #include "lightspeed/base/containers/autoArray.tcc" #include <string.h> #include "lightspeed/base/text/textParser.tcc" #include "lightspeed/base/text/textFormat.tcc" #include "HttpReqImpl.h" #include "lightspeed/base/debug/dbglog.h" #include "lightspeed/base/streams/netio.tcc" namespace BredyHttpSrv { static atomic contextCounter = 0; ConnHandler::Command ConnHandler::onDataReady(const PNetworkStream &stream, ITCPServerContext *context) throw() { Synchronized<Semaphore> _(busySemaphore); ConnContext *ctx = static_cast<ConnContext *>(context); try { stream->setWaitHandler(this); DbgLog::setThreadName(ctx->ctxName,false); if (ctx->nstream == nil) { ctx->nstream = Constructor1<NStream,PNetworkStream>(stream.getMT()); } ConnHandler::Command cmd = ctx->onData(ctx->nstream); while (cmd == ConnHandler::cmdWaitRead && ctx->nstream->dataReady() > 0) { cmd = ctx->onData(ctx->nstream); } if (cmd == ITCPServerConnHandler::cmdWaitUserWakeup) { LogObject(THISLOCATION).debug("Request uses detach feature"); } if (cmd == cmdRemove) ctx->nstream = nil; return cmd; } catch (std::exception &e) { LogObject(THISLOCATION).note("Uncaught exception: %1") << e.what(); ctx->nstream->getBuffer().discardOutput(naturalNull); return cmdRemove; } } natural ConnHandler::wait(const INetworkResource *res, natural waitFor, natural timeout) const { natural k = INetworkResource::WaitHandler::wait(res,waitFor,0); if (k == 0 && timeout != 0) { SyncReleased<Semaphore> _(busySemaphore); k = INetworkResource::WaitHandler::wait(res,waitFor,timeout); } return k; } ConnHandler::Command ConnHandler::onWriteReady(const PNetworkStream &stream, ITCPServerContext *context) throw() { //because handler can't wait for both reading or writing, it is always known, what expected //so we can route onWriteReady through onDataReady return onDataReady(stream,context); } ConnHandler::Command ConnHandler::onTimeout(const PNetworkStream &, ITCPServerContext *context) throw () { //when timeout - remove connection return cmdRemove; } void ConnHandler::onDisconnectByPeer(ITCPServerContext *context) throw () { //while stream is disconnected, we need to close all contexts //before rest part of object becomes invalud //contexts can be accessed from other threads //so it is responsibility of they creators to use proper synchronization //and perform any cleanup before contexts are destroyed ConnContext *ctx = static_cast<ConnContext *>(context); ctx->prepareToDisconnect(); } ITCPServerContext *ConnHandler::onIncome(const NetworkAddress &addr) throw() { DbgLog::setThreadName("server",false); ConnContext* x = new ConnContext(*this,addr); x->setStaticObj(); return x; } ConnHandler::Command ConnHandler::onAccept(ITCPServerConnControl *controlObject, ITCPServerContext *context) { controlObject->setDataReadyTimeout(120000); controlObject->setWriteReadyTimeout(120000); ConnContext *ctx = static_cast<ConnContext *>(context); ctx->setControlObject(controlObject); return cmdWaitRead; } void ConnHandler::addSite(ConstStrA path, IHttpHandler* handler) { pathMap.addHandler(path,handler); } void ConnHandler::removeSite(ConstStrA path) { pathMap.removeHandler(path); } class DurationMeasure { public: DurationMeasure(ConnHandler *target):target(target), begin(SysTime::now()) {} ~DurationMeasure() { try { SysTime end = SysTime::now(); target->recordRequestDuration((end - begin).msecs()); } catch (...) { } } protected: ConnHandler *target; SysTime begin; }; natural ConnContext::callHandler(IHttpRequest &request, ConstStrA path, IHttpHandler **h) { DurationMeasure _(&owner); PathMapper::MappingIter iter = owner.pathMap.findPathMapping(path); while (iter.hasItems()) { const PathMapper::Record &rc = iter.getNext(); ConstStrA vpath = path.offset(rc.key.length()); natural res = rc.value->onRequest(request,vpath); if (request.headersSent() || res != 0) { if (h) *h = rc.value; return res; } } if (h) *h = 0; return 404; } ConnContext::ConnContext(ConnHandler &owner, const NetworkAddress &addr) :HttpReqImpl(owner.baseUrl,owner.serverIdent, owner.busySemaphore), owner(owner) { natural contextId = lockInc(contextCounter); peerAddr = addr; TextFormatBuff<char, StaticAlloc<100> > fmt; fmt("Http:%1") << contextId; ctxName = fmt.write(); (LogObject(THISLOCATION).info("New connection %1 ") << ctxName ) ; } ConnContext::~ConnContext() { prepareToDisconnect(); DbgLog::setThreadName("",true); LogObject(THISLOCATION).info("Connection closed %1") << ctxName ; } void* ConnContext::proxyInterface(IInterfaceRequest& p) { if (p.getType() == TypeInfo(typeid(ITCPServerConnControl))) { return controlObject.get(); } void *r = HttpReqImpl::proxyInterface(p); if (r == 0) r = owner.proxyInterface(p); return r; } const void* ConnContext::proxyInterface(const IInterfaceRequest& p) const { if (p.getType() == TypeInfo(typeid(ITCPServerConnControl))) { return controlObject.get(); } const void *r = HttpReqImpl::proxyInterface(p); if (r == 0) r = owner.proxyInterface(p); return r; } void* ConnHandler::proxyInterface(IInterfaceRequest& p) { return IHttpMapper::proxyInterface(p); } const void* ConnHandler::proxyInterface(const IInterfaceRequest& p) const { return IHttpMapper::proxyInterface(p); } ConnHandler::Command ConnHandler::onUserWakeup( const PNetworkStream &stream, ITCPServerContext *context ) throw() { try { Synchronized<Semaphore> _(busySemaphore); ConnContext *ctx = static_cast<ConnContext *>(context); DbgLog::setThreadName(ctx->ctxName,false); //we need context otherwise close connection if (ctx == 0) return cmdRemove; return ctx->onUserWakeup(); } catch (std::exception &e) { LogObject(THISLOCATION).note("Uncaught exception: %1") << e.what(); return cmdRemove; } } ConstStrA trimSpaces(ConstStrA what) { if (what.empty()) return what; if (isspace(what[0])) return trimSpaces(what.crop(1,0)); if (isspace(what[what.length() - 1])) return trimSpaces(what.crop(0,1)); return what; } ConstStrA ConnHandler::getRealAddr(ConstStrA ip, ConstStrA proxies) { natural sep = proxies.findLast(','); while (sep != naturalNull) { ConstStrA first = trimSpaces(proxies.offset(sep + 1)); proxies = proxies.head(sep); if (first.empty()) continue; if (isPeerTrustedProxy(ip)) { ip = first; } else { return ip; } sep = proxies.findLast(','); } ConstStrA last = trimSpaces(proxies); if (isPeerTrustedProxy(ip)) { return last; } else { return ip; } } ConstStrA ConnContext::getPeerAddrStr() const { if (peerAddrStr.empty()) peerAddrStr = peerAddr.asString(false); return peerAddrStr; } natural ConnContext::getSourceId() const { return controlObject->getSourceId(); } void ConnContext::setControlObject(Pointer<ITCPServerConnControl> controlObject) { this->controlObject = controlObject; } void ConnContext::prepareToDisconnect() { //destroy context, because there still can be other thread accessing it setRequestContext(0); //destroy context, because there still can be other thread accessing it setConnectionContext(0); } void ConnContext::clear() { HttpReqImpl::clear(); peerRealAddrStr.clear(); } LightSpeed::ConstStrA ConnContext::getPeerRealAddr() const { if (peerRealAddrStr.empty()) { StringA ipport = getPeerAddrStr(); natural sep = ipport.findLast(':'); ConstStrA ip = ipport.head(sep); HeaderValue proxies = getHeaderField(fldXForwardedFor); if (proxies.defined) peerRealAddrStr = owner.getRealAddr(ip, proxies); else peerRealAddrStr = ip; } return peerRealAddrStr; } }
discard content of buffer when closing connection due exception. This avoid to propagate exception to the higher levek
discard content of buffer when closing connection due exception. This avoid to propagate exception to the higher levek
C++
mit
ondra-novak/jsonrpcserver,ondra-novak/jsonrpcserver,ondra-novak/jsonrpcserver,ondra-novak/jsonrpcserver
2a5d4f646c2fb16dae52e725a8c871e31b3d120f
chrome/browser/download/download_uitest.cc
chrome/browser/download/download_uitest.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <sstream> #include <string> #include "build/build_config.h" #if defined(OS_WIN) #include <shlwapi.h> #endif #include "base/command_line.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/platform_thread.h" #include "base/string_util.h" #include "chrome/browser/automation/url_request_mock_http_job.h" #include "chrome/browser/automation/url_request_slow_download_job.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui/ui_test.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" namespace { const wchar_t kDocRoot[] = L"chrome/test/data"; #if defined(OS_WIN) // Checks if the volume supports Alternate Data Streams. This is required for // the Zone Identifier implementation. bool VolumeSupportsADS(const std::wstring path) { wchar_t drive[MAX_PATH] = {0}; wcscpy_s(drive, MAX_PATH, path.c_str()); EXPECT_TRUE(PathStripToRootW(drive)); DWORD fs_flags = 0; EXPECT_TRUE(GetVolumeInformationW(drive, NULL, 0, 0, NULL, &fs_flags, NULL, 0)); if (fs_flags & FILE_NAMED_STREAMS) return true; return false; } // Checks if the ZoneIdentifier is correctly set to "Internet" (3) void CheckZoneIdentifier(const std::wstring full_path) { const DWORD kShare = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; std::wstring path = full_path + L":Zone.Identifier"; HANDLE file = CreateFile(path.c_str(), GENERIC_READ, kShare, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); ASSERT_TRUE(INVALID_HANDLE_VALUE != file); char buffer[100] = {0}; DWORD read = 0; ASSERT_TRUE(ReadFile(file, buffer, 100, &read, NULL)); CloseHandle(file); const char kIdentifier[] = "[ZoneTransfer]\nZoneId=3"; ASSERT_EQ(arraysize(kIdentifier), read); ASSERT_EQ(0, strcmp(kIdentifier, buffer)); } #endif // defined(OS_WIN) class DownloadTest : public UITest { protected: DownloadTest() : UITest() {} void CleanUpDownload(const FilePath& client_filename, const FilePath& server_filename) { // Find the path on the client. FilePath file_on_client = download_prefix_.Append(client_filename); EXPECT_TRUE(file_util::PathExists(file_on_client)); // Find the path on the server. FilePath file_on_server; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_on_server)); file_on_server = file_on_server.Append(server_filename); ASSERT_TRUE(file_util::PathExists(file_on_server)); // Check that we downloaded the file correctly. EXPECT_TRUE(file_util::ContentsEqual(file_on_server, file_on_client)); #if defined(OS_WIN) // Check if the Zone Identifier is correctly set. if (VolumeSupportsADS(file_on_client.value())) CheckZoneIdentifier(file_on_client.value()); #endif // Delete the client copy of the file. EXPECT_TRUE(file_util::Delete(file_on_client, false)); } void CleanUpDownload(const FilePath& file) { CleanUpDownload(file, file); } virtual void SetUp() { UITest::SetUp(); download_prefix_ = FilePath::FromWStringHack(GetDownloadDirectory()); } protected: void RunSizeTest(const GURL& url, const std::wstring& expected_title_in_progress, const std::wstring& expected_title_finished) { { EXPECT_EQ(1, GetTabCount()); NavigateToURL(url); // Downloads appear in the shelf WaitUntilTabCount(1); // TODO(tc): check download status text // Complete sending the request. We do this by loading a second URL in a // separate tab. scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); EXPECT_TRUE(window->AppendTab(GURL( URLRequestSlowDownloadJob::kFinishDownloadUrl))); EXPECT_EQ(2, GetTabCount()); // TODO(tc): check download status text // Make sure the download shelf is showing. EXPECT_TRUE(WaitForDownloadShelfVisible(window.get())); } FilePath filename; net::FileURLToFilePath(url, &filename); filename = filename.BaseName(); FilePath download_path = download_prefix_.Append(filename); EXPECT_TRUE(file_util::PathExists(download_path)); // Delete the file we just downloaded. for (int i = 0; i < 10; ++i) { if (file_util::Delete(download_path, false)) break; PlatformThread::Sleep(action_max_timeout_ms() / 10); } EXPECT_FALSE(file_util::PathExists(download_path)); } FilePath download_prefix_; }; // Download a file with non-viewable content, verify that the // download tab opened and the file exists. TEST_F(DownloadTest, DownloadMimeType) { FilePath file(FILE_PATH_LITERAL("download-test1.lib")); EXPECT_EQ(1, GetTabCount()); NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack())); // No new tabs created, downloads appear in the current tab's download shelf. WaitUntilTabCount(1); // Wait until the file is downloaded. PlatformThread::Sleep(action_timeout_ms()); CleanUpDownload(file); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get())); } // Access a file with a viewable mime-type, verify that a download // did not initiate. TEST_F(DownloadTest, NoDownload) { FilePath file(FILE_PATH_LITERAL("download-test2.html")); FilePath file_path = download_prefix_.Append(file); if (file_util::PathExists(file_path)) ASSERT_TRUE(file_util::Delete(file_path, false)); EXPECT_EQ(1, GetTabCount()); NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack())); WaitUntilTabCount(1); // Wait to see if the file will be downloaded. PlatformThread::Sleep(action_timeout_ms()); EXPECT_FALSE(file_util::PathExists(file_path)); if (file_util::PathExists(file_path)) ASSERT_TRUE(file_util::Delete(file_path, false)); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); EXPECT_FALSE(WaitForDownloadShelfVisible(browser.get())); } // Download a 0-size file with a content-disposition header, verify that the // download tab opened and the file exists as the filename specified in the // header. This also ensures we properly handle empty file downloads. TEST_F(DownloadTest, ContentDisposition) { FilePath file(FILE_PATH_LITERAL("download-test3.gif")); FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif")); EXPECT_EQ(1, GetTabCount()); NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack())); WaitUntilTabCount(1); // Wait until the file is downloaded. PlatformThread::Sleep(action_timeout_ms()); CleanUpDownload(download_file, file); // Ensure the download shelf is visible on the window. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get())); } // Test that the download shelf is per-window by starting a download in one // tab, opening a second tab, closing the shelf, going back to the first tab, // and checking that the shelf is closed. TEST_F(DownloadTest, PerWindowShelf) { FilePath file(FILE_PATH_LITERAL("download-test3.gif")); FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif")); EXPECT_EQ(1, GetTabCount()); NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack())); WaitUntilTabCount(1); // Wait until the file is downloaded. PlatformThread::Sleep(action_timeout_ms()); CleanUpDownload(download_file, file); // Ensure the download shelf is visible on the window. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get())); // Open a second tab browser->AppendTab(GURL("")); WaitUntilTabCount(2); // Hide shelf browser->SetShelfVisible(false); EXPECT_TRUE(WaitForDownloadShelfInvisible(browser.get())); // Go to first tab EXPECT_TRUE(browser->ActivateTab(0)); int tab_count; EXPECT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); bool shelf_visible; EXPECT_TRUE(browser->IsShelfVisible(&shelf_visible)); ASSERT_FALSE(shelf_visible); } // UnknownSize and KnownSize are tests which depend on // URLRequestSlowDownloadJob to serve content in a certain way. Data will be // sent in two chunks where the first chunk is 35K and the second chunk is 10K. // The test will first attempt to download a file; but the server will "pause" // in the middle until the server receives a second request for // "download-finish. At that time, the download will finish. TEST_F(DownloadTest, UnknownSize) { GURL url(URLRequestSlowDownloadJob::kUnknownSizeUrl); FilePath filename; net::FileURLToFilePath(url, &filename); filename = filename.BaseName(); RunSizeTest(url, L"32.0 KB - " + filename.ToWStringHack(), L"100% - " + filename.ToWStringHack()); } // http://b/1158253 TEST_F(DownloadTest, DISABLED_KnownSize) { GURL url(URLRequestSlowDownloadJob::kKnownSizeUrl); FilePath filename; net::FileURLToFilePath(url, &filename); filename = filename.BaseName(); RunSizeTest(url, L"71% - " + filename.ToWStringHack(), L"100% - " + filename.ToWStringHack()); } } // namespace
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <sstream> #include <string> #include "build/build_config.h" #if defined(OS_WIN) #include <shlwapi.h> #endif #include "base/command_line.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/platform_thread.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/automation/url_request_mock_http_job.h" #include "chrome/browser/automation/url_request_slow_download_job.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui/ui_test.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" namespace { const wchar_t kDocRoot[] = L"chrome/test/data"; #if defined(OS_WIN) // Checks if the volume supports Alternate Data Streams. This is required for // the Zone Identifier implementation. bool VolumeSupportsADS(const std::wstring path) { wchar_t drive[MAX_PATH] = {0}; wcscpy_s(drive, MAX_PATH, path.c_str()); EXPECT_TRUE(PathStripToRootW(drive)); DWORD fs_flags = 0; EXPECT_TRUE(GetVolumeInformationW(drive, NULL, 0, 0, NULL, &fs_flags, NULL, 0)); if (fs_flags & FILE_NAMED_STREAMS) return true; return false; } // Checks if the ZoneIdentifier is correctly set to "Internet" (3) void CheckZoneIdentifier(const std::wstring full_path) { const DWORD kShare = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; std::wstring path = full_path + L":Zone.Identifier"; HANDLE file = CreateFile(path.c_str(), GENERIC_READ, kShare, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); ASSERT_TRUE(INVALID_HANDLE_VALUE != file); char buffer[100] = {0}; DWORD read = 0; ASSERT_TRUE(ReadFile(file, buffer, 100, &read, NULL)); CloseHandle(file); const char kIdentifier[] = "[ZoneTransfer]\nZoneId=3"; ASSERT_EQ(arraysize(kIdentifier), read); ASSERT_EQ(0, strcmp(kIdentifier, buffer)); } #endif // defined(OS_WIN) class DownloadTest : public UITest { protected: DownloadTest() : UITest() {} void CleanUpDownload(const FilePath& client_filename, const FilePath& server_filename) { // Find the path on the client. FilePath file_on_client = download_prefix_.Append(client_filename); EXPECT_TRUE(file_util::PathExists(file_on_client)); // Find the path on the server. FilePath file_on_server; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_on_server)); file_on_server = file_on_server.Append(server_filename); ASSERT_TRUE(file_util::PathExists(file_on_server)); // Check that we downloaded the file correctly. EXPECT_TRUE(file_util::ContentsEqual(file_on_server, file_on_client)); #if defined(OS_WIN) // Check if the Zone Identifier is correctly set. if (VolumeSupportsADS(file_on_client.value())) CheckZoneIdentifier(file_on_client.value()); #endif // Delete the client copy of the file. EXPECT_TRUE(file_util::Delete(file_on_client, false)); } void CleanUpDownload(const FilePath& file) { CleanUpDownload(file, file); } virtual void SetUp() { UITest::SetUp(); download_prefix_ = FilePath::FromWStringHack(GetDownloadDirectory()); } protected: void RunSizeTest(const GURL& url, const std::wstring& expected_title_in_progress, const std::wstring& expected_title_finished) { { EXPECT_EQ(1, GetTabCount()); NavigateToURL(url); // Downloads appear in the shelf WaitUntilTabCount(1); // TODO(tc): check download status text // Complete sending the request. We do this by loading a second URL in a // separate tab. scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); EXPECT_TRUE(window->AppendTab(GURL( URLRequestSlowDownloadJob::kFinishDownloadUrl))); EXPECT_EQ(2, GetTabCount()); // TODO(tc): check download status text // Make sure the download shelf is showing. EXPECT_TRUE(WaitForDownloadShelfVisible(window.get())); } FilePath filename; net::FileURLToFilePath(url, &filename); filename = filename.BaseName(); FilePath download_path = download_prefix_.Append(filename); EXPECT_TRUE(file_util::PathExists(download_path)); // Delete the file we just downloaded. for (int i = 0; i < 10; ++i) { if (file_util::Delete(download_path, false)) break; PlatformThread::Sleep(action_max_timeout_ms() / 10); } EXPECT_FALSE(file_util::PathExists(download_path)); } FilePath download_prefix_; }; // Download a file with non-viewable content, verify that the // download tab opened and the file exists. TEST_F(DownloadTest, DownloadMimeType) { FilePath file(FILE_PATH_LITERAL("download-test1.lib")); EXPECT_EQ(1, GetTabCount()); NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack())); // No new tabs created, downloads appear in the current tab's download shelf. WaitUntilTabCount(1); // Wait until the file is downloaded. PlatformThread::Sleep(action_timeout_ms()); CleanUpDownload(file); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get())); } // Access a file with a viewable mime-type, verify that a download // did not initiate. TEST_F(DownloadTest, NoDownload) { FilePath file(FILE_PATH_LITERAL("download-test2.html")); FilePath file_path = download_prefix_.Append(file); if (file_util::PathExists(file_path)) ASSERT_TRUE(file_util::Delete(file_path, false)); EXPECT_EQ(1, GetTabCount()); NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack())); WaitUntilTabCount(1); // Wait to see if the file will be downloaded. PlatformThread::Sleep(action_timeout_ms()); EXPECT_FALSE(file_util::PathExists(file_path)); if (file_util::PathExists(file_path)) ASSERT_TRUE(file_util::Delete(file_path, false)); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); EXPECT_FALSE(WaitForDownloadShelfVisible(browser.get())); } // Download a 0-size file with a content-disposition header, verify that the // download tab opened and the file exists as the filename specified in the // header. This also ensures we properly handle empty file downloads. TEST_F(DownloadTest, ContentDisposition) { FilePath file(FILE_PATH_LITERAL("download-test3.gif")); FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif")); EXPECT_EQ(1, GetTabCount()); NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack())); WaitUntilTabCount(1); // Wait until the file is downloaded. PlatformThread::Sleep(action_timeout_ms()); CleanUpDownload(download_file, file); // Ensure the download shelf is visible on the window. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get())); } // Test that the download shelf is per-window by starting a download in one // tab, opening a second tab, closing the shelf, going back to the first tab, // and checking that the shelf is closed. TEST_F(DownloadTest, PerWindowShelf) { FilePath file(FILE_PATH_LITERAL("download-test3.gif")); FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif")); EXPECT_EQ(1, GetTabCount()); NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack())); WaitUntilTabCount(1); // Wait until the file is downloaded. PlatformThread::Sleep(action_timeout_ms()); CleanUpDownload(download_file, file); // Ensure the download shelf is visible on the window. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get())); // Open a second tab browser->AppendTab(GURL("")); WaitUntilTabCount(2); // Hide shelf browser->SetShelfVisible(false); EXPECT_TRUE(WaitForDownloadShelfInvisible(browser.get())); // Go to first tab EXPECT_TRUE(browser->ActivateTab(0)); int tab_count; EXPECT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); bool shelf_visible; EXPECT_TRUE(browser->IsShelfVisible(&shelf_visible)); ASSERT_FALSE(shelf_visible); } // UnknownSize and KnownSize are tests which depend on // URLRequestSlowDownloadJob to serve content in a certain way. Data will be // sent in two chunks where the first chunk is 35K and the second chunk is 10K. // The test will first attempt to download a file; but the server will "pause" // in the middle until the server receives a second request for // "download-finish. At that time, the download will finish. TEST_F(DownloadTest, UnknownSize) { GURL url(URLRequestSlowDownloadJob::kUnknownSizeUrl); FilePath filename; net::FileURLToFilePath(url, &filename); filename = filename.BaseName(); RunSizeTest(url, L"32.0 KB - " + filename.ToWStringHack(), L"100% - " + filename.ToWStringHack()); } // http://b/1158253 TEST_F(DownloadTest, DISABLED_KnownSize) { GURL url(URLRequestSlowDownloadJob::kKnownSizeUrl); FilePath filename; net::FileURLToFilePath(url, &filename); filename = filename.BaseName(); RunSizeTest(url, L"71% - " + filename.ToWStringHack(), L"100% - " + filename.ToWStringHack()); } // Test that when downloading an item in Incognito mode, we don't crash when // closing the last Incognito window (http://crbug.com/13983). TEST_F(DownloadTest, IncognitoDownload) { // Open a regular window and sanity check default values for window / tab // count and shelf visibility. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); int window_count = 0; automation()->GetBrowserWindowCount(&window_count); ASSERT_EQ(1, window_count); EXPECT_EQ(1, GetTabCount()); bool is_shelf_visible; browser->IsShelfVisible(&is_shelf_visible); EXPECT_FALSE(is_shelf_visible); // Open an Incognito window. ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW)); scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1)); scoped_refptr<TabProxy> tab(incognito->GetTab(0)); automation()->GetBrowserWindowCount(&window_count); ASSERT_EQ(2, window_count); // Download something. FilePath file(FILE_PATH_LITERAL("download-test1.lib")); ASSERT_TRUE(tab->NavigateToURL( URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack()))); PlatformThread::Sleep(action_timeout_ms()); // Verify that the download shelf is showing for the Incognito window. EXPECT_TRUE(WaitForDownloadShelfVisible(incognito.get())); // Close the Incognito window and don't crash. ASSERT_TRUE(incognito->RunCommand(IDC_CLOSE_WINDOW)); automation()->GetBrowserWindowCount(&window_count); ASSERT_EQ(1, window_count); // Verify that the regular window does not have a download shelf. browser->IsShelfVisible(&is_shelf_visible); EXPECT_FALSE(is_shelf_visible); CleanUpDownload(file); } } // namespace
Add a UI test for downloading in incognito mode.
Add a UI test for downloading in incognito mode. This test opens an incognito window and verifies that downloads work and that closing the incognito window does not crash (see bug http://crbug.com/13983). TEST=Test should run and not crash. BUG=none Review URL: http://codereview.chromium.org/126181 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@18534 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,ropik/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,ropik/chromium
9e9548216cd9ec8e41a81fb5dc71a7ddd90ae280
include/dll/trainer/dbn_trainer.hpp
include/dll/trainer/dbn_trainer.hpp
//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "cpp_utils/algorithm.hpp" // For parallel_shuffle #include "etl/etl.hpp" #include "dll/util/labels.hpp" #include "dll/util/timers.hpp" #include "dll/util/batch.hpp" // For make_batch #include "dll/test.hpp" #include "dll/dbn_traits.hpp" #include "dll/trainer/sgd_context.hpp" // TODO Remove later namespace dll { template <typename Iterator> struct range { private: Iterator first; Iterator last; public: range(Iterator first, Iterator last) : first(first), last(last) {} Iterator begin() const { return first; } Iterator end() const { return last; } }; template <typename Iterator> range<Iterator> make_range(Iterator first, Iterator last) { return {first, last}; } /*! * \brief A generic trainer for Deep Belief Network * * This trainer use the specified trainer of the DBN to perform supervised * fine-tuning. */ template <typename DBN> struct dbn_trainer { using dbn_t = DBN; using error_type = typename dbn_t::weight; template <typename R> using trainer_t = typename dbn_t::desc::template trainer_t<R>; template <typename R> using watcher_t = typename dbn_t::desc::template watcher_t<R>; template <typename Iterator, typename LIterator> error_type train(DBN& dbn, Iterator first, Iterator last, LIterator lfirst, LIterator llast, size_t max_epochs) const { auto error_function = [&dbn, first, last, lfirst, llast]() { return test_set(dbn, first, last, lfirst, llast, [](dbn_t& dbn, auto& image) { return dbn.predict(image); }); }; auto label_transformer = [](const auto& value, size_t n) { return dll::make_fake_etl(value, n); }; auto input_transformer = [](const auto& /*value*/){ // NOP }; return train_impl(dbn, false, first, last, lfirst, llast, max_epochs, error_function, input_transformer, label_transformer); } template <typename Iterator> error_type train_ae(DBN& dbn, Iterator first, Iterator last, size_t max_epochs) const { auto error_function = [&dbn, first, last]() { return test_set_ae(dbn, first, last); }; auto label_transformer = [](const auto& value, size_t /*n*/) { return value; }; auto input_transformer = [](const auto& /*value*/){ // NOP }; return train_impl(dbn, true, first, last, first, last, max_epochs, error_function, input_transformer, label_transformer); } template <typename Iterator> error_type train_dae(DBN& dbn, Iterator first, Iterator last, size_t max_epochs, double corrupt) const { auto error_function = [&dbn, first, last]() { return test_set_ae(dbn, first, last); }; auto label_transformer = [](const auto& value, size_t /*n*/) { return value; }; auto input_transformer = [corrupt](auto&& value){ static std::random_device rd; static std::default_random_engine g(rd()); std::uniform_real_distribution<double> dist(0.0, 1000.0); for(auto& v : value){ v *= dist(g) < corrupt * 1000.0 ? 0.0 : 1.0; } }; return train_impl(dbn, true, first, last, first, last, max_epochs, error_function, input_transformer, label_transformer); } template <typename D, typename It> static void copy_inputs(D& dest, It first, It last) { size_t i = 0; while (first != last) { dest(i++) = *first++; } } template <typename Iterator, typename LIterator, typename Error, typename InputTransformer, typename LabelTransformer> error_type train_impl(DBN& dbn, bool ae, Iterator first, Iterator last, LIterator lfirst, LIterator /*llast*/, size_t max_epochs, Error error_function, InputTransformer input_transformer, LabelTransformer label_transformer) const { dll::auto_timer timer("dbn::trainer::train_impl"); decltype(auto) input_layer = dbn.template layer_get<dbn_t::input_layer_n>(); decltype(auto) output_layer = dbn.template layer_get<dbn_t::output_layer_n>(); decltype(auto) first_layer = dbn.template layer_get<0>(); decltype(auto) last_layer = dbn.template layer_get<dbn_t::layers - 1>(); using input_layer_t = typename dbn_t::template layer_type<dbn_t::input_layer_n>; using output_layer_t = typename dbn_t::template layer_type<dbn_t::output_layer_n>; constexpr const auto batch_size = std::decay_t<DBN>::batch_size; constexpr const auto big_batch_size = std::decay_t<DBN>::big_batch_size; //Initialize the momentum dbn.momentum = dbn.initial_momentum; //Initialize the watcher watcher_t<dbn_t> watcher; watcher.fine_tuning_begin(dbn); auto trainer = std::make_unique<trainer_t<dbn_t>>(dbn); trainer->set_autoencoder(ae); //Initialize the trainer if necessary trainer->init_training(batch_size); error_type error = 0.0; if (!dbn.batch_mode()) { dll::auto_timer timer("dbn::trainer::train_impl::fast"); // The number of elements on which to train const size_t n = std::distance(first, last); // Prepare the data // TODO Create correctly the type for conv etl::dyn_matrix<typename input_layer_t::weight, 2> data(n, input_layer.input_size()); for(size_t l = 0; l < n; ++l){ data(l) = *first++; } // Prepare the labels etl::dyn_matrix<typename output_layer_t::weight, 2> labels(n, output_layer.output_size(), typename output_layer_t::weight(0.0)); for(size_t l = 0; l < n; ++l){ labels(l) = label_transformer(*lfirst++, output_layer.output_size()); } //Compute the number of batches auto batches = n / batch_size + (n % batch_size == 0 ? 0 : 1); // Prepare a fast error function using the contiguous memory auto error_function_batch = [&] () { if(ae){ return error_function(); } else { //TODO Ideally, this should be done without //acessing the sgd context and probably in dbn.inl decltype(auto) input_ctx = input_layer.template get_sgd_context<dbn_t>(); decltype(auto) first_ctx = first_layer.template get_sgd_context<dbn_t>(); decltype(auto) last_ctx = last_layer.template get_sgd_context<dbn_t>(); double error = 0.0; //Train one mini-batch at a time for (size_t i = 0; i < batches; ++i) { auto start = i * batch_size; auto end = std::min(start + batch_size, n); input_ctx.input = slice(data, start, end); first_layer.batch_activate_hidden(first_ctx.output, first_ctx.input); dbn.for_each_layer_pair([](auto& layer_1, auto& layer_2) { auto& ctx1 = layer_1.template get_sgd_context<dbn_t>(); auto& ctx2 = layer_2.template get_sgd_context<dbn_t>(); ctx2.input = ctx1.output; layer_2.batch_activate_hidden(ctx2.output, ctx2.input); }); // TODO Review this calculation // The result is correct, but can probably be done in a more clean way // TODO This is not correct for ae! for(size_t b = 0; b < end - start; ++b){ error += std::min(1.0, (double) etl::sum(abs(labels(start + b) - one_if_max(last_ctx.output(b))))); } } return error / n; } }; //Train for max_epochs epoch for (size_t epoch = 0; epoch < max_epochs; ++epoch) { dll::auto_timer timer("dbn::trainer::train_impl::epoch"); // Shuffle before the epoch if necessary if(dbn_traits<dbn_t>::shuffle()){ static std::random_device rd; static std::mt19937_64 g(rd()); etl::parallel_shuffle(data, labels); } double loss = 0; //Train one mini-batch at a time for (size_t i = 0; i < batches; ++i) { dll::auto_timer timer("dbn::trainer::train_impl::epoch::batch"); const auto start = i * batch_size; const auto end = std::min(start + batch_size, n); double batch_error; double batch_loss; std::tie(batch_error, batch_loss) = trainer->train_batch( epoch, slice(data, start, end), slice(labels, start, end), input_transformer); if(dbn_traits<dbn_t>::is_verbose()){ watcher.ft_batch_end(epoch, i, batches, batch_error, batch_loss, error_function_batch(), dbn); } loss += batch_loss; } loss /= batches; // Save the last error auto last_error = error; // Compute the error at this epoch { dll::auto_timer timer("dbn::trainer::train_impl::epoch::error"); error = error_function_batch(); } //After some time increase the momentum if (dbn_traits<dbn_t>::has_momentum() && epoch == dbn.final_momentum_epoch) { dbn.momentum = dbn.final_momentum; } watcher.ft_epoch_end(epoch, error, loss, dbn); //Once the goal is reached, stop training if (error <= dbn.goal) { break; } if (dbn_traits<dbn_t>::lr_driver() == lr_driver_type::BOLD) { if (epoch) { if (error > last_error + 1e-8) { //Error increased dbn.learning_rate *= dbn.lr_bold_dec; watcher.lr_adapt(dbn); dbn.restore_weights(); } else if (error < last_error - 1e-10) { //Error decreased dbn.learning_rate *= dbn.lr_bold_inc; watcher.lr_adapt(dbn); dbn.backup_weights(); } else { //Error didn't change enough dbn.backup_weights(); } } else { dbn.backup_weights(); } } if (dbn_traits<dbn_t>::lr_driver() == lr_driver_type::STEP) { if (epoch && epoch % dbn.lr_step_size == 0) { dbn.learning_rate *= dbn.lr_step_gamma; watcher.lr_adapt(dbn); } } } } else { auto total_batch_size = big_batch_size * batch_size; //Prepare some space for converted data etl::dyn_matrix<typename input_layer_t::weight, 2> input_cache(total_batch_size, input_layer.input_size()); etl::dyn_matrix<typename output_layer_t::weight, 2> label_cache(total_batch_size, output_layer.output_size()); //Train for max_epochs epoch for (size_t epoch = 0; epoch < max_epochs; ++epoch) { auto it = first; auto lit = lfirst; double loss = 0.0; size_t n = 0; //Train all mini-batches while (it != last) { label_cache = 0.0; //Fill the input caches size_t i = 0; while (it != last && i < total_batch_size) { input_cache(i) = *it++; label_cache(i) = label_transformer(*lit++, output_layer.output_size()); ++i; ++n; } auto full_batches = i / batch_size; //Train all the full batches for (size_t b = 0; b < full_batches; ++b) { const auto start = b * batch_size; const auto end = (b + 1) * batch_size; double batch_error; double batch_loss; std::tie(batch_error, batch_loss) = trainer->train_batch( epoch, slice(input_cache, start, end), slice(label_cache, start, end), input_transformer); if(dbn_traits<dbn_t>::is_verbose()){ watcher.ft_batch_end(epoch, batch_error, batch_loss, error_function(), dbn); } loss += batch_loss; } //Train the last incomplete batch, if any if (i % batch_size > 0) { const auto start = full_batches * batch_size; const auto end = i; double batch_error; double batch_loss; std::tie(batch_error, batch_loss) = trainer->train_batch( epoch, slice(input_cache, start, end), slice(label_cache, start, end), input_transformer); if(dbn_traits<dbn_t>::is_verbose()){ watcher.ft_batch_end(epoch, batch_error, batch_loss, error_function(), dbn); } loss += batch_loss; } } error = error_function(); loss /= n; //After some time increase the momentum if (dbn_traits<dbn_t>::has_momentum() && epoch == dbn.final_momentum_epoch) { dbn.momentum = dbn.final_momentum; } watcher.ft_epoch_end(epoch, error, loss, dbn); //Once the goal is reached, stop training if (error <= dbn.goal) { break; } } } watcher.fine_tuning_end(dbn); return error; } }; } //end of dll namespace
//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "cpp_utils/algorithm.hpp" // For parallel_shuffle #include "etl/etl.hpp" #include "dll/util/labels.hpp" #include "dll/util/timers.hpp" #include "dll/util/batch.hpp" // For make_batch #include "dll/test.hpp" #include "dll/dbn_traits.hpp" #include "dll/trainer/sgd_context.hpp" // TODO Remove later namespace dll { template <typename Iterator> struct range { private: Iterator first; Iterator last; public: range(Iterator first, Iterator last) : first(first), last(last) {} Iterator begin() const { return first; } Iterator end() const { return last; } }; template <typename Iterator> range<Iterator> make_range(Iterator first, Iterator last) { return {first, last}; } /*! * \brief A generic trainer for Deep Belief Network * * This trainer use the specified trainer of the DBN to perform supervised * fine-tuning. */ template <typename DBN> struct dbn_trainer { using dbn_t = DBN; using error_type = typename dbn_t::weight; template <typename R> using trainer_t = typename dbn_t::desc::template trainer_t<R>; template <typename R> using watcher_t = typename dbn_t::desc::template watcher_t<R>; template <typename Iterator, typename LIterator> error_type train(DBN& dbn, Iterator first, Iterator last, LIterator lfirst, LIterator llast, size_t max_epochs) const { auto error_function = [&dbn, first, last, lfirst, llast]() { return test_set(dbn, first, last, lfirst, llast, [](dbn_t& dbn, auto& image) { return dbn.predict(image); }); }; auto label_transformer = [](const auto& value, size_t n) { return dll::make_fake_etl(value, n); }; auto input_transformer = [](const auto& /*value*/){ // NOP }; return train_impl(dbn, false, first, last, lfirst, llast, max_epochs, error_function, input_transformer, label_transformer); } template <typename Iterator> error_type train_ae(DBN& dbn, Iterator first, Iterator last, size_t max_epochs) const { auto error_function = [&dbn, first, last]() { return test_set_ae(dbn, first, last); }; auto label_transformer = [](const auto& value, size_t /*n*/) { return value; }; auto input_transformer = [](const auto& /*value*/){ // NOP }; return train_impl(dbn, true, first, last, first, last, max_epochs, error_function, input_transformer, label_transformer); } template <typename Iterator> error_type train_dae(DBN& dbn, Iterator first, Iterator last, size_t max_epochs, double corrupt) const { auto error_function = [&dbn, first, last]() { return test_set_ae(dbn, first, last); }; auto label_transformer = [](const auto& value, size_t /*n*/) { return value; }; auto input_transformer = [corrupt](auto&& value){ static std::random_device rd; static std::default_random_engine g(rd()); std::uniform_real_distribution<double> dist(0.0, 1000.0); for(auto& v : value){ v *= dist(g) < corrupt * 1000.0 ? 0.0 : 1.0; } }; return train_impl(dbn, true, first, last, first, last, max_epochs, error_function, input_transformer, label_transformer); } template <typename D, typename It> static void copy_inputs(D& dest, It first, It last) { size_t i = 0; while (first != last) { dest(i++) = *first++; } } template <typename Iterator, typename LIterator, typename Error, typename InputTransformer, typename LabelTransformer> error_type train_impl(DBN& dbn, bool ae, Iterator first, Iterator last, LIterator lfirst, LIterator /*llast*/, size_t max_epochs, Error error_function, InputTransformer input_transformer, LabelTransformer label_transformer) const { dll::auto_timer timer("dbn::trainer::train_impl"); decltype(auto) input_layer = dbn.template layer_get<dbn_t::input_layer_n>(); decltype(auto) output_layer = dbn.template layer_get<dbn_t::output_layer_n>(); decltype(auto) first_layer = dbn.template layer_get<0>(); decltype(auto) last_layer = dbn.template layer_get<dbn_t::layers - 1>(); using input_layer_t = typename dbn_t::template layer_type<dbn_t::input_layer_n>; using output_layer_t = typename dbn_t::template layer_type<dbn_t::output_layer_n>; constexpr const auto batch_size = std::decay_t<DBN>::batch_size; constexpr const auto big_batch_size = std::decay_t<DBN>::big_batch_size; //Initialize the momentum dbn.momentum = dbn.initial_momentum; //Initialize the watcher watcher_t<dbn_t> watcher; watcher.fine_tuning_begin(dbn); auto trainer = std::make_unique<trainer_t<dbn_t>>(dbn); trainer->set_autoencoder(ae); //Initialize the trainer if necessary trainer->init_training(batch_size); error_type error = 0.0; if (!dbn.batch_mode()) { dll::auto_timer timer("dbn::trainer::train_impl::fast"); // The number of elements on which to train const size_t n = std::distance(first, last); // Prepare the data // TODO Create correctly the type for conv etl::dyn_matrix<typename input_layer_t::weight, 2> data(n, input_layer.input_size()); for(size_t l = 0; l < n; ++l){ data(l) = *first++; } // Prepare the labels etl::dyn_matrix<typename output_layer_t::weight, 2> labels(n, output_layer.output_size(), typename output_layer_t::weight(0.0)); for(size_t l = 0; l < n; ++l){ labels(l) = label_transformer(*lfirst++, output_layer.output_size()); } //Compute the number of batches auto batches = n / batch_size + (n % batch_size == 0 ? 0 : 1); // Prepare a fast error function using the contiguous memory auto error_function_batch = [&] () { if(ae){ return error_function(); } else { //Note: Ideally, this should be done without //using the SGD context, but this would mean //a complete overhault of creation of batches... decltype(auto) input_ctx = input_layer.template get_sgd_context<dbn_t>(); decltype(auto) first_ctx = first_layer.template get_sgd_context<dbn_t>(); decltype(auto) last_ctx = last_layer.template get_sgd_context<dbn_t>(); double error = 0.0; //Train one mini-batch at a time for (size_t i = 0; i < batches; ++i) { auto start = i * batch_size; auto end = std::min(start + batch_size, n); input_ctx.input = slice(data, start, end); first_layer.batch_activate_hidden(first_ctx.output, first_ctx.input); dbn.for_each_layer_pair([](auto& layer_1, auto& layer_2) { auto& ctx1 = layer_1.template get_sgd_context<dbn_t>(); auto& ctx2 = layer_2.template get_sgd_context<dbn_t>(); ctx2.input = ctx1.output; layer_2.batch_activate_hidden(ctx2.output, ctx2.input); }); // TODO Review this calculation // The result is correct, but can probably be done in a more clean way // TODO This is not correct for ae! for(size_t b = 0; b < end - start; ++b){ error += std::min(1.0, (double) etl::sum(abs(labels(start + b) - one_if_max(last_ctx.output(b))))); } } return error / n; } }; //Train for max_epochs epoch for (size_t epoch = 0; epoch < max_epochs; ++epoch) { dll::auto_timer timer("dbn::trainer::train_impl::epoch"); // Shuffle before the epoch if necessary if(dbn_traits<dbn_t>::shuffle()){ static std::random_device rd; static std::mt19937_64 g(rd()); etl::parallel_shuffle(data, labels); } double loss = 0; //Train one mini-batch at a time for (size_t i = 0; i < batches; ++i) { dll::auto_timer timer("dbn::trainer::train_impl::epoch::batch"); const auto start = i * batch_size; const auto end = std::min(start + batch_size, n); double batch_error; double batch_loss; std::tie(batch_error, batch_loss) = trainer->train_batch( epoch, slice(data, start, end), slice(labels, start, end), input_transformer); if(dbn_traits<dbn_t>::is_verbose()){ watcher.ft_batch_end(epoch, i, batches, batch_error, batch_loss, error_function_batch(), dbn); } loss += batch_loss; } loss /= batches; // Save the last error auto last_error = error; // Compute the error at this epoch { dll::auto_timer timer("dbn::trainer::train_impl::epoch::error"); error = error_function_batch(); } //After some time increase the momentum if (dbn_traits<dbn_t>::has_momentum() && epoch == dbn.final_momentum_epoch) { dbn.momentum = dbn.final_momentum; } watcher.ft_epoch_end(epoch, error, loss, dbn); //Once the goal is reached, stop training if (error <= dbn.goal) { break; } if (dbn_traits<dbn_t>::lr_driver() == lr_driver_type::BOLD) { if (epoch) { if (error > last_error + 1e-8) { //Error increased dbn.learning_rate *= dbn.lr_bold_dec; watcher.lr_adapt(dbn); dbn.restore_weights(); } else if (error < last_error - 1e-10) { //Error decreased dbn.learning_rate *= dbn.lr_bold_inc; watcher.lr_adapt(dbn); dbn.backup_weights(); } else { //Error didn't change enough dbn.backup_weights(); } } else { dbn.backup_weights(); } } if (dbn_traits<dbn_t>::lr_driver() == lr_driver_type::STEP) { if (epoch && epoch % dbn.lr_step_size == 0) { dbn.learning_rate *= dbn.lr_step_gamma; watcher.lr_adapt(dbn); } } } } else { auto total_batch_size = big_batch_size * batch_size; //Prepare some space for converted data etl::dyn_matrix<typename input_layer_t::weight, 2> input_cache(total_batch_size, input_layer.input_size()); etl::dyn_matrix<typename output_layer_t::weight, 2> label_cache(total_batch_size, output_layer.output_size()); //Train for max_epochs epoch for (size_t epoch = 0; epoch < max_epochs; ++epoch) { auto it = first; auto lit = lfirst; double loss = 0.0; size_t n = 0; //Train all mini-batches while (it != last) { label_cache = 0.0; //Fill the input caches size_t i = 0; while (it != last && i < total_batch_size) { input_cache(i) = *it++; label_cache(i) = label_transformer(*lit++, output_layer.output_size()); ++i; ++n; } auto full_batches = i / batch_size; //Train all the full batches for (size_t b = 0; b < full_batches; ++b) { const auto start = b * batch_size; const auto end = (b + 1) * batch_size; double batch_error; double batch_loss; std::tie(batch_error, batch_loss) = trainer->train_batch( epoch, slice(input_cache, start, end), slice(label_cache, start, end), input_transformer); if(dbn_traits<dbn_t>::is_verbose()){ watcher.ft_batch_end(epoch, batch_error, batch_loss, error_function(), dbn); } loss += batch_loss; } //Train the last incomplete batch, if any if (i % batch_size > 0) { const auto start = full_batches * batch_size; const auto end = i; double batch_error; double batch_loss; std::tie(batch_error, batch_loss) = trainer->train_batch( epoch, slice(input_cache, start, end), slice(label_cache, start, end), input_transformer); if(dbn_traits<dbn_t>::is_verbose()){ watcher.ft_batch_end(epoch, batch_error, batch_loss, error_function(), dbn); } loss += batch_loss; } } error = error_function(); loss /= n; //After some time increase the momentum if (dbn_traits<dbn_t>::has_momentum() && epoch == dbn.final_momentum_epoch) { dbn.momentum = dbn.final_momentum; } watcher.ft_epoch_end(epoch, error, loss, dbn); //Once the goal is reached, stop training if (error <= dbn.goal) { break; } } } watcher.fine_tuning_end(dbn); return error; } }; } //end of dll namespace
Change note
Change note
C++
mit
wichtounet/dll,wichtounet/dll,wichtounet/dll
b64fbb6903714ee4ab48e253382e1496fc1aee3e
zmqml/zmqsocket.cpp
zmqml/zmqsocket.cpp
/* * ZmQML - QML binding for zeromq. * * Copyright (C) 2014 Riccardo Ferrazzo * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "zmqsocket.h" #include "zmqcontext.h" #include <QDebug> #include <QSocketNotifier> #include <QUuid> using namespace std::placeholders; inline void zmqError(const QString &message) { qWarning() << message << zmq_strerror(zmq_errno()); } ZMQSocket::ZMQSocket(QObject *parent) : QObject(parent), _connection_status(Invalid), _type(Null), _identity(QUuid::createUuid().toByteArray()), socket(0) {setupOptionsTable();} ZMQSocket::~ZMQSocket() { if (socket) zmq_close(socket); } ZMQSocket::ConnectionStatus ZMQSocket::status() const { return _connection_status; } ZMQSocket::SocketType ZMQSocket::type() const { return _type; } QByteArray ZMQSocket::identity() const { return _identity; } QVariantList ZMQSocket::addresses() const { return _addr; } QStringList ZMQSocket::subscriptions() const { return _subscriptions.toList(); } void ZMQSocket::setType(const ZMQSocket::SocketType type) { if (_type != Null) return; _type = type; emit typeChanged(); setup(); } void ZMQSocket::setIdentity(const QByteArray &id) { if (_identity == id) return; if (socket) { int rc = zmq_setsockopt(socket, ZMQ_IDENTITY, (void *) id.data(), id.size()); if (rc < 0 ) zmqError("Identity error:"); } _identity = id; emit identityChanged(); } void ZMQSocket::setAddresses(const QVariantList &addresses) { if (socket && _connection_status == Connected) { int (*dfun)(void *, const char*) = _connection_method == Connect ? zmq_disconnect : zmq_unbind; foreach (const QVariant &a, _addr) { int rc = dfun(socket, qPrintable(a.toUrl().toString())); if (rc < 0) zmqError("Disconnection error:"); } int (*cfun)(void *, const char*) = _connection_method == Connect ? zmq_connect : zmq_bind; int result; foreach(const QVariant &addr, addresses) { result = cfun(socket, qPrintable(addr.toUrl().toString())); if (result == -1) zmqError("Connection error:"); } } _addr = addresses; emit addressesChanged(); } void ZMQSocket::setSubscriptions(const QStringList &sub) { const QSet<QString> new_subs = sub.toSet(); if (_subscriptions == new_subs) return; if (socket && _type == Sub) { const QSet<QString> removed = _subscriptions - new_subs; const QSet<QString> added = new_subs - _subscriptions; foreach (const QString &s, removed) { const QByteArray &b = s.toUtf8(); zmq_setsockopt(socket, ZMQ_UNSUBSCRIBE, (void *) b.data(), b.size()); } foreach (const QString &s, added) { const QByteArray &b = s.toUtf8(); zmq_setsockopt(socket, ZMQ_SUBSCRIBE, (void *) b.data(), b.size()); } } _subscriptions = new_subs; emit subscriptionsChanged(); } bool ZMQSocket::setSockOption(ZMQSocket::SockOption option, const QVariant &value) { if (!socket) { qWarning() << "Error, socket not ready"; return false; } if (!options.contains(option)) { qWarning() << "ZMQSocket::setSockOption: unknown option" << option; return false; } return options[option].setter(value); } QVariant ZMQSocket::getSockOption(ZMQSocket::SockOption option) const { if (!options.contains(option)) { qWarning() << "ZMQSocket::getSockOption: unknown option" << option; return QVariant(); } return options[option].getter(); } bool ZMQSocket::connectSocket() { return setupConnection(Connect); } bool ZMQSocket::bindSocket() { return setupConnection(Bind); } void ZMQSocket::sendMessage(const QByteArray &message) { const int res = zmq_send(socket, message.data(), message.size(), 0); if (res == -1) { zmqError("Error sending message:"); return; } } void ZMQSocket::sendMessage(const QList<QByteArray> &message) { QList<QByteArray>::const_iterator i; for (i = message.constBegin(); i != message.constEnd(); ++i) { int flags = (i+1) == message.constEnd() ? 0 : ZMQ_SNDMORE; const int res = zmq_send(socket, (*i).constData(), (*i).size(), flags); if (res == -1) { zmqError("Error sending message:"); return; } } } void ZMQSocket::setup() { if (!_type) return; socket = zmq_socket(ZMQContext::instance()->context, int(_type)); if (!socket) { zmqError("Socket creation error:"); return; } _connection_status = Disconnected; emit connectionStatusChanged(); zmq_setsockopt(socket, ZMQ_IDENTITY, (void *) _identity.data(), _identity.size()); qint32 fd; size_t size = sizeof(fd); zmq_getsockopt(socket, ZMQ_FD, &fd, &size); notifier = new QSocketNotifier(fd, QSocketNotifier::Read, this); connect(notifier, &QSocketNotifier::activated, [=]() { notifier->setEnabled(false); quint32 event = ZMQ_POLLIN; QList<QByteArray> message; while(event & ZMQ_POLLIN){ size_t ev_size = sizeof(event); zmq_getsockopt(socket, ZMQ_EVENTS, (void *) &event, &ev_size); zmq_msg_t part; int rc = zmq_msg_init(&part); if (rc < 0) { zmqError("Error initializing message:"); break; } const int res = zmq_msg_recv(&part, socket, ZMQ_NOBLOCK); if (res < 0) continue; message << QByteArray((char *) zmq_msg_data(&part), zmq_msg_size(&part)); zmq_msg_close(&part); qint64 more = 0; size_t size = sizeof(more); zmq_getsockopt(socket, ZMQ_RCVMORE, static_cast<void *>(&more), &size); if (!more && message.length()) { emit messageReceived(message); message.clear(); } } if (message.length() > 0) emit messageReceived(message); notifier->setEnabled(true); } ); } bool ZMQSocket::setupConnection(ConnectionMethod method) { if (_connection_status != Disconnected) { qWarning() << QString("Socket is not ready to %1").arg(method == Connect ? "connect" : "bind"); return false; } int (*fun)(void *, const char *) = method == Connect ? zmq_connect : zmq_bind; int result; foreach(const QVariant &addr, _addr) { result = fun(socket, qPrintable(addr.toUrl().toString())); if (result == -1) { zmqError("Connection error:"); return false; } } _connection_method = method; _connection_status = Connected; emit connectionStatusChanged(); return true; } void ZMQSocket::setupOptionsTable() { if (options.size()) return; auto setIntValue = [this] (SockOption key, const QVariant &value) { bool ok; int int_val = value.toInt(&ok); if (!ok) { qWarning() << "Value is not int"; return false; } const int rc = zmq_setsockopt(socket, static_cast<int>(key), static_cast<void *>(&int_val), sizeof(int)); if (rc != 0) { zmqError(QString("Error setting option %1:").arg(key)); return false; } return true; }; auto getIntValue = [this] (SockOption key) { int option; size_t size = sizeof(option); const int rc = zmq_getsockopt(socket, static_cast<int>(key), static_cast<void *>(&option), &size); if (rc != 0) { zmqError(QString("Error getting option %1:").arg(key)); return QVariant(); } return QVariant(option); }; auto setByteArrayValue = [this] (SockOption key, const QVariant &value) { QByteArray ba_value = value.toByteArray(); if (ba_value.isNull()) { qWarning() << "Value is not a QByteArray"; return false; } const int rc = zmq_setsockopt(socket, static_cast<int>(key), ba_value.data(), ba_value.size()); if (rc != 0) { zmqError(QString("Error setting option %1:").arg(key)); return false; } return true; }; auto getByteArrayValue = [this] (SockOption key, size_t size) { QByteArray data(size, ' '); const int rc = zmq_getsockopt(socket, static_cast<int>(key), static_cast<void *>(data.data()), &size); if (rc != 0) { zmqError(QString("Error getting option %1:").arg(key)); return QVariant(); } data.resize(data.indexOf('\0')); return QVariant(data); }; options = QHash<SockOption, Option>({ {SndHwm, {std::bind(setIntValue, SndHwm, _1), std::bind(getIntValue, SndHwm)}}, {RcvHwm, {std::bind(setIntValue, RcvHwm, _1), std::bind(getIntValue, RcvHwm)}}, {Rate, {std::bind(setIntValue, Rate, _1), std::bind(getIntValue, Rate)}}, {RecoveryIvl, {std::bind(setIntValue, RecoveryIvl, _1), std::bind(getIntValue, RecoveryIvl)}}, {SndBuf, {std::bind(setIntValue, SndBuf, _1), std::bind(getIntValue, SndBuf)}}, {RcvBuf, {std::bind(setIntValue, RcvBuf, _1), std::bind(getIntValue, RcvBuf)}}, {Linger, {std::bind(setIntValue, Linger, _1), std::bind(getIntValue, Linger)}}, {ReconnectIvl, {std::bind(setIntValue, ReconnectIvl, _1), std::bind(getIntValue, ReconnectIvl)}}, {ReconnectIvlMax, {std::bind(setIntValue, ReconnectIvlMax, _1), std::bind(getIntValue, ReconnectIvlMax)}}, {Backlog, {std::bind(setIntValue, Backlog, _1), std::bind(getIntValue, Backlog)}}, {MulticastHops, {std::bind(setIntValue, MulticastHops, _1), std::bind(getIntValue, MulticastHops)}}, {SndTimeOut, {std::bind(setIntValue, SndTimeOut, _1), std::bind(getIntValue, SndTimeOut)}}, {IPV4Only, {std::bind(setIntValue, IPV4Only, _1), std::bind(getIntValue, IPV4Only)}}, {RouterMandatory, {std::bind(setIntValue, RouterMandatory, _1), std::bind(getIntValue, RouterMandatory)}}, {XPubVerbose, {std::bind(setIntValue, XPubVerbose, _1), std::bind(getIntValue, XPubVerbose)}}, {TcpKeepalive, {std::bind(setIntValue, TcpKeepalive, _1), std::bind(getIntValue, TcpKeepalive)}}, {TcpKeepaliveIdle, {std::bind(setIntValue, TcpKeepaliveIdle, _1), std::bind(getIntValue, TcpKeepaliveIdle)}}, {TcpKeepaliveCnt, {std::bind(setIntValue, TcpKeepaliveCnt, _1), std::bind(getIntValue, TcpKeepaliveCnt)}}, {TcpKeepaliveIntvl, {std::bind(setIntValue, TcpKeepaliveIntvl, _1), std::bind(getIntValue, TcpKeepaliveIntvl)}}, #if ZMQ_VERSION_MAJOR > 3 {IPV6, {std::bind(setIntValue, IPV6, _1), std::bind(getIntValue, IPV6)}}, {Immediate, {std::bind(setIntValue, Immediate, _1), std::bind(getIntValue, Immediate)}}, {RouterRaw, {std::bind(setIntValue, RouterRaw, _1), std::bind(getIntValue, RouterRaw)}}, {ProbeRouter, {std::bind(setIntValue, ProbeRouter, _1), std::bind(getIntValue, ProbeRouter)}}, {ReqCorrelate, {std::bind(setIntValue, ReqCorrelate, _1), std::bind(getIntValue, ReqCorrelate)}}, {ReqRelaxed, {std::bind(setIntValue, ReqRelaxed, _1), std::bind(getIntValue, ReqRelaxed)}}, {CurveServer, {std::bind(setIntValue, CurveServer, _1), std::bind(getIntValue, CurveServer)}}, {CurvePublicKey, {std::bind(setByteArrayValue, CurvePublicKey, _1), std::bind(getByteArrayValue, CurvePublicKey, 41)}}, {CurveSecretKey, {std::bind(setByteArrayValue, CurveSecretKey, _1), std::bind(getByteArrayValue, CurveSecretKey, 41)}}, {CurveServerKey, {std::bind(setByteArrayValue, CurveServerKey, _1), std::bind(getByteArrayValue, CurveServerKey, 41)}}, {ZapDomain, {std::bind(setByteArrayValue, ZapDomain, _1), std::bind(getByteArrayValue, ZapDomain, 255)}}, #endif }); }
/* * ZmQML - QML binding for zeromq. * * Copyright (C) 2014 Riccardo Ferrazzo * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "zmqsocket.h" #include "zmqcontext.h" #include <QDebug> #include <QSocketNotifier> #include <QUuid> using namespace std::placeholders; inline void zmqError(const QString &message) { qWarning() << message << zmq_strerror(zmq_errno()); } ZMQSocket::ZMQSocket(QObject *parent) : QObject(parent), _connection_status(Invalid), _type(Null), _identity(QUuid::createUuid().toByteArray()), socket(0) {setupOptionsTable();} ZMQSocket::~ZMQSocket() { if (socket) zmq_close(socket); } ZMQSocket::ConnectionStatus ZMQSocket::status() const { return _connection_status; } ZMQSocket::SocketType ZMQSocket::type() const { return _type; } QByteArray ZMQSocket::identity() const { return _identity; } QVariantList ZMQSocket::addresses() const { return _addr; } QStringList ZMQSocket::subscriptions() const { return _subscriptions.toList(); } void ZMQSocket::setType(const ZMQSocket::SocketType type) { if (_type != Null) return; _type = type; emit typeChanged(); setup(); } void ZMQSocket::setIdentity(const QByteArray &id) { if (_identity == id) return; if (socket) { int rc = zmq_setsockopt(socket, ZMQ_IDENTITY, (void *) id.data(), id.size()); if (rc < 0 ) zmqError("Identity error:"); } _identity = id; emit identityChanged(); } void ZMQSocket::setAddresses(const QVariantList &addresses) { if (socket && _connection_status == Connected) { int (*dfun)(void *, const char*) = _connection_method == Connect ? zmq_disconnect : zmq_unbind; foreach (const QVariant &a, _addr) { int rc = dfun(socket, qPrintable(a.toUrl().toString())); if (rc < 0) zmqError("Disconnection error:"); } int (*cfun)(void *, const char*) = _connection_method == Connect ? zmq_connect : zmq_bind; int result; foreach(const QVariant &addr, addresses) { result = cfun(socket, qPrintable(addr.toUrl().toString())); if (result == -1) zmqError("Connection error:"); } } _addr = addresses; emit addressesChanged(); } void ZMQSocket::setSubscriptions(const QStringList &sub) { const QSet<QString> new_subs = sub.toSet(); if (_subscriptions == new_subs) return; if (socket && _type == Sub) { const QSet<QString> removed = _subscriptions - new_subs; const QSet<QString> added = new_subs - _subscriptions; foreach (const QString &s, removed) { const QByteArray &b = s.toUtf8(); zmq_setsockopt(socket, ZMQ_UNSUBSCRIBE, (void *) b.data(), b.size()); } foreach (const QString &s, added) { const QByteArray &b = s.toUtf8(); zmq_setsockopt(socket, ZMQ_SUBSCRIBE, (void *) b.data(), b.size()); } } _subscriptions = new_subs; emit subscriptionsChanged(); } bool ZMQSocket::setSockOption(ZMQSocket::SockOption option, const QVariant &value) { if (!socket) { qWarning() << "Error, socket not ready"; return false; } if (!options.contains(option)) { qWarning() << "ZMQSocket::setSockOption: unknown option" << option; return false; } return options[option].setter(value); } QVariant ZMQSocket::getSockOption(ZMQSocket::SockOption option) const { if (!options.contains(option)) { qWarning() << "ZMQSocket::getSockOption: unknown option" << option; return QVariant(); } return options.value(option).getter(); } bool ZMQSocket::connectSocket() { return setupConnection(Connect); } bool ZMQSocket::bindSocket() { return setupConnection(Bind); } void ZMQSocket::sendMessage(const QByteArray &message) { const int res = zmq_send(socket, message.data(), message.size(), 0); if (res == -1) { zmqError("Error sending message:"); return; } } void ZMQSocket::sendMessage(const QList<QByteArray> &message) { QList<QByteArray>::const_iterator i; for (i = message.constBegin(); i != message.constEnd(); ++i) { int flags = (i+1) == message.constEnd() ? 0 : ZMQ_SNDMORE; const int res = zmq_send(socket, (*i).constData(), (*i).size(), flags); if (res == -1) { zmqError("Error sending message:"); return; } } } void ZMQSocket::setup() { if (!_type) return; socket = zmq_socket(ZMQContext::instance()->context, int(_type)); if (!socket) { zmqError("Socket creation error:"); return; } _connection_status = Disconnected; emit connectionStatusChanged(); zmq_setsockopt(socket, ZMQ_IDENTITY, (void *) _identity.data(), _identity.size()); qint32 fd; size_t size = sizeof(fd); zmq_getsockopt(socket, ZMQ_FD, &fd, &size); notifier = new QSocketNotifier(fd, QSocketNotifier::Read, this); connect(notifier, &QSocketNotifier::activated, [=]() { notifier->setEnabled(false); quint32 event = ZMQ_POLLIN; QList<QByteArray> message; while(event & ZMQ_POLLIN){ size_t ev_size = sizeof(event); zmq_getsockopt(socket, ZMQ_EVENTS, (void *) &event, &ev_size); zmq_msg_t part; int rc = zmq_msg_init(&part); if (rc < 0) { zmqError("Error initializing message:"); break; } const int res = zmq_msg_recv(&part, socket, ZMQ_NOBLOCK); if (res < 0) continue; message << QByteArray((char *) zmq_msg_data(&part), zmq_msg_size(&part)); zmq_msg_close(&part); qint64 more = 0; size_t size = sizeof(more); zmq_getsockopt(socket, ZMQ_RCVMORE, static_cast<void *>(&more), &size); if (!more && message.length()) { emit messageReceived(message); message.clear(); } } if (message.length() > 0) emit messageReceived(message); notifier->setEnabled(true); } ); } bool ZMQSocket::setupConnection(ConnectionMethod method) { if (_connection_status != Disconnected) { qWarning() << QString("Socket is not ready to %1").arg(method == Connect ? "connect" : "bind"); return false; } int (*fun)(void *, const char *) = method == Connect ? zmq_connect : zmq_bind; int result; foreach(const QVariant &addr, _addr) { result = fun(socket, qPrintable(addr.toUrl().toString())); if (result == -1) { zmqError("Connection error:"); return false; } } _connection_method = method; _connection_status = Connected; emit connectionStatusChanged(); return true; } void ZMQSocket::setupOptionsTable() { if (options.size()) return; auto setIntValue = [this] (SockOption key, const QVariant &value) { bool ok; int int_val = value.toInt(&ok); if (!ok) { qWarning() << "Value is not int"; return false; } const int rc = zmq_setsockopt(socket, static_cast<int>(key), static_cast<void *>(&int_val), sizeof(int)); if (rc != 0) { zmqError(QString("Error setting option %1:").arg(key)); return false; } return true; }; auto getIntValue = [this] (SockOption key) { int option; size_t size = sizeof(option); const int rc = zmq_getsockopt(socket, static_cast<int>(key), static_cast<void *>(&option), &size); if (rc != 0) { zmqError(QString("Error getting option %1:").arg(key)); return QVariant(); } return QVariant(option); }; auto setByteArrayValue = [this] (SockOption key, const QVariant &value) { QByteArray ba_value = value.toByteArray(); if (ba_value.isNull()) { qWarning() << "Value is not a QByteArray"; return false; } const int rc = zmq_setsockopt(socket, static_cast<int>(key), ba_value.data(), ba_value.size()); if (rc != 0) { zmqError(QString("Error setting option %1:").arg(key)); return false; } return true; }; auto getByteArrayValue = [this] (SockOption key, size_t size) { QByteArray data(size, ' '); const int rc = zmq_getsockopt(socket, static_cast<int>(key), static_cast<void *>(data.data()), &size); if (rc != 0) { zmqError(QString("Error getting option %1:").arg(key)); return QVariant(); } data.resize(data.indexOf('\0')); return QVariant(data); }; options = QHash<SockOption, Option>({ {SndHwm, {std::bind(setIntValue, SndHwm, _1), std::bind(getIntValue, SndHwm)}}, {RcvHwm, {std::bind(setIntValue, RcvHwm, _1), std::bind(getIntValue, RcvHwm)}}, {Rate, {std::bind(setIntValue, Rate, _1), std::bind(getIntValue, Rate)}}, {RecoveryIvl, {std::bind(setIntValue, RecoveryIvl, _1), std::bind(getIntValue, RecoveryIvl)}}, {SndBuf, {std::bind(setIntValue, SndBuf, _1), std::bind(getIntValue, SndBuf)}}, {RcvBuf, {std::bind(setIntValue, RcvBuf, _1), std::bind(getIntValue, RcvBuf)}}, {Linger, {std::bind(setIntValue, Linger, _1), std::bind(getIntValue, Linger)}}, {ReconnectIvl, {std::bind(setIntValue, ReconnectIvl, _1), std::bind(getIntValue, ReconnectIvl)}}, {ReconnectIvlMax, {std::bind(setIntValue, ReconnectIvlMax, _1), std::bind(getIntValue, ReconnectIvlMax)}}, {Backlog, {std::bind(setIntValue, Backlog, _1), std::bind(getIntValue, Backlog)}}, {MulticastHops, {std::bind(setIntValue, MulticastHops, _1), std::bind(getIntValue, MulticastHops)}}, {SndTimeOut, {std::bind(setIntValue, SndTimeOut, _1), std::bind(getIntValue, SndTimeOut)}}, {IPV4Only, {std::bind(setIntValue, IPV4Only, _1), std::bind(getIntValue, IPV4Only)}}, {RouterMandatory, {std::bind(setIntValue, RouterMandatory, _1), std::bind(getIntValue, RouterMandatory)}}, {XPubVerbose, {std::bind(setIntValue, XPubVerbose, _1), std::bind(getIntValue, XPubVerbose)}}, {TcpKeepalive, {std::bind(setIntValue, TcpKeepalive, _1), std::bind(getIntValue, TcpKeepalive)}}, {TcpKeepaliveIdle, {std::bind(setIntValue, TcpKeepaliveIdle, _1), std::bind(getIntValue, TcpKeepaliveIdle)}}, {TcpKeepaliveCnt, {std::bind(setIntValue, TcpKeepaliveCnt, _1), std::bind(getIntValue, TcpKeepaliveCnt)}}, {TcpKeepaliveIntvl, {std::bind(setIntValue, TcpKeepaliveIntvl, _1), std::bind(getIntValue, TcpKeepaliveIntvl)}}, #if ZMQ_VERSION_MAJOR > 3 {IPV6, {std::bind(setIntValue, IPV6, _1), std::bind(getIntValue, IPV6)}}, {Immediate, {std::bind(setIntValue, Immediate, _1), std::bind(getIntValue, Immediate)}}, {RouterRaw, {std::bind(setIntValue, RouterRaw, _1), std::bind(getIntValue, RouterRaw)}}, {ProbeRouter, {std::bind(setIntValue, ProbeRouter, _1), std::bind(getIntValue, ProbeRouter)}}, {ReqCorrelate, {std::bind(setIntValue, ReqCorrelate, _1), std::bind(getIntValue, ReqCorrelate)}}, {ReqRelaxed, {std::bind(setIntValue, ReqRelaxed, _1), std::bind(getIntValue, ReqRelaxed)}}, {CurveServer, {std::bind(setIntValue, CurveServer, _1), std::bind(getIntValue, CurveServer)}}, {CurvePublicKey, {std::bind(setByteArrayValue, CurvePublicKey, _1), std::bind(getByteArrayValue, CurvePublicKey, 41)}}, {CurveSecretKey, {std::bind(setByteArrayValue, CurveSecretKey, _1), std::bind(getByteArrayValue, CurveSecretKey, 41)}}, {CurveServerKey, {std::bind(setByteArrayValue, CurveServerKey, _1), std::bind(getByteArrayValue, CurveServerKey, 41)}}, {ZapDomain, {std::bind(setByteArrayValue, ZapDomain, _1), std::bind(getByteArrayValue, ZapDomain, 255)}}, #endif }); }
Use value instead of [] to get option
Use value instead of [] to get option
C++
mpl-2.0
rferrazz/zmqml
fb3af873b3059e4eca78c33e929ab78b2364d05e
src/libzlog/view_reader.cc
src/libzlog/view_reader.cc
#include "libzlog/view_reader.h" #include "include/zlog/backend.h" #include "log_backend.h" #include <iostream> // TODO: client requests that see a nullptr sequencer shoudl block and wait for // updates // TODO: use a smarter index for epoch waiters // TODO build a log's initial view for exclusive sequencers namespace zlog { ViewReader::ViewReader( const std::shared_ptr<LogBackend> backend, const Options& options) : shutdown_(false), backend_(backend), options_(options), view_(nullptr), refresh_thread_(std::thread(&ViewReader::refresh_entry_, this)) { assert(backend); } ViewReader::~ViewReader() { { std::lock_guard<std::mutex> lk(lock_); if (shutdown_) { assert(refresh_waiters_.empty()); assert(!refresh_thread_.joinable()); return; } } shutdown(); std::lock_guard<std::mutex> lk(lock_); assert(shutdown_); assert(refresh_waiters_.empty()); assert(!refresh_thread_.joinable()); } void ViewReader::shutdown() { { std::lock_guard<std::mutex> lk(lock_); shutdown_ = true; } refresh_cond_.notify_one(); refresh_thread_.join(); } void ViewReader::refresh_entry_() { while (true) { { std::unique_lock<std::mutex> lk(lock_); refresh_cond_.wait(lk, [&] { return !refresh_waiters_.empty() || shutdown_; }); if (shutdown_) { for (auto waiter : refresh_waiters_) { waiter->done = true; waiter->cond.notify_one(); } refresh_waiters_.clear(); break; } } refresh_view(); const auto current_view = view(); if (!current_view) { continue; } std::list<RefreshWaiter*> waiters; { std::lock_guard<std::mutex> lk(lock_); waiters.swap(refresh_waiters_); } for (auto it = waiters.begin(); it != waiters.end();) { const auto waiter = *it; // trying to make this locking fine grained to avoid blocking clients // is admirable, but really we probably just need a finger grained lock // to protect the waiters list rather than lock/unlock/lock/unlock/... std::lock_guard<std::mutex> lk(lock_); if (current_view->epoch() > waiter->epoch) { waiter->done = true; waiter->cond.notify_one(); it = waiters.erase(it); } else { it++; } } // add any waiters that weren't notified back into the master list. don't // naively replace the list as other waiters may have shown up recently. if (!waiters.empty()) { std::lock_guard<std::mutex> lk(lock_); refresh_waiters_.splice(refresh_waiters_.begin(), waiters); } } } std::shared_ptr<const VersionedView> ViewReader::view() const { std::lock_guard<std::mutex> lk(lock_); return view_; } void ViewReader::wait_for_newer_view(const uint64_t epoch) { std::unique_lock<std::mutex> lk(lock_); if (shutdown_) { return; } RefreshWaiter waiter(epoch); // XXX: is it necessary to hold the lock here to ensure that the epoch set // above in waiter is always seen by by the refresh thread, even though the // refresh thread will always grab the lock too to discover the waiter? need // to go do a quick refresher on the memory consistency semantics. refresh_waiters_.emplace_back(&waiter); refresh_cond_.notify_one(); waiter.cond.wait(lk, [&waiter] { return waiter.done; }); } std::unique_ptr<VersionedView> ViewReader::get_latest_view() const { std::map<uint64_t, std::string> views; int ret = backend_->ReadViews(0, 1, &views); if (ret) { std::cerr << "get_latest_view failed to read view " << ret << std::endl; return nullptr; } const auto it = views.crbegin(); if (it == views.crend()) { std::cerr << "get_latest_view no views found" << std::endl; // this would happen if there are no views return nullptr; } return std::unique_ptr<VersionedView>( new VersionedView(it->first, it->second)); } void ViewReader::refresh_view() { auto latest_view = get_latest_view(); if (!latest_view) { std::cerr << "refresh_view failed to get latest view" << std::endl; return; } assert(!latest_view->seq); std::lock_guard<std::mutex> lk(lock_); if (view_) { assert(latest_view->epoch() >= view_->epoch()); if (latest_view->epoch() == view_->epoch()) { return; } } // if the latest view has a sequencer config and secret that matches this log // client instance, then we will become a sequencer / exclusive writer. if (latest_view->seq_config() && latest_view->seq_config()->secret() == backend_->secret()) { // there are two cases for initializing the new view's sequencer: // // 1) reuse sequencer from previous view // 2) create a new sequencer instance // // if a previous view has a sequencer with the same secret, then we might be // able to reuse it. however, if the previous view that we have and the // latest view are separated by views with _other_ sequencers in the log, // but which we haven't observed, then we need to take that into account. // in order to catch this scenario, we also check that the previous view has // an initialization epoch that matches the epoch in the latest view's // sequencer config. // // the sequencer config in a view either copied or a new sequencer config is // proposed. whenver a sequencer config is successfully proposed, it's // initialization epoch will be unique (even for different proposals from // the same log client). so, if the secret and the initialization epoch are // equal, then we can be assured that the sequencer hasn't changed and we // can reuse the state. // if (view_ && view_->seq_config() && view_->seq_config()->secret() == backend_->secret() && view_->seq_config()->epoch() == latest_view->seq_config()->epoch()) { // // note about thread safety. here we copy the pointer to the existing // sequencer which may be in-use concurrently. it wouldn't be sufficient // to create a new sequencer object initialized with the existing state // (we could miss updates to the seq state until all new threads saw the // new view) unless concurrent updates were blocked by a lock, but that // would introduce a lock on the i/o path. // assert(view_->seq); latest_view->seq = view_->seq; } else { // create a new instance for this sequencer latest_view->seq = std::make_shared<Sequencer>(latest_view->epoch(), latest_view->seq_config()->position()); } } view_ = std::move(latest_view); } }
#include "libzlog/view_reader.h" #include "include/zlog/backend.h" #include "log_backend.h" #include <iostream> // TODO: client requests that see a nullptr sequencer shoudl block and wait for // updates // TODO: use a smarter index for epoch waiters // TODO build a log's initial view for exclusive sequencers namespace zlog { ViewReader::ViewReader( const std::shared_ptr<LogBackend> backend, const Options& options) : shutdown_(false), backend_(backend), options_(options), view_(nullptr), refresh_thread_(std::thread(&ViewReader::refresh_entry_, this)) { assert(backend); } ViewReader::~ViewReader() { { std::lock_guard<std::mutex> lk(lock_); if (shutdown_) { assert(refresh_waiters_.empty()); assert(!refresh_thread_.joinable()); return; } } shutdown(); std::lock_guard<std::mutex> lk(lock_); assert(shutdown_); assert(refresh_waiters_.empty()); assert(!refresh_thread_.joinable()); } void ViewReader::shutdown() { { std::lock_guard<std::mutex> lk(lock_); shutdown_ = true; } refresh_cond_.notify_one(); refresh_thread_.join(); } void ViewReader::refresh_entry_() { while (true) { { std::unique_lock<std::mutex> lk(lock_); refresh_cond_.wait(lk, [&] { return !refresh_waiters_.empty() || shutdown_; }); if (shutdown_) { for (auto waiter : refresh_waiters_) { waiter->done = true; waiter->cond.notify_one(); } refresh_waiters_.clear(); break; } } refresh_view(); const auto current_view = view(); if (!current_view) { continue; } std::lock_guard<std::mutex> lk(lock_); for (auto it = refresh_waiters_.begin(); it != refresh_waiters_.end();) { auto waiter = *it; if (current_view->epoch() > waiter->epoch) { waiter->done = true; waiter->cond.notify_one(); it = refresh_waiters_.erase(it); } else { it++; } } } } std::shared_ptr<const VersionedView> ViewReader::view() const { std::lock_guard<std::mutex> lk(lock_); return view_; } void ViewReader::wait_for_newer_view(const uint64_t epoch) { std::unique_lock<std::mutex> lk(lock_); if (shutdown_) { return; } // TODO: is it necessary to hold the lock while initializing the waiter object // that will be read by the refresher thread? RefreshWaiter waiter(epoch); refresh_waiters_.emplace_back(&waiter); refresh_cond_.notify_one(); waiter.cond.wait(lk, [&waiter] { return waiter.done; }); } std::unique_ptr<VersionedView> ViewReader::get_latest_view() const { std::map<uint64_t, std::string> views; int ret = backend_->ReadViews(0, 1, &views); if (ret) { std::cerr << "get_latest_view failed to read view " << ret << std::endl; return nullptr; } const auto it = views.crbegin(); if (it == views.crend()) { std::cerr << "get_latest_view no views found" << std::endl; // this would happen if there are no views return nullptr; } return std::unique_ptr<VersionedView>( new VersionedView(it->first, it->second)); } void ViewReader::refresh_view() { auto latest_view = get_latest_view(); if (!latest_view) { std::cerr << "refresh_view failed to get latest view" << std::endl; return; } assert(!latest_view->seq); std::lock_guard<std::mutex> lk(lock_); if (view_) { assert(latest_view->epoch() >= view_->epoch()); if (latest_view->epoch() == view_->epoch()) { return; } } // if the latest view has a sequencer config and secret that matches this log // client instance, then we will become a sequencer / exclusive writer. if (latest_view->seq_config() && latest_view->seq_config()->secret() == backend_->secret()) { // there are two cases for initializing the new view's sequencer: // // 1) reuse sequencer from previous view // 2) create a new sequencer instance // // if a previous view has a sequencer with the same secret, then we might be // able to reuse it. however, if the previous view that we have and the // latest view are separated by views with _other_ sequencers in the log, // but which we haven't observed, then we need to take that into account. // in order to catch this scenario, we also check that the previous view has // an initialization epoch that matches the epoch in the latest view's // sequencer config. // // the sequencer config in a view either copied or a new sequencer config is // proposed. whenver a sequencer config is successfully proposed, it's // initialization epoch will be unique (even for different proposals from // the same log client). so, if the secret and the initialization epoch are // equal, then we can be assured that the sequencer hasn't changed and we // can reuse the state. // if (view_ && view_->seq_config() && view_->seq_config()->secret() == backend_->secret() && view_->seq_config()->epoch() == latest_view->seq_config()->epoch()) { // // note about thread safety. here we copy the pointer to the existing // sequencer which may be in-use concurrently. it wouldn't be sufficient // to create a new sequencer object initialized with the existing state // (we could miss updates to the seq state until all new threads saw the // new view) unless concurrent updates were blocked by a lock, but that // would introduce a lock on the i/o path. // assert(view_->seq); latest_view->seq = view_->seq; } else { // create a new instance for this sequencer latest_view->seq = std::make_shared<Sequencer>(latest_view->epoch(), latest_view->seq_config()->position()); } } view_ = std::move(latest_view); } }
simplify waiter mgmt locking
view_reader: simplify waiter mgmt locking Signed-off-by: Noah Watkins <[email protected]>
C++
lgpl-2.1
noahdesu/zlog,noahdesu/zlog,noahdesu/zlog,noahdesu/zlog,noahdesu/zlog
ca7b579b8430a512826dc0da7c4d8f24ea515caa
rsocket/examples/resumption/WarmResumption_Client.cpp
rsocket/examples/resumption/WarmResumption_Client.cpp
// Copyright (c) Facebook, Inc. and its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <folly/init/Init.h> #include <folly/io/async/ScopedEventBaseThread.h> #include <folly/portability/GFlags.h> #include "rsocket/RSocket.h" #include "rsocket/examples/util/ExampleSubscriber.h" #include "rsocket/internal/ClientResumeStatusCallback.h" #include "rsocket/transports/tcp/TcpConnectionFactory.h" #include "yarpl/Flowable.h" using namespace rsocket_example; using namespace rsocket; DEFINE_string(host, "localhost", "host to connect to"); DEFINE_int32(port, 9898, "host:port to connect to"); namespace { class HelloSubscriber : public yarpl::flowable::Subscriber<Payload> { public: void request(int n) { LOG(INFO) << "... requesting " << n; while (!subscription_) { std::this_thread::yield(); } subscription_->request(n); } void cancel() { if (auto subscription = std::move(subscription_)) { subscription->cancel(); } } int rcvdCount() const { return count_; }; protected: void onSubscribe(std::shared_ptr<yarpl::flowable::Subscription> subscription) noexcept override { subscription_ = subscription; } void onNext(Payload element) noexcept override { LOG(INFO) << "Received: " << element.moveDataToString() << std::endl; count_++; } void onComplete() noexcept override { LOG(INFO) << "Received: onComplete"; } void onError(folly::exception_wrapper) noexcept override { LOG(INFO) << "Received: onError "; } private: std::shared_ptr<yarpl::flowable::Subscription> subscription_{nullptr}; std::atomic<int> count_{0}; }; } // namespace std::unique_ptr<RSocketClient> getClientAndRequestStream( folly::EventBase* eventBase, std::shared_ptr<HelloSubscriber> subscriber) { folly::SocketAddress address; address.setFromHostPort(FLAGS_host, FLAGS_port); SetupParameters setupParameters; setupParameters.resumable = true; auto client = RSocket::createConnectedClient( std::make_unique<TcpConnectionFactory>( *eventBase, std::move(address)), std::move(setupParameters)) .get(); client->getRequester()->requestStream(Payload("Jane"))->subscribe(subscriber); return client; } int main(int argc, char* argv[]) { FLAGS_logtostderr = true; FLAGS_minloglevel = 0; folly::init(&argc, &argv); folly::ScopedEventBaseThread worker1; auto subscriber1 = std::make_shared<HelloSubscriber>(); auto client = getClientAndRequestStream(worker1.getEventBase(), subscriber1); subscriber1->request(7); while (subscriber1->rcvdCount() < 3) { std::this_thread::yield(); } client->disconnect(std::runtime_error("disconnect triggered from client")); folly::ScopedEventBaseThread worker2; client->resume() .via(worker2.getEventBase()) .then([subscriber1] { // continue with the old client. subscriber1->request(3); while (subscriber1->rcvdCount() < 10) { std::this_thread::yield(); } subscriber1->cancel(); }) .onError([&](folly::exception_wrapper ex) { LOG(INFO) << "Resumption Failed: " << ex.what(); try { ex.throw_exception(); } catch (const ResumptionException& e) { LOG(INFO) << "ResumptionException"; } catch (const ConnectionException& e) { LOG(INFO) << "ConnectionException"; } catch (const std::exception& e) { LOG(INFO) << "UnknownException " << typeid(e).name(); } // Create a new client auto subscriber2 = std::make_shared<HelloSubscriber>(); auto client = getClientAndRequestStream(worker1.getEventBase(), subscriber2); subscriber2->request(7); while (subscriber2->rcvdCount() < 7) { std::this_thread::yield(); } subscriber2->cancel(); }); getchar(); return 0; }
// Copyright (c) Facebook, Inc. and its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <folly/init/Init.h> #include <folly/io/async/ScopedEventBaseThread.h> #include <folly/portability/GFlags.h> #include "rsocket/RSocket.h" #include "rsocket/examples/util/ExampleSubscriber.h" #include "rsocket/internal/ClientResumeStatusCallback.h" #include "rsocket/transports/tcp/TcpConnectionFactory.h" #include "yarpl/Flowable.h" using namespace rsocket_example; using namespace rsocket; DEFINE_string(host, "localhost", "host to connect to"); DEFINE_int32(port, 9898, "host:port to connect to"); namespace { class HelloSubscriber : public yarpl::flowable::Subscriber<Payload> { public: void request(int n) { LOG(INFO) << "... requesting " << n; while (!subscription_) { std::this_thread::yield(); } subscription_->request(n); } void cancel() { if (auto subscription = std::move(subscription_)) { subscription->cancel(); } } int rcvdCount() const { return count_; }; protected: void onSubscribe(std::shared_ptr<yarpl::flowable::Subscription> subscription) noexcept override { subscription_ = subscription; } void onNext(Payload element) noexcept override { LOG(INFO) << "Received: " << element.moveDataToString() << std::endl; count_++; } void onComplete() noexcept override { LOG(INFO) << "Received: onComplete"; } void onError(folly::exception_wrapper) noexcept override { LOG(INFO) << "Received: onError "; } private: std::shared_ptr<yarpl::flowable::Subscription> subscription_{nullptr}; std::atomic<int> count_{0}; }; } // namespace std::unique_ptr<RSocketClient> getClientAndRequestStream( folly::EventBase* eventBase, std::shared_ptr<HelloSubscriber> subscriber) { folly::SocketAddress address; address.setFromHostPort(FLAGS_host, FLAGS_port); SetupParameters setupParameters; setupParameters.resumable = true; auto client = RSocket::createConnectedClient( std::make_unique<TcpConnectionFactory>( *eventBase, std::move(address)), std::move(setupParameters)) .get(); client->getRequester()->requestStream(Payload("Jane"))->subscribe(subscriber); return client; } int main(int argc, char* argv[]) { FLAGS_logtostderr = true; FLAGS_minloglevel = 0; folly::init(&argc, &argv); folly::ScopedEventBaseThread worker1; auto subscriber1 = std::make_shared<HelloSubscriber>(); auto client = getClientAndRequestStream(worker1.getEventBase(), subscriber1); subscriber1->request(7); while (subscriber1->rcvdCount() < 3) { std::this_thread::yield(); } client->disconnect(std::runtime_error("disconnect triggered from client")); folly::ScopedEventBaseThread worker2; client->resume() .via(worker2.getEventBase()) .thenValue([subscriber1](folly::Unit) { // continue with the old client. subscriber1->request(3); while (subscriber1->rcvdCount() < 10) { std::this_thread::yield(); } subscriber1->cancel(); }) .onError([&](folly::exception_wrapper ex) { LOG(INFO) << "Resumption Failed: " << ex.what(); try { ex.throw_exception(); } catch (const ResumptionException& e) { LOG(INFO) << "ResumptionException"; } catch (const ConnectionException& e) { LOG(INFO) << "ConnectionException"; } catch (const std::exception& e) { LOG(INFO) << "UnknownException " << typeid(e).name(); } // Create a new client auto subscriber2 = std::make_shared<HelloSubscriber>(); auto client = getClientAndRequestStream(worker1.getEventBase(), subscriber2); subscriber2->request(7); while (subscriber2->rcvdCount() < 7) { std::this_thread::yield(); } subscriber2->cancel(); }); getchar(); return 0; }
fix a compile error in the examples
fix a compile error in the examples Summary: Fix the resumption example so it builds again. Reviewed By: yfeldblum Differential Revision: D12813736 fbshipit-source-id: db2c877c70a0f90579cd6bb38f7dc567988ea1d1
C++
unknown
ReactiveSocket/reactivesocket-cpp,ReactiveSocket/reactivesocket-cpp,rsocket/rsocket-cpp,phoad/rsocket-cpp,phoad/rsocket-cpp,phoad/rsocket-cpp,rsocket/rsocket-cpp,rsocket/rsocket-cpp,rsocket/rsocket-cpp,phoad/rsocket-cpp,ReactiveSocket/reactivesocket-cpp,phoad/rsocket-cpp
76502ae91923b36b479c7116b1c6348cd0164230
main.cc
main.cc
#include <GL/glew.h> #define GLM_SWIZZLE #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <SDL/SDL.h> #include <list> #include <algorithm> #include <functional> #include "RenderingContext.h" #include "scene/GraphNode.h" #include "scene/Skybox.h" #include "scene/Terrain.h" #include "scene/Mech.h" #include "animations/Animation.h" GraphNode *scene = NULL; RenderingContext *rc; std::list<Animation*> animations; class TestSceneRotation : public Animation { private: float rotation; GraphNode* subject; public: TestSceneRotation(GraphNode* subject) : subject(subject) { rotation = 0; }; virtual void update(float timestep) { glm::vec4 cam_pos = subject->getWorldCoordinates( glm::rotate(rotation, glm::vec3(0.0f, 1.0f, 0.0f)) * glm::vec4(0.0f, 1.0f, 3.0f, 1.0f)); rc->setCamera(cam_pos.xyz(), subject); rotation += timestep*8; while (rotation > 360.0f) rotation -= 360.0f; } }; class MechWalk : public Animation { private: Mech* subject; Terrain* terrain; public: MechWalk(Mech* subject, Terrain* terrain) : subject(subject), terrain(terrain) {}; virtual void update(float timestep) { glm::vec4 current_pos = subject->getWorldCoordinates(); glm::vec3 new_pos(current_pos.x, terrain->getHeight(current_pos.x, current_pos.z), current_pos.z); subject->setPosition(new_pos.x, new_pos.y, new_pos.z); } }; void reshape(int width, int height) { glViewport(0, 0, (GLint) width, (GLint) height); rc->reshape(width, height); } /// Sets up rendering and creates the initial scene graph. void init_scene() { static GLfloat pos[4] = {5.0, 5.0, 10.0, 0.0}; glLightfv(GL_LIGHT0, GL_POSITION, pos); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_NORMALIZE); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_TEXTURE_2D); //glEnable(GL_MULTISAMPLE); scene = new GraphNode; scene->addMember(new Skybox); Mech *mech = new Mech(); scene->addMember(mech); //mech->setVisibility(false); Terrain *terrain = new Terrain("textures/heightmap.bmp", 5.0f); scene->addMember(terrain); rc = new RenderingContext(scene); rc->setCamera(glm::vec3(0.0f, 1.0f, -3.0f), mech); animations.push_back(new TestSceneRotation(mech)); animations.push_back(new MechWalk(mech, terrain)); } /// Sets up a new frame and renders the scene. void draw_scene() { rc->update(); GLenum error = glGetError(); if (error != GL_NO_ERROR) puts((const char*)gluErrorString(error)); } /// Updates scene state void update_scene(float timestep) { std::for_each( animations.begin(), animations.end(), std::bind2nd(std::mem_fun(&Animation::update), timestep)); } int main(int argc, char const *argv[]) { SDL_Surface *screen; Uint8 *keys; if (0 != SDL_Init(SDL_INIT_EVERYTHING)) return 1; SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); //SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 1); screen = SDL_SetVideoMode(800, 600, 32, SDL_OPENGL|SDL_RESIZABLE); if ( ! screen ) { puts(SDL_GetError()); SDL_Quit(); exit(2); } SDL_WM_SetCaption("Mech", "mech"); glewInit(); init_scene(); reshape(screen->w, screen->h); Uint32 previous_ticks = SDL_GetTicks(); Uint32 fps_prev_t = previous_ticks, frames = 0; int done = 0; SDL_Event event; while (!done) { while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_VIDEORESIZE: screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 16, SDL_OPENGL|SDL_RESIZABLE); if (screen) reshape(screen->w, screen->h); break; case SDL_QUIT: done = 1; break; } } keys = SDL_GetKeyState(NULL); if (keys[SDLK_ESCAPE]) { done = 1; } // update Uint32 t = SDL_GetTicks(); update_scene((float)(t - previous_ticks) / 1000.0f); previous_ticks = t; // count FPS frames++; if (fps_prev_t + 5000 < t) { printf("FPS: %f\n", (float)frames / ((float)(t - fps_prev_t) / 1000.0f)); fps_prev_t = t; frames = 0; } // render draw_scene(); } SDL_Quit(); delete scene; return 0; }
#include <GL/glew.h> #define GLM_SWIZZLE #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <SDL/SDL.h> #include <list> #include <algorithm> #include <functional> #include "RenderingContext.h" #include "scene/GraphNode.h" #include "scene/Skybox.h" #include "scene/Terrain.h" #include "scene/Mech.h" #include "animations/Animation.h" GraphNode *scene = NULL; RenderingContext *rc; std::list<Animation*> animations; class TestSceneRotation : public Animation { private: float rotation; GraphNode* subject; public: TestSceneRotation(GraphNode* subject) : subject(subject) { rotation = 0; }; virtual void update(float timestep) { glm::vec4 cam_pos = subject->getWorldCoordinates( glm::rotate(rotation, glm::vec3(0.0f, 1.0f, 0.0f)) * glm::vec4(0.0f, 1.0f, 3.0f, 1.0f)); rc->setCamera(cam_pos.xyz(), subject); rotation += timestep*8; while (rotation > 360.0f) rotation -= 360.0f; } }; class MechWalk : public Animation { private: Mech* subject; Terrain* terrain; public: MechWalk(Mech* subject, Terrain* terrain) : subject(subject), terrain(terrain) {}; virtual void update(float timestep) { glm::vec4 current_pos = subject->getWorldCoordinates(); glm::vec3 new_pos(current_pos.x, terrain->getHeight(current_pos.x, current_pos.z), current_pos.z); subject->setPosition(new_pos.x, new_pos.y, new_pos.z); } }; void reshape(int width, int height) { glViewport(0, 0, (GLint) width, (GLint) height); rc->reshape(width, height); } /// Sets up rendering and creates the initial scene graph. void init_scene() { static GLfloat pos[4] = {5.0, 5.0, 10.0, 0.0}; glLightfv(GL_LIGHT0, GL_POSITION, pos); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_NORMALIZE); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_TEXTURE_2D); //glEnable(GL_MULTISAMPLE); scene = new GraphNode; scene->addMember(new Skybox); Mech *mech = new Mech(); scene->addMember(mech); //mech->setVisibility(false); Terrain *terrain = new Terrain("textures/heightmap.bmp", 5.0f); scene->addMember(terrain); rc = new RenderingContext(scene); rc->setCamera(glm::vec3(0.0f, 1.0f, -3.0f), mech); animations.push_back(new TestSceneRotation(mech)); animations.push_back(new MechWalk(mech, terrain)); } /// Sets up a new frame and renders the scene. void draw_scene() { rc->update(); GLenum error = glGetError(); if (error != GL_NO_ERROR) puts((const char*)gluErrorString(error)); } /// Updates scene state void update_scene(float timestep) { std::for_each( animations.begin(), animations.end(), std::bind2nd(std::mem_fun(&Animation::update), timestep)); } int main(int argc, char const *argv[]) { SDL_Surface *screen; Uint8 *keys; if (0 != SDL_Init(SDL_INIT_EVERYTHING)) return 1; // Do we have a joystick? printf("%i joysticks were found.\n", SDL_NumJoysticks() ); for (int i=0; i < SDL_NumJoysticks(); i++) { printf(" %s\n", SDL_JoystickName(i)); } // Set up an OpenGL window SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); //SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 1); screen = SDL_SetVideoMode(800, 600, 32, SDL_OPENGL|SDL_RESIZABLE); if ( ! screen ) { puts(SDL_GetError()); SDL_Quit(); exit(2); } SDL_WM_SetCaption("Mech", "mech"); glewInit(); init_scene(); reshape(screen->w, screen->h); Uint32 previous_ticks = SDL_GetTicks(); Uint32 fps_prev_t = previous_ticks, frames = 0; int done = 0; SDL_Event event; while (!done) { while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_VIDEORESIZE: screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 16, SDL_OPENGL|SDL_RESIZABLE); if (screen) reshape(screen->w, screen->h); break; case SDL_QUIT: done = 1; break; } } keys = SDL_GetKeyState(NULL); if (keys[SDLK_ESCAPE]) { done = 1; } // update Uint32 t = SDL_GetTicks(); update_scene((float)(t - previous_ticks) / 1000.0f); previous_ticks = t; // count FPS frames++; if (fps_prev_t + 5000 < t) { printf("FPS: %f\n", (float)frames / ((float)(t - fps_prev_t) / 1000.0f)); fps_prev_t = t; frames = 0; } // render draw_scene(); } SDL_Quit(); delete scene; return 0; }
Test joystick enumaration.
Test joystick enumaration.
C++
mit
pstiasny/derpengine,pstiasny/derpengine
e1ba56ad0f556f5b7b266a326ffe6ecf85f12f42
pns.cpp
pns.cpp
#include <assert.h> #include <stdio.h> #include <string.h> #include <sstream> #include "board.h" #include "egtb.h" #include "logging.h" #include "movegen.h" #include "pns.h" #include "stringutil.h" #include "zobrist.h" Pns::Pns(int nodeMax, int moveMax, int childMax, int parentMax, Pns* pn1) { this->nodeMax = nodeMax; this->moveMax = moveMax; this->childMax = childMax; this->parentMax = parentMax; this->pn1 = pn1; this->node = (PnsNode*)malloc(nodeMax * sizeof(PnsNode)); this->move = (Move*)malloc(moveMax * sizeof(Move)); this->child = (int*)malloc(childMax * sizeof(int)); this->parent = (PnsNodeList*)malloc(parentMax * sizeof(PnsNodeList)); reset(); } u64 Pns::getProof() { return node[0].proof; } u64 Pns::getDisproof() { return node[0].disproof; } PnsNode* Pns::getNode(int t) { assert(t < nodeSize); return &node[t]; } Move Pns::getMove(int m) { assert(m < moveSize); return move[m]; } int Pns::getNumParents(PnsNode* t) { int result = 0; int p = t->parent; while (p != NIL) { p = parent[p].next; result++; } return result; } int Pns::getParent(PnsNode* t, int k) { int p = t->parent; while (p != NIL && k) { p = parent[p].next; k--; } assert(p != NIL); return parent[p].node; } void Pns::reset() { nodeSize = moveSize = childSize = parentSize = 0; trans.clear(); } int Pns::allocateLeaf() { assert(nodeSize < nodeMax); node[nodeSize].proof = 1; node[nodeSize].disproof = 1; node[nodeSize].numChildren = 0; node[nodeSize].parent = NIL; return nodeSize++; } int Pns::allocateMoves(int n) { moveSize += n; assert(moveSize <= moveMax); return moveSize - n; } /* Creates child pointers in the statically allocated memory */ int Pns::allocateChildren(int n) { childSize += n; assert(childSize <= childMax); return childSize - n; } void Pns::addParent(int childIndex, int parentIndex) { if (parentIndex != NIL) { assert(parentSize < parentMax); parent[parentSize].node = parentIndex; parent[parentSize].next = node[childIndex].parent; node[childIndex].parent = parentSize++; } } void Pns::printTree(int t, int level) { for (int i = 0; i < node[t].numChildren; i++) { for (int j = 0; j < level; j++) { printf(" "); } Move m = move[node[t].move + i]; int c = child[node[t].child + i]; string from = SQUARE_NAME(m.from); string to = SQUARE_NAME(m.to); printf("%s%s %llu/%llu\n", from.c_str(), to.c_str(), node[c].proof, node[c].disproof); printTree(c, level + 1); } } void Pns::hashAncestors(int t) { bool insertSuccess = ancestors.insert(t).second; if (insertSuccess) { // new element int p = node[t].parent; while (p != NIL) { hashAncestors(parent[p].node); p = parent[p].next; } } } int Pns::selectMpn(Board *b) { int t = 0; // Start at the root while (node[t].numChildren) { int i = 0, c = node[t].child; while ((i < node[t].numChildren) && (node[child[c]].disproof != node[t].proof)) { i++; c++; } assert(i < node[t].numChildren); makeMove(b, move[node[t].move + i]); t = child[c]; } ancestors.clear(); hashAncestors(t); return t; } void Pns::setScoreNoMoves(int t, Board *b) { int indexMe = (b->side == WHITE) ? BB_WALL : BB_BALL; int indexOther = BB_WALL + BB_BALL - indexMe; int countMe = popCount(b->bb[indexMe]); int countOther = popCount(b->bb[indexOther]); // international rules: can win or draw, but never lose node[t].proof = (countMe < countOther) ? 0 : INFTY64; node[t].disproof = INFTY64; } void Pns::setScoreEgtb(int t, int score) { if (score == EGTB_DRAW) { // EGTB draw node[t].proof = INFTY64; node[t].disproof = INFTY64; } else if (score > 0) { // EGTB win node[t].proof = 0; node[t].disproof = INFTY64; } else { // EGTB loss node[t].proof = INFTY64; node[t].disproof = 0; } } void Pns::copyMovesFromPn1() { memcpy(move + moveSize, pn1->move + pn1->node[0].move, pn1->node[0].numChildren * sizeof(Move)); } bool Pns::expand(int t, Board *b) { // Looking up the board in EGTB is unnecessary in PN2. However, it is // relatively cheap so we do it for clarity. int score = egtbLookup(b); if (score != EGTB_UNKNOWN) { setScoreEgtb(t, score); // EGTB node return true; } int nc; if (pn1) { Board bc = *b; printBoard(b); pn1->analyzeBoard(&bc); log(LOG_INFO, "Back from PN1"); nc = pn1->node[0].numChildren; copyMovesFromPn1(); } else { nc = getAllMoves(b, move + moveSize, FORWARD); } node[t].numChildren = nc; if (!nc) { // No legal moves setScoreNoMoves(t, b); return true; } if (nodeSize + nc > nodeMax) { // not enough room left to expand return false; } node[t].move = allocateMoves(nc); // a bit unsound, we already used the space node[t].child = allocateChildren(nc); u64 z = getZobrist(b); for (int i = 0; i < nc; i++) { int c = node[t].child + i; u64 z2 = updateZobrist(z, b, move[node[t].move + i]); int orig = trans[z2]; if (!orig) { // Regular child child[c] = allocateLeaf(); trans[z2] = child[c]; if (pn1) { // copy the i-th child's proof/disproof values from the PN1 root int pn1c = pn1->node[0].child + i; node[child[c]].proof = pn1->node[pn1c].proof; node[child[c]].disproof = pn1->node[pn1c].disproof; } } else if (ancestors.find(orig) == ancestors.end()) { // Transposition child[c] = orig; } else { // Repetition child[c] = allocateLeaf(); node[child[c]].proof = node[child[c]].disproof = INFTY64; } addParent(child[c], t); } return true; } void Pns::update(int t) { if (node[t].numChildren) { // If t has no children, then presumably it's a stalemate or EGTB position, so it already has correct P/D values. u64 p = INFTY64, d = 0; for (int i = 0; i < node[t].numChildren; i++) { int c = child[node[t].child + i]; p = MIN(p, node[c].disproof); d += node[c].proof; } node[t].proof = p; node[t].disproof = MIN(d, INFTY64); } int u = node[t].parent; while (u != NIL) { update(parent[u].node); u = parent[u].next; } } void Pns::analyzeBoard(Board *b) { reset(); allocateLeaf(); bool full = false; while (!full && node[0].proof && node[0].disproof && (node[0].proof < INFTY64 || node[0].disproof < INFTY64)) { Board current = *b; int mpn = selectMpn(&current); if (expand(mpn, &current)) { update(mpn); if (pn1) { printf("root: %llu/%llu\n", node[0].proof, node[0].disproof); printTree(0, 0); } } else { full = true; } } log(LOG_INFO, "Tree size %d, proof %llu, disproof %llu", nodeSize, node[0].proof, node[0].disproof); log(LOG_INFO, "Usage: nodes %d/%d moves %d/%d children %d/%d parents %d/%d", nodeSize, nodeMax, moveSize, moveMax, childSize, childMax, parentSize, parentMax); } void Pns::analyzeString(string input, string fileName) { Board *b; if (isFen(input)) { // Input is a board in FEN notation b = fenToBoard(input.c_str()); } else { // Input is a sequence of moves. Tokenize it. stringstream in(input); string moves[MAX_MOVES]; int n = 0; while (in.good() && n < MAX_MOVES){ in >> moves[n++]; } if (moves[n - 1].empty()) { n--; } b = makeMoveSequence(n, moves); } loadTree(b, fileName); analyzeBoard(b); saveTree(b, fileName); free(b); } void Pns::saveTree(Board *b, string fileName) { FILE *f = fopen(fileName.c_str(), "w"); fwrite(b, sizeof(Board), 1, f); fwrite(&nodeSize, sizeof(nodeSize), 1, f); fwrite(&nodeMax, sizeof(nodeMax), 1, f); fwrite(node, sizeof(PnsNode), nodeSize, f); fwrite(&moveSize, sizeof(moveSize), 1, f); fwrite(&moveMax, sizeof(moveMax), 1, f); fwrite(move, sizeof(Move), moveSize, f); fwrite(&childSize, sizeof(childSize), 1, f); fwrite(&childMax, sizeof(childMax), 1, f); fwrite(child, sizeof(int), childSize, f); fwrite(&parentSize, sizeof(parentSize), 1, f); fwrite(&parentMax, sizeof(parentMax), 1, f); fwrite(parent, sizeof(PnsNodeList), parentSize, f); fclose(f); } void Pns::loadTree(Board *b, string fileName) { FILE *f = fopen(fileName.c_str(), "r"); if (f) { Board b2; assert(fread(&b2, sizeof(Board), 1, f) == 1); if (!equalBoard(b, &b2)) { printBoard(&b2); die("Input file stores a PN^2 tree for a different board (see above)."); } assert(fread(&nodeSize, sizeof(nodeSize), 1, f) == 1); assert(fread(&nodeMax, sizeof(nodeMax), 1, f) == 1); assert((int)fread(node, sizeof(PnsNode), nodeSize, f) == nodeSize); assert(fread(&moveSize, sizeof(moveSize), 1, f) == 1); assert(fread(&moveMax, sizeof(moveMax), 1, f) == 1); assert((int)fread(move, sizeof(Move), moveSize, f) == moveSize); assert(fread(&childSize, sizeof(childSize), 1, f) == 1); assert(fread(&childMax, sizeof(childMax), 1, f) == 1); assert((int)fread(child, sizeof(int), childSize, f) == childSize); assert(fread(&parentSize, sizeof(parentSize), 1, f) == 1); assert(fread(&parentMax, sizeof(parentMax), 1, f) == 1); assert((int)fread(parent, sizeof(PnsNodeList), parentSize, f) == parentSize); fclose(f); log(LOG_INFO, "Loaded tree from %s.", fileName.c_str()); } else if (errno == ENOENT) { // File does not exist log(LOG_INFO, "File %s does not exist, creating new tree.", fileName.c_str()); int t = allocateLeaf(); trans[getZobrist(b)] = t; } else { // File exists, but cannot be read for other reasons die("Input file [%s] exists, but cannot be read.", fileName.c_str()); } }
#include <assert.h> #include <stdio.h> #include <string.h> #include <sstream> #include "board.h" #include "egtb.h" #include "logging.h" #include "movegen.h" #include "pns.h" #include "stringutil.h" #include "zobrist.h" Pns::Pns(int nodeMax, int moveMax, int childMax, int parentMax, Pns* pn1) { this->nodeMax = nodeMax; this->moveMax = moveMax; this->childMax = childMax; this->parentMax = parentMax; this->pn1 = pn1; this->node = (PnsNode*)malloc(nodeMax * sizeof(PnsNode)); this->move = (Move*)malloc(moveMax * sizeof(Move)); this->child = (int*)malloc(childMax * sizeof(int)); this->parent = (PnsNodeList*)malloc(parentMax * sizeof(PnsNodeList)); reset(); } u64 Pns::getProof() { return node[0].proof; } u64 Pns::getDisproof() { return node[0].disproof; } PnsNode* Pns::getNode(int t) { assert(t < nodeSize); return &node[t]; } Move Pns::getMove(int m) { assert(m < moveSize); return move[m]; } int Pns::getNumParents(PnsNode* t) { int result = 0; int p = t->parent; while (p != NIL) { p = parent[p].next; result++; } return result; } int Pns::getParent(PnsNode* t, int k) { int p = t->parent; while (p != NIL && k) { p = parent[p].next; k--; } assert(p != NIL); return parent[p].node; } void Pns::reset() { nodeSize = moveSize = childSize = parentSize = 0; trans.clear(); } int Pns::allocateLeaf() { assert(nodeSize < nodeMax); node[nodeSize].proof = 1; node[nodeSize].disproof = 1; node[nodeSize].numChildren = 0; node[nodeSize].parent = NIL; return nodeSize++; } int Pns::allocateMoves(int n) { moveSize += n; assert(moveSize <= moveMax); return moveSize - n; } /* Creates child pointers in the statically allocated memory */ int Pns::allocateChildren(int n) { childSize += n; assert(childSize <= childMax); return childSize - n; } void Pns::addParent(int childIndex, int parentIndex) { if (parentIndex != NIL) { assert(parentSize < parentMax); parent[parentSize].node = parentIndex; parent[parentSize].next = node[childIndex].parent; node[childIndex].parent = parentSize++; } } void Pns::printTree(int t, int level) { for (int i = 0; i < node[t].numChildren; i++) { for (int j = 0; j < level; j++) { printf(" "); } Move m = move[node[t].move + i]; int c = child[node[t].child + i]; string from = SQUARE_NAME(m.from); string to = SQUARE_NAME(m.to); printf("%s%s %llu/%llu\n", from.c_str(), to.c_str(), node[c].proof, node[c].disproof); printTree(c, level + 1); } } void Pns::hashAncestors(int t) { bool insertSuccess = ancestors.insert(t).second; if (insertSuccess) { // new element int p = node[t].parent; while (p != NIL) { hashAncestors(parent[p].node); p = parent[p].next; } } } int Pns::selectMpn(Board *b) { int t = 0; // Start at the root while (node[t].numChildren) { int i = 0, c = node[t].child; while ((i < node[t].numChildren) && (node[child[c]].disproof != node[t].proof)) { i++; c++; } assert(i < node[t].numChildren); makeMove(b, move[node[t].move + i]); t = child[c]; } ancestors.clear(); hashAncestors(t); return t; } void Pns::setScoreNoMoves(int t, Board *b) { int indexMe = (b->side == WHITE) ? BB_WALL : BB_BALL; int indexOther = BB_WALL + BB_BALL - indexMe; int countMe = popCount(b->bb[indexMe]); int countOther = popCount(b->bb[indexOther]); // international rules: can win or draw, but never lose node[t].proof = (countMe < countOther) ? 0 : INFTY64; node[t].disproof = INFTY64; } void Pns::setScoreEgtb(int t, int score) { if (score == EGTB_DRAW) { // EGTB draw node[t].proof = INFTY64; node[t].disproof = INFTY64; } else if (score > 0) { // EGTB win node[t].proof = 0; node[t].disproof = INFTY64; } else { // EGTB loss node[t].proof = INFTY64; node[t].disproof = 0; } } void Pns::copyMovesFromPn1() { memcpy(move + moveSize, pn1->move + pn1->node[0].move, pn1->node[0].numChildren * sizeof(Move)); } bool Pns::expand(int t, Board *b) { // Looking up the board in EGTB is unnecessary in PN2. However, it is // relatively cheap so we do it for clarity. int score = egtbLookup(b); if (score != EGTB_UNKNOWN) { setScoreEgtb(t, score); // EGTB node return true; } int nc; if (pn1) { Board bc = *b; printBoard(b); pn1->analyzeBoard(&bc); log(LOG_INFO, "Back from PN1"); nc = pn1->node[0].numChildren; copyMovesFromPn1(); } else { nc = getAllMoves(b, move + moveSize, FORWARD); } node[t].numChildren = nc; if (!nc) { // No legal moves setScoreNoMoves(t, b); return true; } if (nodeSize + nc > nodeMax) { // not enough room left to expand return false; } node[t].move = allocateMoves(nc); // a bit unsound, we already used the space node[t].child = allocateChildren(nc); u64 z = getZobrist(b); for (int i = 0; i < nc; i++) { int c = node[t].child + i; u64 z2 = updateZobrist(z, b, move[node[t].move + i]); int orig = trans[z2]; if (!orig) { // Regular child child[c] = allocateLeaf(); trans[z2] = child[c]; if (pn1) { // copy the i-th child's proof/disproof values from the PN1 root int pn1c = pn1->node[0].child + i; node[child[c]].proof = pn1->node[pn1c].proof; node[child[c]].disproof = pn1->node[pn1c].disproof; } } else if (ancestors.find(orig) == ancestors.end()) { // Transposition child[c] = orig; } else { // Repetition child[c] = allocateLeaf(); node[child[c]].proof = node[child[c]].disproof = INFTY64; } addParent(child[c], t); } return true; } void Pns::update(int t) { u64 origP = node[t].proof, origD = node[t].disproof; bool changed = true; if (node[t].numChildren) { // If t has no children, then presumably it's a stalemate or EGTB position, so it already has correct P/D values. u64 p = INFTY64, d = 0; for (int i = 0; i < node[t].numChildren; i++) { int c = child[node[t].child + i]; p = MIN(p, node[c].disproof); d += node[c].proof; } d = MIN(d, INFTY64); if (origP != p || origD != d) { node[t].proof = p; node[t].disproof = d; } else { changed = false; } } if (changed) { int u = node[t].parent; while (u != NIL) { update(parent[u].node); u = parent[u].next; } } } void Pns::analyzeBoard(Board *b) { reset(); allocateLeaf(); bool full = false; while (!full && node[0].proof && node[0].disproof && (node[0].proof < INFTY64 || node[0].disproof < INFTY64)) { Board current = *b; int mpn = selectMpn(&current); if (expand(mpn, &current)) { update(mpn); if (pn1) { printf("root: %llu/%llu\n", node[0].proof, node[0].disproof); printTree(0, 0); } } else { full = true; } } log(LOG_INFO, "Tree size %d, proof %llu, disproof %llu", nodeSize, node[0].proof, node[0].disproof); log(LOG_INFO, "Usage: nodes %d/%d moves %d/%d children %d/%d parents %d/%d", nodeSize, nodeMax, moveSize, moveMax, childSize, childMax, parentSize, parentMax); } void Pns::analyzeString(string input, string fileName) { Board *b; if (isFen(input)) { // Input is a board in FEN notation b = fenToBoard(input.c_str()); } else { // Input is a sequence of moves. Tokenize it. stringstream in(input); string moves[MAX_MOVES]; int n = 0; while (in.good() && n < MAX_MOVES){ in >> moves[n++]; } if (moves[n - 1].empty()) { n--; } b = makeMoveSequence(n, moves); } loadTree(b, fileName); analyzeBoard(b); saveTree(b, fileName); free(b); } void Pns::saveTree(Board *b, string fileName) { FILE *f = fopen(fileName.c_str(), "w"); fwrite(b, sizeof(Board), 1, f); fwrite(&nodeSize, sizeof(nodeSize), 1, f); fwrite(&nodeMax, sizeof(nodeMax), 1, f); fwrite(node, sizeof(PnsNode), nodeSize, f); fwrite(&moveSize, sizeof(moveSize), 1, f); fwrite(&moveMax, sizeof(moveMax), 1, f); fwrite(move, sizeof(Move), moveSize, f); fwrite(&childSize, sizeof(childSize), 1, f); fwrite(&childMax, sizeof(childMax), 1, f); fwrite(child, sizeof(int), childSize, f); fwrite(&parentSize, sizeof(parentSize), 1, f); fwrite(&parentMax, sizeof(parentMax), 1, f); fwrite(parent, sizeof(PnsNodeList), parentSize, f); fclose(f); } void Pns::loadTree(Board *b, string fileName) { FILE *f = fopen(fileName.c_str(), "r"); if (f) { Board b2; assert(fread(&b2, sizeof(Board), 1, f) == 1); if (!equalBoard(b, &b2)) { printBoard(&b2); die("Input file stores a PN^2 tree for a different board (see above)."); } assert(fread(&nodeSize, sizeof(nodeSize), 1, f) == 1); assert(fread(&nodeMax, sizeof(nodeMax), 1, f) == 1); assert((int)fread(node, sizeof(PnsNode), nodeSize, f) == nodeSize); assert(fread(&moveSize, sizeof(moveSize), 1, f) == 1); assert(fread(&moveMax, sizeof(moveMax), 1, f) == 1); assert((int)fread(move, sizeof(Move), moveSize, f) == moveSize); assert(fread(&childSize, sizeof(childSize), 1, f) == 1); assert(fread(&childMax, sizeof(childMax), 1, f) == 1); assert((int)fread(child, sizeof(int), childSize, f) == childSize); assert(fread(&parentSize, sizeof(parentSize), 1, f) == 1); assert(fread(&parentMax, sizeof(parentMax), 1, f) == 1); assert((int)fread(parent, sizeof(PnsNodeList), parentSize, f) == parentSize); fclose(f); log(LOG_INFO, "Loaded tree from %s.", fileName.c_str()); } else if (errno == ENOENT) { // File does not exist log(LOG_INFO, "File %s does not exist, creating new tree.", fileName.c_str()); int t = allocateLeaf(); trans[getZobrist(b)] = t; } else { // File exists, but cannot be read for other reasons die("Input file [%s] exists, but cannot be read.", fileName.c_str()); } }
Stop P/D number updates when nothing changes. 50% speed increase...
Stop P/D number updates when nothing changes. 50% speed increase...
C++
agpl-3.0
CatalinFrancu/colibri,CatalinFrancu/colibri,CatalinFrancu/colibri,CatalinFrancu/colibri
a8b601208da20c674f6eff182a2e28f4a356664c
python/py-initialize-ifaint.cpp
python/py-initialize-ifaint.cpp
// -*- coding: us-ascii-unix -*- // Copyright 2014 Lukas Kemmer // // 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 <fstream> #include "python/py-include.hh" #include "python/py-initialize-ifaint.hh" #include "python/py-bitmap.hh" #include "python/py-canvas.hh" #include "python/py-faint-singletons.hh" #include "python/py-frame-props.hh" #include "python/py-frame.hh" #include "python/py-functions.hh" #include "python/py-grid.hh" #include "python/py-linear-gradient.hh" #include "python/py-pattern.hh" #include "python/py-radial-gradient.hh" #include "python/py-settings.hh" #include "python/py-something.hh" #include "python/py-tri.hh" #include "python/py-util.hh" #include "python/python-context.hh" #include "python/py-add-type-object.hh" #include "python/py-clipboard.hh" #include "util/paint-map.hh" #include "util-wx/key-codes.hh" #include "util-wx/file-path.hh" #include "util-wx/file-path-util.hh" #include "text/formatting.hh" namespace faint{ void add_faint_types(PyObject* module){ add_type_object(module, BitmapType, "Bitmap"); add_type_object(module, PatternType, "Pattern"); add_type_object(module, SmthType, "Something"); add_type_object(module, CanvasType, "Canvas"); add_type_object(module, FrameType, "Frame"); add_type_object(module, LinearGradientType, "LinearGradient"); add_type_object(module, RadialGradientType, "RadialGradient"); add_type_object(module, SettingsType, "Settings"); add_type_object(module, TriType, "Tri"); add_type_object(module, ImagePropsType, "ImageProps"); add_type_object(module, FramePropsType, "FrameProps"); add_type_object(module, GridType, "Grid"); PyObject* binds = PyDict_New(); PyModule_AddObject(module, "_binds", binds); PyModule_AddObject(module, "LoadError", get_load_exception_type()); PyModule_AddObject(module, "SaveError", get_save_exception_type()); } static struct PyModuleDef keyModule = { PyModuleDef_HEAD_INIT, "ifaint_key", "Key identifiers", -1, // m_size nullptr, // m_methods nullptr, // m_reload nullptr, // m_traverse nullptr, // m_clear nullptr, // m_free }; static PyObject* create_key_module(){ PyObject* module = PyModule_Create(&keyModule); PyModule_AddIntConstant(module, "arrow_down", key::down); PyModule_AddIntConstant(module, "arrow_left", key::left); PyModule_AddIntConstant(module, "arrow_right", key::right); PyModule_AddIntConstant(module, "arrow_up", key::up); PyModule_AddIntConstant(module, "asterisk", key::asterisk); PyModule_AddIntConstant(module, "backspace", key::back); PyModule_AddIntConstant(module, "delete", key::del); PyModule_AddIntConstant(module, "end", key::end); PyModule_AddIntConstant(module, "f1", key::F1); PyModule_AddIntConstant(module, "f2", key::F2); PyModule_AddIntConstant(module, "f3", key::F3); PyModule_AddIntConstant(module, "f4", key::F4); PyModule_AddIntConstant(module, "f5", key::F5); PyModule_AddIntConstant(module, "f6", key::F6); PyModule_AddIntConstant(module, "f7", key::F7); PyModule_AddIntConstant(module, "f8", key::F8); PyModule_AddIntConstant(module, "f9", key::F9); PyModule_AddIntConstant(module, "f10", key::F10); PyModule_AddIntConstant(module, "f11", key::F11); PyModule_AddIntConstant(module, "f12", key::F12); PyModule_AddIntConstant(module, "home", key::home); PyModule_AddIntConstant(module, "num_minus", key::num_minus); PyModule_AddIntConstant(module, "num_plus", key::num_plus); PyModule_AddIntConstant(module, "paragraph", key::paragraph); PyModule_AddIntConstant(module, "pgdn", key::pgdn); PyModule_AddIntConstant(module, "pgup", key::pgup); PyModule_AddIntConstant(module, "space", key::space); return module; } static struct PyModuleDef pngModule = { PyModuleDef_HEAD_INIT, "ifaint_png", "PNG constants, for use with the write_png function.", -1, // m_size nullptr, // m_methods nullptr, // m_reload nullptr, // m_traverse nullptr, // m_clear nullptr, // m_free }; static PyObject* create_png_module(){ PyObject* module = PyModule_Create(&pngModule); PyModule_AddIntConstant(module, "RGB", 0); PyModule_AddIntConstant(module, "RGB_ALPHA", 1); PyModule_AddIntConstant(module, "GRAY", 2); PyModule_AddIntConstant(module, "GRAY_ALPHA", 3); return module; } static struct PyModuleDef modifierModule = { PyModuleDef_HEAD_INIT, "ifaint_mod", "Key modifier identifiers", -1, // m_size nullptr, // m_methods nullptr, // m_reload nullptr, // m_traverse nullptr, // m_clear nullptr, // m_free }; static PyObject* create_modifier_module(){ PyObject* module = PyModule_Create(&modifierModule); PyModule_AddIntConstant(module, "alt", Alt.Raw()); PyModule_AddIntConstant(module, "shift", Shift.Raw()); PyModule_AddIntConstant(module, "ctrl", Ctrl.Raw()); return module; } static struct PyModuleDef faintInterfaceModule = { PyModuleDef_HEAD_INIT, "ifaint", "ifaint\n\nThe built in functions and classes for faint-graphics-editor.\n", -1, // m_size get_py_functions(), // m_methods nullptr, // m_reload nullptr, // m_traverse nullptr, // m_clear nullptr, // m_free }; static PyObject* ifaintError; PyMODINIT_FUNC PyInit_ifaint(){ PyObject* module_ifaint = PyModule_Create(&faintInterfaceModule); assert(module_ifaint != nullptr); add_faint_types(module_ifaint); ifaintError = PyErr_NewException("ifaint.error", nullptr, nullptr); Py_INCREF(ifaintError); PyModule_AddObject(module_ifaint, "error", ifaintError); PyModule_AddObject(module_ifaint, "key", create_key_module()); PyModule_AddObject(module_ifaint, "mod", create_modifier_module()); PyModule_AddObject(module_ifaint, "png", create_png_module()); PyModule_AddObject(module_ifaint, "clipboard", create_clipboard_module()); return module_ifaint; } static void add_to_python_path(const DirPath& dirPath){ scoped_ref sys(PyImport_ImportModule("sys")); assert(sys != nullptr); auto dict = borrowed(PyModule_GetDict(sys.get())); assert(dict != nullptr); auto path = borrowed(PyDict_GetItemString(dict.get(), "path")); assert(path != nullptr); int result = PyList_Append(path.get(), build_unicode(dirPath.Str())); assert(result == 0); } static void run_envsetup(const FilePath& path){ assert(exists(path)); auto err = run_python_file(path); assert(err.NotSet()); } static void add_python_singletons(PyObject* ifaint, PyFuncContext& ctx){ // These objects require "context", are rather tightly coupled // to Faint and can not be created from the Python side. add_App(ctx, ifaint); add_global_functions(ctx, ifaint); add_dialog_functions(ctx, ifaint); add_ActiveSettings(ctx.app, ifaint); add_Palette(ctx.app, ifaint); add_Window(ctx.app, ifaint); add_Interpreter(ctx.app, ifaint); } bool init_python(const utf8_string& arg, PyFuncContext& ctx){ PyImport_AppendInittab("ifaint", PyInit_ifaint); Py_Initialize(); scoped_ref ifaint(PyImport_ImportModule("ifaint")); add_python_singletons(ifaint.get(), ctx); DirPath dataDir = get_data_dir(); add_to_python_path(dataDir.SubDir("py")); run_envsetup(dataDir.SubDir("py").SubDir("core").File("envsetup.py")); if (!arg.empty()){ auto dict = borrowed(PyModule_GetDict(ifaint.get())); PyDict_SetItemString(dict.get(), "cmd_arg", build_unicode(arg)); } return true; } void display_error_info(const FaintPyExc& info, PythonContext& python){ python.IntFaintPrint(format_error_info(info)); } Optional<FaintPyExc> run_python_file(const FilePath& path){ std::ifstream f(iostream_friendly(path)); if (!f.good()){ FaintPyExc err; err.type = "OSError"; err.message = "Failed opening " + path.Str(); return option(err); } std::string text; std::string line; while (std::getline(f, line)){ text += line + "\n"; } scoped_ref module(PyImport_ImportModule("__main__")); assert(module != nullptr); auto dict = borrowed(PyModule_GetDict(module.get())); assert(dict != nullptr); scoped_ref obj(PyRun_String(text.c_str(), Py_file_input, dict.get(), dict.get())); if (obj == nullptr){ return option(py_error_info()); } return no_option(); } static void write_python_user_config(const FilePath& dstPath, PythonContext& python) { // Rewriting the ini file instead of copying it should give // the os-correct eol markers Optional<FilePath> srcPath = make_absolute_file_path( get_data_dir().Str() + "/py/core/default_ini.py"); assert(srcPath.IsSet()); std::ifstream defaultIni(iostream_friendly(srcPath.Get())); if (!defaultIni.good()){ python.IntFaintPrint("Failed opening standard ini"); return; } std::ofstream userIni(iostream_friendly(dstPath)); std::string line; while (std::getline(defaultIni, line)){ userIni << line << std::endl; } } bool run_python_user_config(PythonContext& python){ // Execute the user's ini-script FilePath configPath(get_user_config_file_path()); if (!exists(configPath)){ // Recreate the config file from the default write_python_user_config(configPath, python); } if (exists(configPath)){ Optional<FaintPyExc> err = run_python_file(configPath); if (err.IsSet()){ python.IntFaintPrint("\n"); python.IntFaintPrint(space_sep("Error in personal config file", bracketed(quoted(configPath.Str()))) + ":\n"); display_error_info(err.Get(), python); return false; } else{ python.IntFaintPrint(space_sep("Executed personal config file at", quoted(configPath.Str())) + "\n"); return true; } } else { utf8_string userIniInfo( space_sep("Personal config file not found at", quoted(configPath.Str()))); python.IntFaintPrint(userIniInfo + "\n"); return false; } return true; } } // namespace
// -*- coding: us-ascii-unix -*- // Copyright 2014 Lukas Kemmer // // 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 <fstream> #include "python/py-include.hh" #include "python/py-initialize-ifaint.hh" #include "python/py-bitmap.hh" #include "python/py-canvas.hh" #include "python/py-faint-singletons.hh" #include "python/py-frame-props.hh" #include "python/py-frame.hh" #include "python/py-functions.hh" #include "python/py-grid.hh" #include "python/py-linear-gradient.hh" #include "python/py-pattern.hh" #include "python/py-radial-gradient.hh" #include "python/py-settings.hh" #include "python/py-something.hh" #include "python/py-tri.hh" #include "python/py-util.hh" #include "python/python-context.hh" #include "python/py-add-type-object.hh" #include "python/py-clipboard.hh" #include "util/paint-map.hh" #include "util-wx/key-codes.hh" #include "util-wx/file-path.hh" #include "util-wx/file-path-util.hh" #include "text/formatting.hh" namespace faint{ void add_faint_types(PyObject* module){ add_type_object(module, BitmapType, "Bitmap"); add_type_object(module, PatternType, "Pattern"); add_type_object(module, SmthType, "Something"); add_type_object(module, CanvasType, "Canvas"); add_type_object(module, FrameType, "Frame"); add_type_object(module, LinearGradientType, "LinearGradient"); add_type_object(module, RadialGradientType, "RadialGradient"); add_type_object(module, SettingsType, "Settings"); add_type_object(module, TriType, "Tri"); add_type_object(module, ImagePropsType, "ImageProps"); add_type_object(module, FramePropsType, "FrameProps"); add_type_object(module, GridType, "Grid"); PyObject* binds = PyDict_New(); PyModule_AddObject(module, "_binds", binds); PyModule_AddObject(module, "LoadError", get_load_exception_type()); PyModule_AddObject(module, "SaveError", get_save_exception_type()); } static struct PyModuleDef keyModule = { PyModuleDef_HEAD_INIT, "ifaint_key", "Key identifiers", -1, // m_size nullptr, // m_methods nullptr, // m_reload nullptr, // m_traverse nullptr, // m_clear nullptr, // m_free }; static PyObject* create_key_module(){ PyObject* module = PyModule_Create(&keyModule); PyModule_AddIntConstant(module, "arrow_down", key::down); PyModule_AddIntConstant(module, "arrow_left", key::left); PyModule_AddIntConstant(module, "arrow_right", key::right); PyModule_AddIntConstant(module, "arrow_up", key::up); PyModule_AddIntConstant(module, "asterisk", key::asterisk); PyModule_AddIntConstant(module, "backspace", key::back); PyModule_AddIntConstant(module, "delete", key::del); PyModule_AddIntConstant(module, "end", key::end); PyModule_AddIntConstant(module, "f1", key::F1); PyModule_AddIntConstant(module, "f2", key::F2); PyModule_AddIntConstant(module, "f3", key::F3); PyModule_AddIntConstant(module, "f4", key::F4); PyModule_AddIntConstant(module, "f5", key::F5); PyModule_AddIntConstant(module, "f6", key::F6); PyModule_AddIntConstant(module, "f7", key::F7); PyModule_AddIntConstant(module, "f8", key::F8); PyModule_AddIntConstant(module, "f9", key::F9); PyModule_AddIntConstant(module, "f10", key::F10); PyModule_AddIntConstant(module, "f11", key::F11); PyModule_AddIntConstant(module, "f12", key::F12); PyModule_AddIntConstant(module, "home", key::home); PyModule_AddIntConstant(module, "num_minus", key::num_minus); PyModule_AddIntConstant(module, "num_plus", key::num_plus); PyModule_AddIntConstant(module, "paragraph", key::paragraph); PyModule_AddIntConstant(module, "pgdn", key::pgdn); PyModule_AddIntConstant(module, "pgup", key::pgup); PyModule_AddIntConstant(module, "space", key::space); return module; } static struct PyModuleDef pngModule = { PyModuleDef_HEAD_INIT, "ifaint_png", "PNG constants, for use with the write_png function.", -1, // m_size nullptr, // m_methods nullptr, // m_reload nullptr, // m_traverse nullptr, // m_clear nullptr, // m_free }; static PyObject* create_png_module(){ PyObject* module = PyModule_Create(&pngModule); PyModule_AddIntConstant(module, "RGB", 0); PyModule_AddIntConstant(module, "RGB_ALPHA", 1); PyModule_AddIntConstant(module, "GRAY", 2); PyModule_AddIntConstant(module, "GRAY_ALPHA", 3); return module; } static struct PyModuleDef modifierModule = { PyModuleDef_HEAD_INIT, "ifaint_mod", "Key modifier identifiers", -1, // m_size nullptr, // m_methods nullptr, // m_reload nullptr, // m_traverse nullptr, // m_clear nullptr, // m_free }; static PyObject* create_modifier_module(){ PyObject* module = PyModule_Create(&modifierModule); PyModule_AddIntConstant(module, "alt", Alt.Raw()); PyModule_AddIntConstant(module, "shift", Shift.Raw()); PyModule_AddIntConstant(module, "ctrl", Ctrl.Raw()); return module; } static struct PyModuleDef faintInterfaceModule = { PyModuleDef_HEAD_INIT, "ifaint", "ifaint\n\nThe built in functions and classes for faint-graphics-editor.\n", -1, // m_size get_py_functions(), // m_methods nullptr, // m_reload nullptr, // m_traverse nullptr, // m_clear nullptr, // m_free }; static PyObject* ifaintError; PyMODINIT_FUNC PyInit_ifaint(){ PyObject* module_ifaint = PyModule_Create(&faintInterfaceModule); assert(module_ifaint != nullptr); add_faint_types(module_ifaint); ifaintError = PyErr_NewException("ifaint.error", nullptr, nullptr); Py_INCREF(ifaintError); PyModule_AddObject(module_ifaint, "error", ifaintError); PyModule_AddObject(module_ifaint, "key", create_key_module()); PyModule_AddObject(module_ifaint, "mod", create_modifier_module()); PyModule_AddObject(module_ifaint, "png", create_png_module()); PyModule_AddObject(module_ifaint, "clipboard", create_clipboard_module()); return module_ifaint; } static void prepend_to_python_path(const DirPath& dirPath){ scoped_ref sys(PyImport_ImportModule("sys")); assert(sys != nullptr); auto dict = borrowed(PyModule_GetDict(sys.get())); assert(dict != nullptr); auto path = borrowed(PyDict_GetItemString(dict.get(), "path")); assert(path != nullptr); int result = PyList_Insert(path.get(), 0, build_unicode(dirPath.Str())); assert(result == 0); } static void run_envsetup(const FilePath& path){ assert(exists(path)); auto err = run_python_file(path); assert(err.NotSet()); } static void add_python_singletons(PyObject* ifaint, PyFuncContext& ctx){ // These objects require "context", are rather tightly coupled // to Faint and can not be created from the Python side. add_App(ctx, ifaint); add_global_functions(ctx, ifaint); add_dialog_functions(ctx, ifaint); add_ActiveSettings(ctx.app, ifaint); add_Palette(ctx.app, ifaint); add_Window(ctx.app, ifaint); add_Interpreter(ctx.app, ifaint); } bool init_python(const utf8_string& arg, PyFuncContext& ctx){ PyImport_AppendInittab("ifaint", PyInit_ifaint); Py_Initialize(); scoped_ref ifaint(PyImport_ImportModule("ifaint")); add_python_singletons(ifaint.get(), ctx); DirPath dataDir = get_data_dir(); // Add the py-dir to path, so that Faint:s .py-files (in py/faint/) // are found from envsetup and the user ini. The path is prepended // so that the "faint" py module takes precedence over any // namesakes. prepend_to_python_path(dataDir.SubDir("py")); run_envsetup(dataDir.SubDir("py").SubDir("core").File("envsetup.py")); if (!arg.empty()){ auto dict = borrowed(PyModule_GetDict(ifaint.get())); PyDict_SetItemString(dict.get(), "cmd_arg", build_unicode(arg)); } return true; } void display_error_info(const FaintPyExc& info, PythonContext& python){ python.IntFaintPrint(format_error_info(info)); } Optional<FaintPyExc> run_python_file(const FilePath& path){ std::ifstream f(iostream_friendly(path)); if (!f.good()){ FaintPyExc err; err.type = "OSError"; err.message = "Failed opening " + path.Str(); return option(err); } std::string text; std::string line; while (std::getline(f, line)){ text += line + "\n"; } scoped_ref module(PyImport_ImportModule("__main__")); assert(module != nullptr); auto dict = borrowed(PyModule_GetDict(module.get())); assert(dict != nullptr); scoped_ref obj(PyRun_String(text.c_str(), Py_file_input, dict.get(), dict.get())); if (obj == nullptr){ return option(py_error_info()); } return no_option(); } static void write_python_user_config(const FilePath& dstPath, PythonContext& python) { // Rewriting the ini file instead of copying it should give // the os-correct eol markers Optional<FilePath> srcPath = make_absolute_file_path( get_data_dir().Str() + "/py/core/default_ini.py"); assert(srcPath.IsSet()); std::ifstream defaultIni(iostream_friendly(srcPath.Get())); if (!defaultIni.good()){ python.IntFaintPrint("Failed opening standard ini"); return; } std::ofstream userIni(iostream_friendly(dstPath)); std::string line; while (std::getline(defaultIni, line)){ userIni << line << std::endl; } } bool run_python_user_config(PythonContext& python){ // Execute the user's ini-script FilePath configPath(get_user_config_file_path()); if (!exists(configPath)){ // Recreate the config file from the default write_python_user_config(configPath, python); } if (exists(configPath)){ Optional<FaintPyExc> err = run_python_file(configPath); if (err.IsSet()){ python.IntFaintPrint("\n"); python.IntFaintPrint(space_sep("Error in personal config file", bracketed(quoted(configPath.Str()))) + ":\n"); display_error_info(err.Get(), python); return false; } else{ python.IntFaintPrint(space_sep("Executed personal config file at", quoted(configPath.Str())) + "\n"); return true; } } else { utf8_string userIniInfo( space_sep("Personal config file not found at", quoted(configPath.Str()))); python.IntFaintPrint(userIniInfo + "\n"); return false; } return true; } } // namespace
Prepend py to sys.path instead of append.
Prepend py to sys.path instead of append. So that a module named faint.pyd does not take precedence over the faint-graphics-editor/py/faint module.
C++
apache-2.0
lukas-ke/faint-graphics-editor,lukas-ke/faint-graphics-editor,lukas-ke/faint-graphics-editor,lukas-ke/faint-graphics-editor
f4bb236c0463a393c1a2d70ceb50c506514a23fa
simgear/environment/test_metar.cxx
simgear/environment/test_metar.cxx
#ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include <simgear/compiler.h> #include <iostream> #include <cstdlib> #include <cstdio> #ifdef _MSC_VER # define random rand #endif #include <simgear/misc/sg_dir.hxx> #include <simgear/structure/exception.hxx> #include "metar.hxx" using std::cout; using std::cerr; using std::endl; using std::string; #define COMPARE(a, b) \ if ((a) != (b)) { \ cerr << "failed:" << #a << " != " << #b << endl; \ cerr << "\tgot:" << a << endl; \ exit(1); \ } #define VERIFY(a) \ if (!(a)) { \ cerr << "failed:" << #a << endl; \ exit(1); \ } void test_basic() { SGMetar m1("2011/10/20 11:25 EHAM 201125Z 27012KT 240V300 9999 VCSH FEW025CB SCT048 10/05 Q1025 TEMPO VRB03KT"); COMPARE(m1.getYear(), 2011); COMPARE(m1.getMonth(), 10); COMPARE(m1.getDay(), 20); COMPARE(m1.getHour(), 11); COMPARE(m1.getMinute(), 25); COMPARE(m1.getReportType(), -1); // should default to NIL? COMPARE(m1.getWindDir(), 270); COMPARE(m1.getWindSpeed_kt(), 12); COMPARE(m1.getTemperature_C(), 10); COMPARE(m1.getDewpoint_C(), 5); COMPARE(m1.getPressure_hPa(), 1025); } int main(int argc, char* argv[]) { try { test_basic(); } catch (sg_exception& e) { cerr << "got exception:" << e.getMessage() << endl; return -1; } return 0; }
#ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include <simgear/compiler.h> #include <iostream> #include <cstdlib> #include <cstdio> #ifdef _MSC_VER # define random rand #endif #include <simgear/misc/sg_dir.hxx> #include <simgear/structure/exception.hxx> #include "metar.hxx" using std::cout; using std::cerr; using std::endl; using std::string; #define COMPARE(a, b) \ if ((a) != (b)) { \ cerr << "failed:" << #a << " != " << #b << endl; \ cerr << "\tgot:" << a << endl; \ exit(1); \ } #define FUZZY_COMPARE(a, b, epsilon) \ if (fabs(a - b) > epsilon) { \ cerr << "failed:" << #a << " != " << #b << endl; \ cerr << "\tgot:" << a << endl; \ cerr << "\tepsilon:" << epsilon << endl; \ } #define VERIFY(a) \ if (!(a)) { \ cerr << "failed:" << #a << endl; \ exit(1); \ } const double TEST_EPSILON = 1e-9; void test_basic() { SGMetar m1("2011/10/20 11:25 EHAM 201125Z 27012KT 240V300 9999 VCSH FEW025CB SCT048 10/05 Q1025 TEMPO VRB03KT"); COMPARE(m1.getYear(), 2011); COMPARE(m1.getMonth(), 10); COMPARE(m1.getDay(), 20); COMPARE(m1.getHour(), 11); COMPARE(m1.getMinute(), 25); COMPARE(m1.getReportType(), -1); // should default to NIL? COMPARE(m1.getWindDir(), 270); FUZZY_COMPARE(m1.getWindSpeed_kt(), 12, TEST_EPSILON); FUZZY_COMPARE(m1.getTemperature_C(), 10, TEST_EPSILON); FUZZY_COMPARE(m1.getDewpoint_C(), 5, TEST_EPSILON); FUZZY_COMPARE(m1.getPressure_hPa(), 1025, TEST_EPSILON); } int main(int argc, char* argv[]) { try { test_basic(); } catch (sg_exception& e) { cerr << "got exception:" << e.getMessage() << endl; return -1; } return 0; }
Add FUZZY_COMPARE to me tar unit-test, tolerate lower-order imprecision in FPUs
Add FUZZY_COMPARE to me tar unit-test, tolerate lower-order imprecision in FPUs
C++
lgpl-2.1
slowriot/simgear,slowriot/simgear
b9f39a2dbd692cbcdc68f8e02f3e77d0b9243e15
modules/vapor/vpr/md/BOOST/IO/Socket/SocketDatagramImplBOOST.cpp
modules/vapor/vpr/md/BOOST/IO/Socket/SocketDatagramImplBOOST.cpp
/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2011 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <string.h> //#include <strings.h> #include <sstream> #include <sys/types.h> //#include <sys/socket.h> #include <errno.h> #include <vpr/IO/Socket/ConnectionResetException.h> #include <vpr/IO/Socket/UnknownHostException.h> #include <vpr/IO/Socket/NoRouteToHostException.h> #include <vpr/IO/IOException.h> #include <vpr/IO/TimeoutException.h> #include <vpr/IO/WouldBlockException.h> #include <vpr/Util/Assert.h> #include <vpr/Util/Debug.h> #include <vpr/md/BOOST/IO/Socket/SocketDatagramImplBOOST.h> #include <boost/bind.hpp> #include <vpr/System.h> namespace vpr { // ============================================================================ // Public methods. // ============================================================================ SocketDatagramImplBOOST::SocketDatagramImplBOOST() : SocketImplBOOST(SocketTypes::DATAGRAM) { /* Do nothing. */ ; } SocketDatagramImplBOOST::SocketDatagramImplBOOST(const InetAddr& localAddr, const InetAddr& remoteAddr) : SocketImplBOOST(localAddr, remoteAddr, SocketTypes::DATAGRAM) { /* Do nothing. */ ; } SocketDatagramImplBOOST:: SocketDatagramImplBOOST(const SocketDatagramImplBOOST& sock) : SocketImplBOOST(sock.mLocalAddr, sock.mRemoteAddr, SocketTypes::DATAGRAM) { mUdpSocket = sock.mUdpSocket; mTcpSocket = sock.mTcpSocket; mLocalAddr = sock.mLocalAddr; mRemoteAddr = sock.mRemoteAddr; //mIOService = sock.mIOService; } vpr::Uint32 SocketDatagramImplBOOST::recvfrom(void* msg, const vpr::Uint32 length, vpr::InetAddr& from, const vpr::Interval& timeout) { mBytesRead = 0; // NOTE: It appears that binding the address of a stack variable // (timer_result) to an asynchronous callback functor works here because // the I/O service is being pumped by this method. boost::optional<boost::system::error_code> timer_result; boost::asio::deadline_timer timer(mUdpSocket->get_io_service()); timer.expires_from_now(boost::posix_time::microseconds(timeout.msec())); timer.async_wait(boost::bind(&SocketDatagramImplBOOST::setResult, this, &timer_result, _1, -1)); // Same situation for read_result. boost::optional<boost::system::error_code> read_result; mUdpSocket->async_receive_from(boost::asio::buffer(msg, length), from.mUdpAddr, boost::bind(&SocketDatagramImplBOOST::setResult, this, &read_result, _1, _2)); mUdpSocket->get_io_service().reset(); static bool cancel_supported(true); while (mUdpSocket->io_service().run_one()) { if (read_result) { timer.cancel(); } else if (timer_result) { if (cancel_supported) { try { mUdpSocket->cancel(); } catch (std::exception & ex) { vprDEBUG(vprDBG_ALL, vprDBG_CONFIG_STATUS_LVL) << "[SocketDatagramImplBOOST] caught an exception " < "cancelling UDP socket, switching to pre-Vista mode..." << std::endl << vprDEBUG_FLUSH; cancel_supported = false; } } if (! cancel_supported) { const bool was_bound(isBound()); this->close(); this->open(); if (was_bound) { this->bind(); } } throw TimeoutException("recvfrom operation timed out", VPR_LOCATION); } } return mBytesRead; } vpr::Uint32 SocketDatagramImplBOOST::sendto(const void* msg, const vpr::Uint32 length, const vpr::InetAddr& to, const vpr::Interval& timeout) { boost::system::error_code ec; vpr::Uint32 bytes_sent(0); bytes_sent = mUdpSocket->send_to(boost::asio::buffer(msg, length), to.mUdpAddr, 0, ec); if (ec) { //TODO handle errors } return bytes_sent; } void SocketDatagramImplBOOST:: setResult(boost::optional<boost::system::error_code>* a, const boost::system::error_code b, const std::size_t bytes) { a->reset(b); if (bytes != -1) { mBytesRead = bytes; } } } // End of vpr namespace
/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2011 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <string.h> //#include <strings.h> #include <sstream> #include <sys/types.h> //#include <sys/socket.h> #include <errno.h> #include <vpr/IO/Socket/ConnectionResetException.h> #include <vpr/IO/Socket/UnknownHostException.h> #include <vpr/IO/Socket/NoRouteToHostException.h> #include <vpr/IO/IOException.h> #include <vpr/IO/TimeoutException.h> #include <vpr/IO/WouldBlockException.h> #include <vpr/Util/Assert.h> #include <vpr/Util/Debug.h> #include <vpr/md/BOOST/IO/Socket/SocketDatagramImplBOOST.h> #include <boost/bind.hpp> #include <vpr/System.h> namespace vpr { // ============================================================================ // Public methods. // ============================================================================ SocketDatagramImplBOOST::SocketDatagramImplBOOST() : SocketImplBOOST(SocketTypes::DATAGRAM) { /* Do nothing. */ ; } SocketDatagramImplBOOST::SocketDatagramImplBOOST(const InetAddr& localAddr, const InetAddr& remoteAddr) : SocketImplBOOST(localAddr, remoteAddr, SocketTypes::DATAGRAM) { /* Do nothing. */ ; } SocketDatagramImplBOOST:: SocketDatagramImplBOOST(const SocketDatagramImplBOOST& sock) : SocketImplBOOST(sock.mLocalAddr, sock.mRemoteAddr, SocketTypes::DATAGRAM) { mUdpSocket = sock.mUdpSocket; mTcpSocket = sock.mTcpSocket; mLocalAddr = sock.mLocalAddr; mRemoteAddr = sock.mRemoteAddr; //mIOService = sock.mIOService; } vpr::Uint32 SocketDatagramImplBOOST::recvfrom(void* msg, const vpr::Uint32 length, vpr::InetAddr& from, const vpr::Interval& timeout) { mBytesRead = 0; // NOTE: It appears that binding the address of a stack variable // (timer_result) to an asynchronous callback functor works here because // the I/O service is being pumped by this method. boost::optional<boost::system::error_code> timer_result; boost::asio::deadline_timer timer(mUdpSocket->get_io_service()); timer.expires_from_now(boost::posix_time::microseconds(timeout.msec())); timer.async_wait(boost::bind(&SocketDatagramImplBOOST::setResult, this, &timer_result, _1, -1)); // Same situation for read_result. boost::optional<boost::system::error_code> read_result; mUdpSocket->async_receive_from(boost::asio::buffer(msg, length), from.mUdpAddr, boost::bind(&SocketDatagramImplBOOST::setResult, this, &read_result, _1, _2)); mUdpSocket->get_io_service().reset(); static bool cancel_supported(true); while (mUdpSocket->io_service().run_one()) { if (read_result) { timer.cancel(); } else if (timer_result) { if (cancel_supported) { try { mUdpSocket->cancel(); } catch (std::exception & ex) { vprDEBUG(vprDBG_ALL, vprDBG_CONFIG_STATUS_LVL) << "[SocketDatagramImplBOOST] caught an exception " << "cancelling UDP socket, switching to pre-Vista mode..." << std::endl << vprDEBUG_FLUSH; cancel_supported = false; } } if (! cancel_supported) { const bool was_bound(isBound()); this->close(); this->open(); if (was_bound) { this->bind(); } } throw TimeoutException("recvfrom operation timed out", VPR_LOCATION); } } return mBytesRead; } vpr::Uint32 SocketDatagramImplBOOST::sendto(const void* msg, const vpr::Uint32 length, const vpr::InetAddr& to, const vpr::Interval& timeout) { boost::system::error_code ec; vpr::Uint32 bytes_sent(0); bytes_sent = mUdpSocket->send_to(boost::asio::buffer(msg, length), to.mUdpAddr, 0, ec); if (ec) { //TODO handle errors } return bytes_sent; } void SocketDatagramImplBOOST:: setResult(boost::optional<boost::system::error_code>* a, const boost::system::error_code b, const std::size_t bytes) { a->reset(b); if (bytes != -1) { mBytesRead = bytes; } } } // End of vpr namespace
Fix from 3.0 branch: Patch from Doug McCorkle to fix compile error with boost sockets.
Fix from 3.0 branch: Patch from Doug McCorkle to fix compile error with boost sockets. git-svn-id: a341ccba1312b2efdbe34f40faf90581f48aa49f@21659 08b38cba-cd3b-11de-854e-f91c5b6e4272
C++
lgpl-2.1
godbyk/vrjuggler-upstream-old,LiuKeHua/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,godbyk/vrjuggler-upstream-old,MichaelMcDonnell/vrjuggler,MichaelMcDonnell/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,vrjuggler/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,vancegroup-mirrors/vrjuggler,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,LiuKeHua/vrjuggler,vancegroup-mirrors/vrjuggler,godbyk/vrjuggler-upstream-old,godbyk/vrjuggler-upstream-old,godbyk/vrjuggler-upstream-old,vancegroup-mirrors/vrjuggler
ce68a403f276c5337a4f72603952e8f091ac6c4a
lib/Fuzzer/test/TableLookupTest.cpp
lib/Fuzzer/test/TableLookupTest.cpp
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Make sure the fuzzer eventually finds all possible values of a variable // within a range. #include <cstring> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cassert> #include <set> const size_t N = 1 << 12; // Define an array of counters that will be understood by libFuzzer // as extra coverage signal. The array must be: // * uint8_t // * aligned by 64 // * in the section named __libfuzzer_extra_counters. // The target code may declare more than one such array. // // Use either `Counters[Idx] = 1` or `Counters[Idx]++;` // depending on whether multiple occurrences of the event 'Idx' // is important to distinguish from one occurrence. alignas(64) __attribute__((section("__libfuzzer_extra_counters"))) static uint8_t Counters[N]; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { static std::set<uint16_t> SeenIdx; if (Size != 4) return 0; uint32_t Idx; memcpy(&Idx, Data, 4); Idx %= N; assert(Counters[Idx] == 0); // libFuzzer should reset these between the runs. // Or Counters[Idx]=1 if we don't care how many times this happened. Counters[Idx]++; SeenIdx.insert(Idx); if (SeenIdx.size() == N) { fprintf(stderr, "BINGO: found all values\n"); abort(); } return 0; }
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Make sure the fuzzer eventually finds all possible values of a variable // within a range. #include <cstring> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cassert> #include <set> const size_t N = 1 << 12; // Define an array of counters that will be understood by libFuzzer // as extra coverage signal. The array must be: // * uint8_t // * aligned by 64 // * in the section named __libfuzzer_extra_counters. // The target code may declare more than one such array. // // Use either `Counters[Idx] = 1` or `Counters[Idx]++;` // depending on whether multiple occurrences of the event 'Idx' // is important to distinguish from one occurrence. #ifdef __linux__ alignas(64) __attribute__((section("__libfuzzer_extra_counters"))) #endif static uint8_t Counters[N]; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { static std::set<uint16_t> SeenIdx; if (Size != 4) return 0; uint32_t Idx; memcpy(&Idx, Data, 4); Idx %= N; assert(Counters[Idx] == 0); // libFuzzer should reset these between the runs. // Or Counters[Idx]=1 if we don't care how many times this happened. Counters[Idx]++; SeenIdx.insert(Idx); if (SeenIdx.size() == N) { fprintf(stderr, "BINGO: found all values\n"); abort(); } return 0; }
fix non-linux build
[libFuzzer] fix non-linux build git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@298666 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm
b7bdd91739d6d977839df8f3dc0b1004ff1fc03c
lib/MetaProcessor/MetaProcessor.cpp
lib/MetaProcessor/MetaProcessor.cpp
//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/MetaProcessor/MetaProcessor.h" #include "Display.h" #include "InputValidator.h" #include "MetaParser.h" #include "MetaSema.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/Path.h" #include <fstream> #include <cstdlib> #include <cctype> #include <stdio.h> #ifndef WIN32 #include <unistd.h> #else #include <io.h> #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif using namespace clang; namespace cling { MetaProcessor::MaybeRedirectOutputRAII::MaybeRedirectOutputRAII( MetaProcessor* p) :m_MetaProcessor(p), m_isCurrentlyRedirecting(0) { StringRef redirectionFile; m_MetaProcessor->increaseRedirectionRAIILevel(); if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); redirect(stdout, redirectionFile.str(), kSTDOUT); } if (!m_MetaProcessor->m_PrevStderrFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStderrFileName.back(); // Deal with the case 2>&1 and 2&>1 if (strcmp(redirectionFile.data(), "_IO_2_1_stdout_") == 0) { // If out is redirected to a file. if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); } else { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } redirect(stderr, redirectionFile.str(), kSTDERR); } } MetaProcessor::MaybeRedirectOutputRAII::~MaybeRedirectOutputRAII() { pop(); m_MetaProcessor->decreaseRedirectionRAIILevel(); } void MetaProcessor::MaybeRedirectOutputRAII::redirect(FILE* file, const std::string& fileName, MetaProcessor::RedirectionScope scope) { if (!fileName.empty()) { FILE* redirectionFile = freopen(fileName.c_str(), "a", file); if (!redirectionFile) { llvm::errs()<<"cling::MetaProcessor::MaybeRedirectOutputRAII::redirect:" " Not succefully reopened the redirection file " << fileName.c_str() << "\n."; } else { m_isCurrentlyRedirecting |= scope; } } } void MetaProcessor::MaybeRedirectOutputRAII::pop() { //If we have only one redirection RAII //only then do the unredirection. if (m_MetaProcessor->getRedirectionRAIILevel() != 1) return; if (m_isCurrentlyRedirecting & kSTDOUT) { unredirect(m_MetaProcessor->m_backupFDStdout, STDOUT_FILENO, stdout); } if (m_isCurrentlyRedirecting & kSTDERR) { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } void MetaProcessor::MaybeRedirectOutputRAII::unredirect(int backupFD, int expectedFD, FILE* file) { // Switch back to previous file after line is processed. // Flush the current content if there is any. if (!feof(file)) { fflush(file); } // Copy the original fd for the std. if (dup2(backupFD, expectedFD) != expectedFD) { llvm::errs() << "cling::MetaProcessor::unredirect " << "The unredirection file descriptor not valid " << backupFD << ".\n"; } } MetaProcessor::MetaProcessor(Interpreter& interp, raw_ostream& outs) : m_Interp(interp), m_Outs(&outs) { m_InputValidator.reset(new InputValidator()); m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this))); m_backupFDStdout = copyFileDescriptor(STDOUT_FILENO); m_backupFDStderr = copyFileDescriptor(STDERR_FILENO); } MetaProcessor::~MetaProcessor() { close(m_backupFDStdout); close(m_backupFDStderr); } int MetaProcessor::process(const char* input_text, Interpreter::CompilationResult& compRes, Value* result) { if (result) *result = Value(); compRes = Interpreter::kSuccess; int expectedIndent = m_InputValidator->getExpectedIndent(); if (expectedIndent) compRes = Interpreter::kMoreInputExpected; if (!input_text || !input_text[0]) { // nullptr / empty string, nothing to do. return expectedIndent; } std::string input_line(input_text); if (input_line == "\n") { // just a blank line, nothing to do. return expectedIndent; } // Check for and handle meta commands. m_MetaParser->enterNewInputLine(input_line); MetaSema::ActionResult actionResult = MetaSema::AR_Success; if (!m_InputValidator->inBlockComment() && m_MetaParser->isMetaCommand(actionResult, result)) { if (m_MetaParser->isQuitRequested()) return -1; if (actionResult != MetaSema::AR_Success) compRes = Interpreter::kFailure; // ExpectedIndent might have changed after meta command. return m_InputValidator->getExpectedIndent(); } // Check if the current statement is now complete. If not, return to // prompt for more. if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) { compRes = Interpreter::kMoreInputExpected; return m_InputValidator->getExpectedIndent(); } // We have a complete statement, compile and execute it. std::string input; m_InputValidator->reset(&input); // if (m_Options.RawInput) // compResLocal = m_Interp.declare(input); // else compRes = m_Interp.process(input, result); return 0; } void MetaProcessor::cancelContinuation() const { m_InputValidator->reset(); } int MetaProcessor::getExpectedIndent() const { return m_InputValidator->getExpectedIndent(); } Interpreter::CompilationResult MetaProcessor::readInputFromFile(llvm::StringRef filename, Value* result, size_t posOpenCurly) { { // check that it's not binary: std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary); char magic[1024] = {0}; in.read(magic, sizeof(magic)); size_t readMagic = in.gcount(); // Binary files < 300 bytes are rare, and below newlines etc make the // heuristic unreliable. if (readMagic >= 300) { llvm::StringRef magicStr(magic,in.gcount()); llvm::sys::fs::file_magic fileType = llvm::sys::fs::identify_magic(magicStr); if (fileType != llvm::sys::fs::file_magic::unknown) { llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a binary file!\n"; return Interpreter::kFailure; } unsigned printable = 0; for (size_t i = 0; i < readMagic; ++i) if (isprint(magic[i])) ++printable; if (10 * printable < 5 * readMagic) { // 50% printable for ASCII files should be a safe guess. llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a (likely) binary file!\n" << printable; return Interpreter::kFailure; } } } std::ifstream in(filename.str().c_str()); in.seekg(0, std::ios::end); size_t size = in.tellg(); std::string content(size, ' '); in.seekg(0); in.read(&content[0], size); if (posOpenCurly != (size_t)-1 && !content.empty()) { assert(content[posOpenCurly] == '{' && "No curly at claimed position of opening curly!"); // hide the curly brace: content[posOpenCurly] = ' '; // and the matching closing '}' static const char whitespace[] = " \t\r\n"; size_t posCloseCurly = content.find_last_not_of(whitespace); if (posCloseCurly != std::string::npos) { if (content[posCloseCurly] == ';' && content[posCloseCurly-1] == '}') { content[posCloseCurly--] = ' '; // replace ';' and enter next if } if (content[posCloseCurly] == '}') { content[posCloseCurly] = ' '; // replace '}' } else { std::string::size_type posBlockClose = content.find_last_of('}'); if (posBlockClose != std::string::npos) { content[posBlockClose] = ' '; // replace '}' } std::string::size_type posComment = content.find_first_not_of(whitespace, posBlockClose); if (posComment != std::string::npos && content[posComment] == '/' && content[posComment+1] == '/') { // More text (comments) are okay after the last '}', but // we can not easily find it to remove it (so we need to upgrade // this code to better handle the case with comments or // preprocessor code before and after the leading { and // trailing }) while (posComment <= posCloseCurly) { content[posComment++] = ' '; // replace '}' and comment } } else { content[posCloseCurly] = '{'; // By putting the '{' back, we keep the code as consistent as // the user wrote it ... but we should still warn that we not // goint to treat this file an unamed macro. llvm::errs() << "Warning in cling::MetaProcessor: can not find the closing '}', " << llvm::sys::path::filename(filename) << " is not handled as an unamed script!\n"; } // did not find "//" } // remove comments after the trailing '}' } // find '}' } // ignore outermost block std::string strFilename(filename.str()); m_CurrentlyExecutingFile = strFilename; bool topmost = !m_TopExecutingFile.data(); if (topmost) m_TopExecutingFile = m_CurrentlyExecutingFile; Interpreter::CompilationResult ret; // We don't want to value print the results of a unnamed macro. content = "#line 2 \"" + filename.str() + "\" \n" + content; if (process((content + ";").c_str(), ret, result)) { // Input file has to be complete. llvm::errs() << "Error in cling::MetaProcessor: file " << llvm::sys::path::filename(filename) << " is incomplete (missing parenthesis or similar)!\n"; ret = Interpreter::kFailure; } m_CurrentlyExecutingFile = llvm::StringRef(); if (topmost) m_TopExecutingFile = llvm::StringRef(); return ret; } void MetaProcessor::setFileStream(llvm::StringRef file, bool append, int fd, llvm::SmallVector<llvm::SmallString<128>, 2>& prevFileStack) { // If we have a fileName to redirect to store it. if (!file.empty()) { prevFileStack.push_back(file); // pop and push a null terminating 0. // SmallVectorImpl<T> does not have a c_str(), thus instead of casting to // a SmallString<T> we null terminate the data that we have and pop the // 0 char back. prevFileStack.back().push_back(0); prevFileStack.back().pop_back(); if (!append) { FILE * f; if (!(f = fopen(file.data(), "w"))) { llvm::errs() << "cling::MetaProcessor::setFileStream:" " The file path " << file.data() << " is not valid.\n"; } else { fclose(f); } } // Else unredirection, so switch to the previous file. } else { // If there is no previous file on the stack we pop the file if (!prevFileStack.empty()) { prevFileStack.pop_back(); } } } void MetaProcessor::setStdStream(llvm::StringRef file, RedirectionScope stream, bool append) { if (stream & kSTDOUT) { setFileStream(file, append, STDOUT_FILENO, m_PrevStdoutFileName); } if (stream & kSTDERR) { setFileStream(file, append, STDERR_FILENO, m_PrevStderrFileName); } } int MetaProcessor::copyFileDescriptor(int fd) { int backupFD = dup(fd); if (backupFD < 0) { llvm::errs() << "MetaProcessor::copyFileDescriptor: Duplicating the file" " descriptor " << fd << " resulted in an error." " Will not be able to unredirect.\n"; } return backupFD; } void MetaProcessor::registerUnloadPoint(const Transaction* T, llvm::StringRef filename) { m_MetaParser->getActions().registerUnloadPoint(T, filename); } } // end namespace cling
//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/MetaProcessor/MetaProcessor.h" #include "Display.h" #include "InputValidator.h" #include "MetaParser.h" #include "MetaSema.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/Path.h" #include <fstream> #include <cstdlib> #include <cctype> #include <stdio.h> #ifndef WIN32 #include <unistd.h> #else #include <io.h> #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif using namespace clang; namespace cling { MetaProcessor::MaybeRedirectOutputRAII::MaybeRedirectOutputRAII( MetaProcessor* p) :m_MetaProcessor(p), m_isCurrentlyRedirecting(0) { StringRef redirectionFile; m_MetaProcessor->increaseRedirectionRAIILevel(); if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); redirect(stdout, redirectionFile.str(), kSTDOUT); } if (!m_MetaProcessor->m_PrevStderrFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStderrFileName.back(); // Deal with the case 2>&1 and 2&>1 if (strcmp(redirectionFile.data(), "_IO_2_1_stdout_") == 0) { // If out is redirected to a file. if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); } else { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } redirect(stderr, redirectionFile.str(), kSTDERR); } } MetaProcessor::MaybeRedirectOutputRAII::~MaybeRedirectOutputRAII() { pop(); m_MetaProcessor->decreaseRedirectionRAIILevel(); } void MetaProcessor::MaybeRedirectOutputRAII::redirect(FILE* file, const std::string& fileName, MetaProcessor::RedirectionScope scope) { if (!fileName.empty()) { FILE* redirectionFile = freopen(fileName.c_str(), "a", file); if (!redirectionFile) { llvm::errs()<<"cling::MetaProcessor::MaybeRedirectOutputRAII::redirect:" " Not succefully reopened the redirection file " << fileName.c_str() << "\n."; } else { m_isCurrentlyRedirecting |= scope; } } } void MetaProcessor::MaybeRedirectOutputRAII::pop() { //If we have only one redirection RAII //only then do the unredirection. if (m_MetaProcessor->getRedirectionRAIILevel() != 1) return; if (m_isCurrentlyRedirecting & kSTDOUT) { unredirect(m_MetaProcessor->m_backupFDStdout, STDOUT_FILENO, stdout); } if (m_isCurrentlyRedirecting & kSTDERR) { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } void MetaProcessor::MaybeRedirectOutputRAII::unredirect(int backupFD, int expectedFD, FILE* file) { // Switch back to previous file after line is processed. // Flush the current content if there is any. if (!feof(file)) { fflush(file); } // Copy the original fd for the std. if (dup2(backupFD, expectedFD) != expectedFD) { llvm::errs() << "cling::MetaProcessor::unredirect " << "The unredirection file descriptor not valid " << backupFD << ".\n"; } } MetaProcessor::MetaProcessor(Interpreter& interp, raw_ostream& outs) : m_Interp(interp), m_Outs(&outs) { m_InputValidator.reset(new InputValidator()); m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this))); m_backupFDStdout = copyFileDescriptor(STDOUT_FILENO); m_backupFDStderr = copyFileDescriptor(STDERR_FILENO); } MetaProcessor::~MetaProcessor() { close(m_backupFDStdout); close(m_backupFDStderr); } int MetaProcessor::process(const char* input_text, Interpreter::CompilationResult& compRes, Value* result) { if (result) *result = Value(); compRes = Interpreter::kSuccess; int expectedIndent = m_InputValidator->getExpectedIndent(); if (expectedIndent) compRes = Interpreter::kMoreInputExpected; if (!input_text || !input_text[0]) { // nullptr / empty string, nothing to do. return expectedIndent; } std::string input_line(input_text); if (input_line == "\n") { // just a blank line, nothing to do. return expectedIndent; } // Check for and handle meta commands. m_MetaParser->enterNewInputLine(input_line); MetaSema::ActionResult actionResult = MetaSema::AR_Success; if (!m_InputValidator->inBlockComment() && m_MetaParser->isMetaCommand(actionResult, result)) { if (m_MetaParser->isQuitRequested()) return -1; if (actionResult != MetaSema::AR_Success) compRes = Interpreter::kFailure; // ExpectedIndent might have changed after meta command. return m_InputValidator->getExpectedIndent(); } // Check if the current statement is now complete. If not, return to // prompt for more. if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) { compRes = Interpreter::kMoreInputExpected; return m_InputValidator->getExpectedIndent(); } // We have a complete statement, compile and execute it. std::string input; m_InputValidator->reset(&input); // if (m_Options.RawInput) // compResLocal = m_Interp.declare(input); // else compRes = m_Interp.process(input, result); return 0; } void MetaProcessor::cancelContinuation() const { m_InputValidator->reset(); } int MetaProcessor::getExpectedIndent() const { return m_InputValidator->getExpectedIndent(); } static Interpreter::CompilationResult reportIOErr(llvm::StringRef File, const char* What) { llvm::errs() << "Error in cling::MetaProcessor: " "cannot " << What << " input: '" << File << "'\n"; return Interpreter::kFailure; } Interpreter::CompilationResult MetaProcessor::readInputFromFile(llvm::StringRef filename, Value* result, size_t posOpenCurly) { // FIXME: This will fail for Unicode BOMs (and seems really weird) { // check that it's not binary: std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary); if (in.fail()) return reportIOErr(filename, "open"); char magic[1024] = {0}; in.read(magic, sizeof(magic)); size_t readMagic = in.gcount(); // Binary files < 300 bytes are rare, and below newlines etc make the // heuristic unreliable. if (!in.fail() && readMagic >= 300) { llvm::StringRef magicStr(magic,in.gcount()); llvm::sys::fs::file_magic fileType = llvm::sys::fs::identify_magic(magicStr); if (fileType != llvm::sys::fs::file_magic::unknown) return reportIOErr(filename, "read from binary"); unsigned printable = 0; for (size_t i = 0; i < readMagic; ++i) if (isprint(magic[i])) ++printable; if (10 * printable < 5 * readMagic) { // 50% printable for ASCII files should be a safe guess. return reportIOErr(filename, "won't read from likely binary"); } } } std::ifstream in(filename.str().c_str()); if (in.fail()) return reportIOErr(filename, "open"); in.seekg(0, std::ios::end); if (in.fail()) return reportIOErr(filename, "seek"); size_t size = in.tellg(); if (in.fail()) return reportIOErr(filename, "tell"); in.seekg(0); if (in.fail()) return reportIOErr(filename, "rewind"); std::string content(size, ' '); in.read(&content[0], size); if (in.fail()) return reportIOErr(filename, "read"); if (posOpenCurly != (size_t)-1 && !content.empty()) { assert(content[posOpenCurly] == '{' && "No curly at claimed position of opening curly!"); // hide the curly brace: content[posOpenCurly] = ' '; // and the matching closing '}' static const char whitespace[] = " \t\r\n"; size_t posCloseCurly = content.find_last_not_of(whitespace); if (posCloseCurly != std::string::npos) { if (content[posCloseCurly] == ';' && content[posCloseCurly-1] == '}') { content[posCloseCurly--] = ' '; // replace ';' and enter next if } if (content[posCloseCurly] == '}') { content[posCloseCurly] = ' '; // replace '}' } else { std::string::size_type posBlockClose = content.find_last_of('}'); if (posBlockClose != std::string::npos) { content[posBlockClose] = ' '; // replace '}' } std::string::size_type posComment = content.find_first_not_of(whitespace, posBlockClose); if (posComment != std::string::npos && content[posComment] == '/' && content[posComment+1] == '/') { // More text (comments) are okay after the last '}', but // we can not easily find it to remove it (so we need to upgrade // this code to better handle the case with comments or // preprocessor code before and after the leading { and // trailing }) while (posComment <= posCloseCurly) { content[posComment++] = ' '; // replace '}' and comment } } else { content[posCloseCurly] = '{'; // By putting the '{' back, we keep the code as consistent as // the user wrote it ... but we should still warn that we not // goint to treat this file an unamed macro. llvm::errs() << "Warning in cling::MetaProcessor: can not find the closing '}', " << llvm::sys::path::filename(filename) << " is not handled as an unamed script!\n"; } // did not find "//" } // remove comments after the trailing '}' } // find '}' } // ignore outermost block m_CurrentlyExecutingFile = filename; bool topmost = !m_TopExecutingFile.data(); if (topmost) m_TopExecutingFile = m_CurrentlyExecutingFile; Interpreter::CompilationResult ret; // We don't want to value print the results of a unnamed macro. content = "#line 2 \"" + filename.str() + "\" \n" + content; if (process((content + ";").c_str(), ret, result)) { // Input file has to be complete. llvm::errs() << "Error in cling::MetaProcessor: file " << llvm::sys::path::filename(filename) << " is incomplete (missing parenthesis or similar)!\n"; ret = Interpreter::kFailure; } m_CurrentlyExecutingFile = llvm::StringRef(); if (topmost) m_TopExecutingFile = llvm::StringRef(); return ret; } void MetaProcessor::setFileStream(llvm::StringRef file, bool append, int fd, llvm::SmallVector<llvm::SmallString<128>, 2>& prevFileStack) { // If we have a fileName to redirect to store it. if (!file.empty()) { prevFileStack.push_back(file); // pop and push a null terminating 0. // SmallVectorImpl<T> does not have a c_str(), thus instead of casting to // a SmallString<T> we null terminate the data that we have and pop the // 0 char back. prevFileStack.back().push_back(0); prevFileStack.back().pop_back(); if (!append) { FILE * f; if (!(f = fopen(file.data(), "w"))) { llvm::errs() << "cling::MetaProcessor::setFileStream:" " The file path " << file.data() << " is not valid.\n"; } else { fclose(f); } } // Else unredirection, so switch to the previous file. } else { // If there is no previous file on the stack we pop the file if (!prevFileStack.empty()) { prevFileStack.pop_back(); } } } void MetaProcessor::setStdStream(llvm::StringRef file, RedirectionScope stream, bool append) { if (stream & kSTDOUT) { setFileStream(file, append, STDOUT_FILENO, m_PrevStdoutFileName); } if (stream & kSTDERR) { setFileStream(file, append, STDERR_FILENO, m_PrevStderrFileName); } } int MetaProcessor::copyFileDescriptor(int fd) { int backupFD = dup(fd); if (backupFD < 0) { llvm::errs() << "MetaProcessor::copyFileDescriptor: Duplicating the file" " descriptor " << fd << " resulted in an error." " Will not be able to unredirect.\n"; } return backupFD; } void MetaProcessor::registerUnloadPoint(const Transaction* T, llvm::StringRef filename) { m_MetaParser->getActions().registerUnloadPoint(T, filename); } } // end namespace cling
Add error handling to MetaProcessor::readInputFromFile.
Add error handling to MetaProcessor::readInputFromFile.
C++
lgpl-2.1
marsupial/cling,marsupial/cling,karies/cling,marsupial/cling,marsupial/cling,root-mirror/cling,karies/cling,karies/cling,karies/cling,marsupial/cling,karies/cling,root-mirror/cling,karies/cling,root-mirror/cling,root-mirror/cling,root-mirror/cling,marsupial/cling,root-mirror/cling
f914cb52bca24d35c3bebe651a119bf4856ac328
lib/Transforms/LowerUnsignedICmp.cc
lib/Transforms/LowerUnsignedICmp.cc
/** * Replace ULT and ULE comparison instructions with SLT and SLE. **/ #include "llvm/Pass.h" #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/InstIterator.h" #include "llvm/Support/Debug.h" #include <vector> #define DEBUG_TYPE "lower-unsigned-icmp" namespace crab_llvm { using namespace llvm; static CmpInst* mkNonNegative(Value *V, Instruction *insertPt) { Value *zero = ConstantInt::getSigned (V->getType(), 0); Twine name = (V->hasName() ? V->getName() + "_SGE_0" : "check_SGE_0"); return CmpInst::Create (Instruction::ICmp, CmpInst::ICMP_SGE, V, zero, name, insertPt); } static CmpInst* mkNonNegative(Value *V, BasicBlock *insertPt) { Value *zero = ConstantInt::getSigned (V->getType(), 0); Twine name = (V->hasName() ? V->getName() + "_SGE_0" : "check_SGE_0"); return CmpInst::Create (Instruction::ICmp, CmpInst::ICMP_SGE, V, zero, name, insertPt); } static bool isNonNegIntCst (Value *V) { if (ConstantInt *K = dyn_cast<ConstantInt> (V)) return (K->getSExtValue() >= 0); return false; } static void normalizeCmpInst(CmpInst *I) { switch (I->getPredicate()){ case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_SGT: I->swapOperands(); break; case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_SGE: I->swapOperands(); break; default: ; } } STATISTIC(totalUnsignedICmpLowered, "Number of Lowered ULT and ULE Instructions"); class LowerUnsignedICmp: public FunctionPass { void processUnsignedICmp(ICmpInst *CI) { BasicBlock *cur = CI->getParent(); BasicBlock * cont = cur->splitBasicBlock (CI, cur->getName() + "PHILowerICmp"); Function *F = cur->getParent(); Value *op1 = CI->getOperand(0); Value *op2 = CI->getOperand(1); bool is_nonneg_op1 = isNonNegIntCst(op1); bool is_nonneg_op2 = isNonNegIntCst(op2); if (is_nonneg_op2 && is_nonneg_op1) { // -- This should not happen after InstCombine return; } if (is_nonneg_op2 || is_nonneg_op1) { // -- special case: one of the two operands is an integer // -- constant /* For the case %z is constant (the case %y is constant is symmetric): %b = %y ult %z CONT | V cur: %b1 = %y geq 0 br %b1, %bb1, %bb2 bb1: %b2 = %y lt %z br %cont bb2: br %cont cont: %b = PHI (%b2, %bb1) (true, %bb2) */ // Check whether the non-constant operand is >= 0 BasicBlock* tt = BasicBlock::Create (F->getContext(), "TrueLowerICmp", F, cont); BasicBlock* ff = BasicBlock::Create (F->getContext(), "FalseLowerICmp", F, cont); BranchInst::Create (cont,tt); BranchInst::Create (cont,ff); CmpInst *NonNegOp1 = mkNonNegative(is_nonneg_op2 ? op1: op2, cur->getTerminator()); cur->getTerminator()->eraseFromParent(); BranchInst::Create (tt, ff, NonNegOp1, cur); // Create signed comparison that will replace the unsigned one CmpInst *newCI = CmpInst::Create (Instruction::ICmp, CI->getSignedPredicate(), op1, op2, CI->getName(), tt->getTerminator()); // Insert a phi node just before the unsigned instruction in // cont PHINode *PHI=PHINode::Create (CI->getType(), 0, CI->getName(), CI); PHI->addIncoming (newCI,tt); if (is_nonneg_op2) { PHI->addIncoming (ConstantInt::getTrue(newCI->getType()),ff); } else { PHI->addIncoming (ConstantInt::getFalse(newCI->getType()),ff); } // Make sure any users of the unsigned comparison is now an // user of the phi node. CI->replaceAllUsesWith(PHI); // Finally we remove the unsigned instruction CI->eraseFromParent(); } else { // -- general case: both operands are non-constant /* %b = %y ult %z CONT | V cur: %b1 = %y geq 0 br %b1, %bb1, %bb2 bb1: %b2 = %z gep 0 br %b2, %bb3, %cont bb2: %b3 = %z gep 0 br %b3, cont, %bb4 bb3: %b4 = %y lt %z br %cont bb4: %b5 = %y lt %z br %cont cont: %b = PHI (%b4, %bb3) (false, %bb1) (true, %bb2) (%b5, %bb4) */ // Check whether the first operand is >= 0 BasicBlock* bb1 = BasicBlock::Create (F->getContext(), "TrueLowerICmp", F, cont); BasicBlock* bb2 = BasicBlock::Create (F->getContext(), "FalseLowerICmp", F, cont); BasicBlock* bb3 = BasicBlock::Create (F->getContext(), "TrueLowerICmp", F, cont); BasicBlock* bb4 = BasicBlock::Create (F->getContext(), "FalseLowerICmp", F, cont); CmpInst *b1 = mkNonNegative(op1, cur->getTerminator()); cur->getTerminator()->eraseFromParent(); BranchInst::Create (bb1, bb2, b1, cur); // Check whether the second operand is >= 0 CmpInst *b2 = mkNonNegative(op2, bb1); BranchInst::Create (bb3, cont, b2, bb1); // Check whether the second operand is >= 0 CmpInst *b3 = mkNonNegative(op2, bb2); BranchInst::Create (cont, bb4, b3, bb2); // Create signed comparison that will replace the unsigned one CmpInst *b4 = CmpInst::Create (Instruction::ICmp, CI->getSignedPredicate(), op1, op2, CI->getName(), bb3); BranchInst::Create (cont, bb3); // Create signed comparison that will replace the unsigned one CmpInst *b5 = CmpInst::Create (Instruction::ICmp, CI->getSignedPredicate(), op1, op2, CI->getName(), bb4); BranchInst::Create (cont, bb4); // Insert a phi node just before the unsigned instruction in // cont PHINode *PHI=PHINode::Create (CI->getType(), 0, CI->getName(), CI); PHI->addIncoming (ConstantInt::getFalse(CI->getType()),bb1); PHI->addIncoming (ConstantInt::getTrue(CI->getType()),bb2); PHI->addIncoming (b4,bb3); PHI->addIncoming (b5,bb4); // Make sure any users of the unsigned comparison is now an // user of the phi node. CI->replaceAllUsesWith(PHI); // Finally we remove the unsigned instruction CI->eraseFromParent(); } totalUnsignedICmpLowered++; } public: static char ID; LowerUnsignedICmp(): FunctionPass(ID){ } virtual bool runOnFunction(Function &F) { std::vector<ICmpInst*> worklist; for (inst_iterator It = inst_begin(F), E = inst_end(F); It != E; ++It) { Instruction *I = &*It; if (ICmpInst *CI = dyn_cast<ICmpInst>(I)) { if (!CI->getOperand(0)->getType()->isIntegerTy() || !CI->getOperand(1)->getType()->isIntegerTy()) { // -- we only lower the instruction if both operands are // integer continue; } // ensure only EQ, NEQ, SLT, ULT, SLE, ULE normalizeCmpInst(CI); if (CI->getPredicate() == CmpInst::ICMP_ULT || CI->getPredicate() == CmpInst::ICMP_ULE) { worklist.push_back(CI); } } } bool change = !worklist.empty(); while (!worklist.empty()) { ICmpInst *CI = worklist.back(); worklist.pop_back(); processUnsignedICmp(CI); } //llvm::errs () << F << "\n"; return change; } virtual StringRef getPassName() const { return "CrabLlvm: Lower ULT and ULE instructions"; } virtual void getAnalysisUsage (AnalysisUsage &AU) const { //AU.setPreservesAll (); } }; char LowerUnsignedICmp::ID = 0; Pass* createLowerUnsignedICmpPass () { return new LowerUnsignedICmp (); } } // end namespace
/** * Replace ULT and ULE comparison instructions with SLT and SLE. **/ #include "llvm/Pass.h" #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/InstIterator.h" #include "llvm/Support/Debug.h" #include <vector> #define DEBUG_TYPE "lower-unsigned-icmp" namespace crab_llvm { using namespace llvm; static CmpInst* mkNonNegative(Value *V, Instruction *insertPt) { Value *zero = ConstantInt::getSigned (V->getType(), 0); Twine name = (V->hasName() ? V->getName() + "_SGE_0" : "check_SGE_0"); return CmpInst::Create (Instruction::ICmp, CmpInst::ICMP_SGE, V, zero, name, insertPt); } static CmpInst* mkNonNegative(Value *V, BasicBlock *insertPt) { Value *zero = ConstantInt::getSigned (V->getType(), 0); Twine name = (V->hasName() ? V->getName() + "_SGE_0" : "check_SGE_0"); return CmpInst::Create (Instruction::ICmp, CmpInst::ICMP_SGE, V, zero, name, insertPt); } static bool isNonNegIntCst (Value *V) { if (ConstantInt *K = dyn_cast<ConstantInt> (V)) return (K->getValue().isNonNegative() >= 0); return false; } static void normalizeCmpInst(CmpInst *I) { switch (I->getPredicate()){ case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_SGT: I->swapOperands(); break; case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_SGE: I->swapOperands(); break; default: ; } } STATISTIC(totalUnsignedICmpLowered, "Number of Lowered ULT and ULE Instructions"); class LowerUnsignedICmp: public FunctionPass { void processUnsignedICmp(ICmpInst *CI) { BasicBlock *cur = CI->getParent(); BasicBlock * cont = cur->splitBasicBlock (CI, cur->getName() + "PHILowerICmp"); Function *F = cur->getParent(); Value *op1 = CI->getOperand(0); Value *op2 = CI->getOperand(1); bool is_nonneg_op1 = isNonNegIntCst(op1); bool is_nonneg_op2 = isNonNegIntCst(op2); if (is_nonneg_op2 && is_nonneg_op1) { // -- This should not happen after InstCombine return; } if (is_nonneg_op2 || is_nonneg_op1) { // -- special case: one of the two operands is an integer // -- constant /* For the case %z is constant (the case %y is constant is symmetric): %b = %y ult %z CONT | V cur: %b1 = %y geq 0 br %b1, %bb1, %bb2 bb1: %b2 = %y lt %z br %cont bb2: br %cont cont: %b = PHI (%b2, %bb1) (true, %bb2) */ // Check whether the non-constant operand is >= 0 BasicBlock* tt = BasicBlock::Create (F->getContext(), "TrueLowerICmp", F, cont); BasicBlock* ff = BasicBlock::Create (F->getContext(), "FalseLowerICmp", F, cont); BranchInst::Create (cont,tt); BranchInst::Create (cont,ff); CmpInst *NonNegOp1 = mkNonNegative(is_nonneg_op2 ? op1: op2, cur->getTerminator()); cur->getTerminator()->eraseFromParent(); BranchInst::Create (tt, ff, NonNegOp1, cur); // Create signed comparison that will replace the unsigned one CmpInst *newCI = CmpInst::Create (Instruction::ICmp, CI->getSignedPredicate(), op1, op2, CI->getName(), tt->getTerminator()); // Insert a phi node just before the unsigned instruction in // cont PHINode *PHI=PHINode::Create (CI->getType(), 0, CI->getName(), CI); PHI->addIncoming (newCI,tt); if (is_nonneg_op2) { PHI->addIncoming (ConstantInt::getTrue(newCI->getType()),ff); } else { PHI->addIncoming (ConstantInt::getFalse(newCI->getType()),ff); } // Make sure any users of the unsigned comparison is now an // user of the phi node. CI->replaceAllUsesWith(PHI); // Finally we remove the unsigned instruction CI->eraseFromParent(); } else { // -- general case: both operands are non-constant /* %b = %y ult %z CONT | V cur: %b1 = %y geq 0 br %b1, %bb1, %bb2 bb1: %b2 = %z gep 0 br %b2, %bb3, %cont bb2: %b3 = %z gep 0 br %b3, cont, %bb4 bb3: %b4 = %y lt %z br %cont bb4: %b5 = %y lt %z br %cont cont: %b = PHI (%b4, %bb3) (false, %bb1) (true, %bb2) (%b5, %bb4) */ // Check whether the first operand is >= 0 BasicBlock* bb1 = BasicBlock::Create (F->getContext(), "TrueLowerICmp", F, cont); BasicBlock* bb2 = BasicBlock::Create (F->getContext(), "FalseLowerICmp", F, cont); BasicBlock* bb3 = BasicBlock::Create (F->getContext(), "TrueLowerICmp", F, cont); BasicBlock* bb4 = BasicBlock::Create (F->getContext(), "FalseLowerICmp", F, cont); CmpInst *b1 = mkNonNegative(op1, cur->getTerminator()); cur->getTerminator()->eraseFromParent(); BranchInst::Create (bb1, bb2, b1, cur); // Check whether the second operand is >= 0 CmpInst *b2 = mkNonNegative(op2, bb1); BranchInst::Create (bb3, cont, b2, bb1); // Check whether the second operand is >= 0 CmpInst *b3 = mkNonNegative(op2, bb2); BranchInst::Create (cont, bb4, b3, bb2); // Create signed comparison that will replace the unsigned one CmpInst *b4 = CmpInst::Create (Instruction::ICmp, CI->getSignedPredicate(), op1, op2, CI->getName(), bb3); BranchInst::Create (cont, bb3); // Create signed comparison that will replace the unsigned one CmpInst *b5 = CmpInst::Create (Instruction::ICmp, CI->getSignedPredicate(), op1, op2, CI->getName(), bb4); BranchInst::Create (cont, bb4); // Insert a phi node just before the unsigned instruction in // cont PHINode *PHI=PHINode::Create (CI->getType(), 0, CI->getName(), CI); PHI->addIncoming (ConstantInt::getFalse(CI->getType()),bb1); PHI->addIncoming (ConstantInt::getTrue(CI->getType()),bb2); PHI->addIncoming (b4,bb3); PHI->addIncoming (b5,bb4); // Make sure any users of the unsigned comparison is now an // user of the phi node. CI->replaceAllUsesWith(PHI); // Finally we remove the unsigned instruction CI->eraseFromParent(); } totalUnsignedICmpLowered++; } public: static char ID; LowerUnsignedICmp(): FunctionPass(ID){ } virtual bool runOnFunction(Function &F) { std::vector<ICmpInst*> worklist; for (inst_iterator It = inst_begin(F), E = inst_end(F); It != E; ++It) { Instruction *I = &*It; if (ICmpInst *CI = dyn_cast<ICmpInst>(I)) { if (!CI->getOperand(0)->getType()->isIntegerTy() || !CI->getOperand(1)->getType()->isIntegerTy()) { // -- we only lower the instruction if both operands are // integer continue; } // ensure only EQ, NEQ, SLT, ULT, SLE, ULE normalizeCmpInst(CI); if (CI->getPredicate() == CmpInst::ICMP_ULT || CI->getPredicate() == CmpInst::ICMP_ULE) { worklist.push_back(CI); } } } bool change = !worklist.empty(); while (!worklist.empty()) { ICmpInst *CI = worklist.back(); worklist.pop_back(); processUnsignedICmp(CI); } //llvm::errs () << F << "\n"; return change; } virtual StringRef getPassName() const { return "CrabLlvm: Lower ULT and ULE instructions"; } virtual void getAnalysisUsage (AnalysisUsage &AU) const { //AU.setPreservesAll (); } }; char LowerUnsignedICmp::ID = 0; Pass* createLowerUnsignedICmpPass () { return new LowerUnsignedICmp (); } } // end namespace
Use APInt instead of converting to 64 bit integers
Use APInt instead of converting to 64 bit integers
C++
apache-2.0
seahorn/crab-llvm,seahorn/crab-llvm,seahorn/crab-llvm
5e441ede904a8040fa7d6e9f7c7feb90e368280e
libvast/src/system/sink_command.cpp
libvast/src/system/sink_command.cpp
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/sink_command.hpp" #include <csignal> #include <iostream> #include <memory> #include <string> #include <string_view> #include <caf/scoped_actor.hpp> #include "vast/logger.hpp" #include "vast/system/signal_monitor.hpp" using namespace std::chrono_literals; using namespace caf; namespace vast::system { int sink_command::run_impl(caf::actor_system& sys, const caf::config_value_map& options, argument_iterator begin, argument_iterator end) { // Get a convenient and blocking way to interact with actors. scoped_actor self{sys}; // Get VAST node. auto node_opt = spawn_or_connect_to_node(self, options); if (!node_opt) return EXIT_FAILURE; auto node = std::move(*node_opt); /// Spawn an actor that takes care of CTRL+C and friends. auto sig_mon = self->spawn<detached>(system::signal_monitor, 750ms, self); auto guard = caf::detail::make_scope_guard([&] { self->send_exit(sig_mon, exit_reason::user_shutdown); }); // Spawn a sink. VAST_DEBUG(this, "spawns sink with parameters:", deep_to_string(options)); auto snk_opt = make_sink(self, options, begin, end); if (!snk_opt) { std::cerr << "unable to spawn sink: " << sys.render(snk_opt.error()) << std::endl; return EXIT_FAILURE; } auto snk = std::move(*snk_opt); // Spawn exporter at the node. actor exp; // TODO: we need to also include arguments in CLI format from the export // command; we really should forward `options` to the node actor // instead to clean this up auto args = caf::message_builder{begin, end}.move_to_message(); args = make_message("exporter") + args; if (get_or<bool>(options, "continuous", false)) args += make_message("--continuous"); if (get_or<bool>(options, "historical", false)) args += make_message("--historical"); if (get_or<bool>(options, "unified", false)) args += make_message("--unified"); auto max_events = get_or<uint64_t>(options, "events", 0u); args += make_message("-e", std::to_string(max_events)); VAST_DEBUG(this, "spawns exporter with parameters:", to_string(args)); self->request(node, infinite, "spawn", args).receive( [&](const actor& a) { exp = a; }, [&](const error& e) { VAST_IGNORE_UNUSED(e); VAST_ERROR(this, "failed to spawn exporter:", self->system().render(e)); } ); if (!exp) { self->send_exit(snk, exit_reason::user_shutdown); return EXIT_FAILURE; } // Start the exporter. self->send(exp, system::sink_atom::value, snk); self->send(exp, system::run_atom::value); self->monitor(snk); self->monitor(exp); auto rc = EXIT_SUCCESS; auto stop = false; self->do_receive( [&](const down_msg& msg) { if (msg.source == node) { VAST_DEBUG(this, "received DOWN from node"); self->send_exit(snk, exit_reason::user_shutdown); self->send_exit(exp, exit_reason::user_shutdown); rc = EXIT_FAILURE; } else if (msg.source == exp) { VAST_DEBUG(this, "received DOWN from exporter"); self->send_exit(snk, exit_reason::user_shutdown); } else if (msg.source == snk) { VAST_DEBUG(this, "received DOWN from sink"); self->send_exit(exp, exit_reason::user_shutdown); rc = EXIT_FAILURE; } else { VAST_ASSERT(!"received DOWN from inexplicable actor"); } if (msg.reason) { VAST_WARNING( this, "received error message:", self->system().render(msg.reason)); rc = EXIT_FAILURE; } stop = true; }, [&](system::signal_atom, int signal) { VAST_DEBUG(this, "got " << ::strsignal(signal)); if (signal == SIGINT || signal == SIGTERM) { self->send_exit(exp, exit_reason::user_shutdown); self->send_exit(snk, exit_reason::user_shutdown); } } ).until([&] { return stop; }); cleanup(node); return rc; } } // namespace vast::system
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/sink_command.hpp" #include <csignal> #include <iostream> #include <memory> #include <string> #include <string_view> #include <caf/scoped_actor.hpp> #include "vast/logger.hpp" #include "vast/system/signal_monitor.hpp" using namespace std::chrono_literals; using namespace caf; namespace vast::system { int sink_command::run_impl(caf::actor_system& sys, const caf::config_value_map& options, argument_iterator begin, argument_iterator end) { // Get a convenient and blocking way to interact with actors. scoped_actor self{sys}; // Get VAST node. auto node_opt = spawn_or_connect_to_node(self, options); if (!node_opt) return EXIT_FAILURE; auto node = std::move(*node_opt); /// Spawn an actor that takes care of CTRL+C and friends. auto sig_mon = self->spawn<detached>(system::signal_monitor, 750ms, self); auto guard = caf::detail::make_scope_guard([&] { self->send_exit(sig_mon, exit_reason::user_shutdown); }); // Spawn a sink. VAST_DEBUG(this, "spawns sink with parameters:", deep_to_string(options)); auto snk_opt = make_sink(self, options, begin, end); if (!snk_opt) { std::cerr << "unable to spawn sink: " << sys.render(snk_opt.error()) << std::endl; return EXIT_FAILURE; } auto snk = std::move(*snk_opt); // Spawn exporter at the node. actor exp; // TODO: we need to also include arguments in CLI format from the export // command; we really should forward `options` to the node actor // instead to clean this up auto args = caf::message_builder{begin, end}.move_to_message(); args = make_message("exporter") + args; if (get_or<bool>(options, "continuous", false)) args += make_message("--continuous"); if (get_or<bool>(options, "historical", false)) args += make_message("--historical"); if (get_or<bool>(options, "unified", false)) args += make_message("--unified"); auto max_events = get_or<uint64_t>(options, "events", 0u); args += make_message("-e", std::to_string(max_events)); VAST_DEBUG(this, "spawns exporter with parameters:", to_string(args)); self->request(node, infinite, "spawn", args).receive( [&](const actor& a) { exp = a; }, [&](const error& e) { VAST_IGNORE_UNUSED(e); VAST_ERROR(this, "failed to spawn exporter:", self->system().render(e)); } ); if (!exp) { self->send_exit(snk, exit_reason::user_shutdown); return EXIT_FAILURE; } // Start the exporter. self->send(exp, system::sink_atom::value, snk); self->send(exp, system::run_atom::value); self->monitor(snk); self->monitor(exp); auto rc = EXIT_SUCCESS; auto stop = false; self->do_receive( [&](const down_msg& msg) { if (msg.source == node) { VAST_DEBUG(this, "received DOWN from node"); self->send_exit(snk, exit_reason::user_shutdown); self->send_exit(exp, exit_reason::user_shutdown); } else if (msg.source == exp) { VAST_DEBUG(this, "received DOWN from exporter"); self->send_exit(snk, exit_reason::user_shutdown); } else if (msg.source == snk) { VAST_DEBUG(this, "received DOWN from sink"); self->send_exit(exp, exit_reason::user_shutdown); } else { VAST_ASSERT(!"received DOWN from inexplicable actor"); } if (msg.reason) { VAST_WARNING( this, "received error message:", self->system().render(msg.reason)); rc = EXIT_FAILURE; } stop = true; }, [&](system::signal_atom, int signal) { VAST_DEBUG(this, "got " << ::strsignal(signal)); if (signal == SIGINT || signal == SIGTERM) { self->send_exit(exp, exit_reason::user_shutdown); self->send_exit(snk, exit_reason::user_shutdown); } } ).until([&] { return stop; }); cleanup(node); return rc; } } // namespace vast::system
fix return value from sink_command
fix return value from sink_command
C++
bsd-3-clause
vast-io/vast,mavam/vast,vast-io/vast,mavam/vast,vast-io/vast,mavam/vast,vast-io/vast,mavam/vast,vast-io/vast
12a501cddc3f4c4c93190cb2e64bb2b9c1f558c0
Modules/Registration/Common/test/itkImageToSpatialObjectRegistrationTest.cxx
Modules/Registration/Common/test/itkImageToSpatialObjectRegistrationTest.cxx
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkEllipseSpatialObject.h" #include "itkLineSpatialObject.h" #include "itkGroupSpatialObject.h" #include "itkSpatialObjectToImageFilter.h" #include "itkImageToSpatialObjectRegistrationMethod.h" #include "itkOnePlusOneEvolutionaryOptimizer.h" #include "itkEuler2DTransform.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkNormalVariateGenerator.h" #include "itkTestingMacros.h" namespace itk { /** \class Iteration callback */ template <typename TOptimizer> class IterationCallback : public Command { public: using Self = IterationCallback; using Superclass = itk::Command; using Pointer = itk::SmartPointer<Self>; using ConstPointer = itk::SmartPointer<const Self>; itkTypeMacro(IterationCallback, Superclass); itkNewMacro(Self); /** Type defining the optimizer */ using OptimizerType = TOptimizer; /** Set Optimizer */ void SetOptimizer(OptimizerType * optimizer) { m_Optimizer = optimizer; m_Optimizer->AddObserver(itk::IterationEvent(), this); } /** Execute method will print data at each iteration */ void Execute(itk::Object * caller, const itk::EventObject & event) override { Execute((const itk::Object *)caller, event); } void Execute(const itk::Object *, const itk::EventObject & event) override { if (typeid(event) == typeid(itk::StartEvent)) { std::cout << std::endl << "Position Value"; std::cout << std::endl << std::endl; } else if (typeid(event) == typeid(itk::IterationEvent)) { std::cout << "#" << m_Optimizer->GetCurrentIteration() << " Current parameters = " << m_Optimizer->GetCurrentPosition() << std::endl; } else if (typeid(event) == typeid(itk::EndEvent)) { std::cout << std::endl << std::endl; std::cout << "After " << m_Optimizer->GetCurrentIteration(); std::cout << " iterations " << std::endl; std::cout << "Solution is = " << m_Optimizer->GetCurrentPosition(); std::cout << std::endl; } } protected: IterationCallback() = default; WeakPointer<OptimizerType> m_Optimizer; }; /** \class Cost Function */ template <typename TFixedImage, typename TMovingSpatialObject> class SimpleImageToSpatialObjectMetric : public ImageToSpatialObjectMetric<TFixedImage, TMovingSpatialObject> { public: /** Standard class type aliases. */ using Self = SimpleImageToSpatialObjectMetric; using Superclass = ImageToSpatialObjectMetric<TFixedImage, TMovingSpatialObject>; using Pointer = SmartPointer<Self>; using ConstPointer = SmartPointer<const Self>; using PointType = Point<double, 2>; using PointListType = std::list<PointType>; using MovingSpatialObjectType = TMovingSpatialObject; using typename Superclass::ParametersType; using typename Superclass::DerivativeType; using typename Superclass::MeasureType; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(SimpleImageToSpatialObjectMetric, ImageToSpatialObjectMetric); enum { SpaceDimension = 3 }; /** Connect the MovingSpatialObject */ void SetMovingSpatialObject(const MovingSpatialObjectType * object) override { if (!this->m_FixedImage) { std::cout << "Please set the image before the moving spatial object" << std::endl; return; } this->m_MovingSpatialObject = object; m_PointList.clear(); using myIteratorType = itk::ImageRegionConstIteratorWithIndex<TFixedImage>; myIteratorType it(this->m_FixedImage, this->m_FixedImage->GetLargestPossibleRegion()); itk::Point<double, 2> point; while (!it.IsAtEnd()) { for (unsigned int i = 0; i < Self::ObjectDimension; ++i) { point[i] = it.GetIndex()[i]; } if (this->m_MovingSpatialObject->IsInsideInWorldSpace(point, 99999)) { m_PointList.push_back(point); } ++it; } std::cout << "Number of points in the metric = " << static_cast<unsigned long>(m_PointList.size()) << std::endl; } /** Get the Derivatives of the Match Measure */ void GetDerivative(const ParametersType &, DerivativeType &) const override { return; } /** Get the Value for SingleValue Optimizers */ MeasureType GetValue(const ParametersType & parameters) const override { double value; this->m_Transform->SetParameters(parameters); auto it = m_PointList.begin(); Index<2> index; value = 0; while (it != m_PointList.end()) { PointType transformedPoint = this->m_Transform->TransformPoint(*it); index = this->m_FixedImage->TransformPhysicalPointToIndex(transformedPoint); if (index[0] > 0L && index[1] > 0L && index[0] < static_cast<signed long>(this->m_FixedImage->GetLargestPossibleRegion().GetSize()[0]) && index[1] < static_cast<signed long>(this->m_FixedImage->GetLargestPossibleRegion().GetSize()[1])) { value += this->m_FixedImage->GetPixel(index); } ++it; } return value; } /** Get Value and Derivatives for MultipleValuedOptimizers */ void GetValueAndDerivative(const ParametersType & parameters, MeasureType & Value, DerivativeType & Derivative) const override { Value = this->GetValue(parameters); this->GetDerivative(parameters, Derivative); } private: PointListType m_PointList; }; } // end namespace itk /** test */ int itkImageToSpatialObjectRegistrationTest(int, char *[]) { using GroupType = itk::GroupSpatialObject<2>; using EllipseType = itk::EllipseSpatialObject<2>; // Create a group with 3 ellipses linked by lines. auto ellipse1 = EllipseType::New(); auto ellipse2 = EllipseType::New(); auto ellipse3 = EllipseType::New(); // Set the radius ellipse1->SetRadiusInObjectSpace(10); ellipse2->SetRadiusInObjectSpace(10); ellipse3->SetRadiusInObjectSpace(10); // Place each ellipse at the right position to form a triangle EllipseType::TransformType::OffsetType offset; offset[0] = 100; offset[1] = 40; ellipse1->SetCenterInObjectSpace(offset); ellipse1->Update(); offset[0] = 40; offset[1] = 150; ellipse2->SetCenterInObjectSpace(offset); ellipse2->Update(); offset[0] = 150; offset[1] = 150; // Moving the object using the ObjectToParentTransform should // be equivalent to setting its CenterInObjectSpace ellipse3->GetModifiableObjectToParentTransform()->SetOffset(offset); ellipse3->Update(); auto group = GroupType::New(); group->AddChild(ellipse1); group->AddChild(ellipse2); group->AddChild(ellipse3); group->Update(); using ImageType = itk::Image<double, 2>; using SpatialObjectToImageFilterType = itk::SpatialObjectToImageFilter<GroupType, ImageType>; auto imageFilter = SpatialObjectToImageFilterType::New(); imageFilter->SetInput(group); ImageType::SizeType size; size[0] = 200; size[1] = 200; imageFilter->SetSize(size); imageFilter->Update(); ImageType::Pointer image = imageFilter->GetOutput(); // blurr the image to have a global maximum using GaussianFilterType = itk::DiscreteGaussianImageFilter<ImageType, ImageType>; auto gaussianFilter = GaussianFilterType::New(); gaussianFilter->SetInput(image); constexpr double variance = 20; gaussianFilter->SetVariance(variance); gaussianFilter->Update(); image = gaussianFilter->GetOutput(); using RegistrationType = itk::ImageToSpatialObjectRegistrationMethod<ImageType, GroupType>; auto registration = RegistrationType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(registration, ImageToSpatialObjectRegistrationMethod, ProcessObject); using MetricType = itk::SimpleImageToSpatialObjectMetric<ImageType, GroupType>; auto metric = MetricType::New(); std::cout << "metric = " << metric << std::endl; using InterpolatorType = itk::LinearInterpolateImageFunction<ImageType, double>; auto interpolator = InterpolatorType::New(); using OptimizerType = itk::OnePlusOneEvolutionaryOptimizer; auto optimizer = OptimizerType::New(); using TransformType = itk::Euler2DTransform<>; auto transform = TransformType::New(); metric->SetTransform(transform); std::cout << "Number of Parameters : " << metric->GetNumberOfParameters() << std::endl; ITK_TEST_EXPECT_EQUAL(metric->GetNumberOfParameters(), 3); bool catching; try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } registration->SetFixedImage(image); ITK_TEST_SET_GET_VALUE(image, registration->GetFixedImage()); try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } registration->SetMovingSpatialObject(group); ITK_TEST_SET_GET_VALUE(group, registration->GetMovingSpatialObject()); try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } registration->SetMetric(metric); ITK_TEST_SET_GET_VALUE(metric, registration->GetMetric()); try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } /** Setup the optimizer */ TransformType::ParametersType m_ParametersScale; m_ParametersScale.set_size(3); m_ParametersScale[0] = 100; // angle scale for (unsigned int i = 1; i < 3; ++i) { m_ParametersScale[i] = 1; // offset scale } optimizer->SetScales(m_ParametersScale); TransformType::ParametersType initialParameters; initialParameters.set_size(3); initialParameters[0] = 0.2; // angle initialParameters[1] = 7; // offset initialParameters[2] = 6; // offset std::cout << "Initial Parameters : " << initialParameters << std::endl; registration->SetInitialTransformParameters(initialParameters); ITK_TEST_SET_GET_VALUE(initialParameters, registration->GetInitialTransformParameters()); optimizer->MaximizeOn(); itk::Statistics::NormalVariateGenerator::Pointer generator = itk::Statistics::NormalVariateGenerator::New(); generator->Initialize(12345); optimizer->SetNormalVariateGenerator(generator); optimizer->Initialize(1.02, 1.1); optimizer->SetEpsilon(0.01); optimizer->SetMaximumIteration(500); using IterationCallbackType = itk::IterationCallback<OptimizerType>; auto callback = IterationCallbackType::New(); callback->SetOptimizer(optimizer); registration->SetOptimizer(optimizer); ITK_TEST_SET_GET_VALUE(optimizer, registration->GetOptimizer()); try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } registration->SetTransform(transform); ITK_TEST_SET_GET_VALUE(transform, registration->GetTransform()); try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } registration->SetInterpolator(interpolator); ITK_TEST_SET_GET_VALUE(interpolator, registration->GetInterpolator()); registration->Update(); RegistrationType::ParametersType finalParameters = registration->GetLastTransformParameters(); std::cout << "Final Solution is : " << finalParameters << std::endl; for (unsigned int i = 0; i < 3; ++i) { if (finalParameters[i] > 1) // if we are not within 1 pixel the registration fails { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } } std::cout << "Test Succeed!" << std::endl; return EXIT_SUCCESS; }
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkEllipseSpatialObject.h" #include "itkLineSpatialObject.h" #include "itkGroupSpatialObject.h" #include "itkSpatialObjectToImageFilter.h" #include "itkImageToSpatialObjectRegistrationMethod.h" #include "itkOnePlusOneEvolutionaryOptimizer.h" #include "itkEuler2DTransform.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkNormalVariateGenerator.h" #include "itkTestingMacros.h" namespace itk { /** \class Iteration callback */ template <typename TOptimizer> class IterationCallback : public Command { public: using Self = IterationCallback; using Superclass = itk::Command; using Pointer = itk::SmartPointer<Self>; using ConstPointer = itk::SmartPointer<const Self>; itkTypeMacro(IterationCallback, Superclass); itkNewMacro(Self); /** Type defining the optimizer */ using OptimizerType = TOptimizer; /** Set Optimizer */ void SetOptimizer(OptimizerType * optimizer) { m_Optimizer = optimizer; m_Optimizer->AddObserver(itk::IterationEvent(), this); } /** Execute method will print data at each iteration */ void Execute(itk::Object * caller, const itk::EventObject & event) override { Execute((const itk::Object *)caller, event); } void Execute(const itk::Object *, const itk::EventObject & event) override { if (typeid(event) == typeid(itk::StartEvent)) { std::cout << std::endl << "Position Value"; std::cout << std::endl << std::endl; } else if (typeid(event) == typeid(itk::IterationEvent)) { std::cout << "#" << m_Optimizer->GetCurrentIteration() << " Current parameters = " << m_Optimizer->GetCurrentPosition() << std::endl; } else if (typeid(event) == typeid(itk::EndEvent)) { std::cout << std::endl << std::endl; std::cout << "After " << m_Optimizer->GetCurrentIteration(); std::cout << " iterations " << std::endl; std::cout << "Solution is = " << m_Optimizer->GetCurrentPosition(); std::cout << std::endl; } } protected: IterationCallback() = default; WeakPointer<OptimizerType> m_Optimizer; }; /** \class Cost Function */ template <typename TFixedImage, typename TMovingSpatialObject> class SimpleImageToSpatialObjectMetric : public ImageToSpatialObjectMetric<TFixedImage, TMovingSpatialObject> { public: /** Standard class type aliases. */ using Self = SimpleImageToSpatialObjectMetric; using Superclass = ImageToSpatialObjectMetric<TFixedImage, TMovingSpatialObject>; using Pointer = SmartPointer<Self>; using ConstPointer = SmartPointer<const Self>; using PointType = Point<double, 2>; using PointListType = std::list<PointType>; using MovingSpatialObjectType = TMovingSpatialObject; using typename Superclass::ParametersType; using typename Superclass::DerivativeType; using typename Superclass::MeasureType; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(SimpleImageToSpatialObjectMetric, ImageToSpatialObjectMetric); enum { SpaceDimension = 3 }; /** Connect the MovingSpatialObject */ void SetMovingSpatialObject(const MovingSpatialObjectType * object) override { if (!this->m_FixedImage) { std::cout << "Please set the image before the moving spatial object" << std::endl; return; } this->m_MovingSpatialObject = object; m_PointList.clear(); using myIteratorType = itk::ImageRegionConstIteratorWithIndex<TFixedImage>; myIteratorType it(this->m_FixedImage, this->m_FixedImage->GetLargestPossibleRegion()); itk::Point<double, 2> point; while (!it.IsAtEnd()) { for (unsigned int i = 0; i < Self::ObjectDimension; ++i) { point[i] = it.GetIndex()[i]; } if (this->m_MovingSpatialObject->IsInsideInWorldSpace(point, 99999)) { m_PointList.push_back(point); } ++it; } std::cout << "Number of points in the metric = " << static_cast<unsigned long>(m_PointList.size()) << std::endl; } /** Get the Derivatives of the Match Measure */ void GetDerivative(const ParametersType &, DerivativeType &) const override { return; } /** Get the Value for SingleValue Optimizers */ MeasureType GetValue(const ParametersType & parameters) const override { double value; this->m_Transform->SetParameters(parameters); auto it = m_PointList.begin(); Index<2> index; value = 0; while (it != m_PointList.end()) { PointType transformedPoint = this->m_Transform->TransformPoint(*it); index = this->m_FixedImage->TransformPhysicalPointToIndex(transformedPoint); if (index[0] > 0L && index[1] > 0L && index[0] < static_cast<signed long>(this->m_FixedImage->GetLargestPossibleRegion().GetSize()[0]) && index[1] < static_cast<signed long>(this->m_FixedImage->GetLargestPossibleRegion().GetSize()[1])) { value += this->m_FixedImage->GetPixel(index); } ++it; } return value; } /** Get Value and Derivatives for MultipleValuedOptimizers */ void GetValueAndDerivative(const ParametersType & parameters, MeasureType & Value, DerivativeType & Derivative) const override { Value = this->GetValue(parameters); this->GetDerivative(parameters, Derivative); } private: PointListType m_PointList; }; } // end namespace itk /** test */ int itkImageToSpatialObjectRegistrationTest(int, char *[]) { using GroupType = itk::GroupSpatialObject<2>; using EllipseType = itk::EllipseSpatialObject<2>; // Create a group with 3 ellipses linked by lines. auto ellipse1 = EllipseType::New(); auto ellipse2 = EllipseType::New(); auto ellipse3 = EllipseType::New(); // Set the radius ellipse1->SetRadiusInObjectSpace(10); ellipse2->SetRadiusInObjectSpace(10); ellipse3->SetRadiusInObjectSpace(10); // Place each ellipse at the right position to form a triangle EllipseType::PointType point; point[0] = 100; point[1] = 40; ellipse1->SetCenterInObjectSpace(point); ellipse1->Update(); point[0] = 40; point[1] = 150; ellipse2->SetCenterInObjectSpace(point); ellipse2->Update(); EllipseType::TransformType::OffsetType offset; offset[0] = 150; offset[1] = 150; // Moving the object using the ObjectToParentTransform should // be equivalent to setting its CenterInObjectSpace ellipse3->GetModifiableObjectToParentTransform()->SetOffset(offset); ellipse3->Update(); auto group = GroupType::New(); group->AddChild(ellipse1); group->AddChild(ellipse2); group->AddChild(ellipse3); group->Update(); using ImageType = itk::Image<double, 2>; using SpatialObjectToImageFilterType = itk::SpatialObjectToImageFilter<GroupType, ImageType>; auto imageFilter = SpatialObjectToImageFilterType::New(); imageFilter->SetInput(group); ImageType::SizeType size; size[0] = 200; size[1] = 200; imageFilter->SetSize(size); imageFilter->Update(); ImageType::Pointer image = imageFilter->GetOutput(); // blurr the image to have a global maximum using GaussianFilterType = itk::DiscreteGaussianImageFilter<ImageType, ImageType>; auto gaussianFilter = GaussianFilterType::New(); gaussianFilter->SetInput(image); constexpr double variance = 20; gaussianFilter->SetVariance(variance); gaussianFilter->Update(); image = gaussianFilter->GetOutput(); using RegistrationType = itk::ImageToSpatialObjectRegistrationMethod<ImageType, GroupType>; auto registration = RegistrationType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(registration, ImageToSpatialObjectRegistrationMethod, ProcessObject); using MetricType = itk::SimpleImageToSpatialObjectMetric<ImageType, GroupType>; auto metric = MetricType::New(); std::cout << "metric = " << metric << std::endl; using InterpolatorType = itk::LinearInterpolateImageFunction<ImageType, double>; auto interpolator = InterpolatorType::New(); using OptimizerType = itk::OnePlusOneEvolutionaryOptimizer; auto optimizer = OptimizerType::New(); using TransformType = itk::Euler2DTransform<>; auto transform = TransformType::New(); metric->SetTransform(transform); std::cout << "Number of Parameters : " << metric->GetNumberOfParameters() << std::endl; ITK_TEST_EXPECT_EQUAL(metric->GetNumberOfParameters(), 3); bool catching; try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } registration->SetFixedImage(image); ITK_TEST_SET_GET_VALUE(image, registration->GetFixedImage()); try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } registration->SetMovingSpatialObject(group); ITK_TEST_SET_GET_VALUE(group, registration->GetMovingSpatialObject()); try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } registration->SetMetric(metric); ITK_TEST_SET_GET_VALUE(metric, registration->GetMetric()); try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } /** Setup the optimizer */ TransformType::ParametersType m_ParametersScale; m_ParametersScale.set_size(3); m_ParametersScale[0] = 100; // angle scale for (unsigned int i = 1; i < 3; ++i) { m_ParametersScale[i] = 1; // offset scale } optimizer->SetScales(m_ParametersScale); TransformType::ParametersType initialParameters; initialParameters.set_size(3); initialParameters[0] = 0.2; // angle initialParameters[1] = 7; // offset initialParameters[2] = 6; // offset std::cout << "Initial Parameters : " << initialParameters << std::endl; registration->SetInitialTransformParameters(initialParameters); ITK_TEST_SET_GET_VALUE(initialParameters, registration->GetInitialTransformParameters()); optimizer->MaximizeOn(); itk::Statistics::NormalVariateGenerator::Pointer generator = itk::Statistics::NormalVariateGenerator::New(); generator->Initialize(12345); optimizer->SetNormalVariateGenerator(generator); optimizer->Initialize(1.02, 1.1); optimizer->SetEpsilon(0.01); optimizer->SetMaximumIteration(500); using IterationCallbackType = itk::IterationCallback<OptimizerType>; auto callback = IterationCallbackType::New(); callback->SetOptimizer(optimizer); registration->SetOptimizer(optimizer); ITK_TEST_SET_GET_VALUE(optimizer, registration->GetOptimizer()); try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } registration->SetTransform(transform); ITK_TEST_SET_GET_VALUE(transform, registration->GetTransform()); try { catching = false; registration->Update(); } catch (...) { catching = true; } if (!catching) { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } registration->SetInterpolator(interpolator); ITK_TEST_SET_GET_VALUE(interpolator, registration->GetInterpolator()); registration->Update(); RegistrationType::ParametersType finalParameters = registration->GetLastTransformParameters(); std::cout << "Final Solution is : " << finalParameters << std::endl; for (unsigned int i = 0; i < 3; ++i) { if (finalParameters[i] > 1) // if we are not within 1 pixel the registration fails { std::cout << "Test failed!" << std::endl; return EXIT_FAILURE; } } std::cout << "Test Succeed!" << std::endl; return EXIT_SUCCESS; }
Fix `SetCenterInObjectSpace` calls in Registration test
BUG: Fix `SetCenterInObjectSpace` calls in Registration test Calls to `EllipseSpatialObject::SetCenterInObjectSpace` should have a point as argument, not an offset. Bug found by locally (temporarily) declaring converting constructors of `itk::Point` "explicit".
C++
apache-2.0
hjmjohnson/ITK,thewtex/ITK,thewtex/ITK,thewtex/ITK,BRAINSia/ITK,richardbeare/ITK,Kitware/ITK,hjmjohnson/ITK,richardbeare/ITK,richardbeare/ITK,thewtex/ITK,BRAINSia/ITK,thewtex/ITK,InsightSoftwareConsortium/ITK,BRAINSia/ITK,richardbeare/ITK,hjmjohnson/ITK,hjmjohnson/ITK,richardbeare/ITK,Kitware/ITK,Kitware/ITK,richardbeare/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,hjmjohnson/ITK,Kitware/ITK,BRAINSia/ITK,richardbeare/ITK,BRAINSia/ITK,Kitware/ITK,thewtex/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,BRAINSia/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,hjmjohnson/ITK,thewtex/ITK,hjmjohnson/ITK
f5f3f4d68cfba7131f1a76329e5836f1eeecebf5
include/CompositeAction.hh
include/CompositeAction.hh
#ifndef COMPOSITEACTION_HH #define COMPOSITEACTION_HH #include <iostream> #include <list> #include <algorithm> namespace g4 { /** * Composite action. * * In Geant4, you can typically add only one user action of each type. * If you combine multiple libraries together, each of which wants to * define such action, a conflict arises. * * This class can be easily used on its own (as is). */ template<typename ActionType> class CompositeAction : public ActionType { public: CompositeAction() : _actions() { } void AddSubAction(ActionType* action) { // TODO: Check if already present _actions.push_back(action); } void RemoveSubAction(ActionType* action) { // Erases just one (first) copy of the action. typename std::list<ActionType*>::iterator it = find(_actions.begin(), _actions.end(), action); if (it != _actions.end()) { _actions.erase(it); } } protected: template<typename ArgType> void Invoke(void (ActionType::*func)(ArgType), ArgType arg) { // All sub-actions for (typename std::list<ActionType*>::iterator it = _actions.begin(); it != _actions.end(); it++) { ActionType& action = **it; // Weird syntax for calling pointed-to-member-function // According to http://www.parashift.com/c++-faq/macro-for-ptr-to-memfn.html ((action).*(func))(arg); } } std::list<ActionType*> _actions; }; } #endif // COMPOSITEACTION_HH
#ifndef COMPOSITEACTION_HH #define COMPOSITEACTION_HH #include <iostream> #include <list> #include <algorithm> namespace g4 { /** * Composite action. * * In Geant4, you can typically add only one user action of each type. * If you combine multiple libraries together, each of which wants to * define such action, a conflict arises. * * This class can be easily used on its own (as is). */ template<typename ActionType> class CompositeAction : public ActionType { public: CompositeAction() : _actions() { } /** * @short Add action. * * If already present, nothing happens. */ void AddSubAction(ActionType* action) { if (find(_actions.begin(), _actions.end(), action) == _actions.end()) { _actions.push_back(action); } } /** * @short Remove action. */ void RemoveSubAction(ActionType* action) { // Erases just one (first) copy of the action. typename std::list<ActionType*>::iterator it = find(_actions.begin(), _actions.end(), action); if (it != _actions.end()) { _actions.erase(it); } } protected: /** * @short Call a member method on all actions. */ template<typename ArgType> void Invoke(void (ActionType::*func)(ArgType), ArgType arg) { // All sub-actions for (typename std::list<ActionType*>::iterator it = _actions.begin(); it != _actions.end(); it++) { ActionType& action = **it; // Weird syntax for calling pointed-to-member-function // According to http://www.parashift.com/c++-faq/macro-for-ptr-to-memfn.html ((action).*(func))(arg); } } private: std::list<ActionType*> _actions; }; } #endif // COMPOSITEACTION_HH
Check for uniqueness when adding action to CompositeAction
Check for uniqueness when adding action to CompositeAction
C++
mit
janpipek/g4application
331596d1543eba7c62be405f32201ed121bed999
include/cybozu/nlp/svd.hpp
include/cybozu/nlp/svd.hpp
#pragma once /** @file @brief fast non-probabilistic SVD Copyright (C) 2012 Cybozu Labs, Inc., all rights reserved. @author MITSUNARI Shigeo */ #include <assert.h> #include <vector> #include <string> #include <fstream> #include <sstream> #include <iomanip> //#define CYBOZU_NLP_SVD_USE_RANDOM #ifdef CYBOZU_NLP_SVD_USE_RANDOM #include <cybozu/nlp/random.hpp> #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4714) // force inline #endif #include <eigen3/Eigen/Dense> #include <eigen3/Eigen/Eigenvalues> #ifdef _MSC_VER // #pragma warning(pop) #endif /*** text format Matrix(dense) --- # M D <row> <col> data1_1 data1_2 data1_3 ... data2_1 data2_2 ... .... --- Matrix(sparse) --- # M S <row> <col> c1:data1_c1 c2:data1_c2 c3:data1_c3 ... c1:data2_c1 c2:data2_c2 c3:data2_c3 ... .... --- ex. M = (1.0 2.0 3.0) (1.2 2.4 3.5) --- # M D 2 3 1.0 2.0 3.0 1.2 2.4 3.5 --- M = (1.0 0 3.0) (0 4.2 0 ) --- # M S 2 3 0:1.0 2:3.0 1:4.2 --- */ namespace cybozu { namespace nlp { namespace svd { #ifdef CYBOZU_NLP_SVD_USE_RANDOM template<class Matrix> void InitRandomMatrix(Matrix& M) { cybozu::nlp::NormalRandomGenerator r; for (int i = 0; i < M.rows(); i++) { for (int j = 0; j < M.cols(); j++) { M(i, j) = typename Matrix::Scalar(r.get()); } } } #endif template<class Matrix> void InitUnitMatrix(Matrix& m) { typedef typename Matrix::Scalar Double; m.setZero(); const int row = m.rows(); const int col = m.cols(); assert(col <= row); #if 1 const int adj = 0;//(col & 1) ? row/2 : 0; for (int i = 0; i < row; i++) { m(i, (i * col + adj) / row) = 1; } #else const int q0 = row / col; const int r0 = row % col; const double rcol = 1.0 / col; int b = 0; int q = q0; int e = r0; int rowIdx = 0; int colIdx = 0; for (;;) { if (b > 0) { m(rowIdx, colIdx) = Double(b * rcol); rowIdx++; } for (int j = 0; j < q; j++) { m(rowIdx, colIdx) = 1; rowIdx++; } if (e > 0) { m(rowIdx, colIdx) = Double(e * rcol); } if (colIdx == col - 1) break; b = e == 0 ? 0 : col - e; e = r0 - b; if (e < 0) { q = q0 - 1; e += col; } else { q = q0; } colIdx++; } assert(rowIdx == row); #endif } /* m(row, col) => M(row, r) r <= col */ template<class Matrix1, class Matrix2> void CompressCol(Matrix1& out, const Matrix2& m, int r) { typedef typename Matrix1::Scalar Double; const int row = m.rows(); const int col = m.cols(); assert(r <= col); out.resize(row, r); #if 1 int begin = 0; for (int j = 0; j < r; j++) { int end = std::min(((j + 1) * col + r - 1) / r, col); // printf("%d [%d, %d)\n", j, begin, end); for (int i = 0; i < row; i++) { double x = 0; for (int k = begin; k < end; k++) { x += m(i, k); } out(i, j) = Double(x); } begin = end; } #else const int q0 = col / r; const int r0 = col % r; const double rr = 1.0 / r; int b = 0; int q = q0; int e = r0; int colIdx = 0; int rIdx = 0; for (;;) { for (int i = 0; i < row; i++) { double x = 0; int k = colIdx; if (b > 0) { x += m(i, k) * b * rr; k++; } for (int j = 0; j < q; j++) { x += m(i, k); k++; } if (e > 0) { x += m(i, k) * e * rr; } out(i, rIdx) = Double(x); } if (b > 0) colIdx++; colIdx += q; if (rIdx == r - 1) break; b = e == 0 ? 0 : r - e; e = r0 - b; if (e < 0) { q = q0 - 1; e += r; } else { q = q0; } rIdx++; } assert(colIdx == col); #endif } template<class Matrix> void OrthonormalizeMatrix(Matrix& M) { const double eps = 1e-5; typedef typename Matrix::Scalar Double; for (int i = 0; i < M.cols(); i++) { double norm = M.col(i).norm(); if (norm < eps) { M.col(i).setZero(); } else { Double rev = Double(1.0 / norm); M.col(i) *= rev; for (int j = i + 1; j < M.cols(); j++) { Double x = M.col(i).dot(M.col(j)); M.col(j) -= M.col(i) * x; } } } } inline bool LoadHeader(bool *isMatrix, bool *isSparse, int *row, int *col, std::istream& ifs) { std::string line; if (std::getline(ifs, line)) { std::istringstream is(line); char c, vec, type; is >> c >> vec >> type >> *row >> *col; if (c != '#') { fprintf(stderr, "top char is #(%c)\n", c); goto ERR; } if (vec != 'M' && vec != 'V') { fprintf(stderr, "vec is M(matrix) or V(vector) (%c)\n", vec); goto ERR; } *isMatrix = vec == 'M'; if (type != 'S' && type != 'D') { fprintf(stderr, "type is D(dense) or S(sparse) (%c)\n", type); goto ERR; } *isSparse = type == 'S'; if (*row <= 0 || *col <= 0) { fprintf(stderr, "row(%d) and col(%d) should be positive\n", *row, *col); goto ERR; } fprintf(stderr, "input (%c, %c, %d, %d)\n", vec, type, *row, *col); return true; } ERR: fprintf(stderr, "bad format top line must be '# (M|V) (D|S) <row> <col>'\n"); return false; } template<class Matrix> bool LoadMatrix(Matrix& A, const std::string& input) { std::ifstream ifs(input.c_str(), std::ios::binary); bool isMatrix = false; bool isSparse = false; int row = 0, col = 0; if (!LoadHeader(&isMatrix, &isSparse, &row, &col, ifs) || !isMatrix) { return false; } A.resize(row, col); if (isSparse) { for (int i = 0; i < row; i++) { A.row(i).setZero(); std::string line; if (!std::getline(ifs, line)) { fprintf(stderr, "can't read %d line\n", i); return false; } std::istringstream is(line); for (;;) { int idx; char sep; double v; is >> idx >> sep >> v; if (!is) break; if (sep != ':' || idx < 0 || idx >= col) { fprintf(stderr, "can't read %s\n", line.c_str()); return false; } A(i, idx) = typename Matrix::Scalar(v); } } } else { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { double v; ifs >> v; if (!ifs) { fprintf(stderr, "can't read (%d,%d)\n", i, j); return false; } A(i, j) = typename Matrix::Scalar(v); } } } return true; } template<class Matrix> bool SaveMatrix(const std::string& outName, const Matrix& M) { std::ofstream ofs(outName.c_str(), std::ios::binary); ofs << std::setprecision(8); ofs << "# M D " << M.rows() << " " << M.cols() << std::endl; for (int i = 0; i < M.rows(); i++) { for (int j = 0; j < M.cols(); j++) { if (j > 0) ofs << ' '; ofs << M(i, j); } ofs << std::endl; } return ofs.good(); } template<class Vector> bool SaveVector(const std::string& outName, const Vector& V) { std::ofstream ofs(outName.c_str(), std::ios::binary); ofs << std::setprecision(8); ofs << "# V D " << V.rows() << std::endl; for (int i = 0; i < V.rows(); i++) { ofs << V(i) << std::endl; } return ofs.good(); } } // svd /* approximate singular value decomposition A = U S t(V) with rank r t(M) : transpose of M t(U) U = I t(V) V = I R : compressed unit matrix Y = t(A) R Y = orthonormalize(Y) ; t(Y) Y = I B = A Y Z = orthonormalize(B) ; t(Z) Z = I C = t(Z) B C = U' S t(V') A \simeq A Y t(Y) = B t(Y) \simeq Z t(Z) B t(Y) = Z C t(Y) = Z U' S t(V') t(Y) = (Z U') S t(YV') = U S V */ template<class Matrix, class Vector> bool ComputeSVD(Matrix& U, Vector& S, Matrix& V, const Matrix& A, int rank) { const int row = A.rows(); const int col = A.cols(); const int r = std::min(std::min(col, row), rank); if (r <= 0) return false; #if 0 Matrix R(row, r); svd::InitRandomMatrix(R); // svd::InitUnitMatrix(R); Matrix Y = A.transpose() * R; #else Matrix Y; svd::CompressCol(Y, A.transpose(), r); #endif svd::OrthonormalizeMatrix(Y); const Matrix B = A * Y; Matrix Z = B; svd::OrthonormalizeMatrix(Z); const Matrix C = Z.transpose() * B; const Eigen::JacobiSVD<Matrix> svd(C, Eigen::ComputeThinU | Eigen::ComputeThinV); U = Z * svd.matrixU(); S = svd.singularValues(); V = Y * svd.matrixV(); return true; } } } // cybozu::nlp
#pragma once /** @file @brief fast non-probabilistic SVD Copyright (C) 2012 Cybozu Labs, Inc., all rights reserved. @author MITSUNARI Shigeo */ #include <assert.h> #include <vector> #include <string> #include <fstream> #include <sstream> #include <iomanip> //#define CYBOZU_NLP_SVD_USE_RANDOM #ifdef CYBOZU_NLP_SVD_USE_RANDOM #include <cybozu/nlp/random.hpp> #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4714) // force inline #endif #include <eigen3/Eigen/Dense> #include <eigen3/Eigen/Eigenvalues> #ifdef _MSC_VER // #pragma warning(pop) #endif /*** text format Matrix(dense) --- # M D <row> <col> data1_1 data1_2 data1_3 ... data2_1 data2_2 ... .... --- Matrix(sparse) --- # M S <row> <col> c1:data1_c1 c2:data1_c2 c3:data1_c3 ... c1:data2_c1 c2:data2_c2 c3:data2_c3 ... .... --- ex. M = (1.0 2.0 3.0) (1.2 2.4 3.5) --- # M D 2 3 1.0 2.0 3.0 1.2 2.4 3.5 --- M = (1.0 0 3.0) (0 4.2 0 ) --- # M S 2 3 0:1.0 2:3.0 1:4.2 --- */ namespace cybozu { namespace nlp { namespace svd { #ifdef CYBOZU_NLP_SVD_USE_RANDOM template<class Matrix> void InitRandomMatrix(Matrix& M) { cybozu::nlp::NormalRandomGenerator r; for (int i = 0; i < M.rows(); i++) { for (int j = 0; j < M.cols(); j++) { M(i, j) = typename Matrix::Scalar(r.get()); } } } #endif template<class Matrix> void InitUnitMatrix(Matrix& m) { typedef typename Matrix::Scalar Double; m.setZero(); const int row = m.rows(); const int col = m.cols(); assert(col <= row); #if 1 const int adj = 0;//(col & 1) ? row/2 : 0; for (int i = 0; i < row; i++) { m(i, (i * col + adj) / row) = 1; } #else const int q0 = row / col; const int r0 = row % col; const double rcol = 1.0 / col; int b = 0; int q = q0; int e = r0; int rowIdx = 0; int colIdx = 0; for (;;) { if (b > 0) { m(rowIdx, colIdx) = Double(b * rcol); rowIdx++; } for (int j = 0; j < q; j++) { m(rowIdx, colIdx) = 1; rowIdx++; } if (e > 0) { m(rowIdx, colIdx) = Double(e * rcol); } if (colIdx == col - 1) break; b = e == 0 ? 0 : col - e; e = r0 - b; if (e < 0) { q = q0 - 1; e += col; } else { q = q0; } colIdx++; } assert(rowIdx == row); #endif } /* m(row, col) => M(row, r) r <= col */ template<class Matrix1, class Matrix2> void CompressCol(Matrix1& out, const Matrix2& m, int r) { typedef typename Matrix1::Scalar Double; const int row = m.rows(); const int col = m.cols(); assert(r <= col); out.resize(row, r); #if 1 int begin = 0; for (int j = 0; j < r; j++) { int end = std::min(((j + 1) * col + r - 1) / r, col); // printf("%d [%d, %d)\n", j, begin, end); for (int i = 0; i < row; i++) { double x = 0; for (int k = begin; k < end; k++) { x += m(i, k); } out(i, j) = Double(x); } begin = end; } #else const int q0 = col / r; const int r0 = col % r; const double rr = 1.0 / r; int b = 0; int q = q0; int e = r0; int colIdx = 0; int rIdx = 0; for (;;) { for (int i = 0; i < row; i++) { double x = 0; int k = colIdx; if (b > 0) { x += m(i, k) * b * rr; k++; } for (int j = 0; j < q; j++) { x += m(i, k); k++; } if (e > 0) { x += m(i, k) * e * rr; } out(i, rIdx) = Double(x); } if (b > 0) colIdx++; colIdx += q; if (rIdx == r - 1) break; b = e == 0 ? 0 : r - e; e = r0 - b; if (e < 0) { q = q0 - 1; e += r; } else { q = q0; } rIdx++; } assert(colIdx == col); #endif } template<class Matrix> void OrthonormalizeMatrix(Matrix& M) { const double eps = 1e-5; typedef typename Matrix::Scalar Double; for (int i = 0; i < M.cols(); i++) { double norm = M.col(i).norm(); if (norm < eps) { M.col(i).setZero(); } else { Double rev = Double(1.0 / norm); M.col(i) *= rev; for (int j = i + 1; j < M.cols(); j++) { Double x = M.col(i).dot(M.col(j)); M.col(j) -= M.col(i) * x; } } } } inline bool LoadHeader(bool *isMatrix, bool *isSparse, int *row, int *col, std::ifstream& ifs, const std::string& input) { ifs.open(input.c_str(), std::ios::binary); if (!ifs) { fprintf(stderr, "can't open %s\n", input.c_str()); return false; } std::string line; if (std::getline(ifs, line)) { std::istringstream is(line); char c, vec, type; is >> c >> vec >> type >> *row >> *col; if (c != '#') { fprintf(stderr, "top char is #(%c)\n", c); goto ERR; } if (*row <= 0) { fprintf(stderr, "row(%d) should be positive\n", *row); goto ERR; } if (type != 'S' && type != 'D') { fprintf(stderr, "type is D(dense) or S(sparse) (%c)\n", type); goto ERR; } *isSparse = type == 'S'; switch (vec) { case 'M': if (*col <= 0) { fprintf(stderr, "col(%d) should be positive\n", *col); goto ERR; } *isMatrix = true; break; case 'V': *col = 1; *isMatrix = false; break; default: fprintf(stderr, "vec is M(matrix) or V(vector) (%c)\n", vec); goto ERR; } fprintf(stderr, "input (%c, %c, %d, %d)\n", vec, type, *row, *col); return true; } ERR: fprintf(stderr, "bad format top line must be '# (M|V) (D|S) <row> <col>'\n"); return false; } template<class Matrix> bool LoadMatrix(Matrix& A, const std::string& input) { std::ifstream ifs; bool isMatrix = false; bool isSparse = false; int row = 0, col = 0; if (!LoadHeader(&isMatrix, &isSparse, &row, &col, ifs, input) || !isMatrix) { return false; } A.resize(row, col); if (isSparse) { for (int i = 0; i < row; i++) { A.row(i).setZero(); std::string line; if (!std::getline(ifs, line)) { fprintf(stderr, "can't read %d line\n", i); return false; } std::istringstream is(line); for (;;) { int idx; char sep; double v; is >> idx >> sep >> v; if (!is) break; if (sep != ':' || idx < 0 || idx >= col) { fprintf(stderr, "can't read %s\n", line.c_str()); return false; } A(i, idx) = typename Matrix::Scalar(v); } } } else { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { double v; ifs >> v; if (!ifs) { fprintf(stderr, "can't read (%d,%d)\n", i, j); return false; } A(i, j) = typename Matrix::Scalar(v); } } } return true; } template<class Vector> bool LoadVector(Vector& V, const std::string& input) { std::ifstream ifs; bool isMatrix = false; bool isSparse = false; int row = 0, col = 0; if (!LoadHeader(&isMatrix, &isSparse, &row, &col, ifs, input) || isMatrix) { return false; } V.resize(row, 1); for (int i = 0; i < row; i++) { double v; ifs >> v; if (!ifs) { fprintf(stderr, "can't read (%d)\n", i); return false; } V(i) = typename Vector::Scalar(v); } return true; } template<class Matrix> bool SaveMatrix(const std::string& outName, const Matrix& M) { std::ofstream ofs(outName.c_str(), std::ios::binary); ofs << std::setprecision(8); ofs << "# M D " << M.rows() << " " << M.cols() << std::endl; for (int i = 0; i < M.rows(); i++) { for (int j = 0; j < M.cols(); j++) { if (j > 0) ofs << ' '; ofs << M(i, j); } ofs << std::endl; } return ofs.good(); } template<class Vector> bool SaveVector(const std::string& outName, const Vector& V) { std::ofstream ofs(outName.c_str(), std::ios::binary); ofs << std::setprecision(8); ofs << "# V D " << V.rows() << std::endl; for (int i = 0; i < V.rows(); i++) { ofs << V(i) << std::endl; } return ofs.good(); } } // svd /* approximate singular value decomposition A = U S t(V) with rank r t(M) : transpose of M t(U) U = I t(V) V = I R : compressed unit matrix Y = t(A) R Y = orthonormalize(Y) ; t(Y) Y = I B = A Y Z = orthonormalize(B) ; t(Z) Z = I C = t(Z) B C = U' S t(V') A \simeq A Y t(Y) = B t(Y) \simeq Z t(Z) B t(Y) = Z C t(Y) = Z U' S t(V') t(Y) = (Z U') S t(YV') = U S V */ template<class Matrix, class Vector> bool ComputeSVD(Matrix& U, Vector& S, Matrix& V, const Matrix& A, int rank) { const int row = A.rows(); const int col = A.cols(); const int r = std::min(std::min(col, row), rank); if (r <= 0) return false; #if 0 Matrix R(row, r); svd::InitRandomMatrix(R); // svd::InitUnitMatrix(R); Matrix Y = A.transpose() * R; #else Matrix Y; svd::CompressCol(Y, A.transpose(), r); #endif svd::OrthonormalizeMatrix(Y); const Matrix B = A * Y; Matrix Z = B; svd::OrthonormalizeMatrix(Z); const Matrix C = Z.transpose() * B; const Eigen::JacobiSVD<Matrix> svd(C, Eigen::ComputeThinU | Eigen::ComputeThinV); U = Z * svd.matrixU(); S = svd.singularValues(); V = Y * svd.matrixV(); return true; } } } // cybozu::nlp
add LoadVector
add LoadVector
C++
bsd-3-clause
herumi/cybozulib,herumi/cybozulib
505bbd9f39ed9800d39322899b11e8bc591bce0d
include/dll/dbn_traits.hpp
include/dll/dbn_traits.hpp
//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_DBN_TRAITS_HPP #define DLL_DBN_TRAITS_HPP #include "tmp.hpp" #include "decay_type.hpp" namespace dll { template<typename Desc> struct conv_dbn; /*! * \brief Type Traits to get information on DBN type */ template<typename DBN> struct dbn_traits { using dbn_t = DBN; HAS_STATIC_FIELD(Momentum, has_momentum_field) HAS_STATIC_FIELD(Concatenate, has_concatenate_field) HAS_STATIC_FIELD(Decay, has_decay_field) /*! * \brief Indicates if the DBN is convolutional */ static constexpr bool is_convolutional(){ return cpp::is_specialization_of<conv_dbn, dbn_t>::value; } template<typename D = DBN, cpp::enable_if_u<has_momentum_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr bool has_momentum(){ return dbn_t::desc::Momentum; } template<typename D = DBN, cpp::disable_if_u<has_momentum_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr bool has_momentum(){ return false; } template<typename D = DBN, cpp::enable_if_u<has_concatenate_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr bool concatenate(){ return dbn_t::desc::Concatenate; } template<typename D = DBN, cpp::disable_if_u<has_concatenate_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr bool concatenate(){ return false; } template<typename D = DBN, cpp::enable_if_u<has_decay_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr decay_type decay(){ return dbn_t::desc::Decay; } template<typename D = DBN, cpp::disable_if_u<has_decay_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr decay_type decay(){ return decay_type::NONE; } }; } //end of dll namespace #endif
//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_DBN_TRAITS_HPP #define DLL_DBN_TRAITS_HPP #include "tmp.hpp" #include "decay_type.hpp" namespace dll { template<typename Desc> struct conv_dbn; template<typename Desc> struct dyn_dbn; /*! * \brief Type Traits to get information on DBN type */ template<typename DBN> struct dbn_traits { using dbn_t = DBN; HAS_STATIC_FIELD(Momentum, has_momentum_field) HAS_STATIC_FIELD(Concatenate, has_concatenate_field) HAS_STATIC_FIELD(Decay, has_decay_field) /*! * \brief Indicates if the DBN is convolutional */ static constexpr bool is_convolutional(){ return cpp::is_specialization_of<conv_dbn, dbn_t>::value; } /*! * \brief Indicates if the DBN is dynamic */ static constexpr bool is_dynamic(){ return cpp::is_specialization_of<dyn_dbn, dbn_t>::value; } template<typename D = DBN, cpp::enable_if_u<has_momentum_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr bool has_momentum(){ return dbn_t::desc::Momentum; } template<typename D = DBN, cpp::disable_if_u<has_momentum_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr bool has_momentum(){ return false; } template<typename D = DBN, cpp::enable_if_u<has_concatenate_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr bool concatenate(){ return dbn_t::desc::Concatenate; } template<typename D = DBN, cpp::disable_if_u<has_concatenate_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr bool concatenate(){ return false; } template<typename D = DBN, cpp::enable_if_u<has_decay_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr decay_type decay(){ return dbn_t::desc::Decay; } template<typename D = DBN, cpp::disable_if_u<has_decay_field<typename D::desc>::value> = cpp::detail::dummy> static constexpr decay_type decay(){ return decay_type::NONE; } }; } //end of dll namespace #endif
Add is_dynamic traits
Add is_dynamic traits
C++
mit
wichtounet/dll,wichtounet/dll,wichtounet/dll
a4bf1c4372b060f7ae46f42c5e9828a624a71713
src/ngraph/op/constant.hpp
src/ngraph/op/constant.hpp
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include <cstring> #include <sstream> #include "ngraph/coordinate_diff.hpp" #include "ngraph/node.hpp" #include "ngraph/runtime/aligned_buffer.hpp" #include "ngraph/type/element_type.hpp" #include "ngraph/util.hpp" namespace ngraph { namespace op { /// \brief Class for constants. class Constant : public Node { public: NGRAPH_API static constexpr NodeTypeInfo type_info{"Constant", 0}; const NodeTypeInfo& get_type_info() const override { return type_info; } /// \brief Constructs a tensor constant. /// /// \param type The element type of the tensor constant. /// \param shape The shape of the tensor constant. /// \param values A vector of literals for initializing the tensor constant. The size /// of values must match the size of the shape. template <typename T> Constant(const element::Type& type, Shape shape, const std::vector<T>& values) : m_element_type(type) , m_shape(shape) , m_data(new runtime::AlignedBuffer(shape_size(m_shape) * m_element_type.size(), host_alignment())) { NODE_VALIDATION_CHECK( this, values.size() == 1 || values.size() == shape_size(m_shape), "Did not get the expected number of literals for a constant of shape ", m_shape, " (got ", values.size(), ", expected ", (shape_size(m_shape) == 1 ? "" : "1 or "), shape_size(m_shape), ")."); if (values.size() == 1) { write_values(std::vector<T>(shape_size(m_shape), values[0])); } else { write_values(values); } constructor_validate_and_infer_types(); } /// \brief Constructs a tensor constant /// This constructor is mainly to support deserialization of constants. /// /// \param type The element type of the tensor constant. /// \param shape The shape of the tensor constant. /// \param values A list of string values to use as the constant data. Constant(const element::Type& type, Shape shape, const std::vector<std::string>& values) : m_element_type(type) , m_shape(shape) , m_data(new runtime::AlignedBuffer(shape_size(m_shape) * m_element_type.size(), host_alignment())) { NODE_VALIDATION_CHECK( this, values.size() == shape_size(m_shape) || values.size() == 1, "Did not get the expected number of literals for a constant of shape ", m_shape, " (got ", values.size(), ", expected ", shape_size(m_shape), "."); if (values.size()) { if (type.is_integral()) { if (type.is_signed()) { std::vector<int64_t> dvalues = parse_string<int64_t>(values); if (values.size() == 1 && shape_size(m_shape) != 1) { dvalues = std::vector<int64_t>(shape_size(m_shape), dvalues[0]); } write_values(dvalues); } else { std::vector<uint64_t> dvalues = parse_string<uint64_t>(values); if (values.size() == 1 && shape_size(m_shape) != 1) { dvalues = std::vector<uint64_t>(shape_size(m_shape), dvalues[0]); } write_values(dvalues); } } else { std::vector<double> dvalues = parse_string<double>(values); if (values.size() == 1 && shape_size(m_shape) != 1) { dvalues = std::vector<double>(shape_size(m_shape), dvalues[0]); } write_values(dvalues); } } constructor_validate_and_infer_types(); } /// \brief Constructs a tensor constant with the same initialization value copied across // the tensor. This constructor is to support deserialization of constants. /// /// \param type The element type of the tensor constant. /// \param shape The shape of the tensor constant. /// \param data A void* to constant data. Constant(const element::Type& type, const Shape& shape, const void* data) : m_element_type(type) , m_shape(shape) , m_data(nullptr) { size_t size = shape_size(m_shape) * m_element_type.size(); m_data.reset(new runtime::AlignedBuffer(shape_size(m_shape) * m_element_type.size(), host_alignment())); std::memcpy(m_data->get_ptr(), data, size); constructor_validate_and_infer_types(); } virtual ~Constant() override; void validate_and_infer_types() override { infer_element_type(); set_output_type(0, m_element_type, m_shape); } /// \brief Returns the value of the constant node as a Shape object /// Can only be used on element::i64 nodes and interprets /// negative values as zeros. Shape get_shape_val() const; /// \brief Returns the value of the constant node as a Strides /// object /// Can only be used on element::i64 nodes and interprets /// negative values as zeros. Strides get_strides_val() const; /// \brief Returns the value of the constant node as a Coordinate /// object /// Can only be used on element::i64 nodes and interprets /// negative values as zeros. Coordinate get_coordinate_val() const; /// \brief Returns the value of the constant node as a /// CoordinateDiff object /// Can only be used on element::i64 nodes. CoordinateDiff get_coordinate_diff_val() const; /// \brief Returns the value of the constant node as an AxisVector /// object /// Can only be used on element::i64 nodes and interprets /// negative values as zeros. AxisVector get_axis_vector_val() const; /// \brief Returns the value of the constant node as an AxisSet /// object /// Can only be used on element::i64 nodes and interprets /// negative values as zeros. /// Repeated values are allowed. AxisSet get_axis_set_val() const; /// \brief Wrapper around constructing a shared_ptr of a Constant /// /// \param type The element type of the tensor constant. /// \param shape The shape of the tensor constant. /// \param values A vector of values to use as the constant data. template <typename T> static std::shared_ptr<op::Constant> create(const element::Type& type, Shape shape, const std::vector<T> values) { auto result = std::make_shared<op::Constant>(type, shape, values); result->validate_and_infer_types(); return result; } /// \brief Wrapper around constructing a shared_ptr of a Constant /// /// \param type The element type of the tensor constant. /// \param shape The shape of the tensor constant. /// \param values An initializer_list of values to use as the constant data. template <typename T> static std::shared_ptr<op::Constant> create(const element::Type& type, Shape shape, std::initializer_list<T> values) { auto result = std::make_shared<op::Constant>(type, shape, std::vector<T>{values}); result->validate_and_infer_types(); return result; } virtual std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const override; /// \return The initialization literals for the tensor constant. std::vector<std::string> get_value_strings() const; template <typename T> std::vector<T> get_vector() const { if (sizeof(T) > m_element_type.size() && shape_size(m_shape) > 0) { throw ngraph_error("Buffer over-read"); } std::vector<T> rc; const T* p = reinterpret_cast<const T*>(m_data->get_ptr()); for (size_t i = 0; i < shape_size(m_shape); i++) { rc.push_back(p[i]); } return rc; } const void* get_data_ptr() const { return (m_data ? m_data->get_ptr() : nullptr); } template <typename T> const T* get_data_ptr() const { return reinterpret_cast<const T*>(get_data_ptr()); } bool is_constant() const override { return true; } bool are_all_data_elements_bitwise_identical() const; std::string convert_value_to_string(size_t index) const; protected: void* get_data_ptr_nc() { return (m_data ? m_data->get_ptr() : nullptr); } Constant(const OutputVector& args) : Node(args) , m_shape({}) { } virtual void infer_element_type() {} template <typename T> void write_values(const std::vector<T>& values) { write_to_buffer( m_element_type, m_shape, values, get_data_ptr_nc(), shape_size(m_shape)); } template <typename T, typename U> void write_buffer(void* target, const std::vector<U>& source, size_t count) { T* p = reinterpret_cast<T*>(target); for (size_t i = 0; i < count; i++) { p[i] = static_cast<T>(source[i]); } } template <typename T> void write_to_buffer(const element::Type& target_type, const Shape& /* target_shape */, const std::vector<T>& source, void* target, size_t target_element_count) { if (source.size() != target_element_count) { throw std::runtime_error("Constant initializer does not match shape"); } #if defined(__GNUC__) && !(__GNUC__ == 4 && __GNUC_MINOR__ == 8) #pragma GCC diagnostic push #pragma GCC diagnostic error "-Wswitch" #pragma GCC diagnostic error "-Wswitch-enum" #endif switch (target_type) { case element::Type_t::boolean: write_buffer<char, T>(target, source, target_element_count); break; case element::Type_t::bf16: write_buffer<bfloat16, T>(target, source, target_element_count); break; case element::Type_t::f16: write_buffer<float16, T>(target, source, target_element_count); break; case element::Type_t::f32: write_buffer<float, T>(target, source, target_element_count); break; case element::Type_t::f64: write_buffer<double, T>(target, source, target_element_count); break; case element::Type_t::i8: write_buffer<int8_t, T>(target, source, target_element_count); break; case element::Type_t::i16: write_buffer<int16_t, T>(target, source, target_element_count); break; case element::Type_t::i32: write_buffer<int32_t, T>(target, source, target_element_count); break; case element::Type_t::i64: write_buffer<int64_t, T>(target, source, target_element_count); break; case element::Type_t::u8: write_buffer<uint8_t, T>(target, source, target_element_count); break; case element::Type_t::u16: write_buffer<uint16_t, T>(target, source, target_element_count); break; case element::Type_t::u32: write_buffer<uint32_t, T>(target, source, target_element_count); break; case element::Type_t::u64: write_buffer<uint64_t, T>(target, source, target_element_count); break; case element::Type_t::undefined: throw std::runtime_error("unsupported type"); case element::Type_t::dynamic: throw std::runtime_error("unsupported type"); } #if defined(__GNUC__) && !(__GNUC__ == 4 && __GNUC_MINOR__ == 8) #pragma GCC diagnostic pop #endif } static constexpr size_t host_alignment() { return 64; } element::Type m_element_type; Shape m_shape{}; std::unique_ptr<runtime::AlignedBuffer> m_data; Constant(const Constant&) = delete; Constant operator=(const Constant&) = delete; }; class ScalarConstantLikeBase : public Constant { public: NGRAPH_API static constexpr NodeTypeInfo type_info{"ScalarConstantLikeBase", 0}; const NodeTypeInfo& get_type_info() const override { return type_info; } std::shared_ptr<op::Constant> as_constant() const; protected: ScalarConstantLikeBase(const OutputVector& args) : Constant(args) { } }; /// \brief A scalar constant whose element type is the same as like. class ScalarConstantLike : public ScalarConstantLikeBase { public: /// \brief A scalar constant whose element type is the same as like. /// /// Once the element type is known, the dependency on like will be removed and /// this node will be replaced with an equivalent constant. /// /// \param like A tensor that will supply the element type. /// \param value The value of the scalar. template <typename T> ScalarConstantLike(const Output<Node>& like, T value) : ScalarConstantLikeBase({like}) , m_value(static_cast<double>(value)) { constructor_validate_and_infer_types(); } std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const override; protected: void infer_element_type() override; double m_value; }; } }
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include <cstring> #include <sstream> #include "ngraph/coordinate_diff.hpp" #include "ngraph/node.hpp" #include "ngraph/runtime/aligned_buffer.hpp" #include "ngraph/type/element_type.hpp" #include "ngraph/util.hpp" namespace ngraph { namespace op { /// \brief Class for constants. class Constant : public Op { public: NGRAPH_API static constexpr NodeTypeInfo type_info{"Constant", 0}; const NodeTypeInfo& get_type_info() const override { return type_info; } /// \brief Constructs a tensor constant. /// /// \param type The element type of the tensor constant. /// \param shape The shape of the tensor constant. /// \param values A vector of literals for initializing the tensor constant. The size /// of values must match the size of the shape. template <typename T> Constant(const element::Type& type, Shape shape, const std::vector<T>& values) : m_element_type(type) , m_shape(shape) , m_data(new runtime::AlignedBuffer(shape_size(m_shape) * m_element_type.size(), host_alignment())) { NODE_VALIDATION_CHECK( this, values.size() == 1 || values.size() == shape_size(m_shape), "Did not get the expected number of literals for a constant of shape ", m_shape, " (got ", values.size(), ", expected ", (shape_size(m_shape) == 1 ? "" : "1 or "), shape_size(m_shape), ")."); if (values.size() == 1) { write_values(std::vector<T>(shape_size(m_shape), values[0])); } else { write_values(values); } constructor_validate_and_infer_types(); } /// \brief Constructs a tensor constant /// This constructor is mainly to support deserialization of constants. /// /// \param type The element type of the tensor constant. /// \param shape The shape of the tensor constant. /// \param values A list of string values to use as the constant data. Constant(const element::Type& type, Shape shape, const std::vector<std::string>& values) : m_element_type(type) , m_shape(shape) , m_data(new runtime::AlignedBuffer(shape_size(m_shape) * m_element_type.size(), host_alignment())) { NODE_VALIDATION_CHECK( this, values.size() == shape_size(m_shape) || values.size() == 1, "Did not get the expected number of literals for a constant of shape ", m_shape, " (got ", values.size(), ", expected ", shape_size(m_shape), "."); if (values.size()) { if (type.is_integral()) { if (type.is_signed()) { std::vector<int64_t> dvalues = parse_string<int64_t>(values); if (values.size() == 1 && shape_size(m_shape) != 1) { dvalues = std::vector<int64_t>(shape_size(m_shape), dvalues[0]); } write_values(dvalues); } else { std::vector<uint64_t> dvalues = parse_string<uint64_t>(values); if (values.size() == 1 && shape_size(m_shape) != 1) { dvalues = std::vector<uint64_t>(shape_size(m_shape), dvalues[0]); } write_values(dvalues); } } else { std::vector<double> dvalues = parse_string<double>(values); if (values.size() == 1 && shape_size(m_shape) != 1) { dvalues = std::vector<double>(shape_size(m_shape), dvalues[0]); } write_values(dvalues); } } constructor_validate_and_infer_types(); } /// \brief Constructs a tensor constant with the same initialization value copied across // the tensor. This constructor is to support deserialization of constants. /// /// \param type The element type of the tensor constant. /// \param shape The shape of the tensor constant. /// \param data A void* to constant data. Constant(const element::Type& type, const Shape& shape, const void* data) : m_element_type(type) , m_shape(shape) , m_data(nullptr) { size_t size = shape_size(m_shape) * m_element_type.size(); m_data.reset(new runtime::AlignedBuffer(shape_size(m_shape) * m_element_type.size(), host_alignment())); std::memcpy(m_data->get_ptr(), data, size); constructor_validate_and_infer_types(); } virtual ~Constant() override; void validate_and_infer_types() override { infer_element_type(); set_output_type(0, m_element_type, m_shape); } /// \brief Returns the value of the constant node as a Shape object /// Can only be used on element::i64 nodes and interprets /// negative values as zeros. Shape get_shape_val() const; /// \brief Returns the value of the constant node as a Strides /// object /// Can only be used on element::i64 nodes and interprets /// negative values as zeros. Strides get_strides_val() const; /// \brief Returns the value of the constant node as a Coordinate /// object /// Can only be used on element::i64 nodes and interprets /// negative values as zeros. Coordinate get_coordinate_val() const; /// \brief Returns the value of the constant node as a /// CoordinateDiff object /// Can only be used on element::i64 nodes. CoordinateDiff get_coordinate_diff_val() const; /// \brief Returns the value of the constant node as an AxisVector /// object /// Can only be used on element::i64 nodes and interprets /// negative values as zeros. AxisVector get_axis_vector_val() const; /// \brief Returns the value of the constant node as an AxisSet /// object /// Can only be used on element::i64 nodes and interprets /// negative values as zeros. /// Repeated values are allowed. AxisSet get_axis_set_val() const; /// \brief Wrapper around constructing a shared_ptr of a Constant /// /// \param type The element type of the tensor constant. /// \param shape The shape of the tensor constant. /// \param values A vector of values to use as the constant data. template <typename T> static std::shared_ptr<op::Constant> create(const element::Type& type, Shape shape, const std::vector<T> values) { auto result = std::make_shared<op::Constant>(type, shape, values); result->validate_and_infer_types(); return result; } /// \brief Wrapper around constructing a shared_ptr of a Constant /// /// \param type The element type of the tensor constant. /// \param shape The shape of the tensor constant. /// \param values An initializer_list of values to use as the constant data. template <typename T> static std::shared_ptr<op::Constant> create(const element::Type& type, Shape shape, std::initializer_list<T> values) { auto result = std::make_shared<op::Constant>(type, shape, std::vector<T>{values}); result->validate_and_infer_types(); return result; } virtual std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const override; /// \return The initialization literals for the tensor constant. std::vector<std::string> get_value_strings() const; template <typename T> std::vector<T> get_vector() const { if (sizeof(T) > m_element_type.size() && shape_size(m_shape) > 0) { throw ngraph_error("Buffer over-read"); } std::vector<T> rc; const T* p = reinterpret_cast<const T*>(m_data->get_ptr()); for (size_t i = 0; i < shape_size(m_shape); i++) { rc.push_back(p[i]); } return rc; } const void* get_data_ptr() const { return (m_data ? m_data->get_ptr() : nullptr); } template <typename T> const T* get_data_ptr() const { return reinterpret_cast<const T*>(get_data_ptr()); } bool is_constant() const override { return true; } bool are_all_data_elements_bitwise_identical() const; std::string convert_value_to_string(size_t index) const; protected: void* get_data_ptr_nc() { return (m_data ? m_data->get_ptr() : nullptr); } Constant(const OutputVector& args) : Op(args) , m_shape({}) { } virtual void infer_element_type() {} template <typename T> void write_values(const std::vector<T>& values) { write_to_buffer( m_element_type, m_shape, values, get_data_ptr_nc(), shape_size(m_shape)); } template <typename T, typename U> void write_buffer(void* target, const std::vector<U>& source, size_t count) { T* p = reinterpret_cast<T*>(target); for (size_t i = 0; i < count; i++) { p[i] = static_cast<T>(source[i]); } } template <typename T> void write_to_buffer(const element::Type& target_type, const Shape& /* target_shape */, const std::vector<T>& source, void* target, size_t target_element_count) { if (source.size() != target_element_count) { throw std::runtime_error("Constant initializer does not match shape"); } #if defined(__GNUC__) && !(__GNUC__ == 4 && __GNUC_MINOR__ == 8) #pragma GCC diagnostic push #pragma GCC diagnostic error "-Wswitch" #pragma GCC diagnostic error "-Wswitch-enum" #endif switch (target_type) { case element::Type_t::boolean: write_buffer<char, T>(target, source, target_element_count); break; case element::Type_t::bf16: write_buffer<bfloat16, T>(target, source, target_element_count); break; case element::Type_t::f16: write_buffer<float16, T>(target, source, target_element_count); break; case element::Type_t::f32: write_buffer<float, T>(target, source, target_element_count); break; case element::Type_t::f64: write_buffer<double, T>(target, source, target_element_count); break; case element::Type_t::i8: write_buffer<int8_t, T>(target, source, target_element_count); break; case element::Type_t::i16: write_buffer<int16_t, T>(target, source, target_element_count); break; case element::Type_t::i32: write_buffer<int32_t, T>(target, source, target_element_count); break; case element::Type_t::i64: write_buffer<int64_t, T>(target, source, target_element_count); break; case element::Type_t::u8: write_buffer<uint8_t, T>(target, source, target_element_count); break; case element::Type_t::u16: write_buffer<uint16_t, T>(target, source, target_element_count); break; case element::Type_t::u32: write_buffer<uint32_t, T>(target, source, target_element_count); break; case element::Type_t::u64: write_buffer<uint64_t, T>(target, source, target_element_count); break; case element::Type_t::undefined: throw std::runtime_error("unsupported type"); case element::Type_t::dynamic: throw std::runtime_error("unsupported type"); } #if defined(__GNUC__) && !(__GNUC__ == 4 && __GNUC_MINOR__ == 8) #pragma GCC diagnostic pop #endif } static constexpr size_t host_alignment() { return 64; } element::Type m_element_type; Shape m_shape{}; std::unique_ptr<runtime::AlignedBuffer> m_data; Constant(const Constant&) = delete; Constant operator=(const Constant&) = delete; }; class ScalarConstantLikeBase : public Constant { public: NGRAPH_API static constexpr NodeTypeInfo type_info{"ScalarConstantLikeBase", 0}; const NodeTypeInfo& get_type_info() const override { return type_info; } std::shared_ptr<op::Constant> as_constant() const; protected: ScalarConstantLikeBase(const OutputVector& args) : Constant(args) { } }; /// \brief A scalar constant whose element type is the same as like. class ScalarConstantLike : public ScalarConstantLikeBase { public: /// \brief A scalar constant whose element type is the same as like. /// /// Once the element type is known, the dependency on like will be removed and /// this node will be replaced with an equivalent constant. /// /// \param like A tensor that will supply the element type. /// \param value The value of the scalar. template <typename T> ScalarConstantLike(const Output<Node>& like, T value) : ScalarConstantLikeBase({like}) , m_value(static_cast<double>(value)) { constructor_validate_and_infer_types(); } std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const override; protected: void infer_element_type() override; double m_value; }; } }
Make Constant an op (#3752)
Make Constant an op (#3752)
C++
apache-2.0
NervanaSystems/ngraph,NervanaSystems/ngraph,NervanaSystems/ngraph,NervanaSystems/ngraph
e54f7fc092b8c78c8e6720541df665ce2f3ef5b0
src/node/zp_ping_thread.cc
src/node/zp_ping_thread.cc
#include "zp_ping_thread.h" #include <glog/logging.h> #include "zp_data_server.h" #include "zp_meta.pb.h" #include "zp_const.h" extern ZPDataServer* zp_data_server; ZPPingThread::~ZPPingThread() { should_exit_ = true; pthread_join(thread_id(), NULL); delete cli_; LOG(INFO) << " Ping thread " << pthread_self() << " exit!!!"; } pink::Status ZPPingThread::Send() { ZPMeta::MetaCmd request; int64_t meta_epoch = zp_data_server->meta_epoch(); ZPMeta::MetaCmd_Ping* ping = request.mutable_ping(); ping->set_version(meta_epoch); ZPMeta::Node* node = ping->mutable_node(); node->set_ip(zp_data_server->local_ip()); node->set_port(zp_data_server->local_port()); request.set_type(ZPMeta::Type::PING); std::unordered_map<std::string, std::vector<PartitionBinlogOffset>> all_offset; zp_data_server->DumpTableBinlogOffsets(all_offset); for (auto& item : all_offset) { for(auto& p : item.second) { ZPMeta::SyncOffset *offset = ping->add_offset(); offset->set_table_name(item.first); offset->set_partition(p.partition_id); offset->set_filenum(p.filenum); offset->set_filenum(p.offset); } } DLOG(INFO) << "Ping Meta (" << zp_data_server->meta_ip() << ":" << zp_data_server->meta_port() + kMetaPortShiftCmd << ") with Epoch: " << meta_epoch; return cli_->Send(&request); } pink::Status ZPPingThread::RecvProc() { pink::Status result; ZPMeta::MetaCmdResponse response; result = cli_->Recv(&response); DLOG(INFO) << "Ping Recv from Meta (" << zp_data_server->meta_ip() << ":" << zp_data_server->meta_port() + kMetaPortShiftCmd << ")"; if (!result.ok()) { return result; } if (response.code() != ZPMeta::StatusCode::OK) { return pink::Status::Corruption("Receive reponse with error code"); } // StatusCode OK if (response.type() == ZPMeta::Type::PING) { zp_data_server->TryUpdateEpoch(response.ping().version()); return pink::Status::OK(); } return pink::Status::Corruption("Receive reponse whose type is not ping"); } void* ZPPingThread::ThreadMain() { struct timeval now, last_interaction; pink::Status s; while (!should_exit_) { zp_data_server->PickMeta(); std::string meta_ip = zp_data_server->meta_ip(); int meta_port = zp_data_server->meta_port() + kMetaPortShiftCmd; // Connect with heartbeat port DLOG(INFO) << "Ping will connect ("<< meta_ip << ":" << meta_port << ")"; s = cli_->Connect(meta_ip, meta_port); if (s.ok()) { DLOG(INFO) << "Ping connect ("<< meta_ip << ":" << meta_port << ") ok!"; gettimeofday(&now, NULL); last_interaction = now; cli_->set_send_timeout(1000); cli_->set_recv_timeout(1000); // Send && Recv while (!should_exit_) { gettimeofday(&now, NULL); if (now.tv_sec - last_interaction.tv_sec > kNodeMetaTimeoutN) { LOG(WARNING) << "Ping meta ("<< meta_ip << ":" << meta_port << ") timeout, reconnect!"; break; } sleep(kPingInterval); // Send ping to meta s = Send(); if (!s.ok()) { LOG(WARNING) << "Ping send to ("<< meta_ip << ":" << meta_port << ") failed! caz: " << s.ToString(); continue; } DLOG(INFO) << "Ping send to ("<< meta_ip << ":" << meta_port << ") success!"; // Recv from meta s = RecvProc(); if (!s.ok()) { LOG(WARNING) << "Ping recv from ("<< meta_ip << ":" << meta_port << ") failed! caz: " << s.ToString(); continue; } gettimeofday(&last_interaction, NULL); DLOG(INFO) << "Ping recv from ("<< meta_ip << ":" << meta_port << ") success!"; } cli_->Close(); } else { LOG(WARNING) << "Ping connect ("<< meta_ip << ":" << meta_port << ") failed!"; } sleep(kPingInterval); } return NULL; }
#include "zp_ping_thread.h" #include <glog/logging.h> #include "zp_data_server.h" #include "zp_meta.pb.h" #include "zp_const.h" extern ZPDataServer* zp_data_server; ZPPingThread::~ZPPingThread() { should_exit_ = true; pthread_join(thread_id(), NULL); delete cli_; LOG(INFO) << " Ping thread " << pthread_self() << " exit!!!"; } pink::Status ZPPingThread::Send() { ZPMeta::MetaCmd request; int64_t meta_epoch = zp_data_server->meta_epoch(); ZPMeta::MetaCmd_Ping* ping = request.mutable_ping(); ping->set_version(meta_epoch); ZPMeta::Node* node = ping->mutable_node(); node->set_ip(zp_data_server->local_ip()); node->set_port(zp_data_server->local_port()); request.set_type(ZPMeta::Type::PING); std::unordered_map<std::string, std::vector<PartitionBinlogOffset>> all_offset; zp_data_server->DumpTableBinlogOffsets(all_offset); for (auto& item : all_offset) { for(auto& p : item.second) { ZPMeta::SyncOffset *offset = ping->add_offset(); offset->set_table_name(item.first); offset->set_partition(p.partition_id); offset->set_filenum(p.filenum); offset->set_offset(p.offset); } } DLOG(INFO) << "Ping Meta (" << zp_data_server->meta_ip() << ":" << zp_data_server->meta_port() + kMetaPortShiftCmd << ") with Epoch: " << meta_epoch; return cli_->Send(&request); } pink::Status ZPPingThread::RecvProc() { pink::Status result; ZPMeta::MetaCmdResponse response; result = cli_->Recv(&response); DLOG(INFO) << "Ping Recv from Meta (" << zp_data_server->meta_ip() << ":" << zp_data_server->meta_port() + kMetaPortShiftCmd << ")"; if (!result.ok()) { return result; } if (response.code() != ZPMeta::StatusCode::OK) { return pink::Status::Corruption("Receive reponse with error code"); } // StatusCode OK if (response.type() == ZPMeta::Type::PING) { zp_data_server->TryUpdateEpoch(response.ping().version()); return pink::Status::OK(); } return pink::Status::Corruption("Receive reponse whose type is not ping"); } void* ZPPingThread::ThreadMain() { struct timeval now, last_interaction; pink::Status s; while (!should_exit_) { zp_data_server->PickMeta(); std::string meta_ip = zp_data_server->meta_ip(); int meta_port = zp_data_server->meta_port() + kMetaPortShiftCmd; // Connect with heartbeat port DLOG(INFO) << "Ping will connect ("<< meta_ip << ":" << meta_port << ")"; s = cli_->Connect(meta_ip, meta_port); if (s.ok()) { DLOG(INFO) << "Ping connect ("<< meta_ip << ":" << meta_port << ") ok!"; gettimeofday(&now, NULL); last_interaction = now; cli_->set_send_timeout(1000); cli_->set_recv_timeout(1000); // Send && Recv while (!should_exit_) { gettimeofday(&now, NULL); if (now.tv_sec - last_interaction.tv_sec > kNodeMetaTimeoutN) { LOG(WARNING) << "Ping meta ("<< meta_ip << ":" << meta_port << ") timeout, reconnect!"; break; } sleep(kPingInterval); // Send ping to meta s = Send(); if (!s.ok()) { LOG(WARNING) << "Ping send to ("<< meta_ip << ":" << meta_port << ") failed! caz: " << s.ToString(); continue; } DLOG(INFO) << "Ping send to ("<< meta_ip << ":" << meta_port << ") success!"; // Recv from meta s = RecvProc(); if (!s.ok()) { LOG(WARNING) << "Ping recv from ("<< meta_ip << ":" << meta_port << ") failed! caz: " << s.ToString(); continue; } gettimeofday(&last_interaction, NULL); DLOG(INFO) << "Ping recv from ("<< meta_ip << ":" << meta_port << ") success!"; } cli_->Close(); } else { LOG(WARNING) << "Ping connect ("<< meta_ip << ":" << meta_port << ") failed!"; } sleep(kPingInterval); } return NULL; }
send offset in ping request
send offset in ping request
C++
apache-2.0
baotiao/zeppelin,baotiao/zeppelin,baotiao/zeppelin,baotiao/zeppelin,baotiao/zeppelin,baotiao/zeppelin
a90fd02edfb4c23f4d6b4aa5d4f634739d990935
plugins/multimedia/symbian/mediaplayer/s60mediaplayersession.cpp
plugins/multimedia/symbian/mediaplayer/s60mediaplayersession.cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used 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. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60mediaplayersession.h" #include <QtCore/qdebug.h> #include <QtCore/qdir.h> #include <QtCore/qvariant.h> #include <QtCore/qtimer.h> #include <QtCore/private/qcore_symbian_p.h> #include <mmf/common/mmferrors.h> #include <qmediatimerange.h> S60MediaPlayerSession::S60MediaPlayerSession(QObject *parent) : QObject(parent) , m_playbackRate(0) , m_muted(false) , m_volume(0) , m_state(QMediaPlayer::StoppedState) , m_mediaStatus(QMediaPlayer::NoMedia) , m_timer(new QTimer(this)) , m_error(KErrNone) , m_localMediaFile(true) , m_play_requested(false) { connect(m_timer, SIGNAL(timeout()), this, SLOT(tick())); } S60MediaPlayerSession::~S60MediaPlayerSession() { } int S60MediaPlayerSession::volume() const { return m_volume; } void S60MediaPlayerSession::setVolume(int volume) { if (m_volume == volume) return; m_volume = volume; if (mediaStatus() == QMediaPlayer::LoadedMedia && !isMuted()) { TRAPD(err, doSetVolumeL(m_volume)); setError(err); } } bool S60MediaPlayerSession::isMuted() const { return m_muted; } bool S60MediaPlayerSession::isSeekable() const { if (m_metaDataMap.isEmpty()) return true; return m_metaDataMap.value("seekable").toBool(); } void S60MediaPlayerSession::setMediaStatus(QMediaPlayer::MediaStatus status) { if (m_mediaStatus == status) return; m_mediaStatus = status; emit mediaStatusChanged(status); if (m_play_requested) play(); } void S60MediaPlayerSession::setState(QMediaPlayer::State state) { if (m_state == state) return; m_state = state; emit stateChanged(state); } QMediaPlayer::State S60MediaPlayerSession::state() const { return m_state; } QMediaPlayer::MediaStatus S60MediaPlayerSession::mediaStatus() const { return m_mediaStatus; } void S60MediaPlayerSession::load(const QUrl &url) { m_localMediaFile = true; doStop(); setMediaStatus(QMediaPlayer::LoadingMedia); TRAPD(err, doLoadL(qt_QString2TPtrC(QDir::toNativeSeparators(url.toLocalFile())))); setError(err); } void S60MediaPlayerSession::loadUrl(const QUrl &url) { m_localMediaFile = false; doStop(); setMediaStatus(QMediaPlayer::LoadingMedia); TRAPD(err, doLoadUrlL(qt_QString2TPtrC(url.toString()))); setError(err); } void S60MediaPlayerSession::play() { if (state() == QMediaPlayer::PlayingState) return; if (mediaStatus() != QMediaPlayer::LoadedMedia) { m_play_requested = true; return; } m_play_requested = false; setState(QMediaPlayer::PlayingState); m_timer->start(1000); doPlay(); } void S60MediaPlayerSession::pause() { m_timer->stop(); setState(QMediaPlayer::PausedState); TRAPD(err, doPauseL()); setError(err); } void S60MediaPlayerSession::stop() { setState(QMediaPlayer::StoppedState); m_timer->stop(); doStop(); } void S60MediaPlayerSession::setVideoRenderer(QObject *renderer) { Q_UNUSED(renderer); } int S60MediaPlayerSession::mediaLoadingProgress() { int progress = 0; TRAPD(err, progress = doGetMediaLoadingProgressL()); setError(err); return progress; } bool S60MediaPlayerSession::isMetadataAvailable() const { return !m_metaDataMap.isEmpty(); } QVariant S60MediaPlayerSession::metaData(const QString &key) const { return m_metaDataMap.value(key); } QMap<QString, QVariant> S60MediaPlayerSession::availableMetaData() const { return m_metaDataMap; } qreal S60MediaPlayerSession::playbackRate() const { return m_playbackRate; } void S60MediaPlayerSession::setMuted(bool muted) { if (m_muted == muted) return; m_muted = muted; emit mutingChanged(m_muted); if (isMuted()) { TRAPD(err, doSetVolumeL(0)); setError(err); } else { setVolume(volume()); } } void S60MediaPlayerSession::setPlaybackRate(qreal rate) { if (m_playbackRate == rate) return; m_playbackRate = rate; emit playbackRateChanged(m_playbackRate); //None of symbian players supports this. } qint64 S60MediaPlayerSession::duration() const { qint64 pos = 0; //Cannot seterror since const, error ignored TRAP_IGNORE(pos = doGetDurationL()); return pos; } qint64 S60MediaPlayerSession::position() const { qint64 pos = 0; //Cannot seterror since const, error ignored TRAP_IGNORE(pos = doGetPositionL()); return pos; } void S60MediaPlayerSession::setPosition(qint64 pos) { if (position() == pos) return; if (state() == QMediaPlayer::PlayingState) pause(); TRAPD(err, doSetPositionL(pos * 1000)); setError(err); if (state() == QMediaPlayer::PausedState) play(); emit positionChanged(position()); } void S60MediaPlayerSession::initComplete() { if (m_error == KErrNone) { setMediaStatus(QMediaPlayer::LoadedMedia); TRAPD(err, updateMetaDataEntriesL()); setError(err); setVolume(volume()); emit durationChanged(duration()); } else { setMediaStatus(QMediaPlayer::NoMedia); } } void S60MediaPlayerSession::playComplete() { setMediaStatus(QMediaPlayer::EndOfMedia); setState(QMediaPlayer::StoppedState); emit positionChanged(0); } QMap<QString, QVariant>& S60MediaPlayerSession::metaDataEntries() { return m_metaDataMap; } QMediaPlayer::Error S60MediaPlayerSession::fromSymbianErrorToMultimediaError(int error) { switch(error) { case KErrNoMemory: case KErrNotFound: case KErrBadHandle: case KErrMMAudioDevice: case KErrMMVideoDevice: return QMediaPlayer::ResourceError; case KErrMMDecoder: case KErrNotSupported: case KErrCorrupt: return QMediaPlayer::FormatError; case KErrMMNotEnoughBandwidth: case KErrMMSocketServiceNotFound: case KErrMMNetworkRead: case KErrMMNetworkWrite: case KErrMMServerSocket: case KErrMMServerNotSupported: case KErrMMUDPReceive: case KErrMMInvalidProtocol: case KErrMMInvalidURL: case KErrMMMulticast: case KErrMMProxyServer: case KErrMMProxyServerNotSupported: case KErrMMProxyServerConnect: return QMediaPlayer::NetworkError; case KErrNotReady: case KErrInUse: case KErrAccessDenied: case KErrLocked: case KErrMMDRMNotAuthorized: case KErrPermissionDenied: return QMediaPlayer::AccessDeniedError; case KErrMMPartialPlayback: default: return QMediaPlayer::NoError; } } void S60MediaPlayerSession::setError(int error, const QString &errorString) { if (error == KErrNone || error == KErrMMPartialPlayback) return; m_error = error; QMediaPlayer::Error mediaError = fromSymbianErrorToMultimediaError(m_error); // TODO: fix to user friendly string at some point // These error string are only dev usable QString symbianError = QString(errorString); symbianError.append("From Symbian:"); symbianError.append(QString(m_error)); emit this->error(mediaError, symbianError); switch(mediaError){ case QMediaPlayer::FormatError: setMediaStatus(QMediaPlayer::InvalidMedia); break; case QMediaPlayer::ResourceError: case QMediaPlayer::NetworkError: case QMediaPlayer::AccessDeniedError: case QMediaPlayer::ServiceMissingError: setMediaStatus(QMediaPlayer::NoMedia); break; default: break; } } void S60MediaPlayerSession::tick() { emit positionChanged(position()); if (mediaFileLocal() && mediaLoadingProgress() != 100) emit bufferStatusChanged(mediaLoadingProgress()); } bool S60MediaPlayerSession::mediaFileLocal() const { return m_localMediaFile; } void S60MediaPlayerSession::setMediaFileLocal(bool localMediaFile) { if (m_localMediaFile == localMediaFile) return; m_localMediaFile = localMediaFile; }
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used 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. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60mediaplayersession.h" #include <QtCore/qdebug.h> #include <QtCore/qdir.h> #include <QtCore/qvariant.h> #include <QtCore/qtimer.h> #include <QtCore/private/qcore_symbian_p.h> #include <mmf/common/mmferrors.h> #include <qmediatimerange.h> S60MediaPlayerSession::S60MediaPlayerSession(QObject *parent) : QObject(parent) , m_playbackRate(0) , m_muted(false) , m_volume(0) , m_state(QMediaPlayer::StoppedState) , m_mediaStatus(QMediaPlayer::NoMedia) , m_timer(new QTimer(this)) , m_error(KErrNone) , m_localMediaFile(true) , m_play_requested(false) { connect(m_timer, SIGNAL(timeout()), this, SLOT(tick())); } S60MediaPlayerSession::~S60MediaPlayerSession() { } int S60MediaPlayerSession::volume() const { return m_volume; } void S60MediaPlayerSession::setVolume(int volume) { if (m_volume == volume) return; m_volume = volume; if (mediaStatus() == QMediaPlayer::LoadedMedia && !isMuted()) { TRAPD(err, doSetVolumeL(m_volume)); setError(err); } } bool S60MediaPlayerSession::isMuted() const { return m_muted; } bool S60MediaPlayerSession::isSeekable() const { if (m_metaDataMap.isEmpty()) return true; return m_metaDataMap.value("seekable").toBool(); } void S60MediaPlayerSession::setMediaStatus(QMediaPlayer::MediaStatus status) { if (m_mediaStatus == status) return; m_mediaStatus = status; emit mediaStatusChanged(status); if (m_play_requested) play(); } void S60MediaPlayerSession::setState(QMediaPlayer::State state) { if (m_state == state) return; m_state = state; emit stateChanged(state); } QMediaPlayer::State S60MediaPlayerSession::state() const { return m_state; } QMediaPlayer::MediaStatus S60MediaPlayerSession::mediaStatus() const { return m_mediaStatus; } void S60MediaPlayerSession::load(const QUrl &url) { m_localMediaFile = true; doStop(); setMediaStatus(QMediaPlayer::LoadingMedia); TRAPD(err, doLoadL(qt_QString2TPtrC(QDir::toNativeSeparators(url.toLocalFile())))); setError(err); } void S60MediaPlayerSession::loadUrl(const QUrl &url) { m_localMediaFile = false; doStop(); setMediaStatus(QMediaPlayer::LoadingMedia); TRAPD(err, doLoadUrlL(qt_QString2TPtrC(url.toString()))); setError(err); } void S60MediaPlayerSession::play() { if (state() == QMediaPlayer::PlayingState) return; if (mediaStatus() != QMediaPlayer::LoadedMedia) { m_play_requested = true; return; } m_play_requested = false; setState(QMediaPlayer::PlayingState); m_timer->start(1000); doPlay(); } void S60MediaPlayerSession::pause() { m_timer->stop(); setState(QMediaPlayer::PausedState); TRAPD(err, doPauseL()); setError(err); } void S60MediaPlayerSession::stop() { setState(QMediaPlayer::StoppedState); m_timer->stop(); doStop(); } void S60MediaPlayerSession::setVideoRenderer(QObject *renderer) { Q_UNUSED(renderer); } int S60MediaPlayerSession::mediaLoadingProgress() { int progress = 0; TRAPD(err, progress = doGetMediaLoadingProgressL()); setError(err); return progress; } bool S60MediaPlayerSession::isMetadataAvailable() const { return !m_metaDataMap.isEmpty(); } QVariant S60MediaPlayerSession::metaData(const QString &key) const { return m_metaDataMap.value(key); } QMap<QString, QVariant> S60MediaPlayerSession::availableMetaData() const { return m_metaDataMap; } qreal S60MediaPlayerSession::playbackRate() const { return m_playbackRate; } void S60MediaPlayerSession::setMuted(bool muted) { if (m_muted == muted) return; m_muted = muted; emit mutingChanged(m_muted); if (isMuted()) { TRAPD(err, doSetVolumeL(0)); setError(err); } else { setVolume(volume()); } } void S60MediaPlayerSession::setPlaybackRate(qreal rate) { if (m_playbackRate == rate) return; m_playbackRate = rate; emit playbackRateChanged(m_playbackRate); //None of symbian players supports this. } qint64 S60MediaPlayerSession::duration() const { qint64 pos = 0; //Cannot seterror since const, error ignored TRAP_IGNORE(pos = doGetDurationL()); return pos; } qint64 S60MediaPlayerSession::position() const { qint64 pos = 0; //Cannot seterror since const, error ignored TRAP_IGNORE(pos = doGetPositionL()); return pos; } void S60MediaPlayerSession::setPosition(qint64 pos) { if (position() == pos) return; if (state() == QMediaPlayer::PlayingState) pause(); TRAPD(err, doSetPositionL(pos * 1000)); setError(err); if (state() == QMediaPlayer::PausedState) play(); emit positionChanged(position()); } void S60MediaPlayerSession::initComplete() { if (m_error == KErrNone) { setMediaStatus(QMediaPlayer::LoadedMedia); TRAPD(err, updateMetaDataEntriesL()); setError(err); setVolume(volume()); emit durationChanged(duration()); } else { setMediaStatus(QMediaPlayer::NoMedia); } } void S60MediaPlayerSession::playComplete() { setMediaStatus(QMediaPlayer::EndOfMedia); setState(QMediaPlayer::StoppedState); emit positionChanged(0); } QMap<QString, QVariant>& S60MediaPlayerSession::metaDataEntries() { return m_metaDataMap; } QMediaPlayer::Error S60MediaPlayerSession::fromSymbianErrorToMultimediaError(int error) { switch(error) { case KErrNoMemory: case KErrNotFound: case KErrBadHandle: case KErrMMAudioDevice: case KErrMMVideoDevice: return QMediaPlayer::ResourceError; case KErrMMDecoder: case KErrNotSupported: case KErrCorrupt: return QMediaPlayer::FormatError; case KErrMMNotEnoughBandwidth: case KErrMMSocketServiceNotFound: case KErrMMNetworkRead: case KErrMMNetworkWrite: case KErrMMServerSocket: case KErrMMServerNotSupported: case KErrMMUDPReceive: case KErrMMInvalidProtocol: case KErrMMInvalidURL: case KErrMMMulticast: case KErrMMProxyServer: case KErrMMProxyServerNotSupported: case KErrMMProxyServerConnect: return QMediaPlayer::NetworkError; case KErrNotReady: case KErrInUse: case KErrAccessDenied: case KErrLocked: case KErrMMDRMNotAuthorized: case KErrPermissionDenied: return QMediaPlayer::AccessDeniedError; case KErrMMPartialPlayback: default: return QMediaPlayer::NoError; } } void S60MediaPlayerSession::setError(int error, const QString &errorString) { if (error == KErrNone || error == KErrMMPartialPlayback) return; m_error = error; QMediaPlayer::Error mediaError = fromSymbianErrorToMultimediaError(m_error); // TODO: fix to user friendly string at some point // These error string are only dev usable QString symbianError = QString(errorString); symbianError.append("Symbian:"); symbianError.append(QString::number(m_error)); emit this->error(mediaError, symbianError); switch(mediaError){ case QMediaPlayer::FormatError: setMediaStatus(QMediaPlayer::InvalidMedia); break; case QMediaPlayer::ResourceError: case QMediaPlayer::NetworkError: case QMediaPlayer::AccessDeniedError: case QMediaPlayer::ServiceMissingError: setMediaStatus(QMediaPlayer::NoMedia); break; default: break; } } void S60MediaPlayerSession::tick() { emit positionChanged(position()); if (mediaFileLocal() && mediaLoadingProgress() != 100) emit bufferStatusChanged(mediaLoadingProgress()); } bool S60MediaPlayerSession::mediaFileLocal() const { return m_localMediaFile; } void S60MediaPlayerSession::setMediaFileLocal(bool localMediaFile) { if (m_localMediaFile == localMediaFile) return; m_localMediaFile = localMediaFile; }
Fix MediaSession error string Symbian error number is now correctly converted to QString.
Fix MediaSession error string Symbian error number is now correctly converted to QString.
C++
lgpl-2.1
tmcguire/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,enthought/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,kaltsi/qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,qtproject/qt-mobility,tmcguire/qt-mobility,KDE/android-qt-mobility
a85253ff2255e32621b6836b53690c7ad989062d
j1a/verilator/sim_main.cpp
j1a/verilator/sim_main.cpp
#include <stdio.h> #include "Vj1a.h" #include "verilated_vcd_c.h" int main(int argc, char **argv) { Verilated::commandArgs(argc, argv); Vj1a* top = new Vj1a; // Verilated::traceEverOn(true); // VerilatedVcdC* tfp = new VerilatedVcdC; // top->trace (tfp, 99); // tfp->open ("simx.vcd"); if (argc != 2) { fprintf(stderr, "usage: sim <hex-file>\n"); exit(1); } FILE *hex = fopen(argv[1], "r"); int i; for (i = 0; i < 2048; i++) { unsigned int v; if (fscanf(hex, "%x\n", &v) != 1) { fprintf(stderr, "invalid hex value at line %d\n", i + 1); exit(1); } top->v__DOT__ram_prog[i] = v; } for (i = 0; i < 2048; i++) { unsigned int v; if (fscanf(hex, "%x\n", &v) != 1) { fprintf(stderr, "invalid hex value at line %d\n", i + 1); exit(1); } top->v__DOT__ram_data[i] = v; } // FILE *input = fopen(argv[1], "r"); // if (!input) { // perror(argv[1]); // exit(1); // } // top->io_din = getc(input); top->resetq = 0; top->eval(); top->resetq = 1; FILE *log = fopen("log", "w"); int t = 0; // for (i = 0; /*i < 534563551 */; i++) { for (i = 0; ; i++) { top->clk = 1; top->eval(); // tfp->dump(t); t += 20; top->clk = 0; top->eval(); // tfp->dump(t); t += 20; if (top->uart0_wr) { // printf("out %d\n", top->uart_w); putchar(top->uart_w); putc(top->uart_w, log); } if (top->uart0_rd) { int c = getchar(); top->uart0_data = (c == '\n') ? '\r' : c; if (c == EOF) break; } } printf("Simulation ended after %d cycles\n", i); delete top; // tfp->close(); fclose(log); exit(0); }
#include <stdio.h> #include "Vj1a.h" #include "verilated_vcd_c.h" int main(int argc, char **argv) { Verilated::commandArgs(argc, argv); Vj1a* top = new Vj1a; if (argc != 2) { fprintf(stderr, "usage: sim <hex-file>\n"); exit(1); } FILE *hex = fopen(argv[1], "r"); int i; for (i = 0; i < 2048; i++) { unsigned int v; if (fscanf(hex, "%x\n", &v) != 1) { fprintf(stderr, "invalid hex value at line %d\n", i + 1); exit(1); } top->v__DOT__ram_prog[i] = v; } for (i = 0; i < 2048; i++) { unsigned int v; if (fscanf(hex, "%x\n", &v) != 1) { fprintf(stderr, "invalid hex value at line %d\n", i + 1); exit(1); } top->v__DOT__ram_data[i] = v; } top->resetq = 0; top->eval(); top->resetq = 1; top->uart0_valid = 1; // pretend to always have a character waiting for (i = 0; ; i++) { top->clk = 1; top->eval(); top->clk = 0; top->eval(); if (top->uart0_wr) { putchar(top->uart_w); } if (top->uart0_rd) { int c = getchar(); top->uart0_data = (c == '\n') ? '\r' : c; if (c == EOF) break; } } printf("Simulation ended after %d cycles\n", i); delete top; exit(0); }
Fix UART hang in toy Verilator simulator
Fix UART hang in toy Verilator simulator
C++
bsd-3-clause
GuzTech/swapforth,jamesbowman/swapforth,jamesbowman/swapforth,zuloloxi/swapforth,jamesbowman/swapforth,zuloloxi/swapforth,GuzTech/swapforth,GuzTech/swapforth,uho/swapforth,RGD2/swapforth,zuloloxi/swapforth,uho/swapforth,RGD2/swapforth,zuloloxi/swapforth,uho/swapforth,RGD2/swapforth,GuzTech/swapforth,jamesbowman/swapforth,uho/swapforth,RGD2/swapforth
a1465162b8eefc94db9024fa5a9f643b0e96e868
bitops/include/bitops.hh
bitops/include/bitops.hh
#ifndef BITOPS_HH #define BITOPS_HH #include <limits> #include <type_traits> #include <cstdint> #include <climits> namespace std { /////////////////////////// //Basic bitwise operations /////////////////////////// //Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined. template <typename T> constexpr int ctz(T t) noexcept = delete; template <> constexpr int ctz(unsigned int t) noexcept { return __builtin_ctz(t); } template <> constexpr int ctz(unsigned long t) noexcept { return __builtin_ctzl(t); } template <> constexpr int ctz(unsigned long long t) noexcept { return __builtin_ctzll(t); } template <> constexpr int ctz(unsigned char t) noexcept { return ctz<unsigned int>(t); } template <> constexpr int ctz(unsigned short t) noexcept { return ctz<unsigned int>(t); } //Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined. template <typename T> constexpr int clz(T t) noexcept = delete; template <> constexpr int clz(unsigned int t) noexcept { return __builtin_clz(t); } template <> constexpr int clz(unsigned long t) noexcept { return __builtin_clzl(t); } template <> constexpr int clz(unsigned long long t) noexcept { return __builtin_clzll(t); } template <> constexpr int clz(unsigned char t) noexcept { return clz<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT); } template <> constexpr int clz(unsigned short t) noexcept { return clz<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT); } //Return position of the first bit set in t. template <typename T> constexpr int ffs(T t) noexcept = delete; template <> constexpr int ffs(unsigned int t) noexcept { return __builtin_ffs(t); } template <> constexpr int ffs(unsigned long t) noexcept { return __builtin_ffsl(t); } template <> constexpr int ffs(unsigned long long t) noexcept { return __builtin_ffsll(t); } template <> constexpr int ffs(unsigned char t) noexcept { return ffs<unsigned int>(t); } template <> constexpr int ffs(unsigned short t) noexcept { return ffs<unsigned int>(t); } //Returns position of the last bit set in t template <typename T> constexpr int fls(T t) noexcept { static_assert(std::is_unsigned<T>::value, "T must be unsigned!"); return (sizeof(t) * CHAR_BIT) - clz(t); } //Returns the number of leading redundant sign bits in x, i.e. the number of bits following the most significant bit that are identical to it. There are no special cases for 0 or other values template <typename T> constexpr int clrsb(T t) noexcept = delete; template <> constexpr int clrsb(unsigned int t) noexcept { return __builtin_clrsb(t); } template <> constexpr int clrsb(unsigned long t) noexcept { return __builtin_clrsbl(t); } template <> constexpr int clrsb(unsigned long long t) noexcept { return __builtin_clrsbll(t); } template <> constexpr int clrsb(unsigned char t) noexcept { return clrsb<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT); } template <> constexpr int clrsb(unsigned short t) noexcept { return clrsb<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT); } //Returns the number of 1-bits in x. template <typename T> constexpr int popcount(T t) noexcept = delete; template <> constexpr int popcount(unsigned int t) noexcept { return __builtin_popcount(t); } template <> constexpr int popcount(unsigned long t) noexcept { return __builtin_popcount(t); } template <> constexpr int popcount(unsigned long long t) noexcept { return __builtin_popcount(t); } template <> constexpr int popcount(unsigned char t) noexcept { return popcount<unsigned int>(t); } template <> constexpr int popcount(unsigned short t) noexcept { return popcount<unsigned int>(t); } //Returns the parity of x, i.e. the number of 1-bits in x modulo 2. template <typename T> constexpr int parity(T t) noexcept = delete; template <> constexpr int parity(unsigned int t) noexcept { return __builtin_parity(t); } template <> constexpr int parity(unsigned long t) noexcept { return __builtin_parityl(t); } template <> constexpr int parity(unsigned long long t) noexcept { return __builtin_parityll(t); } template <> constexpr int parity(unsigned char t) noexcept { return parity<unsigned int>(t); } template <> constexpr int parity(unsigned short t) noexcept { return parity<unsigned int>(t); } /////////////////////////// //Explicit bit shifts /////////////////////////// //logical shift left template <typename T, typename S> constexpr auto shl(T t, S s) noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type { static_assert(std::is_unsigned<S>::value, "s must be unsigned!"); return t << s; } //logical shift right template <typename T, typename S> constexpr auto shr(T t, S s) noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type { //For unsigned types, built in right shift is guaranteed to be logical static_assert(std::is_unsigned<S>::value, "s must be unsigned!"); return t >> s; } template <typename T, typename S> constexpr auto shr(T t, S s) noexcept -> typename std::enable_if<std::is_signed<T>::value,T>::type { //For signed types, built in right shift is implementation defined. Cast to unsigned and shift. static_assert(std::is_unsigned<S>::value, "s must be unsigned!"); return static_cast<T>(shr(typename make_unsigned<T>::type(t), s)); } template <typename T, typename S> constexpr auto shift(T t, S s) noexcept -> typename std::enable_if<std::is_signed<T>::value,T>::type { static_assert(std::is_integral<S>::value, "s must be integral!"); return s < 0 ? shl(t, -s) : shr(t, s); } //left shift arithmetic template <typename T, typename S> constexpr T sal(T t, S s) noexcept { static_assert(std::is_unsigned<S>::value, "s must be unsigned!"); return shl(t, s); } //right shift arithmetic. This implementation assumes right shift on signed types in arithmetic. template <typename T, typename S> constexpr auto sar(T t, S s) noexcept -> typename std::enable_if<std::is_signed<T>::value,T>::type { return t >> s; } template <typename T, typename S> constexpr auto sar(T t, S s) noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type { return sar(typename make_signed<T>::type(t), s); } //Left rotate shift template <typename T, typename S> constexpr T rotl(T t, S s) noexcept { return shl(t, s) | shr(t, (sizeof(t) * CHAR_BIT) - s); } //Right rotate shift template <typename T, typename S> constexpr T rotr(T t, S s) noexcept { return shr(t, s) | shl(t, (sizeof(t) * CHAR_BIT) - s); } /////////////////////////// //Alignment manipulation /////////////////////////// //Returns the smallest number n when n >= val && is_aligned(n, align). align must be a power of 2! //Question: Provide a version of this for char* pointers? Or require user to cast to uint_ptr_t? template <typename T, typename A> constexpr T align_up(T val, A align) noexcept { return ((val + (align -1)) & -align); } //Returns the largest number n when n <= val && is_aligned(n, align). align must be a power of 2! //Question: Provide a version of this for char* pointers? Or require user to cast to uint_ptr_t? template <typename T, typename A> constexpr T align_down(T val, A align) noexcept { return val & -align; } //Returns true if t is aligned to a //Question: Provide a version of this for char* pointers? Or require user to cast to uint_ptr_t? template <typename T, typename A> constexpr bool is_aligned(T t, A a) noexcept { return ((t & (a-1)) == 0); } /////////////////////////// //Power of 2 manipulation /////////////////////////// //Returns true if t == 0 or t is a power of 2 template <typename T> constexpr bool is_pow2_or_zero(T t) noexcept { static_assert(is_unsigned<T>::value, "T must be an unsigned type!"); return (t & (t-1)) == 0; } //Returns true if t is a power of 2 template <typename T> constexpr bool is_pow2(T t) noexcept { static_assert(is_unsigned<T>::value, "T must be an unsigned type!"); return (t != 0) && is_pow2_or_zero(t); } //Return smallest power of 2 >= t template <typename T> constexpr T pow2_ge(T t) noexcept { static_assert(is_unsigned<T>::value, "T must be an unsigned type!"); return is_pow2(t) ? t : pow2_gt(t); } //Return smallest power of 2 > t template <typename T> constexpr T pow2_gt(T t) noexcept; //Return smallest power of 2 <= t template <typename T> constexpr T pow2_le(T t) noexcept { return is_pow2(t) ? t : pow2_lt(t); } //Return smallest power of 2 < t template <typename T> constexpr T pow2_lt(T t) noexcept; /////////////////////////// //Setting/Resetting bits /////////////////////////// //Sets bit b of t, no effect if b >= number of bits in t template <typename T, typename B> constexpr T set_bit(T t, B b) noexcept { return t | (1 << b); } //Set all bits in t >= b template <typename T, typename B> constexpr T set_bits_gt(T t, B b) noexcept { return t | ~((1 << (b+1)) -1); } //Set all bits in t > b template <typename T, typename B> constexpr T set_bits_ge(T t, B b) noexcept { return t | ~((1 << b) -1); } //Set all bits in t <= b template <typename T, typename B> constexpr T set_bits_le(T t, B b) noexcept { return t | ((1 << (b+1)) -1); } //Set all bits in t < b template <typename T, typename B> constexpr T set_bits_lt(T t, B b) noexcept { return t | ((1 << b) -1); } //Resets bit b of t, no effect if b >= number of bits in t template <typename T, typename B> constexpr T reset_bit(T t, B b) noexcept { return t & ~(1 << b); } //Reset all bits in t >= b template <typename T, typename B> constexpr T reset_bits_gt(T t, B b) noexcept ; //Reset all bits in t > b template <typename T, typename B> constexpr T reset_bits_ge(T t, B b) noexcept ; //Reset all bits in t <= b template <typename T, typename B> constexpr T reset_bits_le(T t, B b) noexcept ; //Reset all bits in t < b template <typename T, typename B> constexpr T reset_bits_lt(T t, B b) noexcept ; //Resets the least significant bit set template <typename T> constexpr T reset_lsb(T t) noexcept { return t & (t -1); } //Resets the most significant bit set template <typename T> constexpr T reset_msb(T t); //////////////////////// //Saturated Arithmetic //////////////////////// //Saturated addition, like normal addition except on overflow the result will be the maximum value for decltype(L + R). template <typename L, typename R> constexpr auto sat_add(L l, R r) -> decltype(l+r) { typedef decltype(l+r) LR; return static_cast<LR>(l) > numeric_limits<LR>::max() - static_cast<LR>(r) ? numeric_limits<LR>::max() : l + r; } //Saturated subtraction, like normal subtraction except on overflow the result will be the minimum value for decltype(L - R). template <typename L, typename R> constexpr auto sat_sub(L l, R r) -> decltype(l-r) { typedef decltype(l-r) LR; return static_cast<LR>(l) < numeric_limits<LR>::min() + static_cast<LR>(r) ? numeric_limits<LR>::min() : l - r; } //////////////////////// //Misc //////////////////////// //Reverses all of the bits in t template <typename T> constexpr T reverse_bits(T t) noexcept ; //Returns a value whos even bits are set to the even bits of even, and odd bits set to the odd bits of odd. template <typename T> constexpr T interleave_bits(T even, T odd); //Swaps the nibbles (4 bits) of the given byte constexpr uint8_t swap_nibbles(uint8_t byte) { return (byte >> 4) | (byte << 4); } } //namespace std #endif
#ifndef BITOPS_HH #define BITOPS_HH #include <limits> #include <type_traits> #include <cstdint> #include <climits> namespace std { /////////////////////////// //Basic bitwise operations /////////////////////////// //Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined. template <typename T> constexpr int ctz(T t) noexcept = delete; template <> constexpr int ctz(unsigned int t) noexcept { return __builtin_ctz(t); } template <> constexpr int ctz(unsigned long t) noexcept { return __builtin_ctzl(t); } template <> constexpr int ctz(unsigned long long t) noexcept { return __builtin_ctzll(t); } template <> constexpr int ctz(unsigned char t) noexcept { return ctz<unsigned int>(t); } template <> constexpr int ctz(unsigned short t) noexcept { return ctz<unsigned int>(t); } //Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined. template <typename T> constexpr int clz(T t) noexcept = delete; template <> constexpr int clz(unsigned int t) noexcept { return __builtin_clz(t); } template <> constexpr int clz(unsigned long t) noexcept { return __builtin_clzl(t); } template <> constexpr int clz(unsigned long long t) noexcept { return __builtin_clzll(t); } template <> constexpr int clz(unsigned char t) noexcept { return clz<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT); } template <> constexpr int clz(unsigned short t) noexcept { return clz<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT); } //Return position of the first bit set in t. template <typename T> constexpr int ffs(T t) noexcept = delete; template <> constexpr int ffs(unsigned int t) noexcept { return __builtin_ffs(t); } template <> constexpr int ffs(unsigned long t) noexcept { return __builtin_ffsl(t); } template <> constexpr int ffs(unsigned long long t) noexcept { return __builtin_ffsll(t); } template <> constexpr int ffs(unsigned char t) noexcept { return ffs<unsigned int>(t); } template <> constexpr int ffs(unsigned short t) noexcept { return ffs<unsigned int>(t); } //Returns position of the last bit set in t template <typename T> constexpr int fls(T t) noexcept { static_assert(std::is_unsigned<T>::value, "T must be unsigned!"); return (sizeof(t) * CHAR_BIT) - clz(t); } //Returns the number of leading redundant sign bits in x, i.e. the number of bits following the most significant bit that are identical to it. There are no special cases for 0 or other values template <typename T> constexpr int clrsb(T t) noexcept = delete; template <> constexpr int clrsb(unsigned int t) noexcept { return __builtin_clrsb(t); } template <> constexpr int clrsb(unsigned long t) noexcept { return __builtin_clrsbl(t); } template <> constexpr int clrsb(unsigned long long t) noexcept { return __builtin_clrsbll(t); } template <> constexpr int clrsb(unsigned char t) noexcept { return clrsb<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT); } template <> constexpr int clrsb(unsigned short t) noexcept { return clrsb<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT); } //Returns the number of 1-bits in x. template <typename T> constexpr int popcount(T t) noexcept = delete; template <> constexpr int popcount(unsigned int t) noexcept { return __builtin_popcount(t); } template <> constexpr int popcount(unsigned long t) noexcept { return __builtin_popcount(t); } template <> constexpr int popcount(unsigned long long t) noexcept { return __builtin_popcount(t); } template <> constexpr int popcount(unsigned char t) noexcept { return popcount<unsigned int>(t); } template <> constexpr int popcount(unsigned short t) noexcept { return popcount<unsigned int>(t); } //Returns the parity of x, i.e. the number of 1-bits in x modulo 2. template <typename T> constexpr int parity(T t) noexcept = delete; template <> constexpr int parity(unsigned int t) noexcept { return __builtin_parity(t); } template <> constexpr int parity(unsigned long t) noexcept { return __builtin_parityl(t); } template <> constexpr int parity(unsigned long long t) noexcept { return __builtin_parityll(t); } template <> constexpr int parity(unsigned char t) noexcept { return parity<unsigned int>(t); } template <> constexpr int parity(unsigned short t) noexcept { return parity<unsigned int>(t); } /////////////////////////// //Explicit bit shifts /////////////////////////// //logical shift left template <typename T> constexpr auto shl(T t, unsigned int s) noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type { return t << s; } //logical shift right template <typename T> constexpr auto shr(T t, unsigned int s) { noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type { //For unsigned types, built in right shift is guaranteed to be logical return t >> s; } template <typename T> { constexpr auto shr(T t, unsigned int s) { noexcept -> typename std::enable_if<std::is_signed<T>::value,T>::type { //For signed types, built in right shift is implementation defined. Cast to unsigned and shift. return static_cast<T>(shr(typename make_unsigned<T>::type(t), s)); } template <typename T> constexpr auto shift(T t, int s) noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type { return s < 0 ? shl(t, -s) : shr(t, s); } //left shift arithmetic template <typename T> constexpr T sal(T t, unsigned int s) noexcept { return shl(t, s); } //right shift arithmetic. This implementation assumes right shift on signed types is arithmetic. template <typename T> constexpr auto sar(T t, unsigned int s) noexcept -> typename std::enable_if<std::is_signed<T>::value,T>::type { return t >> s; } template <typename T> constexpr auto sar(T t, unsigned int s) noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type { return sar(typename make_signed<T>::type(t), s); } template <typename T> constexpr auto sa(T t, int s) noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type { return s < 0 ? sal(t, -s) : sar(t, s); } //Left rotate shift template <typename T> constexpr T rotl(T t, unsigned int s) noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type { return shl(t, s) | shr(t, (sizeof(t) * CHAR_BIT) - s); } //Right rotate shift template <typename T> constexpr T rotr(T t, unsigned int s) noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type { return shr(t, s) | shl(t, (sizeof(t) * CHAR_BIT) - s); } template <typename T> constexpr T rot(T t, int s) noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type { return s < 0 ? rotl(t, -s) : rotr(t, s); } /////////////////////////// //Alignment manipulation /////////////////////////// //Returns the smallest number n when n >= val && is_aligned(n, align). align must be a power of 2! //Question: Provide a version of this for char* pointers? Or require user to cast to uint_ptr_t? template <typename T> constexpr T align_up(T val, size_t a) noexcept { return ((val + (a -1)) & -a); } //Returns the largest number n when n <= val && is_aligned(n, align). align must be a power of 2! //Question: Provide a version of this for char* pointers? Or require user to cast to uint_ptr_t? template <typename T> constexpr T align_down(T val, size_t a) noexcept { return val & -a; } //Returns true if t is aligned to a //Question: Provide a version of this for char* pointers? Or require user to cast to uint_ptr_t? template <typename T> constexpr bool is_aligned(T t, size_t a) noexcept { return ((t & (a-1)) == 0); } /////////////////////////// //Power of 2 manipulation /////////////////////////// //Returns true if t == 0 or t is a power of 2 template <typename T> constexpr bool is_pow2_or_zero(T t) noexcept { static_assert(is_unsigned<T>::value, "T must be an unsigned type!"); return (t & (t-1)) == 0; } //Returns true if t is a power of 2 template <typename T> constexpr bool is_pow2(T t) noexcept { static_assert(is_unsigned<T>::value, "T must be an unsigned type!"); return (t != 0) && is_pow2_or_zero(t); } //Return smallest power of 2 >= t template <typename T> constexpr T pow2_ge(T t) noexcept { static_assert(is_unsigned<T>::value, "T must be an unsigned type!"); return is_pow2(t) ? t : pow2_gt(t); } //Return smallest power of 2 > t template <typename T> constexpr T pow2_gt(T t) noexcept; //Return smallest power of 2 <= t template <typename T> constexpr T pow2_le(T t) noexcept { return is_pow2(t) ? t : pow2_lt(t); } //Return smallest power of 2 < t template <typename T> constexpr T pow2_lt(T t) noexcept; /////////////////////////// //Setting/Resetting bits /////////////////////////// //Sets bit b of t, no effect if b >= number of bits in t template <typename T, typename B> constexpr T set_bit(T t, B b) noexcept { return t | (1 << b); } //Set all bits in t >= b template <typename T, typename B> constexpr T set_bits_gt(T t, B b) noexcept { return t | ~((1 << (b+1)) -1); } //Set all bits in t > b template <typename T, typename B> constexpr T set_bits_ge(T t, B b) noexcept { return t | ~((1 << b) -1); } //Set all bits in t <= b template <typename T, typename B> constexpr T set_bits_le(T t, B b) noexcept { return t | ((1 << (b+1)) -1); } //Set all bits in t < b template <typename T, typename B> constexpr T set_bits_lt(T t, B b) noexcept { return t | ((1 << b) -1); } //Resets bit b of t, no effect if b >= number of bits in t template <typename T, typename B> constexpr T reset_bit(T t, B b) noexcept { return t & ~(1 << b); } //Reset all bits in t >= b template <typename T, typename B> constexpr T reset_bits_gt(T t, B b) noexcept ; //Reset all bits in t > b template <typename T, typename B> constexpr T reset_bits_ge(T t, B b) noexcept ; //Reset all bits in t <= b template <typename T, typename B> constexpr T reset_bits_le(T t, B b) noexcept ; //Reset all bits in t < b template <typename T, typename B> constexpr T reset_bits_lt(T t, B b) noexcept ; //Resets the least significant bit set template <typename T> constexpr T reset_lsb(T t) noexcept { return t & (t -1); } //Resets the most significant bit set template <typename T> constexpr T reset_msb(T t); //////////////////////// //Saturated Arithmetic //////////////////////// //Saturated addition, like normal addition except on overflow the result will be the maximum value for decltype(L + R). template <typename L, typename R> constexpr auto sat_add(L l, R r) -> decltype(l+r) { typedef decltype(l+r) LR; return static_cast<LR>(l) > numeric_limits<LR>::max() - static_cast<LR>(r) ? numeric_limits<LR>::max() : l + r; } //Saturated subtraction, like normal subtraction except on overflow the result will be the minimum value for decltype(L - R). template <typename L, typename R> constexpr auto sat_sub(L l, R r) -> decltype(l-r) { typedef decltype(l-r) LR; return static_cast<LR>(l) < numeric_limits<LR>::min() + static_cast<LR>(r) ? numeric_limits<LR>::min() : l - r; } //////////////////////// //Misc //////////////////////// //Reverses all of the bits in t template <typename T> constexpr T reverse_bits(T t) noexcept ; //Returns a value whos even bits are set to the even bits of even, and odd bits set to the odd bits of odd. template <typename T> constexpr T interleave_bits(T even, T odd); //Swaps the nibbles (4 bits) of the given byte constexpr uint8_t swap_nibbles(uint8_t byte) { return (byte >> 4) | (byte << 4); } } //namespace std #endif
remove second template arg from shifts and aligns
remove second template arg from shifts and aligns
C++
mit
fmatthew5876/stdcxx-bitops,fmatthew5876/stdcxx-bitops,fmatthew5876/stdcxx
faca9d8057ef064280711be5fe2c332f3b9b3599
mjolnir/io/toml/read_forcefield.hpp
mjolnir/io/toml/read_forcefield.hpp
#ifndef MJOLNIR_TOML_READ_FORCEFIELD #define MJOLNIR_TOML_READ_FORCEFIELD #include <mjolnir/io/toml/read_global_forcefield.hpp> #include <mjolnir/io/toml/read_local_forcefield.hpp> #include <mjolnir/core/ForceField.hpp> #include <toml/toml.hpp> namespace mjolnir { template<typename traitsT> ForceField<traitsT> read_force_field(const toml::Table& tab) { MJOLNIR_SET_LOGGER("read_toml_file"); MJOLNIR_LOG_DEBUG("read_force_field CALLED"); LocalForceField<traitsT> local; try { const toml::Array<toml::Table> lff = toml::get<toml::Array<toml::Table>>(tab.at("localforcefield")); LocalForceField<traitsT> tmp = read_local_force_field<traitsT>(lff); local = std::move(tmp); } catch(std::exception& except){} GlobalForceField<traitsT> global; try { const toml::Array<toml::Table> gff = toml::get<toml::Array<toml::Table>>(tab.at("globalforcefield")); GlobalForceField<traitsT> tmp = read_global_force_field<traitsT>(gff); global = std::move(tmp); } catch(std::exception& except){} ForceField<traitsT> ff(std::move(local), std::move(global)); MJOLNIR_LOG_DEBUG("read_force_field RETURNED"); return ff; } }//mjolnir #endif/* MJOLNIR_TOML_READ_FORCEFIELD */
#ifndef MJOLNIR_TOML_READ_FORCEFIELD #define MJOLNIR_TOML_READ_FORCEFIELD #include <mjolnir/io/toml/read_global_forcefield.hpp> #include <mjolnir/io/toml/read_local_forcefield.hpp> #include <mjolnir/core/ForceField.hpp> #include <toml/toml.hpp> namespace mjolnir { template<typename traitsT> ForceField<traitsT> read_force_field(const toml::Table& tab) { MJOLNIR_SET_LOGGER("read_toml_file"); MJOLNIR_LOG_DEBUG("read_force_field CALLED"); LocalForceField<traitsT> local; try { const toml::Array<toml::Table> lff = toml::get<toml::Array<toml::Table>>(tab.at("localforcefield")); LocalForceField<traitsT> tmp = read_local_force_field<traitsT>(lff); local = std::move(tmp); } catch(std::exception& except) { MJOLNIR_LOG_ERROR("exception thrown:", except.what()); } GlobalForceField<traitsT> global; try { const toml::Array<toml::Table> gff = toml::get<toml::Array<toml::Table>>(tab.at("globalforcefield")); GlobalForceField<traitsT> tmp = read_global_force_field<traitsT>(gff); global = std::move(tmp); } catch(std::exception& except) { MJOLNIR_LOG_ERROR("exception thrown:", except.what()); } ForceField<traitsT> ff(std::move(local), std::move(global)); MJOLNIR_LOG_DEBUG("read_force_field RETURNED"); return ff; } }//mjolnir #endif/* MJOLNIR_TOML_READ_FORCEFIELD */
add log of exception
add log of exception
C++
mit
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
4e30b2aca90dc910353963a60e284d5faeac4343
src/tokenizer.cc
src/tokenizer.cc
#include <vector> #include <utility> #include <algorithm> #include <functional> #include <unordered_set> #include <set> #include "tokenizer.h" #include "shl_exception.h" using std::stack; using std::function; using std::unordered_set; using std::set; namespace shl { vector<pair<Range, Scope> > Tokenizer::tokenize(const Grammar& grammar, const string& text) { vector<pair<Range, Scope> > tokens; vector<const Rule*> rule_stack; tokens.push_back(std::make_pair(Range(0, text.size()), Scope(grammar.name))); tokenize(text, grammar, Match::make_dummy(0,0), rule_stack, tokens); return tokens; } static const Rule& resolve_include(const Rule& rule, vector<const Rule*>& stack) { if ( rule.include.is_base_ref ) { return *stack[0]; } else if (rule.include.ptr) { return *rule.include.ptr; } else { return rule; } } static void for_all_subrules(const Rule& rule, set<const Rule*>& visited, vector<const Rule*>& stack, function<void(const Rule&)> callback) { const Rule& real_rule = resolve_include(rule, stack); if (visited.count(&real_rule) > 0) return; visited.insert(&real_rule); if (real_rule.begin.empty()) { for (auto& subrule : real_rule.patterns) { for_all_subrules(subrule, visited, stack, callback); } } else { // we don't need to look at it's subrule at this time callback(real_rule); } } static void for_all_subrules(const vector<Rule>& rules, vector<const Rule*>& stack, function<void(const Rule&)> callback) { set<const Rule*> visited; for (auto& rule : rules) { for_all_subrules(rule, visited, stack, callback); } } static inline bool is_end_match_first(const Rule& rule, const Match& end_match, const Match& current_first_match) { if (rule.applyEndPatternLast) { return end_match[0].position < current_first_match[0].position; } else { return end_match[0].position <= current_first_match[0].position; } } /** * Find the next lexeme iteratively * * This method find the next lexeme by matching all begin field of the sub-patterns * of current rule, and its own end field, whichever comes first will be seleteced * * When true returned, found will contain the selected next pattern, and match will hold * the results. When false returned, there are 3 scenarios: * 1. end field is matched, found & match contains results * 2. current pattern is toplevel rule, so no end field, found is nullptr * 3. When nothing can be matched(either source text or syntax definition is invalid), * and user specified OPTION_TOLERATE_ERROR, found will be nullptr, otherwise exception * will be thrown * * Note: * begin_end_pos: this is the offset of current pattern's begin match.end(), it's meant to * support Perl style \G, and stands for the *previous* match.end() */ bool Tokenizer::next_lexeme(const string& text, const Match& begin_lexeme, const Match& last_lexeme, const Rule& rule, const Rule** found, Match& match, vector<const Rule*>& stack) { int begin_end_pos = begin_lexeme[0].end(); int pos = last_lexeme[0].end(); const Rule* found_rule = nullptr; Match first_match; bool is_close = false; // first find pattern or end pattern, whichever comes first for_all_subrules(rule.patterns, stack, [&found_rule , &first_match, pos, &text, begin_end_pos](const Rule& sub_rule) { Match tmp = sub_rule.begin.match(text, pos, begin_end_pos); if (tmp != Match::NOT_MATCHED) { if( found_rule == nullptr || tmp[0].position < first_match[0].position) { first_match = std::move(tmp); found_rule = &sub_rule; } } }); if (!rule.end.empty()) { Match end_match = rule.end.match(begin_lexeme, text, pos, begin_end_pos); if (end_match != Match::NOT_MATCHED) { if( found_rule == nullptr || is_end_match_first(rule, end_match, first_match)) { first_match = std::move(end_match); found_rule= &rule; is_close = true; } } } if ( found_rule != nullptr) { *found = found_rule; match = first_match; return !is_close; } // special handle for toplevel rule if (rule.end.empty()) { // all rule with begin will has an end, which is enforced by grammar loader // so only toplevel rules can be here *found = nullptr; is_close = true; return false; } // When no lexeme found if (_option & OPTION_TOLERATE_ERROR) { *found = nullptr; return false; } else { throw InvalidSourceException("scope not properly closed"); } } vector<string> compile_scope_name(vector<const Rule*>& stack, const string& name, const string& enclosing_name, const vector<string> additional) { vector<string> names; for(auto rule: stack) { names.push_back(rule->name); names.push_back(rule->content_name); } if (!enclosing_name.empty()) names.push_back(enclosing_name); for(auto elem : additional) { names.push_back(elem); } names.push_back(name); // name can't be empty, enforced by caller return names; } void Tokenizer::add_scope(vector<pair<Range, Scope> >& tokens, const Range& range, vector<const Rule*>& stack, const string& name, const string& enclosing_name, const vector<string>& additional) { if (name.empty()) return; if (range.length == 0) return; // only captures can potentially has 0 length Scope scope(compile_scope_name(stack, name, enclosing_name, additional)); tokens.push_back(std::make_pair(range, scope)); } inline void append_back(vector<pair<Range, Scope> >& target, const vector<pair<Range, Scope> >& source ) { std::move(source.begin(), source.end(), std::back_inserter(target)); } vector<string> get_parent_capture_names(const Match& match, const map<int, string>& capture, size_t pos) { vector<string> addictinal; for (size_t it = 0; it < pos; it++) { auto it_name = capture.find(it); if (match[it].contain(match[pos]) && it_name != capture.end()) { addictinal.push_back(it_name->second); } } return addictinal; } void Tokenizer::process_capture(vector<pair<Range, Scope> >& tokens, const Match& match, vector<const Rule*>& stack, const map<int, string>& capture, const string& enclosing_name) { for (auto& pair : capture) { unsigned int capture_num = pair.first; const string& name = pair.second; if (match.size() > capture_num) { if (match[0].contain(match[capture_num])) { add_scope(tokens, match[capture_num], stack, name, enclosing_name, get_parent_capture_names(match, capture, capture_num)); } } else { if (_option & OPTION_STRICT) { throw InvalidSourceException("capture number out of range"); } } } } // when we can't find the end, last found lexeme will be returned // But when current rule even dose not contain any sub-rule, then // the last found lexeme will be the begin lexeme of current rule // In this case we should advance the parser pointer by 1 to avoid infinite loop inline static bool detect_infinite_loop(const Match& begin, Match& end) { return (begin[0].end() >= end[0].end()); } Match Tokenizer::tokenize(const string& text, const Rule& rule, const Match& begin_lexeme, vector<const Rule*>& stack, vector<pair<Range, Scope> >& tokens) { stack.push_back(&rule); const Rule* found_rule = nullptr; Match last_lexeme, match; last_lexeme = begin_lexeme; while(next_lexeme(text, begin_lexeme, last_lexeme, rule, &found_rule, match, stack)) { if (found_rule->is_match_rule) { add_scope(tokens, match[0], stack, found_rule->name); process_capture(tokens, match, stack, found_rule->begin_captures, found_rule->name); last_lexeme = match; } else { vector<pair<Range, Scope> > child_tokens; Match end_match = tokenize(text, *found_rule, match, stack, child_tokens); if (detect_infinite_loop(match, end_match)) { last_lexeme = end_match; last_lexeme[0].length++; } else { Range name_range = Range(match[0].position, end_match[0].end() - match[0].position); add_scope(tokens, name_range, stack, found_rule->name); process_capture(tokens, match, stack, found_rule->begin_captures, found_rule->name); Range content_range = Range(match[0].end(), end_match[0].position - match[0].end()); add_scope(tokens, content_range, stack, found_rule->content_name, found_rule->name); append_back(tokens, child_tokens); process_capture(tokens, end_match, stack, found_rule->end_captures, found_rule->name); last_lexeme = end_match; } } } stack.pop_back(); if ( found_rule == nullptr) { //see comments for next_lexeme return last_lexeme; } else { return match; } } }
#include <vector> #include <utility> #include <algorithm> #include <functional> #include <unordered_set> #include <set> #include "tokenizer.h" #include "shl_exception.h" using std::stack; using std::function; using std::unordered_set; using std::set; namespace shl { vector<pair<Range, Scope> > Tokenizer::tokenize(const Grammar& grammar, const string& text) { vector<pair<Range, Scope> > tokens; vector<const Rule*> rule_stack; tokens.push_back(std::make_pair(Range(0, text.size()), Scope(grammar.name))); tokenize(text, grammar, Match::make_dummy(0,0), rule_stack, tokens); return tokens; } static const Rule& resolve_include(const Rule& rule, vector<const Rule*>& stack) { if ( rule.include.is_base_ref ) { return *stack[0]; } else if (rule.include.ptr) { return *rule.include.ptr; } else { return rule; } } static void for_all_subrules(const Rule& rule, set<const Rule*>& visited, vector<const Rule*>& stack, function<void(const Rule&)> callback) { const Rule& real_rule = resolve_include(rule, stack); if (visited.count(&real_rule) > 0) return; visited.insert(&real_rule); if (real_rule.begin.empty()) { for (auto& subrule : real_rule.patterns) { for_all_subrules(subrule, visited, stack, callback); } } else { // we don't need to look at it's subrule at this time callback(real_rule); } } static void for_all_subrules(const vector<Rule>& rules, vector<const Rule*>& stack, function<void(const Rule&)> callback) { set<const Rule*> visited; for (auto& rule : rules) { for_all_subrules(rule, visited, stack, callback); } } static inline bool is_end_match_first(const Rule& rule, const Match& end_match, const Match& current_first_match) { if (rule.applyEndPatternLast) { return end_match[0].position < current_first_match[0].position; } else { return end_match[0].position <= current_first_match[0].position; } } /** * Find the next lexeme iteratively * * This method find the next lexeme by matching all begin field of the sub-patterns * of current rule, and its own end field, whichever comes first will be seleteced * * When true returned, found will contain the selected next pattern, and match will hold * the results. When false returned, there are 3 scenarios: * 1. end field is matched, found & match contains results * 2. current pattern is toplevel rule, so no end field, found is nullptr * 3. When nothing can be matched(either source text or syntax definition is invalid), * and user specified OPTION_TOLERATE_ERROR, found will be nullptr, otherwise exception * will be thrown * * Note: * begin_end_pos: this is the offset of current pattern's begin match.end(), it's meant to * support Perl style \G, and stands for the *previous* match.end() */ bool Tokenizer::next_lexeme(const string& text, const Match& begin_lexeme, const Match& last_lexeme, const Rule& rule, const Rule** found, Match& match, vector<const Rule*>& stack) { int begin_end_pos = begin_lexeme[0].end(); int pos = last_lexeme[0].end(); const Rule* found_rule = nullptr; Match first_match; bool is_close = false; // first find pattern or end pattern, whichever comes first for_all_subrules(rule.patterns, stack, [&found_rule , &first_match, pos, &text, begin_end_pos](const Rule& sub_rule) { Match tmp = sub_rule.begin.match(text, pos, begin_end_pos); if (tmp != Match::NOT_MATCHED) { if( found_rule == nullptr || tmp[0].position < first_match[0].position) { first_match = std::move(tmp); found_rule = &sub_rule; } } }); if (!rule.end.empty()) { Match end_match = rule.end.match(begin_lexeme, text, pos, begin_end_pos); if (end_match != Match::NOT_MATCHED) { if( found_rule == nullptr || is_end_match_first(rule, end_match, first_match)) { first_match = std::move(end_match); found_rule= &rule; is_close = true; } } } if ( found_rule != nullptr) { *found = found_rule; match = first_match; return !is_close; } // special handle for toplevel rule if (rule.end.empty()) { // all rule with begin will has an end, which is enforced by grammar loader // so only toplevel rules can be here *found = nullptr; is_close = true; return false; } // When no lexeme found if (_option & OPTION_TOLERATE_ERROR) { *found = nullptr; return false; } else { throw InvalidSourceException("scope not properly closed: " + rule.name); } } vector<string> compile_scope_name(vector<const Rule*>& stack, const string& name, const string& enclosing_name, const vector<string> additional) { vector<string> names; for(auto rule: stack) { names.push_back(rule->name); names.push_back(rule->content_name); } if (!enclosing_name.empty()) names.push_back(enclosing_name); for(auto elem : additional) { names.push_back(elem); } names.push_back(name); // name can't be empty, enforced by caller return names; } void Tokenizer::add_scope(vector<pair<Range, Scope> >& tokens, const Range& range, vector<const Rule*>& stack, const string& name, const string& enclosing_name, const vector<string>& additional) { if (name.empty()) return; if (range.length == 0) return; // only captures can potentially has 0 length Scope scope(compile_scope_name(stack, name, enclosing_name, additional)); tokens.push_back(std::make_pair(range, scope)); } inline void append_back(vector<pair<Range, Scope> >& target, const vector<pair<Range, Scope> >& source ) { std::move(source.begin(), source.end(), std::back_inserter(target)); } vector<string> get_parent_capture_names(const Match& match, const map<int, string>& capture, size_t pos) { vector<string> addictinal; for (size_t it = 0; it < pos; it++) { auto it_name = capture.find(it); if (match[it].contain(match[pos]) && it_name != capture.end()) { addictinal.push_back(it_name->second); } } return addictinal; } void Tokenizer::process_capture(vector<pair<Range, Scope> >& tokens, const Match& match, vector<const Rule*>& stack, const map<int, string>& capture, const string& enclosing_name) { for (auto& pair : capture) { unsigned int capture_num = pair.first; const string& name = pair.second; if (match.size() > capture_num) { if (match[0].contain(match[capture_num])) { add_scope(tokens, match[capture_num], stack, name, enclosing_name, get_parent_capture_names(match, capture, capture_num)); } } else { if (_option & OPTION_STRICT) { throw InvalidSourceException("capture number out of range"); } } } } // when we can't find the end, last found lexeme will be returned // But when current rule even dose not contain any sub-rule, then // the last found lexeme will be the begin lexeme of current rule // In this case we should advance the parser pointer by 1 to avoid infinite loop inline static bool detect_infinite_loop(const Match& begin, Match& end) { return (begin[0].end() >= end[0].end()); } Match Tokenizer::tokenize(const string& text, const Rule& rule, const Match& begin_lexeme, vector<const Rule*>& stack, vector<pair<Range, Scope> >& tokens) { stack.push_back(&rule); const Rule* found_rule = nullptr; Match last_lexeme, match; last_lexeme = begin_lexeme; while(next_lexeme(text, begin_lexeme, last_lexeme, rule, &found_rule, match, stack)) { if (found_rule->is_match_rule) { add_scope(tokens, match[0], stack, found_rule->name); process_capture(tokens, match, stack, found_rule->begin_captures, found_rule->name); last_lexeme = match; } else { vector<pair<Range, Scope> > child_tokens; Match end_match = tokenize(text, *found_rule, match, stack, child_tokens); if (detect_infinite_loop(match, end_match)) { last_lexeme = end_match; last_lexeme[0].length++; } else { Range name_range = Range(match[0].position, end_match[0].end() - match[0].position); add_scope(tokens, name_range, stack, found_rule->name); process_capture(tokens, match, stack, found_rule->begin_captures, found_rule->name); Range content_range = Range(match[0].end(), end_match[0].position - match[0].end()); add_scope(tokens, content_range, stack, found_rule->content_name, found_rule->name); append_back(tokens, child_tokens); process_capture(tokens, end_match, stack, found_rule->end_captures, found_rule->name); last_lexeme = end_match; } } } stack.pop_back(); if ( found_rule == nullptr) { //see comments for next_lexeme return last_lexeme; } else { return match; } } }
include rule name in the exception message
include rule name in the exception message
C++
mit
dahakawang/SharpHighlighter,dahakawang/SharpHighlighter
b86c7d160a05a30d9f61562f44af4a567ead9022
sandbox/src/crosscall_server.cc
sandbox/src/crosscall_server.cc
// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include <vector> #include "sandbox/src/crosscall_server.h" #include "sandbox/src/crosscall_params.h" #include "sandbox/src/crosscall_client.h" #include "base/logging.h" // This code performs the ipc message validation. Potential security flaws // on the ipc are likelier to be found in this code than in the rest of // the ipc code. namespace { // The buffer for a message must match the max channel size. const size_t kMaxBufferSize = sandbox::kIPCChannelSize; } namespace sandbox { // Returns the actual size for the parameters in an IPC buffer. Returns // zero if the |param_count| is zero or too big. size_t GetActualBufferSize(size_t param_count, void* buffer_base) { // The template types are used to calculate the maximum expected size. typedef ActualCallParams<1, kMaxBufferSize> ActualCP1; typedef ActualCallParams<2, kMaxBufferSize> ActualCP2; typedef ActualCallParams<3, kMaxBufferSize> ActualCP3; typedef ActualCallParams<4, kMaxBufferSize> ActualCP4; typedef ActualCallParams<5, kMaxBufferSize> ActualCP5; typedef ActualCallParams<6, kMaxBufferSize> ActualCP6; typedef ActualCallParams<7, kMaxBufferSize> ActualCP7; typedef ActualCallParams<8, kMaxBufferSize> ActualCP8; typedef ActualCallParams<9, kMaxBufferSize> ActualCP9; // Retrieve the actual size and the maximum size of the params buffer. switch (param_count) { case 0: return 0; case 1: return reinterpret_cast<ActualCP1*>(buffer_base)->GetSize(); case 2: return reinterpret_cast<ActualCP2*>(buffer_base)->GetSize(); case 3: return reinterpret_cast<ActualCP3*>(buffer_base)->GetSize(); case 4: return reinterpret_cast<ActualCP4*>(buffer_base)->GetSize(); case 5: return reinterpret_cast<ActualCP5*>(buffer_base)->GetSize(); case 6: return reinterpret_cast<ActualCP6*>(buffer_base)->GetSize(); case 7: return reinterpret_cast<ActualCP7*>(buffer_base)->GetSize(); case 8: return reinterpret_cast<ActualCP8*>(buffer_base)->GetSize(); case 9: return reinterpret_cast<ActualCP9*>(buffer_base)->GetSize(); default: NOTREACHED(); return 0; } } CrossCallParamsEx::CrossCallParamsEx() :CrossCallParams(0, 0) { } // We override the delete operator because the object's backing memory // is hand allocated in CreateFromBuffer. We don't override the new operator // because the constructors are private so there is no way to mismatch // new & delete. void CrossCallParamsEx::operator delete(void* raw_memory) throw() { if (NULL == raw_memory) { // C++ standard allows 'delete 0' behavior. return; } delete[] reinterpret_cast<char*>(raw_memory); } // This function uses a SEH try block so cannot use C++ objects that // have destructors or else you get Compiler Error C2712. So no DCHECKs // inside this function. CrossCallParamsEx* CrossCallParamsEx::CreateFromBuffer(void* buffer_base, size_t buffer_size, size_t* output_size) { // IMPORTANT: Everything inside buffer_base and derived from it such // as param_count and declared_size is untrusted. if (NULL == buffer_base) { return NULL; } if (buffer_size < sizeof(CrossCallParams)) { return NULL; } if (buffer_size > kMaxBufferSize) { return NULL; } char* backing_mem = NULL; size_t param_count = 0; size_t declared_size; size_t min_declared_size; CrossCallParamsEx* copied_params = NULL; // Touching the untrusted buffer is done under a SEH try block. This // will catch memory access violations so we don't crash. __try { CrossCallParams* call_params = reinterpret_cast<CrossCallParams*>(buffer_base); // Check against the minimum size given the number of stated params // if too small we bail out. param_count = call_params->GetParamsCount(); min_declared_size = sizeof(CrossCallParamsEx) + (param_count * sizeof(ParamInfo)); if ((buffer_size < min_declared_size) || (sizeof(CrossCallParamsEx) > min_declared_size)) { // Minimal computed size bigger than existing buffer or param_count // integer overflow. return NULL; } // Retrieve the declared size which if it fails returns 0. declared_size = GetActualBufferSize(param_count, buffer_base); if ((declared_size > buffer_size) || (declared_size < min_declared_size)) { // Declared size is bigger than buffer or smaller than computed size // or param_count 0 or bigger than 9. return NULL; } // Now we copy the actual amount of the message. *output_size = declared_size; backing_mem = new char[declared_size]; copied_params = reinterpret_cast<CrossCallParamsEx*>(backing_mem); memcpy(backing_mem, call_params, declared_size); } __except(EXCEPTION_EXECUTE_HANDLER) { // In case of a windows exception we know it occurred while touching the // untrusted buffer so we bail out as is. delete [] backing_mem; return NULL; } const char* last_byte = &backing_mem[declared_size]; const char* first_byte = &backing_mem[min_declared_size]; // Verify here that all and each parameters make sense. This is done in the // local copy. for (size_t ix =0; ix != param_count; ++ix) { size_t size = 0; ArgType type; char* address = reinterpret_cast<char*>( copied_params->GetRawParameter(ix, &size, &type)); if ((NULL == address) || // No null params. (INVALID_TYPE >= type) || (LAST_TYPE <= type) || // Unknown type. (address < backing_mem) || // Start cannot point before buffer. (address < first_byte) || // Start cannot point too low. (address > last_byte) || // Start cannot point past buffer. ((address + size) < address) || // Invalid size. ((address + size) > last_byte)) { // End cannot point past buffer. // Malformed. delete[] backing_mem; return NULL; } } // The parameter buffer looks good. return copied_params; } // Accessors to the parameters in the raw buffer. void* CrossCallParamsEx::GetRawParameter(size_t index, size_t* size, ArgType* type) { if (index >= GetParamsCount()) { return NULL; } // The size is always computed from the parameter minus the next // parameter, this works because the message has an extra parameter slot *size = param_info_[index].size_; *type = param_info_[index].type_; return param_info_[index].offset_ + reinterpret_cast<char*>(this); } // Covers common case for 32 bit integers. bool CrossCallParamsEx::GetParameter32(size_t index, uint32* param) { size_t size = 0; ArgType type; void* start = GetRawParameter(index, &size, &type); if ((NULL == start) || (4 != size) || (ULONG_TYPE != type)) { return false; } // Copy the 4 bytes. *(reinterpret_cast<uint32*>(param)) = *(reinterpret_cast<uint32*>(start)); return true; } bool CrossCallParamsEx::GetParameterVoidPtr(size_t index, void** param) { size_t size = 0; ArgType type; void* start = GetRawParameter(index, &size, &type); if ((NULL == start) || (sizeof(void*) != size) || (VOIDPTR_TYPE != type)) { return false; } *param = *(reinterpret_cast<void**>(start)); return true; } // Covers the common case of reading a string. Note that the string is not // scanned for invalid characters. bool CrossCallParamsEx::GetParameterStr(size_t index, std::wstring* string) { size_t size = 0; ArgType type; void* start = GetRawParameter(index, &size, &type); if (WCHAR_TYPE != type) { return false; } // Check if this is an empty string. if (size == 0) { *string = L""; return true; } if ((NULL == start) || ((size % sizeof(wchar_t)) != 0)) { return false; } string->append(reinterpret_cast<wchar_t*>(start), size/(sizeof(wchar_t))); return true; } bool CrossCallParamsEx::GetParameterPtr(size_t index, size_t expected_size, void** pointer) { size_t size = 0; ArgType type; void* start = GetRawParameter(index, &size, &type); if ((size != expected_size) || (INOUTPTR_TYPE != type)) { return false; } if (NULL == start) { return false; } *pointer = start; return true; } void SetCallError(ResultCode error, CrossCallReturn* call_return) { call_return->call_outcome = error; call_return->extended_count = 0; } void SetCallSuccess(CrossCallReturn* call_return) { call_return->call_outcome = SBOX_ALL_OK; } Dispatcher* Dispatcher::OnMessageReady(IPCParams* ipc, CallbackGeneric* callback) { DCHECK(callback); std::vector<IPCCall>::iterator it = ipc_calls_.begin(); for (; it != ipc_calls_.end(); ++it) { if (it->params.Matches(ipc)) { *callback = it->callback; return this; } } return NULL; } } // namespace sandbox
// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include <vector> #include "sandbox/src/crosscall_server.h" #include "sandbox/src/crosscall_params.h" #include "sandbox/src/crosscall_client.h" #include "base/logging.h" // This code performs the ipc message validation. Potential security flaws // on the ipc are likelier to be found in this code than in the rest of // the ipc code. namespace { // The buffer for a message must match the max channel size. const size_t kMaxBufferSize = sandbox::kIPCChannelSize; } namespace sandbox { // Returns the actual size for the parameters in an IPC buffer. Returns // zero if the |param_count| is zero or too big. size_t GetActualBufferSize(size_t param_count, void* buffer_base) { // The template types are used to calculate the maximum expected size. typedef ActualCallParams<1, kMaxBufferSize> ActualCP1; typedef ActualCallParams<2, kMaxBufferSize> ActualCP2; typedef ActualCallParams<3, kMaxBufferSize> ActualCP3; typedef ActualCallParams<4, kMaxBufferSize> ActualCP4; typedef ActualCallParams<5, kMaxBufferSize> ActualCP5; typedef ActualCallParams<6, kMaxBufferSize> ActualCP6; typedef ActualCallParams<7, kMaxBufferSize> ActualCP7; typedef ActualCallParams<8, kMaxBufferSize> ActualCP8; typedef ActualCallParams<9, kMaxBufferSize> ActualCP9; // Retrieve the actual size and the maximum size of the params buffer. switch (param_count) { case 0: return 0; case 1: return reinterpret_cast<ActualCP1*>(buffer_base)->GetSize(); case 2: return reinterpret_cast<ActualCP2*>(buffer_base)->GetSize(); case 3: return reinterpret_cast<ActualCP3*>(buffer_base)->GetSize(); case 4: return reinterpret_cast<ActualCP4*>(buffer_base)->GetSize(); case 5: return reinterpret_cast<ActualCP5*>(buffer_base)->GetSize(); case 6: return reinterpret_cast<ActualCP6*>(buffer_base)->GetSize(); case 7: return reinterpret_cast<ActualCP7*>(buffer_base)->GetSize(); case 8: return reinterpret_cast<ActualCP8*>(buffer_base)->GetSize(); case 9: return reinterpret_cast<ActualCP9*>(buffer_base)->GetSize(); default: NOTREACHED(); return 0; } } CrossCallParamsEx::CrossCallParamsEx() :CrossCallParams(0, 0) { } // We override the delete operator because the object's backing memory // is hand allocated in CreateFromBuffer. We don't override the new operator // because the constructors are private so there is no way to mismatch // new & delete. void CrossCallParamsEx::operator delete(void* raw_memory) throw() { if (NULL == raw_memory) { // C++ standard allows 'delete 0' behavior. return; } delete[] reinterpret_cast<char*>(raw_memory); } // This function uses a SEH try block so cannot use C++ objects that // have destructors or else you get Compiler Error C2712. So no DCHECKs // inside this function. CrossCallParamsEx* CrossCallParamsEx::CreateFromBuffer(void* buffer_base, size_t buffer_size, size_t* output_size) { // IMPORTANT: Everything inside buffer_base and derived from it such // as param_count and declared_size is untrusted. if (NULL == buffer_base) { return NULL; } if (buffer_size < sizeof(CrossCallParams)) { return NULL; } if (buffer_size > kMaxBufferSize) { return NULL; } char* backing_mem = NULL; size_t param_count = 0; size_t declared_size; size_t min_declared_size; CrossCallParamsEx* copied_params = NULL; // Touching the untrusted buffer is done under a SEH try block. This // will catch memory access violations so we don't crash. __try { CrossCallParams* call_params = reinterpret_cast<CrossCallParams*>(buffer_base); // Check against the minimum size given the number of stated params // if too small we bail out. param_count = call_params->GetParamsCount(); min_declared_size = sizeof(CrossCallParamsEx) + (param_count * sizeof(ParamInfo)); if ((buffer_size < min_declared_size) || (sizeof(CrossCallParamsEx) > min_declared_size)) { // Minimal computed size bigger than existing buffer or param_count // integer overflow. return NULL; } // Retrieve the declared size which if it fails returns 0. declared_size = GetActualBufferSize(param_count, buffer_base); if ((declared_size > buffer_size) || (declared_size < min_declared_size)) { // Declared size is bigger than buffer or smaller than computed size // or param_count 0 or bigger than 9. return NULL; } // Now we copy the actual amount of the message. *output_size = declared_size; backing_mem = new char[declared_size]; copied_params = reinterpret_cast<CrossCallParamsEx*>(backing_mem); memcpy(backing_mem, call_params, declared_size); // Check params count in case it got changed right before the memcpy. if (copied_params->GetParamsCount() != param_count) { delete [] backing_mem; return NULL; } } __except(EXCEPTION_EXECUTE_HANDLER) { // In case of a windows exception we know it occurred while touching the // untrusted buffer so we bail out as is. delete [] backing_mem; return NULL; } const char* last_byte = &backing_mem[declared_size]; const char* first_byte = &backing_mem[min_declared_size]; // Verify here that all and each parameters make sense. This is done in the // local copy. for (size_t ix =0; ix != param_count; ++ix) { size_t size = 0; ArgType type; char* address = reinterpret_cast<char*>( copied_params->GetRawParameter(ix, &size, &type)); if ((NULL == address) || // No null params. (INVALID_TYPE >= type) || (LAST_TYPE <= type) || // Unknown type. (address < backing_mem) || // Start cannot point before buffer. (address < first_byte) || // Start cannot point too low. (address > last_byte) || // Start cannot point past buffer. ((address + size) < address) || // Invalid size. ((address + size) > last_byte)) { // End cannot point past buffer. // Malformed. delete[] backing_mem; return NULL; } } // The parameter buffer looks good. return copied_params; } // Accessors to the parameters in the raw buffer. void* CrossCallParamsEx::GetRawParameter(size_t index, size_t* size, ArgType* type) { if (index >= GetParamsCount()) { return NULL; } // The size is always computed from the parameter minus the next // parameter, this works because the message has an extra parameter slot *size = param_info_[index].size_; *type = param_info_[index].type_; return param_info_[index].offset_ + reinterpret_cast<char*>(this); } // Covers common case for 32 bit integers. bool CrossCallParamsEx::GetParameter32(size_t index, uint32* param) { size_t size = 0; ArgType type; void* start = GetRawParameter(index, &size, &type); if ((NULL == start) || (4 != size) || (ULONG_TYPE != type)) { return false; } // Copy the 4 bytes. *(reinterpret_cast<uint32*>(param)) = *(reinterpret_cast<uint32*>(start)); return true; } bool CrossCallParamsEx::GetParameterVoidPtr(size_t index, void** param) { size_t size = 0; ArgType type; void* start = GetRawParameter(index, &size, &type); if ((NULL == start) || (sizeof(void*) != size) || (VOIDPTR_TYPE != type)) { return false; } *param = *(reinterpret_cast<void**>(start)); return true; } // Covers the common case of reading a string. Note that the string is not // scanned for invalid characters. bool CrossCallParamsEx::GetParameterStr(size_t index, std::wstring* string) { size_t size = 0; ArgType type; void* start = GetRawParameter(index, &size, &type); if (WCHAR_TYPE != type) { return false; } // Check if this is an empty string. if (size == 0) { *string = L""; return true; } if ((NULL == start) || ((size % sizeof(wchar_t)) != 0)) { return false; } string->append(reinterpret_cast<wchar_t*>(start), size/(sizeof(wchar_t))); return true; } bool CrossCallParamsEx::GetParameterPtr(size_t index, size_t expected_size, void** pointer) { size_t size = 0; ArgType type; void* start = GetRawParameter(index, &size, &type); if ((size != expected_size) || (INOUTPTR_TYPE != type)) { return false; } if (NULL == start) { return false; } *pointer = start; return true; } void SetCallError(ResultCode error, CrossCallReturn* call_return) { call_return->call_outcome = error; call_return->extended_count = 0; } void SetCallSuccess(CrossCallReturn* call_return) { call_return->call_outcome = SBOX_ALL_OK; } Dispatcher* Dispatcher::OnMessageReady(IPCParams* ipc, CallbackGeneric* callback) { DCHECK(callback); std::vector<IPCCall>::iterator it = ipc_calls_.begin(); for (; it != ipc_calls_.end(); ++it) { if (it->params.Matches(ipc)) { *callback = it->callback; return this; } } return NULL; } } // namespace sandbox
Fix race in CrossCallParamsEx::CreateFromBuffer
Fix race in CrossCallParamsEx::CreateFromBuffer Credit goes to Willem Pinckaers / Matasano No unittest because to trigger this codepath you need to win a very thight race. BUG=121726 TEST=none Review URL: https://chromiumcodereview.appspot.com/9965117 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@130505 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
adobe/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,adobe/chromium,adobe/chromium,adobe/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium
26ebc8ba75a06ae2407faa255061b1b56175b4e2
kaddressbook/aboutdata.cpp
kaddressbook/aboutdata.cpp
/* This file is part of KAddressBook. Copyright (c) 2009 Laurent Montel <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "aboutdata.h" #include <klocale.h> AboutData::AboutData() : KAboutData( "kaddressbook", 0, ki18n( "KAddressBook" ), "0.1", ki18n( "The KDE Address Book Application" ), KAboutData::License_GPL_V2, ki18n( "(c) 2007-2009 The KDE PIM Team" ) ) { addAuthor( ki18n( "Tobias Koenig" ), ki18n( "Current maintainer" ), "[email protected]" ); addAuthor( ki18n("Laurent Montel"), ki18n( "Kontact integration" ), "[email protected]" ); } AboutData::~AboutData() { }
/* This file is part of KAddressBook. Copyright (c) 2009 Laurent Montel <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kdepim-version.h" #include "aboutdata.h" #include <klocale.h> AboutData::AboutData() : KAboutData( "kaddressbook", 0, ki18n( "KAddressBook" ), KDEPIM_VERSION, ki18n( "The KDE Address Book Application" ), KAboutData::License_GPL_V2, ki18n( "(c) 2007-2009 The KDE PIM Team" ) ) { addAuthor( ki18n( "Tobias Koenig" ), ki18n( "Current maintainer" ), "[email protected]" ); addAuthor( ki18n( "Laurent Montel" ), ki18n( "Kontact integration" ), "[email protected]" ); } AboutData::~AboutData() { }
Use KDEPIM_VERSION instead of hardcoded value
Use KDEPIM_VERSION instead of hardcoded value svn path=/trunk/KDE/kdepim/kaddressbook/; revision=1048705
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
34a4f6106e85d570e726bf734ebc29c9b4e29b3d
problems/twosum/solution.cpp
problems/twosum/solution.cpp
#include <bits/stdc++.h> using namespace std; int main() { int a, b; cin >> a >> b; cout << (a+b) << endl; return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int a; cin >> a; int b; cin >> b; cout << a + b << endl; return 0; }
Update solutions for clarity
Update solutions for clarity
C++
mit
ArVID220u/judge,ArVID220u/judge,ArVID220u/judge
528f4dfbd20a51abe00344d7a86c30cd4fc240ef
programs/cli_wallet/main.cpp
programs/cli_wallet/main.cpp
#include <bts/app/api.hpp> #include <bts/chain/address.hpp> #include <bts/utilities/key_conversion.hpp> #include <fc/io/json.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/websocket_api.hpp> #include <fc/io/stdio.hpp> #include <iostream> #include <fc/rpc/cli.hpp> #include <iomanip> using namespace bts::app; using namespace bts::chain; using namespace bts::utilities; using namespace std; struct wallet_data { flat_set<account_id_type> accounts; map<key_id_type, string> keys; string ws_server = "ws://localhost:8090"; string ws_user; string ws_password; }; FC_REFLECT( wallet_data, (accounts)(keys)(ws_server)(ws_user)(ws_password) ); /** * This wallet assumes nothing about where the database server is * located and performs minimal caching. This API could be provided * locally to be used by a web interface. */ class wallet_api { public: wallet_api( fc::api<login_api> rapi ) :_remote_api(rapi) { _remote_db = _remote_api->database(); _remote_net = _remote_api->network(); } string help()const; string suggest_brain_key()const { return string("dummy"); } variant get_object( object_id_type id ) { return _remote_db->get_objects({id}); } account_object get_account( string account_name_or_id ) { FC_ASSERT( account_name_or_id.size() > 0 ); vector<optional<account_object>> opt_account; if( std::isdigit( account_name_or_id.front() ) ) opt_account = _remote_db->get_accounts( {fc::variant(account_name_or_id).as<account_id_type>()} ); else opt_account = _remote_db->lookup_account_names( {account_name_or_id} ); FC_ASSERT( opt_account.size() && opt_account.front() ); return *opt_account.front(); } bool import_key( string account_name_or_id, string wif_key ) { auto opt_priv_key = wif_to_key(wif_key); FC_ASSERT( opt_priv_key.valid() ); auto wif_key_address = opt_priv_key->get_public_key(); auto acnt = get_account( account_name_or_id ); flat_set<key_id_type> keys; for( auto item : acnt.active.auths ) { if( item.first.type() == key_object_type ) keys.insert( item.first ); } for( auto item : acnt.owner.auths ) { if( item.first.type() == key_object_type ) keys.insert( item.first ); } auto opt_keys = _remote_db->get_keys( vector<key_id_type>(keys.begin(),keys.end()) ); for( auto opt_key : opt_keys ) { FC_ASSERT( opt_key.valid() ); if( opt_key->key_address() == wif_key_address ) { _wallet.keys[ opt_key->id ] = wif_key; return true; } } ilog( "key not for account ${name}", ("name",account_name_or_id) ); return false; } string normalize_brain_key( string s ) { size_t i = 0, n = s.length(); std::string result; char c; result.reserve( n ); bool preceded_by_whitespace = false; bool non_empty = false; while( i < n ) { c = s[i++]; switch( c ) { case ' ': case '\t': case '\r': case '\n': case '\v': case '\f': preceded_by_whitespace = true; continue; case 'a': c = 'A'; break; case 'b': c = 'B'; break; case 'c': c = 'C'; break; case 'd': c = 'D'; break; case 'e': c = 'E'; break; case 'f': c = 'F'; break; case 'g': c = 'G'; break; case 'h': c = 'H'; break; case 'i': c = 'I'; break; case 'j': c = 'J'; break; case 'k': c = 'K'; break; case 'l': c = 'L'; break; case 'm': c = 'M'; break; case 'n': c = 'N'; break; case 'o': c = 'O'; break; case 'p': c = 'P'; break; case 'q': c = 'Q'; break; case 'r': c = 'R'; break; case 's': c = 'S'; break; case 't': c = 'T'; break; case 'u': c = 'U'; break; case 'v': c = 'V'; break; case 'w': c = 'W'; break; case 'x': c = 'X'; break; case 'y': c = 'Y'; break; case 'z': c = 'Z'; break; default: break; } if( preceded_by_whitespace && non_empty ) result.push_back(' '); result.push_back(c); preceded_by_whitespace = false; non_empty = true; } return result; } fc::ecc::private_key derive_private_key( const std::string& prefix_string, int sequence_number) { std::string sequence_string = std::to_string(sequence_number); fc::sha512 h = fc::sha512::hash(prefix_string + " " + sequence_string); fc::ecc::private_key derived_key = fc::ecc::private_key::regenerate(fc::sha256::hash(h)); return derived_key; } signed_transaction create_account_with_brain_key( string brain_key, string account_name, string pay_from_account ) { // TODO: process when pay_from_account is ID account_object pay_from_account_object = this->get_account( pay_from_account ); account_id_type pay_from_account_id = pay_from_account_object.id; string normalized_brain_key = normalize_brain_key( brain_key ); // TODO: scan blockchain for accounts that exist with same brain key fc::ecc::private_key owner_privkey = derive_private_key( normalized_brain_key, 0 ); fc::ecc::private_key active_privkey = derive_private_key( key_to_wif(owner_privkey), 0); bts::chain::public_key_type owner_pubkey = owner_privkey.get_public_key(); bts::chain::public_key_type active_pubkey = active_privkey.get_public_key(); // get pay_from_account_id key_create_operation owner_key_create_op; owner_key_create_op.fee_paying_account = pay_from_account_id; owner_key_create_op.key_data = owner_pubkey; key_create_operation active_key_create_op; active_key_create_op.fee_paying_account = pay_from_account_id; active_key_create_op.key_data = active_pubkey; // key_create_op.calculate_fee(db.current_fee_schedule()); // TODO: Check if keys already exist!!! account_create_operation account_create_op; vector<string> v_pay_from_account; v_pay_from_account.push_back( pay_from_account ); account_create_op.registrar = pay_from_account_id; relative_key_id_type owner_rkid(0); relative_key_id_type active_rkid(1); account_create_op.name = account_name; account_create_op.owner = authority(1, owner_rkid, 1); account_create_op.active = authority(1, active_rkid, 1); account_create_op.memo_key = active_rkid; account_create_op.voting_key = active_rkid; account_create_op.vote = flat_set<vote_tally_id_type>(); // current_fee_schedule() // find_account(pay_from_account) // account_create_op.fee = account_create_op.calculate_fee(db.current_fee_schedule()); signed_transaction tx; tx.operations.push_back( owner_key_create_op ); tx.operations.push_back( active_key_create_op ); tx.operations.push_back( account_create_op ); tx.visit( operation_set_fee( _remote_db->get_global_properties().parameters.current_fees ) ); vector<key_id_type> paying_keys = pay_from_account_object.active.get_keys(); tx.validate(); for( key_id_type& key : paying_keys ) { auto it = _wallet.keys.find(key); if( it != _wallet.keys.end() ) { fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second ); if( !privkey.valid() ) { FC_ASSERT( false, "Malformed private key in _wallet.keys" ); } tx.sign( *privkey ); } } return tx; } signed_transaction transfer( string from, string to, uint64_t amount, string asset_symbol, string memo, bool broadcast = false ) { auto opt_asset = _remote_db->lookup_asset_symbols( {asset_symbol} ); wdump( (opt_asset) ); return signed_transaction(); } wallet_data _wallet; fc::api<login_api> _remote_api; fc::api<database_api> _remote_db; fc::api<network_api> _remote_net; }; FC_API( wallet_api, (help) (import_key) (suggest_brain_key) (create_account_with_brain_key) (transfer) (get_account) (get_object) (normalize_brain_key) ) struct help_visitor { help_visitor( std::stringstream& s ):ss(s){} std::stringstream& ss; template<typename R, typename... Args> void operator()( const char* name, std::function<R(Args...)>& memb )const { ss << std::setw(40) << std::left << fc::get_typename<R>::name() << " " << name << "( "; vector<string> args{ fc::get_typename<Args>::name()... }; for( uint32_t i = 0; i < args.size(); ++i ) ss << args[i] << (i==args.size()-1?" ":", "); ss << ")\n"; } }; string wallet_api::help()const { fc::api<wallet_api> tmp; std::stringstream ss; tmp->visit( help_visitor(ss) ); return ss.str(); } int main( int argc, char** argv ) { try { FC_ASSERT( argc > 1, "usage: ${cmd} WALLET_FILE", ("cmd",argv[0]) ); fc::ecc::private_key genesis_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("genesis"))); idump( (key_to_wif( genesis_private_key ) ) ); idump( (account_id_type()) ); wallet_data wallet; fc::path wallet_file(argv[1]); if( fc::exists( wallet_file ) ) wallet = fc::json::from_file( wallet_file ).as<wallet_data>(); fc::http::websocket_client client; auto con = client.connect( wallet.ws_server ); auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con); con->closed.connect( [&](){ elog( "connection closed" ); } ); auto remote_api = apic->get_remote_api< login_api >(); FC_ASSERT( remote_api->login( wallet.ws_user, wallet.ws_password ) ); auto wapiptr = std::make_shared<wallet_api>(remote_api); wapiptr->_wallet = wallet; fc::api<wallet_api> wapi(wapiptr); auto wallet_cli = std::make_shared<fc::rpc::cli>(); wallet_cli->format_result( "help", [&]( variant result, const fc::variants& a) { return result.get_string(); }); wallet_cli->register_api( wapi ); wallet_cli->start(); wallet_cli->wait(); } catch ( const fc::exception& e ) { std::cout << e.to_detail_string() << "\n"; } return -1; }
#include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <fc/io/json.hpp> #include <fc/io/stdio.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/cli.hpp> #include <fc/rpc/websocket_api.hpp> #include <bts/app/api.hpp> #include <bts/chain/address.hpp> #include <bts/utilities/key_conversion.hpp> using namespace bts::app; using namespace bts::chain; using namespace bts::utilities; using namespace std; struct wallet_data { flat_set<account_id_type> accounts; // map of key_id -> base58 private key map<key_id_type, string> keys; // map of account_name -> base58_private_key for // incomplete account regs map<string, string> pending_account_registrations; string ws_server = "ws://localhost:8090"; string ws_user; string ws_password; }; FC_REFLECT( wallet_data, (accounts)(keys)(pending_account_registrations)(ws_server)(ws_user)(ws_password) ); /** * This wallet assumes nothing about where the database server is * located and performs minimal caching. This API could be provided * locally to be used by a web interface. */ class wallet_api { public: wallet_api( fc::api<login_api> rapi ) :_remote_api(rapi) { _remote_db = _remote_api->database(); _remote_net = _remote_api->network(); } string help()const; string suggest_brain_key()const { return string("dummy"); } variant get_object( object_id_type id ) { return _remote_db->get_objects({id}); } account_object get_account( string account_name_or_id ) { FC_ASSERT( account_name_or_id.size() > 0 ); vector<optional<account_object>> opt_account; if( std::isdigit( account_name_or_id.front() ) ) opt_account = _remote_db->get_accounts( {fc::variant(account_name_or_id).as<account_id_type>()} ); else opt_account = _remote_db->lookup_account_names( {account_name_or_id} ); FC_ASSERT( opt_account.size() && opt_account.front() ); return *opt_account.front(); } bool import_key( string account_name_or_id, string wif_key ) { auto opt_priv_key = wif_to_key(wif_key); FC_ASSERT( opt_priv_key.valid() ); bts::chain::address wif_key_address = bts::chain::address( opt_priv_key->get_public_key() ); auto acnt = get_account( account_name_or_id ); flat_set<key_id_type> keys; for( auto item : acnt.active.auths ) { if( item.first.type() == key_object_type ) keys.insert( item.first ); } for( auto item : acnt.owner.auths ) { if( item.first.type() == key_object_type ) keys.insert( item.first ); } auto opt_keys = _remote_db->get_keys( vector<key_id_type>(keys.begin(),keys.end()) ); for( const fc::optional<key_object>& opt_key : opt_keys ) { // the requested key ID's should all exist because they are // keys for an account FC_ASSERT( opt_key.valid() ); // we do this check by address because key objects on the // blockchain may not contain a key (i.e. are simply an address) if( opt_key->key_address() == wif_key_address ) { _wallet.keys[ opt_key->id ] = wif_key; return true; } } ilog( "key not for account ${name}", ("name",account_name_or_id) ); return false; } string normalize_brain_key( string s ) { size_t i = 0, n = s.length(); std::string result; char c; result.reserve( n ); bool preceded_by_whitespace = false; bool non_empty = false; while( i < n ) { c = s[i++]; switch( c ) { case ' ': case '\t': case '\r': case '\n': case '\v': case '\f': preceded_by_whitespace = true; continue; case 'a': c = 'A'; break; case 'b': c = 'B'; break; case 'c': c = 'C'; break; case 'd': c = 'D'; break; case 'e': c = 'E'; break; case 'f': c = 'F'; break; case 'g': c = 'G'; break; case 'h': c = 'H'; break; case 'i': c = 'I'; break; case 'j': c = 'J'; break; case 'k': c = 'K'; break; case 'l': c = 'L'; break; case 'm': c = 'M'; break; case 'n': c = 'N'; break; case 'o': c = 'O'; break; case 'p': c = 'P'; break; case 'q': c = 'Q'; break; case 'r': c = 'R'; break; case 's': c = 'S'; break; case 't': c = 'T'; break; case 'u': c = 'U'; break; case 'v': c = 'V'; break; case 'w': c = 'W'; break; case 'x': c = 'X'; break; case 'y': c = 'Y'; break; case 'z': c = 'Z'; break; default: break; } if( preceded_by_whitespace && non_empty ) result.push_back(' '); result.push_back(c); preceded_by_whitespace = false; non_empty = true; } return result; } fc::ecc::private_key derive_private_key( const std::string& prefix_string, int sequence_number) { std::string sequence_string = std::to_string(sequence_number); fc::sha512 h = fc::sha512::hash(prefix_string + " " + sequence_string); fc::ecc::private_key derived_key = fc::ecc::private_key::regenerate(fc::sha256::hash(h)); return derived_key; } signed_transaction create_account_with_brain_key( string brain_key, string account_name, string pay_from_account ) { // TODO: process when pay_from_account is ID account_object pay_from_account_object = this->get_account( pay_from_account ); account_id_type pay_from_account_id = pay_from_account_object.id; string normalized_brain_key = normalize_brain_key( brain_key ); // TODO: scan blockchain for accounts that exist with same brain key fc::ecc::private_key owner_privkey = derive_private_key( normalized_brain_key, 0 ); fc::ecc::private_key active_privkey = derive_private_key( key_to_wif(owner_privkey), 0); bts::chain::public_key_type owner_pubkey = owner_privkey.get_public_key(); bts::chain::public_key_type active_pubkey = active_privkey.get_public_key(); // get pay_from_account_id key_create_operation owner_key_create_op; owner_key_create_op.fee_paying_account = pay_from_account_id; owner_key_create_op.key_data = owner_pubkey; key_create_operation active_key_create_op; active_key_create_op.fee_paying_account = pay_from_account_id; active_key_create_op.key_data = active_pubkey; // key_create_op.calculate_fee(db.current_fee_schedule()); // TODO: Check if keys already exist!!! account_create_operation account_create_op; vector<string> v_pay_from_account; v_pay_from_account.push_back( pay_from_account ); account_create_op.registrar = pay_from_account_id; relative_key_id_type owner_rkid(0); relative_key_id_type active_rkid(1); account_create_op.name = account_name; account_create_op.owner = authority(1, owner_rkid, 1); account_create_op.active = authority(1, active_rkid, 1); account_create_op.memo_key = active_rkid; account_create_op.voting_key = active_rkid; account_create_op.vote = flat_set<vote_tally_id_type>(); // current_fee_schedule() // find_account(pay_from_account) // account_create_op.fee = account_create_op.calculate_fee(db.current_fee_schedule()); signed_transaction tx; tx.operations.push_back( owner_key_create_op ); tx.operations.push_back( active_key_create_op ); tx.operations.push_back( account_create_op ); tx.visit( operation_set_fee( _remote_db->get_global_properties().parameters.current_fees ) ); vector<key_id_type> paying_keys = pay_from_account_object.active.get_keys(); tx.validate(); for( key_id_type& key : paying_keys ) { auto it = _wallet.keys.find(key); if( it != _wallet.keys.end() ) { fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second ); if( !privkey.valid() ) { FC_ASSERT( false, "Malformed private key in _wallet.keys" ); } tx.sign( *privkey ); } } // we do not insert owner_privkey here because // it is intended to only be used for key recovery _wallet.pending_account_registrations[ account_name ] = key_to_wif( active_privkey ); return tx; } signed_transaction transfer( string from, string to, uint64_t amount, string asset_symbol, string memo, bool broadcast = false ) { auto opt_asset = _remote_db->lookup_asset_symbols( {asset_symbol} ); wdump( (opt_asset) ); return signed_transaction(); } // methods that start with underscore are not incuded in API void _resync() { // this method is used to update wallet_data annotations // e.g. wallet has been restarted and was not notified // of events while it was down // // everything that is done "incremental style" when a push // notification is received, should also be done here // "batch style" by querying the blockchain if( _wallet.pending_account_registrations.size() > 0 ) { std::vector<string> v_names; v_names.reserve( _wallet.pending_account_registrations.size() ); for( auto it : _wallet.pending_account_registrations ) v_names.push_back( it.first ); std::vector< fc::optional< bts::chain::account_object >> v_accounts = _remote_db->lookup_account_names( v_names ); for( fc::optional< bts::chain::account_object > opt_account : v_accounts ) { if( ! opt_account.valid() ) continue; string account_name = opt_account->name; auto it = _wallet.pending_account_registrations.find( account_name ); FC_ASSERT( it != _wallet.pending_account_registrations.end() ); if( import_key( account_name, it->second ) ) { // somebody else beat our pending registration, there is // nothing we can do except log it and move on ilog( "account ${name} registered by someone else first!", ("name", account_name) ); // might as well remove it from pending regs, // because there is now no way this registration // can become valid (even in the extremely rare // possibility of migrating to a fork where the // name is available, the user can always // manually re-register) } _wallet.pending_account_registrations.erase( it ); } } return; } wallet_data _wallet; fc::api<login_api> _remote_api; fc::api<database_api> _remote_db; fc::api<network_api> _remote_net; }; FC_API( wallet_api, (help) (import_key) (suggest_brain_key) (create_account_with_brain_key) (transfer) (get_account) (get_object) (normalize_brain_key) ) struct help_visitor { help_visitor( std::stringstream& s ):ss(s){} std::stringstream& ss; template<typename R, typename... Args> void operator()( const char* name, std::function<R(Args...)>& memb )const { ss << std::setw(40) << std::left << fc::get_typename<R>::name() << " " << name << "( "; vector<string> args{ fc::get_typename<Args>::name()... }; for( uint32_t i = 0; i < args.size(); ++i ) ss << args[i] << (i==args.size()-1?" ":", "); ss << ")\n"; } }; string wallet_api::help()const { fc::api<wallet_api> tmp; std::stringstream ss; tmp->visit( help_visitor(ss) ); return ss.str(); } int main( int argc, char** argv ) { try { FC_ASSERT( argc > 1, "usage: ${cmd} WALLET_FILE", ("cmd",argv[0]) ); fc::ecc::private_key genesis_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("genesis"))); idump( (key_to_wif( genesis_private_key ) ) ); idump( (account_id_type()) ); wallet_data wallet; fc::path wallet_file(argv[1]); if( fc::exists( wallet_file ) ) wallet = fc::json::from_file( wallet_file ).as<wallet_data>(); fc::http::websocket_client client; auto con = client.connect( wallet.ws_server ); auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con); con->closed.connect( [&](){ elog( "connection closed" ); } ); auto remote_api = apic->get_remote_api< login_api >(); FC_ASSERT( remote_api->login( wallet.ws_user, wallet.ws_password ) ); auto wapiptr = std::make_shared<wallet_api>(remote_api); wapiptr->_wallet = wallet; fc::api<wallet_api> wapi(wapiptr); auto wallet_cli = std::make_shared<fc::rpc::cli>(); wallet_cli->format_result( "help", [&]( variant result, const fc::variants& a) { return result.get_string(); }); wallet_cli->register_api( wapi ); wallet_cli->start(); wallet_cli->wait(); } catch ( const fc::exception& e ) { std::cout << e.to_detail_string() << "\n"; } return -1; }
Implement create_account_with_brain_key
cli_wallet: Implement create_account_with_brain_key
C++
cc0-1.0
bitshares/bitshares-toolkit,bitshares/bitshares-toolkit
7ad0c00e7f9f4f26ae5ec0d852a70dd856e7bb4e
kpilot/kpilot/syncStack.cc
kpilot/kpilot/syncStack.cc
/* syncStack.cc KPilot ** ** Copyright (C) 1998-2001 by Dan Pilone ** ** This defines the "ActionQueue", which is the pile of actions ** that will occur during a HotSync. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, ** MA 02111-1307, USA. */ /* ** Bug reports and questions can be sent to [email protected] */ #include "options.h" static const char *syncStack_id = "$Id$"; #include <qtimer.h> #include <qfile.h> #include <kservice.h> #include <kservicetype.h> #include <kuserprofile.h> #include <klibloader.h> #include "pilotUser.h" #include "hotSync.h" #include "interactiveSync.h" #include "fileInstaller.h" #include "syncStack.moc" WelcomeAction::WelcomeAction(KPilotDeviceLink *p) : SyncAction(p,"welcomeAction") { FUNCTIONSETUP; (void) syncStack_id; } /* virtual */ bool WelcomeAction::exec() { FUNCTIONSETUP; addSyncLogEntry(i18n("KPilot %1 HotSync starting...\n") .arg(QString::fromLatin1(KPILOT_VERSION))); emit syncDone(this); return true; } SorryAction::SorryAction(KPilotDeviceLink *p) : SyncAction(p,"sorryAction") { } bool SorryAction::exec() { FUNCTIONSETUP; addSyncLogEntry(i18n("KPilot is busy and cannot process the " "HotSync right now.")); return delayDone(); } ConduitProxy::ConduitProxy(KPilotDeviceLink *p, const QString &name, int m) : ConduitAction(p,name.latin1()), fDesktopName(name), fMode(m) { FUNCTIONSETUP; } /* virtual */ bool ConduitProxy::exec() { FUNCTIONSETUP; // query that service KSharedPtr < KService > o = KService::serviceByDesktopName(fDesktopName); if (!o) { kdWarning() << k_funcinfo << ": Can't find desktop file for conduit " << fDesktopName << endl; addSyncLogEntry(i18n("Couldn't find conduit %1.").arg(fDesktopName)); emit syncDone(this); return true; } // load the lib #ifdef DEBUG DEBUGKPILOT << fname << ": Loading desktop " << fDesktopName << " with lib " << o->library() << endl; #endif fLibraryName = o->library(); KLibFactory *factory = KLibLoader::self()->factory( QFile::encodeName(o->library())); if (!factory) { kdWarning() << k_funcinfo << ": Can't load library " << o->library() << endl; addSyncLogEntry(i18n("Couldn't load conduit %1.").arg(fDesktopName)); emit syncDone(this); return true; } QStringList l; switch(fMode & ActionQueue::ActionMask) { case ActionQueue::Backup : l.append(CSL1("--backup")); break; default: ; } if (fMode & ActionQueue::FlagTest) l.append(CSL1("--test")); if (fMode & ActionQueue::FlagLocal) l.append(CSL1("--local")); // do a full sync also when changing PCs if ( (fMode & ActionQueue::FlagFull) || (fHandle->getPilotUser()->getLastSyncPC()!=(unsigned long)gethostid() ) ) l.append(CSL1("--full")); if (fMode & ActionQueue::FlagHHToPC) l.append(CSL1("--copyHHToPC")); if (fMode & ActionQueue::FlagPCToHH) l.append(CSL1("--copyPCToHH")); QObject *object = factory->create(fHandle,name(),"SyncAction",l); if (!object) { kdWarning() << k_funcinfo << ": Can't create SyncAction." << endl; addSyncLogEntry(i18n("Couldn't create conduit %1.").arg(fDesktopName)); emit syncDone(this); return true; } fConduit = dynamic_cast<ConduitAction *>(object); if (!fConduit) { kdWarning() << k_funcinfo << ": Can't cast to ConduitAction." << endl; addSyncLogEntry(i18n("Couldn't create conduit %1.").arg(fDesktopName)); emit syncDone(this); return true; } fConduit->setConfig(fConfig); logMessage(i18n("[Conduit %1]").arg(fDesktopName)); QString conduitFlags = TODO_I18N("Running with flags: "); for (QStringList::ConstIterator i = l.begin() ; i!=l.end(); ++i) { conduitFlags.append(*i); conduitFlags.append(CSL1(" ")); } logMessage(conduitFlags); #ifdef DEBUG DEBUGKPILOT<<conduitFlags<<endl; #endif // Handle the syncDone signal properly & unload the conduit. QObject::connect(fConduit,SIGNAL(syncDone(SyncAction *)), this,SLOT(execDone(SyncAction *))); // Proxy all the log and error messages. QObject::connect(fConduit,SIGNAL(logMessage(const QString &)), this,SIGNAL(logMessage(const QString &))); QObject::connect(fConduit,SIGNAL(logError(const QString &)), this,SIGNAL(logError(const QString &))); QObject::connect(fConduit,SIGNAL(logProgress(const QString &,int)), this,SIGNAL(logProgress(const QString &,int))); QTimer::singleShot(0,fConduit,SLOT(execConduit())); return true; } void ConduitProxy::execDone(SyncAction *p) { FUNCTIONSETUP; if (p!=fConduit) { kdError() << k_funcinfo << ": Unknown conduit @" << (int) p << " finished." << endl; emit syncDone(this); return; } delete p; emit syncDone(this); } ActionQueue::ActionQueue(KPilotDeviceLink *d, KConfig *config, const QStringList &conduits, const QString &dir, const QStringList &files) : SyncAction(d,"ActionQueue"), fReady(false), fConfig(config), fInstallerDir(dir), fInstallerFiles(files), fConduits(conduits) { FUNCTIONSETUP; #ifdef DEBUG if (!conduits.count()) { DEBUGCONDUIT << fname << ": No conduits." << endl; } else { DEBUGCONDUIT << fname << ": Conduits : " << conduits.join(CSL1(" + ")) << endl; } #endif kdWarning() << "SyncStack usage is deprecated." << endl; } ActionQueue::ActionQueue(KPilotDeviceLink *d) : SyncAction(d,"ActionQueue"), fReady(false), fConfig(0L) // The string lists have default constructors { FUNCTIONSETUP; } ActionQueue::~ActionQueue() { FUNCTIONSETUP; } void ActionQueue::prepare(int m) { FUNCTIONSETUP; #ifdef DEBUG DEBUGDAEMON << fname << ": Using sync mode " << m << endl; #endif switch ( m & (Test | Backup | Restore | HotSync)) { case Test: case Backup: case Restore: case HotSync: fReady=true; break; default: kdWarning() << k_funcinfo << ": Strange sync mode " << m << " set. Aborting." << endl; return; } queueInit(m); if (m & WithConduits) queueConduits(fConfig,fConduits,m); switch ( m & (Test | Backup | Restore | HotSync)) { case Test: addAction(new TestLink(fHandle)); break; case Backup: addAction(new BackupAction(fHandle)); break; case Restore: addAction(new RestoreAction(fHandle)); break; case HotSync: break; default: // We already checked for this case! fReady=false; return; } if (m & WithInstaller) queueInstaller(fInstallerDir,fInstallerFiles); queueCleanup(); } void ActionQueue::queueInit(int m) { FUNCTIONSETUP; addAction(new WelcomeAction(fHandle)); if (m & WithUserCheck) { addAction(new CheckUser(fHandle)); } } void ActionQueue::queueConduits(KConfig *config,const QStringList &l,int m) { FUNCTIONSETUP; // Add conduits here ... // // for (QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) { ConduitProxy *cp = new ConduitProxy(fHandle,*it,m); cp->setConfig(config); addAction(cp); } } void ActionQueue::queueInstaller(const QString &dir, const QStringList &files) { addAction(new FileInstallAction(fHandle,dir,files)); } void ActionQueue::queueCleanup() { addAction(new CleanupAction(fHandle)); } bool ActionQueue::exec() { actionCompleted(0L); return true; } void ActionQueue::actionCompleted(SyncAction *b) { FUNCTIONSETUP; if (b) { #ifdef DEBUG DEBUGDAEMON << fname << ": Completed action " << b->name() << endl; #endif delete b; } if (isEmpty()) { emit syncDone(this); return; } SyncAction *a = nextAction(); if (!a) { kdWarning() << k_funcinfo << ": NULL action on stack." << endl; return; } #ifdef DEBUG DEBUGDAEMON << fname << ": Will run action " << a->name() << endl; #endif QObject::connect(a, SIGNAL(logMessage(const QString &)), this, SIGNAL(logMessage(const QString &))); QObject::connect(a, SIGNAL(logError(const QString &)), this, SIGNAL(logMessage(const QString &))); QObject::connect(a, SIGNAL(logProgress(const QString &, int)), this, SIGNAL(logProgress(const QString &, int))); QObject::connect(a, SIGNAL(syncDone(SyncAction *)), this, SLOT(actionCompleted(SyncAction *))); QTimer::singleShot(0,a,SLOT(execConduit())); }
/* syncStack.cc KPilot ** ** Copyright (C) 1998-2001 by Dan Pilone ** ** This defines the "ActionQueue", which is the pile of actions ** that will occur during a HotSync. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, ** MA 02111-1307, USA. */ /* ** Bug reports and questions can be sent to [email protected] */ #include "options.h" static const char *syncStack_id = "$Id$"; #include <unistd.h> #include <qtimer.h> #include <qfile.h> #include <kservice.h> #include <kservicetype.h> #include <kuserprofile.h> #include <klibloader.h> #include "pilotUser.h" #include "hotSync.h" #include "interactiveSync.h" #include "fileInstaller.h" #include "syncStack.moc" WelcomeAction::WelcomeAction(KPilotDeviceLink *p) : SyncAction(p,"welcomeAction") { FUNCTIONSETUP; (void) syncStack_id; } /* virtual */ bool WelcomeAction::exec() { FUNCTIONSETUP; addSyncLogEntry(i18n("KPilot %1 HotSync starting...\n") .arg(QString::fromLatin1(KPILOT_VERSION))); emit syncDone(this); return true; } SorryAction::SorryAction(KPilotDeviceLink *p) : SyncAction(p,"sorryAction") { } bool SorryAction::exec() { FUNCTIONSETUP; addSyncLogEntry(i18n("KPilot is busy and cannot process the " "HotSync right now.")); return delayDone(); } ConduitProxy::ConduitProxy(KPilotDeviceLink *p, const QString &name, int m) : ConduitAction(p,name.latin1()), fDesktopName(name), fMode(m) { FUNCTIONSETUP; } /* virtual */ bool ConduitProxy::exec() { FUNCTIONSETUP; // query that service KSharedPtr < KService > o = KService::serviceByDesktopName(fDesktopName); if (!o) { kdWarning() << k_funcinfo << ": Can't find desktop file for conduit " << fDesktopName << endl; addSyncLogEntry(i18n("Couldn't find conduit %1.").arg(fDesktopName)); emit syncDone(this); return true; } // load the lib #ifdef DEBUG DEBUGKPILOT << fname << ": Loading desktop " << fDesktopName << " with lib " << o->library() << endl; #endif fLibraryName = o->library(); KLibFactory *factory = KLibLoader::self()->factory( QFile::encodeName(o->library())); if (!factory) { kdWarning() << k_funcinfo << ": Can't load library " << o->library() << endl; addSyncLogEntry(i18n("Couldn't load conduit %1.").arg(fDesktopName)); emit syncDone(this); return true; } QStringList l; switch(fMode & ActionQueue::ActionMask) { case ActionQueue::Backup : l.append(CSL1("--backup")); break; default: ; } if (fMode & ActionQueue::FlagTest) l.append(CSL1("--test")); if (fMode & ActionQueue::FlagLocal) l.append(CSL1("--local")); // do a full sync also when changing PCs if ( (fMode & ActionQueue::FlagFull) || (fHandle->getPilotUser()->getLastSyncPC()!=(unsigned long)gethostid() ) ) l.append(CSL1("--full")); if (fMode & ActionQueue::FlagHHToPC) l.append(CSL1("--copyHHToPC")); if (fMode & ActionQueue::FlagPCToHH) l.append(CSL1("--copyPCToHH")); QObject *object = factory->create(fHandle,name(),"SyncAction",l); if (!object) { kdWarning() << k_funcinfo << ": Can't create SyncAction." << endl; addSyncLogEntry(i18n("Couldn't create conduit %1.").arg(fDesktopName)); emit syncDone(this); return true; } fConduit = dynamic_cast<ConduitAction *>(object); if (!fConduit) { kdWarning() << k_funcinfo << ": Can't cast to ConduitAction." << endl; addSyncLogEntry(i18n("Couldn't create conduit %1.").arg(fDesktopName)); emit syncDone(this); return true; } fConduit->setConfig(fConfig); logMessage(i18n("[Conduit %1]").arg(fDesktopName)); QString conduitFlags = TODO_I18N("Running with flags: "); for (QStringList::ConstIterator i = l.begin() ; i!=l.end(); ++i) { conduitFlags.append(*i); conduitFlags.append(CSL1(" ")); } logMessage(conduitFlags); #ifdef DEBUG DEBUGKPILOT<<conduitFlags<<endl; #endif // Handle the syncDone signal properly & unload the conduit. QObject::connect(fConduit,SIGNAL(syncDone(SyncAction *)), this,SLOT(execDone(SyncAction *))); // Proxy all the log and error messages. QObject::connect(fConduit,SIGNAL(logMessage(const QString &)), this,SIGNAL(logMessage(const QString &))); QObject::connect(fConduit,SIGNAL(logError(const QString &)), this,SIGNAL(logError(const QString &))); QObject::connect(fConduit,SIGNAL(logProgress(const QString &,int)), this,SIGNAL(logProgress(const QString &,int))); QTimer::singleShot(0,fConduit,SLOT(execConduit())); return true; } void ConduitProxy::execDone(SyncAction *p) { FUNCTIONSETUP; if (p!=fConduit) { kdError() << k_funcinfo << ": Unknown conduit @" << (int) p << " finished." << endl; emit syncDone(this); return; } delete p; emit syncDone(this); } ActionQueue::ActionQueue(KPilotDeviceLink *d, KConfig *config, const QStringList &conduits, const QString &dir, const QStringList &files) : SyncAction(d,"ActionQueue"), fReady(false), fConfig(config), fInstallerDir(dir), fInstallerFiles(files), fConduits(conduits) { FUNCTIONSETUP; #ifdef DEBUG if (!conduits.count()) { DEBUGCONDUIT << fname << ": No conduits." << endl; } else { DEBUGCONDUIT << fname << ": Conduits : " << conduits.join(CSL1(" + ")) << endl; } #endif kdWarning() << "SyncStack usage is deprecated." << endl; } ActionQueue::ActionQueue(KPilotDeviceLink *d) : SyncAction(d,"ActionQueue"), fReady(false), fConfig(0L) // The string lists have default constructors { FUNCTIONSETUP; } ActionQueue::~ActionQueue() { FUNCTIONSETUP; } void ActionQueue::prepare(int m) { FUNCTIONSETUP; #ifdef DEBUG DEBUGDAEMON << fname << ": Using sync mode " << m << endl; #endif switch ( m & (Test | Backup | Restore | HotSync)) { case Test: case Backup: case Restore: case HotSync: fReady=true; break; default: kdWarning() << k_funcinfo << ": Strange sync mode " << m << " set. Aborting." << endl; return; } queueInit(m); if (m & WithConduits) queueConduits(fConfig,fConduits,m); switch ( m & (Test | Backup | Restore | HotSync)) { case Test: addAction(new TestLink(fHandle)); break; case Backup: addAction(new BackupAction(fHandle)); break; case Restore: addAction(new RestoreAction(fHandle)); break; case HotSync: break; default: // We already checked for this case! fReady=false; return; } if (m & WithInstaller) queueInstaller(fInstallerDir,fInstallerFiles); queueCleanup(); } void ActionQueue::queueInit(int m) { FUNCTIONSETUP; addAction(new WelcomeAction(fHandle)); if (m & WithUserCheck) { addAction(new CheckUser(fHandle)); } } void ActionQueue::queueConduits(KConfig *config,const QStringList &l,int m) { FUNCTIONSETUP; // Add conduits here ... // // for (QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) { ConduitProxy *cp = new ConduitProxy(fHandle,*it,m); cp->setConfig(config); addAction(cp); } } void ActionQueue::queueInstaller(const QString &dir, const QStringList &files) { addAction(new FileInstallAction(fHandle,dir,files)); } void ActionQueue::queueCleanup() { addAction(new CleanupAction(fHandle)); } bool ActionQueue::exec() { actionCompleted(0L); return true; } void ActionQueue::actionCompleted(SyncAction *b) { FUNCTIONSETUP; if (b) { #ifdef DEBUG DEBUGDAEMON << fname << ": Completed action " << b->name() << endl; #endif delete b; } if (isEmpty()) { emit syncDone(this); return; } SyncAction *a = nextAction(); if (!a) { kdWarning() << k_funcinfo << ": NULL action on stack." << endl; return; } #ifdef DEBUG DEBUGDAEMON << fname << ": Will run action " << a->name() << endl; #endif QObject::connect(a, SIGNAL(logMessage(const QString &)), this, SIGNAL(logMessage(const QString &))); QObject::connect(a, SIGNAL(logError(const QString &)), this, SIGNAL(logMessage(const QString &))); QObject::connect(a, SIGNAL(logProgress(const QString &, int)), this, SIGNAL(logProgress(const QString &, int))); QObject::connect(a, SIGNAL(syncDone(SyncAction *)), this, SLOT(actionCompleted(SyncAction *))); QTimer::singleShot(0,a,SLOT(execConduit())); }
Make it compile
Make it compile svn path=/trunk/kdepim/; revision=258507
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
d5c2179307f61b94ce72a8132d9e1e5c09774cba
src/import/chips/p9/procedures/hwp/pm/p9_cpu_special_wakeup_ex.C
src/import/chips/p9/procedures/hwp/pm/p9_cpu_special_wakeup_ex.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_cpu_special_wakeup_ex.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file : p9_cpu_special_wakeup_ex.C /// @brief : HWP to perform special wakeup of an EX "chiplet" // *HWP HW Owner : Greg Still <[email protected]> // *HWP FW Owner : Prem S Jha <[email protected]> // *HWP Team : PM // *HWP Level : 3 // *HWP Consumed by : OCC:FSP:HOST:CRO // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <p9_cpu_special_wakeup.H> #include <p9_cpu_special_wakeup_lib.H> #include <p9_ppe_defs.H> #include <p9_ppe_utils.H> fapi2::ReturnCode collectExTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_EX>& i_target, ProcessingValues_t i_processing_info ); /// ---------------------------------------------------------------------------- /// @brief Sets a normal eq chiplet into special wakeup state. /// @param[in] i_target eq target /// @param[in] i_operation Special Wakeup Operation i.e. assert or deassert /// @param[in] i_entity entity to be considered for special wakeup. /// @return fapi2 return code. /// fapi2::ReturnCode p9_cpu_special_wakeup_ex( const fapi2::Target < fapi2::TARGET_TYPE_EX>& i_target, const p9specialWakeup::PROC_SPCWKUP_OPS i_operation, const p9specialWakeup::PROC_SPCWKUP_ENTITY i_entity ) { FAPI_INF(">> p9_cpu_special_wakeup_ex"); fapi2::ReturnCode l_rc; ProcessingValues_t l_processing_info; fapi2::buffer<uint64_t> l_autoSpWkUp; fapi2::buffer<uint64_t> l_sgpeActive; uint8_t l_exPos = 0; uint8_t l_autoSpWkUpEn = 0; uint8_t l_spWakeUpInProg = 0; auto l_eqTarget = i_target.getParent<fapi2::TARGET_TYPE_EQ>(); auto l_procChip = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, i_target, l_exPos ); FAPI_TRY( getScom( l_procChip, PU_OCB_OCI_OCCFLG_SCOM, l_sgpeActive ) ); FAPI_ATTR_GET( fapi2::ATTR_EX_INSIDE_SPECIAL_WAKEUP, i_target, l_spWakeUpInProg ); // A special wakeup is already in progress. In all likelyhood, a special // wakeup has timed out and we are in FFDC collection path. During this // FFDC collection, we SCOMed a register which itself needs a special // wakeup. if( l_spWakeUpInProg ) { FAPI_INF("exiting ex recurssion"); return fapi2::FAPI2_RC_SUCCESS; } p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::BLOCK ); //Special wakeup request can't be serviced if //SGPE did not boot auto Special wakeup not enabled if( !l_sgpeActive.getBit( SGPE_ACTIVE_BIT ) ) { l_rc = getScom( i_target, EQ_CME_SCOM_LMCR_SCOM, l_autoSpWkUp ); if( !l_rc ) { l_autoSpWkUpEn = l_autoSpWkUp.getBit( AUTO_SPWKUP_DIS_POS + (l_exPos & 0x01) ) ? 0 : 1; FAPI_ASSERT( (!l_rc && l_autoSpWkUpEn ), fapi2::EX_SPECIAL_WAKEUP_NOT_FEASIBLE() .set_EX_POS( l_exPos ), "Special Wakeup Request Cannot Be Serviced on This Ex" ); } } l_rc = _special_wakeup( i_target, i_operation, i_entity, l_processing_info ); if ( l_rc == (uint32_t)fapi2::RC_INTERNAL_SPCWKUP_TIMEOUT ) { collectExTimeoutFailInfo( i_target, l_processing_info ); } fapi_try_exit: FAPI_INF("<< p9_cpu_special_wakeup_ex" ); p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::UNBLOCK ); return fapi2::current_err; } /// ---------------------------------------------------------------------------- /// /// @brief Collect FFDC for EQ Special Wakeup timeout /// @param[in] i_target ex target /// @param[in] i_operation info pertaining to special wakeup /// @return fapi2 return code. /// fapi2::ReturnCode collectExTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_EX>& i_target, ProcessingValues_t i_processing_info ) { FAPI_INF(">> collectExTimeoutFailInfo" ); fapi2::buffer<uint64_t> l_CPMMR[CORES_PER_EX]; fapi2::buffer<uint64_t> l_GPMMR[CORES_PER_EX]; fapi2::buffer<uint64_t> l_spWakeupRegVal[CORES_PER_EX]; fapi2::buffer<uint64_t> l_histRegVal[CORES_PER_EX]; fapi2::buffer<uint64_t> l_netCtrlVal[CORES_PER_EX]; uint32_t l_coreId = 0; auto l_core_vector = i_target.getChildren<fapi2::TARGET_TYPE_CORE>( fapi2::TARGET_STATE_PRESENT ); for( uint8_t i = 0; i < CORES_PER_EX; i++ ) { l_CPMMR[i].insert( INIT_REG_PATT, 0, 64 ); l_GPMMR[i].insert( INIT_REG_PATT, 0, 64 ); l_spWakeupRegVal[i].insert( INIT_REG_PATT, 0, 64 ); l_histRegVal[i].insert( INIT_REG_PATT, 0, 64 ); } for ( auto it : l_core_vector ) { if( it.isFunctional() ) { fapi2::getScom( it, C_CPPM_CPMMR, l_CPMMR[l_coreId] ); fapi2::getScom( it, C_PPM_GPMMR_SCOM, l_GPMMR[l_coreId] ); fapi2::getScom( it, i_processing_info.spwkup_address[l_coreId], l_spWakeupRegVal[l_coreId] ); fapi2::getScom( it, i_processing_info.history_address[l_coreId], l_histRegVal[l_coreId] ); fapi2::getScom( it, i_processing_info.netctrl_address[l_coreId], l_netCtrlVal[l_coreId] ); } l_coreId++; } uint8_t l_exPos = 0; FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, i_target, l_exPos ); // Collect CME, SGPE and PGPE FFDC, currently we only collect XIRs std::vector<uint64_t> l_ppeBaseAddresses; l_ppeBaseAddresses.push_back (getCmeBaseAddress (l_exPos)); l_ppeBaseAddresses.push_back (SGPE_BASE_ADDRESS); l_ppeBaseAddresses.push_back (PGPE_BASE_ADDRESS); //From this point onwards, any usage of FAPI TRY in physical or //logical path can be a serious problem. Hence, should not be used. FAPI_ASSERT( false , fapi2::SPCWKUP_EX_TIMEOUT(). set_POLLCOUNT( i_processing_info.poll_count ). set_C0_NETCTRL( l_netCtrlVal[0] ). set_C1_NETCTRL( l_netCtrlVal[1] ). set_C0_SP_WKUP_REG_VALUE( l_spWakeupRegVal[0] ). set_C1_SP_WKUP_REG_VALUE( l_spWakeupRegVal[1] ). set_C0_HISTORY_VALUE( l_histRegVal[0] ). set_C1_HISTORY_VALUE( l_histRegVal[1] ). set_ENTITY( i_processing_info.entity ). set_C0_CPMMR( l_CPMMR[0] ). set_C1_CPMMR( l_CPMMR[1] ). set_C0_GPMMR( l_GPMMR[0] ). set_C1_GPMMR( l_GPMMR[1] ). set_EQ_TARGET( i_target.getParent<fapi2::TARGET_TYPE_EQ>() ). set_EX_TARGET( i_target ). set_PROC_CHIP_TARGET( i_processing_info.procTgt ). set_PPE_BASE_ADDRESSES( l_ppeBaseAddresses ). set_PPE_STATE_MODE( XIRS ), "Timed Out In Setting The EX Special Wakeup" ); fapi_try_exit: FAPI_INF("<< collectExTimeoutFailInfo" ); return fapi2::current_err; } /// ---------------------------------------------------------------------------- /// @param[in] i_chipletTarget ex target /// @param[in] i_processing_info struct storing processing info /// @param[in] i_msgId Id pertaining to debug message string. /// @return fapi2 return code. fapi2::ReturnCode spwkup_deassert( const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_chipletTarget, const ProcessingValues_t i_processing_info, p9specialWakeup::SpecialWakeUpMsg i_msgId ) { FAPI_INF("> spwkup_deassert core EX" ); uint64_t l_address; for (uint32_t i = 0; i < i_processing_info.num_addresses; ++i) { l_address = i_processing_info.spwkup_address[i]; FAPI_TRY(_spwkup_deassert(i_chipletTarget, l_address, i_msgId)); } fapi_try_exit: FAPI_INF("< spwkup_deassert EX" ); return fapi2::current_err; } /// ---------------------------------------------------------------------------- /// @param[in] i_chipletTarget ex target /// @param[in] i_processing_info struct storing processing info /// @param[in] i_entity . /// @return fapi2 return code. template<> fapi2::ReturnCode set_addresses(const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target, ProcessingValues_t& i_structure, const uint32_t i_entity ) { FAPI_INF("> set_addresses for EX"); FAPI_DBG("i_processing: setaddr start" "entity = %d " "b_xstop_flag = %d " "b_ignore_xstop_flag = %d " "b_wakeup_on_entry_flag = %d " "b_ex_flag = %d \n", i_structure.entity, i_structure.b_xstop_flag, i_structure.b_ignore_xstop_flag, i_structure.b_wakeup_on_entry_flag, i_structure.b_ex_flag); uint8_t l_ex_num = 0; uint8_t l_core_num = 0; uint32_t i = 0; // Determine the good cores in the EX auto l_core_functional_vector = i_target.getChildren<fapi2::TARGET_TYPE_CORE>(fapi2::TARGET_STATE_FUNCTIONAL); FAPI_ASSERT(l_core_functional_vector.size() > 0, fapi2::SPCWKUP_NOEXCORES(), "No good cores to special wake-up in targeted EX"); for (auto it : l_core_functional_vector) { FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, it, l_core_num), "fapiGetAttribute of ATTR_CHIP_UNIT_POS"); FAPI_DBG("EX %d being procesed. Setting up for Core %d with index %d", l_ex_num, l_core_num, i); i_structure.spwkup_address[i] = SPCWKUP_ADDR[i_entity][p9specialWakeup::SPW_CORE] + 0x01000000 * l_core_num; i_structure.history_address[i] = SPCWKUP_HIST_ADDR[i_entity][p9specialWakeup::SPW_CORE] + 0x01000000 * l_core_num; i_structure.netctrl_address[i] = SPCWKUP_NETCTRL0_ADDR[p9specialWakeup::SPW_CORE] + 0x01000000 * l_core_num; i_structure.gpmmr_address[i] = SPCWKUP_GPMMR_ADDR[p9specialWakeup::SPW_CORE] + 0x01000000 * l_core_num; FAPI_DBG("i_structure.spwkup_address[%d] = 0x%08llX \n " "i_structure.history_address[%d] = 0x%08llX \n " "i_structure.netctrl_address[%d] = 0x%08llX \n " "i_structure.gpmmr_addresss[%d] = 0x%08llX \n " , i, i_structure.spwkup_address[i], i, i_structure.history_address[i], i, i_structure.netctrl_address[i], i, i_structure.gpmmr_address[i]); ++i; } i_structure.num_addresses = i; fapi_try_exit: FAPI_INF("< set_addresses for EX"); return fapi2::current_err; }
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_cpu_special_wakeup_ex.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file : p9_cpu_special_wakeup_ex.C /// @brief : HWP to perform special wakeup of an EX "chiplet" // *HWP HW Owner : Greg Still <[email protected]> // *HWP FW Owner : Prem S Jha <[email protected]> // *HWP Team : PM // *HWP Level : 3 // *HWP Consumed by : OCC:FSP:HOST:CRO // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <p9_cpu_special_wakeup.H> #include <p9_cpu_special_wakeup_lib.H> #include <p9_ppe_defs.H> #include <p9_ppe_utils.H> fapi2::ReturnCode collectExTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_EX>& i_target, ProcessingValues_t i_processing_info ); /// ---------------------------------------------------------------------------- /// @brief Sets a normal eq chiplet into special wakeup state. /// @param[in] i_target eq target /// @param[in] i_operation Special Wakeup Operation i.e. assert or deassert /// @param[in] i_entity entity to be considered for special wakeup. /// @return fapi2 return code. /// fapi2::ReturnCode p9_cpu_special_wakeup_ex( const fapi2::Target < fapi2::TARGET_TYPE_EX>& i_target, const p9specialWakeup::PROC_SPCWKUP_OPS i_operation, const p9specialWakeup::PROC_SPCWKUP_ENTITY i_entity ) { FAPI_INF(">> p9_cpu_special_wakeup_ex"); fapi2::ReturnCode l_rc; ProcessingValues_t l_processing_info; fapi2::buffer<uint64_t> l_autoSpWkUp; fapi2::buffer<uint64_t> l_sgpeActive; uint8_t l_exPos = 0; uint8_t l_autoSpWkUpEn = 0; uint8_t l_spWakeUpInProg = 0; auto l_eqTarget = i_target.getParent<fapi2::TARGET_TYPE_EQ>(); auto l_procChip = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, i_target, l_exPos ); FAPI_TRY( getScom( l_procChip, PU_OCB_OCI_OCCFLG_SCOM, l_sgpeActive ) ); FAPI_ATTR_GET( fapi2::ATTR_EX_INSIDE_SPECIAL_WAKEUP, i_target, l_spWakeUpInProg ); // A special wakeup is already in progress. In all likelyhood, a special // wakeup has timed out and we are in FFDC collection path. During this // FFDC collection, we SCOMed a register which itself needs a special // wakeup. if( l_spWakeUpInProg ) { FAPI_INF("exiting ex recurssion"); return fapi2::FAPI2_RC_SUCCESS; } p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::BLOCK ); //Special wakeup request can't be serviced if //SGPE did not boot auto Special wakeup not enabled if( !l_sgpeActive.getBit( SGPE_ACTIVE_BIT ) ) { l_rc = getScom( i_target, EQ_CME_SCOM_LMCR_SCOM, l_autoSpWkUp ); if( !l_rc ) { l_autoSpWkUpEn = l_autoSpWkUp.getBit( AUTO_SPWKUP_DIS_POS + (l_exPos & 0x01) ) ? 0 : 1; } FAPI_ASSERT( (!l_rc && l_autoSpWkUpEn ), fapi2::EX_SPECIAL_WAKEUP_NOT_FEASIBLE() .set_EX_POS( l_exPos ), "Special Wakeup Request Cannot Be Serviced on This Ex" ); } l_rc = _special_wakeup( i_target, i_operation, i_entity, l_processing_info ); if ( l_rc == (uint32_t)fapi2::RC_INTERNAL_SPCWKUP_TIMEOUT ) { collectExTimeoutFailInfo( i_target, l_processing_info ); } fapi_try_exit: FAPI_INF("<< p9_cpu_special_wakeup_ex" ); p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::UNBLOCK ); return fapi2::current_err; } /// ---------------------------------------------------------------------------- /// /// @brief Collect FFDC for EQ Special Wakeup timeout /// @param[in] i_target ex target /// @param[in] i_operation info pertaining to special wakeup /// @return fapi2 return code. /// fapi2::ReturnCode collectExTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_EX>& i_target, ProcessingValues_t i_processing_info ) { FAPI_INF(">> collectExTimeoutFailInfo" ); fapi2::buffer<uint64_t> l_CPMMR[CORES_PER_EX]; fapi2::buffer<uint64_t> l_GPMMR[CORES_PER_EX]; fapi2::buffer<uint64_t> l_spWakeupRegVal[CORES_PER_EX]; fapi2::buffer<uint64_t> l_histRegVal[CORES_PER_EX]; fapi2::buffer<uint64_t> l_netCtrlVal[CORES_PER_EX]; uint32_t l_coreId = 0; auto l_core_vector = i_target.getChildren<fapi2::TARGET_TYPE_CORE>( fapi2::TARGET_STATE_PRESENT ); for( uint8_t i = 0; i < CORES_PER_EX; i++ ) { l_CPMMR[i].insert( INIT_REG_PATT, 0, 64 ); l_GPMMR[i].insert( INIT_REG_PATT, 0, 64 ); l_spWakeupRegVal[i].insert( INIT_REG_PATT, 0, 64 ); l_histRegVal[i].insert( INIT_REG_PATT, 0, 64 ); } for ( auto it : l_core_vector ) { if( it.isFunctional() ) { fapi2::getScom( it, C_CPPM_CPMMR, l_CPMMR[l_coreId] ); fapi2::getScom( it, C_PPM_GPMMR_SCOM, l_GPMMR[l_coreId] ); fapi2::getScom( it, i_processing_info.spwkup_address[l_coreId], l_spWakeupRegVal[l_coreId] ); fapi2::getScom( it, i_processing_info.history_address[l_coreId], l_histRegVal[l_coreId] ); fapi2::getScom( it, i_processing_info.netctrl_address[l_coreId], l_netCtrlVal[l_coreId] ); } l_coreId++; } uint8_t l_exPos = 0; FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, i_target, l_exPos ); // Collect CME, SGPE and PGPE FFDC, currently we only collect XIRs std::vector<uint64_t> l_ppeBaseAddresses; l_ppeBaseAddresses.push_back (getCmeBaseAddress (l_exPos)); l_ppeBaseAddresses.push_back (SGPE_BASE_ADDRESS); l_ppeBaseAddresses.push_back (PGPE_BASE_ADDRESS); //From this point onwards, any usage of FAPI TRY in physical or //logical path can be a serious problem. Hence, should not be used. FAPI_ASSERT( false , fapi2::SPCWKUP_EX_TIMEOUT(). set_POLLCOUNT( i_processing_info.poll_count ). set_C0_NETCTRL( l_netCtrlVal[0] ). set_C1_NETCTRL( l_netCtrlVal[1] ). set_C0_SP_WKUP_REG_VALUE( l_spWakeupRegVal[0] ). set_C1_SP_WKUP_REG_VALUE( l_spWakeupRegVal[1] ). set_C0_HISTORY_VALUE( l_histRegVal[0] ). set_C1_HISTORY_VALUE( l_histRegVal[1] ). set_ENTITY( i_processing_info.entity ). set_C0_CPMMR( l_CPMMR[0] ). set_C1_CPMMR( l_CPMMR[1] ). set_C0_GPMMR( l_GPMMR[0] ). set_C1_GPMMR( l_GPMMR[1] ). set_EQ_TARGET( i_target.getParent<fapi2::TARGET_TYPE_EQ>() ). set_EX_TARGET( i_target ). set_PROC_CHIP_TARGET( i_processing_info.procTgt ). set_PPE_BASE_ADDRESSES( l_ppeBaseAddresses ). set_PPE_STATE_MODE( XIRS ), "Timed Out In Setting The EX Special Wakeup" ); fapi_try_exit: FAPI_INF("<< collectExTimeoutFailInfo" ); return fapi2::current_err; } /// ---------------------------------------------------------------------------- /// @param[in] i_chipletTarget ex target /// @param[in] i_processing_info struct storing processing info /// @param[in] i_msgId Id pertaining to debug message string. /// @return fapi2 return code. fapi2::ReturnCode spwkup_deassert( const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_chipletTarget, const ProcessingValues_t i_processing_info, p9specialWakeup::SpecialWakeUpMsg i_msgId ) { FAPI_INF("> spwkup_deassert core EX" ); uint64_t l_address; for (uint32_t i = 0; i < i_processing_info.num_addresses; ++i) { l_address = i_processing_info.spwkup_address[i]; FAPI_TRY(_spwkup_deassert(i_chipletTarget, l_address, i_msgId)); } fapi_try_exit: FAPI_INF("< spwkup_deassert EX" ); return fapi2::current_err; } /// ---------------------------------------------------------------------------- /// @param[in] i_chipletTarget ex target /// @param[in] i_processing_info struct storing processing info /// @param[in] i_entity . /// @return fapi2 return code. template<> fapi2::ReturnCode set_addresses(const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target, ProcessingValues_t& i_structure, const uint32_t i_entity ) { FAPI_INF("> set_addresses for EX"); FAPI_DBG("i_processing: setaddr start" "entity = %d " "b_xstop_flag = %d " "b_ignore_xstop_flag = %d " "b_wakeup_on_entry_flag = %d " "b_ex_flag = %d \n", i_structure.entity, i_structure.b_xstop_flag, i_structure.b_ignore_xstop_flag, i_structure.b_wakeup_on_entry_flag, i_structure.b_ex_flag); uint8_t l_ex_num = 0; uint8_t l_core_num = 0; uint32_t i = 0; // Determine the good cores in the EX auto l_core_functional_vector = i_target.getChildren<fapi2::TARGET_TYPE_CORE>(fapi2::TARGET_STATE_FUNCTIONAL); FAPI_ASSERT(l_core_functional_vector.size() > 0, fapi2::SPCWKUP_NOEXCORES(), "No good cores to special wake-up in targeted EX"); for (auto it : l_core_functional_vector) { FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, it, l_core_num), "fapiGetAttribute of ATTR_CHIP_UNIT_POS"); FAPI_DBG("EX %d being procesed. Setting up for Core %d with index %d", l_ex_num, l_core_num, i); i_structure.spwkup_address[i] = SPCWKUP_ADDR[i_entity][p9specialWakeup::SPW_CORE] + 0x01000000 * l_core_num; i_structure.history_address[i] = SPCWKUP_HIST_ADDR[i_entity][p9specialWakeup::SPW_CORE] + 0x01000000 * l_core_num; i_structure.netctrl_address[i] = SPCWKUP_NETCTRL0_ADDR[p9specialWakeup::SPW_CORE] + 0x01000000 * l_core_num; i_structure.gpmmr_address[i] = SPCWKUP_GPMMR_ADDR[p9specialWakeup::SPW_CORE] + 0x01000000 * l_core_num; FAPI_DBG("i_structure.spwkup_address[%d] = 0x%08llX \n " "i_structure.history_address[%d] = 0x%08llX \n " "i_structure.netctrl_address[%d] = 0x%08llX \n " "i_structure.gpmmr_addresss[%d] = 0x%08llX \n " , i, i_structure.spwkup_address[i], i, i_structure.history_address[i], i, i_structure.netctrl_address[i], i, i_structure.gpmmr_address[i]); ++i; } i_structure.num_addresses = i; fapi_try_exit: FAPI_INF("< set_addresses for EX"); return fapi2::current_err; }
Fix check for EQ_CME_SCOM_LMCR_SCOM
Fix check for EQ_CME_SCOM_LMCR_SCOM Change-Id: I7d6eb2a98478cd350d95f4d72c55a1243beb6c88 Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/57599 Reviewed-by: Prem Shanker Jha <[email protected]> Tested-by: FSP CI Jenkins <[email protected]> Tested-by: Jenkins Server <[email protected]> Tested-by: HWSV CI <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Dean Sanner <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
e2b8fd7b118a232d5ffa406041acb58cde1c2543
src/modules/commander/Arming/PreFlightCheck/checks/ekf2Check.cpp
src/modules/commander/Arming/PreFlightCheck/checks/ekf2Check.cpp
/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "../PreFlightCheck.hpp" #include <HealthFlags.h> #include <math.h> #include <lib/parameters/param.h> #include <systemlib/mavlink_log.h> #include <uORB/Subscription.hpp> #include <uORB/topics/estimator_status.h> #include <uORB/topics/subsystem_info.h> bool PreFlightCheck::ekf2Check(orb_advert_t *mavlink_log_pub, vehicle_status_s &vehicle_status, const bool optional, const bool report_fail, const bool enforce_gps_required) { bool success = true; // start with a pass and change to a fail if any test fails bool ahrs_present = true; float test_limit = 1.0f; // pass limit re-used for each test int32_t mag_strength_check_enabled = 1; param_get(param_find("COM_ARM_MAG_STR"), &mag_strength_check_enabled); bool gps_success = true; bool gps_present = true; // Get estimator status data if available and exit with a fail recorded if not uORB::SubscriptionData<estimator_status_s> status_sub{ORB_ID(estimator_status)}; status_sub.update(); const estimator_status_s &status = status_sub.get(); if (status.timestamp == 0) { ahrs_present = false; goto out; } // Check if preflight check performed by estimator has failed if (status.pre_flt_fail_innov_heading || status.pre_flt_fail_innov_vel_horiz || status.pre_flt_fail_innov_vel_vert || status.pre_flt_fail_innov_height) { if (report_fail) { if (status.pre_flt_fail_innov_heading) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: heading estimate not stable"); } else if (status.pre_flt_fail_innov_vel_horiz) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: horizontal velocity estimate not stable"); } else if (status.pre_flt_fail_innov_vel_horiz) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: vertical velocity estimate not stable"); } else if (status.pre_flt_fail_innov_height) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: height estimate not stable"); } } success = false; goto out; } if ((mag_strength_check_enabled == 1) && status.pre_flt_fail_mag_field_disturbed) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: strong magnetic interference detected"); } success = false; goto out; } // check vertical position innovation test ratio param_get(param_find("COM_ARM_EKF_HGT"), &test_limit); if (status.hgt_test_ratio > test_limit) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Height estimate error"); } success = false; goto out; } // check velocity innovation test ratio param_get(param_find("COM_ARM_EKF_VEL"), &test_limit); if (status.vel_test_ratio > test_limit) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Velocity estimate error"); } success = false; goto out; } // check horizontal position innovation test ratio param_get(param_find("COM_ARM_EKF_POS"), &test_limit); if (status.pos_test_ratio > test_limit) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Position estimate error"); } success = false; goto out; } // check magnetometer innovation test ratio param_get(param_find("COM_ARM_EKF_YAW"), &test_limit); if (status.mag_test_ratio > test_limit) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Yaw estimate error"); } success = false; goto out; } // check accelerometer delta velocity bias estimates param_get(param_find("COM_ARM_EKF_AB"), &test_limit); for (uint8_t index = 13; index < 16; index++) { // allow for higher uncertainty in estimates for axes that are less observable to prevent false positives // adjust test threshold by 3-sigma float test_uncertainty = 3.0f * sqrtf(fmaxf(status.covariances[index], 0.0f)); if (fabsf(status.states[index]) > test_limit + test_uncertainty) { PX4_ERR("state %d: |%.8f| > %.8f + %.8f", index, (double)status.states[index], (double)test_limit, (double)test_uncertainty); if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: High Accelerometer Bias"); } success = false; goto out; } } // check gyro delta angle bias estimates param_get(param_find("COM_ARM_EKF_GB"), &test_limit); if (fabsf(status.states[10]) > test_limit || fabsf(status.states[11]) > test_limit || fabsf(status.states[12]) > test_limit) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: High Gyro Bias"); } success = false; goto out; } // If GPS aiding is required, declare fault condition if the required GPS quality checks are failing if (enforce_gps_required || report_fail) { const bool ekf_gps_fusion = status.control_mode_flags & (1 << estimator_status_s::CS_GPS); const bool ekf_gps_check_fail = status.gps_check_fail_flags > 0; gps_success = ekf_gps_fusion; // default to success if gps data is fused if (ekf_gps_check_fail) { if (report_fail) { // Only report the first failure to avoid spamming const char *message = nullptr; if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_GPS_FIX)) { message = "Preflight%s: GPS fix too low"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MIN_SAT_COUNT)) { message = "Preflight%s: not enough GPS Satellites"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MIN_PDOP)) { message = "Preflight%s: GPS PDOP too low"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_HORZ_ERR)) { message = "Preflight%s: GPS Horizontal Pos Error too high"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_VERT_ERR)) { message = "Preflight%s: GPS Vertical Pos Error too high"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_SPD_ERR)) { message = "Preflight%s: GPS Speed Accuracy too low"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_HORZ_DRIFT)) { message = "Preflight%s: GPS Horizontal Pos Drift too high"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_VERT_DRIFT)) { message = "Preflight%s: GPS Vertical Pos Drift too high"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_HORZ_SPD_ERR)) { message = "Preflight%s: GPS Hor Speed Drift too high"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_VERT_SPD_ERR)) { message = "Preflight%s: GPS Vert Speed Drift too high"; } else { if (!ekf_gps_fusion) { // Likely cause unknown message = "Preflight%s: Estimator not using GPS"; gps_present = false; } else { // if we land here there was a new flag added and the code not updated. Show a generic message. message = "Preflight%s: Poor GPS Quality"; } } if (message) { if (enforce_gps_required) { mavlink_log_critical(mavlink_log_pub, message, " Fail"); } else { mavlink_log_warning(mavlink_log_pub, message, ""); } } } gps_success = false; if (enforce_gps_required) { success = false; goto out; } } } out: //PX4_INFO("AHRS CHECK: %s", (success && ahrs_present) ? "OK" : "FAIL"); set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_AHRS, ahrs_present, true, success && ahrs_present, vehicle_status); set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_GPS, gps_present, enforce_gps_required, gps_success, vehicle_status); return success; }
/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "../PreFlightCheck.hpp" #include <HealthFlags.h> #include <math.h> #include <lib/parameters/param.h> #include <systemlib/mavlink_log.h> #include <uORB/Subscription.hpp> #include <uORB/topics/estimator_status.h> #include <uORB/topics/subsystem_info.h> bool PreFlightCheck::ekf2Check(orb_advert_t *mavlink_log_pub, vehicle_status_s &vehicle_status, const bool optional, const bool report_fail, const bool enforce_gps_required) { bool success = true; // start with a pass and change to a fail if any test fails bool ahrs_present = true; float test_limit = 1.0f; // pass limit re-used for each test int32_t mag_strength_check_enabled = 1; param_get(param_find("COM_ARM_MAG_STR"), &mag_strength_check_enabled); bool gps_success = true; bool gps_present = true; // Get estimator status data if available and exit with a fail recorded if not uORB::SubscriptionData<estimator_status_s> status_sub{ORB_ID(estimator_status)}; status_sub.update(); const estimator_status_s &status = status_sub.get(); if (status.timestamp == 0) { ahrs_present = false; goto out; } // Check if preflight check performed by estimator has failed if (status.pre_flt_fail_innov_heading || status.pre_flt_fail_innov_vel_horiz || status.pre_flt_fail_innov_vel_vert || status.pre_flt_fail_innov_height) { if (report_fail) { if (status.pre_flt_fail_innov_heading) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: heading estimate not stable"); } else if (status.pre_flt_fail_innov_vel_horiz) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: horizontal velocity estimate not stable"); } else if (status.pre_flt_fail_innov_vel_horiz) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: vertical velocity estimate not stable"); } else if (status.pre_flt_fail_innov_height) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: height estimate not stable"); } } success = false; goto out; } if ((mag_strength_check_enabled == 1) && status.pre_flt_fail_mag_field_disturbed) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: strong magnetic interference detected"); } success = false; goto out; } // check vertical position innovation test ratio param_get(param_find("COM_ARM_EKF_HGT"), &test_limit); if (status.hgt_test_ratio > test_limit) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Height estimate error"); } success = false; goto out; } // check velocity innovation test ratio param_get(param_find("COM_ARM_EKF_VEL"), &test_limit); if (status.vel_test_ratio > test_limit) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Velocity estimate error"); } success = false; goto out; } // check horizontal position innovation test ratio param_get(param_find("COM_ARM_EKF_POS"), &test_limit); if (status.pos_test_ratio > test_limit) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Position estimate error"); } success = false; goto out; } // check magnetometer innovation test ratio param_get(param_find("COM_ARM_EKF_YAW"), &test_limit); if (status.mag_test_ratio > test_limit) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Yaw estimate error"); } success = false; goto out; } // check accelerometer delta velocity bias estimates param_get(param_find("COM_ARM_EKF_AB"), &test_limit); for (uint8_t index = 13; index < 16; index++) { // allow for higher uncertainty in estimates for axes that are less observable to prevent false positives // adjust test threshold by 3-sigma float test_uncertainty = 3.0f * sqrtf(fmaxf(status.covariances[index], 0.0f)); if (fabsf(status.states[index]) > test_limit + test_uncertainty) { if (report_fail) { PX4_ERR("state %d: |%.8f| > %.8f + %.8f", index, (double)status.states[index], (double)test_limit, (double)test_uncertainty); mavlink_log_critical(mavlink_log_pub, "Preflight Fail: High Accelerometer Bias"); } success = false; goto out; } } // check gyro delta angle bias estimates param_get(param_find("COM_ARM_EKF_GB"), &test_limit); if (fabsf(status.states[10]) > test_limit || fabsf(status.states[11]) > test_limit || fabsf(status.states[12]) > test_limit) { if (report_fail) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: High Gyro Bias"); } success = false; goto out; } // If GPS aiding is required, declare fault condition if the required GPS quality checks are failing if (enforce_gps_required || report_fail) { const bool ekf_gps_fusion = status.control_mode_flags & (1 << estimator_status_s::CS_GPS); const bool ekf_gps_check_fail = status.gps_check_fail_flags > 0; gps_success = ekf_gps_fusion; // default to success if gps data is fused if (ekf_gps_check_fail) { if (report_fail) { // Only report the first failure to avoid spamming const char *message = nullptr; if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_GPS_FIX)) { message = "Preflight%s: GPS fix too low"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MIN_SAT_COUNT)) { message = "Preflight%s: not enough GPS Satellites"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MIN_PDOP)) { message = "Preflight%s: GPS PDOP too low"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_HORZ_ERR)) { message = "Preflight%s: GPS Horizontal Pos Error too high"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_VERT_ERR)) { message = "Preflight%s: GPS Vertical Pos Error too high"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_SPD_ERR)) { message = "Preflight%s: GPS Speed Accuracy too low"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_HORZ_DRIFT)) { message = "Preflight%s: GPS Horizontal Pos Drift too high"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_VERT_DRIFT)) { message = "Preflight%s: GPS Vertical Pos Drift too high"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_HORZ_SPD_ERR)) { message = "Preflight%s: GPS Hor Speed Drift too high"; } else if (status.gps_check_fail_flags & (1 << estimator_status_s::GPS_CHECK_FAIL_MAX_VERT_SPD_ERR)) { message = "Preflight%s: GPS Vert Speed Drift too high"; } else { if (!ekf_gps_fusion) { // Likely cause unknown message = "Preflight%s: Estimator not using GPS"; gps_present = false; } else { // if we land here there was a new flag added and the code not updated. Show a generic message. message = "Preflight%s: Poor GPS Quality"; } } if (message) { if (enforce_gps_required) { mavlink_log_critical(mavlink_log_pub, message, " Fail"); } else { mavlink_log_warning(mavlink_log_pub, message, ""); } } } gps_success = false; if (enforce_gps_required) { success = false; goto out; } } } out: //PX4_INFO("AHRS CHECK: %s", (success && ahrs_present) ? "OK" : "FAIL"); set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_AHRS, ahrs_present, true, success && ahrs_present, vehicle_status); set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_GPS, gps_present, enforce_gps_required, gps_success, vehicle_status); return success; }
fix preflight check spam
commander: fix preflight check spam
C++
bsd-3-clause
krbeverx/Firmware,acfloria/Firmware,krbeverx/Firmware,PX4/Firmware,krbeverx/Firmware,krbeverx/Firmware,acfloria/Firmware,PX4/Firmware,PX4/Firmware,acfloria/Firmware,krbeverx/Firmware,krbeverx/Firmware,acfloria/Firmware,acfloria/Firmware,acfloria/Firmware,PX4/Firmware,krbeverx/Firmware,PX4/Firmware,acfloria/Firmware,PX4/Firmware,PX4/Firmware
abd7d3f3004aa4194ec9ed7e4ff5b51b4af647b5
test/elgamal_test.cpp
test/elgamal_test.cpp
#include <cybozu/test.hpp> #include <cybozu/random_generator.hpp> #include <cybozu/crypto.hpp> #include <mcl/fp.hpp> #include <mcl/ecparam.hpp> #include <mcl/elgamal.hpp> struct TagZn; typedef mcl::FpT<> Fp; typedef mcl::FpT<TagZn> Zn; typedef mcl::EcT<Fp> Ec; typedef mcl::ElgamalT<Ec, Zn> ElgamalEc; const mcl::EcParam& para = mcl::ecparam::secp192k1; cybozu::RandomGenerator rg; CYBOZU_TEST_AUTO(testEc) { Fp::init(para.p); Zn::init(para.n); Ec::init(para.a, para.b); const Fp x0(para.gx); const Fp y0(para.gy); const size_t bitSize = Zn::getBitSize(); const Ec P(x0, y0); /* Zn = <P> */ ElgamalEc::PrivateKey prv; prv.init(P, bitSize, rg); const ElgamalEc::PublicKey& pub = prv.getPublicKey(); const int m1 = 12345; const int m2 = 17655; ElgamalEc::CipherText c1, c2; pub.enc(c1, m1, rg); pub.enc(c2, m2, rg); Zn dec1, dec2; prv.dec(dec1, c1); prv.dec(dec2, c2); // dec(enc) = id CYBOZU_TEST_EQUAL(dec1, m1); CYBOZU_TEST_EQUAL(dec2, m2); // iostream { ElgamalEc::PublicKey pub2; ElgamalEc::PrivateKey prv2; ElgamalEc::CipherText cc1, cc2; { std::stringstream ss; ss << prv; ss >> prv2; } Zn d; prv2.dec(d, c1); CYBOZU_TEST_EQUAL(d, m1); { std::stringstream ss; ss << c1; ss >> cc1; } d = 0; prv2.dec(d, cc1); CYBOZU_TEST_EQUAL(d, m1); { std::stringstream ss; ss << pub; ss >> pub2; } pub2.enc(cc2, m2, rg); prv.dec(d, cc2); CYBOZU_TEST_EQUAL(d, m2); } // enc(m1) enc(m2) = enc(m1 + m2) c1.add(c2); prv.dec(dec1, c1); CYBOZU_TEST_EQUAL(dec1, m1 + m2); // enc(m1) x = enc(m1 + x) const int x = 555; pub.add(c1, x); prv.dec(dec1, c1); CYBOZU_TEST_EQUAL(dec1, m1 + m2 + x); // rerandomize c1 = c2; pub.rerandomize(c1, rg); // verify c1 != c2 CYBOZU_TEST_ASSERT(c1.c1 != c2.c1); CYBOZU_TEST_ASSERT(c1.c2 != c2.c2); prv.dec(dec1, c1); // dec(c1) = dec(c2) CYBOZU_TEST_EQUAL(dec1, m2); // check neg { ElgamalEc::CipherText c; Zn m = 1234; pub.enc(c, m, rg); c.neg(); Zn dec; prv.dec(dec, c); CYBOZU_TEST_EQUAL(dec, -m); } // check mul { ElgamalEc::CipherText c; Zn m = 123; int x = 111; pub.enc(c, m, rg); Zn dec; prv.dec(dec, c); c.mul(x); prv.dec(dec, c); m *= x; CYBOZU_TEST_EQUAL(dec, m); } // check negative value for (int i = -10; i < 10; i++) { ElgamalEc::CipherText c; const Zn mm = i; pub.enc(c, mm, rg); Zn dec; prv.dec(dec, c, 1000); CYBOZU_TEST_EQUAL(dec, mm); } // isZeroMessage for (int m = 0; m < 10; m++) { ElgamalEc::CipherText c0; pub.enc(c0, m, rg); if (m == 0) { CYBOZU_TEST_ASSERT(prv.isZeroMessage(c0)); } else { CYBOZU_TEST_ASSERT(!prv.isZeroMessage(c0)); } } // zkp { ElgamalEc::Zkp zkp; ElgamalEc::CipherText c; // cybozu::Sha1 hash; cybozu::crypto::Hash hash(cybozu::crypto::Hash::N_SHA256); pub.encWithZkp(c, zkp, 0, hash, rg); CYBOZU_TEST_ASSERT(pub.verify(c, zkp, hash)); zkp.s0 += 1; CYBOZU_TEST_ASSERT(!pub.verify(c, zkp, hash)); pub.encWithZkp(c, zkp, 1, hash, rg); CYBOZU_TEST_ASSERT(pub.verify(c, zkp, hash)); zkp.s0 += 1; CYBOZU_TEST_ASSERT(!pub.verify(c, zkp, hash)); CYBOZU_TEST_EXCEPTION_MESSAGE(pub.encWithZkp(c, zkp, 2, hash, rg), cybozu::Exception, "encWithZkp"); } }
#include <cybozu/test.hpp> #include <cybozu/random_generator.hpp> #include <cybozu/crypto.hpp> #include <mcl/fp.hpp> #include <mcl/ecparam.hpp> #include <mcl/elgamal.hpp> struct TagZn; typedef mcl::FpT<> Fp; typedef mcl::FpT<TagZn> Zn; typedef mcl::EcT<Fp> Ec; typedef mcl::ElgamalT<Ec, Zn> ElgamalEc; const mcl::EcParam& para = mcl::ecparam::secp192k1; cybozu::RandomGenerator rg; CYBOZU_TEST_AUTO(testEc) { Fp::init(para.p); Zn::init(para.n); Ec::init(para.a, para.b); const Fp x0(para.gx); const Fp y0(para.gy); const size_t bitSize = Zn::getBitSize(); const Ec P(x0, y0); /* Zn = <P> */ ElgamalEc::PrivateKey prv; prv.init(P, bitSize, rg); prv.setCache(0, 60000); const ElgamalEc::PublicKey& pub = prv.getPublicKey(); const int m1 = 12345; const int m2 = 17655; ElgamalEc::CipherText c1, c2; pub.enc(c1, m1, rg); pub.enc(c2, m2, rg); Zn dec1, dec2; prv.dec(dec1, c1); prv.dec(dec2, c2); // dec(enc) = id CYBOZU_TEST_EQUAL(dec1, m1); CYBOZU_TEST_EQUAL(dec2, m2); CYBOZU_TEST_EQUAL(prv.dec(c1), m1); CYBOZU_TEST_EQUAL(prv.dec(c2), m2); // iostream { ElgamalEc::PublicKey pub2; ElgamalEc::PrivateKey prv2; ElgamalEc::CipherText cc1, cc2; { std::stringstream ss; ss << prv; ss >> prv2; } Zn d; prv2.dec(d, c1); CYBOZU_TEST_EQUAL(d, m1); { std::stringstream ss; ss << c1; ss >> cc1; } d = 0; prv2.dec(d, cc1); CYBOZU_TEST_EQUAL(d, m1); { std::stringstream ss; ss << pub; ss >> pub2; } pub2.enc(cc2, m2, rg); prv.dec(d, cc2); CYBOZU_TEST_EQUAL(d, m2); } // enc(m1) enc(m2) = enc(m1 + m2) c1.add(c2); prv.dec(dec1, c1); CYBOZU_TEST_EQUAL(dec1, m1 + m2); // enc(m1) x = enc(m1 + x) const int x = 555; pub.add(c1, x); prv.dec(dec1, c1); CYBOZU_TEST_EQUAL(dec1, m1 + m2 + x); // rerandomize c1 = c2; pub.rerandomize(c1, rg); // verify c1 != c2 CYBOZU_TEST_ASSERT(c1.c1 != c2.c1); CYBOZU_TEST_ASSERT(c1.c2 != c2.c2); prv.dec(dec1, c1); // dec(c1) = dec(c2) CYBOZU_TEST_EQUAL(dec1, m2); // check neg { ElgamalEc::CipherText c; Zn m = 1234; pub.enc(c, m, rg); c.neg(); Zn dec; prv.dec(dec, c); CYBOZU_TEST_EQUAL(dec, -m); } // check mul { ElgamalEc::CipherText c; Zn m = 123; int x = 111; pub.enc(c, m, rg); Zn dec; prv.dec(dec, c); c.mul(x); prv.dec(dec, c); m *= x; CYBOZU_TEST_EQUAL(dec, m); } // check negative value for (int i = -10; i < 10; i++) { ElgamalEc::CipherText c; const Zn mm = i; pub.enc(c, mm, rg); Zn dec; prv.dec(dec, c, 1000); CYBOZU_TEST_EQUAL(dec, mm); } // isZeroMessage for (int m = 0; m < 10; m++) { ElgamalEc::CipherText c0; pub.enc(c0, m, rg); if (m == 0) { CYBOZU_TEST_ASSERT(prv.isZeroMessage(c0)); } else { CYBOZU_TEST_ASSERT(!prv.isZeroMessage(c0)); } } // zkp { ElgamalEc::Zkp zkp; ElgamalEc::CipherText c; // cybozu::Sha1 hash; cybozu::crypto::Hash hash(cybozu::crypto::Hash::N_SHA256); pub.encWithZkp(c, zkp, 0, hash, rg); CYBOZU_TEST_ASSERT(pub.verify(c, zkp, hash)); zkp.s0 += 1; CYBOZU_TEST_ASSERT(!pub.verify(c, zkp, hash)); pub.encWithZkp(c, zkp, 1, hash, rg); CYBOZU_TEST_ASSERT(pub.verify(c, zkp, hash)); zkp.s0 += 1; CYBOZU_TEST_ASSERT(!pub.verify(c, zkp, hash)); CYBOZU_TEST_EXCEPTION_MESSAGE(pub.encWithZkp(c, zkp, 2, hash, rg), cybozu::Exception, "encWithZkp"); } }
add test for setCache
add test for setCache
C++
bsd-3-clause
herumi/mcl,herumi/mcl,herumi/mcl,herumi/mcl,herumi/mcl,herumi/mcl,herumi/mcl,herumi/mcl
ced48beb6f554f8a8b9018ca1df1a4aa51940639
src/plugins/qt4projectmanager/qt-maemo/maemoconfigtestdialog.cpp
src/plugins/qt4projectmanager/qt-maemo/maemoconfigtestdialog.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** GNU Lesser General Public License Usage ** ** This file may be used 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. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "maemoconfigtestdialog.h" #include "ui_maemoconfigtestdialog.h" #include "maemodeviceconfigurations.h" #include "maemoglobal.h" #include "maemousedportsgatherer.h" #include <utils/ssh/sshremoteprocessrunner.h> #include <QtGui/QPalette> #include <QtGui/QPushButton> using namespace Utils; namespace Qt4ProjectManager { namespace Internal { MaemoConfigTestDialog::MaemoConfigTestDialog(const MaemoDeviceConfig::ConstPtr &config, QWidget *parent) : QDialog(parent) , m_ui(new Ui_MaemoConfigTestDialog) , m_config(config) , m_portsGatherer(new MaemoUsedPortsGatherer(this)) { setAttribute(Qt::WA_DeleteOnClose); m_ui->setupUi(this); m_closeButton = m_ui->buttonBox->button(QDialogButtonBox::Close); connect(m_closeButton, SIGNAL(clicked()), SLOT(stopConfigTest())); connect(m_portsGatherer, SIGNAL(error(QString)), SLOT(handlePortListFailure(QString))); connect(m_portsGatherer, SIGNAL(portListReady()), SLOT(handlePortListReady())); startConfigTest(); } MaemoConfigTestDialog::~MaemoConfigTestDialog() { stopConfigTest(); } void MaemoConfigTestDialog::startConfigTest() { if (m_testProcessRunner) return; m_currentTest = GeneralTest; const QString testingText = m_config->type() == MaemoDeviceConfig::Emulator ? tr("Testing configuration. This may take a while.") : tr("Testing configuration..."); m_ui->testResultEdit->setPlainText(testingText); m_closeButton->setText(tr("Stop Test")); // We need to explicitly create the connection here, because the other // constructor uses a managed connection, i.e. it might re-use an // existing one, which we explicitly don't want here. m_testProcessRunner = SshRemoteProcessRunner::create(SshConnection::create(m_config->sshParameters())); connect(m_testProcessRunner.data(), SIGNAL(connectionError(Utils::SshError)), this, SLOT(handleConnectionError())); connect(m_testProcessRunner.data(), SIGNAL(processClosed(int)), this, SLOT(handleTestProcessFinished(int))); connect(m_testProcessRunner.data(), SIGNAL(processOutputAvailable(QByteArray)), this, SLOT(processSshOutput(QByteArray))); const QLatin1String sysInfoCmd("uname -rsm"); QString command = sysInfoCmd; QString qtInfoCmd; switch (MaemoGlobal::packagingSystem(m_config->osVersion())) { case MaemoGlobal::Rpm: qtInfoCmd = QLatin1String("rpm -qa 'libqt*' " "--queryformat '%{NAME} %{VERSION}\\n'"); break; case MaemoGlobal::Dpkg: qtInfoCmd = QLatin1String("dpkg-query -W -f " "'${Package} ${Version} ${Status}\n' 'libqt*' |grep ' installed$'"); break; default: break; } if (!qtInfoCmd.isEmpty()) command += QLatin1String(" && ") + qtInfoCmd; m_testProcessRunner->run(command.toUtf8()); } void MaemoConfigTestDialog::handleConnectionError() { if (!m_testProcessRunner) return; QString output = tr("Could not connect to host: %1") .arg(m_testProcessRunner->connection()->errorString()); if (m_config->type() == MaemoDeviceConfig::Emulator) output += tr("\nDid you start Qemu?"); m_ui->testResultEdit->setPlainText(output); stopConfigTest(); } void MaemoConfigTestDialog::handleTestProcessFinished(int exitStatus) { if (!m_testProcessRunner) return; Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart || exitStatus == SshRemoteProcess::KilledBySignal || exitStatus == SshRemoteProcess::ExitedNormally); if (m_currentTest == GeneralTest) handleGeneralTestResult(exitStatus); else handleMadDeveloperTestResult(exitStatus); } void MaemoConfigTestDialog::handleGeneralTestResult(int exitStatus) { if (exitStatus != SshRemoteProcess::ExitedNormally || m_testProcessRunner->process()->exitCode() != 0) { m_ui->testResultEdit->setPlainText(tr("Remote process failed: %1") .arg(m_testProcessRunner->process()->errorString())); } else { const QString &output = parseTestOutput(); if (!m_qtVersionOk) { m_ui->errorLabel->setText(tr("Qt version mismatch! " " Expected Qt on device: 4.6.2 or later.")); } m_ui->testResultEdit->setPlainText(output); } switch (m_config->osVersion()) { case MaemoDeviceConfig::Maemo5: case MaemoDeviceConfig::Maemo6: case MaemoDeviceConfig::Meego: m_currentTest = MadDeveloperTest; disconnect(m_testProcessRunner.data(), SIGNAL(processOutputAvailable(QByteArray)), this, SLOT(processSshOutput(QByteArray))); m_testProcessRunner->run("test -x " + MaemoGlobal::devrootshPath().toUtf8()); break; default: testPorts(); } } void MaemoConfigTestDialog::handleMadDeveloperTestResult(int exitStatus) { if (exitStatus != SshRemoteProcess::ExitedNormally) { m_ui->testResultEdit->setPlainText(tr("Remote process failed: %1") .arg(m_testProcessRunner->process()->errorString())); } else if (m_testProcessRunner->process()->exitCode() != 0) { QString errorMsg = m_ui->errorLabel->text() + QLatin1String("<br>") + tr("%1 is not installed.<br>You will not be able to deploy " "to this device.") .arg(MaemoGlobal::madDeveloperUiName(m_config->osVersion())); if (m_config->osVersion() == MaemoDeviceConfig::Maemo6) { errorMsg += QLatin1String("<br>") + tr("Please switch the device to developer mode via Settings -> Security."); } m_ui->errorLabel->setText(errorMsg); } testPorts(); } void MaemoConfigTestDialog::handlePortListFailure(const QString &errMsg) { m_ui->testResultEdit->appendPlainText(tr("Error retrieving list of used ports: %1") .arg(errMsg)); finish(); } void MaemoConfigTestDialog::handlePortListReady() { const QList<int> &usedPorts = m_portsGatherer->usedPorts(); QString output; if (usedPorts.isEmpty()) { output = tr("All specified ports are available."); } else { output = tr("The following supposedly free ports are being used on the device:"); foreach (const int port, usedPorts) output += QLatin1Char(' ') + QString::number(port); } m_ui->testResultEdit->appendPlainText(output); finish(); } void MaemoConfigTestDialog::testPorts() { if (m_config->freePorts().hasMore()) m_portsGatherer->start(m_testProcessRunner->connection(), m_config); else finish(); } void MaemoConfigTestDialog::finish() { if (m_ui->errorLabel->text().isEmpty()) { QPalette palette = m_ui->errorLabel->palette(); palette.setColor(m_ui->errorLabel->foregroundRole(), QColor(QLatin1String("blue"))); m_ui->errorLabel->setPalette(palette); m_ui->errorLabel->setText(tr("Device configuration okay.")); } stopConfigTest(); } void MaemoConfigTestDialog::stopConfigTest() { if (m_testProcessRunner) { disconnect(m_testProcessRunner.data(), 0, this, 0); m_testProcessRunner = SshRemoteProcessRunner::Ptr(); } m_deviceTestOutput.clear(); m_closeButton->setText(tr("Close")); } void MaemoConfigTestDialog::processSshOutput(const QByteArray &output) { m_deviceTestOutput.append(QString::fromUtf8(output)); } QString MaemoConfigTestDialog::parseTestOutput() { m_qtVersionOk = false; QString output; const QRegExp unamePattern(QLatin1String("Linux (\\S+)\\s(\\S+)")); int index = unamePattern.indexIn(m_deviceTestOutput); if (index == -1) { output = tr("Device configuration test failed: Unexpected output:\n%1") .arg(m_deviceTestOutput); return output; } output = tr("Hardware architecture: %1\n").arg(unamePattern.cap(2)); output.append(tr("Kernel version: %1\n").arg(unamePattern.cap(1))); if (m_config->osVersion() == MaemoDeviceConfig::GenericLinux) { m_qtVersionOk = true; return output; } QString patternString; switch (MaemoGlobal::packagingSystem(m_config->osVersion())) { case MaemoGlobal::Rpm: patternString = QLatin1String("(libqt\\S+) ((\\d+)\\.(\\d+)\\.(\\d+))"); break; case MaemoGlobal::Dpkg: patternString = QLatin1String("(\\S+) (\\S*(\\d+)\\.(\\d+)\\.(\\d+)\\S*) \\S+ \\S+ \\S+"); break; default: return output; } const QRegExp packagePattern(patternString); index = packagePattern.indexIn(m_deviceTestOutput); if (index == -1) { output.append(tr("No Qt packages installed.")); return output; } output.append(tr("List of installed Qt packages:") + QLatin1Char('\n')); do { output.append(QLatin1Char('\t') + packagePattern.cap(1) + QLatin1Char(' ') + packagePattern.cap(2) + QLatin1Char('\n')); index = packagePattern.indexIn(m_deviceTestOutput, index + packagePattern.cap(0).length()); if (!m_qtVersionOk && QT_VERSION_CHECK(packagePattern.cap(3).toInt(), packagePattern.cap(4).toInt(), packagePattern.cap(5).toInt()) >= 0x040602) { m_qtVersionOk = true; } } while (index != -1); return output; } } // namespace Internal } // namespace Qt4ProjectManager
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** GNU Lesser General Public License Usage ** ** This file may be used 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. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "maemoconfigtestdialog.h" #include "ui_maemoconfigtestdialog.h" #include "maemodeviceconfigurations.h" #include "maemoglobal.h" #include "maemousedportsgatherer.h" #include <utils/ssh/sshremoteprocessrunner.h> #include <QtGui/QPalette> #include <QtGui/QPushButton> using namespace Utils; namespace Qt4ProjectManager { namespace Internal { MaemoConfigTestDialog::MaemoConfigTestDialog(const MaemoDeviceConfig::ConstPtr &config, QWidget *parent) : QDialog(parent) , m_ui(new Ui_MaemoConfigTestDialog) , m_config(config) , m_portsGatherer(new MaemoUsedPortsGatherer(this)) { setAttribute(Qt::WA_DeleteOnClose); m_ui->setupUi(this); m_closeButton = m_ui->buttonBox->button(QDialogButtonBox::Close); connect(m_closeButton, SIGNAL(clicked()), SLOT(stopConfigTest())); connect(m_portsGatherer, SIGNAL(error(QString)), SLOT(handlePortListFailure(QString))); connect(m_portsGatherer, SIGNAL(portListReady()), SLOT(handlePortListReady())); startConfigTest(); } MaemoConfigTestDialog::~MaemoConfigTestDialog() { stopConfigTest(); } void MaemoConfigTestDialog::startConfigTest() { if (m_testProcessRunner) return; m_currentTest = GeneralTest; const QString testingText = m_config->type() == MaemoDeviceConfig::Emulator ? tr("Testing configuration. This may take a while.") : tr("Testing configuration..."); m_ui->testResultEdit->setPlainText(testingText); m_closeButton->setText(tr("Stop Test")); // We need to explicitly create the connection here, because the other // constructor uses a managed connection, i.e. it might re-use an // existing one, which we explicitly don't want here. m_testProcessRunner = SshRemoteProcessRunner::create(SshConnection::create(m_config->sshParameters())); connect(m_testProcessRunner.data(), SIGNAL(connectionError(Utils::SshError)), this, SLOT(handleConnectionError())); connect(m_testProcessRunner.data(), SIGNAL(processClosed(int)), this, SLOT(handleTestProcessFinished(int))); connect(m_testProcessRunner.data(), SIGNAL(processOutputAvailable(QByteArray)), this, SLOT(processSshOutput(QByteArray))); const QLatin1String sysInfoCmd("uname -rsm"); QString command = sysInfoCmd; QString qtInfoCmd; switch (MaemoGlobal::packagingSystem(m_config->osVersion())) { case MaemoGlobal::Rpm: qtInfoCmd = QLatin1String("rpm -qa 'libqt*' " "--queryformat '%{NAME} %{VERSION}\\n'"); break; case MaemoGlobal::Dpkg: qtInfoCmd = QLatin1String("dpkg-query -W -f " "'${Package} ${Version} ${Status}\n' 'libqt*' |grep ' installed$'"); break; default: break; } if (!qtInfoCmd.isEmpty()) command += QLatin1String(" && ") + qtInfoCmd; m_testProcessRunner->run(command.toUtf8()); } void MaemoConfigTestDialog::handleConnectionError() { if (!m_testProcessRunner) return; QString output = tr("Could not connect to host: %1") .arg(m_testProcessRunner->connection()->errorString()); if (m_config->type() == MaemoDeviceConfig::Emulator) output += tr("\nDid you start Qemu?"); m_ui->testResultEdit->setPlainText(output); stopConfigTest(); } void MaemoConfigTestDialog::handleTestProcessFinished(int exitStatus) { if (!m_testProcessRunner) return; Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart || exitStatus == SshRemoteProcess::KilledBySignal || exitStatus == SshRemoteProcess::ExitedNormally); if (m_currentTest == GeneralTest) handleGeneralTestResult(exitStatus); else handleMadDeveloperTestResult(exitStatus); } void MaemoConfigTestDialog::handleGeneralTestResult(int exitStatus) { if (exitStatus != SshRemoteProcess::ExitedNormally || m_testProcessRunner->process()->exitCode() != 0) { m_ui->testResultEdit->setPlainText(tr("Remote process failed: %1") .arg(m_testProcessRunner->process()->errorString())); } else { const QString &output = parseTestOutput(); if (!m_qtVersionOk) { m_ui->errorLabel->setText(tr("Qt version mismatch! " " Expected Qt on device: 4.6.2 or later.")); } m_ui->testResultEdit->setPlainText(output); } switch (m_config->osVersion()) { case MaemoDeviceConfig::Maemo5: case MaemoDeviceConfig::Maemo6: case MaemoDeviceConfig::Meego: m_currentTest = MadDeveloperTest; disconnect(m_testProcessRunner.data(), SIGNAL(processOutputAvailable(QByteArray)), this, SLOT(processSshOutput(QByteArray))); m_testProcessRunner->run("test -x " + MaemoGlobal::devrootshPath().toUtf8()); break; default: testPorts(); } } void MaemoConfigTestDialog::handleMadDeveloperTestResult(int exitStatus) { if (exitStatus != SshRemoteProcess::ExitedNormally) { m_ui->testResultEdit->setPlainText(tr("Remote process failed: %1") .arg(m_testProcessRunner->process()->errorString())); } else if (m_testProcessRunner->process()->exitCode() != 0) { QString errorMsg = m_ui->errorLabel->text() + QLatin1String("<br>") + tr("%1 is not installed.<br>You will not be able to deploy " "to this device.") .arg(MaemoGlobal::madDeveloperUiName(m_config->osVersion())); if (m_config->osVersion() == MaemoDeviceConfig::Maemo6) { errorMsg += QLatin1String("<br>") + tr("Please switch the device to developer mode via Settings -> Security."); } m_ui->errorLabel->setText(errorMsg); } testPorts(); } void MaemoConfigTestDialog::handlePortListFailure(const QString &errMsg) { m_ui->testResultEdit->appendPlainText(tr("Error retrieving list of used ports: %1") .arg(errMsg)); finish(); } void MaemoConfigTestDialog::handlePortListReady() { const QList<int> &usedPorts = m_portsGatherer->usedPorts(); QString output; if (usedPorts.isEmpty()) { output = tr("All specified ports are available."); } else { output = tr("The following supposedly free ports are being used on the device:"); foreach (const int port, usedPorts) output += QLatin1Char(' ') + QString::number(port); } m_ui->testResultEdit->appendPlainText(output); finish(); } void MaemoConfigTestDialog::testPorts() { if (m_config->freePorts().hasMore()) m_portsGatherer->start(m_testProcessRunner->connection(), m_config); else finish(); } void MaemoConfigTestDialog::finish() { if (m_ui->errorLabel->text().isEmpty()) { QPalette palette = m_ui->errorLabel->palette(); palette.setColor(m_ui->errorLabel->foregroundRole(), QColor(QLatin1String("blue"))); m_ui->errorLabel->setPalette(palette); m_ui->errorLabel->setText(tr("Device configuration okay.")); } stopConfigTest(); } void MaemoConfigTestDialog::stopConfigTest() { if (m_testProcessRunner) { disconnect(m_testProcessRunner.data(), 0, this, 0); m_testProcessRunner = SshRemoteProcessRunner::Ptr(); } m_deviceTestOutput.clear(); m_closeButton->setText(tr("Close")); } void MaemoConfigTestDialog::processSshOutput(const QByteArray &output) { m_deviceTestOutput.append(QString::fromUtf8(output)); } QString MaemoConfigTestDialog::parseTestOutput() { m_qtVersionOk = false; QString output; const QRegExp unamePattern(QLatin1String("Linux (\\S+)\\s(\\S+)")); int index = unamePattern.indexIn(m_deviceTestOutput); if (index == -1) { output = tr("Device configuration test failed: Unexpected output:\n%1") .arg(m_deviceTestOutput); return output; } output = tr("Hardware architecture: %1\n").arg(unamePattern.cap(2)); output.append(tr("Kernel version: %1\n").arg(unamePattern.cap(1))); QString patternString; switch (MaemoGlobal::packagingSystem(m_config->osVersion())) { case MaemoGlobal::Rpm: patternString = QLatin1String("(libqt\\S+) ((\\d+)\\.(\\d+)\\.(\\d+))"); break; case MaemoGlobal::Dpkg: patternString = QLatin1String("(\\S+) (\\S*(\\d+)\\.(\\d+)\\.(\\d+)\\S*) \\S+ \\S+ \\S+"); break; default: m_qtVersionOk = true; return output; } const QRegExp packagePattern(patternString); index = packagePattern.indexIn(m_deviceTestOutput); if (index == -1) { output.append(tr("No Qt packages installed.")); return output; } output.append(tr("List of installed Qt packages:") + QLatin1Char('\n')); do { output.append(QLatin1Char('\t') + packagePattern.cap(1) + QLatin1Char(' ') + packagePattern.cap(2) + QLatin1Char('\n')); index = packagePattern.indexIn(m_deviceTestOutput, index + packagePattern.cap(0).length()); if (!m_qtVersionOk && QT_VERSION_CHECK(packagePattern.cap(3).toInt(), packagePattern.cap(4).toInt(), packagePattern.cap(5).toInt()) >= 0x040602) { m_qtVersionOk = true; } } while (index != -1); return output; } } // namespace Internal } // namespace Qt4ProjectManager
Fix device configuration dialog for all OS types.
Maemo: Fix device configuration dialog for all OS types. There could potentially be types other than GenericLinux that don't use dpkg or rpm. Change-Id: I62a03aa1f532a4f589be8e43e07410beb1370cb2 Reviewed-on: http://codereview.qt.nokia.com/26 Reviewed-by: Christian Kandeler <[email protected]>
C++
lgpl-2.1
danimo/qt-creator,jonnor/qt-creator,richardmg/qtcreator,renatofilho/QtCreator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,colede/qtcreator,omniacreator/qtcreator,richardmg/qtcreator,martyone/sailfish-qtcreator,danimo/qt-creator,hdweiss/qt-creator-visualizer,dmik/qt-creator-os2,azat/qtcreator,omniacreator/qtcreator,renatofilho/QtCreator,Distrotech/qtcreator,xianian/qt-creator,maui-packages/qt-creator,martyone/sailfish-qtcreator,KDAB/KDAB-Creator,martyone/sailfish-qtcreator,dmik/qt-creator-os2,KDAB/KDAB-Creator,colede/qtcreator,dmik/qt-creator-os2,pcacjr/qt-creator,dmik/qt-creator-os2,hdweiss/qt-creator-visualizer,KDE/android-qt-creator,duythanhphan/qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,danimo/qt-creator,richardmg/qtcreator,KDAB/KDAB-Creator,AltarBeastiful/qt-creator,kuba1/qtcreator,omniacreator/qtcreator,syntheticpp/qt-creator,richardmg/qtcreator,darksylinc/qt-creator,bakaiadam/collaborative_qt_creator,syntheticpp/qt-creator,amyvmiwei/qt-creator,maui-packages/qt-creator,amyvmiwei/qt-creator,malikcjm/qtcreator,darksylinc/qt-creator,colede/qtcreator,darksylinc/qt-creator,pcacjr/qt-creator,AltarBeastiful/qt-creator,malikcjm/qtcreator,dmik/qt-creator-os2,ostash/qt-creator-i18n-uk,darksylinc/qt-creator,darksylinc/qt-creator,duythanhphan/qt-creator,kuba1/qtcreator,renatofilho/QtCreator,martyone/sailfish-qtcreator,syntheticpp/qt-creator,maui-packages/qt-creator,pcacjr/qt-creator,darksylinc/qt-creator,duythanhphan/qt-creator,kuba1/qtcreator,malikcjm/qtcreator,pcacjr/qt-creator,jonnor/qt-creator,pcacjr/qt-creator,syntheticpp/qt-creator,KDAB/KDAB-Creator,farseerri/git_code,KDE/android-qt-creator,danimo/qt-creator,danimo/qt-creator,bakaiadam/collaborative_qt_creator,duythanhphan/qt-creator,KDE/android-qt-creator,bakaiadam/collaborative_qt_creator,maui-packages/qt-creator,kuba1/qtcreator,ostash/qt-creator-i18n-uk,renatofilho/QtCreator,ostash/qt-creator-i18n-uk,malikcjm/qtcreator,azat/qtcreator,omniacreator/qtcreator,jonnor/qt-creator,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,Distrotech/qtcreator,farseerri/git_code,kuba1/qtcreator,amyvmiwei/qt-creator,kuba1/qtcreator,bakaiadam/collaborative_qt_creator,martyone/sailfish-qtcreator,duythanhphan/qt-creator,danimo/qt-creator,farseerri/git_code,danimo/qt-creator,KDE/android-qt-creator,Distrotech/qtcreator,danimo/qt-creator,kuba1/qtcreator,jonnor/qt-creator,syntheticpp/qt-creator,hdweiss/qt-creator-visualizer,amyvmiwei/qt-creator,omniacreator/qtcreator,renatofilho/QtCreator,omniacreator/qtcreator,KDE/android-qt-creator,Distrotech/qtcreator,richardmg/qtcreator,amyvmiwei/qt-creator,farseerri/git_code,malikcjm/qtcreator,colede/qtcreator,AltarBeastiful/qt-creator,KDAB/KDAB-Creator,AltarBeastiful/qt-creator,azat/qtcreator,xianian/qt-creator,KDE/android-qt-creator,xianian/qt-creator,ostash/qt-creator-i18n-uk,martyone/sailfish-qtcreator,ostash/qt-creator-i18n-uk,xianian/qt-creator,richardmg/qtcreator,duythanhphan/qt-creator,maui-packages/qt-creator,pcacjr/qt-creator,maui-packages/qt-creator,xianian/qt-creator,Distrotech/qtcreator,jonnor/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,renatofilho/QtCreator,colede/qtcreator,amyvmiwei/qt-creator,malikcjm/qtcreator,hdweiss/qt-creator-visualizer,hdweiss/qt-creator-visualizer,azat/qtcreator,danimo/qt-creator,amyvmiwei/qt-creator,hdweiss/qt-creator-visualizer,darksylinc/qt-creator,malikcjm/qtcreator,dmik/qt-creator-os2,farseerri/git_code,farseerri/git_code,bakaiadam/collaborative_qt_creator,xianian/qt-creator,richardmg/qtcreator,AltarBeastiful/qt-creator,ostash/qt-creator-i18n-uk,azat/qtcreator,pcacjr/qt-creator,kuba1/qtcreator,colede/qtcreator,dmik/qt-creator-os2,kuba1/qtcreator,bakaiadam/collaborative_qt_creator,KDE/android-qt-creator,azat/qtcreator,KDE/android-qt-creator,farseerri/git_code,xianian/qt-creator,darksylinc/qt-creator,jonnor/qt-creator,ostash/qt-creator-i18n-uk,xianian/qt-creator,bakaiadam/collaborative_qt_creator,syntheticpp/qt-creator,farseerri/git_code,martyone/sailfish-qtcreator,omniacreator/qtcreator,duythanhphan/qt-creator,amyvmiwei/qt-creator,maui-packages/qt-creator,colede/qtcreator,KDAB/KDAB-Creator,Distrotech/qtcreator
df57df94f83410d7a97b8eda508b4fa7aa5e5f0e
paddle/fluid/operators/grid_sampler_op.cc
paddle/fluid/operators/grid_sampler_op.cc
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/grid_sampler_op.h" #include <memory> #include <string> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/op_version_registry.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cudnn_helper.h" #endif #ifdef PADDLE_WITH_HIP #include "paddle/fluid/platform/miopen_helper.h" #endif namespace paddle { namespace operators { using Tensor = framework::Tensor; class GridSampleOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "GridSampler"); OP_INOUT_CHECK(ctx->HasInput("Grid"), "Input", "Grid", "GridSampler"); OP_INOUT_CHECK(ctx->HasOutput("Output"), "Output", "Output", "GridSampler"); auto x_dims = ctx->GetInputDim("X"); auto grid_dims = ctx->GetInputDim("Grid"); PADDLE_ENFORCE_EQ(x_dims.size(), 4, platform::errors::InvalidArgument( "Input(X) of GridSampleOp should be 4-D Tensor, but " "received X dimension size(%d)", x_dims.size())); PADDLE_ENFORCE_EQ(grid_dims.size(), 4, platform::errors::InvalidArgument( "Input(Grid) of GridSampleOp should be 4-D Tensor, " "but received X dimension size(%d)", grid_dims.size())); if (ctx->IsRuntime() || grid_dims[3] > 0) { PADDLE_ENFORCE_EQ( grid_dims[3], 2, platform::errors::InvalidArgument( "Input(Grid) dimension[3] should be 2, but received %d", grid_dims[3])); } if (ctx->IsRuntime()) { PADDLE_ENFORCE_EQ( grid_dims[0], x_dims[0], platform::errors::InvalidArgument( "Input(X) and Input(Grid) dimension[0] should be equal, but " "received X dimension[0](%d) != Grid dimension[0](%d)", x_dims[0], grid_dims[0])); } ctx->SetOutputDim("Output", {x_dims[0], x_dims[1], grid_dims[1], grid_dims[2]}); ctx->ShareLoD("X", "Output"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { framework::LibraryType library_{framework::LibraryType::kPlain}; #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) if (platform::CanCUDNNBeUsed(ctx)) { library_ = framework::LibraryType::kCUDNN; } #endif return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace(), framework::DataLayout::kAnyLayout, library_); } }; class GridSampleOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(Tensor) The input data of GridSampleOp, " "This is a 4-D tensor with shape of [N, C, H, W]"); AddInput( "Grid", "(Tensor) The input grid of GridSampleOp generated by AffineGridOp, " "This is a 4-D tensor with shape of [N, H, W, 2] is the concatenation " "of x and y coordinates with shape [N, H, W] in last dimension"); AddOutput("Output", "(Tensor) Output tensor with shape [N, C, H, W]"); AddAttr<bool>( "use_cudnn", "(bool, default true) Only used in cudnn kernel, need install cudnn") .SetDefault(true); AddAttr<bool>( "align_corners", "(bool, default true) If align_corners is true, it will project" "-1 and 1 to the centers of the corner pixels. Otherwise, it will " "project" "-1 and 1 to the image edges.") .SetDefault(true); AddAttr<std::string>( "mode", "(bool, default true) The interpolation method which can be 'bilinear'" " or 'nearest'.") .SetDefault("bilinear"); AddAttr<std::string>( "padding_mode", "(bool, default true) The padding method used when source" "index is out of input images. It can be 'zeros', 'reflection' and " "'border'.") .SetDefault("zeros"); AddComment(R"DOC( This operation samples input X by using bilinear or nearest interpolation based on flow field grid, which is usually generated by affine_grid. The grid of shape [N, H, W, 2] is the concatenation of (grid_x, grid_y) coordinates with shape [N, H, W] each, where grid_x is indexing the 4th dimension (in width dimension) of input data x and grid_y is indexing the 3rd dimension (in height dimension), finally results is the bilinear interpolation value or nearest value of 4 nearest corner points. For bilinear interpolation mode: Step 1: Get (x, y) grid coordinates and scale to [0, H-1/W-1]. grid_x = 0.5 * (grid[:, :, :, 0] + 1) * (W - 1) grid_y = 0.5 * (grid[:, :, :, 1] + 1) * (H - 1) Step 2: Indices input data X with grid (x, y) in each [H, W] area, and bilinear interpolate point value by 4 nearest points. wn ------- y_n ------- en | | | | d_n | | | | x_w --d_w-- grid--d_e-- x_e | | | | d_s | | | | ws ------- y_s ------- wn x_w = floor(x) // west side x coord x_e = x_w + 1 // east side x coord y_n = floor(y) // north side y coord y_s = y_s + 1 // south side y coord d_w = grid_x - x_w // distance to west side d_e = x_e - grid_x // distance to east side d_n = grid_y - y_n // distance to north side d_s = y_s - grid_y // distance to south side wn = X[:, :, y_n, x_w] // north-west point value en = X[:, :, y_n, x_e] // north-east point value ws = X[:, :, y_s, x_w] // south-east point value es = X[:, :, y_s, x_w] // north-east point value output = wn * d_e * d_s + en * d_w * d_s + ws * d_e * d_n + es * d_w * d_n )DOC"); } }; class GridSampleOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output", framework::GradVarName("X"), "grid_sampler"); auto input_dims = ctx->GetInputDim("X"); auto grid_dims = ctx->GetInputDim("Grid"); if (ctx->HasOutput(framework::GradVarName("X"))) { ctx->SetOutputDim(framework::GradVarName("X"), input_dims); } if (ctx->HasOutput(framework::GradVarName("Grid"))) { ctx->SetOutputDim(framework::GradVarName("Grid"), grid_dims); } } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { framework::LibraryType library_{framework::LibraryType::kPlain}; #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) if (platform::CanCUDNNBeUsed(ctx)) { library_ = framework::LibraryType::kCUDNN; } #endif return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace(), framework::DataLayout::kAnyLayout, library_); } }; template <typename T> class GridSampleGradMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("grid_sampler_grad"); op->SetInput("X", this->Input("X")); op->SetInput("Grid", this->Input("Grid")); op->SetInput(framework::GradVarName("Output"), this->OutputGrad("Output")); op->SetAttrMap(this->Attrs()); op->SetOutput(framework::GradVarName("X"), this->InputGrad("X")); op->SetOutput(framework::GradVarName("Grid"), this->InputGrad("Grid")); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(grid_sampler, ops::GridSampleOp, ops::GridSampleOpMaker, ops::GridSampleGradMaker<paddle::framework::OpDesc>, ops::GridSampleGradMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(grid_sampler_grad, ops::GridSampleOpGrad); REGISTER_OP_CPU_KERNEL( grid_sampler, ops::GridSampleOpKernel<paddle::platform::CPUDeviceContext, float>, ops::GridSampleOpKernel<paddle::platform::CPUDeviceContext, double>); REGISTER_OP_CPU_KERNEL( grid_sampler_grad, ops::GridSampleGradOpKernel<paddle::platform::CPUDeviceContext, float>, ops::GridSampleGradOpKernel<paddle::platform::CPUDeviceContext, double>); REGISTER_OP_VERSION(grid_sampler) .AddCheckpoint( R"ROC( Upgrade grid_sampler add a new attribute [mode]. )ROC", paddle::framework::compatible::OpVersionDesc().NewAttr( "mode", "In order to specify interpolation mode", "bilinear"));
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/grid_sampler_op.h" #include <memory> #include <string> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/op_version_registry.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cudnn_helper.h" #endif #ifdef PADDLE_WITH_HIP #include "paddle/fluid/platform/miopen_helper.h" #endif namespace paddle { namespace operators { using Tensor = framework::Tensor; class GridSampleOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "GridSampler"); OP_INOUT_CHECK(ctx->HasInput("Grid"), "Input", "Grid", "GridSampler"); OP_INOUT_CHECK(ctx->HasOutput("Output"), "Output", "Output", "GridSampler"); auto x_dims = ctx->GetInputDim("X"); auto grid_dims = ctx->GetInputDim("Grid"); PADDLE_ENFORCE_EQ(x_dims.size(), 4, platform::errors::InvalidArgument( "Input(X) of GridSampleOp should be 4-D Tensor, but " "received X dimension size(%d)", x_dims.size())); PADDLE_ENFORCE_EQ(grid_dims.size(), 4, platform::errors::InvalidArgument( "Input(Grid) of GridSampleOp should be 4-D Tensor, " "but received X dimension size(%d)", grid_dims.size())); if (ctx->IsRuntime() || grid_dims[3] > 0) { PADDLE_ENFORCE_EQ( grid_dims[3], 2, platform::errors::InvalidArgument( "Input(Grid) dimension[3] should be 2, but received %d", grid_dims[3])); } if (ctx->IsRuntime()) { PADDLE_ENFORCE_EQ( grid_dims[0], x_dims[0], platform::errors::InvalidArgument( "Input(X) and Input(Grid) dimension[0] should be equal, but " "received X dimension[0](%d) != Grid dimension[0](%d)", x_dims[0], grid_dims[0])); } ctx->SetOutputDim("Output", {x_dims[0], x_dims[1], grid_dims[1], grid_dims[2]}); ctx->ShareLoD("X", "Output"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { framework::LibraryType library_{framework::LibraryType::kPlain}; #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) if (platform::CanCUDNNBeUsed(ctx)) { library_ = framework::LibraryType::kCUDNN; } #endif return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace(), framework::DataLayout::kAnyLayout, library_); } }; class GridSampleOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(Tensor) The input data of GridSampleOp, " "This is a 4-D tensor with shape of [N, C, H, W]"); AddInput( "Grid", "(Tensor) The input grid of GridSampleOp generated by AffineGridOp, " "This is a 4-D tensor with shape of [N, H, W, 2] is the concatenation " "of x and y coordinates with shape [N, H, W] in last dimension"); AddOutput("Output", "(Tensor) Output tensor with shape [N, C, H, W]"); AddAttr<bool>( "use_cudnn", "(bool, default true) Only used in cudnn kernel, need install cudnn") .SetDefault(true) .AsExtra(); AddAttr<bool>( "align_corners", "(bool, default true) If align_corners is true, it will project" "-1 and 1 to the centers of the corner pixels. Otherwise, it will " "project" "-1 and 1 to the image edges.") .SetDefault(true); AddAttr<std::string>( "mode", "(bool, default true) The interpolation method which can be 'bilinear'" " or 'nearest'.") .SetDefault("bilinear"); AddAttr<std::string>( "padding_mode", "(bool, default true) The padding method used when source" "index is out of input images. It can be 'zeros', 'reflection' and " "'border'.") .SetDefault("zeros"); AddComment(R"DOC( This operation samples input X by using bilinear or nearest interpolation based on flow field grid, which is usually generated by affine_grid. The grid of shape [N, H, W, 2] is the concatenation of (grid_x, grid_y) coordinates with shape [N, H, W] each, where grid_x is indexing the 4th dimension (in width dimension) of input data x and grid_y is indexing the 3rd dimension (in height dimension), finally results is the bilinear interpolation value or nearest value of 4 nearest corner points. For bilinear interpolation mode: Step 1: Get (x, y) grid coordinates and scale to [0, H-1/W-1]. grid_x = 0.5 * (grid[:, :, :, 0] + 1) * (W - 1) grid_y = 0.5 * (grid[:, :, :, 1] + 1) * (H - 1) Step 2: Indices input data X with grid (x, y) in each [H, W] area, and bilinear interpolate point value by 4 nearest points. wn ------- y_n ------- en | | | | d_n | | | | x_w --d_w-- grid--d_e-- x_e | | | | d_s | | | | ws ------- y_s ------- wn x_w = floor(x) // west side x coord x_e = x_w + 1 // east side x coord y_n = floor(y) // north side y coord y_s = y_s + 1 // south side y coord d_w = grid_x - x_w // distance to west side d_e = x_e - grid_x // distance to east side d_n = grid_y - y_n // distance to north side d_s = y_s - grid_y // distance to south side wn = X[:, :, y_n, x_w] // north-west point value en = X[:, :, y_n, x_e] // north-east point value ws = X[:, :, y_s, x_w] // south-east point value es = X[:, :, y_s, x_w] // north-east point value output = wn * d_e * d_s + en * d_w * d_s + ws * d_e * d_n + es * d_w * d_n )DOC"); } }; class GridSampleOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output", framework::GradVarName("X"), "grid_sampler"); auto input_dims = ctx->GetInputDim("X"); auto grid_dims = ctx->GetInputDim("Grid"); if (ctx->HasOutput(framework::GradVarName("X"))) { ctx->SetOutputDim(framework::GradVarName("X"), input_dims); } if (ctx->HasOutput(framework::GradVarName("Grid"))) { ctx->SetOutputDim(framework::GradVarName("Grid"), grid_dims); } } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { framework::LibraryType library_{framework::LibraryType::kPlain}; #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) if (platform::CanCUDNNBeUsed(ctx)) { library_ = framework::LibraryType::kCUDNN; } #endif return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace(), framework::DataLayout::kAnyLayout, library_); } }; template <typename T> class GridSampleGradMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("grid_sampler_grad"); op->SetInput("X", this->Input("X")); op->SetInput("Grid", this->Input("Grid")); op->SetInput(framework::GradVarName("Output"), this->OutputGrad("Output")); op->SetAttrMap(this->Attrs()); op->SetOutput(framework::GradVarName("X"), this->InputGrad("X")); op->SetOutput(framework::GradVarName("Grid"), this->InputGrad("Grid")); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(grid_sampler, ops::GridSampleOp, ops::GridSampleOpMaker, ops::GridSampleGradMaker<paddle::framework::OpDesc>, ops::GridSampleGradMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(grid_sampler_grad, ops::GridSampleOpGrad); REGISTER_OP_CPU_KERNEL( grid_sampler, ops::GridSampleOpKernel<paddle::platform::CPUDeviceContext, float>, ops::GridSampleOpKernel<paddle::platform::CPUDeviceContext, double>); REGISTER_OP_CPU_KERNEL( grid_sampler_grad, ops::GridSampleGradOpKernel<paddle::platform::CPUDeviceContext, float>, ops::GridSampleGradOpKernel<paddle::platform::CPUDeviceContext, double>); REGISTER_OP_VERSION(grid_sampler) .AddCheckpoint( R"ROC( Upgrade grid_sampler add a new attribute [mode]. )ROC", paddle::framework::compatible::OpVersionDesc().NewAttr( "mode", "In order to specify interpolation mode", "bilinear"));
add AsExtra for grid_sampler_op (#35339)
add AsExtra for grid_sampler_op (#35339)
C++
apache-2.0
PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle
76586498f454c716c9d6fd38e1d7fea97e910ed9
test/include/test.hpp
test/include/test.hpp
#pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #include <catch.hpp> #pragma GCC diagnostic pop #include <pbf.hpp> extern std::string get_file_data(const std::string& filename);
#include <catch.hpp> #include <pbf.hpp> extern std::string get_file_data(const std::string& filename);
Revert "Disable -Wshadow for catch.hpp for GCC."
Revert "Disable -Wshadow for catch.hpp for GCC." This reverts commit b396b71b0edfe6652d74b10cad785090b0de17c2. It leads to more warnings than before...
C++
bsd-2-clause
mapbox/pbf.hpp,mapbox/pbf.hpp,mapbox/pbf.hpp
3e7d01e92e578abd042f4603e7eef110bae92111
test/dma_tp/dma_tp.cc
test/dma_tp/dma_tp.cc
#include <cstdio> #include <cstdlib> #include <cassert> #include <cstring> #include <time.h> #include "lowlevel.h" #include "lowlevel_impl.h" #include "channel.h" #define DIM_X 128 #define DIM_Y 128 #define DIM_Z 64 #define NUM_TEST 1 #define PATH_LEN 2 #define NUM_FIELDS 8 #define NUM_REQUESTS 64 #define MEM_KIND_SIZE 20 using namespace LegionRuntime::LowLevel; using namespace LegionRuntime::Accessor; using namespace LegionRuntime::Arrays; enum { TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0, WORKER_TASK = Processor::TASK_ID_FIRST_AVAILABLE+1, }; struct InputArgs { int argc; char **argv; }; InputArgs& get_input_args(void) { static InputArgs args; return args; } void initialize_region_data(Domain domain, RegionInstance inst, std::vector<size_t> field_order) { // TODO: fix it if (get_runtime()->get_instance_impl(inst)->memory.kind() == Memory::GPU_FB_MEM) return; RegionAccessor<AccessorType::Generic> acc = inst.get_accessor(); switch(domain.dim) { case 0: assert(false); break; case 1: { Rect<1> rect = domain.get_rect<1>(); int idx = 0; int read_data[NUM_FIELDS]; for(GenericPointInRectIterator<1> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { read_data[i] = idx * i; acc.write_untyped(DomainPoint::from_point<1>(pir.p), &read_data[i], sizeof(int), field_order[i] * sizeof(int)); } } break; } case 2: { Rect<2> rect = domain.get_rect<2>(); int idx = 0; int read_data[NUM_FIELDS]; for(GenericPointInRectIterator<2> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { read_data[i] = idx * i; acc.write_untyped(DomainPoint::from_point<2>(pir.p), &read_data[i], sizeof(int), field_order[i] * sizeof(int)); } } break; } case 3: { Rect<3> rect = domain.get_rect<3>(); int idx = 0; int read_data[NUM_FIELDS]; for(GenericPointInRectIterator<3> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { read_data[i] = idx * i; acc.write_untyped(DomainPoint::from_point<3>(pir.p), &read_data[i], sizeof(int), field_order[i] * sizeof(int)); } } break; } default: assert(false); } } bool verify_region_data(Domain domain, RegionInstance inst, std::vector<size_t> field_order) { RegionAccessor<AccessorType::Generic> acc = inst.get_accessor(); bool check = true; switch(domain.dim) { case 0: assert(false); break; case 1: { Rect<1> rect = domain.get_rect<1>(); int idx = 0; int read_data; for(GenericPointInRectIterator<1> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { acc.read_untyped(DomainPoint::from_point<1>(pir.p), &read_data, sizeof(int), field_order[i] * sizeof(int)); check = check && (read_data == idx * i); if (read_data != idx * i) { printf("read_data = %d, expected = %d\n", read_data, idx * i); assert(0); } } } break; } case 2: { Rect<2> rect = domain.get_rect<2>(); int idx = 0; int read_data; for(GenericPointInRectIterator<2> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { acc.read_untyped(DomainPoint::from_point<2>(pir.p), &read_data, sizeof(int), field_order[i] * sizeof(int)); check = check && (read_data == idx * i); } } break; } case 3: { Rect<3> rect = domain.get_rect<3>(); int idx = 0; int read_data; for(GenericPointInRectIterator<3> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { acc.read_untyped(DomainPoint::from_point<3>(pir.p), &read_data, sizeof(int), field_order[i] * sizeof(int)); check = check && (read_data == idx * i); } } break; } default: assert(false); } return check; } struct WorkerTaskArgs { Memory src_mem, dst_mem; }; void top_level_task(const void *args, size_t arglen, const void *user_data, size_t user_data_len, Processor p) { printf("top level task - DMA random tests\n"); bool only_remote = false; // Parse the input arguments #define INT_ARG(argname, varname) do { \ if(!strcmp((argv)[i], argname)) { \ varname = atoi((argv)[++i]); \ continue; \ } } while(0) #define BOOL_ARG(argname, varname) do { \ if(!strcmp((argv)[i], argname)) { \ varname = true; \ continue; \ } } while(0) { InputArgs &inputs = get_input_args(); char **argv = inputs.argv; for (int i = 1; i < inputs.argc; i++) { BOOL_ARG("-r", only_remote); } } #undef INT_ARG #undef BOOL_ARG Machine machine = Machine::get_machine(); std::set<Memory> all_mem, src_mem_set, dst_mem_set; machine.get_all_memories(all_mem); for(std::set<Memory>::iterator it = all_mem.begin(); it != all_mem.end(); it++) { if (gasnet_mynode() == ID(*it).node() && it->kind() != Memory::HDF_MEM && it->kind() != Memory::FILE_MEM) src_mem_set.insert(*it); if ((gasnet_mynode() != ID(*it).node() || !only_remote) && it->kind() != Memory::HDF_MEM && it->kind() != Memory::FILE_MEM) dst_mem_set.insert(*it); } Processor cur_proc = p; for(std::set<Memory>::iterator src_it = src_mem_set.begin(); src_it != src_mem_set.end(); src_it++) for(std::set<Memory>::iterator dst_it = dst_mem_set.begin(); dst_it != dst_mem_set.end(); dst_it++) { WorkerTaskArgs args; args.src_mem = *src_it; args.dst_mem = *dst_it; Event event = cur_proc.spawn(WORKER_TASK, &args, sizeof(args)); event.wait(); } printf("finish top level task......\n"); } void worker_task(const void *args, size_t arglen, const void *user_data, size_t user_data_len, Processor p) { printf("start worker task\n"); const WorkerTaskArgs& worker_args = *(const WorkerTaskArgs *)args; Memory src_mem = worker_args.src_mem, dst_mem = worker_args.dst_mem; std::vector<size_t> field_sizes; for (unsigned i = 0; i < NUM_FIELDS; i++) field_sizes.push_back(sizeof(int)); for (unsigned i = 0; i < NUM_TEST; i++) { printf("Test case #%u:\n", i); int dim = 3; Domain domain; switch (dim) { case 0: case 1: { Point<1> lo = make_point(0), hi = make_point(DIM_X - 1); Rect<1> rect(lo, hi); domain = Domain::from_rect<1>(rect); break; } case 2: { Point<2> lo = make_point(0, 0), hi = make_point(DIM_X - 1, DIM_Y - 1); Rect<2> rect(lo, hi); domain = Domain::from_rect<2>(rect); break; } case 3: { Point<3> lo = make_point(0, 0, 0), hi = make_point(DIM_X - 1, DIM_Y - 1, DIM_Z - 1); Rect<3> rect(lo, hi); domain = Domain::from_rect<3>(rect); break; } default: assert(false); } RegionInstance src_inst, dst_inst; std::deque<RegionInstance> inst_vec; std::vector<size_t> field_order[PATH_LEN]; int block_size_vec[PATH_LEN]; for (unsigned j = 0; j < PATH_LEN; j++) { //block_size_vec[j] = rand() % domain.get_volume() + 1; block_size_vec[j] = domain.get_volume(); //printf("node = %d, kind = %d\n", ID(*it).node(), it->kind()); // random field order of this region instance std::vector<size_t> rand_order; rand_order.clear(); for (size_t k = 0; k < NUM_FIELDS; k++) rand_order.push_back(k); field_order[j].clear(); while (!rand_order.empty()) { size_t idx = rand() % rand_order.size(); std::vector<size_t>::iterator field_iter = rand_order.begin(); while (idx > 0) {idx--; field_iter++;} field_order[j].push_back(*field_iter); rand_order.erase(field_iter); } if (j == 0) { // we initialize the first region instance src_inst = domain.create_instance(src_mem, field_sizes, block_size_vec[j]); inst_vec.push_back(src_inst); initialize_region_data(domain, inst_vec[0], field_order[0]); } else { assert(j == 1); std::set<Event> wait_on; UserEvent start_event = UserEvent::create_user_event(); for (unsigned k = 0; k < NUM_REQUESTS; k++) { if (k == 0 || dst_mem.kind() != Memory::GPU_FB_MEM) { dst_inst = domain.create_instance(dst_mem, field_sizes, block_size_vec[j]); inst_vec.push_back(dst_inst); } std::vector<Domain::CopySrcDstField> src_fields, dst_fields; src_fields.clear(); dst_fields.clear(); // we submit a copy request for (size_t k = 0; k < NUM_FIELDS; k++) { Domain::CopySrcDstField src_field(src_inst, field_order[j-1][k] * sizeof(int), sizeof(int)); Domain::CopySrcDstField dst_field(dst_inst, field_order[j][k] * sizeof(int), sizeof(int)); src_fields.push_back(src_field); dst_fields.push_back(dst_field); } Event copyEvent = domain.copy(src_fields, dst_fields, start_event); wait_on.insert(copyEvent); } double starttime = Realm::Clock::current_time_in_microseconds(); start_event.trigger(); Event::merge_events(wait_on).wait(); printf("[%d] inst[%u] {%d (%d) -> %d (%d)}: ", gasnet_mynode(), j, get_runtime()->get_instance_impl(inst_vec[j-1])->memory.kind(), ID(get_runtime()->get_instance_impl(inst_vec[j-1])->memory).node(), get_runtime()->get_instance_impl(inst_vec[j])->memory.kind(), ID(get_runtime()->get_instance_impl(inst_vec[j])->memory).node()); double stoptime = Realm::Clock::current_time_in_microseconds(); double totalsize = domain.get_volume(); totalsize = totalsize * NUM_REQUESTS; double throughput = totalsize * sizeof(int) * NUM_FIELDS / (stoptime - starttime); printf("time = %.2lfus, tp = %.2lfMB/s\n", stoptime - starttime, throughput); } } while (!inst_vec.empty()) { RegionInstance inst = inst_vec.front(); inst_vec.pop_front(); get_runtime()->get_memory_impl(get_runtime()->get_instance_impl(inst)->memory)->destroy_instance(inst, false); } } printf("finish worker task..\n"); return; } int main(int argc, char **argv) { Runtime rt; bool ok = rt.init(&argc, &argv); assert(ok); rt.register_task(TOP_LEVEL_TASK, top_level_task); rt.register_task(WORKER_TASK, worker_task); // Set the input args get_input_args().argv = argv; get_input_args().argc = argc; // select a processor to run the top level task on Processor p = Processor::NO_PROC; { std::set<Processor> all_procs; Machine::get_machine().get_all_processors(all_procs); for(std::set<Processor>::const_iterator it = all_procs.begin(); it != all_procs.end(); it++) if(it->kind() == Processor::LOC_PROC) { p = *it; break; } } assert(p.exists()); // collective launch of a single task - everybody gets the same finish event Event e = rt.collective_spawn(p, TOP_LEVEL_TASK, 0, 0); // request shutdown once that task is complete rt.shutdown(e); // now sleep this thread until that shutdown actually happens rt.wait_for_shutdown(); return 0; }
#include <cstdio> #include <cstdlib> #include <cassert> #include <cstring> #include <time.h> #include "lowlevel.h" #include "lowlevel_impl.h" #include "channel.h" #define DIM_X 128 #define DIM_Y 128 #define DIM_Z 64 #define NUM_TEST 1 #define PATH_LEN 2 #define NUM_FIELDS 8 #define NUM_REQUESTS 64 #define MEM_KIND_SIZE 20 using namespace LegionRuntime::LowLevel; using namespace LegionRuntime::Accessor; using namespace LegionRuntime::Arrays; enum { TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0, WORKER_TASK = Processor::TASK_ID_FIRST_AVAILABLE+1, }; struct InputArgs { int argc; char **argv; }; InputArgs& get_input_args(void) { static InputArgs args; return args; } void initialize_region_data(Domain domain, RegionInstance inst, std::vector<size_t> field_order) { // TODO: fix it if (get_runtime()->get_instance_impl(inst)->memory.kind() == Memory::GPU_FB_MEM) return; RegionAccessor<AccessorType::Generic> acc = inst.get_accessor(); switch(domain.dim) { case 0: assert(false); break; case 1: { Rect<1> rect = domain.get_rect<1>(); int idx = 0; int read_data[NUM_FIELDS]; for(GenericPointInRectIterator<1> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { read_data[i] = idx * i; acc.write_untyped(DomainPoint::from_point<1>(pir.p), &read_data[i], sizeof(int), field_order[i] * sizeof(int)); } } break; } case 2: { Rect<2> rect = domain.get_rect<2>(); int idx = 0; int read_data[NUM_FIELDS]; for(GenericPointInRectIterator<2> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { read_data[i] = idx * i; acc.write_untyped(DomainPoint::from_point<2>(pir.p), &read_data[i], sizeof(int), field_order[i] * sizeof(int)); } } break; } case 3: { Rect<3> rect = domain.get_rect<3>(); int idx = 0; int read_data[NUM_FIELDS]; for(GenericPointInRectIterator<3> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { read_data[i] = idx * i; acc.write_untyped(DomainPoint::from_point<3>(pir.p), &read_data[i], sizeof(int), field_order[i] * sizeof(int)); } } break; } default: assert(false); } } bool verify_region_data(Domain domain, RegionInstance inst, std::vector<size_t> field_order) { RegionAccessor<AccessorType::Generic> acc = inst.get_accessor(); bool check = true; switch(domain.dim) { case 0: assert(false); break; case 1: { Rect<1> rect = domain.get_rect<1>(); int idx = 0; int read_data; for(GenericPointInRectIterator<1> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { acc.read_untyped(DomainPoint::from_point<1>(pir.p), &read_data, sizeof(int), field_order[i] * sizeof(int)); check = check && (read_data == idx * i); if (read_data != idx * i) { printf("read_data = %d, expected = %d\n", read_data, idx * i); assert(0); } } } break; } case 2: { Rect<2> rect = domain.get_rect<2>(); int idx = 0; int read_data; for(GenericPointInRectIterator<2> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { acc.read_untyped(DomainPoint::from_point<2>(pir.p), &read_data, sizeof(int), field_order[i] * sizeof(int)); check = check && (read_data == idx * i); } } break; } case 3: { Rect<3> rect = domain.get_rect<3>(); int idx = 0; int read_data; for(GenericPointInRectIterator<3> pir(rect); pir; pir++) { idx++; for (int i = 0; i < NUM_FIELDS; i++) { acc.read_untyped(DomainPoint::from_point<3>(pir.p), &read_data, sizeof(int), field_order[i] * sizeof(int)); check = check && (read_data == idx * i); } } break; } default: assert(false); } return check; } struct WorkerTaskArgs { Memory src_mem, dst_mem; bool test_xfer; }; void top_level_task(const void *args, size_t arglen, const void *user_data, size_t user_data_len, Processor p) { printf("top level task - DMA random tests\n"); bool only_remote = false, test_xfer = false; // Parse the input arguments #define INT_ARG(argname, varname) do { \ if(!strcmp((argv)[i], argname)) { \ varname = atoi((argv)[++i]); \ continue; \ } } while(0) #define BOOL_ARG(argname, varname) do { \ if(!strcmp((argv)[i], argname)) { \ varname = true; \ continue; \ } } while(0) { InputArgs &inputs = get_input_args(); char **argv = inputs.argv; for (int i = 1; i < inputs.argc; i++) { BOOL_ARG("-r", only_remote); BOOL_ARG("-t", test_xfer); } } #undef INT_ARG #undef BOOL_ARG Machine machine = Machine::get_machine(); std::set<Memory> all_mem, src_mem_set, dst_mem_set; machine.get_all_memories(all_mem); for(std::set<Memory>::iterator it = all_mem.begin(); it != all_mem.end(); it++) { if (gasnet_mynode() == ID(*it).node() && it->kind() != Memory::HDF_MEM && it->kind() != Memory::FILE_MEM) src_mem_set.insert(*it); if ((gasnet_mynode() != ID(*it).node() || !only_remote) && it->kind() != Memory::HDF_MEM && it->kind() != Memory::FILE_MEM) dst_mem_set.insert(*it); } Processor cur_proc = p; for(std::set<Memory>::iterator src_it = src_mem_set.begin(); src_it != src_mem_set.end(); src_it++) for(std::set<Memory>::iterator dst_it = dst_mem_set.begin(); dst_it != dst_mem_set.end(); dst_it++) { WorkerTaskArgs args; args.src_mem = *src_it; args.dst_mem = *dst_it; args.test_xfer = test_xfer; Event event = cur_proc.spawn(WORKER_TASK, &args, sizeof(args)); event.wait(); } printf("finish top level task......\n"); } void worker_task(const void *args, size_t arglen, const void *user_data, size_t user_data_len, Processor p) { printf("start worker task\n"); const WorkerTaskArgs& worker_args = *(const WorkerTaskArgs *)args; Memory src_mem = worker_args.src_mem, dst_mem = worker_args.dst_mem; bool test_xfer = worker_args.test_xfer; std::vector<size_t> field_sizes; for (unsigned i = 0; i < NUM_FIELDS; i++) field_sizes.push_back(sizeof(int)); for (unsigned i = 0; i < NUM_TEST; i++) { printf("Test case #%u:\n", i); int dim = 3; Domain domain; switch (dim) { case 0: case 1: { Point<1> lo = make_point(0), hi = make_point(DIM_X - 1); Rect<1> rect(lo, hi); domain = Domain::from_rect<1>(rect); break; } case 2: { Point<2> lo = make_point(0, 0), hi = make_point(DIM_X - 1, DIM_Y - 1); Rect<2> rect(lo, hi); domain = Domain::from_rect<2>(rect); break; } case 3: { Point<3> lo = make_point(0, 0, 0), hi = make_point(DIM_X - 1, DIM_Y - 1, DIM_Z - 1); Rect<3> rect(lo, hi); domain = Domain::from_rect<3>(rect); break; } default: assert(false); } RegionInstance src_inst, dst_inst; std::deque<RegionInstance> inst_vec; std::vector<size_t> field_order[PATH_LEN]; int block_size_vec[PATH_LEN]; for (unsigned j = 0; j < PATH_LEN; j++) { //block_size_vec[j] = rand() % domain.get_volume() + 1; if (j == 0 || !test_xfer) block_size_vec[j] = domain.get_volume(); else block_size_vec[j] = 1; //printf("node = %d, kind = %d\n", ID(*it).node(), it->kind()); // random field order of this region instance std::vector<size_t> rand_order; rand_order.clear(); for (size_t k = 0; k < NUM_FIELDS; k++) rand_order.push_back(k); field_order[j].clear(); while (!rand_order.empty()) { size_t idx = rand() % rand_order.size(); std::vector<size_t>::iterator field_iter = rand_order.begin(); while (idx > 0) {idx--; field_iter++;} field_order[j].push_back(*field_iter); rand_order.erase(field_iter); } if (j == 0) { // we initialize the first region instance src_inst = domain.create_instance(src_mem, field_sizes, block_size_vec[j]); inst_vec.push_back(src_inst); initialize_region_data(domain, inst_vec[0], field_order[0]); } else { assert(j == 1); std::set<Event> wait_on; UserEvent start_event = UserEvent::create_user_event(); for (unsigned k = 0; k < NUM_REQUESTS; k++) { if (k == 0 || dst_mem.kind() != Memory::GPU_FB_MEM) { dst_inst = domain.create_instance(dst_mem, field_sizes, block_size_vec[j]); inst_vec.push_back(dst_inst); } std::vector<Domain::CopySrcDstField> src_fields, dst_fields; src_fields.clear(); dst_fields.clear(); // we submit a copy request for (size_t k = 0; k < NUM_FIELDS; k++) { Domain::CopySrcDstField src_field(src_inst, field_order[j-1][k] * sizeof(int), sizeof(int)); Domain::CopySrcDstField dst_field(dst_inst, field_order[j][k] * sizeof(int), sizeof(int)); src_fields.push_back(src_field); dst_fields.push_back(dst_field); } Event copyEvent = domain.copy(src_fields, dst_fields, start_event); wait_on.insert(copyEvent); } double starttime = Realm::Clock::current_time_in_microseconds(); start_event.trigger(); Event::merge_events(wait_on).wait(); printf("[%d] inst[%u] {%d (%d) -> %d (%d)}: ", gasnet_mynode(), j, get_runtime()->get_instance_impl(inst_vec[j-1])->memory.kind(), ID(get_runtime()->get_instance_impl(inst_vec[j-1])->memory).node(), get_runtime()->get_instance_impl(inst_vec[j])->memory.kind(), ID(get_runtime()->get_instance_impl(inst_vec[j])->memory).node()); double stoptime = Realm::Clock::current_time_in_microseconds(); double totalsize = domain.get_volume(); totalsize = totalsize * NUM_REQUESTS; double throughput = totalsize * sizeof(int) * NUM_FIELDS / (stoptime - starttime); printf("time = %.2lfus, tp = %.2lfMB/s\n", stoptime - starttime, throughput); } } while (!inst_vec.empty()) { RegionInstance inst = inst_vec.front(); inst_vec.pop_front(); get_runtime()->get_memory_impl(get_runtime()->get_instance_impl(inst)->memory)->destroy_instance(inst, false); } } printf("finish worker task..\n"); return; } int main(int argc, char **argv) { Runtime rt; bool ok = rt.init(&argc, &argv); assert(ok); rt.register_task(TOP_LEVEL_TASK, top_level_task); rt.register_task(WORKER_TASK, worker_task); // Set the input args get_input_args().argv = argv; get_input_args().argc = argc; // select a processor to run the top level task on Processor p = Processor::NO_PROC; { std::set<Processor> all_procs; Machine::get_machine().get_all_processors(all_procs); for(std::set<Processor>::const_iterator it = all_procs.begin(); it != all_procs.end(); it++) if(it->kind() == Processor::LOC_PROC) { p = *it; break; } } assert(p.exists()); // collective launch of a single task - everybody gets the same finish event Event e = rt.collective_spawn(p, TOP_LEVEL_TASK, 0, 0); // request shutdown once that task is complete rt.shutdown(e); // now sleep this thread until that shutdown actually happens rt.wait_for_shutdown(); return 0; }
add layout transfer test
dma: add layout transfer test
C++
apache-2.0
StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion
02216b1fb6dd727fce2912efc9d4cc069ef8dacb
benchmarks/halide/blurxy_coli.cpp
benchmarks/halide/blurxy_coli.cpp
#include <isl/set.h> #include <isl/union_map.h> #include <isl/union_set.h> #include <isl/ast_build.h> #include <isl/schedule.h> #include <isl/schedule_node.h> #include <coli/debug.h> #include <coli/core.h> #include <string.h> #include <Halide.h> #include "halide_image_io.h" /* Halide code. Func blurxy(Func input, Func blur_y) { Func blur_x, blur_y; Var x, y, xi, yi; blur_x(x, y) = (input(x-1, y) + input(x, y) + input(x+1, y))/3; blur_y(x, y) = (blur_x(x, y-1) + blur_x(x, y) + blur_x(x, y+1))/3; blur_y.split(y, y, yi, 8).parallel(y).vectorize(x, 8); blur_x.store_at(blur_y, y).compute_at(blur_y, yi).vectorize(x, 8); } */ using namespace coli; int main(int argc, char **argv) { // Set default coli options. global::set_default_coli_options(); // A hack to represent the image size. TODO: this should be retrieved from // the function arguments. Halide::Image<uint16_t> in_image = Halide::Tools::load_image("./images/rgb.png"); int SIZE0 = in_image.extent(0) - 8; int SIZE1 = in_image.extent(1) - 2; /* * Declare a function blurxy. * Declare two arguments (coli buffers) for the function: b_input and b_blury * Declare an invariant for the function. */ function blurxy("blurxy_coli"); buffer b_input("b_input", 2, {coli::expr(SIZE0),coli::expr(SIZE1)}, p_uint16, NULL, a_input, &blurxy); buffer b_blury("b_blury", 2, {coli::expr(SIZE0),coli::expr(SIZE1)}, p_uint16, NULL, a_output, &blurxy); expr e_p0 = expr((int32_t) SIZE0); expr e_p1 = expr((int32_t) SIZE1); constant p0("N", e_p0, p_int32, true, NULL, 0, &blurxy); constant p1("M", e_p1, p_int32, true, NULL, 0, &blurxy); // Declare the computations c_blurx and c_blury. computation c_input("[N]->{c_input[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint16, &blurxy); idx i = idx("i"); idx j = idx("j"); expr e1 = (c_input(i-1, j) + c_input(i, j) + c_input(i+1, j))/((uint16_t) 3); computation c_blurx("[N,M]->{c_blurx[i,j]: 1<i<N-2 and 1<j<M-2}", e1, true, p_uint16, &blurxy); expr e2 = (c_blurx(i, j-1) + c_blurx(i, j) + c_blurx(i, j+1))/((uint16_t) 3); computation c_blury("[N,M]->{c_blury[i,j]: 1<i<N-2 and 1<j<M-2}", e2, true, p_uint16, &blurxy); // Create a memory buffer (2 dimensional). buffer b_blurx("b_blurx", 2, {coli::expr(SIZE0),coli::expr(SIZE1)}, p_uint16, NULL, a_temporary, &blurxy); // Map the computations to a buffer. c_input.set_access("{c_input[i,j]->b_input[i,j]}"); c_blurx.set_access("{c_blurx[i,j]->b_blurx[i,j]}"); c_blury.set_access("{c_blury[i,j]->b_blury[i,j]}"); // Set the schedule of each computation. /*c_blury.split(1, 8); c_blury.tag_parallel_dimension(0); c_blury.split(5, 8); c_blury.tag_vector_dimension(3); */ c_blury.after(c_blurx, 1); /* c_blurx.set_schedule("[N,M]->{c_blurx[i,j]->[i1,j1,0,i2,j2]: 0<i<N-1 and 0<j<M-1 and i1=floor(i/8) and i2=i%8 and j1=floor(j/8) and j2=j%8}"); c_blury.set_schedule("[N,M]->{c_blury[i,j]->[i1,j1,1,i2,j2]: 0<i<N-1 and 0<j<M-1 and i1=floor(i/8) and i2=i%8 and j1=floor(j/8) and j2=j%8}"); */ c_blury.tag_parallel_dimension(0); // Set the arguments to blurxy blurxy.set_arguments({&b_input, &b_blury}); // Generate code blurxy.gen_isl_ast(); blurxy.gen_halide_stmt(); blurxy.gen_halide_obj("build/generated_fct_blurxy.o"); // Some debugging blurxy.dump_iteration_domain(); blurxy.dump_halide_stmt(); // Dump all the fields of the blurxy class. blurxy.dump(true); return 0; }
#include <isl/set.h> #include <isl/union_map.h> #include <isl/union_set.h> #include <isl/ast_build.h> #include <isl/schedule.h> #include <isl/schedule_node.h> #include <coli/debug.h> #include <coli/core.h> #include <string.h> #include <Halide.h> #include "halide_image_io.h" /* Halide code. Func blurxy(Func input, Func blur_y) { Func blur_x, blur_y; Var x, y, xi, yi; blur_x(x, y) = (input(x-1, y) + input(x, y) + input(x+1, y))/3; blur_y(x, y) = (blur_x(x, y-1) + blur_x(x, y) + blur_x(x, y+1))/3; blur_y.split(y, y, yi, 8).parallel(y).vectorize(x, 8); blur_x.store_at(blur_y, y).compute_at(blur_y, yi).vectorize(x, 8); } */ using namespace coli; int main(int argc, char **argv) { // Set default coli options. global::set_default_coli_options(); // A hack to represent the image size. TODO: this should be retrieved from // the function arguments. Halide::Image<uint16_t> in_image = Halide::Tools::load_image("./images/rgb.png"); int SIZE0 = in_image.extent(0) - 8; int SIZE1 = in_image.extent(1) - 2; /* * Declare a function blurxy. * Declare two arguments (coli buffers) for the function: b_input and b_blury * Declare an invariant for the function. */ function blurxy("blurxy_coli"); buffer b_input("b_input", 2, {coli::expr(SIZE0),coli::expr(SIZE1)}, p_uint16, NULL, a_input, &blurxy); buffer b_blury("b_blury", 2, {coli::expr(SIZE0),coli::expr(SIZE1)}, p_uint16, NULL, a_output, &blurxy); expr e_p0 = expr((int32_t) SIZE0); expr e_p1 = expr((int32_t) SIZE1); constant p0("N", e_p0, p_int32, true, NULL, 0, &blurxy); constant p1("M", e_p1, p_int32, true, NULL, 0, &blurxy); // Declare the computations c_blurx and c_blury. computation c_input("[N]->{c_input[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint16, &blurxy); idx i = idx("i"); idx j = idx("j"); expr e1 = (c_input(i-1, j) + c_input(i, j) + c_input(i+1, j))/((uint16_t) 3); computation c_blurx("[N,M]->{c_blurx[i,j]: 0<i<N-1 and 1<j<M-2}", e1, true, p_uint16, &blurxy); expr e2 = (c_blurx(i, j-1) + c_blurx(i, j) + c_blurx(i, j+1))/((uint16_t) 3); computation c_blury("[N,M]->{c_blury[i,j]: 0<i<N-1 and 1<j<M-2}", e2, true, p_uint16, &blurxy); // Create a memory buffer (2 dimensional). buffer b_blurx("b_blurx", 2, {coli::expr(SIZE0),coli::expr(SIZE1)}, p_uint16, NULL, a_temporary, &blurxy); // Map the computations to a buffer. c_input.set_access("{c_input[i,j]->b_input[i,j]}"); c_blurx.set_access("{c_blurx[i,j]->b_blurx[i,j]}"); c_blury.set_access("{c_blury[i,j]->b_blury[i,j]}"); // Set the schedule of each computation. /*c_blury.split(1, 8); c_blury.tag_parallel_dimension(0); c_blury.split(5, 8); c_blury.tag_vector_dimension(3); */ // c_blury.after(c_blurx, 1); c_blurx.set_schedule("[N,M]->{c_blurx[i,j]->[i,0,j1,j2]: 0<i<N-1 and 0<j<M-1 and j1=floor(j/8) and j2=j%8}"); c_blury.set_schedule("[N,M]->{c_blury[i,j]->[i,1,j1,j2]: 0<i<N-1 and 0<j<M-1 and j1=floor(j/8) and j2=j%8}"); c_blury.tag_parallel_dimension(0); // Set the arguments to blurxy blurxy.set_arguments({&b_input, &b_blury}); // Generate code blurxy.gen_isl_ast(); blurxy.gen_halide_stmt(); blurxy.gen_halide_obj("build/generated_fct_blurxy.o"); // Some debugging blurxy.dump_iteration_domain(); blurxy.dump_halide_stmt(); // Dump all the fields of the blurxy class. blurxy.dump(true); return 0; }
Fix blurxy benchmark
Fix blurxy benchmark
C++
mit
rbaghdadi/ISIR,rbaghdadi/tiramisu,rbaghdadi/COLi,rbaghdadi/tiramisu,rbaghdadi/ISIR,rbaghdadi/COLi,rbaghdadi/tiramisu,rbaghdadi/tiramisu
db91bedc9d80aa390904036abe981a3e53de9dd9
test/libpqxx/main.cpp
test/libpqxx/main.cpp
#include <iostream> #include <vector> #include <pqxx/connection> #include <pqxx/nontransaction> #include <pqxx/tablewriter> #include <pqxx/transaction> #include <string> #include <pqxx/notification> #include "jmsg/pqxxutils.hpp" #include "jmsg/jmsg_rcver.hpp" #include "jmsg/jmsg_sender.hpp" #include "exemodel/poller.hpp" #include "exemodel/evt_cb.hpp" #define NOTIFICATION_TEST #ifndef NOTIFICATION_TEST template< typename _T > static bool load_others(pqxx::nontransaction & w, rcver & rcv, const std::string name, _T & dst) { pqxx::result r = w.exec("SELECT cfg FROM others WHERE name = '" + name + "'"); for (auto row = r.begin(); row != r.end(); ++row) { for (auto cell = row->begin(); cell != row->end(); ++cell) { rcv.convert(dst, cell->c_str()); return true; } } return false; } bool load_fsparam(pqxx::nontransaction & w, int index, fs_param_cfg_t & dst) { std::cout << "prepare load fsparam!" << std::endl; pqxx::result r = w.prepared("load_fsparam")(index).exec(); for (const auto & i : r) { std::cout << "pqxx2c fsparam!" << std::endl; pqxx2c(dst, i.begin()); std::cout << "pqxx2c fsparam done!" << std::endl; return true; } return false; } bool save_fsparam(pqxx::nontransaction & w, int index, const fs_param_cfg_t & src) { pqxx::result r = w.prepared("save_fsparam")(src)(index).exec(); for (const auto & i : r) { ///pqxx2c(dst, i.begin()); return true; } return false; } static fs_param_cfg_t g_fsparam; static misc_cfg_t g_misccfg; static void test_fsparam() { pqxx::connection c("host=127.0.0.1 user=postgres dbname=postgres"); c.prepare("load_fsparam", "SELECT " PQKL_fs_param_cfg " FROM fs_param WHERE seqn=$1"); c.prepare("save_fsparam", "UPDATE fs_param SET (" PQKL_fs_param_cfg ")=(" PQOL_fs_param_cfg ")" " WHERE seqn=$" PQMS_fs_param_cfg "RETURNING " PQKL_fs_param_cfg); pqxx::nontransaction w(c, "misc"); rcver rcv; load_others(w, rcv, "misc", g_misccfg); std::cout << "fsparamidx: " << g_misccfg.fsParamIdx << std::endl; g_misccfg.fsParamIdx = 1; load_fsparam(w, g_misccfg.fsParamIdx, g_fsparam); std::cout << "fsparamleftfibertype: " << (int)g_fsparam.lfti << std::endl; std::cout << "fsparamrightfibertype: " << (int)g_fsparam.rfti << std::endl; //save_fsparam(w, g_misccfg.fsParamIdx, g_fsparam); } #else //using namespace PGSTD; //using namespace pqxx; // Simple test program for libpqxx. Write a predetermined data set to a table // using a tablewriter. This data will be used by subsequent tests. Any data // previously in the table will be deleted. // // Usage: test005 [connect-string] [tablename] // // Where connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. // // The tablename argument determines which table the data will be written to. // If none is given, it defaults to "pqxxorgevents". class receiver : public pqxx::notification_receiver { public: receiver(pqxx::connection_base & c, const std::string & channel) : pqxx::notification_receiver(c, channel), receiver_id(c.backendpid()) {} ~receiver() {} virtual void operator()(const std::string & payload, int backend) { std::cout << "payload: " << payload << std::endl; std::cout << "backend: " << backend << std::endl; std::cout << "backendpid: " << receiver_id << std::endl; } private: int receiver_id; }; class receiver_test : public exemodel::pollee, public exemodel::evt_cb<exemodel::poller&> { public: explicit receiver_test(pqxx::connection_base & c, const std::string & ch) : exemodel::pollee(c.sock(), (uint32_t)(::EPOLLIN), "receiver_test"), m_c(c), m_rcvr(c, ch) {} ~receiver_test() {} virtual void dispose(exemodel::poller & p, uint32_t) { this->exe(p); } pqxx::connection_base & mc() { return m_c; } private: pqxx::connection_base & m_c; receiver m_rcvr; }; class rcvr_test : public exemodel::poller { public: explicit rcvr_test(pqxx::connection_base & c, const std::string & ch) : exemodel::poller(), m_rcvr_test(c, ch) { m_rcvr_test.connect([this](exemodel::poller&) { int backend_id = m_rcvr_test.mc().get_notifs(); std::cout << "get notifs return value is: " << backend_id << std::endl; }); this->add(m_rcvr_test); } ~rcvr_test() { this->del(m_rcvr_test); } private: receiver_test m_rcvr_test; }; void receiver_test_func(const std::string & ch) { pqxx::connection c("host=127.0.0.1 user=postgres dbname=postgres"); rcvr_test rtest(c, ch); rtest.run(); } // void receiver_test(const std::string & ch, const char * payload = NULL) { // pqxx::connection c("host=127.0.0.1 user=postgres dbname=postgres"); // for(int i = 0; i < 10; ++i) { // receiver rcvr(c, ch); // pqxx::nontransaction w(c); // std::string SQL = "NOTIFY \"" + ch + "\""; // if (payload) SQL += ", " + w.quote(payload); // w.exec(SQL); // w.commit(); // c.await_notification(); // std::cout << "sock: " << c.sock() << std::endl; // } // } #endif int main(int argc, char *argv[]) { #ifndef NOTIFICATION_TEST test_fsparam(); try { // Set up a connection to the backend static char opt[] = "host=127.0.0.1 user=postgres dbname=fsdb"; pqxx::connection C(opt); std::string TableName((argc > 2) ? argv[2] : "tbl_test2"); // First create a separate transaction to drop old table, if any. This may // fail if the table didn't previously exist. std::cout << "Dropping old " << TableName << std::endl; try { pqxx::work Drop(C, "drop_" + TableName); Drop.exec("DROP TABLE " + TableName); Drop.commit(); } catch (const pqxx::undefined_table &e) { std::cout << "(Expected) Couldn't drop table: " << e.what() << std::endl << "Query was: " << e.query() << std::endl; } catch (const pqxx::sql_error &e) { std::cerr << "Couldn't drop table: " << e.what() << std::endl << "Query was: " << e.query() << std::endl; } // Now begin new transaction to create new table & write data pqxx::work T(C, "test5"); T.exec("CREATE TABLE " + TableName + "(year INTEGER, event VARCHAR)"); pqxx::tablewriter W(T, TableName); // TODO: Move this stuff to a file! const char *const CData[][2] = { { "71", "jtv" }, { "38", "time_t overflow" }, { "1", "'911' WTC\"\" attack" }, { "81", "C:\\>" }, { "1978", "bloody\t\tcold" }, { "99", "" }, { "2002", "libpqxx" }, { "1989", "Ode an die Freiheit" }, { "2001", "New millennium" }, { "1974", "fdsafdsa" }, { "97", "Asian crisis" }, { "2001", "A Space Odyssey" }, { nullptr, nullptr} }; std::cout << "Writing data to " << TableName << std::endl; // Insert tuple of data using "begin" and "end" abstraction for (int i=0; CData[i][0]; ++i) W.insert(&CData[i][0], &CData[i][2]); // Insert tuple of data held in container std::vector<std::string> MoreData; MoreData.push_back("10"); MoreData.push_back("Odyssey Two"); W.insert(MoreData); // Now that MoreData has been inserted, we can get rid of the original // and use it for something else. And this time, we use the insertion // operator. MoreData[0] = "3001"; MoreData[1] = "Final Odyssey"; W << MoreData; W.complete(); // Now that our tablewriter is done, it's safe to commit T. T.commit(); // Query /// @note: the work or transaction are all disposable, you can't reuse it after commit. C.prepare("queryXX", "SELECT $1 FROM "); pqxx::nontransaction NS(C); /** * @note: if you use SELECT (year, event) ..., the result will contain only single column. */ pqxx::result r = NS.exec("SELECT year, event FROM " + TableName + " "); NS.commit(); for (auto row = r.begin(); row != r.end(); ++row) { for (auto tbl_filed = row->begin(); tbl_filed != row->end(); ++tbl_filed) { std::cout << tbl_filed->c_str() << ": " << '\t'; } std::cout << std::endl; } } catch (const pqxx::sql_error &e) { // If we're interested in the text of a failed query, we can write separate // exception handling code for this type of exception std::cerr << "SQL error: " << e.what() << std::endl << "Query was: '" << e.query() << "'" << std::endl; return 1; } catch (const std::exception &e) { // All exceptions thrown by libpqxx are derived from std::exception std::cerr << "Exception: " << e.what() << std::endl; return 2; } catch (...) { // This is really unexpected (see above) std::cerr << "Unhandled exception" << std::endl; return 100; } #else (void)argc; (void )argv[0][0]; receiver_test_func("changed"); // receiver_test("changed", "haha"); #endif return 0; }
#include <iostream> #include <vector> #include <pqxx/connection> #include <pqxx/nontransaction> #include <pqxx/tablewriter> #include <pqxx/transaction> #include <string> #include <pqxx/notification> #include "jmsg/pqxxutils.hpp" #include "jmsg/jmsg_rcver.hpp" #include "jmsg/jmsg_sender.hpp" #include "exemodel/poller.hpp" #include "exemodel/evt_cb.hpp" #define NOTIFICATION_TEST #ifndef NOTIFICATION_TEST template< typename _T > static bool load_others(pqxx::nontransaction & w, rcver & rcv, const std::string name, _T & dst) { pqxx::result r = w.exec("SELECT cfg FROM others WHERE name = '" + name + "'"); for (auto row = r.begin(); row != r.end(); ++row) { for (auto cell = row->begin(); cell != row->end(); ++cell) { rcv.convert(dst, cell->c_str()); return true; } } return false; } bool load_fsparam(pqxx::nontransaction & w, int index, fs_param_cfg_t & dst) { std::cout << "prepare load fsparam!" << std::endl; pqxx::result r = w.prepared("load_fsparam")(index).exec(); for (const auto & i : r) { std::cout << "pqxx2c fsparam!" << std::endl; pqxx2c(dst, i.begin()); std::cout << "pqxx2c fsparam done!" << std::endl; return true; } return false; } bool save_fsparam(pqxx::nontransaction & w, int index, const fs_param_cfg_t & src) { pqxx::result r = w.prepared("save_fsparam")(src)(index).exec(); for (const auto & i : r) { ///pqxx2c(dst, i.begin()); return true; } return false; } static fs_param_cfg_t g_fsparam; static misc_cfg_t g_misccfg; static void test_fsparam() { pqxx::connection c("host=127.0.0.1 user=postgres dbname=postgres"); c.prepare("load_fsparam", "SELECT " PQKL_fs_param_cfg " FROM fs_param WHERE seqn=$1"); c.prepare("save_fsparam", "UPDATE fs_param SET (" PQKL_fs_param_cfg ")=(" PQOL_fs_param_cfg ")" " WHERE seqn=$" PQMS_fs_param_cfg "RETURNING " PQKL_fs_param_cfg); pqxx::nontransaction w(c, "misc"); rcver rcv; load_others(w, rcv, "misc", g_misccfg); std::cout << "fsparamidx: " << g_misccfg.fsParamIdx << std::endl; g_misccfg.fsParamIdx = 1; load_fsparam(w, g_misccfg.fsParamIdx, g_fsparam); std::cout << "fsparamleftfibertype: " << (int)g_fsparam.lfti << std::endl; std::cout << "fsparamrightfibertype: " << (int)g_fsparam.rfti << std::endl; //save_fsparam(w, g_misccfg.fsParamIdx, g_fsparam); } //using namespace PGSTD; //using namespace pqxx; // Simple test program for libpqxx. Write a predetermined data set to a table // using a tablewriter. This data will be used by subsequent tests. Any data // previously in the table will be deleted. // // Usage: test005 [connect-string] [tablename] // // Where connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. // // The tablename argument determines which table the data will be written to. // If none is given, it defaults to "pqxxorgevents". #else class receiver : public pqxx::notification_receiver { public: receiver(pqxx::connection_base & c, const std::string & channel) : pqxx::notification_receiver(c, channel), receiver_id(c.backendpid()) {} ~receiver() {} virtual void operator()(const std::string & payload, int backend) { std::cout << "payload: " << payload << std::endl; std::cout << "backend: " << backend << std::endl; std::cout << "backendpid: " << receiver_id << std::endl; } private: int receiver_id; }; class receiver_test : public exemodel::pollee, public exemodel::evt_cb<exemodel::poller&> { public: explicit receiver_test(pqxx::connection_base & c, const std::string & ch) : exemodel::pollee(c.sock(), (uint32_t)(::EPOLLIN), "receiver_test"), m_c(c), m_rcvr(c, ch) {} ~receiver_test() {} virtual void dispose(exemodel::poller & p, uint32_t) { this->exe(p); } pqxx::connection_base & mc() { return m_c; } private: pqxx::connection_base & m_c; receiver m_rcvr; }; class rcvr_test : public exemodel::poller { public: explicit rcvr_test(pqxx::connection_base & c, const std::string & ch) : exemodel::poller(), m_rcvr_test(c, ch) { m_rcvr_test.connect([this](exemodel::poller&) { int backend_id = m_rcvr_test.mc().get_notifs(); std::cout << "get notifs return value is: " << backend_id << std::endl; }); this->add(m_rcvr_test); } ~rcvr_test() { this->del(m_rcvr_test); } private: receiver_test m_rcvr_test; }; void receiver_test_func(const std::string & ch) { pqxx::connection c("host=127.0.0.1 user=postgres dbname=postgres"); rcvr_test rtest(c, ch); rtest.run(); } #endif int main(int argc, char *argv[]) { #ifndef NOTIFICATION_TEST test_fsparam(); try { // Set up a connection to the backend static char opt[] = "host=127.0.0.1 user=postgres dbname=fsdb"; pqxx::connection C(opt); std::string TableName((argc > 2) ? argv[2] : "tbl_test2"); // First create a separate transaction to drop old table, if any. This may // fail if the table didn't previously exist. std::cout << "Dropping old " << TableName << std::endl; try { pqxx::work Drop(C, "drop_" + TableName); Drop.exec("DROP TABLE " + TableName); Drop.commit(); } catch (const pqxx::undefined_table &e) { std::cout << "(Expected) Couldn't drop table: " << e.what() << std::endl << "Query was: " << e.query() << std::endl; } catch (const pqxx::sql_error &e) { std::cerr << "Couldn't drop table: " << e.what() << std::endl << "Query was: " << e.query() << std::endl; } // Now begin new transaction to create new table & write data pqxx::work T(C, "test5"); T.exec("CREATE TABLE " + TableName + "(year INTEGER, event VARCHAR)"); pqxx::tablewriter W(T, TableName); // TODO: Move this stuff to a file! const char *const CData[][2] = { { "71", "jtv" }, { "38", "time_t overflow" }, { "1", "'911' WTC\"\" attack" }, { "81", "C:\\>" }, { "1978", "bloody\t\tcold" }, { "99", "" }, { "2002", "libpqxx" }, { "1989", "Ode an die Freiheit" }, { "2001", "New millennium" }, { "1974", "fdsafdsa" }, { "97", "Asian crisis" }, { "2001", "A Space Odyssey" }, { nullptr, nullptr} }; std::cout << "Writing data to " << TableName << std::endl; // Insert tuple of data using "begin" and "end" abstraction for (int i=0; CData[i][0]; ++i) W.insert(&CData[i][0], &CData[i][2]); // Insert tuple of data held in container std::vector<std::string> MoreData; MoreData.push_back("10"); MoreData.push_back("Odyssey Two"); W.insert(MoreData); // Now that MoreData has been inserted, we can get rid of the original // and use it for something else. And this time, we use the insertion // operator. MoreData[0] = "3001"; MoreData[1] = "Final Odyssey"; W << MoreData; W.complete(); // Now that our tablewriter is done, it's safe to commit T. T.commit();receiver_test // Query /// @note: the work or transaction are all disposable, you can't reuse it after commit. C.prepare("queryXX", "SELECT $1 FROM "); pqxx::nontransaction NS(C); /** * @note: if you use SELECT (year, event) ..., the result will contain only single column. */ pqxx::result r = NS.exec("SELECT year, event FROM " + TableName + " "); NS.commit(); for (auto row = r.begin(); row != r.end(); ++row) { for (auto tbl_filed = row->begin(); tbl_filed != row->end(); ++tbl_filed) { std::cout << tbl_filed->c_str() << ": " << '\t'; } std::cout << std::endl; } } catch (const pqxx::sql_error &e) { // If we're interested in the text of a failed query, we can write separate // exception handling code for this type of exception std::cerr << "SQL error: " << e.what() << std::endl << "Query was: '" << e.query() << "'" << std::endl; return 1; } catch (const std::exception &e) { // All exceptions thrown by libpqxx are derived from std::exception std::cerr << "Exception: " << e.what() << std::endl; return 2; } catch (...) { // This is really unexpected (see above) std::cerr << "Unhandled exception" << std::endl; return 100; } #else (void)argc; (void )argv[0][0]; receiver_test_func("changed"); #endif return 0; }
delete unrelated test codes.
delete unrelated test codes. Signed-off-by: yangbk <[email protected]>
C++
apache-2.0
walkthetalk/libem,walkthetalk/libem,walkthetalk/libem
ce33bd142d0c7c33a549747948e71ec70d72d491
Apoc/Math/Vector.cpp
Apoc/Math/Vector.cpp
/* Copyright (c) 2014, Madd Games. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 <Apoc/Math/Vector.h> Vector::Vector() { coords[0] = 0.0; coords[1] = 0.0; coords[2] = 0.0; coords[3] = 1.0; }; Vector::Vector(float x, float y) { coords[0] = x; coords[1] = y; coords[2] = 0.0; coords[3] = 1.0; }; Vector::Vector(float x, float y, float z) { coords[0] = x; coords[1] = y; coords[2] = z; coords[3] = 1.0; }; Vector::Vector(float x, float y, float z, float w) { coords[0] = x; coords[1] = y; coords[2] = z; coords[3] = w; };
/* Copyright (c) 2014, Madd Games. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 <Apoc/Math/Vector.h> Vector::Vector() { coords[0] = 0.0; coords[1] = 0.0; coords[2] = 0.0; coords[3] = 1.0; }; Vector::Vector(float x, float y) { coords[0] = x; coords[1] = y; coords[2] = 0.0; coords[3] = 1.0; }; Vector::Vector(float x, float y, float z) { coords[0] = x; coords[1] = y; coords[2] = z; coords[3] = 1.0; }; Vector::Vector(float x, float y, float z, float w) { coords[0] = x; coords[1] = y; coords[2] = z; coords[3] = w; }; float& Vector::x() { return coords[0]; }; float& Vector::y() { return coords[1]; }; float& Vector::z() { return coords[2]; }; float& Vector::w() { return coords[3]; }; float& Vector::operator[](int i) { return coords[i]; };
Update Vector.cpp
Update Vector.cpp
C++
bsd-2-clause
madd-games/apocalypse,madd-games/apocalypse,madd-games/apocalypse,madd-games/apocalypse,madd-games/apocalypse
c1f29626e01e493e1b3146eb4f8f5dddfe0d6ba7
net/base/keygen_handler_unittest.cc
net/base/keygen_handler_unittest.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/keygen_handler.h" #include <string> #include "base/base64.h" #include "base/logging.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace { TEST(KeygenHandlerTest, SmokeTest) { KeygenHandler handler(2048, "some challenge"); handler.set_stores_key(false); // Don't leave the key-pair behind std::string result = handler.GenKeyAndSignChallenge(); LOG(INFO) << "KeygenHandler produced: " << result; ASSERT_GT(result.length(), 0U); // Verify it's valid base64: std::string spkac; ASSERT_TRUE(base::Base64Decode(result, &spkac)); // In lieu of actually parsing and validating the DER data, // just check that it exists and has a reasonable length. // (It's almost always 590 bytes, but the DER encoding of the random key // and signature could sometimes be a few bytes different.) ASSERT_GE(spkac.length(), 580U); ASSERT_LE(spkac.length(), 600U); // NOTE: // The value of |result| can be validated by prefixing 'SPKAC=' to it // and piping it through // openssl spkac -verify // whose output should look like: // Netscape SPKI: // Public Key Algorithm: rsaEncryption // RSA Public Key: (2048 bit) // Modulus (2048 bit): // 00:b6:cc:14:c9:43:b5:2d:51:65:7e:11:8b:80:9e: ..... // Exponent: 65537 (0x10001) // Challenge String: some challenge // Signature Algorithm: md5WithRSAEncryption // 92:f3:cc:ff:0b:d3:d0:4a:3a:4c:ba:ff:d6:38:7f:a5:4b:b5: ..... // Signature OK // // The value of |spkac| can be ASN.1-parsed with: // openssl asn1parse -inform DER } } // namespace } // namespace net
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/keygen_handler.h" #include <string> #include "base/base64.h" #include "base/logging.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace { TEST(KeygenHandlerTest, FLAKY_SmokeTest) { KeygenHandler handler(2048, "some challenge"); handler.set_stores_key(false); // Don't leave the key-pair behind std::string result = handler.GenKeyAndSignChallenge(); LOG(INFO) << "KeygenHandler produced: " << result; ASSERT_GT(result.length(), 0U); // Verify it's valid base64: std::string spkac; ASSERT_TRUE(base::Base64Decode(result, &spkac)); // In lieu of actually parsing and validating the DER data, // just check that it exists and has a reasonable length. // (It's almost always 590 bytes, but the DER encoding of the random key // and signature could sometimes be a few bytes different.) ASSERT_GE(spkac.length(), 580U); ASSERT_LE(spkac.length(), 600U); // NOTE: // The value of |result| can be validated by prefixing 'SPKAC=' to it // and piping it through // openssl spkac -verify // whose output should look like: // Netscape SPKI: // Public Key Algorithm: rsaEncryption // RSA Public Key: (2048 bit) // Modulus (2048 bit): // 00:b6:cc:14:c9:43:b5:2d:51:65:7e:11:8b:80:9e: ..... // Exponent: 65537 (0x10001) // Challenge String: some challenge // Signature Algorithm: md5WithRSAEncryption // 92:f3:cc:ff:0b:d3:d0:4a:3a:4c:ba:ff:d6:38:7f:a5:4b:b5: ..... // Signature OK // // The value of |spkac| can be ASN.1-parsed with: // openssl asn1parse -inform DER } } // namespace } // namespace net
Fix build by marking new Keygen test as flaky.
TBR: Fix build by marking new Keygen test as flaky. git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@40389 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
da65fd4f8e581be5eab29a8d05cf44a19d8bc620
neurolabi/gui/swc/zswcresampler.cpp
neurolabi/gui/swc/zswcresampler.cpp
#include "swc/zswcresampler.h" #include "zswctree.h" #include "swctreenode.h" #include "tz_error.h" ZSwcResampler::ZSwcResampler() { } int ZSwcResampler::suboptimalDownsample(ZSwcTree *tree) { int count = 0; int treeCount = tree->updateIterator(); int checked = 0; Swc_Tree_Node *tn = tree->begin(); while (tn != NULL) { Swc_Tree_Node *next = tn->next; //std::cout << "before: " << next <<std::endl; ++checked; if (SwcTreeNode::isContinuation(tn)) { Swc_Tree_Node *parent = SwcTreeNode::parent(tn); Swc_Tree_Node *child = SwcTreeNode::firstChild(tn); bool redundant = false; if (SwcTreeNode::isWithin(tn, parent) || SwcTreeNode::isWithin(tn, child)) { redundant = true; } if (!redundant) { redundant = isInterRedundant(tn, parent); } if (redundant) { next = next->next; SwcTreeNode::mergeToParent(tn); ++count; } } tn = next; } std::cout << count << " removed" << std::endl; std::cout << checked << " " << treeCount << std::endl; return count; } void ZSwcResampler::optimalDownsample(ZSwcTree *tree) { int n = 0; while (suboptimalDownsample(tree) > 0) { std::cout << "iter: " << ++n << std::endl; } optimizeCriticalParent(tree); } int ZSwcResampler::optimizeCriticalParent(ZSwcTree *tree) { //Check nodes connected to leaves tree->updateIterator(); Swc_Tree_Node *tn = tree->begin(); int count = 0; while (tn != NULL) { Swc_Tree_Node *next = tn->next; if ((SwcTreeNode::isBranchPoint(tn) || SwcTreeNode::isLeaf(tn)) && !SwcTreeNode::isRoot(tn)) { Swc_Tree_Node *parent = SwcTreeNode::parent(tn); bool redundant = false; if (SwcTreeNode::isContinuation(parent)) { //Set leaf to be the same as its parent if it's covered by the parent if (SwcTreeNode::isWithin(tn, parent)) { SwcTreeNode::copyProperty(parent, tn); redundant = true; } if (!redundant) { if (SwcTreeNode::isWithin(parent, tn)) { redundant = true; } } if (!redundant) { redundant = isInterRedundant(parent, tn); } } if (redundant) { TZ_ASSERT(!SwcTreeNode::isRoot(parent), "Invalid node"); SwcTreeNode::mergeToParent(parent); ++count; } } tn = next; } std::cout << count << " critical removed" << std::endl; return count; } bool ZSwcResampler::isInterRedundant( const Swc_Tree_Node *tn, const Swc_Tree_Node *master) const { bool redundant = false; Swc_Tree_Node *parent = SwcTreeNode::parent(tn); Swc_Tree_Node *child = SwcTreeNode::firstChild(tn); if (parent == master || child == master) { if (SwcTreeNode::isContinuation(tn) && SwcTreeNode::hasOverlap(tn, master)) { double d1 = SwcTreeNode::distance(tn, parent); double d2 = SwcTreeNode::distance(tn, child); double lambda = d2 / (d1 + d2); Swc_Tree_Node tmpNode; SwcTreeNode::setDefault(&tmpNode); SwcTreeNode::interpolate(parent, child, lambda, &tmpNode); TZ_ASSERT(SwcTreeNode::isRegular(&tmpNode), "Unexpected virtual node"); double sizeScale = 1.2; if (SwcTreeNode::distance(tn, &tmpNode) * 2.0 < SwcTreeNode::radius(&tmpNode)) { //not too far away if ((SwcTreeNode::radius(tn) * sizeScale > SwcTreeNode::radius(&tmpNode)) && (SwcTreeNode::radius(tn) < SwcTreeNode::radius(&tmpNode) * sizeScale)) { redundant = true; } } } } return redundant; }
#include "swc/zswcresampler.h" #include "zswctree.h" #include "swctreenode.h" #include "tz_error.h" ZSwcResampler::ZSwcResampler() { } int ZSwcResampler::suboptimalDownsample(ZSwcTree *tree) { int count = 0; int treeCount = tree->updateIterator(); int checked = 0; Swc_Tree_Node *tn = tree->begin(); while (tn != NULL) { Swc_Tree_Node *next = tn->next; //std::cout << "before: " << next <<std::endl; ++checked; if (SwcTreeNode::isContinuation(tn)) { Swc_Tree_Node *parent = SwcTreeNode::parent(tn); Swc_Tree_Node *child = SwcTreeNode::firstChild(tn); bool redundant = false; bool mergingToChild = false; if (SwcTreeNode::isWithin(tn, parent) || SwcTreeNode::isWithin(tn, child)) { redundant = true; if (SwcTreeNode::isWithin(tn, child)) { mergingToChild = true; } } if (!redundant) { redundant = isInterRedundant(tn, parent); } if (redundant) { next = next->next; if (mergingToChild) { SwcTreeNode::copyProperty(tn, parent); } SwcTreeNode::mergeToParent(tn); ++count; } } tn = next; } std::cout << count << " removed" << std::endl; std::cout << checked << " " << treeCount << std::endl; return count; } void ZSwcResampler::optimalDownsample(ZSwcTree *tree) { int n = 0; while (suboptimalDownsample(tree) > 0) { std::cout << "iter: " << ++n << std::endl; } optimizeCriticalParent(tree); } int ZSwcResampler::optimizeCriticalParent(ZSwcTree *tree) { //Check nodes connected to leaves tree->updateIterator(); Swc_Tree_Node *tn = tree->begin(); int count = 0; while (tn != NULL) { Swc_Tree_Node *next = tn->next; if ((SwcTreeNode::isBranchPoint(tn) || SwcTreeNode::isLeaf(tn)) && !SwcTreeNode::isRoot(tn)) { Swc_Tree_Node *parent = SwcTreeNode::parent(tn); bool redundant = false; if (SwcTreeNode::isContinuation(parent)) { //Set leaf to be the same as its parent if it's covered by the parent if (SwcTreeNode::isWithin(tn, parent)) { SwcTreeNode::copyProperty(parent, tn); redundant = true; } if (!redundant) { if (SwcTreeNode::isWithin(parent, tn)) { redundant = true; } } if (!redundant) { redundant = isInterRedundant(parent, tn); } } if (redundant) { TZ_ASSERT(!SwcTreeNode::isRoot(parent), "Invalid node"); SwcTreeNode::mergeToParent(parent); ++count; } } tn = next; } std::cout << count << " critical removed" << std::endl; return count; } bool ZSwcResampler::isInterRedundant( const Swc_Tree_Node *tn, const Swc_Tree_Node *master) const { bool redundant = false; Swc_Tree_Node *parent = SwcTreeNode::parent(tn); Swc_Tree_Node *child = SwcTreeNode::firstChild(tn); if (parent == master || child == master) { if (SwcTreeNode::isContinuation(tn) && SwcTreeNode::hasOverlap(tn, master)) { double d1 = SwcTreeNode::distance(tn, parent); double d2 = SwcTreeNode::distance(tn, child); double lambda = d2 / (d1 + d2); Swc_Tree_Node tmpNode; SwcTreeNode::setDefault(&tmpNode); SwcTreeNode::interpolate(parent, child, lambda, &tmpNode); TZ_ASSERT(SwcTreeNode::isRegular(&tmpNode), "Unexpected virtual node"); double sizeScale = 1.2; if (SwcTreeNode::distance(tn, &tmpNode) * 2.0 < SwcTreeNode::radius(&tmpNode)) { //not too far away if ((SwcTreeNode::radius(tn) * sizeScale > SwcTreeNode::radius(&tmpNode)) && (SwcTreeNode::radius(tn) < SwcTreeNode::radius(&tmpNode) * sizeScale)) { redundant = true; } } } } return redundant; }
fix parent point merging
fix parent point merging
C++
bsd-3-clause
stephenplaza/NeuTu,stephenplaza/NeuTu,stephenplaza/NeuTu,stephenplaza/NeuTu,stephenplaza/NeuTu,stephenplaza/NeuTu,stephenplaza/NeuTu,stephenplaza/NeuTu
edc84ac163362edc1801e42df6fd56ca8eb18ea5
platform/android/Rhodes/jni/src/alert.cpp
platform/android/Rhodes/jni/src/alert.cpp
#include "rhodes/JNIRhodes.h" #include "rhodes/jni/com_rhomobile_rhodes_alert_Alert.h" #include <common/rhoparams.h> #include <common/RhodesApp.h> #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "Alert" RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_alert_Alert_doCallback (JNIEnv *env, jclass, jstring url, jstring id, jstring title) { rho_rhodesapp_callPopupCallback(rho_cast<std::string>(env, url).c_str(), rho_cast<std::string>(env, id).c_str(), rho_cast<std::string>(env, title).c_str()); } RHO_GLOBAL void alert_show_status(const char* szTitle, const char* szMessage, const char* szHide) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "showStatusPopup", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); if (!mid) return; RAWLOG_INFO("alert_show_status"); jstring strMsg = rho_cast<jstring>(szMessage); jstring strHide = rho_cast<jstring>(szHide); jstring strTitle = rho_cast<jstring>(szTitle); env->CallStaticVoidMethod(cls, mid, strTitle, strMsg, strHide); env->DeleteLocalRef(strMsg); } RHO_GLOBAL void alert_show_popup(rho_param *p) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "showPopup", "(Ljava/lang/Object;)V"); if (!mid) return; if (p->type != RHO_PARAM_STRING && p->type != RHO_PARAM_HASH) { RAWLOG_ERROR("show_popup: wrong input parameter (expect String or Hash)"); return; } jobject paramsObj = RhoValueConverter(env).createObject(p); env->CallStaticVoidMethod(cls, mid, paramsObj); env->DeleteLocalRef(paramsObj); } RHO_GLOBAL void alert_hide_popup() { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "hidePopup", "()V"); if (!mid) return; env->CallStaticVoidMethod(cls, mid); } RHO_GLOBAL void alert_vibrate(void *arg) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "vibrate", "(I)V"); if (!mid) return; jint duration = 2500; if (arg) duration = (jint)arg; env->CallStaticVoidMethod(cls, mid, duration); } RHO_GLOBAL void alert_play_file(char* file_name, char *media_type) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "playFile", "(Ljava/lang/String;Ljava/lang/String;)V"); if (!mid) return; jstring objFileName = rho_cast<jstring>(file_name); jstring objMediaType = media_type ? rho_cast<jstring>(media_type) : NULL; env->CallStaticVoidMethod(cls, mid, objFileName, objMediaType); env->DeleteLocalRef(objFileName); if (objMediaType) env->DeleteLocalRef(objMediaType); }
#include "rhodes/JNIRhodes.h" #include "rhodes/jni/com_rhomobile_rhodes_alert_Alert.h" #include <common/rhoparams.h> #include <common/RhodesApp.h> #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "Alert" RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_alert_Alert_doCallback (JNIEnv *env, jclass, jstring url, jstring id, jstring title) { rho_rhodesapp_callPopupCallback(rho_cast<std::string>(env, url).c_str(), rho_cast<std::string>(env, id).c_str(), rho_cast<std::string>(env, title).c_str()); } RHO_GLOBAL void alert_show_status(const char* szTitle, const char* szMessage, const char* szHide) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "showStatusPopup", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); if (!mid) return; RAWLOG_INFO("alert_show_status"); jstring strMsg = rho_cast<jstring>(szMessage); jstring strHide = rho_cast<jstring>(szHide); jstring strTitle = rho_cast<jstring>(szTitle); env->CallStaticVoidMethod(cls, mid, strTitle, strMsg, strHide); env->DeleteLocalRef(strTitle); env->DeleteLocalRef(strHide); env->DeleteLocalRef(strMsg); } RHO_GLOBAL void alert_show_popup(rho_param *p) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "showPopup", "(Ljava/lang/Object;)V"); if (!mid) return; if (p->type != RHO_PARAM_STRING && p->type != RHO_PARAM_HASH) { RAWLOG_ERROR("show_popup: wrong input parameter (expect String or Hash)"); return; } jobject paramsObj = RhoValueConverter(env).createObject(p); env->CallStaticVoidMethod(cls, mid, paramsObj); env->DeleteLocalRef(paramsObj); } RHO_GLOBAL void alert_hide_popup() { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "hidePopup", "()V"); if (!mid) return; env->CallStaticVoidMethod(cls, mid); } RHO_GLOBAL void alert_vibrate(void *arg) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "vibrate", "(I)V"); if (!mid) return; jint duration = 2500; if (arg) duration = (jint)arg; env->CallStaticVoidMethod(cls, mid, duration); } RHO_GLOBAL void alert_play_file(char* file_name, char *media_type) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "playFile", "(Ljava/lang/String;Ljava/lang/String;)V"); if (!mid) return; jstring objFileName = rho_cast<jstring>(file_name); jstring objMediaType = media_type ? rho_cast<jstring>(media_type) : NULL; env->CallStaticVoidMethod(cls, mid, objFileName, objMediaType); env->DeleteLocalRef(objFileName); if (objMediaType) env->DeleteLocalRef(objMediaType); }
Fix JNI string leaks on Android
Fix JNI string leaks on Android This cause rhogallery crashes on ~20 minutes after start
C++
mit
pslgoh/rhodes,watusi/rhodes,tauplatform/tau,rhomobile/rhodes,watusi/rhodes,pslgoh/rhodes,rhomobile/rhodes,tauplatform/tau,tauplatform/tau,watusi/rhodes,rhomobile/rhodes,rhomobile/rhodes,watusi/rhodes,pslgoh/rhodes,watusi/rhodes,watusi/rhodes,tauplatform/tau,watusi/rhodes,watusi/rhodes,pslgoh/rhodes,pslgoh/rhodes,tauplatform/tau,rhomobile/rhodes,tauplatform/tau,rhomobile/rhodes,pslgoh/rhodes,watusi/rhodes,rhomobile/rhodes,rhomobile/rhodes,pslgoh/rhodes,tauplatform/tau,pslgoh/rhodes,rhomobile/rhodes,tauplatform/tau,pslgoh/rhodes,pslgoh/rhodes,rhomobile/rhodes,watusi/rhodes,tauplatform/tau,tauplatform/tau
5ed80c1763110b1bde83bc408b365b091729c5aa
test/modern/smoke.cxx
test/modern/smoke.cxx
/* * Fast Positive Tuples (libfptu), aka Позитивные Кортежи * Copyright 2016-2020 Leonid Yuriev <[email protected]> * * 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 "../fptu_test.h" #include "fast_positive/tuples/details/cpu_features.h" #include <array> #include <vector> #include "fast_positive/tuples/details/warnings_push_pt.h" //------------------------------------------------------------------------------ #pragma pack(push, 1) struct Foo { char x; int Bar; }; #pragma pack(pop) struct MyToken_FooBar_int : public FPTU_TOKEN(Foo, Bar) { MyToken_FooBar_int() noexcept { static_assert(static_offset == 1, "WTF?"); static_assert(std::is_base_of<::fptu::details::token_static_tag, MyToken_FooBar_int>::value, "WTF?"); static_assert(MyToken_FooBar_int::is_static_token::value, "WTF?"); } }; FPTU_TEMPLATE_FOR_STATIC_TOKEN bool probe2static(const TOKEN &token) { (void)token; return true; } bool probe2static(const fptu::token &token) { (void)token; return false; } TEST(Token, StaticPreplaced) { MyToken_FooBar_int token; EXPECT_TRUE(token.is_preplaced()); EXPECT_FALSE(token.is_loose()); EXPECT_FALSE(token.is_inlay()); EXPECT_FALSE(token.is_collection()); EXPECT_EQ(fptu::genus::i32, token.type()); EXPECT_TRUE(probe2static(token)); EXPECT_TRUE(MyToken_FooBar_int::is_static_preplaced()); EXPECT_TRUE(MyToken_FooBar_int::is_static_token::value); #ifndef __clang__ const fptu::tuple_ro_weak tuple_ro; /* FIXME: CLANG ?-6-7-8 WTF? */ EXPECT_THROW(tuple_ro.collection(token).empty(), ::fptu::collection_required); #endif } #ifdef __clang__ TEST(clang_WTF, DISABLED_ExceptionHandling) { #else TEST(clang_WTF, ExceptionHandling) { #endif try { bool got_collection_required_exception = false; try { // fptu::throw_collection_required(); const fptu::tuple_ro_weak tuple_ro; MyToken_FooBar_int token; tuple_ro.collection(token).empty(); } catch (const ::fptu::collection_required &) { got_collection_required_exception = true; } EXPECT_TRUE(got_collection_required_exception); } catch (const ::std::exception &e) { std::string msg = fptu::format("Unexpected exception type '%s': %s", typeid(e).name(), e.what()); GTEST_FATAL_FAILURE_(msg.c_str()); } catch (...) { GTEST_FATAL_FAILURE_("Unknown NOT std::exception"); } } //------------------------------------------------------------------------------ TEST(Smoke, trivia_set) { fptu::tuple_rw_managed rw; fptu::token token(fptu::u16, 0); rw.set_u16(token, 42); auto value = rw.get_u16(token); EXPECT_EQ(42, value); } TEST(Smoke, trivia_autogrowth) { fptu::tuple_rw_managed rw; fptu::token token(fptu::text, 0, true); EXPECT_GT(size_t(fptu::max_tuple_bytes_netto), rw.capacity()); for (int i = 1; i < 555; ++i) rw.insert_string(token, fptu::format("This is the string #%*d.", i - 555, i)); EXPECT_EQ(size_t(fptu::max_tuple_bytes_netto), rw.capacity()); } TEST(Smoke, autogrowth_with_preplaced) { auto schema = fptu::schema::create(); std::vector<std::pair<std::string, std::size_t>> values = { {"event_src.host", 16}, {"event_src.hostname", 16}, {"event_src.subsys", 8}, {"event_src.title", 7}, {"event_src.vendor", 9}, /*{"generator", 9},*/ {"id", 53}, {"mime", 25}, {"msgid", 4}, {"object.id", 1037}}; for (auto p : values) schema->define_loose(std::move(p.first), fptu::genus::text); schema->define_preplaced("generator", fptu::genus::text); fptu::defaults::setup(fptu::initiation_scale::small, std::move(schema)); fptu::tuple_rw_managed rw; for (auto p : values) { std::string stub{}; stub.resize(p.second, 'a'); rw.set_string(fptu::defaults::schema->get_token(p.first.data()), stub); } rw.take_managed_clone_optimized(); } TEST(Smoke, trivia_managing) { cxx14_constexpr fptu::token token_utc32(fptu::genus::datetime_utc, 0); cxx14_constexpr fptu::token token_datetime64(fptu::genus::datetime_utc, 0); cxx14_constexpr fptu::token token_i64(fptu::i64, 0); fptu::tuple_rw_fixed rw_fixed; rw_fixed.set_datetime(token_utc32, fptu::datetime_t::now()); rw_fixed.set_datetime(token_utc32, fptu::datetime_t::now_coarse()); rw_fixed.set_datetime(token_datetime64, fptu::datetime_t::now_fine()); rw_fixed.set_integer(token_i64, INT64_MIN); rw_fixed.set_integer(token_i64, INT64_MAX); fptu::tuple_ro_weak ro_weak = rw_fixed.take_weak().first; EXPECT_FALSE(ro_weak.empty()); EXPECT_TRUE(ro_weak.is_present(token_utc32)); EXPECT_TRUE(ro_weak.is_present(token_datetime64)); EXPECT_TRUE(ro_weak.is_present(token_i64)); fptu::tuple_ro_managed ro_managed = rw_fixed.take_managed_clone().first; EXPECT_EQ(ro_weak.size(), ro_managed.size()); EXPECT_EQ(0, std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size())); ro_managed = rw_fixed.move_to_ro(); EXPECT_EQ(ro_weak.size(), ro_managed.size()); EXPECT_EQ(0, std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size())); rw_fixed = std::move(ro_managed); ro_managed = rw_fixed.take_managed_clone().first; EXPECT_EQ(ro_weak.size(), ro_managed.size()); EXPECT_EQ(0, std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size())); rw_fixed = fptu::tuple_rw_fixed::clone(ro_managed); ro_weak = rw_fixed.take_weak().first; EXPECT_EQ(ro_weak.size(), ro_managed.size()); EXPECT_EQ(0, std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size())); rw_fixed = fptu::tuple_rw_fixed::clone(ro_weak); ro_weak = rw_fixed.take_weak().first; EXPECT_EQ(ro_weak.size(), ro_managed.size()); EXPECT_EQ(0, std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size())); EXPECT_EQ(1, ro_managed.get_buffer()->ref_counter); auto ro_managed2 = ro_managed; EXPECT_EQ(2, ro_managed.get_buffer()->ref_counter); ro_managed.purge(); EXPECT_FALSE(ro_managed); EXPECT_EQ(1, ro_managed2.get_buffer()->ref_counter); } //------------------------------------------------------------------------------ TEST(Smoke, trivia_schema_definition) { auto schema = fptu::schema::create(); for (unsigned n = 0; n < 42; ++n) for (fptu::genus type = fptu::genus(0); type != fptu::genus::hole; type = fptu::genus(type + 1)) schema->define_field( false, fptu::format("#%u of %s", n, std::to_string(type).c_str()), type); std::set<std::string> names = {"datafield1", "event_src.host", "event_src.ip", "event_src.title", "generator", "id", "mime", "object.name", "reason", "subject.group", "subject.id", "tag", "type"}; for (auto item : names) schema->define_field(item == "generator", std::move(item), fptu::genus::text); fptu::defaults::setup(fptu::initiation_scale::small, std::move(schema)); fptu::tuple_rw_managed rw; rw.set_string(fptu::defaults::schema->get_token("datafield1"), std::string("229099411")); rw.set_string(fptu::defaults::schema->get_token("event_src.host"), std::string("91.142.135.113")); rw.set_string(fptu::defaults::schema->get_token("event_src.ip"), std::string("91.142.135.113")); rw.set_string(fptu::defaults::schema->get_token("event_src.title"), std::string("unix_like")); rw.set_string(fptu::defaults::schema->get_token("generator"), std::string("N8.0.1309")); rw.set_string(fptu::defaults::schema->get_token("id"), std::string("PT_UNIX_like_auditd_syslog_path_msg")); rw.set_string(fptu::defaults::schema->get_token("mime"), std::string("text/plain")); rw.set_string(fptu::defaults::schema->get_token("object.name"), std::string("/proc/1/comm")); rw.set_string(fptu::defaults::schema->get_token("reason"), std::string("File was created or deleted")); rw.set_string(fptu::defaults::schema->get_token("subject.group"), std::string("0")); rw.set_string(fptu::defaults::schema->get_token("subject.id"), std::string("0")); rw.set_string(fptu::defaults::schema->get_token("tag"), std::string("syslog")); rw.set_string(fptu::defaults::schema->get_token("type"), std::string("norm")); rw.take_managed_clone_optimized(); } //------------------------------------------------------------------------------ int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
/* * Fast Positive Tuples (libfptu), aka Позитивные Кортежи * Copyright 2016-2020 Leonid Yuriev <[email protected]> * * 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 "../fptu_test.h" #include "fast_positive/erthink/erthink_misc.h" #include "fast_positive/tuples/details/cpu_features.h" #include <array> #include <vector> #include "fast_positive/tuples/details/warnings_push_pt.h" //------------------------------------------------------------------------------ #pragma pack(push, 1) struct Foo { char x; int Bar; }; #pragma pack(pop) struct MyToken_FooBar_int : public FPTU_TOKEN(Foo, Bar) { MyToken_FooBar_int() noexcept { static_assert(static_offset == 1, "WTF?"); static_assert(std::is_base_of<::fptu::details::token_static_tag, MyToken_FooBar_int>::value, "WTF?"); static_assert(MyToken_FooBar_int::is_static_token::value, "WTF?"); } }; FPTU_TEMPLATE_FOR_STATIC_TOKEN bool probe2static(const TOKEN &token) { (void)token; return true; } bool probe2static(const fptu::token &token) { (void)token; return false; } TEST(Token, StaticPreplaced) { MyToken_FooBar_int token; EXPECT_TRUE(token.is_preplaced()); EXPECT_FALSE(token.is_loose()); EXPECT_FALSE(token.is_inlay()); EXPECT_FALSE(token.is_collection()); EXPECT_EQ(fptu::genus::i32, token.type()); EXPECT_TRUE(probe2static(token)); EXPECT_TRUE(MyToken_FooBar_int::is_static_preplaced()); EXPECT_TRUE(MyToken_FooBar_int::is_static_token::value); #ifndef __clang__ const fptu::tuple_ro_weak tuple_ro; /* FIXME: CLANG ?-6-7-8 WTF? */ EXPECT_THROW(tuple_ro.collection(token).empty(), ::fptu::collection_required); #endif } #ifdef __clang__ TEST(clang_WTF, DISABLED_ExceptionHandling) { #else TEST(clang_WTF, ExceptionHandling) { #endif try { bool got_collection_required_exception = false; try { // fptu::throw_collection_required(); const fptu::tuple_ro_weak tuple_ro; MyToken_FooBar_int token; tuple_ro.collection(token).empty(); } catch (const ::fptu::collection_required &) { got_collection_required_exception = true; } EXPECT_TRUE(got_collection_required_exception); } catch (const ::std::exception &e) { std::string msg = fptu::format("Unexpected exception type '%s': %s", typeid(e).name(), e.what()); GTEST_FATAL_FAILURE_(msg.c_str()); } catch (...) { GTEST_FATAL_FAILURE_("Unknown NOT std::exception"); } } //------------------------------------------------------------------------------ TEST(Smoke, trivia_set) { fptu::tuple_rw_managed rw; fptu::token token(fptu::u16, 0); rw.set_u16(token, 42); auto value = rw.get_u16(token); EXPECT_EQ(42, value); } TEST(Smoke, trivia_autogrowth) { fptu::tuple_rw_managed rw; fptu::token token(fptu::text, 0, true); EXPECT_GT(size_t(fptu::max_tuple_bytes_netto), rw.capacity()); for (int i = 1; i < 555; ++i) rw.insert_string(token, fptu::format("This is the string #%*d.", i - 555, i)); EXPECT_EQ(size_t(fptu::max_tuple_bytes_netto), rw.capacity()); } TEST(Smoke, autogrowth_with_preplaced) { auto schema = fptu::schema::create(); std::vector<std::pair<std::string, std::size_t>> values = { {"event_src.host", 16}, {"event_src.hostname", 16}, {"event_src.subsys", 8}, {"event_src.title", 7}, {"event_src.vendor", 9}, /*{"generator", 9},*/ {"id", 53}, {"mime", 25}, {"msgid", 4}, {"object.id", 1037}}; for (auto p : values) schema->define_loose(std::move(p.first), fptu::genus::text); schema->define_preplaced("generator", fptu::genus::text); fptu::defaults::setup(fptu::initiation_scale::small, std::move(schema)); fptu::tuple_rw_managed rw; for (auto p : values) { std::string stub{}; stub.resize(p.second, 'a'); rw.set_string(fptu::defaults::schema->get_token(p.first.data()), stub); } rw.take_managed_clone_optimized(); } TEST(Smoke, trivia_managing) { cxx14_constexpr fptu::token token_utc32(fptu::genus::datetime_utc, 0); cxx14_constexpr fptu::token token_datetime64(fptu::genus::datetime_utc, 0); cxx14_constexpr fptu::token token_i64(fptu::i64, 0); fptu::tuple_rw_fixed rw_fixed; rw_fixed.set_datetime(token_utc32, fptu::datetime_t::now()); rw_fixed.set_datetime(token_utc32, fptu::datetime_t::now_coarse()); rw_fixed.set_datetime(token_datetime64, fptu::datetime_t::now_fine()); rw_fixed.set_integer(token_i64, INT64_MIN); rw_fixed.set_integer(token_i64, INT64_MAX); fptu::tuple_ro_weak ro_weak = rw_fixed.take_weak().first; EXPECT_FALSE(ro_weak.empty()); EXPECT_TRUE(ro_weak.is_present(token_utc32)); EXPECT_TRUE(ro_weak.is_present(token_datetime64)); EXPECT_TRUE(ro_weak.is_present(token_i64)); fptu::tuple_ro_managed ro_managed = rw_fixed.take_managed_clone().first; EXPECT_EQ(ro_weak.size(), ro_managed.size()); EXPECT_EQ(0, std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size())); ro_managed = rw_fixed.move_to_ro(); EXPECT_EQ(ro_weak.size(), ro_managed.size()); EXPECT_EQ(0, std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size())); rw_fixed = std::move(ro_managed); ro_managed = rw_fixed.take_managed_clone().first; EXPECT_EQ(ro_weak.size(), ro_managed.size()); EXPECT_EQ(0, std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size())); rw_fixed = fptu::tuple_rw_fixed::clone(ro_managed); ro_weak = rw_fixed.take_weak().first; EXPECT_EQ(ro_weak.size(), ro_managed.size()); EXPECT_EQ(0, std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size())); rw_fixed = fptu::tuple_rw_fixed::clone(ro_weak); ro_weak = rw_fixed.take_weak().first; EXPECT_EQ(ro_weak.size(), ro_managed.size()); EXPECT_EQ(0, std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size())); EXPECT_EQ(1, ro_managed.get_buffer()->ref_counter); auto ro_managed2 = ro_managed; EXPECT_EQ(2, ro_managed.get_buffer()->ref_counter); ro_managed.purge(); EXPECT_FALSE(ro_managed); EXPECT_EQ(1, ro_managed2.get_buffer()->ref_counter); } //------------------------------------------------------------------------------ TEST(Smoke, trivia_schema_definition) { auto schema = fptu::schema::create(); for (unsigned n = 0; n < 42; ++n) for (fptu::genus type = fptu::genus(0); type != fptu::genus::hole; type = fptu::genus(type + 1)) schema->define_field( false, fptu::format("#%u of %s", n, std::to_string(type).data()), type); std::set<std::string> names = {"datafield1", "event_src.host", "event_src.ip", "event_src.title", "generator", "id", "mime", "object.name", "reason", "subject.group", "subject.id", "tag", "type"}; for (auto item : names) schema->define_field(item == "generator", std::move(item), fptu::genus::text); fptu::defaults::setup(fptu::initiation_scale::small, std::move(schema)); fptu::tuple_rw_managed rw; rw.set_string(fptu::defaults::schema->get_token("datafield1"), std::string("229099411")); rw.set_string(fptu::defaults::schema->get_token("event_src.host"), std::string("91.142.135.113")); rw.set_string(fptu::defaults::schema->get_token("event_src.ip"), std::string("91.142.135.113")); rw.set_string(fptu::defaults::schema->get_token("event_src.title"), std::string("unix_like")); rw.set_string(fptu::defaults::schema->get_token("generator"), std::string("N8.0.1309")); rw.set_string(fptu::defaults::schema->get_token("id"), std::string("PT_UNIX_like_auditd_syslog_path_msg")); rw.set_string(fptu::defaults::schema->get_token("mime"), std::string("text/plain")); rw.set_string(fptu::defaults::schema->get_token("object.name"), std::string("/proc/1/comm")); rw.set_string(fptu::defaults::schema->get_token("reason"), std::string("File was created or deleted")); rw.set_string(fptu::defaults::schema->get_token("subject.group"), std::string("0")); rw.set_string(fptu::defaults::schema->get_token("subject.id"), std::string("0")); rw.set_string(fptu::defaults::schema->get_token("tag"), std::string("syslog")); rw.set_string(fptu::defaults::schema->get_token("type"), std::string("norm")); rw.take_managed_clone_optimized(); } //------------------------------------------------------------------------------ template <typename Iter> ptrdiff_t distance_safe(Iter from, Iter to, const bool forward, const ptrdiff_t limit) { assert(limit > 0); ptrdiff_t result = 0; while (from != to && limit > result) { if (forward) ++from; else --to; result += 1; } return result; } TEST(Smoke, trivia_iteration_ro) { static const fptu::genus basic_typeset[] = { fptu::genus::text, fptu::genus::i8, fptu::genus::u16, fptu::genus::i32, fptu::genus::f32, fptu::genus::u64, fptu::genus::f64}; const int types_num = erthink::array_length(basic_typeset); const int whole_limit = types_num * 2; int schema_iteration = 0, whole_variations = 0; // iterate schema variants for (int defined = 0; defined <= whole_limit; ++defined) for (int preplaced = 0; preplaced <= defined; ++preplaced) for (int shift_type = 0; shift_type < types_num; ++shift_type) { // prepare schema schema_iteration += 1; std::string context(fptu::format("schema #%d {", schema_iteration)); auto schema = fptu::schema::create(); for (int i = 1; i <= defined; ++i) { const bool define_preplaced = (i <= preplaced); const fptu::genus type = basic_typeset[(i + shift_type) % types_num]; std::string field_name(fptu::format("%c%02d_%s", define_preplaced ? 'P' : 'l', i, std::to_string(type).data())); context.append(" "); context.append(field_name); schema->define_field(define_preplaced, std::move(field_name), type, /* discernible_null */ true); } context.append(" }"); SCOPED_TRACE(context); fptu::defaults::setup(fptu::initiation_scale::small, std::move(schema)); // iterate null/non-null combinations int content_iteration = 0; for (int shift_nulls = 0; shift_nulls == 0 || shift_nulls < defined; ++shift_nulls) for (int nulls = 0; nulls <= defined; ++nulls) { // make tuple content_iteration += 1; fptu::tuple_rw_managed rw; std::string context(fptu::format("tuple #%d {", content_iteration)); for (int i = 0; i < defined; ++i) { const bool null = (i + shift_nulls) % defined < nulls; if (null) continue; const fptu::token token = fptu::defaults::schema->tokens().at(i); context.append(" "); context.append(fptu::defaults::schema->get_name(token)); auto field = rw[token]; if (field.is_text()) field = "42"; else field = 42; } context.append(" }"); SCOPED_TRACE(context); // check RW int expected = defined - nulls; { const auto begin = rw.begin(); const auto end = rw.end(); if (expected != 0) { ASSERT_NE(begin, end); } else { ASSERT_EQ(begin, end); } ASSERT_EQ(expected, distance_safe(begin, end, true, expected + 1)); ASSERT_EQ(expected, distance_safe(begin, end, false, expected + 1)); // check loose-iterators ASSERT_EQ(end, rw.cend()); ASSERT_EQ(end, rw.end_loose()); ASSERT_EQ(end, rw.cend_loose()); // forward auto loose = rw.cbegin_loose(); int n = 0; for (auto i = begin; i != end; ++i) { if (i->is_loose()) { ASSERT_EQ(loose, i); ++loose; ++n; } } ASSERT_EQ(loose, end); ASSERT_EQ(loose, rw.cend_loose()); // bakcward loose = rw.cend_loose(); for (auto i = end; i != begin;) { --i; if (i->is_loose()) { ASSERT_EQ(rw.cbegin_loose() + n, loose); ASSERT_EQ(rw.cbegin_loose(), loose - n); --loose; --n; ASSERT_EQ(loose, i); } } ASSERT_EQ(loose, rw.cbegin_loose()); } // check RO { fptu::tuple_ro_weak ro(rw); const auto begin = ro.begin(); const auto end = ro.end(); if (defined - nulls != 0) { ASSERT_NE(begin, end); } else { ASSERT_EQ(begin, end); } ASSERT_EQ(expected, distance_safe(begin, end, true, expected + 1)); ASSERT_EQ(expected, distance_safe(begin, end, false, expected + 1)); // check loose-iterators ASSERT_EQ(end, ro.end_loose()); ASSERT_EQ(end, ro.cend_loose()); // forward auto loose = ro.cbegin_loose(); int n = 0; for (auto i = begin; i != end; ++i) { if (i->is_loose()) { ASSERT_EQ(loose, i); ++loose; ++n; } } ASSERT_EQ(loose, end); ASSERT_EQ(loose, ro.cend_loose()); // bakcward loose = ro.cend_loose(); for (auto i = end; i != begin;) { --i; if (i->is_loose()) { ASSERT_EQ(ro.cbegin_loose() + n, loose); ASSERT_EQ(ro.cbegin_loose(), loose - n); --loose; --n; ASSERT_EQ(loose, i); } } ASSERT_EQ(loose, ro.cbegin_loose()); } whole_variations += 1; } } std::cerr << "[ ] " << whole_variations << " variations" << std::endl; } //------------------------------------------------------------------------------ int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
add test for whole-tuple ro-iterators for fields.
fptu-test: add test for whole-tuple ro-iterators for fields.
C++
apache-2.0
leo-yuriev/libfptu,leo-yuriev/libfptu
f9a24f53eccdf2004a92cf2a88ebca9fedb15f4b
include/Matrix.hpp
include/Matrix.hpp
#ifndef Matrix_hpp #define Matrix_hpp #include <iostream> template <typename T> class Matrix; template <class T> std::ostream & operator<<(std::ostream & output, const T &); template <class T> std::istream & operator>>(std::istream & output, T &); template <typename T> class Matrix { public: Matrix(const Matrix & matrix); Matrix(unsigned int rows, unsigned int columns); virtual ~Matrix(); auto rows() const -> unsigned int ; auto columns() const -> unsigned int; auto operator[](unsigned int index) const -> const int *; auto operator*(const Matrix &matrix) const -> Matrix; auto operator+(const Matrix &matrix) const -> Matrix; auto operator==(const Matrix &matrix) const -> bool; auto operator=(const Matrix &matrix) -> Matrix &; friend std::ostream & operator<< <>(std::ostream & output, const Matrix<T> & matrix); friend std::istream & operator>> <>(std::istream & input, Matrix<T> & matrix); private: unsigned int m_rows, m_columns; T **m_elements; Matrix(unsigned int rows, unsigned int columns, T **elements); void swap(Matrix & matrix); void fill(T **elements); }; template <typename T> Matrix<T>::Matrix(const Matrix<T> &matrix) : m_rows(matrix.m_rows), m_columns(matrix.m_columns) { fill(matrix.m_elements); } template <typename T> Matrix<T>::Matrix(unsigned int rows, unsigned int columns) : m_rows(rows), m_columns(columns) { fill(nullptr); } template <typename T> Matrix<T>::Matrix(unsigned int rows, unsigned int columns, T **elements) : m_rows(rows), m_columns(columns) { fill(elements); } template <typename T> void Matrix<T>::fill(T **elements) { m_elements = new T *[m_rows]; for (unsigned int i = 0; i < m_rows; ++i) { m_elements[i] = new T[m_columns]; for (unsigned int j = 0; j < m_columns; ++j) { m_elements[i][j] = elements ? elements[i][j] : 0; } } } template <typename T> auto Matrix<T>::operator=(const Matrix & matrix) -> Matrix & { if ( this != &matrix ) { Matrix(matrix).swap(*this); } return *this; } template <typename T> void Matrix<T>::swap(Matrix & matrix) { std::swap(m_rows, matrix.m_rows); std::swap(m_columns, matrix.m_columns); std::swap(m_elements, matrix.m_elements); } template <typename T> Matrix<T>::~Matrix() { for (unsigned int i = 0; i < m_rows; ++i) { delete [] m_elements[i]; } delete [] m_elements; } template <typename T> auto Matrix<T>::rows() const -> unsigned int { return m_rows; } template <typename T> auto Matrix<T>::columns() const -> unsigned int { return m_columns; } template <typename T> auto Matrix<T>::operator[](unsigned int index) const -> const int * { if ( index >= m_rows ) { throw std::invalid_argument("index goes abroad"); } return m_elements[index]; } template <typename T> auto Matrix<T>::operator*(const Matrix & matrix) const -> Matrix { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_columns != matrix.m_rows ) { throw std::invalid_argument("matrix sizes do not match"); } unsigned int n = m_rows; unsigned int m = matrix.m_columns; unsigned int s = m_columns; T **elements = new T *[n]; for (unsigned int i = 0; i < n; ++i) { elements[i] = new T[m]; for (unsigned int j = 0; j < m; ++j) { T value = 0; for (unsigned int k = 0; k < s; ++k) { value += m_elements[i][k] * matrix.m_elements[k][j]; } elements[i][j] = value; } } return Matrix(n, m, elements); } template <typename T> auto Matrix<T>::operator+(const Matrix & matrix) const -> Matrix { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) { throw std::invalid_argument("matrix sizes do not match"); } unsigned int n = m_rows; unsigned int m = m_columns; T **data = new T *[n]; for (unsigned int i = 0; i < n; ++i) { data[i] = new T[m]; for (unsigned int j = 0; j < m; ++j) { data[i][j] = m_elements[i][j] + matrix.m_elements[i][j]; } } return Matrix(n, m, data); } template <typename T> auto Matrix<T>::operator==(const Matrix & matrix) const -> bool { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) { return false; } for (unsigned int i = 0; i < m_rows; ++i) { for (unsigned int j = 0; j < m_columns; ++j) { if ( m_elements[i][j] != matrix.m_elements[i][j] ) { return false; } } } return true; } template <typename T> std::ostream & operator<<(std::ostream & output, const Matrix<T> & matrix) { for (unsigned int i = 0; i < matrix.m_rows; ++i) { output << std::endl; for (unsigned int j = 0; j < matrix.m_columns; ++j) { output << matrix.m_elements[i][j] << "\t"; } } return output; } template <typename T> std::istream & operator>>(std::istream & input, Matrix<T> & matrix) { for (unsigned int i = 0; i < matrix.m_rows; ++i) { for (unsigned int j = 0; j < matrix.m_columns; ++j) { if ( !(input >> matrix.m_elements[i][j]) ) { throw "exception in fill matrix"; } } } return input; } #endif
#ifndef Matrix_hpp #define Matrix_hpp #include <iostream> template <typename T> class Matrix; template <class T> std::ostream & operator<<(std::ostream & output, const Matrix<T> &); template <class T> std::istream & operator>>(std::istream & output, Matrix<T> &); template <typename T> class Matrix { public: Matrix(const Matrix & matrix); Matrix(unsigned int rows, unsigned int columns); virtual ~Matrix(); auto rows() const -> unsigned int ; auto columns() const -> unsigned int; auto operator[](unsigned int index) const -> const int *; auto operator*(const Matrix &matrix) const -> Matrix; auto operator+(const Matrix &matrix) const -> Matrix; auto operator==(const Matrix &matrix) const -> bool; auto operator=(const Matrix &matrix) -> Matrix &; friend std::ostream & operator<< <>(std::ostream & output, const Matrix<T> & matrix); friend std::istream & operator>> <>(std::istream & input, Matrix<T> & matrix); private: unsigned int m_rows, m_columns; T **m_elements; Matrix(unsigned int rows, unsigned int columns, T **elements); void swap(Matrix & matrix); void fill(T **elements); }; template <typename T> Matrix<T>::Matrix(const Matrix<T> &matrix) : m_rows(matrix.m_rows), m_columns(matrix.m_columns) { fill(matrix.m_elements); } template <typename T> Matrix<T>::Matrix(unsigned int rows, unsigned int columns) : m_rows(rows), m_columns(columns) { fill(nullptr); } template <typename T> Matrix<T>::Matrix(unsigned int rows, unsigned int columns, T **elements) : m_rows(rows), m_columns(columns) { fill(elements); } template <typename T> void Matrix<T>::fill(T **elements) { m_elements = new T *[m_rows]; for (unsigned int i = 0; i < m_rows; ++i) { m_elements[i] = new T[m_columns]; for (unsigned int j = 0; j < m_columns; ++j) { m_elements[i][j] = elements ? elements[i][j] : 0; } } } template <typename T> auto Matrix<T>::operator=(const Matrix & matrix) -> Matrix & { if ( this != &matrix ) { Matrix(matrix).swap(*this); } return *this; } template <typename T> void Matrix<T>::swap(Matrix & matrix) { std::swap(m_rows, matrix.m_rows); std::swap(m_columns, matrix.m_columns); std::swap(m_elements, matrix.m_elements); } template <typename T> Matrix<T>::~Matrix() { for (unsigned int i = 0; i < m_rows; ++i) { delete [] m_elements[i]; } delete [] m_elements; } template <typename T> auto Matrix<T>::rows() const -> unsigned int { return m_rows; } template <typename T> auto Matrix<T>::columns() const -> unsigned int { return m_columns; } template <typename T> auto Matrix<T>::operator[](unsigned int index) const -> const int * { if ( index >= m_rows ) { throw std::invalid_argument("index goes abroad"); } return m_elements[index]; } template <typename T> auto Matrix<T>::operator*(const Matrix & matrix) const -> Matrix { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_columns != matrix.m_rows ) { throw std::invalid_argument("matrix sizes do not match"); } unsigned int n = m_rows; unsigned int m = matrix.m_columns; unsigned int s = m_columns; T **elements = new T *[n]; for (unsigned int i = 0; i < n; ++i) { elements[i] = new T[m]; for (unsigned int j = 0; j < m; ++j) { T value = 0; for (unsigned int k = 0; k < s; ++k) { value += m_elements[i][k] * matrix.m_elements[k][j]; } elements[i][j] = value; } } return Matrix(n, m, elements); } template <typename T> auto Matrix<T>::operator+(const Matrix & matrix) const -> Matrix { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) { throw std::invalid_argument("matrix sizes do not match"); } unsigned int n = m_rows; unsigned int m = m_columns; T **data = new T *[n]; for (unsigned int i = 0; i < n; ++i) { data[i] = new T[m]; for (unsigned int j = 0; j < m; ++j) { data[i][j] = m_elements[i][j] + matrix.m_elements[i][j]; } } return Matrix(n, m, data); } template <typename T> auto Matrix<T>::operator==(const Matrix & matrix) const -> bool { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) { return false; } for (unsigned int i = 0; i < m_rows; ++i) { for (unsigned int j = 0; j < m_columns; ++j) { if ( m_elements[i][j] != matrix.m_elements[i][j] ) { return false; } } } return true; } template <typename T> std::ostream & operator<<(std::ostream & output, const Matrix<T> & matrix) { for (unsigned int i = 0; i < matrix.m_rows; ++i) { output << std::endl; for (unsigned int j = 0; j < matrix.m_columns; ++j) { output << matrix.m_elements[i][j] << "\t"; } } return output; } template <typename T> std::istream & operator>>(std::istream & input, Matrix<T> & matrix) { for (unsigned int i = 0; i < matrix.m_rows; ++i) { for (unsigned int j = 0; j < matrix.m_columns; ++j) { if ( !(input >> matrix.m_elements[i][j]) ) { throw "exception in fill matrix"; } } } return input; } #endif
Update Matrix.hpp
Update Matrix.hpp
C++
mit
ArtemKokorinStudent/External-sort,ArtemKokorinStudent/StackW
fbaab01f8fcb929dee2ec83d7120b5562225a0df
include/matrix.hpp
include/matrix.hpp
#include <iostream> #include <fstream> #include <string> #include <stdlib.h> using namespace std; class Matrix { private: int columns; int strings; int **matrix; public: Matrix(); Matrix(int a, int b); void print(void) const; void input(char *path); void set(int x, int y, int z); int get(int x, int y) const; Matrix operator+ (Matrix a) const; Matrix operator* (Matrix a) const; Matrix& operator= (Matrix &other); bool operator== (Matrix &a) const; friend istream& operator>> (istream& infile, const Matrix& result); friend ostream& operator<< (ostream& os, const Matrix& a); friend istream& operator>> (istream& is, Matrix& a); ~Matrix(); };
#include <iostream> #include <fstream> #include <string> #include <stdlib.h> using namespace std; class Matrix { private: int columns; int strings; int **matrix; public: Matrix(); Matrix(int a, int b); void print(void) const; void input(char *path); void set(int x, int y, int z); int get(int x, int y) const; Matrix operator+ (Matrix a) const; Matrix operator* (Matrix a) const; Matrix& operator= (Matrix &other); bool operator== (Matrix &a) const; friend istream& operator>> (istream& infile, const Matrix& result); friend ostream& operator<< (ostream& os, const Matrix& a); ~Matrix(); };
Update matrix.hpp
Update matrix.hpp
C++
mit
elinagabitova/matrix
f488fc513b914ebc9950c55ebf6cfe2bd08a18a8
include/vertex.hpp
include/vertex.hpp
#ifndef VERTEX_H #define VERTEX_H #include <glm/glm.hpp> using namespace glm; class Vertex { public: Vertex(const vec3 &pos) { this->pos = pos; } protected: private: vec3 pos; }; #endif
#ifndef VERTEX_H #define VERTEX_H #include <glm/glm.hpp> using namespace glm; class Vertex { public: Vertex(const vec3 &pos) { this->pos = pos; } protected: private: vec3 pos; }; #endif
format vertex
format vertex
C++
mit
shakram02/opengl_shapes,shakram02/opengl_shapes,shakram02/opengl_shapes
8f6367198fe0417299109a77f92ba772c1e737e7
test/partitioning.cpp
test/partitioning.cpp
#include <cmath> #include "bulk_test_common.hpp" #include "set_backend.hpp" #include <bulk/bulk.hpp> namespace bulk { using namespace experimental; } extern environment env; void test_partitioning() { auto N = (int)sqrt(env.available_processors()); env.spawn(N * N, [](auto& world) { int s = world.processor_id(); int p = world.active_processors(); auto N = (int)sqrt(p); BULK_SKIP_SECTION_IF("Partitionings", N * N != p); BULK_SECTION("Cyclic partitioning to 1D") { auto part = bulk::cyclic_partitioning<2, 1>({5 * p * N, 5 * p * N}, {p}); BULK_CHECK(part.owner({p + 2, 3}) == 2, "compute correctly the cyclic from 2 -> 1 dim"); BULK_CHECK(part.local_size({s})[0] == 5 * N, "compute correctly the extent in cyclic dim"); BULK_CHECK(part.local_size({s})[1] == 5 * p * N, "compute correctly the extent in non-cyclic dim"); BULK_CHECK(part.global_to_local({p + 2, 3})[0] == 1, "compute correctly the local index"); } BULK_SECTION("Cyclic partitioning") { auto part = bulk::cyclic_partitioning<2, 2>({10 * N, 10 * N}, {N, N}); BULK_CHECK(part.grid_owner({4, 3})[0] == 4 % N, "compute correctly the cyclic owner"); BULK_CHECK(part.local_size({s % N, s / N})[0] == 10, "compute correctly the cyclic size"); BULK_CHECK(part.global_to_local({4, 3})[0] == 4 / N, "compute correctly the cyclic local index"); BULK_CHECK(part.local_to_global({1, 1}, {s % N, s / N})[0] == N, "compute correctly the cyclic global index"); } BULK_SECTION("Block partitioning") { auto part = bulk::block_partitioning<2, 2>({10 * N, 10 * N}, {N, N}); BULK_CHECK(part.grid_owner({2 * 10 + 3, 3})[0] == 2, "compute correctly the block owner"); BULK_CHECK(part.local_size({s % N, s / N})[0] == 10, "compute correctly the block extent"); BULK_CHECK(part.global_to_local({3, 12})[1] == 2, "compute correctly the block index"); BULK_CHECK(part.origin(0)[0] == 0, "compute correctly the block origin (0)"); BULK_CHECK(part.origin(1)[0] == 10, "compute correctly the block origin (1)"); BULK_CHECK(part.origin(2)[1] == 10, "compute correctly the block origin (2)"); } BULK_SECTION("Block partitioning custom axes") { // construct a block partitioning only in the 2nd axis auto part = bulk::block_partitioning<2, 1>({10 * p, 10 * p}, {p}, {1}); BULK_CHECK(part.owner({0, 13}) == 1, "compute correctly the block owner"); BULK_CHECK(part.local_size(1)[0] == 10 * p, "compute correctly the block size [0]"); BULK_CHECK(part.local_size(1)[1] == 10, "compute correctly the block size [1]"); BULK_CHECK(part.global_to_local({3, 12})[1] == 2, "compute correctly the block index"); BULK_CHECK(part.origin(0)[1] == 0, "compute correctly the block origin (0)[1]"); BULK_CHECK(part.origin(1)[1] == 10, "compute correctly the block origin (1)[1]"); BULK_CHECK(part.origin(2)[1] == 20, "compute correctly the block origin (2)[1]"); BULK_CHECK(part.origin(0)[0] == 0, "compute correctly the block origin (0)[0]"); BULK_CHECK(part.origin(1)[0] == 0, "compute correctly the block origin (1)[0]"); } BULK_SECTION("Binary-split-partitioning") { using dir = bulk::util::binary_tree<bulk::util::split>::dir; auto tree = bulk::util::binary_tree<bulk::util::split>( bulk::util::split{0, 5}); auto root = tree.root.get(); tree.add(root, dir::left, bulk::util::split{1, 5}); tree.add(root, dir::right, bulk::util::split{1, 5}); auto part = bulk::tree_partitioning<2>({10, 10}, 4, std::move(tree)); BULK_CHECK((part.local_size({0}) == std::array<int, 2>{5, 5}), "extent of bspart are correct"); BULK_CHECK((part.owner({1, 1}) == part.owner({2, 2})), "assign correct owner bspart (1)"); BULK_CHECK((part.owner({1, 1}) != part.owner({6, 7})), "assign correct owner bspart (2)"); BULK_CHECK((part.origin(1) == std::array<int, 2>{5, 0}), "assign correct origin bspart (1)"); BULK_CHECK((part.origin(2) == std::array<int, 2>{0, 5}), "assign correct origin bspart (2)"); BULK_CHECK((part.origin(3) == std::array<int, 2>{5, 5}), "assign correct origin bspart (3)"); BULK_CHECK( (part.global_to_local({6, 6}) == std::array<int, 2>{1, 1}), "assign correct origin bspart"); } BULK_SECTION("Partitioned array") { auto part = bulk::cyclic_partitioning<2>({200, 200}, {N, N}); auto xs = bulk::partitioned_array<int, 2, 2>(world, part); xs.local({0, 0}) = s; xs.local({1, 1}) = s + 1; auto glob = xs.global({1, 1}).get(); world.sync(); BULK_CHECK(glob.value() == N + 1, "obtain remote value"); BULK_CHECK(xs.local({1, 1}) == s + 1, "obtain local value"); xs.global({1, 1}) = 1234; world.sync(); glob = xs.global({1, 1}).get(); world.sync(); BULK_CHECK(glob.value() == 1234, "put remote value"); } }); }
#include <cmath> #include "bulk_test_common.hpp" #include "set_backend.hpp" #include <bulk/bulk.hpp> namespace bulk { using namespace experimental; } extern environment env; void test_partitioning() { auto N = (int)sqrt(env.available_processors()); env.spawn(N * N, [](auto& world) { int s = world.processor_id(); int p = world.active_processors(); auto N = (int)sqrt(p); BULK_SKIP_SECTION_IF("Partitionings", N * N != p); BULK_SECTION("Cyclic partitioning to 1D") { auto part = bulk::cyclic_partitioning<2, 1>({5 * p * N, 5 * p * N}, {p}); BULK_CHECK(part.owner({p + 2, 3}) == 2, "compute correctly the cyclic from 2 -> 1 dim"); BULK_CHECK(part.local_size({s})[0] == 5 * N, "compute correctly the extent in cyclic dim"); BULK_CHECK(part.local_size({s})[1] == 5 * p * N, "compute correctly the extent in non-cyclic dim"); BULK_CHECK(part.global_to_local({p + 2, 3})[0] == 1, "compute correctly the local index"); } BULK_SECTION("Cyclic partitioning") { auto part = bulk::cyclic_partitioning<2, 2>({10 * N, 10 * N}, {N, N}); BULK_CHECK(part.grid_owner({4, 3})[0] == 4 % N, "compute correctly the cyclic owner"); BULK_CHECK(part.local_size({s % N, s / N})[0] == 10, "compute correctly the cyclic size"); BULK_CHECK(part.global_to_local({4, 3})[0] == 4 / N, "compute correctly the cyclic local index"); BULK_CHECK(part.local_to_global({1, 1}, {s % N, s / N})[0] == N + (s % N), "compute correctly the cyclic global index"); } BULK_SECTION("Block partitioning") { auto part = bulk::block_partitioning<2, 2>({10 * N, 10 * N}, {N, N}); BULK_CHECK(part.grid_owner({2 * 10 + 3, 3})[0] == 2, "compute correctly the block owner"); BULK_CHECK(part.local_size({s % N, s / N})[0] == 10, "compute correctly the block extent"); BULK_CHECK(part.global_to_local({3, 12})[1] == 2, "compute correctly the block index"); BULK_CHECK(part.origin(0)[0] == 0, "compute correctly the block origin (0)"); BULK_CHECK(part.origin(1)[0] == 10, "compute correctly the block origin (1)"); BULK_CHECK(part.origin(2)[1] == 10, "compute correctly the block origin (2)"); } BULK_SECTION("Block partitioning custom axes") { // construct a block partitioning only in the 2nd axis auto part = bulk::block_partitioning<2, 1>({10 * p, 10 * p}, {p}, {1}); BULK_CHECK(part.owner({0, 13}) == 1, "compute correctly the block owner"); BULK_CHECK(part.local_size(1)[0] == 10 * p, "compute correctly the block size [0]"); BULK_CHECK(part.local_size(1)[1] == 10, "compute correctly the block size [1]"); BULK_CHECK(part.global_to_local({3, 12})[1] == 2, "compute correctly the block index"); BULK_CHECK(part.origin(0)[1] == 0, "compute correctly the block origin (0)[1]"); BULK_CHECK(part.origin(1)[1] == 10, "compute correctly the block origin (1)[1]"); BULK_CHECK(part.origin(2)[1] == 20, "compute correctly the block origin (2)[1]"); BULK_CHECK(part.origin(0)[0] == 0, "compute correctly the block origin (0)[0]"); BULK_CHECK(part.origin(1)[0] == 0, "compute correctly the block origin (1)[0]"); } BULK_SECTION("Binary-split-partitioning") { using dir = bulk::util::binary_tree<bulk::util::split>::dir; auto tree = bulk::util::binary_tree<bulk::util::split>( bulk::util::split{0, 5}); auto root = tree.root.get(); tree.add(root, dir::left, bulk::util::split{1, 5}); tree.add(root, dir::right, bulk::util::split{1, 5}); auto part = bulk::tree_partitioning<2>({10, 10}, 4, std::move(tree)); BULK_CHECK((part.local_size({0}) == std::array<int, 2>{5, 5}), "extent of bspart are correct"); BULK_CHECK((part.owner({1, 1}) == part.owner({2, 2})), "assign correct owner bspart (1)"); BULK_CHECK((part.owner({1, 1}) != part.owner({6, 7})), "assign correct owner bspart (2)"); BULK_CHECK((part.origin(1) == std::array<int, 2>{5, 0}), "assign correct origin bspart (1)"); BULK_CHECK((part.origin(2) == std::array<int, 2>{0, 5}), "assign correct origin bspart (2)"); BULK_CHECK((part.origin(3) == std::array<int, 2>{5, 5}), "assign correct origin bspart (3)"); BULK_CHECK( (part.global_to_local({6, 6}) == std::array<int, 2>{1, 1}), "assign correct origin bspart"); } BULK_SECTION("Partitioned array") { auto part = bulk::cyclic_partitioning<2>({200, 200}, {N, N}); auto xs = bulk::partitioned_array<int, 2, 2>(world, part); xs.local({0, 0}) = s; xs.local({1, 1}) = s + 1; auto glob = xs.global({1, 1}).get(); world.sync(); BULK_CHECK(glob.value() == N + 1, "obtain remote value"); BULK_CHECK(xs.local({1, 1}) == s + 1, "obtain local value"); xs.global({1, 1}) = 1234; world.sync(); glob = xs.global({1, 1}).get(); world.sync(); BULK_CHECK(glob.value() == 1234, "put remote value"); } }); }
Fix cyclic global index check
Fix cyclic global index check
C++
mit
jwbuurlage/Bulk
d3553a5338e1622682827f49eb12f99eebdbf5e8
o3d/statsreport/metrics_unittest.cc
o3d/statsreport/metrics_unittest.cc
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Metrics report unit testing #include <new> #include <algorithm> #include "gtest/gtest.h" #include "metrics.h" DECLARE_METRIC_count(count); DEFINE_METRIC_count(count); DECLARE_METRIC_timing(timing); DEFINE_METRIC_timing(timing); DECLARE_METRIC_integer(integer); DEFINE_METRIC_integer(integer); DECLARE_METRIC_bool(bool); DEFINE_METRIC_bool(bool); using ::stats_report::BoolMetric; using ::stats_report::CountMetric; using ::stats_report::IntegerMetric; using ::stats_report::MetricBase; using ::stats_report::MetricCollection; using ::stats_report::MetricCollectionBase; using ::stats_report::MetricIterator; using ::stats_report::TimingMetric; using ::stats_report::TimingSample; using ::stats_report::kBoolType; using ::stats_report::kCountType; using ::stats_report::kIntegerType; using ::stats_report::kTimingType; namespace { class MetricsTest: public testing::Test { protected: MetricCollection coll_; }; class MetricsEnumTest: public MetricsTest { public: virtual void SetUp() { coll_.Initialize(); } virtual void TearDown() { coll_.Uninitialize(); } protected: MetricsEnumTest(): count_("count", &coll_), timing_("timing", &coll_), integer_("integer", &coll_), bool_("bool", &coll_) { } CountMetric count_; TimingMetric timing_; IntegerMetric integer_; BoolMetric bool_; }; } // namespace // Validates that the above-declared metrics are available // in the expected namespace TEST_F(MetricsTest, Globals) { EXPECT_EQ(0, ::metric_count.Reset()); TimingMetric::TimingData data = ::metric_timing.Reset(); EXPECT_EQ(0, data.count); EXPECT_EQ(0, data.maximum); EXPECT_EQ(0, data.minimum); EXPECT_EQ(0, data.sum); EXPECT_EQ(0, ::metric_integer.value()); EXPECT_EQ(BoolMetric::kBoolUnset, ::metric_bool.Reset()); // Check for correct initialization EXPECT_STREQ("count", metric_count.name()); EXPECT_STREQ("timing", metric_timing.name()); EXPECT_STREQ("integer", metric_integer.name()); EXPECT_STREQ("bool", metric_bool.name()); } // make GUnit happy inline std::ostream &operator << (std::ostream &str, const MetricIterator &it) { str << std::hex << reinterpret_cast<void*>(*it); return str; } TEST_F(MetricsTest, CollectionInitialization) { // The global MetricCollection is aliased to zero memory so as to ensure // no initialization order snafus. If an initialized MetricCollection // sets any of its storage to non-zero, there's a good chance that e.g. a // vtbl has snuck in there, which must not happen char buf1[sizeof(MetricCollection)] = { 0 }; char buf2[sizeof(MetricCollection)] = { 0 }; // Placement new a MetricCollection to one of the buffers new (buf1) MetricCollection(); // and check they're still equivalent EXPECT_EQ(0, memcmp(buf1, buf2, sizeof(MetricCollection))); // MetricCollection must not extend MetricCollectionBase in size EXPECT_EQ(sizeof(MetricCollection), sizeof(MetricCollectionBase)); } TEST_F(MetricsTest, Count) { CountMetric foo("foo", &coll_); EXPECT_EQ(0, foo.Reset()); EXPECT_EQ(kCountType, foo.type()); ASSERT_TRUE(NULL != foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); ++foo; EXPECT_EQ(1, foo.value()); foo++; EXPECT_EQ(2, foo.value()); foo += 100; EXPECT_EQ(102, foo.value()); } TEST_F(MetricsTest, Timing) { TimingMetric foo("foo", &coll_); EXPECT_EQ(kTimingType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL != foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); foo.AddSample(100); foo.AddSample(50); EXPECT_EQ(2, foo.count()); EXPECT_EQ(150, foo.sum()); EXPECT_EQ(100, foo.maximum()); EXPECT_EQ(50, foo.minimum()); EXPECT_EQ(75, foo.average()); TimingMetric::TimingData data = foo.Reset(); EXPECT_EQ(2, data.count); EXPECT_EQ(150, data.sum); EXPECT_EQ(100, data.maximum); EXPECT_EQ(50, data.minimum); EXPECT_EQ(0, foo.count()); EXPECT_EQ(0, foo.sum()); EXPECT_EQ(0, foo.maximum()); EXPECT_EQ(0, foo.minimum()); EXPECT_EQ(0, foo.average()); // Test counted samples foo.AddSamples(10, 1000); foo.AddSamples(10, 500); EXPECT_EQ(20, foo.count()); EXPECT_EQ(1500, foo.sum()); EXPECT_EQ(100, foo.maximum()); EXPECT_EQ(50, foo.minimum()); EXPECT_EQ(75, foo.average()); } TEST_F(MetricsTest, TimingSample) { TimingMetric foo("foo", &coll_); // add a sample to foo { TimingSample sample(&foo); ::Sleep(30); } TimingMetric::TimingData data = foo.Reset(); // Should be precisely one sample in there EXPECT_EQ(1, data.count); // Disable flaky tests on build server, unfortunately this reduces coverage // too, but it seems preferrable to breaking the build on a regular basis. #ifndef BUILD_SERVER_BUILD // Let's hope the scheduler doesn't leave us hanging more than 10 ms. EXPECT_GT(40, data.sum); // The sleep above seems to often terminate early on the build server, // I've observed captured times down to 18 ms, which is strange. // TODO: figure out whether the timer is broken or whether // sleep is breaking its promise, or whether e.g. we're getting different // walltimes on different CPUs due to BIOS bugs on the build server EXPECT_LT(15, data.sum); #endif // again, this time with a non-unity count { TimingSample sample(&foo, 2); EXPECT_EQ(2, sample.count()); ::Sleep(30); } data = foo.Reset(); // Should be precisely two samples in there EXPECT_EQ(2, data.count); // Disable flaky tests on build server, unfortunately this reduces coverage // too, but it seems preferrable to breaking the build on a regular basis. #ifndef BUILD_SERVER_BUILD // Let's hope the scheduler doesn't leave us hanging more than 10 ms. EXPECT_GT(40, data.sum); EXPECT_LT(15, data.sum); #endif // now with zero count { TimingSample sample(&foo, 0); } data = foo.Reset(); // Should be no samples in there EXPECT_EQ(0, data.count); } TEST_F(MetricsTest, Integer) { IntegerMetric foo("foo", &coll_); EXPECT_EQ(kIntegerType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL != foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); EXPECT_EQ(0, foo.value()); foo.Set(1005); EXPECT_EQ(1005, foo.value()); foo = 1009UL; EXPECT_EQ(1009, foo.value()); foo.Set(0); ++foo; EXPECT_EQ(1, foo.value()); foo++; EXPECT_EQ(2, foo.value()); foo += 100; EXPECT_EQ(102, foo.value()); foo -= 100; EXPECT_EQ(2, foo.value()); foo--; EXPECT_EQ(1, foo.value()); --foo; EXPECT_EQ(0, foo.value()); } TEST_F(MetricsTest, Bool) { BoolMetric foo("foo", &coll_); EXPECT_EQ(kBoolType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL != foo.AsBool()); EXPECT_EQ(BoolMetric::kBoolUnset, foo.Reset()); foo.Set(true); EXPECT_EQ(BoolMetric::kBoolTrue, foo.Reset()); foo.Set(false); EXPECT_EQ(BoolMetric::kBoolFalse, foo.Reset()); EXPECT_EQ(BoolMetric::kBoolUnset, foo.Reset()); } TEST_F(MetricsEnumTest, Enumeration) { MetricBase *metrics[] = { &count_, &timing_, &integer_, &bool_, }; for (int i = 0; i < sizeof(metrics) / sizeof(metrics[0]); ++i) { MetricBase *stat = metrics[i]; MetricBase *curr = coll_.first(); for (; NULL != curr; curr = curr->next()) { if (stat == curr) break; } // if NULL, we didn't find our counter EXPECT_TRUE(NULL != curr); } } TEST_F(MetricsEnumTest, Iterator) { typedef MetricBase *MetricBasePtr; MetricBasePtr metrics[] = { &count_, &timing_, &integer_, &bool_, }; int num_stats = arraysize(metrics); MetricIterator it(coll_), end; EXPECT_NE(it, end); // copy construction EXPECT_EQ(it, MetricIterator(it)); EXPECT_EQ(end, MetricIterator(end)); // # of iterations int i = 0; while (it++ != end) ++i; ASSERT_EQ(num_stats, i); ASSERT_EQ(end, it); // increment past end is idempotent ++it; ASSERT_EQ(end, it); // Check that we return no garbage or nonsense for (it = MetricIterator(coll_); it != end; ++it) { MetricBasePtr *stats_end = &metrics[num_stats]; EXPECT_NE(stats_end, std::find(metrics, stats_end, *it)); } // and that all metrics can be found for (int i = 0; i < sizeof(metrics) / sizeof(metrics[0]); ++i) { MetricBase *stat = metrics[i]; EXPECT_EQ(stat, *std::find(MetricIterator(coll_), end, stat)); } } TEST_F(MetricsTest, SimpleConstruction) { const CountMetric c("c", 100); EXPECT_EQ(100, c.value()); EXPECT_EQ(kCountType, c.type()); EXPECT_STREQ("c", c.name()); EXPECT_TRUE(NULL == c.next()); TimingMetric::TimingData data = { 10, 0, 1000, 10, 500 }; const TimingMetric t("t", data); EXPECT_EQ(10, t.count()); EXPECT_EQ(1000, t.sum()); EXPECT_EQ(10, t.minimum()); EXPECT_EQ(500, t.maximum()); EXPECT_EQ(kTimingType, t.type()); EXPECT_STREQ("t", t.name()); EXPECT_TRUE(NULL == t.next()); const IntegerMetric i("i", 200); EXPECT_EQ(200, i.value()); EXPECT_EQ(kIntegerType, i.type()); EXPECT_STREQ("i", i.name()); EXPECT_TRUE(NULL == i.next()); const BoolMetric bool_true("bool_true", BoolMetric::kBoolTrue); EXPECT_EQ(BoolMetric::kBoolTrue, bool_true.value()); EXPECT_EQ(kBoolType, bool_true.type()); EXPECT_STREQ("bool_true", bool_true.name()); EXPECT_TRUE(NULL == bool_true.next()); const BoolMetric bool_false("bool_false", BoolMetric::kBoolFalse); EXPECT_EQ(BoolMetric::kBoolFalse, bool_false.value()); EXPECT_EQ(kBoolType, bool_false.type()); EXPECT_STREQ("bool_false", bool_false.name()); EXPECT_TRUE(NULL == bool_false.next()); }
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Metrics report unit testing #include <new> #include <algorithm> #include "gtest/gtest.h" #include "metrics.h" DECLARE_METRIC_count(count); DEFINE_METRIC_count(count); DECLARE_METRIC_timing(timing); DEFINE_METRIC_timing(timing); DECLARE_METRIC_integer(integer); DEFINE_METRIC_integer(integer); DECLARE_METRIC_bool(bool); DEFINE_METRIC_bool(bool); using ::stats_report::BoolMetric; using ::stats_report::CountMetric; using ::stats_report::IntegerMetric; using ::stats_report::MetricBase; using ::stats_report::MetricCollection; using ::stats_report::MetricCollectionBase; using ::stats_report::MetricIterator; using ::stats_report::TimingMetric; using ::stats_report::TimingSample; using ::stats_report::kBoolType; using ::stats_report::kCountType; using ::stats_report::kIntegerType; using ::stats_report::kTimingType; namespace { class MetricsTest: public testing::Test { protected: MetricCollection coll_; }; class MetricsEnumTest: public MetricsTest { public: virtual void SetUp() { coll_.Initialize(); } virtual void TearDown() { coll_.Uninitialize(); } protected: MetricsEnumTest(): count_("count", &coll_), timing_("timing", &coll_), integer_("integer", &coll_), bool_("bool", &coll_) { } CountMetric count_; TimingMetric timing_; IntegerMetric integer_; BoolMetric bool_; }; } // namespace // Validates that the above-declared metrics are available // in the expected namespace TEST_F(MetricsTest, Globals) { EXPECT_EQ(0, ::metric_count.Reset()); TimingMetric::TimingData data = ::metric_timing.Reset(); EXPECT_EQ(0, data.count); EXPECT_EQ(0, data.maximum); EXPECT_EQ(0, data.minimum); EXPECT_EQ(0, data.sum); EXPECT_EQ(0, ::metric_integer.value()); EXPECT_EQ(BoolMetric::kBoolUnset, ::metric_bool.Reset()); // Check for correct initialization EXPECT_STREQ("count", metric_count.name()); EXPECT_STREQ("timing", metric_timing.name()); EXPECT_STREQ("integer", metric_integer.name()); EXPECT_STREQ("bool", metric_bool.name()); } // make GUnit happy inline std::ostream &operator << (std::ostream &str, const MetricIterator &it) { str << std::hex << reinterpret_cast<void*>(*it); return str; } TEST_F(MetricsTest, CollectionInitialization) { // The global MetricCollection is aliased to zero memory so as to ensure // no initialization order snafus. If an initialized MetricCollection // sets any of its storage to non-zero, there's a good chance that e.g. a // vtbl has snuck in there, which must not happen char buf1[sizeof(MetricCollection)] = { 0 }; char buf2[sizeof(MetricCollection)] = { 0 }; // Placement new a MetricCollection to one of the buffers new (buf1) MetricCollection(); // and check they're still equivalent EXPECT_EQ(0, memcmp(buf1, buf2, sizeof(MetricCollection))); // MetricCollection must not extend MetricCollectionBase in size EXPECT_EQ(sizeof(MetricCollection), sizeof(MetricCollectionBase)); } TEST_F(MetricsTest, Count) { CountMetric foo("foo", &coll_); EXPECT_EQ(0, foo.Reset()); EXPECT_EQ(kCountType, foo.type()); ASSERT_TRUE(NULL != foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); ++foo; EXPECT_EQ(1, foo.value()); foo++; EXPECT_EQ(2, foo.value()); foo += 100; EXPECT_EQ(102, foo.value()); } TEST_F(MetricsTest, Timing) { TimingMetric foo("foo", &coll_); EXPECT_EQ(kTimingType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL != foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); foo.AddSample(100); foo.AddSample(50); EXPECT_EQ(2, foo.count()); EXPECT_EQ(150, foo.sum()); EXPECT_EQ(100, foo.maximum()); EXPECT_EQ(50, foo.minimum()); EXPECT_EQ(75, foo.average()); TimingMetric::TimingData data = foo.Reset(); EXPECT_EQ(2, data.count); EXPECT_EQ(150, data.sum); EXPECT_EQ(100, data.maximum); EXPECT_EQ(50, data.minimum); EXPECT_EQ(0, foo.count()); EXPECT_EQ(0, foo.sum()); EXPECT_EQ(0, foo.maximum()); EXPECT_EQ(0, foo.minimum()); EXPECT_EQ(0, foo.average()); // Test counted samples foo.AddSamples(10, 1000); foo.AddSamples(10, 500); EXPECT_EQ(20, foo.count()); EXPECT_EQ(1500, foo.sum()); EXPECT_EQ(100, foo.maximum()); EXPECT_EQ(50, foo.minimum()); EXPECT_EQ(75, foo.average()); } TEST_F(MetricsTest, TimingSample) { TimingMetric foo("foo", &coll_); // add a sample to foo { TimingSample sample(&foo); ::Sleep(30); } TimingMetric::TimingData data = foo.Reset(); // Should be precisely one sample in there EXPECT_EQ(1, data.count); // again, this time with a non-unity count { TimingSample sample(&foo, 2); EXPECT_EQ(2, sample.count()); ::Sleep(30); } data = foo.Reset(); // Should be precisely two samples in there EXPECT_EQ(2, data.count); // now with zero count { TimingSample sample(&foo, 0); } data = foo.Reset(); // Should be no samples in there EXPECT_EQ(0, data.count); } TEST_F(MetricsTest, Integer) { IntegerMetric foo("foo", &coll_); EXPECT_EQ(kIntegerType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL != foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); EXPECT_EQ(0, foo.value()); foo.Set(1005); EXPECT_EQ(1005, foo.value()); foo = 1009UL; EXPECT_EQ(1009, foo.value()); foo.Set(0); ++foo; EXPECT_EQ(1, foo.value()); foo++; EXPECT_EQ(2, foo.value()); foo += 100; EXPECT_EQ(102, foo.value()); foo -= 100; EXPECT_EQ(2, foo.value()); foo--; EXPECT_EQ(1, foo.value()); --foo; EXPECT_EQ(0, foo.value()); } TEST_F(MetricsTest, Bool) { BoolMetric foo("foo", &coll_); EXPECT_EQ(kBoolType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL != foo.AsBool()); EXPECT_EQ(BoolMetric::kBoolUnset, foo.Reset()); foo.Set(true); EXPECT_EQ(BoolMetric::kBoolTrue, foo.Reset()); foo.Set(false); EXPECT_EQ(BoolMetric::kBoolFalse, foo.Reset()); EXPECT_EQ(BoolMetric::kBoolUnset, foo.Reset()); } TEST_F(MetricsEnumTest, Enumeration) { MetricBase *metrics[] = { &count_, &timing_, &integer_, &bool_, }; for (int i = 0; i < sizeof(metrics) / sizeof(metrics[0]); ++i) { MetricBase *stat = metrics[i]; MetricBase *curr = coll_.first(); for (; NULL != curr; curr = curr->next()) { if (stat == curr) break; } // if NULL, we didn't find our counter EXPECT_TRUE(NULL != curr); } } TEST_F(MetricsEnumTest, Iterator) { typedef MetricBase *MetricBasePtr; MetricBasePtr metrics[] = { &count_, &timing_, &integer_, &bool_, }; int num_stats = arraysize(metrics); MetricIterator it(coll_), end; EXPECT_NE(it, end); // copy construction EXPECT_EQ(it, MetricIterator(it)); EXPECT_EQ(end, MetricIterator(end)); // # of iterations int i = 0; while (it++ != end) ++i; ASSERT_EQ(num_stats, i); ASSERT_EQ(end, it); // increment past end is idempotent ++it; ASSERT_EQ(end, it); // Check that we return no garbage or nonsense for (it = MetricIterator(coll_); it != end; ++it) { MetricBasePtr *stats_end = &metrics[num_stats]; EXPECT_NE(stats_end, std::find(metrics, stats_end, *it)); } // and that all metrics can be found for (int i = 0; i < sizeof(metrics) / sizeof(metrics[0]); ++i) { MetricBase *stat = metrics[i]; EXPECT_EQ(stat, *std::find(MetricIterator(coll_), end, stat)); } } TEST_F(MetricsTest, SimpleConstruction) { const CountMetric c("c", 100); EXPECT_EQ(100, c.value()); EXPECT_EQ(kCountType, c.type()); EXPECT_STREQ("c", c.name()); EXPECT_TRUE(NULL == c.next()); TimingMetric::TimingData data = { 10, 0, 1000, 10, 500 }; const TimingMetric t("t", data); EXPECT_EQ(10, t.count()); EXPECT_EQ(1000, t.sum()); EXPECT_EQ(10, t.minimum()); EXPECT_EQ(500, t.maximum()); EXPECT_EQ(kTimingType, t.type()); EXPECT_STREQ("t", t.name()); EXPECT_TRUE(NULL == t.next()); const IntegerMetric i("i", 200); EXPECT_EQ(200, i.value()); EXPECT_EQ(kIntegerType, i.type()); EXPECT_STREQ("i", i.name()); EXPECT_TRUE(NULL == i.next()); const BoolMetric bool_true("bool_true", BoolMetric::kBoolTrue); EXPECT_EQ(BoolMetric::kBoolTrue, bool_true.value()); EXPECT_EQ(kBoolType, bool_true.type()); EXPECT_STREQ("bool_true", bool_true.name()); EXPECT_TRUE(NULL == bool_true.next()); const BoolMetric bool_false("bool_false", BoolMetric::kBoolFalse); EXPECT_EQ(BoolMetric::kBoolFalse, bool_false.value()); EXPECT_EQ(kBoolType, bool_false.type()); EXPECT_STREQ("bool_false", bool_false.name()); EXPECT_TRUE(NULL == bool_false.next()); }
Delete bad sleep based tests
Delete bad sleep based tests If you need the tests, refractor them to follow the guidelines instead of having them fail intermittently http://big.corp.google.com/~joejoejoe/testing/2008/05/episode-90-sleeping-synchronization_27.html Review URL: http://codereview.chromium.org/159117 git-svn-id: http://src.chromium.org/svn/trunk/src@21209 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 6cdc7c1ff8610adc45b6103722b7cda73c5b6aab
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
0e9869e6cde55b006e9b69850cc629732813f5a2
onlineml/cmd/train_online_model.cpp
onlineml/cmd/train_online_model.cpp
#include <getopt.h> #include <stdio.h> #include <stdlib.h> #ifdef DEBUG #include <time.h> #endif #include <pthread.h> #include <iostream> #include <map> #include <string> #include <vector> #include <onlineml/common/classifier.hpp> #include <onlineml/common/dict.hpp> #include <onlineml/learner/perceptron.hpp> #include <onlineml/learner/averaged_perceptron.hpp> #include <onlineml/util/string_proc.hpp> #include "arg.hpp" struct Trainer { pthread_t thread; size_t id; size_t epoch; Learner* learner; std::vector< std::vector< std::pair<size_t, float> > > x; std::vector<size_t> y; }; void* run_trainer(void* arg) { struct Trainer* trainer = (struct Trainer*) arg; #ifdef DEBUG clock_t start = clock(); #endif for (size_t i=0; i < trainer->epoch; ++i) { #ifdef DEBUG clock_t start_i = clock(); #endif trainer->learner->fit(trainer->x, trainer->y); #ifdef DEBUG clock_t end_i = clock(); float time_i = (end_i - start_i) / CLOCKS_PER_SEC; printf("id:%d epoch %d/%d: fit thread id:%d %f sec.\n", trainer->id, i+1, trainer->epoch, trainer->id, time_i); #else printf("id:%d epoch %d/%d: fit thread id:%d\n", trainer->id, i+1, trainer->epoch, trainer->id); #endif } trainer->learner->terminate_fitting(); #ifdef DEBUG clock_t end = clock(); float time = (end - start) / CLOCKS_PER_SEC; printf("thread %d: time %f sec. #data:%d\n", trainer->id, time, trainer->x.size()); #endif return NULL; } Learner* ipm(std::vector< std::vector< std::pair<size_t, float> > >& x, std::vector<size_t>& y, size_t epoch, ArgParser& argparser, Dict& labels, Dict& features) { printf("training model...\n"); size_t num_train = x.size(); size_t num_parallel = argparser.num_parallel; size_t avg = num_train / num_parallel; std::vector<size_t> start_idx = std::vector<size_t>(num_parallel, 0); std::vector<size_t> end_idx = std::vector<size_t>(num_parallel, 0); for (size_t i=0; i < num_parallel-1; ++i) { size_t s = i * avg; size_t e = s + avg; start_idx[i] = s; end_idx[i] = e; } start_idx[num_parallel-1] = (num_parallel-1) * avg; end_idx[num_parallel-1] = num_train; std::vector<Trainer> threads; threads = std::vector<Trainer>(num_parallel); for (size_t i=0; i < num_parallel; ++i) { #ifdef DEBUG printf("thread id:%d training idx: %d => %d\n", i, start_idx[i], end_idx[i]); #endif Learner* learner_i; if (argparser.alg == "p") { learner_i = new Perceptron(); } else if (argparser.alg == "ap") { learner_i = new AveragedPerceptron(); } else { printf("alg:%s\n", argparser.alg.c_str()); } learner_i->labels = labels; learner_i->features = features; std::vector< std::vector< std::pair<size_t, float> > > x_i; x_i = std::vector< std::vector< std::pair<size_t, float > > >(end_idx[i]-start_idx[i]); std::vector<size_t> y_i; y_i = std::vector<size_t>(end_idx[i]-start_idx[i]); size_t k = 0; for (size_t j=start_idx[i]; j < end_idx[i]; ++j) { x_i[k] = x[j]; y_i[k] = y[j]; k += 1; } threads[i].learner = learner_i; threads[i].x = x_i; threads[i].y = y_i; threads[i].id = i; threads[i].epoch = epoch; pthread_create(&threads[i].thread, NULL, run_trainer, &threads[i]); } Learner* avg_learner; if (argparser.alg == "p") { avg_learner = new Perceptron(); } else if (argparser.alg == "ap") { avg_learner = new AveragedPerceptron(); } else { printf("alg:%s\n", argparser.alg.c_str()); } for (size_t i=0; i < num_parallel; ++i) { pthread_join(threads[i].thread, NULL); } /* merge learners */ clock_t start = clock(); for (size_t i=0; i < num_parallel; ++i) { Learner* learner_i = threads[i].learner; std::vector< std::vector<float> > w = learner_i->weight; Dict feature_dic_i = learner_i->features; Dict label_dic_i = learner_i->labels; for (size_t j=0; j < label_dic_i.elems.size(); ++j) { std::string y = label_dic_i.elems[j]; if (!avg_learner->labels.has_elem(y)) { avg_learner->labels.add_elem(y); } } for (size_t j=0; j < feature_dic_i.elems.size(); ++j) { std::string feature = feature_dic_i.elems[j]; if (!avg_learner->features.has_elem(feature)) { avg_learner->features.add_elem(feature); } } for (size_t j=0; j < w.size(); ++j) { std::string y = label_dic_i.elems[j]; size_t yid = avg_learner->labels.ids[y]; avg_learner->expand_params(yid); for (size_t k=0; k < w[j].size(); ++k) { std::string f = feature_dic_i.elems[k]; size_t fid = avg_learner->features.ids[f]; avg_learner->expand_params(yid, fid); float w_ = w[j][k]; avg_learner->weight[yid][fid] += (w_ / float(num_parallel)); } } } clock_t end = clock(); std::cout << "duration = " << (double)(end - start) / CLOCKS_PER_SEC << "sec.\n"; return avg_learner; }; int main(int argc, char* argv[]) { ArgParser argparser; argparser.parse_args(argc, argv); size_t epoch = argparser.epoch; std::string modelfile = argparser.model_file; std::string alg = argparser.alg; printf("epoch:%d\n", epoch); printf("modelfile:%s\n", modelfile.c_str()); printf("algoirthm:%s\n", alg.c_str()); printf("trainfile:%s\n", argparser.train_file.c_str()); if (argparser.test_file != "") { printf("testfile:%s\n", argparser.test_file.c_str()); } std::ifstream ifs(argparser.train_file.c_str()); std::string line; std::vector<size_t> y; std::vector< std::vector< std::pair<size_t, float> > > x; Dict features; Dict labels; clock_t start_data = clock(); if (ifs.fail()) { std::cerr << "failed to open file:" << std::endl; } while(getline(ifs, line)) { std::vector<std::string> elems; split(line, ' ', elems); std::string label = elems[0]; std::vector< std::pair<size_t, float> > fv; size_t num_elem = elems.size(); fv = std::vector< std::pair<size_t, float> >(num_elem-1); for (size_t i=1; i < num_elem; ++i) { std::vector<std::string> f_v; split(elems[i], ':', f_v); std::string f = f_v[0]; float v = atof(f_v[1].c_str()); size_t fid; if (!features.has_elem(f)) { fid = features.add_elem(f); } else { fid = features.get_id(f); } std::pair<size_t, float> ftval = std::make_pair(fid, v); fv[i-1] = ftval; } size_t yid; if (!labels.has_elem(label)) { yid = labels.add_elem(label); } else { yid = labels.get_id(label); } y.push_back(yid); x.push_back(fv); } clock_t end_data = clock(); float time_data = (float)(end_data - start_data) / CLOCKS_PER_SEC; printf("reading finished! %f sec.\n", time_data); Learner* learner; if (argparser.num_parallel > 1) { learner = ipm(x, y, epoch, argparser, labels, features); } else { learner = argparser.learner; learner->labels = labels; learner->features = features; for (size_t t=0; t<epoch; t++) { printf("epoch:%d/%d\n", t+1, epoch); learner->fit(x, y); } } learner->save(modelfile.c_str()); if (argparser.test_file == "") { exit(0); } Classifier cls; cls.load(modelfile.c_str()); std::ifstream ifs2(argparser.test_file.c_str()); size_t num_corr = 0; size_t num_total = 0; float accuracy = 0.; while(getline(ifs2, line)) { if (ifs2.fail()) { std::cerr << "failed to open file:" << std::endl; } std::vector<std::string> elems; elems = split(line, ' '); // std::cout << line << std::endl; std::vector< std::pair<std::string, float> > fv; std::string label = elems[0]; for (size_t i=1; i < elems.size(); ++i) { std::vector<std::string> f_v = split(elems[i], ':'); std::string f = f_v[0]; float v = atof(f_v[1].c_str()); fv.push_back(std::make_pair(f, v)); } // size_t pred_ = p->predict(fv); // std::string pred = p->id2label(pred_); size_t pred_ = cls.predict(fv); std::string pred = cls.id2label(pred_); // size_t true_ = p->label2id(label); size_t true_ = cls.label2id(label); if (true_ == pred_) { num_corr += 1; } num_total += 1; accuracy = float(num_corr) / float(num_total); if (num_total % 1000==0) { printf("acc:%f (%d/%d) pred:%s (id:%d) true:%s (id:%d)\n", accuracy, num_corr, num_total, pred.c_str(), pred_, label.c_str(), true_); } } printf("acc:%f (%d/%d)\n", accuracy, num_corr, num_total); return 0; }
#include <getopt.h> #include <stdio.h> #include <stdlib.h> #ifdef DEBUG #include <time.h> #endif #include <pthread.h> #include <iostream> #include <map> #include <string> #include <vector> #include <onlineml/common/classifier.hpp> #include <onlineml/common/dict.hpp> #include <onlineml/learner/perceptron.hpp> #include <onlineml/learner/averaged_perceptron.hpp> #include <onlineml/util/string_proc.hpp> #include "arg.hpp" struct Trainer { pthread_t thread; size_t id; size_t epoch; Learner* learner; std::vector< std::vector< std::pair<size_t, float> > > x; std::vector<size_t> y; }; void* run_trainer(void* arg) { struct Trainer* trainer = (struct Trainer*) arg; #ifdef DEBUG clock_t start = clock(); #endif for (size_t i=0; i < trainer->epoch; ++i) { #ifdef DEBUG clock_t start_i = clock(); #endif trainer->learner->fit(trainer->x, trainer->y); #ifdef DEBUG clock_t end_i = clock(); float time_i = (end_i - start_i) / CLOCKS_PER_SEC; printf("id:%d epoch %d/%d: fit thread id:%d %f sec.\n", trainer->id, i+1, trainer->epoch, trainer->id, time_i); #else printf("id:%d epoch %d/%d: fit thread id:%d\n", trainer->id, i+1, trainer->epoch, trainer->id); #endif } trainer->learner->terminate_fitting(); #ifdef DEBUG clock_t end = clock(); float time = (end - start) / CLOCKS_PER_SEC; printf("thread %d: time %f sec. #data:%d\n", trainer->id, time, trainer->x.size()); #endif return NULL; } Learner* ipm(std::vector< std::vector< std::pair<size_t, float> > >& x, std::vector<size_t>& y, size_t epoch, ArgParser& argparser, Dict& labels, Dict& features) { printf("training model...\n"); size_t num_train = x.size(); size_t num_parallel = argparser.num_parallel; size_t avg = num_train / num_parallel; std::vector<size_t> start_idx = std::vector<size_t>(num_parallel, 0); std::vector<size_t> end_idx = std::vector<size_t>(num_parallel, 0); for (size_t i=0; i < num_parallel-1; ++i) { size_t s = i * avg; size_t e = s + avg; start_idx[i] = s; end_idx[i] = e; } start_idx[num_parallel-1] = (num_parallel-1) * avg; end_idx[num_parallel-1] = num_train; std::vector<Trainer> threads; threads = std::vector<Trainer>(num_parallel); for (size_t i=0; i < num_parallel; ++i) { #ifdef DEBUG printf("thread id:%d training idx: %d => %d\n", i, start_idx[i], end_idx[i]); #endif Learner* learner_i; if (argparser.alg == "p") { learner_i = new Perceptron(); } else if (argparser.alg == "ap") { learner_i = new AveragedPerceptron(); } else { printf("alg:%s\n", argparser.alg.c_str()); } learner_i->labels = labels; learner_i->features = features; std::vector< std::vector< std::pair<size_t, float> > > x_i; x_i = std::vector< std::vector< std::pair<size_t, float > > >(end_idx[i]-start_idx[i]); std::vector<size_t> y_i; y_i = std::vector<size_t>(end_idx[i]-start_idx[i]); size_t k = 0; for (size_t j=start_idx[i]; j < end_idx[i]; ++j) { x_i[k] = x[j]; y_i[k] = y[j]; k += 1; } threads[i].learner = learner_i; threads[i].x = x_i; threads[i].y = y_i; threads[i].id = i; threads[i].epoch = epoch; pthread_create(&threads[i].thread, NULL, run_trainer, &threads[i]); } Learner* avg_learner; if (argparser.alg == "p") { avg_learner = new Perceptron(); } else if (argparser.alg == "ap") { avg_learner = new AveragedPerceptron(); } else { printf("alg:%s\n", argparser.alg.c_str()); } avg_learner->labels = labels; avg_learner->features = features; // avg_learner->expand_params(labels.size()); // avg_learner->expand_params(labels.size(), features.size()); for (size_t i=0; i < num_parallel; ++i) { pthread_join(threads[i].thread, NULL); } /* merge learners */ clock_t start = clock(); for (size_t i=0; i < num_parallel; ++i) { Learner* learner_i = threads[i].learner; std::vector< std::vector<float> > w = learner_i->weight; // Dict feature_dic_i = learner_i->features; // Dict label_dic_i = learner_i->labels; // for (size_t j=0; j < label_dic_i.elems.size(); ++j) { // std::string y = label_dic_i.elems[j]; // if (!avg_learner->labels.has_elem(y)) { // avg_learner->labels.add_elem(y); // } // } // for (size_t j=0; j < feature_dic_i.elems.size(); ++j) { // std::string feature = feature_dic_i.elems[j]; // if (!avg_learner->features.has_elem(feature)) { // avg_learner->features.add_elem(feature); // } // } // for (size_t j=0; j < w.size(); ++j) { // std::string y = label_dic_i.elems[j]; // size_t yid = avg_learner->labels.ids[y]; size_t wsize = w.size(); for (size_t yid=0; yid < wsize; ++yid) { avg_learner->expand_params(yid); // for (size_t k=0; k < w[j].size(); ++k) { // for (size_t k=0; k < w[yid].size(); ++k) { // std::string f = feature_dic_i.elems[k]; // size_t fid = avg_learner->features.ids[f]; size_t wysize = w[yid].size(); for (size_t fid=0; fid < wysize; ++fid) { avg_learner->expand_params(yid, fid); // float w_ = w[j][k]; // float w_ = w[yid][k]; float w_ = w[yid][fid]; if (w_ != 0.) { avg_learner->weight[yid][fid] += (w_ / float(num_parallel)); } } } } clock_t end = clock(); std::cout << "time for merging: " << (double)(end - start) / CLOCKS_PER_SEC << "sec.\n"; return avg_learner; }; int main(int argc, char* argv[]) { ArgParser argparser; argparser.parse_args(argc, argv); size_t epoch = argparser.epoch; std::string modelfile = argparser.model_file; std::string alg = argparser.alg; printf("epoch:%d\n", epoch); printf("modelfile:%s\n", modelfile.c_str()); printf("algoirthm:%s\n", alg.c_str()); printf("trainfile:%s\n", argparser.train_file.c_str()); if (argparser.test_file != "") { printf("testfile:%s\n", argparser.test_file.c_str()); } std::ifstream ifs(argparser.train_file.c_str()); std::string line; std::vector<size_t> y; std::vector< std::vector< std::pair<size_t, float> > > x; Dict features; Dict labels; clock_t start_data = clock(); if (ifs.fail()) { std::cerr << "failed to open file:" << std::endl; } while(getline(ifs, line)) { std::vector<std::string> elems; split(line, ' ', elems); std::string label = elems[0]; std::vector< std::pair<size_t, float> > fv; size_t num_elem = elems.size(); fv = std::vector< std::pair<size_t, float> >(num_elem-1); for (size_t i=1; i < num_elem; ++i) { std::vector<std::string> f_v; split(elems[i], ':', f_v); std::string f = f_v[0]; float v = atof(f_v[1].c_str()); size_t fid; if (!features.has_elem(f)) { fid = features.add_elem(f); } else { fid = features.get_id(f); } std::pair<size_t, float> ftval = std::make_pair(fid, v); fv[i-1] = ftval; } size_t yid; if (!labels.has_elem(label)) { yid = labels.add_elem(label); } else { yid = labels.get_id(label); } y.push_back(yid); x.push_back(fv); } clock_t end_data = clock(); float time_data = (float)(end_data - start_data) / CLOCKS_PER_SEC; printf("reading finished! %f sec.\n", time_data); Learner* learner; if (argparser.num_parallel > 1) { learner = ipm(x, y, epoch, argparser, labels, features); } else { learner = argparser.learner; learner->labels = labels; learner->features = features; for (size_t t=0; t<epoch; t++) { printf("epoch:%d/%d\n", t+1, epoch); learner->fit(x, y); } } learner->save(modelfile.c_str()); if (argparser.test_file == "") { exit(0); } Classifier cls; cls.load(modelfile.c_str()); std::ifstream ifs2(argparser.test_file.c_str()); size_t num_corr = 0; size_t num_total = 0; float accuracy = 0.; while(getline(ifs2, line)) { if (ifs2.fail()) { std::cerr << "failed to open file:" << std::endl; } std::vector<std::string> elems; elems = split(line, ' '); // std::cout << line << std::endl; std::vector< std::pair<std::string, float> > fv; std::string label = elems[0]; for (size_t i=1; i < elems.size(); ++i) { std::vector<std::string> f_v = split(elems[i], ':'); std::string f = f_v[0]; float v = atof(f_v[1].c_str()); fv.push_back(std::make_pair(f, v)); } // size_t pred_ = p->predict(fv); // std::string pred = p->id2label(pred_); size_t pred_ = cls.predict(fv); std::string pred = cls.id2label(pred_); // size_t true_ = p->label2id(label); size_t true_ = cls.label2id(label); if (true_ == pred_) { num_corr += 1; } num_total += 1; accuracy = float(num_corr) / float(num_total); if (num_total % 1000==0) { printf("acc:%f (%d/%d) pred:%s (id:%d) true:%s (id:%d)\n", accuracy, num_corr, num_total, pred.c_str(), pred_, label.c_str(), true_); } } printf("acc:%f (%d/%d)\n", accuracy, num_corr, num_total); return 0; }
refactor merging models in IPM
refactor merging models in IPM
C++
mit
tma15/onlineml,tma15/onlineml,tma15/onlineml,tma15/onlineml
ff463bb60c01001592076db9c67bb265780111e9
C++/reverse-words-in-a-string.cpp
C++/reverse-words-in-a-string.cpp
// Time: O(n) // Space: O(1) class Solution { public: /** * @param s : A string * @return : A string */ string reverseWords(string s) { // Reverse the whole string first. reverse(s.begin(), s.end()); size_t start = 0, end; while ((end = s.find(" ", start)) != string::npos) { // Reverse each word in the string. reverse(s.begin() + start, s.begin() + end); start = end + 1; } // Reverse the last word. reverse(s.begin() + start, s.end()); // Remove beginning blank. if ((start = s.find_first_not_of(" ")) != string::npos) { return s.substr(start); } return s; } };
// Time: O(n) // Space: O(1) class Solution { public: /** * @param s : A string * @return : A string */ string reverseWords(string s) { // Reverse the whole string first. reverse(s.begin(), s.end()); size_t begin = 0, end = 0, len = 0; while ((begin = s.find_first_not_of(" ", end)) != string::npos) { if ((end = s.find(" ", begin)) == string::npos) { end = s.length(); } // Reverse each word in the string. reverse(s.begin() + begin, s.begin() + end); // Shift the word to avoid extra space. move(s.begin() + begin, s.begin() + end, s.begin() + len); len += end - begin; s[len++] = ' '; } s.resize(len ? len - 1 : 0); return s; } };
Update reverse-words-in-a-string.cpp
Update reverse-words-in-a-string.cpp
C++
mit
kamyu104/LintCode,kamyu104/LintCode,jaredkoontz/lintcode,jaredkoontz/lintcode,jaredkoontz/lintcode,kamyu104/LintCode
05b0c12785ffb1f2458ff33cc05e86fd620f1a94
capBAC/issuer_new.cpp
capBAC/issuer_new.cpp
#include <string.h> #include <iostream> #include <fstream> #include <vector> #include <stdio.h> #include <sstream> #include <arpa/inet.h> #include <unistd.h> #include <sys/epoll.h> #include <errno.h> #include <openssl/ec.h> #include <openssl/bn.h> #include <openssl/objects.h> #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "base64.h" #define B64SIZE 64 #define TOKENSIZE 162 using namespace std; using namespace rapidjson; #define MACHINE_IP inet_addr("127.0.0.1") #define PORT_SUBJECT 49151 vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); string tok; while(getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } int sign(Document* d) { const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401"; const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1"; //hex pub key from Sajin's message ECDSA_SIG *sig; char sig_str[B64SIZE]; BN_CTX *ctx; EVP_MD_CTX* mdctx; const EVP_MD* md; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len, buf_len; EC_KEY* auth_key; Value si; auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3); if (auth_key == NULL) { printf("failed to initialize curve\n"); return 1; } ctx = BN_CTX_new(); if(!ctx) { printf("failed to create bn ctx\n"); return 1; } EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx); //hex pub key from Sajin's message BN_CTX_free(ctx); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d->Accept(writer); printf("sig is signing: %s\n", buffer.GetString()); OpenSSL_add_all_digests(); md = EVP_get_digestbyname("sha256"); if(md == 0) { printf("Unknown message digest\n"); return 1; } mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize()); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_destroy(mdctx); printf("digest: "); dump_mem(md_value, md_len); buf_len = ECDSA_size(auth_key); sig = ECDSA_do_sign(md_value, md_len, auth_key); if (sig == NULL) { printf("Signing failed\n"); return 1; } base64encode(sig_str, sig->r, sig->s); si.SetString(sig_str, B64SIZE, d->GetAllocator()); d->AddMember("si", si, d->GetAllocator()); printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s)); } int bootstrap_network(const char* port_sub){ int soc,response_length,n; char *response; uint16_t port = strtol(port_sub, NULL, 10); // from arguments // cout << "port no: " << port << "\n"; soc = socket(AF_INET, SOCK_STREAM, 0); if (soc == -1) { printf("Failed to open socket\n"); return 1; } struct sockaddr_in connectAddress; memset(&connectAddress, 0, sizeof(connectAddress)); connectAddress.sin_family = AF_INET; connectAddress.sin_addr.s_addr = MACHINE_IP; connectAddress.sin_port = htons(port); cout << connectAddress.sin_addr.s_addr << "\t" << connectAddress.sin_port << "\n"; if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) { printf("bootstrap: Failed to bind\n"); exit(1); } if(listen(soc, 5) == -1) { printf( "bootstrap: Failed to listen\n"); exit(1); } return soc; } char* get_request(int fd) { char* message; size_t size = TOKENSIZE; int offset; message = (char*) realloc(NULL, sizeof(char)*size); if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } offset = -1; do { offset++; if (offset == size) { message = (char*) realloc(message, sizeof(char)*(size += 16)); //?? if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } } if(read(fd, message+offset, 1) <= 0) { printf("get_request: EOF encountered\n"); char c = message[offset]; message[offset] = 0; printf("story so far (%d): %s%c\n", offset, message, c); exit(1); } } while (message[offset] != 0); printf("DEBUG: get_request: message at %p: %s\n", message, message); return message; } int listen_block1(int soc) { int fd; socklen_t peer_addr_size = sizeof(struct sockaddr_in); char * sub_request; unsigned char response; struct sockaddr_in retAddress; printf("DEBUG: entering network loop\n"); while(true) { printf("DEBUG: network loop: accepting connection...\n"); fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size); if( fd == -1) { printf("listen: Failed to accept: %s\n", strerror(errno)); exit(1); } printf( "DEBUG: network loop: connection accepted, getting request from subject...\n"); sub_request = get_request(fd); } string message = sub_request; vector<string> sep = split(message, '\n'); const char * pub_key = sep[0].c_str(); const char * res_add = sep[1].c_str(); cout << "public key (b64): " << pub_key << "\n"; cout << "resource address: " << res_add << "\n"; Document d; Value ii, nb, na, suv; char su[B64SIZE]; unsigned int now; d.Parse("{}"); now = time(NULL); ii.SetInt(now); nb.SetInt(now); na.SetInt(1600000000); suv.SetString(pub_key, B64SIZE, d.GetAllocator()); d.AddMember("id", "fake identifier", d.GetAllocator()); d.AddMember("ii", ii, d.GetAllocator()); d.AddMember("is", "fake issuer", d.GetAllocator()); d.AddMember("su", suv, d.GetAllocator()); d.AddMember("de", "res_add", d.GetAllocator()); d.AddMember("ar", "fake access rights", d.GetAllocator()); d.AddMember("nb", nb, d.GetAllocator()); d.AddMember("na", na, d.GetAllocator()); sign(&d); } int listen_block2(int soc){ printf("block2\n"); return 1; } int main(int argc, char *argv[]) { int soc = bootstrap_network(argv[1]); if(!strcmp(argv[2], "1")) listen_block1(soc); else if(!strcmp(argv[2], "2")) listen_block2(soc); else { printf("Invalid mode: %s", argv[2]); exit(1); } return 1; }
#include <string.h> #include <iostream> #include <fstream> #include <vector> #include <stdio.h> #include <sstream> #include <arpa/inet.h> #include <unistd.h> #include <sys/epoll.h> #include <errno.h> #include <openssl/ec.h> #include <openssl/bn.h> #include <openssl/objects.h> #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "base64.h" #define B64SIZE 64 #define TOKENSIZE 162 using namespace std; using namespace rapidjson; #define MACHINE_IP inet_addr("127.0.0.1") #define PORT_SUBJECT 49151 vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); string tok; while(getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } int sign(Document* d) { const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401"; const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1"; //hex pub key from Sajin's message ECDSA_SIG *sig; char sig_str[B64SIZE]; BN_CTX *ctx; EVP_MD_CTX* mdctx; const EVP_MD* md; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len, buf_len; EC_KEY* auth_key; Value si; auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3); if (auth_key == NULL) { printf("failed to initialize curve\n"); return 1; } ctx = BN_CTX_new(); if(!ctx) { printf("failed to create bn ctx\n"); return 1; } EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx); //hex pub key from Sajin's message BN_CTX_free(ctx); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d->Accept(writer); printf("sig is signing: %s\n", buffer.GetString()); OpenSSL_add_all_digests(); md = EVP_get_digestbyname("sha256"); if(md == 0) { printf("Unknown message digest\n"); return 1; } mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize()); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_destroy(mdctx); printf("digest: "); dump_mem(md_value, md_len); buf_len = ECDSA_size(auth_key); sig = ECDSA_do_sign(md_value, md_len, auth_key); if (sig == NULL) { printf("Signing failed\n"); return 1; } base64encode(sig_str, sig->r, sig->s); si.SetString(sig_str, B64SIZE, d->GetAllocator()); d->AddMember("si", si, d->GetAllocator()); printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s)); } int bootstrap_network(const char* port_sub){ int soc,response_length,n; char *response; uint16_t port = strtol(port_sub, NULL, 10); // from arguments // cout << "port no: " << port << "\n"; soc = socket(AF_INET, SOCK_STREAM, 0); if (soc == -1) { printf("Failed to open socket\n"); return 1; } struct sockaddr_in connectAddress; memset(&connectAddress, 0, sizeof(connectAddress)); connectAddress.sin_family = AF_INET; connectAddress.sin_addr.s_addr = MACHINE_IP; connectAddress.sin_port = htons(port); // cout << connectAddress.sin_addr.s_addr << "\t" << connectAddress.sin_port << "\n"; if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) { printf("bootstrap: Failed to bind\n"); exit(1); } if(listen(soc, 5) == -1) { printf( "bootstrap: Failed to listen\n"); exit(1); } return soc; } char* get_request(int fd) { char* message; size_t size = TOKENSIZE; int offset; message = (char*) realloc(NULL, sizeof(char)*size); if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } offset = -1; do { offset++; if (offset == size) { message = (char*) realloc(message, sizeof(char)*(size += 16)); //?? if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } } if(read(fd, message+offset, 1) <= 0) { printf("get_request: EOF encountered\n"); char c = message[offset]; message[offset] = 0; printf("story so far (%d): %s%c\n", offset, message, c); exit(1); } } while (message[offset] != 0); printf("DEBUG: get_request: message at %p: %s\n", message, message); return message; } int listen_block1(int soc) { int fd; socklen_t peer_addr_size = sizeof(struct sockaddr_in); char * sub_request; unsigned char response; struct sockaddr_in retAddress; printf("DEBUG: entering network loop\n"); while(true) { printf("DEBUG: network loop: accepting connection...\n"); fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size); if( fd == -1) { printf("listen: Failed to accept: %s\n", strerror(errno)); exit(1); } printf( "DEBUG: network loop: connection accepted, getting request from subject...\n"); sub_request = get_request(fd); } string message = sub_request; vector<string> sep = split(message, '\n'); const char * pub_key = sep[0].c_str(); const char * res_add = sep[1].c_str(); cout << "public key (b64): " << pub_key << "\n"; cout << "resource address: " << res_add << "\n"; Document d; Value ii, nb, na, suv; char su[B64SIZE]; unsigned int now; d.Parse("{}"); now = time(NULL); ii.SetInt(now); nb.SetInt(now); na.SetInt(1600000000); suv.SetString(pub_key, B64SIZE, d.GetAllocator()); d.AddMember("id", "fake identifier", d.GetAllocator()); d.AddMember("ii", ii, d.GetAllocator()); d.AddMember("is", "fake issuer", d.GetAllocator()); d.AddMember("su", suv, d.GetAllocator()); d.AddMember("de", "res_add", d.GetAllocator()); d.AddMember("ar", "fake access rights", d.GetAllocator()); d.AddMember("nb", nb, d.GetAllocator()); d.AddMember("na", na, d.GetAllocator()); sign(&d); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); if(write(soc, buffer.GetString(), buffer.GetSize()+1) < 0) { printf("Failed to write to socket\n"); //return 1; } } int listen_block2(int soc){ printf("block2\n"); return 1; } int main(int argc, char *argv[]) { int soc = bootstrap_network(argv[1]); if(!strcmp(argv[2], "1")) listen_block1(soc); else if(!strcmp(argv[2], "2")) listen_block2(soc); else { printf("Invalid mode: %s", argv[2]); exit(1); } return 1; }
write token from issuer to subject code added
write token from issuer to subject code added
C++
apache-2.0
jtracey/cuddly-fiesta,jtracey/cuddly-fiesta,jtracey/cuddly-fiesta
112bbc93092555248c2d2f549396cfcc005560fa
src/settings.cpp
src/settings.cpp
/** * Copyright (c) 2011-2016 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/server/settings.hpp> #include <bitcoin/node.hpp> namespace libbitcoin { namespace server { using namespace asio; static const settings setting_defaults() { settings value; value.threads = 2; value.heartbeat_interval_seconds = 5; value.polling_interval_milliseconds = 1; value.subscription_expiration_minutes = 10; value.subscription_limit = 100000000; value.publisher_enabled = true; value.queries_enabled = true; value.log_requests = false; value.query_endpoint = { "tcp://*:9091" }; value.heartbeat_endpoint = { "tcp://*:9092" }; value.block_publish_endpoint = { "tcp://*:9093" }; value.transaction_publish_endpoint = { "tcp://*:9094" }; value.certificate_file = { "" }; value.client_certificates_path = { "" }; value.whitelists = {}; return value; }; const settings settings::defaults = setting_defaults(); duration settings::polling_interval() const { return milliseconds(polling_interval_milliseconds); } duration settings::heartbeat_interval() const { return seconds(heartbeat_interval_seconds); } duration settings::subscription_expiration() const { return minutes(subscription_expiration_minutes); } } // namespace server } // namespace libbitcoin
/** * Copyright (c) 2011-2016 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/server/settings.hpp> #include <bitcoin/node.hpp> namespace libbitcoin { namespace server { using namespace asio; static const settings setting_defaults() { settings value; value.threads = 2; value.heartbeat_interval_seconds = 5; value.polling_interval_milliseconds = 1; value.subscription_expiration_minutes = 10; value.subscription_limit = 100000000; value.publisher_enabled = true; value.queries_enabled = true; value.log_requests = false; value.query_endpoint = { "tcp://*:9091" }; value.heartbeat_endpoint = { "tcp://*:9092" }; value.block_publish_endpoint = { "tcp://*:9093" }; value.transaction_publish_endpoint = { "tcp://*:9094" }; value.certificate_file = { "" }; value.client_certificates_path = { "" }; value.whitelists = { {} }; return value; }; const settings settings::defaults = setting_defaults(); duration settings::polling_interval() const { return milliseconds(polling_interval_milliseconds); } duration settings::heartbeat_interval() const { return seconds(heartbeat_interval_seconds); } duration settings::subscription_expiration() const { return minutes(subscription_expiration_minutes); } } // namespace server } // namespace libbitcoin
Fix static init syntax.
Fix static init syntax.
C++
agpl-3.0
RojavaCrypto/libbitcoin-server,RojavaCrypto/libbitcoin-server,RojavaCrypto/libbitcoin-server
590455ae11d9ff0527f8a70c240137a641c85ee1
src/parser/trees/evalb.cpp
src/parser/trees/evalb.cpp
/** * @file evalb.cpp * @author Chase Geigle */ #include <iostream> #include <set> #include <unordered_set> #include "util/comparable.h" #include "parser/trees/evalb.h" #include "parser/trees/visitors/visitor.h" #include "parser/trees/visitors/annotation_remover.h" #include "parser/trees/visitors/tree_transformer.h" #include "parser/trees/visitors/empty_remover.h" #include "parser/trees/visitors/multi_transformer.h" #include "parser/trees/visitors/unary_chain_remover.h" #include "parser/trees/internal_node.h" #include "parser/trees/leaf_node.h" namespace meta { namespace parser { namespace { struct constituent : public util::comparable<constituent> { class_label category; uint64_t start; uint64_t end; // non-inclusive! }; bool crosses(const constituent& first, const constituent& second) { return (first.start < second.start && second.start < first.end && first.end < second.end) || (second.start < first.start && first.start < second.end && second.end < first.end); } bool operator<(const constituent& first, const constituent& second) { return std::tie(first.category, first.start, first.end) < std::tie(second.category, second.start, second.end); } class constituent_finder : public const_visitor<void> { public: void operator()(const leaf_node&) override { ++curr_leaf_; } void operator()(const internal_node& in) override { constituent con; con.category = in.category(); con.start = curr_leaf_; in.each_child([&](const node* child) { child->accept(*this); }); con.end = curr_leaf_; constituents_.emplace(std::move(con)); } std::multiset<constituent> constituents() { return std::move(constituents_); } private: uint64_t curr_leaf_ = 0; std::multiset<constituent> constituents_; }; std::multiset<constituent> get_constituents(const parse_tree& tree) { constituent_finder const_finder; tree.visit(const_finder); return const_finder.constituents(); } class collinizer : public tree_transformer { public: std::unique_ptr<node> operator()(const leaf_node& ln) override { // remove punctuation preterminals if (punct_cats.find(ln.category()) != punct_cats.end()) return nullptr; return ln.clone(); } std::unique_ptr<node> operator()(const internal_node& in) override { std::unique_ptr<internal_node> res; // remove the top root node if (in.category() == "ROOT"_cl) return in.child(0)->accept(*this); // weird equivalence... if (in.category() == "PRT"_cl) res = make_unique<internal_node>("ADVP"_cl); else res = make_unique<internal_node>(in.category()); in.each_child([&](const node* c) { auto child = c->accept(*this); if (child) res->add_child(std::move(child)); }); return std::move(res); } private: const std::unordered_set<class_label> punct_cats = {"''", "'", "``", "``", ".", ":", ","}; }; } void evalb::add_tree(parse_tree proposed, parse_tree gold) { static multi_transformer<annotation_remover, collinizer, empty_remover> trnsfm; proposed.transform(trnsfm); gold.transform(trnsfm); auto prop_const = get_constituents(proposed); auto gold_const = get_constituents(gold); uint64_t crossings = 0; for (const auto& guess : prop_const) { for (const auto& gold : gold_const) { if (crosses(guess, gold)) { ++crossings; break; } } } if (crossings == 0) ++zero_crossing_; crossed_ += crossings; ++total_trees_; proposed_total_ += prop_const.size(); uint64_t gold_total = gold_const.size(); uint64_t matched = 0; for (const auto& guess : prop_const) { auto it = gold_const.find(guess); if (it != gold_const.end()) { ++matched; gold_const.erase(it); } } if (matched == gold_total && matched == prop_const.size()) ++perfect_; gold_total_ += gold_total; proposed_correct_ += matched; } } }
/** * @file evalb.cpp * @author Chase Geigle */ #include <iostream> #include <set> #include <unordered_set> #include "util/comparable.h" #include "parser/trees/evalb.h" #include "parser/trees/visitors/visitor.h" #include "parser/trees/visitors/annotation_remover.h" #include "parser/trees/visitors/tree_transformer.h" #include "parser/trees/visitors/empty_remover.h" #include "parser/trees/visitors/multi_transformer.h" #include "parser/trees/visitors/unary_chain_remover.h" #include "parser/trees/internal_node.h" #include "parser/trees/leaf_node.h" namespace meta { namespace parser { namespace { struct constituent : public util::comparable<constituent> { class_label category; uint64_t start; uint64_t end; // non-inclusive! }; bool crosses(const constituent& first, const constituent& second) { return (first.start < second.start && second.start < first.end && first.end < second.end) || (second.start < first.start && first.start < second.end && second.end < first.end); } bool operator<(const constituent& first, const constituent& second) { return std::tie(first.category, first.start, first.end) < std::tie(second.category, second.start, second.end); } class constituent_finder : public const_visitor<void> { public: void operator()(const leaf_node&) override { ++curr_leaf_; } void operator()(const internal_node& in) override { constituent con; con.category = in.category(); con.start = curr_leaf_; in.each_child([&](const node* child) { child->accept(*this); }); con.end = curr_leaf_; constituents_.emplace(std::move(con)); } std::multiset<constituent> constituents() { return std::move(constituents_); } private: uint64_t curr_leaf_ = 0; std::multiset<constituent> constituents_; }; std::multiset<constituent> get_constituents(const parse_tree& tree) { constituent_finder const_finder; tree.visit(const_finder); return const_finder.constituents(); } class collinizer : public tree_transformer { public: std::unique_ptr<node> operator()(const leaf_node& ln) override { // remove punctuation preterminals if (punct_cats.find(ln.category()) != punct_cats.end()) return nullptr; return ln.clone(); } std::unique_ptr<node> operator()(const internal_node& in) override { std::unique_ptr<internal_node> res; // remove the top root node if (in.category() == "ROOT"_cl) return in.child(0)->accept(*this); // weird equivalence... if (in.category() == "PRT"_cl) res = make_unique<internal_node>("ADVP"_cl); else res = make_unique<internal_node>(in.category()); in.each_child([&](const node* c) { auto child = c->accept(*this); if (child) res->add_child(std::move(child)); }); return std::move(res); } private: const std::unordered_set<class_label> punct_cats = {"''"_cl, "'"_cl, "``"_cl, "``"_cl, "."_cl, ":"_cl, ","_cl}; }; } void evalb::add_tree(parse_tree proposed, parse_tree gold) { static multi_transformer<annotation_remover, collinizer, empty_remover> trnsfm; proposed.transform(trnsfm); gold.transform(trnsfm); auto prop_const = get_constituents(proposed); auto gold_const = get_constituents(gold); uint64_t crossings = 0; for (const auto& guess : prop_const) { for (const auto& gold : gold_const) { if (crosses(guess, gold)) { ++crossings; break; } } } if (crossings == 0) ++zero_crossing_; crossed_ += crossings; ++total_trees_; proposed_total_ += prop_const.size(); uint64_t gold_total = gold_const.size(); uint64_t matched = 0; for (const auto& guess : prop_const) { auto it = gold_const.find(guess); if (it != gold_const.end()) { ++matched; gold_const.erase(it); } } if (matched == gold_total && matched == prop_const.size()) ++perfect_; gold_total_ += gold_total; proposed_correct_ += matched; } } }
Fix compilation in debug mode for evalb.
Fix compilation in debug mode for evalb.
C++
mit
gef756/meta,husseinhazimeh/meta,saq7/MeTA,saq7/MeTA,esparza83/meta,husseinhazimeh/meta,esparza83/meta,husseinhazimeh/meta,gef756/meta,husseinhazimeh/meta,esparza83/meta,husseinhazimeh/meta,esparza83/meta,saq7/MeTA,gef756/meta,esparza83/meta,gef756/meta,gef756/meta
2c57cf3063a0b5a78e2599e97832a869168a58b0
src/yfontcore.cc
src/yfontcore.cc
#include "config.h" #ifdef CONFIG_COREFONTS #include "ypaint.h" #include "intl.h" #include "yxapp.h" #include "yprefs.h" #include <string.h> #include <locale.h> class YCoreFont : public YFont { public: YCoreFont(char const * name); virtual ~YCoreFont(); virtual bool valid() const { return (NULL != fFont); } virtual int descent() const { return fFont->max_bounds.descent; } virtual int ascent() const { return fFont->max_bounds.ascent; } virtual int textWidth(char const * str, int len) const; virtual void drawGlyphs(class Graphics & graphics, int x, int y, char const * str, int len); private: XFontStruct * fFont; }; #ifdef CONFIG_I18N class YFontSet : public YFont { public: YFontSet(char const * name); virtual ~YFontSet(); virtual bool valid() const { return (None != fFontSet); } virtual int descent() const { return fDescent; } virtual int ascent() const { return fAscent; } virtual int textWidth(char const * str, int len) const; virtual void drawGlyphs(class Graphics & graphics, int x, int y, char const * str, int len); private: static XFontSet getFontSetWithGuess(char const * pattern, char *** missing, int * nMissing, char ** defString); XFontSet fFontSet; int fAscent, fDescent; }; #endif /******************************************************************************/ YCoreFont::YCoreFont(char const * name) { if (NULL == (fFont = XLoadQueryFont(xapp->display(), name))) { warn(_("Could not load font \"%s\"."), name); if (NULL == (fFont = XLoadQueryFont(xapp->display(), "fixed"))) warn(_("Loading of fallback font \"%s\" failed."), "fixed"); } } YCoreFont::~YCoreFont() { if (NULL != fFont) XFreeFont(xapp->display(), fFont); } int YCoreFont::textWidth(const char *str, int len) const { return XTextWidth(fFont, str, len); } void YCoreFont::drawGlyphs(Graphics & graphics, int x, int y, char const * str, int len) { XSetFont(xapp->display(), graphics.handle(), fFont->fid); XDrawString(xapp->display(), graphics.drawable(), graphics.handle(), x - graphics.xorigin(), y - graphics.yorigin(), str, len); } /******************************************************************************/ #ifdef CONFIG_I18N YFontSet::YFontSet(char const * name): fFontSet(None), fAscent(0), fDescent(0) { int nMissing; char **missing, *defString; fFontSet = getFontSetWithGuess(name, &missing, &nMissing, &defString); if (None == fFontSet) { warn(_("Could not load fontset \"%s\"."), name); if (nMissing) XFreeStringList(missing); fFontSet = XCreateFontSet(xapp->display(), "fixed", &missing, &nMissing, &defString); if (None == fFontSet) warn(_("Loading of fallback font \"%s\" failed."), "fixed"); } if (fFontSet) { if (nMissing) { warn(_("Missing codesets for fontset \"%s\":"), name); for (int n(0); n < nMissing; ++n) warn(" %s\n", missing[n]); XFreeStringList(missing); } XFontSetExtents * extents(XExtentsOfFontSet(fFontSet)); if (NULL != extents) { fAscent = -extents->max_logical_extent.y; fDescent = extents->max_logical_extent.height - fAscent; } } } YFontSet::~YFontSet() { if (NULL != fFontSet) XFreeFontSet(xapp->display(), fFontSet); } int YFontSet::textWidth(const char *str, int len) const { return XmbTextEscapement(fFontSet, str, len); } void YFontSet::drawGlyphs(Graphics & graphics, int x, int y, char const * str, int len) { XmbDrawString(xapp->display(), graphics.drawable(), fFontSet, graphics.handle(), x - graphics.xorigin(), y - graphics.yorigin(), str, len); } XFontSet YFontSet::getFontSetWithGuess(char const * pattern, char *** missing, int * nMissing, char ** defString) { XFontSet fontset(XCreateFontSet(xapp->display(), pattern, missing, nMissing, defString)); if (None != fontset && !*nMissing) // --------------- got an exact match --- return fontset; if (*nMissing) XFreeStringList(*missing); if (None == fontset) { // --- get a fallback fontset for pattern analyis --- #warning "remove this broken locale switching" char const * locale(setlocale(LC_CTYPE, NULL)); setlocale(LC_CTYPE, "C"); fontset = XCreateFontSet(xapp->display(), pattern, missing, nMissing, defString); setlocale(LC_CTYPE, locale); } if (None != fontset) { // ----------------------------- get default XLFD --- char ** fontnames; XFontStruct ** fontstructs; XFontsOfFontSet(fontset, &fontstructs, &fontnames); pattern = *fontnames; } char * weight(getNameElement(pattern, 3)); char * slant(getNameElement(pattern, 4)); char * pxlsz(getNameElement(pattern, 7)); // --- build fuzzy font pattern for better matching for various charsets --- if (!strcmp(weight, "*")) { delete[] weight; weight = newstr("medium"); } if (!strcmp(slant, "*")) { delete[] slant; slant = newstr("r"); } pattern = strJoin(pattern, "," "-*-*-", weight, "-", slant, "-*-*-", pxlsz, "-*-*-*-*-*-*-*," "-*-*-*-*-*-*-", pxlsz, "-*-*-*-*-*-*-*,*", NULL); if (fontset) XFreeFontSet(xapp->display(), fontset); delete[] pxlsz; delete[] slant; delete[] weight; MSG(("trying fuzzy fontset pattern: \"%s\"", pattern)); fontset = XCreateFontSet(xapp->display(), pattern, missing, nMissing, defString); delete[] pattern; return fontset; } #endif // CONFIG_I18N YFont *getCoreFont(const char *name) { YFont *font = 0; #ifdef CONFIG_I18N if (multiByte && NULL != (font = new YFontSet(name))) { MSG(("FontSet: %s", name)); if (font->valid()) return font; delete font; msg("failed to load fontset '%s'", name); } #endif if (NULL != (font = new YCoreFont(name))) { MSG(("CoreFont: %s", name)); if (font->valid()) return font; delete font; } msg("failed to load font '%s'", name); return NULL; } #endif
#include "config.h" #ifdef CONFIG_COREFONTS #include "ypaint.h" #include "intl.h" #include "yxapp.h" #include "yprefs.h" #include <string.h> //#include <locale.h> class YCoreFont : public YFont { public: YCoreFont(char const * name); virtual ~YCoreFont(); virtual bool valid() const { return (NULL != fFont); } virtual int descent() const { return fFont->max_bounds.descent; } virtual int ascent() const { return fFont->max_bounds.ascent; } virtual int textWidth(char const * str, int len) const; virtual void drawGlyphs(class Graphics & graphics, int x, int y, char const * str, int len); private: XFontStruct * fFont; }; #ifdef CONFIG_I18N class YFontSet : public YFont { public: YFontSet(char const * name); virtual ~YFontSet(); virtual bool valid() const { return (None != fFontSet); } virtual int descent() const { return fDescent; } virtual int ascent() const { return fAscent; } virtual int textWidth(char const * str, int len) const; virtual void drawGlyphs(class Graphics & graphics, int x, int y, char const * str, int len); private: static XFontSet getFontSetWithGuess(char const * pattern, char *** missing, int * nMissing, char ** defString); XFontSet fFontSet; int fAscent, fDescent; }; #endif /******************************************************************************/ YCoreFont::YCoreFont(char const * name) { if (NULL == (fFont = XLoadQueryFont(xapp->display(), name))) { warn(_("Could not load font \"%s\"."), name); if (NULL == (fFont = XLoadQueryFont(xapp->display(), "fixed"))) warn(_("Loading of fallback font \"%s\" failed."), "fixed"); } } YCoreFont::~YCoreFont() { if (NULL != fFont) XFreeFont(xapp->display(), fFont); } int YCoreFont::textWidth(const char *str, int len) const { return XTextWidth(fFont, str, len); } void YCoreFont::drawGlyphs(Graphics & graphics, int x, int y, char const * str, int len) { XSetFont(xapp->display(), graphics.handle(), fFont->fid); XDrawString(xapp->display(), graphics.drawable(), graphics.handle(), x - graphics.xorigin(), y - graphics.yorigin(), str, len); } /******************************************************************************/ #ifdef CONFIG_I18N YFontSet::YFontSet(char const * name): fFontSet(None), fAscent(0), fDescent(0) { int nMissing; char **missing, *defString; fFontSet = getFontSetWithGuess(name, &missing, &nMissing, &defString); if (None == fFontSet) { warn(_("Could not load fontset \"%s\"."), name); if (nMissing) XFreeStringList(missing); fFontSet = XCreateFontSet(xapp->display(), "fixed", &missing, &nMissing, &defString); if (None == fFontSet) warn(_("Loading of fallback font \"%s\" failed."), "fixed"); } if (fFontSet) { if (nMissing) { warn(_("Missing codesets for fontset \"%s\":"), name); for (int n(0); n < nMissing; ++n) warn(" %s\n", missing[n]); XFreeStringList(missing); } XFontSetExtents * extents(XExtentsOfFontSet(fFontSet)); if (NULL != extents) { fAscent = -extents->max_logical_extent.y; fDescent = extents->max_logical_extent.height - fAscent; } } } YFontSet::~YFontSet() { if (NULL != fFontSet) XFreeFontSet(xapp->display(), fFontSet); } int YFontSet::textWidth(const char *str, int len) const { return XmbTextEscapement(fFontSet, str, len); } void YFontSet::drawGlyphs(Graphics & graphics, int x, int y, char const * str, int len) { XmbDrawString(xapp->display(), graphics.drawable(), fFontSet, graphics.handle(), x - graphics.xorigin(), y - graphics.yorigin(), str, len); } XFontSet YFontSet::getFontSetWithGuess(char const * pattern, char *** missing, int * nMissing, char ** defString) { XFontSet fontset(XCreateFontSet(xapp->display(), pattern, missing, nMissing, defString)); if (None != fontset && !*nMissing) // --------------- got an exact match --- return fontset; if (*nMissing) XFreeStringList(*missing); if (None == fontset) { // --- get a fallback fontset for pattern analyis --- #warning "remove this broken locale switching" char const * locale(setlocale(LC_CTYPE, NULL)); setlocale(LC_CTYPE, "C"); fontset = XCreateFontSet(xapp->display(), pattern, missing, nMissing, defString); setlocale(LC_CTYPE, locale); } if (None != fontset) { // ----------------------------- get default XLFD --- char ** fontnames; XFontStruct ** fontstructs; XFontsOfFontSet(fontset, &fontstructs, &fontnames); pattern = *fontnames; } char * weight(getNameElement(pattern, 3)); char * slant(getNameElement(pattern, 4)); char * pxlsz(getNameElement(pattern, 7)); // --- build fuzzy font pattern for better matching for various charsets --- if (!strcmp(weight, "*")) { delete[] weight; weight = newstr("medium"); } if (!strcmp(slant, "*")) { delete[] slant; slant = newstr("r"); } pattern = strJoin(pattern, "," "-*-*-", weight, "-", slant, "-*-*-", pxlsz, "-*-*-*-*-*-*-*," "-*-*-*-*-*-*-", pxlsz, "-*-*-*-*-*-*-*,*", NULL); if (fontset) XFreeFontSet(xapp->display(), fontset); delete[] pxlsz; delete[] slant; delete[] weight; MSG(("trying fuzzy fontset pattern: \"%s\"", pattern)); fontset = XCreateFontSet(xapp->display(), pattern, missing, nMissing, defString); delete[] pattern; return fontset; } #endif // CONFIG_I18N YFont *getCoreFont(const char *name) { YFont *font = 0; #ifdef CONFIG_I18N if (multiByte && NULL != (font = new YFontSet(name))) { MSG(("FontSet: %s", name)); if (font->valid()) return font; delete font; msg("failed to load fontset '%s'", name); } #endif if (NULL != (font = new YCoreFont(name))) { MSG(("CoreFont: %s", name)); if (font->valid()) return font; delete font; } msg("failed to load font '%s'", name); return NULL; } #endif
remove bad include
remove bad include
C++
lgpl-2.1
bedna-KU/icewm,dicej/icewm,dicej/icewm,dicej/icewm,jinn-alt/icewm,dicej/icewm,bedna-KU/icewm,jinn-alt/icewm,jinn-alt/icewm,bedna-KU/icewm
f5abf53c8524fee697210577c5f78afb53020e71
src/primesieve/CpuInfo.cpp
src/primesieve/CpuInfo.cpp
/// /// @file CpuInfo.cpp /// @brief Get the CPUs cache sizes in bytes. /// /// Copyright (C) 2017 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/CpuInfo.hpp> #include <cstddef> #if defined(__APPLE__) #if !defined(__has_include) #define APPLE_SYSCTL #elif __has_include(<sys/types.h>) && \ __has_include(<sys/sysctl.h>) #define APPLE_SYSCTL #endif #endif #if defined(_WIN32) #include <windows.h> #include <vector> #elif defined(APPLE_SYSCTL) #include <sys/types.h> #include <sys/sysctl.h> #include <vector> #else // all other OSes #include <exception> #include <fstream> #include <sstream> #include <string> using namespace std; namespace { string getString(const string& filename) { ifstream file(filename); string str; if (file) { ostringstream oss; oss << file.rdbuf(); str = oss.str(); } return str; } size_t getValue(const string& filename) { try { // first character after number size_t idx = 0; string str = getString(filename); size_t val = stol(str, &idx); if (idx < str.size()) { // Last character may be: // 'K' = kilobytes // 'M' = megabytes // 'G' = gigabytes if (str[idx] == 'K') val *= 1024; if (str[idx] == 'M') val *= 1024 * 1024; if (str[idx] == 'G') val *= 1024 * 1024 * 1024; } return val; } catch (exception&) { return 0; } } } // namespace #endif using namespace std; namespace primesieve { CpuInfo::CpuInfo() : l1CacheSize_(0), l2CacheSize_(0), privateL2Cache_(false) { initCache(); } size_t CpuInfo::l1CacheSize() const { return l1CacheSize_; } size_t CpuInfo::l2CacheSize() const { return l2CacheSize_; } bool CpuInfo::privateL2Cache() const { return privateL2Cache_; } bool CpuInfo::hasL1Cache() const { return l1CacheSize_ >= (1 << 12) && l1CacheSize_ <= (1ull << 40); } bool CpuInfo::hasL2Cache() const { return l2CacheSize_ >= (1 << 12) && l2CacheSize_ <= (1ull << 40); } #if defined(APPLE_SYSCTL) void CpuInfo::initCache() { size_t l1Length = sizeof(l1CacheSize_); size_t l2Length = sizeof(l2CacheSize_); sysctlbyname("hw.l1dcachesize", &l1CacheSize_, &l1Length, NULL, 0); sysctlbyname("hw.l2cachesize" , &l2CacheSize_, &l2Length, NULL, 0); size_t size = 0; if (!sysctlbyname("hw.cacheconfig", NULL, &size, NULL, 0)) { size_t n = size / sizeof(size); vector<size_t> values(n); if (values.size() > 2) { // https://developer.apple.com/library/content/releasenotes/Performance/RN-AffinityAPI/index.html sysctlbyname("hw.cacheconfig" , &values[0], &size, NULL, 0); size_t l1CacheConfig = values[1]; size_t l2CacheConfig = values[2]; if (l2CacheConfig > 0 && l1CacheConfig == l2CacheConfig) { privateL2Cache_ = true; } } } } #elif defined(_WIN32) void CpuInfo::initCache() { typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); if (glpi) { DWORD bytes = 0; glpi(0, &bytes); size_t size = bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size); glpi(info.data(), &bytes); for (size_t i = 0; i < size; i++) { if (info[i].Relationship == RelationCache) { if (info[i].Cache.Level == 1) l1CacheSize_ = info[i].Cache.Size; if (info[i].Cache.Level == 2) { // Using the Windows API it is not possible to find out // whether the L2 cache is private or shared hence // we assume the L2 cache is private privateL2Cache_ = true; l2CacheSize_ = info[i].Cache.Size; } } } } } #else /// This works on Linux and Android. We also use this /// for all unknown OSes, it might work. /// void CpuInfo::initCache() { string l1CacheMap; string l2CacheMap; for (int i = 0; i <= 3; i++) { string filename = "/sys/devices/system/cpu/cpu0/cache/index" + to_string(i); string cacheLevel = filename + "/level"; string cacheSize = filename + "/size"; string cacheMap = filename + "/shared_cpu_map"; string cacheType = filename + "/type"; size_t level = getValue(cacheLevel); string type = getString(cacheType); if (level == 1 && (type.find("Data") != string::npos || type.find("Unified") != string::npos)) { l1CacheSize_ = getValue(cacheSize); l1CacheMap = getString(cacheMap); } if (level == 2 && (type.find("Data") != string::npos || type.find("Unified") != string::npos)) { l2CacheSize_ = getValue(cacheSize); l2CacheMap = getString(cacheMap); } } if (hasL2Cache() && !l2CacheMap.empty() && l2CacheMap == l1CacheMap) { privateL2Cache_ = true; } } #endif /// Singleton const CpuInfo cpuInfo; } // namespace
/// /// @file CpuInfo.cpp /// @brief Get the CPUs cache sizes in bytes. /// /// Copyright (C) 2017 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/CpuInfo.hpp> #include <cstddef> #if defined(__APPLE__) #if !defined(__has_include) #define APPLE_SYSCTL #elif __has_include(<sys/types.h>) && \ __has_include(<sys/sysctl.h>) #define APPLE_SYSCTL #endif #endif #if defined(_WIN32) #include <windows.h> #include <vector> #elif defined(APPLE_SYSCTL) #include <sys/types.h> #include <sys/sysctl.h> #include <vector> #else // all other OSes #include <exception> #include <fstream> #include <sstream> #include <string> using namespace std; namespace { string getString(const string& filename) { ifstream file(filename); string str; if (file) { ostringstream oss; oss << file.rdbuf(); str = oss.str(); } return str; } size_t getValue(const string& filename) { try { // first character after number size_t idx = 0; string str = getString(filename); size_t val = stol(str, &idx); if (idx < str.size()) { // Last character may be: // 'K' = kilobytes // 'M' = megabytes // 'G' = gigabytes if (str[idx] == 'K') val *= 1024; if (str[idx] == 'M') val *= 1024 * 1024; if (str[idx] == 'G') val *= 1024 * 1024 * 1024; } return val; } catch (exception&) { return 0; } } } // namespace #endif using namespace std; namespace primesieve { CpuInfo::CpuInfo() : l1CacheSize_(0), l2CacheSize_(0), privateL2Cache_(false) { initCache(); } size_t CpuInfo::l1CacheSize() const { return l1CacheSize_; } size_t CpuInfo::l2CacheSize() const { return l2CacheSize_; } bool CpuInfo::privateL2Cache() const { return privateL2Cache_; } bool CpuInfo::hasL1Cache() const { return l1CacheSize_ >= (1 << 12) && l1CacheSize_ <= (1ull << 40); } bool CpuInfo::hasL2Cache() const { return l2CacheSize_ >= (1 << 12) && l2CacheSize_ <= (1ull << 40); } #if defined(APPLE_SYSCTL) void CpuInfo::initCache() { size_t l1Length = sizeof(l1CacheSize_); size_t l2Length = sizeof(l2CacheSize_); sysctlbyname("hw.l1dcachesize", &l1CacheSize_, &l1Length, NULL, 0); sysctlbyname("hw.l2cachesize" , &l2CacheSize_, &l2Length, NULL, 0); size_t size = 0; if (!sysctlbyname("hw.cacheconfig", NULL, &size, NULL, 0)) { size_t n = size / sizeof(size); vector<size_t> values(n); if (values.size() > 2) { // https://developer.apple.com/library/content/releasenotes/Performance/RN-AffinityAPI/index.html sysctlbyname("hw.cacheconfig" , &values[0], &size, NULL, 0); size_t l1CacheConfig = values[1]; size_t l2CacheConfig = values[2]; if (l2CacheConfig > 0 && l1CacheConfig == l2CacheConfig) { privateL2Cache_ = true; } } } } #elif defined(_WIN32) void CpuInfo::initCache() { typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); if (glpi) { DWORD bytes = 0; glpi(0, &bytes); size_t size = bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size); glpi(info.data(), &bytes); for (size_t i = 0; i < size; i++) { if (info[i].Relationship == RelationCache) { if (info[i].Cache.Level == 1 && (info[i].Cache.Type == CacheData || info[i].Cache.Type == CacheUnified)) { l1CacheSize_ = info[i].Cache.Size; } if (info[i].Cache.Level == 2 && (info[i].Cache.Type == CacheData || info[i].Cache.Type == CacheUnified)) { // Using the Windows API it is not possible to find out // whether the L2 cache is private or shared hence // we assume the L2 cache is private privateL2Cache_ = true; l2CacheSize_ = info[i].Cache.Size; } } } } } #else /// This works on Linux and Android. We also use this /// for all unknown OSes, it might work. /// void CpuInfo::initCache() { string l1CacheMap; string l2CacheMap; for (int i = 0; i <= 3; i++) { string filename = "/sys/devices/system/cpu/cpu0/cache/index" + to_string(i); string cacheLevel = filename + "/level"; string cacheSize = filename + "/size"; string cacheMap = filename + "/shared_cpu_map"; string cacheType = filename + "/type"; size_t level = getValue(cacheLevel); string type = getString(cacheType); if (level == 1 && (type.find("Data") != string::npos || type.find("Unified") != string::npos)) { l1CacheSize_ = getValue(cacheSize); l1CacheMap = getString(cacheMap); } if (level == 2 && (type.find("Data") != string::npos || type.find("Unified") != string::npos)) { l2CacheSize_ = getValue(cacheSize); l2CacheMap = getString(cacheMap); } } if (hasL2Cache() && !l2CacheMap.empty() && l2CacheMap == l1CacheMap) { privateL2Cache_ = true; } } #endif /// Singleton const CpuInfo cpuInfo; } // namespace
Improve Windows cache size detection
Improve Windows cache size detection
C++
bsd-2-clause
kimwalisch/primesieve,kimwalisch/primesieve,kimwalisch/primesieve
9b77ea56ff7fd028f46a3780f11de59ab69cdd13
src/qoi/src/rayfire_mesh.C
src/qoi/src/rayfire_mesh.C
//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014-2016 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/rayfire_mesh.h" // GRINS #include "grins/multiphysics_sys.h" #include "grins/assembly_context.h" #include "grins/materials_parsing.h" #include "grins/math_constants.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/fem_system.h" #include "libmesh/quadrature.h" #include "libmesh/point_locator_list.h" #include "libmesh/elem.h" #include "libmesh/edge_edge2.h" #include "libmesh/analytic_function.h" #include "libmesh/enum_elem_type.h" #include "libmesh/fe.h" #include "libmesh/fe_interface.h" namespace GRINS { RayfireMesh::RayfireMesh(libMesh::Point& origin, libMesh::Real theta, libMesh::Real phi) : _dim(3), _origin(origin), _theta(theta), _phi(phi) { libmesh_not_implemented(); } RayfireMesh::RayfireMesh(libMesh::Point& origin, libMesh::Real theta) : _dim(2), _origin(origin), _theta(theta), _phi(-7.0) // bounds on angles are +/- 2pi { if (std::abs(_theta) > 2.0*Constants::pi) libmesh_error_msg("Please supply a theta value between -2*pi and 2*pi"); } void RayfireMesh::init(const libMesh::MeshBase& mesh_base) { // consistency check if(mesh_base.mesh_dimension() != _dim) { std::stringstream ss; ss <<"The supplied mesh object is " <<mesh_base.mesh_dimension() <<"D, but the RayfireMesh object was created with the " <<_dim <<"D constructor"; libmesh_error_msg(ss.str()); } _mesh = new libMesh::Mesh(mesh_base.comm(),(unsigned char)1); unsigned int node_id = 0; libMesh::Point* start_point = new libMesh::Point(_origin); // get first element libMesh::UniquePtr<libMesh::PointLocatorBase> locator = mesh_base.sub_point_locator(); const libMesh::Elem* start_elem = (*locator)(_origin); if (!start_elem) libmesh_error_msg("Origin is not on mesh"); // ensure the origin is on a boundary element // AND on the boundary of said element check_origin_on_boundary(start_elem); // add the origin point to the point list _mesh->add_point(*start_point,node_id++); libMesh::Point* end_point = new libMesh::Point(); const libMesh::Elem* next_elem; const libMesh::Elem* prev_elem = start_elem; do { // calculate the end point and // get the next elem in the rayfire next_elem = get_next_elem(prev_elem,start_point,end_point); // add end point as node on the rayfire mesh _mesh->add_point(*end_point,node_id); libMesh::Elem* elem = _mesh->add_elem(new libMesh::Edge2); elem->set_node(0) = _mesh->node_ptr(node_id-1); elem->set_node(1) = _mesh->node_ptr(node_id++); // add new rayfire elem to the map _elem_id_map[prev_elem->id()] = elem; start_point = end_point; prev_elem = next_elem; } while(next_elem); } const libMesh::Elem* RayfireMesh::map_to_rayfire_elem(const libMesh::dof_id_type elem_id) { std::map<libMesh::dof_id_type,libMesh::Elem*>::iterator it; it = _elem_id_map.find(elem_id); if (it != _elem_id_map.end()) return it->second; return NULL; } // private functions void RayfireMesh::check_origin_on_boundary(const libMesh::Elem* start_elem) { // first, make sure the elem is on a boundary if ( !(start_elem->on_boundary()) ) libmesh_error_msg("The supplied origin point is not on a boundary element"); // second, check all boundary sides of the elem // to see if one of them conatins the origin point bool valid = false; for (unsigned int s=0; s<start_elem->n_sides(); s++) { // neighbor() returns NULL on boundary elems if ( start_elem->neighbor(s) ) continue; // we found a boundary elem, so make an edge and see if it contains the origin libMesh::UniquePtr<libMesh::Elem> edge_elem = start_elem->build_edge(s); valid |= edge_elem->contains_point(_origin); } if (!valid) libmesh_error_msg("The supplied origin point is not on the boundary of the starting element"); } const libMesh::Elem* RayfireMesh::get_next_elem(const libMesh::Elem* cur_elem, libMesh::Point* start_point, libMesh::Point* next_point) { libMesh::Point* intersection_point = new libMesh::Point(); // loop over all sides of the elem and check each one for intersection for (unsigned int s=0; s<cur_elem->n_sides(); s++) { const libMesh::UniquePtr<libMesh::Elem> edge_elem = cur_elem->build_edge(s); if (edge_elem->contains_point(*start_point)) continue; bool converged = newton_solve_intersection(*start_point,edge_elem.get(),intersection_point); if (converged) { if ( check_valid_point(*intersection_point,*start_point,*edge_elem,next_point) ) return get_correct_neighbor(*intersection_point,cur_elem,s); } else continue; } // for s return NULL; // no intersection } bool RayfireMesh::check_valid_point(libMesh::Point& intersection_point, libMesh::Point& start_point, libMesh::Elem& edge_elem, libMesh::Point* next_point) { bool is_not_start = !(intersection_point.absolute_fuzzy_equals(start_point)); bool is_on_edge = edge_elem.contains_point(intersection_point); bool is_valid = is_not_start && is_on_edge; if ( is_valid ) { (*next_point)(0) = intersection_point(0); (*next_point)(1) = intersection_point(1); } return is_valid; } const libMesh::Elem* RayfireMesh::get_correct_neighbor(libMesh::Point& end_point, const libMesh::Elem* cur_elem, unsigned int side) { // check if side is a boundary if( !(cur_elem->neighbor(side)) ) return NULL; // check if the intersection point is a vertex bool is_vertex = false; for(unsigned int n=0; n<4; n++) is_vertex |= (cur_elem->get_node(n))->absolute_fuzzy_equals(end_point); if (is_vertex) { // rayfire goes through vertex // get all elems that share this vertex std::set<const libMesh::Elem*> elem_set; cur_elem->find_point_neighbors(end_point,elem_set); std::set<const libMesh::Elem *>::const_iterator it = elem_set.begin(); const std::set<const libMesh::Elem *>::const_iterator end = elem_set.end(); // iterate over each elem for (; it != end; ++it) { const libMesh::Elem* elem = *it; if (elem == cur_elem) // skip the current elem continue; // move a little bit along the rayfire // and see if we are in the elem libMesh::Real L = elem->hmin(); L *= 0.1; // parametric representation of rayfire line libMesh::Real x = end_point(0) + L*std::cos(_theta); libMesh::Real y = end_point(1) + L*std::sin(_theta); if ( elem->contains_point(libMesh::Point(x,y)) ) return elem; } } else { // not a vertex, so just get the elem on that side return cur_elem->neighbor(side); } libmesh_error_msg("We shouldn't be here..."); return NULL; } bool RayfireMesh::newton_solve_intersection(libMesh::Point& initial_point, const libMesh::Elem* edge_elem, libMesh::Point* intersection_point) { unsigned int iter_max = 20; // max iterations // the number of shape functions needed for the edge_elem unsigned int n_sf = libMesh::FE<1,libMesh::LAGRANGE>::n_shape_functions(edge_elem->type(),edge_elem->default_order()); // starting point on the elem libMesh::Real x0 = initial_point(0); libMesh::Real y0 = initial_point(1); // shape functions and derivatives w.r.t reference coordinate std::vector<libMesh::Real> phi(n_sf); std::vector<libMesh::Real> dphi(n_sf); // Newton iteration step libMesh::Real d_xi; // tan(theta) is the slope, so precompute since it is used repeatedly libMesh::Real tan_theta = std::tan(_theta); // Initial guess is center of the edge_elem libMesh::Real xi = 0.0; // Newton iteration for(unsigned int it=0; it<iter_max; it++) { // Get the shape function and derivative values at the reference coordinate // phi.size() == dphi.size() for(unsigned int i=0; i<phi.size(); i++) { phi[i] = libMesh::FE<1,libMesh::LAGRANGE>::shape(edge_elem->type(), edge_elem->default_order(), i, xi); dphi[i] = libMesh::FE<1,libMesh::LAGRANGE>::shape_deriv(edge_elem->type(), edge_elem->default_order(), i, 0, // const unsigned int libmesh_dbg_varj xi); } // for i libMesh::Real X=0.0, Y=0.0, dX=0.0, dY=0.0; for(unsigned int i=0; i<phi.size(); i++) { X += (*(edge_elem->get_node(i)))(0) * phi[i]; dX += (*(edge_elem->get_node(i)))(0) * dphi[i]; Y += (*(edge_elem->get_node(i)))(1) * phi[i]; dY += (*(edge_elem->get_node(i)))(1) * dphi[i]; } libMesh::Real f = tan_theta*(X-x0) - (Y-y0); libMesh::Real df = tan_theta*(dX) - dY; d_xi = f/df; if(std::abs(d_xi) < libMesh::TOLERANCE) { // convergence (*intersection_point)(0) = X; (*intersection_point)(1) = Y; return true; } else xi -= d_xi; } // for it // no convergence return false; } } //namespace GRINS
//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014-2016 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/rayfire_mesh.h" // GRINS #include "grins/multiphysics_sys.h" #include "grins/assembly_context.h" #include "grins/materials_parsing.h" #include "grins/math_constants.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/fem_system.h" #include "libmesh/quadrature.h" #include "libmesh/point_locator_base.h" #include "libmesh/elem.h" #include "libmesh/edge_edge2.h" #include "libmesh/analytic_function.h" #include "libmesh/enum_elem_type.h" #include "libmesh/fe.h" #include "libmesh/fe_interface.h" namespace GRINS { RayfireMesh::RayfireMesh(libMesh::Point& origin, libMesh::Real theta, libMesh::Real phi) : _dim(3), _origin(origin), _theta(theta), _phi(phi) { libmesh_not_implemented(); } RayfireMesh::RayfireMesh(libMesh::Point& origin, libMesh::Real theta) : _dim(2), _origin(origin), _theta(theta), _phi(-7.0) // bounds on angles are +/- 2pi { if (std::abs(_theta) > 2.0*Constants::pi) libmesh_error_msg("Please supply a theta value between -2*pi and 2*pi"); } void RayfireMesh::init(const libMesh::MeshBase& mesh_base) { // consistency check if(mesh_base.mesh_dimension() != _dim) { std::stringstream ss; ss <<"The supplied mesh object is " <<mesh_base.mesh_dimension() <<"D, but the RayfireMesh object was created with the " <<_dim <<"D constructor"; libmesh_error_msg(ss.str()); } _mesh = new libMesh::Mesh(mesh_base.comm(),(unsigned char)1); unsigned int node_id = 0; libMesh::Point* start_point = new libMesh::Point(_origin); // get first element libMesh::UniquePtr<libMesh::PointLocatorBase> locator = mesh_base.sub_point_locator(); const libMesh::Elem* start_elem = (*locator)(_origin); if (!start_elem) libmesh_error_msg("Origin is not on mesh"); // ensure the origin is on a boundary element // AND on the boundary of said element check_origin_on_boundary(start_elem); // add the origin point to the point list _mesh->add_point(*start_point,node_id++); libMesh::Point* end_point = new libMesh::Point(); const libMesh::Elem* next_elem; const libMesh::Elem* prev_elem = start_elem; do { // calculate the end point and // get the next elem in the rayfire next_elem = get_next_elem(prev_elem,start_point,end_point); // add end point as node on the rayfire mesh _mesh->add_point(*end_point,node_id); libMesh::Elem* elem = _mesh->add_elem(new libMesh::Edge2); elem->set_node(0) = _mesh->node_ptr(node_id-1); elem->set_node(1) = _mesh->node_ptr(node_id++); // add new rayfire elem to the map _elem_id_map[prev_elem->id()] = elem; start_point = end_point; prev_elem = next_elem; } while(next_elem); } const libMesh::Elem* RayfireMesh::map_to_rayfire_elem(const libMesh::dof_id_type elem_id) { std::map<libMesh::dof_id_type,libMesh::Elem*>::iterator it; it = _elem_id_map.find(elem_id); if (it != _elem_id_map.end()) return it->second; return NULL; } // private functions void RayfireMesh::check_origin_on_boundary(const libMesh::Elem* start_elem) { // first, make sure the elem is on a boundary if ( !(start_elem->on_boundary()) ) libmesh_error_msg("The supplied origin point is not on a boundary element"); // second, check all boundary sides of the elem // to see if one of them conatins the origin point bool valid = false; for (unsigned int s=0; s<start_elem->n_sides(); s++) { // neighbor() returns NULL on boundary elems if ( start_elem->neighbor(s) ) continue; // we found a boundary elem, so make an edge and see if it contains the origin libMesh::UniquePtr<libMesh::Elem> edge_elem = start_elem->build_edge(s); valid |= edge_elem->contains_point(_origin); } if (!valid) libmesh_error_msg("The supplied origin point is not on the boundary of the starting element"); } const libMesh::Elem* RayfireMesh::get_next_elem(const libMesh::Elem* cur_elem, libMesh::Point* start_point, libMesh::Point* next_point) { libMesh::Point* intersection_point = new libMesh::Point(); // loop over all sides of the elem and check each one for intersection for (unsigned int s=0; s<cur_elem->n_sides(); s++) { const libMesh::UniquePtr<libMesh::Elem> edge_elem = cur_elem->build_edge(s); if (edge_elem->contains_point(*start_point)) continue; bool converged = newton_solve_intersection(*start_point,edge_elem.get(),intersection_point); if (converged) { if ( check_valid_point(*intersection_point,*start_point,*edge_elem,next_point) ) return get_correct_neighbor(*intersection_point,cur_elem,s); } else continue; } // for s return NULL; // no intersection } bool RayfireMesh::check_valid_point(libMesh::Point& intersection_point, libMesh::Point& start_point, libMesh::Elem& edge_elem, libMesh::Point* next_point) { bool is_not_start = !(intersection_point.absolute_fuzzy_equals(start_point)); bool is_on_edge = edge_elem.contains_point(intersection_point); bool is_valid = is_not_start && is_on_edge; if ( is_valid ) { (*next_point)(0) = intersection_point(0); (*next_point)(1) = intersection_point(1); } return is_valid; } const libMesh::Elem* RayfireMesh::get_correct_neighbor(libMesh::Point& end_point, const libMesh::Elem* cur_elem, unsigned int side) { // check if side is a boundary if( !(cur_elem->neighbor(side)) ) return NULL; // check if the intersection point is a vertex bool is_vertex = false; for(unsigned int n=0; n<4; n++) is_vertex |= (cur_elem->get_node(n))->absolute_fuzzy_equals(end_point); if (is_vertex) { // rayfire goes through vertex // get all elems that share this vertex std::set<const libMesh::Elem*> elem_set; cur_elem->find_point_neighbors(end_point,elem_set); std::set<const libMesh::Elem *>::const_iterator it = elem_set.begin(); const std::set<const libMesh::Elem *>::const_iterator end = elem_set.end(); // iterate over each elem for (; it != end; ++it) { const libMesh::Elem* elem = *it; if (elem == cur_elem) // skip the current elem continue; // move a little bit along the rayfire // and see if we are in the elem libMesh::Real L = elem->hmin(); L *= 0.1; // parametric representation of rayfire line libMesh::Real x = end_point(0) + L*std::cos(_theta); libMesh::Real y = end_point(1) + L*std::sin(_theta); if ( elem->contains_point(libMesh::Point(x,y)) ) return elem; } } else { // not a vertex, so just get the elem on that side return cur_elem->neighbor(side); } libmesh_error_msg("We shouldn't be here..."); return NULL; } bool RayfireMesh::newton_solve_intersection(libMesh::Point& initial_point, const libMesh::Elem* edge_elem, libMesh::Point* intersection_point) { unsigned int iter_max = 20; // max iterations // the number of shape functions needed for the edge_elem unsigned int n_sf = libMesh::FE<1,libMesh::LAGRANGE>::n_shape_functions(edge_elem->type(),edge_elem->default_order()); // starting point on the elem libMesh::Real x0 = initial_point(0); libMesh::Real y0 = initial_point(1); // shape functions and derivatives w.r.t reference coordinate std::vector<libMesh::Real> phi(n_sf); std::vector<libMesh::Real> dphi(n_sf); // Newton iteration step libMesh::Real d_xi; // tan(theta) is the slope, so precompute since it is used repeatedly libMesh::Real tan_theta = std::tan(_theta); // Initial guess is center of the edge_elem libMesh::Real xi = 0.0; // Newton iteration for(unsigned int it=0; it<iter_max; it++) { // Get the shape function and derivative values at the reference coordinate // phi.size() == dphi.size() for(unsigned int i=0; i<phi.size(); i++) { phi[i] = libMesh::FE<1,libMesh::LAGRANGE>::shape(edge_elem->type(), edge_elem->default_order(), i, xi); dphi[i] = libMesh::FE<1,libMesh::LAGRANGE>::shape_deriv(edge_elem->type(), edge_elem->default_order(), i, 0, // const unsigned int libmesh_dbg_varj xi); } // for i libMesh::Real X=0.0, Y=0.0, dX=0.0, dY=0.0; for(unsigned int i=0; i<phi.size(); i++) { X += (*(edge_elem->get_node(i)))(0) * phi[i]; dX += (*(edge_elem->get_node(i)))(0) * dphi[i]; Y += (*(edge_elem->get_node(i)))(1) * phi[i]; dY += (*(edge_elem->get_node(i)))(1) * dphi[i]; } libMesh::Real f = tan_theta*(X-x0) - (Y-y0); libMesh::Real df = tan_theta*(dX) - dY; d_xi = f/df; if(std::abs(d_xi) < libMesh::TOLERANCE) { // convergence (*intersection_point)(0) = X; (*intersection_point)(1) = Y; return true; } else xi -= d_xi; } // for it // no convergence return false; } } //namespace GRINS
Use header for PointLocatorBase
Use header for PointLocatorBase Not the subclass. In particular, this subclass is being removed from post 1.0 libMesh, so this actually doesn't even compile.
C++
lgpl-2.1
nicholasmalaya/grins,nicholasmalaya/grins,nicholasmalaya/grins,nicholasmalaya/grins
4994af6626db61f8f0ac2d0e42c849a40763c477
examples/mtran/transpose.cpp
examples/mtran/transpose.cpp
#include <iostream> #include <random> #include <string> #include <vector> #include "tuner_api.h" #define USE_CUDA 1 #define USE_PROFILING 0 #if USE_CUDA == 0 #if defined(_MSC_VER) #define KTT_KERNEL_FILE "../examples/mtran/mtran_kernel.cl" #define KTT_REFERENCE_KERNEL_FILE "../examples/mtran/mtran_reference_kernel.cl" #else #define KTT_KERNEL_FILE "../../examples/mtran/mtran_kernel.cl" #define KTT_REFERENCE_KERNEL_FILE "../../examples/mtran/mtran_reference_kernel.cl" #endif #else #if defined(_MSC_VER) #define KTT_KERNEL_FILE "../examples/mtran/mtran_kernel.cu" #define KTT_REFERENCE_KERNEL_FILE "../examples/mtran/mtran_reference_kernel.cu" #else #define KTT_KERNEL_FILE "../../examples/mtran/mtran_kernel.cu" #define KTT_REFERENCE_KERNEL_FILE "../../examples/mtran/mtran_reference_kernel.cu" #endif #endif int main(int argc, char **argv) { // Initialize platform index, device index and paths to kernels ktt::PlatformIndex platformIndex = 0; ktt::DeviceIndex deviceIndex = 0; std::string kernelFile = KTT_KERNEL_FILE; std::string referenceKernelFile = KTT_REFERENCE_KERNEL_FILE; if (argc >= 2) { platformIndex = std::stoul(std::string(argv[1])); if (argc >= 3) { deviceIndex = std::stoul(std::string(argv[2])); if (argc >= 4) { kernelFile = std::string(argv[3]); if (argc >= 5) { referenceKernelFile = std::string(argv[4]); } } } } // Declare kernel parameters #if USE_PROFILING == 0 const int width = 8192; const int height = 8192; #else const int width = 4096; const int height = 4096; #endif const ktt::DimensionVector ndRangeDimensions(width, height); const ktt::DimensionVector ndRangeDimensionsReference(width/16, height/16); const ktt::DimensionVector referenceWorkGroupDimensions(16, 16); // Declare data variables std::vector<float> dst(width * height); std::vector<float> src(width * height); // Initialize data std::random_device device; std::default_random_engine engine(device()); std::uniform_real_distribution<float> distribution(0.0f, 10.0f); for (int i = 0; i < width*height; i++) { src[i] = distribution(engine); } // Create tuner #if USE_CUDA == 0 ktt::Tuner tuner(platformIndex, deviceIndex); tuner.setGlobalSizeType(ktt::GlobalSizeType::CUDA); #else ktt::Tuner tuner(platformIndex, deviceIndex, ktt::ComputeAPI::CUDA); #if USE_PROFILING == 1 printf("Executing with profiling switched ON.\n"); tuner.setKernelProfiling(true); #endif #endif tuner.setPrintingTimeUnit(ktt::TimeUnit::Microseconds); // Create kernel and configure input/output ktt::KernelId kernelId = tuner.addKernelFromFile(kernelFile, "mtran", ndRangeDimensions, ktt::DimensionVector(1, 1)); ktt::KernelId referenceKernelId = tuner.addKernelFromFile(referenceKernelFile, "mtranReference", ndRangeDimensionsReference, referenceWorkGroupDimensions); ktt::ArgumentId srcId = tuner.addArgumentVector(src, ktt::ArgumentAccessType::ReadOnly); ktt::ArgumentId dstId = tuner.addArgumentVector(dst, ktt::ArgumentAccessType::WriteOnly); ktt::ArgumentId widthId = tuner.addArgumentScalar(width); ktt::ArgumentId heightId = tuner.addArgumentScalar(height); tuner.setKernelArguments(kernelId, std::vector<ktt::ArgumentId>{dstId, srcId, widthId, heightId}); tuner.setKernelArguments(referenceKernelId, std::vector<ktt::ArgumentId>{dstId, srcId, widthId, heightId}); // Create tuning space tuner.addParameter(kernelId, "LOCAL_MEM", { 0, 1 }); #if USE_CUDA == 0 tuner.addParameter(kernelId, "VECTOR_TYPE", { 1, 2, 4, 8 }); #else tuner.addParameter(kernelId, "VECTOR_TYPE", { 1, 2, 4 }); #endif tuner.addParameter(kernelId, "CR", { 0, 1 }); #if USE_CUDA == 0 tuner.addParameter(kernelId, "PREFETCH", { 0, 1, 2 }); #endif tuner.addParameter(kernelId, "PADD_LOCAL", { 0, 1 }); tuner.addParameter(kernelId, "WORK_GROUP_SIZE_X", { 1, 2, 4, 8, 16, 32, 64 }); tuner.addParameter(kernelId, "WORK_GROUP_SIZE_Y", { 1, 2, 4, 8, 16, 32, 64 }); tuner.addParameter(kernelId, "TILE_SIZE_X", { 1, 2, 4, 8, 16, 32, 64 }); tuner.addParameter(kernelId, "TILE_SIZE_Y", { 1, 2, 4, 8, 16, 32, 64 }); tuner.addParameter(kernelId, "DIAGONAL_MAP", {0, 1}); // Constraint tuning space auto xConstraint = [] (std::vector<size_t> v) { return (v[0] == v[1]); }; auto yConstraint = [] (std::vector<size_t> v) { return (v[1] <= v[0]); }; auto tConstraint = [] (std::vector<size_t> v) { return (!v[0] || (v[1] <= v[2]*v[3])); }; auto pConstraint = [] (std::vector<size_t> v) { return (v[0] || !v[1]); }; auto vConstraint = [] (std::vector<size_t> v) { return (v[0]*v[1] <= 64); }; auto vlConstraint = [] (std::vector<size_t> v) { return (!v[0] || v[1] == 1); }; auto minparConstraint = [] (std::vector<size_t> v) {return (v[0] * v[1] >= 32);}; tuner.addConstraint(kernelId, { "TILE_SIZE_X", "WORK_GROUP_SIZE_X" }, xConstraint); tuner.addConstraint(kernelId, { "TILE_SIZE_Y", "WORK_GROUP_SIZE_Y" }, yConstraint); tuner.addConstraint(kernelId, { "LOCAL_MEM", "TILE_SIZE_Y", "WORK_GROUP_SIZE_X", "WORK_GROUP_SIZE_Y" }, tConstraint); tuner.addConstraint(kernelId, { "LOCAL_MEM", "PADD_LOCAL" }, pConstraint); tuner.addConstraint(kernelId, { "TILE_SIZE_X", "VECTOR_TYPE" }, vConstraint); tuner.addConstraint(kernelId, { "LOCAL_MEM", "VECTOR_TYPE" }, vlConstraint); // tuner.addConstraint(kernelId, { "TILE_SIZE_X", "TILE_SIZE_Y" }, minparConstraint); // Configure parallelism tuner.setThreadModifier(kernelId, ktt::ModifierType::Local, ktt::ModifierDimension::X, "WORK_GROUP_SIZE_X", ktt::ModifierAction::Multiply); tuner.setThreadModifier(kernelId, ktt::ModifierType::Local, ktt::ModifierDimension::Y, "WORK_GROUP_SIZE_Y", ktt::ModifierAction::Multiply); auto xGlobalModifier = [](const size_t size, const std::vector<size_t>& vector) {return size / vector.at(0) / vector.at(1);}; tuner.setThreadModifier(kernelId, ktt::ModifierType::Global, ktt::ModifierDimension::X, std::vector<std::string>{ "TILE_SIZE_X", "VECTOR_TYPE" }, xGlobalModifier); tuner.setThreadModifier(kernelId, ktt::ModifierType::Global, ktt::ModifierDimension::Y, "TILE_SIZE_Y", ktt::ModifierAction::Divide); auto wgSize = [](const std::vector<size_t>& v) {return v[0]*v[1] >= 32;}; tuner.addConstraint(kernelId, {"WORK_GROUP_SIZE_X", "WORK_GROUP_SIZE_Y"}, wgSize); // Assign reference and set error check tuner.setReferenceKernel(kernelId, referenceKernelId, std::vector<ktt::ParameterPair>{}, std::vector<ktt::ArgumentId>{dstId}); tuner.setValidationMethod(ktt::ValidationMethod::SideBySideComparison, 0.0001); // Perform tuning tuner.tuneKernel(kernelId); tuner.printResult(kernelId, std::cout, ktt::PrintFormat::Verbose); tuner.printResult(kernelId, "mtran_output.csv", ktt::PrintFormat::CSV); return 0; }
#include <iostream> #include <random> #include <string> #include <vector> #include "tuner_api.h" #define USE_CUDA 0 #define USE_PROFILING 0 #if USE_CUDA == 0 #if defined(_MSC_VER) #define KTT_KERNEL_FILE "../examples/mtran/mtran_kernel.cl" #define KTT_REFERENCE_KERNEL_FILE "../examples/mtran/mtran_reference_kernel.cl" #else #define KTT_KERNEL_FILE "../../examples/mtran/mtran_kernel.cl" #define KTT_REFERENCE_KERNEL_FILE "../../examples/mtran/mtran_reference_kernel.cl" #endif #else #if defined(_MSC_VER) #define KTT_KERNEL_FILE "../examples/mtran/mtran_kernel.cu" #define KTT_REFERENCE_KERNEL_FILE "../examples/mtran/mtran_reference_kernel.cu" #else #define KTT_KERNEL_FILE "../../examples/mtran/mtran_kernel.cu" #define KTT_REFERENCE_KERNEL_FILE "../../examples/mtran/mtran_reference_kernel.cu" #endif #endif int main(int argc, char **argv) { // Initialize platform index, device index and paths to kernels ktt::PlatformIndex platformIndex = 0; ktt::DeviceIndex deviceIndex = 0; std::string kernelFile = KTT_KERNEL_FILE; std::string referenceKernelFile = KTT_REFERENCE_KERNEL_FILE; if (argc >= 2) { platformIndex = std::stoul(std::string(argv[1])); if (argc >= 3) { deviceIndex = std::stoul(std::string(argv[2])); if (argc >= 4) { kernelFile = std::string(argv[3]); if (argc >= 5) { referenceKernelFile = std::string(argv[4]); } } } } // Declare kernel parameters #if USE_PROFILING == 0 const int width = 8192; const int height = 8192; #else const int width = 4096; const int height = 4096; #endif const ktt::DimensionVector ndRangeDimensions(width, height); const ktt::DimensionVector ndRangeDimensionsReference(width/16, height/16); const ktt::DimensionVector referenceWorkGroupDimensions(16, 16); // Declare data variables std::vector<float> dst(width * height); std::vector<float> src(width * height); // Initialize data std::random_device device; std::default_random_engine engine(device()); std::uniform_real_distribution<float> distribution(0.0f, 10.0f); for (int i = 0; i < width*height; i++) { src[i] = distribution(engine); } // Create tuner #if USE_CUDA == 0 ktt::Tuner tuner(platformIndex, deviceIndex); tuner.setGlobalSizeType(ktt::GlobalSizeType::CUDA); #else ktt::Tuner tuner(platformIndex, deviceIndex, ktt::ComputeAPI::CUDA); #if USE_PROFILING == 1 printf("Executing with profiling switched ON.\n"); tuner.setKernelProfiling(true); #endif #endif tuner.setPrintingTimeUnit(ktt::TimeUnit::Microseconds); // Create kernel and configure input/output ktt::KernelId kernelId = tuner.addKernelFromFile(kernelFile, "mtran", ndRangeDimensions, ktt::DimensionVector(1, 1)); ktt::KernelId referenceKernelId = tuner.addKernelFromFile(referenceKernelFile, "mtranReference", ndRangeDimensionsReference, referenceWorkGroupDimensions); ktt::ArgumentId srcId = tuner.addArgumentVector(src, ktt::ArgumentAccessType::ReadOnly); ktt::ArgumentId dstId = tuner.addArgumentVector(dst, ktt::ArgumentAccessType::WriteOnly); ktt::ArgumentId widthId = tuner.addArgumentScalar(width); ktt::ArgumentId heightId = tuner.addArgumentScalar(height); tuner.setKernelArguments(kernelId, std::vector<ktt::ArgumentId>{dstId, srcId, widthId, heightId}); tuner.setKernelArguments(referenceKernelId, std::vector<ktt::ArgumentId>{dstId, srcId, widthId, heightId}); // Create tuning space tuner.addParameter(kernelId, "LOCAL_MEM", { 0, 1 }); #if USE_CUDA == 0 tuner.addParameter(kernelId, "VECTOR_TYPE", { 1, 2, 4, 8 }); #else tuner.addParameter(kernelId, "VECTOR_TYPE", { 1, 2, 4 }); #endif tuner.addParameter(kernelId, "CR", { 0, 1 }); #if USE_CUDA == 0 tuner.addParameter(kernelId, "PREFETCH", { 0, 1, 2 }); #endif tuner.addParameter(kernelId, "PADD_LOCAL", { 0, 1 }); tuner.addParameter(kernelId, "WORK_GROUP_SIZE_X", { 1, 2, 4, 8, 16, 32, 64 }); tuner.addParameter(kernelId, "WORK_GROUP_SIZE_Y", { 1, 2, 4, 8, 16, 32, 64 }); tuner.addParameter(kernelId, "TILE_SIZE_X", { 1, 2, 4, 8, 16, 32, 64 }); tuner.addParameter(kernelId, "TILE_SIZE_Y", { 1, 2, 4, 8, 16, 32, 64 }); tuner.addParameter(kernelId, "DIAGONAL_MAP", {0, 1}); // Constraint tuning space auto xConstraint = [] (std::vector<size_t> v) { return (v[0] == v[1]); }; auto yConstraint = [] (std::vector<size_t> v) { return (v[1] <= v[0]); }; auto tConstraint = [] (std::vector<size_t> v) { return (!v[0] || (v[1] <= v[2]*v[3])); }; auto pConstraint = [] (std::vector<size_t> v) { return (v[0] || !v[1]); }; auto vConstraint = [] (std::vector<size_t> v) { return (v[0]*v[1] <= 64); }; auto vlConstraint = [] (std::vector<size_t> v) { return (!v[0] || v[1] == 1); }; auto minparConstraint = [] (std::vector<size_t> v) {return (v[0] * v[1] >= 32);}; tuner.addConstraint(kernelId, { "TILE_SIZE_X", "WORK_GROUP_SIZE_X" }, xConstraint); tuner.addConstraint(kernelId, { "TILE_SIZE_Y", "WORK_GROUP_SIZE_Y" }, yConstraint); tuner.addConstraint(kernelId, { "LOCAL_MEM", "TILE_SIZE_Y", "WORK_GROUP_SIZE_X", "WORK_GROUP_SIZE_Y" }, tConstraint); tuner.addConstraint(kernelId, { "LOCAL_MEM", "PADD_LOCAL" }, pConstraint); tuner.addConstraint(kernelId, { "TILE_SIZE_X", "VECTOR_TYPE" }, vConstraint); tuner.addConstraint(kernelId, { "LOCAL_MEM", "VECTOR_TYPE" }, vlConstraint); // tuner.addConstraint(kernelId, { "TILE_SIZE_X", "TILE_SIZE_Y" }, minparConstraint); // Configure parallelism tuner.setThreadModifier(kernelId, ktt::ModifierType::Local, ktt::ModifierDimension::X, "WORK_GROUP_SIZE_X", ktt::ModifierAction::Multiply); tuner.setThreadModifier(kernelId, ktt::ModifierType::Local, ktt::ModifierDimension::Y, "WORK_GROUP_SIZE_Y", ktt::ModifierAction::Multiply); auto xGlobalModifier = [](const size_t size, const std::vector<size_t>& vector) {return size / vector.at(0) / vector.at(1);}; tuner.setThreadModifier(kernelId, ktt::ModifierType::Global, ktt::ModifierDimension::X, std::vector<std::string>{ "TILE_SIZE_X", "VECTOR_TYPE" }, xGlobalModifier); tuner.setThreadModifier(kernelId, ktt::ModifierType::Global, ktt::ModifierDimension::Y, "TILE_SIZE_Y", ktt::ModifierAction::Divide); auto wgSize = [](const std::vector<size_t>& v) {return v[0]*v[1] >= 32;}; tuner.addConstraint(kernelId, {"WORK_GROUP_SIZE_X", "WORK_GROUP_SIZE_Y"}, wgSize); // Assign reference and set error check tuner.setReferenceKernel(kernelId, referenceKernelId, std::vector<ktt::ParameterPair>{}, std::vector<ktt::ArgumentId>{dstId}); tuner.setValidationMethod(ktt::ValidationMethod::SideBySideComparison, 0.0001); // Perform tuning tuner.tuneKernel(kernelId); tuner.printResult(kernelId, std::cout, ktt::PrintFormat::Verbose); tuner.printResult(kernelId, "mtran_output.csv", ktt::PrintFormat::CSV); return 0; }
use OpenCL by default in matrix transpose
use OpenCL by default in matrix transpose
C++
mit
Fillo7/KTT,Fillo7/KTT
b0b494ad7a7d244559289307d650b4acde0e3714
api/gossiper.cc
api/gossiper.cc
/* * Copyright 2015 Cloudius Systems */ #include "gossiper.hh" #include "api/api-doc/gossiper.json.hh" #include <gms/gossiper.hh> #include <vector> #include <sstream> namespace api { template<class T> std::vector<sstring> addr_to_vec(const T& container) { auto res = std::vector<sstring>(container.size()); for (auto i : container) { std::stringstream ss; ss << i; res.push_back(ss.str()); } return res; } void set_gossiper(http_context& ctx, routes& r) { httpd::gossiper_json::get_down_endpoint.set(r, [](std::unique_ptr<request> req) { return gms::get_unreachable_members().then([](std::set<gms::inet_address> res) { return make_ready_future<json::json_return_type>(addr_to_vec(res)); }); }); httpd::gossiper_json::get_live_endpoint.set(r, [](std::unique_ptr<request> req) { return gms::get_live_members().then([](std::set<gms::inet_address> res) { return make_ready_future<json::json_return_type>(addr_to_vec(res)); }); }); httpd::gossiper_json::get_endpoint_downtime.set(r, [](std::unique_ptr<request> req) { gms::inet_address ep(req->param.at("addr").substr(1)); return gms::get_endpoint_downtime(ep).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); httpd::gossiper_json::get_current_generation_number.set(r, [](std::unique_ptr<request> req) { gms::inet_address ep(req->param.at("addr").substr(1)); return gms::get_current_generation_number(ep).then([](int res) { return make_ready_future<json::json_return_type>(res); }); }); httpd::gossiper_json::assassinate_endpoint.set(r, [](std::unique_ptr<request> req) { if (req->get_query_param("unsafe") != "True") { return gms::assassinate_endpoint(req->param.at("addr").substr(1)).then([] { return make_ready_future<json::json_return_type>(""); }); } return gms::unsafe_assassinate_endpoint(req->param.at("addr").substr(1)).then([] { return make_ready_future<json::json_return_type>(""); }); }); } }
/* * Copyright 2015 Cloudius Systems */ #include "gossiper.hh" #include "api/api-doc/gossiper.json.hh" #include <gms/gossiper.hh> namespace api { void set_gossiper(http_context& ctx, routes& r) { httpd::gossiper_json::get_down_endpoint.set(r, [](std::unique_ptr<request> req) { return gms::get_unreachable_members().then([](std::set<gms::inet_address> res) { return make_ready_future<json::json_return_type>(container_to_vec(res)); }); }); httpd::gossiper_json::get_live_endpoint.set(r, [](std::unique_ptr<request> req) { return gms::get_live_members().then([](std::set<gms::inet_address> res) { return make_ready_future<json::json_return_type>(container_to_vec(res)); }); }); httpd::gossiper_json::get_endpoint_downtime.set(r, [](std::unique_ptr<request> req) { gms::inet_address ep(req->param["addr"]); return gms::get_endpoint_downtime(ep).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); httpd::gossiper_json::get_current_generation_number.set(r, [](std::unique_ptr<request> req) { gms::inet_address ep(req->param["addr"]); return gms::get_current_generation_number(ep).then([](int res) { return make_ready_future<json::json_return_type>(res); }); }); httpd::gossiper_json::assassinate_endpoint.set(r, [](std::unique_ptr<request> req) { if (req->get_query_param("unsafe") != "True") { return gms::assassinate_endpoint(req->param["addr"]).then([] { return make_ready_future<json::json_return_type>(""); }); } return gms::unsafe_assassinate_endpoint(req->param["addr"]).then([] { return make_ready_future<json::json_return_type>(""); }); }); } }
clean up the gossiper API impl
api: clean up the gossiper API impl This patch clean up the gossiper implementation by using the new square bracket operator for path param and by using the general function container_to_vec. Signed-off-by: Amnon Heiman <[email protected]> Reviewed-by: Pekka Enberg <[email protected]>
C++
agpl-3.0
dwdm/scylla,scylladb/scylla,justintung/scylla,shaunstanislaus/scylla,eklitzke/scylla,senseb/scylla,rluta/scylla,stamhe/scylla,guiquanz/scylla,respu/scylla,linearregression/scylla,victorbriz/scylla,victorbriz/scylla,kangkot/scylla,avikivity/scylla,eklitzke/scylla,guiquanz/scylla,rentongzhang/scylla,rluta/scylla,stamhe/scylla,scylladb/scylla,raphaelsc/scylla,rentongzhang/scylla,dwdm/scylla,gwicke/scylla,acbellini/scylla,raphaelsc/scylla,kangkot/scylla,kjniemi/scylla,kjniemi/scylla,wildinto/scylla,respu/scylla,rentongzhang/scylla,phonkee/scylla,tempbottle/scylla,rluta/scylla,aruanruan/scylla,glommer/scylla,capturePointer/scylla,gwicke/scylla,glommer/scylla,asias/scylla,justintung/scylla,shaunstanislaus/scylla,linearregression/scylla,senseb/scylla,glommer/scylla,tempbottle/scylla,capturePointer/scylla,eklitzke/scylla,scylladb/scylla,bowlofstew/scylla,aruanruan/scylla,duarten/scylla,phonkee/scylla,gwicke/scylla,kangkot/scylla,shaunstanislaus/scylla,wildinto/scylla,respu/scylla,phonkee/scylla,justintung/scylla,wildinto/scylla,kjniemi/scylla,asias/scylla,acbellini/scylla,scylladb/scylla,duarten/scylla,victorbriz/scylla,avikivity/scylla,bowlofstew/scylla,acbellini/scylla,dwdm/scylla,duarten/scylla,guiquanz/scylla,raphaelsc/scylla,tempbottle/scylla,senseb/scylla,aruanruan/scylla,asias/scylla,bowlofstew/scylla,stamhe/scylla,linearregression/scylla,avikivity/scylla,capturePointer/scylla
57d6248ca9b9874f390f73c608c847aa7400e01a
heaptrack_interpret.cpp
heaptrack_interpret.cpp
/* * Copyright 2014 Milian Wolff <[email protected]> * * This program 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file heaptrack_interpret.cpp * * @brief Interpret raw heaptrack data and add Dwarf based debug information. */ #include <iostream> #include <sstream> #include <unordered_map> #include <vector> #include <tuple> #include <algorithm> #include <cxxabi.h> #include <boost/algorithm/string/predicate.hpp> #include "libbacktrace/backtrace.h" #include "linereader.h" using namespace std; namespace { string demangle(const char* function) { if (!function) { return {}; } else if (function[0] != '_' || function[1] != 'Z') { return {function}; } string ret; int status = 0; char* demangled = abi::__cxa_demangle(function, 0, 0, &status); if (demangled) { ret = demangled; free(demangled); } return ret; } struct AddressInformation { string function; string file; int line = 0; }; struct Module { Module(string _fileName, uintptr_t addressStart, uintptr_t addressEnd, backtrace_state* backtraceState) : fileName(move(_fileName)) , addressStart(addressStart) , addressEnd(addressEnd) , backtraceState(backtraceState) { } AddressInformation resolveAddress(uintptr_t address) const { AddressInformation info; if (!backtraceState) { return info; } backtrace_pcinfo(backtraceState, address, [] (void *data, uintptr_t /*addr*/, const char *file, int line, const char *function) -> int { auto info = reinterpret_cast<AddressInformation*>(data); info->function = demangle(function); info->file = file ? file : ""; info->line = line; return 0; }, &emptyErrorCallback, &info); if (info.function.empty()) { backtrace_syminfo(backtraceState, address, [] (void *data, uintptr_t /*pc*/, const char *symname, uintptr_t /*symval*/, uintptr_t /*symsize*/) { if (symname) { reinterpret_cast<AddressInformation*>(data)->function = demangle(symname); } }, &errorCallback, &info); } return info; } static void errorCallback(void */*data*/, const char *msg, int errnum) { cerr << "Module backtrace error (code " << errnum << "): " << msg << endl; } static void emptyErrorCallback(void */*data*/, const char */*msg*/, int /*errnum*/) { } bool operator<(const Module& module) const { return make_tuple(addressStart, addressEnd, fileName) < make_tuple(module.addressStart, module.addressEnd, module.fileName); } bool operator!=(const Module& module) const { return make_tuple(addressStart, addressEnd, fileName) != make_tuple(module.addressStart, module.addressEnd, module.fileName); } backtrace_state* backtraceState; string fileName; uintptr_t addressStart; uintptr_t addressEnd; }; struct Allocation { // backtrace entry point size_t ipIndex; // number of allocations size_t allocations; // amount of bytes leaked size_t leaked; }; /** * Information for a single call to an allocation function */ struct AllocationInfo { size_t ipIndex; size_t size; }; struct ResolvedIP { size_t moduleIndex = 0; size_t fileIndex = 0; size_t functionIndex = 0; int line = 0; }; struct AccumulatedTraceData { AccumulatedTraceData() { m_modules.reserve(256); m_backtraceStates.reserve(64); m_internedData.reserve(4096); m_encounteredIps.reserve(32768); } ~AccumulatedTraceData() { cout << dec; cout << "# strings: " << m_internedData.size() << '\n'; cout << "# ips: " << m_encounteredIps.size() << '\n'; } ResolvedIP resolve(const uintptr_t ip) { if (m_modulesDirty) { // sort by addresses, required for binary search below sort(m_modules.begin(), m_modules.end()); for (size_t i = 0; i < m_modules.size(); ++i) { const auto& m1 = m_modules[i]; for (size_t j = i + 1; j < m_modules.size(); ++j) { if (i == j) { continue; } const auto& m2 = m_modules[j]; if ((m1.addressStart <= m2.addressStart && m1.addressEnd > m2.addressStart) || (m1.addressStart < m2.addressEnd && m1.addressEnd >= m2.addressEnd)) { cerr << "OVERLAPPING MODULES: " << hex << m1.fileName << " (" << m1.addressStart << " to " << m1.addressEnd << ") and " << m2.fileName << " (" << m2.addressStart << " to " << m2.addressEnd << ")\n" << dec; } else if (m2.addressStart >= m1.addressEnd) { break; } } } m_modulesDirty = false; } ResolvedIP data; // find module for this instruction pointer auto module = lower_bound(m_modules.begin(), m_modules.end(), ip, [] (const Module& module, const uintptr_t ip) -> bool { return module.addressEnd < ip; }); if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) { data.moduleIndex = intern(module->fileName); const auto info = module->resolveAddress(ip); data.fileIndex = intern(info.file); data.functionIndex = intern(info.function); data.line = info.line; } return data; } size_t intern(const string& str) { if (str.empty()) { return 0; } auto it = m_internedData.find(str); if (it != m_internedData.end()) { return it->second; } const size_t id = m_internedData.size() + 1; m_internedData.insert(it, make_pair(str, id)); cout << "s " << str << '\n'; return id; } void addModule(const string& fileName, const bool isExe, const uintptr_t addressStart, const uintptr_t addressEnd) { backtrace_state* backtraceState = findBacktraceState(fileName, addressStart, isExe); m_modules.emplace_back(fileName, addressStart, addressEnd, backtraceState); m_modulesDirty = true; } void clearModules() { // TODO: optimize this, reuse modules that are still valid m_modules.clear(); m_modulesDirty = true; } size_t addIp(const uintptr_t instructionPointer) { if (!instructionPointer) { return 0; } auto it = m_encounteredIps.find(instructionPointer); if (it != m_encounteredIps.end()) { return it->second; } const size_t ipId = m_encounteredIps.size() + 1; m_encounteredIps.insert(it, make_pair(instructionPointer, ipId)); const auto ip = resolve(instructionPointer); cout << "i " << instructionPointer << ' ' << ip.moduleIndex; if (ip.functionIndex || ip.fileIndex) { cout << ' ' << ip.functionIndex; if (ip.fileIndex) { cout << ' ' << ip.fileIndex << ' ' << ip.line; } } cout << '\n'; return ipId; } private: /** * Prevent the same file from being initialized multiple times. * This drastically cuts the memory consumption down */ backtrace_state* findBacktraceState(const string& fileName, uintptr_t addressStart, bool isExe) { if (boost::algorithm::starts_with(fileName, "linux-vdso.so")) { // prevent warning, since this will always fail return nullptr; } auto it = m_backtraceStates.find(fileName); if (it != m_backtraceStates.end()) { return it->second; } struct CallbackData { const string* fileName; }; CallbackData data = {&fileName}; auto state = backtrace_create_state(fileName.c_str(), /* we are single threaded, so: not thread safe */ false, [] (void *rawData, const char *msg, int errnum) { auto data = reinterpret_cast<const CallbackData*>(rawData); cerr << "Failed to create backtrace state for module " << *data->fileName << ": " << msg << " (error code " << errnum << ")" << endl; }, &data); if (state) { // when we could initialize the backtrace state, we initialize it with the first address // we get since that is the lowest one backtrace_fileline_initialize(state, addressStart, isExe, [] (void *rawData, const char *msg, int errnum) { auto data = reinterpret_cast<CallbackData*>(rawData); cerr << "Failed to initialize backtrace fileline for module " << *data->fileName << ": " << msg << " (error code " << errnum << ")" << endl; }, &data); } m_backtraceStates.insert(it, make_pair(fileName, state)); return state; } vector<Module> m_modules; unordered_map<string, backtrace_state*> m_backtraceStates; bool m_modulesDirty = false; unordered_map<string, size_t> m_internedData; unordered_map<uintptr_t, size_t> m_encounteredIps; }; } int main(int /*argc*/, char** /*argv*/) { // optimize: we only have a single thread ios_base::sync_with_stdio(false); AccumulatedTraceData data; LineReader reader; cin >> hex; cout << hex; while (reader.getLine(cin)) { if (reader.mode() == 'm') { string fileName; reader >> fileName; if (fileName == "-") { data.clearModules(); } else { bool isExe = false; uintptr_t addressStart = 0; uintptr_t addressEnd = 0; if (!(reader >> isExe) || !(reader >> addressStart) || !(reader >> addressEnd)) { cerr << "failed to parse line: " << reader.line() << endl; return 1; } data.addModule(fileName, isExe, addressStart, addressEnd); } } else if (reader.mode() == 't') { uintptr_t instructionPointer = 0; size_t parentIndex = 0; if (!(reader >> instructionPointer) || !(reader >> parentIndex)) { cerr << "failed to parse line: " << reader.line() << endl; return 1; } // ensure ip is encountered const auto ipId = data.addIp(instructionPointer); // trace point, map current output index to parent index cout << "t " << ipId << ' ' << parentIndex << '\n'; } else { cout << reader.line() << '\n'; } } return 0; }
/* * Copyright 2014 Milian Wolff <[email protected]> * * This program 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file heaptrack_interpret.cpp * * @brief Interpret raw heaptrack data and add Dwarf based debug information. */ #include <iostream> #include <sstream> #include <unordered_map> #include <vector> #include <tuple> #include <algorithm> #include <cxxabi.h> #include <boost/algorithm/string/predicate.hpp> #include "libbacktrace/backtrace.h" #include "linereader.h" using namespace std; namespace { string demangle(const char* function) { if (!function) { return {}; } else if (function[0] != '_' || function[1] != 'Z') { return {function}; } string ret; int status = 0; char* demangled = abi::__cxa_demangle(function, 0, 0, &status); if (demangled) { ret = demangled; free(demangled); } return ret; } struct AddressInformation { string function; string file; int line = 0; }; struct Module { Module(string _fileName, uintptr_t addressStart, uintptr_t addressEnd, backtrace_state* backtraceState) : fileName(move(_fileName)) , addressStart(addressStart) , addressEnd(addressEnd) , backtraceState(backtraceState) { } AddressInformation resolveAddress(uintptr_t address) const { AddressInformation info; if (!backtraceState) { return info; } backtrace_pcinfo(backtraceState, address, [] (void *data, uintptr_t /*addr*/, const char *file, int line, const char *function) -> int { auto info = reinterpret_cast<AddressInformation*>(data); info->function = demangle(function); info->file = file ? file : ""; info->line = line; return 0; }, &emptyErrorCallback, &info); if (info.function.empty()) { backtrace_syminfo(backtraceState, address, [] (void *data, uintptr_t /*pc*/, const char *symname, uintptr_t /*symval*/, uintptr_t /*symsize*/) { if (symname) { reinterpret_cast<AddressInformation*>(data)->function = demangle(symname); } }, &errorCallback, &info); } return info; } static void errorCallback(void */*data*/, const char *msg, int errnum) { cerr << "Module backtrace error (code " << errnum << "): " << msg << endl; } static void emptyErrorCallback(void */*data*/, const char */*msg*/, int /*errnum*/) { } bool operator<(const Module& module) const { return make_tuple(addressStart, addressEnd, fileName) < make_tuple(module.addressStart, module.addressEnd, module.fileName); } bool operator!=(const Module& module) const { return make_tuple(addressStart, addressEnd, fileName) != make_tuple(module.addressStart, module.addressEnd, module.fileName); } backtrace_state* backtraceState; string fileName; uintptr_t addressStart; uintptr_t addressEnd; }; struct Allocation { // backtrace entry point size_t ipIndex; // number of allocations size_t allocations; // amount of bytes leaked size_t leaked; }; /** * Information for a single call to an allocation function */ struct AllocationInfo { size_t ipIndex; size_t size; }; struct ResolvedIP { size_t moduleIndex = 0; size_t fileIndex = 0; size_t functionIndex = 0; int line = 0; }; struct AccumulatedTraceData { AccumulatedTraceData() { m_modules.reserve(256); m_backtraceStates.reserve(64); m_internedData.reserve(4096); m_encounteredIps.reserve(32768); } ~AccumulatedTraceData() { cout << dec; cout << "# strings: " << m_internedData.size() << '\n'; cout << "# ips: " << m_encounteredIps.size() << '\n'; } ResolvedIP resolve(const uintptr_t ip) { if (m_modulesDirty) { // sort by addresses, required for binary search below sort(m_modules.begin(), m_modules.end()); for (size_t i = 0; i < m_modules.size(); ++i) { const auto& m1 = m_modules[i]; for (size_t j = i + 1; j < m_modules.size(); ++j) { if (i == j) { continue; } const auto& m2 = m_modules[j]; if ((m1.addressStart <= m2.addressStart && m1.addressEnd > m2.addressStart) || (m1.addressStart < m2.addressEnd && m1.addressEnd >= m2.addressEnd)) { cerr << "OVERLAPPING MODULES: " << hex << m1.fileName << " (" << m1.addressStart << " to " << m1.addressEnd << ") and " << m2.fileName << " (" << m2.addressStart << " to " << m2.addressEnd << ")\n" << dec; } else if (m2.addressStart >= m1.addressEnd) { break; } } } m_modulesDirty = false; } ResolvedIP data; // find module for this instruction pointer auto module = lower_bound(m_modules.begin(), m_modules.end(), ip, [] (const Module& module, const uintptr_t ip) -> bool { return module.addressEnd < ip; }); if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) { data.moduleIndex = intern(module->fileName); const auto info = module->resolveAddress(ip); data.fileIndex = intern(info.file); data.functionIndex = intern(info.function); data.line = info.line; } return data; } size_t intern(const string& str) { if (str.empty()) { return 0; } auto it = m_internedData.find(str); if (it != m_internedData.end()) { return it->second; } const size_t id = m_internedData.size() + 1; m_internedData.insert(it, make_pair(str, id)); cout << "s " << str << '\n'; return id; } void addModule(const string& fileName, const bool isExe, const uintptr_t addressStart, const uintptr_t addressEnd) { backtrace_state* backtraceState = findBacktraceState(fileName, addressStart, isExe); m_modules.emplace_back(fileName, addressStart, addressEnd, backtraceState); m_modulesDirty = true; } void clearModules() { // TODO: optimize this, reuse modules that are still valid m_modules.clear(); m_modulesDirty = true; } size_t addIp(const uintptr_t instructionPointer) { if (!instructionPointer) { return 0; } auto it = m_encounteredIps.find(instructionPointer); if (it != m_encounteredIps.end()) { return it->second; } const size_t ipId = m_encounteredIps.size() + 1; m_encounteredIps.insert(it, make_pair(instructionPointer, ipId)); const auto ip = resolve(instructionPointer); cout << "i " << instructionPointer << ' ' << ip.moduleIndex; if (ip.functionIndex || ip.fileIndex) { cout << ' ' << ip.functionIndex; if (ip.fileIndex) { cout << ' ' << ip.fileIndex << ' ' << ip.line; } } cout << '\n'; return ipId; } private: /** * Prevent the same file from being initialized multiple times. * This drastically cuts the memory consumption down */ backtrace_state* findBacktraceState(const string& fileName, uintptr_t addressStart, bool isExe) { if (boost::algorithm::starts_with(fileName, "linux-vdso.so")) { // prevent warning, since this will always fail return nullptr; } auto it = m_backtraceStates.find(fileName); if (it != m_backtraceStates.end()) { return it->second; } struct CallbackData { const string* fileName; }; CallbackData data = {&fileName}; auto errorHandler = [] (void *rawData, const char *msg, int errnum) { auto data = reinterpret_cast<const CallbackData*>(rawData); cerr << "Failed to create backtrace state for module " << *data->fileName << ": " << msg << " (error code " << errnum << ")" << endl; }; auto state = backtrace_create_state(fileName.c_str(), /* we are single threaded, so: not thread safe */ false, errorHandler, &data); if (state) { // when we could initialize the backtrace state, we initialize it with the first address // we get since that is the lowest one backtrace_fileline_initialize(state, addressStart, isExe, errorHandler, &data); } m_backtraceStates.insert(it, make_pair(fileName, state)); return state; } vector<Module> m_modules; unordered_map<string, backtrace_state*> m_backtraceStates; bool m_modulesDirty = false; unordered_map<string, size_t> m_internedData; unordered_map<uintptr_t, size_t> m_encounteredIps; }; } int main(int /*argc*/, char** /*argv*/) { // optimize: we only have a single thread ios_base::sync_with_stdio(false); AccumulatedTraceData data; LineReader reader; cin >> hex; cout << hex; while (reader.getLine(cin)) { if (reader.mode() == 'm') { string fileName; reader >> fileName; if (fileName == "-") { data.clearModules(); } else { bool isExe = false; uintptr_t addressStart = 0; uintptr_t addressEnd = 0; if (!(reader >> isExe) || !(reader >> addressStart) || !(reader >> addressEnd)) { cerr << "failed to parse line: " << reader.line() << endl; return 1; } data.addModule(fileName, isExe, addressStart, addressEnd); } } else if (reader.mode() == 't') { uintptr_t instructionPointer = 0; size_t parentIndex = 0; if (!(reader >> instructionPointer) || !(reader >> parentIndex)) { cerr << "failed to parse line: " << reader.line() << endl; return 1; } // ensure ip is encountered const auto ipId = data.addIp(instructionPointer); // trace point, map current output index to parent index cout << "t " << ipId << ' ' << parentIndex << '\n'; } else { cout << reader.line() << '\n'; } } return 0; }
Use the same error handler for both init error callbacks.
Use the same error handler for both init error callbacks. This happens rarely, and the error message is still helpful.
C++
lgpl-2.1
muojp/heaptrack,muojp/heaptrack,stormspirit/heaptrack,stormspirit/heaptrack,muojp/heaptrack,muojp/heaptrack,muojp/heaptrack,stormspirit/heaptrack
ca05dedc9bd5fbf636ea218e8238637a29a1f701
src/AssimpWorker/worker/Worker.cpp
src/AssimpWorker/worker/Worker.cpp
/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ #include <iostream> #include <fstream> #include <Poco/Net/NetException.h> #include <Poco/TemporaryFile.h> #include <boost/filesystem.hpp> #include "../import/AssimpImporter.hpp" #include "../import/AiImporter/AiSceneImporter.hpp" #include "../import/AMLImporter/AMLImporter.hpp" #include <atlas/model/Asset.hpp> #include "../internal/configuration.hpp" #include "../connection/FeedbackProducer.hpp" #include "Worker.hpp" #include "../internal/Exception.hpp" namespace AssimpWorker { using ATLAS::Model::Asset; Worker::Worker() : storageService(), currentWorkUnit(NULL) { return; } Worker::~Worker() { return; } void Worker::import(WorkUnit& workUnit) { try { currentWorkUnit = &workUnit; time(&currentWorkUnit->startTime); sendFeedback("processing"); if (currentWorkUnit->fileType == "zip") { std::cout << "File is a zip, decompressing..." << std::endl; importZipFile(); } else if (currentWorkUnit->fileType == "dae") { std::cout << "File is a Collada file, importing..." << std::endl; importSingleColladaFile(); } currentWorkUnit->detail = log.getAllErrors(); std::cout << currentWorkUnit->detail << std::endl; time(&currentWorkUnit->endTime); if (currentWorkUnit->resultPath.empty()) { sendFeedback("failed"); } else { sendFeedback("complete"); } } catch (const Poco::Net::ConnectionRefusedException& ex) { std::cerr << "Error connecting to the ATLAS server: " << ex.displayText() << std::endl << std::endl; } catch (const std::exception& e) { std::cerr << "Error during import operation: " << e.what() << std::endl << std::endl; } catch (...) { std::cerr << "Unknown error during import operation." << std::endl << std::endl; } } void Worker::importSingleColladaFile() { std::istream& response = storageService.retrieveFile(currentWorkUnit->sourcePath); // Patches welcome... Poco::TemporaryFile tmp; std::ofstream ostr; ostr.open(tmp.path().c_str()); std::streamsize n; char buffer[1024] = { 0x0 }; response.read(buffer, 1024); while ((n = response.gcount()) != 0) { ostr.write(buffer, n); if (n) { response.read(buffer, 1024); } } ostr.close(); currentWorkUnit->resultPath = importColladaAndStore(tmp.path()); } void Worker::importZipFile() { Configuration& config = Configuration::getInstance(); std::string decompressionPath = config.get("decompression-path").as<std::string>(); AssimpWorker::ZipFileExtractor decompressor(decompressionPath); decompressZipFile(currentWorkUnit->sourcePath, decompressor); std::cout << "Decompression complete, beginning import..." << std::endl; currentWorkUnit->resultPath = importAssetFromDecompressedZip(decompressionPath); boost::filesystem::remove_all(decompressionPath); } void Worker::decompressZipFile(const std::string& zipId, AssimpWorker::ZipFileExtractor& decompressor) { std::istream& response = storageService.retrieveFile(zipId); decompressor.decompressArchive(response); } std::string Worker::importColladaAndStore(const std::string& filesystemPathToColladaFile) { std::cout << "importColladaAndStore, filesystemPathToColladaFile: " << filesystemPathToColladaFile << std::endl; std::string pathToFolder = filesystemPathToColladaFile.substr(0, filesystemPathToColladaFile.find_last_of('/') + 1); Poco::URI& uri = Poco::URI(filesystemPathToColladaFile); AssimpWorker::ColladaImporter importer = AssimpWorker::ColladaImporter(uri, log, pathToFolder); Asset asset; importer.addElementsTo(asset); return storeAsset(asset); } std::string Worker::storeAsset(Asset& asset) { asset.setName(currentWorkUnit->assetName); std::cout << "Conversion done, storing..." << std::endl; std::string revisionHash = storageService.storeAssetRevision(currentWorkUnit->assetName, asset); std::string relativePathToAsset = currentWorkUnit->assetName + "/" + revisionHash; std::cout << "Saved asset to path " << relativePathToAsset << std::endl; return relativePathToAsset; } std::string Worker::importAutomationMLAndStore(const std::string& filesystemPathToAMLFile) { try { AMLImporter amlImporter(filesystemPathToAMLFile, log); Asset asset; amlImporter.addElementsTo(asset); return storeAsset(asset); } catch (const Exception& e) { log.error("Error while processing the AML: " + e.getMessage()); return ""; } } std::string Worker::importAssetFromDecompressedZip(const std::string& path){ boost::filesystem::directory_iterator end; boost::filesystem::directory_iterator it(path); std::string daePath = ""; for (; it != end; ++it) { std::string extension = boost::filesystem::extension(*it); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); // Any AML file should take priority over Collada files, so we delay Collada importing until all extensions are checked if (extension == ".dae" && daePath == "") { daePath = it->path().generic_string(); } if (extension == ".aml") { return importAutomationMLAndStore(it->path().generic_string()); } } if (daePath != "") { return importColladaAndStore(daePath); } log.error("Could not find a supported file type to convert. Make sure the format you are trying to import is supported by ATLAS. Also, remember: Folders are not supported by ATLAS, make sure the file to be imported is within the toplevel of the zip-file."); return ""; } void Worker::sendFeedback(const std::string& message) { //Producer connection is created on demand to avoid having to heartbeat it FeedbackProducer producer; producer.sendWorkFeedbackMessage(*currentWorkUnit, message); } }
/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ #include <iostream> #include <fstream> #include <Poco/Net/NetException.h> #include <Poco/TemporaryFile.h> #include <boost/filesystem.hpp> #include "../import/AssimpImporter.hpp" #include "../import/AiImporter/AiSceneImporter.hpp" #include "../import/AMLImporter/AMLImporter.hpp" #include <atlas/model/Asset.hpp> #include "../internal/configuration.hpp" #include "../connection/FeedbackProducer.hpp" #include "Worker.hpp" #include "../internal/Exception.hpp" namespace AssimpWorker { using ATLAS::Model::Asset; Worker::Worker() : storageService(), currentWorkUnit(NULL) { return; } Worker::~Worker() { return; } void Worker::import(WorkUnit& workUnit) { try { currentWorkUnit = &workUnit; time(&currentWorkUnit->startTime); sendFeedback("processing"); if (currentWorkUnit->fileType == "zip") { std::cout << "File is a zip, decompressing..." << std::endl; importZipFile(); } else if (currentWorkUnit->fileType == "dae") { std::cout << "File is a Collada file, importing..." << std::endl; importSingleColladaFile(); } currentWorkUnit->detail = log.getAllErrors(); std::cout << currentWorkUnit->detail << std::endl; time(&currentWorkUnit->endTime); if (currentWorkUnit->resultPath.empty()) { sendFeedback("failed"); } else { sendFeedback("complete"); } } catch (const Poco::Net::ConnectionRefusedException& ex) { std::cerr << "Error connecting to the ATLAS server: " << ex.displayText() << std::endl << std::endl; } catch (const std::exception& e) { std::cerr << "Error during import operation: " << e.what() << std::endl << std::endl; } catch (...) { std::cerr << "Unknown error during import operation." << std::endl << std::endl; } } void Worker::importSingleColladaFile() { std::istream& response = storageService.retrieveFile(currentWorkUnit->sourcePath); // Patches welcome... std::string decompressionPath = Configuration::getInstance().get("decompression-path").as<std::string>(); Poco::TemporaryFile tmp(decompressionPath); std::ofstream ostr; ostr.open(tmp.path().c_str()); std::streamsize n; char buffer[1024] = { 0x0 }; response.read(buffer, 1024); while ((n = response.gcount()) != 0) { ostr.write(buffer, n); if (n) { response.read(buffer, 1024); } } ostr.close(); currentWorkUnit->resultPath = importColladaAndStore(tmp.path()); } void Worker::importZipFile() { Configuration& config = Configuration::getInstance(); std::string decompressionPath = config.get("decompression-path").as<std::string>(); AssimpWorker::ZipFileExtractor decompressor(decompressionPath); decompressZipFile(currentWorkUnit->sourcePath, decompressor); std::cout << "Decompression complete, beginning import..." << std::endl; currentWorkUnit->resultPath = importAssetFromDecompressedZip(decompressionPath); boost::filesystem::remove_all(decompressionPath); } void Worker::decompressZipFile(const std::string& zipId, AssimpWorker::ZipFileExtractor& decompressor) { std::istream& response = storageService.retrieveFile(zipId); decompressor.decompressArchive(response); } std::string Worker::importColladaAndStore(const std::string& filesystemPathToColladaFile) { std::cout << "importColladaAndStore, filesystemPathToColladaFile: " << filesystemPathToColladaFile << std::endl; std::string pathToFolder = filesystemPathToColladaFile.substr(0, filesystemPathToColladaFile.find_last_of('/') + 1); Poco::URI& uri = Poco::URI(filesystemPathToColladaFile); AssimpWorker::ColladaImporter importer = AssimpWorker::ColladaImporter(uri, log, pathToFolder); Asset asset; importer.addElementsTo(asset); return storeAsset(asset); } std::string Worker::storeAsset(Asset& asset) { asset.setName(currentWorkUnit->assetName); std::cout << "Conversion done, storing..." << std::endl; std::string revisionHash = storageService.storeAssetRevision(currentWorkUnit->assetName, asset); std::string relativePathToAsset = currentWorkUnit->assetName + "/" + revisionHash; std::cout << "Saved asset to path " << relativePathToAsset << std::endl; return relativePathToAsset; } std::string Worker::importAutomationMLAndStore(const std::string& filesystemPathToAMLFile) { try { AMLImporter amlImporter(filesystemPathToAMLFile, log); Asset asset; amlImporter.addElementsTo(asset); return storeAsset(asset); } catch (const Exception& e) { log.error("Error while processing the AML: " + e.getMessage()); return ""; } } std::string Worker::importAssetFromDecompressedZip(const std::string& path){ boost::filesystem::directory_iterator end; boost::filesystem::directory_iterator it(path); std::string daePath = ""; for (; it != end; ++it) { std::string extension = boost::filesystem::extension(*it); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); // Any AML file should take priority over Collada files, so we delay Collada importing until all extensions are checked if (extension == ".dae" && daePath == "") { daePath = it->path().generic_string(); } if (extension == ".aml") { return importAutomationMLAndStore(it->path().generic_string()); } } if (daePath != "") { return importColladaAndStore(daePath); } log.error("Could not find a supported file type to convert. Make sure the format you are trying to import is supported by ATLAS. Also, remember: Folders are not supported by ATLAS, make sure the file to be imported is within the toplevel of the zip-file."); return ""; } void Worker::sendFeedback(const std::string& message) { //Producer connection is created on demand to avoid having to heartbeat it FeedbackProducer producer; producer.sendWorkFeedbackMessage(*currentWorkUnit, message); } }
Use the decompression path to place temporary files
Use the decompression path to place temporary files
C++
apache-2.0
dfki-asr/atlas-worker,dfki-asr/atlas-worker
139fc1795bf3ddc8717eb2b26182526daa89911e
Cutelyst/headers.cpp
Cutelyst/headers.cpp
/* * Copyright (C) 2014-2016 Daniel Nicoletti <[email protected]> * * 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; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "headers_p.h" #include "common.h" #include <QStringList> using namespace Cutelyst; Headers::Headers() { } QString Headers::contentEncoding() const { return m_data.value(QStringLiteral("content_encoding")); } void Headers::setContentEncoding(const QString &encoding) { m_data.insert(QStringLiteral("content_encoding"), encoding); } QString Headers::contentType() const { const auto it = m_data.constFind(QStringLiteral("content_type")); if (it == m_data.constEnd()) { return QString(); } const QString ct = it.value(); return ct.mid(0, ct.indexOf(QLatin1Char(';'))).toLower(); } void Headers::setContentType(const QString &contentType) { m_data.insert(QStringLiteral("content_type"), contentType); } QString Headers::contentTypeCharset() const { const auto it = m_data.constFind(QStringLiteral("content_type")); if (it == m_data.constEnd()) { return QString(); } const QString contentType = it.value(); int pos = contentType.indexOf(QLatin1String("charset="), 0, Qt::CaseInsensitive); if (pos != -1) { int endPos = contentType.indexOf(QLatin1Char(';'), pos); return contentType.mid(pos + 8, endPos).trimmed().toUpper(); } return QString(); } void Headers::setContentTypeCharset(const QString &charset) { const auto it = m_data.constFind(QStringLiteral("content_type")); if (it == m_data.constEnd() || (it.value().isEmpty() && !charset.isEmpty())) { m_data.insert(QStringLiteral("content_type"), QLatin1String("charset=") + charset); return; } QString contentType = it.value(); int pos = contentType.indexOf(QLatin1String("charset="), 0, Qt::CaseInsensitive); if (pos != -1) { int endPos = contentType.indexOf(QLatin1Char(';'), pos); if (endPos == -1) { if (charset.isEmpty()) { int lastPos = contentType.lastIndexOf(QLatin1Char(';'), pos); if (lastPos == -1) { m_data.remove(QStringLiteral("content_type")); return; } else { contentType.remove(lastPos, contentType.length() - lastPos); } } else { contentType.replace(pos + 8, contentType.length() - pos + 8, charset); } } else { contentType.replace(pos + 8, endPos, charset); } } else if (!charset.isEmpty()) { contentType.append(QLatin1String("; charset=") + charset); } m_data.insert(QStringLiteral("content_type"), contentType); } bool Headers::contentIsText() const { return m_data.value(QStringLiteral("content_type")).startsWith(QLatin1String("text/")); } bool Headers::contentIsHtml() const { const QString ct = contentType(); return ct == QLatin1String("text/html") || ct == QLatin1String("application/xhtml+xml") || ct == QLatin1String("application/vnd.wap.xhtml+xml"); } bool Headers::contentIsXHtml() const { const QString ct = contentType(); return ct == QLatin1String("application/xhtml+xml") || ct == QLatin1String("application/vnd.wap.xhtml+xml"); } bool Headers::contentIsXml() const { const QString ct = contentType(); return ct == QLatin1String("text/xml") || ct == QLatin1String("application/xml") || ct.endsWith(QLatin1String("xml")); } qint64 Headers::contentLength() const { return m_data.value(QStringLiteral("content_length")).toLongLong(); } void Headers::setContentLength(qint64 value) { m_data.insert(QStringLiteral("content_length"), QString::number(value)); } QString Headers::setDateWithDateTime(const QDateTime &date) { // ALL dates must be in GMT timezone http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html // and follow RFC 822 const QString dt = QLocale::c().toString(date.toUTC(), QStringLiteral("ddd, dd MMM yyyy hh:mm:ss 'GMT")); m_data.insert(QStringLiteral("date"), dt); return dt; } QDateTime Headers::date() { auto it = m_data.constFind(QStringLiteral("date")); if (it == m_data.constEnd()) { return QDateTime(); } const QString date = it.value(); QDateTime localDT; if (date.endsWith(QLatin1String(" GMT"))) { localDT = QLocale::c().toDateTime(date.left(date.size() - 4), QStringLiteral("ddd, dd MMM yyyy hh:mm:ss")); } else { localDT = QLocale::c().toDateTime(date, QStringLiteral("ddd, dd MMM yyyy hh:mm:ss")); } return QDateTime(localDT.date(), localDT.time(), Qt::UTC); } QString Headers::ifModifiedSince() const { return header(QStringLiteral("if_modified_since")); } QDateTime Headers::ifModifiedSinceDateTime() const { auto it = m_data.constFind(QStringLiteral("if_modified_since")); if (it == m_data.constEnd()) { return QDateTime(); } const QString ifModifiedStr = it.value(); QDateTime localDT; if (ifModifiedStr.endsWith(QLatin1String(" GMT"))) { localDT = QLocale::c().toDateTime(ifModifiedStr.left(ifModifiedStr.size() - 4), QStringLiteral("ddd, dd MMM yyyy hh:mm:ss")); } else { localDT = QLocale::c().toDateTime(ifModifiedStr, QStringLiteral("ddd, dd MMM yyyy hh:mm:ss")); } return QDateTime(localDT.date(), localDT.time(), Qt::UTC); } QString Headers::lastModified() const { return m_data.value(QStringLiteral("last_modified")); } void Headers::setLastModified(const QString &value) { m_data.insert(QStringLiteral("last_modified"), value); } QString Headers::setLastModified(const QDateTime &lastModified) { // ALL dates must be in GMT timezone http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html // and follow RFC 822 const auto dt = QLocale::c().toString(lastModified.toUTC(), QStringLiteral("ddd, dd MMM yyyy hh:mm:ss 'GMT")); setLastModified(dt); return dt; } QString Headers::server() const { return m_data.value(QStringLiteral("server")); } void Headers::setServer(const QString &value) { m_data.insert(QStringLiteral("server"), value); } QString Headers::userAgent() const { return m_data.value(QStringLiteral("user_agent")); } QString Headers::referer() const { return m_data.value(QStringLiteral("referer")); } void Headers::setReferer(const QString &uri) { int fragmentPos = uri.indexOf(QLatin1Char('#')); if (fragmentPos != -1) { // Strip fragment per RFC 2616, section 14.36. m_data.insert(QStringLiteral("referer"), uri.mid(0, fragmentPos)); } else { m_data.insert(QStringLiteral("referer"), uri); } } void Headers::setWwwAuthenticate(const QString &value) { m_data.insert(QStringLiteral("www_authenticate"), value); } void Headers::setProxyAuthenticate(const QString &value) { m_data.insert(QStringLiteral("proxy_authenticate"), value); } QString Headers::authorization() const { return m_data.value(QStringLiteral("authorization")); } QString Headers::authorizationBasic() const { return QString::fromLatin1(HeadersPrivate::decodeBasicAuth(authorization())); } QPair<QString, QString> Headers::authorizationBasicPair() const { return HeadersPrivate::decodeBasicAuthPair(authorization()); } QString Headers::setAuthorizationBasic(const QString &username, const QString &password) { if (username.contains(QLatin1Char(':'))) { qCWarning(CUTELYST_CORE) << "Headers::Basic authorization user name can't contain ':'"; return QString(); } const QString result = username + QLatin1Char(':') + password; const QString value = QStringLiteral("Basic ") + QString::fromLatin1(result.toLatin1().toBase64()); m_data.insert(QStringLiteral("authorization"), value); return value; } QString Headers::proxyAuthorization() const { return m_data.value(QStringLiteral("proxy_authorization")); } QString Headers::proxyAuthorizationBasic() const { return QString::fromLatin1(HeadersPrivate::decodeBasicAuth(proxyAuthorization())); } QPair<QString, QString> Headers::proxyAuthorizationBasicPair() const { return HeadersPrivate::decodeBasicAuthPair(proxyAuthorization()); } QString Headers::header(const QString &field) const { return m_data.value(HeadersPrivate::normalizeHeaderKey(field)); } QString Headers::header(const QString &field, const QString &defaultValue) const { return m_data.value(HeadersPrivate::normalizeHeaderKey(field), defaultValue); } void Headers::setHeader(const QString &field, const QString &value) { m_data.insert(HeadersPrivate::normalizeHeaderKey(field), value); } void Headers::setHeader(const QString &field, const QStringList &values) { setHeader(field, values.join(QStringLiteral(", "))); } void Headers::pushHeader(const QString &field, const QString &value) { const QString key = HeadersPrivate::normalizeHeaderKey(field); const QString old = Headers::header(key); if (old.isEmpty()) { m_data.insert(key, value); } else { m_data.insert(key, old + QLatin1String(", ") + value); } } void Headers::pushHeader(const QString &field, const QStringList &values) { pushHeader(field, values.join(QStringLiteral(", "))); } void Headers::removeHeader(const QString &field) { m_data.remove(HeadersPrivate::normalizeHeaderKey(field)); } bool Headers::contains(const QString &field) { return m_data.contains(HeadersPrivate::normalizeHeaderKey(field)); } QString &Headers::operator[](const QString &key) { return m_data[key]; } const QString Headers::operator[](const QString &key) const { return m_data[key]; } QString HeadersPrivate::normalizeHeaderKey(const QString &field) { QString key = field; int i = 0; while (i < key.size()) { QCharRef c = key[i]; if (c.isSpace()) { key.remove(i, 1); continue; } else if (c == QLatin1Char('-')) { c = QLatin1Char('_'); } else { c = c.toLower(); } ++i; } return key; } QByteArray HeadersPrivate::decodeBasicAuth(const QString &auth) { if (!auth.isEmpty() && auth.startsWith(QLatin1String("Basic "))) { int pos = auth.lastIndexOf(QLatin1Char(' ')); if (pos != -1) { return QByteArray::fromBase64(auth.mid(pos).toLatin1()); } } return QByteArray(); } QPair<QString, QString> HeadersPrivate::decodeBasicAuthPair(const QString &auth) { const QByteArray authorization = decodeBasicAuth(auth); if (!authorization.isEmpty()) { int pos = authorization.indexOf(':'); if (pos == -1) { return qMakePair(QString::fromLatin1(authorization), QString()); } else { return qMakePair(QString::fromLatin1(authorization.left(pos)), QString::fromLatin1(authorization.mid(pos + 1))); } } return qMakePair(QString(), QString()); }
/* * Copyright (C) 2014-2016 Daniel Nicoletti <[email protected]> * * 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; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "headers_p.h" #include "common.h" #include <QStringList> using namespace Cutelyst; Headers::Headers() { } QString Headers::contentEncoding() const { return m_data.value(QStringLiteral("content_encoding")); } void Headers::setContentEncoding(const QString &encoding) { m_data.insert(QStringLiteral("content_encoding"), encoding); } QString Headers::contentType() const { const auto it = m_data.constFind(QStringLiteral("content_type")); if (it == m_data.constEnd()) { return QString(); } const QString ct = it.value(); return ct.mid(0, ct.indexOf(QLatin1Char(';'))).toLower(); } void Headers::setContentType(const QString &contentType) { m_data.insert(QStringLiteral("content_type"), contentType); } QString Headers::contentTypeCharset() const { const auto it = m_data.constFind(QStringLiteral("content_type")); if (it == m_data.constEnd()) { return QString(); } const QString contentType = it.value(); int pos = contentType.indexOf(QLatin1String("charset="), 0, Qt::CaseInsensitive); if (pos != -1) { int endPos = contentType.indexOf(QLatin1Char(';'), pos); return contentType.mid(pos + 8, endPos).trimmed().toUpper(); } return QString(); } void Headers::setContentTypeCharset(const QString &charset) { const auto it = m_data.constFind(QStringLiteral("content_type")); if (it == m_data.constEnd() || (it.value().isEmpty() && !charset.isEmpty())) { m_data.insert(QStringLiteral("content_type"), QLatin1String("charset=") + charset); return; } QString contentType = it.value(); int pos = contentType.indexOf(QLatin1String("charset="), 0, Qt::CaseInsensitive); if (pos != -1) { int endPos = contentType.indexOf(QLatin1Char(';'), pos); if (endPos == -1) { if (charset.isEmpty()) { int lastPos = contentType.lastIndexOf(QLatin1Char(';'), pos); if (lastPos == -1) { m_data.remove(QStringLiteral("content_type")); return; } else { contentType.remove(lastPos, contentType.length() - lastPos); } } else { contentType.replace(pos + 8, contentType.length() - pos + 8, charset); } } else { contentType.replace(pos + 8, endPos, charset); } } else if (!charset.isEmpty()) { contentType.append(QLatin1String("; charset=") + charset); } m_data.insert(QStringLiteral("content_type"), contentType); } bool Headers::contentIsText() const { return m_data.value(QStringLiteral("content_type")).startsWith(QLatin1String("text/")); } bool Headers::contentIsHtml() const { const QString ct = contentType(); return ct == QLatin1String("text/html") || ct == QLatin1String("application/xhtml+xml") || ct == QLatin1String("application/vnd.wap.xhtml+xml"); } bool Headers::contentIsXHtml() const { const QString ct = contentType(); return ct == QLatin1String("application/xhtml+xml") || ct == QLatin1String("application/vnd.wap.xhtml+xml"); } bool Headers::contentIsXml() const { const QString ct = contentType(); return ct == QLatin1String("text/xml") || ct == QLatin1String("application/xml") || ct.endsWith(QLatin1String("xml")); } qint64 Headers::contentLength() const { return m_data.value(QStringLiteral("content_length")).toLongLong(); } void Headers::setContentLength(qint64 value) { m_data.insert(QStringLiteral("content_length"), QString::number(value)); } QString Headers::setDateWithDateTime(const QDateTime &date) { // ALL dates must be in GMT timezone http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html // and follow RFC 822 const QString dt = QLocale::c().toString(date.toUTC(), QStringLiteral("ddd, dd MMM yyyy hh:mm:ss 'GMT")); m_data.insert(QStringLiteral("date"), dt); return dt; } QDateTime Headers::date() { auto it = m_data.constFind(QStringLiteral("date")); if (it == m_data.constEnd()) { return QDateTime(); } const QString date = it.value(); QDateTime localDT; if (date.endsWith(QLatin1String(" GMT"))) { localDT = QLocale::c().toDateTime(date.left(date.size() - 4), QStringLiteral("ddd, dd MMM yyyy hh:mm:ss")); } else { localDT = QLocale::c().toDateTime(date, QStringLiteral("ddd, dd MMM yyyy hh:mm:ss")); } return QDateTime(localDT.date(), localDT.time(), Qt::UTC); } QString Headers::ifModifiedSince() const { return header(QStringLiteral("if_modified_since")); } QDateTime Headers::ifModifiedSinceDateTime() const { auto it = m_data.constFind(QStringLiteral("if_modified_since")); if (it == m_data.constEnd()) { return QDateTime(); } const QString ifModifiedStr = it.value(); QDateTime localDT; if (ifModifiedStr.endsWith(QLatin1String(" GMT"))) { localDT = QLocale::c().toDateTime(ifModifiedStr.left(ifModifiedStr.size() - 4), QStringLiteral("ddd, dd MMM yyyy hh:mm:ss")); } else { localDT = QLocale::c().toDateTime(ifModifiedStr, QStringLiteral("ddd, dd MMM yyyy hh:mm:ss")); } return QDateTime(localDT.date(), localDT.time(), Qt::UTC); } QString Headers::lastModified() const { return m_data.value(QStringLiteral("last_modified")); } void Headers::setLastModified(const QString &value) { m_data.insert(QStringLiteral("last_modified"), value); } QString Headers::setLastModified(const QDateTime &lastModified) { // ALL dates must be in GMT timezone http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html // and follow RFC 822 const auto dt = QLocale::c().toString(lastModified.toUTC(), QStringLiteral("ddd, dd MMM yyyy hh:mm:ss 'GMT")); setLastModified(dt); return dt; } QString Headers::server() const { return m_data.value(QStringLiteral("server")); } void Headers::setServer(const QString &value) { m_data.insert(QStringLiteral("server"), value); } QString Headers::userAgent() const { return m_data.value(QStringLiteral("user_agent")); } QString Headers::referer() const { return m_data.value(QStringLiteral("referer")); } void Headers::setReferer(const QString &uri) { int fragmentPos = uri.indexOf(QLatin1Char('#')); if (fragmentPos != -1) { // Strip fragment per RFC 2616, section 14.36. m_data.insert(QStringLiteral("referer"), uri.mid(0, fragmentPos)); } else { m_data.insert(QStringLiteral("referer"), uri); } } void Headers::setWwwAuthenticate(const QString &value) { m_data.insert(QStringLiteral("www_authenticate"), value); } void Headers::setProxyAuthenticate(const QString &value) { m_data.insert(QStringLiteral("proxy_authenticate"), value); } QString Headers::authorization() const { return m_data.value(QStringLiteral("authorization")); } QString Headers::authorizationBasic() const { return QString::fromLatin1(HeadersPrivate::decodeBasicAuth(authorization())); } QPair<QString, QString> Headers::authorizationBasicPair() const { return HeadersPrivate::decodeBasicAuthPair(authorization()); } QString Headers::setAuthorizationBasic(const QString &username, const QString &password) { if (username.contains(QLatin1Char(':'))) { qCWarning(CUTELYST_CORE) << "Headers::Basic authorization user name can't contain ':'"; return QString(); } const QString result = username + QLatin1Char(':') + password; const QString value = QStringLiteral("Basic ") + QString::fromLatin1(result.toLatin1().toBase64()); m_data.insert(QStringLiteral("authorization"), value); return value; } QString Headers::proxyAuthorization() const { return m_data.value(QStringLiteral("proxy_authorization")); } QString Headers::proxyAuthorizationBasic() const { return QString::fromLatin1(HeadersPrivate::decodeBasicAuth(proxyAuthorization())); } QPair<QString, QString> Headers::proxyAuthorizationBasicPair() const { return HeadersPrivate::decodeBasicAuthPair(proxyAuthorization()); } QString Headers::header(const QString &field) const { return m_data.value(HeadersPrivate::normalizeHeaderKey(field)); } QString Headers::header(const QString &field, const QString &defaultValue) const { return m_data.value(HeadersPrivate::normalizeHeaderKey(field), defaultValue); } void Headers::setHeader(const QString &field, const QString &value) { m_data.insert(HeadersPrivate::normalizeHeaderKey(field), value); } void Headers::setHeader(const QString &field, const QStringList &values) { setHeader(field, values.join(QStringLiteral(", "))); } void Headers::pushHeader(const QString &field, const QString &value) { m_data.insertMulti(HeadersPrivate::normalizeHeaderKey(field), value); } void Headers::pushHeader(const QString &field, const QStringList &values) { m_data.insertMulti(HeadersPrivate::normalizeHeaderKey(field), values.join(QStringLiteral(", "))); } void Headers::removeHeader(const QString &field) { m_data.remove(HeadersPrivate::normalizeHeaderKey(field)); } bool Headers::contains(const QString &field) { return m_data.contains(HeadersPrivate::normalizeHeaderKey(field)); } QString &Headers::operator[](const QString &key) { return m_data[key]; } const QString Headers::operator[](const QString &key) const { return m_data[key]; } QString HeadersPrivate::normalizeHeaderKey(const QString &field) { QString key = field; int i = 0; while (i < key.size()) { QCharRef c = key[i]; if (c.isSpace()) { key.remove(i, 1); continue; } else if (c == QLatin1Char('-')) { c = QLatin1Char('_'); } else { c = c.toLower(); } ++i; } return key; } QByteArray HeadersPrivate::decodeBasicAuth(const QString &auth) { if (!auth.isEmpty() && auth.startsWith(QLatin1String("Basic "))) { int pos = auth.lastIndexOf(QLatin1Char(' ')); if (pos != -1) { return QByteArray::fromBase64(auth.mid(pos).toLatin1()); } } return QByteArray(); } QPair<QString, QString> HeadersPrivate::decodeBasicAuthPair(const QString &auth) { const QByteArray authorization = decodeBasicAuth(auth); if (!authorization.isEmpty()) { int pos = authorization.indexOf(':'); if (pos == -1) { return qMakePair(QString::fromLatin1(authorization), QString()); } else { return qMakePair(QString::fromLatin1(authorization.left(pos)), QString::fromLatin1(authorization.mid(pos + 1))); } } return qMakePair(QString(), QString()); }
Fix Headers::pushHeader() behavior
Fix Headers::pushHeader() behavior
C++
bsd-3-clause
buschmann23/cutelyst,cutelyst/cutelyst,simonaw/cutelyst,buschmann23/cutelyst,cutelyst/cutelyst,buschmann23/cutelyst,simonaw/cutelyst,cutelyst/cutelyst
f4e0d3e1bb98727eb38c453b42d440253114eb54
src/Tools/Polar/Puncturer/Puncturer_polar_wangliu.cpp
src/Tools/Polar/Puncturer/Puncturer_polar_wangliu.cpp
#include <cmath> #include "../../../Decoder/decoder_functions.h" #include "Puncturer_polar_wangliu.hpp" template <typename B, typename R> Puncturer_polar_wangliu<B,R> ::Puncturer_polar_wangliu(const int & N, const int & K, const Frozenbits_generator<B> &fb_generator) : N(N), N_2(std::exp2(std::ceil(std::log2(N)))), Np(N_2 - N), K(K), puncturing_pattern(N_2, 0), fb_generator(fb_generator) { for (auto i = N_2 - Np ; i < N_2 ; i++) puncturing_pattern[i] = 1; } template <typename B, typename R> Puncturer_polar_wangliu<B,R> ::~Puncturer_polar_wangliu() { } template <typename B, typename R> void Puncturer_polar_wangliu<B,R> ::gen_frozen_bits(mipp::vector<B>& frozen_bits) { const std::vector<int>& best_channels = fb_generator.get_best_channels(); int info_bits_placed = 0; // initialize all bits to frozen for (auto i = 0 ; i < N_2 ; i++) frozen_bits[i] = (B)1; auto i = 0; while (info_bits_placed < K) { if (best_channels[i] < N_2 - Np) // choose best channels in interval [0 ; N_2 - Np] { // interval [0 ; N_2 - Np] are frozen frozen_bits[best_channels[i]] = (B)0; info_bits_placed++; } i++; } } template <typename B, typename R> void Puncturer_polar_wangliu<B,R> ::puncture(mipp::vector<R>& Y_N) const { for (int i = 0 ; i < N_2 ; i++) if (puncturing_pattern[i]) Y_N[i] = sat_vals<R>().second; } // ==================================================================================== explicit template instantiation #include "../../types.h" #ifdef MULTI_PREC template class Puncturer_polar_wangliu<B_8,Q_8>; template class Puncturer_polar_wangliu<B_16,Q_16>; template class Puncturer_polar_wangliu<B_32,Q_32>; template class Puncturer_polar_wangliu<B_64,Q_64>; #else template class Puncturer_polar_wangliu<B,Q>; #endif // ==================================================================================== explicit template instantiation
#include <cmath> #include "../../../Decoder/decoder_functions.h" #include "Puncturer_polar_wangliu.hpp" template <typename B, typename R> Puncturer_polar_wangliu<B,R> ::Puncturer_polar_wangliu(const int & N, const int & K, const Frozenbits_generator<B> &fb_generator) : N(N), N_2(std::exp2(std::ceil(std::log2(N)))), Np(N_2 - N), K(K), puncturing_pattern(N_2), fb_generator(fb_generator) { std::fill(puncturing_pattern.begin() , puncturing_pattern.begin() + N_2 - Np, 0); std::fill(puncturing_pattern.begin() + N_2 - Np, puncturing_pattern.end() , 1); } template <typename B, typename R> Puncturer_polar_wangliu<B,R> ::~Puncturer_polar_wangliu() { } template <typename B, typename R> void Puncturer_polar_wangliu<B,R> ::gen_frozen_bits(mipp::vector<B>& frozen_bits) { const std::vector<int>& best_channels = fb_generator.get_best_channels(); int info_bits_placed = 0; // initialize all bits to frozen for (auto i = 0 ; i < N_2 ; i++) frozen_bits[i] = (B)1; auto i = 0; while (info_bits_placed < K) { if (best_channels[i] < N_2 - Np) // choose best channels in interval [0 ; N_2 - Np] { // interval [0 ; N_2 - Np] are frozen frozen_bits[best_channels[i]] = (B)0; info_bits_placed++; } i++; } } template <typename B, typename R> void Puncturer_polar_wangliu<B,R> ::puncture(mipp::vector<R>& Y_N) const { for (int i = 0 ; i < N_2 ; i++) if (puncturing_pattern[i]) Y_N[i] = sat_vals<R>().second; } // ==================================================================================== explicit template instantiation #include "../../types.h" #ifdef MULTI_PREC template class Puncturer_polar_wangliu<B_8,Q_8>; template class Puncturer_polar_wangliu<B_16,Q_16>; template class Puncturer_polar_wangliu<B_32,Q_32>; template class Puncturer_polar_wangliu<B_64,Q_64>; #else template class Puncturer_polar_wangliu<B,Q>; #endif // ==================================================================================== explicit template instantiation
Fix wangliu puncturer contructor, which caused compilation issues with certain compilers.
Fix wangliu puncturer contructor, which caused compilation issues with certain compilers. Signed-off-by: Mathieu Léonardon <[email protected]>
C++
mit
aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct
0a6764281799b863ba71dc7aff3120a768f29900
fuzzer/cbor_decode.cpp
fuzzer/cbor_decode.cpp
#include "inc/cxx/json.hpp" #include "inc/cxx/cbor.hpp" #include <string_view> #include <cstddef> #include <cstdint> extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { cxx::json::byte_view bytes(reinterpret_cast<cxx::byte const*>(data), size); try { while (!std::empty(bytes)) { auto const json = cxx::cbor::decode(bytes); cxx::cbor::encode(json); } } catch (cxx::cbor::error const&) { }; return 0; }
#include "inc/cxx/json.hpp" #include "inc/cxx/cbor.hpp" #include <string_view> #include <cstddef> #include <cstdint> extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { cxx::json::byte_view bytes(reinterpret_cast<cxx::byte const*>(data), size); try { while (!std::empty(bytes)) { auto const json = cxx::cbor::decode(cxx::by_ref(bytes)); cxx::cbor::encode(json); } } catch (cxx::cbor::error const&) { }; return 0; }
fix fuzzer build
fix fuzzer build
C++
mit
attugit/cxxjson,attugit/cxxjson,attugit/cxxjson
b9bfae9abd3d2f11de9534568c9c8dc641ad33a2
test/src/unit/reg.cpp
test/src/unit/reg.cpp
//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "dll_test.hpp" #include "dll/neural/dense_layer.hpp" #include "dll/neural/rnn_layer.hpp" #include "dll/neural/recurrent_last_layer.hpp" #include "dll/network.hpp" #include "dll/datasets.hpp" namespace { void generate(std::vector<etl::fast_dyn_matrix<float, 3>>& samples, std::vector<size_t>& labels){ std::random_device rd; std::mt19937_64 engine(rd()); std::uniform_int_distribution<int> dist(0, 25); for(size_t i = 0; i < 1000; ++i){ samples.emplace_back(); auto& back = samples.back(); back[0] = dist(engine) / 25.0f; back[1] = dist(engine) / 25.0f; back[2] = dist(engine) / 25.0f; labels.push_back((back[0] + back[1] + back[2]) / 3.0f); } } } // end of anonymous namespace TEST_CASE("unit/reg/1", "[unit][reg]") { std::vector<etl::fast_dyn_matrix<float, 3>> samples; std::vector<size_t> labels; generate(samples, labels); using network_t = dll::dyn_network_desc< dll::network_layers< dll::dense_layer<3, 1, dll::tanh> > , dll::mean_squared_error , dll::batch_size<10> , dll::adadelta >::network_t; auto net = std::make_unique<network_t>(); REQUIRE(net->fine_tune_reg(samples, labels, 30) < 0.15); //REQUIRE(net->evaluate_error(samples, labels) < 0.25); }
//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "dll_test.hpp" #include "dll/neural/dense_layer.hpp" #include "dll/neural/rnn_layer.hpp" #include "dll/neural/recurrent_last_layer.hpp" #include "dll/network.hpp" #include "dll/datasets.hpp" namespace { void generate(std::vector<etl::fast_dyn_matrix<float, 3>>& samples, std::vector<size_t>& labels){ std::random_device rd; std::mt19937_64 engine(rd()); std::uniform_int_distribution<int> dist(0, 25); for(size_t i = 0; i < 1000; ++i){ samples.emplace_back(); auto& back = samples.back(); back[0] = dist(engine) / 25.0f; back[1] = dist(engine) / 25.0f; back[2] = dist(engine) / 25.0f; labels.push_back((back[0] + back[1] + back[2]) / 3.0f); } } } // end of anonymous namespace TEST_CASE("unit/reg/1", "[unit][reg]") { std::vector<etl::fast_dyn_matrix<float, 3>> samples; std::vector<size_t> labels; generate(samples, labels); using network_t = dll::dyn_network_desc< dll::network_layers< dll::dense_layer<3, 1, dll::tanh> > , dll::mean_squared_error , dll::batch_size<10> , dll::adadelta >::network_t; auto net = std::make_unique<network_t>(); REQUIRE(net->fine_tune_reg(samples, labels, 30) < 0.15); // Mostly here for compilation's sake net->evaluate_reg(samples, labels); REQUIRE(net->evaluate_error_reg(samples, labels) < 0.25); }
Add evaluation to the regression test
Add evaluation to the regression test
C++
mit
wichtounet/dll,wichtounet/dll,wichtounet/dll
3ea4ed5c8254cadc024ecb80ff93c5148facccbd
source/Pictus/adjust.cpp
source/Pictus/adjust.cpp
#include "adjust.h" #include <wx/button.h> #include <wx/checkbox.h> #include <wx/sizer.h> #include <wx/statbox.h> #include "wintypes.h" #include "illa/config.h" using namespace Intl; namespace App { void Adjust::Brightness(int newBright) { if (newBright != m_brightness->GetValue()) { m_brightness->SetValue(newBright); } } int Adjust::Brightness() const { return m_brightness->GetValue(); } void Adjust::Contrast(int newContrast) { if (newContrast != m_contrast->GetValue()) { m_contrast->SetValue(newContrast); } } int Adjust::Contrast() const { return m_contrast->GetValue(); } void Adjust::Gamma(int newGamma) { if (newGamma != m_gamma->GetValue()) { m_gamma->SetValue(newGamma); } } int Adjust::Gamma() const { return m_gamma->GetValue(); } Adjust::Adjust(wxWindow* parent): wxDialog(parent, wxID_ANY, Win::GetStringWx(SIDAdjust), wxDefaultPosition,wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxSTAY_ON_TOP) { auto applyFunc = [this](wxCommandEvent& evt) { Apply(); }; auto closeFunc = [this](wxCommandEvent& evt) { Close(); }; auto defaultFunc = [this](wxCommandEvent& evt) { Default(); }; auto onChange = [this](wxCommandEvent& evt) { if (!isAutoProof()) return false; Apply(); return true; }; auto brightnessBox = new wxStaticBoxSizer(wxVERTICAL, this, Win::GetStringWx(SIDAdjustBrightness)); m_brightness = new wxSlider(brightnessBox->GetStaticBox(), wxID_ANY, 0, Img::MinBrightness, Img::MaxBrightness, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL | wxSL_AUTOTICKS); brightnessBox->Add(m_brightness, wxSizerFlags(0).Border(wxALL, 10).Expand()); auto contrastBox = new wxStaticBoxSizer(wxVERTICAL, this, Win::GetStringWx(SIDAdjustContrast)); m_contrast = new wxSlider(contrastBox->GetStaticBox(), wxID_ANY, Img::ContrastStep, Img::MinContrast, Img::MaxContrast, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL | wxSL_AUTOTICKS); contrastBox->Add(m_contrast, wxSizerFlags(0).Border(wxALL, 10).Expand()); auto gammaBox = new wxStaticBoxSizer(wxVERTICAL, this, Win::GetStringWx(SIDAdjustGamma)); m_gamma = new wxSlider(gammaBox->GetStaticBox(), wxID_ANY, 10, Img::MinGamma, Img::MaxGamma, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL | wxSL_AUTOTICKS); gammaBox->Add(m_gamma, wxSizerFlags(0).Border(wxALL, 10).Expand()); m_brightness->SetTickFreq((Img::MaxBrightness - Img::MinBrightness) / 10); m_contrast->SetTickFreq((Img::MaxContrast - Img::MinContrast) / 10); m_gamma->SetTickFreq((Img::MaxGamma - Img::MinGamma) / 10); m_autoApply = new wxCheckBox(this, wxID_ANY, Win::GetStringWx(SIDAdjustAutoApply)); auto applyButton = new wxButton(this, wxID_ANY, Win::GetStringWx(SIDDialogApply)); auto defaultButton = new wxButton(this, wxID_ANY, Win::GetStringWx(SIDAdjustDefault)); auto closeButton = new wxButton(this, wxID_ANY, Win::GetStringWx(SIDDialogClose)); auto buttonSizer = new wxBoxSizer(wxHORIZONTAL); buttonSizer->Add(applyButton, wxSizerFlags(1)); buttonSizer->Add(defaultButton, wxSizerFlags(1).Border(wxLEFT | wxRIGHT, 10)); buttonSizer->Add(closeButton, wxSizerFlags(1)); m_brightness->Bind(wxEVT_SLIDER, onChange); m_contrast->Bind(wxEVT_SLIDER, onChange); m_gamma->Bind(wxEVT_SLIDER, onChange); m_autoApply->Bind(wxEVT_CHECKBOX, applyFunc); applyButton->Bind(wxEVT_BUTTON, applyFunc); defaultButton->Bind(wxEVT_BUTTON, defaultFunc); closeButton->Bind(wxEVT_BUTTON, closeFunc); auto topmostSizer = new wxBoxSizer(wxVERTICAL); topmostSizer->Add(brightnessBox, wxSizerFlags(0).Border(wxALL, 10).Expand()); topmostSizer->Add(contrastBox, wxSizerFlags(0).Border(wxALL, 10).Expand()); topmostSizer->Add(gammaBox, wxSizerFlags(0).Border(wxALL, 10).Expand()); topmostSizer->Add(m_autoApply, wxSizerFlags(0).Border(wxALL, 10).Expand()); topmostSizer->Add(buttonSizer, wxSizerFlags(0).Border(wxALL, 10).Expand()); SetSizerAndFit(topmostSizer); } bool Adjust::isAutoProof() { return m_autoApply->GetValue(); } void Adjust::Apply() { OnChange(Brightness(), Contrast(), Gamma()); } void Adjust::Default() { Brightness(0); Contrast(10); Gamma(10); if (isAutoProof()) { Apply(); } } }
#include "adjust.h" #include <wx/button.h> #include <wx/checkbox.h> #include <wx/sizer.h> #include <wx/statbox.h> #include "wintypes.h" #include "illa/config.h" using namespace Intl; namespace App { void Adjust::Brightness(int newBright) { if (newBright != m_brightness->GetValue()) { m_brightness->SetValue(newBright); } } int Adjust::Brightness() const { return m_brightness->GetValue(); } void Adjust::Contrast(int newContrast) { if (newContrast != m_contrast->GetValue()) { m_contrast->SetValue(newContrast); } } int Adjust::Contrast() const { return m_contrast->GetValue(); } void Adjust::Gamma(int newGamma) { if (newGamma != m_gamma->GetValue()) { m_gamma->SetValue(newGamma); } } int Adjust::Gamma() const { return m_gamma->GetValue(); } Adjust::Adjust(wxWindow* parent): wxDialog(parent, wxID_ANY, Win::GetStringWx(SIDAdjust), wxDefaultPosition,wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxSTAY_ON_TOP) { auto applyFunc = [this](wxCommandEvent& evt) { Apply(); }; auto defaultFunc = [this](wxCommandEvent& evt) { Default(); }; auto onChange = [this](wxCommandEvent& evt) { if (!isAutoProof()) return false; Apply(); return true; }; auto brightnessBox = new wxStaticBoxSizer(wxVERTICAL, this, Win::GetStringWx(SIDAdjustBrightness)); m_brightness = new wxSlider(brightnessBox->GetStaticBox(), wxID_ANY, 0, Img::MinBrightness, Img::MaxBrightness, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL | wxSL_AUTOTICKS); brightnessBox->Add(m_brightness, wxSizerFlags(0).Border(wxALL, 10).Expand()); auto contrastBox = new wxStaticBoxSizer(wxVERTICAL, this, Win::GetStringWx(SIDAdjustContrast)); m_contrast = new wxSlider(contrastBox->GetStaticBox(), wxID_ANY, Img::ContrastStep, Img::MinContrast, Img::MaxContrast, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL | wxSL_AUTOTICKS); contrastBox->Add(m_contrast, wxSizerFlags(0).Border(wxALL, 10).Expand()); auto gammaBox = new wxStaticBoxSizer(wxVERTICAL, this, Win::GetStringWx(SIDAdjustGamma)); m_gamma = new wxSlider(gammaBox->GetStaticBox(), wxID_ANY, 10, Img::MinGamma, Img::MaxGamma, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL | wxSL_AUTOTICKS); gammaBox->Add(m_gamma, wxSizerFlags(0).Border(wxALL, 10).Expand()); m_brightness->SetTickFreq((Img::MaxBrightness - Img::MinBrightness) / 10); m_contrast->SetTickFreq((Img::MaxContrast - Img::MinContrast) / 10); m_gamma->SetTickFreq((Img::MaxGamma - Img::MinGamma) / 10); m_autoApply = new wxCheckBox(this, wxID_ANY, Win::GetStringWx(SIDAdjustAutoApply)); auto applyButton = new wxButton(this, wxID_ANY, Win::GetStringWx(SIDDialogApply)); auto defaultButton = new wxButton(this, wxID_ANY, Win::GetStringWx(SIDAdjustDefault)); auto closeButton = new wxButton(this, wxID_CANCEL, Win::GetStringWx(SIDDialogClose)); auto buttonSizer = new wxBoxSizer(wxHORIZONTAL); buttonSizer->Add(applyButton, wxSizerFlags(1)); buttonSizer->Add(defaultButton, wxSizerFlags(1).Border(wxLEFT | wxRIGHT, 10)); buttonSizer->Add(closeButton, wxSizerFlags(1)); m_brightness->Bind(wxEVT_SLIDER, onChange); m_contrast->Bind(wxEVT_SLIDER, onChange); m_gamma->Bind(wxEVT_SLIDER, onChange); m_autoApply->Bind(wxEVT_CHECKBOX, applyFunc); applyButton->Bind(wxEVT_BUTTON, applyFunc); defaultButton->Bind(wxEVT_BUTTON, defaultFunc); auto topmostSizer = new wxBoxSizer(wxVERTICAL); topmostSizer->Add(brightnessBox, wxSizerFlags(0).Border(wxALL, 10).Expand()); topmostSizer->Add(contrastBox, wxSizerFlags(0).Border(wxALL, 10).Expand()); topmostSizer->Add(gammaBox, wxSizerFlags(0).Border(wxALL, 10).Expand()); topmostSizer->Add(m_autoApply, wxSizerFlags(0).Border(wxALL, 10).Expand()); topmostSizer->Add(buttonSizer, wxSizerFlags(0).Border(wxALL, 10).Expand()); SetSizerAndFit(topmostSizer); } bool Adjust::isAutoProof() { return m_autoApply->GetValue(); } void Adjust::Apply() { OnChange(Brightness(), Contrast(), Gamma()); } void Adjust::Default() { Brightness(0); Contrast(10); Gamma(10); if (isAutoProof()) { Apply(); } } }
Make escape key work in adjust dialog
Make escape key work in adjust dialog
C++
mit
poppeman/Pictus,poppeman/Pictus,poppeman/Pictus
e514fff2a1a47a0150fdcf6f255970271a4b1319
test/test_context.cpp
test/test_context.cpp
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "flusspferd/context.hpp" #include "flusspferd/spidermonkey/context.hpp" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE( null_context ) { flusspferd::context null_context; BOOST_CHECK(!null_context.is_valid()); } BOOST_AUTO_TEST_CASE( copy_null_context ) { flusspferd::context original_null_context; BOOST_REQUIRE(!original_null_context.is_valid()); flusspferd::context null_context; BOOST_CHECK(!null_context.is_valid()); } BOOST_AUTO_TEST_SUITE( spidermonkey ) BOOST_AUTO_TEST_CASE( direct_null_context ) { flusspferd::context null_context(flusspferd::Impl::wrap_context(0)); BOOST_CHECK(!null_context.is_valid()); } BOOST_AUTO_TEST_SUITE_END()
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "flusspferd/context.hpp" #include "flusspferd/spidermonkey/context.hpp" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE( null_context ) { flusspferd::context null_context; BOOST_CHECK(!null_context.is_valid()); } BOOST_AUTO_TEST_CASE( copy_null_context ) { flusspferd::context original_null_context; BOOST_REQUIRE(!original_null_context.is_valid()); flusspferd::context null_context; BOOST_CHECK(!null_context.is_valid()); } BOOST_AUTO_TEST_CASE( create_context ) { flusspferd::context context(flusspferd::context::create()); BOOST_CHECK(context.is_valid()); } BOOST_AUTO_TEST_SUITE( spidermonkey ) BOOST_AUTO_TEST_CASE( direct_null_context ) { flusspferd::context null_context(flusspferd::Impl::wrap_context(0)); BOOST_CHECK(!null_context.is_valid()); } BOOST_AUTO_TEST_SUITE_END()
check is_valid() for context::create()
check is_valid() for context::create()
C++
mit
Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd
b2a6903b018be035fce0593d9b67e687d6805501
pythran/pythonic/utils/broadcast_copy.hpp
pythran/pythonic/utils/broadcast_copy.hpp
#ifndef PYTHONIC_UTILS_BROADCAST_COPY_HPP #define PYTHONIC_UTILS_BROADCAST_COPY_HPP #include "pythonic/types/tuple.hpp" #ifdef USE_BOOST_SIMD #include <boost/simd/sdk/simd/native.hpp> #endif #ifdef _OPENMP #include <omp.h> // as a macro so that an enlightened user can modify this non-documented variable :-) #ifndef PYTHRAN_OPENMP_MIN_ITERATION_COUNT #define PYTHRAN_OPENMP_MIN_ITERATION_COUNT 1000 #endif #endif namespace pythonic { namespace utils { /* helper function to get the dimension of an array * yields 0 for scalar types */ template <class T, typename EnableDefault = void> struct dim_of { static const size_t value = T::value; }; template<class T, size_t N> struct dim_of<types::array<T,N>, void> { static const size_t value = 1 + dim_of<T>::value; }; template<class T> struct dim_of<T, typename std::enable_if<std::is_fundamental<T>::value>::type> { static const size_t value = 0; }; #define SPECIALIZE_DIM_OF(TYPE) template<> struct dim_of<TYPE> { static const size_t value = 0; } SPECIALIZE_DIM_OF(std::complex<float>); SPECIALIZE_DIM_OF(std::complex<double>); #undef SPECIALIZE_DIM_OF /* helper for specialization of the broadcasting, vectorizing copy operator * due to expression templates, this may also triggers a lot of computations! * * ``vector_form'' is set to true if the operation can be done using Boost.SIMD * * the call operator has four template parameters: * * template <class E, class F, size_t N> * void operator()(E &&self, F const &other, utils::int_<N>, utils::int_<M>) * * ``E'' is the type of the object to which the data are copied * * ``F'' is the type of the object from which the data are copied * * ``N'' is the depth of the loop nest. When it reaches ``1'', we have a raw loop * that may be vectorizable * * ``D'' is the delta between the number of dimensions of E and F. When set to a * value greater than ``0'', some broadcasting is needed */ template <bool vector_form> struct _broadcast_copy { template <class E, class F, size_t N> void operator()(E &&self, F const &other, utils::int_<N>, utils::int_<0>) { long self_size = std::distance(self.begin(), self.end()), other_size = std::distance(other.begin(), other.end()); if (other_size > 0) { // empty array sometimes happen when filtering #ifdef _OPENMP if (other_size >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for(long i = 0; i < other_size; ++i) self.fast(i) = other.fast(i); else #endif std::copy(other.begin(), other.end(), self.begin()); // eventually repeat the pattern size_t n = self_size / other_size; #ifdef _OPENMP if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); else #endif for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); } } // ``D'' is not ``0'' so we should broadcast template <class E, class F, size_t N, size_t D> void operator()(E &&self, F const &other, utils::int_<N>, utils::int_<D>) { self.fast(0) = other; long n = self.shape[0]; #ifdef _OPENMP if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for(long i = 1; i < n; ++i) self.fast(i) = self.fast(0); else #endif std::fill(self.begin() + 1, self.end(), self.fast(0)); } }; #ifdef USE_BOOST_SIMD // specialize for SIMD only if available // otherwise use the std::copy fallback template <> struct _broadcast_copy<true> { template <class E, class F> void operator()(E &&self, F const &other, utils::int_<1>, utils::int_<0>) { typedef typename F::dtype T; typedef typename boost::simd::native<T, BOOST_SIMD_DEFAULT_EXTENSION> vT; long self_size = std::distance(self.begin(), self.end()), other_size = std::distance(other.begin(), other.end()); if (other_size > 0) { // empty array sometimes happen when filtering static const std::size_t vN = boost::simd::meta::cardinal_of<vT>::value; const long bound = other_size / vN * vN; long i; #ifdef _OPENMP if (bound >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for (i = 0; i < bound; i += vN) self.store(other.load(i), i); else #endif for (i = 0; i < bound; i += vN) self.store(other.load(i), i); for (; i < other_size; ++i) self.fast(i) = other.fast(i); size_t n = self_size / other_size; #ifdef _OPENMP if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); else #endif for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); } } template <class E, class F, size_t N> void operator()(E &&self, F const &other, utils::int_<N>, utils::int_<0>) { long self_size = std::distance(self.begin(), self.end()), other_size = std::distance(other.begin(), other.end()); if (other_size > 0) { // empty array sometimes happen when filtering #ifdef _OPENMP if (other_size >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for(long i = 0; i < other_size; ++i) (*this)(self.fast(i), other.fast(i), utils::int_<N - 1>(), utils::int_<0>()); else #endif for(long i = 0; i < other_size; ++i) (*this)(self.fast(i), other.fast(i), utils::int_<N - 1>(), utils::int_<0>()); // eventually repeat the pattern size_t n = self_size / other_size; #ifdef _OPENMP if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); else #endif for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); } } // ``D'' is not ``0'' so we should broadcast template <class E, class F, size_t N, size_t D> void operator()(E &&self, F const &other, utils::int_<N>, utils::int_<D>) { (*this)(self.fast(0), other, utils::int_<N - 1>(), utils::int_<D - 1>()); long n = self.shape[0]; #ifdef _OPENMP if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for(long i = 1; i < n; ++i) self.fast(i) = self.fast(0); else #endif std::fill(self.begin() + 1, self.end(), self.fast(0)); } }; #endif template <class E, class F, size_t N, size_t D, bool vector_form> E& broadcast_copy(E &self, F const &other) { _broadcast_copy<vector_form> {} (self, other, utils::int_<N>(), utils::int_<D>()); return self; } } } #endif
#ifndef PYTHONIC_UTILS_BROADCAST_COPY_HPP #define PYTHONIC_UTILS_BROADCAST_COPY_HPP #include "pythonic/types/tuple.hpp" #ifdef USE_BOOST_SIMD #include <boost/simd/sdk/simd/native.hpp> #endif #ifdef _OPENMP #include <omp.h> // as a macro so that an enlightened user can modify this non-documented variable :-) #ifndef PYTHRAN_OPENMP_MIN_ITERATION_COUNT #define PYTHRAN_OPENMP_MIN_ITERATION_COUNT 1000 #endif #endif namespace pythonic { namespace utils { /* helper function to get the dimension of an array * yields 0 for scalar types */ template <class T, typename EnableDefault = void> struct dim_of { static const size_t value = T::value; }; template<class T, size_t N> struct dim_of<types::array<T,N>, void> { static const size_t value = 1 + dim_of<T>::value; }; template<class T> struct dim_of<T, typename std::enable_if<std::is_fundamental<T>::value>::type> { static const size_t value = 0; }; #define SPECIALIZE_DIM_OF(TYPE) template<> struct dim_of<TYPE> { static const size_t value = 0; } SPECIALIZE_DIM_OF(std::complex<float>); SPECIALIZE_DIM_OF(std::complex<double>); #undef SPECIALIZE_DIM_OF /* helper for specialization of the broadcasting, vectorizing copy operator * due to expression templates, this may also triggers a lot of computations! * * ``vector_form'' is set to true if the operation can be done using Boost.SIMD * * the call operator has four template parameters: * * template <class E, class F, size_t N> * void operator()(E &&self, F const &other, utils::int_<N>, utils::int_<M>) * * ``E'' is the type of the object to which the data are copied * * ``F'' is the type of the object from which the data are copied * * ``N'' is the depth of the loop nest. When it reaches ``1'', we have a raw loop * that may be vectorizable * * ``D'' is the delta between the number of dimensions of E and F. When set to a * value greater than ``0'', some broadcasting is needed */ template <bool vector_form> struct _broadcast_copy { template <class E, class F, size_t N> void operator()(E &&self, F const &other, utils::int_<N>, utils::int_<0>) { long self_size = std::distance(self.begin(), self.end()), other_size = std::distance(other.begin(), other.end()); if (other_size > 0) { // empty array sometimes happen when filtering #ifdef _OPENMP if (other_size >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for(long i = 0; i < other_size; ++i) self.fast(i) = other.fast(i); else #endif std::copy(other.begin(), other.end(), self.begin()); // eventually repeat the pattern size_t n = self_size / other_size; #ifdef _OPENMP if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); else #endif for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); } } // ``D'' is not ``0'' so we should broadcast template <class E, class F, size_t N, size_t D> void operator()(E &&self, F const &other, utils::int_<N>, utils::int_<D>) { self.fast(0) = other; #ifdef _OPENMP long n = self.shape[0]; if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for(long i = 1; i < n; ++i) self.fast(i) = self.fast(0); else #endif std::fill(self.begin() + 1, self.end(), self.fast(0)); } }; #ifdef USE_BOOST_SIMD // specialize for SIMD only if available // otherwise use the std::copy fallback template <> struct _broadcast_copy<true> { template <class E, class F> void operator()(E &&self, F const &other, utils::int_<1>, utils::int_<0>) { typedef typename F::dtype T; typedef typename boost::simd::native<T, BOOST_SIMD_DEFAULT_EXTENSION> vT; long self_size = std::distance(self.begin(), self.end()), other_size = std::distance(other.begin(), other.end()); if (other_size > 0) { // empty array sometimes happen when filtering static const std::size_t vN = boost::simd::meta::cardinal_of<vT>::value; const long bound = other_size / vN * vN; long i; #ifdef _OPENMP if (bound >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for (i = 0; i < bound; i += vN) self.store(other.load(i), i); else #endif for (i = 0; i < bound; i += vN) self.store(other.load(i), i); for (; i < other_size; ++i) self.fast(i) = other.fast(i); size_t n = self_size / other_size; #ifdef _OPENMP if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); else #endif for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); } } template <class E, class F, size_t N> void operator()(E &&self, F const &other, utils::int_<N>, utils::int_<0>) { long self_size = std::distance(self.begin(), self.end()), other_size = std::distance(other.begin(), other.end()); if (other_size > 0) { // empty array sometimes happen when filtering #ifdef _OPENMP if (other_size >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for(long i = 0; i < other_size; ++i) (*this)(self.fast(i), other.fast(i), utils::int_<N - 1>(), utils::int_<0>()); else #endif for(long i = 0; i < other_size; ++i) (*this)(self.fast(i), other.fast(i), utils::int_<N - 1>(), utils::int_<0>()); // eventually repeat the pattern size_t n = self_size / other_size; #ifdef _OPENMP if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); else #endif for (size_t i = 1; i < n; ++i) std::copy_n(self.begin(), other_size, self.begin() + i * other_size); } } // ``D'' is not ``0'' so we should broadcast template <class E, class F, size_t N, size_t D> void operator()(E &&self, F const &other, utils::int_<N>, utils::int_<D>) { (*this)(self.fast(0), other, utils::int_<N - 1>(), utils::int_<D - 1>()); #ifdef _OPENMP long n = self.shape[0]; if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT) #pragma omp parallel for for(long i = 1; i < n; ++i) self.fast(i) = self.fast(0); else #endif std::fill(self.begin() + 1, self.end(), self.fast(0)); } }; #endif template <class E, class F, size_t N, size_t D, bool vector_form> E& broadcast_copy(E &self, F const &other) { _broadcast_copy<vector_form> {} (self, other, utils::int_<N>(), utils::int_<D>()); return self; } } } #endif
Remove unused variable warning when OpenMP is disable
Remove unused variable warning when OpenMP is disable
C++
bsd-3-clause
artas360/pythran,hainm/pythran,pbrunet/pythran,hainm/pythran,pbrunet/pythran,pombredanne/pythran,hainm/pythran,serge-sans-paille/pythran,pbrunet/pythran,artas360/pythran,pombredanne/pythran,artas360/pythran,serge-sans-paille/pythran,pombredanne/pythran
3269523c41e87d8f69c652b21b877ab93a20d89f
test/test_geometry.cc
test/test_geometry.cc
#include "gtest/gtest.h" #include "../include/spica.h" using namespace spica; // ------------------------------ // Primitive class test // ------------------------------ TEST(PrimitiveTest, InstanceTest) { Primitive p; EXPECT_EQ(0.0, p.emission().x()); EXPECT_EQ(0.0, p.emission().y()); EXPECT_EQ(0.0, p.emission().z()); EXPECT_EQ(0.0, p.color().x()); EXPECT_EQ(0.0, p.color().y()); EXPECT_EQ(0.0, p.color().z()); EXPECT_EQ(0, p.reftype()); Ray ray; HitPoint hitpoint; ASSERT_DEATH(p.intersect(ray, hitpoint), ""); Primitive q(Material(Color(0.25, 0.50, 0.75), Color(0.1, 0.2, 0.3), REFLECTION_REFRACTION)); EXPECT_EQ(0.25, q.emission().x()); EXPECT_EQ(0.50, q.emission().y()); EXPECT_EQ(0.75, q.emission().z()); EXPECT_EQ(0.1, q.color().x()); EXPECT_EQ(0.2, q.color().y()); EXPECT_EQ(0.3, q.color().z()); EXPECT_EQ(REFLECTION_REFRACTION, q.reftype()); p = q; EXPECT_EQ(0.25, p.emission().x()); EXPECT_EQ(0.50, p.emission().y()); EXPECT_EQ(0.75, p.emission().z()); EXPECT_EQ(0.1, p.color().x()); EXPECT_EQ(0.2, p.color().y()); EXPECT_EQ(0.3, p.color().z()); p = Primitive(q); EXPECT_EQ(0.25, p.emission().x()); EXPECT_EQ(0.50, p.emission().y()); EXPECT_EQ(0.75, p.emission().z()); EXPECT_EQ(0.1, p.color().x()); EXPECT_EQ(0.2, p.color().y()); EXPECT_EQ(0.3, p.color().z()); } // ------------------------------ // Plane class test // ------------------------------ TEST(PlaneTest, InstanceTest) { Plane pl(3.0, Vector3(-1.0, 0.0, 0.0), Material(Color(0.1, 0.2, 0.3), Color(0.25, 0.50, 0.75), REFLECTION_DIFFUSE)); EXPECT_EQ(3.0, pl.distance()); EXPECT_EQ(-1.0, pl.normal().x()); EXPECT_EQ(0.0, pl.normal().y()); EXPECT_EQ(0.0, pl.normal().z()); EXPECT_EQ(0.1, pl.emission().x()); EXPECT_EQ(0.2, pl.emission().y()); EXPECT_EQ(0.3, pl.emission().z()); EXPECT_EQ(0.25, pl.color().x()); EXPECT_EQ(0.50, pl.color().y()); EXPECT_EQ(0.75, pl.color().z()); HitPoint hitpoint; EXPECT_TRUE(pl.intersect(Ray(Vector3(0.0, 1.0, 1.0), Vector3(3.0, 4.0, 0.0).normalized()), hitpoint)); EXPECT_EQ(3.0, hitpoint.position().x()); EXPECT_EQ(5.0, hitpoint.position().y()); EXPECT_EQ(1.0, hitpoint.position().z()); EXPECT_EQ(5.0, hitpoint.distance()); EXPECT_FALSE(pl.intersect(Ray(Vector3(0.0, 1.0, 1.0), Vector3(-1.0, 0.0, 0.0)), hitpoint)); } // ------------------------------ // Sphere class test // ------------------------------ TEST(SphereTest, InstanceTest) { Sphere sp0; EXPECT_EQ(0.0, sp0.center().x()); EXPECT_EQ(0.0, sp0.center().y()); EXPECT_EQ(0.0, sp0.center().z()); EXPECT_EQ(0.0, sp0.radius()); Sphere sp(2.0, Vector3(0.0, 0.0, 0.0), Material(Color(), Color(0.75, 0.75, 0.75), REFLECTION_DIFFUSE)); EXPECT_EQ(0.0, sp.center().x()); EXPECT_EQ(0.0, sp.center().y()); EXPECT_EQ(0.0, sp.center().z()); EXPECT_EQ(0.0, sp.emission().x()); EXPECT_EQ(0.0, sp.emission().y()); EXPECT_EQ(0.0, sp.emission().z()); EXPECT_EQ(0.75, sp.color().x()); EXPECT_EQ(0.75, sp.color().y()); EXPECT_EQ(0.75, sp.color().z()); EXPECT_EQ(REFLECTION_DIFFUSE, sp.reftype()); // copy constructor sp0 = sp; EXPECT_EQ(0.0, sp0.center().x()); EXPECT_EQ(0.0, sp0.center().y()); EXPECT_EQ(0.0, sp0.center().z()); EXPECT_EQ(0.0, sp0.emission().x()); EXPECT_EQ(0.0, sp0.emission().y()); EXPECT_EQ(0.0, sp0.emission().z()); EXPECT_EQ(0.75, sp0.color().x()); EXPECT_EQ(0.75, sp0.color().y()); EXPECT_EQ(0.75, sp0.color().z()); // intersection HitPoint hitpoint; EXPECT_TRUE(sp.intersect(Ray(Vector3(10.0, 0.0, 0.0), Vector3(-1.0, 0.0, 0.0)), hitpoint)); EXPECT_EQ(2.0, hitpoint.position().x()); EXPECT_EQ(0.0, hitpoint.position().y()); EXPECT_EQ(0.0, hitpoint.position().z()); EXPECT_EQ(1.0, hitpoint.normal().x()); EXPECT_EQ(0.0, hitpoint.normal().y()); EXPECT_EQ(0.0, hitpoint.normal().z()); EXPECT_FALSE(sp.intersect(Ray(Vector3(10.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0)), hitpoint)); }
#include "gtest/gtest.h" #include "../include/spica.h" using namespace spica; // ------------------------------ // Primitive class test // ------------------------------ TEST(PrimitiveTest, InstanceTest) { Primitive p; EXPECT_EQ(0.0, p.emission().x()); EXPECT_EQ(0.0, p.emission().y()); EXPECT_EQ(0.0, p.emission().z()); EXPECT_EQ(0.0, p.color().x()); EXPECT_EQ(0.0, p.color().y()); EXPECT_EQ(0.0, p.color().z()); EXPECT_EQ(REFLECTION_DIFFUSE, p.reftype()); Ray ray; HitPoint hitpoint; ASSERT_DEATH(p.intersect(ray, hitpoint), ""); Primitive q(Material(Color(0.25, 0.50, 0.75), Color(0.1, 0.2, 0.3), REFLECTION_REFRACTION)); EXPECT_EQ(0.25, q.emission().x()); EXPECT_EQ(0.50, q.emission().y()); EXPECT_EQ(0.75, q.emission().z()); EXPECT_EQ(0.1, q.color().x()); EXPECT_EQ(0.2, q.color().y()); EXPECT_EQ(0.3, q.color().z()); EXPECT_EQ(REFLECTION_REFRACTION, q.reftype()); p = q; EXPECT_EQ(0.25, p.emission().x()); EXPECT_EQ(0.50, p.emission().y()); EXPECT_EQ(0.75, p.emission().z()); EXPECT_EQ(0.1, p.color().x()); EXPECT_EQ(0.2, p.color().y()); EXPECT_EQ(0.3, p.color().z()); p = Primitive(q); EXPECT_EQ(0.25, p.emission().x()); EXPECT_EQ(0.50, p.emission().y()); EXPECT_EQ(0.75, p.emission().z()); EXPECT_EQ(0.1, p.color().x()); EXPECT_EQ(0.2, p.color().y()); EXPECT_EQ(0.3, p.color().z()); } // ------------------------------ // Plane class test // ------------------------------ TEST(PlaneTest, InstanceTest) { Plane pl(3.0, Vector3(-1.0, 0.0, 0.0), Material(Color(0.1, 0.2, 0.3), Color(0.25, 0.50, 0.75), REFLECTION_DIFFUSE)); EXPECT_EQ(3.0, pl.distance()); EXPECT_EQ(-1.0, pl.normal().x()); EXPECT_EQ(0.0, pl.normal().y()); EXPECT_EQ(0.0, pl.normal().z()); EXPECT_EQ(0.1, pl.emission().x()); EXPECT_EQ(0.2, pl.emission().y()); EXPECT_EQ(0.3, pl.emission().z()); EXPECT_EQ(0.25, pl.color().x()); EXPECT_EQ(0.50, pl.color().y()); EXPECT_EQ(0.75, pl.color().z()); HitPoint hitpoint; EXPECT_TRUE(pl.intersect(Ray(Vector3(0.0, 1.0, 1.0), Vector3(3.0, 4.0, 0.0).normalized()), hitpoint)); EXPECT_EQ(3.0, hitpoint.position().x()); EXPECT_EQ(5.0, hitpoint.position().y()); EXPECT_EQ(1.0, hitpoint.position().z()); EXPECT_EQ(5.0, hitpoint.distance()); EXPECT_FALSE(pl.intersect(Ray(Vector3(0.0, 1.0, 1.0), Vector3(-1.0, 0.0, 0.0)), hitpoint)); } // ------------------------------ // Sphere class test // ------------------------------ TEST(SphereTest, InstanceTest) { Sphere sp0; EXPECT_EQ(0.0, sp0.center().x()); EXPECT_EQ(0.0, sp0.center().y()); EXPECT_EQ(0.0, sp0.center().z()); EXPECT_EQ(0.0, sp0.radius()); Sphere sp(2.0, Vector3(0.0, 0.0, 0.0), Material(Color(), Color(0.75, 0.75, 0.75), REFLECTION_DIFFUSE)); EXPECT_EQ(0.0, sp.center().x()); EXPECT_EQ(0.0, sp.center().y()); EXPECT_EQ(0.0, sp.center().z()); EXPECT_EQ(0.0, sp.emission().x()); EXPECT_EQ(0.0, sp.emission().y()); EXPECT_EQ(0.0, sp.emission().z()); EXPECT_EQ(0.75, sp.color().x()); EXPECT_EQ(0.75, sp.color().y()); EXPECT_EQ(0.75, sp.color().z()); EXPECT_EQ(REFLECTION_DIFFUSE, sp.reftype()); // copy constructor sp0 = sp; EXPECT_EQ(0.0, sp0.center().x()); EXPECT_EQ(0.0, sp0.center().y()); EXPECT_EQ(0.0, sp0.center().z()); EXPECT_EQ(0.0, sp0.emission().x()); EXPECT_EQ(0.0, sp0.emission().y()); EXPECT_EQ(0.0, sp0.emission().z()); EXPECT_EQ(0.75, sp0.color().x()); EXPECT_EQ(0.75, sp0.color().y()); EXPECT_EQ(0.75, sp0.color().z()); // intersection HitPoint hitpoint; EXPECT_TRUE(sp.intersect(Ray(Vector3(10.0, 0.0, 0.0), Vector3(-1.0, 0.0, 0.0)), hitpoint)); EXPECT_EQ(2.0, hitpoint.position().x()); EXPECT_EQ(0.0, hitpoint.position().y()); EXPECT_EQ(0.0, hitpoint.position().z()); EXPECT_EQ(1.0, hitpoint.normal().x()); EXPECT_EQ(0.0, hitpoint.normal().y()); EXPECT_EQ(0.0, hitpoint.normal().z()); EXPECT_FALSE(sp.intersect(Ray(Vector3(10.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0)), hitpoint)); }
Update test for geometry Primitive.
Update test for geometry Primitive.
C++
mit
tatsy/spica,tatsy/spica,tatsy/spica
5760a809601eb0b6aa404a47e0f97a98424992fd
builder/dali-builder.cpp
builder/dali-builder.cpp
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ //------------------------------------------------------------------------------ // // Run a json script layout file // // - watches an named file and reloads actor tree if the file changes // ie run // builder-run layout.json // // and edit layout.json in a text editor saving to trigger the reload // //------------------------------------------------------------------------------ #include <dali/dali.h> #include <dali-toolkit/dali-toolkit.h> #include <dali-toolkit/devel-api/builder/builder.h> #include <dali-toolkit/devel-api/builder/tree-node.h> #include <iostream> #include <map> #include <string> #include <fstream> #include <streambuf> #include "sys/stat.h" #include <ctime> #include <dali/integration-api/debug.h> #define TOKEN_STRING(x) #x using namespace Dali; using namespace Dali::Toolkit; namespace { std::string JSON_BROKEN(" \ { \ 'stage': \ [ \ { \ 'type':'TextActor', \ 'size': [50,50,1], \ 'parentOrigin': 'CENTER', \ 'text':'COULD NOT LOAD JSON FILE' \ } \ ] \ } \ "); std::string ReplaceQuotes(const std::string &single_quoted) { std::string s(single_quoted); // wrong as no embedded quote but had regex link problems std::replace(s.begin(), s.end(), '\'', '"'); return s; } } // anon namespace //------------------------------------------------------------------------------ // // // //------------------------------------------------------------------------------ class FileWatcher { public: FileWatcher(void); ~FileWatcher(void); explicit FileWatcher(const std::string &fn): mLastTime(0) { SetFilename(fn) ; }; void SetFilename(const std::string &fn); std::string GetFilename(); bool FileHasChanged(void); std::string GetFileContents(void) { return GetFileContents(mstringPath) ; }; private: // compiler does // FileWatcher(const FileWatcher&); // FileWatcher &operator=(const FileWatcher &); std::time_t mLastTime; std::string mstringPath; std::string GetFileContents(const std::string &fn) { std::ifstream t(fn.c_str()); return std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); }; }; FileWatcher::FileWatcher(void) : mLastTime(0) { } bool FileWatcher::FileHasChanged(void) { struct stat buf; if(0 != stat(mstringPath.c_str(), &buf)) { DALI_LOG_WARNING("File does not exist '%s'\n", mstringPath.c_str()); return false; } else { if(buf.st_mtime > mLastTime) { mLastTime = buf.st_mtime; return true; } else { mLastTime = buf.st_mtime; return false; } } return false; } FileWatcher::~FileWatcher() { } void FileWatcher::SetFilename(const std::string &fn) { mstringPath = fn; } std::string FileWatcher::GetFilename(void) { return mstringPath; } //------------------------------------------------------------------------------ // // // //------------------------------------------------------------------------------ class ExampleApp : public ConnectionTracker { public: ExampleApp(Application &app) : mApp(app) { app.InitSignal().Connect(this, &ExampleApp::Create); } ~ExampleApp() {} public: void SetJSONFilename(std::string const &fn) { fw.SetFilename(fn) ; }; void Create(Application& app) { mTimer = Timer::New( 500 ); // ms mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer); mTimer.Start(); // Connect to key events in order to exit Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent); } private: Application& mApp; Layer mRootLayer; FileWatcher fw; Timer mTimer; void ReloadJsonFile(Builder& builder, Layer& layer) { Stage stage = Stage::GetCurrent(); builder = Builder::New(); builder.QuitSignal().Connect( this, &ExampleApp::OnBuilderQuit ); Property::Map defaultDirs; defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR; defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ] = DALI_MODEL_DIR; defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR; builder.AddConstants( defaultDirs ); if(!layer) { layer = Layer::New(); layer.SetParentOrigin(ParentOrigin::CENTER); layer.SetAnchorPoint(AnchorPoint::CENTER); layer.SetSize( stage.GetRootLayer().GetCurrentSize() ); stage.GetRootLayer().Add(layer); // render tasks may have been setup last load so remove them RenderTaskList taskList = stage.GetRenderTaskList(); if( taskList.GetTaskCount() > 1 ) { typedef std::vector<RenderTask> Collection; typedef Collection::iterator ColIter; Collection tasks; for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i) { tasks.push_back( taskList.GetTask(i) ); } for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter) { taskList.RemoveTask(*iter); } RenderTask defaultTask = taskList.GetTask(0); defaultTask.SetSourceActor( stage.GetRootLayer() ); defaultTask.SetTargetFrameBuffer( FrameBufferImage() ); } } unsigned int numChildren = layer.GetChildCount(); for(unsigned int i=0; i<numChildren; ++i) { layer.Remove( layer.GetChildAt(0) ); } std::string data(fw.GetFileContents()); try { builder.LoadFromString(data); } catch(...) { builder.LoadFromString(ReplaceQuotes(JSON_BROKEN)); } builder.AddActors( layer ); } bool OnTimer(void) { if(fw.FileHasChanged()) { ReloadJsonFile( mBuilder, mRootLayer ); } return true; } // Process Key events to Quit on back-key void OnKeyEvent( const KeyEvent& event ) { if( event.state == KeyEvent::Down ) { if( IsKey( event, Dali::DALI_KEY_ESCAPE ) || IsKey( event, Dali::DALI_KEY_BACK ) ) { mApp.Quit(); } } } void OnBuilderQuit() { mApp.Quit(); } Builder mBuilder; }; //------------------------------------------------------------------------------ // // // //------------------------------------------------------------------------------ int main(int argc, char **argv) { Application dali_app = Application::New(&argc, &argv); ExampleApp app(dali_app); std::cout << "DALi Core: \t" << CORE_MAJOR_VERSION << "." << CORE_MINOR_VERSION << "." << CORE_MICRO_VERSION << " (" << CORE_BUILD_DATE << ")" << std::endl; std::cout << "DALi Adaptor: \t" << ADAPTOR_MAJOR_VERSION << "." << ADAPTOR_MINOR_VERSION << "." << ADAPTOR_MICRO_VERSION << " (" << ADAPTOR_BUILD_DATE << ")\n"; std::cout << "DALi Toolkit: \t" << Toolkit::TOOLKIT_MAJOR_VERSION << "." << Toolkit::TOOLKIT_MINOR_VERSION << "." << Toolkit::TOOLKIT_MICRO_VERSION << " (" << Toolkit::TOOLKIT_BUILD_DATE << ")\n"; if(argc > 1) { std::cout << "Loading file:" << argc << " " << argv[1] << std::endl; app.SetJSONFilename(argv[1]); } else { DALI_ASSERT_ALWAYS(!"Specify JSON file on command line\n"); } dali_app.MainLoop(); return 0; }
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ //------------------------------------------------------------------------------ // // Run a json script layout file // // - watches an named file and reloads actor tree if the file changes // ie run // builder-run layout.json // // and edit layout.json in a text editor saving to trigger the reload // //------------------------------------------------------------------------------ #include <dali/dali.h> #include <dali-toolkit/dali-toolkit.h> #include <dali-toolkit/devel-api/builder/builder.h> #include <dali-toolkit/devel-api/builder/tree-node.h> #include <iostream> #include <map> #include <string> #include <fstream> #include <streambuf> #include "sys/stat.h" #include <ctime> #include <dali/integration-api/debug.h> #define TOKEN_STRING(x) #x using namespace Dali; using namespace Dali::Toolkit; namespace { std::string JSON_BROKEN(" \ { \ 'stage': \ [ \ { \ 'type':'TextActor', \ 'size': [50,50,1], \ 'parentOrigin': 'CENTER', \ 'text':'COULD NOT LOAD JSON FILE' \ } \ ] \ } \ "); std::string ReplaceQuotes(const std::string &single_quoted) { std::string s(single_quoted); // wrong as no embedded quote but had regex link problems std::replace(s.begin(), s.end(), '\'', '"'); return s; } } // anon namespace //------------------------------------------------------------------------------ // // // //------------------------------------------------------------------------------ class FileWatcher { public: FileWatcher(void); ~FileWatcher(void); explicit FileWatcher(const std::string &fn): mLastTime(0) { SetFilename(fn) ; }; void SetFilename(const std::string &fn); std::string GetFilename(); bool FileHasChanged(void); std::string GetFileContents(void) { return GetFileContents(mstringPath) ; }; private: // compiler does // FileWatcher(const FileWatcher&); // FileWatcher &operator=(const FileWatcher &); std::time_t mLastTime; std::string mstringPath; std::string GetFileContents(const std::string &fn) { std::ifstream t(fn.c_str()); return std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); }; }; FileWatcher::FileWatcher(void) : mLastTime(0) { } bool FileWatcher::FileHasChanged(void) { struct stat buf; if(0 != stat(mstringPath.c_str(), &buf)) { DALI_LOG_WARNING("File does not exist '%s'\n", mstringPath.c_str()); return false; } else { if(buf.st_mtime > mLastTime) { mLastTime = buf.st_mtime; return true; } else { mLastTime = buf.st_mtime; return false; } } return false; } FileWatcher::~FileWatcher() { } void FileWatcher::SetFilename(const std::string &fn) { mstringPath = fn; } std::string FileWatcher::GetFilename(void) { return mstringPath; } //------------------------------------------------------------------------------ // // // //------------------------------------------------------------------------------ class ExampleApp : public ConnectionTracker { public: ExampleApp(Application &app) : mApp(app) { app.InitSignal().Connect(this, &ExampleApp::Create); } ~ExampleApp() {} public: void SetJSONFilename(std::string const &fn) { fw.SetFilename(fn) ; }; void Create(Application& app) { mTimer = Timer::New( 500 ); // ms mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer); mTimer.Start(); // Connect to key events in order to exit Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent); } private: Application& mApp; Layer mRootLayer; FileWatcher fw; Timer mTimer; void ReloadJsonFile(Builder& builder, Layer& layer) { Stage stage = Stage::GetCurrent(); stage.SetBackgroundColor( Color::WHITE ); builder = Builder::New(); builder.QuitSignal().Connect( this, &ExampleApp::OnBuilderQuit ); Property::Map defaultDirs; defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR; defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ] = DALI_MODEL_DIR; defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR; builder.AddConstants( defaultDirs ); if(!layer) { layer = Layer::New(); layer.SetParentOrigin(ParentOrigin::CENTER); layer.SetAnchorPoint(AnchorPoint::CENTER); layer.SetSize( stage.GetRootLayer().GetCurrentSize() ); stage.GetRootLayer().Add(layer); // render tasks may have been setup last load so remove them RenderTaskList taskList = stage.GetRenderTaskList(); if( taskList.GetTaskCount() > 1 ) { typedef std::vector<RenderTask> Collection; typedef Collection::iterator ColIter; Collection tasks; for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i) { tasks.push_back( taskList.GetTask(i) ); } for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter) { taskList.RemoveTask(*iter); } RenderTask defaultTask = taskList.GetTask(0); defaultTask.SetSourceActor( stage.GetRootLayer() ); defaultTask.SetTargetFrameBuffer( FrameBufferImage() ); } } unsigned int numChildren = layer.GetChildCount(); for(unsigned int i=0; i<numChildren; ++i) { layer.Remove( layer.GetChildAt(0) ); } std::string data(fw.GetFileContents()); try { builder.LoadFromString(data); } catch(...) { builder.LoadFromString(ReplaceQuotes(JSON_BROKEN)); } builder.AddActors( layer ); } bool OnTimer(void) { if(fw.FileHasChanged()) { ReloadJsonFile( mBuilder, mRootLayer ); } return true; } // Process Key events to Quit on back-key void OnKeyEvent( const KeyEvent& event ) { if( event.state == KeyEvent::Down ) { if( IsKey( event, Dali::DALI_KEY_ESCAPE ) || IsKey( event, Dali::DALI_KEY_BACK ) ) { mApp.Quit(); } } } void OnBuilderQuit() { mApp.Quit(); } Builder mBuilder; }; //------------------------------------------------------------------------------ // // // //------------------------------------------------------------------------------ int main(int argc, char **argv) { Application dali_app = Application::New(&argc, &argv); ExampleApp app(dali_app); std::cout << "DALi Core: \t" << CORE_MAJOR_VERSION << "." << CORE_MINOR_VERSION << "." << CORE_MICRO_VERSION << " (" << CORE_BUILD_DATE << ")" << std::endl; std::cout << "DALi Adaptor: \t" << ADAPTOR_MAJOR_VERSION << "." << ADAPTOR_MINOR_VERSION << "." << ADAPTOR_MICRO_VERSION << " (" << ADAPTOR_BUILD_DATE << ")\n"; std::cout << "DALi Toolkit: \t" << Toolkit::TOOLKIT_MAJOR_VERSION << "." << Toolkit::TOOLKIT_MINOR_VERSION << "." << Toolkit::TOOLKIT_MICRO_VERSION << " (" << Toolkit::TOOLKIT_BUILD_DATE << ")\n"; if(argc > 1) { std::cout << "Loading file:" << argc << " " << argv[1] << std::endl; app.SetJSONFilename(argv[1]); } else { DALI_ASSERT_ALWAYS(!"Specify JSON file on command line\n"); } dali_app.MainLoop(); return 0; }
Change dali-builder background colour to WHITE
Change dali-builder background colour to WHITE Change-Id: I42df9f8118c56a963c5f37d7a1da61d7cf72f17d
C++
apache-2.0
dalihub/dali-demo,dalihub/dali-demo,dalihub/dali-demo,dalihub/dali-demo
d74b27e1db6dcb1f68bf12cc685847180af464bc
tests/common/tree.cpp
tests/common/tree.cpp
/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "catch/catch.hpp" #include "common/tree.h" TEST_CASE("tree returns valid iterators for allocated depth levels", "[Tree]") { using namespace game; Quadtree<int> tree; tree.set_depth(3); // Check our sanity. REQUIRE(tree.level_begin(0) != tree.end()); REQUIRE(tree.level_begin(1) != tree.end()); REQUIRE(tree.level_begin(2) != tree.end()); REQUIRE(tree.level_begin(3) == tree.end()); SECTION("adding depth doesn't change previous levels") { constexpr int expect = 5; tree.level_begin(2)->val = expect; // Resize (specifically expand) the tree. tree.set_depth(4); // Make sure we actually did the allocation. REQUIRE(tree.level_begin(3) != tree.end()); REQUIRE(tree.level_begin(2)->val == expect); SECTION("subtracting depth doesn't corrupt unchanged levels") { tree.set_depth(3); REQUIRE(tree.level_begin(2)->val == expect); } } }
/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "catch/catch.hpp" #include "common/tree.h" TEST_CASE("tree returns valid iterators for allocated depth levels", "[Tree]") { using namespace game; Quadtree<int> tree; tree.set_depth(3); // Check our sanity. REQUIRE(tree.level_begin(0) != tree.end()); REQUIRE(tree.level_begin(1) != tree.end()); REQUIRE(tree.level_begin(2) != tree.end()); REQUIRE(tree.level_begin(3) == tree.end()); SECTION("adding depth doesn't change previous levels") { constexpr int expect = 5; tree.level_begin(2)->val = expect; // Resize (specifically expand) the tree. tree.set_depth(4); // Make sure we actually did the allocation. REQUIRE(tree.level_begin(3) != tree.end()); REQUIRE(tree.level_begin(2)->val == expect); SECTION("subtracting depth doesn't corrupt unchanged levels") { tree.set_depth(3); REQUIRE(tree.level_begin(2)->val == expect); } } SECTION("iterators to begin and end of level work") { // The iterator to the beginning of the first level should definitely be // equal to the very beginning of the tree. REQUIRE(tree.level_begin(0) == tree.begin()); // Level zero always contains a single node. REQUIRE(tree.level_end(0) == tree.begin()+1); // For a quadtree, the second level should start at 1 and end at 5 REQUIRE(tree.level_begin(1) == tree.begin()+1); REQUIRE(tree.level_end(1) == tree.begin()+5); REQUIRE(tree.level_begin(2) == tree.begin()+5); REQUIRE(tree.level_end(2) == tree.begin()+21); } SECTION("indexing works as expected") { constexpr int expect = 3; tree.node_at_depth(2, 0).val = expect; REQUIRE(tree.level_begin(2)->val == expect); tree.node_at_depth(0, 0).val = expect; REQUIRE(tree.level_begin(0)->val == expect); tree.node_at_depth(1, 1).val = expect; REQUIRE((tree.begin()+2)->val == expect); // This is pretty weird usage, but might be found in the wild tree.node_at_depth(0, 1).val = expect; REQUIRE(tree.level_begin(1)->val == expect); REQUIRE((tree.level_begin(0) + 1)->val == expect); // Test that same usage in a different way. tree.node_at_depth(1, 4).val = expect; REQUIRE(tree.level_begin(2)->val == expect); REQUIRE((tree.level_begin(1) + 4)->val == expect); REQUIRE((tree.level_begin(0) + 5)->val == expect); } }
Add more tests for the tree template
Add more tests for the tree template
C++
bsd-3-clause
RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine
766b6f86a61818f353460e5be013c4ef86a494f2
test/test_rand_io.cpp
test/test_rand_io.cpp
/** * Copyright 2013 Da Zheng * * This file is part of SAFSlib. * * SAFSlib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SAFSlib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SAFSlib. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/time.h> #include <stdlib.h> #include <sys/resource.h> #include <sys/mman.h> #include <string.h> #include <errno.h> #include <pthread.h> #include <assert.h> #include <numa.h> #include <numaif.h> #ifdef PROFILER #include <google/profiler.h> #endif #include <vector> #include <set> #include <iostream> #include <string> #include <deque> #include <algorithm> #define NUM_THREADS 1024 #include "workload.h" #include "thread_private.h" #include "RAID_config.h" #include "io_interface.h" #include "cache_config.h" #include "config.h" #include "debugger.h" //#define USE_PROCESS #define GC_SIZE 10000 enum { NORMAL, DIRECT, MMAP, }; struct timeval global_start; char static_buf[PAGE_SIZE * 8] __attribute__((aligned(PAGE_SIZE))); thread_private *threads[NUM_THREADS]; str2int access_methods[] = { { "normal", READ_ACCESS }, { "direct", DIRECT_ACCESS }, { "aio", AIO_ACCESS }, { "remote", REMOTE_ACCESS }, { "global_cache", GLOBAL_CACHE_ACCESS }, { "parted_global", PART_GLOBAL_ACCESS }, }; str2int workloads[] = { { "SEQ", SEQ_OFFSET }, { "RAND", RAND_OFFSET }, { "RAND_PERMUTE", RAND_PERMUTE }, { "HIT_DEFINED", HIT_DEFINED }, { "user_file", USER_FILE_WORKLOAD }, }; str2int req_buf_types[] = { { "SINGLE_LARGE", SINGLE_LARGE_BUF }, { "SINGLE_SMALL", SINGLE_SMALL_BUF }, { "MULTI", MULTI_BUF }, }; #ifdef PROFILER std::string prof_file = "rand-read.prof"; #endif test_config config; void test_config::init(const std::map<std::string, std::string> &configs) { str2int_map access_map(access_methods, sizeof(access_methods) / sizeof(access_methods[0])); str2int_map workload_map(workloads, sizeof(workloads) / sizeof(workloads[0])); str2int_map buf_type_map(req_buf_types, sizeof(req_buf_types) / sizeof(req_buf_types[0])); std::map<std::string, std::string>::const_iterator it; it = configs.find("option"); if (it != configs.end()) { access_option = access_map.map(it->second); if (access_option < 0) { fprintf(stderr, "can't find the right access option\n"); exit(1); } } it = configs.find("num_reqs"); if (it != configs.end()) { num_reqs = atoi(it->second.c_str()); } it = configs.find("threads"); if (it != configs.end()) { nthreads = atoi(it->second.c_str()); } it = configs.find("read_percent"); if (it != configs.end()) { read_ratio = (((double) atoi(it->second.c_str())) / 100); } it = configs.find("repeats"); if (it != configs.end()) { num_repeats = atoi(it->second.c_str()); } it = configs.find("entry_size"); if (it != configs.end()) { entry_size = (int) str2size(it->second); workload_gen::set_default_entry_size(entry_size); } it = configs.find("workload"); if (it != configs.end()) { workload = workload_map.map(it->second); if (workload == -1) { workload_file = it->second; } } it = configs.find("access"); if (it != configs.end()) { if(it->second.compare("read") == 0) workload_gen::set_default_access_method(READ); else if(it->second.compare("write") == 0) workload_gen::set_default_access_method(WRITE); else { fprintf(stderr, "wrong default access method\n"); exit(1); } } it = configs.find("high_prio"); if (it != configs.end()) { high_prio = true; } it = configs.find("buf_type"); if (it != configs.end()) { buf_type = buf_type_map.map(it->second); } it = configs.find("buf_size"); if (it != configs.end()) { buf_size = (int) str2size(it->second); } it = configs.find("sync"); if (it != configs.end()) { use_aio = false; } #ifdef PROFILER it = configs.find("prof"); if (it != configs.end()) { prof_file = it->second; } #endif } void test_config::print() { printf("the configuration of the test program\n"); printf("\toption: %d\n", access_option); printf("\tnum_reqs: %ld\n", num_reqs); printf("\tthreads: %d\n", nthreads); printf("\tread_ratio: %f\n", read_ratio); printf("\trepeats: %d\n", num_repeats); printf("\tentry_size: %d\n", entry_size); printf("\tworkload: %d\n", workload); printf("\thigh_prio: %d\n", high_prio); printf("\tbuf_type: %d\n", buf_type); printf("\tbuf_size: %d\n", buf_size); printf("\tsync: %d\n", !use_aio); } void test_config::print_help() { str2int_map access_map(access_methods, sizeof(access_methods) / sizeof(access_methods[0])); str2int_map workload_map(workloads, sizeof(workloads) / sizeof(workloads[0])); str2int_map buf_type_map(req_buf_types, sizeof(req_buf_types) / sizeof(req_buf_types[0])); printf("test options:\n"); access_map.print("access options: "); printf("\tnum_reqs: the number of requests generated in a workload\n"); printf("\tread_ratio: the read percentage of a synthetic workload\n"); printf("\trepeats: the number of repeats in a random permutation workload\n"); printf("\tthreads: the number of test threads\n"); printf("\tentry_size: the size of each access\n"); workload_map.print("\tworkloads: "); printf("\thigh_prio: run the test program in a higher OS priority\n"); buf_type_map.print("\tbuf types: "); printf("\tbuf_size: the buffer size for each access\n"); printf("\tsync: whether to use sync or async\n"); printf("\troot_conf: a config file to specify the root paths of the RAID\n"); } void int_handler(int sig_num) { #ifdef PROFILER if (!prof_file.empty()) ProfilerStop(); #endif #ifdef STATISTICS for (int i = 0; i < config.get_nthreads(); i++) { if (threads[i]) threads[i]->print_stat(); } print_io_thread_stat(); #endif exit(0); } const long TEST_DATA_SIZE = 15L * 1024 * 1024 * 4096; class debug_workload_gens: public debug_task { std::vector<workload_gen *> workloads; public: debug_workload_gens(const std::vector<workload_gen *> &workloads) { this->workloads = workloads; } void run() { for (unsigned i = 0; i < workloads.size(); i++) workloads[i]->print_state(); } }; int main(int argc, char *argv[]) { int ret = 0; struct timeval start_time, end_time; ssize_t read_bytes = 0; if (argc < 3) { fprintf(stderr, "there are %d argments\n", argc); fprintf(stderr, "test_rand_io conf_file data_file [conf_key=conf_value]\n"); config.print_help(); params.print_help(); exit(1); } std::string conf_file = argv[1]; std::string data_file = argv[2]; signal(SIGINT, int_handler); // The file that contains all data files. config_map configs(conf_file); configs.add_options(argv + 3, argc - 3); config.init(configs.get_options()); config.print(); printf("use a different random sequence\n"); srandom(time(NULL)); if (config.get_nthreads() > NUM_THREADS) { fprintf(stderr, "too many threads\n"); exit(1); } int remainings = config.get_num_reqs() % config.get_nthreads(); int shift = 0; long start; long end = 0; assert(config.get_nthreads() % params.get_num_nodes() == 0); init_io_system(configs); file_io_factory *factory = create_io_factory(data_file, config.get_access_option()); std::vector<int> node_id_array; for (int i = 0; i < params.get_num_nodes(); i++) node_id_array.push_back(i); int nthread_per_node = config.get_nthreads() / node_id_array.size(); std::vector<workload_gen *> workload_gens; for (unsigned i = 0; i < node_id_array.size(); i++) { int node_id = node_id_array[i]; for (int j = 0; j < nthread_per_node; j++) { /* * we still assign each thread a range regardless of the number * of threads. read_private will choose the right file descriptor * according to the offset. */ start = end; end = start + ((long) config.get_num_reqs() / config.get_nthreads() + (shift < remainings)) * PAGE_SIZE / config.get_entry_size(); if (remainings != shift) shift++; #ifdef DEBUG printf("thread %d starts %ld ends %ld\n", j, start, end); #endif workload_gen *gen; switch (config.get_workload()) { case SEQ_OFFSET: gen = new seq_workload(start, end, config.get_entry_size()); break; case RAND_OFFSET: assert(config.get_read_ratio() >= 0); gen = new rand_workload(start, end, config.get_entry_size(), end - start, (int) (config.get_read_ratio() * 100)); break; case RAND_PERMUTE: assert(config.get_read_ratio() >= 0); gen = new global_rand_permute_workload(config.get_entry_size(), (((long) config.get_num_reqs()) * PAGE_SIZE) / config.get_entry_size(), config.get_num_repeats(), config.get_read_ratio()); break; case -1: { static long length = 0; static workload_t *workloads = NULL; if (workloads == NULL) workloads = load_file_workload(config.get_workload_file(), length); long num_reqs = length; if (config.get_num_reqs() >= 0) num_reqs = min(config.get_num_reqs(), num_reqs); gen = new file_workload(workloads, num_reqs, j, config.get_nthreads(), (int) (config.get_read_ratio() * 100)); break; } default: fprintf(stderr, "unsupported workload\n"); exit(1); } workload_gens.push_back(gen); int idx = i * nthread_per_node + j; threads[idx] = new thread_private(node_id, idx, config.get_entry_size(), factory, gen); } } debug.register_task(new debug_workload_gens(workload_gens)); if (config.is_high_prio()) { ret = setpriority(PRIO_PROCESS, getpid(), -20); if (ret < 0) { perror("setpriority"); exit(1); } } gettimeofday(&start_time, NULL); global_start = start_time; #ifdef PROFILER if (!prof_file.empty()) ProfilerStart(prof_file.c_str()); #endif for (int i = 0; i < config.get_nthreads(); i++) { threads[i]->start(); } for (int i = 0; i < config.get_nthreads(); i++) { threads[i]->join(); read_bytes += threads[i]->get_read_bytes(); } #ifdef PROFILER if (!prof_file.empty()) ProfilerStop(); #endif gettimeofday(&end_time, NULL); printf("read %ld bytes, takes %f seconds\n", read_bytes, end_time.tv_sec - start_time.tv_sec + ((float)(end_time.tv_usec - start_time.tv_usec))/1000000); #ifdef STATISTICS for (int i = 0; i < config.get_nthreads(); i++) { threads[i]->print_stat(); } print_io_thread_stat(); #endif for (unsigned i = 0; i < workload_gens.size(); i++) delete workload_gens[i]; for (int i = 0; i < config.get_nthreads(); i++) delete threads[i]; destroy_io_factory(factory); }
/** * Copyright 2013 Da Zheng * * This file is part of SAFSlib. * * SAFSlib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SAFSlib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SAFSlib. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/time.h> #include <stdlib.h> #include <sys/resource.h> #include <sys/mman.h> #include <string.h> #include <errno.h> #include <pthread.h> #include <assert.h> #include <numa.h> #include <numaif.h> #ifdef PROFILER #include <google/profiler.h> #endif #include <vector> #include <set> #include <iostream> #include <string> #include <deque> #include <algorithm> #define NUM_THREADS 1024 #include "workload.h" #include "thread_private.h" #include "RAID_config.h" #include "io_interface.h" #include "cache_config.h" #include "config.h" #include "debugger.h" //#define USE_PROCESS #define GC_SIZE 10000 enum { NORMAL, DIRECT, MMAP, }; struct timeval global_start; char static_buf[PAGE_SIZE * 8] __attribute__((aligned(PAGE_SIZE))); thread_private *threads[NUM_THREADS]; str2int access_methods[] = { { "normal", READ_ACCESS }, { "direct", DIRECT_ACCESS }, { "aio", AIO_ACCESS }, { "remote", REMOTE_ACCESS }, { "global_cache", GLOBAL_CACHE_ACCESS }, { "parted_global", PART_GLOBAL_ACCESS }, }; str2int workloads[] = { { "SEQ", SEQ_OFFSET }, { "RAND", RAND_OFFSET }, { "RAND_PERMUTE", RAND_PERMUTE }, { "HIT_DEFINED", HIT_DEFINED }, { "user_file", USER_FILE_WORKLOAD }, }; str2int req_buf_types[] = { { "SINGLE_LARGE", SINGLE_LARGE_BUF }, { "SINGLE_SMALL", SINGLE_SMALL_BUF }, { "MULTI", MULTI_BUF }, }; #ifdef PROFILER std::string prof_file = "rand-read.prof"; #endif test_config config; void test_config::init(const std::map<std::string, std::string> &configs) { str2int_map access_map(access_methods, sizeof(access_methods) / sizeof(access_methods[0])); str2int_map workload_map(workloads, sizeof(workloads) / sizeof(workloads[0])); str2int_map buf_type_map(req_buf_types, sizeof(req_buf_types) / sizeof(req_buf_types[0])); std::map<std::string, std::string>::const_iterator it; it = configs.find("option"); if (it != configs.end()) { access_option = access_map.map(it->second); if (access_option < 0) { fprintf(stderr, "can't find the right access option\n"); exit(1); } } it = configs.find("num_reqs"); if (it != configs.end()) { num_reqs = atoi(it->second.c_str()); } it = configs.find("threads"); if (it != configs.end()) { nthreads = atoi(it->second.c_str()); } it = configs.find("read_percent"); if (it != configs.end()) { read_ratio = (((double) atoi(it->second.c_str())) / 100); } it = configs.find("repeats"); if (it != configs.end()) { num_repeats = atoi(it->second.c_str()); } it = configs.find("entry_size"); if (it != configs.end()) { entry_size = (int) str2size(it->second); workload_gen::set_default_entry_size(entry_size); } it = configs.find("workload"); if (it != configs.end()) { workload = workload_map.map(it->second); if (workload == -1) { workload_file = it->second; } } it = configs.find("access"); if (it != configs.end()) { if(it->second.compare("read") == 0) workload_gen::set_default_access_method(READ); else if(it->second.compare("write") == 0) workload_gen::set_default_access_method(WRITE); else { fprintf(stderr, "wrong default access method\n"); exit(1); } } it = configs.find("high_prio"); if (it != configs.end()) { high_prio = true; } it = configs.find("buf_type"); if (it != configs.end()) { buf_type = buf_type_map.map(it->second); } it = configs.find("buf_size"); if (it != configs.end()) { buf_size = (int) str2size(it->second); } it = configs.find("sync"); if (it != configs.end()) { use_aio = false; } #ifdef PROFILER it = configs.find("prof"); if (it != configs.end()) { prof_file = it->second; } #endif } void test_config::print() { printf("the configuration of the test program\n"); printf("\toption: %d\n", access_option); printf("\tnum_reqs: %ld\n", num_reqs); printf("\tthreads: %d\n", nthreads); printf("\tread_ratio: %f\n", read_ratio); printf("\trepeats: %d\n", num_repeats); printf("\tentry_size: %d\n", entry_size); printf("\tworkload: %d\n", workload); printf("\thigh_prio: %d\n", high_prio); printf("\tbuf_type: %d\n", buf_type); printf("\tbuf_size: %d\n", buf_size); printf("\tsync: %d\n", !use_aio); } void test_config::print_help() { str2int_map access_map(access_methods, sizeof(access_methods) / sizeof(access_methods[0])); str2int_map workload_map(workloads, sizeof(workloads) / sizeof(workloads[0])); str2int_map buf_type_map(req_buf_types, sizeof(req_buf_types) / sizeof(req_buf_types[0])); printf("test options:\n"); access_map.print("access options: "); printf("\tnum_reqs: the number of requests generated in a workload\n"); printf("\tread_ratio: the read percentage of a synthetic workload\n"); printf("\trepeats: the number of repeats in a random permutation workload\n"); printf("\tthreads: the number of test threads\n"); printf("\tentry_size: the size of each access\n"); workload_map.print("\tworkloads: "); printf("\thigh_prio: run the test program in a higher OS priority\n"); buf_type_map.print("\tbuf types: "); printf("\tbuf_size: the buffer size for each access\n"); printf("\tsync: whether to use sync or async\n"); printf("\troot_conf: a config file to specify the root paths of the RAID\n"); } void int_handler(int sig_num) { #ifdef PROFILER if (!prof_file.empty()) ProfilerStop(); #endif #ifdef STATISTICS for (int i = 0; i < config.get_nthreads(); i++) { if (threads[i]) threads[i]->print_stat(); } print_io_thread_stat(); #endif exit(0); } const long TEST_DATA_SIZE = 15L * 1024 * 1024 * 4096; class debug_workload_gens: public debug_task { std::vector<workload_gen *> workloads; public: debug_workload_gens(const std::vector<workload_gen *> &workloads) { this->workloads = workloads; } void run() { for (unsigned i = 0; i < workloads.size(); i++) workloads[i]->print_state(); } }; int main(int argc, char *argv[]) { int ret = 0; struct timeval start_time, end_time; ssize_t read_bytes = 0; if (argc < 3) { fprintf(stderr, "there are %d argments\n", argc); fprintf(stderr, "test_rand_io conf_file data_file [conf_key=conf_value]\n"); config.print_help(); params.print_help(); exit(1); } std::string conf_file = argv[1]; std::string data_file = argv[2]; signal(SIGINT, int_handler); // The file that contains all data files. config_map configs(conf_file); configs.add_options(argv + 3, argc - 3); config.init(configs.get_options()); config.print(); printf("use a different random sequence\n"); srandom(time(NULL)); if (config.get_nthreads() > NUM_THREADS) { fprintf(stderr, "too many threads\n"); exit(1); } int remainings = config.get_num_reqs() % config.get_nthreads(); int shift = 0; long start; long end = 0; assert(config.get_nthreads() % params.get_num_nodes() == 0); init_io_system(configs); file_io_factory *factory = create_io_factory(data_file, config.get_access_option()); std::vector<int> node_id_array; for (int i = 0; i < params.get_num_nodes(); i++) node_id_array.push_back(i); int nthread_per_node = config.get_nthreads() / node_id_array.size(); std::vector<workload_gen *> workload_gens; for (unsigned i = 0; i < node_id_array.size(); i++) { int node_id = node_id_array[i]; for (int j = 0; j < nthread_per_node; j++) { int idx = i * nthread_per_node + j; /* * we still assign each thread a range regardless of the number * of threads. read_private will choose the right file descriptor * according to the offset. */ start = end; end = start + ((long) config.get_num_reqs() / config.get_nthreads() + (shift < remainings)) * PAGE_SIZE / config.get_entry_size(); if (remainings != shift) shift++; #ifdef DEBUG printf("thread %d starts %ld ends %ld\n", j, start, end); #endif workload_gen *gen; switch (config.get_workload()) { case SEQ_OFFSET: gen = new seq_workload(start, end, config.get_entry_size()); break; case RAND_OFFSET: assert(config.get_read_ratio() >= 0); gen = new rand_workload(start, end, config.get_entry_size(), end - start, (int) (config.get_read_ratio() * 100)); break; case RAND_PERMUTE: assert(config.get_read_ratio() >= 0); gen = new global_rand_permute_workload(config.get_entry_size(), (((long) config.get_num_reqs()) * PAGE_SIZE) / config.get_entry_size(), config.get_num_repeats(), config.get_read_ratio()); break; case -1: { static long length = 0; static workload_t *workloads = NULL; if (workloads == NULL) workloads = load_file_workload(config.get_workload_file(), length); long num_reqs = length; if (config.get_num_reqs() >= 0) num_reqs = min(config.get_num_reqs(), num_reqs); gen = new file_workload(workloads, num_reqs, idx, config.get_nthreads(), (int) (config.get_read_ratio() * 100)); break; } default: fprintf(stderr, "unsupported workload\n"); exit(1); } workload_gens.push_back(gen); threads[idx] = new thread_private(node_id, idx, config.get_entry_size(), factory, gen); } } debug.register_task(new debug_workload_gens(workload_gens)); if (config.is_high_prio()) { ret = setpriority(PRIO_PROCESS, getpid(), -20); if (ret < 0) { perror("setpriority"); exit(1); } } gettimeofday(&start_time, NULL); global_start = start_time; #ifdef PROFILER if (!prof_file.empty()) ProfilerStart(prof_file.c_str()); #endif for (int i = 0; i < config.get_nthreads(); i++) { threads[i]->start(); } for (int i = 0; i < config.get_nthreads(); i++) { threads[i]->join(); read_bytes += threads[i]->get_read_bytes(); } #ifdef PROFILER if (!prof_file.empty()) ProfilerStop(); #endif gettimeofday(&end_time, NULL); printf("read %ld bytes, takes %f seconds\n", read_bytes, end_time.tv_sec - start_time.tv_sec + ((float)(end_time.tv_usec - start_time.tv_usec))/1000000); #ifdef STATISTICS for (int i = 0; i < config.get_nthreads(); i++) { threads[i]->print_stat(); } print_io_thread_stat(); #endif for (unsigned i = 0; i < workload_gens.size(); i++) delete workload_gens[i]; for (int i = 0; i < config.get_nthreads(); i++) delete threads[i]; destroy_io_factory(factory); }
fix a bug in test_rand_io for distributing workloads.
[Test-bug]: fix a bug in test_rand_io for distributing workloads. test_rand_io assigns a wrong thread id to file_workload generators. But it doesn't matter with the current implementation because the workload loaded from a file is dynamically assigned to threads.
C++
apache-2.0
icoming/FlashGraph,icoming/FlashGraph,icoming/FlashGraph,icoming/FlashX,flashxio/FlashX,zheng-da/FlashX,icoming/FlashX,silky/FlashGraph,zheng-da/FlashX,zheng-da/FlashX,flashxio/FlashX,flashxio/FlashX,icoming/FlashX,zheng-da/FlashX,silky/FlashGraph,flashxio/FlashX,zheng-da/FlashX,flashxio/FlashX,icoming/FlashGraph,silky/FlashGraph,silky/FlashGraph,icoming/FlashX,icoming/FlashX,silky/FlashGraph,icoming/FlashGraph,flashxio/FlashX
876dd67fbcf15cca3598c00bdfbedc6c8e425d6c
test/test_recheck.cpp
test/test_recheck.cpp
/* Copyright (c) 2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/time.hpp" #include "libtorrent/file.hpp" #include "libtorrent/error_code.hpp" #include <boost/tuple/tuple.hpp> #include <boost/bind.hpp> #include "test.hpp" #include "setup_transfer.hpp" #include <fstream> #include <iostream> using namespace libtorrent; const int mask = alert::all_categories & ~(alert::performance_warning | alert::stats_notification); void wait_for_complete(session& ses, torrent_handle h) { for (int i = 0; i < 200; ++i) { print_alerts(ses, "ses1"); torrent_status st = h.status(); fprintf(stderr, "%f %%\n", st.progress_ppm / 10000.f); if (st.progress_ppm == 1000000) return; test_sleep(100); } TEST_CHECK(false); } int test_main() { error_code ec; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48675, 49000), "0.0.0.0", 0, mask); create_directory("tmp1_recheck", ec); if (ec) fprintf(stderr, "create_directory: %s\n", ec.message().c_str()); std::ofstream file("tmp1_recheck/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 4 * 1024 * 1024, 7); file.close(); add_torrent_params param; param.flags &= ~add_torrent_params::flag_paused; param.flags &= ~add_torrent_params::flag_auto_managed; param.ti = t; param.save_path = "tmp1_recheck"; param.flags |= add_torrent_params::flag_seed_mode; torrent_handle tor1 = ses1.add_torrent(param, ec); if (ec) fprintf(stderr, "add_torrent: %s\n", ec.message().c_str()); wait_for_listen(ses1, "ses1"); tor1.force_recheck(); torrent_status st1 = tor1.status(); TEST_CHECK(!st1.progress_ppm < 1000000); wait_for_complete(ses1, tor1); tor1.force_recheck(); st1 = tor1.status(); TEST_CHECK(!st1.progress_ppm < 1000000); wait_for_complete(ses1, tor1); return 0; }
/* Copyright (c) 2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/time.hpp" #include "libtorrent/file.hpp" #include "libtorrent/error_code.hpp" #include <boost/tuple/tuple.hpp> #include <boost/bind.hpp> #include "test.hpp" #include "setup_transfer.hpp" #include <fstream> #include <iostream> using namespace libtorrent; const int mask = alert::all_categories & ~(alert::performance_warning | alert::stats_notification); void wait_for_complete(session& ses, torrent_handle h) { for (int i = 0; i < 50; ++i) { print_alerts(ses, "ses1"); torrent_status st = h.status(); fprintf(stderr, "%f %%\n", st.progress_ppm / 10000.f); if (st.progress_ppm == 1000000) return; test_sleep(500); } TEST_CHECK(false); } int test_main() { error_code ec; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48675, 49000), "0.0.0.0", 0, mask); create_directory("tmp1_recheck", ec); if (ec) fprintf(stderr, "create_directory: %s\n", ec.message().c_str()); std::ofstream file("tmp1_recheck/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 4 * 1024 * 1024, 7); file.close(); add_torrent_params param; param.flags &= ~add_torrent_params::flag_paused; param.flags &= ~add_torrent_params::flag_auto_managed; param.ti = t; param.save_path = "tmp1_recheck"; param.flags |= add_torrent_params::flag_seed_mode; torrent_handle tor1 = ses1.add_torrent(param, ec); if (ec) fprintf(stderr, "add_torrent: %s\n", ec.message().c_str()); wait_for_listen(ses1, "ses1"); tor1.force_recheck(); torrent_status st1 = tor1.status(); TEST_CHECK(!st1.progress_ppm < 1000000); wait_for_complete(ses1, tor1); tor1.force_recheck(); st1 = tor1.status(); TEST_CHECK(!st1.progress_ppm < 1000000); wait_for_complete(ses1, tor1); return 0; }
fix test_recheck
fix test_recheck git-svn-id: 51f496e7cf1b55ee487494d18ee2d308bae7fe77@7155 f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda
C++
bsd-3-clause
steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent
c556128fcf61e145597d919002e1ee900dfa8ea9
build/tsan_suppressions_webrtc.cc
build/tsan_suppressions_webrtc.cc
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // This file contains the WebRTC suppressions for ThreadSanitizer. // Please refer to // http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2 // for more info. #if defined(THREAD_SANITIZER) // Please make sure the code below declares a single string variable // kTSanDefaultSuppressions contains TSan suppressions delimited by newlines. // See http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2 // for the instructions on writing suppressions. char kTSanDefaultSuppressions[] = // WebRTC specific suppressions. // Split up suppressions covered previously by thread.cc and messagequeue.cc. "race:rtc::MessageQueue::Quit\n" "race:FileVideoCapturerTest::VideoCapturerListener::OnFrameCaptured\n" "race:vp8cx_remove_encoder_threads\n" // Usage of trace callback and trace level is racy in libjingle_media_unittests. // https://code.google.com/p/webrtc/issues/detail?id=3372 "race:webrtc::TraceImpl::WriteToFile\n" "race:webrtc::VideoEngine::SetTraceFilter\n" "race:webrtc::VoiceEngine::SetTraceFilter\n" "race:webrtc::Trace::set_level_filter\n" "race:webrtc::GetStaticInstance<webrtc::TraceImpl>\n" // Audio processing // https://code.google.com/p/webrtc/issues/detail?id=2521 for details. "race:webrtc/modules/audio_processing/aec/aec_core.c\n" "race:webrtc/modules/audio_processing/aec/aec_rdft.c\n" // libjingle_p2p_unittest // https://code.google.com/p/webrtc/issues/detail?id=2079 "race:webrtc/base/testclient.cc\n" "race:webrtc/base/virtualsocketserver.cc\n" "race:talk/p2p/base/stunserver_unittest.cc\n" // libjingle_unittest // https://code.google.com/p/webrtc/issues/detail?id=2080 "race:webrtc/base/logging.cc\n" "race:webrtc/base/sharedexclusivelock_unittest.cc\n" "race:webrtc/base/signalthread_unittest.cc\n" // third_party/usrsctp // TODO(jiayl): https://code.google.com/p/webrtc/issues/detail?id=3492 "race:user_sctp_timer_iterate\n" // Potential deadlocks detected after roll in r6516. // https://code.google.com/p/webrtc/issues/detail?id=3509 "deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::InputFrame\n" "deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::SetCapturer\n" "deadlock:webrtc::ProcessThreadImpl::RegisterModule\n" "deadlock:webrtc::RTCPReceiver::SetSsrcs\n" "deadlock:webrtc::RTPSenderAudio::RegisterAudioPayload\n" "deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\n" "deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\n" "deadlock:webrtc::ViECaptureImpl::ConnectCaptureDevice\n" "deadlock:webrtc::ViEChannel::StartSend\n" "deadlock:webrtc::ViECodecImpl::GetSendSideDelay\n" "deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\n" "deadlock:webrtc::ViESender::RegisterSendTransport\n" // End of suppressions. ; // Please keep this semicolon. #endif // THREAD_SANITIZER
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // This file contains the WebRTC suppressions for ThreadSanitizer. // Please refer to // http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2 // for more info. #if defined(THREAD_SANITIZER) // Please make sure the code below declares a single string variable // kTSanDefaultSuppressions contains TSan suppressions delimited by newlines. // See http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2 // for the instructions on writing suppressions. char kTSanDefaultSuppressions[] = // WebRTC specific suppressions. // Split up suppressions covered previously by thread.cc and messagequeue.cc. "race:rtc::MessageQueue::Quit\n" "race:FileVideoCapturerTest::VideoCapturerListener::OnFrameCaptured\n" "race:vp8cx_remove_encoder_threads\n" // Usage of trace callback and trace level is racy in libjingle_media_unittests. // https://code.google.com/p/webrtc/issues/detail?id=3372 "race:webrtc::TraceImpl::WriteToFile\n" "race:webrtc::VideoEngine::SetTraceFilter\n" "race:webrtc::VoiceEngine::SetTraceFilter\n" "race:webrtc::Trace::set_level_filter\n" "race:webrtc::GetStaticInstance<webrtc::TraceImpl>\n" // Audio processing // https://code.google.com/p/webrtc/issues/detail?id=2521 for details. "race:webrtc/modules/audio_processing/aec/aec_core.c\n" "race:webrtc/modules/audio_processing/aec/aec_rdft.c\n" // libjingle_p2p_unittest // https://code.google.com/p/webrtc/issues/detail?id=2079 "race:webrtc/base/testclient.cc\n" "race:webrtc/base/virtualsocketserver.cc\n" "race:talk/p2p/base/stunserver_unittest.cc\n" // libjingle_unittest // https://code.google.com/p/webrtc/issues/detail?id=2080 "race:webrtc/base/logging.cc\n" "race:webrtc/base/sharedexclusivelock_unittest.cc\n" "race:webrtc/base/signalthread_unittest.cc\n" // third_party/usrsctp // TODO(jiayl): https://code.google.com/p/webrtc/issues/detail?id=3492 "race:user_sctp_timer_iterate\n" // Potential deadlocks detected after roll in r6516. // https://code.google.com/p/webrtc/issues/detail?id=3509 "deadlock:webrtc::ProcessThreadImpl::RegisterModule\n" "deadlock:webrtc::RTCPReceiver::SetSsrcs\n" "deadlock:webrtc::RTPSenderAudio::RegisterAudioPayload\n" "deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\n" "deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\n" "deadlock:webrtc::ViECaptureImpl::ConnectCaptureDevice\n" "deadlock:webrtc::ViEChannel::StartSend\n" "deadlock:webrtc::ViECodecImpl::GetSendSideDelay\n" "deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\n" "deadlock:webrtc::ViESender::RegisterSendTransport\n" // End of suppressions. ; // Please keep this semicolon. #endif // THREAD_SANITIZER
Remove potential deadlock in WebRtcVideoEngine2.
Remove potential deadlock in WebRtcVideoEngine2. Fixes lock-order inversions between capturer's SignalVideoFrame and WebRtcVideoSendStream. Additionally also removes all deadlock suppressions for WebRtcVideoEngine2. [email protected] [email protected] BUG=1788,2999 Review URL: https://webrtc-codereview.appspot.com/26729004 git-svn-id: 03ae4fbe531b1eefc9d815f31e49022782c42458@7386 4adac7df-926f-26a2-2b94-8c16560cd09d
C++
bsd-3-clause
jchavanton/webrtc,krieger-od/webrtc,Alkalyne/webrtctrunk,krieger-od/nwjs_chromium_webrtc,krieger-od/nwjs_chromium_webrtc,krieger-od/webrtc,jchavanton/webrtc,jchavanton/webrtc,Alkalyne/webrtctrunk,krieger-od/webrtc,krieger-od/nwjs_chromium_webrtc,aleonliao/webrtc-trunk,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,PersonifyInc/chromium_webrtc,aleonliao/webrtc-trunk,krieger-od/webrtc,jchavanton/webrtc,jchavanton/webrtc,sippet/webrtc,krieger-od/webrtc,Alkalyne/webrtctrunk,PersonifyInc/chromium_webrtc,krieger-od/webrtc,PersonifyInc/chromium_webrtc,Alkalyne/webrtctrunk,sippet/webrtc,sippet/webrtc,krieger-od/nwjs_chromium_webrtc,sippet/webrtc,Alkalyne/webrtctrunk,aleonliao/webrtc-trunk,jchavanton/webrtc,PersonifyInc/chromium_webrtc,aleonliao/webrtc-trunk,Alkalyne/webrtctrunk,sippet/webrtc,jchavanton/webrtc,aleonliao/webrtc-trunk,PersonifyInc/chromium_webrtc,krieger-od/nwjs_chromium_webrtc,aleonliao/webrtc-trunk,PersonifyInc/chromium_webrtc,krieger-od/nwjs_chromium_webrtc,sippet/webrtc
501af0d2c792c404e6820fc1a8f026fa4701b767
source/solver/calc_artificial_viscosity.cpp
source/solver/calc_artificial_viscosity.cpp
// // NSolver::calc_artificial_viscosity.cpp // // Created by Lei Qiao on 15/9/2. // A work based on deal.II tutorial step-33. // #include <NSolver/solver/NSolver.h> namespace NSFEMSolver { using namespace dealii; template <int dim> void NSolver<dim>::calc_artificial_viscosity() { switch (parameters->diffusion_type) { case Parameters::AllParameters<dim>::diffu_entropy: { // Entropy viscosity FEValues<dim> fe_values (fe, quadrature, update_values | update_gradients | update_quadrature_points); const unsigned int n_q_points = quadrature.size(); const unsigned int dofs_per_cell = fe_values.dofs_per_cell; std::vector<Vector<double> > W (n_q_points, Vector<double> (EquationComponents<dim>::n_components)); std::vector<std::vector<Tensor<1,dim> > > grad_W (n_q_points, std::vector<Tensor<1,dim> > (EquationComponents<dim>::n_components)); std::vector<Vector<double> > W_old (n_q_points, Vector<double> (EquationComponents<dim>::n_components)); std::vector<types::global_dof_index> global_indices_of_local_dofs (dofs_per_cell); typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(); const typename DoFHandler<dim>::active_cell_iterator endc = dof_handler.end(); for (; cell!=endc; ++cell) { if (cell->is_locally_owned()) { fe_values.reinit (cell); fe_values.get_function_values (current_solution, W); fe_values.get_function_gradients (current_solution, grad_W); fe_values.get_function_values (old_solution, W_old); const double dt = parameters->use_local_time_step_size ? local_time_step_size[cell->active_cell_index()] : global_time_step_size; cell->get_dof_indices (global_indices_of_local_dofs); double rho_max (-1.0), D_h_max (-1.0), characteristic_speed_max (-1.0); for (unsigned int q=0; q<n_q_points; ++q) { // Here, we need to evaluate the derivatives of entropy flux respect to Euler equation independent variables $w$ // rather than the unknown vector $W$. So we have to set up a new Sacado::Fad::DFad system. std_cxx11::array<Sacado::Fad::DFad<double>, EquationComponents<dim>::n_components> w_for_entropy_flux; for (unsigned int c=0; c<EquationComponents<dim>::n_components; ++c) { w_for_entropy_flux[c] = W[q][c]; w_for_entropy_flux[c].diff (c, EquationComponents<dim>::n_components); } const Sacado::Fad::DFad<double> entropy = EulerEquations<dim>::template compute_entropy (w_for_entropy_flux); const double entroy_old = EulerEquations<dim>::template compute_entropy (W_old[q]); double D_h1 (0.0),D_h2 (0.0); D_h1 = (entropy.val() - entroy_old)/dt; D_h2 = (W[q][EquationComponents<dim>::density_component] - W_old[q][EquationComponents<dim>::density_component])/dt; //sum up divergence for (unsigned int d=0; d<dim; d++) { const Sacado::Fad::DFad<double> entropy_flux = entropy * w_for_entropy_flux[EquationComponents<dim>::first_velocity_component + d]; for (unsigned int c=0; c<EquationComponents<dim>::n_components; ++c) { D_h1 += entropy_flux.fastAccessDx (c) * grad_W[q][c][d]; } D_h2 += grad_W[q][EquationComponents<dim>::first_velocity_component + d][d] * W[q][EquationComponents<dim>::density_component] + W[q][EquationComponents<dim>::first_velocity_component + d] * grad_W[q][EquationComponents<dim>::density_component][d]; } D_h2 *= entropy.val()/W[q][EquationComponents<dim>::density_component]; D_h_max = std::max (D_h_max, std::abs (D_h1)); D_h_max = std::max (D_h_max, std::abs (D_h2)); rho_max = std::max (rho_max, W[q][EquationComponents<dim>::density_component]); const double sound_speed = EulerEquations<dim>::template compute_sound_speed (W[q]); const double velocity = EulerEquations<dim>::template compute_velocity_magnitude (W[q]); characteristic_speed_max = std::max (characteristic_speed_max, velocity + sound_speed); } const double entropy_visc = parameters->entropy_visc_cE * rho_max * std::pow (cell->diameter(), 2.0) * D_h_max; const double miu_max = parameters->entropy_visc_cLinear * cell->diameter() * rho_max * characteristic_speed_max; artificial_viscosity[cell->active_cell_index()] = std::min (miu_max, entropy_visc); } // End if cell is locally owned } // End for active cells break; } case Parameters::AllParameters<dim>::diffu_cell_size: { typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(); const typename DoFHandler<dim>::active_cell_iterator endc = dof_handler.end(); for (; cell!=endc; ++cell) { if (cell->is_locally_owned()) { artificial_viscosity[cell->active_cell_index()] = parameters->diffusion_coefficoent * std::pow (cell->diameter(), parameters->diffusion_power); } // End if cell is locally owned } // End for active cells break; } case Parameters::AllParameters<dim>::diffu_const: { std::fill (artificial_viscosity.begin(), artificial_viscosity.end(), parameters->diffusion_coefficoent); break; } default: { Assert (false, ExcNotImplemented()); break; } } // End switch case } // End function #include "NSolver.inst" }
// // NSolver::calc_artificial_viscosity.cpp // // Created by Lei Qiao on 15/9/2. // A work based on deal.II tutorial step-33. // #include <NSolver/solver/NSolver.h> namespace NSFEMSolver { using namespace dealii; template <int dim> void NSolver<dim>::calc_artificial_viscosity() { switch (parameters->diffusion_type) { case Parameters::AllParameters<dim>::diffu_entropy: { // Entropy viscosity double local_h_min (std::numeric_limits<double>::max()); if (parameters->entropy_use_global_h_min) { typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(); const typename DoFHandler<dim>::active_cell_iterator endc = dof_handler.end(); for (; cell!=endc; ++cell) { if (cell->is_locally_owned()) { local_h_min = std::min (cell->diameter(), local_h_min); } } } const double global_h_min = Utilities::MPI::min (local_h_min, mpi_communicator); // This is to say local_h_min will never be used here after. (void)local_h_min; FEValues<dim> fe_values (fe, quadrature, update_values | update_gradients | update_quadrature_points); const unsigned int n_q_points = quadrature.size(); const unsigned int dofs_per_cell = fe_values.dofs_per_cell; std::vector<Vector<double> > W (n_q_points, Vector<double> (EquationComponents<dim>::n_components)); std::vector<std::vector<Tensor<1,dim> > > grad_W (n_q_points, std::vector<Tensor<1,dim> > (EquationComponents<dim>::n_components)); std::vector<Vector<double> > W_old (n_q_points, Vector<double> (EquationComponents<dim>::n_components)); std::vector<types::global_dof_index> global_indices_of_local_dofs (dofs_per_cell); typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(); const typename DoFHandler<dim>::active_cell_iterator endc = dof_handler.end(); for (; cell!=endc; ++cell) { if (cell->is_locally_owned()) { fe_values.reinit (cell); fe_values.get_function_values (current_solution, W); fe_values.get_function_gradients (current_solution, grad_W); fe_values.get_function_values (old_solution, W_old); const double dt = parameters->use_local_time_step_size ? local_time_step_size[cell->active_cell_index()] : global_time_step_size; cell->get_dof_indices (global_indices_of_local_dofs); double rho_max (-1.0), D_h_max (-1.0), characteristic_speed_max (-1.0); for (unsigned int q=0; q<n_q_points; ++q) { // Here, we need to evaluate the derivatives of entropy flux respect to Euler equation independent variables $w$ // rather than the unknown vector $W$. So we have to set up a new Sacado::Fad::DFad system. std_cxx11::array<Sacado::Fad::DFad<double>, EquationComponents<dim>::n_components> w_for_entropy_flux; for (unsigned int c=0; c<EquationComponents<dim>::n_components; ++c) { w_for_entropy_flux[c] = W[q][c]; w_for_entropy_flux[c].diff (c, EquationComponents<dim>::n_components); } const Sacado::Fad::DFad<double> entropy = EulerEquations<dim>::template compute_entropy (w_for_entropy_flux); const double entroy_old = EulerEquations<dim>::template compute_entropy (W_old[q]); double D_h1 (0.0),D_h2 (0.0); D_h1 = (entropy.val() - entroy_old)/dt; D_h2 = (W[q][EquationComponents<dim>::density_component] - W_old[q][EquationComponents<dim>::density_component])/dt; //sum up divergence for (unsigned int d=0; d<dim; d++) { const Sacado::Fad::DFad<double> entropy_flux = entropy * w_for_entropy_flux[EquationComponents<dim>::first_velocity_component + d]; for (unsigned int c=0; c<EquationComponents<dim>::n_components; ++c) { D_h1 += entropy_flux.fastAccessDx (c) * grad_W[q][c][d]; } D_h2 += grad_W[q][EquationComponents<dim>::first_velocity_component + d][d] * W[q][EquationComponents<dim>::density_component] + W[q][EquationComponents<dim>::first_velocity_component + d] * grad_W[q][EquationComponents<dim>::density_component][d]; } D_h2 *= entropy.val()/W[q][EquationComponents<dim>::density_component]; D_h_max = std::max (D_h_max, std::abs (D_h1)); D_h_max = std::max (D_h_max, std::abs (D_h2)); rho_max = std::max (rho_max, W[q][EquationComponents<dim>::density_component]); const double sound_speed = EulerEquations<dim>::template compute_sound_speed (W[q]); const double velocity = EulerEquations<dim>::template compute_velocity_magnitude (W[q]); characteristic_speed_max = std::max (characteristic_speed_max, velocity + sound_speed); } const double h = parameters->entropy_use_global_h_min ? global_h_min : cell->diameter(); const double entropy_visc = parameters->entropy_visc_cE * rho_max * std::pow (h, 2.0) * D_h_max; const double miu_max = parameters->entropy_visc_cLinear * h * rho_max * characteristic_speed_max; artificial_viscosity[cell->active_cell_index()] = std::min (miu_max, entropy_visc); } // End if cell is locally owned } // End for active cells break; } case Parameters::AllParameters<dim>::diffu_cell_size: { typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(); const typename DoFHandler<dim>::active_cell_iterator endc = dof_handler.end(); for (; cell!=endc; ++cell) { if (cell->is_locally_owned()) { artificial_viscosity[cell->active_cell_index()] = parameters->diffusion_coefficoent * std::pow (cell->diameter(), parameters->diffusion_power); } // End if cell is locally owned } // End for active cells break; } case Parameters::AllParameters<dim>::diffu_const: { std::fill (artificial_viscosity.begin(), artificial_viscosity.end(), parameters->diffusion_coefficoent); break; } default: { Assert (false, ExcNotImplemented()); break; } } // End switch case } // End function #include "NSolver.inst" }
use paramter entropy_use_global_h_min
use paramter entropy_use_global_h_min
C++
lgpl-2.1
QiaoLei-88/NSolver,QiaoLei-88/NSolver