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
|
---|---|---|---|---|---|---|---|---|---|
5a2ee77c36b53b226851f7c93ec05baffb088eb3
|
core/src/builders/CacheBuilder.hpp
|
core/src/builders/CacheBuilder.hpp
|
#ifndef BUILDERS_CACHEBUILDER_HPP_DEFINED
#define BUILDERS_CACHEBUILDER_HPP_DEFINED
#include "builders/BuilderContext.hpp"
#include "builders/ElementBuilder.hpp"
#include "builders/EmptyBuilder.hpp"
#include "builders/MeshCache.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
namespace utymap { namespace builders {
/// Provides the way to cache element builder output.
template <typename T>
class CacheBuilder final : public ElementBuilder
{
public:
CacheBuilder(MeshCache& meshCache, const BuilderContext& context) :
ElementBuilder(context), meshCache_(meshCache) { }
void prepare() override {
if (meshCache_.fetch(context_))
builder_ = utymap::utils::make_unique<EmptyBuilder>(context_);
else
builder_ = utymap::utils::make_unique<T>(meshCache_.wrap(context_));
}
void visitNode(const utymap::entities::Node& node) override {
builder_->visitNode(node);
}
void visitWay(const utymap::entities::Way& way) override {
builder_->visitWay(way);
}
void visitArea(const utymap::entities::Area& area) override {
builder_->visitArea(area);
}
void visitRelation(const utymap::entities::Relation& relation) override {
builder_->visitRelation(relation);
}
void complete() override {
builder_->complete();
meshCache_.unwrap(context_);
}
private:
MeshCache& meshCache_;
std::unique_ptr<ElementBuilder> builder_;
};
}}
#endif // BUILDERS_CACHEBUILDER_HPP_DEFINED
|
#ifndef BUILDERS_CACHEBUILDER_HPP_DEFINED
#define BUILDERS_CACHEBUILDER_HPP_DEFINED
#include "builders/BuilderContext.hpp"
#include "builders/ElementBuilder.hpp"
#include "builders/EmptyBuilder.hpp"
#include "builders/MeshCache.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
namespace utymap { namespace builders {
/// Provides the way to cache element builder output.
template <typename T>
class CacheBuilder final : public ElementBuilder
{
public:
CacheBuilder(MeshCache& meshCache, const BuilderContext& context) :
ElementBuilder(context),
meshCache_(meshCache),
cacheContext_(meshCache_.wrap(context)) { }
void prepare() override {
if (meshCache_.fetch(context_))
builder_ = utymap::utils::make_unique<EmptyBuilder>(context_);
else
builder_ = utymap::utils::make_unique<T>(cacheContext_);
}
void visitNode(const utymap::entities::Node& node) override {
builder_->visitNode(node);
}
void visitWay(const utymap::entities::Way& way) override {
builder_->visitWay(way);
}
void visitArea(const utymap::entities::Area& area) override {
builder_->visitArea(area);
}
void visitRelation(const utymap::entities::Relation& relation) override {
builder_->visitRelation(relation);
}
void complete() override {
builder_->complete();
meshCache_.unwrap(cacheContext_);
}
private:
MeshCache& meshCache_;
BuilderContext cacheContext_;
std::unique_ptr<ElementBuilder> builder_;
};
}}
#endif // BUILDERS_CACHEBUILDER_HPP_DEFINED
|
fix issue with builder context for caching
|
core: fix issue with builder context for caching
|
C++
|
apache-2.0
|
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
|
f232f161332a6a11c387e18cba179c99783aa09f
|
cpp/src/test/utils/TestRanking.cpp
|
cpp/src/test/utils/TestRanking.cpp
|
#include <vector>
#include <gtest/gtest.h>
#include "../../main/utils/Ranking.h"
class DummyModel : public Model {
public:
DummyModel(){
scores.resize(20);
scores[9]=0.8;
scores[0]=0.6;
scores[4]=0.6;
scores[5]=0.6;
scores[8]=0.6;
scores[2]=0.5;
scores[3]=0.4;
scores[6]=0.4;
scores[7]=0.4;
scores[1]=0.3;
}
vector<double> scores;
double prediction(RecDat* rec_dat) override {
return scores[rec_dat->item];
}
void add(RecDat* recDat){
}
};
class DummyToplistModel : public Model, public TopListRecommender {
public:
DummyToplistModel(){}
double prediction(RecDat* rec_dat) override {
return 0;
}
void add(RecDat* recDat){}
vector<pair<int,double>> get_top_list(int user, int k, SpMatrix *exclude) override {
if(user == 1){
return {{1,0},{2,0},{3,0},{4,0},{5,0}};
} else if(user == 2){
return {{5,0},{4,0},{3,0},{2,0},{1,0}};
} else if(user == 3){
return {{7,0},{6,0},{1,0}};
}
throw exception(); //never happens
}
};
namespace {
class TestRankComputer : public ::testing::Test {
public:
RankComputer * rankComputer;
SpMatrix trainMatrix;
DummyModel model;
DummyToplistModel toplist_model;
vector<int> items;
vector<int> itemMap;
TopPopContainer pop;
vector<RecDat*> recDats;
TestRankComputer() {
}
virtual ~TestRankComputer() {
// You can do clean-up work that doesn't throw exceptions here.
}
virtual void SetUp(){
RankComputerParameters parameters;
parameters.top_k = 6;
parameters.random_seed = 1231232;
rankComputer = new RankComputer(¶meters);
rankComputer->set_train_matrix(&trainMatrix);
rankComputer->set_model(&model);
rankComputer->set_top_pop_container(&pop);
srand(34723892);
learn(createRecDat(2,0,0.0));
learn(createRecDat(2,1,0.0));
learn(createRecDat(2,2,0.0));
learn(createRecDat(2,3,0.0));
learn(createRecDat(2,4,0.0));
learn(createRecDat(2,5,0.0));
learn(createRecDat(2,6,0.0));
learn(createRecDat(2,7,0.0));
learn(createRecDat(2,8,0.0));
learn(createRecDat(2,9,0.0));
}
virtual void TearDown(){
delete rankComputer;
}
RecDat* createRecDat(int user, int item, double score){
RecDat* recDat = new RecDat;
recDat -> user = user;
recDat -> item = item;
recDat -> score = score;
recDats.push_back(recDat);
return recDat;
}
void learn(RecDat* recDat){
pop.increase(recDat->item);
if ((int)itemMap.size()<=recDat->item) itemMap.resize(recDat->item+1);
if (itemMap[recDat->item]==0) items.push_back(recDat->item);
itemMap[recDat->item]=1;
trainMatrix.update(recDat->user,recDat->item,recDat->score);
}
};
// class TestTopListCreator : public ::testing::Test {
// public:
// TopListCreator * topListCreator;
// SpMatrix trainMatrix;
// OnlineRecommender * recommender;
// DummyModel model;
// vector<int> items;
// vector<int> itemMap;
// vector<RecDat*> recDats;
// TestTopListCreator() {
// }
// virtual ~TestTopListCreator() {
// // You can do clean-up work that doesn't throw exceptions here.
// }
// virtual void SetUp(){
// recommender = new OnlineRecommender;
// recommender->set_model(&model);
// TopListCreatorParameters parameters;
// parameters.trainMatrix = &trainMatrix;
// parameters.recommender = recommender;
// parameters.items = &items;
// parameters.topK = 6;
// topListCreator = new TopListCreator(¶meters);
// srand(34723892);
// learn(createRecDat(2,0,0.0));
// learn(createRecDat(2,1,0.0));
// learn(createRecDat(2,2,0.0));
// learn(createRecDat(2,3,0.0));
// learn(createRecDat(2,4,0.0));
// learn(createRecDat(2,5,0.0));
// learn(createRecDat(2,6,0.0));
// learn(createRecDat(2,7,0.0));
// learn(createRecDat(2,8,0.0));
// learn(createRecDat(2,9,0.0));
// }
// virtual void TearDown(){
// delete recommender;
// delete topListCreator;
// }
// RecDat* createRecDat(int user, int item, double score){
// RecDat* recDat = new RecDat;
// recDat -> user = user;
// recDat -> item = item;
// recDat -> score = score;
// recDats.push_back(recDat);
// return recDat;
// }
// void learn(RecDat* recDat){
// if ((int)itemMap.size()<=recDat->item) itemMap.resize(recDat->item+1);
// if (itemMap[recDat->item]==0) items.push_back(recDat->item);
// itemMap[recDat->item]=1;
// trainMatrix.update(recDat->user,recDat->item,recDat->score);
// }
// };
}
TEST_F(TestRankComputer,rank) {
/*
scores[9]=0.8;
scores[0]=0.6;
scores[4]=0.6;
scores[5]=0.6;
scores[8]=0.6;
scores[2]=0.5;
scores[3]=0.4;
scores[6]=0.4;
scores[7]=0.4;
scores[1]=0.3;
*/
EXPECT_EQ(5,rankComputer->get_rank(createRecDat(2,2,0.0)));
EXPECT_EQ(0,rankComputer->get_rank(createRecDat(2,9,0.0)));
//cerr << "9: " << rankComputer->get_rank(createRecDat(2,9,0.0)) << endl;
//cerr << "0: " << rankComputer->get_rank(createRecDat(2,0,0.0)) << endl;
//cerr << "4: " << rankComputer->get_rank(createRecDat(2,4,0.0)) << endl;
//cerr << "5: " << rankComputer->get_rank(createRecDat(2,5,0.0)) << endl;
//cerr << "8: " << rankComputer->get_rank(createRecDat(2,8,0.0)) << endl;
//cerr << "2: " << rankComputer->get_rank(createRecDat(2,2,0.0)) << endl;
//cerr << "3: " << rankComputer->get_rank(createRecDat(2,3,0.0)) << endl;
//cerr << "6: " << rankComputer->get_rank(createRecDat(2,6,0.0)) << endl;
//cerr << "7: " << rankComputer->get_rank(createRecDat(2,7,0.0)) << endl;
//cerr << "1: " << rankComputer->get_rank(createRecDat(2,1,0.0)) << endl;
}
TEST_F(TestRankComputer,threshold){
EXPECT_EQ(6,rankComputer->get_rank(createRecDat(2,1,0.0)));
}
TEST_F(TestRankComputer,random){
int rank = rankComputer->get_rank(createRecDat(2,0,0.0));
EXPECT_LE(1,rank);
EXPECT_GE(4,rank);
rank = rankComputer->get_rank(createRecDat(2,4,0.0));
EXPECT_LE(1,rank);
EXPECT_GE(4,rank);
rank = rankComputer->get_rank(createRecDat(2,5,0.0));
EXPECT_LE(1,rank);
EXPECT_GE(4,rank);
rank = rankComputer->get_rank(createRecDat(2,8,0.0));
EXPECT_LE(1,rank);
EXPECT_GE(4,rank);
rank = rankComputer->get_rank(createRecDat(2,3,0.0));
EXPECT_LE(6,rank);
EXPECT_GE(8,rank);
rank = rankComputer->get_rank(createRecDat(2,6,0.0));
EXPECT_LE(6,rank);
EXPECT_GE(8,rank);
rank = rankComputer->get_rank(createRecDat(2,7,0.0));
EXPECT_LE(6,rank);
EXPECT_GE(8,rank);
}
TEST_F(TestRankComputer,testTopListRanks){
RankComputerParameters parameters;
parameters.top_k = 5;
parameters.random_seed = 1231232;
rankComputer = new RankComputer(¶meters);
rankComputer->set_train_matrix(&trainMatrix);
rankComputer->set_model(&toplist_model);
rankComputer->set_top_pop_container(&pop);
rankComputer->initialize();
EXPECT_EQ(0,rankComputer->get_rank(createRecDat(1,1,0.0)));
EXPECT_EQ(5,rankComputer->get_rank(createRecDat(1,10,0.0)));
EXPECT_EQ(5,rankComputer->get_rank(createRecDat(3,2,0.0)));
EXPECT_EQ(1,rankComputer->get_rank(createRecDat(3,6,0.0)));
EXPECT_EQ(2,rankComputer->get_rank(createRecDat(2,3,0.0)));
}
//TEST_F(TestTopListCreator,test) {
// /*
// scores[9]=0.8;
// scores[0]=0.6;
// scores[4]=0.6;
// scores[5]=0.6;
// scores[8]=0.6;
// scores[2]=0.5;
// scores[3]=0.4;
// scores[6]=0.4;
// scores[7]=0.4;
// scores[1]=0.3;
// */
// RecMap* toplist = topListCreator->getTopRecommendation(createRecDat(2,2,0.0));
// EXPECT_EQ(6,toplist->size());
// EXPECT_EQ(1,toplist->at(9));
// EXPECT_GE(1/2.0,toplist->at(0));
// EXPECT_GE(1/2.0,toplist->at(4));
// EXPECT_GE(1/2.0,toplist->at(5));
// EXPECT_GE(1/2.0,toplist->at(8));
// EXPECT_LE(1/5.0,toplist->at(0));
// EXPECT_LE(1/5.0,toplist->at(4));
// EXPECT_LE(1/5.0,toplist->at(5));
// EXPECT_LE(1/5.0,toplist->at(8));
// EXPECT_EQ(1/6.0,toplist->at(2));
//}
int main (int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#include <vector>
#include <gtest/gtest.h>
#include "../../main/utils/Ranking.h"
class DummyModel : public Model {
public:
DummyModel(){
scores.resize(20);
scores[9]=0.8;
scores[0]=0.6;
scores[4]=0.6;
scores[5]=0.6;
scores[8]=0.6;
scores[2]=0.5;
scores[3]=0.4;
scores[6]=0.4;
scores[7]=0.4;
scores[1]=0.3;
}
vector<double> scores;
double prediction(RecDat* rec_dat) override {
return scores[rec_dat->item];
}
void add(RecDat* recDat){
}
};
class DummyToplistModel : public Model, public TopListRecommender {
public:
DummyToplistModel(){}
double prediction(RecDat* rec_dat) override {
return 0;
}
void add(RecDat* recDat){}
vector<pair<int,double>> get_top_list(int user, int k, const SpMatrix *exclude) override {
if(user == 1){
return {{1,0},{2,0},{3,0},{4,0},{5,0}};
} else if(user == 2){
return {{5,0},{4,0},{3,0},{2,0},{1,0}};
} else if(user == 3){
return {{7,0},{6,0},{1,0}};
}
throw exception(); //never happens
}
};
namespace {
class TestRankComputer : public ::testing::Test {
public:
RankComputer * rankComputer;
SpMatrix trainMatrix;
DummyModel model;
DummyToplistModel toplist_model;
vector<int> items;
vector<int> itemMap;
TopPopContainer pop;
vector<RecDat*> recDats;
TestRankComputer() {
}
virtual ~TestRankComputer() {
// You can do clean-up work that doesn't throw exceptions here.
}
virtual void SetUp(){
RankComputerParameters parameters;
parameters.top_k = 6;
parameters.random_seed = 1231232;
rankComputer = new RankComputer(¶meters);
rankComputer->set_train_matrix(&trainMatrix);
rankComputer->set_model(&model);
rankComputer->set_top_pop_container(&pop);
srand(34723892);
learn(createRecDat(2,0,0.0));
learn(createRecDat(2,1,0.0));
learn(createRecDat(2,2,0.0));
learn(createRecDat(2,3,0.0));
learn(createRecDat(2,4,0.0));
learn(createRecDat(2,5,0.0));
learn(createRecDat(2,6,0.0));
learn(createRecDat(2,7,0.0));
learn(createRecDat(2,8,0.0));
learn(createRecDat(2,9,0.0));
}
virtual void TearDown(){
delete rankComputer;
}
RecDat* createRecDat(int user, int item, double score){
RecDat* recDat = new RecDat;
recDat -> user = user;
recDat -> item = item;
recDat -> score = score;
recDats.push_back(recDat);
return recDat;
}
void learn(RecDat* recDat){
pop.increase(recDat->item);
if ((int)itemMap.size()<=recDat->item) itemMap.resize(recDat->item+1);
if (itemMap[recDat->item]==0) items.push_back(recDat->item);
itemMap[recDat->item]=1;
trainMatrix.update(recDat->user,recDat->item,recDat->score);
}
};
// class TestTopListCreator : public ::testing::Test {
// public:
// TopListCreator * topListCreator;
// SpMatrix trainMatrix;
// OnlineRecommender * recommender;
// DummyModel model;
// vector<int> items;
// vector<int> itemMap;
// vector<RecDat*> recDats;
// TestTopListCreator() {
// }
// virtual ~TestTopListCreator() {
// // You can do clean-up work that doesn't throw exceptions here.
// }
// virtual void SetUp(){
// recommender = new OnlineRecommender;
// recommender->set_model(&model);
// TopListCreatorParameters parameters;
// parameters.trainMatrix = &trainMatrix;
// parameters.recommender = recommender;
// parameters.items = &items;
// parameters.topK = 6;
// topListCreator = new TopListCreator(¶meters);
// srand(34723892);
// learn(createRecDat(2,0,0.0));
// learn(createRecDat(2,1,0.0));
// learn(createRecDat(2,2,0.0));
// learn(createRecDat(2,3,0.0));
// learn(createRecDat(2,4,0.0));
// learn(createRecDat(2,5,0.0));
// learn(createRecDat(2,6,0.0));
// learn(createRecDat(2,7,0.0));
// learn(createRecDat(2,8,0.0));
// learn(createRecDat(2,9,0.0));
// }
// virtual void TearDown(){
// delete recommender;
// delete topListCreator;
// }
// RecDat* createRecDat(int user, int item, double score){
// RecDat* recDat = new RecDat;
// recDat -> user = user;
// recDat -> item = item;
// recDat -> score = score;
// recDats.push_back(recDat);
// return recDat;
// }
// void learn(RecDat* recDat){
// if ((int)itemMap.size()<=recDat->item) itemMap.resize(recDat->item+1);
// if (itemMap[recDat->item]==0) items.push_back(recDat->item);
// itemMap[recDat->item]=1;
// trainMatrix.update(recDat->user,recDat->item,recDat->score);
// }
// };
}
TEST_F(TestRankComputer,rank) {
/*
scores[9]=0.8;
scores[0]=0.6;
scores[4]=0.6;
scores[5]=0.6;
scores[8]=0.6;
scores[2]=0.5;
scores[3]=0.4;
scores[6]=0.4;
scores[7]=0.4;
scores[1]=0.3;
*/
EXPECT_EQ(5,rankComputer->get_rank(createRecDat(2,2,0.0)));
EXPECT_EQ(0,rankComputer->get_rank(createRecDat(2,9,0.0)));
//cerr << "9: " << rankComputer->get_rank(createRecDat(2,9,0.0)) << endl;
//cerr << "0: " << rankComputer->get_rank(createRecDat(2,0,0.0)) << endl;
//cerr << "4: " << rankComputer->get_rank(createRecDat(2,4,0.0)) << endl;
//cerr << "5: " << rankComputer->get_rank(createRecDat(2,5,0.0)) << endl;
//cerr << "8: " << rankComputer->get_rank(createRecDat(2,8,0.0)) << endl;
//cerr << "2: " << rankComputer->get_rank(createRecDat(2,2,0.0)) << endl;
//cerr << "3: " << rankComputer->get_rank(createRecDat(2,3,0.0)) << endl;
//cerr << "6: " << rankComputer->get_rank(createRecDat(2,6,0.0)) << endl;
//cerr << "7: " << rankComputer->get_rank(createRecDat(2,7,0.0)) << endl;
//cerr << "1: " << rankComputer->get_rank(createRecDat(2,1,0.0)) << endl;
}
TEST_F(TestRankComputer,threshold){
EXPECT_EQ(6,rankComputer->get_rank(createRecDat(2,1,0.0)));
}
TEST_F(TestRankComputer,random){
int rank = rankComputer->get_rank(createRecDat(2,0,0.0));
EXPECT_LE(1,rank);
EXPECT_GE(4,rank);
rank = rankComputer->get_rank(createRecDat(2,4,0.0));
EXPECT_LE(1,rank);
EXPECT_GE(4,rank);
rank = rankComputer->get_rank(createRecDat(2,5,0.0));
EXPECT_LE(1,rank);
EXPECT_GE(4,rank);
rank = rankComputer->get_rank(createRecDat(2,8,0.0));
EXPECT_LE(1,rank);
EXPECT_GE(4,rank);
rank = rankComputer->get_rank(createRecDat(2,3,0.0));
EXPECT_LE(6,rank);
EXPECT_GE(8,rank);
rank = rankComputer->get_rank(createRecDat(2,6,0.0));
EXPECT_LE(6,rank);
EXPECT_GE(8,rank);
rank = rankComputer->get_rank(createRecDat(2,7,0.0));
EXPECT_LE(6,rank);
EXPECT_GE(8,rank);
}
TEST_F(TestRankComputer,testTopListRanks){
RankComputerParameters parameters;
parameters.top_k = 5;
parameters.random_seed = 1231232;
rankComputer = new RankComputer(¶meters);
rankComputer->set_train_matrix(&trainMatrix);
rankComputer->set_model(&toplist_model);
rankComputer->set_top_pop_container(&pop);
rankComputer->initialize();
EXPECT_EQ(0,rankComputer->get_rank(createRecDat(1,1,0.0)));
EXPECT_EQ(5,rankComputer->get_rank(createRecDat(1,10,0.0)));
EXPECT_EQ(5,rankComputer->get_rank(createRecDat(3,2,0.0)));
EXPECT_EQ(1,rankComputer->get_rank(createRecDat(3,6,0.0)));
EXPECT_EQ(2,rankComputer->get_rank(createRecDat(2,3,0.0)));
}
//TEST_F(TestTopListCreator,test) {
// /*
// scores[9]=0.8;
// scores[0]=0.6;
// scores[4]=0.6;
// scores[5]=0.6;
// scores[8]=0.6;
// scores[2]=0.5;
// scores[3]=0.4;
// scores[6]=0.4;
// scores[7]=0.4;
// scores[1]=0.3;
// */
// RecMap* toplist = topListCreator->getTopRecommendation(createRecDat(2,2,0.0));
// EXPECT_EQ(6,toplist->size());
// EXPECT_EQ(1,toplist->at(9));
// EXPECT_GE(1/2.0,toplist->at(0));
// EXPECT_GE(1/2.0,toplist->at(4));
// EXPECT_GE(1/2.0,toplist->at(5));
// EXPECT_GE(1/2.0,toplist->at(8));
// EXPECT_LE(1/5.0,toplist->at(0));
// EXPECT_LE(1/5.0,toplist->at(4));
// EXPECT_LE(1/5.0,toplist->at(5));
// EXPECT_LE(1/5.0,toplist->at(8));
// EXPECT_EQ(1/6.0,toplist->at(2));
//}
int main (int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
fix TestRanking
|
fix TestRanking
|
C++
|
apache-2.0
|
proto-n/Alpenglow,rpalovics/Alpenglow,proto-n/Alpenglow,proto-n/Alpenglow,rpalovics/Alpenglow,rpalovics/Alpenglow
|
4b4ed354e8d6d14296d82ee32e2aa2a4a0ac0de1
|
src/HomieNode.cpp
|
src/HomieNode.cpp
|
#include "HomieNode.h"
using namespace HomieInternals;
HomieNode::HomieNode(const char* id, const char* type, NodeInputHandler inputHandler, bool subscribeToAll)
: _inputHandler(inputHandler)
, _subscriptionsCount(0)
, _subscribeToAll(subscribeToAll) {
if (strlen(id) + 1 > MAX_NODE_ID_LENGTH || strlen(type) + 1 > MAX_NODE_TYPE_LENGTH) {
Serial.println(F("β HomieNode(): either the id or type string is too long"));
abort();
}
this->_id = id;
this->_type = type;
}
void HomieNode::subscribe(const char* property, PropertyInputHandler inputHandler) {
if (this->_subscribeToAll) return;
if (strlen(property) + 1 > MAX_NODE_PROPERTY_LENGTH) {
Serial.println(F("β subscribe(): the property string is too long"));
abort();
}
if (this->_subscriptionsCount > MAX_SUBSCRIPTIONS_COUNT_PER_NODE) {
Serial.println(F("β subscribe(): the max subscription count has been reached"));
abort();
}
Subscription subscription;
strcpy(subscription.property, property);
subscription.inputHandler = inputHandler;
this->_subscriptions[this->_subscriptionsCount++] = subscription;
}
const char* HomieNode::getId() const {
return this->_id;
}
const char* HomieNode::getType() const {
return this->_type;
}
const Subscription* HomieNode::getSubscriptions() const {
return this->_subscriptions;
}
unsigned char HomieNode::getSubscriptionsCount() const {
return this->_subscriptionsCount;
}
bool HomieNode::getSubscribeToAll() const {
return this->_subscribeToAll;
}
NodeInputHandler HomieNode::getInputHandler() const {
return this->_inputHandler;
}
|
#include "HomieNode.h"
using namespace HomieInternals;
HomieNode::HomieNode(const char* id, const char* type, NodeInputHandler inputHandler, bool subscribeToAll)
: _inputHandler(inputHandler)
, _subscriptionsCount(0)
, _subscribeToAll(subscribeToAll) {
if (strlen(id) + 1 > MAX_NODE_ID_LENGTH || strlen(type) + 1 > MAX_NODE_TYPE_LENGTH) {
Serial.println(F("β HomieNode(): either the id or type string is too long"));
abort();
}
this->_id = id;
this->_type = type;
}
void HomieNode::subscribe(const char* property, PropertyInputHandler inputHandler) {
if (strlen(property) + 1 > MAX_NODE_PROPERTY_LENGTH) {
Serial.println(F("β subscribe(): the property string is too long"));
abort();
}
if (this->_subscriptionsCount > MAX_SUBSCRIPTIONS_COUNT_PER_NODE) {
Serial.println(F("β subscribe(): the max subscription count has been reached"));
abort();
}
Subscription subscription;
strcpy(subscription.property, property);
subscription.inputHandler = inputHandler;
this->_subscriptions[this->_subscriptionsCount++] = subscription;
}
const char* HomieNode::getId() const {
return this->_id;
}
const char* HomieNode::getType() const {
return this->_type;
}
const Subscription* HomieNode::getSubscriptions() const {
return this->_subscriptions;
}
unsigned char HomieNode::getSubscriptionsCount() const {
return this->_subscriptionsCount;
}
bool HomieNode::getSubscribeToAll() const {
return this->_subscribeToAll;
}
NodeInputHandler HomieNode::getInputHandler() const {
return this->_inputHandler;
}
|
Allow individual subscribes along with global subscribe
|
Allow individual subscribes along with global subscribe
|
C++
|
mit
|
marvinroger/homie-esp8266,euphi/homie-esp8266,euphi/homie-esp8266,marvinroger/homie-esp8266,marvinroger/homie-esp8266,euphi/homie-esp8266,marvinroger/homie-esp8266,euphi/homie-esp8266
|
60bedadf1ea86aa519f409b591c4952651b9c64f
|
src/NodeArray.cpp
|
src/NodeArray.cpp
|
#include "NodeArray.h"
#include <glm/gtc/packing.hpp>
#include <algorithm>
#include <cassert>
#include <sstream>
using namespace std;
NodeArray::NodeArray() : size_method(SizeMethod::CONSTANT, 1.0f) {
}
std::string
NodeArray::getNodeLabel(int node_id) const {
string label, uname, name;
long long id = 0;
auto & nd = getNodeData(node_id);
NodeType type = nd.type;
assert(type != NODE_ANY_MALE && type != NODE_ANY_FEMALE && type != NODE_ANY_PAGE &&
type != NODE_TOKEN && type != NODE_USER);
if (type == NODE_COMMUNITY) return "";
else if (type == NODE_LANG_ATTRIBUTE) return "(language)";
else if (type == NODE_ATTRIBUTE) return "(attr)";
if (label_method.getValue() == LabelMethod::AUTOMATIC_LABEL) {
for (auto & cd : getTable().getColumns()) {
auto & n = cd.first;
if (strcasecmp(n.c_str(), "label") == 0) {
label = cd.second->getText(node_id);
} else if (strcasecmp(n.c_str(), "uname") == 0) {
uname = cd.second->getText(node_id);
} else if (strcasecmp(n.c_str(), "name") == 0) {
name = cd.second->getText(node_id);
} else if (strcasecmp(n.c_str(), "id") == 0) {
id = cd.second->getInt64(node_id);
}
}
}
if (label_method.getValue() == LabelMethod::LABEL_FROM_COLUMN) {
label = getTable()[label_method.getColumn()].getText(node_id);
} else if (label_method.getValue() == LabelMethod::AUTOMATIC_LABEL && label.empty()) {
int source_id = getTable()["source"].getInt(node_id);
bool is_vimeo = source_id == 13 || source_id == 18 || source_id == 69;
if (!uname.empty() && type != NODE_URL && type != NODE_IMAGE && !is_vimeo) {
label = uname;
} else if (!name.empty()) {
label = name;
} else if (!uname.empty()) {
label = uname;
} else if (id) {
label = to_string(id);
}
}
return label;
}
static table::Column * sort_col = 0;
static bool compareRows(const int & a, const int & b) {
return sort_col->compare(a, b);
}
void
NodeArray::setLabelTexture(const skey & key, int texture) {
auto it2 = getNodeCache().find(key);
if (it2 != getNodeCache().end()) {
setLabelTexture(it2->second, texture);
}
}
void
NodeArray::setRandomPosition(int node_id, bool use_2d) {
glm::vec3 v1( 256.0f * rand() / RAND_MAX - 128.0f,
256.0f * rand() / RAND_MAX - 128.0f,
use_2d ? 0.0f : 256.0f * rand() / RAND_MAX - 128.0f
);
setPosition(node_id, v1);
}
int
NodeArray::createNode2D(double x, double y) {
ostringstream key;
key << x << "/" << y;
map<string, int>::iterator it = node_position_cache.find(key.str());
if (it != node_position_cache.end()) {
return it->second;
} else {
int node_id = node_position_cache[key.str()] = add();
setPosition(node_id, glm::vec3(x, y, 0.0f));
return node_id;
}
}
int
NodeArray::createNode3D(double x, double y, double z) {
ostringstream key;
key << x << "/" << y << "/" << z;
map<string, int>::iterator it = node_position_cache.find(key.str());
if (it != node_position_cache.end()) {
return it->second;
} else {
int node_id = node_position_cache[key.str()] = add();
setPosition(node_id, glm::vec3(x, y, z));
return node_id;
}
}
bool
NodeArray::hasNode(double x, double y, int * r) const {
ostringstream key;
key << x << "/" << y;
auto it = node_position_cache.find(key.str());
if (it != node_position_cache.end()) {
if (r) *r = it->second;
return true;
} else {
return false;
}
}
pair<int, int>
NodeArray::createNodesForArc(const ArcData2D & arc, bool rev) {
assert(arc.data.size() >= 2);
auto & v1 = arc.data.front();
auto & v2 = arc.data.back();
int node1 = createNode2D(v1.x, v1.y);
int node2 = createNode2D(v2.x, v2.y);
assert(node1 >= 0 && node2 >= 0);
if (rev) {
return pair<int, int>(node1, node2);
} else {
return pair<int, int>(node2, node1);
}
}
|
#include "NodeArray.h"
#include <glm/gtc/packing.hpp>
#include <algorithm>
#include <cassert>
#include <sstream>
using namespace std;
NodeArray::NodeArray() : size_method(SizeMethod::CONSTANT, 1.0f) {
}
std::string
NodeArray::getNodeLabel(int node_id) const {
string label, uname, name;
long long id = 0;
auto & nd = getNodeData(node_id);
NodeType type = nd.type;
assert(type != NODE_ANY_MALE && type != NODE_ANY_FEMALE && type != NODE_ANY_PAGE &&
type != NODE_TOKEN && type != NODE_USER);
if (type == NODE_COMMUNITY) return "";
else if (type == NODE_LANG_ATTRIBUTE) return "(language)";
else if (type == NODE_ATTRIBUTE) return "(attr)";
if (label_method.getValue() == LabelMethod::AUTOMATIC_LABEL) {
for (auto & cd : getTable().getColumns()) {
auto & n = cd.first;
if (strcasecmp(n.c_str(), "label") == 0) {
label = cd.second->getText(node_id);
} else if (strcasecmp(n.c_str(), "uname") == 0) {
uname = cd.second->getText(node_id);
} else if (strcasecmp(n.c_str(), "name") == 0) {
name = cd.second->getText(node_id);
} else if (strcasecmp(n.c_str(), "id") == 0) {
id = cd.second->getInt64(node_id);
}
}
}
if (label_method.getValue() == LabelMethod::LABEL_FROM_COLUMN) {
label = getTable()[label_method.getColumn()].getText(node_id);
} else if (label_method.getValue() == LabelMethod::AUTOMATIC_LABEL && label.empty()) {
int source_id = getTable()["source"].getInt(node_id);
bool is_vimeo = source_id == 13 || source_id == 18 || source_id == 69;
if (!uname.empty() && type != NODE_URL && type != NODE_IMAGE && !is_vimeo) {
label = uname;
} else if (!name.empty()) {
label = name;
} else if (!uname.empty()) {
label = uname;
} else if (id) {
label = to_string(id);
}
}
return label;
}
#if 0
static table::ColumnBase * sort_col = 0;
static bool compareRows(const int & a, const int & b) {
return sort_col->compare(a, b);
}
#endif
void
NodeArray::setLabelTexture(const skey & key, int texture) {
auto it2 = getNodeCache().find(key);
if (it2 != getNodeCache().end()) {
setLabelTexture(it2->second, texture);
}
}
void
NodeArray::setRandomPosition(int node_id, bool use_2d) {
glm::vec3 v1( 256.0f * rand() / RAND_MAX - 128.0f,
256.0f * rand() / RAND_MAX - 128.0f,
use_2d ? 0.0f : 256.0f * rand() / RAND_MAX - 128.0f
);
setPosition(node_id, v1);
}
int
NodeArray::createNode2D(double x, double y) {
ostringstream key;
key << x << "/" << y;
map<string, int>::iterator it = node_position_cache.find(key.str());
if (it != node_position_cache.end()) {
return it->second;
} else {
int node_id = node_position_cache[key.str()] = add();
setPosition(node_id, glm::vec3(x, y, 0.0f));
return node_id;
}
}
int
NodeArray::createNode3D(double x, double y, double z) {
ostringstream key;
key << x << "/" << y << "/" << z;
map<string, int>::iterator it = node_position_cache.find(key.str());
if (it != node_position_cache.end()) {
return it->second;
} else {
int node_id = node_position_cache[key.str()] = add();
setPosition(node_id, glm::vec3(x, y, z));
return node_id;
}
}
bool
NodeArray::hasNode(double x, double y, int * r) const {
ostringstream key;
key << x << "/" << y;
auto it = node_position_cache.find(key.str());
if (it != node_position_cache.end()) {
if (r) *r = it->second;
return true;
} else {
return false;
}
}
pair<int, int>
NodeArray::createNodesForArc(const ArcData2D & arc, bool rev) {
assert(arc.data.size() >= 2);
auto & v1 = arc.data.front();
auto & v2 = arc.data.back();
int node1 = createNode2D(v1.x, v1.y);
int node2 = createNode2D(v2.x, v2.y);
assert(node1 >= 0 && node2 >= 0);
if (rev) {
return pair<int, int>(node1, node2);
} else {
return pair<int, int>(node2, node1);
}
}
|
disable some code
|
disable some code
|
C++
|
mit
|
Sometrik/graphlib,Sometrik/graphlib
|
dca6be41c11e9befaa3067564a2de124190c79fe
|
src/SSEServer.cpp
|
src/SSEServer.cpp
|
#include <stdlib.h>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include "Common.h"
#include "SSEServer.h"
#include "SSEClient.h"
#include "HTTPRequest.h"
#include "HTTPResponse.h"
#include "SSEEvent.h"
#include "SSEConfig.h"
#include "SSEChannel.h"
#include "InputSources/amqp/AmqpInputSource.h"
using namespace std;
/**
Constructor.
@param config Pointer to SSEConfig object holding our configuration.
*/
SSEServer::SSEServer(SSEConfig *config) {
_config = config;
stats.Init(_config, this);
}
/**
Destructor.
*/
SSEServer::~SSEServer() {
DLOG(INFO) << "SSEServer destructor called.";
pthread_cancel(_routerthread.native_handle());
close(_serversocket);
close(_efd);
}
bool SSEServer::Broadcast(SSEEvent& event) {
SSEChannel* ch;
const string& chName = event.getpath();
ch = GetChannel(chName, _config->GetValueBool("server.allowUndefinedChannels"));
if (ch == NULL) {
LOG(ERROR) << "Discarding event recieved on invalid channel: " << chName;
return false;
}
ch->BroadcastEvent(&event);
return true;
}
/**
Handle POST requests.
@param client Pointer to SSEClient initiating the request.
@param req Pointer to HTTPRequest.
**/
void SSEServer::PostHandler(SSEClient* client, HTTPRequest* req) {
SSEEvent event(req->GetPostData());
const string& chName = req->GetPath().substr(1);
// Invalid format.
if (!event.compile()) {
HTTPResponse res(400);
client->Send(res.Get());
return;
}
// Check if channel exist.
SSEChannel* ch = GetChannel(chName,
_config->GetValueBool("server.allowUndefinedChannels"));
if (ch == NULL) {
HTTPResponse res(404);
client->Send(res.Get());
return;
}
// Set the event path to the endpoint we recieved the POST on.
event.setpath(chName);
// Client unauthorized.
if (!ch->IsAllowedToPublish(client)) {
HTTPResponse res(403);
client->Send(res.Get());
return;
}
// Broacast the event.
Broadcast(event);
// Event broadcasted OK.
HTTPResponse res(200);
client->Send(res.Get());
}
/**
Start the server.
*/
void SSEServer::Run() {
InitSocket();
_datasource = boost::shared_ptr<SSEInputSource>(new AmqpInputSource());
_datasource->Init(this);
_datasource->Run();
InitChannels();
_routerthread = boost::thread(&SSEServer::ClientRouterLoop, this);
AcceptLoop();
}
/**
Initialize server socket.
*/
void SSEServer::InitSocket() {
int on = 1;
/* Ignore SIGPIPE. */
signal(SIGPIPE, SIG_IGN);
/* Set up listening socket. */
_serversocket = socket(AF_INET, SOCK_STREAM, 0);
LOG_IF(FATAL, _serversocket == -1) << "Error creating listening socket.";
/* Reuse port and address. */
setsockopt(_serversocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
memset((char*)&_sin, '\0', sizeof(_sin));
_sin.sin_family = AF_INET;
_sin.sin_port = htons(_config->GetValueInt("server.port"));
LOG_IF(FATAL, (bind(_serversocket, (struct sockaddr*)&_sin, sizeof(_sin))) == -1) <<
"Could not bind server socket to " << _config->GetValue("server.bindip") << ":" << _config->GetValue("server.port");
LOG_IF(FATAL, (listen(_serversocket, 0)) == -1) << "Call to listen() failed.";
LOG(INFO) << "Listening on " << _config->GetValue("server.bindip") << ":" << _config->GetValue("server.port");
_efd = epoll_create1(0);
LOG_IF(FATAL, _efd == -1) << "epoll_create1 failed.";
}
/**
Initialize static configured channels.
*/
void SSEServer::InitChannels() {
BOOST_FOREACH(ChannelMap_t::value_type& chConf, _config->GetChannels()) {
SSEChannel* ch = new SSEChannel(chConf.second, chConf.first);
_channels.push_back(SSEChannelPtr(ch));
}
}
/**
Get instance pointer to SSEChannel object from id if it exists.
@param The id/path of the channel you want to get a instance pointer to.
*/
SSEChannel* SSEServer::GetChannel(const string id, bool create=false) {
SSEChannelList::iterator it;
SSEChannel* ch = NULL;
for (it = _channels.begin(); it != _channels.end(); it++) {
SSEChannel* chan = static_cast<SSEChannel*>((*it).get());
if (chan->GetId().compare(id) == 0) {
return chan;
}
}
if (create) {
ch = new SSEChannel(_config->GetDefaultChannelConfig(), id);
_channels.push_back(SSEChannelPtr(ch));
}
return ch;
}
/**
Returns a const reference to the channel list.
*/
const SSEChannelList& SSEServer::GetChannelList() {
return _channels;
}
/**
Returns the SSEConfig object.
*/
SSEConfig* SSEServer::GetConfig() {
return _config;
}
/**
Accept new client connections.
*/
void SSEServer::AcceptLoop() {
while(!stop) {
struct sockaddr_in csin;
socklen_t clen;
int tmpfd;
memset((char*)&csin, '\0', sizeof(csin));
clen = sizeof(csin);
// Accept the connection.
tmpfd = accept(_serversocket, (struct sockaddr*)&csin, &clen);
/* Got an error ? Handle it. */
if (tmpfd == -1) {
switch (errno) {
case EMFILE:
LOG(ERROR) << "All connections available used. Exiting.";
// As a safety measure exit when we have no more filehandles available on the system.
// This is a sign that something is wrong and we are better off handling it this way, atleast for now.
exit(1);
break;
default:
LOG_IF(ERROR, !stop) << "Error in accept(): " << strerror(errno);
}
continue; /* Try again. */
}
// Set non-blocking on client socket.
fcntl(tmpfd, F_SETFL, O_NONBLOCK);
// Add it to our epoll eventlist.
SSEClient* client = new SSEClient(tmpfd, &csin);
struct epoll_event event;
event.events = EPOLLIN | EPOLLRDHUP | EPOLLHUP | EPOLLERR;
event.data.ptr = static_cast<SSEClient*>(client);
int ret = epoll_ctl(_efd, EPOLL_CTL_ADD, tmpfd, &event);
if (ret == -1) {
LOG(ERROR) << "Could not add client to epoll eventlist: " << strerror(errno);
client->Destroy();
continue;
}
}
}
/**
Remove socket from epoll fd set.
@param fd File descriptor to remove.
**/
void SSEServer::RemoveSocket(int fd) {
epoll_ctl(_efd, EPOLL_CTL_DEL, fd, NULL);
}
/**
Read request and route client to the requested channel.
*/
void SSEServer::ClientRouterLoop() {
char buf[4096];
boost::shared_ptr<struct epoll_event[]> eventList(new struct epoll_event[MAXEVENTS]);
LOG(INFO) << "Started client router thread.";
while(1) {
int n = epoll_wait(_efd, eventList.get(), MAXEVENTS, -1);
for (int i = 0; i < n; i++) {
SSEClient* client;
client = static_cast<SSEClient*>(eventList[i].data.ptr);
// Close socket if an error occurs.
if (eventList[i].events & EPOLLERR) {
DLOG(WARNING) << "Error occurred while reading data from client " << client->GetIP() << ".";
RemoveSocket(client->Getfd());
client->Destroy();
stats.router_read_errors++;
continue;
}
if ((eventList[i].events & EPOLLHUP) || (eventList[i].events & EPOLLRDHUP)) {
DLOG(WARNING) << "Client " << client->GetIP() << " hung up in router thread.";
RemoveSocket(client->Getfd());
client->Destroy();
continue;
}
// Read from client.
size_t len = client->Read(&buf, 4096);
if (len <= 0) {
stats.router_read_errors++;
RemoveSocket(client->Getfd());
client->Destroy();
continue;
}
buf[len] = '\0';
// Parse the request.
HTTPRequest* req = client->GetHttpReq();
HttpReqStatus reqRet = req->Parse(buf, len);
switch(reqRet) {
case HTTP_REQ_INCOMPLETE: continue;
case HTTP_REQ_FAILED:
RemoveSocket(client->Getfd());
client->Destroy();
stats.invalid_http_req++;
continue;
case HTTP_REQ_TO_BIG:
RemoveSocket(client->Getfd());
client->Destroy();
stats.oversized_http_req++;
continue;
case HTTP_REQ_OK: break;
case HTTP_REQ_POST_INVALID_LENGTH:
{ HTTPResponse res(411, "", false); client->Send(res.Get()); }
RemoveSocket(client->Getfd());
client->Destroy();
continue;
case HTTP_REQ_POST_TOO_LARGE:
DLOG(INFO) << "Client " << client->GetIP() << " sent too much POST data.";
{ HTTPResponse res(413, "", false); client->Send(res.Get()); }
RemoveSocket(client->Getfd());
client->Destroy();
continue;
case HTTP_REQ_POST_START:
{ HTTPResponse res(100, "", false); client->Send(res.Get()); }
continue;
case HTTP_REQ_POST_INCOMPLETE: continue;
case HTTP_REQ_POST_OK:
RemoveSocket(client->Getfd());
PostHandler(client, req);
client->Destroy();
continue;
}
if (!req->GetPath().empty()) {
// Handle /stats endpoint.
if (req->GetPath().compare("/stats") == 0) {
stats.SendToClient(client);
continue;
}
string chName = req->GetPath().substr(1);
SSEChannel *ch = GetChannel(chName);
DLOG(INFO) << "Channel: " << chName;
if (ch != NULL) {
RemoveSocket(client->Getfd());
ch->AddClient(client, req);
} else {
HTTPResponse res;
res.SetBody("Channel does not exist.\n");
client->Send(res.Get());
RemoveSocket(client->Getfd());
client->Destroy();
}
}
}
}
}
|
#include <stdlib.h>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include "Common.h"
#include "SSEServer.h"
#include "SSEClient.h"
#include "HTTPRequest.h"
#include "HTTPResponse.h"
#include "SSEEvent.h"
#include "SSEConfig.h"
#include "SSEChannel.h"
#include "InputSources/amqp/AmqpInputSource.h"
using namespace std;
/**
Constructor.
@param config Pointer to SSEConfig object holding our configuration.
*/
SSEServer::SSEServer(SSEConfig *config) {
_config = config;
stats.Init(_config, this);
}
/**
Destructor.
*/
SSEServer::~SSEServer() {
DLOG(INFO) << "SSEServer destructor called.";
pthread_cancel(_routerthread.native_handle());
close(_serversocket);
close(_efd);
}
bool SSEServer::Broadcast(SSEEvent& event) {
SSEChannel* ch;
const string& chName = event.getpath();
ch = GetChannel(chName, _config->GetValueBool("server.allowUndefinedChannels"));
if (ch == NULL) {
LOG(ERROR) << "Discarding event recieved on invalid channel: " << chName;
return false;
}
ch->BroadcastEvent(&event);
return true;
}
/**
Handle POST requests.
@param client Pointer to SSEClient initiating the request.
@param req Pointer to HTTPRequest.
**/
void SSEServer::PostHandler(SSEClient* client, HTTPRequest* req) {
SSEEvent event(req->GetPostData());
const string& chName = req->GetPath().substr(1);
// Set the event path to the endpoint we recieved the POST on.
event.setpath(chName);
// Invalid format.
if (!event.compile()) {
HTTPResponse res(400);
client->Send(res.Get());
return;
}
// Check if channel exist.
SSEChannel* ch = GetChannel(chName,
_config->GetValueBool("server.allowUndefinedChannels"));
if (ch == NULL) {
HTTPResponse res(404);
client->Send(res.Get());
return;
}
// Client unauthorized.
if (!ch->IsAllowedToPublish(client)) {
HTTPResponse res(403);
client->Send(res.Get());
return;
}
// Broacast the event.
Broadcast(event);
// Event broadcasted OK.
HTTPResponse res(200);
client->Send(res.Get());
}
/**
Start the server.
*/
void SSEServer::Run() {
InitSocket();
_datasource = boost::shared_ptr<SSEInputSource>(new AmqpInputSource());
_datasource->Init(this);
_datasource->Run();
InitChannels();
_routerthread = boost::thread(&SSEServer::ClientRouterLoop, this);
AcceptLoop();
}
/**
Initialize server socket.
*/
void SSEServer::InitSocket() {
int on = 1;
/* Ignore SIGPIPE. */
signal(SIGPIPE, SIG_IGN);
/* Set up listening socket. */
_serversocket = socket(AF_INET, SOCK_STREAM, 0);
LOG_IF(FATAL, _serversocket == -1) << "Error creating listening socket.";
/* Reuse port and address. */
setsockopt(_serversocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
memset((char*)&_sin, '\0', sizeof(_sin));
_sin.sin_family = AF_INET;
_sin.sin_port = htons(_config->GetValueInt("server.port"));
LOG_IF(FATAL, (bind(_serversocket, (struct sockaddr*)&_sin, sizeof(_sin))) == -1) <<
"Could not bind server socket to " << _config->GetValue("server.bindip") << ":" << _config->GetValue("server.port");
LOG_IF(FATAL, (listen(_serversocket, 0)) == -1) << "Call to listen() failed.";
LOG(INFO) << "Listening on " << _config->GetValue("server.bindip") << ":" << _config->GetValue("server.port");
_efd = epoll_create1(0);
LOG_IF(FATAL, _efd == -1) << "epoll_create1 failed.";
}
/**
Initialize static configured channels.
*/
void SSEServer::InitChannels() {
BOOST_FOREACH(ChannelMap_t::value_type& chConf, _config->GetChannels()) {
SSEChannel* ch = new SSEChannel(chConf.second, chConf.first);
_channels.push_back(SSEChannelPtr(ch));
}
}
/**
Get instance pointer to SSEChannel object from id if it exists.
@param The id/path of the channel you want to get a instance pointer to.
*/
SSEChannel* SSEServer::GetChannel(const string id, bool create=false) {
SSEChannelList::iterator it;
SSEChannel* ch = NULL;
for (it = _channels.begin(); it != _channels.end(); it++) {
SSEChannel* chan = static_cast<SSEChannel*>((*it).get());
if (chan->GetId().compare(id) == 0) {
return chan;
}
}
if (create) {
ch = new SSEChannel(_config->GetDefaultChannelConfig(), id);
_channels.push_back(SSEChannelPtr(ch));
}
return ch;
}
/**
Returns a const reference to the channel list.
*/
const SSEChannelList& SSEServer::GetChannelList() {
return _channels;
}
/**
Returns the SSEConfig object.
*/
SSEConfig* SSEServer::GetConfig() {
return _config;
}
/**
Accept new client connections.
*/
void SSEServer::AcceptLoop() {
while(!stop) {
struct sockaddr_in csin;
socklen_t clen;
int tmpfd;
memset((char*)&csin, '\0', sizeof(csin));
clen = sizeof(csin);
// Accept the connection.
tmpfd = accept(_serversocket, (struct sockaddr*)&csin, &clen);
/* Got an error ? Handle it. */
if (tmpfd == -1) {
switch (errno) {
case EMFILE:
LOG(ERROR) << "All connections available used. Exiting.";
// As a safety measure exit when we have no more filehandles available on the system.
// This is a sign that something is wrong and we are better off handling it this way, atleast for now.
exit(1);
break;
default:
LOG_IF(ERROR, !stop) << "Error in accept(): " << strerror(errno);
}
continue; /* Try again. */
}
// Set non-blocking on client socket.
fcntl(tmpfd, F_SETFL, O_NONBLOCK);
// Add it to our epoll eventlist.
SSEClient* client = new SSEClient(tmpfd, &csin);
struct epoll_event event;
event.events = EPOLLIN | EPOLLRDHUP | EPOLLHUP | EPOLLERR;
event.data.ptr = static_cast<SSEClient*>(client);
int ret = epoll_ctl(_efd, EPOLL_CTL_ADD, tmpfd, &event);
if (ret == -1) {
LOG(ERROR) << "Could not add client to epoll eventlist: " << strerror(errno);
client->Destroy();
continue;
}
}
}
/**
Remove socket from epoll fd set.
@param fd File descriptor to remove.
**/
void SSEServer::RemoveSocket(int fd) {
epoll_ctl(_efd, EPOLL_CTL_DEL, fd, NULL);
}
/**
Read request and route client to the requested channel.
*/
void SSEServer::ClientRouterLoop() {
char buf[4096];
boost::shared_ptr<struct epoll_event[]> eventList(new struct epoll_event[MAXEVENTS]);
LOG(INFO) << "Started client router thread.";
while(1) {
int n = epoll_wait(_efd, eventList.get(), MAXEVENTS, -1);
for (int i = 0; i < n; i++) {
SSEClient* client;
client = static_cast<SSEClient*>(eventList[i].data.ptr);
// Close socket if an error occurs.
if (eventList[i].events & EPOLLERR) {
DLOG(WARNING) << "Error occurred while reading data from client " << client->GetIP() << ".";
RemoveSocket(client->Getfd());
client->Destroy();
stats.router_read_errors++;
continue;
}
if ((eventList[i].events & EPOLLHUP) || (eventList[i].events & EPOLLRDHUP)) {
DLOG(WARNING) << "Client " << client->GetIP() << " hung up in router thread.";
RemoveSocket(client->Getfd());
client->Destroy();
continue;
}
// Read from client.
size_t len = client->Read(&buf, 4096);
if (len <= 0) {
stats.router_read_errors++;
RemoveSocket(client->Getfd());
client->Destroy();
continue;
}
buf[len] = '\0';
// Parse the request.
HTTPRequest* req = client->GetHttpReq();
HttpReqStatus reqRet = req->Parse(buf, len);
switch(reqRet) {
case HTTP_REQ_INCOMPLETE: continue;
case HTTP_REQ_FAILED:
RemoveSocket(client->Getfd());
client->Destroy();
stats.invalid_http_req++;
continue;
case HTTP_REQ_TO_BIG:
RemoveSocket(client->Getfd());
client->Destroy();
stats.oversized_http_req++;
continue;
case HTTP_REQ_OK: break;
case HTTP_REQ_POST_INVALID_LENGTH:
{ HTTPResponse res(411, "", false); client->Send(res.Get()); }
RemoveSocket(client->Getfd());
client->Destroy();
continue;
case HTTP_REQ_POST_TOO_LARGE:
DLOG(INFO) << "Client " << client->GetIP() << " sent too much POST data.";
{ HTTPResponse res(413, "", false); client->Send(res.Get()); }
RemoveSocket(client->Getfd());
client->Destroy();
continue;
case HTTP_REQ_POST_START:
{ HTTPResponse res(100, "", false); client->Send(res.Get()); }
continue;
case HTTP_REQ_POST_INCOMPLETE: continue;
case HTTP_REQ_POST_OK:
RemoveSocket(client->Getfd());
PostHandler(client, req);
client->Destroy();
continue;
}
if (!req->GetPath().empty()) {
// Handle /stats endpoint.
if (req->GetPath().compare("/stats") == 0) {
stats.SendToClient(client);
continue;
}
string chName = req->GetPath().substr(1);
SSEChannel *ch = GetChannel(chName);
DLOG(INFO) << "Channel: " << chName;
if (ch != NULL) {
RemoveSocket(client->Getfd());
ch->AddClient(client, req);
} else {
HTTPResponse res;
res.SetBody("Channel does not exist.\n");
client->Send(res.Get());
RemoveSocket(client->Getfd());
client->Destroy();
}
}
}
}
}
|
Set event path before compiling event.
|
Set event path before compiling event.
|
C++
|
mit
|
vgno/ssehub,olesku/ssehub,rexxars/ssehub,vgno/ssehub,sgulseth/ssehub,voldern/ssehub,sgulseth/ssehub,olesku/ssehub,voldern/ssehub,rexxars/ssehub
|
dd7418914df40637288964da269690285627fade
|
test/std/thread/thread.threads/thread.thread.class/thread.thread.member/detach.pass.cpp
|
test/std/thread/thread.threads/thread.thread.class/thread.thread.member/detach.pass.cpp
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// <thread>
// class thread
// void detach();
#include <thread>
#include <atomic>
#include <system_error>
#include <cassert>
#include "test_macros.h"
std::atomic_bool done(false);
class G
{
int alive_;
bool done_;
public:
static int n_alive;
static bool op_run;
G() : alive_(1), done_(false)
{
++n_alive;
}
G(const G& g) : alive_(g.alive_), done_(false)
{
++n_alive;
}
~G()
{
alive_ = 0;
--n_alive;
if (done_) done = true;
}
void operator()()
{
assert(alive_ == 1);
assert(n_alive >= 1);
op_run = true;
done_ = true;
}
};
int G::n_alive = 0;
bool G::op_run = false;
void foo() {}
int main()
{
{
G g;
std::thread t0(g);
assert(t0.joinable());
t0.detach();
assert(!t0.joinable());
while (!done) {}
assert(G::op_run);
assert(G::n_alive == 1);
}
assert(G::n_alive == 0);
#ifndef TEST_HAS_NO_EXCEPTION
{
std::thread t0(foo);
assert(t0.joinable());
t0.detach();
assert(!t0.joinable());
try {
t0.detach();
} catch (std::system_error const& ec) {
}
}
#endif
}
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// <thread>
// class thread
// void detach();
#include <thread>
#include <atomic>
#include <system_error>
#include <cassert>
#include "test_macros.h"
std::atomic_bool done(false);
class G
{
int alive_;
bool done_;
public:
static int n_alive;
static bool op_run;
G() : alive_(1), done_(false)
{
++n_alive;
}
G(const G& g) : alive_(g.alive_), done_(false)
{
++n_alive;
}
~G()
{
alive_ = 0;
--n_alive;
if (done_) done = true;
}
void operator()()
{
assert(alive_ == 1);
assert(n_alive >= 1);
op_run = true;
done_ = true;
}
};
int G::n_alive = 0;
bool G::op_run = false;
void foo() {}
int main()
{
{
G g;
std::thread t0(g);
assert(t0.joinable());
t0.detach();
assert(!t0.joinable());
while (!done) {}
assert(G::op_run);
assert(G::n_alive == 1);
}
assert(G::n_alive == 0);
#ifndef TEST_HAS_NO_EXCEPTIONS
{
std::thread t0(foo);
assert(t0.joinable());
t0.detach();
assert(!t0.joinable());
try {
t0.detach();
} catch (std::system_error const& ec) {
}
}
#endif
}
|
Fix TEST_HAS_NO_EXCEPTIONS misspelling in the test suite.
|
Fix TEST_HAS_NO_EXCEPTIONS misspelling in the test suite.
git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@271501 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
|
45fa39c40311d43b0754a26496461cbf70bb365e
|
src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp
|
src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "propertyeditorcontextobject.h"
#include <QQmlContext>
namespace QmlDesigner {
PropertyEditorContextObject::PropertyEditorContextObject(QObject *parent) :
QObject(parent),
m_isBaseState(false),
m_selectionChanged(false),
m_backendValues(0),
m_majorVersion(-1),
m_minorVersion(-1),
m_qmlComponent(0),
m_qmlContext(0)
{
}
int PropertyEditorContextObject::majorVersion() const
{
return m_majorVersion;
}
void PropertyEditorContextObject::setMajorVersion(int majorVersion)
{
if (m_majorVersion == majorVersion)
return;
m_majorVersion = majorVersion;
emit majorVersionChanged();
}
int PropertyEditorContextObject::minorVersion() const
{
return m_minorVersion;
}
void PropertyEditorContextObject::setMinorVersion(int minorVersion)
{
if (m_minorVersion == minorVersion)
return;
m_minorVersion = minorVersion;
emit minorVersionChanged();
}
void PropertyEditorContextObject::insertInQmlContext(QQmlContext *context)
{
m_qmlContext = context;
m_qmlContext->setContextObject(this);
}
QQmlComponent *PropertyEditorContextObject::specificQmlComponent()
{
if (m_qmlComponent)
return m_qmlComponent;
m_qmlComponent = new QQmlComponent(m_qmlContext->engine(), this);
m_qmlComponent->setData(m_specificQmlData.toAscii(), QUrl::fromLocalFile("specfics.qml"));
return m_qmlComponent;
}
void PropertyEditorContextObject::setGlobalBaseUrl(const QUrl &newBaseUrl)
{
if (newBaseUrl == m_globalBaseUrl)
return;
m_globalBaseUrl = newBaseUrl;
emit globalBaseUrlChanged();
}
void PropertyEditorContextObject::setSpecificsUrl(const QUrl &newSpecificsUrl)
{
if (newSpecificsUrl == m_specificsUrl)
return;
m_specificsUrl = newSpecificsUrl;
emit specificsUrlChanged();
}
void PropertyEditorContextObject::setSpecificQmlData(const QString &newSpecificQmlData)
{
if (m_specificQmlData == newSpecificQmlData)
return;
m_specificQmlData = newSpecificQmlData;
delete m_qmlComponent;
m_qmlComponent = 0;
emit specificQmlComponentChanged();
emit specificQmlDataChanged();
}
void PropertyEditorContextObject::setStateName(const QString &newStateName)
{
if (newStateName == m_stateName)
return;
m_stateName = newStateName;
emit stateNameChanged();
}
void PropertyEditorContextObject::setIsBaseState(bool newIsBaseState)
{
if (newIsBaseState == m_isBaseState)
return;
m_isBaseState = newIsBaseState;
emit isBaseStateChanged();
}
void PropertyEditorContextObject::setSelectionChanged(bool newSelectionChanged)
{
if (newSelectionChanged == m_selectionChanged)
return;
m_selectionChanged = newSelectionChanged;
emit selectionChangedChanged();
}
void PropertyEditorContextObject::setBackendValues(QQmlPropertyMap *newBackendValues)
{
if (newBackendValues == m_backendValues)
return;
m_backendValues = newBackendValues;
emit backendValuesChanged();
}
void PropertyEditorContextObject::triggerSelectionChanged()
{
setSelectionChanged(!m_selectionChanged);
}
} //QmlDesigner
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "propertyeditorcontextobject.h"
#include <QQmlContext>
namespace QmlDesigner {
PropertyEditorContextObject::PropertyEditorContextObject(QObject *parent) :
QObject(parent),
m_isBaseState(false),
m_selectionChanged(false),
m_backendValues(0),
m_majorVersion(-1),
m_minorVersion(-1),
m_qmlComponent(0),
m_qmlContext(0)
{
}
int PropertyEditorContextObject::majorVersion() const
{
return m_majorVersion;
}
void PropertyEditorContextObject::setMajorVersion(int majorVersion)
{
if (m_majorVersion == majorVersion)
return;
m_majorVersion = majorVersion;
emit majorVersionChanged();
}
int PropertyEditorContextObject::minorVersion() const
{
return m_minorVersion;
}
void PropertyEditorContextObject::setMinorVersion(int minorVersion)
{
if (m_minorVersion == minorVersion)
return;
m_minorVersion = minorVersion;
emit minorVersionChanged();
}
void PropertyEditorContextObject::insertInQmlContext(QQmlContext *context)
{
m_qmlContext = context;
m_qmlContext->setContextObject(this);
}
QQmlComponent *PropertyEditorContextObject::specificQmlComponent()
{
if (m_qmlComponent)
return m_qmlComponent;
m_qmlComponent = new QQmlComponent(m_qmlContext->engine(), this);
m_qmlComponent->setData(m_specificQmlData.toLatin1(), QUrl::fromLocalFile("specfics.qml"));
return m_qmlComponent;
}
void PropertyEditorContextObject::setGlobalBaseUrl(const QUrl &newBaseUrl)
{
if (newBaseUrl == m_globalBaseUrl)
return;
m_globalBaseUrl = newBaseUrl;
emit globalBaseUrlChanged();
}
void PropertyEditorContextObject::setSpecificsUrl(const QUrl &newSpecificsUrl)
{
if (newSpecificsUrl == m_specificsUrl)
return;
m_specificsUrl = newSpecificsUrl;
emit specificsUrlChanged();
}
void PropertyEditorContextObject::setSpecificQmlData(const QString &newSpecificQmlData)
{
if (m_specificQmlData == newSpecificQmlData)
return;
m_specificQmlData = newSpecificQmlData;
delete m_qmlComponent;
m_qmlComponent = 0;
emit specificQmlComponentChanged();
emit specificQmlDataChanged();
}
void PropertyEditorContextObject::setStateName(const QString &newStateName)
{
if (newStateName == m_stateName)
return;
m_stateName = newStateName;
emit stateNameChanged();
}
void PropertyEditorContextObject::setIsBaseState(bool newIsBaseState)
{
if (newIsBaseState == m_isBaseState)
return;
m_isBaseState = newIsBaseState;
emit isBaseStateChanged();
}
void PropertyEditorContextObject::setSelectionChanged(bool newSelectionChanged)
{
if (newSelectionChanged == m_selectionChanged)
return;
m_selectionChanged = newSelectionChanged;
emit selectionChangedChanged();
}
void PropertyEditorContextObject::setBackendValues(QQmlPropertyMap *newBackendValues)
{
if (newBackendValues == m_backendValues)
return;
m_backendValues = newBackendValues;
emit backendValuesChanged();
}
void PropertyEditorContextObject::triggerSelectionChanged()
{
setSelectionChanged(!m_selectionChanged);
}
} //QmlDesigner
|
Fix usage of deprecated function.
|
QmlDesigner: Fix usage of deprecated function.
Change-Id: I5d6d6d99e5e61816b974e8b81dcce0e5063ce5e9
Reviewed-by: Thomas Hartmann <[email protected]>
|
C++
|
lgpl-2.1
|
danimo/qt-creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,kuba1/qtcreator,farseerri/git_code,colede/qtcreator,danimo/qt-creator,kuba1/qtcreator,darksylinc/qt-creator,colede/qtcreator,farseerri/git_code,danimo/qt-creator,xianian/qt-creator,maui-packages/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,kuba1/qtcreator,AltarBeastiful/qt-creator,omniacreator/qtcreator,amyvmiwei/qt-creator,darksylinc/qt-creator,martyone/sailfish-qtcreator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,xianian/qt-creator,Distrotech/qtcreator,xianian/qt-creator,darksylinc/qt-creator,amyvmiwei/qt-creator,Distrotech/qtcreator,kuba1/qtcreator,darksylinc/qt-creator,AltarBeastiful/qt-creator,farseerri/git_code,darksylinc/qt-creator,AltarBeastiful/qt-creator,omniacreator/qtcreator,omniacreator/qtcreator,maui-packages/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,Distrotech/qtcreator,colede/qtcreator,xianian/qt-creator,xianian/qt-creator,xianian/qt-creator,maui-packages/qt-creator,farseerri/git_code,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,Distrotech/qtcreator,Distrotech/qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,darksylinc/qt-creator,colede/qtcreator,maui-packages/qt-creator,omniacreator/qtcreator,danimo/qt-creator,kuba1/qtcreator,danimo/qt-creator,danimo/qt-creator,AltarBeastiful/qt-creator,Distrotech/qtcreator,kuba1/qtcreator,martyone/sailfish-qtcreator,darksylinc/qt-creator,maui-packages/qt-creator,martyone/sailfish-qtcreator,colede/qtcreator,colede/qtcreator,omniacreator/qtcreator,kuba1/qtcreator,danimo/qt-creator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,omniacreator/qtcreator,omniacreator/qtcreator,farseerri/git_code,farseerri/git_code,amyvmiwei/qt-creator,danimo/qt-creator,kuba1/qtcreator,Distrotech/qtcreator,farseerri/git_code,AltarBeastiful/qt-creator,farseerri/git_code,colede/qtcreator,darksylinc/qt-creator,amyvmiwei/qt-creator
|
61dfa6b807cb8d9d3d5f62aa505813cc30a6e117
|
packages/Search/examples/distributed_tree_driver/distributed_tree_driver.cpp
|
packages/Search/examples/distributed_tree_driver/distributed_tree_driver.cpp
|
/****************************************************************************
* Copyright (c) 2012-2019 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_DistributedSearchTree.hpp>
#include <Kokkos_DefaultNode.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_CommandLineProcessor.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <Teuchos_Time.hpp>
#include <Teuchos_TimeMonitor.hpp>
#include <cmath> // cbrt
#include <random>
template <class NO>
int main_( Teuchos::CommandLineProcessor &clp, int argc, char *argv[] )
{
Teuchos::Time timer( "timer" );
Teuchos::TimeMonitor time_monitor( timer );
using DeviceType = typename NO::device_type;
using ExecutionSpace = typename DeviceType::execution_space;
int n_values = 50000;
int n_queries = 20000;
int n_neighbors = 10;
double overlap = 0.;
int partition_dim = 3;
bool perform_knn_search = true;
bool perform_radius_search = true;
clp.setOption( "values", &n_values,
"number of indexable values (source) per MPI rank" );
clp.setOption( "queries", &n_queries,
"number of queries (target) per MPI rank" );
clp.setOption( "neighbors", &n_neighbors,
"desired number of results per query" );
clp.setOption( "overlap", &overlap,
"overlap of the point clouds. 0 means the clouds are built "
"next to each other. 1 means that there are built at the "
"same place. Negative values and values larger than two "
"means that the clouds are separated" );
clp.setOption( "partition_dim", &partition_dim,
"number of dimension used by the partitioning of the global "
"point cloud. 1 -> local clouds are aligned on a line, 2 -> "
"local clouds form a board, 3 -> local clouds form a box" );
clp.setOption( "perform-knn-search", "do-not-perform-knn-search",
&perform_knn_search,
"whether or not to perform kNN search" );
clp.setOption( "perform-radius-search", "do-not-perform-radius-search",
&perform_radius_search,
"whether or not to perform radius search" );
clp.recogniseAllOptions( true );
switch ( clp.parse( argc, argv ) )
{
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
return EXIT_SUCCESS;
case Teuchos::CommandLineProcessor::PARSE_ERROR:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
return EXIT_FAILURE;
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
Teuchos::RCP<const Teuchos::Comm<int>> comm =
Teuchos::DefaultComm<int>::getComm();
int rank = Teuchos::rank( *comm );
Kokkos::View<DataTransferKit::Point *, DeviceType> random_points(
"random_points" );
{
// Random points are "reused" between building the tree and performing
// queries. Note that this means that for the points in the middle of
// the local domains there won't be any communication.
auto n = std::max( n_values, n_queries );
Kokkos::resize( random_points, n );
auto random_points_host = Kokkos::create_mirror_view( random_points );
// Generate random points uniformely distributed within a box.
auto const a = std::cbrt( n_values );
std::uniform_real_distribution<double> distribution( -a, +a );
std::default_random_engine generator;
auto random = [&distribution, &generator]() {
return distribution( generator );
};
double offset_x = 0.;
double offset_y = 0.;
double offset_z = 0.;
// Change the geometry of the problem. In 1D, all the point clouds are
// aligned on a line. In 2D, the point clouds create a board and in 3D,
// they create a box.
switch ( partition_dim )
{
case 1:
{
offset_x = 2. * ( 1. - overlap ) * a * rank;
break;
}
case 2:
{
int n_procs = Teuchos::size( *comm );
int i_max = std::ceil( std::sqrt( n_procs ) );
int i = rank % i_max;
int j = rank / i_max;
offset_x = 2. * ( 1. - overlap ) * a * i;
offset_y = 2. * ( 1. - overlap ) * a * j;
break;
}
case 3:
{
int n_procs = Teuchos::size( *comm );
int i_max = std::ceil( std::cbrt( n_procs ) );
int j_max = i_max;
int i = rank % i_max;
int j = ( rank / i_max ) % j_max;
int k = rank / ( i_max * j_max );
offset_x = 2. * ( 1. - overlap ) * a * i;
offset_y = 2. * ( 1. - overlap ) * a * j;
offset_z = 2. * ( 1. - overlap ) * a * k;
break;
}
default:
{
throw std::runtime_error( "partition_dim should be 1, 2, or 3" );
}
}
for ( int i = 0; i < n; ++i )
random_points_host( i ) = {{offset_x + random(),
offset_y + random(),
offset_z + random()}};
Kokkos::deep_copy( random_points, random_points_host );
}
Kokkos::View<DataTransferKit::Box *, DeviceType> bounding_boxes(
Kokkos::ViewAllocateWithoutInitializing( "bounding_boxes" ), n_values );
Kokkos::parallel_for( "bvh_driver:construct_bounding_boxes",
Kokkos::RangePolicy<ExecutionSpace>( 0, n_values ),
KOKKOS_LAMBDA( int i ) {
double const x = random_points( i )[0];
double const y = random_points( i )[1];
double const z = random_points( i )[2];
bounding_boxes( i ) = {
{{x - 1., y - 1., z - 1.}},
{{x + 1., y + 1., z + 1.}}};
} );
Kokkos::fence();
auto construction = time_monitor.getNewTimer( "construction" );
comm->barrier();
construction->start();
DataTransferKit::DistributedSearchTree<DeviceType> distributed_tree(
*( Teuchos::rcp_dynamic_cast<Teuchos::MpiComm<int> const>( comm )
->getRawMpiComm() ),
bounding_boxes );
construction->stop();
std::ostream &os = std::cout;
if ( rank == 0 )
os << "contruction done\n";
if ( perform_knn_search )
{
Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *,
DeviceType>
queries( Kokkos::ViewAllocateWithoutInitializing( "queries" ),
n_queries );
Kokkos::parallel_for(
"bvh_driver:setup_knn_search_queries",
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) = DataTransferKit::nearest<DataTransferKit::Point>(
random_points( i ), n_neighbors );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> ranks( "ranks" );
auto knn = time_monitor.getNewTimer( "knn" );
comm->barrier();
knn->start();
distributed_tree.query( queries, indices, offset, ranks );
knn->stop();
if ( rank == 0 )
os << "knn done\n";
}
if ( perform_radius_search )
{
Kokkos::View<DataTransferKit::Within *, DeviceType> queries(
Kokkos::ViewAllocateWithoutInitializing( "queries" ), n_queries );
// radius chosen in order to control the number of results per query
// NOTE: minus "1+sqrt(3)/2 \approx 1.37" matches the size of the boxes
// inserted into the tree (mid-point between half-edge and
// half-diagonal)
double const r = 2. * std::cbrt( static_cast<double>( n_neighbors ) *
3. / ( 4. * M_PI ) ) -
( 1. + std::sqrt( 3. ) ) / 2.;
Kokkos::parallel_for(
"bvh_driver:setup_radius_search_queries",
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) = DataTransferKit::within( random_points( i ), r );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> ranks( "ranks" );
auto radius = time_monitor.getNewTimer( "radius" );
comm->barrier();
radius->start();
distributed_tree.query( queries, indices, offset, ranks );
radius->stop();
if ( rank == 0 )
os << "radius done\n";
}
time_monitor.summarize( comm.ptr() );
return 0;
}
int main( int argc, char *argv[] )
{
MPI_Init( &argc, &argv );
Kokkos::initialize( argc, argv );
bool success = true;
bool verbose = true;
try
{
const bool throwExceptions = false;
Teuchos::CommandLineProcessor clp( throwExceptions );
std::string node = "";
clp.setOption( "node", &node, "node type (serial | openmp | cuda)" );
clp.recogniseAllOptions( false );
switch ( clp.parse( argc, argv, NULL ) )
{
case Teuchos::CommandLineProcessor::PARSE_ERROR:
success = false;
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
if ( !success )
{
// do nothing, just skip other if clauses
}
else if ( node == "" )
{
typedef KokkosClassic::DefaultNode::DefaultNodeType Node;
main_<Node>( clp, argc, argv );
}
else if ( node == "serial" )
{
#ifdef KOKKOS_ENABLE_SERIAL
typedef Kokkos::Compat::KokkosSerialWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "Serial node type is disabled" );
#endif
}
else if ( node == "openmp" )
{
#ifdef KOKKOS_ENABLE_OPENMP
typedef Kokkos::Compat::KokkosOpenMPWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "OpenMP node type is disabled" );
#endif
}
else if ( node == "cuda" )
{
#ifdef KOKKOS_ENABLE_CUDA
typedef Kokkos::Compat::KokkosCudaWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "CUDA node type is disabled" );
#endif
}
else
{
throw std::runtime_error( "Unrecognized node type" );
}
}
TEUCHOS_STANDARD_CATCH_STATEMENTS( verbose, std::cerr, success );
Kokkos::finalize();
MPI_Finalize();
return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
|
/****************************************************************************
* Copyright (c) 2012-2019 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_DistributedSearchTree.hpp>
#include <Kokkos_DefaultNode.hpp>
#include <Teuchos_CommandLineProcessor.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <mpi.h>
#include <algorithm>
#include <chrono>
#include <cmath> // cbrt
#include <numeric>
#include <random>
#include <utility>
#include <vector>
// Poor man's replacement for Teuchos::TimeMonitor
class TimeMonitor
{
using container_type = std::vector<std::pair<std::string, double>>;
using entry_reference_type = container_type::reference;
container_type _data;
public:
class Timer
{
entry_reference_type _entry;
bool _started;
std::chrono::high_resolution_clock::time_point _tick;
public:
Timer( entry_reference_type ref )
: _entry{ref}
, _started{false}
{
}
void start()
{
assert( !_started );
_tick = std::chrono::high_resolution_clock::now();
_started = true;
}
void stop()
{
assert( _started );
std::chrono::duration<double> duration =
std::chrono::high_resolution_clock::now() - _tick;
// NOTE I have put much thought into whether we should use the
// operator+= and keep track of how many times the timer was
// restarted. To be honest I have not even looked was the original
// TimeMonitor behavior is :)
_entry.second = duration.count();
_started = false;
}
};
std::unique_ptr<Timer> getNewTimer( std::string name )
{
_data.emplace_back( std::move( name ), 0. );
return std::unique_ptr<Timer>( new Timer( _data.back() ) );
}
void summarize( MPI_Comm comm, std::ostream &os = std::cout )
{
// FIXME Haven't tried very hard to format the output.
int comm_size;
MPI_Comm_size( comm, &comm_size );
int comm_rank;
MPI_Comm_rank( comm, &comm_rank );
int n_timers = _data.size();
if ( comm_size == 1 )
{
os << "========================================\n\n";
os << "TimeMonitor results over 1 processor\n\n";
os << "Timer Name\tGlobal Time\n";
os << "----------------------------------------\n";
for ( int i = 0; i < n_timers; ++i )
{
os << _data[i].first << "\t" << _data[i].second << "\n";
}
os << "========================================\n";
return;
}
std::vector<double> all_entries( comm_size * n_timers );
std::transform( _data.begin(), _data.end(),
all_entries.begin() + comm_rank * n_timers,
[]( std::pair<std::string, double> const &x ) {
return x.second;
} );
MPI_Allgather( MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, all_entries.data(),
n_timers, MPI_DOUBLE, comm );
if ( comm_rank == 0 )
{
os << "========================================\n\n";
os << "TimeMonitor results over " << comm_size << " processors\n";
os << "Timer Name\tMinOverProcs\tMeanOverProcs\tMaxOverProcs\n";
os << "----------------------------------------\n";
}
std::vector<double> tmp( comm_size );
for ( int i = 0; i < n_timers; ++i )
{
for ( int j = 0; j < comm_size; ++j )
{
tmp[j] = all_entries[j * n_timers + i];
}
auto min = *std::min_element( tmp.begin(), tmp.end() );
auto max = *std::max_element( tmp.begin(), tmp.end() );
auto mean =
std::accumulate( tmp.begin(), tmp.end(), 0. ) / comm_size;
if ( comm_rank == 0 )
{
os << _data[i].first << "\t" << min << "\t" << mean << "\t"
<< max << "\n";
}
}
if ( comm_rank == 0 )
{
os << "========================================\n";
}
}
};
template <class NO>
int main_( Teuchos::CommandLineProcessor &clp, int argc, char *argv[] )
{
TimeMonitor time_monitor;
using DeviceType = typename NO::device_type;
using ExecutionSpace = typename DeviceType::execution_space;
int n_values = 50000;
int n_queries = 20000;
int n_neighbors = 10;
double overlap = 0.;
int partition_dim = 3;
bool perform_knn_search = true;
bool perform_radius_search = true;
clp.setOption( "values", &n_values,
"number of indexable values (source) per MPI rank" );
clp.setOption( "queries", &n_queries,
"number of queries (target) per MPI rank" );
clp.setOption( "neighbors", &n_neighbors,
"desired number of results per query" );
clp.setOption( "overlap", &overlap,
"overlap of the point clouds. 0 means the clouds are built "
"next to each other. 1 means that there are built at the "
"same place. Negative values and values larger than two "
"means that the clouds are separated" );
clp.setOption( "partition_dim", &partition_dim,
"number of dimension used by the partitioning of the global "
"point cloud. 1 -> local clouds are aligned on a line, 2 -> "
"local clouds form a board, 3 -> local clouds form a box" );
clp.setOption( "perform-knn-search", "do-not-perform-knn-search",
&perform_knn_search,
"whether or not to perform kNN search" );
clp.setOption( "perform-radius-search", "do-not-perform-radius-search",
&perform_radius_search,
"whether or not to perform radius search" );
clp.recogniseAllOptions( true );
switch ( clp.parse( argc, argv ) )
{
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
return EXIT_SUCCESS;
case Teuchos::CommandLineProcessor::PARSE_ERROR:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
return EXIT_FAILURE;
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
MPI_Comm comm = MPI_COMM_WORLD;
int comm_rank;
MPI_Comm_rank( comm, &comm_rank );
int comm_size;
MPI_Comm_size( comm, &comm_size );
Kokkos::View<DataTransferKit::Point *, DeviceType> random_points(
"random_points" );
{
// Random points are "reused" between building the tree and performing
// queries. Note that this means that for the points in the middle of
// the local domains there won't be any communication.
auto n = std::max( n_values, n_queries );
Kokkos::resize( random_points, n );
auto random_points_host = Kokkos::create_mirror_view( random_points );
// Generate random points uniformely distributed within a box.
auto const a = std::cbrt( n_values );
std::uniform_real_distribution<double> distribution( -a, +a );
std::default_random_engine generator;
auto random = [&distribution, &generator]() {
return distribution( generator );
};
double offset_x = 0.;
double offset_y = 0.;
double offset_z = 0.;
// Change the geometry of the problem. In 1D, all the point clouds are
// aligned on a line. In 2D, the point clouds create a board and in 3D,
// they create a box.
switch ( partition_dim )
{
case 1:
{
offset_x = 2. * ( 1. - overlap ) * a * comm_rank;
break;
}
case 2:
{
int i_max = std::ceil( std::sqrt( comm_size ) );
int i = comm_rank % i_max;
int j = comm_rank / i_max;
offset_x = 2. * ( 1. - overlap ) * a * i;
offset_y = 2. * ( 1. - overlap ) * a * j;
break;
}
case 3:
{
int i_max = std::ceil( std::cbrt( comm_size ) );
int j_max = i_max;
int i = comm_rank % i_max;
int j = ( comm_rank / i_max ) % j_max;
int k = comm_rank / ( i_max * j_max );
offset_x = 2. * ( 1. - overlap ) * a * i;
offset_y = 2. * ( 1. - overlap ) * a * j;
offset_z = 2. * ( 1. - overlap ) * a * k;
break;
}
default:
{
throw std::runtime_error( "partition_dim should be 1, 2, or 3" );
}
}
for ( int i = 0; i < n; ++i )
random_points_host( i ) = {{offset_x + random(),
offset_y + random(),
offset_z + random()}};
Kokkos::deep_copy( random_points, random_points_host );
}
Kokkos::View<DataTransferKit::Box *, DeviceType> bounding_boxes(
Kokkos::ViewAllocateWithoutInitializing( "bounding_boxes" ), n_values );
Kokkos::parallel_for( "bvh_driver:construct_bounding_boxes",
Kokkos::RangePolicy<ExecutionSpace>( 0, n_values ),
KOKKOS_LAMBDA( int i ) {
double const x = random_points( i )[0];
double const y = random_points( i )[1];
double const z = random_points( i )[2];
bounding_boxes( i ) = {
{{x - 1., y - 1., z - 1.}},
{{x + 1., y + 1., z + 1.}}};
} );
Kokkos::fence();
auto construction = time_monitor.getNewTimer( "construction" );
MPI_Barrier( comm );
construction->start();
DataTransferKit::DistributedSearchTree<DeviceType> distributed_tree(
comm, bounding_boxes );
construction->stop();
std::ostream &os = std::cout;
if ( comm_rank == 0 )
os << "contruction done\n";
if ( perform_knn_search )
{
Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *,
DeviceType>
queries( Kokkos::ViewAllocateWithoutInitializing( "queries" ),
n_queries );
Kokkos::parallel_for(
"bvh_driver:setup_knn_search_queries",
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) = DataTransferKit::nearest<DataTransferKit::Point>(
random_points( i ), n_neighbors );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> ranks( "ranks" );
auto knn = time_monitor.getNewTimer( "knn" );
MPI_Barrier( comm );
knn->start();
distributed_tree.query( queries, indices, offset, ranks );
knn->stop();
if ( comm_rank == 0 )
os << "knn done\n";
}
if ( perform_radius_search )
{
Kokkos::View<DataTransferKit::Within *, DeviceType> queries(
Kokkos::ViewAllocateWithoutInitializing( "queries" ), n_queries );
// radius chosen in order to control the number of results per query
// NOTE: minus "1+sqrt(3)/2 \approx 1.37" matches the size of the boxes
// inserted into the tree (mid-point between half-edge and
// half-diagonal)
double const r = 2. * std::cbrt( static_cast<double>( n_neighbors ) *
3. / ( 4. * M_PI ) ) -
( 1. + std::sqrt( 3. ) ) / 2.;
Kokkos::parallel_for(
"bvh_driver:setup_radius_search_queries",
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) = DataTransferKit::within( random_points( i ), r );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> ranks( "ranks" );
auto radius = time_monitor.getNewTimer( "radius" );
MPI_Barrier( comm );
radius->start();
distributed_tree.query( queries, indices, offset, ranks );
radius->stop();
if ( comm_rank == 0 )
os << "radius done\n";
}
time_monitor.summarize( comm );
return 0;
}
int main( int argc, char *argv[] )
{
MPI_Init( &argc, &argv );
Kokkos::initialize( argc, argv );
bool success = true;
bool verbose = true;
try
{
const bool throwExceptions = false;
Teuchos::CommandLineProcessor clp( throwExceptions );
std::string node = "";
clp.setOption( "node", &node, "node type (serial | openmp | cuda)" );
clp.recogniseAllOptions( false );
switch ( clp.parse( argc, argv, NULL ) )
{
case Teuchos::CommandLineProcessor::PARSE_ERROR:
success = false;
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
if ( !success )
{
// do nothing, just skip other if clauses
}
else if ( node == "" )
{
typedef KokkosClassic::DefaultNode::DefaultNodeType Node;
main_<Node>( clp, argc, argv );
}
else if ( node == "serial" )
{
#ifdef KOKKOS_ENABLE_SERIAL
typedef Kokkos::Compat::KokkosSerialWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "Serial node type is disabled" );
#endif
}
else if ( node == "openmp" )
{
#ifdef KOKKOS_ENABLE_OPENMP
typedef Kokkos::Compat::KokkosOpenMPWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "OpenMP node type is disabled" );
#endif
}
else if ( node == "cuda" )
{
#ifdef KOKKOS_ENABLE_CUDA
typedef Kokkos::Compat::KokkosCudaWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "CUDA node type is disabled" );
#endif
}
else
{
throw std::runtime_error( "Unrecognized node type" );
}
}
TEUCHOS_STANDARD_CATCH_STATEMENTS( verbose, std::cerr, success );
Kokkos::finalize();
MPI_Finalize();
return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
|
Remove Teuchos::TimeMonitor and Comm from distributed search tree benchmark
|
Remove Teuchos::TimeMonitor and Comm from distributed search tree benchmark
|
C++
|
bsd-3-clause
|
ORNL-CEES/DataTransferKit,ORNL-CEES/DataTransferKit,Rombur/DataTransferKit,Rombur/DataTransferKit,Rombur/DataTransferKit,ORNL-CEES/DataTransferKit,Rombur/DataTransferKit,ORNL-CEES/DataTransferKit
|
a3098c0bccc72a6445fb18f691e88e3a43189eb5
|
c++/main.cpp
|
c++/main.cpp
|
#include <iostream>
#include <vector>
#include <map>
// other function style
int square1(int x) {
return x * x;
}
auto square(int x) -> int {
return x * x;
}
// no return
void disp(const std::string& s) {
std::string buf = "disp: " + s + "\n";
printf(buf.c_str());
}
int abs1(int x) {
if (x >= 0) {
return x;
}
return -x;
}
int abs(int x) {
return x >= 0 ? x : -x;
}
template <class T>
std::string to_str(T t) {
return std::to_string(t);
}
int main() {
/*
* comment
*/
std::cout << "Hello, World!" << std::endl; // comment
const int a = square(3);
const std::string s = "abc";
std::cout << a << std::endl;
disp("Hello World");
int one = 1;
int& b = one;
b = 2;
disp(to_str(one));
disp(to_str(abs(-3)));
const std::vector<int> v = {1, 2, 3};
// get first
disp(to_str(v.front()));
// get last
disp(to_str(v.back()));
// cannot const
std::vector<int> vv = {1,2,3};
vv.push_back(4);
disp(to_str(vv.back()));
vv.pop_back();
disp(to_str(vv.back()));
vv.assign({4,5,6});
disp(to_str(vv.back()));
// normal
for (int i = 0; i < v.size(); ++i) {
disp(to_str(v[i]));
}
// simple
for (const int x: v) {
disp(to_str(x));
}
const std::map<std::string, int> m = {
{"Akira", 24},
{"Milla", 16},
{"Johny", 38}
};
const int age = m.at("Akira");
disp(to_str(age));
std::map<std::string, int> mm = {
{"Akira", 24},
{"Milla", 16},
{"Johny", 38}
};
mm["Sol"] = 150;
int solAge = mm.at("Sol");
disp(to_str(solAge));
return 0;
}
|
#include <iostream>
#include <vector>
#include <map>
// other function style
int square1(int x) {
return x * x;
}
auto square(int x) -> int {
return x * x;
}
// no return
void disp(const std::string& s) {
std::cout << "disp: " << s << std::endl;
}
void disp_int(int s) {
std::cout << s << std::endl;
}
int abs1(int x) {
if (x >= 0) {
return x;
}
return -x;
}
int abs(int x) {
return x >= 0 ? x : -x;
}
template <class T>
std::string to_str(T t) {
return std::to_string(t);
}
int main() {
/*
* comment
*/
std::cout << "Hello, World!" << std::endl; // comment
const int a = square(3);
const std::string s = "abc";
std::cout << a << std::endl;
disp("Hello World");
int one = 1;
int& b = one;
b = 2;
disp(to_str(one));
disp(to_str(abs(-3)));
const std::vector<int> v = {1, 2, 3};
// get first
disp(to_str(v.front()));
// get last
disp(to_str(v.back()));
// cannot const
std::vector<int> vv = {1,2,3};
vv.push_back(4);
disp(to_str(vv.back()));
vv.pop_back();
disp(to_str(vv.back()));
vv.assign({4,5,6});
disp(to_str(vv.back()));
// normal
for (int i = 0; i < v.size(); ++i) {
disp(to_str(v[i]));
}
// simple
for (const int x: v) {
disp(to_str(x));
}
const std::map<std::string, int> m = {
{"Akira", 24},
{"Milla", 16},
{"Johny", 38}
};
const int age = m.at("Akira");
disp(to_str(age));
std::map<std::string, int> mm = {
{"Akira", 24},
{"Milla", 16},
{"Johny", 38}
};
mm["Sol"] = 150;
int solAge = mm.at("Sol");
disp(to_str(solAge));
const std::vector<int> vvv = {1,2,3,4,5,6,7,8,9,10};
std::for_each(vvv.begin(), vvv.end(), &disp_int);
auto it = std::find(vvv.begin(), vvv.end(), 2);
if (it != v.end()) {
std::cout << "found: " << *it << std::endl;
} else {
std::cout << "not found: " << std::endl;
}
return 0;
}
|
Add algorithm
|
Add algorithm
|
C++
|
mit
|
yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program
|
f463dc9d32c69e5e1e7295a0df9cedeb8ecba5eb
|
Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp
|
Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkVolumeVisualizationView.h"
#include <QComboBox>
#include <berryISelectionProvider.h>
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
//#include <berryISelectionService.h>
#include <mitkDataNodeObject.h>
#include <mitkProperties.h>
#include <mitkNodePredicateDataType.h>
#include <mitkTransferFunction.h>
#include <mitkTransferFunctionProperty.h>
#include <mitkTransferFunctionInitializer.h>
#include "mitkHistogramGenerator.h"
#include "QmitkPiecewiseFunctionCanvas.h"
#include "QmitkColorTransferFunctionCanvas.h"
#include "mitkBaseRenderer.h"
#include "mitkVtkVolumeRenderingProperty.h"
#include <mitkIRenderingManager.h>
#include <QToolTip>
const std::string QmitkVolumeVisualizationView::VIEW_ID =
"org.mitk.views.volumevisualization";
enum RenderMode
{
RM_CPU_COMPOSITE_RAYCAST = 0,
RM_CPU_MIP_RAYCAST = 1,
RM_GPU_COMPOSITE_SLICING = 2,
RM_GPU_COMPOSITE_RAYCAST = 3,
RM_GPU_MIP_RAYCAST = 4
};
QmitkVolumeVisualizationView::QmitkVolumeVisualizationView()
: QmitkAbstractView(),
m_Controls(NULL)
{
}
QmitkVolumeVisualizationView::~QmitkVolumeVisualizationView()
{
}
void QmitkVolumeVisualizationView::CreateQtPartControl(QWidget* parent)
{
if (!m_Controls)
{
m_Controls = new Ui::QmitkVolumeVisualizationViewControls;
m_Controls->setupUi(parent);
// Fill the tf presets in the generator widget
std::vector<std::string> names;
mitk::TransferFunctionInitializer::GetPresetNames(names);
for (std::vector<std::string>::const_iterator it = names.begin();
it != names.end(); ++it)
{
m_Controls->m_TransferFunctionGeneratorWidget->AddPreset(QString::fromStdString(*it));
}
m_Controls->m_RenderMode->addItem("CPU raycast");
m_Controls->m_RenderMode->addItem("CPU MIP raycast");
m_Controls->m_RenderMode->addItem("GPU slicing");
// Only with VTK 5.6 or above
#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) ))
m_Controls->m_RenderMode->addItem("GPU raycast");
m_Controls->m_RenderMode->addItem("GPU MIP raycast");
#endif
connect( m_Controls->m_EnableRenderingCB, SIGNAL( toggled(bool) ),this, SLOT( OnEnableRendering(bool) ));
connect( m_Controls->m_EnableLOD, SIGNAL( toggled(bool) ),this, SLOT( OnEnableLOD(bool) ));
connect( m_Controls->m_RenderMode, SIGNAL( activated(int) ),this, SLOT( OnRenderMode(int) ));
connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL( SignalUpdateCanvas( ) ), m_Controls->m_TransferFunctionWidget, SLOT( OnUpdateCanvas( ) ) );
connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL(SignalTransferFunctionModeChanged(int)), SLOT(OnMitkInternalPreset(int)));
m_Controls->m_EnableRenderingCB->setEnabled(false);
m_Controls->m_EnableLOD->setEnabled(false);
m_Controls->m_RenderMode->setEnabled(false);
m_Controls->m_TransferFunctionWidget->setEnabled(false);
m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false);
m_Controls->m_SelectedImageLabel->hide();
m_Controls->m_ErrorImageLabel->hide();
}
}
void QmitkVolumeVisualizationView::OnMitkInternalPreset( int mode )
{
if (m_SelectedNode.IsNull()) return;
mitk::DataNode::Pointer node(m_SelectedNode.GetPointer());
mitk::TransferFunctionProperty::Pointer transferFuncProp;
if (node->GetProperty(transferFuncProp, "TransferFunction"))
{
//first item is only information
if( --mode == -1 )
return;
// -- Creat new TransferFunction
mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(transferFuncProp->GetValue());
tfInit->SetTransferFunctionMode(mode);
RequestRenderWindowUpdate();
m_Controls->m_TransferFunctionWidget->OnUpdateCanvas();
}
}
void QmitkVolumeVisualizationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList<mitk::DataNode::Pointer>& nodes)
{
bool weHadAnImageButItsNotThreeDeeOrFourDee = false;
mitk::DataNode::Pointer node;
foreach (mitk::DataNode::Pointer currentNode, nodes)
{
if( currentNode.IsNotNull() && dynamic_cast<mitk::Image*>(currentNode->GetData()) )
{
if( dynamic_cast<mitk::Image*>(currentNode->GetData())->GetDimension()>=3 )
{
if (node.IsNull())
{
node = currentNode;
}
}
else
{
weHadAnImageButItsNotThreeDeeOrFourDee = true;
}
}
}
if( node.IsNotNull() )
{
m_Controls->m_NoSelectedImageLabel->hide();
m_Controls->m_ErrorImageLabel->hide();
m_Controls->m_SelectedImageLabel->show();
std::string infoText;
if (node->GetName().empty())
infoText = std::string("Selected Image: [currently selected image has no name]");
else
infoText = std::string("Selected Image: ") + node->GetName();
m_Controls->m_SelectedImageLabel->setText( QString( infoText.c_str() ) );
m_SelectedNode = node;
}
else
{
if(weHadAnImageButItsNotThreeDeeOrFourDee)
{
m_Controls->m_NoSelectedImageLabel->hide();
m_Controls->m_ErrorImageLabel->show();
std::string infoText;
infoText = std::string("only 3D or 4D images are supported");
m_Controls->m_ErrorImageLabel->setText( QString( infoText.c_str() ) );
}
else
{
m_Controls->m_SelectedImageLabel->hide();
m_Controls->m_ErrorImageLabel->hide();
m_Controls->m_NoSelectedImageLabel->show();
}
m_SelectedNode = 0;
}
UpdateInterface();
}
void QmitkVolumeVisualizationView::UpdateInterface()
{
if(m_SelectedNode.IsNull())
{
// turnoff all
m_Controls->m_EnableRenderingCB->setChecked(false);
m_Controls->m_EnableRenderingCB->setEnabled(false);
m_Controls->m_EnableLOD->setChecked(false);
m_Controls->m_EnableLOD->setEnabled(false);
m_Controls->m_RenderMode->setCurrentIndex(0);
m_Controls->m_RenderMode->setEnabled(false);
m_Controls->m_TransferFunctionWidget->SetDataNode(0);
m_Controls->m_TransferFunctionWidget->setEnabled(false);
m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0);
m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false);
return;
}
bool enabled = false;
m_SelectedNode->GetBoolProperty("volumerendering",enabled);
m_Controls->m_EnableRenderingCB->setEnabled(true);
m_Controls->m_EnableRenderingCB->setChecked(enabled);
if(!enabled)
{
// turnoff all except volumerendering checkbox
m_Controls->m_EnableLOD->setChecked(false);
m_Controls->m_EnableLOD->setEnabled(false);
m_Controls->m_RenderMode->setCurrentIndex(0);
m_Controls->m_RenderMode->setEnabled(false);
m_Controls->m_TransferFunctionWidget->SetDataNode(0);
m_Controls->m_TransferFunctionWidget->setEnabled(false);
m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0);
m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false);
return;
}
// otherwise we can activate em all
enabled = false;
m_SelectedNode->GetBoolProperty("volumerendering.uselod",enabled);
m_Controls->m_EnableLOD->setEnabled(true);
m_Controls->m_EnableLOD->setChecked(enabled);
m_Controls->m_RenderMode->setEnabled(true);
// Determine Combo Box mode
{
bool usegpu=false;
bool useray=false;
bool usemip=false;
m_SelectedNode->GetBoolProperty("volumerendering.usegpu",usegpu);
// Only with VTK 5.6 or above
#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) ))
m_SelectedNode->GetBoolProperty("volumerendering.useray",useray);
#endif
m_SelectedNode->GetBoolProperty("volumerendering.usemip",usemip);
int mode = 0;
if(useray)
{
if(usemip)
mode=RM_GPU_MIP_RAYCAST;
else
mode=RM_GPU_COMPOSITE_RAYCAST;
}
else if(usegpu)
mode=RM_GPU_COMPOSITE_SLICING;
else
{
if(usemip)
mode=RM_CPU_MIP_RAYCAST;
else
mode=RM_CPU_COMPOSITE_RAYCAST;
}
m_Controls->m_RenderMode->setCurrentIndex(mode);
}
m_Controls->m_TransferFunctionWidget->SetDataNode(m_SelectedNode);
m_Controls->m_TransferFunctionWidget->setEnabled(true);
m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(m_SelectedNode);
m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(true);
}
void QmitkVolumeVisualizationView::OnEnableRendering(bool state)
{
if(m_SelectedNode.IsNull())
return;
m_SelectedNode->SetProperty("volumerendering",mitk::BoolProperty::New(state));
UpdateInterface();
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::OnEnableLOD(bool state)
{
if(m_SelectedNode.IsNull())
return;
m_SelectedNode->SetProperty("volumerendering.uselod",mitk::BoolProperty::New(state));
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::OnRenderMode(int mode)
{
if(m_SelectedNode.IsNull())
return;
bool usegpu=mode==RM_GPU_COMPOSITE_SLICING;
// Only with VTK 5.6 or above
#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) ))
bool useray=(mode==RM_GPU_COMPOSITE_RAYCAST)||(mode==RM_GPU_MIP_RAYCAST);
#endif
bool usemip=(mode==RM_GPU_MIP_RAYCAST)||(mode==RM_CPU_MIP_RAYCAST);
m_SelectedNode->SetProperty("volumerendering.usegpu",mitk::BoolProperty::New(usegpu));
// Only with VTK 5.6 or above
#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) ))
m_SelectedNode->SetProperty("volumerendering.useray",mitk::BoolProperty::New(useray));
#endif
m_SelectedNode->SetProperty("volumerendering.usemip",mitk::BoolProperty::New(usemip));
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::SetFocus()
{
}
void QmitkVolumeVisualizationView::NodeRemoved(const mitk::DataNode* node)
{
if(m_SelectedNode == node)
{
m_SelectedNode=0;
m_Controls->m_SelectedImageLabel->hide();
m_Controls->m_ErrorImageLabel->hide();
m_Controls->m_NoSelectedImageLabel->show();
UpdateInterface();
}
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkVolumeVisualizationView.h"
#include <QComboBox>
#include <vtkVersionMacros.h>
#include <berryISelectionProvider.h>
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
//#include <berryISelectionService.h>
#include <mitkDataNodeObject.h>
#include <mitkProperties.h>
#include <mitkNodePredicateDataType.h>
#include <mitkTransferFunction.h>
#include <mitkTransferFunctionProperty.h>
#include <mitkTransferFunctionInitializer.h>
#include "mitkHistogramGenerator.h"
#include "QmitkPiecewiseFunctionCanvas.h"
#include "QmitkColorTransferFunctionCanvas.h"
#include "mitkBaseRenderer.h"
#include "mitkVtkVolumeRenderingProperty.h"
#include <mitkIRenderingManager.h>
#include <QToolTip>
const std::string QmitkVolumeVisualizationView::VIEW_ID =
"org.mitk.views.volumevisualization";
enum RenderMode
{
RM_CPU_COMPOSITE_RAYCAST = 0,
RM_CPU_MIP_RAYCAST = 1,
RM_GPU_COMPOSITE_SLICING = 2,
RM_GPU_COMPOSITE_RAYCAST = 3,
RM_GPU_MIP_RAYCAST = 4
};
QmitkVolumeVisualizationView::QmitkVolumeVisualizationView()
: QmitkAbstractView(),
m_Controls(NULL)
{
}
QmitkVolumeVisualizationView::~QmitkVolumeVisualizationView()
{
}
void QmitkVolumeVisualizationView::CreateQtPartControl(QWidget* parent)
{
if (!m_Controls)
{
m_Controls = new Ui::QmitkVolumeVisualizationViewControls;
m_Controls->setupUi(parent);
// Fill the tf presets in the generator widget
std::vector<std::string> names;
mitk::TransferFunctionInitializer::GetPresetNames(names);
for (std::vector<std::string>::const_iterator it = names.begin();
it != names.end(); ++it)
{
m_Controls->m_TransferFunctionGeneratorWidget->AddPreset(QString::fromStdString(*it));
}
m_Controls->m_RenderMode->addItem("CPU raycast");
m_Controls->m_RenderMode->addItem("CPU MIP raycast");
m_Controls->m_RenderMode->addItem("GPU slicing");
// Only with VTK 5.6 or above
#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) ))
m_Controls->m_RenderMode->addItem("GPU raycast");
m_Controls->m_RenderMode->addItem("GPU MIP raycast");
#endif
connect( m_Controls->m_EnableRenderingCB, SIGNAL( toggled(bool) ),this, SLOT( OnEnableRendering(bool) ));
connect( m_Controls->m_EnableLOD, SIGNAL( toggled(bool) ),this, SLOT( OnEnableLOD(bool) ));
connect( m_Controls->m_RenderMode, SIGNAL( activated(int) ),this, SLOT( OnRenderMode(int) ));
connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL( SignalUpdateCanvas( ) ), m_Controls->m_TransferFunctionWidget, SLOT( OnUpdateCanvas( ) ) );
connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL(SignalTransferFunctionModeChanged(int)), SLOT(OnMitkInternalPreset(int)));
m_Controls->m_EnableRenderingCB->setEnabled(false);
m_Controls->m_EnableLOD->setEnabled(false);
m_Controls->m_RenderMode->setEnabled(false);
m_Controls->m_TransferFunctionWidget->setEnabled(false);
m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false);
m_Controls->m_SelectedImageLabel->hide();
m_Controls->m_ErrorImageLabel->hide();
}
}
void QmitkVolumeVisualizationView::OnMitkInternalPreset( int mode )
{
if (m_SelectedNode.IsNull()) return;
mitk::DataNode::Pointer node(m_SelectedNode.GetPointer());
mitk::TransferFunctionProperty::Pointer transferFuncProp;
if (node->GetProperty(transferFuncProp, "TransferFunction"))
{
//first item is only information
if( --mode == -1 )
return;
// -- Creat new TransferFunction
mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(transferFuncProp->GetValue());
tfInit->SetTransferFunctionMode(mode);
RequestRenderWindowUpdate();
m_Controls->m_TransferFunctionWidget->OnUpdateCanvas();
}
}
void QmitkVolumeVisualizationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList<mitk::DataNode::Pointer>& nodes)
{
bool weHadAnImageButItsNotThreeDeeOrFourDee = false;
mitk::DataNode::Pointer node;
foreach (mitk::DataNode::Pointer currentNode, nodes)
{
if( currentNode.IsNotNull() && dynamic_cast<mitk::Image*>(currentNode->GetData()) )
{
if( dynamic_cast<mitk::Image*>(currentNode->GetData())->GetDimension()>=3 )
{
if (node.IsNull())
{
node = currentNode;
}
}
else
{
weHadAnImageButItsNotThreeDeeOrFourDee = true;
}
}
}
if( node.IsNotNull() )
{
m_Controls->m_NoSelectedImageLabel->hide();
m_Controls->m_ErrorImageLabel->hide();
m_Controls->m_SelectedImageLabel->show();
std::string infoText;
if (node->GetName().empty())
infoText = std::string("Selected Image: [currently selected image has no name]");
else
infoText = std::string("Selected Image: ") + node->GetName();
m_Controls->m_SelectedImageLabel->setText( QString( infoText.c_str() ) );
m_SelectedNode = node;
}
else
{
if(weHadAnImageButItsNotThreeDeeOrFourDee)
{
m_Controls->m_NoSelectedImageLabel->hide();
m_Controls->m_ErrorImageLabel->show();
std::string infoText;
infoText = std::string("only 3D or 4D images are supported");
m_Controls->m_ErrorImageLabel->setText( QString( infoText.c_str() ) );
}
else
{
m_Controls->m_SelectedImageLabel->hide();
m_Controls->m_ErrorImageLabel->hide();
m_Controls->m_NoSelectedImageLabel->show();
}
m_SelectedNode = 0;
}
UpdateInterface();
}
void QmitkVolumeVisualizationView::UpdateInterface()
{
if(m_SelectedNode.IsNull())
{
// turnoff all
m_Controls->m_EnableRenderingCB->setChecked(false);
m_Controls->m_EnableRenderingCB->setEnabled(false);
m_Controls->m_EnableLOD->setChecked(false);
m_Controls->m_EnableLOD->setEnabled(false);
m_Controls->m_RenderMode->setCurrentIndex(0);
m_Controls->m_RenderMode->setEnabled(false);
m_Controls->m_TransferFunctionWidget->SetDataNode(0);
m_Controls->m_TransferFunctionWidget->setEnabled(false);
m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0);
m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false);
return;
}
bool enabled = false;
m_SelectedNode->GetBoolProperty("volumerendering",enabled);
m_Controls->m_EnableRenderingCB->setEnabled(true);
m_Controls->m_EnableRenderingCB->setChecked(enabled);
if(!enabled)
{
// turnoff all except volumerendering checkbox
m_Controls->m_EnableLOD->setChecked(false);
m_Controls->m_EnableLOD->setEnabled(false);
m_Controls->m_RenderMode->setCurrentIndex(0);
m_Controls->m_RenderMode->setEnabled(false);
m_Controls->m_TransferFunctionWidget->SetDataNode(0);
m_Controls->m_TransferFunctionWidget->setEnabled(false);
m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0);
m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false);
return;
}
// otherwise we can activate em all
enabled = false;
m_SelectedNode->GetBoolProperty("volumerendering.uselod",enabled);
m_Controls->m_EnableLOD->setEnabled(true);
m_Controls->m_EnableLOD->setChecked(enabled);
m_Controls->m_RenderMode->setEnabled(true);
// Determine Combo Box mode
{
bool usegpu=false;
bool useray=false;
bool usemip=false;
m_SelectedNode->GetBoolProperty("volumerendering.usegpu",usegpu);
// Only with VTK 5.6 or above
#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) ))
m_SelectedNode->GetBoolProperty("volumerendering.useray",useray);
#endif
m_SelectedNode->GetBoolProperty("volumerendering.usemip",usemip);
int mode = 0;
if(useray)
{
if(usemip)
mode=RM_GPU_MIP_RAYCAST;
else
mode=RM_GPU_COMPOSITE_RAYCAST;
}
else if(usegpu)
mode=RM_GPU_COMPOSITE_SLICING;
else
{
if(usemip)
mode=RM_CPU_MIP_RAYCAST;
else
mode=RM_CPU_COMPOSITE_RAYCAST;
}
m_Controls->m_RenderMode->setCurrentIndex(mode);
}
m_Controls->m_TransferFunctionWidget->SetDataNode(m_SelectedNode);
m_Controls->m_TransferFunctionWidget->setEnabled(true);
m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(m_SelectedNode);
m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(true);
}
void QmitkVolumeVisualizationView::OnEnableRendering(bool state)
{
if(m_SelectedNode.IsNull())
return;
m_SelectedNode->SetProperty("volumerendering",mitk::BoolProperty::New(state));
UpdateInterface();
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::OnEnableLOD(bool state)
{
if(m_SelectedNode.IsNull())
return;
m_SelectedNode->SetProperty("volumerendering.uselod",mitk::BoolProperty::New(state));
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::OnRenderMode(int mode)
{
if(m_SelectedNode.IsNull())
return;
bool usegpu=mode==RM_GPU_COMPOSITE_SLICING;
// Only with VTK 5.6 or above
#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) ))
bool useray=(mode==RM_GPU_COMPOSITE_RAYCAST)||(mode==RM_GPU_MIP_RAYCAST);
#endif
bool usemip=(mode==RM_GPU_MIP_RAYCAST)||(mode==RM_CPU_MIP_RAYCAST);
m_SelectedNode->SetProperty("volumerendering.usegpu",mitk::BoolProperty::New(usegpu));
// Only with VTK 5.6 or above
#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) ))
m_SelectedNode->SetProperty("volumerendering.useray",mitk::BoolProperty::New(useray));
#endif
m_SelectedNode->SetProperty("volumerendering.usemip",mitk::BoolProperty::New(usemip));
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::SetFocus()
{
}
void QmitkVolumeVisualizationView::NodeRemoved(const mitk::DataNode* node)
{
if(m_SelectedNode == node)
{
m_SelectedNode=0;
m_Controls->m_SelectedImageLabel->hide();
m_Controls->m_ErrorImageLabel->hide();
m_Controls->m_NoSelectedImageLabel->show();
UpdateInterface();
}
}
|
Add vtk include needed for version check to work
|
Add vtk include needed for version check to work
|
C++
|
bsd-3-clause
|
iwegner/MITK,MITK/MITK,MITK/MITK,fmilano/mitk,RabadanLab/MITKats,fmilano/mitk,NifTK/MITK,fmilano/mitk,RabadanLab/MITKats,RabadanLab/MITKats,NifTK/MITK,NifTK/MITK,RabadanLab/MITKats,iwegner/MITK,iwegner/MITK,MITK/MITK,iwegner/MITK,MITK/MITK,RabadanLab/MITKats,NifTK/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk,RabadanLab/MITKats,NifTK/MITK,iwegner/MITK,fmilano/mitk,fmilano/mitk,NifTK/MITK,iwegner/MITK,MITK/MITK
|
5fe8c50f1ca8c59793462b7e1331667b0df39d22
|
software/src/main.cpp
|
software/src/main.cpp
|
#include "DS18B20Temperature.h"
#include "HixConfig.h"
#include "HixMQTT.h"
#include "HixWebServer.h"
#include "secret.h"
#include <ArduinoOTA.h>
#include <FS.h>
#include <HixLED.h>
#include <HixPinDigitalInput.h>
#include <HixPinDigitalOutput.h>
#include <HixString.h>
#include <HixTimeout.h>
// runtime global variables
HixConfig g_config;
HixWebServer g_webServer(g_config);
HixMQTT g_mqtt(g_config,
Secret::WIFI_SSID,
Secret::WIFI_PWD,
g_config.getMQTTServer(),
g_config.getDeviceType(),
g_config.getDeviceVersion(),
g_config.getRoom(),
g_config.getDeviceTag());
//hardware related
HixPinDigitalOutput g_beeper(2);
HixPinDigitalOutput g_relay(14);
HixLED g_led(5);
HixPinDigitalInput g_motion(13);
HixPinDigitalInput g_switch(4);
DS18B20Temperature g_temperature(12);
//software related
HixTimeout g_sampler(1000, true);
HixTimeout g_logger(5000, true);
HixTimeout g_buttonTimeout(500, true);
HixTimeout g_motionTimeout(5000, true);
HixTimeout g_relayTimeout(g_config.getAutoSwitchOffSeconds() * 1000, true);
volatile bool g_bLedBlinking = false;
//sensor values
float g_fTemperature = 0;
volatile bool g_bDetectedMotion = false;
volatile bool g_bPressedSwitch = false;
//////////////////////////////////////////////////////////////////////////////////
// Helper functions
//////////////////////////////////////////////////////////////////////////////////
void configureOTA() {
Serial.println("Configuring OTA, my hostname:");
Serial.println(g_mqtt.getMqttClientName());
ArduinoOTA.setHostname(g_mqtt.getMqttClientName());
ArduinoOTA.setPort(8266);
//setup handlers
ArduinoOTA.onStart([]() {
Serial.println("OTA -> Start");
});
ArduinoOTA.onEnd([]() {
Serial.println("OTA -> End");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("OTA -> Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("OTA -> Error[%u]: ", error);
if (error == OTA_AUTH_ERROR)
Serial.println("OTA -> Auth Failed");
else if (error == OTA_BEGIN_ERROR)
Serial.println("OTA -> Begin Failed");
else if (error == OTA_CONNECT_ERROR)
Serial.println("OTA -> Connect Failed");
else if (error == OTA_RECEIVE_ERROR)
Serial.println("OTA -> Receive Failed");
else if (error == OTA_END_ERROR)
Serial.println("OTA -> End Failed");
});
ArduinoOTA.begin();
}
void resetWithMessage(const char * szMessage) {
Serial.println(szMessage);
delay(2000);
ESP.reset();
}
void selfTest(void) {
g_relay.blink(true, 5, 100);
g_led.blink(true, 5, 100);
g_beeper.blink(true, 5, 100);
}
bool heatingAllowed() {
//if not running no heating allowed
if (g_relayTimeout.isExpired()) {
return false;
}
//ok, heating is allowed...
//if we are currently on, keep heating until high temp reached
if (g_relay.isHigh()) {
return g_fTemperature < g_config.getSwitchOffTemperature();
}
//if currently off switch on if low temp reached
return g_fTemperature < g_config.getSwitchOnTemperature();
}
bool handlePresseeSwitch(void) {
if (!g_bPressedSwitch) return false;
g_bPressedSwitch = false;
//debouncing
if (g_buttonTimeout.isRunning()) {
return false;
}
g_buttonTimeout.restart();
//process command
if (g_relayTimeout.isRunning()) {
g_relayTimeout.invalidate();
} else {
g_relayTimeout.restart();
}
//handled something!
return true;
}
bool handleDetectedMotion(void) {
if (!g_bDetectedMotion) return false;
g_bDetectedMotion = false;
//debouncing
if (g_motionTimeout.isRunning()) {
return false;
}
g_motionTimeout.restart();
//handled something!
return true;
}
//////////////////////////////////////////////////////////////////////////////////
// ISR
//////////////////////////////////////////////////////////////////////////////////
ICACHE_RAM_ATTR void pressedSwitch(void) {
g_bPressedSwitch = true;
}
ICACHE_RAM_ATTR void detectedMotion(void) {
g_bDetectedMotion = true;
}
//////////////////////////////////////////////////////////////////////////////////
// Setup
//////////////////////////////////////////////////////////////////////////////////
void setup() {
//print startup config
Serial.begin(115200);
Serial.print(F("Startup "));
Serial.print(g_config.getDeviceType());
Serial.print(F(" "));
Serial.println(g_config.getDeviceVersion());
//disconnect WiFi -> seams to help for bug that after upload wifi does not want to connect again...
Serial.println(F("Disconnecting WIFI"));
WiFi.disconnect();
//init pins
Serial.println(F("Setting up Beeper"));
g_beeper.begin();
Serial.println(F("Setting up Relay"));
g_relay.begin();
Serial.println(F("Setting up LED"));
g_led.begin();
//setup temp sensor
Serial.println(F("Setting up temperature sensor"));
if (!g_temperature.begin()) resetWithMessage("DS18B20 init failed, resetting");
// configure MQTT
Serial.println(F("Setting up MQTT"));
if (!g_mqtt.begin()) resetWithMessage("MQTT allocation failed, resetting");
//setup SPIFFS
Serial.println(F("Setting up SPIFFS"));
if (!SPIFFS.begin()) resetWithMessage("SPIFFS initialization failed, resetting");
//setup the server
Serial.println(F("Setting up web server"));
g_webServer.begin();
//hookup switch
Serial.println(F("Hooking up the switch"));
g_switch.attachInterrupt(pressedSwitch, FALLING);
//hookup motion detector
Serial.println(F("Hooking up the motion detector"));
g_motion.attachInterrupt(detectedMotion, RISING);
// all done
Serial.println(F("Setup complete"));
}
//////////////////////////////////////////////////////////////////////////////////
// Loop
//////////////////////////////////////////////////////////////////////////////////
void loop() {
//other loop functions
g_mqtt.loop();
g_webServer.handleClient();
ArduinoOTA.handle();
//isr handles & check if should do force publishing
bool bHandledMotion = handleDetectedMotion();
bool bHandledSwitch = handlePresseeSwitch();
if (bHandledSwitch) g_beeper.blink(true, 1, 150);
bool bForcePublishing = bHandledMotion || bHandledSwitch;
//now we calculated if we should forcepublishing we also set motion to true if its still high...
bHandledMotion = bHandledMotion || g_motion.isHigh();
//beep while motion detected
//g_beeper.digitalWrite(bHandledMotion);
//update relay
g_relay.digitalWrite(heatingAllowed());
//blink led if not connected
if (g_mqtt.isConnected()) {
//if allowed to heat
if (g_relayTimeout.isRunning()) {
//and we are actually heating
if (g_relay.isHigh()) {
g_led.on();
}
//no not heating must be to warm...
else {
g_led.fadeInOut();
}
}
//not allow to heat switch off led
else {
g_led.off();
}
} else {
g_led.fastBlink();
}
//my own processing
if (g_sampler.isExpired(true) || bForcePublishing) {
// load sensor values
g_fTemperature = g_temperature.getTemp();
// log to serial
Serial.print(g_fTemperature);
Serial.print(F(" C ; "));
Serial.print(bHandledMotion);
Serial.print(F(" B ; "));
Serial.print(bHandledSwitch);
Serial.print(F(" B ; "));
Serial.print(g_beeper.isHigh());
Serial.print(F(" B ; "));
Serial.print(g_relayTimeout.isRunning());
Serial.print(F(" B ; "));
Serial.print(g_relay.isHigh());
Serial.print(F(" B"));
Serial.println();
}
if (g_logger.isExpired(true) || bForcePublishing) {
g_mqtt.publishStatusValues(g_fTemperature, bHandledMotion, bHandledSwitch, g_beeper.isHigh(), g_relayTimeout.isRunning(), g_relay.isHigh(), g_relayTimeout.timeLeftMs() / 1000);
}
}
//////////////////////////////////////////////////////////////////////////////////
// Required by the MQTT library
//////////////////////////////////////////////////////////////////////////////////
void onConnectionEstablished() {
//setup OTA
if (g_config.getOTAEnabled()) {
configureOTA();
} else {
Serial.println("OTA is disabled");
}
//publish values
g_mqtt.publishDeviceValues();
g_mqtt.publishStatusValues(g_fTemperature, g_bDetectedMotion, g_bPressedSwitch, g_beeper.isHigh(), g_relayTimeout.isRunning(), g_relay.isHigh(), g_relayTimeout.timeLeftMs() / 1000);
//register for display
g_mqtt.subscribe(g_mqtt.topicForPath("subscribe/desired_temperature"), [](const String & payload) {
g_config.setDesiredTemperature(payload.toFloat());
g_config.commitToEEPROM();
g_beeper.blink(1, 1, 10);
g_mqtt.publishDeviceValues();
});
//register for beeper
g_mqtt.subscribe(g_mqtt.topicForPath("subscribe/auto_switchoff_seconds"), [](const String & payload) {
g_config.setAutoSwitchOffSeconds(payload.toInt());
g_relayTimeout.updateTimeoutAndRestart(g_config.getAutoSwitchOffSeconds()*1000);
g_config.commitToEEPROM();
g_beeper.blink(1, 1, 10);
g_mqtt.publishDeviceValues();
});
//register for enable switching on
g_mqtt.subscribe(g_mqtt.topicForPath("subscribe/output_toggle"), [](const String & payload) {
pressedSwitch();
});
}
|
#include "DS18B20Temperature.h"
#include "HixConfig.h"
#include "HixMQTT.h"
#include "HixWebServer.h"
#include "secret.h"
#include <ArduinoOTA.h>
#include <FS.h>
#include <HixLED.h>
#include <HixPinDigitalInput.h>
#include <HixPinDigitalOutput.h>
#include <HixString.h>
#include <HixTimeout.h>
// runtime global variables
HixConfig g_config;
HixWebServer g_webServer(g_config);
HixMQTT g_mqtt(g_config,
Secret::WIFI_SSID,
Secret::WIFI_PWD,
g_config.getMQTTServer(),
g_config.getDeviceType(),
g_config.getDeviceVersion(),
g_config.getRoom(),
g_config.getDeviceTag());
//hardware related
HixPinDigitalOutput g_beeper(2);
HixPinDigitalOutput g_relay(14);
HixLED g_led(5);
HixPinDigitalInput g_motion(13);
HixPinDigitalInput g_switch(4);
DS18B20Temperature g_temperature(12);
//software related
HixTimeout g_sampler(1000, true);
HixTimeout g_logger(5000, true);
HixTimeout g_buttonTimeout(500, true);
HixTimeout g_motionTimeout(5000, true);
HixTimeout g_relayTimeout(g_config.getAutoSwitchOffSeconds() * 1000, true);
volatile bool g_bLedBlinking = false;
//sensor values
float g_fTemperature = 0;
volatile bool g_bDetectedMotion = false;
volatile bool g_bPressedSwitch = false;
//////////////////////////////////////////////////////////////////////////////////
// Helper functions
//////////////////////////////////////////////////////////////////////////////////
void configureOTA() {
Serial.println("Configuring OTA, my hostname:");
Serial.println(g_mqtt.getMqttClientName());
ArduinoOTA.setHostname(g_mqtt.getMqttClientName());
ArduinoOTA.setPort(8266);
//setup handlers
ArduinoOTA.onStart([]() {
Serial.println("OTA -> Start");
});
ArduinoOTA.onEnd([]() {
Serial.println("OTA -> End");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("OTA -> Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("OTA -> Error[%u]: ", error);
if (error == OTA_AUTH_ERROR)
Serial.println("OTA -> Auth Failed");
else if (error == OTA_BEGIN_ERROR)
Serial.println("OTA -> Begin Failed");
else if (error == OTA_CONNECT_ERROR)
Serial.println("OTA -> Connect Failed");
else if (error == OTA_RECEIVE_ERROR)
Serial.println("OTA -> Receive Failed");
else if (error == OTA_END_ERROR)
Serial.println("OTA -> End Failed");
});
ArduinoOTA.begin();
}
void resetWithMessage(const char * szMessage) {
Serial.println(szMessage);
delay(2000);
ESP.reset();
}
void selfTest(void) {
g_relay.blink(true, 5, 100);
g_led.blink(true, 5, 100);
g_beeper.blink(true, 5, 100);
}
bool heatingAllowed() {
//if not running no heating allowed
if (g_relayTimeout.isExpired()) {
return false;
}
//ok, heating is allowed...
//if we are currently on, keep heating until high temp reached
if (g_relay.isHigh()) {
return g_fTemperature < g_config.getSwitchOffTemperature();
}
//if currently off switch on if low temp reached
return g_fTemperature < g_config.getSwitchOnTemperature();
}
bool handlePresseeSwitch(void) {
if (!g_bPressedSwitch) return false;
g_bPressedSwitch = false;
//debouncing
if (g_buttonTimeout.isRunning()) {
return false;
}
g_buttonTimeout.restart();
//process command
if (g_relayTimeout.isRunning()) {
g_relayTimeout.invalidate();
} else {
g_relayTimeout.restart();
}
//handled something!
return true;
}
bool handleDetectedMotion(void) {
if (!g_bDetectedMotion) return false;
g_bDetectedMotion = false;
//debouncing
if (g_motionTimeout.isRunning()) {
return false;
}
g_motionTimeout.restart();
//handled something!
return true;
}
//////////////////////////////////////////////////////////////////////////////////
// ISR
//////////////////////////////////////////////////////////////////////////////////
ICACHE_RAM_ATTR void pressedSwitch(void) {
g_bPressedSwitch = true;
}
ICACHE_RAM_ATTR void detectedMotion(void) {
g_bDetectedMotion = true;
}
//////////////////////////////////////////////////////////////////////////////////
// Setup
//////////////////////////////////////////////////////////////////////////////////
void setup() {
//print startup config
Serial.begin(115200);
Serial.print(F("Startup "));
Serial.print(g_config.getDeviceType());
Serial.print(F(" "));
Serial.println(g_config.getDeviceVersion());
//disconnect WiFi -> seams to help for bug that after upload wifi does not want to connect again...
Serial.println(F("Disconnecting WIFI"));
WiFi.disconnect();
//init pins
Serial.println(F("Setting up Beeper"));
g_beeper.begin();
Serial.println(F("Setting up Relay"));
g_relay.begin();
Serial.println(F("Setting up LED"));
g_led.begin();
//setup temp sensor
Serial.println(F("Setting up temperature sensor"));
if (!g_temperature.begin()) resetWithMessage("DS18B20 init failed, resetting");
// configure MQTT
Serial.println(F("Setting up MQTT"));
if (!g_mqtt.begin()) resetWithMessage("MQTT allocation failed, resetting");
//setup SPIFFS
Serial.println(F("Setting up SPIFFS"));
if (!SPIFFS.begin()) resetWithMessage("SPIFFS initialization failed, resetting");
//setup the server
Serial.println(F("Setting up web server"));
g_webServer.begin();
//hookup switch
Serial.println(F("Hooking up the switch"));
g_switch.attachInterrupt(pressedSwitch, FALLING);
//hookup motion detector
Serial.println(F("Hooking up the motion detector"));
g_motion.begin();
g_motion.attachInterrupt(detectedMotion, RISING);
// all done
Serial.println(F("Setup complete"));
}
//////////////////////////////////////////////////////////////////////////////////
// Loop
//////////////////////////////////////////////////////////////////////////////////
void loop() {
//other loop functions
g_mqtt.loop();
g_webServer.handleClient();
ArduinoOTA.handle();
//isr handles & check if should do force publishing
bool bHandledMotion = handleDetectedMotion();
bool bHandledSwitch = handlePresseeSwitch();
if (bHandledSwitch) g_beeper.blink(true, 1, 150);
bool bForcePublishing = bHandledMotion || bHandledSwitch;
//now we calculated if we should forcepublishing we also set motion to true if its still high...
bHandledMotion = bHandledMotion || g_motion.isHigh();
//beep while motion detected
//g_beeper.digitalWrite(bHandledMotion);
//update relay
g_relay.digitalWrite(heatingAllowed());
//blink led if not connected
if (g_mqtt.isConnected()) {
//if allowed to heat
if (g_relayTimeout.isRunning()) {
//and we are actually heating
if (g_relay.isHigh()) {
g_led.on();
}
//no not heating must be to warm...
else {
g_led.fadeInOut();
}
}
//not allow to heat switch off led
else {
g_led.off();
}
} else {
g_led.fastBlink();
}
//my own processing
if (g_sampler.isExpired(true) || bForcePublishing) {
// load sensor values
g_fTemperature = g_temperature.getTemp();
// log to serial
Serial.print(g_fTemperature);
Serial.print(F(" C ; "));
Serial.print(bHandledMotion);
Serial.print(F(" B ; "));
Serial.print(bHandledSwitch);
Serial.print(F(" B ; "));
Serial.print(g_beeper.isHigh());
Serial.print(F(" B ; "));
Serial.print(g_relayTimeout.isRunning());
Serial.print(F(" B ; "));
Serial.print(g_relay.isHigh());
Serial.print(F(" B"));
Serial.println();
}
if (g_logger.isExpired(true) || bForcePublishing) {
g_mqtt.publishStatusValues(g_fTemperature, bHandledMotion, bHandledSwitch, g_beeper.isHigh(), g_relayTimeout.isRunning(), g_relay.isHigh(), g_relayTimeout.timeLeftMs() / 1000);
}
}
//////////////////////////////////////////////////////////////////////////////////
// Required by the MQTT library
//////////////////////////////////////////////////////////////////////////////////
void onConnectionEstablished() {
//setup OTA
if (g_config.getOTAEnabled()) {
configureOTA();
} else {
Serial.println("OTA is disabled");
}
//publish values
g_mqtt.publishDeviceValues();
g_mqtt.publishStatusValues(g_fTemperature, g_bDetectedMotion, g_bPressedSwitch, g_beeper.isHigh(), g_relayTimeout.isRunning(), g_relay.isHigh(), g_relayTimeout.timeLeftMs() / 1000);
//register for display
g_mqtt.subscribe(g_mqtt.topicForPath("subscribe/desired_temperature"), [](const String & payload) {
g_config.setDesiredTemperature(payload.toFloat());
g_config.commitToEEPROM();
g_beeper.blink(1, 1, 10);
g_mqtt.publishDeviceValues();
});
//register for beeper
g_mqtt.subscribe(g_mqtt.topicForPath("subscribe/auto_switchoff_seconds"), [](const String & payload) {
g_config.setAutoSwitchOffSeconds(payload.toInt());
g_relayTimeout.updateTimeoutAndRestart(g_config.getAutoSwitchOffSeconds()*1000);
g_config.commitToEEPROM();
g_beeper.blink(1, 1, 10);
g_mqtt.publishDeviceValues();
});
//register for enable switching on
g_mqtt.subscribe(g_mqtt.topicForPath("subscribe/output_toggle"), [](const String & payload) {
pressedSwitch();
});
}
|
add input interupt begin
|
add input interupt begin
|
C++
|
mit
|
hixfield/ESP8266Power,hixfield/ESP8266Power
|
3c8df403433be820521809c4735dd2a0a14db620
|
source/FAST/Visualization/ComputationThread.cpp
|
source/FAST/Visualization/ComputationThread.cpp
|
#include "ComputationThread.hpp"
#include "SimpleWindow.hpp"
#include "View.hpp"
#include <QGLContext>
namespace fast {
ComputationThread::ComputationThread(QThread* mainThread) {
mIsRunning = false;
mStop = false;
mMainThread = mainThread;
}
void ComputationThread::addView(View* view) {
mViews.push_back(view);
}
void ComputationThread::clearViews() {
mViews.clear();
}
ComputationThread::~ComputationThread() {
reportInfo() << "Computation thread object destroyed" << Reporter::end();
}
bool ComputationThread::isRunning() {
return mIsRunning;
}
void ComputationThread::run() {
// This is run in the secondary (computation thread)
{
std::unique_lock<std::mutex> lock(mUpdateThreadMutex); // this locks the mutex
mIsRunning = true;
mStop = false;
}
QGLContext* mainGLContext = Window::getMainGLContext();
mainGLContext->makeCurrent();
uint executeToken = 0;
while(true) {
{
std::unique_lock<std::mutex> lock(mUpdateThreadMutex); // this locks the mutex
if(mStop)
break;
}
try {
for(auto po : m_processObjects)
po->update(executeToken);
for(View *view : mViews) {
view->updateRenderersInput(executeToken);
}
for(View *view : mViews) {
view->updateRenderers();
}
} catch(ThreadStopped &e) {
reportInfo() << "Thread stopped exception occured in ComputationThread, exiting.." << reportEnd();
break;
}
++executeToken;
}
// Move GL context back to main thread
mainGLContext->doneCurrent();
mainGLContext->moveToThread(mMainThread);
emit finished();
reportInfo() << "Computation thread has finished in run()" << Reporter::end();
{
std::unique_lock<std::mutex> lock(mUpdateThreadMutex); // this locks the mutex
mIsRunning = false;
}
mUpdateThreadConditionVariable.notify_one();
}
void ComputationThread::stop() {
std::unique_lock<std::mutex> lock(mUpdateThreadMutex); // this locks the mutex
mStop = true;
// This is run in the main thread
reportInfo() << "Stopping pipelines and waking any blocking threads..." << Reporter::end();
for(View* view : mViews) {
view->stopRenderers();
}
reportInfo() << "Pipelines stopped" << Reporter::end();
reportInfo() << "Stopping computation thread..." << Reporter::end();
// Block until mIsRunning is set to false
while(mIsRunning) {
// Unlocks the mutex and wait until someone calls notify.
// When it wakes, the mutex is locked again and mIsRunning is checked.
mUpdateThreadConditionVariable.wait(lock);
}
reportInfo() << "Computation thread stopped" << Reporter::end();
for(View* view : mViews) {
view->resetRenderers();
}
}
void ComputationThread::setProcessObjects(std::vector<std::shared_ptr<ProcessObject>> pos) {
m_processObjects = pos;
}
}
|
#include "ComputationThread.hpp"
#include "SimpleWindow.hpp"
#include "View.hpp"
#include <QGLContext>
namespace fast {
ComputationThread::ComputationThread(QThread* mainThread) {
mIsRunning = false;
mStop = false;
mMainThread = mainThread;
}
void ComputationThread::addView(View* view) {
mViews.push_back(view);
}
void ComputationThread::clearViews() {
mViews.clear();
}
ComputationThread::~ComputationThread() {
reportInfo() << "Computation thread object destroyed" << Reporter::end();
}
bool ComputationThread::isRunning() {
return mIsRunning;
}
void ComputationThread::run() {
// This is run in the secondary (computation thread)
{
std::unique_lock<std::mutex> lock(mUpdateThreadMutex); // this locks the mutex
mIsRunning = true;
mStop = false;
}
QGLContext* mainGLContext = Window::getMainGLContext();
mainGLContext->makeCurrent();
uint executeToken = 0;
while(true) {
bool canUpdate = false;
{
std::unique_lock<std::mutex> lock(mUpdateThreadMutex); // this locks the mutex
if(mStop)
break;
if(m_processObjects.size() > 0)
canUpdate = true;
for(View* view : mViews) {
auto rendererList = view->getRenderers();
if(rendererList.size() > 0)
canUpdate = true;
}
}
if(!canUpdate) { // There is nothing for this computation thread to do atm, sleep a short while
std::this_thread::sleep_for(std::chrono::milliseconds(50));
continue;
}
try {
for(auto po : m_processObjects)
po->update(executeToken);
for(View *view : mViews) {
view->updateRenderersInput(executeToken);
}
for(View *view : mViews) {
view->updateRenderers();
}
} catch(ThreadStopped &e) {
reportInfo() << "Thread stopped exception occured in ComputationThread, exiting.." << reportEnd();
break;
}
++executeToken;
}
// Move GL context back to main thread
mainGLContext->doneCurrent();
mainGLContext->moveToThread(mMainThread);
emit finished();
reportInfo() << "Computation thread has finished in run()" << Reporter::end();
{
std::unique_lock<std::mutex> lock(mUpdateThreadMutex); // this locks the mutex
mIsRunning = false;
}
mUpdateThreadConditionVariable.notify_one();
}
void ComputationThread::stop() {
std::unique_lock<std::mutex> lock(mUpdateThreadMutex); // this locks the mutex
mStop = true;
// This is run in the main thread
reportInfo() << "Stopping pipelines and waking any blocking threads..." << Reporter::end();
for(View* view : mViews) {
view->stopRenderers();
}
reportInfo() << "Pipelines stopped" << Reporter::end();
reportInfo() << "Stopping computation thread..." << Reporter::end();
// Block until mIsRunning is set to false
while(mIsRunning) {
// Unlocks the mutex and wait until someone calls notify.
// When it wakes, the mutex is locked again and mIsRunning is checked.
mUpdateThreadConditionVariable.wait(lock);
}
reportInfo() << "Computation thread stopped" << Reporter::end();
for(View* view : mViews) {
view->resetRenderers();
}
}
void ComputationThread::setProcessObjects(std::vector<std::shared_ptr<ProcessObject>> pos) {
m_processObjects = pos;
}
}
|
Put ComputationThread to sleep if there is nothing for it to do
|
Put ComputationThread to sleep if there is nothing for it to do
|
C++
|
bsd-2-clause
|
smistad/FAST,smistad/FAST,smistad/FAST
|
93712f903d3daf9ed18269de1637f0d37ccb36c6
|
src/bp/Connection.cxx
|
src/bp/Connection.cxx
|
/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 "Connection.hxx"
#include "RLogger.hxx"
#include "Handler.hxx"
#include "Instance.hxx"
#include "strmap.hxx"
#include "http_server/http_server.hxx"
#include "http/IncomingRequest.hxx"
#include "http_server/Handler.hxx"
#include "http_server/Error.hxx"
#include "nghttp2/Server.hxx"
#include "drop.hxx"
#include "address_string.hxx"
#include "pool/UniquePtr.hxx"
#include "fs/FilteredSocket.hxx"
#include "ssl/Filter.hxx"
#include "net/SocketProtocolError.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "net/SocketAddress.hxx"
#include "net/StaticSocketAddress.hxx"
#include "system/Error.hxx"
#include "util/Exception.hxx"
#include "pool/pool.hxx"
#include <assert.h>
#include <unistd.h>
BpConnection::BpConnection(PoolPtr &&_pool, BpInstance &_instance,
const char *_listener_tag,
bool _auth_alt_host,
SocketAddress remote_address,
const SslFilter *ssl_filter) noexcept
:PoolHolder(std::move(_pool)),
instance(_instance),
config(_instance.config),
listener_tag(_listener_tag),
auth_alt_host(_auth_alt_host),
remote_host_and_port(address_to_string(pool, remote_address)),
logger(remote_host_and_port),
peer_subject(ssl_filter != nullptr
? ssl_filter_get_peer_subject(*ssl_filter)
: nullptr),
peer_issuer_subject(ssl_filter != nullptr
? ssl_filter_get_peer_issuer_subject(*ssl_filter)
: nullptr)
{
}
BpConnection::~BpConnection() noexcept
{
if (http != nullptr)
http_server_connection_close(http);
pool_trash(pool);
}
void
BpConnection::Disposer::operator()(BpConnection *c) noexcept
{
c->~BpConnection();
}
void
close_connection(BpConnection *connection) noexcept
{
auto &connections = connection->instance.connections;
assert(!connections.empty());
connections.erase_and_dispose(connections.iterator_to(*connection),
BpConnection::Disposer());
}
gcc_pure
static int
HttpServerLogLevel(std::exception_ptr e) noexcept
{
try {
FindRetrowNested<HttpServerSocketError>(e);
} catch (const HttpServerSocketError &) {
e = std::current_exception();
/* some socket errors caused by our client are less
important */
try {
FindRetrowNested<std::system_error>(e);
} catch (const std::system_error &se) {
if (IsErrno(se, ECONNRESET))
return 4;
}
try {
FindRetrowNested<SocketProtocolError>(e);
} catch (...) {
return 4;
}
}
return 2;
}
/*
* http connection handler
*
*/
void
BpConnection::RequestHeadersFinished(IncomingHttpRequest &request) noexcept
{
++instance.http_request_counter;
request.logger = NewFromPool<BpRequestLogger>(request.pool, instance);
}
void
BpConnection::HandleHttpRequest(IncomingHttpRequest &request,
const StopwatchPtr &parent_stopwatch,
CancellablePointer &cancel_ptr) noexcept
{
handle_http_request(*this, request, parent_stopwatch, cancel_ptr);
}
void
BpConnection::HttpConnectionError(std::exception_ptr e) noexcept
{
http = nullptr;
logger(HttpServerLogLevel(e), e);
close_connection(this);
}
void
BpConnection::HttpConnectionClosed() noexcept
{
http = nullptr;
close_connection(this);
}
/*
* listener handler
*
*/
#ifdef HAVE_NGHTTP2
static bool
IsAlpnHttp2(ConstBuffer<unsigned char> alpn) noexcept
{
return alpn != nullptr && alpn.size == 2 &&
alpn[0] == 'h' && alpn[1] == '2';
}
#endif
void
new_connection(PoolPtr pool, BpInstance &instance,
UniquePoolPtr<FilteredSocket> socket,
const SslFilter *ssl_filter,
SocketAddress address,
const char *listener_tag, bool auth_alt_host) noexcept
{
if (instance.connections.size() >= instance.config.max_connections) {
unsigned num_dropped = drop_some_connections(&instance);
if (num_dropped == 0) {
LogConcat(1, "connection", "too many connections (",
unsigned(instance.connections.size()),
", dropping");
return;
}
}
/* determine the local socket address */
const auto local_address = socket->GetSocket().GetLocalAddress();
auto *connection = NewFromPool<BpConnection>(std::move(pool), instance,
listener_tag, auth_alt_host,
address, ssl_filter);
instance.connections.push_front(*connection);
#ifdef HAVE_NGHTTP2
if (ssl_filter != nullptr &&
IsAlpnHttp2(ssl_filter_get_alpn_selected(*ssl_filter)))
connection->http2 = UniquePoolPtr<NgHttp2::ServerConnection>::Make(connection->GetPool(),
connection->GetPool(),
std::move(socket),
address,
*connection);
else
#endif
connection->http =
http_server_connection_new(connection->GetPool(),
std::move(socket),
local_address.IsDefined()
? (SocketAddress)local_address
: nullptr,
address,
true,
*connection);
#ifndef HAVE_NGHTTP2
(void)ssl_filter;
#endif
}
|
/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 "Connection.hxx"
#include "RLogger.hxx"
#include "Handler.hxx"
#include "Instance.hxx"
#include "strmap.hxx"
#include "http_server/http_server.hxx"
#include "http/IncomingRequest.hxx"
#include "http_server/Handler.hxx"
#include "http_server/Error.hxx"
#include "drop.hxx"
#include "address_string.hxx"
#include "pool/UniquePtr.hxx"
#include "fs/FilteredSocket.hxx"
#include "ssl/Filter.hxx"
#include "net/SocketProtocolError.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "net/SocketAddress.hxx"
#include "net/StaticSocketAddress.hxx"
#include "system/Error.hxx"
#include "util/Exception.hxx"
#include "pool/pool.hxx"
#ifdef HAVE_NGHTTP2
#include "nghttp2/Server.hxx"
#endif
#include <assert.h>
#include <unistd.h>
BpConnection::BpConnection(PoolPtr &&_pool, BpInstance &_instance,
const char *_listener_tag,
bool _auth_alt_host,
SocketAddress remote_address,
const SslFilter *ssl_filter) noexcept
:PoolHolder(std::move(_pool)),
instance(_instance),
config(_instance.config),
listener_tag(_listener_tag),
auth_alt_host(_auth_alt_host),
remote_host_and_port(address_to_string(pool, remote_address)),
logger(remote_host_and_port),
peer_subject(ssl_filter != nullptr
? ssl_filter_get_peer_subject(*ssl_filter)
: nullptr),
peer_issuer_subject(ssl_filter != nullptr
? ssl_filter_get_peer_issuer_subject(*ssl_filter)
: nullptr)
{
}
BpConnection::~BpConnection() noexcept
{
if (http != nullptr)
http_server_connection_close(http);
pool_trash(pool);
}
void
BpConnection::Disposer::operator()(BpConnection *c) noexcept
{
c->~BpConnection();
}
void
close_connection(BpConnection *connection) noexcept
{
auto &connections = connection->instance.connections;
assert(!connections.empty());
connections.erase_and_dispose(connections.iterator_to(*connection),
BpConnection::Disposer());
}
gcc_pure
static int
HttpServerLogLevel(std::exception_ptr e) noexcept
{
try {
FindRetrowNested<HttpServerSocketError>(e);
} catch (const HttpServerSocketError &) {
e = std::current_exception();
/* some socket errors caused by our client are less
important */
try {
FindRetrowNested<std::system_error>(e);
} catch (const std::system_error &se) {
if (IsErrno(se, ECONNRESET))
return 4;
}
try {
FindRetrowNested<SocketProtocolError>(e);
} catch (...) {
return 4;
}
}
return 2;
}
/*
* http connection handler
*
*/
void
BpConnection::RequestHeadersFinished(IncomingHttpRequest &request) noexcept
{
++instance.http_request_counter;
request.logger = NewFromPool<BpRequestLogger>(request.pool, instance);
}
void
BpConnection::HandleHttpRequest(IncomingHttpRequest &request,
const StopwatchPtr &parent_stopwatch,
CancellablePointer &cancel_ptr) noexcept
{
handle_http_request(*this, request, parent_stopwatch, cancel_ptr);
}
void
BpConnection::HttpConnectionError(std::exception_ptr e) noexcept
{
http = nullptr;
logger(HttpServerLogLevel(e), e);
close_connection(this);
}
void
BpConnection::HttpConnectionClosed() noexcept
{
http = nullptr;
close_connection(this);
}
/*
* listener handler
*
*/
#ifdef HAVE_NGHTTP2
static bool
IsAlpnHttp2(ConstBuffer<unsigned char> alpn) noexcept
{
return alpn != nullptr && alpn.size == 2 &&
alpn[0] == 'h' && alpn[1] == '2';
}
#endif
void
new_connection(PoolPtr pool, BpInstance &instance,
UniquePoolPtr<FilteredSocket> socket,
const SslFilter *ssl_filter,
SocketAddress address,
const char *listener_tag, bool auth_alt_host) noexcept
{
if (instance.connections.size() >= instance.config.max_connections) {
unsigned num_dropped = drop_some_connections(&instance);
if (num_dropped == 0) {
LogConcat(1, "connection", "too many connections (",
unsigned(instance.connections.size()),
", dropping");
return;
}
}
/* determine the local socket address */
const auto local_address = socket->GetSocket().GetLocalAddress();
auto *connection = NewFromPool<BpConnection>(std::move(pool), instance,
listener_tag, auth_alt_host,
address, ssl_filter);
instance.connections.push_front(*connection);
#ifdef HAVE_NGHTTP2
if (ssl_filter != nullptr &&
IsAlpnHttp2(ssl_filter_get_alpn_selected(*ssl_filter)))
connection->http2 = UniquePoolPtr<NgHttp2::ServerConnection>::Make(connection->GetPool(),
connection->GetPool(),
std::move(socket),
address,
*connection);
else
#endif
connection->http =
http_server_connection_new(connection->GetPool(),
std::move(socket),
local_address.IsDefined()
? (SocketAddress)local_address
: nullptr,
address,
true,
*connection);
#ifndef HAVE_NGHTTP2
(void)ssl_filter;
#endif
}
|
fix build without nghttp2
|
bp/Connection: fix build without nghttp2
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
667f48b5ef5cdda883488cf5e07d75744d76c919
|
src/build_log_test.cc
|
src/build_log_test.cc
|
#include "build_log.h"
#include "test.h"
struct BuildLogTest : public StateTestWithBuiltinRules {
virtual void SetUp() {
log_filename_ = tempnam(NULL, "ninja");
}
virtual void TearDown() {
unlink(log_filename_.c_str());
}
string log_filename_;
};
TEST_F(BuildLogTest, WriteRead) {
AssertParse(&state_,
"build out: cat mid\n"
"build mid: cat in\n");
BuildLog log1;
string err;
EXPECT_TRUE(log1.OpenForWrite(log_filename_, &err));
ASSERT_EQ("", err);
log1.RecordCommand(state_.edges_[0], 15);
log1.RecordCommand(state_.edges_[1], 20);
log1.Close();
BuildLog log2;
EXPECT_TRUE(log2.Load(log_filename_, &err));
ASSERT_EQ("", err);
ASSERT_EQ(2, log1.log_.size());
ASSERT_EQ(2, log2.log_.size());
BuildLog::LogEntry* e1 = log1.LookupByOutput("out");
ASSERT_TRUE(e1);
BuildLog::LogEntry* e2 = log2.LookupByOutput("out");
ASSERT_TRUE(e2);
ASSERT_TRUE(*e1 == *e2);
ASSERT_EQ(15, e1->time_ms);
ASSERT_EQ("out", e1->output);
}
TEST_F(BuildLogTest, DoubleEntry) {
FILE* f = fopen(log_filename_.c_str(), "wb");
fprintf(f, "0 out command abc\n");
fprintf(f, "0 out command def\n");
fclose(f);
string err;
BuildLog log;
EXPECT_TRUE(log.Load(log_filename_, &err));
ASSERT_EQ("", err);
BuildLog::LogEntry* e = log.LookupByOutput("out");
ASSERT_TRUE(e);
ASSERT_EQ("command def", e->command);
}
|
#include "build_log.h"
#include "test.h"
static const char kTestFilename[] = "BuildLogTest-tempfile";
struct BuildLogTest : public StateTestWithBuiltinRules {
virtual void SetUp() {
}
virtual void TearDown() {
unlink(kTestFilename);
}
};
TEST_F(BuildLogTest, WriteRead) {
AssertParse(&state_,
"build out: cat mid\n"
"build mid: cat in\n");
BuildLog log1;
string err;
EXPECT_TRUE(log1.OpenForWrite(kTestFilename, &err));
ASSERT_EQ("", err);
log1.RecordCommand(state_.edges_[0], 15);
log1.RecordCommand(state_.edges_[1], 20);
log1.Close();
BuildLog log2;
EXPECT_TRUE(log2.Load(kTestFilename, &err));
ASSERT_EQ("", err);
ASSERT_EQ(2, log1.log_.size());
ASSERT_EQ(2, log2.log_.size());
BuildLog::LogEntry* e1 = log1.LookupByOutput("out");
ASSERT_TRUE(e1);
BuildLog::LogEntry* e2 = log2.LookupByOutput("out");
ASSERT_TRUE(e2);
ASSERT_TRUE(*e1 == *e2);
ASSERT_EQ(15, e1->time_ms);
ASSERT_EQ("out", e1->output);
}
TEST_F(BuildLogTest, DoubleEntry) {
FILE* f = fopen(kTestFilename, "wb");
fprintf(f, "0 out command abc\n");
fprintf(f, "0 out command def\n");
fclose(f);
string err;
BuildLog log;
EXPECT_TRUE(log.Load(kTestFilename, &err));
ASSERT_EQ("", err);
BuildLog::LogEntry* e = log.LookupByOutput("out");
ASSERT_TRUE(e);
ASSERT_EQ("command def", e->command);
}
|
remove tempnam
|
remove tempnam
|
C++
|
apache-2.0
|
automeka/ninja,drbo/ninja,pathscale/ninja,purcell/ninja,sorbits/ninja,cipriancraciun/ninja,maximuska/ninja,jhanssen/ninja,kimgr/ninja,jimon/ninja,dpwright/ninja,tychoish/ninja,nornagon/ninja,okuoku/ninja,guiquanz/ninja,glensc/ninja,fifoforlifo/ninja,maruel/ninja,mgaunard/ninja,dabrahams/ninja,kissthink/ninja,sgraham/ninja,ninja-build/ninja,kimgr/ninja,purcell/ninja,PetrWolf/ninja-main,chenyukang/ninja,synaptek/ninja,jimon/ninja,jendrikillner/ninja,iwadon/ninja,barak/ninja,jhanssen/ninja,PetrWolf/ninja-main,ndsol/subninja,kissthink/ninja,nickhutchinson/ninja,tfarina/ninja,tfarina/ninja,nickhutchinson/ninja,synaptek/ninja,ctiller/ninja,nickhutchinson/ninja,autopulated/ninja,Maratyszcza/ninja-pypi,sxlin/dist_ninja,nicolasdespres/ninja,nafest/ninja,ikarienator/ninja,mydongistiny/ninja,ukai/ninja,metti/ninja,bradking/ninja,sgraham/ninja,automeka/ninja,Qix-/ninja,nico/ninja,mgaunard/ninja,chenyukang/ninja,automeka/ninja,mohamed/ninja,nocnokneo/ninja,bmeurer/ninja,juntalis/ninja,LuaDist/ninja,jcfr/ninja,nocnokneo/ninja,sxlin/dist_ninja,mathstuf/ninja,ignatenkobrain/ninja,ninja-build/ninja,mydongistiny/ninja,colincross/ninja,colincross/ninja,tfarina/ninja,juntalis/ninja,colincross/ninja,ikarienator/ninja,Qix-/ninja,dendy/ninja,curinir/ninja,moroten/ninja,dpwright/ninja,nafest/ninja,sxlin/dist_ninja,vvvrrooomm/ninja,nafest/ninja,PetrWolf/ninja,fuchsia-mirror/third_party-ninja,Ju2ender/ninja,sxlin/dist_ninja,mutac/ninja,bmeurer/ninja,ukai/ninja,cipriancraciun/ninja,jsternberg/ninja,TheOneRing/ninja,fifoforlifo/ninja,hnney/ninja,ikarienator/ninja,ikarienator/ninja,SByer/ninja,hnney/ninja,purcell/ninja,SByer/ninja,lizh06/ninja,yannicklm/ninja,martine/ninja,drbo/ninja,rnk/ninja,iwadon/ninja,martine/ninja,atetubou/ninja,glensc/ninja,maximuska/ninja,juntalis/ninja,nico/ninja,TheOneRing/ninja,atetubou/ninja,autopulated/ninja,mdempsky/ninja,mgaunard/ninja,hnney/ninja,nocnokneo/ninja,PetrWolf/ninja,maruel/ninja,LuaDist/ninja,mdempsky/ninja,martine/ninja,ThiagoGarciaAlves/ninja,ehird/ninja,guiquanz/ninja,SByer/ninja,maximuska/ninja,ThiagoGarciaAlves/ninja,liukd/ninja,mohamed/ninja,barak/ninja,dpwright/ninja,fuchsia-mirror/third_party-ninja,nornagon/ninja,tychoish/ninja,ilor/ninja,AoD314/ninja,Ju2ender/ninja,fifoforlifo/ninja,fifoforlifo/ninja,jhanssen/ninja,kimgr/ninja,pathscale/ninja,pathscale/ninja,vvvrrooomm/ninja,rnk/ninja,bradking/ninja,nornagon/ninja,dendy/ninja,PetrWolf/ninja,bmeurer/ninja,TheOneRing/ninja,mdempsky/ninja,jhanssen/ninja,pcc/ninja,nicolasdespres/ninja,bradking/ninja,pcc/ninja,dorgonman/ninja,sorbits/ninja,bradking/ninja,justinsb/ninja,jimon/ninja,chenyukang/ninja,ctiller/ninja,syntheticpp/ninja,rjogrady/ninja,jcfr/ninja,Ju2ender/ninja,mutac/ninja,mohamed/ninja,chenyukang/ninja,jendrikillner/ninja,okuoku/ninja,pck/ninja,ignatenkobrain/ninja,iwadon/ninja,juntalis/ninja,dpwright/ninja,nocnokneo/ninja,tychoish/ninja,mutac/ninja,rnk/ninja,PetrWolf/ninja,ctiller/ninja,nicolasdespres/ninja,jsternberg/ninja,mathstuf/ninja,ndsol/subninja,sgraham/ninja,Qix-/ninja,glensc/ninja,LuaDist/ninja,ninja-build/ninja,fuchsia-mirror/third_party-ninja,jsternberg/ninja,dabrahams/ninja,nornagon/ninja,maximuska/ninja,liukd/ninja,lizh06/ninja,ilor/ninja,glensc/ninja,dorgonman/ninja,synaptek/ninja,tychoish/ninja,drbo/ninja,nickhutchinson/ninja,dabrahams/ninja,AoD314/ninja,nicolasdespres/ninja,colincross/ninja,atetubou/ninja,dendy/ninja,maruel/ninja,dorgonman/ninja,dendy/ninja,sorbits/ninja,curinir/ninja,jcfr/ninja,AoD314/ninja,moroten/ninja,cipriancraciun/ninja,vvvrrooomm/ninja,maruel/ninja,atetubou/ninja,pck/ninja,mathstuf/ninja,tfarina/ninja,ndsol/subninja,nico/ninja,barak/ninja,curinir/ninja,mathstuf/ninja,barak/ninja,pathscale/ninja,Maratyszcza/ninja-pypi,pcc/ninja,dabrahams/ninja,jendrikillner/ninja,ehird/ninja,drbo/ninja,ignatenkobrain/ninja,ehird/ninja,pck/ninja,lizh06/ninja,bmeurer/ninja,hnney/ninja,cipriancraciun/ninja,sxlin/dist_ninja,justinsb/ninja,yannicklm/ninja,ilor/ninja,mydongistiny/ninja,PetrWolf/ninja-main,SByer/ninja,metti/ninja,mdempsky/ninja,pck/ninja,mohamed/ninja,nafest/ninja,liukd/ninja,vvvrrooomm/ninja,ilor/ninja,jcfr/ninja,kimgr/ninja,sorbits/ninja,Maratyszcza/ninja-pypi,syntheticpp/ninja,syntheticpp/ninja,ThiagoGarciaAlves/ninja,mydongistiny/ninja,Maratyszcza/ninja-pypi,liukd/ninja,guiquanz/ninja,ukai/ninja,metti/ninja,jsternberg/ninja,lizh06/ninja,kissthink/ninja,justinsb/ninja,guiquanz/ninja,Ju2ender/ninja,ignatenkobrain/ninja,synaptek/ninja,ctiller/ninja,justinsb/ninja,automeka/ninja,PetrWolf/ninja-main,okuoku/ninja,ThiagoGarciaAlves/ninja,mgaunard/ninja,nico/ninja,curinir/ninja,ninja-build/ninja,LuaDist/ninja,mutac/ninja,fuchsia-mirror/third_party-ninja,autopulated/ninja,jendrikillner/ninja,rjogrady/ninja,yannicklm/ninja,purcell/ninja,kissthink/ninja,Qix-/ninja,yannicklm/ninja,sxlin/dist_ninja,dorgonman/ninja,sxlin/dist_ninja,TheOneRing/ninja,rjogrady/ninja,metti/ninja,rjogrady/ninja,martine/ninja,iwadon/ninja,rnk/ninja,autopulated/ninja,AoD314/ninja,ehird/ninja,ukai/ninja,pcc/ninja,ndsol/subninja,okuoku/ninja,syntheticpp/ninja,moroten/ninja,jimon/ninja,moroten/ninja,sgraham/ninja
|
5b0786cea426485e51dc39675800759a182b51b8
|
src/chaincoin-cli.cpp
|
src/chaincoin-cli.cpp
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/chaincoin-config.h>
#endif
#include <chainparamsbase.h>
#include <clientversion.h>
#include <fs.h>
#include <utilstrencodings.h>
#include <rpc/client.h>
#include <rpc/protocol.h>
#include <util.h>
#include <utilstrencodings.h>
#include <stdio.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
#include <support/events.h>
#include <univalue.h>
static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
static const bool DEFAULT_NAMED=false;
static const int CONTINUE_EXECUTION=-1;
std::string HelpMessageCli()
{
const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
std::string strUsage;
strUsage += HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
AppendParamsHelpMessages(strUsage);
strUsage += HelpMessageOpt("-named", strprintf(_("Pass named instead of positional arguments (default: %s)"), DEFAULT_NAMED));
strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start"));
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout during HTTP requests (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT));
strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases)"));
return strUsage;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
//
// Exception thrown on connection error. This error is used to determine
// when to wait if -rpcwait is given.
//
class CConnectionFailed : public std::runtime_error
{
public:
explicit inline CConnectionFailed(const std::string& msg) :
std::runtime_error(msg)
{}
};
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRPC(int argc, char* argv[])
{
//
// Parameters
//
ParseParameters(argc, argv);
if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) {
std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n";
if (!IsArgSet("-version")) {
strUsage += "\n" + _("Usage:") + "\n" +
" chaincoin-cli [options] <command> [params] " + _("Send command to Chaincoin Core") + "\n" +
" bitcoin-cli [options] -named <command> [name=value] ... " + strprintf(_("Send command to %s (with named arguments)"), _(PACKAGE_NAME)) + "\n" +
" chaincoin-cli [options] help " + _("List commands") + "\n" +
" chaincoin-cli [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessageCli();
}
fprintf(stdout, "%s", strUsage.c_str());
if (argc < 2) {
fprintf(stderr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
if (!fs::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
return EXIT_FAILURE;
}
try {
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return EXIT_FAILURE;
}
// Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause)
try {
SelectBaseParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
if (GetBoolArg("-rpcssl", false))
{
fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n");
return EXIT_FAILURE;
}
return CONTINUE_EXECUTION;
}
/** Reply structure for request_done to fill in */
struct HTTPReply
{
HTTPReply(): status(0), error(-1) {}
int status;
int error;
std::string body;
};
const char *http_errorstring(int code)
{
switch(code) {
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
case EVREQ_HTTP_TIMEOUT:
return "timeout reached";
case EVREQ_HTTP_EOF:
return "EOF reached";
case EVREQ_HTTP_INVALID_HEADER:
return "error while reading header, or invalid header";
case EVREQ_HTTP_BUFFER_ERROR:
return "error encountered while reading or writing";
case EVREQ_HTTP_REQUEST_CANCEL:
return "request was canceled";
case EVREQ_HTTP_DATA_TOO_LONG:
return "response body is larger than allowed";
#endif
default:
return "unknown";
}
}
static void http_request_done(struct evhttp_request *req, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
if (req == nullptr) {
/* If req is nullptr, it means an error occurred while connecting, but
* I'm not sure how to find out which one. We also don't really care.
*/
reply->status = 0;
return;
}
reply->status = evhttp_request_get_response_code(req);
struct evbuffer *buf = evhttp_request_get_input_buffer(req);
if (buf)
{
size_t size = evbuffer_get_length(buf);
const char *data = (const char*)evbuffer_pullup(buf, size);
if (data)
reply->body = std::string(data, size);
evbuffer_drain(buf, size);
}
}
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
static void http_error_cb(enum evhttp_request_error err, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
reply->error = err;
}
#endif
UniValue CallRPC(const std::string& strMethod, const UniValue& params)
{
std::string host;
// In preference order, we choose the following for the port:
// 1. -rpcport
// 2. port in -rpcconnect (ie following : in ipv4 or ]: in ipv6)
// 3. default port for chain
int port = BaseParams().RPCPort();
SplitHostPort(GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host);
port = GetArg("-rpcport", port);
// Obtain event base
raii_event_base base = obtain_event_base();
// Synchronously look up hostname
raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
if (req == NULL)
throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
evhttp_request_set_error_cb(req.get(), http_error_cb);
#endif
// Get credentials
std::string strRPCUserColonPass;
if (GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
_("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
}
} else {
strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
}
struct evkeyvalq *output_headers = evhttp_request_get_output_headers(req.get());
assert(output_headers);
evhttp_add_header(output_headers, "Host", host.c_str());
evhttp_add_header(output_headers, "Connection", "close");
evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
// Attach request data
std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n";
struct evbuffer * output_buffer = evhttp_request_get_output_buffer(req.get());
assert(output_buffer);
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/");
req.release(); // ownership moved to evcon in above call
if (r != 0) {
throw CConnectionFailed("send http request failed");
}
event_base_dispatch(base.get());
if (response.status == 0)
throw CConnectionFailed(strprintf("couldn't connect to server\n(make sure server is running and you are connecting to the correct RPC port: %d %s)", response.error, http_errorstring(response.error)));
else if (response.status == HTTP_UNAUTHORIZED)
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
else if (response.body.empty())
throw std::runtime_error("no response from server");
// Parse reply
UniValue valReply(UniValue::VSTR);
if (!valReply.read(response.body))
throw std::runtime_error("couldn't parse reply from server");
const UniValue& reply = valReply.get_obj();
if (reply.empty())
throw std::runtime_error("expected reply to have result, error and id properties");
return reply;
}
int CommandLineRPC(int argc, char *argv[])
{
std::string strPrint;
int nRet = 0;
try {
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0])) {
argc--;
argv++;
}
std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
if (GetBoolArg("-stdin", false)) {
// Read one arg per line from stdin and append
std::string line;
while (std::getline(std::cin,line))
args.push_back(line);
}
if (args.size() < 1)
throw std::runtime_error("too few parameters (need at least command)");
std::string strMethod = args[0];
args.erase(args.begin()); // Remove trailing method name from arguments vector
UniValue params;
if(GetBoolArg("-named", DEFAULT_NAMED)) {
params = RPCConvertNamedValues(strMethod, args);
} else {
params = RPCConvertValues(strMethod, args);
}
// Execute and handle connection failures with -rpcwait
const bool fWait = GetBoolArg("-rpcwait", false);
do {
try {
const UniValue reply = CallRPC(strMethod, params);
// Parse reply
const UniValue& result = find_value(reply, "result");
const UniValue& error = find_value(reply, "error");
if (!error.isNull()) {
// Error
int code = error["code"].get_int();
if (fWait && code == RPC_IN_WARMUP)
throw CConnectionFailed("server in warmup");
strPrint = "error: " + error.write();
nRet = abs(code);
if (error.isObject())
{
UniValue errCode = find_value(error, "code");
UniValue errMsg = find_value(error, "message");
strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n";
if (errMsg.isStr())
strPrint += "error message:\n"+errMsg.get_str();
}
} else {
// Result
if (result.isNull())
strPrint = "";
else if (result.isStr())
strPrint = result.get_str();
else
strPrint = result.write(2);
}
// Connection succeeded, no need to retry.
break;
}
catch (const CConnectionFailed&) {
if (fWait)
MilliSleep(1000);
else
throw;
}
} while (fWait);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(nullptr, "CommandLineRPC()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
if (!SetupNetworking()) {
fprintf(stderr, "Error: Initializing networking failed\n");
exit(EXIT_FAILURE);
}
try {
int ret = AppInitRPC(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRPC()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "AppInitRPC()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRPC(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRPC()");
} catch (...) {
PrintExceptionContinue(nullptr, "CommandLineRPC()");
}
return ret;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/chaincoin-config.h>
#endif
#include <chainparamsbase.h>
#include <clientversion.h>
#include <fs.h>
#include <rpc/client.h>
#include <rpc/protocol.h>
#include <util.h>
#include <utilstrencodings.h>
#include <stdio.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
#include <support/events.h>
#include <univalue.h>
static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
static const bool DEFAULT_NAMED=false;
static const int CONTINUE_EXECUTION=-1;
std::string HelpMessageCli()
{
const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
std::string strUsage;
strUsage += HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
AppendParamsHelpMessages(strUsage);
strUsage += HelpMessageOpt("-named", strprintf(_("Pass named instead of positional arguments (default: %s)"), DEFAULT_NAMED));
strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start"));
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout during HTTP requests (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT));
strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases)"));
return strUsage;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
//
// Exception thrown on connection error. This error is used to determine
// when to wait if -rpcwait is given.
//
class CConnectionFailed : public std::runtime_error
{
public:
explicit inline CConnectionFailed(const std::string& msg) :
std::runtime_error(msg)
{}
};
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRPC(int argc, char* argv[])
{
//
// Parameters
//
ParseParameters(argc, argv);
if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) {
std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n";
if (!IsArgSet("-version")) {
strUsage += "\n" + _("Usage:") + "\n" +
" chaincoin-cli [options] <command> [params] " + _("Send command to Chaincoin Core") + "\n" +
" bitcoin-cli [options] -named <command> [name=value] ... " + strprintf(_("Send command to %s (with named arguments)"), _(PACKAGE_NAME)) + "\n" +
" chaincoin-cli [options] help " + _("List commands") + "\n" +
" chaincoin-cli [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessageCli();
}
fprintf(stdout, "%s", strUsage.c_str());
if (argc < 2) {
fprintf(stderr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
if (!fs::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
return EXIT_FAILURE;
}
try {
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return EXIT_FAILURE;
}
// Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause)
try {
SelectBaseParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
if (GetBoolArg("-rpcssl", false))
{
fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n");
return EXIT_FAILURE;
}
return CONTINUE_EXECUTION;
}
/** Reply structure for request_done to fill in */
struct HTTPReply
{
HTTPReply(): status(0), error(-1) {}
int status;
int error;
std::string body;
};
const char *http_errorstring(int code)
{
switch(code) {
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
case EVREQ_HTTP_TIMEOUT:
return "timeout reached";
case EVREQ_HTTP_EOF:
return "EOF reached";
case EVREQ_HTTP_INVALID_HEADER:
return "error while reading header, or invalid header";
case EVREQ_HTTP_BUFFER_ERROR:
return "error encountered while reading or writing";
case EVREQ_HTTP_REQUEST_CANCEL:
return "request was canceled";
case EVREQ_HTTP_DATA_TOO_LONG:
return "response body is larger than allowed";
#endif
default:
return "unknown";
}
}
static void http_request_done(struct evhttp_request *req, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
if (req == nullptr) {
/* If req is nullptr, it means an error occurred while connecting, but
* I'm not sure how to find out which one. We also don't really care.
*/
reply->status = 0;
return;
}
reply->status = evhttp_request_get_response_code(req);
struct evbuffer *buf = evhttp_request_get_input_buffer(req);
if (buf)
{
size_t size = evbuffer_get_length(buf);
const char *data = (const char*)evbuffer_pullup(buf, size);
if (data)
reply->body = std::string(data, size);
evbuffer_drain(buf, size);
}
}
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
static void http_error_cb(enum evhttp_request_error err, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
reply->error = err;
}
#endif
UniValue CallRPC(const std::string& strMethod, const UniValue& params)
{
std::string host;
// In preference order, we choose the following for the port:
// 1. -rpcport
// 2. port in -rpcconnect (ie following : in ipv4 or ]: in ipv6)
// 3. default port for chain
int port = BaseParams().RPCPort();
SplitHostPort(GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host);
port = GetArg("-rpcport", port);
// Obtain event base
raii_event_base base = obtain_event_base();
// Synchronously look up hostname
raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
if (req == NULL)
throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
evhttp_request_set_error_cb(req.get(), http_error_cb);
#endif
// Get credentials
std::string strRPCUserColonPass;
if (GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
_("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
}
} else {
strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
}
struct evkeyvalq *output_headers = evhttp_request_get_output_headers(req.get());
assert(output_headers);
evhttp_add_header(output_headers, "Host", host.c_str());
evhttp_add_header(output_headers, "Connection", "close");
evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
// Attach request data
std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n";
struct evbuffer * output_buffer = evhttp_request_get_output_buffer(req.get());
assert(output_buffer);
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/");
req.release(); // ownership moved to evcon in above call
if (r != 0) {
throw CConnectionFailed("send http request failed");
}
event_base_dispatch(base.get());
if (response.status == 0)
throw CConnectionFailed(strprintf("couldn't connect to server\n(make sure server is running and you are connecting to the correct RPC port: %d %s)", response.error, http_errorstring(response.error)));
else if (response.status == HTTP_UNAUTHORIZED)
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
else if (response.body.empty())
throw std::runtime_error("no response from server");
// Parse reply
UniValue valReply(UniValue::VSTR);
if (!valReply.read(response.body))
throw std::runtime_error("couldn't parse reply from server");
const UniValue& reply = valReply.get_obj();
if (reply.empty())
throw std::runtime_error("expected reply to have result, error and id properties");
return reply;
}
int CommandLineRPC(int argc, char *argv[])
{
std::string strPrint;
int nRet = 0;
try {
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0])) {
argc--;
argv++;
}
std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
if (GetBoolArg("-stdin", false)) {
// Read one arg per line from stdin and append
std::string line;
while (std::getline(std::cin,line))
args.push_back(line);
}
if (args.size() < 1)
throw std::runtime_error("too few parameters (need at least command)");
std::string strMethod = args[0];
args.erase(args.begin()); // Remove trailing method name from arguments vector
UniValue params;
if(GetBoolArg("-named", DEFAULT_NAMED)) {
params = RPCConvertNamedValues(strMethod, args);
} else {
params = RPCConvertValues(strMethod, args);
}
// Execute and handle connection failures with -rpcwait
const bool fWait = GetBoolArg("-rpcwait", false);
do {
try {
const UniValue reply = CallRPC(strMethod, params);
// Parse reply
const UniValue& result = find_value(reply, "result");
const UniValue& error = find_value(reply, "error");
if (!error.isNull()) {
// Error
int code = error["code"].get_int();
if (fWait && code == RPC_IN_WARMUP)
throw CConnectionFailed("server in warmup");
strPrint = "error: " + error.write();
nRet = abs(code);
if (error.isObject())
{
UniValue errCode = find_value(error, "code");
UniValue errMsg = find_value(error, "message");
strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n";
if (errMsg.isStr())
strPrint += "error message:\n"+errMsg.get_str();
}
} else {
// Result
if (result.isNull())
strPrint = "";
else if (result.isStr())
strPrint = result.get_str();
else
strPrint = result.write(2);
}
// Connection succeeded, no need to retry.
break;
}
catch (const CConnectionFailed&) {
if (fWait)
MilliSleep(1000);
else
throw;
}
} while (fWait);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(nullptr, "CommandLineRPC()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
if (!SetupNetworking()) {
fprintf(stderr, "Error: Initializing networking failed\n");
exit(EXIT_FAILURE);
}
try {
int ret = AppInitRPC(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRPC()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "AppInitRPC()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRPC(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRPC()");
} catch (...) {
PrintExceptionContinue(nullptr, "CommandLineRPC()");
}
return ret;
}
|
Remove duplicate include
|
Remove duplicate include
|
C++
|
mit
|
chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin
|
54aa7c43e7b45e06639dbd33d5c349c2531cf556
|
src/AndroidClient.cpp
|
src/AndroidClient.cpp
|
#include <AndroidClient.h>
#include <jni.h>
#include <android/log.h>
#include <vector>
class AndroidClient : public HTTPClient {
public:
AndroidClient(JNIEnv * _env, const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive)
: HTTPClient(_user_agent, _enable_cookies, _enable_keepalive), env(_env) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndroidClient Constructor called");
}
void androidInit(){
cookieManagerClass = env->FindClass("android/webkit/CookieManager");
httpClass = env->FindClass("java/net/HttpURLConnection");
urlClass = env->FindClass("java/net/URL");
inputStreamClass = env->FindClass("java/io/InputStream");
getHeaderMethod = env->GetMethodID(httpClass, "getHeaderField", "(Ljava/lang/String;)Ljava/lang/String;");
getHeaderMethodInt = env->GetMethodID(httpClass, "getHeaderField", "(I)Ljava/lang/String;");
getHeaderKeyMethod = env->GetMethodID(httpClass, "getHeaderFieldKey", "(I)Ljava/lang/String;");
readMethod = env->GetMethodID(inputStreamClass, "read", "([B)I");
urlConstructor = env->GetMethodID(urlClass, "<init>", "(Ljava/lang/String;)V");
openConnectionMethod = env->GetMethodID(urlClass, "openConnection", "()Ljava/net/URLConnection;");
setRequestProperty = env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
setRequestMethod = env->GetMethodID(httpClass, "setRequestMethod", "(Ljava/lang/String;)V");
setFollowMethod = env->GetMethodID(httpClass, "setInstanceFollowRedirects", "(Z)V");
setDoInputMethod = env->GetMethodID(httpClass, "setDoInput", "(Z)V");
connectMethod = env->GetMethodID(httpClass, "connect", "()V");
getResponseCodeMethod = env->GetMethodID(httpClass, "getResponseCode", "()I");
getResponseMessageMethod = env->GetMethodID(httpClass, "getResponseMessage", "()Ljava/lang/String;");
setRequestPropertyMethod = env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
clearCookiesMethod = env->GetMethodID(cookieManagerClass, "removeAllCookie", "()V");
getInputStreamMethod = env->GetMethodID(httpClass, "getInputStream", "()Ljava/io/InputStream;");
getErrorStreamMethod = env->GetMethodID(httpClass, "getErrorStream", "()Ljava/io/InputStream;");
initDone = true;
}
HTTPResponse request(const HTTPRequest & req, const Authorization & auth) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndroidClient request called");
if (!initDone){
androidInit();
}
jobject url = env->NewObject(urlClass, urlConstructor, env->NewStringUTF(req.getURI().c_str()));
jobject connection = env->CallObjectMethod(url, openConnectionMethod);
//Authorization example
//env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF("Authorization"), env->NewStringUTF("myUsername"));
// std::string auth_header = auth.createHeader();
// if (!auth_header.empty()) {
// env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF(auth.getHeaderName()), env->NewStringUTF(auth_header.c_str()));
//}
env->CallVoidMethod(connection, setFollowMethod, req.getFollowLocation() ? JNI_TRUE : JNI_FALSE);
// Setting headers for request
for (auto & hd : req.getHeaders()) {
__android_log_print(ANDROID_LOG_INFO, "httpRequest", "Setting header property name = %s", hd.first.c_str());
__android_log_print(ANDROID_LOG_INFO, "httpRequest", "Setting header property value = %s", hd.second.c_str());
env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF(hd.first.c_str()), env->NewStringUTF(hd.second.c_str()));
}
env->CallVoidMethod(connection, setRequestMethod, env->NewStringUTF(req.getTypeString()));
int responseCode = env->CallIntMethod(connection, getResponseCodeMethod);
// Server not found error
if (env->ExceptionCheck()) {
env->ExceptionClear();
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "EXCEPTION http request responsecode = %i", responseCode);
return HTTPResponse(0, "Server not found");
}
const char *errorMessage = "";
jobject input;
if (responseCode >= 400 && responseCode <= 599) {
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "request responsecode = %i", responseCode);
jstring javaMessage = (jstring)env->CallObjectMethod(connection, getResponseMessageMethod);
errorMessage = env->GetStringUTFChars(javaMessage, 0);
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "errorMessage = %s", errorMessage);
input = env->CallObjectMethod(connection, getErrorStreamMethod);
} else {
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "http request responsecode = %i", responseCode);
input = env->CallObjectMethod(connection, getInputStreamMethod);
env->ExceptionClear();
}
jbyteArray array = env->NewByteArray(4096);
int g = 0;
HTTPResponse response;
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Starting to gather content");
// Gather content
while ((g = env->CallIntMethod(input, readMethod, array)) != -1) {
jbyte* content_array = env->GetByteArrayElements(array, NULL);
if (callback) {
callback->handleChunk(g, (char*) content_array);
} else {
response.appendContent(std::string((char*) content_array, g));
}
env->ReleaseByteArrayElements(array, content_array, JNI_ABORT);
}
//Gather headers and values
for (int i = 0; ; i++) {
jstring jheaderKey = (jstring)env->CallObjectMethod(connection, getHeaderKeyMethod, i);
const char * headerKey = env->GetStringUTFChars(jheaderKey, 0);
__android_log_print(ANDROID_LOG_INFO, "content", "header key = %s", headerKey);
jstring jheader = (jstring)env->CallObjectMethod(connection, getHeaderMethodInt, i);
const char * header = env->GetStringUTFChars(jheader, 0);
__android_log_print(ANDROID_LOG_INFO, "content", "header value = %s", header);
if (headerKey == NULL) {
break;
}
response.addHeader(headerKey, header);
env->ReleaseStringUTFChars(jheaderKey, headerKey);
env->ReleaseStringUTFChars(jheader, header);
}
response.setResultCode(responseCode);
if (responseCode >= 300 && responseCode <= 399) {
jstring followURL = (jstring)env->CallObjectMethod(connection, getHeaderMethod, env->NewStringUTF("location"));
const char *followString = env->GetStringUTFChars(followURL, 0);
response.setRedirectUrl(followString);
env->ReleaseStringUTFChars(followURL, followString);
__android_log_print(ANDROID_LOG_INFO, "content", "followURL = %s", followString);
}
return response;
}
void clearCookies() {
env->CallVoidMethod(cookieManagerClass, clearCookiesMethod);
}
protected:
bool initialize() { return true; }
private:
bool initDone = false;
JNIEnv * env;
jclass cookieManagerClass;
jmethodID clearCookiesMethod;
jclass bitmapClass;
jclass factoryClass;
jclass httpClass;
jclass urlClass;
jclass bufferedReaderClass;
jclass inputStreamReaderClass;
jclass inputStreamClass;
jmethodID urlConstructor;
jmethodID openConnectionMethod;
jmethodID setRequestProperty;
jmethodID setRequestMethod;
jmethodID setDoInputMethod;
jmethodID connectMethod;
jmethodID getResponseCodeMethod;
jmethodID getResponseMessageMethod;
jmethodID setRequestPropertyMethod;
jmethodID outputStreamConstructor;
jmethodID factoryDecodeMethod;
jmethodID getInputStreamMethod;
jmethodID getErrorStreamMethod;
jmethodID bufferedReaderConstructor;
jmethodID inputStreamReaderConstructor;
jmethodID readLineMethod;
jmethodID readerCloseMethod;
jmethodID readMethod;
jmethodID inputStreamCloseMethod;
jmethodID setFollowMethod;
jmethodID getHeaderMethod;
jmethodID getHeaderMethodInt;
jmethodID getHeaderKeyMethod;
};
std::shared_ptr<HTTPClient>
AndroidClientFactory::createClient(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {
return std::make_shared<AndroidClient>(env, _user_agent, _enable_cookies, _enable_keepalive);
}
|
#include <AndroidClient.h>
#include <jni.h>
#include <android/log.h>
#include <vector>
class AndroidClient : public HTTPClient {
public:
AndroidClient(JNIEnv * _env, const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive)
: HTTPClient(_user_agent, _enable_cookies, _enable_keepalive), env(_env) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndroidClient Constructor called");
}
void androidInit(){
cookieManagerClass = env->FindClass("android/webkit/CookieManager");
httpClass = env->FindClass("java/net/HttpURLConnection");
urlClass = env->FindClass("java/net/URL");
inputStreamClass = env->FindClass("java/io/InputStream");
getHeaderMethod = env->GetMethodID(httpClass, "getHeaderField", "(Ljava/lang/String;)Ljava/lang/String;");
getHeaderMethodInt = env->GetMethodID(httpClass, "getHeaderField", "(I)Ljava/lang/String;");
getHeaderKeyMethod = env->GetMethodID(httpClass, "getHeaderFieldKey", "(I)Ljava/lang/String;");
readMethod = env->GetMethodID(inputStreamClass, "read", "([B)I");
urlConstructor = env->GetMethodID(urlClass, "<init>", "(Ljava/lang/String;)V");
openConnectionMethod = env->GetMethodID(urlClass, "openConnection", "()Ljava/net/URLConnection;");
setRequestProperty = env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
setRequestMethod = env->GetMethodID(httpClass, "setRequestMethod", "(Ljava/lang/String;)V");
setFollowMethod = env->GetMethodID(httpClass, "setInstanceFollowRedirects", "(Z)V");
setDoInputMethod = env->GetMethodID(httpClass, "setDoInput", "(Z)V");
connectMethod = env->GetMethodID(httpClass, "connect", "()V");
getResponseCodeMethod = env->GetMethodID(httpClass, "getResponseCode", "()I");
getResponseMessageMethod = env->GetMethodID(httpClass, "getResponseMessage", "()Ljava/lang/String;");
setRequestPropertyMethod = env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
clearCookiesMethod = env->GetMethodID(cookieManagerClass, "removeAllCookie", "()V");
getInputStreamMethod = env->GetMethodID(httpClass, "getInputStream", "()Ljava/io/InputStream;");
getErrorStreamMethod = env->GetMethodID(httpClass, "getErrorStream", "()Ljava/io/InputStream;");
initDone = true;
}
HTTPResponse request(const HTTPRequest & req, const Authorization & auth) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndroidClient request called");
if (!initDone){
androidInit();
}
jobject url = env->NewObject(urlClass, urlConstructor, env->NewStringUTF(req.getURI().c_str()));
jobject connection = env->CallObjectMethod(url, openConnectionMethod);
//Authorization example
//env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF("Authorization"), env->NewStringUTF("myUsername"));
// std::string auth_header = auth.createHeader();
// if (!auth_header.empty()) {
// env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF(auth.getHeaderName()), env->NewStringUTF(auth_header.c_str()));
//}
env->CallVoidMethod(connection, setFollowMethod, req.getFollowLocation() ? JNI_TRUE : JNI_FALSE);
// Setting headers for request
for (auto & hd : req.getHeaders()) {
__android_log_print(ANDROID_LOG_INFO, "httpRequest", "Setting header property name = %s", hd.first.c_str());
__android_log_print(ANDROID_LOG_INFO, "httpRequest", "Setting header property value = %s", hd.second.c_str());
env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF(hd.first.c_str()), env->NewStringUTF(hd.second.c_str()));
}
env->CallVoidMethod(connection, setRequestMethod, env->NewStringUTF(req.getTypeString()));
int responseCode = env->CallIntMethod(connection, getResponseCodeMethod);
// Server not found error
if (env->ExceptionCheck()) {
env->ExceptionClear();
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "EXCEPTION http request responsecode = %i", responseCode);
return HTTPResponse(0, "Server not found");
}
const char *errorMessage = "";
jobject input;
if (responseCode >= 400 && responseCode <= 599) {
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "request responsecode = %i", responseCode);
jstring javaMessage = (jstring)env->CallObjectMethod(connection, getResponseMessageMethod);
errorMessage = env->GetStringUTFChars(javaMessage, 0);
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "errorMessage = %s", errorMessage);
input = env->CallObjectMethod(connection, getErrorStreamMethod);
} else {
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "http request responsecode = %i", responseCode);
input = env->CallObjectMethod(connection, getInputStreamMethod);
env->ExceptionClear();
}
jbyteArray array = env->NewByteArray(4096);
int g = 0;
HTTPResponse response;
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Starting to gather content");
//Gather headers and values
for (int i = 0; ; i++) {
jstring jheaderKey = (jstring)env->CallObjectMethod(connection, getHeaderKeyMethod, i);
const char * headerKey = env->GetStringUTFChars(jheaderKey, 0);
__android_log_print(ANDROID_LOG_INFO, "content", "header key = %s", headerKey);
jstring jheader = (jstring)env->CallObjectMethod(connection, getHeaderMethodInt, i);
const char * header = env->GetStringUTFChars(jheader, 0);
__android_log_print(ANDROID_LOG_INFO, "content", "header value = %s", header);
if (headerKey == NULL) {
break;
}
response.addHeader(headerKey, header);
env->ReleaseStringUTFChars(jheaderKey, headerKey);
env->ReleaseStringUTFChars(jheader, header);
}
// Gather content
while ((g = env->CallIntMethod(input, readMethod, array)) != -1) {
jbyte* content_array = env->GetByteArrayElements(array, NULL);
if (callback) {
callback->handleChunk(g, (char*) content_array);
} else {
response.appendContent(std::string((char*) content_array, g));
}
env->ReleaseByteArrayElements(array, content_array, JNI_ABORT);
}
response.setResultCode(responseCode);
if (responseCode >= 300 && responseCode <= 399) {
jstring followURL = (jstring)env->CallObjectMethod(connection, getHeaderMethod, env->NewStringUTF("location"));
const char *followString = env->GetStringUTFChars(followURL, 0);
response.setRedirectUrl(followString);
env->ReleaseStringUTFChars(followURL, followString);
__android_log_print(ANDROID_LOG_INFO, "content", "followURL = %s", followString);
}
return response;
}
void clearCookies() {
env->CallVoidMethod(cookieManagerClass, clearCookiesMethod);
}
protected:
bool initialize() { return true; }
private:
bool initDone = false;
JNIEnv * env;
jclass cookieManagerClass;
jmethodID clearCookiesMethod;
jclass bitmapClass;
jclass factoryClass;
jclass httpClass;
jclass urlClass;
jclass bufferedReaderClass;
jclass inputStreamReaderClass;
jclass inputStreamClass;
jmethodID urlConstructor;
jmethodID openConnectionMethod;
jmethodID setRequestProperty;
jmethodID setRequestMethod;
jmethodID setDoInputMethod;
jmethodID connectMethod;
jmethodID getResponseCodeMethod;
jmethodID getResponseMessageMethod;
jmethodID setRequestPropertyMethod;
jmethodID outputStreamConstructor;
jmethodID factoryDecodeMethod;
jmethodID getInputStreamMethod;
jmethodID getErrorStreamMethod;
jmethodID bufferedReaderConstructor;
jmethodID inputStreamReaderConstructor;
jmethodID readLineMethod;
jmethodID readerCloseMethod;
jmethodID readMethod;
jmethodID inputStreamCloseMethod;
jmethodID setFollowMethod;
jmethodID getHeaderMethod;
jmethodID getHeaderMethodInt;
jmethodID getHeaderKeyMethod;
};
std::shared_ptr<HTTPClient>
AndroidClientFactory::createClient(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {
return std::make_shared<AndroidClient>(env, _user_agent, _enable_cookies, _enable_keepalive);
}
|
Switch code placement with header and content gather
|
Switch code placement with header and content gather
|
C++
|
mit
|
Sometrik/httpclient,Sometrik/httpclient
|
879db6b562efee0f1f54128ab8f74d91585c4f85
|
src/clientversion.cpp
|
src/clientversion.cpp
|
// Copyright (c) 2012-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both flurbod and flurbo-core, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Satoshi");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "$Format:%h$"
#define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
#ifndef BUILD_DATE
#ifdef GIT_COMMIT_DATE
#define BUILD_DATE GIT_COMMIT_DATE
#else
#define BUILD_DATE __DATE__ ", " __TIME__
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/flurbo/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
|
// Copyright (c) 2012-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both flurbod and flurbo-core, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Flurbo");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "$Format:%h$"
#define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
#ifndef BUILD_DATE
#ifdef GIT_COMMIT_DATE
#define BUILD_DATE GIT_COMMIT_DATE
#else
#define BUILD_DATE __DATE__ ", " __TIME__
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/flurbo/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
|
Rename ClientName
|
Rename ClientName
|
C++
|
mit
|
Flurbos/Flurbo,Flurbos/Flurbo,Flurbos/Flurbo,Flurbos/Flurbo,Flurbos/Flurbo,Flurbos/Flurbo
|
cfc702c27c87f9a4e05a09d3b1b3b5e8ac816e69
|
src/cmd/whitelist.cpp
|
src/cmd/whitelist.cpp
|
#include "command.h"
#include "../CommandHandler.h"
#include "../OptionParser.h"
/* full name of the command */
CMDNAME("whitelist");
/* description of the command */
CMDDESCR("exempt websites from moderation");
/* command usage synopsis */
CMDUSAGE("$whitelist [-d] [SITE]");
/* whitelist: exempt websites from moderation */
std::string CommandHandler::whitelist(char *out, struct command *c)
{
if (!P_ALMOD(c->privileges)) {
PERM_DENIED(out, c->nick, c->argv[0]);
return "";
}
std::string website, outp;
bool del;
int opt;
OptionParser op(c->fullCmd, "d");
static struct OptionParser::option long_opts[] = {
{ "delete", NO_ARG, 'd' },
{ "help", NO_ARG, 'h' },
{ 0, 0, 0 }
};
del = false;
while ((opt = op.getopt_long(long_opts)) != EOF) {
switch (opt) {
case 'd':
del = true;
break;
case 'h':
return HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR);
case '?':
return std::string(op.opterr());
default:
return "";
}
}
if (op.optind() == c->fullCmd.length()) {
if (del)
return CMDNAME + ": no website specified";
/* no args: show current whitelist */
return m_modp->getFormattedWhitelist();
}
if ((website = c->fullCmd.substr(op.optind())).find(' ')
!= std::string::npos)
return USAGEMSG(CMDNAME, CMDUSAGE);
outp = "@" + std::string(c->nick) + ", ";
if (m_parsep->parse(website)) {
/* extract domain and add to whitelist */
website = m_parsep->getLast()->subdomain
+ m_parsep->getLast()->domain;
if (del) {
if (m_modp->delurl(website))
return outp + website + " has been "
"removed from the whitelist.";
else
return outp + website + " is not on "
"the whitelist.";
}
if (m_modp->whitelist(website))
return outp + website + " has been whitelisted.";
else
return outp + website + " is already on the whitelist.";
}
return CMDNAME + ": invalid URL: " + website;
}
|
#include <string.h>
#include "command.h"
#include "../CommandHandler.h"
#include "../option.h"
#define MAX_URL 256
/* full name of the command */
_CMDNAME("whitelist");
/* description of the command */
_CMDDESCR("exempt websites from moderation");
/* command usage synopsis */
_CMDUSAGE("$whitelist [-d] [SITE]");
/* whitelist: exempt websites from moderation */
std::string CommandHandler::whitelist(char *out, struct command *c)
{
char url[MAX_URL];
char *s;
int del;
int opt;
static struct option long_opts[] = {
{ "delete", NO_ARG, 'd' },
{ "help", NO_ARG, 'h' },
{ 0, 0, 0 }
};
if (!P_ALMOD(c->privileges)) {
PERM_DENIED(out, c->nick, c->argv[0]);
return "";
}
del = 0;
opt_init();
while ((opt = getopt_long(c->argc, c->argv, "d", long_opts)) != EOF) {
switch (opt) {
case 'd':
del = 1;
break;
case 'h':
_HELPMSG(out, _CMDNAME, _CMDUSAGE, _CMDDESCR);
return "";
case '?':
_sprintf(out, MAX_MSG, "%s", opterr());
return "";
default:
return "";
}
}
if (optind == c->argc) {
if (del)
_sprintf(out, MAX_MSG, "%s: no website specified",
c->argv[0]);
else
_sprintf(out, MAX_MSG, "[WHITELIST] %s",
m_modp->getFormattedWhitelist().c_str());
return "";
}
if (optind != c->argc - 1) {
_USAGEMSG(out, _CMDNAME, _CMDUSAGE);
return "";
}
_sprintf(out, MAX_MSG, "@%s, ", c->nick);
s = strchr(out, '\0');
if (m_parsep->parse(c->argv[optind])) {
/* extract domain and add to whitelist */
_sprintf(url, MAX_URL, "%s%s",
m_parsep->getLast()->subdomain.c_str(),
m_parsep->getLast()->domain.c_str());
if (del) {
if (m_modp->delurl(url))
_sprintf(s, MAX_MSG, "%s has been removed "
"from the whitelist.", url);
else
_sprintf(s, MAX_MSG, "%s is not on the "
"whitelist.", url);
return "";
}
if (m_modp->whitelist(url))
_sprintf(s, MAX_MSG, "%s has beed whitelisted.", url);
else
_sprintf(s, MAX_MSG, "%s is already on the whitelist.",
url);
return "";
}
_sprintf(out, MAX_MSG, "%s: invalid URL: %s", c->argv[0],
c->argv[optind]);
return "";
}
|
Update whitelist command format
|
Update whitelist command format
|
C++
|
mit
|
frolv/lynxbot,frolv/osrs-twitch-bot,frolv/lynxbot,frolv/osrs-twitch-bot
|
89eb7e771635c94025c1bcd50efc65a176f33579
|
src/cincluder.cpp
|
src/cincluder.cpp
|
#pragma warning(push)
#pragma warning(disable:4996)
#pragma warning(disable:4244)
#pragma warning(disable:4291)
#pragma warning(disable:4146)
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/GraphWriter.h"
#pragma warning(pop)
#include <functional>
using namespace std;
using namespace clang;
using namespace clang::tooling;
using namespace llvm;
// ***************************************************************************
// vvZbTΜR[obN
// ***************************************************************************
class cincluder : public PPCallbacks {
private:
Preprocessor &PP;
typedef ::std::hash< ::std::string > hash;
typedef ::std::list< hash::result_type > hash_list;
struct header
{
header() : angled(false) {}
header(const ::std::string& n, bool angled_) : name(n), angled(angled_) {}
::std::string name;
bool angled;
hash_list include;
};
typedef ::std::map< hash::result_type, header > Map;
typedef ::std::map< hash::result_type, hash_list > Depend;
Map m_includes;
Depend m_depends;
hash::result_type m_root;
::std::string m_output;
public:
cincluder(Preprocessor &pp) : PP(pp) {}
cincluder(Preprocessor &pp, const ::std::string& output) : PP(pp), m_output(output) {}
const header& getHeader(hash::result_type h)
{
return m_includes[h];
}
::std::string getFilePath(hash::result_type h)
{
return m_includes[h].name;
}
::std::string getFileName(hash::result_type h)
{
::std::string path = getFilePath(h);
size_t dpos1 = path.rfind('\\');
size_t dpos2 = path.rfind('/');
if( dpos1 == ::std::string::npos ) dpos1 = 0;
if( dpos2 == ::std::string::npos ) dpos2 = 0;
const size_t dpos = (::std::max)(dpos1, dpos2) + 1;
return path.substr( dpos );
}
::std::string getFileName(const header& h)
{
::std::string path = h.name;
size_t dpos1 = path.rfind('\\');
size_t dpos2 = path.rfind('/');
if( dpos1 == ::std::string::npos ) dpos1 = 0;
if( dpos2 == ::std::string::npos ) dpos2 = 0;
const size_t dpos = (::std::max)(dpos1, dpos2) + 1;
return path.substr(dpos);
}
void printRoot(hash::result_type h, int indent, bool expand)
{
if( indent > 2 ) return;
for( int i = 0; i < indent; ++i ) errs() << " ";
if( expand ) errs() << "+ ";
else errs() << " ";
errs() << getFileName(h) << "\n";
if( m_depends.find(h) != m_depends.end() )
{
auto depend = m_depends[h];
if( depend.size() > 1 ) ++indent;
for( auto d : depend )
{
printRoot(d, indent, (depend.size() > 1));
}
}
}
void report()
{
for( auto h : m_depends )
{
if( h.second.size() > 1 )
{
errs() << getFileName(h.first) << " is already include by \n";
for( auto d : h.second )
{
printRoot(d, 1, true);
}
}
}
}
void writeID(raw_ostream& OS, hash::result_type h)
{
OS << "header_" << h;
}
void dot()
{
if( m_output.empty() ) return;
std::error_code EC;
llvm::raw_fd_ostream OS(m_output, EC, llvm::sys::fs::F_Text);
if( EC )
{
PP.getDiagnostics().Report(diag::err_fe_error_opening) << m_output
<< EC.message();
return;
}
const char* endl = "\n";
OS << "digraph \"dependencies\" {" << endl;
for( auto inc : m_includes )
{
writeID(OS, inc.first);
OS << " [ shape=\"box\", label=\"";
OS << DOT::EscapeString(getFileName(inc.second));
OS << "\"];" << endl;
}
for( auto depnd : m_depends )
{
writeID(getHeader(depnd.first));
}
OS << "}" << endl;
}
void EndOfMainFile() override
{
report();
}
void InclusionDirective(SourceLocation HashLoc,
const Token &IncludeTok,
llvm::StringRef FileName,
bool IsAngled,
CharSourceRange FilenameRange,
const FileEntry *File,
llvm::StringRef SearchPath,
llvm::StringRef RelativePath,
const Module *Imported) override
{
if( File == nullptr ) return;
SourceManager& SM = PP.getSourceManager();
const FileEntry* pFromFile = SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(HashLoc)));
if( pFromFile == nullptr ) return;
const auto h = hash()(File->getName());
const auto p = hash()(pFromFile->getName());
{
if( m_includes.find(h) == m_includes.end() )
{
m_includes.insert(::std::make_pair(h, header(File->getName(), IsAngled)));
}
auto it = m_includes.find(p);
if( it == m_includes.end() )
{
m_root = p;
m_includes.insert(::std::make_pair(p, header(pFromFile->getName(), false)));
}
if( it != m_includes.end() )
{
it->second.include.push_back(h);
}
}
if( !IsAngled )
{
auto it = m_depends.find(h);
if( it != m_depends.end() )
{
it->second.push_back(p);
}
else
{
hash_list a;
a.push_back(p);
m_depends.insert(::std::make_pair(h, a));
}
}
#if 0
errs() << "InclusionDirective : ";
if (File) {
if (IsAngled) errs() << "<" << File->getName() << ">\n";
else errs() << "\"" << File->getName() << "\"\n";
} else {
errs() << "not found file ";
if (IsAngled) errs() << "<" << FileName << ">\n";
else errs() << "\"" << FileName << "\"\n";
}
#endif
}
};
class ExampleASTConsumer : public ASTConsumer {
private:
public:
explicit ExampleASTConsumer(CompilerInstance *CI) {
// vvZbTΜR[obNo^
Preprocessor &PP = CI->getPreprocessor();
PP.addPPCallbacks(llvm::make_unique<cincluder>(PP));
//AttachDependencyGraphGen(PP, "test.dot", "");
}
};
class ExampleFrontendAction : public SyntaxOnlyAction /*ASTFrontendAction*/ {
public:
virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) {
return llvm::make_unique<ExampleASTConsumer>(&CI); // pass CI pointer to ASTConsumer
}
};
static cl::OptionCategory MyToolCategory("cincluder");
int main(int argc, const char** argv)
{
CommonOptionsParser op(argc, argv, MyToolCategory);
ClangTool Tool(op.getCompilations(), op.getSourcePathList());
return Tool.run(newFrontendActionFactory<ExampleFrontendAction>().get());
}
|
#pragma warning(push)
#pragma warning(disable:4996)
#pragma warning(disable:4244)
#pragma warning(disable:4291)
#pragma warning(disable:4146)
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/GraphWriter.h"
#pragma warning(pop)
#include <functional>
using namespace std;
using namespace clang;
using namespace clang::tooling;
using namespace llvm;
// ***************************************************************************
// vvZbTΜR[obN
// ***************************************************************************
class cincluder : public PPCallbacks {
private:
Preprocessor &PP;
typedef ::std::hash< ::std::string > hash;
typedef ::std::list< hash::result_type > hash_list;
struct header
{
header() : angled(false) {}
header(const ::std::string& n, bool angled_) : name(n), angled(angled_) {}
::std::string name;
bool angled;
hash_list include;
};
typedef ::std::map< hash::result_type, header > Map;
typedef ::std::map< hash::result_type, hash_list > Depend;
Map m_includes;
Depend m_depends;
hash::result_type m_root;
::std::string m_output;
public:
cincluder(Preprocessor &pp) : PP(pp) {}
cincluder(Preprocessor &pp, const ::std::string& output) : PP(pp), m_output(output) {}
const header& getHeader(hash::result_type h)
{
return m_includes[h];
}
::std::string getFilePath(hash::result_type h)
{
return m_includes[h].name;
}
::std::string getFileName(hash::result_type h)
{
::std::string path = getFilePath(h);
size_t dpos1 = path.rfind('\\');
size_t dpos2 = path.rfind('/');
if( dpos1 == ::std::string::npos ) dpos1 = 0;
if( dpos2 == ::std::string::npos ) dpos2 = 0;
const size_t dpos = (::std::max)(dpos1, dpos2) + 1;
return path.substr( dpos );
}
::std::string getFileName(const header& h)
{
::std::string path = h.name;
size_t dpos1 = path.rfind('\\');
size_t dpos2 = path.rfind('/');
if( dpos1 == ::std::string::npos ) dpos1 = 0;
if( dpos2 == ::std::string::npos ) dpos2 = 0;
const size_t dpos = (::std::max)(dpos1, dpos2) + 1;
return path.substr(dpos);
}
void printRoot(hash::result_type h, int indent, bool expand)
{
if( indent > 2 ) return;
for( int i = 0; i < indent; ++i ) errs() << " ";
if( expand ) errs() << "+ ";
else errs() << " ";
errs() << getFileName(h) << "\n";
if( m_depends.find(h) != m_depends.end() )
{
auto depend = m_depends[h];
if( depend.size() > 1 ) ++indent;
for( auto d : depend )
{
printRoot(d, indent, (depend.size() > 1));
}
}
}
void report()
{
for( auto h : m_depends )
{
if( h.second.size() > 1 )
{
errs() << getFileName(h.first) << " is already include by \n";
for( auto d : h.second )
{
printRoot(d, 1, true);
}
}
}
}
void writeID(raw_ostream& OS, hash::result_type h)
{
OS << "header_" << h;
}
void dot()
{
if( m_output.empty() ) return;
std::error_code EC;
llvm::raw_fd_ostream OS(m_output, EC, llvm::sys::fs::F_Text);
if( EC )
{
PP.getDiagnostics().Report(diag::err_fe_error_opening) << m_output
<< EC.message();
return;
}
const char* endl = "\n";
OS << "digraph \"dependencies\" {" << endl;
for( auto inc : m_includes )
{
writeID(OS, inc.first);
OS << " [ shape=\"box\", label=\"";
OS << DOT::EscapeString(getFileName(inc.second));
OS << "\"];" << endl;
}
for( auto h : m_depends )
{
for(auto depend : h.second)
{
writeID(OS, h.first);
OS << " -> ";
writeID(OS, depend);
OS << endl;
}
}
OS << "}" << endl;
}
void EndOfMainFile() override
{
report();
dot();
}
void InclusionDirective(SourceLocation HashLoc,
const Token &IncludeTok,
llvm::StringRef FileName,
bool IsAngled,
CharSourceRange FilenameRange,
const FileEntry *File,
llvm::StringRef SearchPath,
llvm::StringRef RelativePath,
const Module *Imported) override
{
if( File == nullptr ) return;
SourceManager& SM = PP.getSourceManager();
const FileEntry* pFromFile = SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(HashLoc)));
if( pFromFile == nullptr ) return;
const auto h = hash()(File->getName());
const auto p = hash()(pFromFile->getName());
{
if( m_includes.find(h) == m_includes.end() )
{
m_includes.insert(::std::make_pair(h, header(File->getName(), IsAngled)));
}
auto it = m_includes.find(p);
if( it == m_includes.end() )
{
m_root = p;
m_includes.insert(::std::make_pair(p, header(pFromFile->getName(), false)));
}
if( it != m_includes.end() )
{
it->second.include.push_back(h);
}
}
if( !IsAngled )
{
auto it = m_depends.find(h);
if( it != m_depends.end() )
{
it->second.push_back(p);
}
else
{
hash_list a;
a.push_back(p);
m_depends.insert(::std::make_pair(h, a));
}
}
#if 0
errs() << "InclusionDirective : ";
if (File) {
if (IsAngled) errs() << "<" << File->getName() << ">\n";
else errs() << "\"" << File->getName() << "\"\n";
} else {
errs() << "not found file ";
if (IsAngled) errs() << "<" << FileName << ">\n";
else errs() << "\"" << FileName << "\"\n";
}
#endif
}
};
class ExampleASTConsumer : public ASTConsumer {
private:
public:
explicit ExampleASTConsumer(CompilerInstance *CI) {
// vvZbTΜR[obNo^
Preprocessor &PP = CI->getPreprocessor();
PP.addPPCallbacks(llvm::make_unique<cincluder>(PP, "test.dot"));
//AttachDependencyGraphGen(PP, "test.dot", "");
}
};
class ExampleFrontendAction : public SyntaxOnlyAction /*ASTFrontendAction*/ {
public:
virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) {
return llvm::make_unique<ExampleASTConsumer>(&CI); // pass CI pointer to ASTConsumer
}
};
static cl::OptionCategory MyToolCategory("cincluder");
int main(int argc, const char** argv)
{
CommonOptionsParser op(argc, argv, MyToolCategory);
ClangTool Tool(op.getCompilations(), op.getSourcePathList());
return Tool.run(newFrontendActionFactory<ExampleFrontendAction>().get());
}
|
write .dot
|
write .dot
|
C++
|
bsd-3-clause
|
srz-zumix/cincluder
|
a0b1ed85b41c9805872afbdbc8581e7954f2c49c
|
src/common/config.cpp
|
src/common/config.cpp
|
// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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 "config.hpp"
#include "exception.hpp"
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <pficommon/lang/cast.h>
using namespace std;
using namespace pfi::lang;
using namespace pfi::text::json;
namespace jubatus {
namespace common {
void config_fromlocal(const string& path, string& config)
{
ifstream ifc(path.c_str());
if (!ifc){
throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error("can't read config file."));
}
ifc >> config;
}
#ifdef HAVE_ZOOKEEPER_H
void config_fromzk(lock_service& z,
const string& type, const string& name,
string& config)
{
bool success = true;
string path;
build_config_path(path, type, name);
success = z.exists(path) && success;
// success = z.create(path + "/config_lock", "") && success;
common::lock_service_mutex zlk(z, path);
while(!zlk.try_lock()){ ; }
success = z.read(path, config) && success;
if (!success)
throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error("Failed to get config from zookeeper")
<< jubatus::exception::error_api_func("lock_service::create"));
}
void config_tozk(lock_service& z,
const string& type, const string& name,
string& config)
{
bool success = true;
string path;
build_config_path(path, type, name);
// success = z.create(path + "/config_lock", "") && success;
common::lock_service_mutex zlk(z, path);
while(!zlk.try_lock()){ ; }
success = z.create(path, config) && success;
if (!success)
throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error("Failed to set config to zookeeper")
<< jubatus::exception::error_api_func("lock_service::create"));
}
#endif
} // common
} // jubatus
|
// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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 "config.hpp"
#include "exception.hpp"
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <pficommon/lang/cast.h>
using namespace std;
using namespace pfi::lang;
using namespace pfi::text::json;
namespace jubatus {
namespace common {
void config_fromlocal(const string& path, string& config)
{
ifstream ifc(path.c_str());
if (!ifc){
throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error("can't read config file."));
}
stringstream ss;
ss << ifc.rdbuf();
config = ss.str();
}
#ifdef HAVE_ZOOKEEPER_H
void config_fromzk(lock_service& z,
const string& type, const string& name,
string& config)
{
bool success = true;
string path;
build_config_path(path, type, name);
success = z.exists(path) && success;
// success = z.create(path + "/config_lock", "") && success;
common::lock_service_mutex zlk(z, path);
while(!zlk.try_lock()){ ; }
success = z.read(path, config) && success;
if (!success)
throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error("Failed to get config from zookeeper")
<< jubatus::exception::error_api_func("lock_service::create"));
}
void config_tozk(lock_service& z,
const string& type, const string& name,
string& config)
{
bool success = true;
string path;
build_config_path(path, type, name);
// success = z.create(path + "/config_lock", "") && success;
common::lock_service_mutex zlk(z, path);
while(!zlk.try_lock()){ ; }
success = z.create(path, config) && success;
if (!success)
throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error("Failed to set config to zookeeper")
<< jubatus::exception::error_api_func("lock_service::create"));
}
#endif
} // common
} // jubatus
|
fix bug
|
fix bug
|
C++
|
lgpl-2.1
|
rimms/jubatus,jubatus/jubatus,kmaehashi/jubatus_core,gintenlabo/jubatus_core,roselleebarle04/jubatus,gintenlabo/jubatus,kumagi/jubatus_core,jubatus/jubatus,gintenlabo/jubatus_core,gintenlabo/jubatus_core,roselleebarle04/jubatus,kumagi/jubatus_core,kmaehashi/jubatus,kmaehashi/jubatus_core,kmaehashi/jubatus_core,rimms/jubatus_core,rimms/jubatus,rimms/jubatus_core,jubatus/jubatus,mathn/jubatus,elkingtonmcb/jubatus,gintenlabo/jubatus_core,kmaehashi/jubatus,kumagi/jubatus_core,Asuka52/jubatus,kmaehashi/jubatus_core,rimms/jubatus_core,kumagi/jubatus_core,elkingtonmcb/jubatus,mathn/jubatus,Asuka52/jubatus,gintenlabo/jubatus,rimms/jubatus_core
|
1fb6d3e18285c8b96e3a33eff475bb95a9817734
|
src/common/logging.cc
|
src/common/logging.cc
|
// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: [email protected]
#ifndef COMMON_LOGGING_H_
#define COMMON_LOGGING_H_
#include "logging.h"
#include <assert.h>
#include <boost/bind.hpp>
#include <queue>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string>
#include <syscall.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <common/mutex.h>
#include <common/thread.h>
namespace common {
int g_log_level = 4;
FILE* g_log_file = stdout;
FILE* g_warning_file = NULL;
void SetLogLevel(int level) {
g_log_level = level;
}
class AsyncLogger {
public:
AsyncLogger()
: jobs_(&mu_), stopped_(false) {
thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this));
}
~AsyncLogger() {
stopped_ = true;
{
MutexLock lock(&mu_);
jobs_.Signal();
}
thread_.Join();
// close fd
}
void WriteLog(int log_level, const char* buffer, int32_t len) {
MutexLock lock(&mu_);
buffer_queue_.push(make_pair(log_level, new std::string(buffer, len)));
jobs_.Signal();
}
void AsyncWriter() {
MutexLock lock(&mu_);
while (1) {
int loglen = 0;
int wflen = 0;
while (!buffer_queue_.empty() && !stopped_) {
int log_level = buffer_queue_.front().first;
std::string* str = buffer_queue_.front().second;
buffer_queue_.pop();
mu_.Unlock();
fwrite(str->data(), 1, str->size(), g_log_file);
loglen += str->size();
if (g_warning_file && log_level >= 8) {
fwrite(str->data(), 1, str->size(), g_warning_file);
wflen += str->size();
}
delete str;
mu_.Lock();
}
if (loglen) fflush(g_log_file);
if (wflen) fflush(g_warning_file);
if (stopped_) {
break;
}
jobs_.Wait();
}
}
private:
Mutex mu_;
CondVar jobs_;
bool stopped_;
Thread thread_;
std::queue<std::pair<int, std::string*> > buffer_queue_;
};
AsyncLogger g_logger;
bool SetWarningFile(const char* path, bool append) {
const char* mode = append ? "ab" : "wb";
FILE* fp = fopen(path, mode);
if (fp == NULL) {
return false;
}
if (g_warning_file) {
fclose(g_warning_file);
}
g_warning_file = fp;
return true;
}
bool SetLogFile(const char* path, bool append) {
const char* mode = append ? "ab" : "wb";
FILE* fp = fopen(path, mode);
if (fp == NULL) {
g_log_file = stdout;
return false;
}
if (g_log_file != stdout) {
fclose(g_log_file);
}
g_log_file = fp;
return true;
}
void Logv(int log_level, const char* format, va_list ap) {
const uint64_t thread_id = syscall(__NR_gettid);
// We try twice: the first time with a fixed-size stack allocated buffer,
// and the second time with a much larger dynamically allocated buffer.
char buffer[500];
for (int iter = 0; iter < 2; iter++) {
char* base;
int bufsize;
if (iter == 0) {
bufsize = sizeof(buffer);
base = buffer;
} else {
bufsize = 30000;
base = new char[bufsize];
}
char* p = base;
char* limit = base + bufsize;
struct timeval now_tv;
gettimeofday(&now_tv, NULL);
const time_t seconds = now_tv.tv_sec;
struct tm t;
localtime_r(&seconds, &t);
p += snprintf(p, limit - p,
"%02d/%02d %02d:%02d:%02d.%06d %lld ",
t.tm_mon + 1,
t.tm_mday,
t.tm_hour,
t.tm_min,
t.tm_sec,
static_cast<int>(now_tv.tv_usec),
static_cast<long long unsigned int>(thread_id));
// Print the message
if (p < limit) {
va_list backup_ap;
va_copy(backup_ap, ap);
p += vsnprintf(p, limit - p, format, backup_ap);
va_end(backup_ap);
}
// Truncate to available space if necessary
if (p >= limit) {
if (iter == 0) {
continue; // Try again with larger buffer
} else {
p = limit - 1;
}
}
// Add newline if necessary
if (p == base || p[-1] != '\n') {
*p++ = '\n';
}
assert(p <= limit);
//fwrite(base, 1, p - base, g_log_file);
//fflush(g_log_file);
//if (g_warning_file && log_level >= 8) {
// fwrite(base, 1, p - base, g_warning_file);
// fflush(g_warning_file);
//}
g_logger.WriteLog(log_level, base, p - base);
if (base != buffer) {
delete[] base;
}
break;
}
}
void Log(int level, const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
if (level >= g_log_level) {
Logv(level, fmt, ap);
}
va_end(ap);
}
} // namespace common
#endif // COMMON_LOGGING_H_
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
|
// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: [email protected]
#ifndef COMMON_LOGGING_H_
#define COMMON_LOGGING_H_
#include "logging.h"
#include <assert.h>
#include <boost/bind.hpp>
#include <queue>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string>
#include <syscall.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <common/mutex.h>
#include <common/thread.h>
namespace common {
int g_log_level = 4;
FILE* g_log_file = stdout;
FILE* g_warning_file = NULL;
void SetLogLevel(int level) {
g_log_level = level;
}
class AsyncLogger {
public:
AsyncLogger()
: jobs_(&mu_), stopped_(false) {
thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this));
}
~AsyncLogger() {
stopped_ = true;
{
MutexLock lock(&mu_);
jobs_.Signal();
}
thread_.Join();
// close fd
}
void WriteLog(int log_level, const char* buffer, int32_t len) {
MutexLock lock(&mu_);
buffer_queue_.push(make_pair(log_level, new std::string(buffer, len)));
jobs_.Signal();
}
void AsyncWriter() {
MutexLock lock(&mu_);
while (1) {
int loglen = 0;
int wflen = 0;
while (!buffer_queue_.empty()) {
int log_level = buffer_queue_.front().first;
std::string* str = buffer_queue_.front().second;
buffer_queue_.pop();
mu_.Unlock();
fwrite(str->data(), 1, str->size(), g_log_file);
loglen += str->size();
if (g_warning_file && log_level >= 8) {
fwrite(str->data(), 1, str->size(), g_warning_file);
wflen += str->size();
}
delete str;
mu_.Lock();
}
if (loglen) fflush(g_log_file);
if (wflen) fflush(g_warning_file);
if (stopped_) {
break;
}
jobs_.Wait();
}
}
private:
Mutex mu_;
CondVar jobs_;
bool stopped_;
Thread thread_;
std::queue<std::pair<int, std::string*> > buffer_queue_;
};
AsyncLogger g_logger;
bool SetWarningFile(const char* path, bool append) {
const char* mode = append ? "ab" : "wb";
FILE* fp = fopen(path, mode);
if (fp == NULL) {
return false;
}
if (g_warning_file) {
fclose(g_warning_file);
}
g_warning_file = fp;
return true;
}
bool SetLogFile(const char* path, bool append) {
const char* mode = append ? "ab" : "wb";
FILE* fp = fopen(path, mode);
if (fp == NULL) {
g_log_file = stdout;
return false;
}
if (g_log_file != stdout) {
fclose(g_log_file);
}
g_log_file = fp;
return true;
}
void Logv(int log_level, const char* format, va_list ap) {
const uint64_t thread_id = syscall(__NR_gettid);
// We try twice: the first time with a fixed-size stack allocated buffer,
// and the second time with a much larger dynamically allocated buffer.
char buffer[500];
for (int iter = 0; iter < 2; iter++) {
char* base;
int bufsize;
if (iter == 0) {
bufsize = sizeof(buffer);
base = buffer;
} else {
bufsize = 30000;
base = new char[bufsize];
}
char* p = base;
char* limit = base + bufsize;
struct timeval now_tv;
gettimeofday(&now_tv, NULL);
const time_t seconds = now_tv.tv_sec;
struct tm t;
localtime_r(&seconds, &t);
p += snprintf(p, limit - p,
"%02d/%02d %02d:%02d:%02d.%06d %lld ",
t.tm_mon + 1,
t.tm_mday,
t.tm_hour,
t.tm_min,
t.tm_sec,
static_cast<int>(now_tv.tv_usec),
static_cast<long long unsigned int>(thread_id));
// Print the message
if (p < limit) {
va_list backup_ap;
va_copy(backup_ap, ap);
p += vsnprintf(p, limit - p, format, backup_ap);
va_end(backup_ap);
}
// Truncate to available space if necessary
if (p >= limit) {
if (iter == 0) {
continue; // Try again with larger buffer
} else {
p = limit - 1;
}
}
// Add newline if necessary
if (p == base || p[-1] != '\n') {
*p++ = '\n';
}
assert(p <= limit);
//fwrite(base, 1, p - base, g_log_file);
//fflush(g_log_file);
//if (g_warning_file && log_level >= 8) {
// fwrite(base, 1, p - base, g_warning_file);
// fflush(g_warning_file);
//}
g_logger.WriteLog(log_level, base, p - base);
if (base != buffer) {
delete[] base;
}
break;
}
}
void Log(int level, const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
if (level >= g_log_level) {
Logv(level, fmt, ap);
}
va_end(ap);
}
} // namespace common
#endif // COMMON_LOGGING_H_
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
|
Update logging.cc
|
Update logging.cc
|
C++
|
bsd-3-clause
|
yvxiang/dfs,lylei/dfs,yvxiang/coverage_for_bfs,imotai/bfs,yvxiang/dfs,bluebore/dfs,baidu/bfs,yvxiang/dfs,baidu/bfs,lylei/dfs,bluebore/bfs,yvxiang/coverage_for_bfs,00k/ToyDFS,lylei/dfs,linyvxiang/dfs,myawan/bfs-1,baidu/bfs,imotai/bfs,yvxiang/coverage_for_bfs,myawan/bfs-1,linyvxiang/dfs,lylei/dfs,bluebore/bfs,myawan/bfs-1,myawan/bfs-1,bluebore/dfs,imotai/bfs,00k/ToyDFS,bluebore/bfs,linyvxiang/dfs,yvxiang/dfs,bluebore/dfs,yvxiang/coverage_for_bfs,baidu/bfs
|
5f3cf53e2fa1afab831ae0e2ac3669c0b5a1d7ac
|
ds18b20_sensor/ds18b20_sensor.cpp
|
ds18b20_sensor/ds18b20_sensor.cpp
|
// Author: Brian Scully
// Copyright (c) 2016 Agponics
#include "ds18b20_sensor.h"
void CDs18b20Sensor::set_pin(int pin)
{
CDevice::set_pin(pin);
m_one_wire = OneWire(pin);
m_dt.setOneWire(&m_one_wire);
m_dt.begin();
m_device_cnt = m_dt.getDeviceCount();
if (m_device_cnt > MAX_PROBES)
{
m_device_cnt = MAX_PROBES;
}
for (uint8_t i = 0; i < m_device_cnt; i++)
{
if (!m_dt.getAddress(m_addrs[i], i))
{
DS18B20_DBGMSG("Failed to get address!")
}
}
}
String CDs18b20Sensor::get_status_str()
{
float temp = 0.0;
String out = "";
// have all probes read temp
m_dt.requestTemperatures();
for (uint8_t i = 0; i < m_device_cnt; i++)
{
temp = m_dt.getTempF(m_addrs[i]);
out += CDevice::get_status_str();
out += "probe" + String(i) + ":temp:";
out += String(int(temp));
if (i < m_device_cnt - 1)
{
out += "\n";
}
}
return out;
}
String CDs18b20Sensor::get_addrs_str()
{
uint8_t next_addr[8] = {0};
uint8_t i = 0;
String out = "One-wire Addresses Found:\n";
while (m_dt.getAddress(next_addr, i))
{
out += String(i) + ":";
for (int j = 0; j < 8; j++)
{
out += " 0x" + String(next_addr[j], HEX);
}
out += "\n";
i++;
}
return out;
}
|
// Author: Brian Scully
// Copyright (c) 2016 Agponics
#include "ds18b20_sensor.h"
void CDs18b20Sensor::set_pin(int pin)
{
CDevice::set_pin(pin);
m_one_wire = OneWire(pin);
m_dt.setOneWire(&m_one_wire);
m_dt.begin();
m_device_cnt = m_dt.getDeviceCount();
if (m_device_cnt > MAX_PROBES)
{
m_device_cnt = MAX_PROBES;
}
for (uint8_t i = 0; i < m_device_cnt; i++)
{
if (!m_dt.getAddress(m_addrs[i], i))
{
DS18B20_DBGMSG("Failed to get address!")
}
}
}
String CDs18b20Sensor::get_status_str()
{
float temp = 0.0;
String out = "";
// have all probes read temp
m_dt.requestTemperatures();
for (uint8_t i = 0; i < m_device_cnt; i++)
{
temp = m_dt.getTempF(m_addrs[i]);
out += CDevice::get_status_str();
out += "probe" + String(i) + "temp:";
out += String(int(temp));
if (i < m_device_cnt - 1)
{
out += "\n";
}
}
return out;
}
String CDs18b20Sensor::get_addrs_str()
{
uint8_t next_addr[8] = {0};
uint8_t i = 0;
String out = "One-wire Addresses Found:\n";
while (m_dt.getAddress(next_addr, i))
{
out += String(i) + ":";
for (int j = 0; j < 8; j++)
{
out += " 0x" + String(next_addr[j], HEX);
}
out += "\n";
i++;
}
return out;
}
|
Remove ':' from DS18B20 status
|
Remove ':' from DS18B20 status
|
C++
|
artistic-2.0
|
Agponics/arduinolibs,Agponics/arduinolibs
|
9e6013809d63f3365023e6047fa31865db4e556d
|
src/cli/utils.cpp
|
src/cli/utils.cpp
|
/*
* (C) 2009,2010,2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "cli.h"
#include <botan/version.h>
#include <botan/auto_rng.h>
#include <botan/hash.h>
#include <botan/cpuid.h>
#include <botan/hex.h>
#if defined(BOTAN_HAS_BASE64_CODEC)
#include <botan/base64.h>
#endif
#if defined(BOTAN_HAS_SYSTEM_RNG)
#include <botan/system_rng.h>
#endif
#if defined(BOTAN_HAS_HTTP_UTIL)
#include <botan/http_util.h>
#endif
#if defined(BOTAN_HAS_BCRYPT)
#include <botan/bcrypt.h>
#endif
namespace Botan_CLI {
class Config_Info final : public Command
{
public:
Config_Info() : Command("config info_type") {}
std::string help_text() const override
{
return "Usage: config info_type\n"
" prefix: Print install prefix\n"
" cflags: Print include params\n"
" ldflags: Print linker params\n"
" libs: Print libraries\n";
}
void go() override
{
const std::string arg = get_arg("info_type");
if(arg == "prefix")
{
output() << BOTAN_INSTALL_PREFIX << "\n";
}
else if(arg == "cflags")
{
output() << "-I" << BOTAN_INSTALL_PREFIX << "/" << BOTAN_INSTALL_HEADER_DIR << "\n";
}
else if(arg == "ldflags")
{
output() << "-L" << BOTAN_INSTALL_PREFIX << "/" << BOTAN_INSTALL_LIB_DIR << "\n";
}
else if(arg == "libs")
{
output() << "-lbotan-" << Botan::version_major() << "." << Botan::version_minor()
<< " " << BOTAN_LIB_LINK << "\n";
}
else
{
throw CLI_Usage_Error("Unknown option to botan config " + arg);
}
}
};
BOTAN_REGISTER_COMMAND("config", Config_Info);
class Version_Info final : public Command
{
public:
Version_Info() : Command("version --full") {}
void go() override
{
if(flag_set("full"))
{
output() << Botan::version_string() << "\n";
}
else
{
output() << Botan::version_major() << "."
<< Botan::version_minor() << "."
<< Botan::version_patch() << "\n";
}
}
};
BOTAN_REGISTER_COMMAND("version", Version_Info);
class Print_Cpuid final : public Command
{
public:
Print_Cpuid() : Command("cpuid") {}
void go() override
{
Botan::CPUID::print(output());
}
};
BOTAN_REGISTER_COMMAND("cpuid", Print_Cpuid);
class Hash final : public Command
{
public:
Hash() : Command("hash --algo=SHA-256 --buf-size=4096 *files") {}
void go() override
{
const std::string hash_algo = get_arg("algo");
std::unique_ptr<Botan::HashFunction> hash_fn(Botan::HashFunction::create(hash_algo));
if(!hash_fn)
throw CLI_Error_Unsupported("hashing", hash_algo);
const size_t buf_size = get_arg_sz("buf-size");
auto files = get_arg_list("files");
if(files.empty())
files.push_back("-"); // read stdin if no arguments on command line
for(auto fsname : files)
{
try
{
auto update_hash = [&](const uint8_t b[], size_t l) { hash_fn->update(b, l); };
read_file(fsname, update_hash, buf_size);
output() << Botan::hex_encode(hash_fn->final()) << " " << fsname << "\n";
}
catch(CLI_IO_Error& e)
{
error_output() << e.what() << "\n";
}
}
}
};
BOTAN_REGISTER_COMMAND("hash", Hash);
class RNG final : public Command
{
public:
RNG() : Command("rng bytes --system") {}
void go() override
{
const size_t bytes = get_arg_sz("bytes");
if(flag_set("system"))
{
#if defined(BOTAN_HAS_SYSTEM_RNG)
output() << Botan::hex_encode(Botan::system_rng().random_vec(bytes)) << "\n";
#else
error_output() << "system_rng disabled in build\n";
#endif
}
else
{
Botan::AutoSeeded_RNG rng;
output() << Botan::hex_encode(rng.random_vec(bytes)) << "\n";
}
}
};
BOTAN_REGISTER_COMMAND("rng", RNG);
#if defined(BOTAN_HAS_HTTP_UTIL)
class HTTP_Get final : public Command
{
public:
HTTP_Get() : Command("http_get url") {}
void go() override
{
output() << Botan::HTTP::GET_sync(get_arg("url")) << "\n";
}
};
BOTAN_REGISTER_COMMAND("http_get", HTTP_Get);
#endif // http_util
#if defined(BOTAN_HAS_BASE64_CODEC)
class Base64_Encode final : public Command
{
public:
Base64_Encode() : Command("base64_enc file") {}
void go() override
{
this->read_file(get_arg("file"),
[&](const uint8_t b[], size_t l) { output() << Botan::base64_encode(b, l); },
768);
}
};
BOTAN_REGISTER_COMMAND("base64_enc", Base64_Encode);
class Base64_Decode final : public Command
{
public:
Base64_Decode() : Command("base64_dec file") {}
void go() override
{
auto write_bin = [&](const uint8_t b[], size_t l)
{
Botan::secure_vector<uint8_t> bin = Botan::base64_decode(reinterpret_cast<const char*>(b), l);
output().write(reinterpret_cast<const char*>(bin.data()), bin.size());
};
this->read_file(get_arg("file"),
write_bin,
1024);
}
};
BOTAN_REGISTER_COMMAND("base64_dec", Base64_Decode);
#endif // base64
#if defined(BOTAN_HAS_BCRYPT)
class Generate_Bcrypt final : public Command
{
public:
Generate_Bcrypt() : Command("gen_bcrypt --work-factor=12 password") {}
void go() override
{
const std::string password = get_arg("password");
const size_t wf = get_arg_sz("work_factor");
output() << Botan::generate_bcrypt(password, rng(), wf) << "\n";
}
};
BOTAN_REGISTER_COMMAND("gen_bcrypt", Generate_Bcrypt);
class Check_Bcrypt final : public Command
{
public:
Check_Bcrypt() : Command("check_bcrypt password hash") {}
void go() override
{
const std::string password = get_arg("password");
const std::string hash = get_arg("hash");
if(hash.length() != 60)
{
error_output() << "Note: bcrypt '" << hash << "' has wrong length and cannot be valid\n";
}
const bool ok = Botan::check_bcrypt(password, hash);
output() << "Password is " << (ok ? "valid" : "NOT valid") << std::endl;
}
};
BOTAN_REGISTER_COMMAND("check_bcrypt", Check_Bcrypt);
#endif // bcrypt
}
|
/*
* (C) 2009,2010,2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "cli.h"
#include <botan/version.h>
#include <botan/auto_rng.h>
#include <botan/hash.h>
#include <botan/cpuid.h>
#include <botan/hex.h>
#if defined(BOTAN_HAS_BASE64_CODEC)
#include <botan/base64.h>
#endif
#if defined(BOTAN_HAS_SYSTEM_RNG)
#include <botan/system_rng.h>
#endif
#if defined(BOTAN_HAS_HTTP_UTIL)
#include <botan/http_util.h>
#endif
#if defined(BOTAN_HAS_BCRYPT)
#include <botan/bcrypt.h>
#endif
namespace Botan_CLI {
class Config_Info final : public Command
{
public:
Config_Info() : Command("config info_type") {}
std::string help_text() const override
{
return "Usage: config info_type\n"
" prefix: Print install prefix\n"
" cflags: Print include params\n"
" ldflags: Print linker params\n"
" libs: Print libraries\n";
}
void go() override
{
const std::string arg = get_arg("info_type");
if(arg == "prefix")
{
output() << BOTAN_INSTALL_PREFIX << "\n";
}
else if(arg == "cflags")
{
output() << "-I" << BOTAN_INSTALL_PREFIX << "/" << BOTAN_INSTALL_HEADER_DIR << "\n";
}
else if(arg == "ldflags")
{
output() << "-L" << BOTAN_INSTALL_PREFIX << "/" << BOTAN_INSTALL_LIB_DIR << "\n";
}
else if(arg == "libs")
{
output() << "-lbotan-" << Botan::version_major() << "." << Botan::version_minor()
<< " " << BOTAN_LIB_LINK << "\n";
}
else
{
throw CLI_Usage_Error("Unknown option to botan config " + arg);
}
}
};
BOTAN_REGISTER_COMMAND("config", Config_Info);
class Version_Info final : public Command
{
public:
Version_Info() : Command("version --full") {}
void go() override
{
if(flag_set("full"))
{
output() << Botan::version_string() << "\n";
}
else
{
output() << Botan::version_major() << "."
<< Botan::version_minor() << "."
<< Botan::version_patch() << "\n";
}
}
};
BOTAN_REGISTER_COMMAND("version", Version_Info);
class Print_Cpuid final : public Command
{
public:
Print_Cpuid() : Command("cpuid") {}
void go() override
{
Botan::CPUID::print(output());
}
};
BOTAN_REGISTER_COMMAND("cpuid", Print_Cpuid);
class Hash final : public Command
{
public:
Hash() : Command("hash --algo=SHA-256 --buf-size=4096 *files") {}
void go() override
{
const std::string hash_algo = get_arg("algo");
std::unique_ptr<Botan::HashFunction> hash_fn(Botan::HashFunction::create(hash_algo));
if(!hash_fn)
throw CLI_Error_Unsupported("hashing", hash_algo);
const size_t buf_size = get_arg_sz("buf-size");
auto files = get_arg_list("files");
if(files.empty())
files.push_back("-"); // read stdin if no arguments on command line
for(auto fsname : files)
{
try
{
auto update_hash = [&](const uint8_t b[], size_t l) { hash_fn->update(b, l); };
read_file(fsname, update_hash, buf_size);
output() << Botan::hex_encode(hash_fn->final()) << " " << fsname << "\n";
}
catch(CLI_IO_Error& e)
{
error_output() << e.what() << "\n";
}
}
}
};
BOTAN_REGISTER_COMMAND("hash", Hash);
class RNG final : public Command
{
public:
RNG() : Command("rng --system *bytes") {}
void go() override
{
std::unique_ptr<Botan::RNG> rng;
if(flag_set("system"))
{
#if defined(BOTAN_HAS_SYSTEM_RNG)
rng.reset(new Botan::System_RNG);
#else
error_output() << "system_rng disabled in build\n";
return;
#endif
}
else
{
rng.reset(new Botan::AutoSeeded_RNG);
}
for(const std::string& req : get_arg_list("bytes"))
{
output() << Botan::hex_encode(rng->random_vec(Botan::to_u32bit(req))) << "\n";
}
}
};
BOTAN_REGISTER_COMMAND("rng", RNG);
#if defined(BOTAN_HAS_HTTP_UTIL)
class HTTP_Get final : public Command
{
public:
HTTP_Get() : Command("http_get url") {}
void go() override
{
output() << Botan::HTTP::GET_sync(get_arg("url")) << "\n";
}
};
BOTAN_REGISTER_COMMAND("http_get", HTTP_Get);
#endif // http_util
#if defined(BOTAN_HAS_BASE64_CODEC)
class Base64_Encode final : public Command
{
public:
Base64_Encode() : Command("base64_enc file") {}
void go() override
{
this->read_file(get_arg("file"),
[&](const uint8_t b[], size_t l) { output() << Botan::base64_encode(b, l); },
768);
}
};
BOTAN_REGISTER_COMMAND("base64_enc", Base64_Encode);
class Base64_Decode final : public Command
{
public:
Base64_Decode() : Command("base64_dec file") {}
void go() override
{
auto write_bin = [&](const uint8_t b[], size_t l)
{
Botan::secure_vector<uint8_t> bin = Botan::base64_decode(reinterpret_cast<const char*>(b), l);
output().write(reinterpret_cast<const char*>(bin.data()), bin.size());
};
this->read_file(get_arg("file"),
write_bin,
1024);
}
};
BOTAN_REGISTER_COMMAND("base64_dec", Base64_Decode);
#endif // base64
#if defined(BOTAN_HAS_BCRYPT)
class Generate_Bcrypt final : public Command
{
public:
Generate_Bcrypt() : Command("gen_bcrypt --work-factor=12 password") {}
void go() override
{
const std::string password = get_arg("password");
const size_t wf = get_arg_sz("work_factor");
output() << Botan::generate_bcrypt(password, rng(), wf) << "\n";
}
};
BOTAN_REGISTER_COMMAND("gen_bcrypt", Generate_Bcrypt);
class Check_Bcrypt final : public Command
{
public:
Check_Bcrypt() : Command("check_bcrypt password hash") {}
void go() override
{
const std::string password = get_arg("password");
const std::string hash = get_arg("hash");
if(hash.length() != 60)
{
error_output() << "Note: bcrypt '" << hash << "' has wrong length and cannot be valid\n";
}
const bool ok = Botan::check_bcrypt(password, hash);
output() << "Password is " << (ok ? "valid" : "NOT valid") << std::endl;
}
};
BOTAN_REGISTER_COMMAND("check_bcrypt", Check_Bcrypt);
#endif // bcrypt
}
|
Update rng cli - can make multiple requests
|
Update rng cli - can make multiple requests
|
C++
|
bsd-2-clause
|
randombit/botan,webmaster128/botan,webmaster128/botan,randombit/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan
|
5a1e369d92ca5b344c916ce5df4c2c7a8d6523bd
|
src/Editor/Editor.cpp
|
src/Editor/Editor.cpp
|
#include "Editor.hpp"
#include "Util/EditorSettings.hpp"
#undef CreateDirectory
#include <Engine/Util/Input.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ScriptManager.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Engine/MainWindow.hpp>
#include <Engine/Component/DirectionalLight.hpp>
#include <Engine/Component/Lens.hpp>
#include <Engine/Component/Listener.hpp>
#include "ImGui/Theme.hpp"
#include <imgui.h>
#include <GLFW/glfw3.h>
Editor::Editor() {
// Create Hymns directory.
FileSystem::CreateDirectory((FileSystem::DataPath("Hymn to Beauty") + FileSystem::DELIMITER + "Hymns").c_str());
// Load theme.
std::string theme = EditorSettings::GetInstance().GetString("Theme");
if (FileSystem::FileExists((FileSystem::DataPath("Hymn to Beauty") + FileSystem::DELIMITER + "Themes" + FileSystem::DELIMITER + theme + ".json").c_str())) {
ImGui::LoadTheme(theme.c_str());
} else {
ImGui::LoadDefaultTheme();
}
// Assign controls.
Input()->AssignButton(InputHandler::PROFILE, InputHandler::KEYBOARD, GLFW_KEY_F2);
Input()->AssignButton(InputHandler::PLAYTEST, InputHandler::KEYBOARD, GLFW_KEY_F5);
Input()->AssignButton(InputHandler::CONTROL, InputHandler::KEYBOARD, GLFW_KEY_LEFT_CONTROL);
Input()->AssignButton(InputHandler::NEW, InputHandler::KEYBOARD, GLFW_KEY_N);
Input()->AssignButton(InputHandler::OPEN, InputHandler::KEYBOARD, GLFW_KEY_O);
Input()->AssignButton(InputHandler::CAMERA, InputHandler::MOUSE, GLFW_MOUSE_BUTTON_MIDDLE);
Input()->AssignButton(InputHandler::FORWARD, InputHandler::KEYBOARD, GLFW_KEY_W);
Input()->AssignButton(InputHandler::BACKWARD, InputHandler::KEYBOARD, GLFW_KEY_S);
Input()->AssignButton(InputHandler::LEFT, InputHandler::KEYBOARD, GLFW_KEY_A);
Input()->AssignButton(InputHandler::RIGHT, InputHandler::KEYBOARD, GLFW_KEY_D);
// Create editor camera.
cameraEntity = cameraWorld.CreateEntity("Editor Camera");
cameraEntity->AddComponent<Component::Lens>();
cameraEntity->position.z = 10.0f;
// Create cursors.
cursors[0] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
cursors[1] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
cursors[2] = glfwCreateStandardCursor(GLFW_CROSSHAIR_CURSOR);
cursors[3] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
cursors[4] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
}
Editor::~Editor() {
// Destroy cursors.
for (int i=0; i < 5; ++i) {
glfwDestroyCursor(cursors[i]);
}
}
void Editor::Show(float deltaTime) {
bool play = false;
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Main menu bar.
if (ImGui::BeginMainMenuBar()) {
// File menu.
if (ImGui::BeginMenu("File")) {
if (ImGui::MenuItem("New Hymn", "CTRL+N"))
NewHymn();
if (ImGui::MenuItem("Open Hymn", "CTRL+O"))
OpenHymn();
ImGui::Separator();
if (ImGui::MenuItem("Settings"))
settingsWindow.SetVisible(true);
ImGui::EndMenu();
}
// View menu.
if (ImGui::BeginMenu("View")) {
static bool soundSources = EditorSettings::GetInstance().GetBool("Sound Source Icons");
ImGui::MenuItem("Sound Sources", "", &soundSources);
EditorSettings::GetInstance().SetBool("Sound Source Icons", soundSources);
static bool particleEmitters = EditorSettings::GetInstance().GetBool("Particle Emitter Icons");
ImGui::MenuItem("Particle Emitters", "", &particleEmitters);
EditorSettings::GetInstance().SetBool("Particle Emitter Icons", particleEmitters);
static bool lightSources = EditorSettings::GetInstance().GetBool("Light Source Icons");
ImGui::MenuItem("Light Sources", "", &lightSources);
EditorSettings::GetInstance().SetBool("Light Source Icons", lightSources);
static bool cameras = EditorSettings::GetInstance().GetBool("Camera Icons");
ImGui::MenuItem("Cameras", "", &cameras);
EditorSettings::GetInstance().SetBool("Camera Icons", cameras);
ImGui::EndMenu();
}
// Play
if (ImGui::BeginMenu("Play")) {
if (ImGui::MenuItem("Play", "F5"))
play = true;
ImGui::EndMenu();
}
// Hymn
if(Hymn().GetPath() != "") {
if (ImGui::BeginMenu("Hymn")) {
if (ImGui::MenuItem("Input"))
inputWindow.SetVisible(true);
if (ImGui::MenuItem("Filters"))
filtersWindow.SetVisible(true);
ImGui::EndMenu();
}
}
ImGui::EndMainMenuBar();
}
// Show hymn selection window.
if (selectHymnWindow.IsVisible()) {
ImGui::SetNextWindowPosCenter();
selectHymnWindow.Show();
}
if (inputWindow.IsVisible())
inputWindow.Show();
// Show filters window.
if (filtersWindow.IsVisible())
filtersWindow.Show();
// Show resource list.
if (resourceList.IsVisible())
resourceList.Show();
// Show settings window.
if (settingsWindow.IsVisible()) {
settingsWindow.Show();
}
// Control the editor camera.
if (Input()->Pressed(InputHandler::CAMERA)) {
if (Input()->Triggered(InputHandler::CAMERA)) {
lastX = Input()->CursorX();
lastY = Input()->CursorY();
}
float sensitivity = 0.3f;
cameraEntity->rotation.x += sensitivity * (Input()->CursorX() - lastX);
cameraEntity->rotation.y += sensitivity * (Input()->CursorY() - lastY);
lastX = Input()->CursorX();
lastY = Input()->CursorY();
glm::mat4 orientation = cameraEntity->GetOrientation();
glm::vec3 backward(orientation[0][2], orientation[1][2], orientation[2][2]);
glm::vec3 right(orientation[0][0], orientation[1][0], orientation[2][0]);
float speed = 3.0f * deltaTime;
cameraEntity->position += speed * backward * static_cast<float>(Input()->Pressed(InputHandler::BACKWARD) - Input()->Pressed(InputHandler::FORWARD));
cameraEntity->position += speed * right * static_cast<float>(Input()->Pressed(InputHandler::RIGHT) - Input()->Pressed(InputHandler::LEFT));
}
if (Input()->Triggered(InputHandler::PLAYTEST))
play = true;
if (Input()->Triggered(InputHandler::NEW) && Input()->Pressed(InputHandler::CONTROL))
NewHymn();
if (Input()->Triggered(InputHandler::OPEN) && Input()->Pressed(InputHandler::CONTROL))
OpenHymn();
if (play)
Play();
// Set cursor.
if (ImGui::GetMouseCursor() < 5) {
glfwSetCursor(MainWindow::GetInstance()->GetGLFWWindow(), cursors[ImGui::GetMouseCursor()]);
}
}
void Editor::Save() const {
resourceList.SaveScene();
Hymn().Save();
}
bool Editor::IsVisible() const {
return visible;
}
void Editor::SetVisible(bool visible) {
this->visible = visible;
}
Entity* Editor::GetCamera() const {
return cameraEntity;
}
void Editor::Play() {
Save();
SetVisible(false);
resourceList.HideEditors();
resourceList.ResetScene();
Managers().scriptManager->RegisterInput();
Managers().scriptManager->BuildAllScripts();
}
void Editor::NewHymn() {
selectHymnWindow.Scan();
selectHymnWindow.SetClosedCallback(std::bind(&Editor::NewHymnClosed, this, std::placeholders::_1));
selectHymnWindow.SetTitle("New Hymn");
selectHymnWindow.SetOpenButtonName("Create");
selectHymnWindow.SetVisible(true);
}
void Editor::NewHymnClosed(const std::string& hymn) {
// Create new hymn
if (!hymn.empty()) {
resourceList.ResetScene();
Hymn().Clear();
Hymn().world.CreateRoot();
Hymn().SetPath(FileSystem::DataPath("Hymn to Beauty") + FileSystem::DELIMITER + "Hymns" + FileSystem::DELIMITER + hymn);
resourceList.SetVisible(true);
// Default scene.
Hymn().scenes.push_back("Scene #0");
Entity* player = Hymn().world.GetRoot()->AddChild("Player");
player->position.z = 10.f;
player->AddComponent<Component::Lens>();
player->AddComponent<Component::Listener>();
Entity* sun = Hymn().world.GetRoot()->AddChild("Sun");
sun->AddComponent<Component::DirectionalLight>();
}
selectHymnWindow.SetVisible(false);
}
void Editor::OpenHymn() {
selectHymnWindow.Scan();
selectHymnWindow.SetClosedCallback(std::bind(&Editor::OpenHymnClosed, this, std::placeholders::_1));
selectHymnWindow.SetTitle("Open Hymn");
selectHymnWindow.SetOpenButtonName("Open");
selectHymnWindow.SetVisible(true);
}
void Editor::OpenHymnClosed(const std::string& hymn) {
// Open hymn.
if (!hymn.empty()) {
resourceList.ResetScene();
Hymn().Load(FileSystem::DataPath("Hymn to Beauty") + FileSystem::DELIMITER + "Hymns" + FileSystem::DELIMITER + hymn);
resourceList.SetVisible(true);
}
selectHymnWindow.SetVisible(false);
}
|
#include "Editor.hpp"
#include "Util/EditorSettings.hpp"
#undef CreateDirectory
#include <Engine/Util/Input.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ScriptManager.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Engine/MainWindow.hpp>
#include <Engine/Component/DirectionalLight.hpp>
#include <Engine/Component/Lens.hpp>
#include <Engine/Component/Listener.hpp>
#include "ImGui/Theme.hpp"
#include <imgui.h>
#include <GLFW/glfw3.h>
Editor::Editor() {
// Create Hymns directory.
FileSystem::CreateDirectory((FileSystem::DataPath("Hymn to Beauty") + FileSystem::DELIMITER + "Hymns").c_str());
// Load theme.
std::string theme = EditorSettings::GetInstance().GetString("Theme");
if (FileSystem::FileExists((FileSystem::DataPath("Hymn to Beauty") + FileSystem::DELIMITER + "Themes" + FileSystem::DELIMITER + theme + ".json").c_str())) {
ImGui::LoadTheme(theme.c_str());
} else {
ImGui::LoadDefaultTheme();
}
// Assign controls.
Input()->AssignButton(InputHandler::PROFILE, InputHandler::KEYBOARD, GLFW_KEY_F2);
Input()->AssignButton(InputHandler::PLAYTEST, InputHandler::KEYBOARD, GLFW_KEY_F5);
Input()->AssignButton(InputHandler::CONTROL, InputHandler::KEYBOARD, GLFW_KEY_LEFT_CONTROL);
Input()->AssignButton(InputHandler::NEW, InputHandler::KEYBOARD, GLFW_KEY_N);
Input()->AssignButton(InputHandler::OPEN, InputHandler::KEYBOARD, GLFW_KEY_O);
Input()->AssignButton(InputHandler::CAMERA, InputHandler::MOUSE, GLFW_MOUSE_BUTTON_MIDDLE);
Input()->AssignButton(InputHandler::FORWARD, InputHandler::KEYBOARD, GLFW_KEY_W);
Input()->AssignButton(InputHandler::BACKWARD, InputHandler::KEYBOARD, GLFW_KEY_S);
Input()->AssignButton(InputHandler::LEFT, InputHandler::KEYBOARD, GLFW_KEY_A);
Input()->AssignButton(InputHandler::RIGHT, InputHandler::KEYBOARD, GLFW_KEY_D);
// Create editor camera.
cameraEntity = cameraWorld.CreateEntity("Editor Camera");
cameraEntity->AddComponent<Component::Lens>();
cameraEntity->position.z = 10.0f;
// Create cursors.
cursors[0] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
cursors[1] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
cursors[2] = glfwCreateStandardCursor(GLFW_CROSSHAIR_CURSOR);
cursors[3] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
cursors[4] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
}
Editor::~Editor() {
// Destroy cursors.
for (int i=0; i < 5; ++i) {
glfwDestroyCursor(cursors[i]);
}
}
void Editor::Show(float deltaTime) {
bool play = false;
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Main menu bar.
if (ImGui::BeginMainMenuBar()) {
// File menu.
if (ImGui::BeginMenu("File")) {
if (ImGui::MenuItem("New Hymn", "CTRL+N"))
NewHymn();
if (ImGui::MenuItem("Open Hymn", "CTRL+O"))
OpenHymn();
ImGui::Separator();
if (ImGui::MenuItem("Settings"))
settingsWindow.SetVisible(true);
ImGui::EndMenu();
}
// View menu.
if (ImGui::BeginMenu("View")) {
static bool soundSources = EditorSettings::GetInstance().GetBool("Sound Source Icons");
ImGui::MenuItem("Sound Sources", "", &soundSources);
EditorSettings::GetInstance().SetBool("Sound Source Icons", soundSources);
static bool particleEmitters = EditorSettings::GetInstance().GetBool("Particle Emitter Icons");
ImGui::MenuItem("Particle Emitters", "", &particleEmitters);
EditorSettings::GetInstance().SetBool("Particle Emitter Icons", particleEmitters);
static bool lightSources = EditorSettings::GetInstance().GetBool("Light Source Icons");
ImGui::MenuItem("Light Sources", "", &lightSources);
EditorSettings::GetInstance().SetBool("Light Source Icons", lightSources);
static bool cameras = EditorSettings::GetInstance().GetBool("Camera Icons");
ImGui::MenuItem("Cameras", "", &cameras);
EditorSettings::GetInstance().SetBool("Camera Icons", cameras);
ImGui::EndMenu();
}
// Play
if (ImGui::BeginMenu("Play")) {
if (ImGui::MenuItem("Play", "F5"))
play = true;
ImGui::EndMenu();
}
// Hymn
if(Hymn().GetPath() != "") {
if (ImGui::BeginMenu("Hymn")) {
if (ImGui::MenuItem("Input"))
inputWindow.SetVisible(true);
if (ImGui::MenuItem("Filters"))
filtersWindow.SetVisible(true);
ImGui::EndMenu();
}
}
ImGui::EndMainMenuBar();
}
// Show hymn selection window.
if (selectHymnWindow.IsVisible()) {
ImGui::SetNextWindowPosCenter();
selectHymnWindow.Show();
}
if (inputWindow.IsVisible())
inputWindow.Show();
// Show filters window.
if (filtersWindow.IsVisible())
filtersWindow.Show();
// Show resource list.
if (resourceList.IsVisible())
resourceList.Show();
// Show settings window.
if (settingsWindow.IsVisible()) {
settingsWindow.Show();
}
// Control the editor camera.
if (Input()->Pressed(InputHandler::CAMERA)) {
if (Input()->Triggered(InputHandler::CAMERA)) {
lastX = Input()->CursorX();
lastY = Input()->CursorY();
}
float sensitivity = 0.3f;
cameraEntity->rotation.x += sensitivity * (Input()->CursorX() - lastX);
cameraEntity->rotation.y += sensitivity * (Input()->CursorY() - lastY);
lastX = Input()->CursorX();
lastY = Input()->CursorY();
glm::mat4 orientation = cameraEntity->GetCameraOrientation();
glm::vec3 backward(orientation[0][2], orientation[1][2], orientation[2][2]);
glm::vec3 right(orientation[0][0], orientation[1][0], orientation[2][0]);
float speed = 3.0f * deltaTime;
cameraEntity->position += speed * backward * static_cast<float>(Input()->Pressed(InputHandler::BACKWARD) - Input()->Pressed(InputHandler::FORWARD));
cameraEntity->position += speed * right * static_cast<float>(Input()->Pressed(InputHandler::RIGHT) - Input()->Pressed(InputHandler::LEFT));
}
if (Input()->Triggered(InputHandler::PLAYTEST))
play = true;
if (Input()->Triggered(InputHandler::NEW) && Input()->Pressed(InputHandler::CONTROL))
NewHymn();
if (Input()->Triggered(InputHandler::OPEN) && Input()->Pressed(InputHandler::CONTROL))
OpenHymn();
if (play)
Play();
// Set cursor.
if (ImGui::GetMouseCursor() < 5) {
glfwSetCursor(MainWindow::GetInstance()->GetGLFWWindow(), cursors[ImGui::GetMouseCursor()]);
}
}
void Editor::Save() const {
resourceList.SaveScene();
Hymn().Save();
}
bool Editor::IsVisible() const {
return visible;
}
void Editor::SetVisible(bool visible) {
this->visible = visible;
}
Entity* Editor::GetCamera() const {
return cameraEntity;
}
void Editor::Play() {
Save();
SetVisible(false);
resourceList.HideEditors();
resourceList.ResetScene();
Managers().scriptManager->RegisterInput();
Managers().scriptManager->BuildAllScripts();
}
void Editor::NewHymn() {
selectHymnWindow.Scan();
selectHymnWindow.SetClosedCallback(std::bind(&Editor::NewHymnClosed, this, std::placeholders::_1));
selectHymnWindow.SetTitle("New Hymn");
selectHymnWindow.SetOpenButtonName("Create");
selectHymnWindow.SetVisible(true);
}
void Editor::NewHymnClosed(const std::string& hymn) {
// Create new hymn
if (!hymn.empty()) {
resourceList.ResetScene();
Hymn().Clear();
Hymn().world.CreateRoot();
Hymn().SetPath(FileSystem::DataPath("Hymn to Beauty") + FileSystem::DELIMITER + "Hymns" + FileSystem::DELIMITER + hymn);
resourceList.SetVisible(true);
// Default scene.
Hymn().scenes.push_back("Scene #0");
Entity* player = Hymn().world.GetRoot()->AddChild("Player");
player->position.z = 10.f;
player->AddComponent<Component::Lens>();
player->AddComponent<Component::Listener>();
Entity* sun = Hymn().world.GetRoot()->AddChild("Sun");
sun->AddComponent<Component::DirectionalLight>();
}
selectHymnWindow.SetVisible(false);
}
void Editor::OpenHymn() {
selectHymnWindow.Scan();
selectHymnWindow.SetClosedCallback(std::bind(&Editor::OpenHymnClosed, this, std::placeholders::_1));
selectHymnWindow.SetTitle("Open Hymn");
selectHymnWindow.SetOpenButtonName("Open");
selectHymnWindow.SetVisible(true);
}
void Editor::OpenHymnClosed(const std::string& hymn) {
// Open hymn.
if (!hymn.empty()) {
resourceList.ResetScene();
Hymn().Load(FileSystem::DataPath("Hymn to Beauty") + FileSystem::DELIMITER + "Hymns" + FileSystem::DELIMITER + hymn);
resourceList.SetVisible(true);
}
selectHymnWindow.SetVisible(false);
}
|
Fix editor camera movement
|
Fix editor camera movement
|
C++
|
mit
|
Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/HymnToBeauty,Chainsawkitten/HymnToBeauty
|
9a7202b2594c4a668a0c63e0cfa16052678e619e
|
engine/os/android/AndroidFile.cpp
|
engine/os/android/AndroidFile.cpp
|
/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "AndroidFile.h"
#include "Log.h"
namespace crown
{
//-----------------------------------------------------------------------------
AndroidFile::AndroidFile(const char* path) :
File(FOM_READ),
m_file(path, FOM_READ),
m_last_was_read(true)
{
}
//-----------------------------------------------------------------------------
void AndroidFile::seek(size_t position)
{
check_valid();
m_file.seek(position);
}
//-----------------------------------------------------------------------------
void AndroidFile::seek_to_end()
{
check_valid();
m_file.seek_to_end();
}
//-----------------------------------------------------------------------------
void AndroidFile::skip(size_t bytes)
{
check_valid();
m_file.skip(bytes);
}
//-----------------------------------------------------------------------------
void AndroidFile::read(void* buffer, size_t size)
{
check_valid();
if (!m_last_was_read)
{
m_last_was_read = true;
m_file.seek(0);
}
size_t bytes_read = m_file.read(buffer, size);
CE_ASSERT(bytes_read == size, "Failed to read from file");
}
//-----------------------------------------------------------------------------
void AndroidFile::write(const void* /*buffer*/, size_t /*size*/)
{
// Not needed
}
//-----------------------------------------------------------------------------
bool AndroidFile::copy_to(File& /*file*/, size_t /*size = 0*/)
{
// Not needed
return false;
}
//-----------------------------------------------------------------------------
void AndroidFile::flush()
{
// Not needed
}
//-----------------------------------------------------------------------------
bool AndroidFile::is_valid() const
{
return m_file.is_open();
}
//-----------------------------------------------------------------------------
bool AndroidFile::end_of_file() const
{
return position() == size();
}
//-----------------------------------------------------------------------------
size_t AndroidFile::size() const
{
check_valid();
return m_file.size();
}
//-----------------------------------------------------------------------------
size_t AndroidFile::position() const
{
check_valid();
return m_file.position();
}
//-----------------------------------------------------------------------------
bool AndroidFile::can_read() const
{
check_valid();
return true;
}
//-----------------------------------------------------------------------------
bool AndroidFile::can_write() const
{
check_valid();
return true;
}
//-----------------------------------------------------------------------------
bool AndroidFile::can_seek() const
{
check_valid();
return true;
}
} // namespace crown
|
/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "AndroidFile.h"
#include "Log.h"
namespace crown
{
//-----------------------------------------------------------------------------
AndroidFile::AndroidFile(const char* path) :
File(FOM_READ),
m_file(path, FOM_READ),
m_last_was_read(true)
{
}
//-----------------------------------------------------------------------------
void AndroidFile::seek(size_t position)
{
check_valid();
m_file.seek(position);
}
//-----------------------------------------------------------------------------
void AndroidFile::seek_to_end()
{
check_valid();
m_file.seek_to_end();
}
//-----------------------------------------------------------------------------
void AndroidFile::skip(size_t bytes)
{
check_valid();
m_file.skip(bytes);
}
//-----------------------------------------------------------------------------
void AndroidFile::read(void* buffer, size_t size)
{
check_valid();
if (!m_last_was_read)
{
m_last_was_read = true;
m_file.seek(0);
}
size_t bytes_read = m_file.read(buffer, size);
CE_ASSERT(bytes_read == size, "Failed to read from file");
}
//-----------------------------------------------------------------------------
void AndroidFile::write(const void* /*buffer*/, size_t /*size*/)
{
// Not needed
}
//-----------------------------------------------------------------------------
bool AndroidFile::copy_to(File& /*file*/, size_t /*size = 0*/)
{
// Not needed
return false;
}
//-----------------------------------------------------------------------------
void AndroidFile::flush()
{
// Not needed
}
//-----------------------------------------------------------------------------
bool AndroidFile::is_valid() const
{
return m_file.is_open();
}
//-----------------------------------------------------------------------------
bool AndroidFile::end_of_file() const
{
return position() == size();
}
//-----------------------------------------------------------------------------
size_t AndroidFile::size() const
{
check_valid();
return m_file.size();
}
//-----------------------------------------------------------------------------
size_t AndroidFile::position() const
{
check_valid();
return m_file.position();
}
//-----------------------------------------------------------------------------
bool AndroidFile::can_read() const
{
check_valid();
return true;
}
//-----------------------------------------------------------------------------
bool AndroidFile::can_write() const
{
check_valid();
return true;
}
//-----------------------------------------------------------------------------
bool AndroidFile::can_seek() const
{
check_valid();
return true;
}
} // namespace crown
|
clean code
|
clean code
|
C++
|
mit
|
mikymod/crown,dbartolini/crown,mikymod/crown,mikymod/crown,taylor001/crown,galek/crown,taylor001/crown,taylor001/crown,taylor001/crown,galek/crown,galek/crown,dbartolini/crown,galek/crown,dbartolini/crown,dbartolini/crown,mikymod/crown
|
e20a29f3c6f96d2c9f5ac4a9c4959e8fe83df96b
|
src/JpegEnc/block.cpp
|
src/JpegEnc/block.cpp
|
#include "stdafx.h"
#include "block.h"
#include <cmath>
/**
Calculates the number of 8x8 blocks per row and number of rows from image dimensions.
@param[in] Width Width of the image.
@param[in] Height Height of the image.
@param[out] BlocksPerRow Number of blocks per row.
@param[out] RowCount Number of rows.
*/
static void CalculateBlockCount(int Width, int Height, int* BlocksPerRow, int* RowCount)
{
*BlocksPerRow = Width / 8;
if (Width % 8 != 0) {
(*BlocksPerRow)++;
}
*RowCount = Height / 8;
if (Height % 8 != 0) {
(*RowCount)++;
}
}
/**
Repeats edge pixels of the block to fill the whole 8-pixel rows/columns.
@param[in] BlockWidth The width of the existing image data in the block.
@param[in] BlockHeight The height of the existing image data in the block.
@param[in,out] Result The block to complete.
*/
static void RepeatEdgePixels(int BlockWidth, int BlockHeight, Uint8Block* Result)
{
Uint8Block& block = *Result;
if (BlockWidth < 8) {
for (int y = 0; y < BlockHeight; y++) {
std::uint8_t edgePixel = block[y * 8 + BlockWidth - 1];
for (int x = BlockWidth; x < 8; x++) {
block[y * 8 + x] = edgePixel;
}
}
}
if (BlockHeight < 8) {
for (int x = 0; x < BlockWidth; x++) {
std::uint8_t edgePixel = block[(BlockHeight - 1) * 8 + x];
for (int y = BlockHeight; y < 8; y++) {
block[y * 8 + x] = edgePixel;
}
}
}
}
/**
Extracts a single 8x8 block from the pixel data, repeating edge pixels if necessary.
If BlockWidth or BlockHeight is less than 8, edge pixels will be repeated.
@param[in] Pixels The image data to extract the block from.
@param[in] Stride Number of bytes to advance in the buffer until the next row of pixels.
@param[in] NumRows Number of rows in the image.
@param[in] BlockWidth Width of the data to be copied into the destination block.
@param[in] BlockHeight Height of the data to be copied into the destination block.
@param[out] Result The 8x8 block extracted from the image data.
*/
static void ExtractBlock(const std::uint8_t* Pixels, int Stride, int NumRows,
int BlockWidth, int BlockHeight, Uint8Block* Result)
{
Uint8Block& block = *Result;
for (int y = 0; y < BlockHeight; y++) {
for (int x = 0; x < BlockWidth; x++) {
block[y * 8 + x] = Pixels[x];
}
Pixels += Stride;
}
if (BlockWidth < 8 || BlockHeight < 8) {
RepeatEdgePixels(BlockWidth, BlockHeight, Result);
}
}
namespace Util
{
void SplitBlocks(const std::vector<uint8_t>& Pixels, int Width, int Height, std::vector<Uint8Block>* Result)
{
assert(Width > 0 && Height > 0);
int blocksPerRow, rowCount;
CalculateBlockCount(Width, Height, &blocksPerRow, &rowCount);
Result->resize(blocksPerRow * rowCount);
for (int y = 0; y < rowCount; y++) {
for (int x = 0; x < blocksPerRow; x++) {
int blockIndex = y * blocksPerRow + x;
int blockWidth = std::min(8, Width - x * 8);
int blockHeight = std::min(8, Height - y * 8);
Uint8Block* block = &Result->at(blockIndex);
const std::uint8_t* buffer = Pixels.data() + (y * 8 * Height + x * 8);
ExtractBlock(buffer, Width, rowCount, blockWidth, blockHeight, block);
}
}
}
}
static const int ZigzagIndices[] =
{
0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63,
};
namespace Jpeg
{
void ReorderBlock(const Int16Block& Block, Int16Block* Result)
{
Int16Block& result = *Result;
for (int i = 0; i < 64; i++) {
int index = ZigzagIndices[i];
result[i] = Block[index];
}
}
}
|
#include "stdafx.h"
#include "block.h"
#include <cmath>
/**
Calculates the number of 8x8 blocks per row and number of rows from image dimensions.
@param[in] Width Width of the image.
@param[in] Height Height of the image.
@param[out] BlocksPerRow Number of blocks per row.
@param[out] RowCount Number of rows.
*/
static void CalculateBlockCount(int Width, int Height, int* BlocksPerRow, int* RowCount)
{
*BlocksPerRow = Width / 8;
if (Width % 8 != 0) {
(*BlocksPerRow)++;
}
*RowCount = Height / 8;
if (Height % 8 != 0) {
(*RowCount)++;
}
}
/**
Repeats edge pixels of the block to fill the whole 8-pixel rows/columns.
@param[in] BlockWidth The width of the existing image data in the block.
@param[in] BlockHeight The height of the existing image data in the block.
@param[in,out] Result The block to complete.
*/
static void RepeatEdgePixels(int BlockWidth, int BlockHeight, Uint8Block* Result)
{
Uint8Block& block = *Result;
if (BlockWidth < 8) {
for (int y = 0; y < BlockHeight; y++) {
std::uint8_t edgePixel = block[y * 8 + BlockWidth - 1];
for (int x = BlockWidth; x < 8; x++) {
block[y * 8 + x] = edgePixel;
}
}
}
if (BlockHeight < 8) {
for (int x = 0; x < BlockWidth; x++) {
std::uint8_t edgePixel = block[(BlockHeight - 1) * 8 + x];
for (int y = BlockHeight; y < 8; y++) {
block[y * 8 + x] = edgePixel;
}
}
}
}
/**
Extracts a single 8x8 block from the pixel data, repeating edge pixels if necessary.
If BlockWidth or BlockHeight is less than 8, edge pixels will be repeated.
@param[in] Pixels The image data to extract the block from.
@param[in] Stride Number of bytes to advance in the buffer until the next row of pixels.
@param[in] NumRows Number of rows in the image.
@param[in] BlockWidth Width of the data to be copied into the destination block.
@param[in] BlockHeight Height of the data to be copied into the destination block.
@param[out] Result The 8x8 block extracted from the image data.
*/
static void ExtractBlock(const std::uint8_t* Pixels, int Stride, int NumRows,
int BlockWidth, int BlockHeight, Uint8Block* Result)
{
Uint8Block& block = *Result;
for (int y = 0; y < BlockHeight; y++) {
for (int x = 0; x < BlockWidth; x++) {
block[y * 8 + x] = Pixels[x];
}
Pixels += Stride;
}
if (BlockWidth < 8 || BlockHeight < 8) {
RepeatEdgePixels(BlockWidth, BlockHeight, Result);
}
}
namespace Util
{
void SplitBlocks(const std::vector<uint8_t>& Pixels, int Width, int Height, std::vector<Uint8Block>* Result)
{
assert(Width > 0 && Height > 0);
int blocksPerRow, rowCount;
CalculateBlockCount(Width, Height, &blocksPerRow, &rowCount);
Result->resize(blocksPerRow * rowCount);
for (int y = 0; y < rowCount; y++) {
for (int x = 0; x < blocksPerRow; x++) {
int blockIndex = y * blocksPerRow + x;
int blockWidth = std::min(8, Width - x * 8);
int blockHeight = std::min(8, Height - y * 8);
Uint8Block* block = &Result->at(blockIndex);
const std::uint8_t* buffer = Pixels.data() + (y * 8 * Width + x * 8);
ExtractBlock(buffer, Width, rowCount, blockWidth, blockHeight, block);
}
}
}
}
static const int ZigzagIndices[] =
{
0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63,
};
namespace Jpeg
{
void ReorderBlock(const Int16Block& Block, Int16Block* Result)
{
Int16Block& result = *Result;
for (int i = 0; i < 64; i++) {
int index = ZigzagIndices[i];
result[index] = Block[i];
}
}
}
|
Fix block reordering and extraction.
|
Fix block reordering and extraction.
|
C++
|
bsd-3-clause
|
dwarfcrank/yolo-dangerzone,dwarfcrank/yolo-dangerzone
|
3a187b135b6bb492699e75da85f3fe0cfd0dea65
|
fortune_weighted_points/__tests__/algorithm/test_helper/test_output_generator.cpp
|
fortune_weighted_points/__tests__/algorithm/test_helper/test_output_generator.cpp
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
using namespace std;
#include <algorithm>
#include <iostream>
#include <vector>
#include <set>
#include "fortune_weighted_points/algorithm/fortune.h"
#include "fortune_weighted_points/diagram/wsite.h"
#include "fortune_weighted_points/diagram/edge.h"
#include "fortune_weighted_points/diagram/vertice.h"
double W;
vector<WSite> sites;
void read_sites(){
W = 0;
double x,y,wi;
while(scanf("%lf %lf %lf",&x,&y,&wi) != EOF){
W = std::max(W,wi);
sites.push_back(WSite(sites.size(),x,y,wi));
}
}
vector<Edge> edges;
vector<Vertice> vertices;
int main(void){
read_sites();
fortune(sites,W,edges,vertices);
printf("Number of edges: %d\n",(int)edges.size());
for(vector<Edge>::iterator it = edges.begin(); it != edges.end(); it++){
printf("ID: %d\n",it->id);
printf("Sites: %d %d\n",it->p.get_id(),it->q.get_id());
Hyperbole h = it->hyperbole;
printf("Bisector: %lfx^2 + %lfxy + %lfy^2 + %lfx + %lfy + %lf = 0\n\n",
h.A,h.B,h.C,h.D,h.E,h.F);
}
int cnt = 0;
printf("Number of vertices: %d\n",(int)vertices.size());
for(vector<Vertice>::iterator it = vertices.begin(); it != vertices.end(); it++){
printf("V%d = (%lf, %lf)\n",cnt,it->x,it->y);
cnt++;
printf("Incident edges: %d %d %d\n",it->edges[0],it->edges[1],it->edges[2]);
}
return 0;
}
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
using namespace std;
#include <algorithm>
#include <iostream>
#include <vector>
#include <set>
#include "fortune_weighted_points/algorithm/fortune.h"
#include "fortune_weighted_points/diagram/wsite.h"
#include "fortune_weighted_points/diagram/edge.h"
#include "fortune_weighted_points/diagram/vertice.h"
double W;
vector<WSite> sites;
void read_sites(){
W = 0;
double x,y,wi;
int n;
scanf("%d",&n);
while(n--){
scanf("%lf %lf %lf",&x,&y,&wi);
W = std::max(W,wi);
sites.push_back(WSite(sites.size(),x,y,wi));
}
}
vector<Edge> edges;
vector<Vertice> vertices;
int main(void){
read_sites();
fortune(sites,W,edges,vertices);
printf("Number of edges: %d\n",(int)edges.size());
for(vector<Edge>::iterator it = edges.begin(); it != edges.end(); it++){
printf("ID: %d\n",it->id);
printf("Sites: %d %d\n",it->p.get_id(),it->q.get_id());
Hyperbole h = it->hyperbole;
printf("Bisector: %lfx^2 + %lfxy + %lfy^2 + %lfx + %lfy + %lf = 0\n\n",
h.A,h.B,h.C,h.D,h.E,h.F);
}
int cnt = 0;
printf("Number of vertices: %d\n",(int)vertices.size());
for(vector<Vertice>::iterator it = vertices.begin(); it != vertices.end(); it++){
printf("V%d = (%lf, %lf)\n",cnt,it->x,it->y);
cnt++;
printf("Incident edges: %d %d %d\n",it->edges[0],it->edges[1],it->edges[2]);
}
return 0;
}
|
Read n sites
|
Read n sites
|
C++
|
mit
|
matheusdallrosa/voronoi-diagram-construction,matheusdallrosa/voronoi-diagram-construction
|
4e850fbbd9ba7667ddeed1fcec061230cd70e541
|
src/core_read.cpp
|
src/core_read.cpp
|
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "core_io.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "serialize.h"
#include "streams.h"
#include <univalue.h>
#include "util.h"
#include "utilstrencodings.h"
#include "version.h"
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/assign/list_of.hpp>
CScript ParseScript(const std::string& s)
{
CScript result;
static map<std::string, opcodetype> mapOpNames;
if (mapOpNames.empty())
{
for (int op = 0; op <= OP_NOP10; op++)
{
// Allow OP_RESERVED to get into mapOpNames
if (op < OP_NOP && op != OP_RESERVED)
continue;
const char* name = GetOpName((opcodetype)op);
if (strcmp(name, "OP_UNKNOWN") == 0)
continue;
std::string strName(name);
mapOpNames[strName] = (opcodetype)op;
// Convenience: OP_ADD and just ADD are both recognized:
boost::algorithm::replace_first(strName, "OP_", "");
mapOpNames[strName] = (opcodetype)op;
}
}
vector<std::string> words;
boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);
for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
{
if (w->empty())
{
// Empty string, ignore. (boost::split given '' will return one word)
}
else if (all(*w, boost::algorithm::is_digit()) ||
(boost::algorithm::starts_with(*w, "-") && all(string(w->begin()+1, w->end()), boost::algorithm::is_digit())))
{
// Number
int64_t n = atoi64(*w);
result << n;
}
else if (boost::algorithm::starts_with(*w, "0x") && (w->begin()+2 != w->end()) && IsHex(string(w->begin()+2, w->end())))
{
// Raw hex data, inserted NOT pushed onto stack:
std::vector<unsigned char> raw = ParseHex(string(w->begin()+2, w->end()));
result.insert(result.end(), raw.begin(), raw.end());
}
else if (w->size() >= 2 && boost::algorithm::starts_with(*w, "'") && boost::algorithm::ends_with(*w, "'"))
{
// Single-quoted string, pushed as data. NOTE: this is poor-man's
// parsing, spaces/tabs/newlines in single-quoted strings won't work.
std::vector<unsigned char> value(w->begin()+1, w->end()-1);
result << value;
}
else if (mapOpNames.count(*w))
{
// opcode, e.g. OP_ADD or ADD:
result << mapOpNames[*w];
}
else
{
throw runtime_error("script parse error");
}
}
return result;
}
bool DecodeHexTx(CTransaction& tx, const std::string& strHexTx)
{
if (!IsHex(strHexTx))
return false;
vector<unsigned char> txData(ParseHex(strHexTx));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> tx;
}
catch (const std::exception&) {
return false;
}
return true;
}
bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
{
if (!IsHex(strHexBlk))
return false;
std::vector<unsigned char> blockData(ParseHex(strHexBlk));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssBlock >> block;
}
catch (const std::exception&) {
return false;
}
return true;
}
uint256 ParseHashUV(const UniValue& v, const std::string& strName)
{
std::string strHex;
if (v.isStr())
strHex = v.getValStr();
return ParseHashStr(strHex, strName); // Note: ParseHashStr("") throws a runtime_error
}
uint256 ParseHashStr(const std::string& strHex, const std::string& strName)
{
if (!IsHex(strHex)) // Note: IsHex("") is false
throw runtime_error(strName+" must be hexadecimal string (not '"+strHex+"')");
uint256 result;
result.SetHex(strHex);
return result;
}
vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
{
std::string strHex;
if (v.isStr())
strHex = v.getValStr();
if (!IsHex(strHex))
throw runtime_error(strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
|
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "core_io.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "serialize.h"
#include "streams.h"
#include <univalue.h>
#include "util.h"
#include "utilstrencodings.h"
#include "version.h"
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/assign/list_of.hpp>
CScript ParseScript(const std::string& s)
{
CScript result;
static map<std::string, opcodetype> mapOpNames;
if (mapOpNames.empty())
{
for (int op = 0; op <= OP_NOP10; op++)
{
// Allow OP_RESERVED to get into mapOpNames
if (op < OP_NOP && op != OP_RESERVED)
continue;
const char* name = GetOpName((opcodetype)op);
if (strcmp(name, "OP_UNKNOWN") == 0)
continue;
std::string strName(name);
mapOpNames[strName] = (opcodetype)op;
// Convenience: OP_ADD and just ADD are both recognized:
boost::algorithm::replace_first(strName, "OP_", "");
mapOpNames[strName] = (opcodetype)op;
}
}
std::vector<std::string> words;
boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);
for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
{
if (w->empty())
{
// Empty string, ignore. (boost::split given '' will return one word)
}
else if (all(*w, boost::algorithm::is_digit()) ||
(boost::algorithm::starts_with(*w, "-") && all(string(w->begin()+1, w->end()), boost::algorithm::is_digit())))
{
// Number
int64_t n = atoi64(*w);
result << n;
}
else if (boost::algorithm::starts_with(*w, "0x") && (w->begin()+2 != w->end()) && IsHex(string(w->begin()+2, w->end())))
{
// Raw hex data, inserted NOT pushed onto stack:
std::vector<unsigned char> raw = ParseHex(string(w->begin()+2, w->end()));
result.insert(result.end(), raw.begin(), raw.end());
}
else if (w->size() >= 2 && boost::algorithm::starts_with(*w, "'") && boost::algorithm::ends_with(*w, "'"))
{
// Single-quoted string, pushed as data. NOTE: this is poor-man's
// parsing, spaces/tabs/newlines in single-quoted strings won't work.
std::vector<unsigned char> value(w->begin()+1, w->end()-1);
result << value;
}
else if (mapOpNames.count(*w))
{
// opcode, e.g. OP_ADD or ADD:
result << mapOpNames[*w];
}
else
{
throw runtime_error("script parse error");
}
}
return result;
}
bool DecodeHexTx(CTransaction& tx, const std::string& strHexTx)
{
if (!IsHex(strHexTx))
return false;
std::vector<unsigned char> txData(ParseHex(strHexTx));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> tx;
}
catch (const std::exception&) {
return false;
}
return true;
}
bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
{
if (!IsHex(strHexBlk))
return false;
std::vector<unsigned char> blockData(ParseHex(strHexBlk));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssBlock >> block;
}
catch (const std::exception&) {
return false;
}
return true;
}
uint256 ParseHashUV(const UniValue& v, const std::string& strName)
{
std::string strHex;
if (v.isStr())
strHex = v.getValStr();
return ParseHashStr(strHex, strName); // Note: ParseHashStr("") throws a runtime_error
}
uint256 ParseHashStr(const std::string& strHex, const std::string& strName)
{
if (!IsHex(strHex)) // Note: IsHex("") is false
throw runtime_error(strName+" must be hexadecimal string (not '"+strHex+"')");
uint256 result;
result.SetHex(strHex);
return result;
}
std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
{
std::string strHex;
if (v.isStr())
strHex = v.getValStr();
if (!IsHex(strHex))
throw runtime_error(strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
|
update all vectore to std::vector in core_read.cpp
|
update all vectore to std::vector in core_read.cpp
|
C++
|
mit
|
bitcoinclassic/bitcoinclassic,zander/bitcoinclassic,bitcoinclassic/bitcoinclassic,zander/bitcoinclassic,bitcoinclassic/bitcoinclassic,zander/bitcoinclassic,bitcoinclassic/bitcoinclassic,zander/bitcoinclassic,zander/bitcoinclassic,bitcoinclassic/bitcoinclassic,zander/bitcoinclassic,bitcoinclassic/bitcoinclassic
|
53c6368dc223aed72e57f3aefdc7ad2ea1561403
|
You-DataStore/datastore.cpp
|
You-DataStore/datastore.cpp
|
#include "stdafx.h"
#include "internal/internal_datastore.h"
#include "internal/operations/post_operation.h"
#include "internal/operations/put_operation.h"
#include "internal/operations/erase_operation.h"
#include "datastore.h"
namespace You {
namespace DataStore {
DataStore& DataStore::get() {
static DataStore ds;
return ds;
}
Transaction& DataStore::begin() {
while (this->isServing) { }
isServing = true;
transactionStack.push(std::shared_ptr<Transaction>(new Transaction()));
return *(transactionStack.top());
}
void DataStore::post(TaskId taskId, const SerializedTask& task) {
std::shared_ptr<Internal::IOperation> operation =
std::make_shared<Internal::PostOperation>(taskId, task);
transactionStack.top()->push(operation);
}
void DataStore::put(TaskId taskId, const SerializedTask& task) {
std::shared_ptr<Internal::IOperation> operation =
std::make_shared<Internal::PutOperation>(taskId, task);
transactionStack.top()->push(operation);
}
void DataStore::erase(TaskId taskId) {
std::shared_ptr<Internal::IOperation> operation =
std::make_shared<Internal::EraseOperation>(taskId);
transactionStack.top()->push(operation);
}
std::vector<SerializedTask> DataStore::getAllTask() {
return internalDataStore.getAllTask();
}
void DataStore::notify() {
isServing = false;
}
} // namespace DataStore
} // namespace You
|
#include "stdafx.h"
#include "internal/internal_datastore.h"
#include "internal/operations/post_operation.h"
#include "internal/operations/put_operation.h"
#include "internal/operations/erase_operation.h"
#include "datastore.h"
namespace You {
namespace DataStore {
DataStore& DataStore::get() {
static DataStore ds;
return ds;
}
Transaction& DataStore::begin() {
while (this->isServing) { } // for thread-safety
isServing = true;
internalDataStore.loadData();
transactionStack.push(std::shared_ptr<Transaction>(new Transaction()));
return *(transactionStack.top());
}
void DataStore::post(TaskId taskId, const SerializedTask& task) {
std::shared_ptr<Internal::IOperation> operation =
std::make_shared<Internal::PostOperation>(taskId, task);
transactionStack.top()->push(operation);
}
void DataStore::put(TaskId taskId, const SerializedTask& task) {
std::shared_ptr<Internal::IOperation> operation =
std::make_shared<Internal::PutOperation>(taskId, task);
transactionStack.top()->push(operation);
}
void DataStore::erase(TaskId taskId) {
std::shared_ptr<Internal::IOperation> operation =
std::make_shared<Internal::EraseOperation>(taskId);
transactionStack.top()->push(operation);
}
std::vector<SerializedTask> DataStore::getAllTask() {
return internalDataStore.getAllTask();
}
void DataStore::notify() {
bool isSaved = internalDataStore.saveData();
if (isSaved) {
isServing = false;
}
// TODO(digawp): else throw exception?
}
} // namespace DataStore
} // namespace You
|
Load data during begin(), save data during notify()
|
Load data during begin(), save data during notify()
|
C++
|
mit
|
cs2103aug2014-w10-1c/main,cs2103aug2014-w10-1c/main
|
d59836a785f459d342b03b1add4d4d0b2f99e296
|
src/core/histogram.cc
|
src/core/histogram.cc
|
// Copyright (c) 2016 Alexander Gallego. All rights reserved.
//
#include "smf/histogram.h"
#include <cstdlib>
#include <hdr_histogram.h>
#include <hdr_histogram_log.h>
#include <iostream>
namespace smf {
seastar::lw_shared_ptr<histogram>
histogram::make_lw_shared(int64_t max_value) {
auto x = seastar::make_lw_shared<histogram>(max_value);
assert(x->hist_->hist);
return x;
}
std::unique_ptr<histogram>
histogram::make_unique(int64_t max_value) {
std::unique_ptr<histogram> p(new histogram(max_value));
assert(p->hist_->hist);
return p;
}
histogram::histogram(int64_t max_value)
: hist_(std::make_unique<hist_t>(max_value)) {}
histogram::histogram(histogram &&o) noexcept : hist_(std::move(o.hist_)) {}
histogram &
histogram::operator+=(const histogram &o) {
::hdr_add(hist_->hist, o.hist_->hist);
return *this;
}
histogram &
histogram::operator+=(const hist_t *o) {
::hdr_add(hist_->hist, o->hist);
return *this;
}
histogram &
histogram::operator=(histogram &&o) noexcept {
hist_ = std::move(o.hist_);
return *this;
}
void
histogram::record(const uint64_t &v) {
hist_->sample_count++;
hist_->sample_sum += v;
::hdr_record_value(hist_->hist, v);
}
void
histogram::record_multiple_times(const uint64_t &v, const uint32_t ×) {
hist_->sample_count += times;
hist_->sample_sum += v * times;
::hdr_record_values(hist_->hist, v, times);
}
void
histogram::record_corrected(const uint64_t &v, const uint64_t &interval) {
// TODO: how should summation work for coordinated omission values? the sum is
// tracked outside hdr, currently.
hist_->sample_count++;
hist_->sample_sum += v;
::hdr_record_corrected_value(hist_->hist, v, interval);
}
int64_t
histogram::value_at(double percentile) const {
return ::hdr_value_at_percentile(hist_->hist, percentile);
}
double
histogram::stddev() const {
return ::hdr_stddev(hist_->hist);
}
double
histogram::mean() const {
return ::hdr_mean(hist_->hist);
}
size_t
histogram::memory_size() const {
return ::hdr_get_memory_size(hist_->hist);
}
hdr_histogram *
histogram::get() {
assert(hist_);
return hist_->hist;
}
std::unique_ptr<histogram_measure>
histogram::auto_measure() {
return std::make_unique<histogram_measure>(shared_from_this());
}
int
histogram::print(FILE *fp) const {
assert(fp != nullptr);
return ::hdr_percentiles_print(hist_->hist,
fp, // File to write to
5, // Granularity of printed values
1.0, // Multiplier for results
CLASSIC); // Format CLASSIC/CSV supported.
}
seastar::metrics::histogram
histogram::get_seastar_metrics_histogram() const {
// logarithmic histogram configuration. this will range from 10 microseconds
// through around 6000 seconds with 26 buckets doubling.
//
// TODO:
// 1) expose these settings through arguments
// 2) upstream log_base fix for sub-2.0 values. in hdr the log_base is a
// double but is truncated (see the int64_t casts on log_base below which is
// the same as in the hdr C library). this means that if we want buckets
// with a log base of 1.5, the histogram becomes linear...
const size_t num_buckets = 26;
const int64_t first_value = 10;
const double log_base = 2.0;
seastar::metrics::histogram sshist;
sshist.buckets.resize(num_buckets);
sshist.sample_count = hist_->sample_count;
sshist.sample_sum = static_cast<double>(hist_->sample_sum);
// stack allocated; no cleanup needed
struct hdr_iter iter;
struct hdr_iter_log *log = &iter.specifics.log;
hdr_iter_log_init(&iter, hist_->hist, first_value, log_base);
// fill in buckets from hdr histogram logarithmic iteration. there may be more
// or less hdr buckets reported than what will be returned to seastar.
size_t bucket_idx = 0;
while (hdr_iter_next(&iter) && bucket_idx < sshist.buckets.size()) {
auto &bucket = sshist.buckets[bucket_idx];
bucket.count = iter.cumulative_count;
bucket.upper_bound = iter.value_iterated_to;
bucket_idx++;
}
if (bucket_idx == 0) {
// if the histogram is empty hdr_iter_init doesn't initialize the first
// bucket value which is neede by the loop below.
iter.value_iterated_to = first_value;
} else if (bucket_idx < sshist.buckets.size()) {
// if there are padding buckets that need to be created, advance the bucket
// boundary which would normally be done by hdr_iter_next, except that
// doesn't happen when iteration reaches the end of the recorded values.
iter.value_iterated_to *= static_cast<int64_t>(log->log_base);
}
// prometheus expects a fixed number of buckets. hdr iteration will stop after
// the max observed value. this loops pads buckets past iteration, if needed.
for (; bucket_idx < sshist.buckets.size(); bucket_idx++) {
auto &bucket = sshist.buckets[bucket_idx];
bucket.count = iter.cumulative_count;
bucket.upper_bound = iter.value_iterated_to;
iter.value_iterated_to *= static_cast<int64_t>(log->log_base);
}
return sshist;
}
histogram::~histogram() {}
} // namespace smf
|
// Copyright (c) 2016 Alexander Gallego. All rights reserved.
//
#include "smf/histogram.h"
#include <cstdlib>
#include <hdr_histogram.h>
#include <hdr_histogram_log.h>
#include <iostream>
namespace smf {
seastar::lw_shared_ptr<histogram>
histogram::make_lw_shared(int64_t max_value) {
auto x = seastar::make_lw_shared<histogram>(max_value);
assert(x->hist_->hist);
return x;
}
std::unique_ptr<histogram>
histogram::make_unique(int64_t max_value) {
std::unique_ptr<histogram> p(new histogram(max_value));
assert(p->hist_->hist);
return p;
}
histogram::histogram(int64_t max_value)
: hist_(std::make_unique<hist_t>(max_value)) {}
histogram::histogram(histogram &&o) noexcept : hist_(std::move(o.hist_)) {}
histogram &
histogram::operator+=(const histogram &o) {
::hdr_add(hist_->hist, o.hist_->hist);
return *this;
}
histogram &
histogram::operator+=(const hist_t *o) {
::hdr_add(hist_->hist, o->hist);
return *this;
}
histogram &
histogram::operator=(histogram &&o) noexcept {
hist_ = std::move(o.hist_);
return *this;
}
void
histogram::record(const uint64_t &v) {
hist_->sample_count++;
hist_->sample_sum += v;
::hdr_record_value(hist_->hist, v);
}
void
histogram::record_multiple_times(const uint64_t &v, const uint32_t ×) {
hist_->sample_count += times;
hist_->sample_sum += v * times;
::hdr_record_values(hist_->hist, v, times);
}
void
histogram::record_corrected(const uint64_t &v, const uint64_t &interval) {
// TODO: how should summation work for coordinated omission values? the sum is
// tracked outside hdr, currently.
hist_->sample_count++;
hist_->sample_sum += v;
::hdr_record_corrected_value(hist_->hist, v, interval);
}
int64_t
histogram::value_at(double percentile) const {
return ::hdr_value_at_percentile(hist_->hist, percentile);
}
double
histogram::stddev() const {
return ::hdr_stddev(hist_->hist);
}
double
histogram::mean() const {
return ::hdr_mean(hist_->hist);
}
size_t
histogram::memory_size() const {
return ::hdr_get_memory_size(hist_->hist);
}
hdr_histogram *
histogram::get() {
assert(hist_);
return hist_->hist;
}
std::unique_ptr<histogram_measure>
histogram::auto_measure() {
return std::make_unique<histogram_measure>(shared_from_this());
}
int
histogram::print(FILE *fp) const {
assert(fp != nullptr);
return ::hdr_percentiles_print(hist_->hist,
fp, // File to write to
5, // Granularity of printed values
1.0, // Multiplier for results
CLASSIC); // Format CLASSIC/CSV supported.
}
seastar::metrics::histogram
histogram::get_seastar_metrics_histogram() const {
// logarithmic histogram configuration. this will range from 10 microseconds
// through around 6000 seconds with 26 buckets doubling.
//
// TODO:
// 1) expose these settings through arguments
// 2) upstream log_base fix for sub-2.0 values. in hdr the log_base is a
// double but is truncated (see the int64_t casts on log_base below which is
// the same as in the hdr C library). this means that if we want buckets
// with a log base of 1.5, the histogram becomes linear...
constexpr size_t num_buckets = 26;
constexpr int64_t first_value = 10;
constexpr double log_base = 2.0;
seastar::metrics::histogram sshist;
sshist.buckets.resize(num_buckets);
sshist.sample_count = hist_->sample_count;
sshist.sample_sum = static_cast<double>(hist_->sample_sum);
// stack allocated; no cleanup needed
struct hdr_iter iter;
struct hdr_iter_log *log = &iter.specifics.log;
hdr_iter_log_init(&iter, hist_->hist, first_value, log_base);
// fill in buckets from hdr histogram logarithmic iteration. there may be more
// or less hdr buckets reported than what will be returned to seastar.
size_t bucket_idx = 0;
while (hdr_iter_next(&iter) && bucket_idx < sshist.buckets.size()) {
auto &bucket = sshist.buckets[bucket_idx];
bucket.count = iter.cumulative_count;
bucket.upper_bound = iter.value_iterated_to;
bucket_idx++;
}
if (bucket_idx == 0) {
// if the histogram is empty hdr_iter_init doesn't initialize the first
// bucket value which is neede by the loop below.
iter.value_iterated_to = first_value;
} else if (bucket_idx < sshist.buckets.size()) {
// if there are padding buckets that need to be created, advance the bucket
// boundary which would normally be done by hdr_iter_next, except that
// doesn't happen when iteration reaches the end of the recorded values.
iter.value_iterated_to *= static_cast<int64_t>(log->log_base);
}
// prometheus expects a fixed number of buckets. hdr iteration will stop after
// the max observed value. this loops pads buckets past iteration, if needed.
for (; bucket_idx < sshist.buckets.size(); bucket_idx++) {
auto &bucket = sshist.buckets[bucket_idx];
bucket.count = iter.cumulative_count;
bucket.upper_bound = iter.value_iterated_to;
iter.value_iterated_to *= static_cast<int64_t>(log->log_base);
}
return sshist;
}
histogram::~histogram() {}
} // namespace smf
|
use constexpr
|
histogram: use constexpr
Signed-off-by: Noah Watkins <[email protected]>
|
C++
|
agpl-3.0
|
senior7515/smurf,senior7515/smurf,senior7515/smurf
|
7599edffa9a2b3d4fc92b34cb88715a02fb19cf4
|
src/idvaluemap.hh
|
src/idvaluemap.hh
|
#ifndef idvaluemap_hh_INCLUDED
#define idvaluemap_hh_INCLUDED
namespace Kakoune
{
template<typename _Id, typename _Value>
class idvaluemap
{
public:
typedef std::pair<_Id, _Value> value_type;
typedef std::vector<value_type> container_type;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
void append(const value_type& value)
{
m_content.push_back(value);
}
void append(value_type&& value)
{
m_content.push_back(std::forward<value_type>(value));
}
iterator find(const _Id& id)
{
for (auto it = begin(); it != end(); ++it)
{
if (it->first == id)
return it;
}
return end();
}
const_iterator find(const _Id& id) const
{
for (auto it = begin(); it != end(); ++it)
{
if (it->first == id)
return it;
}
return end();
}
bool contains(const _Id& id) const
{
return find(id) != end();
}
void remove(const _Id& id)
{
for (auto it = m_content.begin(); it != m_content.end(); ++it)
{
if (it->first == id)
{
m_content.erase(it);
return;
}
}
}
template<std::string (*id_to_string)(const _Id&)>
CandidateList complete_id(const std::string& prefix,
size_t cursor_pos)
{
std::string real_prefix = prefix.substr(0, cursor_pos);
CandidateList result;
for (auto& value : m_content)
{
std::string id_str = id_to_string(value.first);
if (id_str.substr(0, real_prefix.length()) == real_prefix)
result.push_back(std::move(id_str));
}
return result;
}
iterator begin() { return m_content.begin(); }
iterator end() { return m_content.end(); }
const_iterator begin() const { return m_content.begin(); }
const_iterator end() const { return m_content.end(); }
private:
container_type m_content;
};
}
#endif // idvaluemap_hh_INCLUDED
|
#ifndef idvaluemap_hh_INCLUDED
#define idvaluemap_hh_INCLUDED
#include <vector>
#include "completion.hh"
namespace Kakoune
{
template<typename _Id, typename _Value>
class idvaluemap
{
public:
typedef std::pair<_Id, _Value> value_type;
typedef std::vector<value_type> container_type;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
void append(const value_type& value)
{
m_content.push_back(value);
}
void append(value_type&& value)
{
m_content.push_back(std::forward<value_type>(value));
}
iterator find(const _Id& id)
{
for (auto it = begin(); it != end(); ++it)
{
if (it->first == id)
return it;
}
return end();
}
const_iterator find(const _Id& id) const
{
for (auto it = begin(); it != end(); ++it)
{
if (it->first == id)
return it;
}
return end();
}
bool contains(const _Id& id) const
{
return find(id) != end();
}
void remove(const _Id& id)
{
for (auto it = m_content.begin(); it != m_content.end(); ++it)
{
if (it->first == id)
{
m_content.erase(it);
return;
}
}
}
template<std::string (*id_to_string)(const _Id&)>
CandidateList complete_id(const std::string& prefix,
size_t cursor_pos)
{
std::string real_prefix = prefix.substr(0, cursor_pos);
CandidateList result;
for (auto& value : m_content)
{
std::string id_str = id_to_string(value.first);
if (id_str.substr(0, real_prefix.length()) == real_prefix)
result.push_back(std::move(id_str));
}
return result;
}
iterator begin() { return m_content.begin(); }
iterator end() { return m_content.end(); }
const_iterator begin() const { return m_content.begin(); }
const_iterator end() const { return m_content.end(); }
private:
container_type m_content;
};
}
#endif // idvaluemap_hh_INCLUDED
|
add missing includes
|
idvaluemap: add missing includes
|
C++
|
unlicense
|
flavius/kakoune,danielma/kakoune,jjthrash/kakoune,lenormf/kakoune,rstacruz/kakoune,Asenar/kakoune,occivink/kakoune,ekie/kakoune,danielma/kakoune,flavius/kakoune,jkonecny12/kakoune,alpha123/kakoune,Somasis/kakoune,casimir/kakoune,zakgreant/kakoune,jjthrash/kakoune,casimir/kakoune,alexherbo2/kakoune,lenormf/kakoune,Somasis/kakoune,xificurC/kakoune,xificurC/kakoune,danr/kakoune,danielma/kakoune,occivink/kakoune,mawww/kakoune,jkonecny12/kakoune,ekie/kakoune,alexherbo2/kakoune,jjthrash/kakoune,xificurC/kakoune,zakgreant/kakoune,casimir/kakoune,alexherbo2/kakoune,Asenar/kakoune,Somasis/kakoune,mawww/kakoune,danr/kakoune,danielma/kakoune,danr/kakoune,Asenar/kakoune,alpha123/kakoune,Asenar/kakoune,mawww/kakoune,alpha123/kakoune,jkonecny12/kakoune,Somasis/kakoune,xificurC/kakoune,mawww/kakoune,rstacruz/kakoune,danr/kakoune,ekie/kakoune,casimir/kakoune,occivink/kakoune,occivink/kakoune,flavius/kakoune,rstacruz/kakoune,zakgreant/kakoune,jjthrash/kakoune,zakgreant/kakoune,lenormf/kakoune,elegios/kakoune,jkonecny12/kakoune,ekie/kakoune,elegios/kakoune,elegios/kakoune,flavius/kakoune,rstacruz/kakoune,elegios/kakoune,alexherbo2/kakoune,lenormf/kakoune,alpha123/kakoune
|
67a6f9549e4cd56cd29277598b9b9eff6078e1e6
|
src/jobs_test.cpp
|
src/jobs_test.cpp
|
/**
* @author Andrew Stone <[email protected]>
* @copyright 2015 Andrew Stone
*
* This file is part of paratec and is released under the MIT License:
* http://opensource.org/licenses/MIT
*/
#include <atomic>
#include <iostream>
#include <sys/wait.h>
#include <thread>
#include "jobs.hpp"
#include "main.hpp"
#include "util.hpp"
#include "util_test.hpp"
namespace pt
{
TEST(_0)
{
printf("%s", pt_get_name());
}
TEST(_1)
{
printf("%s", pt_get_name());
}
TEST(_2)
{
printf("%s", pt_get_name());
}
TEST(_3)
{
printf("%s", pt_get_name());
}
TEST(jobsNoFork)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(std::cout, { "paratec", "--nofork" });
});
pt_in("Running: _0\n=========", e.stdout_);
}
TEST(jobsNoForkFiltered)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(std::cout, { "paratec", "--nofork", "-f", "_2" });
});
pt_in("Running: _2", e.stdout_);
pt_in("100%: of 1", e.stdout_);
}
TEST(_threadedAssertion)
{
std::thread th([]() { pt_fail("from another thread"); });
while (true) {
usleep(1000000);
}
}
TEST(jobsNoForkThreadedAssertion)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_threadedAssertion) });
m.run(std::cout, { "paratec", "--nofork" });
});
pt_in("Whoa there!", e.stdout_);
}
TEST(jobsFork)
{
std::stringstream out;
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(out, { "paratec" });
auto s = out.str();
pt_in("100%", s);
}
TEST(jobsForkFiltered)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(std::cout, { "paratec", "-f", "_2" });
});
pt_in("100%: of 1", e.stdout_);
}
TEST(jobsForkNoCapture)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(std::cout, { "paratec", "--nocapture" });
});
pt_in("_0", e.stdout_);
pt_in("_1", e.stdout_);
pt_in("_2", e.stdout_);
pt_in("_3", e.stdout_);
}
TEST(jobsVeryVerbose)
{
std::stringstream out;
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(out, { "paratec", "-vvvv" });
auto s = out.str();
pt_in("stdout\n", s);
pt_in("_0", s);
pt_in("_1", s);
pt_in("_2", s);
pt_in("_3", s);
}
TEST(_benchNever, PTBENCH())
{
pt_fail("this bench may never run");
}
TEST(jobsBenchNever)
{
std::stringstream out;
Main m({ MKTEST(_benchNever) });
m.run(out, { "paratec", "-vvvv" });
auto s = out.str();
pt_in("Ran 0 benches.", s);
pt_in("DISABLED : _benchNever", s);
}
TEST(_bench, PTBENCH())
{
pt_ne(_N, 0u);
}
TEST(jobsBenches)
{
std::stringstream out;
Main m({ MKTEST(_bench) });
m.run(out, { "paratec", "-b" });
auto s = out.str();
pt_in("Ran 1 benches.", s);
pt_in("BENCH : _bench", s);
pt_in("ns/op)", s);
}
TEST(jobsAbortSignal, PTSIG(SIGABRT))
{
abort();
}
TEST(_signalMismatch, PTSIG(5))
{
}
TEST(jobsSignal)
{
std::stringstream out;
Main m({ MKTEST(_signalMismatch) });
m.run(out, { "paratec" });
auto s = out.str();
pt_in("received signal", s);
}
TEST(_exitMismatch, PTEXIT(1))
{
}
TEST(jobsExit)
{
std::stringstream out;
Main m({ MKTEST(_exitMismatch) });
m.run(out, { "paratec" });
auto s = out.str();
pt_in("got exit code", s);
}
TEST(_timeout, PTTIME(.001))
{
std::this_thread::sleep_for(std::chrono::seconds(10));
}
TEST(jobsTimeout)
{
std::stringstream out;
Main m({ MKTEST(_timeout) });
m.run(out, { "paratec" });
auto s = out.str();
pt_in("TIME OUT : _timeout", s);
}
static SharedMem<std::atomic_bool> _sleeping;
TEST(_sleep)
{
signal(SIGINT, SIG_IGN);
signal(SIGTERM, SIG_IGN);
_sleeping->store(true);
std::this_thread::sleep_for(std::chrono::seconds(10));
}
TEST(jobsTerminateFromSignal)
{
Fork f;
int status;
bool parent = f.fork(false, true);
if (!parent) {
Main m({ MKTEST(_sleep) });
m.run(std::cout, { "paratec" });
exit(0);
}
// Wait until the test is firmly asleep before trying to kill.
pt_wait_for(_sleeping->load());
auto err = f.terminate(&status);
OSErr(err, {}, "failed to reap child");
pt_eq(f.pid(), err);
pt(WIFSIGNALED(status));
// There's a race condition here with the paratec child sometimes
// terminating its child with SIGKILL and exiting before this process
// sends SIGKILL.
pt(WTERMSIG(status) == SIGTERM || WTERMSIG(status) == SIGKILL);
}
TEST(_fail)
{
pt_fail("failure");
}
static void _fail(bool fork)
{
std::stringstream out;
std::vector<const char *> args({ "paratec", "-vvv" });
if (!fork) {
args.push_back("--nofork");
}
Main m({ MKTEST(_fail) });
m.run(out, args);
auto s = out.str();
pt_in("FAIL : _fail", s);
pt_in("0%: of 1", s);
pt_in("1 failures", s);
}
TEST(jobsForkFail)
{
_fail(true);
}
TEST(jobsNoForkFail)
{
_fail(false);
}
TEST(_error)
{
abort();
}
// This can only run in a forked env since it calls exit()
TEST(jobsError)
{
std::stringstream out;
Main m({ MKTEST(_error) });
m.run(out, { "paratec", "-vvv" });
auto s = out.str();
pt_in("ERROR : _error", s);
pt_in("0%: of 1", s);
pt_in("1 errors", s);
}
TEST(jobsDisabled)
{
std::stringstream out;
Main m({ MKTEST(_0) });
m.run(out, { "paratec", "-vvv", "-f=-_0" });
auto s = out.str();
pt_in("DISABLED : _0", s);
pt_in("100%: of 0", s);
}
TEST(_skip)
{
pt_skip();
}
static void _skip(bool fork)
{
std::stringstream out;
std::vector<const char *> args({ "paratec", "-vvv" });
if (!fork) {
args.push_back("--nofork");
}
Main m({ MKTEST(_0), MKTEST(_skip) });
m.run(out, args);
auto s = out.str();
pt_in("SKIP : _skip", s);
pt_in("100%: of 1", s);
pt_in("1 skipped", s);
}
TEST(jobsForkSkip)
{
_skip(true);
}
TEST(jobsNoForkSkip)
{
_skip(false);
}
TEST(_port)
{
auto p = pt_get_port(0);
pt_gt(p, (uint16_t)0);
pt_gt(pt_get_port(1), p);
}
static void _getPort(bool fork)
{
std::vector<const char *> args({ "paratec" });
if (!fork) {
args.push_back("--nofork");
}
Main m({ MKTEST(_port), MKTEST(_port), MKTEST(_port) });
auto res = m.run(std::cout, args);
pt_eq(res.exitCode(), 0);
}
TEST(jobsForkGetPort)
{
_getPort(true);
}
TEST(jobsNoForkGetPort)
{
_getPort(false);
}
TEST(jobsGetCppName)
{
pt_eq("jobsGetCppName", pt_get_name());
}
extern "C" {
TEST(jobsGetCName)
{
pt_eq("jobsGetCName", pt_get_name());
}
}
TEST(_iterName, PTI(-5, 5))
{
pt_set_iter_name("fun:%" PRId64, _i);
}
TEST(_notIterSetName)
{
pt_set_iter_name("what am i doing?");
}
static void _setIterName(bool fork)
{
std::stringstream out;
std::vector<const char *> args({ "paratec", "-vvv" });
if (!fork) {
args.push_back("--nofork");
}
Main m({ MKTEST(_iterName), MKTEST(_notIterSetName) });
m.run(out, args);
auto s = out.str();
pt_in("PASS : _iterName:-1:fun:-1", s);
pt_in("PASS : _iterName:0:fun:0", s);
pt_in("PASS : _iterName:4:fun:4", s);
pt_in("PASS : _notIterSetName (", s);
}
TEST(jobsForkSetIterName)
{
_setIterName(true);
}
TEST(jobsNoForkSetIterName)
{
_setIterName(false);
}
TEST(_noIters0, PTI(0, 0))
{
}
TEST(_noIters1, PTI(1, 1))
{
}
static int _empty[] = {};
TESTV(_emptyVector, _empty)
{
}
TEST(jobsEmptyIterTest)
{
std::stringstream out;
Main m({ MKTEST(_noIters0), MKTEST(_noIters1), MKTEST(_emptyVector) });
m.run(out, { "paratec", "--nofork" });
auto s = out.str();
pt_in("100%: of 0 tests", s);
}
TEST(_null)
{
std::cout << std::string("null: \0", 7);
pt_fail("nulls?");
}
TEST(jobsCaptureNullByteInOutput)
{
std::stringstream out;
Main m({ MKTEST(_null) });
m.run(out, { "paratec" });
auto s = out.str();
pt_in(std::string("null: \0", 7), s);
}
static void _fixtureUp()
{
printf("up\n");
}
static void _fixtureDown()
{
printf("down\n");
}
static void _fixtureCleanup()
{
printf("cleanup\n");
}
PARATEC(_fixture,
PTUP(_fixtureUp),
PTDOWN(_fixtureDown),
PTCLEANUP(_fixtureCleanup))
{
}
TEST(jobsFixtures)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_fixture) });
m.run(std::cout, { "paratec", "-vvvv" });
});
pt_in("cleanup\n", e.stdout_);
pt_in("| up\n", e.stdout_);
pt_in("| down\n", e.stdout_);
}
TEST(jobsFixturesOrdering)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_fixture) });
m.run(std::cout, { "paratec", "--nocapture" });
});
pt_in("up\ndown\ncleanup\n", e.stdout_);
}
TEST(_assertInTest)
{
pt_eq(0, 1);
}
static void _assertOutTest()
{
pt_eq(0, 1);
}
TEST(_assertOutTest)
{
_assertOutTest();
}
TEST(_assertMarkBeforeOut)
{
pt_mark();
_assertOutTest();
}
TEST(jobsAssertionLines)
{
Main m({ MKTEST(_assertInTest),
MKTEST(_assertOutTest),
MKTEST(_assertMarkBeforeOut) });
auto rslts = m.run(std::cout, { "paratec" });
auto res = rslts.get("_assertInTest");
pt_in("jobs_test.cpp", res.last_line_);
pt_ni("last test assert", res.last_line_);
res = rslts.get("_assertOutTest");
pt_in("last test assert: test start", res.last_line_);
res = rslts.get("_assertMarkBeforeOut");
pt_in("last test assert: " __FILE__, res.last_line_);
}
}
|
/**
* @author Andrew Stone <[email protected]>
* @copyright 2015 Andrew Stone
*
* This file is part of paratec and is released under the MIT License:
* http://opensource.org/licenses/MIT
*/
#include <atomic>
#include <iostream>
#include <sys/wait.h>
#include <thread>
#include "jobs.hpp"
#include "main.hpp"
#include "util.hpp"
#include "util_test.hpp"
namespace pt
{
TEST(_0)
{
printf("%s", pt_get_name());
}
TEST(_1)
{
printf("%s", pt_get_name());
}
TEST(_2)
{
printf("%s", pt_get_name());
}
TEST(_3)
{
printf("%s", pt_get_name());
}
TEST(jobsNoFork)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(std::cout, { "paratec", "--nofork" });
});
pt_in("Running: _0\n=========", e.stdout_);
}
TEST(jobsNoForkFiltered)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(std::cout, { "paratec", "--nofork", "-f", "_2" });
});
pt_in("Running: _2", e.stdout_);
pt_in("100%: of 1", e.stdout_);
}
TEST(_threadedAssertion)
{
std::thread th([]() { pt_fail("from another thread"); });
while (true) {
usleep(1000000);
}
}
TEST(jobsNoForkThreadedAssertion)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_threadedAssertion) });
m.run(std::cout, { "paratec", "--nofork" });
});
pt_in("Whoa there!", e.stdout_);
}
TEST(jobsFork)
{
std::stringstream out;
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(out, { "paratec" });
auto s = out.str();
pt_in("100%", s);
}
TEST(jobsForkFiltered)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(std::cout, { "paratec", "-f", "_2" });
});
pt_in("100%: of 1", e.stdout_);
}
TEST(jobsForkNoCapture)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(std::cout, { "paratec", "--nocapture" });
});
pt_in("_0", e.stdout_);
pt_in("_1", e.stdout_);
pt_in("_2", e.stdout_);
pt_in("_3", e.stdout_);
}
TEST(jobsVeryVerbose)
{
std::stringstream out;
Main m({ MKTEST(_0), MKTEST(_1), MKTEST(_2), MKTEST(_3) });
m.run(out, { "paratec", "-vvvv" });
auto s = out.str();
pt_in("stdout\n", s);
pt_in("_0", s);
pt_in("_1", s);
pt_in("_2", s);
pt_in("_3", s);
}
TEST(_benchNever, PTBENCH())
{
pt_fail("this bench may never run");
}
TEST(jobsBenchNever)
{
std::stringstream out;
Main m({ MKTEST(_benchNever) });
m.run(out, { "paratec", "-vvvv" });
auto s = out.str();
pt_in("Ran 0 benches.", s);
pt_in("DISABLED : _benchNever", s);
}
TEST(_bench, PTBENCH())
{
pt_ne(_N, 0u);
}
TEST(jobsBenches)
{
std::stringstream out;
Main m({ MKTEST(_bench) });
m.run(out, { "paratec", "-b" });
auto s = out.str();
pt_in("Ran 1 benches.", s);
pt_in("BENCH : _bench", s);
pt_in("ns/op)", s);
}
TEST(jobsAbortSignal, PTSIG(SIGABRT))
{
abort();
}
TEST(_signalMismatch, PTSIG(5))
{
}
TEST(jobsSignal)
{
std::stringstream out;
Main m({ MKTEST(_signalMismatch) });
m.run(out, { "paratec" });
auto s = out.str();
pt_in("received signal", s);
}
TEST(_exitMismatch, PTEXIT(1))
{
}
TEST(jobsExit)
{
std::stringstream out;
Main m({ MKTEST(_exitMismatch) });
m.run(out, { "paratec" });
auto s = out.str();
pt_in("got exit code", s);
}
TEST(_timeout, PTTIME(.001))
{
std::this_thread::sleep_for(std::chrono::seconds(10));
}
TEST(jobsTimeout)
{
std::stringstream out;
Main m({ MKTEST(_timeout) });
m.run(out, { "paratec" });
auto s = out.str();
pt_in("TIME OUT : _timeout", s);
}
static SharedMem<std::atomic_bool> _sleeping;
TEST(_sleep)
{
signal(SIGINT, SIG_IGN);
signal(SIGTERM, SIG_IGN);
_sleeping->store(true);
std::this_thread::sleep_for(std::chrono::seconds(10));
}
TEST(jobsTerminateFromSignal)
{
Fork f;
int status;
bool parent = f.fork(false, true);
if (!parent) {
Main m({ MKTEST(_sleep) });
m.run(std::cout, { "paratec" });
exit(0);
}
// Wait until the test is firmly asleep before trying to kill.
pt_wait_for(_sleeping->load());
auto err = f.terminate(&status);
OSErr(err, {}, "failed to reap child");
pt_eq(f.pid(), err);
pt(WIFSIGNALED(status));
// There's a race condition here with the paratec child sometimes
// terminating its child with SIGKILL and exiting before this process
// sends SIGKILL.
pt(WTERMSIG(status) == SIGTERM || WTERMSIG(status) == SIGKILL);
}
TEST(_fail)
{
pt_fail("failure");
}
static void _fail(bool fork)
{
std::stringstream out;
std::vector<const char *> args({ "paratec", "-vvv" });
if (!fork) {
args.push_back("--nofork");
}
Main m({ MKTEST(_fail) });
m.run(out, args);
auto s = out.str();
pt_in("FAIL : _fail", s);
pt_in("0%: of 1", s);
pt_in("1 failures", s);
}
TEST(jobsForkFail)
{
_fail(true);
}
TEST(jobsNoForkFail)
{
_fail(false);
}
TEST(_error)
{
abort();
}
// This can only run in a forked env since it calls exit()
TEST(jobsError)
{
std::stringstream out;
Main m({ MKTEST(_error) });
m.run(out, { "paratec", "-vvv" });
auto s = out.str();
pt_in("ERROR : _error", s);
pt_in("0%: of 1", s);
pt_in("1 errors", s);
}
TEST(jobsDisabled)
{
std::stringstream out;
Main m({ MKTEST(_0) });
m.run(out, { "paratec", "-vvv", "-f=-_0" });
auto s = out.str();
pt_in("DISABLED : _0", s);
pt_in("100%: of 0", s);
}
TEST(_skip)
{
pt_skip();
}
static void _skip(bool fork)
{
std::stringstream out;
std::vector<const char *> args({ "paratec", "-vvv" });
if (!fork) {
args.push_back("--nofork");
}
Main m({ MKTEST(_0), MKTEST(_skip) });
m.run(out, args);
auto s = out.str();
pt_in("SKIP : _skip", s);
pt_in("100%: of 1", s);
pt_in("1 skipped", s);
}
TEST(jobsForkSkip)
{
_skip(true);
}
TEST(jobsNoForkSkip)
{
_skip(false);
}
TEST(_port)
{
auto p = pt_get_port(0);
pt_gt(p, (uint16_t)0);
pt_gt(pt_get_port(1), p);
}
static void _getPort(bool fork)
{
std::vector<const char *> args({ "paratec" });
if (!fork) {
args.push_back("--nofork");
}
Main m({ MKTEST(_port), MKTEST(_port), MKTEST(_port) });
auto res = m.run(std::cout, args);
pt_eq(res.exitCode(), 0);
}
TEST(jobsForkGetPort)
{
_getPort(true);
}
TEST(jobsNoForkGetPort)
{
_getPort(false);
}
TEST(jobsGetCppName)
{
pt_eq("jobsGetCppName", pt_get_name());
}
extern "C" {
TEST(jobsGetCName)
{
pt_eq("jobsGetCName", pt_get_name());
}
}
TEST(_iterName, PTI(-5, 5))
{
pt_set_iter_name("fun:%" PRId64, _i);
}
TEST(_notIterSetName)
{
pt_set_iter_name("what am i doing?");
}
static void _setIterName(bool fork)
{
std::stringstream out;
std::vector<const char *> args({ "paratec", "-vvv" });
if (!fork) {
args.push_back("--nofork");
}
Main m({ MKTEST(_iterName), MKTEST(_notIterSetName) });
m.run(out, args);
auto s = out.str();
pt_in("PASS : _iterName:-1:fun:-1", s);
pt_in("PASS : _iterName:0:fun:0", s);
pt_in("PASS : _iterName:4:fun:4", s);
pt_in("PASS : _notIterSetName (", s);
}
TEST(jobsForkSetIterName)
{
_setIterName(true);
}
TEST(jobsNoForkSetIterName)
{
_setIterName(false);
}
TEST(_noIters0, PTI(0, 0))
{
pt_fail("should not be called");
}
TEST(_noIters1, PTI(1, 1))
{
pt_fail("should not be called");
}
static int _empty[] = {};
TESTV(_emptyVector, _empty)
{
pt_fail("should not be called");
}
TEST(jobsEmptyIterTest)
{
std::stringstream out;
Main m({ MKTEST(_noIters0), MKTEST(_noIters1), MKTEST(_emptyVector) });
m.run(out, { "paratec", "--nofork" });
auto s = out.str();
pt_in("100%: of 0 tests", s);
}
TEST(_null)
{
std::cout << std::string("null: \0", 7);
pt_fail("nulls?");
}
TEST(jobsCaptureNullByteInOutput)
{
std::stringstream out;
Main m({ MKTEST(_null) });
m.run(out, { "paratec" });
auto s = out.str();
pt_in(std::string("null: \0", 7), s);
}
static void _fixtureUp()
{
printf("up\n");
}
static void _fixtureDown()
{
printf("down\n");
}
static void _fixtureCleanup()
{
printf("cleanup\n");
}
PARATEC(_fixture,
PTUP(_fixtureUp),
PTDOWN(_fixtureDown),
PTCLEANUP(_fixtureCleanup))
{
}
TEST(jobsFixtures)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_fixture) });
m.run(std::cout, { "paratec", "-vvvv" });
});
pt_in("cleanup\n", e.stdout_);
pt_in("| up\n", e.stdout_);
pt_in("| down\n", e.stdout_);
}
TEST(jobsFixturesOrdering)
{
auto e = Fork().run([]() {
Main m({ MKTEST(_fixture) });
m.run(std::cout, { "paratec", "--nocapture" });
});
pt_in("up\ndown\ncleanup\n", e.stdout_);
}
TEST(_assertInTest)
{
pt_eq(0, 1);
}
static void _assertOutTest()
{
pt_eq(0, 1);
}
TEST(_assertOutTest)
{
_assertOutTest();
}
TEST(_assertMarkBeforeOut)
{
pt_mark();
_assertOutTest();
}
TEST(jobsAssertionLines)
{
Main m({ MKTEST(_assertInTest),
MKTEST(_assertOutTest),
MKTEST(_assertMarkBeforeOut) });
auto rslts = m.run(std::cout, { "paratec" });
auto res = rslts.get("_assertInTest");
pt_in("jobs_test.cpp", res.last_line_);
pt_ni("last test assert", res.last_line_);
res = rslts.get("_assertOutTest");
pt_in("last test assert: test start", res.last_line_);
res = rslts.get("_assertMarkBeforeOut");
pt_in("last test assert: " __FILE__, res.last_line_);
}
}
|
Add fail assertions, just in case
|
Add fail assertions, just in case
|
C++
|
mit
|
thatguystone/paratec,thatguystone/paratec
|
804c57ca5429487ab212b395efd0656da2b2ace8
|
src/c4/yml/common.hpp
|
src/c4/yml/common.hpp
|
#ifndef _C4_YML_COMMON_HPP_
#define _C4_YML_COMMON_HPP_
#include <cstddef>
#define RYML_INLINE inline
#ifndef C4_QUOTE
# define C4_QUOTE(x) #x
# define C4_XQUOTE(x) C4_QUOTE(x)
#endif
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable: 4068/*unknown pragma*/)
#endif
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma GCC system_header
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#ifndef C4_ERROR
# define C4_ERROR(msg) \
c4::yml::error(__FILE__ ":" C4_XQUOTE(__LINE__) ": fatal error: " msg "\n")
#endif
#ifndef C4_ASSERT
# ifdef NDEBUG
# define C4_ASSERT(expr) (void)(0)
# else
# ifndef C4_DEBUG_BREAK /* generates SIGTRAP. This assumes x86. Disable at will. */
# ifdef _MSC_VER
# define C4_DEBUG_BREAK() __debugbreak()
# else
# define C4_DEBUG_BREAK() asm("int $3")
# endif
# endif
# include <assert.h>
# define C4_ASSERT(expr) \
{ \
if( ! (expr)) \
{ \
C4_DEBUG_BREAK(); \
c4::yml::error(__FILE__ ":" C4_XQUOTE(__LINE__) ": assert failed: " #expr "\n"); \
} \
}
# endif
#endif
#pragma clang diagnostic pop
#pragma GCC diagnostic pop
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace c4 {
namespace yml {
/** a null position */
enum : size_t { npos = size_t(-1) };
/** an index to none */
enum : size_t { NONE = size_t(-1) };
/** the type of the function used to allocate memory */
using allocate_callback = void* (*)(size_t len, void* hint);
/** the type of the function used to free memory */
using free_callback = void (*)(void* mem, size_t size);
/** the type of the function used to report errors */
using error_callback = void (*)(const char* msg, size_t msg_len);
void set_allocate_callback(allocate_callback fn);
allocate_callback get_allocate_callback();
void* allocate(size_t len, void *hint);
void set_free_callback(free_callback fn);
free_callback get_free_callback();
void free(void *mem, size_t mem_len);
void set_error_callback(error_callback fn);
error_callback get_error_callback();
void error(const char *msg, size_t msg_len);
template< size_t N >
inline void error(const char (&msg)[N])
{
error(msg, N-1);
}
} // namespace yml
} // namespace c4
#endif /* _C4_YML_COMMON_HPP_ */
|
#ifndef _C4_YML_COMMON_HPP_
#define _C4_YML_COMMON_HPP_
#include <cstddef>
#define RYML_INLINE inline
#ifndef C4_QUOTE
# define C4_QUOTE(x) #x
# define C4_XQUOTE(x) C4_QUOTE(x)
#endif
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable: 4068/*unknown pragma*/)
#endif
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma GCC system_header
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#ifndef C4_DEBUG_BREAK /* generates SIGTRAP. This assumes x86. Disable at will. */
# ifdef _MSC_VER
# define C4_DEBUG_BREAK() __debugbreak()
# else
# define C4_DEBUG_BREAK() asm("int $3")
# endif
#endif
#ifndef C4_ASSERT
# ifdef NDEBUG
# define C4_ASSERT(expr) (void)(0)
# else
# include <assert.h>
# define C4_ASSERT(expr) \
{ \
if( ! (expr)) \
{ \
C4_DEBUG_BREAK(); \
c4::yml::error(__FILE__ ":" C4_XQUOTE(__LINE__) ": assert failed: " #expr "\n"); \
} \
}
# endif
#endif
#ifndef C4_ERROR
# define C4_ERROR(msg) \
c4::yml::error(__FILE__ ":" C4_XQUOTE(__LINE__) ": fatal error: " msg "\n")
#endif
#define C4_ERROR_IF(cond, msg) \
if(cond) \
{ \
C4_ERROR(msg); \
}
#define C4_ERROR_IF_NOT(cond, msg) \
if(!(cond)) \
{ \
C4_ERROR(msg); \
}
#pragma clang diagnostic pop
#pragma GCC diagnostic pop
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace c4 {
namespace yml {
/** a null position */
enum : size_t { npos = size_t(-1) };
/** an index to none */
enum : size_t { NONE = size_t(-1) };
/** the type of the function used to allocate memory */
using allocate_callback = void* (*)(size_t len, void* hint);
/** the type of the function used to free memory */
using free_callback = void (*)(void* mem, size_t size);
/** the type of the function used to report errors */
using error_callback = void (*)(const char* msg, size_t msg_len);
void set_allocate_callback(allocate_callback fn);
allocate_callback get_allocate_callback();
void* allocate(size_t len, void *hint);
void set_free_callback(free_callback fn);
free_callback get_free_callback();
void free(void *mem, size_t mem_len);
void set_error_callback(error_callback fn);
error_callback get_error_callback();
void error(const char *msg, size_t msg_len);
template< size_t N >
inline void error(const char (&msg)[N])
{
error(msg, N-1);
}
} // namespace yml
} // namespace c4
#endif /* _C4_YML_COMMON_HPP_ */
|
add C4_ERROR_IF macros
|
add C4_ERROR_IF macros
|
C++
|
mit
|
biojppm/rapidyaml,biojppm/rapidyaml,biojppm/rapidyaml
|
dcf888bf1262267ab54a423204770318147f6b2f
|
src/cli/OglSubmit.cpp
|
src/cli/OglSubmit.cpp
|
#include <ace/SOCK_Connector.h>
#include <ace/Get_Opt.h>
#include "Object.h"
#include "Commands.h"
#include "Connection.h"
#include "JobProxy.h"
#include "TaskProxy.h"
#include "Exception.h"
#include <iostream>
using namespace std;
using namespace ogl;
void print_help()
{
const char* help =
"Usage: oglsub -j job name -c commad line [OPTION]\n"
"Submit a command line as job to Job Manager Server.\n"
"\n"
" -j Job name\n"
" -c Job command\n"
" -n The number of tasks\n"
"\n"
"Home & Bugs: <https://github.com/dma1982/ogl>\n"
"\n";
cout << help ;
}
void printTaskInfo(TaskProxy* task)
{
char buf[BUFSIZ] = {0};
size_t size = BUFSIZ;
task->output(buf, size);
cout << buf << endl;
}
int main(int argc, char** argv)
{
ACE_Get_Opt getOpt(argc, argv, "hj:c:n:");
int arg;
int taskCount = 0;
JobOption jobOption;
while ((arg = getOpt()) != EOF)
{
switch (arg)
{
case 'j':
jobOption.name(getOpt.optarg);
break;
case 'c':
jobOption.command(getOpt.optarg);
break;
case 'n':
taskCount = atoi(getOpt.optarg);
break;
case 'h':
default:
print_help();
return 0;
}
}
if (jobOption.name() == 0 ||
jobOption.command() == 0)
{
print_help();
return -1;
}
printf("INFO: Creating job <%s> with command <%s>.\n", jobOption.name(), jobOption.command());
try
{
Connection connection;
JobProxy* job = connection.addJob(&jobOption);
printf("INFO: Create job successfully, job id is <%d>.\n", (int)(job->option().id()));
list<TaskProxy*> taskList;
for ( int i = 0; i < taskCount; i++)
{
TaskOption taskOption;
TaskProxy* task = job->addTask(&taskOption);
printf("INFO: Create task <%d>.\n", (int)(task->taskId()));
taskList.push_back(task);
}
for_each(taskList.begin(), taskList.end(), printTaskInfo);
job->closeJob();
}
catch (Exception& e)
{
cout << "*ERROR*: " << e.what() << endl;
}
}
|
#include <ace/SOCK_Connector.h>
#include <ace/Get_Opt.h>
#include "Object.h"
#include "Commands.h"
#include "Connection.h"
#include "JobProxy.h"
#include "TaskProxy.h"
#include "Exception.h"
#include <iostream>
using namespace std;
using namespace ogl;
void print_help()
{
const char* help =
"Usage: oglsub -j job name -c commad line [OPTION]\n"
"Submit a command line as job to Job Manager Server.\n"
"\n"
" -j Job name\n"
" -c Job command\n"
" -n The number of tasks\n"
"\n"
"Home & Bugs: <https://github.com/dma1982/ogl>\n";
cout << help << endl;
}
void printTaskInfo(TaskProxy* task)
{
char buf[BUFSIZ] = {0};
size_t size = BUFSIZ;
task->output(buf, size);
cout << buf << endl;
}
int main(int argc, char** argv)
{
ACE_Get_Opt getOpt(argc, argv, "hj:c:n:");
int arg;
int taskCount = 1;
JobOption jobOption;
while ((arg = getOpt()) != EOF)
{
switch (arg)
{
case 'j':
jobOption.name(getOpt.optarg);
break;
case 'c':
jobOption.command(getOpt.optarg);
break;
case 'n':
taskCount = atoi(getOpt.optarg);
break;
case 'h':
default:
print_help();
return 0;
}
}
if (jobOption.name() == 0 ||
jobOption.command() == 0 ||
taskCount <= 0)
{
print_help();
return -1;
}
printf("INFO: Creating job <%s> with command <%s>.\n", jobOption.name(), jobOption.command());
try
{
Connection connection;
JobProxy* job = connection.addJob(&jobOption);
printf("INFO: Create job successfully, job id is <%d>.\n", (int)(job->option().id()));
list<TaskProxy*> taskList;
for ( int i = 0; i < taskCount; i++)
{
TaskOption taskOption;
TaskProxy* task = job->addTask(&taskOption);
printf("INFO: Create task <%d>.\n", (int)(task->taskId()));
taskList.push_back(task);
}
for_each(taskList.begin(), taskList.end(), printTaskInfo);
job->closeJob();
}
catch (Exception& e)
{
cout << "*ERROR*: " << e.what() << endl;
}
}
|
check task count
|
check task count
|
C++
|
mit
|
dma1982/ogl,dma1982/ogl
|
3f0fc0f8e1538fa94c64702b0a25e5416f476998
|
src/commands/Info.cpp
|
src/commands/Info.cpp
|
// cfiles, an analysis frontend for the Chemfiles library
// Copyright (C) Guillaume Fraux and contributors -- BSD license
#include <iostream>
#include <sstream>
#include <docopt/docopt.h>
#include <chemfiles.hpp>
#include "Info.hpp"
#include "Errors.hpp"
#include "utils.hpp"
using namespace chemfiles;
static const char OPTIONS[] =
R"(Get various information and metadata from a trajectory.
Usage:
cfiles info [options] <input>
cfiles info (-h | --help)
Examples:
cfiles info water.xyz
cfiles info --guess-bonds --step 4 water.xyz
Options:
-h --help show this help
--guess-bonds guess the bonds in the input
--step=<step> give informations about the frame at <step>
[default: 0]
)";
static Info::Options parse_options(int argc, const char* argv[]) {
auto options_str = command_header("info", Info().description());
options_str += "Guillaume Fraux <[email protected]>\n\n";
options_str += OPTIONS;
auto args = docopt::docopt(options_str, {argv, argv + argc}, true, "");
Info::Options options;
options.input = args["<input>"].asString();
options.guess_bonds = args.at("--guess-bonds").asBool();
auto step = args.at("--step").asLong();
if (step >= 0) {
options.step = static_cast<size_t>(step);
} else {
throw CFilesError("step must be positive");
}
return options;
}
std::string Info::description() const {
return "get information on a trajectory";
}
int Info::run(int argc, const char* argv[]) {
auto options = parse_options(argc, argv);
auto input = Trajectory(options.input, 'r', "");
std::stringstream output;
output << "information for " << options.input << std::endl;
output << std::endl << "global:" << std::endl;
output << " steps = " << input.nsteps() << std::endl;
if (input.nsteps() > options.step) {
auto frame = input.read_step(options.step);
output << std::endl << "frame " << frame.step() << ":" << std::endl;
output << " atoms = " << frame.size() << std::endl;
if (options.guess_bonds) {
frame.guess_topology();
}
auto& topology = frame.topology();
output << " bonds = " << topology.bonds().size() << std::endl;
output << " angles = " << topology.angles().size() << std::endl;
output << " dihedrals = " << topology.dihedrals().size() << std::endl;
output << " residues = " << topology.residues().size() << std::endl;
}
std::cout << output.str();
return 0;
}
|
// cfiles, an analysis frontend for the Chemfiles library
// Copyright (C) Guillaume Fraux and contributors -- BSD license
#include <iostream>
#include <sstream>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <docopt/docopt.h>
#include <chemfiles.hpp>
#include "Info.hpp"
#include "Errors.hpp"
#include "utils.hpp"
using namespace chemfiles;
static const char OPTIONS[] =
R"(Get various information and metadata from a trajectory.
Usage:
cfiles info [options] <input>
cfiles info (-h | --help)
Examples:
cfiles info water.xyz
cfiles info --guess-bonds --step 4 water.xyz
Options:
-h --help show this help
--guess-bonds guess the bonds in the input
--step=<step> give informations about the frame at <step>
[default: 0]
)";
static Info::Options parse_options(int argc, const char* argv[]) {
auto options_str = command_header("info", Info().description());
options_str += "Guillaume Fraux <[email protected]>\n\n";
options_str += OPTIONS;
auto args = docopt::docopt(options_str, {argv, argv + argc}, true, "");
Info::Options options;
options.input = args["<input>"].asString();
options.guess_bonds = args.at("--guess-bonds").asBool();
auto step = args.at("--step").asLong();
if (step >= 0) {
options.step = static_cast<size_t>(step);
} else {
throw CFilesError("step must be positive");
}
return options;
}
std::string Info::description() const {
return "get information on a trajectory";
}
int Info::run(int argc, const char* argv[]) {
auto options = parse_options(argc, argv);
auto input = Trajectory(options.input, 'r', "");
std::stringstream output;
fmt::print(output, "file = {}\n", options.input);
fmt::print(output, "steps = {}\n", input.nsteps());
if (input.nsteps() > options.step) {
auto frame = input.read_step(options.step);
fmt::print(output, "\n[frame]\n", frame.step());
fmt::print(output, "step = {}\n", options.step);
auto& cell = frame.cell();
fmt::print(output, "cell = [{}, {}, {}, {}, {}, {}]\n",
cell.a(), cell.b(), cell.c(),
cell.alpha(), cell.beta(), cell.gamma()
);
if (options.guess_bonds) {
frame.guess_topology();
}
auto& topology = frame.topology();
fmt::print(output, "atoms_count = {}\n", frame.size());
fmt::print(output, "bonds_count = {}\n", topology.bonds().size());
fmt::print(output, "angles_count = {}\n", topology.angles().size());
fmt::print(output, "dihedrals_count = {}\n", topology.dihedrals().size());
fmt::print(output, "impropers_count = {}\n", topology.impropers().size());
fmt::print(output, "residues_count = {}\n", topology.residues().size());
}
std::cout << output.str();
return 0;
}
|
Convert Info to use fmt
|
Convert Info to use fmt
|
C++
|
mpl-2.0
|
chemfiles/chrp,Luthaf/chrp
|
bc184e7c0689b26e0c62d36d3cb701cce6236876
|
src/common/cynara.cpp
|
src/common/cynara.cpp
|
/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
*
* Contact: Rafal Krypa <[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
*/
/*
* @file cynara.cpp
* @author Rafal Krypa <[email protected]>
* @brief Wrapper class for Cynara interface
*/
#include <cstring>
#include "cynara.h"
#include <dpl/log/log.h>
namespace SecurityManager {
/**
* Rules for apps and users are organized into set of buckets stored in Cynara.
* Bucket is set of rules (app, uid, privilege) -> (DENY, ALLOW, BUCKET, ...).
* |------------------------|
* | <<allow>> |
* | PRIVACY_MANAGER |
* |------------------------|
* | A U P policy|
* |------------------------|
* | app1 uid1 priv1 DENY |
* | * uid2 priv2 DENY |
* | * * * Bucket:MAIN|
* |------------------------|
*
* For details about buckets see Cynara documentation.
*
* Security Manager currently defines 8 buckets:
* - PRIVACY_MANAGER - first bucket during search (which is actually default bucket
* with empty string as id). If user specifies his preference then required rule
* is created here.
* - MAIN - holds rules denied by manufacturer, redirects to MANIFESTS
* bucket and holds entries for each user pointing to User Type
* specific buckets
* - MANIFESTS - stores rules needed by installed apps (from package
* manifest)
* - USER_TYPE_ADMIN
* - USER_TYPE_SYSTEM
* - USER_TYPE_NORMAL
* - USER_TYPE_GUEST - they store privileges from templates for apropriate
* user type. ALLOW rules only.
* - ADMIN - stores custom rules introduced by device administrator.
* Ignored if no matching rule found.
*
* Below is basic layout of buckets:
*
* |------------------------|
* | <<allow>> |
* | PRIVACY_MANAGER |
* | |
* | * * * Bucket:MAIN| |------------------|
* |------------------------| | <<deny>> |
* | |->| MANIFESTS |
* ----------------- | | |
* | | |------------------|
* V |
* |------------------------| |
* | <<deny>> |---|
* | MAIN |
* |---------------| | | |-------------------|
* | <<deny>> |<--| * * * Bucket:MANIFESTS|---->| <<deny>> |
* | USER_TYPE_SYST| |------------------------| | USER_TYPE_NORMAL |
* | | | | | |
* |---------------| | | |-------------------|
* | | | |
* | V V |
* | |---------------| |---------------| |
* | | <<deny>> | | <<deny>> | |
* | |USER_TYPE_GUEST| |USER_TYPE_ADMIN| |
* | | | | | |
* | |---------------| |---------------| |
* | | | |
* | |---- -----| |
* | | | |
* | V V |
* | |------------------| |
* |-------------> | <<none>> | <---------------|
* | ADMIN |
* | |
* |------------------|
*
*/
CynaraAdmin::BucketsMap CynaraAdmin::Buckets =
{
{ Bucket::PRIVACY_MANAGER, std::string(CYNARA_ADMIN_DEFAULT_BUCKET)},
{ Bucket::MAIN, std::string("MAIN")},
{ Bucket::USER_TYPE_ADMIN, std::string("USER_TYPE_ADMIN")},
{ Bucket::USER_TYPE_NORMAL, std::string("USER_TYPE_NORMAL")},
{ Bucket::USER_TYPE_GUEST, std::string("USER_TYPE_GUEST") },
{ Bucket::USER_TYPE_SYSTEM, std::string("USER_TYPE_SYSTEM")},
{ Bucket::ADMIN, std::string("ADMIN")},
{ Bucket::MANIFESTS, std::string("MANIFESTS")},
};
CynaraAdminPolicy::CynaraAdminPolicy(const std::string &client, const std::string &user,
const std::string &privilege, Operation operation,
const std::string &bucket)
{
this->client = strdup(client.c_str());
this->user = strdup(user.c_str());
this->privilege = strdup(privilege.c_str());
this->bucket = strdup(bucket.c_str());
if (this->bucket == nullptr || this->client == nullptr ||
this->user == nullptr || this->privilege == nullptr) {
free(this->bucket);
free(this->client);
free(this->user);
free(this->privilege);
ThrowMsg(CynaraException::OutOfMemory,
std::string("Error in CynaraAdminPolicy allocation."));
}
this->result = static_cast<int>(operation);
this->result_extra = nullptr;
}
CynaraAdminPolicy::CynaraAdminPolicy(const std::string &client, const std::string &user,
const std::string &privilege, const std::string &goToBucket,
const std::string &bucket)
{
this->bucket = strdup(bucket.c_str());
this->client = strdup(client.c_str());
this->user = strdup(user.c_str());
this->privilege = strdup(privilege.c_str());
this->result_extra = strdup(goToBucket.c_str());
this->result = CYNARA_ADMIN_BUCKET;
if (this->bucket == nullptr || this->client == nullptr ||
this->user == nullptr || this->privilege == nullptr ||
this->result_extra == nullptr) {
free(this->bucket);
free(this->client);
free(this->user);
free(this->privilege);
free(this->result_extra);
ThrowMsg(CynaraException::OutOfMemory,
std::string("Error in CynaraAdminPolicy allocation."));
}
}
CynaraAdminPolicy::CynaraAdminPolicy(CynaraAdminPolicy &&that)
{
bucket = that.bucket;
client = that.client;
user = that.user;
privilege = that.privilege;
result_extra = that.result_extra;
result = that.result;
that.bucket = nullptr;
that.client = nullptr;
that.user = nullptr;
that.privilege = nullptr;
that.result_extra = nullptr;
}
CynaraAdminPolicy::~CynaraAdminPolicy()
{
free(this->bucket);
free(this->client);
free(this->user);
free(this->privilege);
free(this->result_extra);
}
static bool checkCynaraError(int result, const std::string &msg)
{
switch (result) {
case CYNARA_API_SUCCESS:
case CYNARA_API_ACCESS_ALLOWED:
return true;
case CYNARA_API_ACCESS_DENIED:
return false;
case CYNARA_API_OUT_OF_MEMORY:
ThrowMsg(CynaraException::OutOfMemory, msg);
case CYNARA_API_INVALID_PARAM:
ThrowMsg(CynaraException::InvalidParam, msg);
case CYNARA_API_SERVICE_NOT_AVAILABLE:
ThrowMsg(CynaraException::ServiceNotAvailable, msg);
default:
ThrowMsg(CynaraException::UnknownError, msg);
}
}
CynaraAdmin::CynaraAdmin()
{
checkCynaraError(
cynara_admin_initialize(&m_CynaraAdmin),
"Cannot connect to Cynara administrative interface.");
}
CynaraAdmin::~CynaraAdmin()
{
cynara_admin_finish(m_CynaraAdmin);
}
CynaraAdmin &CynaraAdmin::getInstance()
{
static CynaraAdmin cynaraAdmin;
return cynaraAdmin;
}
void CynaraAdmin::SetPolicies(const std::vector<CynaraAdminPolicy> &policies)
{
std::vector<const struct cynara_admin_policy *> pp_policies(policies.size() + 1);
LogDebug("Sending " << policies.size() << " policies to Cynara");
for (std::size_t i = 0; i < policies.size(); ++i) {
pp_policies[i] = static_cast<const struct cynara_admin_policy *>(&policies[i]);
LogDebug("policies[" << i << "] = {" <<
".bucket = " << pp_policies[i]->bucket << ", " <<
".client = " << pp_policies[i]->client << ", " <<
".user = " << pp_policies[i]->user << ", " <<
".privilege = " << pp_policies[i]->privilege << ", " <<
".result = " << pp_policies[i]->result << ", " <<
".result_extra = " << pp_policies[i]->result_extra << "}");
}
pp_policies[policies.size()] = nullptr;
checkCynaraError(
cynara_admin_set_policies(m_CynaraAdmin, pp_policies.data()),
"Error while updating Cynara policy.");
}
void CynaraAdmin::UpdateAppPolicy(
const std::string &label,
const std::string &user,
const std::vector<std::string> &oldPrivileges,
const std::vector<std::string> &newPrivileges)
{
std::vector<CynaraAdminPolicy> policies;
// Perform sort-merge join on oldPrivileges and newPrivileges.
// Assume that they are already sorted and without duplicates.
auto oldIter = oldPrivileges.begin();
auto newIter = newPrivileges.begin();
while (oldIter != oldPrivileges.end() && newIter != newPrivileges.end()) {
int compare = oldIter->compare(*newIter);
if (compare == 0) {
LogDebug("(user = " << user << " label = " << label << ") " <<
"keeping privilege " << *newIter);
++oldIter;
++newIter;
continue;
} else if (compare < 0) {
LogDebug("(user = " << user << " label = " << label << ") " <<
"removing privilege " << *oldIter);
policies.push_back(CynaraAdminPolicy(label, user, *oldIter,
CynaraAdminPolicy::Operation::Delete));
++oldIter;
} else {
LogDebug("(user = " << user << " label = " << label << ") " <<
"adding privilege " << *newIter);
policies.push_back(CynaraAdminPolicy(label, user, *newIter,
CynaraAdminPolicy::Operation::Allow));
++newIter;
}
}
for (; oldIter != oldPrivileges.end(); ++oldIter) {
LogDebug("(user = " << user << " label = " << label << ") " <<
"removing privilege " << *oldIter);
policies.push_back(CynaraAdminPolicy(label, user, *oldIter,
CynaraAdminPolicy::Operation::Delete));
}
for (; newIter != newPrivileges.end(); ++newIter) {
LogDebug("(user = " << user << " label = " << label << ") " <<
"adding privilege " << *newIter);
policies.push_back(CynaraAdminPolicy(label, user, *newIter,
CynaraAdminPolicy::Operation::Allow));
}
SetPolicies(policies);
}
Cynara::Cynara()
{
checkCynaraError(
cynara_initialize(&m_Cynara, nullptr),
"Cannot connect to Cynara policy interface.");
}
Cynara::~Cynara()
{
cynara_finish(m_Cynara);
}
Cynara &Cynara::getInstance()
{
static Cynara cynara;
return cynara;
}
bool Cynara::check(const std::string &label, const std::string &privilege,
const std::string &user, const std::string &session)
{
return checkCynaraError(
cynara_check(m_Cynara,
label.c_str(), session.c_str(), user.c_str(), privilege.c_str()),
"Cannot check permission with Cynara.");
}
} // namespace SecurityManager
|
/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
*
* Contact: Rafal Krypa <[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
*/
/*
* @file cynara.cpp
* @author Rafal Krypa <[email protected]>
* @brief Wrapper class for Cynara interface
*/
#include <cstring>
#include "cynara.h"
#include <dpl/log/log.h>
namespace SecurityManager {
/**
* Rules for apps and users are organized into set of buckets stored in Cynara.
* Bucket is set of rules (app, uid, privilege) -> (DENY, ALLOW, BUCKET, ...).
* |------------------------|
* | <<allow>> |
* | PRIVACY_MANAGER |
* |------------------------|
* | A U P policy|
* |------------------------|
* | app1 uid1 priv1 DENY |
* | * uid2 priv2 DENY |
* | * * * Bucket:MAIN|
* |------------------------|
*
* For details about buckets see Cynara documentation.
*
* Security Manager currently defines 8 buckets:
* - PRIVACY_MANAGER - first bucket during search (which is actually default bucket
* with empty string as id). If user specifies his preference then required rule
* is created here.
* - MAIN - holds rules denied by manufacturer, redirects to MANIFESTS
* bucket and holds entries for each user pointing to User Type
* specific buckets
* - MANIFESTS - stores rules needed by installed apps (from package
* manifest)
* - USER_TYPE_ADMIN
* - USER_TYPE_SYSTEM
* - USER_TYPE_NORMAL
* - USER_TYPE_GUEST - they store privileges from templates for apropriate
* user type. ALLOW rules only.
* - ADMIN - stores custom rules introduced by device administrator.
* Ignored if no matching rule found.
*
* Below is basic layout of buckets:
*
* |------------------------|
* | <<allow>> |
* | PRIVACY_MANAGER |
* | |
* | * * * Bucket:MAIN| |------------------|
* |------------------------| | <<deny>> |
* | |->| MANIFESTS |
* ----------------- | | |
* | | |------------------|
* V |
* |------------------------| |
* | <<deny>> |---|
* | MAIN |
* |---------------| | | |-------------------|
* | <<deny>> |<--| * * * Bucket:MANIFESTS|---->| <<deny>> |
* | USER_TYPE_SYST| |------------------------| | USER_TYPE_NORMAL |
* | | | | | |
* |---------------| | | |-------------------|
* | | | |
* | V V |
* | |---------------| |---------------| |
* | | <<deny>> | | <<deny>> | |
* | |USER_TYPE_GUEST| |USER_TYPE_ADMIN| |
* | | | | | |
* | |---------------| |---------------| |
* | | | |
* | |---- -----| |
* | | | |
* | V V |
* | |------------------| |
* |-------------> | <<none>> | <---------------|
* | ADMIN |
* | |
* |------------------|
*
*/
CynaraAdmin::BucketsMap CynaraAdmin::Buckets =
{
{ Bucket::PRIVACY_MANAGER, std::string(CYNARA_ADMIN_DEFAULT_BUCKET)},
{ Bucket::MAIN, std::string("MAIN")},
{ Bucket::USER_TYPE_ADMIN, std::string("USER_TYPE_ADMIN")},
{ Bucket::USER_TYPE_NORMAL, std::string("USER_TYPE_NORMAL")},
{ Bucket::USER_TYPE_GUEST, std::string("USER_TYPE_GUEST") },
{ Bucket::USER_TYPE_SYSTEM, std::string("USER_TYPE_SYSTEM")},
{ Bucket::ADMIN, std::string("ADMIN")},
{ Bucket::MANIFESTS, std::string("MANIFESTS")},
};
CynaraAdminPolicy::CynaraAdminPolicy(const std::string &client, const std::string &user,
const std::string &privilege, Operation operation,
const std::string &bucket)
{
this->client = strdup(client.c_str());
this->user = strdup(user.c_str());
this->privilege = strdup(privilege.c_str());
this->bucket = strdup(bucket.c_str());
if (this->bucket == nullptr || this->client == nullptr ||
this->user == nullptr || this->privilege == nullptr) {
free(this->bucket);
free(this->client);
free(this->user);
free(this->privilege);
ThrowMsg(CynaraException::OutOfMemory,
std::string("Error in CynaraAdminPolicy allocation."));
}
this->result = static_cast<int>(operation);
this->result_extra = nullptr;
}
CynaraAdminPolicy::CynaraAdminPolicy(const std::string &client, const std::string &user,
const std::string &privilege, const std::string &goToBucket,
const std::string &bucket)
{
this->bucket = strdup(bucket.c_str());
this->client = strdup(client.c_str());
this->user = strdup(user.c_str());
this->privilege = strdup(privilege.c_str());
this->result_extra = strdup(goToBucket.c_str());
this->result = CYNARA_ADMIN_BUCKET;
if (this->bucket == nullptr || this->client == nullptr ||
this->user == nullptr || this->privilege == nullptr ||
this->result_extra == nullptr) {
free(this->bucket);
free(this->client);
free(this->user);
free(this->privilege);
free(this->result_extra);
ThrowMsg(CynaraException::OutOfMemory,
std::string("Error in CynaraAdminPolicy allocation."));
}
}
CynaraAdminPolicy::CynaraAdminPolicy(CynaraAdminPolicy &&that)
{
bucket = that.bucket;
client = that.client;
user = that.user;
privilege = that.privilege;
result_extra = that.result_extra;
result = that.result;
that.bucket = nullptr;
that.client = nullptr;
that.user = nullptr;
that.privilege = nullptr;
that.result_extra = nullptr;
}
CynaraAdminPolicy::~CynaraAdminPolicy()
{
free(this->bucket);
free(this->client);
free(this->user);
free(this->privilege);
free(this->result_extra);
}
static bool checkCynaraError(int result, const std::string &msg)
{
switch (result) {
case CYNARA_API_SUCCESS:
case CYNARA_API_ACCESS_ALLOWED:
return true;
case CYNARA_API_ACCESS_DENIED:
return false;
case CYNARA_API_OUT_OF_MEMORY:
ThrowMsg(CynaraException::OutOfMemory, msg);
case CYNARA_API_INVALID_PARAM:
ThrowMsg(CynaraException::InvalidParam, msg);
case CYNARA_API_SERVICE_NOT_AVAILABLE:
ThrowMsg(CynaraException::ServiceNotAvailable, msg);
default:
ThrowMsg(CynaraException::UnknownError, msg);
}
}
CynaraAdmin::CynaraAdmin()
{
checkCynaraError(
cynara_admin_initialize(&m_CynaraAdmin),
"Cannot connect to Cynara administrative interface.");
}
CynaraAdmin::~CynaraAdmin()
{
cynara_admin_finish(m_CynaraAdmin);
}
CynaraAdmin &CynaraAdmin::getInstance()
{
static CynaraAdmin cynaraAdmin;
return cynaraAdmin;
}
void CynaraAdmin::SetPolicies(const std::vector<CynaraAdminPolicy> &policies)
{
std::vector<const struct cynara_admin_policy *> pp_policies(policies.size() + 1);
LogDebug("Sending " << policies.size() << " policies to Cynara");
for (std::size_t i = 0; i < policies.size(); ++i) {
pp_policies[i] = static_cast<const struct cynara_admin_policy *>(&policies[i]);
LogDebug("policies[" << i << "] = {" <<
".bucket = " << pp_policies[i]->bucket << ", " <<
".client = " << pp_policies[i]->client << ", " <<
".user = " << pp_policies[i]->user << ", " <<
".privilege = " << pp_policies[i]->privilege << ", " <<
".result = " << pp_policies[i]->result << ", " <<
".result_extra = " << pp_policies[i]->result_extra << "}");
}
pp_policies[policies.size()] = nullptr;
checkCynaraError(
cynara_admin_set_policies(m_CynaraAdmin, pp_policies.data()),
"Error while updating Cynara policy.");
}
void CynaraAdmin::UpdateAppPolicy(
const std::string &label,
const std::string &user,
const std::vector<std::string> &oldPrivileges,
const std::vector<std::string> &newPrivileges)
{
std::vector<CynaraAdminPolicy> policies;
// Perform sort-merge join on oldPrivileges and newPrivileges.
// Assume that they are already sorted and without duplicates.
auto oldIter = oldPrivileges.begin();
auto newIter = newPrivileges.begin();
while (oldIter != oldPrivileges.end() && newIter != newPrivileges.end()) {
int compare = oldIter->compare(*newIter);
if (compare == 0) {
LogDebug("(user = " << user << " label = " << label << ") " <<
"keeping privilege " << *newIter);
++oldIter;
++newIter;
continue;
} else if (compare < 0) {
LogDebug("(user = " << user << " label = " << label << ") " <<
"removing privilege " << *oldIter);
policies.push_back(CynaraAdminPolicy(label, user, *oldIter,
CynaraAdminPolicy::Operation::Delete,
Buckets.at(Bucket::MANIFESTS)));
++oldIter;
} else {
LogDebug("(user = " << user << " label = " << label << ") " <<
"adding privilege " << *newIter);
policies.push_back(CynaraAdminPolicy(label, user, *newIter,
CynaraAdminPolicy::Operation::Allow,
Buckets.at(Bucket::MANIFESTS)));
++newIter;
}
}
for (; oldIter != oldPrivileges.end(); ++oldIter) {
LogDebug("(user = " << user << " label = " << label << ") " <<
"removing privilege " << *oldIter);
policies.push_back(CynaraAdminPolicy(label, user, *oldIter,
CynaraAdminPolicy::Operation::Delete,
Buckets.at(Bucket::MANIFESTS)));
}
for (; newIter != newPrivileges.end(); ++newIter) {
LogDebug("(user = " << user << " label = " << label << ") " <<
"adding privilege " << *newIter);
policies.push_back(CynaraAdminPolicy(label, user, *newIter,
CynaraAdminPolicy::Operation::Allow,
Buckets.at(Bucket::MANIFESTS)));
}
SetPolicies(policies);
}
Cynara::Cynara()
{
checkCynaraError(
cynara_initialize(&m_Cynara, nullptr),
"Cannot connect to Cynara policy interface.");
}
Cynara::~Cynara()
{
cynara_finish(m_Cynara);
}
Cynara &Cynara::getInstance()
{
static Cynara cynara;
return cynara;
}
bool Cynara::check(const std::string &label, const std::string &privilege,
const std::string &user, const std::string &session)
{
return checkCynaraError(
cynara_check(m_Cynara,
label.c_str(), session.c_str(), user.c_str(), privilege.c_str()),
"Cannot check permission with Cynara.");
}
} // namespace SecurityManager
|
Add app permissions to MANIFESTS bucket instead of default.
|
Add app permissions to MANIFESTS bucket instead of default.
Change-Id: Ic19078c83c7075717c3d6b3c10c8883944519e5f
Signed-off-by: Michal Eljasiewicz <[email protected]>
|
C++
|
apache-2.0
|
pohly/security-manager,Samsung/security-manager,pohly/security-manager,Samsung/security-manager,pohly/security-manager,Samsung/security-manager
|
8bdc276bbc981e8dc7ccba726284a251994e6e22
|
src/console-server.cc
|
src/console-server.cc
|
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <libport/unistd.h>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <libport/cstring>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <libport/asio.hh>
#include <libport/cli.hh>
#include <libport/debug.hh>
#include <libport/exception.hh>
#include <libport/foreach.hh>
#include <libport/format.hh>
#ifndef NO_OPTION_PARSER
# include <libport/option-parser.hh>
# define IF_OPTION_PARSER(a, b) a
#else
#define IF_OPTION_PARSER(a, b) b
#endif
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/read-stdin.hh>
#include <libport/semaphore.hh>
#include <libport/sys/socket.h>
#include <libport/sysexits.hh>
#include <libport/thread.hh>
#include <libport/utime.hh>
#include <libport/windows.hh>
#include <libltdl/ltdl.h>
// Inclusion order matters for windows. Leave userver.hh after network.hh.
#include <kernel/uqueue.hh>
#include <kernel/userver.hh>
#include <kernel/uconnection.hh>
#include <sched/configuration.hh>
#include <sched/scheduler.hh>
#include <kernel/connection.hh>
#include <kernel/ubanner.hh>
#include <object/symbols.hh>
#include <object/object.hh>
#include <object/float.hh>
#include <object/system.hh>
#include <urbi/export.hh>
#include <urbi/umain.hh>
#include <urbi/uobject.hh>
GD_INIT();
GD_ADD_CATEGORY(URBI);
#define URBI_EXIT(Status, Args) \
throw urbi::Exit(Status, libport::format Args)
class ConsoleServer
: public kernel::UServer
, public libport::Socket
{
public:
ConsoleServer(bool fast)
: kernel::UServer("console")
, libport::Socket(kernel::UServer::get_io_service())
, fast(fast)
, ctime(0)
{}
virtual ~ConsoleServer()
{}
virtual void reset()
{}
virtual void reboot()
{}
virtual libport::utime_t getTime()
{
return fast ? ctime : libport::utime();
}
virtual
UErrorValue
save_file(const std::string& filename, const std::string& content)
{
//! \todo check this code
std::ofstream os(filename.c_str());
os << content;
os.close();
return os.good() ? USUCCESS : UFAIL;
}
virtual
void effectiveDisplay(const char* t)
{
std::cout << t;
}
boost::asio::io_service&
get_io_service()
{
return kernel::UServer::get_io_service();
}
bool fast;
libport::utime_t ctime;
};
namespace
{
#ifndef NO_OPTION_PARSER
static
void
help(libport::OptionParser& parser)
{
std::stringstream output;
output
<< "usage: " << libport::program_name()
<< " [OPTIONS] [PROGRAM_FILE] [ARGS...]" << std::endl
<< std::endl
<< " PROGRAM_FILE Urbi script to load."
<< " `-' stands for standard input" << std::endl
<< " ARGS user arguments passed to PROGRAM_FILE" << std::endl
<< parser;
throw urbi::Exit(EX_OK, output.str());
}
#endif
static
void
version()
{
throw urbi::Exit(EX_OK, kernel::UServer::package_info().signature());
}
static
void
forbid_option(const std::string& arg)
{
if (arg.size() > 1 && arg[0] == '-')
URBI_EXIT(EX_USAGE,
("unrecognized command line option: %s", arg));
}
}
namespace urbi
{
/// Command line options needed in the main loop.
struct LoopData
{
LoopData()
: interactive(false)
, fast(false)
, network(true)
, server(0)
{}
bool interactive;
bool fast;
/// Whether network connections are enabled.
bool network;
ConsoleServer* server;
};
int main_loop(LoopData& l);
static libport::Socket*
connectionFactory()
{
kernel::Connection* c = new kernel::Connection();
kernel::urbiserver->connection_add(c);
return c;
}
static std::string convert_input_file(const std::string& arg)
{
return (arg == "-") ? "/dev/stdin" : arg;
}
/// Data to send to the server.
struct Input
{
Input(bool f, const std::string& v)
: file_p(f), value(v)
{}
/// Whether it's a file (or a litteral).
bool file_p;
/// File name or litteral value.
std::string value;
};
static int
init(const libport::cli_args_type& _args, bool errors,
libport::Semaphore* sem)
{
libport::Finally f;
if (sem)
f << boost::bind(&libport::Semaphore::operator++, sem);
if (errors)
{
try
{
return init(_args, false, sem);
}
catch (const urbi::Exit& e)
{
std::cerr << libport::program_name() << ": " << e.what() << std::endl;
return e.error_get();
}
catch (const std::exception& e)
{
std::cerr << libport::program_name() << ": " << e.what() << std::endl;
return 1;
}
}
GD_CATEGORY(URBI);
libport::cli_args_type args = _args;
object::system_set_program_name(args[0]);
args.erase(args.begin());
// Input files.
typedef std::vector<Input> input_type;
input_type input;
/// The size of the stacks.
size_t arg_stack_size = 0;
// Parse the command line.
LoopData data;
#ifndef NO_OPTION_PARSER
libport::OptionFlag
arg_fast("ignore system time, go as fast as possible",
"fast", 'F'),
arg_interactive("read and parse stdin in a nonblocking way",
"interactive", 'i'),
arg_no_net("ignored for backward compatibility", "no-network", 'n');
libport::OptionValue
arg_period ("ignored for backward compatibility", "period", 'P'),
arg_port_file("write port number to the specified file.",
"port-file", 'w', "FILE"),
arg_stack ("set the job stack size in KB", "stack-size", 's', "SIZE");
libport::OptionValues
arg_exps("run expression", "expression", 'e', "EXP");
{
libport::OptionParser parser;
parser
<< "Options:"
<< arg_fast
<< libport::opts::help
<< libport::opts::version
<< libport::opts::debug
<< arg_period
<< "Tuning:"
<< arg_stack
<< "Networking:"
<< libport::opts::host_l
<< libport::opts::port_l
<< arg_port_file
<< arg_no_net
<< "Execution:"
<< arg_exps
<< libport::opts::files
<< arg_interactive
;
try
{
args = parser(args);
}
catch (libport::Error& e)
{
URBI_EXIT(EX_USAGE, ("command line error: %s", e.what()));
}
if (libport::opts::help.get())
help(parser);
if (libport::opts::version.get())
version();
#endif
data.interactive = IF_OPTION_PARSER(arg_interactive.get(), true);
data.fast = IF_OPTION_PARSER(arg_fast.get(), false);
#ifndef NO_OPTION_PARSER
foreach (const std::string& exp, arg_exps.get())
input.push_back(Input(false, exp));
foreach (const std::string& file, libport::opts::files.get())
input.push_back(Input(true, convert_input_file(file)));
arg_stack_size = arg_stack.get<size_t>(static_cast<size_t>(0));
// Unrecognized options. These are a script file, followed by user args.
if (!args.empty())
{
forbid_option(args[0]);
input.push_back(Input(true, convert_input_file(args[0])));
// Anything left is user argument
for (unsigned i = 1; i < args.size(); ++i)
{
std::string arg = args[i];
forbid_option(arg);
object::system_push_argument(arg);
}
}
}
#endif
// If not defined in command line, use the envvar.
if (IF_OPTION_PARSER(!arg_stack.filled() && , ) getenv("URBI_STACK_SIZE"))
arg_stack_size = libport::convert_envvar<size_t> ("URBI_STACK_SIZE");
if (arg_stack_size)
{
// Make sure the result is a multiple of the page size. This
// required at least on OSX (which unfortunately fails with errno
// = 0).
arg_stack_size *= 1024;
size_t pagesize = getpagesize();
arg_stack_size = ((arg_stack_size + pagesize - 1) / pagesize) * pagesize;
sched::configuration.default_stack_size = arg_stack_size;
}
data.server = new ConsoleServer(data.fast);
ConsoleServer& s = *data.server;
/*----------------.
| --port/--host. |
`----------------*/
int port = -1;
{
int desired_port = IF_OPTION_PARSER(libport::opts::port_l.get<int>(-1),
UAbstractClient::URBI_PORT);
if (desired_port != -1)
{
std::string host = IF_OPTION_PARSER(libport::opts::host_l.value(""),"");
if (boost::system::error_code err =
s.listen(&connectionFactory, host, desired_port))
URBI_EXIT(EX_UNAVAILABLE,
("cannot listen to port %s:%s: %s",
host, desired_port, err.message()));
port = s.getLocalPort();
// Port not allocated at all, or port differs from (non null)
// request.
if (!port
|| (desired_port && port != desired_port))
URBI_EXIT(EX_UNAVAILABLE,
("cannot listen to port %s:%s", host, desired_port));
}
}
data.network = 0 < port;
// In Urbi: System.listenPort = <port>.
object::system_class->slot_set(SYMBOL(listenPort),
object::to_urbi(port),
true);
s.initialize(data.interactive);
/*--------------.
| --port-file. |
`--------------*/
// Write the port file after initialize returned; that is, after
// urbi.u is loaded.
IF_OPTION_PARSER(
if (arg_port_file.filled())
std::ofstream(arg_port_file.value().c_str(), std::ios::out)
<< port << std::endl;,
)
kernel::UConnection& c = s.ghost_connection_get();
GD_INFO_TRACE("got ghost connection");
foreach (const Input& i, input)
{
// FIXME: We target s for files and c for strings.
if (i.file_p)
{
if (s.load_file(i.value, c.recv_queue_get()) != USUCCESS)
URBI_EXIT(EX_NOINPUT, ("failed to process file %s", i.value));
}
else
c.recv_queue_get().push(i.value.c_str());
}
c.received("");
GD_INFO_TRACE("going to work...");
if (sem)
(*sem)++;
return main_loop(data);
}
int
main_loop(LoopData& data)
{
ConsoleServer& s = *data.server;
libport::utime_t next_time = 0;
while (true)
{
if (data.interactive)
{
std::string input;
try
{
input = libport::read_stdin();
}
catch (const libport::exception::Exception& e)
{
std::cerr << libport::program_name() << ": "
<< e.what() << std::endl;
data.interactive = false;
}
if (!input.empty())
s.ghost_connection_get().received(input);
}
if (data.network)
{
libport::utime_t select_time = 0;
if (!data.fast)
{
select_time = std::max(next_time - libport::utime(), select_time);
if (data.interactive)
select_time = std::min(100000LL, select_time);
}
if (select_time)
libport::pollFor(select_time, true, s.get_io_service());
else
{
s.get_io_service().reset();
s.get_io_service().poll();
}
}
next_time = s.work();
if (next_time == sched::SCHED_EXIT)
break;
s.ctime = std::max(next_time, s.ctime + 1000L);
}
return EX_OK;
}
int
main(const libport::cli_args_type& _args, bool block, bool errors)
{
if (block)
return init(_args, errors, 0);
else
{
// The semaphore must survive this block, as init will use it when
// exiting.
libport::Semaphore* s = new libport::Semaphore;
libport::startThread(boost::bind(&init, boost::ref(_args),
errors, s));
(*s)--;
return 0;
}
}
}
|
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <libport/unistd.h>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <libport/cstring>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <libport/asio.hh>
#include <libport/cli.hh>
#include <libport/debug.hh>
#include <libport/exception.hh>
#include <libport/foreach.hh>
#include <libport/format.hh>
#ifndef NO_OPTION_PARSER
# include <libport/option-parser.hh>
# include <libport/tokenizer.hh>
# define IF_OPTION_PARSER(a, b) a
#else
#define IF_OPTION_PARSER(a, b) b
#endif
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/read-stdin.hh>
#include <libport/semaphore.hh>
#include <libport/sys/socket.h>
#include <libport/sysexits.hh>
#include <libport/thread.hh>
#include <libport/utime.hh>
#include <libport/windows.hh>
#include <libltdl/ltdl.h>
// Inclusion order matters for windows. Leave userver.hh after network.hh.
#include <kernel/uqueue.hh>
#include <kernel/userver.hh>
#include <kernel/uconnection.hh>
#include <sched/configuration.hh>
#include <sched/scheduler.hh>
#include <kernel/connection.hh>
#include <kernel/ubanner.hh>
#include <object/symbols.hh>
#include <object/object.hh>
#include <object/float.hh>
#include <object/system.hh>
#include <urbi/export.hh>
#include <urbi/umain.hh>
#include <urbi/uobject.hh>
GD_INIT();
GD_ADD_CATEGORY(URBI);
#define URBI_EXIT(Status, Args) \
throw urbi::Exit(Status, libport::format Args)
class ConsoleServer
: public kernel::UServer
, public libport::Socket
{
public:
ConsoleServer(bool fast)
: kernel::UServer("console")
, libport::Socket(kernel::UServer::get_io_service())
, fast(fast)
, ctime(0)
{}
virtual ~ConsoleServer()
{}
virtual void reset()
{}
virtual void reboot()
{}
virtual libport::utime_t getTime()
{
return fast ? ctime : libport::utime();
}
virtual
UErrorValue
save_file(const std::string& filename, const std::string& content)
{
//! \todo check this code
std::ofstream os(filename.c_str());
os << content;
os.close();
return os.good() ? USUCCESS : UFAIL;
}
virtual
void effectiveDisplay(const char* t)
{
std::cout << t;
}
boost::asio::io_service&
get_io_service()
{
return kernel::UServer::get_io_service();
}
bool fast;
libport::utime_t ctime;
};
namespace
{
#ifndef NO_OPTION_PARSER
static
void
help(libport::OptionParser& parser)
{
std::stringstream output;
output
<< "usage: " << libport::program_name()
<< " [OPTIONS] [PROGRAM_FILE | -- ] [ARGS...]" << std::endl
<< std::endl
<< " PROGRAM_FILE Urbi script to load."
<< " `-' stands for standard input" << std::endl
<< " ARGS user arguments passed to PROGRAM_FILE" << std::endl
<< parser;
throw urbi::Exit(EX_OK, output.str());
}
#endif
static
void
version()
{
throw urbi::Exit(EX_OK, kernel::UServer::package_info().signature());
}
static
void
forbid_option(const std::string& arg)
{
if (arg.size() > 1 && arg[0] == '-')
URBI_EXIT(EX_USAGE,
("unrecognized command line option: %s", arg));
}
}
namespace urbi
{
/// Command line options needed in the main loop.
struct LoopData
{
LoopData()
: interactive(false)
, fast(false)
, network(true)
, server(0)
{}
bool interactive;
bool fast;
/// Whether network connections are enabled.
bool network;
ConsoleServer* server;
};
int main_loop(LoopData& l);
static libport::Socket*
connectionFactory()
{
kernel::Connection* c = new kernel::Connection();
kernel::urbiserver->connection_add(c);
return c;
}
static std::string convert_input_file(const std::string& arg)
{
return (arg == "-") ? "/dev/stdin" : arg;
}
/// Data to send to the server.
struct Input
{
Input(bool f, const std::string& v)
: file_p(f), value(v)
{}
/// Whether it's a file (or a litteral).
bool file_p;
/// File name or litteral value.
std::string value;
};
static int
init(const libport::cli_args_type& _args, bool errors,
libport::Semaphore* sem)
{
libport::Finally f;
if (sem)
f << boost::bind(&libport::Semaphore::operator++, sem);
if (errors)
{
try
{
return init(_args, false, sem);
}
catch (const urbi::Exit& e)
{
std::cerr << libport::program_name() << ": " << e.what() << std::endl;
return e.error_get();
}
catch (const std::exception& e)
{
std::cerr << libport::program_name() << ": " << e.what() << std::endl;
return 1;
}
}
GD_CATEGORY(URBI);
libport::cli_args_type args = _args;
object::system_set_program_name(args[0]);
args.erase(args.begin());
#ifndef NO_OPTION_PARSER
// Detect shebang mode
if (!args.empty() && !args[0].empty() && args[0][1] == '-'
&& args[0].find_first_of(' ') != args[0].npos)
{ // All our arguments are in args[0]
std::string arg0(args[0]);
libport::cli_args_type nargs;
foreach(const std::string& arg, libport::make_tokenizer(arg0, " "))
nargs.push_back(arg);
for (size_t i = 1; i< args.size(); ++i)
nargs.push_back(args[i]);
args = nargs;
}
#endif
// Input files.
typedef std::vector<Input> input_type;
input_type input;
/// The size of the stacks.
size_t arg_stack_size = 0;
// Parse the command line.
LoopData data;
#ifndef NO_OPTION_PARSER
libport::OptionFlag
arg_fast("ignore system time, go as fast as possible",
"fast", 'F'),
arg_interactive("read and parse stdin in a nonblocking way",
"interactive", 'i'),
arg_no_net("ignored for backward compatibility", "no-network", 'n');
libport::OptionValue
arg_period ("ignored for backward compatibility", "period", 'P'),
arg_port_file("write port number to the specified file.",
"port-file", 'w', "FILE"),
arg_stack ("set the job stack size in KB", "stack-size", 's', "SIZE");
libport::OptionValues
arg_exps("run expression", "expression", 'e', "EXP");
libport::OptionsEnd arg_remaining(true);
{
libport::OptionParser parser;
parser
<< "Options:"
<< arg_fast
<< libport::opts::help
<< libport::opts::version
<< libport::opts::debug
<< arg_period
<< "Tuning:"
<< arg_stack
<< "Networking:"
<< libport::opts::host_l
<< libport::opts::port_l
<< arg_port_file
<< arg_no_net
<< "Execution:"
<< arg_exps
<< libport::opts::files
<< arg_interactive
<< arg_remaining
;
try
{
args = parser(args);
}
catch (libport::Error& e)
{
URBI_EXIT(EX_USAGE, ("command line error: %s", e.what()));
}
if (libport::opts::help.get())
help(parser);
if (libport::opts::version.get())
version();
#endif
data.interactive = IF_OPTION_PARSER(arg_interactive.get(), true);
data.fast = IF_OPTION_PARSER(arg_fast.get(), false);
#ifndef NO_OPTION_PARSER
foreach (const std::string& exp, arg_exps.get())
input.push_back(Input(false, exp));
foreach (const std::string& file, libport::opts::files.get())
input.push_back(Input(true, convert_input_file(file)));
arg_stack_size = arg_stack.get<size_t>(static_cast<size_t>(0));
// Since arg_remaining ate everything, args should be empty unless the user
// made a mistake
if (!args.empty())
forbid_option(args[0]);
// Unrecognized options. These are a script file, followed by user args.
// or '--' followed by user args.
libport::OptionsEnd::values_type remaining_args = arg_remaining.get();
if (!remaining_args.empty())
{
unsigned startPos = 0;
if (!arg_remaining.found_separator())
{ // first argument is an input file.
input.push_back(Input(true, convert_input_file(remaining_args[0])));
++startPos;
}
// Anything left is user argument
for (unsigned i = startPos; i < remaining_args.size(); ++i)
{
std::string arg = remaining_args[i];
object::system_push_argument(arg);
}
}
}
#endif
// If not defined in command line, use the envvar.
if (IF_OPTION_PARSER(!arg_stack.filled() && , ) getenv("URBI_STACK_SIZE"))
arg_stack_size = libport::convert_envvar<size_t> ("URBI_STACK_SIZE");
if (arg_stack_size)
{
// Make sure the result is a multiple of the page size. This
// required at least on OSX (which unfortunately fails with errno
// = 0).
arg_stack_size *= 1024;
size_t pagesize = getpagesize();
arg_stack_size = ((arg_stack_size + pagesize - 1) / pagesize) * pagesize;
sched::configuration.default_stack_size = arg_stack_size;
}
data.server = new ConsoleServer(data.fast);
ConsoleServer& s = *data.server;
/*----------------.
| --port/--host. |
`----------------*/
int port = -1;
{
int desired_port = IF_OPTION_PARSER(libport::opts::port_l.get<int>(-1),
UAbstractClient::URBI_PORT);
if (desired_port != -1)
{
std::string host = IF_OPTION_PARSER(libport::opts::host_l.value(""),"");
if (boost::system::error_code err =
s.listen(&connectionFactory, host, desired_port))
URBI_EXIT(EX_UNAVAILABLE,
("cannot listen to port %s:%s: %s",
host, desired_port, err.message()));
port = s.getLocalPort();
// Port not allocated at all, or port differs from (non null)
// request.
if (!port
|| (desired_port && port != desired_port))
URBI_EXIT(EX_UNAVAILABLE,
("cannot listen to port %s:%s", host, desired_port));
}
}
data.network = 0 < port;
// In Urbi: System.listenPort = <port>.
object::system_class->slot_set(SYMBOL(listenPort),
object::to_urbi(port),
true);
s.initialize(data.interactive);
/*--------------.
| --port-file. |
`--------------*/
// Write the port file after initialize returned; that is, after
// urbi.u is loaded.
IF_OPTION_PARSER(
if (arg_port_file.filled())
std::ofstream(arg_port_file.value().c_str(), std::ios::out)
<< port << std::endl;,
)
kernel::UConnection& c = s.ghost_connection_get();
GD_INFO_TRACE("got ghost connection");
foreach (const Input& i, input)
{
// FIXME: We target s for files and c for strings.
if (i.file_p)
{
if (s.load_file(i.value, c.recv_queue_get()) != USUCCESS)
URBI_EXIT(EX_NOINPUT, ("failed to process file %s", i.value));
}
else
c.recv_queue_get().push(i.value.c_str());
}
c.received("");
GD_INFO_TRACE("going to work...");
if (sem)
(*sem)++;
return main_loop(data);
}
int
main_loop(LoopData& data)
{
ConsoleServer& s = *data.server;
libport::utime_t next_time = 0;
while (true)
{
if (data.interactive)
{
std::string input;
try
{
input = libport::read_stdin();
}
catch (const libport::exception::Exception& e)
{
std::cerr << libport::program_name() << ": "
<< e.what() << std::endl;
data.interactive = false;
}
if (!input.empty())
s.ghost_connection_get().received(input);
}
if (data.network)
{
libport::utime_t select_time = 0;
if (!data.fast)
{
select_time = std::max(next_time - libport::utime(), select_time);
if (data.interactive)
select_time = std::min(100000LL, select_time);
}
if (select_time)
libport::pollFor(select_time, true, s.get_io_service());
else
{
s.get_io_service().reset();
s.get_io_service().poll();
}
}
next_time = s.work();
if (next_time == sched::SCHED_EXIT)
break;
s.ctime = std::max(next_time, s.ctime + 1000L);
}
return EX_OK;
}
int
main(const libport::cli_args_type& _args, bool block, bool errors)
{
if (block)
return init(_args, errors, 0);
else
{
// The semaphore must survive this block, as init will use it when
// exiting.
libport::Semaphore* s = new libport::Semaphore;
libport::startThread(boost::bind(&init, boost::ref(_args),
errors, s));
(*s)--;
return 0;
}
}
}
|
Improve command-line parsing to handle '--' and shebang mode.
|
main: Improve command-line parsing to handle '--' and shebang mode.
* src/console-server.cc (init): Use libport::OptionEnd to gather
all args after '--' or at the first non-option argument. Also
split argv[1] on ' ' if it contains spaces and starts with '-'.
|
C++
|
bsd-3-clause
|
urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi
|
4968c3668e69058754834128e635524cca59b32a
|
src/console-server.cc
|
src/console-server.cc
|
//#define ENABLE_DEBUG_TRACES
#include "libport/compiler.hh"
#include "libport/unistd.h"
#include "libport/sysexits.hh"
#include "libport/windows.hh"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <boost/foreach.hpp>
#include "libport/cli.hh"
#include "libport/program-name.hh"
#include "libport/tokenizer.hh"
#include "libport/utime.hh"
#include "libport/read-stdin.hh"
#include "libport/exception.hh"
// Inclusion order matters for windows. Leave userver.hh after network.hh.
#include <network/bsdnet/network.hh>
#include "kernel/userver.hh"
#include "kernel/uconnection.hh"
#include "ubanner.hh"
class ConsoleServer
: public UServer
{
public:
ConsoleServer(bool fast)
: UServer("console"), fast(fast), ctime(0)
{
if (const char* cp = getenv ("URBI_PATH"))
{
std::string up(cp);
std::list<std::string> paths;
BOOST_FOREACH (const std::string& s, libport::make_tokenizer(up, ":"))
{
if (s[0] == '\\' && paths.back().length() == 1)
paths.back() += ':' + s;
else
paths.push_back(s);
}
BOOST_FOREACH (const std::string& s, paths)
search_path.append_dir(s);
}
}
virtual ~ConsoleServer()
{}
virtual void shutdown()
{
UServer::shutdown ();
exit (EX_OK);
}
virtual void beforeWork()
{
}
virtual void reset()
{}
virtual void reboot()
{}
virtual libport::utime_t getTime()
{
return fast ? ctime : libport::utime();
}
virtual ufloat getPower()
{
return ufloat(1);
}
//! Called to display the header at each coonection start
virtual void getCustomHeader(int line, char* header, int maxlength)
{
// FIXME: This interface is really really ridiculous and fragile.
strncpy(header, uconsole_banner[line], maxlength);
}
virtual
UErrorValue
saveFile (const std::string& filename, const std::string& content)
{
//! \todo check this code
std::ofstream os (filename.c_str ());
os << content;
os.close ();
return os.good () ? USUCCESS : UFAIL;
}
virtual
void effectiveDisplay(const char* t)
{
std::cout << t;
}
bool fast;
libport::utime_t ctime;
};
namespace
{
static
void
usage ()
{
std::cout <<
"usage: " << libport::program_name << " [OPTIONS] [FILE]\n"
"\n"
" FILE to load\n"
"\n"
"Options:\n"
" -h, --help display this message and exit successfully\n"
" -v, --version display version information\n"
" -P, --period PERIOD ignored for backward compatibility\n"
" -p, --port PORT tcp port URBI will listen to.\n"
" -f, --fast ignore system time, go as fast as possible\n"
" -i, --interactive read and parse stdin in a nonblocking way\n"
" -w, --port-file FILE write port number to specified file.\n"
;
exit (EX_OK);
}
static
void
version ()
{
userver_package_info_dump(std::cout) << std::endl;
exit (EX_OK);
}
}
int
main (int argc, const char* argv[])
{
libport::program_name = argv[0];
// Input file.
const char* in = "/dev/stdin";
/// The port to use. 0 means automatic selection.
int arg_port = 0;
/// Where to write the port we use.
const char* arg_port_filename = 0;
/// fast mode
bool fast = false;
/// interactive mode
bool interactive = false;
// Parse the command line.
{
int argp = 1;
for (int i = 1; i < argc; ++i)
{
std::string arg = argv[i];
if (arg == "--fast" || arg == "-f")
fast = true;
else if (arg == "--help" || arg == "-h")
usage();
else if (arg == "--interactive" || arg == "-i")
interactive = true;
else if (arg == "--period" || arg == "-P")
(void) libport::convert_argument<int> (arg, argv[++i]);
else if (arg == "--port" || arg == "-p")
arg_port = libport::convert_argument<int> (arg, argv[++i]);
else if (arg == "--port-file" || arg == "-w")
arg_port_filename = argv[++i];
else if (arg == "--version" || arg == "-v")
version();
else if (arg[0] == '-')
libport::invalid_option (arg);
else
// An argument.
switch (argp++)
{
case 1:
in = argv[i];
break;
default:
std::cerr << libport::program_name
<< ": unexpected argument: " << arg << std::endl
<< libport::exit (EX_USAGE);
break;
}
}
}
ConsoleServer s (fast);
int port = Network::createTCPServer(arg_port, "localhost");
if (!port)
std::cerr << libport::program_name
<< ": cannot bind to port " << arg_port
<< " on localhost" << std::endl
<< libport::exit (EX_UNAVAILABLE);
if (arg_port_filename)
std::ofstream(arg_port_filename, std::ios::out) << port << std::endl;
s.initialize ();
UConnection& c = s.getGhostConnection ();
std::cerr << libport::program_name
<< ": got ghost connection" << std::endl;
if (!interactive)
if (s.loadFile(in, c.recv_queue_get ()) != USUCCESS)
std::cerr << libport::program_name
<< ": failed to process " << in << std::endl
<< libport::exit(EX_NOINPUT);
c.new_data_added_get() = true;
std::cerr << libport::program_name << ": going to work..." << std::endl;
libport::utime_t next_time = 0;
while (true)
{
if (interactive)
{
std::string input;
try
{
input = libport::read_stdin();
}
catch(libport::exception::Exception e)
{
std::cerr << e.what() << std::endl;
interactive = false;
}
if (!input.empty())
s.getGhostConnection ().received (input.c_str(), input.length());
}
libport::utime_t select_time = 0;
if (!fast)
{
libport::utime_t ctime = libport::utime();
if (ctime < next_time)
select_time = next_time - ctime;
if (interactive)
select_time = std::min(100000LL, select_time);
}
Network::selectAndProcess(select_time);
next_time = s.work ();
s.ctime = std::max (next_time, s.ctime + 1000L);
}
}
|
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <libport/unistd.h>
#include <libport/sysexits.hh>
#include <libport/windows.hh>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <boost/foreach.hpp>
#include <libport/cli.hh>
#include <libport/program-name.hh>
#include <libport/tokenizer.hh>
#include <libport/utime.hh>
#include <libport/read-stdin.hh>
#include <libport/exception.hh>
// Inclusion order matters for windows. Leave userver.hh after network.hh.
#include <network/bsdnet/network.hh>
#include "kernel/userver.hh"
#include "kernel/uconnection.hh"
#include "ubanner.hh"
class ConsoleServer
: public UServer
{
public:
ConsoleServer(bool fast)
: UServer("console"), fast(fast), ctime(0)
{
if (const char* cp = getenv ("URBI_PATH"))
{
std::string up(cp);
std::list<std::string> paths;
BOOST_FOREACH (const std::string& s, libport::make_tokenizer(up, ":"))
{
if (s[0] == '\\' && paths.back().length() == 1)
paths.back() += ':' + s;
else
paths.push_back(s);
}
BOOST_FOREACH (const std::string& s, paths)
search_path.append_dir(s);
}
}
virtual ~ConsoleServer()
{}
virtual void shutdown()
{
UServer::shutdown ();
exit (EX_OK);
}
virtual void beforeWork()
{
}
virtual void reset()
{}
virtual void reboot()
{}
virtual libport::utime_t getTime()
{
return fast ? ctime : libport::utime();
}
virtual ufloat getPower()
{
return ufloat(1);
}
//! Called to display the header at each coonection start
virtual void getCustomHeader(int line, char* header, int maxlength)
{
// FIXME: This interface is really really ridiculous and fragile.
strncpy(header, uconsole_banner[line], maxlength);
}
virtual
UErrorValue
saveFile (const std::string& filename, const std::string& content)
{
//! \todo check this code
std::ofstream os (filename.c_str ());
os << content;
os.close ();
return os.good () ? USUCCESS : UFAIL;
}
virtual
void effectiveDisplay(const char* t)
{
std::cout << t;
}
bool fast;
libport::utime_t ctime;
};
namespace
{
static
void
usage ()
{
std::cout <<
"usage: " << libport::program_name << " [OPTIONS] [FILE]\n"
"\n"
" FILE to load\n"
"\n"
"Options:\n"
" -h, --help display this message and exit successfully\n"
" -v, --version display version information\n"
" -P, --period PERIOD ignored for backward compatibility\n"
" -p, --port PORT tcp port URBI will listen to.\n"
" -f, --fast ignore system time, go as fast as possible\n"
" -i, --interactive read and parse stdin in a nonblocking way\n"
" -w, --port-file FILE write port number to specified file.\n"
;
exit (EX_OK);
}
static
void
version ()
{
userver_package_info_dump(std::cout) << std::endl;
exit (EX_OK);
}
}
int
main (int argc, const char* argv[])
{
libport::program_name = argv[0];
// Input file.
const char* in = "/dev/stdin";
/// The port to use. 0 means automatic selection.
int arg_port = 0;
/// Where to write the port we use.
const char* arg_port_filename = 0;
/// fast mode
bool fast = false;
/// interactive mode
bool interactive = false;
// Parse the command line.
{
int argp = 1;
for (int i = 1; i < argc; ++i)
{
std::string arg = argv[i];
if (arg == "--fast" || arg == "-f")
fast = true;
else if (arg == "--help" || arg == "-h")
usage();
else if (arg == "--interactive" || arg == "-i")
interactive = true;
else if (arg == "--period" || arg == "-P")
(void) libport::convert_argument<int> (arg, argv[++i]);
else if (arg == "--port" || arg == "-p")
arg_port = libport::convert_argument<int> (arg, argv[++i]);
else if (arg == "--port-file" || arg == "-w")
arg_port_filename = argv[++i];
else if (arg == "--version" || arg == "-v")
version();
else if (arg[0] == '-')
libport::invalid_option (arg);
else
// An argument.
switch (argp++)
{
case 1:
in = argv[i];
break;
default:
std::cerr << libport::program_name
<< ": unexpected argument: " << arg << std::endl
<< libport::exit (EX_USAGE);
break;
}
}
}
ConsoleServer s (fast);
int port = Network::createTCPServer(arg_port, "localhost");
if (!port)
std::cerr << libport::program_name
<< ": cannot bind to port " << arg_port
<< " on localhost" << std::endl
<< libport::exit (EX_UNAVAILABLE);
if (arg_port_filename)
std::ofstream(arg_port_filename, std::ios::out) << port << std::endl;
s.initialize ();
UConnection& c = s.getGhostConnection ();
std::cerr << libport::program_name
<< ": got ghost connection" << std::endl;
if (!interactive)
if (s.loadFile(in, c.recv_queue_get ()) != USUCCESS)
std::cerr << libport::program_name
<< ": failed to process " << in << std::endl
<< libport::exit(EX_NOINPUT);
c.new_data_added_get() = true;
std::cerr << libport::program_name << ": going to work..." << std::endl;
libport::utime_t next_time = 0;
while (true)
{
if (interactive)
{
std::string input;
try
{
input = libport::read_stdin();
}
catch(libport::exception::Exception e)
{
std::cerr << e.what() << std::endl;
interactive = false;
}
if (!input.empty())
s.getGhostConnection ().received (input.c_str(), input.length());
}
libport::utime_t select_time = 0;
if (!fast)
{
libport::utime_t ctime = libport::utime();
if (ctime < next_time)
select_time = next_time - ctime;
if (interactive)
select_time = std::min(100000LL, select_time);
}
Network::selectAndProcess(select_time);
next_time = s.work ();
s.ctime = std::max (next_time, s.ctime + 1000L);
}
}
|
Use <> for libport.
|
Use <> for libport.
* src/console-server.cc: Use include <> for libport headers.
|
C++
|
bsd-3-clause
|
urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi
|
cf7a60947e372cdd0b7f3f19a024353439893a1c
|
C++/minimum-depth-of-binary-tree.cpp
|
C++/minimum-depth-of-binary-tree.cpp
|
// Time: O(n)
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int minDepth(TreeNode *root) {
if (root == nullptr) {
return 0;
}
// Both children exist.
if (root->left != nullptr && root->right != nullptr) {
return 1 + min(minDepth(root->left), minDepth(root->right));
}
else {
return 1 + max(minDepth(root->left), minDepth(root->right));
}
}
};
|
// Time: O(n)
// Space: O(h)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int minDepth(TreeNode *root) {
if (root == nullptr) {
return 0;
}
// Both children exist.
if (root->left != nullptr && root->right != nullptr) {
return 1 + min(minDepth(root->left), minDepth(root->right));
}
else {
return 1 + max(minDepth(root->left), minDepth(root->right));
}
}
};
|
Update minimum-depth-of-binary-tree.cpp
|
Update minimum-depth-of-binary-tree.cpp
|
C++
|
mit
|
jaredkoontz/lintcode,kamyu104/LintCode,kamyu104/LintCode,jaredkoontz/lintcode,kamyu104/LintCode,jaredkoontz/lintcode
|
d4d26f07dd3e82d83811f3f018460f364630e40c
|
C++Tutorials/Step_5/S5_Fibonacci.cpp
|
C++Tutorials/Step_5/S5_Fibonacci.cpp
|
#include <iostream>
using namespace std;
int Fibonacci(int n)
{
if (n==0)
return 0;
if (n==1)
return 1;
return( Fibonacci(n-2) + Fibonacci(n-1) );
}
int main(){
int n;
cout << "Enter a number" << endl;
cin >> n;
cout<< Fibonacci(n) << endl;
}
|
//
// Program Name - S5_Fibonacci.cpp
// Series: GetOnToC++ Step: 5
//
// Purpose: This program uses recursion to return a Fibonacci number
//
// Compile: g++ S5_Fibonacci.cpp -o S5_Fibonacci
// Execute: ./S5_Fibonacci
//
// Created by Narayan Mahadevan on 18/08/13.
//
#include <iostream>
using namespace std;
int Fibonacci(int n)
{
if (n==0)
return 0;
if (n==1)
return 1;
return( Fibonacci(n-2) + Fibonacci(n-1) );
}
int main(){
int n;
cout << "Enter a number" << endl;
cin >> n;
cout<< Fibonacci(n) << endl;
}
|
Update S5_Fibonacci.cpp
|
Update S5_Fibonacci.cpp
|
C++
|
apache-2.0
|
NarayanMahadevan/MakeTechEz
|
bb2c0f577facd75547ee7277334a79250e8b83b9
|
src/delegate/Glue.cxx
|
src/delegate/Glue.cxx
|
/*
* This helper library glues delegate_stock and delegate_client
* together.
*
* author: Max Kellermann <[email protected]>
*/
#include "Glue.hxx"
#include "Client.hxx"
#include "Handler.hxx"
#include "Stock.hxx"
#include "stock/Item.hxx"
#include "stock/MapStock.hxx"
#include "lease.hxx"
#include "pool.hxx"
#include "util/Cancellable.hxx"
#include <daemon/log.h>
#include <errno.h>
struct DelegateGlue final : Lease {
StockItem &item;
explicit DelegateGlue(StockItem &_item):item(_item) {}
/* virtual methods from class Lease */
void ReleaseLease(bool reuse) override {
item.Put(!reuse);
}
};
void
delegate_stock_open(StockMap *stock, struct pool *pool,
const char *helper,
const ChildOptions &options,
const char *path,
DelegateHandler &handler,
CancellablePointer &cancel_ptr)
{
GError *error = nullptr;
auto *item = delegate_stock_get(stock, pool, helper, options, &error);
if (item == nullptr) {
handler.OnDelegateError(error);
return;
}
auto glue = NewFromPool<DelegateGlue>(*pool, *item);
delegate_open(stock->GetEventLoop(), delegate_stock_item_get(*item), *glue,
pool, path,
handler, cancel_ptr);
}
|
/*
* This helper library glues delegate_stock and delegate_client
* together.
*
* author: Max Kellermann <[email protected]>
*/
#include "Glue.hxx"
#include "Client.hxx"
#include "Handler.hxx"
#include "Stock.hxx"
#include "stock/Item.hxx"
#include "stock/MapStock.hxx"
#include "lease.hxx"
#include "pool.hxx"
struct DelegateGlue final : Lease {
StockItem &item;
explicit DelegateGlue(StockItem &_item):item(_item) {}
/* virtual methods from class Lease */
void ReleaseLease(bool reuse) override {
item.Put(!reuse);
}
};
void
delegate_stock_open(StockMap *stock, struct pool *pool,
const char *helper,
const ChildOptions &options,
const char *path,
DelegateHandler &handler,
CancellablePointer &cancel_ptr)
{
GError *error = nullptr;
auto *item = delegate_stock_get(stock, pool, helper, options, &error);
if (item == nullptr) {
handler.OnDelegateError(error);
return;
}
auto glue = NewFromPool<DelegateGlue>(*pool, *item);
delegate_open(stock->GetEventLoop(), delegate_stock_item_get(*item), *glue,
pool, path,
handler, cancel_ptr);
}
|
include cleanup
|
delegate: include cleanup
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
999c14894fd39367443656bd9dbb61fd8f3c7075
|
src/dev/dma_device.cc
|
src/dev/dma_device.cc
|
/*
* Copyright (c) 2012, 2015, 2017 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Nathan Binkert
* Andreas Hansson
* Andreas Sandberg
*/
#include "dev/dma_device.hh"
#include <utility>
#include "base/chunk_generator.hh"
#include "debug/DMA.hh"
#include "debug/Drain.hh"
#include "mem/port_proxy.hh"
#include "sim/system.hh"
DmaPort::DmaPort(MemObject *dev, System *s)
: MasterPort(dev->name() + ".dma", dev),
device(dev), sys(s), masterId(s->getMasterId(dev->name())),
sendEvent([this]{ sendDma(); }, dev->name()),
pendingCount(0), inRetry(false)
{ }
void
DmaPort::handleResp(PacketPtr pkt, Tick delay)
{
// should always see a response with a sender state
assert(pkt->isResponse());
// get the DMA sender state
DmaReqState *state = dynamic_cast<DmaReqState*>(pkt->senderState);
assert(state);
DPRINTF(DMA, "Received response %s for addr: %#x size: %d nb: %d," \
" tot: %d sched %d\n",
pkt->cmdString(), pkt->getAddr(), pkt->req->getSize(),
state->numBytes, state->totBytes,
state->completionEvent ?
state->completionEvent->scheduled() : 0);
assert(pendingCount != 0);
pendingCount--;
// update the number of bytes received based on the request rather
// than the packet as the latter could be rounded up to line sizes
state->numBytes += pkt->req->getSize();
assert(state->totBytes >= state->numBytes);
// if we have reached the total number of bytes for this DMA
// request, then signal the completion and delete the sate
if (state->totBytes == state->numBytes) {
if (state->completionEvent) {
delay += state->delay;
device->schedule(state->completionEvent, curTick() + delay);
}
delete state;
}
// delete the request that we created and also the packet
delete pkt->req;
delete pkt;
// we might be drained at this point, if so signal the drain event
if (pendingCount == 0)
signalDrainDone();
}
bool
DmaPort::recvTimingResp(PacketPtr pkt)
{
// We shouldn't ever get a cacheable block in Modified state
assert(pkt->req->isUncacheable() ||
!(pkt->cacheResponding() && !pkt->hasSharers()));
handleResp(pkt);
return true;
}
DmaDevice::DmaDevice(const Params *p)
: PioDevice(p), dmaPort(this, sys)
{ }
void
DmaDevice::init()
{
if (!dmaPort.isConnected())
panic("DMA port of %s not connected to anything!", name());
PioDevice::init();
}
DrainState
DmaPort::drain()
{
if (pendingCount == 0) {
return DrainState::Drained;
} else {
DPRINTF(Drain, "DmaPort not drained\n");
return DrainState::Draining;
}
}
void
DmaPort::recvReqRetry()
{
assert(transmitList.size());
trySendTimingReq();
}
RequestPtr
DmaPort::dmaAction(Packet::Command cmd, Addr addr, int size, Event *event,
uint8_t *data, Tick delay, Request::Flags flag)
{
// one DMA request sender state for every action, that is then
// split into many requests and packets based on the block size,
// i.e. cache line size
DmaReqState *reqState = new DmaReqState(event, size, delay);
// (functionality added for Table Walker statistics)
// We're only interested in this when there will only be one request.
// For simplicity, we return the last request, which would also be
// the only request in that case.
RequestPtr req = NULL;
DPRINTF(DMA, "Starting DMA for addr: %#x size: %d sched: %d\n", addr, size,
event ? event->scheduled() : -1);
for (ChunkGenerator gen(addr, size, sys->cacheLineSize());
!gen.done(); gen.next()) {
req = new Request(gen.addr(), gen.size(), flag, masterId);
req->taskId(ContextSwitchTaskId::DMA);
PacketPtr pkt = new Packet(req, cmd);
// Increment the data pointer on a write
if (data)
pkt->dataStatic(data + gen.complete());
pkt->senderState = reqState;
DPRINTF(DMA, "--Queuing DMA for addr: %#x size: %d\n", gen.addr(),
gen.size());
queueDma(pkt);
}
// in zero time also initiate the sending of the packets we have
// just created, for atomic this involves actually completing all
// the requests
sendDma();
return req;
}
void
DmaPort::queueDma(PacketPtr pkt)
{
transmitList.push_back(pkt);
// remember that we have another packet pending, this will only be
// decremented once a response comes back
pendingCount++;
}
void
DmaPort::trySendTimingReq()
{
// send the first packet on the transmit list and schedule the
// following send if it is successful
PacketPtr pkt = transmitList.front();
DPRINTF(DMA, "Trying to send %s addr %#x\n", pkt->cmdString(),
pkt->getAddr());
inRetry = !sendTimingReq(pkt);
if (!inRetry) {
transmitList.pop_front();
DPRINTF(DMA, "-- Done\n");
// if there is more to do, then do so
if (!transmitList.empty())
// this should ultimately wait for as many cycles as the
// device needs to send the packet, but currently the port
// does not have any known width so simply wait a single
// cycle
device->schedule(sendEvent, device->clockEdge(Cycles(1)));
} else {
DPRINTF(DMA, "-- Failed, waiting for retry\n");
}
DPRINTF(DMA, "TransmitList: %d, inRetry: %d\n",
transmitList.size(), inRetry);
}
void
DmaPort::sendDma()
{
// some kind of selcetion between access methods
// more work is going to have to be done to make
// switching actually work
assert(transmitList.size());
if (sys->isTimingMode()) {
// if we are either waiting for a retry or are still waiting
// after sending the last packet, then do not proceed
if (inRetry || sendEvent.scheduled()) {
DPRINTF(DMA, "Can't send immediately, waiting to send\n");
return;
}
trySendTimingReq();
} else if (sys->isAtomicMode()) {
// send everything there is to send in zero time
while (!transmitList.empty()) {
PacketPtr pkt = transmitList.front();
transmitList.pop_front();
DPRINTF(DMA, "Sending DMA for addr: %#x size: %d\n",
pkt->req->getPaddr(), pkt->req->getSize());
Tick lat = sendAtomic(pkt);
handleResp(pkt, lat);
}
} else
panic("Unknown memory mode.");
}
BaseMasterPort &
DmaDevice::getMasterPort(const std::string &if_name, PortID idx)
{
if (if_name == "dma") {
return dmaPort;
}
return PioDevice::getMasterPort(if_name, idx);
}
DmaReadFifo::DmaReadFifo(DmaPort &_port, size_t size,
unsigned max_req_size,
unsigned max_pending,
Request::Flags flags)
: maxReqSize(max_req_size), fifoSize(size),
reqFlags(flags), port(_port),
buffer(size),
nextAddr(0), endAddr(0)
{
freeRequests.resize(max_pending);
for (auto &e : freeRequests)
e.reset(new DmaDoneEvent(this, max_req_size));
}
DmaReadFifo::~DmaReadFifo()
{
for (auto &p : pendingRequests) {
DmaDoneEvent *e(p.release());
if (e->done()) {
delete e;
} else {
// We can't kill in-flight DMAs, so we'll just transfer
// ownership to the event queue so that they get freed
// when they are done.
e->kill();
}
}
}
void
DmaReadFifo::serialize(CheckpointOut &cp) const
{
assert(pendingRequests.empty());
SERIALIZE_CONTAINER(buffer);
SERIALIZE_SCALAR(endAddr);
SERIALIZE_SCALAR(nextAddr);
}
void
DmaReadFifo::unserialize(CheckpointIn &cp)
{
UNSERIALIZE_CONTAINER(buffer);
UNSERIALIZE_SCALAR(endAddr);
UNSERIALIZE_SCALAR(nextAddr);
}
bool
DmaReadFifo::tryGet(uint8_t *dst, size_t len)
{
if (buffer.size() >= len) {
buffer.read(dst, len);
resumeFill();
return true;
} else {
return false;
}
}
void
DmaReadFifo::get(uint8_t *dst, size_t len)
{
const bool success(tryGet(dst, len));
panic_if(!success, "Buffer underrun in DmaReadFifo::get()\n");
}
void
DmaReadFifo::startFill(Addr start, size_t size)
{
assert(atEndOfBlock());
nextAddr = start;
endAddr = start + size;
resumeFill();
}
void
DmaReadFifo::stopFill()
{
// Prevent new DMA requests by setting the next address to the end
// address. Pending requests will still complete.
nextAddr = endAddr;
// Flag in-flight accesses as canceled. This prevents their data
// from being written to the FIFO.
for (auto &p : pendingRequests)
p->cancel();
}
void
DmaReadFifo::resumeFill()
{
// Don't try to fetch more data if we are draining. This ensures
// that the DMA engine settles down before we checkpoint it.
if (drainState() == DrainState::Draining)
return;
const bool old_eob(atEndOfBlock());
if (port.sys->bypassCaches())
resumeFillFunctional();
else
resumeFillTiming();
if (!old_eob && atEndOfBlock())
onEndOfBlock();
}
void
DmaReadFifo::resumeFillFunctional()
{
const size_t fifo_space = buffer.capacity() - buffer.size();
const size_t kvm_watermark = port.sys->cacheLineSize();
if (fifo_space >= kvm_watermark || buffer.capacity() < kvm_watermark) {
const size_t block_remaining = endAddr - nextAddr;
const size_t xfer_size = std::min(fifo_space, block_remaining);
std::vector<uint8_t> tmp_buffer(xfer_size);
assert(pendingRequests.empty());
DPRINTF(DMA, "KVM Bypassing startAddr=%#x xfer_size=%#x " \
"fifo_space=%#x block_remaining=%#x\n",
nextAddr, xfer_size, fifo_space, block_remaining);
port.sys->physProxy.readBlob(nextAddr, tmp_buffer.data(), xfer_size);
buffer.write(tmp_buffer.begin(), xfer_size);
nextAddr += xfer_size;
}
}
void
DmaReadFifo::resumeFillTiming()
{
size_t size_pending(0);
for (auto &e : pendingRequests)
size_pending += e->requestSize();
while (!freeRequests.empty() && !atEndOfBlock()) {
const size_t req_size(std::min(maxReqSize, endAddr - nextAddr));
if (buffer.size() + size_pending + req_size > fifoSize)
break;
DmaDoneEventUPtr event(std::move(freeRequests.front()));
freeRequests.pop_front();
assert(event);
event->reset(req_size);
port.dmaAction(MemCmd::ReadReq, nextAddr, req_size, event.get(),
event->data(), 0, reqFlags);
nextAddr += req_size;
size_pending += req_size;
pendingRequests.emplace_back(std::move(event));
}
}
void
DmaReadFifo::dmaDone()
{
const bool old_active(isActive());
handlePending();
resumeFill();
if (!old_active && isActive())
onIdle();
}
void
DmaReadFifo::handlePending()
{
while (!pendingRequests.empty() && pendingRequests.front()->done()) {
// Get the first finished pending request
DmaDoneEventUPtr event(std::move(pendingRequests.front()));
pendingRequests.pop_front();
if (!event->canceled())
buffer.write(event->data(), event->requestSize());
// Move the event to the list of free requests
freeRequests.emplace_back(std::move(event));
}
if (pendingRequests.empty())
signalDrainDone();
}
DrainState
DmaReadFifo::drain()
{
return pendingRequests.empty() ? DrainState::Drained : DrainState::Draining;
}
DmaReadFifo::DmaDoneEvent::DmaDoneEvent(DmaReadFifo *_parent,
size_t max_size)
: parent(_parent), _done(false), _canceled(false), _data(max_size, 0)
{
}
void
DmaReadFifo::DmaDoneEvent::kill()
{
parent = nullptr;
setFlags(AutoDelete);
}
void
DmaReadFifo::DmaDoneEvent::cancel()
{
_canceled = true;
}
void
DmaReadFifo::DmaDoneEvent::reset(size_t size)
{
assert(size <= _data.size());
_done = false;
_canceled = false;
_requestSize = size;
}
void
DmaReadFifo::DmaDoneEvent::process()
{
if (!parent)
return;
assert(!_done);
_done = true;
parent->dmaDone();
}
|
/*
* Copyright (c) 2012, 2015, 2017 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Nathan Binkert
* Andreas Hansson
* Andreas Sandberg
*/
#include "dev/dma_device.hh"
#include <utility>
#include "base/chunk_generator.hh"
#include "debug/DMA.hh"
#include "debug/Drain.hh"
#include "mem/port_proxy.hh"
#include "sim/system.hh"
DmaPort::DmaPort(MemObject *dev, System *s)
: MasterPort(dev->name() + ".dma", dev),
device(dev), sys(s), masterId(s->getMasterId(dev->name())),
sendEvent([this]{ sendDma(); }, dev->name()),
pendingCount(0), inRetry(false)
{ }
void
DmaPort::handleResp(PacketPtr pkt, Tick delay)
{
// should always see a response with a sender state
assert(pkt->isResponse());
// get the DMA sender state
DmaReqState *state = dynamic_cast<DmaReqState*>(pkt->senderState);
assert(state);
DPRINTF(DMA, "Received response %s for addr: %#x size: %d nb: %d," \
" tot: %d sched %d\n",
pkt->cmdString(), pkt->getAddr(), pkt->req->getSize(),
state->numBytes, state->totBytes,
state->completionEvent ?
state->completionEvent->scheduled() : 0);
assert(pendingCount != 0);
pendingCount--;
// update the number of bytes received based on the request rather
// than the packet as the latter could be rounded up to line sizes
state->numBytes += pkt->req->getSize();
assert(state->totBytes >= state->numBytes);
// if we have reached the total number of bytes for this DMA
// request, then signal the completion and delete the sate
if (state->totBytes == state->numBytes) {
if (state->completionEvent) {
delay += state->delay;
device->schedule(state->completionEvent, curTick() + delay);
}
delete state;
}
// delete the request that we created and also the packet
delete pkt->req;
delete pkt;
// we might be drained at this point, if so signal the drain event
if (pendingCount == 0)
signalDrainDone();
}
bool
DmaPort::recvTimingResp(PacketPtr pkt)
{
// We shouldn't ever get a cacheable block in Modified state
assert(pkt->req->isUncacheable() ||
!(pkt->cacheResponding() && !pkt->hasSharers()));
handleResp(pkt);
return true;
}
DmaDevice::DmaDevice(const Params *p)
: PioDevice(p), dmaPort(this, sys)
{ }
void
DmaDevice::init()
{
if (!dmaPort.isConnected())
panic("DMA port of %s not connected to anything!", name());
PioDevice::init();
}
DrainState
DmaPort::drain()
{
if (pendingCount == 0) {
return DrainState::Drained;
} else {
DPRINTF(Drain, "DmaPort not drained\n");
return DrainState::Draining;
}
}
void
DmaPort::recvReqRetry()
{
assert(transmitList.size());
trySendTimingReq();
}
RequestPtr
DmaPort::dmaAction(Packet::Command cmd, Addr addr, int size, Event *event,
uint8_t *data, Tick delay, Request::Flags flag)
{
// one DMA request sender state for every action, that is then
// split into many requests and packets based on the block size,
// i.e. cache line size
DmaReqState *reqState = new DmaReqState(event, size, delay);
// (functionality added for Table Walker statistics)
// We're only interested in this when there will only be one request.
// For simplicity, we return the last request, which would also be
// the only request in that case.
RequestPtr req = NULL;
DPRINTF(DMA, "Starting DMA for addr: %#x size: %d sched: %d\n", addr, size,
event ? event->scheduled() : -1);
for (ChunkGenerator gen(addr, size, sys->cacheLineSize());
!gen.done(); gen.next()) {
req = new Request(gen.addr(), gen.size(), flag, masterId);
req->taskId(ContextSwitchTaskId::DMA);
PacketPtr pkt = new Packet(req, cmd);
// Increment the data pointer on a write
if (data)
pkt->dataStatic(data + gen.complete());
pkt->senderState = reqState;
DPRINTF(DMA, "--Queuing DMA for addr: %#x size: %d\n", gen.addr(),
gen.size());
queueDma(pkt);
}
// in zero time also initiate the sending of the packets we have
// just created, for atomic this involves actually completing all
// the requests
sendDma();
return req;
}
void
DmaPort::queueDma(PacketPtr pkt)
{
transmitList.push_back(pkt);
// remember that we have another packet pending, this will only be
// decremented once a response comes back
pendingCount++;
}
void
DmaPort::trySendTimingReq()
{
// send the first packet on the transmit list and schedule the
// following send if it is successful
PacketPtr pkt = transmitList.front();
DPRINTF(DMA, "Trying to send %s addr %#x\n", pkt->cmdString(),
pkt->getAddr());
inRetry = !sendTimingReq(pkt);
if (!inRetry) {
transmitList.pop_front();
DPRINTF(DMA, "-- Done\n");
// if there is more to do, then do so
if (!transmitList.empty())
// this should ultimately wait for as many cycles as the
// device needs to send the packet, but currently the port
// does not have any known width so simply wait a single
// cycle
device->schedule(sendEvent, device->clockEdge(Cycles(1)));
} else {
DPRINTF(DMA, "-- Failed, waiting for retry\n");
}
DPRINTF(DMA, "TransmitList: %d, inRetry: %d\n",
transmitList.size(), inRetry);
}
void
DmaPort::sendDma()
{
// some kind of selcetion between access methods
// more work is going to have to be done to make
// switching actually work
assert(transmitList.size());
if (sys->isTimingMode()) {
// if we are either waiting for a retry or are still waiting
// after sending the last packet, then do not proceed
if (inRetry || sendEvent.scheduled()) {
DPRINTF(DMA, "Can't send immediately, waiting to send\n");
return;
}
trySendTimingReq();
} else if (sys->isAtomicMode()) {
// send everything there is to send in zero time
while (!transmitList.empty()) {
PacketPtr pkt = transmitList.front();
transmitList.pop_front();
DPRINTF(DMA, "Sending DMA for addr: %#x size: %d\n",
pkt->req->getPaddr(), pkt->req->getSize());
Tick lat = sendAtomic(pkt);
handleResp(pkt, lat);
}
} else
panic("Unknown memory mode.");
}
BaseMasterPort &
DmaDevice::getMasterPort(const std::string &if_name, PortID idx)
{
if (if_name == "dma") {
return dmaPort;
}
return PioDevice::getMasterPort(if_name, idx);
}
DmaReadFifo::DmaReadFifo(DmaPort &_port, size_t size,
unsigned max_req_size,
unsigned max_pending,
Request::Flags flags)
: maxReqSize(max_req_size), fifoSize(size),
reqFlags(flags), port(_port),
buffer(size),
nextAddr(0), endAddr(0)
{
freeRequests.resize(max_pending);
for (auto &e : freeRequests)
e.reset(new DmaDoneEvent(this, max_req_size));
}
DmaReadFifo::~DmaReadFifo()
{
for (auto &p : pendingRequests) {
DmaDoneEvent *e(p.release());
if (e->done()) {
delete e;
} else {
// We can't kill in-flight DMAs, so we'll just transfer
// ownership to the event queue so that they get freed
// when they are done.
e->kill();
}
}
}
void
DmaReadFifo::serialize(CheckpointOut &cp) const
{
assert(pendingRequests.empty());
SERIALIZE_CONTAINER(buffer);
SERIALIZE_SCALAR(endAddr);
SERIALIZE_SCALAR(nextAddr);
}
void
DmaReadFifo::unserialize(CheckpointIn &cp)
{
UNSERIALIZE_CONTAINER(buffer);
UNSERIALIZE_SCALAR(endAddr);
UNSERIALIZE_SCALAR(nextAddr);
}
bool
DmaReadFifo::tryGet(uint8_t *dst, size_t len)
{
if (buffer.size() >= len) {
buffer.read(dst, len);
resumeFill();
return true;
} else {
return false;
}
}
void
DmaReadFifo::get(uint8_t *dst, size_t len)
{
const bool success(tryGet(dst, len));
panic_if(!success, "Buffer underrun in DmaReadFifo::get()\n");
}
void
DmaReadFifo::startFill(Addr start, size_t size)
{
assert(atEndOfBlock());
nextAddr = start;
endAddr = start + size;
resumeFill();
}
void
DmaReadFifo::stopFill()
{
// Prevent new DMA requests by setting the next address to the end
// address. Pending requests will still complete.
nextAddr = endAddr;
// Flag in-flight accesses as canceled. This prevents their data
// from being written to the FIFO.
for (auto &p : pendingRequests)
p->cancel();
}
void
DmaReadFifo::resumeFill()
{
// Don't try to fetch more data if we are draining. This ensures
// that the DMA engine settles down before we checkpoint it.
if (drainState() == DrainState::Draining)
return;
const bool old_eob(atEndOfBlock());
if (port.sys->bypassCaches())
resumeFillFunctional();
else
resumeFillTiming();
if (!old_eob && atEndOfBlock())
onEndOfBlock();
}
void
DmaReadFifo::resumeFillFunctional()
{
const size_t fifo_space = buffer.capacity() - buffer.size();
const size_t kvm_watermark = port.sys->cacheLineSize();
if (fifo_space >= kvm_watermark || buffer.capacity() < kvm_watermark) {
const size_t block_remaining = endAddr - nextAddr;
const size_t xfer_size = std::min(fifo_space, block_remaining);
std::vector<uint8_t> tmp_buffer(xfer_size);
assert(pendingRequests.empty());
DPRINTF(DMA, "KVM Bypassing startAddr=%#x xfer_size=%#x " \
"fifo_space=%#x block_remaining=%#x\n",
nextAddr, xfer_size, fifo_space, block_remaining);
port.sys->physProxy.readBlob(nextAddr, tmp_buffer.data(), xfer_size);
buffer.write(tmp_buffer.begin(), xfer_size);
nextAddr += xfer_size;
}
}
void
DmaReadFifo::resumeFillTiming()
{
size_t size_pending(0);
for (auto &e : pendingRequests)
size_pending += e->requestSize();
while (!freeRequests.empty() && !atEndOfBlock()) {
const size_t req_size(std::min(maxReqSize, endAddr - nextAddr));
if (buffer.size() + size_pending + req_size > fifoSize)
break;
DmaDoneEventUPtr event(std::move(freeRequests.front()));
freeRequests.pop_front();
assert(event);
event->reset(req_size);
port.dmaAction(MemCmd::ReadReq, nextAddr, req_size, event.get(),
event->data(), 0, reqFlags);
nextAddr += req_size;
size_pending += req_size;
pendingRequests.emplace_back(std::move(event));
}
}
void
DmaReadFifo::dmaDone()
{
const bool old_active(isActive());
handlePending();
resumeFill();
if (old_active && !isActive())
onIdle();
}
void
DmaReadFifo::handlePending()
{
while (!pendingRequests.empty() && pendingRequests.front()->done()) {
// Get the first finished pending request
DmaDoneEventUPtr event(std::move(pendingRequests.front()));
pendingRequests.pop_front();
if (!event->canceled())
buffer.write(event->data(), event->requestSize());
// Move the event to the list of free requests
freeRequests.emplace_back(std::move(event));
}
if (pendingRequests.empty())
signalDrainDone();
}
DrainState
DmaReadFifo::drain()
{
return pendingRequests.empty() ? DrainState::Drained : DrainState::Draining;
}
DmaReadFifo::DmaDoneEvent::DmaDoneEvent(DmaReadFifo *_parent,
size_t max_size)
: parent(_parent), _done(false), _canceled(false), _data(max_size, 0)
{
}
void
DmaReadFifo::DmaDoneEvent::kill()
{
parent = nullptr;
setFlags(AutoDelete);
}
void
DmaReadFifo::DmaDoneEvent::cancel()
{
_canceled = true;
}
void
DmaReadFifo::DmaDoneEvent::reset(size_t size)
{
assert(size <= _data.size());
_done = false;
_canceled = false;
_requestSize = size;
}
void
DmaReadFifo::DmaDoneEvent::process()
{
if (!parent)
return;
assert(!_done);
_done = true;
parent->dmaDone();
}
|
Fix OnIdle test in DmaReadFifo
|
dev: Fix OnIdle test in DmaReadFifo
OnIdle() is never called since DMA active check is completely
opposite to what it should be. old active status should be 'true'
and new active status should be false for OnIdle to be called
Change-Id: I94eca50edbe96113190837c7f6e50a0d061158a6
Reported-by: Rohit Kurup <[email protected]>
Signed-off-by: Rohit Kurup <[email protected]>
Signed-off-by: Andreas Sandberg <[email protected]>
Reviewed-on: https://gem5-review.googlesource.com/3966
Reviewed-by: Michael LeBeane <[email protected]>
|
C++
|
bsd-3-clause
|
gem5/gem5,sobercoder/gem5,TUD-OS/gem5-dtu,gem5/gem5,rallylee/gem5,sobercoder/gem5,sobercoder/gem5,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,gem5/gem5,sobercoder/gem5,rallylee/gem5,sobercoder/gem5,rallylee/gem5,rallylee/gem5,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,rallylee/gem5,rallylee/gem5,sobercoder/gem5,gem5/gem5,gem5/gem5,rallylee/gem5,TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,sobercoder/gem5
|
7384cf4dbccf42b56cd88f16e2d8308e8280f13e
|
ada_server/SSLContainer.cpp
|
ada_server/SSLContainer.cpp
|
/**
* @file SSLContainer.cpp
*
* @brief implementation of SSLContainer class
*
* @author Matus Blaho
* @version 1.0
*/
#include "SSLContainer.h"
SSLContainer::SSLContainer(Loger *l)
{
l->WriteMessage(TRACE,"Entering " + this->_Name + "::Constructor");
this->_log=l;
this->container = new std::map <unsigned long long int, tadapter*>();
this->_log->WriteMessage(TRACE,"Exiting " + this->_Name + "::Constructor");
}
SSLContainer::~SSLContainer()
{
this->_log->WriteMessage(TRACE,"Entering " + this->_Name + "::Destructor");
for (std::map<unsigned long long int, tadapter *>::iterator it = this->container->begin(); it != this->container->end(); ++it)
{
close(SSL_get_fd(it->second->connection));
SSL_shutdown(it->second->connection);
SSL_free(it->second->connection);
it->second->connection = nullptr;
delete it->second;
}
delete container;
this->_log->WriteMessage(TRACE,"Exiting " + this->_Name + "::Destructor");
}
void SSLContainer::InsertSSL(unsigned long long adapterID,SSL *ssl,float cp)
{
this->_log->WriteMessage(TRACE,"Entering " + this->_Name + "::InsertSSL");
tadapter *adapter;
try
{
adapter = container->at(adapterID);
this->_log->WriteMessage(DEBUG,"Adapter found rewriting data");
close(SSL_get_fd(adapter->connection));
delete adapter->connection;
adapter->connection = ssl;
adapter->protocol_version = cp;
}
catch (const std::exception &e)
{
this->_log->WriteMessage(DEBUG,"Inserting new adapter");
adapter = new tadapter(ssl,cp);
container->insert(std::pair<unsigned long long int,tadapter*>(adapterID,adapter));
}
this->_log->WriteMessage(TRACE,"Exiting " + this->_Name + "::InsertSSL");
}
tadapter* SSLContainer::GetSSL(unsigned long long adapter)
{
this->_log->WriteMessage(TRACE,"Entering " + this->_Name + "::GetSSL");
try
{
return container->at(adapter);
}
catch (const std::exception &e)
{
this->_log->WriteMessage(WARN,"Adapter not found");
}
this->_log->WriteMessage(TRACE,"Exiting " + this->_Name + "::GetSSL");
return nullptr;
}
|
/**
* @file SSLContainer.cpp
*
* @brief implementation of SSLContainer class
*
* @author Matus Blaho
* @version 1.0
*/
#include "SSLContainer.h"
#include "ping.h"
SSLContainer::SSLContainer(Loger *l)
{
l->WriteMessage(TRACE,"Entering " + this->_Name + "::Constructor");
this->_log=l;
this->container = new std::map <unsigned long long int, tadapter*>();
this->_log->WriteMessage(TRACE,"Exiting " + this->_Name + "::Constructor");
}
SSLContainer::~SSLContainer()
{
this->_log->WriteMessage(TRACE,"Entering " + this->_Name + "::Destructor");
for (std::map<unsigned long long int, tadapter *>::iterator it = this->container->begin(); it != this->container->end(); ++it)
{
close(SSL_get_fd(it->second->connection));
SSL_shutdown(it->second->connection);
SSL_free(it->second->connection);
it->second->connection = nullptr;
delete it->second;
}
delete container;
this->_log->WriteMessage(TRACE,"Exiting " + this->_Name + "::Destructor");
}
void SSLContainer::InsertSSL(unsigned long long adapterID,SSL *ssl,float cp)
{
this->_log->WriteMessage(TRACE,"Entering " + this->_Name + "::InsertSSL");
tadapter *adapter;
try
{
adapter = container->at(adapterID);
this->_log->WriteMessage(DEBUG,"Adapter found rewriting data");
close(SSL_get_fd(adapter->connection));
delete adapter->connection;
adapter->connection = ssl;
adapter->protocol_version = cp;
}
catch (const std::exception &e)
{
this->_log->WriteMessage(DEBUG,"Inserting new adapter");
adapter = new tadapter(ssl,cp);
container->insert(std::pair<unsigned long long int,tadapter*>(adapterID,adapter));
}
PingService *ping;
ping = PingService::getInstance();
ping->setStatus(adapterID, "available");
this->_log->WriteMessage(TRACE,"Exiting " + this->_Name + "::InsertSSL");
}
tadapter* SSLContainer::GetSSL(unsigned long long adapter)
{
this->_log->WriteMessage(TRACE,"Entering " + this->_Name + "::GetSSL");
try
{
return container->at(adapter);
}
catch (const std::exception &e)
{
PingService *single;
single = PingService::getInstance();
single->setStatus(adapter, "unavailable");
this->_log->WriteMessage(WARN,"Adapter not found");
}
this->_log->WriteMessage(TRACE,"Exiting " + this->_Name + "::GetSSL");
return nullptr;
}
|
set gateway availability when connecting to server
|
ada_server: set gateway availability when connecting to server
A gateway is considered to be available on its connection
to the server. On the other hand, it is considered
unavailable when a gateway is not connected to the server.
Acked-by: Jan Viktorin <[email protected]>
|
C++
|
bsd-3-clause
|
BeeeOn/server,BeeeOn/server,BeeeOn/server,BeeeOn/server
|
fffb9c8a2cafb359b1a894ffdbe7e2aa8c2168ee
|
Contractor/EdgeBasedGraphFactory.cpp
|
Contractor/EdgeBasedGraphFactory.cpp
|
/*
open source routing machine
Copyright (C) Dennis Luxen, others 2010
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
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 Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/agpl.txt.
*/
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include "../Util/OpenMPReplacement.h"
#include "EdgeBasedGraphFactory.h"
template<>
EdgeBasedGraphFactory::EdgeBasedGraphFactory(int nodes, std::vector<NodeBasedEdge> & inputEdges, std::vector<NodeID> & bn, std::vector<NodeID> & tl, std::vector<_Restriction> & irs, std::vector<NodeInfo> & nI, boost::property_tree::ptree speedProfile, std::string & srtm) : inputNodeInfoList(nI), numberOfTurnRestrictions(irs.size()), trafficSignalPenalty(0) {
INFO("Nodes size: " << inputNodeInfoList.size());
BOOST_FOREACH(_Restriction & restriction, irs) {
std::pair<NodeID, NodeID> restrictionSource = std::make_pair(restriction.fromNode, restriction.viaNode);
unsigned index;
RestrictionMap::iterator restrIter = _restrictionMap.find(restrictionSource);
if(restrIter == _restrictionMap.end()) {
index = _restrictionBucketVector.size();
_restrictionBucketVector.resize(index+1);
_restrictionMap[restrictionSource] = index;
} else {
index = restrIter->second;
//Map already contains an is_only_*-restriction
if(_restrictionBucketVector.at(index).begin()->second)
continue;
else if(restriction.flags.isOnly){
//We are going to insert an is_only_*-restriction. There can be only one.
_restrictionBucketVector.at(index).clear();
}
}
_restrictionBucketVector.at(index).push_back(std::make_pair(restriction.toNode, restriction.flags.isOnly));
}
std::string usedSpeedProfile(speedProfile.get_child("").begin()->first);
BOOST_FOREACH(boost::property_tree::ptree::value_type &v, speedProfile.get_child(usedSpeedProfile)) {
if("trafficSignalPenalty" == v.first) {
std::string value = v.second.get<std::string>("");
try {
trafficSignalPenalty = 10*boost::lexical_cast<int>(v.second.get<std::string>(""));
} catch(boost::bad_lexical_cast &) {
trafficSignalPenalty = 0;
}
}
}
INFO("traffic signal penalty: " << trafficSignalPenalty);
BOOST_FOREACH(NodeID id, bn)
_barrierNodes[id] = true;
BOOST_FOREACH(NodeID id, tl)
_trafficLights[id] = true;
std::vector< _NodeBasedEdge > edges;
edges.reserve( 2 * inputEdges.size() );
for ( std::vector< NodeBasedEdge >::const_iterator i = inputEdges.begin(), e = inputEdges.end(); i != e; ++i ) {
_NodeBasedEdge edge;
edge.source = i->source();
edge.target = i->target();
if(edge.source == edge.target)
continue;
edge.data.distance = (std::max)((int)i->weight(), 1 );
assert( edge.data.distance > 0 );
edge.data.shortcut = false;
edge.data.roundabout = i->isRoundabout();
edge.data.ignoreInGrid = i->ignoreInGrid();
edge.data.nameID = i->name();
edge.data.type = i->type();
edge.data.forward = i->isForward();
edge.data.backward = i->isBackward();
edge.data.edgeBasedNodeID = edges.size();
edges.push_back( edge );
if( edge.data.backward ) {
std::swap( edge.source, edge.target );
edge.data.forward = i->isBackward();
edge.data.backward = i->isForward();
edge.data.edgeBasedNodeID = edges.size();
edges.push_back( edge );
}
}
sort( edges.begin(), edges.end() );
_nodeBasedGraph.reset(new _NodeBasedDynamicGraph( nodes, edges ));
INFO("Converted " << inputEdges.size() << " node-based edges into " << _nodeBasedGraph->GetNumberOfEdges() << " edge-based nodes.");
}
template<>
void EdgeBasedGraphFactory::GetEdgeBasedEdges( std::vector< EdgeBasedEdge >& outputEdgeList ) {
GUARANTEE(0 == outputEdgeList.size(), "Vector passed to EdgeBasedGraphFactory::GetEdgeBasedEdges(..) is not empty");
GUARANTEE(0 != edgeBasedEdges.size(), "No edges in edge based graph");
edgeBasedEdges.swap(outputEdgeList);
}
void EdgeBasedGraphFactory::GetEdgeBasedNodes( std::vector< EdgeBasedNode> & nodes) {
BOOST_FOREACH(EdgeBasedNode & node, edgeBasedNodes){
assert(node.lat1 != INT_MAX); assert(node.lon1 != INT_MAX);
assert(node.lat2 != INT_MAX); assert(node.lon2 != INT_MAX);
}
nodes.swap(edgeBasedNodes);
}
NodeID EdgeBasedGraphFactory::CheckForEmanatingIsOnlyTurn(const NodeID u, const NodeID v) const {
std::pair < NodeID, NodeID > restrictionSource = std::make_pair(u, v);
RestrictionMap::const_iterator restrIter = _restrictionMap.find(restrictionSource);
if (restrIter != _restrictionMap.end()) {
unsigned index = restrIter->second;
BOOST_FOREACH(RestrictionSource restrictionTarget, _restrictionBucketVector.at(index)) {
if(restrictionTarget.second) {
return restrictionTarget.first;
}
}
}
return UINT_MAX;
}
bool EdgeBasedGraphFactory::CheckIfTurnIsRestricted(const NodeID u, const NodeID v, const NodeID w) const {
//only add an edge if turn is not a U-turn except it is the end of dead-end street.
std::pair < NodeID, NodeID > restrictionSource = std::make_pair(u, v);
RestrictionMap::const_iterator restrIter = _restrictionMap.find(restrictionSource);
if (restrIter != _restrictionMap.end()) {
unsigned index = restrIter->second;
BOOST_FOREACH(RestrictionTarget restrictionTarget, _restrictionBucketVector.at(index)) {
if(w == restrictionTarget.first)
return true;
}
}
return false;
}
void EdgeBasedGraphFactory::InsertEdgeBasedNode(
_NodeBasedDynamicGraph::EdgeIterator e1,
_NodeBasedDynamicGraph::NodeIterator u,
_NodeBasedDynamicGraph::NodeIterator v) {
_NodeBasedDynamicGraph::EdgeData & data = _nodeBasedGraph->GetEdgeData(e1);
EdgeBasedNode currentNode;
currentNode.nameID = data.nameID;
currentNode.lat1 = inputNodeInfoList[u].lat;
currentNode.lon1 = inputNodeInfoList[u].lon;
currentNode.lat2 = inputNodeInfoList[v].lat;
currentNode.lon2 = inputNodeInfoList[v].lon;
currentNode.id = data.edgeBasedNodeID;
currentNode.ignoreInGrid = data.ignoreInGrid;
currentNode.weight = data.distance;
//currentNode.weight += ComputeHeightPenalty(u, v);
edgeBasedNodes.push_back(currentNode);
}
void EdgeBasedGraphFactory::Run() {
INFO("Generating edge based representation of input data");
edgeBasedNodes.reserve(_nodeBasedGraph->GetNumberOfEdges());
Percent p(_nodeBasedGraph->GetNumberOfNodes());
int numberOfSkippedTurns(0);
int nodeBasedEdgeCounter(0);
//loop over all edges and generate new set of nodes.
for(_NodeBasedDynamicGraph::NodeIterator u = 0; u < _nodeBasedGraph->GetNumberOfNodes(); ++u ) {
for(_NodeBasedDynamicGraph::EdgeIterator e1 = _nodeBasedGraph->BeginEdges(u); e1 < _nodeBasedGraph->EndEdges(u); ++e1) {
_NodeBasedDynamicGraph::NodeIterator v = _nodeBasedGraph->GetTarget(e1);
if(_nodeBasedGraph->GetEdgeData(e1).type != SHRT_MAX) {
assert(e1 != UINT_MAX);
assert(u != UINT_MAX);
assert(v != UINT_MAX);
InsertEdgeBasedNode(e1, u, v);
}
}
}
//Loop over all turns and generate new set of edges.
//Three nested loop look super-linear, but we are dealing with a linear number of turns only.
for(_NodeBasedDynamicGraph::NodeIterator u = 0; u < _nodeBasedGraph->GetNumberOfNodes(); ++u ) {
for(_NodeBasedDynamicGraph::EdgeIterator e1 = _nodeBasedGraph->BeginEdges(u); e1 < _nodeBasedGraph->EndEdges(u); ++e1) {
_NodeBasedDynamicGraph::NodeIterator v = _nodeBasedGraph->GetTarget(e1);
//EdgeWeight heightPenalty = ComputeHeightPenalty(u, v);
NodeID onlyToNode = CheckForEmanatingIsOnlyTurn(u, v);
for(_NodeBasedDynamicGraph::EdgeIterator e2 = _nodeBasedGraph->BeginEdges(v); e2 < _nodeBasedGraph->EndEdges(v); ++e2) {
_NodeBasedDynamicGraph::NodeIterator w = _nodeBasedGraph->GetTarget(e2);
if(onlyToNode != UINT_MAX && w != onlyToNode) { //We are at an only_-restriction but not at the right turn.
++numberOfSkippedTurns;
continue;
}
bool isBollardNode = (_barrierNodes.find(v) != _barrierNodes.end());
if( (!isBollardNode && (u != w || 1 == _nodeBasedGraph->GetOutDegree(v))) || ((u == w) && isBollardNode)) { //only add an edge if turn is not a U-turn except it is the end of dead-end street.
if (!CheckIfTurnIsRestricted(u, v, w) || (onlyToNode != UINT_MAX && w == onlyToNode)) { //only add an edge if turn is not prohibited
const _NodeBasedDynamicGraph::EdgeData edgeData1 = _nodeBasedGraph->GetEdgeData(e1);
const _NodeBasedDynamicGraph::EdgeData edgeData2 = _nodeBasedGraph->GetEdgeData(e2);
assert(edgeData1.edgeBasedNodeID < _nodeBasedGraph->GetNumberOfEdges());
assert(edgeData2.edgeBasedNodeID < _nodeBasedGraph->GetNumberOfEdges());
unsigned distance = edgeData1.distance;
//distance += heightPenalty;
//distance += ComputeTurnPenalty(u, v, w);
if(_trafficLights.find(v) != _trafficLights.end()) {
distance += trafficSignalPenalty;
}
short turnInstruction = AnalyzeTurn(u, v, w);
assert(edgeData1.edgeBasedNodeID != edgeData2.edgeBasedNodeID);
EdgeBasedEdge newEdge(edgeData1.edgeBasedNodeID, edgeData2.edgeBasedNodeID, v, edgeData2.nameID, distance, true, false, turnInstruction);
edgeBasedEdges.push_back(newEdge);
++nodeBasedEdgeCounter;
} else {
++numberOfSkippedTurns;
}
}
}
}
p.printIncrement();
}
std::sort(edgeBasedNodes.begin(), edgeBasedNodes.end());
edgeBasedNodes.erase( std::unique(edgeBasedNodes.begin(), edgeBasedNodes.end()), edgeBasedNodes.end() );
INFO("Node-based graph contains " << nodeBasedEdgeCounter << " edges");
INFO("Edge-based graph contains " << edgeBasedEdges.size() << " edges, blowup is " << (double)edgeBasedEdges.size()/(double)nodeBasedEdgeCounter);
INFO("Edge-based graph skipped " << numberOfSkippedTurns << " turns, defined by " << numberOfTurnRestrictions << " restrictions.");
INFO("Generated " << edgeBasedNodes.size() << " edge based nodes");
}
short EdgeBasedGraphFactory::AnalyzeTurn(const NodeID u, const NodeID v, const NodeID w) const {
if(u == w) {
return TurnInstructions.UTurn;
}
_NodeBasedDynamicGraph::EdgeIterator edge1 = _nodeBasedGraph->FindEdge(u, v);
_NodeBasedDynamicGraph::EdgeIterator edge2 = _nodeBasedGraph->FindEdge(v, w);
_NodeBasedDynamicGraph::EdgeData & data1 = _nodeBasedGraph->GetEdgeData(edge1);
_NodeBasedDynamicGraph::EdgeData & data2 = _nodeBasedGraph->GetEdgeData(edge2);
//roundabouts need to be handled explicitely
if(data1.roundabout && data2.roundabout) {
//Is a turn possible? If yes, we stay on the roundabout!
if( 1 == (_nodeBasedGraph->EndEdges(v) - _nodeBasedGraph->BeginEdges(v)) ) {
//No turn possible.
return TurnInstructions.NoTurn;
} else {
return TurnInstructions.StayOnRoundAbout;
}
}
//Does turn start or end on roundabout?
if(data1.roundabout || data2.roundabout) {
//We are entering the roundabout
if( (!data1.roundabout) && data2.roundabout)
return TurnInstructions.EnterRoundAbout;
//We are leaving the roundabout
if(data1.roundabout && (!data2.roundabout) )
return TurnInstructions.LeaveRoundAbout;
}
//If street names stay the same and if we are certain that it is not a roundabout, we skip it.
if( (data1.nameID == data2.nameID) && (0 != data1.nameID))
return TurnInstructions.NoTurn;
if( (data1.nameID == data2.nameID) && (0 == data1.nameID) && (_nodeBasedGraph->GetOutDegree(v) <= 2) )
return TurnInstructions.NoTurn;
double angle = GetAngleBetweenTwoEdges(inputNodeInfoList[u], inputNodeInfoList[v], inputNodeInfoList[w]);
return TurnInstructions.GetTurnDirectionOfInstruction(angle);
}
unsigned EdgeBasedGraphFactory::GetNumberOfNodes() const {
return _nodeBasedGraph->GetNumberOfEdges();
}
/* Get angle of line segment (A,C)->(C,B), atan2 magic, formerly cosine theorem*/
template<class CoordinateT>
double EdgeBasedGraphFactory::GetAngleBetweenTwoEdges(const CoordinateT& A, const CoordinateT& C, const CoordinateT& B) const {
const int v1x = A.lon - C.lon;
const int v1y = A.lat - C.lat;
const int v2x = B.lon - C.lon;
const int v2y = B.lat - C.lat;
double angle = (atan2((double)v2y,v2x) - atan2((double)v1y,v1x) )*180/M_PI;
while(angle < 0)
angle += 360;
return angle;
}
|
/*
open source routing machine
Copyright (C) Dennis Luxen, others 2010
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
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 Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/agpl.txt.
*/
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include "../Util/OpenMPReplacement.h"
#include "EdgeBasedGraphFactory.h"
template<>
EdgeBasedGraphFactory::EdgeBasedGraphFactory(int nodes, std::vector<NodeBasedEdge> & inputEdges, std::vector<NodeID> & bn, std::vector<NodeID> & tl, std::vector<_Restriction> & irs, std::vector<NodeInfo> & nI, boost::property_tree::ptree speedProfile, std::string & srtm) : inputNodeInfoList(nI), numberOfTurnRestrictions(irs.size()), trafficSignalPenalty(0) {
INFO("Nodes size: " << inputNodeInfoList.size());
BOOST_FOREACH(_Restriction & restriction, irs) {
std::pair<NodeID, NodeID> restrictionSource = std::make_pair(restriction.fromNode, restriction.viaNode);
unsigned index;
RestrictionMap::iterator restrIter = _restrictionMap.find(restrictionSource);
if(restrIter == _restrictionMap.end()) {
index = _restrictionBucketVector.size();
_restrictionBucketVector.resize(index+1);
_restrictionMap[restrictionSource] = index;
} else {
index = restrIter->second;
//Map already contains an is_only_*-restriction
if(_restrictionBucketVector.at(index).begin()->second)
continue;
else if(restriction.flags.isOnly){
//We are going to insert an is_only_*-restriction. There can be only one.
_restrictionBucketVector.at(index).clear();
}
}
_restrictionBucketVector.at(index).push_back(std::make_pair(restriction.toNode, restriction.flags.isOnly));
}
std::string usedSpeedProfile(speedProfile.get_child("").begin()->first);
BOOST_FOREACH(boost::property_tree::ptree::value_type &v, speedProfile.get_child(usedSpeedProfile)) {
if("trafficSignalPenalty" == v.first) {
std::string value = v.second.get<std::string>("");
try {
trafficSignalPenalty = 10*boost::lexical_cast<int>(v.second.get<std::string>(""));
} catch(boost::bad_lexical_cast &) {
trafficSignalPenalty = 0;
}
}
}
INFO("traffic signal penalty: " << trafficSignalPenalty);
BOOST_FOREACH(NodeID id, bn)
_barrierNodes[id] = true;
BOOST_FOREACH(NodeID id, tl)
_trafficLights[id] = true;
std::vector< _NodeBasedEdge > edges;
edges.reserve( 2 * inputEdges.size() );
for ( std::vector< NodeBasedEdge >::const_iterator i = inputEdges.begin(), e = inputEdges.end(); i != e; ++i ) {
_NodeBasedEdge edge;
edge.source = i->source();
edge.target = i->target();
if(edge.source == edge.target)
continue;
edge.data.distance = (std::max)((int)i->weight(), 1 );
assert( edge.data.distance > 0 );
edge.data.shortcut = false;
edge.data.roundabout = i->isRoundabout();
edge.data.ignoreInGrid = i->ignoreInGrid();
edge.data.nameID = i->name();
edge.data.type = i->type();
edge.data.forward = i->isForward();
edge.data.backward = i->isBackward();
edge.data.edgeBasedNodeID = edges.size();
edges.push_back( edge );
if( edge.data.backward ) {
std::swap( edge.source, edge.target );
edge.data.forward = i->isBackward();
edge.data.backward = i->isForward();
edge.data.edgeBasedNodeID = edges.size();
edges.push_back( edge );
}
}
sort( edges.begin(), edges.end() );
_nodeBasedGraph.reset(new _NodeBasedDynamicGraph( nodes, edges ));
INFO("Converted " << inputEdges.size() << " node-based edges into " << _nodeBasedGraph->GetNumberOfEdges() << " edge-based nodes.");
}
template<>
void EdgeBasedGraphFactory::GetEdgeBasedEdges( std::vector< EdgeBasedEdge >& outputEdgeList ) {
GUARANTEE(0 == outputEdgeList.size(), "Vector passed to EdgeBasedGraphFactory::GetEdgeBasedEdges(..) is not empty");
GUARANTEE(0 != edgeBasedEdges.size(), "No edges in edge based graph");
edgeBasedEdges.swap(outputEdgeList);
}
void EdgeBasedGraphFactory::GetEdgeBasedNodes( std::vector< EdgeBasedNode> & nodes) {
BOOST_FOREACH(EdgeBasedNode & node, edgeBasedNodes){
assert(node.lat1 != INT_MAX); assert(node.lon1 != INT_MAX);
assert(node.lat2 != INT_MAX); assert(node.lon2 != INT_MAX);
}
nodes.swap(edgeBasedNodes);
}
NodeID EdgeBasedGraphFactory::CheckForEmanatingIsOnlyTurn(const NodeID u, const NodeID v) const {
std::pair < NodeID, NodeID > restrictionSource = std::make_pair(u, v);
RestrictionMap::const_iterator restrIter = _restrictionMap.find(restrictionSource);
if (restrIter != _restrictionMap.end()) {
unsigned index = restrIter->second;
BOOST_FOREACH(RestrictionSource restrictionTarget, _restrictionBucketVector.at(index)) {
if(restrictionTarget.second) {
return restrictionTarget.first;
}
}
}
return UINT_MAX;
}
bool EdgeBasedGraphFactory::CheckIfTurnIsRestricted(const NodeID u, const NodeID v, const NodeID w) const {
//only add an edge if turn is not a U-turn except it is the end of dead-end street.
std::pair < NodeID, NodeID > restrictionSource = std::make_pair(u, v);
RestrictionMap::const_iterator restrIter = _restrictionMap.find(restrictionSource);
if (restrIter != _restrictionMap.end()) {
unsigned index = restrIter->second;
BOOST_FOREACH(RestrictionTarget restrictionTarget, _restrictionBucketVector.at(index)) {
if(w == restrictionTarget.first)
return true;
}
}
return false;
}
void EdgeBasedGraphFactory::InsertEdgeBasedNode(
_NodeBasedDynamicGraph::EdgeIterator e1,
_NodeBasedDynamicGraph::NodeIterator u,
_NodeBasedDynamicGraph::NodeIterator v) {
_NodeBasedDynamicGraph::EdgeData & data = _nodeBasedGraph->GetEdgeData(e1);
EdgeBasedNode currentNode;
currentNode.nameID = data.nameID;
currentNode.lat1 = inputNodeInfoList[u].lat;
currentNode.lon1 = inputNodeInfoList[u].lon;
currentNode.lat2 = inputNodeInfoList[v].lat;
currentNode.lon2 = inputNodeInfoList[v].lon;
currentNode.id = data.edgeBasedNodeID;
currentNode.ignoreInGrid = data.ignoreInGrid;
currentNode.weight = data.distance;
//currentNode.weight += ComputeHeightPenalty(u, v);
edgeBasedNodes.push_back(currentNode);
}
void EdgeBasedGraphFactory::Run() {
INFO("Generating edge based representation of input data");
edgeBasedNodes.reserve(_nodeBasedGraph->GetNumberOfEdges());
Percent p(_nodeBasedGraph->GetNumberOfNodes());
int numberOfSkippedTurns(0);
int nodeBasedEdgeCounter(0);
//loop over all edges and generate new set of nodes.
for(_NodeBasedDynamicGraph::NodeIterator u = 0; u < _nodeBasedGraph->GetNumberOfNodes(); ++u ) {
for(_NodeBasedDynamicGraph::EdgeIterator e1 = _nodeBasedGraph->BeginEdges(u); e1 < _nodeBasedGraph->EndEdges(u); ++e1) {
_NodeBasedDynamicGraph::NodeIterator v = _nodeBasedGraph->GetTarget(e1);
if(_nodeBasedGraph->GetEdgeData(e1).type != SHRT_MAX) {
assert(e1 != UINT_MAX);
assert(u != UINT_MAX);
assert(v != UINT_MAX);
InsertEdgeBasedNode(e1, u, v);
}
}
}
//Loop over all turns and generate new set of edges.
//Three nested loop look super-linear, but we are dealing with a linear number of turns only.
for(_NodeBasedDynamicGraph::NodeIterator u = 0; u < _nodeBasedGraph->GetNumberOfNodes(); ++u ) {
for(_NodeBasedDynamicGraph::EdgeIterator e1 = _nodeBasedGraph->BeginEdges(u); e1 < _nodeBasedGraph->EndEdges(u); ++e1) {
++nodeBasedEdgeCounter;
_NodeBasedDynamicGraph::NodeIterator v = _nodeBasedGraph->GetTarget(e1);
//EdgeWeight heightPenalty = ComputeHeightPenalty(u, v);
NodeID onlyToNode = CheckForEmanatingIsOnlyTurn(u, v);
for(_NodeBasedDynamicGraph::EdgeIterator e2 = _nodeBasedGraph->BeginEdges(v); e2 < _nodeBasedGraph->EndEdges(v); ++e2) {
_NodeBasedDynamicGraph::NodeIterator w = _nodeBasedGraph->GetTarget(e2);
if(onlyToNode != UINT_MAX && w != onlyToNode) { //We are at an only_-restriction but not at the right turn.
++numberOfSkippedTurns;
continue;
}
bool isBollardNode = (_barrierNodes.find(v) != _barrierNodes.end());
if( (!isBollardNode && (u != w || 1 == _nodeBasedGraph->GetOutDegree(v))) || ((u == w) && isBollardNode)) { //only add an edge if turn is not a U-turn except it is the end of dead-end street.
if (!CheckIfTurnIsRestricted(u, v, w) || (onlyToNode != UINT_MAX && w == onlyToNode)) { //only add an edge if turn is not prohibited
const _NodeBasedDynamicGraph::EdgeData edgeData1 = _nodeBasedGraph->GetEdgeData(e1);
const _NodeBasedDynamicGraph::EdgeData edgeData2 = _nodeBasedGraph->GetEdgeData(e2);
assert(edgeData1.edgeBasedNodeID < _nodeBasedGraph->GetNumberOfEdges());
assert(edgeData2.edgeBasedNodeID < _nodeBasedGraph->GetNumberOfEdges());
unsigned distance = edgeData1.distance;
//distance += heightPenalty;
//distance += ComputeTurnPenalty(u, v, w);
if(_trafficLights.find(v) != _trafficLights.end()) {
distance += trafficSignalPenalty;
}
short turnInstruction = AnalyzeTurn(u, v, w);
assert(edgeData1.edgeBasedNodeID != edgeData2.edgeBasedNodeID);
EdgeBasedEdge newEdge(edgeData1.edgeBasedNodeID, edgeData2.edgeBasedNodeID, v, edgeData2.nameID, distance, true, false, turnInstruction);
edgeBasedEdges.push_back(newEdge);
} else {
++numberOfSkippedTurns;
}
}
}
}
p.printIncrement();
}
std::sort(edgeBasedNodes.begin(), edgeBasedNodes.end());
edgeBasedNodes.erase( std::unique(edgeBasedNodes.begin(), edgeBasedNodes.end()), edgeBasedNodes.end() );
INFO("Node-based graph contains " << nodeBasedEdgeCounter << " edges");
INFO("Edge-based graph contains " << edgeBasedEdges.size() << " edges, blowup is " << (double)edgeBasedEdges.size()/(double)nodeBasedEdgeCounter);
INFO("Edge-based graph skipped " << numberOfSkippedTurns << " turns, defined by " << numberOfTurnRestrictions << " restrictions.");
INFO("Generated " << edgeBasedNodes.size() << " edge based nodes");
}
short EdgeBasedGraphFactory::AnalyzeTurn(const NodeID u, const NodeID v, const NodeID w) const {
if(u == w) {
return TurnInstructions.UTurn;
}
_NodeBasedDynamicGraph::EdgeIterator edge1 = _nodeBasedGraph->FindEdge(u, v);
_NodeBasedDynamicGraph::EdgeIterator edge2 = _nodeBasedGraph->FindEdge(v, w);
_NodeBasedDynamicGraph::EdgeData & data1 = _nodeBasedGraph->GetEdgeData(edge1);
_NodeBasedDynamicGraph::EdgeData & data2 = _nodeBasedGraph->GetEdgeData(edge2);
//roundabouts need to be handled explicitely
if(data1.roundabout && data2.roundabout) {
//Is a turn possible? If yes, we stay on the roundabout!
if( 1 == (_nodeBasedGraph->EndEdges(v) - _nodeBasedGraph->BeginEdges(v)) ) {
//No turn possible.
return TurnInstructions.NoTurn;
} else {
return TurnInstructions.StayOnRoundAbout;
}
}
//Does turn start or end on roundabout?
if(data1.roundabout || data2.roundabout) {
//We are entering the roundabout
if( (!data1.roundabout) && data2.roundabout)
return TurnInstructions.EnterRoundAbout;
//We are leaving the roundabout
if(data1.roundabout && (!data2.roundabout) )
return TurnInstructions.LeaveRoundAbout;
}
//If street names stay the same and if we are certain that it is not a roundabout, we skip it.
if( (data1.nameID == data2.nameID) && (0 != data1.nameID))
return TurnInstructions.NoTurn;
if( (data1.nameID == data2.nameID) && (0 == data1.nameID) && (_nodeBasedGraph->GetOutDegree(v) <= 2) )
return TurnInstructions.NoTurn;
double angle = GetAngleBetweenTwoEdges(inputNodeInfoList[u], inputNodeInfoList[v], inputNodeInfoList[w]);
return TurnInstructions.GetTurnDirectionOfInstruction(angle);
}
unsigned EdgeBasedGraphFactory::GetNumberOfNodes() const {
return _nodeBasedGraph->GetNumberOfEdges();
}
/* Get angle of line segment (A,C)->(C,B), atan2 magic, formerly cosine theorem*/
template<class CoordinateT>
double EdgeBasedGraphFactory::GetAngleBetweenTwoEdges(const CoordinateT& A, const CoordinateT& C, const CoordinateT& B) const {
const int v1x = A.lon - C.lon;
const int v1y = A.lat - C.lat;
const int v2x = B.lon - C.lon;
const int v2y = B.lat - C.lat;
double angle = (atan2((double)v2y,v2x) - atan2((double)v1y,v1x) )*180/M_PI;
while(angle < 0)
angle += 360;
return angle;
}
|
Correct counting of node-based edges
|
Correct counting of node-based edges
|
C++
|
bsd-2-clause
|
KnockSoftware/osrm-backend,arnekaiser/osrm-backend,chaupow/osrm-backend,ramyaragupathy/osrm-backend,chaupow/osrm-backend,bjtaylor1/Project-OSRM-Old,nagyistoce/osrm-backend,ammeurer/osrm-backend,antoinegiret/osrm-backend,neilbu/osrm-backend,felixguendling/osrm-backend,bjtaylor1/Project-OSRM-Old,Project-OSRM/osrm-backend,Conggge/osrm-backend,bjtaylor1/osrm-backend,jpizarrom/osrm-backend,duizendnegen/osrm-backend,ammeurer/osrm-backend,atsuyim/osrm-backend,oxidase/osrm-backend,KnockSoftware/osrm-backend,yuryleb/osrm-backend,duizendnegen/osrm-backend,ammeurer/osrm-backend,bitsteller/osrm-backend,deniskoronchik/osrm-backend,neilbu/osrm-backend,beemogmbh/osrm-backend,Conggge/osrm-backend,bjtaylor1/osrm-backend,duizendnegen/osrm-backend,hydrays/osrm-backend,alex85k/Project-OSRM,hydrays/osrm-backend,bjtaylor1/Project-OSRM-Old,tkhaxton/osrm-backend,alex85k/Project-OSRM,jpizarrom/osrm-backend,antoinegiret/osrm-backend,stevevance/Project-OSRM,antoinegiret/osrm-geovelo,beemogmbh/osrm-backend,hydrays/osrm-backend,raymond0/osrm-backend,ammeurer/osrm-backend,atsuyim/osrm-backend,nagyistoce/osrm-backend,skyborla/osrm-backend,Conggge/osrm-backend,stevevance/Project-OSRM,raymond0/osrm-backend,antoinegiret/osrm-geovelo,oxidase/osrm-backend,felixguendling/osrm-backend,arnekaiser/osrm-backend,ibikecph/osrm-backend,ammeurer/osrm-backend,KnockSoftware/osrm-backend,oxidase/osrm-backend,frodrigo/osrm-backend,raymond0/osrm-backend,agruss/osrm-backend,jpizarrom/osrm-backend,Carsten64/OSRM-aux-git,alex85k/Project-OSRM,bjtaylor1/Project-OSRM-Old,frodrigo/osrm-backend,Project-OSRM/osrm-backend,ibikecph/osrm-backend,Tristramg/osrm-backend,neilbu/osrm-backend,tkhaxton/osrm-backend,Project-OSRM/osrm-backend,Project-OSRM/osrm-backend,stevevance/Project-OSRM,keesklopt/matrix,bitsteller/osrm-backend,ammeurer/osrm-backend,yuryleb/osrm-backend,hydrays/osrm-backend,skyborla/osrm-backend,prembasumatary/osrm-backend,arnekaiser/osrm-backend,deniskoronchik/osrm-backend,antoinegiret/osrm-geovelo,beemogmbh/osrm-backend,Conggge/osrm-backend,keesklopt/matrix,agruss/osrm-backend,oxidase/osrm-backend,antoinegiret/osrm-backend,raymond0/osrm-backend,agruss/osrm-backend,Carsten64/OSRM-aux-git,stevevance/Project-OSRM,ammeurer/osrm-backend,Carsten64/OSRM-aux-git,Tristramg/osrm-backend,arnekaiser/osrm-backend,prembasumatary/osrm-backend,skyborla/osrm-backend,yuryleb/osrm-backend,felixguendling/osrm-backend,deniskoronchik/osrm-backend,Carsten64/OSRM-aux-git,beemogmbh/osrm-backend,neilbu/osrm-backend,bjtaylor1/osrm-backend,ramyaragupathy/osrm-backend,ramyaragupathy/osrm-backend,keesklopt/matrix,bjtaylor1/osrm-backend,frodrigo/osrm-backend,bitsteller/osrm-backend,keesklopt/matrix,KnockSoftware/osrm-backend,prembasumatary/osrm-backend,deniskoronchik/osrm-backend,nagyistoce/osrm-backend,ibikecph/osrm-backend,atsuyim/osrm-backend,frodrigo/osrm-backend,yuryleb/osrm-backend,chaupow/osrm-backend,tkhaxton/osrm-backend,duizendnegen/osrm-backend,Tristramg/osrm-backend
|
e973859f374803f0d6a52dd83f64e825b4395186
|
Cutelyst/Actions/REST/actionrest.cpp
|
Cutelyst/Actions/REST/actionrest.cpp
|
/*
* Copyright (C) 2013-2018 Daniel Nicoletti <[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 "actionrest_p.h"
#include "context.h"
#include "controller.h"
#include "dispatcher.h"
#include <QUrl>
#include <QDebug>
using namespace Cutelyst;
/*!
* \class Cutelyst::ActionREST actionrest.h Cutelyst/Actions/REST/ActionREST
* \brief Automated REST Method Dispatching
*
* \code{.h}
* C_ATTR(foo, :Local :ActionClass(REST))
* void foo(Context *c); // do setup for HTTP method specific handlers
*
* C_ATTR(foo_GET, :Private)
* void foo_GET(Context *c); // do something for GET requests
*
* C_ATTR(foo_PUT, :Private)
* void foo_PUT(Context *c); // do something for PUT requests
* \endcode
*
* This Action handles doing automatic method dispatching for REST requests. It takes a normal Cutelyst action, and changes
* the dispatch to append an underscore and method name. First it will try dispatching to an action with the generated name,
* and failing that it will try to dispatch to a regular method.
*
* For example, in the synopsis above, calling GET on "/foo" would result in the foo_GET method being dispatched.
*
* If a method is requested that is not implemented, this action will return a status 405 (Method Not Found). It will populate
* the "Allow" header with the list of implemented request methods. You can override this behavior by implementing a custom
* 405 handler like so:
*
* \code{.h}
* C_ATTR(foo_not_implemented, :Private)
* void foo_not_implemented(Context *c); // handle not implemented methods
* \endcode
*
* If you do not provide an _OPTIONS method, we will automatically respond with a 200 OK. The "Allow" header will be populated
* with the list of implemented request methods. If you do not provide an _HEAD either, we will auto dispatch to the _GET one
* in case it exists.
*/
ActionREST::ActionREST(QObject *parent) : Action(parent)
, d_ptr(new ActionRESTPrivate)
{
d_ptr->q_ptr = this;
}
ActionREST::~ActionREST()
{
delete d_ptr;
}
bool ActionREST::doExecute(Context *c)
{
Q_D(const ActionREST);
if (!Action::doExecute(c)) {
return false;
}
return d->dispatchRestMethod(c, c->request()->method());
}
bool ActionRESTPrivate::dispatchRestMethod(Context *c, const QString &httpMethod) const
{
Q_Q(const ActionREST);
const QString restMethod = q->name() + QLatin1Char('_') + httpMethod;
Controller *controller = c->controller();
Action *action = controller->actionFor(restMethod);
if (!action) {
// Look for non registered actions in this controller
const ActionList actions = controller->actions();
for (Action *controllerAction : actions) {
if (controllerAction->name() == restMethod) {
action = controllerAction;
break;
}
}
}
if (action) {
return c->execute(action);
}
bool ret = false;
if (httpMethod == QLatin1String("OPTIONS")) {
ret = returnOptions(c, q->name());
} else if (httpMethod == QLatin1String("HEAD")) {
// redispatch to GET
ret = dispatchRestMethod(c, QStringLiteral("GET"));
} else if (httpMethod != QLatin1String("not_implemented")) {
// try dispatching to foo_not_implemented
ret = dispatchRestMethod(c, QStringLiteral("not_implemented"));
} else {
// not_implemented
ret = returnNotImplemented(c, q->name());
}
return ret;
}
bool ActionRESTPrivate::returnOptions(Context *c, const QString &methodName) const
{
Response *response = c->response();
response->setContentType(QStringLiteral("text/plain"));
response->setStatus(Response::OK); // 200
response->setHeader(QStringLiteral("ALLOW"),
getAllowedMethods(c->controller(), methodName));
response->body().clear();
return true;
}
bool ActionRESTPrivate::returnNotImplemented(Context *c, const QString &methodName) const
{
Response *response = c->response();
response->setStatus(Response::MethodNotAllowed); // 405
response->setHeader(QStringLiteral("ALLOW"),
getAllowedMethods(c->controller(), methodName));
const QString body = QLatin1String("Method ") + c->req()->method()
+ QLatin1String(" not implemented for ") + c->uriFor(methodName).toString();
response->setBody(body);
return true;
}
QString Cutelyst::ActionRESTPrivate::getAllowedMethods(Controller *controller, const QString &methodName) const
{
QStringList methods;
const QString name = methodName + QLatin1Char('_');
const ActionList actions = controller->actions();
for (Action *action : actions) {
const QString method = action->name();
if (method.startsWith(name)) {
methods.append(method.mid(name.size()));
}
}
if (methods.contains(QStringLiteral("GET"))) {
methods.append(QStringLiteral("HEAD"));
}
methods.removeAll(QStringLiteral("not_implemented"));
methods.sort();
methods.removeDuplicates();
return methods.join(QStringLiteral(", "));
}
#include "moc_actionrest.cpp"
|
/*
* Copyright (C) 2013-2018 Daniel Nicoletti <[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 "actionrest_p.h"
#include "context.h"
#include "controller.h"
#include "dispatcher.h"
#include <QUrl>
#include <QDebug>
using namespace Cutelyst;
/*!
* \class Cutelyst::ActionREST actionrest.h Cutelyst/Actions/REST/ActionREST
* \brief Automated REST Method Dispatching
*
* \code{.h}
* C_ATTR(foo, :Local :ActionClass(REST))
* void foo(Context *c); // do setup for HTTP method specific handlers
*
* C_ATTR(foo_GET, :Private)
* void foo_GET(Context *c); // do something for GET requests
*
* C_ATTR(foo_PUT, :Private)
* void foo_PUT(Context *c); // do something for PUT requests
* \endcode
*
* This Action handles doing automatic method dispatching for REST requests. It takes a normal Cutelyst action, and changes
* the dispatch to append an underscore and method name. First it will try dispatching to an action with the generated name,
* and failing that it will try to dispatch to a regular method.
*
* For example, in the synopsis above, calling GET on "/foo" would result in the foo_GET method being dispatched.
*
* If a method is requested that is not implemented, this action will return a status 405 (Method Not Found). It will populate
* the "Allow" header with the list of implemented request methods. You can override this behavior by implementing a custom
* 405 handler like so:
*
* \code{.h}
* C_ATTR(foo_not_implemented, :Private)
* void foo_not_implemented(Context *c); // handle not implemented methods
* \endcode
*
* If you do not provide an _OPTIONS method, we will automatically respond with a 200 OK. The "Allow" header will be populated
* with the list of implemented request methods. If you do not provide an _HEAD either, we will auto dispatch to the _GET one
* in case it exists.
*/
ActionREST::ActionREST(QObject *parent) : Action(parent)
, d_ptr(new ActionRESTPrivate)
{
d_ptr->q_ptr = this;
}
ActionREST::~ActionREST()
{
delete d_ptr;
}
bool ActionREST::doExecute(Context *c)
{
Q_D(const ActionREST);
if (!Action::doExecute(c)) {
return false;
}
return d->dispatchRestMethod(c, c->request()->method());
}
bool ActionRESTPrivate::dispatchRestMethod(Context *c, const QString &httpMethod) const
{
Q_Q(const ActionREST);
const QString restMethod = q->name() + QLatin1Char('_') + httpMethod;
Controller *controller = q->controller();
Action *action = controller->actionFor(restMethod);
if (!action) {
// Look for non registered actions in this controller
const ActionList actions = controller->actions();
for (Action *controllerAction : actions) {
if (controllerAction->name() == restMethod) {
action = controllerAction;
break;
}
}
}
if (action) {
return c->execute(action);
}
bool ret = false;
if (httpMethod == QLatin1String("OPTIONS")) {
ret = returnOptions(c, q->name());
} else if (httpMethod == QLatin1String("HEAD")) {
// redispatch to GET
ret = dispatchRestMethod(c, QStringLiteral("GET"));
} else if (httpMethod != QLatin1String("not_implemented")) {
// try dispatching to foo_not_implemented
ret = dispatchRestMethod(c, QStringLiteral("not_implemented"));
} else {
// not_implemented
ret = returnNotImplemented(c, q->name());
}
return ret;
}
bool ActionRESTPrivate::returnOptions(Context *c, const QString &methodName) const
{
Response *response = c->response();
response->setContentType(QStringLiteral("text/plain"));
response->setStatus(Response::OK); // 200
response->setHeader(QStringLiteral("ALLOW"),
getAllowedMethods(c->controller(), methodName));
response->body().clear();
return true;
}
bool ActionRESTPrivate::returnNotImplemented(Context *c, const QString &methodName) const
{
Response *response = c->response();
response->setStatus(Response::MethodNotAllowed); // 405
response->setHeader(QStringLiteral("ALLOW"),
getAllowedMethods(c->controller(), methodName));
const QString body = QLatin1String("Method ") + c->req()->method()
+ QLatin1String(" not implemented for ") + c->uriFor(methodName).toString();
response->setBody(body);
return true;
}
QString Cutelyst::ActionRESTPrivate::getAllowedMethods(Controller *controller, const QString &methodName) const
{
QStringList methods;
const QString name = methodName + QLatin1Char('_');
const ActionList actions = controller->actions();
for (Action *action : actions) {
const QString method = action->name();
if (method.startsWith(name)) {
methods.append(method.mid(name.size()));
}
}
if (methods.contains(QStringLiteral("GET"))) {
methods.append(QStringLiteral("HEAD"));
}
methods.removeAll(QStringLiteral("not_implemented"));
methods.sort();
methods.removeDuplicates();
return methods.join(QStringLiteral(", "));
}
#include "moc_actionrest.cpp"
|
Allow ActionREST actions to be forwarded from other Controllers
|
REST: Allow ActionREST actions to be forwarded from other Controllers
|
C++
|
bsd-3-clause
|
cutelyst/cutelyst,buschmann23/cutelyst,cutelyst/cutelyst,cutelyst/cutelyst,buschmann23/cutelyst,buschmann23/cutelyst
|
d6defdcdca1eeda83f007a3f29e72eab7cb6dae2
|
agentserver/agentthread.cpp
|
agentserver/agentthread.cpp
|
/*
Copyright (c) 2010 Volker Krause <[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 "agentthread.h"
#include "uirunnable.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QPluginLoader>
#include <shared/akdebug.h>
#include <qmetaobject.h>
using namespace Akonadi;
AgentThread::AgentThread(const QString& identifier, QObject *factory, QObject* parent):
QThread(parent),
m_identifier(identifier),
m_factory( factory ),
m_instance(0)
{
}
void AgentThread::run()
{
const bool invokeSucceeded = QMetaObject::invokeMethod( m_factory,
"createInstance",
Qt::DirectConnection,
Q_RETURN_ARG( QObject*, m_instance ),
Q_ARG(QString, m_identifier) );
if ( invokeSucceeded ) {
qDebug() << Q_FUNC_INFO << "agent instance created: " << m_instance;
// TODO: We might somehow require that the signal is actually there to avoid
// unexpected behavior.
connect( m_instance, SIGNAL( runRequest( Akonadi::UiRunnable * ) ),
SLOT( run( Akonadi::UiRunnable * ) ), Qt::BlockingQueuedConnection );
} else {
qDebug() << Q_FUNC_INFO << "agent instance creation failed";
}
exec();
}
void AgentThread::run( UiRunnable *runnable )
{
qDebug() << "!!!!!!!!!!" << ( QCoreApplication::instance()->thread() == currentThread() );
//runnable->run();
}
#include "agentthread.moc"
|
/*
Copyright (c) 2010 Volker Krause <[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 "agentthread.h"
#include "uirunnable.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QPluginLoader>
#include <shared/akdebug.h>
#include <qmetaobject.h>
using namespace Akonadi;
AgentThread::AgentThread(const QString& identifier, QObject *factory, QObject* parent):
QThread(parent),
m_identifier(identifier),
m_factory( factory ),
m_instance(0)
{
}
void AgentThread::run()
{
const bool invokeSucceeded = QMetaObject::invokeMethod( m_factory,
"createInstance",
Qt::DirectConnection,
Q_RETURN_ARG( QObject*, m_instance ),
Q_ARG(QString, m_identifier) );
if ( invokeSucceeded ) {
qDebug() << Q_FUNC_INFO << "agent instance created: " << m_instance;
// TODO: We might somehow require that the signal is actually there to avoid
// unexpected behavior.
connect( m_instance, SIGNAL( runRequest( Akonadi::UiRunnable * ) ),
SLOT( run( Akonadi::UiRunnable * ) ), Qt::BlockingQueuedConnection );
} else {
qDebug() << Q_FUNC_INFO << "agent instance creation failed";
}
exec();
}
void AgentThread::run( UiRunnable *runnable )
{
qDebug() << "!!!!!!!!!!" << ( QCoreApplication::instance()->thread() == currentThread() );
runnable->run();
}
#include "agentthread.moc"
|
Call run on runnable to make sure that actually something happens
|
Call run on runnable to make sure that actually something happens
svn path=/branches/work/akonadi-agentserver/; revision=1177889
|
C++
|
lgpl-2.1
|
kolab-groupware/akonadi,kolab-groupware/akonadi,kolab-groupware/akonadi,kolab-groupware/akonadi
|
d53f2096262951a777cb8299761e838babab4ab0
|
format.cc
|
format.cc
|
/*
String formatting library for C++
Copyright (c) 2012, Victor Zverovich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "format.h"
#include <stdint.h>
#include <cassert>
#include <cctype>
#include <climits>
#include <cstring>
#include <algorithm>
using std::size_t;
using fmt::Formatter;
#if _MSC_VER
# define snprintf _snprintf
#endif
namespace {
// Flags.
enum { PLUS_FLAG = 1, ZERO_FLAG = 2, HEX_PREFIX_FLAG = 4 };
void ReportUnknownType(char code, const char *type) {
if (std::isprint(code)) {
throw fmt::FormatError(
str(fmt::Format("unknown format code '{0}' for {1}") << code << type));
}
throw fmt::FormatError(
str(fmt::Format("unknown format code '\\x{0:02x}' for {1}")
<< static_cast<unsigned>(code) << type));
}
// Information about an integer type.
template <typename T>
struct IntTraits {
typedef T UnsignedType;
static bool IsNegative(T) { return false; }
};
template <>
struct IntTraits<int> {
typedef unsigned UnsignedType;
static bool IsNegative(int value) { return value < 0; }
};
template <>
struct IntTraits<long> {
typedef unsigned long UnsignedType;
static bool IsNegative(long value) { return value < 0; }
};
template <typename T>
struct IsLongDouble { enum {VALUE = 0}; };
template <>
struct IsLongDouble<long double> { enum {VALUE = 1}; };
}
// Throws Exception(message) if format contains '}', otherwise throws
// FormatError reporting unmatched '{'. The idea is that unmatched '{'
// should override other errors.
void Formatter::ReportError(const char *s, const std::string &message) const {
for (int num_open_braces = num_open_braces_; *s; ++s) {
if (*s == '{') {
++num_open_braces;
} else if (*s == '}') {
if (--num_open_braces == 0)
throw fmt::FormatError(message);
}
}
throw fmt::FormatError("unmatched '{' in format");
}
template <typename T>
void Formatter::FormatInt(T value, unsigned flags, int width, char type) {
int size = 0;
char sign = 0;
typedef typename IntTraits<T>::UnsignedType UnsignedType;
UnsignedType abs_value = value;
if (IntTraits<T>::IsNegative(value)) {
sign = '-';
++size;
abs_value = -value;
} else if ((flags & PLUS_FLAG) != 0) {
sign = '+';
++size;
}
char fill = (flags & ZERO_FLAG) != 0 ? '0' : ' ';
size_t start = buffer_.size();
char *p = 0;
switch (type) {
case 0: case 'd': {
UnsignedType n = abs_value;
do {
++size;
} while ((n /= 10) != 0);
width = std::max(width, size);
p = GrowBuffer(width) + width - 1;
n = abs_value;
do {
*p-- = '0' + (n % 10);
} while ((n /= 10) != 0);
break;
}
case 'x': case 'X': {
UnsignedType n = abs_value;
bool print_prefix = (flags & HEX_PREFIX_FLAG) != 0;
if (print_prefix) size += 2;
do {
++size;
} while ((n >>= 4) != 0);
width = std::max(width, size);
p = GrowBuffer(width) + width - 1;
n = abs_value;
const char *digits = type == 'x' ? "0123456789abcdef" : "0123456789ABCDEF";
do {
*p-- = digits[n & 0xf];
} while ((n >>= 4) != 0);
if (print_prefix) {
*p-- = type;
*p-- = '0';
}
break;
}
case 'o': {
UnsignedType n = abs_value;
do {
++size;
} while ((n >>= 3) != 0);
width = std::max(width, size);
p = GrowBuffer(width) + width - 1;
n = abs_value;
do {
*p-- = '0' + (n & 7);
} while ((n >>= 3) != 0);
break;
}
default:
ReportUnknownType(type, "integer");
break;
}
if (sign) {
if ((flags & ZERO_FLAG) != 0)
buffer_[start++] = sign;
else
*p-- = sign;
}
std::fill(&buffer_[start], p + 1, fill);
}
template <typename T>
void Formatter::FormatDouble(
T value, unsigned flags, int width, int precision, char type) {
// Check type.
switch (type) {
case 0:
type = 'g';
break;
case 'e': case 'E': case 'f': case 'g': case 'G':
break;
case 'F':
#ifdef _MSC_VER
// MSVC's printf doesn't support 'F'.
type = 'f';
#endif
break;
default:
ReportUnknownType(type, "double");
break;
}
// Build format string.
enum { MAX_FORMAT_SIZE = 9}; // longest format: %+0*.*Lg
char format[MAX_FORMAT_SIZE];
char *format_ptr = format;
*format_ptr++ = '%';
if ((flags & PLUS_FLAG) != 0)
*format_ptr++ = '+';
if ((flags & ZERO_FLAG) != 0)
*format_ptr++ = '0';
if (width > 0)
*format_ptr++ = '*';
if (precision >= 0) {
*format_ptr++ = '.';
*format_ptr++ = '*';
}
if (IsLongDouble<T>::VALUE)
*format_ptr++ = 'L';
*format_ptr++ = type;
*format_ptr = '\0';
// Format using snprintf.
size_t offset = buffer_.size();
for (;;) {
size_t size = buffer_.capacity() - offset;
int n = 0;
if (width <= 0) {
n = precision < 0 ?
snprintf(&buffer_[offset], size, format, value) :
snprintf(&buffer_[offset], size, format, precision, value);
} else {
n = precision < 0 ?
snprintf(&buffer_[offset], size, format, width, value) :
snprintf(&buffer_[offset], size, format, width, precision, value);
}
if (n >= 0 && offset + n < buffer_.capacity()) {
GrowBuffer(n);
return;
}
buffer_.reserve(n >= 0 ? offset + n + 1 : 2 * buffer_.capacity());
}
}
// Parses an unsigned integer advancing s to the end of the parsed input.
// This function assumes that the first character of s is a digit.
unsigned Formatter::ParseUInt(const char *&s) const {
assert('0' <= *s && *s <= '9');
unsigned value = 0;
do {
unsigned new_value = value * 10 + (*s++ - '0');
if (new_value < value) // Check if value wrapped around.
ReportError(s, "number is too big in format");
value = new_value;
} while ('0' <= *s && *s <= '9');
return value;
}
const Formatter::Arg &Formatter::ParseArgIndex(const char *&s) const {
if (*s < '0' || *s > '9')
ReportError(s, "missing argument index in format string");
unsigned arg_index = ParseUInt(s);
if (arg_index >= args_.size())
ReportError(s, "argument index is out of range in format");
return *args_[arg_index];
}
void Formatter::DoFormat() {
const char *start = format_;
format_ = 0;
const char *s = start;
while (*s) {
char c = *s++;
if (c != '{' && c != '}') continue;
if (*s == c) {
buffer_.append(start, s);
start = ++s;
continue;
}
if (c == '}')
throw FormatError("unmatched '}' in format");
num_open_braces_= 1;
buffer_.append(start, s - 1);
const Arg &arg = ParseArgIndex(s);
unsigned flags = 0;
int width = 0;
int precision = -1;
char type = 0;
if (*s == ':') {
++s;
if (*s == '+') {
++s;
if (arg.type > LAST_NUMERIC_TYPE)
ReportError(s, "format specifier '+' requires numeric argument");
if (arg.type == UINT || arg.type == ULONG) {
ReportError(s,
"format specifier '+' requires signed argument");
}
flags |= PLUS_FLAG;
}
if (*s == '0') {
++s;
if (arg.type > LAST_NUMERIC_TYPE)
ReportError(s, "format specifier '0' requires numeric argument");
flags |= ZERO_FLAG;
}
// Parse width.
if ('0' <= *s && *s <= '9') {
unsigned value = ParseUInt(s);
if (value > INT_MAX)
ReportError(s, "number is too big in format");
width = value;
}
// Parse precision.
if (*s == '.') {
++s;
precision = 0;
if ('0' <= *s && *s <= '9') {
unsigned value = ParseUInt(s);
if (value > INT_MAX)
ReportError(s, "number is too big in format");
precision = value;
} else if (*s == '{') {
++s;
++num_open_braces_;
const Arg &precision_arg = ParseArgIndex(s);
unsigned long value = 0;
switch (precision_arg.type) {
case INT:
if (precision_arg.int_value < 0)
ReportError(s, "negative precision in format");
value = precision_arg.int_value;
break;
case UINT:
value = precision_arg.uint_value;
break;
case LONG:
if (precision_arg.long_value < 0)
ReportError(s, "negative precision in format");
value = precision_arg.long_value;
break;
case ULONG:
value = precision_arg.ulong_value;
break;
default:
ReportError(s, "precision is not integer");
}
if (value > INT_MAX)
ReportError(s, "number is too big in format");
precision = value;
if (*s++ != '}')
throw FormatError("unmatched '{' in format");
--num_open_braces_;
} else {
ReportError(s, "missing precision in format");
}
if (arg.type != DOUBLE && arg.type != LONG_DOUBLE) {
ReportError(s,
"precision specifier requires floating-point argument");
}
}
// Parse type.
if (*s != '}' && *s)
type = *s++;
}
if (*s++ != '}')
throw FormatError("unmatched '{' in format");
start = s;
// Format argument.
switch (arg.type) {
case INT:
FormatInt(arg.int_value, flags, width, type);
break;
case UINT:
FormatInt(arg.uint_value, flags, width, type);
break;
case LONG:
FormatInt(arg.long_value, flags, width, type);
break;
case ULONG:
FormatInt(arg.ulong_value, flags, width, type);
break;
case DOUBLE:
FormatDouble(arg.double_value, flags, width, precision, type);
break;
case LONG_DOUBLE:
FormatDouble(arg.long_double_value, flags, width, precision, type);
break;
case CHAR: {
if (type && type != 'c')
ReportUnknownType(type, "char");
char *out = GrowBuffer(std::max(width, 1));
*out++ = arg.int_value;
if (width > 1)
std::fill_n(out, width - 1, ' ');
break;
}
case STRING: {
if (type && type != 's')
ReportUnknownType(type, "string");
const char *str = arg.string.value;
size_t size = arg.string.size;
if (size == 0 && *str)
size = std::strlen(str);
char *out = GrowBuffer(std::max<size_t>(width, size));
out = std::copy(str, str + size, out);
if (static_cast<unsigned>(width) > size)
std::fill_n(out, width - size, ' ');
break;
}
case POINTER:
if (type && type != 'p')
ReportUnknownType(type, "pointer");
FormatInt(reinterpret_cast<uintptr_t>(
arg.pointer_value), HEX_PREFIX_FLAG, width, 'x');
break;
case CUSTOM:
if (type)
ReportUnknownType(type, "object");
(this->*arg.custom.format)(arg.custom.value, width);
break;
default:
assert(false);
break;
}
}
buffer_.append(start, s + 1);
buffer_.resize(buffer_.size() - 1); // Don't count the terminating zero.
}
|
/*
String formatting library for C++
Copyright (c) 2012, Victor Zverovich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
// Disable useless MSVC warnings.
#define _CRT_SECURE_NO_WARNINGS
#include "format.h"
#include <stdint.h>
#include <cassert>
#include <cctype>
#include <climits>
#include <cstring>
#include <algorithm>
using std::size_t;
using fmt::Formatter;
#if _MSC_VER
# define snprintf _snprintf
#endif
namespace {
// Flags.
enum { PLUS_FLAG = 1, ZERO_FLAG = 2, HEX_PREFIX_FLAG = 4 };
void ReportUnknownType(char code, const char *type) {
if (std::isprint(code)) {
throw fmt::FormatError(
str(fmt::Format("unknown format code '{0}' for {1}") << code << type));
}
throw fmt::FormatError(
str(fmt::Format("unknown format code '\\x{0:02x}' for {1}")
<< static_cast<unsigned>(code) << type));
}
// Information about an integer type.
template <typename T>
struct IntTraits {
typedef T UnsignedType;
static bool IsNegative(T) { return false; }
};
template <>
struct IntTraits<int> {
typedef unsigned UnsignedType;
static bool IsNegative(int value) { return value < 0; }
};
template <>
struct IntTraits<long> {
typedef unsigned long UnsignedType;
static bool IsNegative(long value) { return value < 0; }
};
template <typename T>
struct IsLongDouble { enum {VALUE = 0}; };
template <>
struct IsLongDouble<long double> { enum {VALUE = 1}; };
}
// Throws Exception(message) if format contains '}', otherwise throws
// FormatError reporting unmatched '{'. The idea is that unmatched '{'
// should override other errors.
void Formatter::ReportError(const char *s, const std::string &message) const {
for (int num_open_braces = num_open_braces_; *s; ++s) {
if (*s == '{') {
++num_open_braces;
} else if (*s == '}') {
if (--num_open_braces == 0)
throw fmt::FormatError(message);
}
}
throw fmt::FormatError("unmatched '{' in format");
}
template <typename T>
void Formatter::FormatInt(T value, unsigned flags, int width, char type) {
int size = 0;
char sign = 0;
typedef typename IntTraits<T>::UnsignedType UnsignedType;
UnsignedType abs_value = value;
if (IntTraits<T>::IsNegative(value)) {
sign = '-';
++size;
abs_value = -value;
} else if ((flags & PLUS_FLAG) != 0) {
sign = '+';
++size;
}
char fill = (flags & ZERO_FLAG) != 0 ? '0' : ' ';
size_t start = buffer_.size();
char *p = 0;
switch (type) {
case 0: case 'd': {
UnsignedType n = abs_value;
do {
++size;
} while ((n /= 10) != 0);
width = std::max(width, size);
p = GrowBuffer(width) + width - 1;
n = abs_value;
do {
*p-- = '0' + (n % 10);
} while ((n /= 10) != 0);
break;
}
case 'x': case 'X': {
UnsignedType n = abs_value;
bool print_prefix = (flags & HEX_PREFIX_FLAG) != 0;
if (print_prefix) size += 2;
do {
++size;
} while ((n >>= 4) != 0);
width = std::max(width, size);
p = GrowBuffer(width) + width - 1;
n = abs_value;
const char *digits = type == 'x' ? "0123456789abcdef" : "0123456789ABCDEF";
do {
*p-- = digits[n & 0xf];
} while ((n >>= 4) != 0);
if (print_prefix) {
*p-- = type;
*p-- = '0';
}
break;
}
case 'o': {
UnsignedType n = abs_value;
do {
++size;
} while ((n >>= 3) != 0);
width = std::max(width, size);
p = GrowBuffer(width) + width - 1;
n = abs_value;
do {
*p-- = '0' + (n & 7);
} while ((n >>= 3) != 0);
break;
}
default:
ReportUnknownType(type, "integer");
break;
}
if (sign) {
if ((flags & ZERO_FLAG) != 0)
buffer_[start++] = sign;
else
*p-- = sign;
}
std::fill(&buffer_[start], p + 1, fill);
}
template <typename T>
void Formatter::FormatDouble(
T value, unsigned flags, int width, int precision, char type) {
// Check type.
switch (type) {
case 0:
type = 'g';
break;
case 'e': case 'E': case 'f': case 'g': case 'G':
break;
case 'F':
#ifdef _MSC_VER
// MSVC's printf doesn't support 'F'.
type = 'f';
#endif
break;
default:
ReportUnknownType(type, "double");
break;
}
// Build format string.
enum { MAX_FORMAT_SIZE = 9}; // longest format: %+0*.*Lg
char format[MAX_FORMAT_SIZE];
char *format_ptr = format;
*format_ptr++ = '%';
if ((flags & PLUS_FLAG) != 0)
*format_ptr++ = '+';
if ((flags & ZERO_FLAG) != 0)
*format_ptr++ = '0';
if (width > 0)
*format_ptr++ = '*';
if (precision >= 0) {
*format_ptr++ = '.';
*format_ptr++ = '*';
}
if (IsLongDouble<T>::VALUE)
*format_ptr++ = 'L';
*format_ptr++ = type;
*format_ptr = '\0';
// Format using snprintf.
size_t offset = buffer_.size();
for (;;) {
size_t size = buffer_.capacity() - offset;
int n = 0;
if (width <= 0) {
n = precision < 0 ?
snprintf(&buffer_[offset], size, format, value) :
snprintf(&buffer_[offset], size, format, precision, value);
} else {
n = precision < 0 ?
snprintf(&buffer_[offset], size, format, width, value) :
snprintf(&buffer_[offset], size, format, width, precision, value);
}
if (n >= 0 && offset + n < buffer_.capacity()) {
GrowBuffer(n);
return;
}
buffer_.reserve(n >= 0 ? offset + n + 1 : 2 * buffer_.capacity());
}
}
// Parses an unsigned integer advancing s to the end of the parsed input.
// This function assumes that the first character of s is a digit.
unsigned Formatter::ParseUInt(const char *&s) const {
assert('0' <= *s && *s <= '9');
unsigned value = 0;
do {
unsigned new_value = value * 10 + (*s++ - '0');
if (new_value < value) // Check if value wrapped around.
ReportError(s, "number is too big in format");
value = new_value;
} while ('0' <= *s && *s <= '9');
return value;
}
const Formatter::Arg &Formatter::ParseArgIndex(const char *&s) const {
if (*s < '0' || *s > '9')
ReportError(s, "missing argument index in format string");
unsigned arg_index = ParseUInt(s);
if (arg_index >= args_.size())
ReportError(s, "argument index is out of range in format");
return *args_[arg_index];
}
void Formatter::DoFormat() {
const char *start = format_;
format_ = 0;
const char *s = start;
while (*s) {
char c = *s++;
if (c != '{' && c != '}') continue;
if (*s == c) {
buffer_.append(start, s);
start = ++s;
continue;
}
if (c == '}')
throw FormatError("unmatched '}' in format");
num_open_braces_= 1;
buffer_.append(start, s - 1);
const Arg &arg = ParseArgIndex(s);
unsigned flags = 0;
int width = 0;
int precision = -1;
char type = 0;
if (*s == ':') {
++s;
if (*s == '+') {
++s;
if (arg.type > LAST_NUMERIC_TYPE)
ReportError(s, "format specifier '+' requires numeric argument");
if (arg.type == UINT || arg.type == ULONG) {
ReportError(s,
"format specifier '+' requires signed argument");
}
flags |= PLUS_FLAG;
}
if (*s == '0') {
++s;
if (arg.type > LAST_NUMERIC_TYPE)
ReportError(s, "format specifier '0' requires numeric argument");
flags |= ZERO_FLAG;
}
// Parse width.
if ('0' <= *s && *s <= '9') {
unsigned value = ParseUInt(s);
if (value > INT_MAX)
ReportError(s, "number is too big in format");
width = value;
}
// Parse precision.
if (*s == '.') {
++s;
precision = 0;
if ('0' <= *s && *s <= '9') {
unsigned value = ParseUInt(s);
if (value > INT_MAX)
ReportError(s, "number is too big in format");
precision = value;
} else if (*s == '{') {
++s;
++num_open_braces_;
const Arg &precision_arg = ParseArgIndex(s);
unsigned long value = 0;
switch (precision_arg.type) {
case INT:
if (precision_arg.int_value < 0)
ReportError(s, "negative precision in format");
value = precision_arg.int_value;
break;
case UINT:
value = precision_arg.uint_value;
break;
case LONG:
if (precision_arg.long_value < 0)
ReportError(s, "negative precision in format");
value = precision_arg.long_value;
break;
case ULONG:
value = precision_arg.ulong_value;
break;
default:
ReportError(s, "precision is not integer");
}
if (value > INT_MAX)
ReportError(s, "number is too big in format");
precision = value;
if (*s++ != '}')
throw FormatError("unmatched '{' in format");
--num_open_braces_;
} else {
ReportError(s, "missing precision in format");
}
if (arg.type != DOUBLE && arg.type != LONG_DOUBLE) {
ReportError(s,
"precision specifier requires floating-point argument");
}
}
// Parse type.
if (*s != '}' && *s)
type = *s++;
}
if (*s++ != '}')
throw FormatError("unmatched '{' in format");
start = s;
// Format argument.
switch (arg.type) {
case INT:
FormatInt(arg.int_value, flags, width, type);
break;
case UINT:
FormatInt(arg.uint_value, flags, width, type);
break;
case LONG:
FormatInt(arg.long_value, flags, width, type);
break;
case ULONG:
FormatInt(arg.ulong_value, flags, width, type);
break;
case DOUBLE:
FormatDouble(arg.double_value, flags, width, precision, type);
break;
case LONG_DOUBLE:
FormatDouble(arg.long_double_value, flags, width, precision, type);
break;
case CHAR: {
if (type && type != 'c')
ReportUnknownType(type, "char");
char *out = GrowBuffer(std::max(width, 1));
*out++ = arg.int_value;
if (width > 1)
std::fill_n(out, width - 1, ' ');
break;
}
case STRING: {
if (type && type != 's')
ReportUnknownType(type, "string");
const char *str = arg.string.value;
size_t size = arg.string.size;
if (size == 0 && *str)
size = std::strlen(str);
char *out = GrowBuffer(std::max<size_t>(width, size));
out = std::copy(str, str + size, out);
if (static_cast<unsigned>(width) > size)
std::fill_n(out, width - size, ' ');
break;
}
case POINTER:
if (type && type != 'p')
ReportUnknownType(type, "pointer");
FormatInt(reinterpret_cast<uintptr_t>(
arg.pointer_value), HEX_PREFIX_FLAG, width, 'x');
break;
case CUSTOM:
if (type)
ReportUnknownType(type, "object");
(this->*arg.custom.format)(arg.custom.value, width);
break;
default:
assert(false);
break;
}
}
buffer_.append(start, s + 1);
buffer_.resize(buffer_.size() - 1); // Don't count the terminating zero.
}
|
Disable "secure" warnings in format.cc too.
|
Disable "secure" warnings in format.cc too.
|
C++
|
bsd-2-clause
|
lightslife/cppformat,seungrye/cppformat,alabuzhev/fmt,lightslife/cppformat,dean0x7d/cppformat,seungrye/cppformat,cppformat/cppformat,cppformat/cppformat,nelson4722/cppformat,dean0x7d/cppformat,dean0x7d/cppformat,Jopie64/cppformat,alabuzhev/fmt,blaquee/cppformat,wangshijin/cppformat,Jopie64/cppformat,mojoBrendan/fmt,alabuzhev/fmt,Jopie64/cppformat,wangshijin/cppformat,wangshijin/cppformat,cppformat/cppformat,mojoBrendan/fmt,lightslife/cppformat,nelson4722/cppformat,mojoBrendan/fmt,blaquee/cppformat,blaquee/cppformat,seungrye/cppformat,nelson4722/cppformat
|
2eebffcdcb65a32bfb8ee6183ae7fc971d4ac495
|
src/Bull/Render/Context/Wgl/WglContext.cpp
|
src/Bull/Render/Context/Wgl/WglContext.cpp
|
#include <limits>
#include <Bull/Core/Exception/InternalError.hpp>
#include <Bull/Core/Support/Win32/Win32Error.hpp>
#include <Bull/Core/System/Library.hpp>
#include <Bull/Core/Utility/StringUtils.hpp>
#include <Bull/Render/Context/Wgl/WglContext.hpp>
#include <Bull/Render/Context/Wgl/WglCreateContextARB.hpp>
#include <Bull/Render/Context/Wgl/WglMultisampleARB.hpp>
#include <Bull/Render/Context/Wgl/WglPbufferARB.hpp>
#include <Bull/Render/Context/Wgl/WglPixelFormatARB.hpp>
#include <Bull/Render/Context/Wgl/WglSwapControlEXT.hpp>
namespace Bull
{
namespace prv
{
void* WglContext::getFunction(const String& function)
{
void* functionProc = reinterpret_cast<void*>(wglGetProcAddress(function.getBuffer()));
if(functionProc)
{
return functionProc;
}
// wglGetProcAddress will set the last error to 127 if a function is not found but we don't care here
SetLastError(0);
static Library library("opengl32.dll");
if(!library)
{
return nullptr;
}
return reinterpret_cast<void*>(library.getFunction(function));
}
void WglContext::requireExtensions(ExtensionsLoader::Instance& loader)
{
loader->require(wglCreateContext);
loader->require(wglPixelFormat);
loader->require(wglSwapControl);
loader->require(wglPbuffer);
}
int WglContext::getBestPixelFormat(HDC device, Uint8 bitsPerPixel, const ContextSettings& settings, bool usePbuffer)
{
int bestPixelFormat = 0;
if(wglPixelFormat.isLoaded())
{
static const int attribs[] = {
WGL_DRAW_TO_WINDOW_ARB, 1,
WGL_SUPPORT_OPENGL_ARB, 1,
WGL_DOUBLE_BUFFER_ARB, 1,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
0
};
int formats[512];
UINT count = 0;
bool isValid = wglChoosePixelFormat(device, attribs, nullptr, 512, formats, &count) != 0;
if(isValid && count > 0)
{
int bestScore = std::numeric_limits<int>::max();
for(UINT i = 0; i < count; i++)
{
int format[7] = {0};
int sample[2] = {0};
static const int formatAttribs[] = {
WGL_RED_BITS_ARB,
WGL_GREEN_BITS_ARB,
WGL_BLUE_BITS_ARB,
WGL_ALPHA_BITS_ARB,
WGL_DEPTH_BITS_ARB,
WGL_STENCIL_BITS_ARB,
WGL_ACCELERATION_ARB
};
if(!wglGetPixelFormatAttribiv(device, formats[i], PFD_MAIN_PLANE, 7, formatAttribs, format))
{
break;
}
if(isSupported("WGL_ARB_multisample"))
{
static const int sampleAttribs[] = {
WGL_SAMPLE_BUFFERS_ARB,
WGL_SAMPLES_ARB
};
if(!wglGetPixelFormatAttribiv(device, formats[i], PFD_MAIN_PLANE, 2, sampleAttribs, sample))
{
break;
}
}
if(usePbuffer)
{
int pbuffer;
static const int pbufferAttribs[] = {
WGL_DRAW_TO_PBUFFER_ARB
};
if(!wglGetPixelFormatAttribiv(device, formats[i], PFD_MAIN_PLANE, 1, pbufferAttribs, &pbuffer))
{
break;
}
else if(pbuffer != 1)
{
continue;
}
}
/// We don't care about non hardware accelerated pixel format
if(format[6])
{
int colors = format[0] + format[1] + format[2] + format[3];
int score = evaluatePixelFormat(colors, format[4], format[5], sample[0] ? sample[1] : 0, bitsPerPixel, settings);
if(bestScore > score)
{
bestScore = score;
bestPixelFormat = formats[i];
}
}
}
}
}
if(usePbuffer)
{
return bestPixelFormat;
}
if(!bestPixelFormat)
{
PIXELFORMATDESCRIPTOR descriptor;
ZeroMemory(&descriptor, sizeof(descriptor));
descriptor.nSize = sizeof(descriptor);
descriptor.nVersion = 1;
descriptor.iLayerType = PFD_MAIN_PLANE;
descriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
descriptor.iPixelType = PFD_TYPE_RGBA;
descriptor.cColorBits = bitsPerPixel;
descriptor.cDepthBits = settings.depths;
descriptor.cStencilBits = settings.stencil;
descriptor.cAlphaBits = bitsPerPixel == 32 ? 8 : 0;
bestPixelFormat = ChoosePixelFormat(device, &descriptor);
}
return bestPixelFormat;
}
WglContext::WglContext(const WglContext* shared) :
WglContext(shared, VideoMode(1, 1), ContextSettings())
{
/// Nothing
}
WglContext::WglContext(const WglContext* shared, const VideoMode& mode, const ContextSettings& settings) :
GlContext(settings),
m_device(nullptr),
m_render(nullptr),
m_pbuffer(nullptr),
m_ownWindow(false)
{
createSurface(shared, mode.width, mode.height, mode.bitsPerPixel);
if(m_device)
{
setPixelFormat(mode.bitsPerPixel);
createContext(shared);
}
}
WglContext::WglContext(const WglContext* shared, Uint8 bitsPerPixel, const ContextSettings& settings) :
WglContext(shared, VideoMode(1, 1, bitsPerPixel), settings)
{
/// Nothing
}
WglContext::WglContext(const WglContext* shared, const WindowImpl& window, Uint8 bitsPerPixel, const ContextSettings& settings) :
GlContext(settings),
m_device(nullptr),
m_render(nullptr),
m_pbuffer(nullptr),
m_ownWindow(false)
{
createSurface(window);
if(m_device)
{
setPixelFormat(bitsPerPixel);
createContext(shared);
}
}
WglContext::~WglContext()
{
if(m_render)
{
if(wglGetCurrentContext() == m_render)
{
wglMakeCurrent(nullptr, nullptr);
}
wglDeleteContext(m_render);
}
if(m_device)
{
if(m_pbuffer)
{
wglReleasePbufferDC(m_pbuffer, m_device);
wglDestroyPbuffer(m_pbuffer);
}
else
{
ReleaseDC(m_window, m_device);
}
}
if(m_window && m_ownWindow)
{
DestroyWindow(m_window);
}
}
SurfaceHandler WglContext::getSurfaceHandler() const
{
return m_device;
}
void WglContext::display()
{
if(m_device && m_render)
{
SwapBuffers(m_device);
}
}
void WglContext::enableVsync(bool active)
{
if(wglSwapControl.isLoaded())
{
wglSwapInterval(active ? 1 : 0);
}
}
void WglContext::makeCurrent()
{
if(m_pbuffer)
{
int flag = 0;
wglQueryPbuffer(m_pbuffer, WGL_PBUFFER_LOST_ARB, &flag);
Expect(!flag, Throw(InternalError, "WglContext::makeCurrent", "PBuffer is became invalid"));
}
Expect(wglMakeCurrent(m_device, m_render), Throw(Win32Error, "WglContext::makeCurrent", "Failed to make context current"));
}
void WglContext::createSurface(const WindowImpl& window)
{
m_window = window.getSystemHandler();
m_device = GetDC(m_window);
}
void WglContext::createSurface(const WglContext* shared, unsigned int width, unsigned int height, Uint8 bitsPerPixel)
{
if(wglPbuffer.isLoaded() && shared)
{
int format = getBestPixelFormat(shared->m_device, bitsPerPixel, m_settings, true);
if(format)
{
m_pbuffer = wglCreatePbuffer(shared->m_device, format, width, height, nullptr);
if(m_pbuffer)
{
m_device = wglGetPbufferDC(m_pbuffer);
if(!m_device)
{
m_log->warning("Failed to get device context from PBuffer");
wglDestroyPbuffer(m_pbuffer);
}
}
}
}
if(!m_device)
{
m_window = CreateWindow("STATIC", nullptr,
WS_DISABLED | WS_POPUP,
0, 0,
width, height,
nullptr,
nullptr,
GetModuleHandle(nullptr),
nullptr);
Expect(m_window != INVALID_HANDLE_VALUE, Throw(Win32Error, "WglContext::createSurface", "Failed to create internal window"));
m_device = GetDC(m_window);
m_ownWindow = true;
}
}
void WglContext::setPixelFormat(Uint8 bitsPerPixel)
{
PIXELFORMATDESCRIPTOR descriptor;
int bestFormat = getBestPixelFormat(m_device, bitsPerPixel, m_settings);
descriptor.nSize = sizeof(PIXELFORMATDESCRIPTOR);
descriptor.nVersion = 1;
DescribePixelFormat(m_device, bestFormat, sizeof(PIXELFORMATDESCRIPTOR), &descriptor);
Expect(SetPixelFormat(m_device, bestFormat, &descriptor), Throw(Win32Error, "WglContext::setPixelFormat", "Failed to set pixel format"));
}
void WglContext::createContext(const WglContext* shared)
{
HGLRC sharedHandler = shared ? shared->m_render : nullptr;
if(wglCreateContext.isLoaded())
{
do
{
std::vector<int> attribs;
attribs.emplace_back(WGL_CONTEXT_MAJOR_VERSION_ARB);
attribs.emplace_back(m_settings.major);
attribs.emplace_back(WGL_CONTEXT_MINOR_VERSION_ARB);
attribs.emplace_back(m_settings.minor);
if(isSupported("WGL_ARB_create_context_profile"))
{
int flags = 0;
int profile = (m_settings.profile == ContextSettingsProfile_Compatibility) ? WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB : WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
if(m_settings.type == ContextSettingsType_Debug)
{
flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
}
if(m_settings.type == ContextSettingsType_ForwardCompatible)
{
flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
}
attribs.emplace_back(WGL_CONTEXT_PROFILE_MASK_ARB);
attribs.emplace_back(profile);
attribs.emplace_back(WGL_CONTEXT_FLAGS_ARB);
attribs.emplace_back(flags);
}
attribs.emplace_back(0);
m_render = wglCreateContextAttribs(m_device, sharedHandler, &attribs[0]);
if(!m_render)
{
m_log->warning("Failed to create WglContext with version " + StringUtils::number(m_settings.major) + "." + StringUtils::number(m_settings.minor));
if(m_settings.minor == 0)
{
m_settings.major -= 1;
m_settings.minor = 9;
}
else
{
m_settings.minor -= 1;
}
}
else
{
m_log->info("Create WglContext with version " + StringUtils::number(m_settings.major) + "." + StringUtils::number(m_settings.minor));
}
}while(!m_render && m_settings.major >= 1);
}
if(m_render == nullptr)
{
m_render = ::wglCreateContext(m_device);
Expect(m_render, Throw(InternalError, "WglContext::createContext", "Failed to create legacy/shared WglContext"));
if(shared)
{
static std::mutex mutex;
m_log->info("Create legacy WglContext");
std::lock_guard<std::mutex> lock(mutex);
wglShareLists(sharedHandler, m_render);
}
else
{
m_log->info("Create shared WglContext");
}
}
updateSettings();
}
void WglContext::updateSettings()
{
PIXELFORMATDESCRIPTOR pfd;
pfd.nVersion = 1;
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
int pixelFormat = GetPixelFormat(m_device);
DescribePixelFormat(m_device, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
if(wglPixelFormat.isLoaded())
{
int format[2] = {0};
static const int formatAttribs[] = {
WGL_DEPTH_BITS_ARB,
WGL_STENCIL_BITS_ARB
};
if(wglGetPixelFormatAttribiv(m_device, pixelFormat, PFD_MAIN_PLANE, 2, formatAttribs, format))
{
m_settings.depths = static_cast<Uint8>(format[0]);
m_settings.stencil = static_cast<Uint8>(format[1]);
}
else
{
m_settings.depths = pfd.cDepthBits;
m_settings.stencil = pfd.cStencilBits;
}
if(isSupported("WGL_ARB_multisample"))
{
int sample[2] = {0};
static const int sampleAttribs[] = {
WGL_SAMPLE_BUFFERS_ARB,
WGL_SAMPLES_ARB
};
if(wglGetPixelFormatAttribiv(m_device, pixelFormat, PFD_MAIN_PLANE, 2, sampleAttribs, sample))
{
m_settings.antialiasing = sample[0] ? sample[1] : 0;
}
else
{
m_settings.antialiasing = 0;
}
}
else
{
m_settings.antialiasing = 0;
}
}
else
{
m_settings.depths = pfd.cDepthBits;
m_settings.stencil = pfd.cStencilBits;
m_settings.antialiasing = 0;
}
}
}
}
|
#include <limits>
#include <Bull/Core/Exception/InternalError.hpp>
#include <Bull/Core/Support/Win32/Win32Error.hpp>
#include <Bull/Core/System/Library.hpp>
#include <Bull/Core/Utility/StringUtils.hpp>
#include <Bull/Render/Context/Wgl/WglContext.hpp>
#include <Bull/Render/Context/Wgl/WglCreateContextARB.hpp>
#include <Bull/Render/Context/Wgl/WglMultisampleARB.hpp>
#include <Bull/Render/Context/Wgl/WglPbufferARB.hpp>
#include <Bull/Render/Context/Wgl/WglPixelFormatARB.hpp>
#include <Bull/Render/Context/Wgl/WglSwapControlEXT.hpp>
namespace Bull
{
namespace prv
{
void* WglContext::getFunction(const String& function)
{
void* functionProc = reinterpret_cast<void*>(wglGetProcAddress(function.getBuffer()));
if(functionProc)
{
return functionProc;
}
// wglGetProcAddress will set the last error to 127 if a function is not found but we don't care here
SetLastError(0);
static Library library("opengl32.dll");
if(!library)
{
return nullptr;
}
return reinterpret_cast<void*>(library.getFunction(function));
}
void WglContext::requireExtensions(ExtensionsLoader::Instance& loader)
{
loader->require(wglCreateContext);
loader->require(wglPixelFormat);
loader->require(wglSwapControl);
loader->require(wglPbuffer);
}
int WglContext::getBestPixelFormat(HDC device, Uint8 bitsPerPixel, const ContextSettings& settings, bool usePbuffer)
{
int bestPixelFormat = 0;
if(wglPixelFormat.isLoaded())
{
static const int attribs[] = {
WGL_DRAW_TO_WINDOW_ARB, 1,
WGL_SUPPORT_OPENGL_ARB, 1,
WGL_DOUBLE_BUFFER_ARB, 1,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
0
};
int formats[512];
UINT count = 0;
bool isValid = wglChoosePixelFormat(device, attribs, nullptr, 512, formats, &count) != 0;
if(isValid && count > 0)
{
int bestScore = std::numeric_limits<int>::max();
for(UINT i = 0; i < count; i++)
{
int format[7] = {0};
int sample[2] = {0};
static const int formatAttribs[] = {
WGL_RED_BITS_ARB,
WGL_GREEN_BITS_ARB,
WGL_BLUE_BITS_ARB,
WGL_ALPHA_BITS_ARB,
WGL_DEPTH_BITS_ARB,
WGL_STENCIL_BITS_ARB,
WGL_ACCELERATION_ARB
};
if(!wglGetPixelFormatAttribiv(device, formats[i], PFD_MAIN_PLANE, 7, formatAttribs, format))
{
break;
}
if(isSupported("WGL_ARB_multisample"))
{
static const int sampleAttribs[] = {
WGL_SAMPLE_BUFFERS_ARB,
WGL_SAMPLES_ARB
};
if(!wglGetPixelFormatAttribiv(device, formats[i], PFD_MAIN_PLANE, 2, sampleAttribs, sample))
{
break;
}
}
if(usePbuffer)
{
int pbuffer;
static const int pbufferAttribs[] = {
WGL_DRAW_TO_PBUFFER_ARB
};
if(!wglGetPixelFormatAttribiv(device, formats[i], PFD_MAIN_PLANE, 1, pbufferAttribs, &pbuffer))
{
break;
}
else if(pbuffer != 1)
{
continue;
}
}
/// We don't care about non hardware accelerated pixel format
if(format[6])
{
int colors = format[0] + format[1] + format[2] + format[3];
int score = evaluatePixelFormat(colors, format[4], format[5], sample[0] ? sample[1] : 0, bitsPerPixel, settings);
if(bestScore > score)
{
bestScore = score;
bestPixelFormat = formats[i];
}
}
}
}
}
if(usePbuffer)
{
return bestPixelFormat;
}
if(!bestPixelFormat)
{
PIXELFORMATDESCRIPTOR descriptor;
ZeroMemory(&descriptor, sizeof(descriptor));
descriptor.nSize = sizeof(descriptor);
descriptor.nVersion = 1;
descriptor.iLayerType = PFD_MAIN_PLANE;
descriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
descriptor.iPixelType = PFD_TYPE_RGBA;
descriptor.cColorBits = bitsPerPixel;
descriptor.cDepthBits = settings.depths;
descriptor.cStencilBits = settings.stencil;
descriptor.cAlphaBits = bitsPerPixel == 32 ? 8 : 0;
bestPixelFormat = ChoosePixelFormat(device, &descriptor);
}
return bestPixelFormat;
}
WglContext::WglContext(const WglContext* shared) :
WglContext(shared, VideoMode(1, 1), ContextSettings())
{
/// Nothing
}
WglContext::WglContext(const WglContext* shared, const VideoMode& mode, const ContextSettings& settings) :
GlContext(settings),
m_device(nullptr),
m_render(nullptr),
m_pbuffer(nullptr),
m_ownWindow(false)
{
createSurface(shared, mode.width, mode.height, mode.bitsPerPixel);
setPixelFormat(mode.bitsPerPixel);
createContext(shared);
}
WglContext::WglContext(const WglContext* shared, Uint8 bitsPerPixel, const ContextSettings& settings) :
WglContext(shared, VideoMode(1, 1, bitsPerPixel), settings)
{
/// Nothing
}
WglContext::WglContext(const WglContext* shared, const WindowImpl& window, Uint8 bitsPerPixel, const ContextSettings& settings) :
GlContext(settings),
m_device(nullptr),
m_render(nullptr),
m_pbuffer(nullptr),
m_ownWindow(false)
{
createSurface(window);
setPixelFormat(bitsPerPixel);
createContext(shared);
}
WglContext::~WglContext()
{
if(m_render)
{
if(wglGetCurrentContext() == m_render)
{
wglMakeCurrent(nullptr, nullptr);
}
wglDeleteContext(m_render);
}
if(m_device)
{
if(m_pbuffer)
{
wglReleasePbufferDC(m_pbuffer, m_device);
wglDestroyPbuffer(m_pbuffer);
}
else
{
ReleaseDC(m_window, m_device);
}
}
if(m_window && m_ownWindow)
{
DestroyWindow(m_window);
}
}
SurfaceHandler WglContext::getSurfaceHandler() const
{
return m_device;
}
void WglContext::display()
{
if(m_device && m_render)
{
SwapBuffers(m_device);
}
}
void WglContext::enableVsync(bool active)
{
if(wglSwapControl.isLoaded())
{
wglSwapInterval(active ? 1 : 0);
}
}
void WglContext::makeCurrent()
{
if(m_pbuffer)
{
int flag = 0;
wglQueryPbuffer(m_pbuffer, WGL_PBUFFER_LOST_ARB, &flag);
Expect(!flag, Throw(InternalError, "WglContext::makeCurrent", "PBuffer is became invalid"));
}
Expect(wglMakeCurrent(m_device, m_render), Throw(Win32Error, "WglContext::makeCurrent", "Failed to make context current"));
}
void WglContext::createSurface(const WindowImpl& window)
{
m_window = window.getSystemHandler();
m_device = GetDC(m_window);
Expect(m_device != INVALID_HANDLE_VALUE, Throw(Win32Error, "WglContext::createSurface", "Failed to get device context from WindowImpl"));
}
void WglContext::createSurface(const WglContext* shared, unsigned int width, unsigned int height, Uint8 bitsPerPixel)
{
if(wglPbuffer.isLoaded() && shared)
{
int format = getBestPixelFormat(shared->m_device, bitsPerPixel, m_settings, true);
if(format)
{
m_pbuffer = wglCreatePbuffer(shared->m_device, format, width, height, nullptr);
if(m_pbuffer)
{
m_device = wglGetPbufferDC(m_pbuffer);
if(!m_device)
{
m_log->warning("Failed to get device context from PBuffer");
wglDestroyPbuffer(m_pbuffer);
}
}
}
}
if(!m_device)
{
m_window = CreateWindow("STATIC", nullptr,
WS_DISABLED | WS_POPUP,
0, 0,
width, height,
nullptr,
nullptr,
GetModuleHandle(nullptr),
nullptr);
Expect(m_window != INVALID_HANDLE_VALUE, Throw(Win32Error, "WglContext::createSurface", "Failed to create internal window"));
m_device = GetDC(m_window);
Expect(m_device != INVALID_HANDLE_VALUE, Throw(Win32Error, "WglContext::createSurface", "Failed to get device context"));
m_ownWindow = true;
}
}
void WglContext::setPixelFormat(Uint8 bitsPerPixel)
{
PIXELFORMATDESCRIPTOR descriptor;
int bestFormat = getBestPixelFormat(m_device, bitsPerPixel, m_settings);
descriptor.nSize = sizeof(PIXELFORMATDESCRIPTOR);
descriptor.nVersion = 1;
DescribePixelFormat(m_device, bestFormat, sizeof(PIXELFORMATDESCRIPTOR), &descriptor);
Expect(SetPixelFormat(m_device, bestFormat, &descriptor), Throw(Win32Error, "WglContext::setPixelFormat", "Failed to set pixel format"));
}
void WglContext::createContext(const WglContext* shared)
{
HGLRC sharedHandler = shared ? shared->m_render : nullptr;
if(wglCreateContext.isLoaded())
{
do
{
std::vector<int> attribs;
attribs.emplace_back(WGL_CONTEXT_MAJOR_VERSION_ARB);
attribs.emplace_back(m_settings.major);
attribs.emplace_back(WGL_CONTEXT_MINOR_VERSION_ARB);
attribs.emplace_back(m_settings.minor);
if(isSupported("WGL_ARB_create_context_profile"))
{
int flags = 0;
int profile = (m_settings.profile == ContextSettingsProfile_Compatibility) ? WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB : WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
if(m_settings.type == ContextSettingsType_Debug)
{
flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
}
if(m_settings.type == ContextSettingsType_ForwardCompatible)
{
flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
}
attribs.emplace_back(WGL_CONTEXT_PROFILE_MASK_ARB);
attribs.emplace_back(profile);
attribs.emplace_back(WGL_CONTEXT_FLAGS_ARB);
attribs.emplace_back(flags);
}
attribs.emplace_back(0);
m_render = wglCreateContextAttribs(m_device, sharedHandler, &attribs[0]);
if(!m_render)
{
m_log->warning("Failed to create WglContext with version " + StringUtils::number(m_settings.major) + "." + StringUtils::number(m_settings.minor));
if(m_settings.minor == 0)
{
m_settings.major -= 1;
m_settings.minor = 9;
}
else
{
m_settings.minor -= 1;
}
}
else
{
m_log->info("Create WglContext with version " + StringUtils::number(m_settings.major) + "." + StringUtils::number(m_settings.minor));
}
}while(!m_render && m_settings.major >= 1);
}
if(m_render == nullptr)
{
m_render = ::wglCreateContext(m_device);
Expect(m_render, Throw(InternalError, "WglContext::createContext", "Failed to create legacy/shared WglContext"));
if(shared)
{
static std::mutex mutex;
m_log->info("Create legacy WglContext");
std::lock_guard<std::mutex> lock(mutex);
wglShareLists(sharedHandler, m_render);
}
else
{
m_log->info("Create shared WglContext");
}
}
updateSettings();
}
void WglContext::updateSettings()
{
PIXELFORMATDESCRIPTOR pfd;
pfd.nVersion = 1;
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
int pixelFormat = GetPixelFormat(m_device);
DescribePixelFormat(m_device, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
if(wglPixelFormat.isLoaded())
{
int format[2] = {0};
static const int formatAttribs[] = {
WGL_DEPTH_BITS_ARB,
WGL_STENCIL_BITS_ARB
};
if(wglGetPixelFormatAttribiv(m_device, pixelFormat, PFD_MAIN_PLANE, 2, formatAttribs, format))
{
m_settings.depths = static_cast<Uint8>(format[0]);
m_settings.stencil = static_cast<Uint8>(format[1]);
}
else
{
m_settings.depths = pfd.cDepthBits;
m_settings.stencil = pfd.cStencilBits;
}
if(isSupported("WGL_ARB_multisample"))
{
int sample[2] = {0};
static const int sampleAttribs[] = {
WGL_SAMPLE_BUFFERS_ARB,
WGL_SAMPLES_ARB
};
if(wglGetPixelFormatAttribiv(m_device, pixelFormat, PFD_MAIN_PLANE, 2, sampleAttribs, sample))
{
m_settings.antialiasing = sample[0] ? sample[1] : 0;
}
else
{
m_settings.antialiasing = 0;
}
}
else
{
m_settings.antialiasing = 0;
}
}
else
{
m_settings.depths = pfd.cDepthBits;
m_settings.stencil = pfd.cStencilBits;
m_settings.antialiasing = 0;
}
}
}
}
|
Validate device context before create the render context
|
[Render/WglContext] Validate device context before create the render context
|
C++
|
mit
|
siliace/Bull
|
9790c4fcd209f6616c4451164bc1e6427aa1569b
|
groups/bal/balm/balm_category.cpp
|
groups/bal/balm/balm_category.cpp
|
// balm_category.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <balm_category.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(balm_category_cpp,"$Id$ $CSID$")
#include <bsl_ostream.h>
namespace BloombergLP {
namespace balm {
// --------------
// class Category
// --------------
// CREATORS
Category::~Category()
{
// Reset the linked-list of category holders registered with this object.
while (d_holders_p) {
CategoryHolder *next = d_holders_p->next();
d_holders_p->reset();
d_holders_p = next;
}
}
// MANIPULATORS
void Category::setEnabled(bool enabledFlag)
{
if (d_enabled != enabledFlag) {
// Update the linked-list of category holder's registered with this
// category.
CategoryHolder *holder = d_holders_p;
while (holder) {
holder->setEnabled(enabledFlag);
holder = holder->next();
}
d_enabled = enabledFlag;
}
}
void Category::registerCategoryHolder(CategoryHolder *holder)
{
holder->setEnabled(d_enabled);
holder->setCategory(this);
holder->setNext(d_holders_p);
d_holders_p = holder;
}
// ACCESSORS
bsl::ostream& Category::print(bsl::ostream& stream) const
{
stream << "[ " << d_name_p << (d_enabled ? " ENABLED ]" : " DISABLED ]");
return stream;
}
// --------------------
// class CategoryHolder
// --------------------
// MANIPULATORS
void CategoryHolder::reset()
{
d_enabled = false;
d_category_p = 0;
d_next_p = 0;
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
|
// balm_category.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <balm_category.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(balm_category_cpp,"$Id$ $CSID$")
#include <bsl_ostream.h>
namespace BloombergLP {
namespace balm {
// --------------
// class Category
// --------------
// CREATORS
Category::~Category()
{
// Reset the linked-list of category holders registered with this object.
while (d_holders_p) {
CategoryHolder *next = d_holders_p->next();
d_holders_p->reset();
d_holders_p = next;
}
}
// MANIPULATORS
void Category::setEnabled(bool enabledFlag)
{
// Note that in practice, this is only called by
// 'MetricsManager::setCategoryEnabled', which performs the function under
// a lock.
if (d_enabled != enabledFlag) {
// Update the linked-list of category holder's registered with this
// category.
CategoryHolder *holder = d_holders_p;
while (holder) {
holder->setEnabled(enabledFlag);
holder = holder->next();
}
d_enabled = enabledFlag;
}
}
void Category::registerCategoryHolder(CategoryHolder *holder)
{
holder->setEnabled(d_enabled);
holder->setCategory(this);
holder->setNext(d_holders_p);
d_holders_p = holder;
}
// ACCESSORS
bsl::ostream& Category::print(bsl::ostream& stream) const
{
stream << "[ " << d_name_p << (d_enabled ? " ENABLED ]" : " DISABLED ]");
return stream;
}
// --------------------
// class CategoryHolder
// --------------------
// MANIPULATORS
void CategoryHolder::reset()
{
d_enabled = false;
d_category_p = 0;
d_next_p = 0;
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
|
Update balm_category.cpp
|
Update balm_category.cpp
|
C++
|
apache-2.0
|
che2/bde,che2/bde,che2/bde,bloomberg/bde,bloomberg/bde,bloomberg/bde,che2/bde,bloomberg/bde,bloomberg/bde
|
0581a4f8703bd7063b3f582b6e6d18a83d667af8
|
C++/counting-bits.cpp
|
C++/counting-bits.cpp
|
// Time: O(n)
// Space: O(n)
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res{0};
for (int i = 0, cnt = res.size();
res.size() <= num;
i = (i + 1) % cnt) {
if (i == 0) {
cnt = res.size();
}
res.emplace_back(res[i] + 1);
}
return res;
}
};
|
// Time: O(n)
// Space: O(n)
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res{0};
for (int i = 1; i <= num; ++i) {
res.emplace_back(res[i >> 1] + (i & 1));
}
return res;
}
};
// Time: O(n)
// Space: O(n)
class Solution2 {
public:
vector<int> countBits(int num) {
vector<int> res{0};
for (int i = 0, cnt = res.size();
res.size() <= num;
i = (i + 1) % cnt) {
if (i == 0) {
cnt = res.size();
}
res.emplace_back(res[i] + 1);
}
return res;
}
};
|
Update counting-bits.cpp
|
Update counting-bits.cpp
|
C++
|
mit
|
yiwen-luo/LeetCode,yiwen-luo/LeetCode,githubutilities/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,yiwen-luo/LeetCode,githubutilities/LeetCode,jaredkoontz/leetcode,jaredkoontz/leetcode,githubutilities/LeetCode,kamyu104/LeetCode,yiwen-luo/LeetCode,githubutilities/LeetCode,jaredkoontz/leetcode,githubutilities/LeetCode,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015
|
a3f3255bf3d8cb4f35d351580eb867506a4874cb
|
C++/single-number.cpp
|
C++/single-number.cpp
|
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param A: Array of integers.
* return: The single number.
*/
int singleNumber(vector<int> &A) {
int single = 0;
for (const auto& i : A) {
single ^= i;
}
return single;
}
};
|
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param A: Array of integers.
* return: The single number.
*/
int singleNumber(vector<int> &A) {
return accumulate(A.cbegin(), A.cend(), 0, std::bit_xor<int>());
}
};
class Solution2 {
public:
/**
* @param A: Array of integers.
* return: The single number.
*/
int singleNumber(vector<int> &A) {
int single = 0;
for (const auto& i : A) {
single ^= i;
}
return single;
}
};
|
Update single-number.cpp
|
Update single-number.cpp
|
C++
|
mit
|
kamyu104/LintCode,jaredkoontz/lintcode,jaredkoontz/lintcode,kamyu104/LintCode,jaredkoontz/lintcode,kamyu104/LintCode
|
0a23232a5fd1e0d4b6c4af0043a7139b07068db5
|
depthview2/include/dv_vrdriver.hpp
|
depthview2/include/dv_vrdriver.hpp
|
#include "dvvirtualscreenmanager.hpp"
#include <QVector>
#include <QVector2D>
#include <QVector3D>
class QQuickItem;
class DV_VRDriver {
protected:
DVWindow* window;
/* Only used by subclasses. */
DV_VRDriver(DVWindow* w);
public:
virtual ~DV_VRDriver() = 0;
virtual bool render() = 0;
virtual void frameSwapped() = 0;
uint32_t renderWidth, renderHeight;
QQuickItem* backgroundImageItem = nullptr;
bool lockMouse;
bool mirrorUI;
bool snapSurroundPan;
qreal screenCurve;
qreal screenSize;
qreal screenDistance;
qreal screenHeight;
qreal renderSizeFac;
QUrl backgroundImage;
DVSourceMode::Type backgroundSourceMode;
bool backgroundSwap;
qreal backgroundPan;
qreal backgroundDim;
QVector<QVector3D> screen;
QVector<QVector2D> screenUV;
QString errorString;
#ifdef DV_OPENVR
static DV_VRDriver* createOpenVRDriver(DVWindow* window);
#endif
};
|
#include "dvvirtualscreenmanager.hpp"
#include <QVector>
#include <QVector2D>
#include <QVector3D>
class QQuickItem;
class DV_VRDriver {
protected:
DVWindow* window;
/* Only used by subclasses. */
DV_VRDriver(DVWindow* w);
public:
virtual ~DV_VRDriver() = default;
virtual bool render() = 0;
virtual void frameSwapped() = 0;
uint32_t renderWidth, renderHeight;
QQuickItem* backgroundImageItem = nullptr;
bool lockMouse;
bool mirrorUI;
bool snapSurroundPan;
qreal screenCurve;
qreal screenSize;
qreal screenDistance;
qreal screenHeight;
qreal renderSizeFac;
QUrl backgroundImage;
DVSourceMode::Type backgroundSourceMode;
bool backgroundSwap;
qreal backgroundPan;
qreal backgroundDim;
QVector<QVector3D> screen;
QVector<QVector2D> screenUV;
QString errorString;
#ifdef DV_OPENVR
static DV_VRDriver* createOpenVRDriver(DVWindow* window);
#endif
};
|
Fix last commit not building on Windows.
|
Fix last commit not building on Windows.
|
C++
|
mit
|
chipgw/depthview2
|
3c348c2d3fcd6f8ea6553e3f81f6641c05d56c0e
|
src/core/film.cpp
|
src/core/film.cpp
|
/*
MIT License
Copyright (c) 2019 ZhuQian
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 "core/film.h"
#include "core/memory.h"
#include "core/imageio.h"
NARUKAMI_BEGIN
Film::Film(const Point2i &resolution, const Bounds2f &cropped_pixel_bounds,float const filter_radius,const float gaussian_alpha) : resolution(resolution),_filter_radius(filter_radius),_inv_filter_radius(1.0f/filter_radius),_gaussian_alpha(gaussian_alpha),_gaussian_exp(exp(-gaussian_alpha*FILTER_RADIUS*FILTER_RADIUS))
{
Point2i bounds_min_p = Point2i((int)ceil(resolution.x * cropped_pixel_bounds.min_point.x), (int)ceil(resolution.y * cropped_pixel_bounds.min_point.y));
Point2i bounds_max_p = Point2i((int)ceil(resolution.x * cropped_pixel_bounds.max_point.x), (int)ceil(resolution.y * cropped_pixel_bounds.max_point.y));
this->_cropped_pixel_bounds = Bounds2i(bounds_min_p, bounds_max_p);
_pixels = std::unique_ptr<Pixel[]>(new Pixel[area(_cropped_pixel_bounds)]);
//init filter LUT
for(int i=0;i<FILTER_LUT_WIDTH;++i){
float x = (i+0.5f)/FILTER_LUT_WIDTH;
_filter_lut[i]=gaussian_1D(x);
}
}
Pixel &Film::get_pixel(const Point2i &p) const
{
assert(inside_exclusive(p, _cropped_pixel_bounds));
auto width = _cropped_pixel_bounds[1].x - _cropped_pixel_bounds[0].x;
auto x = p.x - _cropped_pixel_bounds[0].x;
auto y = p.y - _cropped_pixel_bounds[0].y;
return _pixels[y * width + x];
}
float Film::gaussian_1D(float x) const
{
return max(0.0f,exp(-_gaussian_alpha*x*x)-_gaussian_exp);
}
void Film::write_to_file(const char *file_name) const
{
std::vector<float> data;
for (int y = _cropped_pixel_bounds[0].y; y < _cropped_pixel_bounds[1].y; ++y)
{
for (int x = _cropped_pixel_bounds[0].x; x < _cropped_pixel_bounds[1].x; ++x)
{
const Pixel &pixel = get_pixel(Point2i(x, y));
float inv_w = rcp(pixel.weight);
if(EXPECT_NOT_TAKEN(pixel.weight==0.0f)){
inv_w=1.0f;
}
data.push_back(pixel.rgb[0] * inv_w);
data.push_back(pixel.rgb[1] * inv_w);
data.push_back(pixel.rgb[2] * inv_w);
}
}
write_image_to_file(file_name, &data[0], resolution.x, resolution.y);
}
void Film::add_sample(const Point2f &pos, const Spectrum &l, const float weight) const
{
//calculate bounds
auto dp=pos-Vector2f(0.5f,0.5f);
Point2i p0=(Point2i)ceil(dp-_filter_radius);
Point2i p1=(Point2i)floor(dp+_filter_radius) + Point2i(1, 1);
p0=max(p0,_cropped_pixel_bounds.min_point);
p1=min(p1,_cropped_pixel_bounds.max_point);
for(int x = p0.x;x<p1.x;++x){
int idx_x=min((int)floor(abs(x-dp.x)*_inv_filter_radius*FILTER_LUT_WIDTH),FILTER_LUT_WIDTH-1);
float filter_weight_x = _filter_lut[idx_x];
for(int y = p0.y;y<p1.y;++y){
int idx_y=min((int)floor(abs(y-dp.y)*_inv_filter_radius*FILTER_LUT_WIDTH),FILTER_LUT_WIDTH-1);
float filter_weight = _filter_lut[idx_y]*filter_weight_x;
Pixel &pixel = get_pixel( Point2i(x,y));
pixel.rgb[0] += l.r * weight*filter_weight;
pixel.rgb[1] += l.g * weight*filter_weight;
pixel.rgb[2] += l.b * weight*filter_weight;
pixel.weight += filter_weight;
}
}
}
NARUKAMI_END
|
/*
MIT License
Copyright (c) 2019 ZhuQian
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 "core/film.h"
#include "core/memory.h"
#include "core/imageio.h"
NARUKAMI_BEGIN
Film::Film(const Point2i &resolution, const Bounds2f &cropped_pixel_bounds,float const filter_radius,const float gaussian_alpha) : resolution(resolution),_filter_radius(filter_radius),_inv_filter_radius(1.0f/filter_radius),_gaussian_alpha(gaussian_alpha),_gaussian_exp(exp(-gaussian_alpha*filter_radius*filter_radius))
{
Point2i bounds_min_p = Point2i((int)ceil(resolution.x * cropped_pixel_bounds.min_point.x), (int)ceil(resolution.y * cropped_pixel_bounds.min_point.y));
Point2i bounds_max_p = Point2i((int)ceil(resolution.x * cropped_pixel_bounds.max_point.x), (int)ceil(resolution.y * cropped_pixel_bounds.max_point.y));
this->_cropped_pixel_bounds = Bounds2i(bounds_min_p, bounds_max_p);
_pixels = std::unique_ptr<Pixel[]>(new Pixel[area(_cropped_pixel_bounds)]);
//init filter LUT
for(int i=0;i<FILTER_LUT_WIDTH;++i){
float x = (i+0.5f)/FILTER_LUT_WIDTH;
_filter_lut[i]=gaussian_1D(x);
}
}
Pixel &Film::get_pixel(const Point2i &p) const
{
assert(inside_exclusive(p, _cropped_pixel_bounds));
auto width = _cropped_pixel_bounds[1].x - _cropped_pixel_bounds[0].x;
auto x = p.x - _cropped_pixel_bounds[0].x;
auto y = p.y - _cropped_pixel_bounds[0].y;
return _pixels[y * width + x];
}
float Film::gaussian_1D(float x) const
{
return max(0.0f,exp(-_gaussian_alpha*x*x)-_gaussian_exp);
}
void Film::write_to_file(const char *file_name) const
{
std::vector<float> data;
for (int y = _cropped_pixel_bounds[0].y; y < _cropped_pixel_bounds[1].y; ++y)
{
for (int x = _cropped_pixel_bounds[0].x; x < _cropped_pixel_bounds[1].x; ++x)
{
const Pixel &pixel = get_pixel(Point2i(x, y));
float inv_w = rcp(pixel.weight);
if(EXPECT_NOT_TAKEN(pixel.weight==0.0f)){
inv_w=1.0f;
}
data.push_back(pixel.rgb[0] * inv_w);
data.push_back(pixel.rgb[1] * inv_w);
data.push_back(pixel.rgb[2] * inv_w);
}
}
write_image_to_file(file_name, &data[0], resolution.x, resolution.y);
}
void Film::add_sample(const Point2f &pos, const Spectrum &l, const float weight) const
{
//calculate bounds
auto dp=pos-Vector2f(0.5f,0.5f);
Point2i p0=(Point2i)ceil(dp-_filter_radius);
Point2i p1=(Point2i)floor(dp+_filter_radius) + Point2i(1, 1);
p0=max(p0,_cropped_pixel_bounds.min_point);
p1=min(p1,_cropped_pixel_bounds.max_point);
for(int x = p0.x;x<p1.x;++x){
int idx_x=min((int)floor(abs(x-dp.x)*_inv_filter_radius*FILTER_LUT_WIDTH),FILTER_LUT_WIDTH-1);
float filter_weight_x = _filter_lut[idx_x];
for(int y = p0.y;y<p1.y;++y){
int idx_y=min((int)floor(abs(y-dp.y)*_inv_filter_radius*FILTER_LUT_WIDTH),FILTER_LUT_WIDTH-1);
float filter_weight = _filter_lut[idx_y]*filter_weight_x;
Pixel &pixel = get_pixel( Point2i(x,y));
pixel.rgb[0] += l.r * weight*filter_weight;
pixel.rgb[1] += l.g * weight*filter_weight;
pixel.rgb[2] += l.b * weight*filter_weight;
pixel.weight += filter_weight;
}
}
}
NARUKAMI_END
|
fix a compile error
|
fix a compile error
|
C++
|
mit
|
zq317157782/Narukami,zq317157782/Narukami,zq317157782/Narukami
|
594c061c603359ef9c5273e19e5eb9e7114a6a68
|
2019/src/day06.cpp
|
2019/src/day06.cpp
|
#include <iostream>
#include <regex>
#include <queue>
#include <unordered_set>
#include "days.hpp"
namespace {
std::vector<std::pair<std::string, std::string>> read_orbits(std::istream &input) {
std::vector<std::pair<std::string, std::string>> result;
std::string buffer;
std::regex regex("^([A-Z0-9]+)\\)([A-Z0-9]+)$");
std::smatch match_results;
while (std::getline(input, buffer)) {
if (!std::regex_match(buffer, match_results, regex)) {
std::string error = "Invalid line: ";
error += buffer;
throw std::domain_error(error);
}
result.emplace_back(match_results[1], match_results[2]);
}
return result;
}
}
void aoc2019::day06_part1(std::istream &input, std::ostream &output) {
std::unordered_map<std::string, std::vector<std::string>> orbits;
for (auto[a, b] : read_orbits(input)) {
orbits[std::move(a)].emplace_back(std::move(b));
}
std::deque<std::pair<std::string, int>> todo = {{"COM", 0}};
int total_orbits = 0;
while (!todo.empty()) {
auto[name, offset] = todo.front();
todo.pop_front();
total_orbits += offset;
for (const auto& partner : orbits[name]) {
todo.emplace_back(partner, offset + 1);
}
}
output << total_orbits << std::endl;
}
void aoc2019::day06_part2(std::istream &input, std::ostream &output) {
std::unordered_map<std::string, std::string> ancestors;
for (auto[a, b] : read_orbits(input)) {
ancestors[std::move(b)] = std::move(a);
}
std::unordered_map<std::string, int> santa_ancestors;
for (auto current = ancestors["SAN"]; current != "COM"; current = ancestors[current]) {
santa_ancestors[ancestors[current]] = santa_ancestors[current] + 1;
}
int dist = 0;
for (auto current = ancestors["YOU"]; current != "COM"; current = ancestors[current], ++dist) {
if (auto it = santa_ancestors.find(current); it != santa_ancestors.end()) {
output << dist + it->second << std::endl;
return;
}
}
throw std::domain_error("No valid path.");
}
|
#include <deque>
#include <iostream>
#include <unordered_map>
#include <vector>
#include "days.hpp"
namespace {
std::vector<std::pair<std::string, std::string>> read_orbits(std::istream &input) {
std::vector<std::pair<std::string, std::string>> result;
std::string name1, name2;
while (std::getline(input, name1, ')')) {
std::getline(input, name2);
result.emplace_back(name1, name2);
}
return result;
}
}
void aoc2019::day06_part1(std::istream &input, std::ostream &output) {
std::unordered_map<std::string, std::vector<std::string>> orbits;
for (auto[a, b] : read_orbits(input)) {
orbits[std::move(a)].emplace_back(std::move(b));
}
std::deque<std::pair<std::string, int>> todo = {{"COM", 0}};
int total_orbits = 0;
while (!todo.empty()) {
auto[name, offset] = todo.front();
todo.pop_front();
total_orbits += offset;
for (const auto& partner : orbits[name]) {
todo.emplace_back(partner, offset + 1);
}
}
output << total_orbits << std::endl;
}
void aoc2019::day06_part2(std::istream &input, std::ostream &output) {
std::unordered_map<std::string, std::string> ancestors;
for (auto[a, b] : read_orbits(input)) {
ancestors[std::move(b)] = std::move(a);
}
std::unordered_map<std::string, int> santa_ancestors;
for (auto current = ancestors["SAN"]; current != "COM"; current = ancestors[current]) {
santa_ancestors[ancestors[current]] = santa_ancestors[current] + 1;
}
int dist = 0;
for (auto current = ancestors["YOU"]; current != "COM"; current = ancestors[current], ++dist) {
if (auto it = santa_ancestors.find(current); it != santa_ancestors.end()) {
output << dist + it->second << std::endl;
return;
}
}
throw std::domain_error("No valid path.");
}
|
Replace regex with simpler string parsing.
|
Replace regex with simpler string parsing.
Remove the dependency on std::regex which is slow to both compile and
run. Saves about half the execution time.
|
C++
|
mit
|
bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode
|
2ab8e5360ce2d5cb4f65894a19c7b05c5e0382c9
|
src/find_includes.cpp
|
src/find_includes.cpp
|
#include "find_includes.hpp"
using std::shared_ptr;
using std::make_shared;
using std::static_pointer_cast;
using std::vector;
using std::set;
using std::map;
using std::move;
using std::string;
namespace backend {
find_includes::find_includes(const registry& reg)
: m_reg(reg), m_outer(true) {}
find_includes::result_type find_includes::operator()(const suite& n) {
bool outer_suite = m_outer;
m_outer = false;
shared_ptr<const suite> rewritten =
static_pointer_cast<const suite>(this->rewriter::operator()(n));
if (!outer_suite) {
return rewritten;
}
//We're the outer suite, add include statements
vector<shared_ptr<const statement> > augmented_statements;
for(auto i = m_includes.begin();
i != m_includes.end();
i++) {
augmented_statements.push_back(
make_shared<include>(
make_shared<literal>(
*i)));
}
for(auto i = n.begin();
i != n.end();
i++) {
augmented_statements.push_back(
static_pointer_cast<const statement>(n.ptr()));
}
return make_shared<const suite>(move(augmented_statements));
}
find_includes::result_type find_includes::operator()(const apply& n) {
const string& fn_name = n.fn().id();
const map<string, string>& include_map = m_reg.fn_includes();
auto include_it = include_map.find(fn_name);
if (include_it != include_map.end()) {
m_includes.insert(include_it->second);
}
return this->rewriter::operator()(n);
}
}
|
#include "find_includes.hpp"
using std::shared_ptr;
using std::make_shared;
using std::static_pointer_cast;
using std::vector;
using std::set;
using std::map;
using std::move;
using std::string;
namespace backend {
find_includes::find_includes(const registry& reg)
: m_reg(reg), m_outer(true) {}
find_includes::result_type find_includes::operator()(const suite& n) {
bool outer_suite = m_outer;
m_outer = false;
shared_ptr<const suite> rewritten =
static_pointer_cast<const suite>(this->rewriter::operator()(n));
if (!outer_suite) {
return rewritten;
}
//We're the outer suite, add include statements
vector<shared_ptr<const statement> > augmented_statements;
for(auto i = m_includes.begin();
i != m_includes.end();
i++) {
augmented_statements.push_back(
make_shared<include>(
make_shared<literal>(
*i)));
}
for(auto i = n.begin();
i != n.end();
i++) {
augmented_statements.push_back(
static_pointer_cast<const statement>(i->ptr()));
}
return make_shared<const suite>(move(augmented_statements));
}
find_includes::result_type find_includes::operator()(const apply& n) {
const string& fn_name = n.fn().id();
const map<string, string>& include_map = m_reg.fn_includes();
auto include_it = include_map.find(fn_name);
if (include_it != include_map.end()) {
m_includes.insert(include_it->second);
}
return this->rewriter::operator()(n);
}
}
|
Fix double include bug.
|
Fix double include bug.
|
C++
|
apache-2.0
|
copperhead/copperhead-compiler,copperhead/copperhead-compiler,copperhead/copperhead-compiler
|
8c723f3f326674de02841d50c9160155232c2662
|
src/dbn_mnist.cpp
|
src/dbn_mnist.cpp
|
//=======================================================================
// 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)
//=======================================================================
#include <iostream>
#include <memory>
#include "dbn.hpp"
#include "layer.hpp"
#include "conf.hpp"
#include "mnist_reader.hpp"
#include "image_utils.hpp"
int main(int argc, char* argv[]){
auto prediction = false;
if(argc > 1){
std::string command(argv[1]);
if(command == "predict"){
prediction = true;
}
}
auto training_images = mnist::read_training_images();
binarize_each(training_images);
typedef dbn::dbn<dbn::conf<>, dbn::layer<28 * 28, 500>, dbn::layer<500, 2000>, dbn::layer<2000, 10>> dbn_t;
auto dbn = std::make_shared<dbn_t>();
dbn->train(training_images, 5);
//TODO Train
if(prediction){
//TODO
}
return 0;
}
|
//=======================================================================
// 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)
//=======================================================================
#include <iostream>
#include <memory>
#include "dbn.hpp"
#include "layer.hpp"
#include "conf.hpp"
#include "mnist_reader.hpp"
#include "image_utils.hpp"
int main(int argc, char* argv[]){
auto prediction = false;
if(argc > 1){
std::string command(argv[1]);
if(command == "predict"){
prediction = true;
}
}
auto training_images = mnist::read_training_images();
binarize_each(training_images);
typedef dbn::dbn<dbn::conf<true, 50>, dbn::layer<28 * 28, 100>, dbn::layer<100, 300>, dbn::layer<300, 500>> dbn_t;
auto dbn = std::make_shared<dbn_t>();
dbn->train(training_images, 5);
//TODO Train
if(prediction){
//TODO
}
return 0;
}
|
Use momentum
|
Use momentum
|
C++
|
mit
|
wichtounet/dll,wichtounet/dll,wichtounet/dll
|
c4aaf4c7c98a01cde67413d2c17752ea5d175d53
|
src/devicemanager.cpp
|
src/devicemanager.cpp
|
/*
Copyright (C) 2007-2008 Tanguy Krotoff <[email protected]>
Copyright (C) 2008 Lukas Durfina <[email protected]>
Copyright (C) 2009 Fathi Boudra <[email protected]>
Copyright (C) 2009-2010 vlc-phonon AUTHORS
Copyright (C) 2011 Harald Sitter <[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, see <http://www.gnu.org/licenses/>.
*/
#include "devicemanager.h"
#ifdef PHONON_PULSESUPPORT
# include <phonon/pulsesupport.h>
#endif
#include <vlc/vlc.h>
#include "backend.h"
#include "utils/debug.h"
#include "utils/libvlc.h"
#include "utils/vstring.h"
QT_BEGIN_NAMESPACE
namespace Phonon
{
namespace VLC
{
/*
* Device Info
*/
DeviceInfo::DeviceInfo(const QString &name, bool isAdvanced)
{
// Get an id
static int counter = 0;
m_id = counter++;
// Get name and description for the device
m_name = name;
m_isAdvanced = isAdvanced;
m_capabilities = None;
// A default device should never be advanced
if (name.startsWith("default", Qt::CaseInsensitive))
m_isAdvanced = false;
}
int DeviceInfo::id() const
{
return m_id;
}
const QString& DeviceInfo::name() const
{
return m_name;
}
const QString& DeviceInfo::description() const
{
return m_description;
}
bool DeviceInfo::isAdvanced() const
{
return m_isAdvanced;
}
void DeviceInfo::setAdvanced(bool advanced)
{
m_isAdvanced = advanced;
}
const DeviceAccessList& DeviceInfo::accessList() const
{
return m_accessList;
}
void DeviceInfo::addAccess(const DeviceAccess& access)
{
if (m_accessList.isEmpty())
m_description = access.first + ": " + access.second;
m_accessList.append(access);
}
quint16 DeviceInfo::capabilities() const
{
return m_capabilities;
}
void DeviceInfo::setCapabilities(quint16 cap)
{
m_capabilities = cap;
}
/*
* Device Manager
*/
DeviceManager::DeviceManager(Backend *parent)
: QObject(parent)
, m_backend(parent)
{
Q_ASSERT(parent);
updateDeviceList();
}
DeviceManager::~DeviceManager()
{
}
QList<int> DeviceManager::deviceIds(ObjectDescriptionType type)
{
DeviceInfo::Capability capability = DeviceInfo::None;
switch (type) {
case Phonon::AudioOutputDeviceType:
capability = DeviceInfo::AudioOutput;
break;
case Phonon::AudioCaptureDeviceType:
capability = DeviceInfo::AudioCapture;
break;
case Phonon::VideoCaptureDeviceType:
capability = DeviceInfo::VideoCapture;
break;
default: ;
}
QList<int> ids;
foreach (const DeviceInfo &device, m_devices) {
if (device.capabilities() & capability)
ids.append(device.id());
}
return ids;
}
QHash<QByteArray, QVariant> DeviceManager::deviceProperties(int id)
{
QHash<QByteArray, QVariant> properties;
foreach (const DeviceInfo &device, m_devices) {
if (device.id() == id) {
properties.insert("name", device.name());
properties.insert("description", device.description());
properties.insert("isAdvanced", device.isAdvanced());
properties.insert("deviceAccessList", QVariant::fromValue<Phonon::DeviceAccessList>(device.accessList()));
properties.insert("discovererIcon", "vlc");
if (device.capabilities() & DeviceInfo::AudioOutput) {
properties.insert("icon", QLatin1String("audio-card"));
}
if (device.capabilities() & DeviceInfo::AudioCapture) {
properties.insert("hasaudio", true);
properties.insert("icon", QLatin1String("audio-input-microphone"));
}
if (device.capabilities() & DeviceInfo::VideoCapture) {
properties.insert("hasvideo", true);
properties.insert("icon", QLatin1String("camera-web"));
}
break;
}
}
return properties;
}
const DeviceInfo *DeviceManager::device(int id) const
{
for (int i = 0; i < m_devices.size(); i ++) {
if (m_devices[i].id() == id)
return &m_devices[i];
}
return NULL;
}
static QList<QByteArray> vlcAudioOutBackends()
{
QList<QByteArray> ret;
libvlc_audio_output_t *firstAudioOut = libvlc_audio_output_list_get(libvlc);
if (!firstAudioOut) {
error() << "libVLC:" << LibVLC::errorMessage();
return ret;
}
for (libvlc_audio_output_t *audioOut = firstAudioOut; audioOut; audioOut = audioOut->p_next) {
QByteArray name(audioOut->psz_name);
if (!ret.contains(name))
ret.append(name);
}
libvlc_audio_output_list_release(firstAudioOut);
return ret;
}
void DeviceManager::updateDeviceList()
{
QList<DeviceInfo> newDeviceList;
if (!LibVLC::self || !libvlc)
return;
QList<QByteArray> audioOutBackends = vlcAudioOutBackends();
#ifdef PHONON_PULSESUPPORT
PulseSupport *pulse = PulseSupport::getInstance();
if (pulse && pulse->isActive()) {
if (audioOutBackends.contains("pulse")) {
DeviceInfo defaultAudioOutputDevice(tr("Default"), false);
defaultAudioOutputDevice.setCapabilities(DeviceInfo::AudioOutput);
defaultAudioOutputDevice.addAccess(DeviceAccess("pulse", "default"));
newDeviceList.append(defaultAudioOutputDevice);
return;
} else {
pulse->enable(false);
}
}
#endif
QList<QByteArray> knownSoundSystems;
// Whitelist
knownSoundSystems << QByteArray("alsa")
<< QByteArray("oss")
<< QByteArray("jack")
<< QByteArray("directx") // Windows
<< QByteArray("auhal"); // Mac
foreach (const QByteArray &soundSystem, knownSoundSystems) {
if (audioOutBackends.contains(soundSystem)) {
const int deviceCount = libvlc_audio_output_device_count(libvlc, soundSystem);
for (int i = 0; i < deviceCount; i++) {
VString idName(libvlc_audio_output_device_id(libvlc, soundSystem, i));
VString longName(libvlc_audio_output_device_longname(libvlc, soundSystem, i));
DeviceInfo device(longName, true);
device.addAccess(DeviceAccess(soundSystem, idName));
device.setCapabilities(DeviceInfo::AudioOutput);
newDeviceList.append(device);
}
// libVLC gives no devices for some sound systems, like OSS
if (!deviceCount) {
DeviceInfo device(QString("Default %1").arg(QString(soundSystem)), true);
device.addAccess(DeviceAccess(soundSystem, ""));
device.setCapabilities(DeviceInfo::AudioOutput);
newDeviceList.append(device);
}
}
}
/*
* Compares the list with the devices available at the moment with the last list. If
* a new device is seen, a signal is emitted. If a device disappeared, another signal
* is emitted.
*/
// Search for added devices
for (int i = 0; i < newDeviceList.count(); ++i) {
int id = newDeviceList[i].id();
if (!listContainsDevice(m_devices, id)) {
// This is a new device, add it
m_devices.append(newDeviceList[i]);
emit deviceAdded(id);
debug() << "Added backend device" << newDeviceList[i].name();
}
}
// Search for removed devices
for (int i = m_devices.count() - 1; i >= 0; --i) {
int id = m_devices[i].id();
if (!listContainsDevice(newDeviceList, id)) {
emit deviceRemoved(id);
m_devices.removeAt(i);
}
}
}
bool DeviceManager::listContainsDevice(const QList<DeviceInfo> &list, int id)
{
foreach (const DeviceInfo &d, list) {
if (d.id() == id)
return true;
}
return false;
}
}
}
QT_END_NAMESPACE
|
/*
Copyright (C) 2007-2008 Tanguy Krotoff <[email protected]>
Copyright (C) 2008 Lukas Durfina <[email protected]>
Copyright (C) 2009 Fathi Boudra <[email protected]>
Copyright (C) 2009-2010 vlc-phonon AUTHORS
Copyright (C) 2011 Harald Sitter <[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, see <http://www.gnu.org/licenses/>.
*/
#include "devicemanager.h"
#ifdef PHONON_PULSESUPPORT
# include <phonon/pulsesupport.h>
#endif
#include <vlc/vlc.h>
#include "backend.h"
#include "utils/debug.h"
#include "utils/libvlc.h"
#include "utils/vstring.h"
QT_BEGIN_NAMESPACE
namespace Phonon
{
namespace VLC
{
/*
* Device Info
*/
DeviceInfo::DeviceInfo(const QString &name, bool isAdvanced)
{
// Get an id
static int counter = 0;
m_id = counter++;
// Get name and description for the device
m_name = name;
m_isAdvanced = isAdvanced;
m_capabilities = None;
// A default device should never be advanced
if (name.startsWith("default", Qt::CaseInsensitive))
m_isAdvanced = false;
}
int DeviceInfo::id() const
{
return m_id;
}
const QString& DeviceInfo::name() const
{
return m_name;
}
const QString& DeviceInfo::description() const
{
return m_description;
}
bool DeviceInfo::isAdvanced() const
{
return m_isAdvanced;
}
void DeviceInfo::setAdvanced(bool advanced)
{
m_isAdvanced = advanced;
}
const DeviceAccessList& DeviceInfo::accessList() const
{
return m_accessList;
}
void DeviceInfo::addAccess(const DeviceAccess& access)
{
if (m_accessList.isEmpty())
m_description = access.first + ": " + access.second;
m_accessList.append(access);
}
quint16 DeviceInfo::capabilities() const
{
return m_capabilities;
}
void DeviceInfo::setCapabilities(quint16 cap)
{
m_capabilities = cap;
}
/*
* Device Manager
*/
DeviceManager::DeviceManager(Backend *parent)
: QObject(parent)
, m_backend(parent)
{
Q_ASSERT(parent);
updateDeviceList();
}
DeviceManager::~DeviceManager()
{
}
QList<int> DeviceManager::deviceIds(ObjectDescriptionType type)
{
DeviceInfo::Capability capability = DeviceInfo::None;
switch (type) {
case Phonon::AudioOutputDeviceType:
capability = DeviceInfo::AudioOutput;
break;
case Phonon::AudioCaptureDeviceType:
capability = DeviceInfo::AudioCapture;
break;
case Phonon::VideoCaptureDeviceType:
capability = DeviceInfo::VideoCapture;
break;
default: ;
}
QList<int> ids;
foreach (const DeviceInfo &device, m_devices) {
if (device.capabilities() & capability)
ids.append(device.id());
}
return ids;
}
QHash<QByteArray, QVariant> DeviceManager::deviceProperties(int id)
{
QHash<QByteArray, QVariant> properties;
foreach (const DeviceInfo &device, m_devices) {
if (device.id() == id) {
properties.insert("name", device.name());
properties.insert("description", device.description());
properties.insert("isAdvanced", device.isAdvanced());
properties.insert("deviceAccessList", QVariant::fromValue<Phonon::DeviceAccessList>(device.accessList()));
properties.insert("discovererIcon", "vlc");
if (device.capabilities() & DeviceInfo::AudioOutput) {
properties.insert("icon", QLatin1String("audio-card"));
}
if (device.capabilities() & DeviceInfo::AudioCapture) {
properties.insert("hasaudio", true);
properties.insert("icon", QLatin1String("audio-input-microphone"));
}
if (device.capabilities() & DeviceInfo::VideoCapture) {
properties.insert("hasvideo", true);
properties.insert("icon", QLatin1String("camera-web"));
}
break;
}
}
return properties;
}
const DeviceInfo *DeviceManager::device(int id) const
{
for (int i = 0; i < m_devices.size(); i ++) {
if (m_devices[i].id() == id)
return &m_devices[i];
}
return NULL;
}
static QList<QByteArray> vlcAudioOutBackends()
{
QList<QByteArray> ret;
libvlc_audio_output_t *firstAudioOut = libvlc_audio_output_list_get(libvlc);
if (!firstAudioOut) {
error() << "libVLC:" << LibVLC::errorMessage();
return ret;
}
for (libvlc_audio_output_t *audioOut = firstAudioOut; audioOut; audioOut = audioOut->p_next) {
QByteArray name(audioOut->psz_name);
if (!ret.contains(name))
ret.append(name);
}
libvlc_audio_output_list_release(firstAudioOut);
return ret;
}
void DeviceManager::updateDeviceList()
{
QList<DeviceInfo> newDeviceList;
if (!LibVLC::self || !libvlc)
return;
QList<QByteArray> audioOutBackends = vlcAudioOutBackends();
#ifdef PHONON_PULSESUPPORT
PulseSupport *pulse = PulseSupport::getInstance();
if (pulse && pulse->isActive()) {
if (audioOutBackends.contains("pulse")) {
DeviceInfo defaultAudioOutputDevice(tr("Default"), false);
defaultAudioOutputDevice.setCapabilities(DeviceInfo::AudioOutput);
defaultAudioOutputDevice.addAccess(DeviceAccess("pulse", "default"));
newDeviceList.append(defaultAudioOutputDevice);
return;
} else {
pulse->enable(false);
}
}
#endif
QList<QByteArray> knownSoundSystems;
// Whitelist
knownSoundSystems << QByteArray("alsa")
<< QByteArray("oss")
<< QByteArray("jack")
<< QByteArray("directx") // Windows
<< QByteArray("auhal"); // Mac
foreach (const QByteArray &soundSystem, knownSoundSystems) {
if (!audioOutBackends.contains(soundSystem)) {
debug() << "Sound system" << soundSystem << "not supported by libvlc";
continue;
}
const int deviceCount = libvlc_audio_output_device_count(libvlc, soundSystem);
for (int i = 0; i < deviceCount; i++) {
VString idName(libvlc_audio_output_device_id(libvlc, soundSystem, i));
VString longName(libvlc_audio_output_device_longname(libvlc, soundSystem, i));
debug() << "found device" << soundSystem << idName << longName;
DeviceInfo device(longName, true);
device.addAccess(DeviceAccess(soundSystem, idName));
device.setCapabilities(DeviceInfo::AudioOutput);
newDeviceList.append(device);
}
// libVLC gives no devices for some sound systems, like OSS
if (deviceCount == 0) {
debug() << "manually injecting sound system" << soundSystem;
DeviceInfo device(QString::fromUtf8(soundSystem), true);
device.addAccess(DeviceAccess(soundSystem, ""));
device.setCapabilities(DeviceInfo::AudioOutput);
newDeviceList.append(device);
}
}
/*
* Compares the list with the devices available at the moment with the last list. If
* a new device is seen, a signal is emitted. If a device disappeared, another signal
* is emitted.
*/
// Search for added devices
for (int i = 0; i < newDeviceList.count(); ++i) {
int id = newDeviceList[i].id();
if (!listContainsDevice(m_devices, id)) {
// This is a new device, add it
m_devices.append(newDeviceList[i]);
emit deviceAdded(id);
debug() << "Added backend device" << newDeviceList[i].name();
}
}
// Search for removed devices
for (int i = m_devices.count() - 1; i >= 0; --i) {
int id = m_devices[i].id();
if (!listContainsDevice(newDeviceList, id)) {
emit deviceRemoved(id);
m_devices.removeAt(i);
}
}
}
bool DeviceManager::listContainsDevice(const QList<DeviceInfo> &list, int id)
{
foreach (const DeviceInfo &d, list) {
if (d.id() == id)
return true;
}
return false;
}
}
}
QT_END_NAMESPACE
|
fix device check a bit
|
fix device check a bit
- less indention in the device check
- fix manual injection to not use untranslated strings, simply use the name
- a tad more debugging
|
C++
|
lgpl-2.1
|
KDE/phonon-vlc,BinChengfei/phonon-vlc,KDE/phonon-vlc,BinChengfei/phonon-vlc,BinChengfei/phonon-vlc,KDE/phonon-vlc
|
bc275825e3b11d6848efede381e4b869daf42ccd
|
src/Tools/Perf/Transpose/transpose_selector.cpp
|
src/Tools/Perf/Transpose/transpose_selector.cpp
|
#include <iostream>
#include <mipp.h>
#include "Tools/Exception/exception.hpp"
#ifdef __AVX2__
#include "transpose_AVX.h"
#elif defined(__SSE4_1__)
#include "transpose_SSE.h"
#endif
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
#include "transpose_NEON.h"
#endif
#include "transpose_selector.h"
bool aff3ct::tools::char_transpose(const signed char *src, signed char *dst, int n)
{
bool is_transposed = false;
#if defined(__MIC__) || defined(__KNCNI__) || defined(__AVX512__) || defined(__AVX512F__)
// is_transposed = false;
#elif defined(__AVX2__)
if (n >= 256)
{
if (((uintptr_t)src) % (256 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (256 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_transpose_avx((__m256i*) src, (__m256i*) dst, n);
is_transposed = true;
}
#elif defined(__SSE4_1__)
if (n >= 128)
{
if (((uintptr_t)src) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_transpose_sse((__m128i*) src, (__m128i*) dst, n);
is_transposed = true;
}
#elif (defined(__ARM_NEON__) || defined(__ARM_NEON))
if (n >= 128)
{
if (((uintptr_t)src) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_transpose_neon((trans_TYPE*) src, (trans_TYPE*) dst, n);
is_transposed = true;
}
#else
throw runtime_error(__FILE__, __LINE__, __func__, "Transposition does not support this architecture "
"(supported architectures are: NEON, NEONv2, SSE4.1 and AVX2).");
#endif
return is_transposed;
}
bool aff3ct::tools::char_itranspose(const signed char *src, signed char *dst, int n)
{
bool is_itransposed = false;
#if defined(__MIC__) || defined(__KNCNI__) || defined(__AVX512__) || defined(__AVX512F__)
// is_itransposed = false;
#elif defined(__AVX2__)
if (n >= 256)
{
if (((uintptr_t)src) % (256 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (256 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_itranspose_avx((__m256i*) src, (__m256i*) dst, n / 8);
is_itransposed = true;
}
#elif defined(__SSE4_1__)
if (n >= 128)
{
if (((uintptr_t)src) % (128))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_itranspose_sse((__m128i*) src, (__m128i*) dst, n / 8);
is_itransposed = true;
}
#elif (defined(__ARM_NEON__) || defined(__ARM_NEON))
if (n >= 128)
{
if (((uintptr_t)src) % (128))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_itranspose_neon((trans_TYPE*) src, (trans_TYPE*) dst, n / 8);
is_itransposed = true;
}
#else
throw runtime_error(__FILE__, __LINE__, __func__, "Transposition inverse does not support this architecture "
"(supported architectures are: NEON, NEONv2, SSE4.1 and AVX2).");
#endif
return is_itransposed;
}
|
#include <iostream>
#include <mipp.h>
#include "Tools/Exception/exception.hpp"
#ifdef __AVX2__
#include "transpose_AVX.h"
#elif defined(__SSE4_1__)
#include "transpose_SSE.h"
#endif
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
#include "transpose_NEON.h"
#endif
#include "transpose_selector.h"
bool aff3ct::tools::char_transpose(const signed char *src, signed char *dst, int n)
{
bool is_transposed = false;
#if defined(__MIC__) || defined(__KNCNI__) || defined(__AVX512__) || defined(__AVX512F__)
// is_transposed = false;
#elif defined(__AVX2__)
if (n >= 256)
{
if (((uintptr_t)src) % (256 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (256 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_transpose_avx((__m256i*) src, (__m256i*) dst, n);
is_transposed = true;
}
#elif defined(__SSE4_1__)
if (n >= 128)
{
if (((uintptr_t)src) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_transpose_sse((__m128i*) src, (__m128i*) dst, n);
is_transposed = true;
}
#elif (defined(__ARM_NEON__) || defined(__ARM_NEON))
if (n >= 128)
{
if (((uintptr_t)src) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_transpose_neon((trans_TYPE*) src, (trans_TYPE*) dst, n);
is_transposed = true;
}
#else
throw runtime_error(__FILE__, __LINE__, __func__, "Transposition does not support this architecture "
"(supported architectures are: NEON, NEONv2, SSE4.1 and AVX2).");
#endif
return is_transposed;
}
bool aff3ct::tools::char_itranspose(const signed char *src, signed char *dst, int n)
{
bool is_itransposed = false;
#if defined(__MIC__) || defined(__KNCNI__) || defined(__AVX512__) || defined(__AVX512F__)
// is_itransposed = false;
#elif defined(__AVX2__)
if (n >= 256)
{
if (((uintptr_t)src) % (256 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (256 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_itranspose_avx((__m256i*) src, (__m256i*) dst, n / 8);
is_itransposed = true;
}
#elif defined(__SSE4_1__)
if (n >= 128)
{
if (((uintptr_t)src) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_itranspose_sse((__m128i*) src, (__m128i*) dst, n / 8);
is_itransposed = true;
}
#elif (defined(__ARM_NEON__) || defined(__ARM_NEON))
if (n >= 128)
{
if (((uintptr_t)src) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'src' is unaligned memory.");
if (((uintptr_t)dst) % (128 / 8))
throw runtime_error(__FILE__, __LINE__, __func__, "'dst' is unaligned memory.");
uchar_itranspose_neon((trans_TYPE*) src, (trans_TYPE*) dst, n / 8);
is_itransposed = true;
}
#else
throw runtime_error(__FILE__, __LINE__, __func__, "Transposition inverse does not support this architecture "
"(supported architectures are: NEON, NEONv2, SSE4.1 and AVX2).");
#endif
return is_itransposed;
}
|
Fix a bug in alignment control.
|
Fix a bug in alignment control.
|
C++
|
mit
|
aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct
|
8b69e23e2801e32194d7ef9607bc02294b713847
|
src/abaclade/exception-fault_converter-mach.cxx
|
src/abaclade/exception-fault_converter-mach.cxx
|
ο»Ώ/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2014
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
// #include <abaclade.hxx> already done in exception-fault_converter.cxx.
// TODO: use Mach threads instead of pthreads for the exception-catching thread.
#include <pthread.h> // pthread_create()
// Mach reference: <http://web.mit.edu/darwin/src/modules/xnu/osfmk/man/>.
#include <mach/mach.h> // boolean_t mach_msg_header_t
#include <mach/mach_traps.h> // mach_task_self()
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::exception::fault_converter
/*! Handles a kernel-reported thread exception. This is exposed by Mach, but for some reason not
declared in any system headers. See <http://web.mit.edu/darwin/src/modules/xnu/osfmk/man/
exc_server.html>.
@param pmsghRequest
Pointer to the request message.
@param pmsghReply
Pointer to the message that will receive the reply.
@return
true if the message was handled and catch_exception_raise() (defined in this file) was called, or
false if the message had nothing to do with exceptions.
*/
extern "C" ::boolean_t exc_server(
::mach_msg_header_t * pmsghRequest, ::mach_msg_header_t * pmsghReply
);
/*! Called by exc_server() when the latter is passed an exception message, giving the process a way
to do something about it. What we do is change the next instruction in the faulting thread to
throw_after_fault().
@param mpExceptions
?
@param mpThread
Faulting thread.
@param mpTask
?
@param exctype
Type of exception.
@param piExcCodes
Pointer to an array of machine-dependent exception codes (sub-types).
@param cExcCodes
Count of elements in the array pointed to by piExcCodes.
@return
One of the KERN_* constants.
*/
extern "C" ::kern_return_t ABACLADE_SYM catch_exception_raise(
::mach_port_t mpExceptions, ::mach_port_t mpThread, ::mach_port_t mpTask,
::exception_type_t exctype, ::exception_data_t piExcCodes, ::mach_msg_type_number_t cExcCodes
) {
ABC_UNUSED_ARG(mpExceptions);
ABC_UNUSED_ARG(mpTask);
#if ABC_HOST_ARCH_X86_64
typedef ::x86_exception_state64_t arch_exception_state_t;
typedef ::x86_thread_state64_t arch_thread_state_t;
static ::thread_state_flavor_t const sc_tsfException = x86_EXCEPTION_STATE64;
static ::thread_state_flavor_t const sc_tsfThread = x86_THREAD_STATE64;
static ::mach_msg_type_number_t const sc_cExceptionStateWords = x86_EXCEPTION_STATE64_COUNT;
static ::mach_msg_type_number_t const sc_cThreadStateWords = x86_THREAD_STATE64_COUNT;
#else
#error "TODO: HOST_ARCH"
#endif
// Read the exception and convert it into a known C++ type.
fault_exception_types::enum_type fxt;
std::intptr_t iArg0 = 0, iArg1 = 0;
{
arch_exception_state_t excst;
// On input this is a word count, but on output itβs an element count.
::mach_msg_type_number_t iExceptionStatesCount = sc_cExceptionStateWords;
if (::thread_get_state(
mpThread, sc_tsfException, reinterpret_cast< ::thread_state_t>(&excst),
&iExceptionStatesCount
) != KERN_SUCCESS) {
return KERN_FAILURE;
}
switch (exctype) {
case EXC_BAD_ACCESS:
#if ABC_HOST_ARCH_X86_64
iArg0 = static_cast<std::intptr_t>(excst.__faultvaddr);
#else
#error "TODO: HOST_ARCH"
#endif
if (iArg0 == 0) {
fxt = fault_exception_types::null_pointer_error;
} else {
fxt = fault_exception_types::memory_address_error;
}
break;
case EXC_BAD_INSTRUCTION:
#if ABC_HOST_ARCH_X86_64
iArg0 = static_cast<std::intptr_t>(excst.__faultvaddr);
#else
#error "TODO: HOST_ARCH"
#endif
// TODO: better exception type.
fxt = fault_exception_types::memory_access_error;
break;
case EXC_ARITHMETIC:
fxt = fault_exception_types::arithmetic_error;
if (cExcCodes) {
// TODO: can there be more than one exception code passed to a single call?
switch (piExcCodes[0]) {
#if ABC_HOST_ARCH_X86_64
case EXC_I386_DIV:
fxt = fault_exception_types::division_by_zero_error;
break;
/*
case EXC_I386_INTO:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_NOEXT:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_EXTOVR:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_EXTERR:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_EMERR:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_BOUND:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_SSEEXTERR:
fxt = fault_exception_types::arithmetic_error;
break;
*/
#else
#error "TODO: HOST_ARCH"
#endif
}
}
break;
default:
// Should never happen.
return KERN_FAILURE;
}
}
/* Change the address at which mpThread is executing: manipulate the thread state to emulate a
function call to throw_after_fault(). */
// Obtain the faulting threadβs state.
arch_thread_state_t thrst;
// On input this is a word count, but on output itβs an element count.
::mach_msg_type_number_t iThreadStatesCount = sc_cThreadStateWords;
if (::thread_get_state(
mpThread, sc_tsfThread, reinterpret_cast< ::thread_state_t>(&thrst), &iThreadStatesCount
) != KERN_SUCCESS) {
return KERN_FAILURE;
}
// Manipulate the thread state to emulate a call to throw_after_fault.
#if ABC_HOST_ARCH_X86_64
/* Load the arguments to throw_after_fault() in rdi/rsi/rdx, push the address of the current
(failing) instruction, then set rip to the start of throw_after_fault(). These steps emulate a
3-argument subroutine call. */
typedef decltype(thrst.__rsp) reg_t;
reg_t *& rsp = reinterpret_cast<reg_t *&>(thrst.__rsp);
thrst.__rdi = static_cast<reg_t>(fxt);
thrst.__rsi = static_cast<reg_t>(iArg0);
thrst.__rdx = static_cast<reg_t>(iArg1);
// TODO: validate that stack alignment to 16 bytes is done by the callee with push rbp.
*--rsp = thrst.__rip;
thrst.__rip = reinterpret_cast<reg_t>(&throw_after_fault);
#else
#error "TODO: HOST_ARCH"
#endif
// Update the faulting threadβs state.
if (::thread_set_state(
mpThread, sc_tsfThread, reinterpret_cast< ::thread_state_t>(&thrst), iThreadStatesCount
) != KERN_SUCCESS) {
return KERN_FAILURE;
}
return KERN_SUCCESS;
}
namespace abc {
namespace {
//! Thread in charge of handling exceptions for all the other threads.
::pthread_t g_thrExcHandler;
//! Port through which we ask the kernel to communicate exceptions to this process.
::mach_port_t g_mpExceptions;
void * exception_handler_thread(void *) {
for (;;) {
/* The exact definition of these structs is in the kernelβs sources; thankfully all we need to
do with them is pass them around, so just define them as BLOBs and hope that theyβre large
enough. */
struct {
::mach_msg_header_t msgh;
::mach_msg_body_t msgb;
std::uint8_t abData[1024];
} msg;
struct {
::mach_msg_header_t msgh;
std::uint8_t abData[1024];
} reply;
// Block to read from the exception port.
if (::mach_msg(
&msg.msgh, MACH_RCV_MSG | MACH_RCV_LARGE, 0, sizeof msg, g_mpExceptions,
MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL
) != MACH_MSG_SUCCESS) {
std::abort();
}
// Handle the received message by having exc_server() call our catch_exception_raise().
if (::exc_server(&msg.msgh, &reply.msgh)) {
// exc_server() created a reply for the message, send it.
if (::mach_msg(
&reply.msgh, MACH_SEND_MSG, reply.msgh.msgh_size, 0, MACH_PORT_NULL,
MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL
) != MACH_MSG_SUCCESS) {
std::abort();
}
}
}
}
} //namespace
exception::fault_converter::fault_converter() {
::mach_port_t mpThisProc = ::mach_task_self();
// Allocate a right-less port to listen for exceptions.
if (::mach_port_allocate(mpThisProc, MACH_PORT_RIGHT_RECEIVE, &g_mpExceptions) == KERN_SUCCESS) {
// Assign rights to the port.
if (::mach_port_insert_right(
mpThisProc, g_mpExceptions, g_mpExceptions, MACH_MSG_TYPE_MAKE_SEND
) == KERN_SUCCESS) {
// Start the thread that will catch exceptions from all the others.
if (::pthread_create(&g_thrExcHandler, nullptr, exception_handler_thread, nullptr) == 0) {
// Now that the handler thread is running, set the process-wide exception port.
if (::task_set_exception_ports(
mpThisProc,
EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION | EXC_MASK_ARITHMETIC,
g_mpExceptions, EXCEPTION_DEFAULT, MACHINE_THREAD_STATE
) == KERN_SUCCESS) {
// All good.
}
}
}
}
}
exception::fault_converter::~fault_converter() {
}
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
|
ο»Ώ/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2014
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
// #include <abaclade.hxx> already done in exception-fault_converter.cxx.
// TODO: use Mach threads instead of pthreads for the exception-catching thread.
#include <pthread.h> // pthread_create()
// Mach reference: <http://web.mit.edu/darwin/src/modules/xnu/osfmk/man/>.
#include <mach/mach.h> // boolean_t mach_msg_header_t
#include <mach/mach_traps.h> // mach_task_self()
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::exception::fault_converter
/*! Handles a kernel-reported thread exception. This is exposed by Mach, but for some reason not
declared in any system headers. See <http://web.mit.edu/darwin/src/modules/xnu/osfmk/man/
exc_server.html>.
@param pmsghRequest
Pointer to the request message.
@param pmsghReply
Pointer to the message that will receive the reply.
@return
true if the message was handled and catch_exception_raise() (defined in this file) was called, or
false if the message had nothing to do with exceptions.
*/
extern "C" ::boolean_t exc_server(
::mach_msg_header_t * pmsghRequest, ::mach_msg_header_t * pmsghReply
);
/*! Called by exc_server() when the latter is passed an exception message, giving the process a way
to do something about it. What we do is change the next instruction in the faulting thread to
throw_after_fault().
@param mpExceptions
?
@param mpThread
Faulting thread.
@param mpTask
?
@param exctype
Type of exception.
@param piExcCodes
Pointer to an array of machine-dependent exception codes (sub-types).
@param cExcCodes
Count of elements in the array pointed to by piExcCodes.
@return
One of the KERN_* constants.
*/
extern "C" ::kern_return_t ABACLADE_SYM catch_exception_raise(
::mach_port_t mpExceptions, ::mach_port_t mpThread, ::mach_port_t mpTask,
::exception_type_t exctype, ::exception_data_t piExcCodes, ::mach_msg_type_number_t cExcCodes
) {
ABC_UNUSED_ARG(mpExceptions);
ABC_UNUSED_ARG(mpTask);
#if ABC_HOST_ARCH_X86_64
typedef ::x86_exception_state64_t arch_exception_state_t;
typedef ::x86_thread_state64_t arch_thread_state_t;
static ::thread_state_flavor_t const sc_tsfException = x86_EXCEPTION_STATE64;
static ::thread_state_flavor_t const sc_tsfThread = x86_THREAD_STATE64;
static ::mach_msg_type_number_t const sc_cExceptionStateWords = x86_EXCEPTION_STATE64_COUNT;
static ::mach_msg_type_number_t const sc_cThreadStateWords = x86_THREAD_STATE64_COUNT;
#else
#error "TODO: HOST_ARCH"
#endif
// Read the exception and convert it into a known C++ type.
fault_exception_types::enum_type fxt;
std::intptr_t iArg0 = 0, iArg1 = 0;
{
arch_exception_state_t excst;
// On input this is a word count, but on output itβs an element count.
::mach_msg_type_number_t iExceptionStatesCount = sc_cExceptionStateWords;
if (::thread_get_state(
mpThread, sc_tsfException, reinterpret_cast< ::thread_state_t>(&excst),
&iExceptionStatesCount
) != KERN_SUCCESS) {
return KERN_FAILURE;
}
switch (exctype) {
case EXC_BAD_ACCESS:
#if ABC_HOST_ARCH_X86_64
iArg0 = static_cast<std::intptr_t>(excst.__faultvaddr);
#else
#error "TODO: HOST_ARCH"
#endif
if (iArg0 == 0) {
fxt = fault_exception_types::null_pointer_error;
} else {
fxt = fault_exception_types::memory_address_error;
}
break;
case EXC_BAD_INSTRUCTION:
#if ABC_HOST_ARCH_X86_64
iArg0 = static_cast<std::intptr_t>(excst.__faultvaddr);
#else
#error "TODO: HOST_ARCH"
#endif
// TODO: better exception type.
fxt = fault_exception_types::memory_access_error;
break;
case EXC_ARITHMETIC:
fxt = fault_exception_types::arithmetic_error;
if (cExcCodes) {
// TODO: can there be more than one exception code passed to a single call?
switch (piExcCodes[0]) {
#if ABC_HOST_ARCH_X86_64
case EXC_I386_DIV:
fxt = fault_exception_types::division_by_zero_error;
break;
/*
case EXC_I386_INTO:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_NOEXT:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_EXTOVR:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_EXTERR:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_EMERR:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_BOUND:
fxt = fault_exception_types::arithmetic_error;
break;
case EXC_I386_SSEEXTERR:
fxt = fault_exception_types::arithmetic_error;
break;
*/
#else
#error "TODO: HOST_ARCH"
#endif
}
}
break;
default:
// Should never happen.
return KERN_FAILURE;
}
}
/* Change the address at which mpThread is executing: manipulate the thread state to emulate a
function call to throw_after_fault(). */
// Obtain the faulting threadβs state.
arch_thread_state_t thrst;
// On input this is a word count, but on output itβs an element count.
::mach_msg_type_number_t iThreadStatesCount = sc_cThreadStateWords;
if (::thread_get_state(
mpThread, sc_tsfThread, reinterpret_cast< ::thread_state_t>(&thrst), &iThreadStatesCount
) != KERN_SUCCESS) {
return KERN_FAILURE;
}
// Manipulate the thread state to emulate a call to throw_after_fault.
#if ABC_HOST_ARCH_X86_64
/* Load the arguments to throw_after_fault() in rdi/rsi/rdx, push the address of the current
(failing) instruction, then set rip to the start of throw_after_fault(). These steps emulate a
3-argument subroutine call. */
typedef decltype(thrst.__rsp) reg_t;
reg_t *& rsp = reinterpret_cast<reg_t *&>(thrst.__rsp);
thrst.__rdi = static_cast<reg_t>(fxt);
thrst.__rsi = static_cast<reg_t>(iArg0);
thrst.__rdx = static_cast<reg_t>(iArg1);
// TODO: validate that stack alignment to 16 bytes is done by the callee with push rbp.
*--rsp = thrst.__rip;
thrst.__rip = reinterpret_cast<reg_t>(&throw_after_fault);
#else
#error "TODO: HOST_ARCH"
#endif
// Update the faulting threadβs state.
if (::thread_set_state(
mpThread, sc_tsfThread, reinterpret_cast< ::thread_state_t>(&thrst), iThreadStatesCount
) != KERN_SUCCESS) {
return KERN_FAILURE;
}
return KERN_SUCCESS;
}
namespace {
//! Thread in charge of handling exceptions for all the other threads.
::pthread_t g_thrExcHandler;
//! Port through which we ask the kernel to communicate exceptions to this process.
::mach_port_t g_mpExceptions;
void * exception_handler_thread(void *) {
for (;;) {
/* The exact definition of these structs is in the kernelβs sources; thankfully all we need to
do with them is pass them around, so just define them as BLOBs and hope that theyβre large
enough. */
struct {
::mach_msg_header_t msgh;
::mach_msg_body_t msgb;
std::uint8_t abData[1024];
} msg;
struct {
::mach_msg_header_t msgh;
std::uint8_t abData[1024];
} reply;
// Block to read from the exception port.
if (::mach_msg(
&msg.msgh, MACH_RCV_MSG | MACH_RCV_LARGE, 0, sizeof msg, g_mpExceptions,
MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL
) != MACH_MSG_SUCCESS) {
std::abort();
}
// Handle the received message by having exc_server() call our catch_exception_raise().
if (::exc_server(&msg.msgh, &reply.msgh)) {
// exc_server() created a reply for the message, send it.
if (::mach_msg(
&reply.msgh, MACH_SEND_MSG, reply.msgh.msgh_size, 0, MACH_PORT_NULL,
MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL
) != MACH_MSG_SUCCESS) {
std::abort();
}
}
}
}
} //namespace
namespace abc {
exception::fault_converter::fault_converter() {
::mach_port_t mpThisProc = ::mach_task_self();
// Allocate a right-less port to listen for exceptions.
if (::mach_port_allocate(mpThisProc, MACH_PORT_RIGHT_RECEIVE, &g_mpExceptions) == KERN_SUCCESS) {
// Assign rights to the port.
if (::mach_port_insert_right(
mpThisProc, g_mpExceptions, g_mpExceptions, MACH_MSG_TYPE_MAKE_SEND
) == KERN_SUCCESS) {
// Start the thread that will catch exceptions from all the others.
if (::pthread_create(&g_thrExcHandler, nullptr, exception_handler_thread, nullptr) == 0) {
// Now that the handler thread is running, set the process-wide exception port.
if (::task_set_exception_ports(
mpThisProc,
EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION | EXC_MASK_ARITHMETIC,
g_mpExceptions, EXCEPTION_DEFAULT, MACHINE_THREAD_STATE
) == KERN_SUCCESS) {
// All good.
}
}
}
}
}
exception::fault_converter::~fault_converter() {
}
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
|
Move private globals out of abc namespace
|
Move private globals out of abc namespace
|
C++
|
lgpl-2.1
|
raffaellod/lofty,raffaellod/lofty
|
a1fa20c7dac8452a06c27d8fc0bf6ad17a12f5c7
|
src/app/tests/integration/chip_im_initiator.cpp
|
src/app/tests/integration/chip_im_initiator.cpp
|
/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements a chip-im-initiator, for the
* CHIP Interaction Data Model Protocol.
*
* Currently it provides simple command sender with sample cluster and command
*
*/
#include "common.h"
#include <app/CommandHandler.h>
#include <app/CommandSender.h>
#include <app/InteractionModelEngine.h>
#include <core/CHIPCore.h>
#include <platform/CHIPDeviceLayer.h>
#include <support/ErrorStr.h>
#include <system/SystemPacketBuffer.h>
#include <transport/SecurePairingSession.h>
#include <transport/SecureSessionMgr.h>
#include <transport/raw/UDP.h>
#define IM_CLIENT_PORT (CHIP_PORT + 1)
namespace {
// Max value for the number of command request sent.
constexpr size_t kMaxCommandCount = 3;
// The CHIP Command interval time in milliseconds.
constexpr int32_t gCommandInterval = 1000;
// The CommandSender object.
chip::app::CommandSender * gpCommandSender = nullptr;
chip::TransportMgr<chip::Transport::UDP> gTransportManager;
chip::SecureSessionMgr gSessionManager;
chip::Inet::IPAddress gDestAddr;
// The last time a CHIP Command was attempted to be sent.
uint64_t gLastCommandTime = 0;
// True, if the CommandSender is waiting for an CommandResponse
// after sending an CommandRequest, false otherwise.
bool gWaitingForCommandResp = false;
// Count of the number of CommandRequests sent.
uint64_t gCommandCount = 0;
// Count of the number of CommandResponses received.
uint64_t gCommandRespCount = 0;
bool CommandIntervalExpired(void)
{
uint64_t now = chip::System::Timer::GetCurrentEpoch();
return (now >= gLastCommandTime + gCommandInterval);
}
CHIP_ERROR SendCommandRequest(void)
{
CHIP_ERROR err = CHIP_NO_ERROR;
gLastCommandTime = chip::System::Timer::GetCurrentEpoch();
printf("\nSend invoke command request message to Node: %lu\n", chip::kTestDeviceNodeId);
chip::app::Command::CommandParams CommandParams = { 1, // Endpoint
0, // GroupId
6, // ClusterId
40, // CommandId
(chip::app::Command::kCommandPathFlag_EndpointIdValid) };
// Add command data here
uint8_t effectIdentifier = 1; // Dying light
uint8_t effectVariant = 1;
chip::TLV::TLVType dummyType = chip::TLV::kTLVType_NotSpecified;
chip::TLV::TLVWriter writer = gpCommandSender->CreateCommandDataElementTLVWriter();
err = writer.StartContainer(chip::TLV::AnonymousTag, chip::TLV::kTLVType_Structure, dummyType);
SuccessOrExit(err);
err = writer.Put(chip::TLV::ContextTag(1), effectIdentifier);
SuccessOrExit(err);
err = writer.Put(chip::TLV::ContextTag(2), effectVariant);
SuccessOrExit(err);
err = writer.EndContainer(dummyType);
SuccessOrExit(err);
err = writer.Finalize();
SuccessOrExit(err);
err = gpCommandSender->AddCommand(CommandParams);
SuccessOrExit(err);
err = gpCommandSender->SendCommandRequest(chip::kTestDeviceNodeId);
SuccessOrExit(err);
if (err == CHIP_NO_ERROR)
{
gWaitingForCommandResp = true;
gCommandCount++;
}
else
{
printf("Send invoke command request failed, err: %s\n", chip::ErrorStr(err));
}
exit:
return err;
}
CHIP_ERROR EstablishSecureSession()
{
CHIP_ERROR err = CHIP_NO_ERROR;
chip::SecurePairingUsingTestSecret * testSecurePairingSecret = chip::Platform::New<chip::SecurePairingUsingTestSecret>(
chip::Optional<chip::NodeId>::Value(chip::kTestDeviceNodeId), static_cast<uint16_t>(0), static_cast<uint16_t>(0));
VerifyOrExit(testSecurePairingSecret != nullptr, err = CHIP_ERROR_NO_MEMORY);
// Attempt to connect to the peer.
err = gSessionManager.NewPairing(chip::Optional<chip::Transport::PeerAddress>::Value(
chip::Transport::PeerAddress::UDP(gDestAddr, CHIP_PORT, INET_NULL_INTERFACEID)),
chip::kTestDeviceNodeId, testSecurePairingSecret);
exit:
if (err != CHIP_NO_ERROR)
{
printf("Establish secure session failed, err: %s\n", chip::ErrorStr(err));
gLastCommandTime = chip::System::Timer::GetCurrentEpoch();
}
else
{
printf("Establish secure session succeeded\n");
}
return err;
}
void HandleCommandResponseReceived(chip::TLV::TLVReader & aReader, chip::app::Command * apCommandObj)
{
uint32_t respTime = chip::System::Timer::GetCurrentEpoch();
uint32_t transitTime = respTime - gLastCommandTime;
if (aReader.GetLength() != 0)
{
chip::TLV::Debug::Dump(aReader, TLVPrettyPrinter);
}
gWaitingForCommandResp = false;
gCommandRespCount++;
printf("Command Response: %" PRIu64 "/%" PRIu64 "(%.2f%%) time=%.3fms\n", gCommandRespCount, gCommandCount,
static_cast<double>(gCommandRespCount) * 100 / gCommandCount, static_cast<double>(transitTime) / 1000);
}
} // namespace
int main(int argc, char * argv[])
{
CHIP_ERROR err = CHIP_NO_ERROR;
if (argc <= 1)
{
printf("Missing Command Server IP address\n");
ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
}
if (!chip::Inet::IPAddress::FromString(argv[1], gDestAddr))
{
printf("Invalid Command Server IP address: %s\n", argv[1]);
ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
}
InitializeChip();
err = gTransportManager.Init(chip::Transport::UdpListenParameters(&chip::DeviceLayer::InetLayer)
.SetAddressType(chip::Inet::kIPAddressType_IPv4)
.SetListenPort(IM_CLIENT_PORT));
SuccessOrExit(err);
err = gSessionManager.Init(chip::kTestControllerNodeId, &chip::DeviceLayer::SystemLayer, &gTransportManager);
SuccessOrExit(err);
err = gExchangeManager.Init(&gSessionManager);
SuccessOrExit(err);
err = chip::app::InteractionModelEngine::GetInstance()->Init(&gExchangeManager);
SuccessOrExit(err);
chip::app::InteractionModelEngine::GetInstance()->RegisterClusterCommandHandler(
6, 40, chip::app::Command::CommandRoleId::kCommandSenderId, HandleCommandResponseReceived);
// Start the CHIP connection to the CHIP im responder.
err = EstablishSecureSession();
SuccessOrExit(err);
err = chip::app::InteractionModelEngine::GetInstance()->NewCommandSender(&gpCommandSender);
SuccessOrExit(err);
// Connection has been established. Now send the CommandRequests.
for (unsigned int i = 0; i < kMaxCommandCount; i++)
{
if (SendCommandRequest() != CHIP_NO_ERROR)
{
printf("Send request failed: %s\n", chip::ErrorStr(err));
break;
}
// Wait for response until the Command interval.
while (!CommandIntervalExpired())
{
DriveIO();
}
// Check if expected response was received.
if (gWaitingForCommandResp)
{
printf("No response received\n");
gWaitingForCommandResp = false;
}
}
chip::app::InteractionModelEngine::GetInstance()->DeregisterClusterCommandHandler(
6, 40, chip::app::Command::CommandRoleId::kCommandSenderId);
gpCommandSender->Shutdown();
chip::app::InteractionModelEngine::GetInstance()->Shutdown();
ShutdownChip();
exit:
if (err != CHIP_NO_ERROR)
{
printf("ChipCommandSender failed: %s\n", chip::ErrorStr(err));
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
|
/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements a chip-im-initiator, for the
* CHIP Interaction Data Model Protocol.
*
* Currently it provides simple command sender with sample cluster and command
*
*/
#include "common.h"
#include <app/CommandHandler.h>
#include <app/CommandSender.h>
#include <app/InteractionModelEngine.h>
#include <core/CHIPCore.h>
#include <platform/CHIPDeviceLayer.h>
#include <support/ErrorStr.h>
#include <system/SystemPacketBuffer.h>
#include <transport/SecurePairingSession.h>
#include <transport/SecureSessionMgr.h>
#include <transport/raw/UDP.h>
#define IM_CLIENT_PORT (CHIP_PORT + 1)
namespace {
// Max value for the number of command request sent.
constexpr size_t kMaxCommandCount = 3;
// The CHIP Command interval time in milliseconds.
constexpr int32_t gCommandInterval = 1000;
// The CommandSender object.
chip::app::CommandSender * gpCommandSender = nullptr;
chip::TransportMgr<chip::Transport::UDP> gTransportManager;
chip::SecureSessionMgr gSessionManager;
chip::Inet::IPAddress gDestAddr;
// The last time a CHIP Command was attempted to be sent.
uint64_t gLastCommandTime = 0;
// True, if the CommandSender is waiting for an CommandResponse
// after sending an CommandRequest, false otherwise.
bool gWaitingForCommandResp = false;
// Count of the number of CommandRequests sent.
uint64_t gCommandCount = 0;
// Count of the number of CommandResponses received.
uint64_t gCommandRespCount = 0;
bool CommandIntervalExpired(void)
{
uint64_t now = chip::System::Timer::GetCurrentEpoch();
return (now >= gLastCommandTime + gCommandInterval);
}
CHIP_ERROR SendCommandRequest(void)
{
CHIP_ERROR err = CHIP_NO_ERROR;
gLastCommandTime = chip::System::Timer::GetCurrentEpoch();
printf("\nSend invoke command request message to Node: %" PRIu64 "\n", chip::kTestDeviceNodeId);
chip::app::Command::CommandParams CommandParams = { 1, // Endpoint
0, // GroupId
6, // ClusterId
40, // CommandId
(chip::app::Command::kCommandPathFlag_EndpointIdValid) };
// Add command data here
uint8_t effectIdentifier = 1; // Dying light
uint8_t effectVariant = 1;
chip::TLV::TLVType dummyType = chip::TLV::kTLVType_NotSpecified;
chip::TLV::TLVWriter writer = gpCommandSender->CreateCommandDataElementTLVWriter();
err = writer.StartContainer(chip::TLV::AnonymousTag, chip::TLV::kTLVType_Structure, dummyType);
SuccessOrExit(err);
err = writer.Put(chip::TLV::ContextTag(1), effectIdentifier);
SuccessOrExit(err);
err = writer.Put(chip::TLV::ContextTag(2), effectVariant);
SuccessOrExit(err);
err = writer.EndContainer(dummyType);
SuccessOrExit(err);
err = writer.Finalize();
SuccessOrExit(err);
err = gpCommandSender->AddCommand(CommandParams);
SuccessOrExit(err);
err = gpCommandSender->SendCommandRequest(chip::kTestDeviceNodeId);
SuccessOrExit(err);
if (err == CHIP_NO_ERROR)
{
gWaitingForCommandResp = true;
gCommandCount++;
}
else
{
printf("Send invoke command request failed, err: %s\n", chip::ErrorStr(err));
}
exit:
return err;
}
CHIP_ERROR EstablishSecureSession()
{
CHIP_ERROR err = CHIP_NO_ERROR;
chip::SecurePairingUsingTestSecret * testSecurePairingSecret = chip::Platform::New<chip::SecurePairingUsingTestSecret>(
chip::Optional<chip::NodeId>::Value(chip::kTestDeviceNodeId), static_cast<uint16_t>(0), static_cast<uint16_t>(0));
VerifyOrExit(testSecurePairingSecret != nullptr, err = CHIP_ERROR_NO_MEMORY);
// Attempt to connect to the peer.
err = gSessionManager.NewPairing(chip::Optional<chip::Transport::PeerAddress>::Value(
chip::Transport::PeerAddress::UDP(gDestAddr, CHIP_PORT, INET_NULL_INTERFACEID)),
chip::kTestDeviceNodeId, testSecurePairingSecret);
exit:
if (err != CHIP_NO_ERROR)
{
printf("Establish secure session failed, err: %s\n", chip::ErrorStr(err));
gLastCommandTime = chip::System::Timer::GetCurrentEpoch();
}
else
{
printf("Establish secure session succeeded\n");
}
return err;
}
void HandleCommandResponseReceived(chip::TLV::TLVReader & aReader, chip::app::Command * apCommandObj)
{
uint32_t respTime = chip::System::Timer::GetCurrentEpoch();
uint32_t transitTime = respTime - gLastCommandTime;
if (aReader.GetLength() != 0)
{
chip::TLV::Debug::Dump(aReader, TLVPrettyPrinter);
}
gWaitingForCommandResp = false;
gCommandRespCount++;
printf("Command Response: %" PRIu64 "/%" PRIu64 "(%.2f%%) time=%.3fms\n", gCommandRespCount, gCommandCount,
static_cast<double>(gCommandRespCount) * 100 / gCommandCount, static_cast<double>(transitTime) / 1000);
}
} // namespace
int main(int argc, char * argv[])
{
CHIP_ERROR err = CHIP_NO_ERROR;
if (argc <= 1)
{
printf("Missing Command Server IP address\n");
ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
}
if (!chip::Inet::IPAddress::FromString(argv[1], gDestAddr))
{
printf("Invalid Command Server IP address: %s\n", argv[1]);
ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
}
InitializeChip();
err = gTransportManager.Init(chip::Transport::UdpListenParameters(&chip::DeviceLayer::InetLayer)
.SetAddressType(chip::Inet::kIPAddressType_IPv4)
.SetListenPort(IM_CLIENT_PORT));
SuccessOrExit(err);
err = gSessionManager.Init(chip::kTestControllerNodeId, &chip::DeviceLayer::SystemLayer, &gTransportManager);
SuccessOrExit(err);
err = gExchangeManager.Init(&gSessionManager);
SuccessOrExit(err);
err = chip::app::InteractionModelEngine::GetInstance()->Init(&gExchangeManager);
SuccessOrExit(err);
chip::app::InteractionModelEngine::GetInstance()->RegisterClusterCommandHandler(
6, 40, chip::app::Command::CommandRoleId::kCommandSenderId, HandleCommandResponseReceived);
// Start the CHIP connection to the CHIP im responder.
err = EstablishSecureSession();
SuccessOrExit(err);
err = chip::app::InteractionModelEngine::GetInstance()->NewCommandSender(&gpCommandSender);
SuccessOrExit(err);
// Connection has been established. Now send the CommandRequests.
for (unsigned int i = 0; i < kMaxCommandCount; i++)
{
if (SendCommandRequest() != CHIP_NO_ERROR)
{
printf("Send request failed: %s\n", chip::ErrorStr(err));
break;
}
// Wait for response until the Command interval.
while (!CommandIntervalExpired())
{
DriveIO();
}
// Check if expected response was received.
if (gWaitingForCommandResp)
{
printf("No response received\n");
gWaitingForCommandResp = false;
}
}
chip::app::InteractionModelEngine::GetInstance()->DeregisterClusterCommandHandler(
6, 40, chip::app::Command::CommandRoleId::kCommandSenderId);
gpCommandSender->Shutdown();
chip::app::InteractionModelEngine::GetInstance()->Shutdown();
ShutdownChip();
exit:
if (err != CHIP_NO_ERROR)
{
printf("ChipCommandSender failed: %s\n", chip::ErrorStr(err));
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
|
Fix wrong uint64_t print
|
Fix wrong uint64_t print
Problem:
Regression issue
Problem
../../src/app/tests/integration/chip_im_initiator.cpp:86:68: error: format specifies type 'unsigned long' but the argument has type 'chip::NodeId' (aka 'unsigned long long') [-Werror,-Wformat]
Summary of changes
Always use PRIu64 for printing uint64_t, including node ids.
Fixes #4284
|
C++
|
apache-2.0
|
nestlabs/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip
|
f791e5634ee193e7b5040a53581431759ff933c0
|
src/chrono_gpu/physics/ChSystemGpuMesh_impl.cpp
|
src/chrono_gpu/physics/ChSystemGpuMesh_impl.cpp
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2019 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Conlain Kelly, Nic Olsen, Dan Negrut, Radu Serban
// =============================================================================
#include <vector>
#include <algorithm>
#include <fstream>
#include <string>
#include <cmath>
#include "chrono/core/ChGlobal.h"
#include "chrono/core/ChVector.h"
#include "chrono/core/ChQuaternion.h"
#include "chrono/core/ChMatrix33.h"
#include "chrono_gpu/physics/ChSystemGpuMesh_impl.h"
#include "chrono_gpu/utils/ChGpuUtilities.h"
namespace chrono {
namespace gpu {
ChSystemGpuMesh_impl::ChSystemGpuMesh_impl(float sphere_rad, float density, float3 boxDims)
: ChSystemGpu_impl(sphere_rad, density, boxDims),
K_n_s2m_UU(0),
K_t_s2m_UU(0),
Gamma_n_s2m_UU(0),
Gamma_t_s2m_UU(0),
rolling_coeff_s2m_UU(0),
spinning_coeff_s2m_UU(0),
adhesion_s2m_over_gravity(0) {
// Allocate triangle collision parameters
gpuErrchk(cudaMallocManaged(&tri_params, sizeof(MeshParams), cudaMemAttachGlobal));
// Allocate the device soup storage
gpuErrchk(cudaMallocManaged(&meshSoup, sizeof(TriangleSoup), cudaMemAttachGlobal));
// start with no triangles
meshSoup->nTrianglesInSoup = 0;
meshSoup->numTriangleFamilies = 0;
tri_params->static_friction_coeff_s2m = 0;
}
ChSystemGpuMesh_impl::~ChSystemGpuMesh_impl() {
// work to do here
cleanupTriMesh();
}
double ChSystemGpuMesh_impl::get_max_K() const {
return std::max(std::max(K_n_s2s_UU, K_n_s2w_UU), K_n_s2m_UU);
}
void ChSystemGpuMesh_impl::initializeTriangles() {
double K_SU2UU = MASS_SU2UU / (TIME_SU2UU * TIME_SU2UU);
double GAMMA_SU2UU = 1. / TIME_SU2UU;
tri_params->K_n_s2m_SU = (float)(K_n_s2m_UU / K_SU2UU);
tri_params->K_t_s2m_SU = (float)(K_t_s2m_UU / K_SU2UU);
tri_params->Gamma_n_s2m_SU = (float)(Gamma_n_s2m_UU / GAMMA_SU2UU);
tri_params->Gamma_t_s2m_SU = (float)(Gamma_t_s2m_UU / GAMMA_SU2UU);
double magGravAcc = sqrt(X_accGrav * X_accGrav + Y_accGrav * Y_accGrav + Z_accGrav * Z_accGrav);
tri_params->adhesionAcc_s2m = (float)(adhesion_s2m_over_gravity * magGravAcc);
for (unsigned int fam = 0; fam < meshSoup->numTriangleFamilies; fam++) {
meshSoup->familyMass_SU[fam] = (float)(meshSoup->familyMass_SU[fam] / MASS_SU2UU);
}
tri_params->rolling_coeff_s2m_SU = (float)rolling_coeff_s2m_UU;
double* meshRot = new double[4];
memset(meshRot, 0.0, sizeof(meshRot));
meshRot[0] = 1.0;
for (unsigned int fam = 0; fam < meshSoup->numTriangleFamilies; fam++) {
generate_rot_matrix<float>(meshRot, tri_params->fam_frame_broad[fam].rot_mat);
tri_params->fam_frame_broad[fam].pos[0] = (float)0.0;
tri_params->fam_frame_broad[fam].pos[1] = (float)0.0;
tri_params->fam_frame_broad[fam].pos[2] = (float)0.0;
generate_rot_matrix<double>(meshRot, tri_params->fam_frame_narrow[fam].rot_mat);
tri_params->fam_frame_narrow[fam].pos[0] = (double)0.0;
tri_params->fam_frame_narrow[fam].pos[1] = (double)0.0;
tri_params->fam_frame_narrow[fam].pos[2] = (double)0.0;
}
TRACK_VECTOR_RESIZE(SD_numTrianglesTouching, nSDs, "SD_numTrianglesTouching", 0);
TRACK_VECTOR_RESIZE(SD_TriangleCompositeOffsets, nSDs, "SD_TriangleCompositeOffsets", 0);
// TODO do we have a good heuristic???
// this gets resized on-the-fly every timestep
TRACK_VECTOR_RESIZE(triangles_in_SD_composite, 0, "triangles_in_SD_composite", 0);
}
// p = pos + rot_mat * p
void ChSystemGpuMesh_impl::ApplyFrameTransform(float3& p, float* pos, float* rot_mat) {
float3 result;
// Apply rotation matrix to point
result.x = pos[0] + rot_mat[0] * p.x + rot_mat[1] * p.y + rot_mat[2] * p.z;
result.y = pos[1] + rot_mat[3] * p.x + rot_mat[4] * p.y + rot_mat[5] * p.z;
result.z = pos[2] + rot_mat[6] * p.x + rot_mat[7] * p.y + rot_mat[8] * p.z;
// overwrite p only at the end
p = result;
}
void ChSystemGpuMesh_impl::WriteMeshes(std::string filename) const {
if (file_write_mode == CHGPU_OUTPUT_MODE::NONE) {
return;
}
printf("Writing meshes\n");
std::ofstream outfile(filename + "_mesh.vtk", std::ios::out);
std::ostringstream ostream;
ostream << "# vtk DataFile Version 1.0\n";
ostream << "Unstructured Grid Example\n";
ostream << "ASCII\n";
ostream << "\n\n";
ostream << "DATASET UNSTRUCTURED_GRID\n";
ostream << "POINTS " << meshSoup->nTrianglesInSoup * 3 << " float\n";
// Write all vertices
for (unsigned int tri_i = 0; tri_i < meshSoup->nTrianglesInSoup; tri_i++) {
float3 p1 = make_float3(meshSoup->node1[tri_i].x, meshSoup->node1[tri_i].y, meshSoup->node1[tri_i].z);
float3 p2 = make_float3(meshSoup->node2[tri_i].x, meshSoup->node2[tri_i].y, meshSoup->node2[tri_i].z);
float3 p3 = make_float3(meshSoup->node3[tri_i].x, meshSoup->node3[tri_i].y, meshSoup->node3[tri_i].z);
unsigned int fam = meshSoup->triangleFamily_ID[tri_i];
ApplyFrameTransform(p1, tri_params->fam_frame_broad[fam].pos, tri_params->fam_frame_broad[fam].rot_mat);
ApplyFrameTransform(p2, tri_params->fam_frame_broad[fam].pos, tri_params->fam_frame_broad[fam].rot_mat);
ApplyFrameTransform(p3, tri_params->fam_frame_broad[fam].pos, tri_params->fam_frame_broad[fam].rot_mat);
ostream << p1.x << " " << p1.y << " " << p1.z << "\n";
ostream << p2.x << " " << p2.y << " " << p2.z << "\n";
ostream << p3.x << " " << p3.y << " " << p3.z << "\n";
}
ostream << "\n\n";
ostream << "CELLS " << meshSoup->nTrianglesInSoup << " " << 4 * meshSoup->nTrianglesInSoup << "\n";
for (unsigned int tri_i = 0; tri_i < meshSoup->nTrianglesInSoup; tri_i++) {
ostream << "3 " << 3 * tri_i << " " << 3 * tri_i + 1 << " " << 3 * tri_i + 2 << "\n";
}
ostream << "\n\n";
ostream << "CELL_TYPES " << meshSoup->nTrianglesInSoup << "\n";
for (unsigned int tri_i = 0; tri_i < meshSoup->nTrianglesInSoup; tri_i++) {
ostream << "9\n";
}
outfile << ostream.str();
}
void ChSystemGpuMesh_impl::cleanupTriMesh() {
cudaFree(meshSoup->triangleFamily_ID);
cudaFree(meshSoup->familyMass_SU);
cudaFree(meshSoup->node1);
cudaFree(meshSoup->node2);
cudaFree(meshSoup->node3);
cudaFree(meshSoup->vel);
cudaFree(meshSoup->omega);
cudaFree(meshSoup->generalizedForcesPerFamily);
cudaFree(tri_params->fam_frame_broad);
cudaFree(tri_params->fam_frame_narrow);
cudaFree(meshSoup);
cudaFree(tri_params);
}
void ChSystemGpuMesh_impl::ApplyMeshMotion(unsigned int mesh,
const double* pos,
const double* rot,
const double* lin_vel,
const double* ang_vel) {
// Set position and orientation
tri_params->fam_frame_broad[mesh].pos[0] = (float)pos[0];
tri_params->fam_frame_broad[mesh].pos[1] = (float)pos[1];
tri_params->fam_frame_broad[mesh].pos[2] = (float)pos[2];
generate_rot_matrix<float>(rot, tri_params->fam_frame_broad[mesh].rot_mat);
tri_params->fam_frame_narrow[mesh].pos[0] = pos[0];
tri_params->fam_frame_narrow[mesh].pos[1] = pos[1];
tri_params->fam_frame_narrow[mesh].pos[2] = pos[2];
generate_rot_matrix<double>(rot, tri_params->fam_frame_narrow[mesh].rot_mat);
// Set linear and angular velocity
const float C_V = (float)(TIME_SU2UU / LENGTH_SU2UU);
meshSoup->vel[mesh] = make_float3(C_V * (float)lin_vel[0], C_V * (float)lin_vel[1], C_V * (float)lin_vel[2]);
const float C_O = (float)TIME_SU2UU;
meshSoup->omega[mesh] = make_float3(C_O * (float)ang_vel[0], C_O * (float)ang_vel[1], C_O * (float)ang_vel[2]);
}
template <typename T>
void ChSystemGpuMesh_impl::generate_rot_matrix(const double* ep, T* rot_mat) {
rot_mat[0] = (T)(2 * (ep[0] * ep[0] + ep[1] * ep[1] - 0.5));
rot_mat[1] = (T)(2 * (ep[1] * ep[2] - ep[0] * ep[3]));
rot_mat[2] = (T)(2 * (ep[1] * ep[3] + ep[0] * ep[2]));
rot_mat[3] = (T)(2 * (ep[1] * ep[2] + ep[0] * ep[3]));
rot_mat[4] = (T)(2 * (ep[0] * ep[0] + ep[2] * ep[2] - 0.5));
rot_mat[5] = (T)(2 * (ep[2] * ep[3] - ep[0] * ep[1]));
rot_mat[6] = (T)(2 * (ep[1] * ep[3] - ep[0] * ep[2]));
rot_mat[7] = (T)(2 * (ep[2] * ep[3] + ep[0] * ep[1]));
rot_mat[8] = (T)(2 * (ep[0] * ep[0] + ep[3] * ep[3] - 0.5));
}
} // namespace gpu
} // namespace chrono
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2019 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Conlain Kelly, Nic Olsen, Dan Negrut, Radu Serban
// =============================================================================
#include <vector>
#include <algorithm>
#include <fstream>
#include <string>
#include <cmath>
#include "chrono/core/ChGlobal.h"
#include "chrono/core/ChVector.h"
#include "chrono/core/ChQuaternion.h"
#include "chrono/core/ChMatrix33.h"
#include "chrono_gpu/physics/ChSystemGpuMesh_impl.h"
#include "chrono_gpu/utils/ChGpuUtilities.h"
namespace chrono {
namespace gpu {
ChSystemGpuMesh_impl::ChSystemGpuMesh_impl(float sphere_rad, float density, float3 boxDims)
: ChSystemGpu_impl(sphere_rad, density, boxDims),
K_n_s2m_UU(0),
K_t_s2m_UU(0),
Gamma_n_s2m_UU(0),
Gamma_t_s2m_UU(0),
rolling_coeff_s2m_UU(0),
spinning_coeff_s2m_UU(0),
adhesion_s2m_over_gravity(0) {
// Allocate triangle collision parameters
gpuErrchk(cudaMallocManaged(&tri_params, sizeof(MeshParams), cudaMemAttachGlobal));
// Allocate the device soup storage
gpuErrchk(cudaMallocManaged(&meshSoup, sizeof(TriangleSoup), cudaMemAttachGlobal));
// start with no triangles
meshSoup->nTrianglesInSoup = 0;
meshSoup->numTriangleFamilies = 0;
tri_params->static_friction_coeff_s2m = 0;
}
ChSystemGpuMesh_impl::~ChSystemGpuMesh_impl() {
// work to do here
cleanupTriMesh();
}
double ChSystemGpuMesh_impl::get_max_K() const {
return std::max(std::max(K_n_s2s_UU, K_n_s2w_UU), K_n_s2m_UU);
}
void ChSystemGpuMesh_impl::initializeTriangles() {
double K_SU2UU = MASS_SU2UU / (TIME_SU2UU * TIME_SU2UU);
double GAMMA_SU2UU = 1. / TIME_SU2UU;
tri_params->K_n_s2m_SU = (float)(K_n_s2m_UU / K_SU2UU);
tri_params->K_t_s2m_SU = (float)(K_t_s2m_UU / K_SU2UU);
tri_params->Gamma_n_s2m_SU = (float)(Gamma_n_s2m_UU / GAMMA_SU2UU);
tri_params->Gamma_t_s2m_SU = (float)(Gamma_t_s2m_UU / GAMMA_SU2UU);
double magGravAcc = sqrt(X_accGrav * X_accGrav + Y_accGrav * Y_accGrav + Z_accGrav * Z_accGrav);
tri_params->adhesionAcc_s2m = (float)(adhesion_s2m_over_gravity * magGravAcc);
for (unsigned int fam = 0; fam < meshSoup->numTriangleFamilies; fam++) {
meshSoup->familyMass_SU[fam] = (float)(meshSoup->familyMass_SU[fam] / MASS_SU2UU);
}
tri_params->rolling_coeff_s2m_SU = (float)rolling_coeff_s2m_UU;
const double meshRot[4] = {1.,0.,0.,0.};
for (unsigned int fam = 0; fam < meshSoup->numTriangleFamilies; fam++) {
generate_rot_matrix<float>(meshRot, tri_params->fam_frame_broad[fam].rot_mat);
tri_params->fam_frame_broad[fam].pos[0] = (float)0.0;
tri_params->fam_frame_broad[fam].pos[1] = (float)0.0;
tri_params->fam_frame_broad[fam].pos[2] = (float)0.0;
generate_rot_matrix<double>(meshRot, tri_params->fam_frame_narrow[fam].rot_mat);
tri_params->fam_frame_narrow[fam].pos[0] = (double)0.0;
tri_params->fam_frame_narrow[fam].pos[1] = (double)0.0;
tri_params->fam_frame_narrow[fam].pos[2] = (double)0.0;
}
TRACK_VECTOR_RESIZE(SD_numTrianglesTouching, nSDs, "SD_numTrianglesTouching", 0);
TRACK_VECTOR_RESIZE(SD_TriangleCompositeOffsets, nSDs, "SD_TriangleCompositeOffsets", 0);
// TODO do we have a good heuristic???
// this gets resized on-the-fly every timestep
TRACK_VECTOR_RESIZE(triangles_in_SD_composite, 0, "triangles_in_SD_composite", 0);
}
// p = pos + rot_mat * p
void ChSystemGpuMesh_impl::ApplyFrameTransform(float3& p, float* pos, float* rot_mat) {
float3 result;
// Apply rotation matrix to point
result.x = pos[0] + rot_mat[0] * p.x + rot_mat[1] * p.y + rot_mat[2] * p.z;
result.y = pos[1] + rot_mat[3] * p.x + rot_mat[4] * p.y + rot_mat[5] * p.z;
result.z = pos[2] + rot_mat[6] * p.x + rot_mat[7] * p.y + rot_mat[8] * p.z;
// overwrite p only at the end
p = result;
}
void ChSystemGpuMesh_impl::WriteMeshes(std::string filename) const {
if (file_write_mode == CHGPU_OUTPUT_MODE::NONE) {
return;
}
printf("Writing meshes\n");
std::ofstream outfile(filename + "_mesh.vtk", std::ios::out);
std::ostringstream ostream;
ostream << "# vtk DataFile Version 1.0\n";
ostream << "Unstructured Grid Example\n";
ostream << "ASCII\n";
ostream << "\n\n";
ostream << "DATASET UNSTRUCTURED_GRID\n";
ostream << "POINTS " << meshSoup->nTrianglesInSoup * 3 << " float\n";
// Write all vertices
for (unsigned int tri_i = 0; tri_i < meshSoup->nTrianglesInSoup; tri_i++) {
float3 p1 = make_float3(meshSoup->node1[tri_i].x, meshSoup->node1[tri_i].y, meshSoup->node1[tri_i].z);
float3 p2 = make_float3(meshSoup->node2[tri_i].x, meshSoup->node2[tri_i].y, meshSoup->node2[tri_i].z);
float3 p3 = make_float3(meshSoup->node3[tri_i].x, meshSoup->node3[tri_i].y, meshSoup->node3[tri_i].z);
unsigned int fam = meshSoup->triangleFamily_ID[tri_i];
ApplyFrameTransform(p1, tri_params->fam_frame_broad[fam].pos, tri_params->fam_frame_broad[fam].rot_mat);
ApplyFrameTransform(p2, tri_params->fam_frame_broad[fam].pos, tri_params->fam_frame_broad[fam].rot_mat);
ApplyFrameTransform(p3, tri_params->fam_frame_broad[fam].pos, tri_params->fam_frame_broad[fam].rot_mat);
ostream << p1.x << " " << p1.y << " " << p1.z << "\n";
ostream << p2.x << " " << p2.y << " " << p2.z << "\n";
ostream << p3.x << " " << p3.y << " " << p3.z << "\n";
}
ostream << "\n\n";
ostream << "CELLS " << meshSoup->nTrianglesInSoup << " " << 4 * meshSoup->nTrianglesInSoup << "\n";
for (unsigned int tri_i = 0; tri_i < meshSoup->nTrianglesInSoup; tri_i++) {
ostream << "3 " << 3 * tri_i << " " << 3 * tri_i + 1 << " " << 3 * tri_i + 2 << "\n";
}
ostream << "\n\n";
ostream << "CELL_TYPES " << meshSoup->nTrianglesInSoup << "\n";
for (unsigned int tri_i = 0; tri_i < meshSoup->nTrianglesInSoup; tri_i++) {
ostream << "9\n";
}
outfile << ostream.str();
}
void ChSystemGpuMesh_impl::cleanupTriMesh() {
cudaFree(meshSoup->triangleFamily_ID);
cudaFree(meshSoup->familyMass_SU);
cudaFree(meshSoup->node1);
cudaFree(meshSoup->node2);
cudaFree(meshSoup->node3);
cudaFree(meshSoup->vel);
cudaFree(meshSoup->omega);
cudaFree(meshSoup->generalizedForcesPerFamily);
cudaFree(tri_params->fam_frame_broad);
cudaFree(tri_params->fam_frame_narrow);
cudaFree(meshSoup);
cudaFree(tri_params);
}
void ChSystemGpuMesh_impl::ApplyMeshMotion(unsigned int mesh,
const double* pos,
const double* rot,
const double* lin_vel,
const double* ang_vel) {
// Set position and orientation
tri_params->fam_frame_broad[mesh].pos[0] = (float)pos[0];
tri_params->fam_frame_broad[mesh].pos[1] = (float)pos[1];
tri_params->fam_frame_broad[mesh].pos[2] = (float)pos[2];
generate_rot_matrix<float>(rot, tri_params->fam_frame_broad[mesh].rot_mat);
tri_params->fam_frame_narrow[mesh].pos[0] = pos[0];
tri_params->fam_frame_narrow[mesh].pos[1] = pos[1];
tri_params->fam_frame_narrow[mesh].pos[2] = pos[2];
generate_rot_matrix<double>(rot, tri_params->fam_frame_narrow[mesh].rot_mat);
// Set linear and angular velocity
const float C_V = (float)(TIME_SU2UU / LENGTH_SU2UU);
meshSoup->vel[mesh] = make_float3(C_V * (float)lin_vel[0], C_V * (float)lin_vel[1], C_V * (float)lin_vel[2]);
const float C_O = (float)TIME_SU2UU;
meshSoup->omega[mesh] = make_float3(C_O * (float)ang_vel[0], C_O * (float)ang_vel[1], C_O * (float)ang_vel[2]);
}
template <typename T>
void ChSystemGpuMesh_impl::generate_rot_matrix(const double* ep, T* rot_mat) {
rot_mat[0] = (T)(2 * (ep[0] * ep[0] + ep[1] * ep[1] - 0.5));
rot_mat[1] = (T)(2 * (ep[1] * ep[2] - ep[0] * ep[3]));
rot_mat[2] = (T)(2 * (ep[1] * ep[3] + ep[0] * ep[2]));
rot_mat[3] = (T)(2 * (ep[1] * ep[2] + ep[0] * ep[3]));
rot_mat[4] = (T)(2 * (ep[0] * ep[0] + ep[2] * ep[2] - 0.5));
rot_mat[5] = (T)(2 * (ep[2] * ep[3] - ep[0] * ep[1]));
rot_mat[6] = (T)(2 * (ep[1] * ep[3] - ep[0] * ep[2]));
rot_mat[7] = (T)(2 * (ep[2] * ep[3] + ep[0] * ep[1]));
rot_mat[8] = (T)(2 * (ep[0] * ep[0] + ep[3] * ep[3] - 0.5));
}
} // namespace gpu
} // namespace chrono
|
Correct mesh default position initilization in ChSystemGpuMesh_impl
|
Correct mesh default position initilization in ChSystemGpuMesh_impl
|
C++
|
bsd-3-clause
|
Milad-Rakhsha/chrono,dariomangoni/chrono,projectchrono/chrono,Milad-Rakhsha/chrono,Milad-Rakhsha/chrono,projectchrono/chrono,dariomangoni/chrono,dariomangoni/chrono,dariomangoni/chrono,rserban/chrono,Milad-Rakhsha/chrono,rserban/chrono,rserban/chrono,projectchrono/chrono,dariomangoni/chrono,projectchrono/chrono,rserban/chrono,Milad-Rakhsha/chrono,dariomangoni/chrono,Milad-Rakhsha/chrono,rserban/chrono,projectchrono/chrono,projectchrono/chrono,rserban/chrono,rserban/chrono
|
042b10e4ab905bb4296439d616968dff639f86d6
|
src/gui/test_bemo.cpp
|
src/gui/test_bemo.cpp
|
#include <taichi/visual/gui.h>
#include <taichi/common/task.h>
TC_NAMESPACE_BEGIN
auto test_bemo = []() {
GUI gui("Bemo Test", 800, 400, false);
auto canvas = *gui.canvas;
real t = 0;
while (1) {
t += 0.02_f;
canvas.clear(Vector4(0.95));
for (int i = 0; i < 30; i++) {
canvas.circle(i * 10 + 100, 250 + std::sin(t + i * 0.1_f) * 50_f)
.color(0.7_f, 0.2_f, 0.0_f, 0.9_f)
.radius(5);
}
canvas.color(0.0, 0.0, 1.0, 1.0).radius(5 + 2 * std::sin(t * 10_f));
canvas.path()
.path(Vector2(100, 100), Vector2(200, 75 + std::cos(t) * 50_f),
Vector2(300, 75 + std::cos(t) * 50_f))
.close()
.color(0, 0, 0)
.width(5);
for (int i = 0; i < 60; i++) {
canvas.circle(i * 10 + 100, 150 + std::sin(t + i * 0.1_f) * 50_f);
}
gui.update();
}
};
TC_REGISTER_TASK(test_bemo);
TC_NAMESPACE_END
|
#include <taichi/visual/gui.h>
#include <taichi/common/task.h>
TC_NAMESPACE_BEGIN
auto test_bemo = []() {
GUI gui("Bemo Test", 800, 400, false);
auto canvas = *gui.canvas;
real t = 0;
while (1) {
t += 0.02_f;
canvas.clear(Vector4(0.95));
for (int i = 0; i < 30; i++) {
canvas.circle(i * 10 + 100, 250 + std::sin(t + i * 0.1_f) * 50_f)
.color(0.7_f, 0.2_f, 0.0_f, 0.9_f)
.radius(5);
}
canvas.color(0.0_f, 0.0_f, 1.0_f, 1.0_f).radius(5 + 2 * std::sin(t * 10_f));
canvas.path()
.path(Vector2(100, 100), Vector2(200, 75 + std::cos(t) * 50_f),
Vector2(300, 75 + std::cos(t) * 50_f))
.close()
.color(0, 0, 0)
.width(5);
for (int i = 0; i < 60; i++) {
canvas.circle(i * 10 + 100, 150 + std::sin(t + i * 0.1_f) * 50_f);
}
gui.update();
}
};
TC_REGISTER_TASK(test_bemo);
TC_NAMESPACE_END
|
Fix float compilation
|
Fix float compilation
|
C++
|
apache-2.0
|
yuanming-hu/taichi,yuanming-hu/taichi,yuanming-hu/taichi,yuanming-hu/taichi
|
4af94829b94a15c4dc51571a2ddf5a015a81d98a
|
tensorflow/compiler/mlir/tensorflow/transforms/executor_island_coarsening.cc
|
tensorflow/compiler/mlir/tensorflow/transforms/executor_island_coarsening.cc
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This transformation pass takes TFExecutor dialect IslandOps and merges them.
// Note, this currently does not handle TensorFlow V1 style control flow/frames
// or side effecting ops yet.
#include <iterator>
#include <tuple>
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include "mlir/IR/Block.h" // TF:local_config_mlir
#include "mlir/IR/Builders.h" // TF:local_config_mlir
#include "mlir/IR/Location.h" // TF:local_config_mlir
#include "mlir/IR/Operation.h" // TF:local_config_mlir
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/Pass/PassRegistry.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/core/platform/logging.h"
namespace mlir {
namespace TFExecutor {
namespace {
// IslandType is an enum representing if an island is the island (parent)
// merging another island or is the island (child) being being merged.
enum IslandType { kParentIsland, kChildIsland };
// Output is a helper struct holding a result index and island type (parent or
// child).
struct Output {
Output(IslandType island_type, int result_index)
: island_type(island_type), result_index(result_index) {}
IslandType island_type;
int result_index;
};
struct ExecutorIslandCoarsening
: public FunctionPass<ExecutorIslandCoarsening> {
void runOnFunction() override;
private:
void MergeIslands(OpBuilder* builder, tf_executor::IslandOp* parent,
tf_executor::IslandOp* child, IslandType insert_position);
bool MergeIslandWithOperand(OpBuilder* builder, tf_executor::IslandOp* child);
bool MergeIslandWithResult(OpBuilder* builder, tf_executor::IslandOp* parent);
};
// Finds the operation leading to an island that the island can be merged with.
// This looks for the operation, either control input or data input to an op,
// that is closest to the island in the graph. If no candidate can be found or
// the op found is not an island, an empty optional is returned.
llvm::Optional<tf_executor::IslandOp> GetOperandCandidateToMergeWith(
tf_executor::IslandOp* island) {
Operation* graph_op = island->getParentOp();
Operation* candidate = nullptr;
// Check island control operands.
for (Value* input : island->controlInputs()) {
Operation* def = input->getDefiningOp();
DCHECK_EQ(def->getParentOp(), graph_op);
if (!candidate || candidate->isBeforeInBlock(def)) candidate = def;
}
// Check island data operands.
island->walk([graph_op, &candidate](Operation* op) {
for (Value* input : op->getOperands()) {
Operation* def = input->getDefiningOp();
if (!def || def->getParentOp() != graph_op) continue;
if (!candidate || candidate->isBeforeInBlock(def)) candidate = def;
}
});
if (!candidate || !llvm::isa<tf_executor::IslandOp>(candidate))
return llvm::None;
return llvm::Optional<tf_executor::IslandOp>(
llvm::cast<tf_executor::IslandOp>(candidate));
}
// Finds the operation leading from an island that the island can be merged
// with. This looks for the operation, either control output or data output to
// an op, that is closest to the island in the graph. If no candidate can be
// found or the op found is not an island, an empty optional is returned.
llvm::Optional<tf_executor::IslandOp> GetResultCandidateToMergeWith(
tf_executor::IslandOp* island) {
Operation* graph_op = island->getParentOp();
Operation* candidate = nullptr;
// Check island control results.
for (Operation* user : island->control()->getUsers()) {
DCHECK_EQ(user->getParentOp(), graph_op);
if (!candidate || candidate->isBeforeInBlock(user)) candidate = user;
}
// Check island data results.
Block& graph_block = llvm::cast<tf_executor::GraphOp>(graph_op).GetBody();
for (Value* result : island->outputs()) {
for (Operation* user : result->getUsers()) {
Operation* def = graph_block.findAncestorInstInBlock(*user);
DCHECK_NE(def, nullptr);
if (!candidate || def->isBeforeInBlock(candidate)) candidate = def;
}
}
if (!candidate || !llvm::isa<tf_executor::IslandOp>(candidate))
return llvm::None;
return llvm::Optional<tf_executor::IslandOp>(
llvm::cast<tf_executor::IslandOp>(candidate));
}
// Collects the operands for the new island by collecting all control inputs of
// the islands being merged.
llvm::SmallSetVector<Value*, 8> GetNewIslandOperands(
tf_executor::IslandOp* parent, tf_executor::IslandOp* child) {
llvm::SmallSetVector<Value*, 8> operands;
operands.insert(parent->getOperands().begin(), parent->getOperands().end());
operands.insert(child->getOperands().begin(), child->getOperands().end());
operands.remove(parent->control());
return operands;
}
// Collects the results for the new island by going through each data output of
// the islands being merged. Unused results outside of the merged island to be
// formed are pruned. If the child island inner ops consume the parent island
// control output, the child island inner ops will have that respective control
// input pruned. Results of the parent island that are consumed by the child
// island are replaced by the respective inner ops output from the parent
// island.
llvm::SmallVector<Output, 8> GetNewIslandResultsAndForwardOutputs(
mlir::MLIRContext* context, tf_executor::IslandOp* parent,
tf_executor::IslandOp* child, llvm::SmallVector<Type, 8>* result_types) {
llvm::SmallVector<Output, 8> results;
Block& child_body = child->GetBody();
int result_index = 0;
Operation& last_op = parent->GetBody().back();
auto yield_op = cast<tf_executor::YieldOp>(last_op);
for (Value* output : parent->outputs()) {
bool output_captured = false;
Value* yield_input = yield_op.getOperand(result_index);
for (auto& use : llvm::make_early_inc_range(output->getUses())) {
if (child_body.findAncestorInstInBlock(*use.getOwner())) {
// Forward output from inner op.
use.set(yield_input);
} else if (!output_captured) {
results.push_back(Output(IslandType::kParentIsland, result_index));
result_types->push_back(output->getType());
output_captured = true;
}
}
result_index++;
}
result_index = 0;
for (Value* output : child->outputs()) {
if (!output->use_empty()) {
results.push_back(Output(IslandType::kChildIsland, result_index));
result_types->push_back(output->getType());
}
result_index++;
}
// IslandOps always have a control output.
result_types->push_back(tf_executor::ControlType::get(context));
return results;
}
// Creates the new merged island.
tf_executor::IslandOp CreateNewIsland(
OpBuilder* builder, Operation* old_island,
const llvm::SmallVector<Type, 8>& result_types,
const llvm::SmallSetVector<Value*, 8>& operands) {
builder->setInsertionPoint(old_island);
auto new_island = builder->create<tf_executor::IslandOp>(
old_island->getLoc(), result_types, operands.getArrayRef(),
ArrayRef<NamedAttribute>{});
new_island.body().push_back(new Block);
return new_island;
}
// Creates respective YieldOp for the new merged island.
tf_executor::YieldOp CreateNewIslandYieldOp(
OpBuilder* builder, tf_executor::IslandOp* new_island,
const llvm::SmallVector<Output, 8>& results, tf_executor::IslandOp* parent,
tf_executor::IslandOp* child) {
llvm::SmallVector<Value*, 8> yield_operands;
yield_operands.reserve(results.size());
for (auto ret_vals : llvm::zip(results, new_island->outputs())) {
// Get consumed output (island type and result index).
const auto& output = std::get<0>(ret_vals);
tf_executor::IslandOp* output_island =
output.island_type == IslandType::kParentIsland ? parent : child;
Value* result = output_island->getResult(output.result_index);
// Replace original result with new island result.
result->replaceAllUsesWith(std::get<1>(ret_vals));
// Find YieldOp in original island, grab the associated operand (inner op
// output) and add it as a operand to the YieldOp of the merged island.
yield_operands.push_back(
output_island->GetBody().back().getOperand(output.result_index));
}
// Create YieldOp for the new island.
builder->setInsertionPoint(&new_island->GetBody(),
new_island->GetBody().end());
return builder->create<tf_executor::YieldOp>(new_island->getLoc(),
yield_operands);
}
// Moves inner ops (excluding last op/YieldOp) from islands being merged into
// the new merged island.
void MoveInnerOpsToNewIsland(tf_executor::IslandOp* parent,
tf_executor::IslandOp* child,
Operation* new_yield_op) {
Block* block = new_yield_op->getBlock();
auto move_inner_ops = [block, new_yield_op](tf_executor::IslandOp* island) {
auto& island_body = island->GetBody().getOperations();
block->getOperations().splice(new_yield_op->getIterator(), island_body,
island_body.begin(),
std::prev(island_body.end()));
};
move_inner_ops(parent);
move_inner_ops(child);
}
// Merges two islands and places new merged island before parent or child.
void ExecutorIslandCoarsening::MergeIslands(OpBuilder* builder,
tf_executor::IslandOp* parent,
tf_executor::IslandOp* child,
IslandType insert_position) {
// Collect operands for the new merged island.
llvm::SmallSetVector<Value*, 8> operands =
GetNewIslandOperands(parent, child);
// Collect results and result types for the new merged island.
llvm::SmallVector<Type, 8> result_types;
llvm::SmallVector<Output, 8> results = GetNewIslandResultsAndForwardOutputs(
&getContext(), parent, child, &result_types);
// Create the new merged island.
tf_executor::IslandOp new_island = CreateNewIsland(
builder, insert_position == IslandType::kParentIsland ? *parent : *child,
result_types, operands);
// Create associated YieldOp for the new merged island.
tf_executor::YieldOp new_yield_op =
CreateNewIslandYieldOp(builder, &new_island, results, parent, child);
// Move inner ops from original islands into the new island.
MoveInnerOpsToNewIsland(parent, child, new_yield_op.getOperation());
// Update control inputs to point to the new merged island.
child->control()->replaceAllUsesWith(new_island.control());
parent->control()->replaceAllUsesWith(new_island.control());
// Remove merged islands.
child->erase();
parent->erase();
}
// Merges island with the operand closest to the island in the graph. The
// operand must be another IslandOp for merging to take place. A new island is
// created and the islands being merged are removed if a merge took place.
// Returns true if the island was merged with its operand.
bool ExecutorIslandCoarsening::MergeIslandWithOperand(
OpBuilder* builder, tf_executor::IslandOp* child) {
// Find candidate operand to merge island with.
llvm::Optional<tf_executor::IslandOp> candidate =
GetOperandCandidateToMergeWith(child);
if (!candidate.hasValue()) return false;
auto& parent = candidate.getValue();
MergeIslands(builder, &parent, child, IslandType::kParentIsland);
return true;
}
// Merges island with the result closest to the island in the graph. The result
// must be another IslandOp for merging to take place. A new island is created
// and the islands being merged are removed if a merge took place. Returns true
// if the island was merged with its result.
bool ExecutorIslandCoarsening::MergeIslandWithResult(
OpBuilder* builder, tf_executor::IslandOp* parent) {
// Find candidate result to merge island with.
llvm::Optional<tf_executor::IslandOp> candidate =
GetResultCandidateToMergeWith(parent);
if (!candidate.hasValue()) return false;
auto& child = candidate.getValue();
MergeIslands(builder, parent, &child, IslandType::kChildIsland);
return false;
}
void ExecutorIslandCoarsening::runOnFunction() {
getFunction().walk<tf_executor::GraphOp>([this](tf_executor::GraphOp graph) {
Block& graph_body = graph.GetBody();
OpBuilder builder(&graph_body);
bool updated = false;
do {
updated = false;
auto reversed = llvm::reverse(graph_body);
for (Operation& operation : llvm::make_early_inc_range(reversed)) {
auto island = llvm::dyn_cast<tf_executor::IslandOp>(operation);
if (!island) continue;
updated |= MergeIslandWithResult(&builder, &island);
}
for (Operation& operation : llvm::make_early_inc_range(graph_body)) {
auto island = llvm::dyn_cast<tf_executor::IslandOp>(operation);
if (!island) continue;
updated |= MergeIslandWithOperand(&builder, &island);
}
} while (updated);
});
}
} // namespace
FunctionPassBase* CreateTFExecutorIslandCoarseningPass() {
return new ExecutorIslandCoarsening();
}
static PassRegistration<ExecutorIslandCoarsening> pass(
"tf-executor-island-coarsening", "Merges TFExecutor dialect IslandOps");
} // namespace TFExecutor
} // namespace mlir
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This transformation pass takes TFExecutor dialect IslandOps and merges them.
// Note, this currently does not handle TensorFlow V1 style control flow/frames
// or side effecting ops yet.
#include <iterator>
#include <tuple>
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include "mlir/IR/Block.h" // TF:local_config_mlir
#include "mlir/IR/Builders.h" // TF:local_config_mlir
#include "mlir/IR/Location.h" // TF:local_config_mlir
#include "mlir/IR/Operation.h" // TF:local_config_mlir
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/Pass/PassRegistry.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/core/platform/logging.h"
namespace mlir {
namespace TFExecutor {
namespace {
// IslandType is an enum representing if an island is the island (parent)
// merging another island or is the island (child) being being merged.
enum IslandType { kParentIsland, kChildIsland };
// Output is a helper struct holding a result index and island type (parent or
// child).
struct Output {
Output(IslandType island_type, int result_index)
: island_type(island_type), result_index(result_index) {}
IslandType island_type;
int result_index;
};
struct ExecutorIslandCoarsening
: public FunctionPass<ExecutorIslandCoarsening> {
void runOnFunction() override;
private:
void MergeIslands(OpBuilder* builder, tf_executor::IslandOp* parent,
tf_executor::IslandOp* child, IslandType insert_position);
bool MergeIslandWithOperand(OpBuilder* builder, tf_executor::IslandOp* child);
bool MergeIslandWithResult(OpBuilder* builder, tf_executor::IslandOp* parent);
};
// Finds the operation leading to an island that the island can be merged with.
// This looks for the operation, either control input or data input to an op,
// that is closest to the island in the graph. If no candidate can be found or
// the op found is not an island, an empty optional is returned.
llvm::Optional<tf_executor::IslandOp> GetOperandCandidateToMergeWith(
tf_executor::IslandOp* island) {
Operation* graph_op = island->getParentOp();
Operation* candidate = nullptr;
// Check island control operands.
for (Value* input : island->controlInputs()) {
Operation* def = input->getDefiningOp();
DCHECK_EQ(def->getParentOp(), graph_op);
if (!candidate || candidate->isBeforeInBlock(def)) candidate = def;
}
// Check island data operands.
island->walk([graph_op, &candidate](Operation* op) {
for (Value* input : op->getOperands()) {
Operation* def = input->getDefiningOp();
if (!def || def->getParentOp() != graph_op) continue;
if (!candidate || candidate->isBeforeInBlock(def)) candidate = def;
}
});
if (!candidate || !llvm::isa<tf_executor::IslandOp>(candidate))
return llvm::None;
return llvm::Optional<tf_executor::IslandOp>(
llvm::cast<tf_executor::IslandOp>(candidate));
}
// Finds the operation leading from an island that the island can be merged
// with. This looks for the operation, either control output or data output to
// an op, that is closest to the island in the graph. If no candidate can be
// found or the op found is not an island, an empty optional is returned.
llvm::Optional<tf_executor::IslandOp> GetResultCandidateToMergeWith(
tf_executor::IslandOp* island) {
Operation* graph_op = island->getParentOp();
Operation* candidate = nullptr;
// Check island control results.
for (Operation* user : island->control()->getUsers()) {
DCHECK_EQ(user->getParentOp(), graph_op);
if (!candidate || candidate->isBeforeInBlock(user)) candidate = user;
}
// Check island data results.
Block& graph_body = llvm::cast<tf_executor::GraphOp>(graph_op).GetBody();
for (Value* result : island->outputs()) {
for (Operation* user : result->getUsers()) {
Operation* def = graph_body.findAncestorInstInBlock(*user);
DCHECK_NE(def, nullptr);
if (!candidate || def->isBeforeInBlock(candidate)) candidate = def;
}
}
if (!candidate || !llvm::isa<tf_executor::IslandOp>(candidate))
return llvm::None;
return llvm::Optional<tf_executor::IslandOp>(
llvm::cast<tf_executor::IslandOp>(candidate));
}
// Collects the operands for the new island by collecting all control inputs of
// the islands being merged.
llvm::SmallSetVector<Value*, 8> GetNewIslandOperands(
tf_executor::IslandOp* parent, tf_executor::IslandOp* child) {
llvm::SmallSetVector<Value*, 8> operands;
operands.insert(parent->getOperands().begin(), parent->getOperands().end());
operands.insert(child->getOperands().begin(), child->getOperands().end());
operands.remove(parent->control());
return operands;
}
// Collects the results for the new island by going through each data output of
// the islands being merged. Unused results outside of the merged island to be
// formed are pruned. If the child island inner ops consume the parent island
// control output, the child island inner ops will have that respective control
// input pruned. Results of the parent island that are consumed by the child
// island are replaced by the respective inner ops output from the parent
// island.
llvm::SmallVector<Output, 8> GetNewIslandResultsAndForwardOutputs(
mlir::MLIRContext* context, tf_executor::IslandOp* parent,
tf_executor::IslandOp* child, llvm::SmallVector<Type, 8>* result_types) {
llvm::SmallVector<Output, 8> results;
Operation& last_op = parent->GetBody().back();
auto yield_op = cast<tf_executor::YieldOp>(last_op);
Block& child_body = child->GetBody();
for (auto& ret_and_idx : llvm::enumerate(parent->outputs())) {
bool output_captured = false;
Value* yield_input = yield_op.getOperand(ret_and_idx.index());
for (auto& use :
llvm::make_early_inc_range(ret_and_idx.value()->getUses())) {
if (child_body.findAncestorInstInBlock(*use.getOwner())) {
// Forward output from inner op.
use.set(yield_input);
} else if (!output_captured) {
results.push_back(
Output(IslandType::kParentIsland, ret_and_idx.index()));
result_types->push_back(ret_and_idx.value()->getType());
output_captured = true;
}
}
}
for (auto& ret_and_idx : llvm::enumerate(child->outputs())) {
if (!ret_and_idx.value()->use_empty()) {
results.push_back(Output(IslandType::kChildIsland, ret_and_idx.index()));
result_types->push_back(ret_and_idx.value()->getType());
}
}
// IslandOps always have a control output.
result_types->push_back(tf_executor::ControlType::get(context));
return results;
}
// Creates the new merged island.
tf_executor::IslandOp CreateNewIsland(
OpBuilder* builder, Operation* old_island,
const llvm::SmallVector<Type, 8>& result_types,
const llvm::SmallSetVector<Value*, 8>& operands) {
builder->setInsertionPoint(old_island);
auto new_island = builder->create<tf_executor::IslandOp>(
old_island->getLoc(), result_types, operands.getArrayRef(),
ArrayRef<NamedAttribute>{});
new_island.body().push_back(new Block);
return new_island;
}
// Creates respective YieldOp for the new merged island.
tf_executor::YieldOp CreateNewIslandYieldOp(
OpBuilder* builder, tf_executor::IslandOp* new_island,
const llvm::SmallVector<Output, 8>& results, tf_executor::IslandOp* parent,
tf_executor::IslandOp* child) {
llvm::SmallVector<Value*, 8> yield_operands;
yield_operands.reserve(results.size());
for (auto ret_vals : llvm::zip(results, new_island->outputs())) {
// Get consumed output (island type and result index).
const auto& output = std::get<0>(ret_vals);
tf_executor::IslandOp* output_island =
output.island_type == IslandType::kParentIsland ? parent : child;
Value* result = output_island->getResult(output.result_index);
// Replace original result with new island result.
result->replaceAllUsesWith(std::get<1>(ret_vals));
// Find YieldOp in original island, grab the associated operand (inner op
// output) and add it as a operand to the YieldOp of the merged island.
yield_operands.push_back(
output_island->GetBody().back().getOperand(output.result_index));
}
// Create YieldOp for the new island.
builder->setInsertionPoint(&new_island->GetBody(),
new_island->GetBody().end());
return builder->create<tf_executor::YieldOp>(new_island->getLoc(),
yield_operands);
}
// Moves inner ops (excluding last op/YieldOp) from islands being merged into
// the new merged island.
void MoveInnerOpsToNewIsland(tf_executor::IslandOp* parent,
tf_executor::IslandOp* child,
Operation* new_yield_op) {
Block* block = new_yield_op->getBlock();
auto move_inner_ops = [block, new_yield_op](tf_executor::IslandOp* island) {
auto& island_body = island->GetBody().getOperations();
block->getOperations().splice(new_yield_op->getIterator(), island_body,
island_body.begin(),
std::prev(island_body.end()));
};
move_inner_ops(parent);
move_inner_ops(child);
}
// Merges two islands and places new merged island before parent or child.
void ExecutorIslandCoarsening::MergeIslands(OpBuilder* builder,
tf_executor::IslandOp* parent,
tf_executor::IslandOp* child,
IslandType insert_position) {
// Collect operands for the new merged island.
llvm::SmallSetVector<Value*, 8> operands =
GetNewIslandOperands(parent, child);
// Collect results and result types for the new merged island.
llvm::SmallVector<Type, 8> result_types;
llvm::SmallVector<Output, 8> results = GetNewIslandResultsAndForwardOutputs(
&getContext(), parent, child, &result_types);
// Create the new merged island.
tf_executor::IslandOp new_island = CreateNewIsland(
builder, insert_position == IslandType::kParentIsland ? *parent : *child,
result_types, operands);
// Create associated YieldOp for the new merged island.
tf_executor::YieldOp new_yield_op =
CreateNewIslandYieldOp(builder, &new_island, results, parent, child);
// Move inner ops from original islands into the new island.
MoveInnerOpsToNewIsland(parent, child, new_yield_op.getOperation());
// Update control inputs to point to the new merged island.
child->control()->replaceAllUsesWith(new_island.control());
parent->control()->replaceAllUsesWith(new_island.control());
// Remove merged islands.
child->erase();
parent->erase();
}
// Merges island with the operand closest to the island in the graph. The
// operand must be another IslandOp for merging to take place. A new island is
// created and the islands being merged are removed if a merge took place.
// Returns true if the island was merged with its operand.
bool ExecutorIslandCoarsening::MergeIslandWithOperand(
OpBuilder* builder, tf_executor::IslandOp* child) {
// Find candidate operand to merge island with.
llvm::Optional<tf_executor::IslandOp> candidate =
GetOperandCandidateToMergeWith(child);
if (!candidate.hasValue()) return false;
auto& parent = candidate.getValue();
MergeIslands(builder, &parent, child, IslandType::kParentIsland);
return true;
}
// Merges island with the result closest to the island in the graph. The result
// must be another IslandOp for merging to take place. A new island is created
// and the islands being merged are removed if a merge took place. Returns true
// if the island was merged with its result.
bool ExecutorIslandCoarsening::MergeIslandWithResult(
OpBuilder* builder, tf_executor::IslandOp* parent) {
// Find candidate result to merge island with.
llvm::Optional<tf_executor::IslandOp> candidate =
GetResultCandidateToMergeWith(parent);
if (!candidate.hasValue()) return false;
auto& child = candidate.getValue();
MergeIslands(builder, parent, &child, IslandType::kChildIsland);
return false;
}
void ExecutorIslandCoarsening::runOnFunction() {
getFunction().walk<tf_executor::GraphOp>([this](tf_executor::GraphOp graph) {
Block& graph_body = graph.GetBody();
OpBuilder builder(&graph_body);
bool updated = false;
do {
updated = false;
auto reversed = llvm::reverse(graph_body);
for (Operation& operation : llvm::make_early_inc_range(reversed)) {
auto island = llvm::dyn_cast<tf_executor::IslandOp>(operation);
if (!island) continue;
updated |= MergeIslandWithResult(&builder, &island);
}
for (Operation& operation : llvm::make_early_inc_range(graph_body)) {
auto island = llvm::dyn_cast<tf_executor::IslandOp>(operation);
if (!island) continue;
updated |= MergeIslandWithOperand(&builder, &island);
}
} while (updated);
});
}
} // namespace
FunctionPassBase* CreateTFExecutorIslandCoarseningPass() {
return new ExecutorIslandCoarsening();
}
static PassRegistration<ExecutorIslandCoarsening> pass(
"tf-executor-island-coarsening", "Merges TFExecutor dialect IslandOps");
} // namespace TFExecutor
} // namespace mlir
|
Replace separate counter with llvm::enumerate.
|
Replace separate counter with llvm::enumerate.
PiperOrigin-RevId: 262194946
|
C++
|
apache-2.0
|
tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,aldian/tensorflow,adit-chandra/tensorflow,petewarden/tensorflow,petewarden/tensorflow,cxxgtxy/tensorflow,aam-at/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,DavidNorman/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,yongtang/tensorflow,petewarden/tensorflow,arborh/tensorflow,DavidNorman/tensorflow,aam-at/tensorflow,xzturn/tensorflow,freedomtan/tensorflow,xzturn/tensorflow,adit-chandra/tensorflow,chemelnucfin/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,ppwwyyxx/tensorflow,cxxgtxy/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,Intel-Corporation/tensorflow,arborh/tensorflow,ppwwyyxx/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,paolodedios/tensorflow,chemelnucfin/tensorflow,renyi533/tensorflow,jhseu/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,petewarden/tensorflow,sarvex/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,gautam1858/tensorflow,ppwwyyxx/tensorflow,chemelnucfin/tensorflow,karllessard/tensorflow,aldian/tensorflow,gunan/tensorflow,freedomtan/tensorflow,petewarden/tensorflow,adit-chandra/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,cxxgtxy/tensorflow,karllessard/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,paolodedios/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,chemelnucfin/tensorflow,annarev/tensorflow,petewarden/tensorflow,jhseu/tensorflow,gunan/tensorflow,annarev/tensorflow,xzturn/tensorflow,arborh/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,renyi533/tensorflow,arborh/tensorflow,davidzchen/tensorflow,gautam1858/tensorflow,gunan/tensorflow,gunan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,Intel-tensorflow/tensorflow,sarvex/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,renyi533/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,chemelnucfin/tensorflow,freedomtan/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,yongtang/tensorflow,gunan/tensorflow,karllessard/tensorflow,jhseu/tensorflow,renyi533/tensorflow,paolodedios/tensorflow,xzturn/tensorflow,karllessard/tensorflow,ppwwyyxx/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow,DavidNorman/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,karllessard/tensorflow,aam-at/tensorflow,gautam1858/tensorflow,chemelnucfin/tensorflow,renyi533/tensorflow,DavidNorman/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,davidzchen/tensorflow,aldian/tensorflow,arborh/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,annarev/tensorflow,ppwwyyxx/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,xzturn/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,aldian/tensorflow,jhseu/tensorflow,annarev/tensorflow,DavidNorman/tensorflow,xzturn/tensorflow,cxxgtxy/tensorflow,aldian/tensorflow,gunan/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,renyi533/tensorflow,adit-chandra/tensorflow,annarev/tensorflow,adit-chandra/tensorflow,sarvex/tensorflow,DavidNorman/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,DavidNorman/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,adit-chandra/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,Intel-tensorflow/tensorflow,arborh/tensorflow,karllessard/tensorflow,jhseu/tensorflow,tensorflow/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aldian/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,arborh/tensorflow,frreiss/tensorflow-fred,renyi533/tensorflow,jhseu/tensorflow,Intel-Corporation/tensorflow,arborh/tensorflow,chemelnucfin/tensorflow,karllessard/tensorflow,adit-chandra/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,ppwwyyxx/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,aam-at/tensorflow,arborh/tensorflow,gunan/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,davidzchen/tensorflow,chemelnucfin/tensorflow,jhseu/tensorflow,arborh/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,DavidNorman/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,ppwwyyxx/tensorflow,sarvex/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,adit-chandra/tensorflow,aam-at/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,chemelnucfin/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,gautam1858/tensorflow,arborh/tensorflow,sarvex/tensorflow,aldian/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,jhseu/tensorflow,gautam1858/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_saved_model,adit-chandra/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow,chemelnucfin/tensorflow,Intel-tensorflow/tensorflow,DavidNorman/tensorflow,gunan/tensorflow,tensorflow/tensorflow,davidzchen/tensorflow,xzturn/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,ppwwyyxx/tensorflow,cxxgtxy/tensorflow,aldian/tensorflow,petewarden/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jhseu/tensorflow,gunan/tensorflow,aam-at/tensorflow,Intel-tensorflow/tensorflow,xzturn/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,davidzchen/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,jhseu/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,aam-at/tensorflow,gunan/tensorflow,aam-at/tensorflow,xzturn/tensorflow,aam-at/tensorflow,ppwwyyxx/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ppwwyyxx/tensorflow,DavidNorman/tensorflow,petewarden/tensorflow,annarev/tensorflow,arborh/tensorflow,renyi533/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred
|
7d73f09f1d699617244ec64decc02649d1662a5c
|
src/fs/server.cpp
|
src/fs/server.cpp
|
//#include "fused.h"
#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <String.h>
#include <vector>
#include "microhttpd.h"
using std::vector;
using lepcpplib::String;
const short int kPort = 8888;
ssize_t file_server_callback(void *cls, uint64_t pos, char *buf, size_t max)
{
FILE* f = (FILE*)cls;
fseek(f, pos, SEEK_SET);
return fread(buf, 1, max, f);
}
void file_server_free_callback(void* cls)
{
fclose((FILE*)cls);
}
void serve_file()
{
#if 0
struct MHD_Response *
MHD_create_response_from_callback (uint64_t size,
size_t block_size,
MHD_ContentReaderCallback crc, void *crc_cls,
MHD_ContentReaderFreeCallback crfc);
#endif
}
int route_discover(void* cls, MHD_Connection* connection,
const char* url,
const char* method, const char* version,
const char* upload_data,
size_t* upload_data_size, void** con_cls,
vector<String>& tokens)
{
MHD_Response* response;
int result;
String filename;
if (tokens.size() == 2) {
filename = "../www/html/discover.html";
}
else {
filename = "../www/html";
for (int i = 2; i < tokens.size(); ++i)
{
filename = filename + "/" + tokens[i];
}
}
FILE* fp = fopen(filename.toCharArray(), "r");
int fd = fileno(fp);
struct stat buf;
stat(filename.toCharArray(), &buf);
//response = MHD_create_response_from_buffer(output.length(),
// (void*)output.toCharArray(), MHD_RESPMEM_MUST_COPY);
response = MHD_create_response_from_fd(buf.st_size, fd);
result = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
return result;
}
int route_www(void* cls, MHD_Connection* connection,
const char* url,
const char* method, const char* version,
const char* upload_data,
size_t* upload_data_size, void** con_cls,
String& output)
{
output = "<html><body>Hello, discoverer renderer caller.</body></html>";
}
int route_api(void* cls, MHD_Connection* connection,
const char* url,
const char* method, const char* version,
const char* upload_data,
size_t* upload_data_size, void** con_cls,
String& output)
{
output = "<html><body>Hello, api caller.</body></html>";
}
int client_processor(void* cls, MHD_Connection* connection,
const char* url,
const char* method, const char* version,
const char* upload_data,
size_t* upload_data_size, void** con_cls)
{
vector<String> tokens;
String::tokenize(url, '/', tokens);
String output;
if (tokens.size() >= 2) {
if (tokens[1] == "discover") {
return route_discover(cls, connection, url, method, version,
upload_data, upload_data_size, con_cls, tokens);
}
else if (tokens[1] == "api") {
route_api(cls, connection, url, method, version,
upload_data, upload_data_size, con_cls, output);
}
else if (tokens[1] == "www") {
route_www(cls, connection, url, method, version,
upload_data, upload_data_size, con_cls, output);
}
else {
output = "<html><body>Hello, 404 found not.</body></html>";
}
}
MHD_Response* response;
int result;
FILE* fp = fopen("../www/html/discover.html", "r");
int fd = fileno(fp);
struct stat buf;
stat("../www/html/discover.html", &buf);
//response = MHD_create_response_from_buffer(output.length(),
// (void*)output.toCharArray(), MHD_RESPMEM_MUST_COPY);
response = MHD_create_response_from_fd(buf.st_size, fd);
result = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
return result;
}
int main(int argc, char* argv[])
{
MHD_Daemon* daemon;
daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, kPort, NULL, NULL,
&client_processor, NULL, MHD_OPTION_END);
if (daemon == NULL) {
return 1;
}
getchar();
MHD_stop_daemon(daemon);
return 0;
}
|
//#include "fused.h"
#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <String.h>
#include <vector>
#include "microhttpd.h"
using std::vector;
using lepcpplib::String;
const short int kPort = 8888;
const int kFileBlockSize = 32 * 1024 * 1024;
const String k404 = "<html><head><title>File not found</title></head><body>File not found</body></html>";
ssize_t file_server_callback(void *cls, uint64_t pos, char *buf, size_t max)
{
FILE* f = (FILE*)cls;
fseek(f, pos, SEEK_SET);
return fread(buf, 1, max, f);
}
void file_server_free_callback(void* cls)
{
fclose((FILE*)cls);
}
int serve_file(MHD_Connection* connection, String& filename)
{
MHD_Response* response = NULL;
struct stat filestats;
int result = stat(filename.toCharArray(), &filestats);
if (result != -1) {
FILE* fp = fopen(filename.toCharArray(), "r");
response = MHD_create_response_from_callback (filestats.st_size,
kFileBlockSize, file_server_callback, fp, file_server_free_callback);
result = MHD_queue_response(connection, MHD_HTTP_OK, response);
}
else {
response = MHD_create_response_from_buffer(k404.length(),
(void*)k404.toCharArray(), MHD_RESPMEM_PERSISTENT);
result = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
}
MHD_destroy_response(response);
return result;
}
int route_discover(void* cls, MHD_Connection* connection,
const char* url,
const char* method, const char* version,
const char* upload_data,
size_t* upload_data_size, void** con_cls,
vector<String>& tokens)
{
MHD_Response* response;
int result;
String filename;
if (tokens.size() == 2) {
filename = "../www/html/discover.html";
}
else {
filename = "../www/html";
for (int i = 2; i < tokens.size(); ++i)
{
filename = filename + "/" + tokens[i];
}
}
#if 0
FILE* fp = fopen(filename.toCharArray(), "r");
int fd = fileno(fp);
struct stat buf;
stat(filename.toCharArray(), &buf);
//response = MHD_create_response_from_buffer(output.length(),
// (void*)output.toCharArray(), MHD_RESPMEM_MUST_COPY);
response = MHD_create_response_from_fd(buf.st_size, fd);
result = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
return result;
#endif
return serve_file(connection, filename);
}
int route_www(void* cls, MHD_Connection* connection,
const char* url,
const char* method, const char* version,
const char* upload_data,
size_t* upload_data_size, void** con_cls,
String& output)
{
output = "<html><body>Hello, discoverer renderer caller.</body></html>";
}
int route_api(void* cls, MHD_Connection* connection,
const char* url,
const char* method, const char* version,
const char* upload_data,
size_t* upload_data_size, void** con_cls,
String& output)
{
output = "<html><body>Hello, api caller.</body></html>";
}
int client_processor(void* cls, MHD_Connection* connection,
const char* url,
const char* method, const char* version,
const char* upload_data,
size_t* upload_data_size, void** con_cls)
{
vector<String> tokens;
String::tokenize(url, '/', tokens);
String output;
if (tokens.size() >= 2) {
if (tokens[1] == "discover") {
return route_discover(cls, connection, url, method, version,
upload_data, upload_data_size, con_cls, tokens);
}
else if (tokens[1] == "api") {
route_api(cls, connection, url, method, version,
upload_data, upload_data_size, con_cls, output);
}
else if (tokens[1] == "www") {
route_www(cls, connection, url, method, version,
upload_data, upload_data_size, con_cls, output);
}
else {
output = "<html><body>Hello, 404 found not.</body></html>";
}
}
MHD_Response* response;
int result;
FILE* fp = fopen("../www/html/discover.html", "r");
int fd = fileno(fp);
struct stat buf;
stat("../www/html/discover.html", &buf);
//response = MHD_create_response_from_buffer(output.length(),
// (void*)output.toCharArray(), MHD_RESPMEM_MUST_COPY);
response = MHD_create_response_from_fd(buf.st_size, fd);
result = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
return result;
}
int main(int argc, char* argv[])
{
MHD_Daemon* daemon;
daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, kPort, NULL, NULL,
&client_processor, NULL, MHD_OPTION_END);
if (daemon == NULL) {
return 1;
}
getchar();
MHD_stop_daemon(daemon);
return 0;
}
|
refactor file serving.
|
refactor file serving.
|
C++
|
mit
|
praveenster/tagfs,praveenster/tagfs
|
f6ce677acec0050119590fb319fc9452ba442a51
|
IO/vtkDICOMImageReader.cxx
|
IO/vtkDICOMImageReader.cxx
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDICOMImageReader.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "DICOMParser.h"
#include "DICOMAppHelper.h"
#include "vtkDICOMImageReader.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkDirectory.h"
#include <vtkstd/vector>
#include <vtkstd/string>
vtkCxxRevisionMacro(vtkDICOMImageReader, "1.15");
vtkStandardNewMacro(vtkDICOMImageReader);
class vtkDICOMImageReaderVector : public vtkstd::vector<vtkstd::string>
{
};
vtkDICOMImageReader::vtkDICOMImageReader()
{
this->Parser = new DICOMParser();
this->AppHelper = new DICOMAppHelper();
this->DirectoryName = NULL;
this->DICOMFileNames = new vtkDICOMImageReaderVector();
this->FileName = NULL;
}
vtkDICOMImageReader::~vtkDICOMImageReader()
{
delete this->Parser;
delete this->AppHelper;
delete this->DICOMFileNames;
}
void vtkDICOMImageReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkImageReader2::PrintSelf(os, indent);
if (this->DirectoryName)
{
os << "DirectoryName : " << this->DirectoryName << "\n";
}
else
{
os << "DirectoryName : (NULL)" << "\n";
}
if (this->FileName)
{
os << "FileName : " << this->FileName << "\n";
}
else
{
os << "FileName : (NULL)" << "\n";
}
}
int vtkDICOMImageReader::CanReadFile(const char* fname)
{
bool canOpen = this->Parser->OpenFile((char*) fname);
if (canOpen == false)
{
vtkErrorMacro("DICOMParser couldn't open : " << fname);
return 0;
}
bool canRead = this->Parser->IsDICOMFile();
if (canRead == true)
{
return 1;
}
else
{
return 0;
}
}
void vtkDICOMImageReader::ExecuteInformation()
{
if (this->FileName == NULL && this->DirectoryName == NULL)
{
return;
}
if (this->FileName)
{
this->DICOMFileNames->clear();
//this->AppHelper->ClearSeriesUIDMap();
//this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
this->Parser->ClearAllDICOMTagCallbacks();
this->Parser->OpenFile(this->FileName);
// this->AppHelper->SetFileName(this->FileName);
this->AppHelper->RegisterCallbacks(this->Parser);
this->Parser->ReadHeader();
this->SetupOutputInformation(1);
}
else if (this->DirectoryName)
{
vtkDirectory* dir = vtkDirectory::New();
int opened = dir->Open(this->DirectoryName);
if (!opened)
{
vtkErrorMacro("Couldn't open " << this->DirectoryName);
dir->Delete();
return;
}
int numFiles = dir->GetNumberOfFiles();
vtkDebugMacro( << "There are " << numFiles << " files in the directory.");
this->DICOMFileNames->clear();
//this->AppHelper->ClearSeriesUIDMap();
//this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
for (int i = 0; i < numFiles; i++)
{
if (strcmp(dir->GetFile(i), ".") == 0 ||
strcmp(dir->GetFile(i), "..") == 0)
{
continue;
}
vtkstd::string temp = this->DirectoryName;
vtkstd::string temp2 = dir->GetFile(i);
vtkstd::string delim = "/";
vtkstd::string fileString = temp + delim + temp2;
int val = this->CanReadFile(fileString.c_str());
if (val == 1)
{
vtkDebugMacro( << "Adding " << fileString.c_str() << " to DICOMFileNames.");
this->DICOMFileNames->push_back(fileString);
}
else
{
vtkDebugMacro( << fileString.c_str() << " - DICOMParser CanReadFile returned : " << val);
}
}
vtkstd::vector<vtkstd::string>::iterator iter;
for (iter = this->DICOMFileNames->begin();
iter != this->DICOMFileNames->end();
iter++)
{
char* fn = (char*) (*iter).c_str();
vtkDebugMacro( << "Trying : " << fn);
bool couldOpen = this->Parser->OpenFile(fn);
if (!couldOpen)
{
dir->Delete();
return;
}
//HERE
this->Parser->ClearAllDICOMTagCallbacks();
this->AppHelper->RegisterCallbacks(this->Parser);
// this->AppHelper->SetFileName(fn);
this->Parser->ReadHeader();
vtkDebugMacro( << "File name : " << fn );
vtkDebugMacro( << "Slice number : " << this->AppHelper->GetSliceNumber());
}
vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles;
this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles);
// this->AppHelper->SortFilenamesBySlice();
// unsigned int num_files = this->AppHelper->GetNumberOfSortedFilenames();
// for (unsigned int k = 0; k < num_files; k++)
// {
// sortedFiles.push_back(std::pair<int,std::string>(k, this->AppHelper->GetFilenameForSlice(k)));
// }
//this->AppHelper->GetSliceNumberFilenamePairs(sortedFiles);
this->SetupOutputInformation(static_cast<int>(sortedFiles.size()));
//this->AppHelper->OutputSeries();
if (sortedFiles.size() > 0)
{
this->DICOMFileNames->clear();
vtkstd::vector<vtkstd::pair<float, vtkstd::string> >::iterator siter;
for (siter = sortedFiles.begin();
siter != sortedFiles.end();
siter++)
{
vtkDebugMacro(<< "Sorted filename : " << (*siter).second.c_str());
vtkDebugMacro(<< "Adding file " << (*siter).second.c_str() << " at slice : " << (*siter).first);
this->DICOMFileNames->push_back((*siter).second);
}
}
else
{
vtkErrorMacro( << "Couldn't get sorted files. Slices may be in wrong order!");
}
dir->Delete();
}
}
void vtkDICOMImageReader::ExecuteData(vtkDataObject *output)
{
vtkImageData *data = this->AllocateOutputData(output);
data->GetPointData()->GetScalars()->SetName("DICOMImage");
if (this->FileName)
{
vtkDebugMacro( << "Single file : " << this->FileName);
this->Parser->ClearAllDICOMTagCallbacks();
this->Parser->OpenFile(this->FileName);
// this->AppHelper->ClearSeriesUIDMap();
// this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
//this->AppHelper->SetFileName(this->FileName);
this->AppHelper->RegisterCallbacks(this->Parser);
this->AppHelper->RegisterPixelDataCallback(this->Parser);
this->Parser->ReadHeader();
void* imgData = NULL;
DICOMParser::VRTypes dataType;
unsigned long imageDataLength;
this->AppHelper->GetImageData(imgData, dataType, imageDataLength);
void* buffer = data->GetScalarPointer();
if (buffer == NULL)
{
vtkErrorMacro(<< "No memory allocated for image data!");
return;
}
memcpy(buffer, imgData, imageDataLength);
}
else if (this->DICOMFileNames->size() > 0)
{
vtkDebugMacro( << "Multiple files (" << static_cast<int>(this->DICOMFileNames->size()) << ")");
this->Parser->ClearAllDICOMTagCallbacks();
// this->AppHelper->ClearSeriesUIDMap();
// this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
this->AppHelper->RegisterCallbacks(this->Parser);
this->AppHelper->RegisterPixelDataCallback(this->Parser);
void* buffer = data->GetScalarPointer();
if (buffer == NULL)
{
vtkErrorMacro(<< "No memory allocated for image data!");
return;
}
vtkstd::vector<vtkstd::string>::iterator fiter;
int count = 0;
int numFiles = static_cast<int>(this->DICOMFileNames->size());
for (fiter = this->DICOMFileNames->begin();
fiter != this->DICOMFileNames->end();
fiter++)
{
count++;
vtkDebugMacro( << "File : " << (*fiter).c_str());
this->Parser->OpenFile((char*)(*fiter).c_str());
// this->AppHelper->SetFileName((char*)(*fiter).c_str());
this->Parser->ReadHeader();
void* imgData = NULL;
DICOMParser::VRTypes dataType;
unsigned long imageDataLengthInBytes;
this->AppHelper->GetImageData(imgData, dataType, imageDataLengthInBytes);
memcpy(buffer, imgData, imageDataLengthInBytes);
buffer = ((char*) buffer) + imageDataLengthInBytes;
this->UpdateProgress(float(count)/float(numFiles));
int len = static_cast<int> (strlen((char*) (*fiter).c_str()));
char* filename = new char[len+1];
strcpy(filename, (char*) (*fiter).c_str());
this->SetProgressText(filename);
}
}
else
{
vtkDebugMacro( << "Execute data -- no files!");
}
}
void vtkDICOMImageReader::SetupOutputInformation(int num_slices)
{
int width = this->AppHelper->GetWidth();
int height = this->AppHelper->GetHeight();
int bit_depth = this->AppHelper->GetBitsAllocated();
int num_comp = this->AppHelper->GetNumberOfComponents();
this->DataExtent[0] = 0;
this->DataExtent[1] = width - 1;
this->DataExtent[2] = 0;
this->DataExtent[3] = height - 1;
this->DataExtent[4] = 0;
this->DataExtent[5] = num_slices - 1;
bool isFloat = this->AppHelper->RescaledImageDataIsFloat();
bool sign = this->AppHelper->RescaledImageDataIsSigned();
if (isFloat)
{
this->SetDataScalarTypeToFloat();
}
else if (bit_depth <= 8)
{
this->SetDataScalarTypeToUnsignedChar();
}
else
{
if (sign)
{
this->SetDataScalarTypeToShort();
}
else
{
this->SetDataScalarTypeToUnsignedShort();
}
}
this->SetNumberOfScalarComponents(num_comp);
this->vtkImageReader2::ExecuteInformation();
}
void vtkDICOMImageReader::SetDirectoryName(const char* dn)
{
if (dn == NULL)
{
return;
}
int len = static_cast<int>(strlen(dn));
if (this->DirectoryName != NULL)
{
delete [] this->DirectoryName;
}
this->DirectoryName = new char[len+1];
strcpy(this->DirectoryName, dn);
if (this->FileName != NULL)
{
delete [] this->FileName;
this->FileName = NULL;
}
this->Modified();
}
float* vtkDICOMImageReader::GetPixelSpacing()
{
vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles;
this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles);
float* spacing = this->AppHelper->GetPixelSpacing();
this->DataSpacing[0] = spacing[0];
this->DataSpacing[1] = spacing[1];
if (sortedFiles.size() > 1)
{
vtkstd::pair<float, vtkstd::string> p1 = sortedFiles[0];
vtkstd::pair<float, vtkstd::string> p2 = sortedFiles[1];
this->DataSpacing[2] = fabs(p1.first - p2.first);
}
else
{
this->DataSpacing[2] = spacing[2];
}
return this->DataSpacing;
}
int vtkDICOMImageReader::GetWidth()
{
return this->AppHelper->GetWidth();
}
int vtkDICOMImageReader::GetHeight()
{
return this->AppHelper->GetHeight();
}
float* vtkDICOMImageReader::GetImagePositionPatient()
{
return this->AppHelper->GetImagePositionPatient();
}
int vtkDICOMImageReader::GetBitsAllocated()
{
return this->AppHelper->GetBitsAllocated();
}
int vtkDICOMImageReader::GetPixelRepresentation()
{
return this->AppHelper->GetPixelRepresentation();
}
int vtkDICOMImageReader::GetNumberOfComponents()
{
return this->AppHelper->GetNumberOfComponents();
}
const char* vtkDICOMImageReader::GetTransferSyntaxUID()
{
return this->AppHelper->GetTransferSyntaxUID().c_str();
}
float vtkDICOMImageReader::GetRescaleSlope()
{
return this->AppHelper->GetRescaleSlope();
}
float vtkDICOMImageReader::GetRescaleOffset()
{
return this->AppHelper->GetRescaleOffset();
}
const char* vtkDICOMImageReader::GetPatientName()
{
return this->AppHelper->GetPatientName().c_str();
}
const char* vtkDICOMImageReader::GetStudyUID()
{
return this->AppHelper->GetStudyUID().c_str();
}
float vtkDICOMImageReader::GetGantryAngle()
{
return this->AppHelper->GetGantryAngle();
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDICOMImageReader.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "DICOMParser.h"
#include "DICOMAppHelper.h"
#include "vtkDICOMImageReader.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkDirectory.h"
#include <vtkstd/vector>
#include <vtkstd/string>
vtkCxxRevisionMacro(vtkDICOMImageReader, "1.16");
vtkStandardNewMacro(vtkDICOMImageReader);
class vtkDICOMImageReaderVector : public vtkstd::vector<vtkstd::string>
{
};
vtkDICOMImageReader::vtkDICOMImageReader()
{
this->Parser = new DICOMParser();
this->AppHelper = new DICOMAppHelper();
this->DirectoryName = NULL;
this->DICOMFileNames = new vtkDICOMImageReaderVector();
}
vtkDICOMImageReader::~vtkDICOMImageReader()
{
delete this->Parser;
delete this->AppHelper;
delete this->DICOMFileNames;
if (this->DirectoryName)
{
delete [] this->DirectoryName;
}
}
void vtkDICOMImageReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkImageReader2::PrintSelf(os, indent);
if (this->DirectoryName)
{
os << "DirectoryName : " << this->DirectoryName << "\n";
}
else
{
os << "DirectoryName : (NULL)" << "\n";
}
if (this->FileName)
{
os << "FileName : " << this->FileName << "\n";
}
else
{
os << "FileName : (NULL)" << "\n";
}
}
int vtkDICOMImageReader::CanReadFile(const char* fname)
{
bool canOpen = this->Parser->OpenFile((char*) fname);
if (canOpen == false)
{
vtkErrorMacro("DICOMParser couldn't open : " << fname);
return 0;
}
bool canRead = this->Parser->IsDICOMFile();
if (canRead == true)
{
return 1;
}
else
{
return 0;
}
}
void vtkDICOMImageReader::ExecuteInformation()
{
if (this->FileName == NULL && this->DirectoryName == NULL)
{
return;
}
if (this->FileName)
{
this->DICOMFileNames->clear();
//this->AppHelper->ClearSeriesUIDMap();
//this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
this->Parser->ClearAllDICOMTagCallbacks();
this->Parser->OpenFile(this->FileName);
// this->AppHelper->SetFileName(this->FileName);
this->AppHelper->RegisterCallbacks(this->Parser);
this->Parser->ReadHeader();
this->SetupOutputInformation(1);
}
else if (this->DirectoryName)
{
vtkDirectory* dir = vtkDirectory::New();
int opened = dir->Open(this->DirectoryName);
if (!opened)
{
vtkErrorMacro("Couldn't open " << this->DirectoryName);
dir->Delete();
return;
}
int numFiles = dir->GetNumberOfFiles();
vtkDebugMacro( << "There are " << numFiles << " files in the directory.");
this->DICOMFileNames->clear();
//this->AppHelper->ClearSeriesUIDMap();
//this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
for (int i = 0; i < numFiles; i++)
{
if (strcmp(dir->GetFile(i), ".") == 0 ||
strcmp(dir->GetFile(i), "..") == 0)
{
continue;
}
vtkstd::string temp = this->DirectoryName;
vtkstd::string temp2 = dir->GetFile(i);
vtkstd::string delim = "/";
vtkstd::string fileString = temp + delim + temp2;
int val = this->CanReadFile(fileString.c_str());
if (val == 1)
{
vtkDebugMacro( << "Adding " << fileString.c_str() << " to DICOMFileNames.");
this->DICOMFileNames->push_back(fileString);
}
else
{
vtkDebugMacro( << fileString.c_str() << " - DICOMParser CanReadFile returned : " << val);
}
}
vtkstd::vector<vtkstd::string>::iterator iter;
for (iter = this->DICOMFileNames->begin();
iter != this->DICOMFileNames->end();
iter++)
{
char* fn = (char*) (*iter).c_str();
vtkDebugMacro( << "Trying : " << fn);
bool couldOpen = this->Parser->OpenFile(fn);
if (!couldOpen)
{
dir->Delete();
return;
}
//HERE
this->Parser->ClearAllDICOMTagCallbacks();
this->AppHelper->RegisterCallbacks(this->Parser);
// this->AppHelper->SetFileName(fn);
this->Parser->ReadHeader();
vtkDebugMacro( << "File name : " << fn );
vtkDebugMacro( << "Slice number : " << this->AppHelper->GetSliceNumber());
}
vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles;
this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles);
// this->AppHelper->SortFilenamesBySlice();
// unsigned int num_files = this->AppHelper->GetNumberOfSortedFilenames();
// for (unsigned int k = 0; k < num_files; k++)
// {
// sortedFiles.push_back(std::pair<int,std::string>(k, this->AppHelper->GetFilenameForSlice(k)));
// }
//this->AppHelper->GetSliceNumberFilenamePairs(sortedFiles);
this->SetupOutputInformation(static_cast<int>(sortedFiles.size()));
//this->AppHelper->OutputSeries();
if (sortedFiles.size() > 0)
{
this->DICOMFileNames->clear();
vtkstd::vector<vtkstd::pair<float, vtkstd::string> >::iterator siter;
for (siter = sortedFiles.begin();
siter != sortedFiles.end();
siter++)
{
vtkDebugMacro(<< "Sorted filename : " << (*siter).second.c_str());
vtkDebugMacro(<< "Adding file " << (*siter).second.c_str() << " at slice : " << (*siter).first);
this->DICOMFileNames->push_back((*siter).second);
}
}
else
{
vtkErrorMacro( << "Couldn't get sorted files. Slices may be in wrong order!");
}
dir->Delete();
}
}
void vtkDICOMImageReader::ExecuteData(vtkDataObject *output)
{
vtkImageData *data = this->AllocateOutputData(output);
data->GetPointData()->GetScalars()->SetName("DICOMImage");
if (this->FileName)
{
vtkDebugMacro( << "Single file : " << this->FileName);
this->Parser->ClearAllDICOMTagCallbacks();
this->Parser->OpenFile(this->FileName);
// this->AppHelper->ClearSeriesUIDMap();
// this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
//this->AppHelper->SetFileName(this->FileName);
this->AppHelper->RegisterCallbacks(this->Parser);
this->AppHelper->RegisterPixelDataCallback(this->Parser);
this->Parser->ReadHeader();
void* imgData = NULL;
DICOMParser::VRTypes dataType;
unsigned long imageDataLength;
this->AppHelper->GetImageData(imgData, dataType, imageDataLength);
void* buffer = data->GetScalarPointer();
if (buffer == NULL)
{
vtkErrorMacro(<< "No memory allocated for image data!");
return;
}
memcpy(buffer, imgData, imageDataLength);
}
else if (this->DICOMFileNames->size() > 0)
{
vtkDebugMacro( << "Multiple files (" << static_cast<int>(this->DICOMFileNames->size()) << ")");
this->Parser->ClearAllDICOMTagCallbacks();
// this->AppHelper->ClearSeriesUIDMap();
// this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
this->AppHelper->RegisterCallbacks(this->Parser);
this->AppHelper->RegisterPixelDataCallback(this->Parser);
void* buffer = data->GetScalarPointer();
if (buffer == NULL)
{
vtkErrorMacro(<< "No memory allocated for image data!");
return;
}
vtkstd::vector<vtkstd::string>::iterator fiter;
int count = 0;
int numFiles = static_cast<int>(this->DICOMFileNames->size());
for (fiter = this->DICOMFileNames->begin();
fiter != this->DICOMFileNames->end();
fiter++)
{
count++;
vtkDebugMacro( << "File : " << (*fiter).c_str());
this->Parser->OpenFile((char*)(*fiter).c_str());
// this->AppHelper->SetFileName((char*)(*fiter).c_str());
this->Parser->ReadHeader();
void* imgData = NULL;
DICOMParser::VRTypes dataType;
unsigned long imageDataLengthInBytes;
this->AppHelper->GetImageData(imgData, dataType, imageDataLengthInBytes);
memcpy(buffer, imgData, imageDataLengthInBytes);
buffer = ((char*) buffer) + imageDataLengthInBytes;
this->UpdateProgress(float(count)/float(numFiles));
int len = static_cast<int> (strlen((char*) (*fiter).c_str()));
char* filename = new char[len+1];
strcpy(filename, (char*) (*fiter).c_str());
this->SetProgressText(filename);
}
}
else
{
vtkDebugMacro( << "Execute data -- no files!");
}
}
void vtkDICOMImageReader::SetupOutputInformation(int num_slices)
{
int width = this->AppHelper->GetWidth();
int height = this->AppHelper->GetHeight();
int bit_depth = this->AppHelper->GetBitsAllocated();
int num_comp = this->AppHelper->GetNumberOfComponents();
this->DataExtent[0] = 0;
this->DataExtent[1] = width - 1;
this->DataExtent[2] = 0;
this->DataExtent[3] = height - 1;
this->DataExtent[4] = 0;
this->DataExtent[5] = num_slices - 1;
bool isFloat = this->AppHelper->RescaledImageDataIsFloat();
bool sign = this->AppHelper->RescaledImageDataIsSigned();
if (isFloat)
{
this->SetDataScalarTypeToFloat();
}
else if (bit_depth <= 8)
{
this->SetDataScalarTypeToUnsignedChar();
}
else
{
if (sign)
{
this->SetDataScalarTypeToShort();
}
else
{
this->SetDataScalarTypeToUnsignedShort();
}
}
this->SetNumberOfScalarComponents(num_comp);
this->vtkImageReader2::ExecuteInformation();
}
void vtkDICOMImageReader::SetDirectoryName(const char* dn)
{
vtkDebugMacro(<< this->GetClassName() << " (" << this <<
"): setting DirectoryName to " << (dn ? dn : "(null)") );
if ( this->DirectoryName == NULL && dn == NULL)
{
return;
}
if (this->FileName)
{
delete [] this->FileName;
this->FileName = NULL;
}
if ( this->DirectoryName && dn && (!strcmp(this->DirectoryName,dn)))
{
return;
}
if (this->DirectoryName)
{
delete [] this->DirectoryName;
}
if (dn)
{
this->DirectoryName = new char[strlen(dn)+1];
strcpy(this->DirectoryName,dn);
}
else
{
this->DirectoryName = NULL;
}
this->Modified();
}
float* vtkDICOMImageReader::GetPixelSpacing()
{
vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles;
this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles);
float* spacing = this->AppHelper->GetPixelSpacing();
this->DataSpacing[0] = spacing[0];
this->DataSpacing[1] = spacing[1];
if (sortedFiles.size() > 1)
{
vtkstd::pair<float, vtkstd::string> p1 = sortedFiles[0];
vtkstd::pair<float, vtkstd::string> p2 = sortedFiles[1];
this->DataSpacing[2] = fabs(p1.first - p2.first);
}
else
{
this->DataSpacing[2] = spacing[2];
}
return this->DataSpacing;
}
int vtkDICOMImageReader::GetWidth()
{
return this->AppHelper->GetWidth();
}
int vtkDICOMImageReader::GetHeight()
{
return this->AppHelper->GetHeight();
}
float* vtkDICOMImageReader::GetImagePositionPatient()
{
return this->AppHelper->GetImagePositionPatient();
}
int vtkDICOMImageReader::GetBitsAllocated()
{
return this->AppHelper->GetBitsAllocated();
}
int vtkDICOMImageReader::GetPixelRepresentation()
{
return this->AppHelper->GetPixelRepresentation();
}
int vtkDICOMImageReader::GetNumberOfComponents()
{
return this->AppHelper->GetNumberOfComponents();
}
const char* vtkDICOMImageReader::GetTransferSyntaxUID()
{
return this->AppHelper->GetTransferSyntaxUID().c_str();
}
float vtkDICOMImageReader::GetRescaleSlope()
{
return this->AppHelper->GetRescaleSlope();
}
float vtkDICOMImageReader::GetRescaleOffset()
{
return this->AppHelper->GetRescaleOffset();
}
const char* vtkDICOMImageReader::GetPatientName()
{
return this->AppHelper->GetPatientName().c_str();
}
const char* vtkDICOMImageReader::GetStudyUID()
{
return this->AppHelper->GetStudyUID().c_str();
}
float vtkDICOMImageReader::GetGantryAngle()
{
return this->AppHelper->GetGantryAngle();
}
|
fix a few issues
|
fix a few issues
|
C++
|
bsd-3-clause
|
demarle/VTK,mspark93/VTK,sgh/vtk,sankhesh/VTK,sankhesh/VTK,jeffbaumes/jeffbaumes-vtk,berendkleinhaneveld/VTK,keithroe/vtkoptix,sgh/vtk,cjh1/VTK,hendradarwin/VTK,collects/VTK,mspark93/VTK,demarle/VTK,hendradarwin/VTK,sgh/vtk,candy7393/VTK,gram526/VTK,berendkleinhaneveld/VTK,candy7393/VTK,Wuteyan/VTK,keithroe/vtkoptix,keithroe/vtkoptix,SimVascular/VTK,jmerkow/VTK,biddisco/VTK,jmerkow/VTK,spthaolt/VTK,daviddoria/PointGraphsPhase1,sumedhasingla/VTK,aashish24/VTK-old,johnkit/vtk-dev,sumedhasingla/VTK,mspark93/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,jeffbaumes/jeffbaumes-vtk,candy7393/VTK,ashray/VTK-EVM,msmolens/VTK,Wuteyan/VTK,collects/VTK,demarle/VTK,sgh/vtk,berendkleinhaneveld/VTK,cjh1/VTK,mspark93/VTK,SimVascular/VTK,naucoin/VTKSlicerWidgets,aashish24/VTK-old,collects/VTK,jmerkow/VTK,mspark93/VTK,naucoin/VTKSlicerWidgets,SimVascular/VTK,demarle/VTK,jeffbaumes/jeffbaumes-vtk,msmolens/VTK,daviddoria/PointGraphsPhase1,mspark93/VTK,daviddoria/PointGraphsPhase1,msmolens/VTK,Wuteyan/VTK,cjh1/VTK,naucoin/VTKSlicerWidgets,candy7393/VTK,demarle/VTK,arnaudgelas/VTK,sankhesh/VTK,candy7393/VTK,aashish24/VTK-old,keithroe/vtkoptix,ashray/VTK-EVM,naucoin/VTKSlicerWidgets,daviddoria/PointGraphsPhase1,jeffbaumes/jeffbaumes-vtk,ashray/VTK-EVM,demarle/VTK,spthaolt/VTK,johnkit/vtk-dev,sankhesh/VTK,aashish24/VTK-old,ashray/VTK-EVM,biddisco/VTK,cjh1/VTK,berendkleinhaneveld/VTK,gram526/VTK,gram526/VTK,biddisco/VTK,daviddoria/PointGraphsPhase1,SimVascular/VTK,Wuteyan/VTK,mspark93/VTK,demarle/VTK,aashish24/VTK-old,Wuteyan/VTK,johnkit/vtk-dev,johnkit/vtk-dev,spthaolt/VTK,sankhesh/VTK,ashray/VTK-EVM,arnaudgelas/VTK,candy7393/VTK,spthaolt/VTK,candy7393/VTK,ashray/VTK-EVM,johnkit/vtk-dev,msmolens/VTK,sumedhasingla/VTK,hendradarwin/VTK,jmerkow/VTK,msmolens/VTK,gram526/VTK,arnaudgelas/VTK,hendradarwin/VTK,biddisco/VTK,biddisco/VTK,daviddoria/PointGraphsPhase1,hendradarwin/VTK,jeffbaumes/jeffbaumes-vtk,msmolens/VTK,collects/VTK,ashray/VTK-EVM,sumedhasingla/VTK,msmolens/VTK,cjh1/VTK,johnkit/vtk-dev,SimVascular/VTK,sankhesh/VTK,gram526/VTK,SimVascular/VTK,hendradarwin/VTK,keithroe/vtkoptix,berendkleinhaneveld/VTK,sumedhasingla/VTK,collects/VTK,sumedhasingla/VTK,candy7393/VTK,SimVascular/VTK,gram526/VTK,naucoin/VTKSlicerWidgets,sumedhasingla/VTK,ashray/VTK-EVM,gram526/VTK,jeffbaumes/jeffbaumes-vtk,biddisco/VTK,Wuteyan/VTK,berendkleinhaneveld/VTK,demarle/VTK,cjh1/VTK,sankhesh/VTK,jmerkow/VTK,arnaudgelas/VTK,keithroe/vtkoptix,msmolens/VTK,naucoin/VTKSlicerWidgets,keithroe/vtkoptix,sgh/vtk,aashish24/VTK-old,mspark93/VTK,hendradarwin/VTK,spthaolt/VTK,spthaolt/VTK,keithroe/vtkoptix,sgh/vtk,arnaudgelas/VTK,collects/VTK,sumedhasingla/VTK,jmerkow/VTK,Wuteyan/VTK,spthaolt/VTK,biddisco/VTK,jmerkow/VTK,gram526/VTK,arnaudgelas/VTK,SimVascular/VTK,sankhesh/VTK,jmerkow/VTK
|
cc21fc73adac42c6f96fb4de1c584e1b6cf80587
|
benchmarks/halide/edge_tiramisu.cpp
|
benchmarks/halide/edge_tiramisu.cpp
|
#include <tiramisu/tiramisu.h>
#define NN 8192
#define MM 8192
using namespace tiramisu;
int main(int argc, char* argv[])
{
tiramisu::init("edge_tiramisu");
var i("i", 0, NN-2), j("j", 0, MM-2), c("c", 0, 3);
input Img("Img", {c, j, i}, p_uint8);
// Layer I
/* Ring blur filter. */
computation R("R", {c, j, i}, (Img(c, j, i) + Img(c, j+1, i) + Img(c, j+2, i)+
Img(c, j, i+1) + Img(c, j+2, i+1)+
Img(c, j, i+2) + Img(c, j+1, i+2) + Img(c, j+2, i+2))/((uint8_t) 8));
/* Robert's edge detection filter. */
computation Out("Out", {c, j, i}, (R(c, j+1, i+1)-R(c, j, i+2)) + (R(c, j+1, i+2)-R(c, j, i+1)));
// Layer II
Out.after(R, computation::root);
// R.tile(i,j, 64, 64, i1, j1, i2, j2)
// R.vectorize(j2, 64);
// Out.split(i, 64);
// Layer III
buffer b_Img("Img", {NN, MM, 3}, p_uint8, a_input);
buffer b_R("R", {NN, MM, 3}, p_uint8, a_output);
Img.store_in(&b_Img);
R.store_in(&b_R);
Out.store_in(&b_Img);
tiramisu::codegen({&b_Img, &b_R}, "build/generated_fct_edge.o");
return 0;
}
|
#include <tiramisu/tiramisu.h>
#define NN 8192
#define MM 8192
using namespace tiramisu;
int main(int argc, char* argv[])
{
tiramisu::init("edge_tiramisu");
var i("i", 0, NN-2), j("j", 0, MM-2), c("c", 0, 3), i1("i1"), j1("j1"), i2("i2"), j2("j2");
input Img("Img", {c, j, i}, p_uint8);
// Layer I
/* Ring blur filter. */
computation R("R", {i, j, c}, (Img(i, j, c) + Img(i, j+1, c) + Img(i, j+2, c)+
Img(i+1, j, c) + Img(i+1, j+2, c)+
Img(i+2, j, c) + Img(i+2, j+1, c) + Img(i+2, j+2, c))/((uint8_t) 8));
/* Robert's edge detection filter. */
computation Out("Out", {i, j, c}, (R(i+1, j+1, c)-R(i+2, j, c)) + (R(i+2, j+1, c)-R(i+1, j, c)));
// Layer II
Out.after(R, computation::root);
R.tile(i, j, 64, 64, i1, j1, i2, j2);
R.tag_parallel_level(i1);
Out.tag_parallel_level(i);
// R.vectorize(j2, 64);
// Out.split(i, 64);
// Layer III
buffer b_Img("Img", {NN, MM, 3}, p_uint8, a_input);
buffer b_R("R", {NN, MM, 3}, p_uint8, a_output);
Img.store_in(&b_Img);
R.store_in(&b_R);
Out.store_in(&b_Img);
tiramisu::codegen({&b_Img, &b_R}, "build/generated_fct_edge.o");
return 0;
}
|
Fix edge Tiramisu
|
Fix edge Tiramisu
|
C++
|
mit
|
rbaghdadi/ISIR,rbaghdadi/tiramisu,rbaghdadi/tiramisu,rbaghdadi/tiramisu,rbaghdadi/COLi,rbaghdadi/COLi,rbaghdadi/tiramisu,rbaghdadi/ISIR
|
61623b1799bef6ebcc9052697d14760aff048ec2
|
source/core/mining-manager/query-correction-submanager/QueryCorrectionSubmanager.cpp
|
source/core/mining-manager/query-correction-submanager/QueryCorrectionSubmanager.cpp
|
/**@file QueryCorrectionSubmanager.cpp
* @brief source file of Query Correction
* @author Jinglei Zhao&Jinli Liu
* @date 2009-08-21
* @details
* - Log
* - 2009.09.26 add new candidate generation
* - 2009.10.08 add new error model for english
* - 2009.11.27 add isEnglishWord() and isKoreanWord() to check if one word is mixure
* -2010.03.05 add log manager periodical worker.
*/
#include "QueryCorrectionSubmanager.h"
#include <common/SFLogger.h>
#include <util/ustring/ustr_tool.h>
#include <boost/algorithm/string.hpp>
using namespace izenelib::util::ustring_tool;
namespace sf1r
{
std::string QueryCorrectionSubmanager::system_resource_path_;
std::string QueryCorrectionSubmanager::system_working_path_;
boost::shared_ptr<EkQueryCorrection> QueryCorrectionSubmanager::ekmgr_;
boost::unordered_map<std::string, izenelib::util::UString> QueryCorrectionSubmanager::global_inject_data_;
QueryCorrectionSubmanager::QueryCorrectionSubmanager(const string& queryDataPath, bool enableEK, bool enableChn, int ed)
: queryDataPath_(queryDataPath)
, enableEK_(enableEK), enableChn_(enableChn)
, ed_(ed)
, activate_(false)
, default_inject_data_(queryDataPath_.empty() ? global_inject_data_ : collection_inject_data_)
, has_new_inject_(false)
{
static bool FirstRun = true;
if (FirstRun)
{
FirstRun = false;
idmlib::qc::CnQueryCorrection::res_dir_ = system_resource_path_ + "/speller-support/cn";
EkQueryCorrection::path_ = system_resource_path_ + "/speller-support";
EkQueryCorrection::dictEN_ = system_resource_path_ + "/speller-support/dictionary_english";
EkQueryCorrection::dictKR_ = system_resource_path_ + "/speller-support/dictionary_korean";
}
initialize();
}
QueryCorrectionSubmanager& QueryCorrectionSubmanager::getInstance()
{
static QueryCorrectionSubmanager qcManager("", true, true);
return qcManager;
}
//Initialize some member variables
bool QueryCorrectionSubmanager::initialize()
{
std::cout << "Start Speller construction!" << std::endl;
activate_ = true;
if (enableChn_)
{
cmgr_.reset(new idmlib::qc::CnQueryCorrection());
if (!cmgr_->Load())
{
std::cerr << "Failed loading resources for Chinese query correction" << std::endl;
activate_ = false;
return false;
}
}
{
static bool FirstRun = true;
if (FirstRun && enableEK_)
{
FirstRun = false;
ekmgr_.reset(new EkQueryCorrection(ed_));
if (!ekmgr_->initialize())
{
std::cerr << "Failed loading resources for English and Korean query correction" << std::endl;
activate_ = false;
return false;
}
ekmgr_->warmUp();
}
}
//load global inject
{
static bool FirstRun = true;
if (FirstRun)
{
FirstRun = false;
std::string inject_file = system_working_path_ + "/correction_inject.txt";
std::vector<izenelib::util::UString> str_list;
std::ifstream ifs(inject_file.c_str());
std::string line;
while (getline(ifs, line))
{
boost::algorithm::trim(line);
if (line.length() == 0)
{
//do with str_list;
if (str_list.size() >= 1)
{
std::string str_query;
str_list[0].convertString(str_query, izenelib::util::UString::UTF_8);
izenelib::util::UString result;
if (str_list.size() >= 2)
{
result = str_list[1];
}
global_inject_data_.insert(std::make_pair(str_query, result));
}
str_list.resize(0);
continue;
}
str_list.push_back(izenelib::util::UString(line, izenelib::util::UString::UTF_8));
}
ifs.close();
}
}
//load collection-specific inject
if (!queryDataPath_.empty())
{
std::string inject_file = queryDataPath_ + "/correction_inject.txt";
std::vector<izenelib::util::UString> str_list;
std::ifstream ifs(inject_file.c_str());
std::string line;
while (getline(ifs, line))
{
boost::algorithm::trim(line);
if (line.length() == 0)
{
//do with str_list;
if (str_list.size() >= 1)
{
std::string str_query;
str_list[0].convertString(str_query, izenelib::util::UString::UTF_8);
izenelib::util::UString result;
if (str_list.size() >= 2)
{
result = str_list[1];
}
collection_inject_data_.insert(std::make_pair(str_query, result));
}
str_list.resize(0);
continue;
}
str_list.push_back(izenelib::util::UString(line, izenelib::util::UString::UTF_8));
}
ifs.close();
}
std::cout << "End Speller construction!" << std::endl;
return true;
}
QueryCorrectionSubmanager::~QueryCorrectionSubmanager()
{
DLOG(INFO) << "... Query Correction module is destroyed" << std::endl;
}
bool QueryCorrectionSubmanager::getRefinedToken_(const izenelib::util::UString& token, izenelib::util::UString& result)
{
if (enableChn_)
{
std::vector<izenelib::util::UString> vec_result;
if (cmgr_->GetResult(token, vec_result))
{
if (vec_result.size() > 0)
{
result = vec_result[0];
return true;
}
}
}
if (enableEK_)
{
if (ekmgr_->getRefinedQuery(token, result))
{
if (result.length() > 0)
{
return true;
}
}
}
return false;
}
//The public interface, when user input wrong query, given the correct refined query.
bool QueryCorrectionSubmanager::getRefinedQuery(const UString& queryUString, UString& refinedQueryUString)
{
if (queryUString.empty() || !activate_)
{
return false;
}
if (!enableEK_ && !enableChn_)
{
return false;
}
std::string str_query;
queryUString.convertString(str_query, izenelib::util::UString::UTF_8);
boost::algorithm::to_lower(str_query);
boost::unordered_map<std::string, izenelib::util::UString>::const_iterator it = collection_inject_data_.find(str_query);
if (it != collection_inject_data_.end())
{
refinedQueryUString = it->second;
return true;
}
it = global_inject_data_.find(str_query);
if (it != global_inject_data_.end())
{
refinedQueryUString = it->second;
return true;
}
CREATE_SCOPED_PROFILER(getRealRefinedQuery, "QueryCorrectionSubmanager",
"QueryCorrectionSubmanager :: getRealRefinedQuery");
typedef tokenizer<char_separator<char> > tokenizers;
char_separator<char> sep(QueryManager::separatorString.c_str());
std::string queryStr;
queryUString.convertString(queryStr, izenelib::util::UString::UTF_8);
tokenizers stringTokenizer(queryStr, sep);
// Tokenizing and apply query correction.
bool bRefined = false;
bool first = true;
for (tokenizers::const_iterator iter = stringTokenizer.begin();
iter != stringTokenizer.end(); ++iter)
{
if (!first)
{
refinedQueryUString.push_back(' ');
}
izenelib::util::UString token(*iter, izenelib::util::UString::UTF_8);
izenelib::util::UString refined_token;
if (getRefinedToken_(token, refined_token) )
{
refinedQueryUString += refined_token;
bRefined = true;
}
else
{
refinedQueryUString += token;
}
first = false;
}
if (bRefined)
{
return true;
}
else
{
refinedQueryUString.clear();
return false;
}
}
bool QueryCorrectionSubmanager::getPinyin(
const izenelib::util::UString& hanzi,
std::vector<izenelib::util::UString>& pinyin)
{
std::vector<std::string> result_list;
cmgr_->GetPinyin(hanzi, result_list);
for (uint32_t i=0;i<result_list.size();i++)
{
boost::algorithm::replace_all(result_list[i], ",", "");
pinyin.push_back(izenelib::util::UString(result_list[i], izenelib::util::UString::UTF_8));
}
return pinyin.size() > 0;
}
void QueryCorrectionSubmanager::updateCogramAndDict(const QueryLogListType& recentQueryList)
{
DLOG(INFO) << "updateCogramAndDict..." << endl;
cmgr_->Update(recentQueryList);
}
void QueryCorrectionSubmanager::Inject(const izenelib::util::UString& query, const izenelib::util::UString& result)
{
std::string str_query;
query.convertString(str_query, izenelib::util::UString::UTF_8);
std::string str_result;
result.convertString(str_result, izenelib::util::UString::UTF_8);
boost::algorithm::trim(str_query);
if(str_query.empty()) return;
boost::algorithm::to_lower(str_query);
std::cout << "Inject query correction : " << str_query << std::endl;
if (str_result == "__delete__")
{
default_inject_data_.erase(str_query);
}
else
{
default_inject_data_[str_query] = result;
}
has_new_inject_ = true;
}
void QueryCorrectionSubmanager::FinishInject()
{
if (!has_new_inject_) return;
std::string inject_file = (queryDataPath_.empty() ? system_working_path_ : queryDataPath_) + "/correction_inject.txt";
if (boost::filesystem::exists(inject_file))
{
boost::filesystem::remove_all(inject_file);
}
std::ofstream ofs(inject_file.c_str());
for (boost::unordered_map<std::string, izenelib::util::UString>::const_iterator it = default_inject_data_.begin();
it!= default_inject_data_.end(); ++it)
{
std::string result;
it->second.convertString(result, izenelib::util::UString::UTF_8);
ofs << it->first << std::endl;
ofs << result << std::endl;
ofs << std::endl;
}
ofs.close();
has_new_inject_ = false;
std::cout << "Finish inject query correction." << std::endl;
}
}/*namespace sf1r*/
|
/**@file QueryCorrectionSubmanager.cpp
* @brief source file of Query Correction
* @author Jinglei Zhao&Jinli Liu
* @date 2009-08-21
* @details
* - Log
* - 2009.09.26 add new candidate generation
* - 2009.10.08 add new error model for english
* - 2009.11.27 add isEnglishWord() and isKoreanWord() to check if one word is mixure
* -2010.03.05 add log manager periodical worker.
*/
#include "QueryCorrectionSubmanager.h"
#include <common/SFLogger.h>
#include <util/ustring/ustr_tool.h>
#include <boost/algorithm/string.hpp>
using namespace izenelib::util::ustring_tool;
namespace sf1r
{
std::string QueryCorrectionSubmanager::system_resource_path_;
std::string QueryCorrectionSubmanager::system_working_path_;
boost::shared_ptr<EkQueryCorrection> QueryCorrectionSubmanager::ekmgr_;
boost::unordered_map<std::string, izenelib::util::UString> QueryCorrectionSubmanager::global_inject_data_;
QueryCorrectionSubmanager::QueryCorrectionSubmanager(const string& queryDataPath, bool enableEK, bool enableChn, int ed)
: queryDataPath_(queryDataPath)
, enableEK_(enableEK), enableChn_(enableChn)
, ed_(ed)
, activate_(false)
, default_inject_data_(queryDataPath_.empty() ? global_inject_data_ : collection_inject_data_)
, has_new_inject_(false)
{
static bool FirstRun = true;
if (FirstRun)
{
FirstRun = false;
idmlib::qc::CnQueryCorrection::res_dir_ = system_resource_path_ + "/speller-support/cn";
EkQueryCorrection::path_ = system_resource_path_ + "/speller-support";
EkQueryCorrection::dictEN_ = system_resource_path_ + "/speller-support/dictionary_english";
EkQueryCorrection::dictKR_ = system_resource_path_ + "/speller-support/dictionary_korean";
}
initialize();
}
QueryCorrectionSubmanager& QueryCorrectionSubmanager::getInstance()
{
static QueryCorrectionSubmanager qcManager("", true, true);
return qcManager;
}
//Initialize some member variables
bool QueryCorrectionSubmanager::initialize()
{
std::cout << "Start Speller construction!" << std::endl;
activate_ = true;
if (enableChn_)
{
cmgr_.reset(new idmlib::qc::CnQueryCorrection());
if (!cmgr_->Load())
{
std::cerr << "Failed loading resources for Chinese query correction" << std::endl;
activate_ = false;
return false;
}
}
{
static bool FirstRun = true;
if (FirstRun && enableEK_)
{
FirstRun = false;
ekmgr_.reset(new EkQueryCorrection(ed_));
if (!ekmgr_->initialize())
{
std::cerr << "Failed loading resources for English and Korean query correction" << std::endl;
activate_ = false;
return false;
}
ekmgr_->warmUp();
}
}
//load global inject
{
static bool FirstRun = true;
if (FirstRun)
{
FirstRun = false;
std::string inject_file = system_working_path_ + "/query-correction/correction_inject.txt";
std::vector<izenelib::util::UString> str_list;
std::ifstream ifs(inject_file.c_str());
std::string line;
while (getline(ifs, line))
{
boost::algorithm::trim(line);
if (line.length() == 0)
{
//do with str_list;
if (str_list.size() >= 1)
{
std::string str_query;
str_list[0].convertString(str_query, izenelib::util::UString::UTF_8);
izenelib::util::UString result;
if (str_list.size() >= 2)
{
result = str_list[1];
}
global_inject_data_.insert(std::make_pair(str_query, result));
}
str_list.resize(0);
continue;
}
str_list.push_back(izenelib::util::UString(line, izenelib::util::UString::UTF_8));
}
ifs.close();
}
}
//load collection-specific inject
if (!queryDataPath_.empty())
{
std::string inject_file = queryDataPath_ + "/query-corrction/correction_inject.txt";
std::vector<izenelib::util::UString> str_list;
std::ifstream ifs(inject_file.c_str());
std::string line;
while (getline(ifs, line))
{
boost::algorithm::trim(line);
if (line.length() == 0)
{
//do with str_list;
if (str_list.size() >= 1)
{
std::string str_query;
str_list[0].convertString(str_query, izenelib::util::UString::UTF_8);
izenelib::util::UString result;
if (str_list.size() >= 2)
{
result = str_list[1];
}
collection_inject_data_.insert(std::make_pair(str_query, result));
}
str_list.resize(0);
continue;
}
str_list.push_back(izenelib::util::UString(line, izenelib::util::UString::UTF_8));
}
ifs.close();
}
std::cout << "End Speller construction!" << std::endl;
return true;
}
QueryCorrectionSubmanager::~QueryCorrectionSubmanager()
{
DLOG(INFO) << "... Query Correction module is destroyed" << std::endl;
}
bool QueryCorrectionSubmanager::getRefinedToken_(const izenelib::util::UString& token, izenelib::util::UString& result)
{
if (enableChn_)
{
std::vector<izenelib::util::UString> vec_result;
if (cmgr_->GetResult(token, vec_result))
{
if (vec_result.size() > 0)
{
result = vec_result[0];
return true;
}
}
}
if (enableEK_)
{
if (ekmgr_->getRefinedQuery(token, result))
{
if (result.length() > 0)
{
return true;
}
}
}
return false;
}
//The public interface, when user input wrong query, given the correct refined query.
bool QueryCorrectionSubmanager::getRefinedQuery(const UString& queryUString, UString& refinedQueryUString)
{
if (queryUString.empty() || !activate_)
{
return false;
}
if (!enableEK_ && !enableChn_)
{
return false;
}
std::string str_query;
queryUString.convertString(str_query, izenelib::util::UString::UTF_8);
boost::algorithm::to_lower(str_query);
boost::unordered_map<std::string, izenelib::util::UString>::const_iterator it = collection_inject_data_.find(str_query);
if (it != collection_inject_data_.end())
{
refinedQueryUString = it->second;
return true;
}
it = global_inject_data_.find(str_query);
if (it != global_inject_data_.end())
{
refinedQueryUString = it->second;
return true;
}
CREATE_SCOPED_PROFILER(getRealRefinedQuery, "QueryCorrectionSubmanager",
"QueryCorrectionSubmanager :: getRealRefinedQuery");
typedef tokenizer<char_separator<char> > tokenizers;
char_separator<char> sep(QueryManager::separatorString.c_str());
std::string queryStr;
queryUString.convertString(queryStr, izenelib::util::UString::UTF_8);
tokenizers stringTokenizer(queryStr, sep);
// Tokenizing and apply query correction.
bool bRefined = false;
bool first = true;
for (tokenizers::const_iterator iter = stringTokenizer.begin();
iter != stringTokenizer.end(); ++iter)
{
if (!first)
{
refinedQueryUString.push_back(' ');
}
izenelib::util::UString token(*iter, izenelib::util::UString::UTF_8);
izenelib::util::UString refined_token;
if (getRefinedToken_(token, refined_token) )
{
refinedQueryUString += refined_token;
bRefined = true;
}
else
{
refinedQueryUString += token;
}
first = false;
}
if (bRefined)
{
return true;
}
else
{
refinedQueryUString.clear();
return false;
}
}
bool QueryCorrectionSubmanager::getPinyin(
const izenelib::util::UString& hanzi,
std::vector<izenelib::util::UString>& pinyin)
{
std::vector<std::string> result_list;
cmgr_->GetPinyin(hanzi, result_list);
for (uint32_t i=0;i<result_list.size();i++)
{
boost::algorithm::replace_all(result_list[i], ",", "");
pinyin.push_back(izenelib::util::UString(result_list[i], izenelib::util::UString::UTF_8));
}
return pinyin.size() > 0;
}
void QueryCorrectionSubmanager::updateCogramAndDict(const QueryLogListType& recentQueryList)
{
DLOG(INFO) << "updateCogramAndDict..." << endl;
cmgr_->Update(recentQueryList);
}
void QueryCorrectionSubmanager::Inject(const izenelib::util::UString& query, const izenelib::util::UString& result)
{
std::string str_query;
query.convertString(str_query, izenelib::util::UString::UTF_8);
std::string str_result;
result.convertString(str_result, izenelib::util::UString::UTF_8);
boost::algorithm::trim(str_query);
if(str_query.empty()) return;
boost::algorithm::to_lower(str_query);
if (str_result == "__delete__")
{
std::cout << "Delete injected keyword for query correction: " << str_query << std::endl;
default_inject_data_.erase(str_query);
}
else
{
std::cout << "Inject keyword for query correction: " << str_query << std::endl;
default_inject_data_[str_query] = result;
}
has_new_inject_ = true;
}
void QueryCorrectionSubmanager::FinishInject()
{
if (!has_new_inject_)
return;
std::string dir = (queryDataPath_.empty() ? system_working_path_ : queryDataPath_) + "/query-correction";
std::string inject_file = dir + "/correction_inject.txt";
if (boost::filesystem::exists(dir))
{
if (!boost::filesystem::is_directory(dir))
{
boost::filesystem::remove_all(dir);
boost::filesystem::create_directories(dir);
}
if (boost::filesystem::exists(inject_file))
boost::filesystem::remove_all(inject_file);
}
else
boost::filesystem::create_directories(dir);
std::ofstream ofs(inject_file.c_str());
for (boost::unordered_map<std::string, izenelib::util::UString>::const_iterator it = default_inject_data_.begin();
it!= default_inject_data_.end(); ++it)
{
std::string result;
it->second.convertString(result, izenelib::util::UString::UTF_8);
ofs << it->first << std::endl;
ofs << result << std::endl;
ofs << std::endl;
}
ofs.close();
has_new_inject_ = false;
std::cout << "Finish inject query correction." << std::endl;
}
}/*namespace sf1r*/
|
fix the file path for query-correction injection
|
fix the file path for query-correction injection
|
C++
|
apache-2.0
|
pombredanne/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite,pombredanne/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite
|
a4aca9e1f1da96c195c1ec0ab143554c3aeedd77
|
src/js_object.cpp
|
src/js_object.cpp
|
// Copyright (c) 2012 Plenluno All rights reserved.
#include "libj/js_object.h"
namespace libj {
class JsObjectImpl : public JsObject {
private:
static String::CPtr STR_OBJECT;
public:
static Ptr create() {
Ptr p(new JsObjectImpl());
return p;
}
void clear() {
map_->clear();
}
Boolean containsKey(const Value& key) const {
return map_->containsKey(String::valueOf(key));
}
Boolean containsValue(const Value& val) const {
return map_->containsValue(val);
}
Value get(const Value& key) const {
return map_->get(String::valueOf(key));
}
Set::CPtr keySet() const {
return map_->keySet();
}
Value put(const Value& key, const Value& val) {
return map_->put(String::valueOf(key), val);
}
Value remove(const Value& key) {
return map_->remove(String::valueOf(key));
}
Size size() const {
return map_->size();
}
String::CPtr toString() const {
const String::CPtr strObject = String::create("[object Object]");
return strObject;
}
private:
Map::Ptr map_;
JsObjectImpl() : map_(Map::create()) {}
};
JsObject::Ptr JsObject::create() {
return JsObjectImpl::create();
}
} // namespace libj
|
// Copyright (c) 2012 Plenluno All rights reserved.
#include "libj/js_object.h"
namespace libj {
class JsObjectImpl : public JsObject {
public:
static Ptr create() {
Ptr p(new JsObjectImpl());
return p;
}
void clear() {
map_->clear();
}
Boolean containsKey(const Value& key) const {
return map_->containsKey(String::valueOf(key));
}
Boolean containsValue(const Value& val) const {
return map_->containsValue(val);
}
Value get(const Value& key) const {
return map_->get(String::valueOf(key));
}
Set::CPtr keySet() const {
return map_->keySet();
}
Value put(const Value& key, const Value& val) {
return map_->put(String::valueOf(key), val);
}
Value remove(const Value& key) {
return map_->remove(String::valueOf(key));
}
Size size() const {
return map_->size();
}
String::CPtr toString() const {
const String::CPtr strObject = String::create("[object Object]");
return strObject;
}
private:
Map::Ptr map_;
JsObjectImpl() : map_(Map::create()) {}
};
JsObject::Ptr JsObject::create() {
return JsObjectImpl::create();
}
} // namespace libj
|
remove unused variable
|
remove unused variable
|
C++
|
bsd-2-clause
|
plenluno/libj,tempbottle/libj,tempbottle/libj,plenluno/libj
|
df210d138584fadbf903404c2ba36723041f4d4c
|
src/lda/model.cpp
|
src/lda/model.cpp
|
#include <microscopes/lda/model.hpp>
namespace microscopes {
namespace lda {
namespace detail {
// state(const std::vector<std::shared_ptr<models::hypers>> &hypers,
// const microscopes::lda::detail::GroupManager<group_type> &groups)
// : hypers_(hypers), groups_(groups)
// {
// }
}
}
}
|
#include <microscopes/lda/model.hpp>
namespace microscopes {
namespace lda {
}
}
|
Remove useless namespace
|
Remove useless namespace
|
C++
|
bsd-3-clause
|
datamicroscopes/lda,datamicroscopes/lda,datamicroscopes/lda
|
c493546c32f8969b4ba1f508347f4759723a1f84
|
include/boost/test/test_tools.hpp
|
include/boost/test/test_tools.hpp
|
// (C) Copyright Gennadiy Rozental 2001-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
/// @file
/// @brief test tools compatibility header
///
/// This file is used to select the test tools implementation and includes all the necessary headers
// ***************************************************************************
#ifndef BOOST_TEST_TOOLS_HPP_111812GER
#define BOOST_TEST_TOOLS_HPP_111812GER
#include <boost/preprocessor/config/config.hpp>
// Boost.Test
//#define BOOST_TEST_NO_OLD_TOOLS
#if !BOOST_PP_VARIADICS
# define BOOST_TEST_NO_NEW_TOOLS
#endif
// #define BOOST_TEST_TOOLS_UNDER_DEBUGGER
// #define BOOST_TEST_TOOLS_DEBUGGABLE
#include <boost/test/tools/context.hpp>
#ifndef BOOST_TEST_NO_OLD_TOOLS
# include <boost/test/tools/old/interface.hpp>
# include <boost/test/tools/old/impl.hpp>
# include <boost/test/tools/detail/print_helper.hpp>
#endif
#ifndef BOOST_TEST_NO_NEW_TOOLS
# include <boost/test/tools/interface.hpp>
# include <boost/test/tools/assertion.hpp>
# include <boost/test/tools/detail/fwd.hpp>
# include <boost/test/tools/detail/print_helper.hpp>
# include <boost/test/tools/detail/it_pair.hpp>
# include <boost/test/tools/detail/bitwise_manip.hpp>
# include <boost/test/tools/detail/tolerance_manip.hpp>
#endif
#if !BOOST_PP_VARIADICS || ((__cplusplus >= 201103L) && BOOST_NO_CXX11_VARIADIC_MACROS)
#define BOOST_TEST_NO_VARIADIC
#endif
#endif // BOOST_TEST_TOOLS_HPP_111812GER
|
// (C) Copyright Gennadiy Rozental 2001-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
/// @file
/// @brief test tools compatibility header
///
/// This file is used to select the test tools implementation and includes all the necessary headers
// ***************************************************************************
#ifndef BOOST_TEST_TOOLS_HPP_111812GER
#define BOOST_TEST_TOOLS_HPP_111812GER
#include <boost/preprocessor/config/config.hpp>
// Boost.Test
//#define BOOST_TEST_NO_OLD_TOOLS
#if !BOOST_PP_VARIADICS
# define BOOST_TEST_NO_NEW_TOOLS
#endif
// #define BOOST_TEST_TOOLS_UNDER_DEBUGGER
// #define BOOST_TEST_TOOLS_DEBUGGABLE
#include <boost/test/tools/context.hpp>
#ifndef BOOST_TEST_NO_OLD_TOOLS
# include <boost/test/tools/old/interface.hpp>
# include <boost/test/tools/old/impl.hpp>
# include <boost/test/tools/detail/print_helper.hpp>
#endif
#ifndef BOOST_TEST_NO_NEW_TOOLS
# include <boost/test/tools/interface.hpp>
# include <boost/test/tools/assertion.hpp>
# include <boost/test/tools/detail/fwd.hpp>
# include <boost/test/tools/detail/print_helper.hpp>
# include <boost/test/tools/detail/it_pair.hpp>
# include <boost/test/tools/detail/bitwise_manip.hpp>
# include <boost/test/tools/detail/tolerance_manip.hpp>
#endif
#if !BOOST_PP_VARIADICS || ((__cplusplus >= 201103L) && defined(BOOST_NO_CXX11_VARIADIC_MACROS))
#define BOOST_TEST_NO_VARIADIC
#endif
#endif // BOOST_TEST_TOOLS_HPP_111812GER
|
Fix feature test of BOOST_NO_CXX11_VARIADIC_MACROS
|
Fix feature test of BOOST_NO_CXX11_VARIADIC_MACROS
Change b41a935 introduced regression failures due to preprocessor errors with respect to the && operator, leading to the following error:
../boost/test/test_tools.hpp:50:87: error: operator '&&' has no right operand
#if !BOOST_PP_VARIADICS || ((__cplusplus >= 201103L) && BOOST_NO_CXX11_VARIADIC_MACROS)
|
C++
|
mit
|
nihildeb/hme,nihildeb/hme,nihildeb/hme,nihildeb/hme,nihildeb/hme,nihildeb/hme
|
158e411a9e76def48a3d2f63ccde38a51457a983
|
include/mettle/matchers/death.hpp
|
include/mettle/matchers/death.hpp
|
#ifndef INC_METTLE_MATCHERS_DEATH_HPP
#define INC_METTLE_MATCHERS_DEATH_HPP
#include "core.hpp"
#include "result.hpp"
#include <sys/wait.h>
#include <unistd.h>
#include <system_error>
namespace mettle {
namespace detail {
template<typename T, typename U>
int get_status(T &&func, U &&terminate) {
pid_t pid;
if((pid = fork()) < 0)
throw std::system_error(errno, std::system_category());
if(pid == 0) {
try {
func();
}
catch(...) {}
terminate();
assert(false && "should never get here");
}
else {
int status;
if(waitpid(pid, &status, 0) < 0)
throw std::system_error(errno, std::system_category());
return status;
}
}
template<typename Matcher>
class killed_impl : public matcher_tag {
public:
template<typename T>
killed_impl(T &&t, bool verbose = true)
: matcher_(std::forward<T>(t)), verbose_(verbose) {}
template<typename U>
match_result operator ()(U &&value) const {
int status = get_status(std::forward<U>(value), terminate);
if(WIFSIGNALED(status)) {
std::ostringstream ss;
ss << "killed with signal " << WTERMSIG(status);
return { matcher_(WTERMSIG(status)), ss.str() };
}
return { false, "wasn't killed" };
}
std::string desc() const {
std::ostringstream ss;
ss << "killed";
if (verbose_)
ss << " with signal " << matcher_.desc();
return ss.str();
}
private:
[[noreturn]] static void terminate() {
_exit(0);
}
Matcher matcher_;
bool verbose_;
};
template<typename Matcher>
class exited_impl : public matcher_tag {
public:
template<typename T>
exited_impl(T &&t, bool verbose = true)
: matcher_(std::forward<T>(t)), verbose_(verbose) {}
template<typename U>
match_result operator ()(U &&value) const {
int status = get_status(std::forward<U>(value), terminate);
if(WIFEXITED(status)) {
std::ostringstream ss;
ss << "exited with status " << WEXITSTATUS(status);
return { matcher_(WEXITSTATUS(status)), ss.str() };
}
return { false, "didn't exit" };
}
std::string desc() const {
std::ostringstream ss;
ss << "exited";
if (verbose_)
ss << " with status " << matcher_.desc();
return ss.str();
}
private:
[[noreturn]] static void terminate() {
abort();
}
Matcher matcher_;
bool verbose_;
};
}
inline auto killed() {
return detail::killed_impl<decltype(anything())>(anything(), false);
}
template<typename T>
inline auto killed(T &&thing) {
auto matcher = ensure_matcher(std::forward<T>(thing));
return detail::killed_impl<decltype(matcher)>(std::move(matcher));
}
inline auto exited() {
return detail::exited_impl<decltype(anything())>(anything(), false);
}
template<typename T>
inline auto exited(T &&thing) {
auto matcher = ensure_matcher(std::forward<T>(thing));
return detail::exited_impl<decltype(matcher)>(std::move(matcher));
}
} // namespace mettle
#endif
|
#ifndef INC_METTLE_MATCHERS_DEATH_HPP
#define INC_METTLE_MATCHERS_DEATH_HPP
#ifndef _WIN32
#include "core.hpp"
#include "result.hpp"
#include <sys/wait.h>
#include <unistd.h>
#include <system_error>
namespace mettle {
namespace detail {
template<typename T, typename U>
int get_status(T &&func, U &&terminate) {
pid_t pid;
if((pid = fork()) < 0)
throw std::system_error(errno, std::system_category());
if(pid == 0) {
try {
func();
}
catch(...) {}
terminate();
assert(false && "should never get here");
}
else {
int status;
if(waitpid(pid, &status, 0) < 0)
throw std::system_error(errno, std::system_category());
return status;
}
}
template<typename Matcher>
class killed_impl : public matcher_tag {
public:
template<typename T>
killed_impl(T &&t, bool verbose = true)
: matcher_(std::forward<T>(t)), verbose_(verbose) {}
template<typename U>
match_result operator ()(U &&value) const {
int status = get_status(std::forward<U>(value), terminate);
if(WIFSIGNALED(status)) {
std::ostringstream ss;
ss << "killed with signal " << WTERMSIG(status);
return { matcher_(WTERMSIG(status)), ss.str() };
}
return { false, "wasn't killed" };
}
std::string desc() const {
std::ostringstream ss;
ss << "killed";
if (verbose_)
ss << " with signal " << matcher_.desc();
return ss.str();
}
private:
[[noreturn]] static void terminate() {
_exit(0);
}
Matcher matcher_;
bool verbose_;
};
template<typename Matcher>
class exited_impl : public matcher_tag {
public:
template<typename T>
exited_impl(T &&t, bool verbose = true)
: matcher_(std::forward<T>(t)), verbose_(verbose) {}
template<typename U>
match_result operator ()(U &&value) const {
int status = get_status(std::forward<U>(value), terminate);
if(WIFEXITED(status)) {
std::ostringstream ss;
ss << "exited with status " << WEXITSTATUS(status);
return { matcher_(WEXITSTATUS(status)), ss.str() };
}
return { false, "didn't exit" };
}
std::string desc() const {
std::ostringstream ss;
ss << "exited";
if (verbose_)
ss << " with status " << matcher_.desc();
return ss.str();
}
private:
[[noreturn]] static void terminate() {
abort();
}
Matcher matcher_;
bool verbose_;
};
}
inline auto killed() {
return detail::killed_impl<decltype(anything())>(anything(), false);
}
template<typename T>
inline auto killed(T &&thing) {
auto matcher = ensure_matcher(std::forward<T>(thing));
return detail::killed_impl<decltype(matcher)>(std::move(matcher));
}
inline auto exited() {
return detail::exited_impl<decltype(anything())>(anything(), false);
}
template<typename T>
inline auto exited(T &&thing) {
auto matcher = ensure_matcher(std::forward<T>(thing));
return detail::exited_impl<decltype(matcher)>(std::move(matcher));
}
} // namespace mettle
#endif
#endif
|
Disable the death tests on Windows for now
|
Disable the death tests on Windows for now
|
C++
|
bsd-3-clause
|
jimporter/mettle,jimporter/mettle
|
9da26ac4adf2e81acf1e68d56fe8ee6f794cd9fa
|
parse/include/Ab/Parse/LineInfo.hpp
|
parse/include/Ab/Parse/LineInfo.hpp
|
#ifndef AB_PARSE_LINEINFO_HPP_
#define AB_PARSE_LINEINFO_HPP_
#include <Ab/Parse/Location.hpp>
#include <Ab/Assert.hpp>
#include <vector>
namespace Ab::Parse {
/// A table mapping file offsets into lines and column positions.
///
class LineInfo {
public:
LineInfo() {
// first line starts at zero.
store(0);
}
/// Get the start offset of a line.
/// @param n line number
std::size_t line_start(std::size_t n) const {
return breaks_[n];
}
/// Get the end offset of a line. "one past the end". Zero indexed.
/// @param n line number
std::size_t line_end(std::size_t n) const {
return breaks_[n + 1];
}
/// True if offset is within line number n.
///
bool in_line(std::size_t offset, std::size_t n) const {
return line_start(n) <= offset && offset < line_end(n);
}
std::size_t line(SrcPos pos) const { return line(pos.get()); }
std::size_t column(SrcPos pos) const { return column(pos.get()); }
Location location(SrcPos pos) const { return location(pos.get()); }
/// find the line number of a position. Lines are 0-indexed.
/// @param o offset
std::size_t line(std::size_t offset) const {
auto n = breaks_.size();
assert(0 < n);
// If the offset is _after_ the last line break, the offset occurs on
// the last line. The last line has no upper-limit, so we have to treat
// it specially.
if (breaks_[n - 1] <= offset) {
return n - 1;
}
// Otherwise, search for the line who's interval contains the offset.
std::size_t l = 0;
std::size_t r = n - 1;
while (l <= r) {
std::size_t m = (l + r) / 2;
if (line_end(m) < offset + 1) {
l = m + 1;
} else if (offset < line_start(m)) {
r = m - 1;
} else {
return m;
}
}
AB_ASSERT_UNREACHABLE();
}
/// Find the column number of a position. Columns are 0-indexed.
/// @param o offset
std::size_t column(std::size_t o) const {
return o - line_start(line(o));
};
/// Convert a position to a line/column location.
/// @param o offset
Location location(std::size_t o) const {
auto l = line(o);
auto c = o - line_start(l);
return { l, c };
}
/// Convert two positions into a range.
///
LocationRange range(std::size_t start, std::size_t end) const {
return { location(start), location(end) };
}
/// Note a linebreak at position p.
///
void store(std::size_t offset) {
breaks_.push_back(offset);
}
/// Note a linebreak at position p.
///
void record_br(std::size_t offset) {
breaks_.push_back(offset);
}
/// Access the underlying set of recorded line breaks.
///
const std::vector<std::size_t> breaks() const { return breaks_; }
private:
std::vector<std::size_t> breaks_;
};
} // namespace Ab::Parse
#endif // AB_PARSE_LINEINFO_HPP_
|
#ifndef AB_PARSE_LINEINFO_HPP_
#define AB_PARSE_LINEINFO_HPP_
#include <Ab/Parse/Location.hpp>
#include <Ab/Assert.hpp>
#include <vector>
namespace Ab::Parse {
/// A table mapping file offsets into lines and column positions.
///
class LineInfo {
public:
LineInfo() {
// first line starts at zero.
store(0);
}
/// Get the start offset of a line.
/// @param n line number
std::size_t line_start(std::size_t n) const {
return breaks_[n];
}
/// Get the end offset of a line. "one past the end". Zero indexed.
/// @param n line number
std::size_t line_end(std::size_t n) const {
return breaks_[n + 1];
}
/// True if offset is within line number n.
///
bool in_line(std::size_t offset, std::size_t n) const {
return line_start(n) <= offset && offset < line_end(n);
}
std::size_t line(SrcPos pos) const { return line(pos.get()); }
std::size_t column(SrcPos pos) const { return column(pos.get()); }
Location location(SrcPos pos) const { return location(pos.get()); }
/// find the line number of a position. Lines are 0-indexed.
/// @param o offset
std::size_t line(std::size_t offset) const {
auto n = breaks_.size();
// If the offset is _after_ the last line break, the offset occurs on
// the last line. The last line has no upper-limit, so we have to treat
// it specially.
if (breaks_[n - 1] <= offset) {
return n - 1;
}
// Otherwise, search for the line who's interval contains the offset.
std::size_t l = 0;
std::size_t r = n - 1;
while (l <= r) {
std::size_t m = (l + r) / 2;
if (line_end(m) < offset + 1) {
l = m + 1;
} else if (offset < line_start(m)) {
r = m - 1;
} else {
return m;
}
}
AB_ASSERT_UNREACHABLE();
}
/// Find the column number of a position. Columns are 0-indexed.
/// @param o offset
std::size_t column(std::size_t o) const {
return o - line_start(line(o));
};
/// Convert a position to a line/column location.
/// @param o offset
Location location(std::size_t o) const {
auto l = line(o);
auto c = o - line_start(l);
return { l, c };
}
/// Convert two positions into a range.
///
LocationRange range(std::size_t start, std::size_t end) const {
return { location(start), location(end) };
}
/// Note a linebreak at position p.
///
void store(std::size_t offset) {
breaks_.push_back(offset);
}
/// Note a linebreak at position p.
///
void record_br(std::size_t offset) {
breaks_.push_back(offset);
}
/// Access the underlying set of recorded line breaks.
///
const std::vector<std::size_t> breaks() const { return breaks_; }
private:
std::vector<std::size_t> breaks_;
};
} // namespace Ab::Parse
#endif // AB_PARSE_LINEINFO_HPP_
|
Use AB_ASSERT, not C assert
|
Use AB_ASSERT, not C assert
Signed-off-by: Robert Young <[email protected]>
|
C++
|
apache-2.0
|
ab-vm/ab,ab-vm/ab,ab-vm/ab,ab-vm/ab,ab-vm/ab
|
cad767de61dc53b9b297f08ee09cb5a3c0821782
|
ConstantOptimiser.cpp
|
ConstantOptimiser.cpp
|
/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file ConstantOptimiser.cpp
* @author Christian <[email protected]>
* @date 2015
*/
#include "libevmasm/ConstantOptimiser.h"
#include <libevmasm/Assembly.h>
#include <libevmasm/GasMeter.h>
#include <libevmcore/Params.h>
using namespace std;
using namespace dev;
using namespace dev::eth;
unsigned ConstantOptimisationMethod::optimiseConstants(
bool _isCreation,
size_t _runs,
Assembly& _assembly,
AssemblyItems& _items
)
{
unsigned optimisations = 0;
map<AssemblyItem, size_t> pushes;
for (AssemblyItem const& item: _items)
if (item.type() == Push)
pushes[item]++;
for (auto it: pushes)
{
AssemblyItem const& item = it.first;
if (item.data() < 0x100)
continue;
Params params;
params.multiplicity = it.second;
params.isCreation = _isCreation;
params.runs = _runs;
LiteralMethod lit(params, item.data());
bigint literalGas = lit.gasNeeded();
CodeCopyMethod copy(params, item.data());
bigint copyGas = copy.gasNeeded();
ComputeMethod compute(params, item.data());
bigint computeGas = compute.gasNeeded();
if (copyGas < literalGas && copyGas < computeGas)
{
copy.execute(_assembly, _items);
optimisations++;
}
else if (computeGas < literalGas && computeGas < copyGas)
{
compute.execute(_assembly, _items);
optimisations++;
}
}
return optimisations;
}
bigint ConstantOptimisationMethod::simpleRunGas(AssemblyItems const& _items)
{
bigint gas = 0;
for (AssemblyItem const& item: _items)
if (item.type() == Push)
gas += GasMeter::runGas(eth::Instruction::PUSH1);
else if (item.type() == Operation)
gas += GasMeter::runGas(item.instruction());
return gas;
}
bigint ConstantOptimisationMethod::dataGas(bytes const& _data) const
{
if (m_params.isCreation)
{
bigint gas;
for (auto b: _data)
gas += b ? c_txDataNonZeroGas : c_txDataZeroGas;
return gas;
}
else
return c_createDataGas * dataSize();
}
size_t ConstantOptimisationMethod::bytesRequired(AssemblyItems const& _items)
{
size_t size = 0;
for (AssemblyItem const& item: _items)
size += item.bytesRequired(3); // assume 3 byte addresses
return size;
}
void ConstantOptimisationMethod::replaceConstants(
AssemblyItems& _items,
AssemblyItems const& _replacement
) const
{
assertThrow(_items.size() > 0, OptimizerException, "");
for (size_t i = 0; i < _items.size(); ++i)
{
if (_items.at(i) != AssemblyItem(m_value))
continue;
_items[i] = _replacement[0];
_items.insert(_items.begin() + i + 1, _replacement.begin() + 1, _replacement.end());
i += _replacement.size() - 1;
}
}
bigint LiteralMethod::gasNeeded()
{
return combineGas(
simpleRunGas({eth::Instruction::PUSH1}),
// PUSHX plus data
(m_params.isCreation ? c_txDataNonZeroGas : c_createDataGas) + dataGas(),
0
);
}
CodeCopyMethod::CodeCopyMethod(Params const& _params, u256 const& _value):
ConstantOptimisationMethod(_params, _value)
{
m_copyRoutine = AssemblyItems{
u256(0),
eth::Instruction::DUP1,
eth::Instruction::MLOAD, // back up memory
u256(32),
AssemblyItem(PushData, u256(1) << 16), // has to be replaced
eth::Instruction::DUP4,
eth::Instruction::CODECOPY,
eth::Instruction::DUP2,
eth::Instruction::MLOAD,
eth::Instruction::SWAP2,
eth::Instruction::MSTORE
};
}
bigint CodeCopyMethod::gasNeeded()
{
return combineGas(
// Run gas: we ignore memory increase costs
simpleRunGas(m_copyRoutine) + c_copyGas,
// Data gas for copy routines: Some bytes are zero, but we ignore them.
bytesRequired(m_copyRoutine) * (m_params.isCreation ? c_txDataNonZeroGas : c_createDataGas),
// Data gas for data itself
dataGas(toBigEndian(m_value))
);
}
void CodeCopyMethod::execute(Assembly& _assembly, AssemblyItems& _items)
{
bytes data = toBigEndian(m_value);
m_copyRoutine[4] = _assembly.newData(data);
replaceConstants(_items, m_copyRoutine);
}
AssemblyItems ComputeMethod::findRepresentation(u256 const& _value)
{
if (_value < 0x10000)
// Very small value, not worth computing
return AssemblyItems{_value};
else if (dev::bytesRequired(~_value) < dev::bytesRequired(_value))
// Negated is shorter to represent
return findRepresentation(~_value) + AssemblyItems{Instruction::NOT};
else
{
// Decompose value into a * 2**k + b where abs(b) << 2**k
// Is not always better, try literal and decomposition method.
AssemblyItems routine{u256(_value)};
bigint bestGas = gasNeeded(routine);
for (unsigned bits = 255; bits > 8; --bits)
{
unsigned gapDetector = unsigned(_value >> (bits - 8)) & 0x1ff;
if (gapDetector != 0xff && gapDetector != 0x100)
continue;
u256 powerOfTwo = u256(1) << bits;
u256 upperPart = _value >> bits;
bigint lowerPart = _value & (powerOfTwo - 1);
if (abs(powerOfTwo - lowerPart) < lowerPart)
lowerPart = lowerPart - powerOfTwo; // make it negative
if (abs(lowerPart) >= (powerOfTwo >> 8))
continue;
AssemblyItems newRoutine;
if (lowerPart != 0)
newRoutine += findRepresentation(u256(abs(lowerPart)));
newRoutine += AssemblyItems{u256(bits), u256(2), Instruction::EXP};
if (upperPart != 1 && upperPart != 0)
newRoutine += findRepresentation(upperPart) + AssemblyItems{Instruction::MUL};
if (lowerPart > 0)
newRoutine += AssemblyItems{Instruction::ADD};
else if (lowerPart < 0)
newRoutine.push_back(eth::Instruction::SUB);
bigint newGas = gasNeeded(newRoutine);
if (newGas < bestGas)
{
bestGas = move(newGas);
routine = move(newRoutine);
}
}
return routine;
}
}
bigint ComputeMethod::gasNeeded(AssemblyItems const& _routine)
{
size_t numExps = count(_routine.begin(), _routine.end(), eth::Instruction::EXP);
return combineGas(
simpleRunGas(_routine) + numExps * (c_expGas + c_expByteGas),
// Data gas for routine: Some bytes are zero, but we ignore them.
bytesRequired(_routine) * (m_params.isCreation ? c_txDataNonZeroGas : c_createDataGas),
0
);
}
|
/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file ConstantOptimiser.cpp
* @author Christian <[email protected]>
* @date 2015
*/
#include "libevmasm/ConstantOptimiser.h"
#include <libevmasm/Assembly.h>
#include <libevmasm/GasMeter.h>
#include <libevmcore/Params.h>
using namespace std;
using namespace dev;
using namespace dev::eth;
unsigned ConstantOptimisationMethod::optimiseConstants(
bool _isCreation,
size_t _runs,
Assembly& _assembly,
AssemblyItems& _items
)
{
unsigned optimisations = 0;
map<AssemblyItem, size_t> pushes;
for (AssemblyItem const& item: _items)
if (item.type() == Push)
pushes[item]++;
for (auto it: pushes)
{
AssemblyItem const& item = it.first;
if (item.data() < 0x100)
continue;
Params params;
params.multiplicity = it.second;
params.isCreation = _isCreation;
params.runs = _runs;
LiteralMethod lit(params, item.data());
bigint literalGas = lit.gasNeeded();
CodeCopyMethod copy(params, item.data());
bigint copyGas = copy.gasNeeded();
ComputeMethod compute(params, item.data());
bigint computeGas = compute.gasNeeded();
if (copyGas < literalGas && copyGas < computeGas)
{
copy.execute(_assembly, _items);
optimisations++;
}
else if (computeGas < literalGas && computeGas < copyGas)
{
compute.execute(_assembly, _items);
optimisations++;
}
}
return optimisations;
}
bigint ConstantOptimisationMethod::simpleRunGas(AssemblyItems const& _items)
{
bigint gas = 0;
for (AssemblyItem const& item: _items)
if (item.type() == Push)
gas += GasMeter::runGas(Instruction::PUSH1);
else if (item.type() == Operation)
gas += GasMeter::runGas(item.instruction());
return gas;
}
bigint ConstantOptimisationMethod::dataGas(bytes const& _data) const
{
if (m_params.isCreation)
{
bigint gas;
for (auto b: _data)
gas += b ? c_txDataNonZeroGas : c_txDataZeroGas;
return gas;
}
else
return c_createDataGas * dataSize();
}
size_t ConstantOptimisationMethod::bytesRequired(AssemblyItems const& _items)
{
size_t size = 0;
for (AssemblyItem const& item: _items)
size += item.bytesRequired(3); // assume 3 byte addresses
return size;
}
void ConstantOptimisationMethod::replaceConstants(
AssemblyItems& _items,
AssemblyItems const& _replacement
) const
{
assertThrow(_items.size() > 0, OptimizerException, "");
for (size_t i = 0; i < _items.size(); ++i)
{
if (_items.at(i) != AssemblyItem(m_value))
continue;
_items[i] = _replacement[0];
_items.insert(_items.begin() + i + 1, _replacement.begin() + 1, _replacement.end());
i += _replacement.size() - 1;
}
}
bigint LiteralMethod::gasNeeded()
{
return combineGas(
simpleRunGas({Instruction::PUSH1}),
// PUSHX plus data
(m_params.isCreation ? c_txDataNonZeroGas : c_createDataGas) + dataGas(),
0
);
}
CodeCopyMethod::CodeCopyMethod(Params const& _params, u256 const& _value):
ConstantOptimisationMethod(_params, _value)
{
m_copyRoutine = AssemblyItems{
u256(0),
Instruction::DUP1,
Instruction::MLOAD, // back up memory
u256(32),
AssemblyItem(PushData, u256(1) << 16), // has to be replaced
Instruction::DUP4,
Instruction::CODECOPY,
Instruction::DUP2,
Instruction::MLOAD,
Instruction::SWAP2,
Instruction::MSTORE
};
}
bigint CodeCopyMethod::gasNeeded()
{
return combineGas(
// Run gas: we ignore memory increase costs
simpleRunGas(m_copyRoutine) + c_copyGas,
// Data gas for copy routines: Some bytes are zero, but we ignore them.
bytesRequired(m_copyRoutine) * (m_params.isCreation ? c_txDataNonZeroGas : c_createDataGas),
// Data gas for data itself
dataGas(toBigEndian(m_value))
);
}
void CodeCopyMethod::execute(Assembly& _assembly, AssemblyItems& _items)
{
bytes data = toBigEndian(m_value);
m_copyRoutine[4] = _assembly.newData(data);
replaceConstants(_items, m_copyRoutine);
}
AssemblyItems ComputeMethod::findRepresentation(u256 const& _value)
{
if (_value < 0x10000)
// Very small value, not worth computing
return AssemblyItems{_value};
else if (dev::bytesRequired(~_value) < dev::bytesRequired(_value))
// Negated is shorter to represent
return findRepresentation(~_value) + AssemblyItems{Instruction::NOT};
else
{
// Decompose value into a * 2**k + b where abs(b) << 2**k
// Is not always better, try literal and decomposition method.
AssemblyItems routine{u256(_value)};
bigint bestGas = gasNeeded(routine);
for (unsigned bits = 255; bits > 8; --bits)
{
unsigned gapDetector = unsigned(_value >> (bits - 8)) & 0x1ff;
if (gapDetector != 0xff && gapDetector != 0x100)
continue;
u256 powerOfTwo = u256(1) << bits;
u256 upperPart = _value >> bits;
bigint lowerPart = _value & (powerOfTwo - 1);
if (abs(powerOfTwo - lowerPart) < lowerPart)
lowerPart = lowerPart - powerOfTwo; // make it negative
if (abs(lowerPart) >= (powerOfTwo >> 8))
continue;
AssemblyItems newRoutine;
if (lowerPart != 0)
newRoutine += findRepresentation(u256(abs(lowerPart)));
newRoutine += AssemblyItems{u256(bits), u256(2), Instruction::EXP};
if (upperPart != 1 && upperPart != 0)
newRoutine += findRepresentation(upperPart) + AssemblyItems{Instruction::MUL};
if (lowerPart > 0)
newRoutine += AssemblyItems{Instruction::ADD};
else if (lowerPart < 0)
newRoutine.push_back(Instruction::SUB);
bigint newGas = gasNeeded(newRoutine);
if (newGas < bestGas)
{
bestGas = move(newGas);
routine = move(newRoutine);
}
}
return routine;
}
}
bigint ComputeMethod::gasNeeded(AssemblyItems const& _routine)
{
size_t numExps = count(_routine.begin(), _routine.end(), Instruction::EXP);
return combineGas(
simpleRunGas(_routine) + numExps * (c_expGas + c_expByteGas),
// Data gas for routine: Some bytes are zero, but we ignore them.
bytesRequired(_routine) * (m_params.isCreation ? c_txDataNonZeroGas : c_createDataGas),
0
);
}
|
Remove namespace prefixes.
|
Remove namespace prefixes.
|
C++
|
mit
|
ruchevits/solidity,ruchevits/solidity,ruchevits/solidity,ruchevits/solidity
|
5233b53188a40bfc51f38990173d5d906534499a
|
eval/src/vespa/eval/tensor/dense/dense_matmul_function.cpp
|
eval/src/vespa/eval/tensor/dense/dense_matmul_function.cpp
|
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "dense_matmul_function.h"
#include "dense_tensor_view.h"
#include <vespa/vespalib/objects/objectvisitor.h>
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/operation.h>
#include <cassert>
#include <cblas.h>
namespace vespalib::tensor {
using eval::ValueType;
using eval::TensorFunction;
using eval::TensorEngine;
using eval::as;
using eval::Aggr;
using namespace eval::tensor_function;
using namespace eval::operation;
namespace {
template <typename LCT, typename RCT, bool lhs_common_inner, bool rhs_common_inner>
double my_dot_product(const LCT *lhs, const RCT *rhs, size_t lhs_size, size_t common_size, size_t rhs_size) {
double result = 0.0;
for (size_t i = 0; i < common_size; ++i) {
result += ((*lhs) * (*rhs));
lhs += (lhs_common_inner ? 1 : lhs_size);
rhs += (rhs_common_inner ? 1 : rhs_size);
}
return result;
}
template <typename LCT, typename RCT, bool lhs_common_inner, bool rhs_common_inner>
void my_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
using OCT = typename eval::UnifyCellTypes<LCT,RCT>::type;
auto lhs_cells = DenseTensorView::typify_cells<LCT>(state.peek(1));
auto rhs_cells = DenseTensorView::typify_cells<RCT>(state.peek(0));
auto dst_cells = state.stash.create_array<OCT>(self.lhs_size * self.rhs_size);
OCT *dst = dst_cells.begin();
const LCT *lhs = lhs_cells.cbegin();
for (size_t i = 0; i < self.lhs_size; ++i) {
const RCT *rhs = rhs_cells.cbegin();
for (size_t j = 0; j < self.rhs_size; ++j) {
*dst++ = my_dot_product<LCT,RCT,lhs_common_inner,rhs_common_inner>(lhs, rhs, self.lhs_size, self.common_size, self.rhs_size);
rhs += (rhs_common_inner ? self.common_size : 1);
}
lhs += (lhs_common_inner ? self.common_size : 1);
}
state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}
template <bool lhs_common_inner, bool rhs_common_inner>
void my_cblas_double_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
auto lhs_cells = DenseTensorView::typify_cells<double>(state.peek(1));
auto rhs_cells = DenseTensorView::typify_cells<double>(state.peek(0));
auto dst_cells = state.stash.create_array<double>(self.lhs_size * self.rhs_size);
cblas_dgemm(CblasRowMajor, lhs_common_inner ? CblasNoTrans : CblasTrans, rhs_common_inner ? CblasTrans : CblasNoTrans,
self.lhs_size, self.rhs_size, self.common_size, 1.0,
lhs_cells.cbegin(), lhs_common_inner ? self.common_size : self.lhs_size,
rhs_cells.cbegin(), rhs_common_inner ? self.common_size : self.rhs_size,
0.0, dst_cells.begin(), self.rhs_size);
state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}
template <bool lhs_common_inner, bool rhs_common_inner>
void my_cblas_float_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
auto lhs_cells = DenseTensorView::typify_cells<float>(state.peek(1));
auto rhs_cells = DenseTensorView::typify_cells<float>(state.peek(0));
auto dst_cells = state.stash.create_array<float>(self.lhs_size * self.rhs_size);
cblas_sgemm(CblasRowMajor, lhs_common_inner ? CblasNoTrans : CblasTrans, rhs_common_inner ? CblasTrans : CblasNoTrans,
self.lhs_size, self.rhs_size, self.common_size, 1.0,
lhs_cells.cbegin(), lhs_common_inner ? self.common_size : self.lhs_size,
rhs_cells.cbegin(), rhs_common_inner ? self.common_size : self.rhs_size,
0.0, dst_cells.begin(), self.rhs_size);
state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}
template <bool lhs_common_inner, bool rhs_common_inner>
struct MyMatMulOp {
template <typename LCT, typename RCT>
static auto get_fun() { return my_matmul_op<LCT,RCT,lhs_common_inner,rhs_common_inner>; }
};
template <bool lhs_common_inner, bool rhs_common_inner>
eval::InterpretedFunction::op_function my_select3(CellType lct, CellType rct)
{
if (lct == rct) {
if (lct == ValueType::CellType::DOUBLE) {
return my_cblas_double_matmul_op<lhs_common_inner,rhs_common_inner>;
}
if (lct == ValueType::CellType::FLOAT) {
return my_cblas_float_matmul_op<lhs_common_inner,rhs_common_inner>;
}
}
return select_2<MyMatMulOp<lhs_common_inner,rhs_common_inner>>(lct, rct);
}
template <bool lhs_common_inner>
eval::InterpretedFunction::op_function my_select2(CellType lct, CellType rct,
bool rhs_common_inner)
{
if (rhs_common_inner) {
return my_select3<lhs_common_inner,true>(lct, rct);
} else {
return my_select3<lhs_common_inner,false>(lct, rct);
}
}
eval::InterpretedFunction::op_function my_select(CellType lct, CellType rct,
bool lhs_common_inner, bool rhs_common_inner)
{
if (lhs_common_inner) {
return my_select2<true>(lct, rct, rhs_common_inner);
} else {
return my_select2<false>(lct, rct, rhs_common_inner);
}
}
bool is_matrix(const ValueType &type) {
return (type.is_dense() && (type.dimensions().size() == 2));
}
bool is_matmul(const eval::ValueType &a, const eval::ValueType &b,
const vespalib::string &reduce_dim, const eval::ValueType &result_type)
{
size_t npos = ValueType::Dimension::npos;
return (is_matrix(a) && is_matrix(b) && is_matrix(result_type) &&
(a.dimension_index(reduce_dim) != npos) &&
(b.dimension_index(reduce_dim) != npos));
}
const ValueType::Dimension &dim(const TensorFunction &expr, size_t idx) {
return expr.result_type().dimensions()[idx];
}
size_t inv(size_t idx) { return (1 - idx); }
const TensorFunction &create_matmul(const TensorFunction &a, const TensorFunction &b,
const vespalib::string &reduce_dim, const ValueType &result_type, Stash &stash) {
size_t a_idx = a.result_type().dimension_index(reduce_dim);
size_t b_idx = b.result_type().dimension_index(reduce_dim);
assert(a_idx != ValueType::Dimension::npos);
assert(b_idx != ValueType::Dimension::npos);
assert(dim(a, a_idx).size == dim(b, b_idx).size);
bool a_common_inner = (a_idx == 1);
bool b_common_inner = (b_idx == 1);
size_t a_size = dim(a, inv(a_idx)).size;
size_t b_size = dim(b, inv(b_idx)).size;
size_t common_size = dim(a, a_idx).size;
bool a_is_lhs = (dim(a, inv(a_idx)).name < dim(b, inv(b_idx)).name);
if (a_is_lhs) {
return stash.create<DenseMatMulFunction>(result_type, a, b, a_size, common_size, b_size, a_common_inner, b_common_inner);
} else {
return stash.create<DenseMatMulFunction>(result_type, b, a, b_size, common_size, a_size, b_common_inner, a_common_inner);
}
}
} // namespace vespalib::tensor::<unnamed>
DenseMatMulFunction::Self::Self(const eval::ValueType &result_type_in,
size_t lhs_size_in,
size_t common_size_in,
size_t rhs_size_in)
: result_type(result_type_in),
lhs_size(lhs_size_in),
common_size(common_size_in),
rhs_size(rhs_size_in)
{
}
DenseMatMulFunction::Self::~Self() = default;
DenseMatMulFunction::DenseMatMulFunction(const eval::ValueType &result_type,
const eval::TensorFunction &lhs_in,
const eval::TensorFunction &rhs_in,
size_t lhs_size,
size_t common_size,
size_t rhs_size,
bool lhs_common_inner,
bool rhs_common_inner)
: Super(result_type, lhs_in, rhs_in),
_lhs_size(lhs_size),
_common_size(common_size),
_rhs_size(rhs_size),
_lhs_common_inner(lhs_common_inner),
_rhs_common_inner(rhs_common_inner)
{
}
DenseMatMulFunction::~DenseMatMulFunction() = default;
eval::InterpretedFunction::Instruction
DenseMatMulFunction::compile_self(const TensorEngine &, Stash &stash) const
{
Self &self = stash.create<Self>(result_type(), _lhs_size, _common_size, _rhs_size);
auto op = my_select(lhs().result_type().cell_type(), rhs().result_type().cell_type(),
_lhs_common_inner, _rhs_common_inner);
return eval::InterpretedFunction::Instruction(op, (uint64_t)(&self));
}
void
DenseMatMulFunction::visit_self(vespalib::ObjectVisitor &visitor) const
{
Super::visit_self(visitor);
visitor.visitInt("lhs_size", _lhs_size);
visitor.visitInt("common_size", _common_size);
visitor.visitInt("rhs_size", _rhs_size);
visitor.visitBool("lhs_common_inner", _lhs_common_inner);
visitor.visitBool("rhs_common_inner", _rhs_common_inner);
}
const TensorFunction &
DenseMatMulFunction::optimize(const eval::TensorFunction &expr, Stash &stash)
{
auto reduce = as<Reduce>(expr);
if (reduce && (reduce->aggr() == Aggr::SUM) && (reduce->dimensions().size() == 1)) {
auto join = as<Join>(reduce->child());
if (join && (join->function() == Mul::f)) {
const TensorFunction &a = join->lhs();
const TensorFunction &b = join->rhs();
if (is_matmul(a.result_type(), b.result_type(), reduce->dimensions()[0], expr.result_type())) {
return create_matmul(a, b, reduce->dimensions()[0], expr.result_type(), stash);
}
}
}
return expr;
}
} // namespace vespalib::tensor
|
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "dense_matmul_function.h"
#include "dense_tensor_view.h"
#include <vespa/vespalib/objects/objectvisitor.h>
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/operation.h>
#include <cassert>
#include <cblas.h>
namespace vespalib::tensor {
using eval::ValueType;
using eval::TensorFunction;
using eval::TensorEngine;
using eval::as;
using eval::Aggr;
using namespace eval::tensor_function;
using namespace eval::operation;
namespace {
template <typename LCT, typename RCT, bool lhs_common_inner, bool rhs_common_inner>
double my_dot_product(const LCT *lhs, const RCT *rhs, size_t lhs_size, size_t common_size, size_t rhs_size) {
double result = 0.0;
for (size_t i = 0; i < common_size; ++i) {
result += ((*lhs) * (*rhs));
lhs += (lhs_common_inner ? 1 : lhs_size);
rhs += (rhs_common_inner ? 1 : rhs_size);
}
return result;
}
template <typename LCT, typename RCT, bool lhs_common_inner, bool rhs_common_inner>
void my_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
using OCT = typename eval::UnifyCellTypes<LCT,RCT>::type;
auto lhs_cells = DenseTensorView::typify_cells<LCT>(state.peek(1));
auto rhs_cells = DenseTensorView::typify_cells<RCT>(state.peek(0));
auto dst_cells = state.stash.create_array<OCT>(self.lhs_size * self.rhs_size);
OCT *dst = dst_cells.begin();
const LCT *lhs = lhs_cells.cbegin();
for (size_t i = 0; i < self.lhs_size; ++i) {
const RCT *rhs = rhs_cells.cbegin();
for (size_t j = 0; j < self.rhs_size; ++j) {
*dst++ = my_dot_product<LCT,RCT,lhs_common_inner,rhs_common_inner>(lhs, rhs, self.lhs_size, self.common_size, self.rhs_size);
rhs += (rhs_common_inner ? self.common_size : 1);
}
lhs += (lhs_common_inner ? self.common_size : 1);
}
state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}
template <bool lhs_common_inner, bool rhs_common_inner>
void my_cblas_double_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
auto lhs_cells = DenseTensorView::typify_cells<double>(state.peek(1));
auto rhs_cells = DenseTensorView::typify_cells<double>(state.peek(0));
auto dst_cells = state.stash.create_array<double>(self.lhs_size * self.rhs_size);
cblas_dgemm(CblasRowMajor, lhs_common_inner ? CblasNoTrans : CblasTrans, rhs_common_inner ? CblasTrans : CblasNoTrans,
self.lhs_size, self.rhs_size, self.common_size, 1.0,
lhs_cells.cbegin(), lhs_common_inner ? self.common_size : self.lhs_size,
rhs_cells.cbegin(), rhs_common_inner ? self.common_size : self.rhs_size,
0.0, dst_cells.begin(), self.rhs_size);
state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}
template <bool lhs_common_inner, bool rhs_common_inner>
void my_cblas_float_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
auto lhs_cells = DenseTensorView::typify_cells<float>(state.peek(1));
auto rhs_cells = DenseTensorView::typify_cells<float>(state.peek(0));
auto dst_cells = state.stash.create_array<float>(self.lhs_size * self.rhs_size);
cblas_sgemm(CblasRowMajor, lhs_common_inner ? CblasNoTrans : CblasTrans, rhs_common_inner ? CblasTrans : CblasNoTrans,
self.lhs_size, self.rhs_size, self.common_size, 1.0,
lhs_cells.cbegin(), lhs_common_inner ? self.common_size : self.lhs_size,
rhs_cells.cbegin(), rhs_common_inner ? self.common_size : self.rhs_size,
0.0, dst_cells.begin(), self.rhs_size);
state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}
bool is_matrix(const ValueType &type) {
return (type.is_dense() && (type.dimensions().size() == 2));
}
bool is_matmul(const eval::ValueType &a, const eval::ValueType &b,
const vespalib::string &reduce_dim, const eval::ValueType &result_type)
{
size_t npos = ValueType::Dimension::npos;
return (is_matrix(a) && is_matrix(b) && is_matrix(result_type) &&
(a.dimension_index(reduce_dim) != npos) &&
(b.dimension_index(reduce_dim) != npos));
}
const ValueType::Dimension &dim(const TensorFunction &expr, size_t idx) {
return expr.result_type().dimensions()[idx];
}
size_t inv(size_t idx) { return (1 - idx); }
const TensorFunction &create_matmul(const TensorFunction &a, const TensorFunction &b,
const vespalib::string &reduce_dim, const ValueType &result_type, Stash &stash) {
size_t a_idx = a.result_type().dimension_index(reduce_dim);
size_t b_idx = b.result_type().dimension_index(reduce_dim);
assert(a_idx != ValueType::Dimension::npos);
assert(b_idx != ValueType::Dimension::npos);
assert(dim(a, a_idx).size == dim(b, b_idx).size);
bool a_common_inner = (a_idx == 1);
bool b_common_inner = (b_idx == 1);
size_t a_size = dim(a, inv(a_idx)).size;
size_t b_size = dim(b, inv(b_idx)).size;
size_t common_size = dim(a, a_idx).size;
bool a_is_lhs = (dim(a, inv(a_idx)).name < dim(b, inv(b_idx)).name);
if (a_is_lhs) {
return stash.create<DenseMatMulFunction>(result_type, a, b, a_size, common_size, b_size, a_common_inner, b_common_inner);
} else {
return stash.create<DenseMatMulFunction>(result_type, b, a, b_size, common_size, a_size, b_common_inner, a_common_inner);
}
}
template <typename LCT, typename RCT, bool lhs_common_inner, bool rhs_common_inner>
struct MyMatMulOp {
static auto get_fun() {
return my_matmul_op<LCT, RCT, lhs_common_inner, rhs_common_inner>;
}
};
template <bool lhs_common_inner, bool rhs_common_inner>
struct MyMatMulOp<double, double, lhs_common_inner, rhs_common_inner> {
static auto get_fun() {
return my_cblas_double_matmul_op<lhs_common_inner, rhs_common_inner>;
}
};
template <bool lhs_common_inner, bool rhs_common_inner>
struct MyMatMulOp<float, float, lhs_common_inner, rhs_common_inner> {
static auto get_fun() {
return my_cblas_float_matmul_op<lhs_common_inner, rhs_common_inner>;
}
};
struct MyTarget {
template<typename R1, typename R2, typename R3, typename R4>
static auto invoke() {
using MyOp = MyMatMulOp<R1, R2, R3::value, R4::value>;
return MyOp::get_fun();
}
};
} // namespace vespalib::tensor::<unnamed>
DenseMatMulFunction::Self::Self(const eval::ValueType &result_type_in,
size_t lhs_size_in,
size_t common_size_in,
size_t rhs_size_in)
: result_type(result_type_in),
lhs_size(lhs_size_in),
common_size(common_size_in),
rhs_size(rhs_size_in)
{
}
DenseMatMulFunction::Self::~Self() = default;
DenseMatMulFunction::DenseMatMulFunction(const eval::ValueType &result_type,
const eval::TensorFunction &lhs_in,
const eval::TensorFunction &rhs_in,
size_t lhs_size,
size_t common_size,
size_t rhs_size,
bool lhs_common_inner,
bool rhs_common_inner)
: Super(result_type, lhs_in, rhs_in),
_lhs_size(lhs_size),
_common_size(common_size),
_rhs_size(rhs_size),
_lhs_common_inner(lhs_common_inner),
_rhs_common_inner(rhs_common_inner)
{
}
DenseMatMulFunction::~DenseMatMulFunction() = default;
eval::InterpretedFunction::Instruction
DenseMatMulFunction::compile_self(const TensorEngine &, Stash &stash) const
{
using MyTypify = TypifyValue<eval::TypifyCellType,vespalib::TypifyBool>;
Self &self = stash.create<Self>(result_type(), _lhs_size, _common_size, _rhs_size);
auto op = typify_invoke<4,MyTypify,MyTarget>(
lhs().result_type().cell_type(), rhs().result_type().cell_type(),
_lhs_common_inner, _rhs_common_inner);
return eval::InterpretedFunction::Instruction(op, (uint64_t)(&self));
}
void
DenseMatMulFunction::visit_self(vespalib::ObjectVisitor &visitor) const
{
Super::visit_self(visitor);
visitor.visitInt("lhs_size", _lhs_size);
visitor.visitInt("common_size", _common_size);
visitor.visitInt("rhs_size", _rhs_size);
visitor.visitBool("lhs_common_inner", _lhs_common_inner);
visitor.visitBool("rhs_common_inner", _rhs_common_inner);
}
const TensorFunction &
DenseMatMulFunction::optimize(const eval::TensorFunction &expr, Stash &stash)
{
auto reduce = as<Reduce>(expr);
if (reduce && (reduce->aggr() == Aggr::SUM) && (reduce->dimensions().size() == 1)) {
auto join = as<Join>(reduce->child());
if (join && (join->function() == Mul::f)) {
const TensorFunction &a = join->lhs();
const TensorFunction &b = join->rhs();
if (is_matmul(a.result_type(), b.result_type(), reduce->dimensions()[0], expr.result_type())) {
return create_matmul(a, b, reduce->dimensions()[0], expr.result_type(), stash);
}
}
}
return expr;
}
} // namespace vespalib::tensor
|
use typify_invoke to select matmul implementation
|
use typify_invoke to select matmul implementation
* instead of a chain of select functions, use typify_invoke;
use partial specialization on a struct to handle the
double*double and float*float cases specially.
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
116fa259d3f6e13c362319bad6e82cedefcd626b
|
History/Batch-Normalization/main.cpp
|
History/Batch-Normalization/main.cpp
|
#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include "Neural_Networks.h"
using namespace std;
void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {
ifstream file(training_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
}
file.open(training_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
}
file.open(test_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
}
file.open(test_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
}
}
int main() {
int batch_size = 128;
int epochs = 20;
int number_threads = 6;
int number_training = 60000;
int number_test = 10000;
int number_nodes[] = { 784, 10 };
float **x_data = new float*[number_training + number_test];
float **y_data = new float*[number_training + number_test];
float **x_train = x_data;
float **y_train = y_data;
float **x_test = &x_data[number_training];
float **y_test = &y_data[number_training];
double learning_rate = 0.5;
string path;
Neural_Networks NN = Neural_Networks();
cout << "path where MNIST handwritten digits dataset is : ";
getline(cin, path);
for (int h = 0; h < number_training + number_test; h++) {
x_data[h] = new float[number_nodes[0]];
y_data[h] = new float[number_nodes[1]];
}
Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, x_data, y_data);
omp_set_num_threads(number_threads);
srand(1);
NN.Add( 1, 28, 28);
NN.Add(24, 24, 24)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(24, 12, 12);
NN.Add(48, 8, 8)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(48, 4, 4);
NN.Add(512)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(number_nodes[1])->Activation(Activation::softmax);
NN.Connect(1, 0, "W")->Initializer(HeNormal());
NN.Connect(2, 1, "P,max");
NN.Connect(3, 2, "W")->Initializer(HeNormal());
NN.Connect(4, 3, "P,max");
NN.Connect(5, 4, "W")->Initializer(HeNormal());
NN.Connect(6, 5, "W")->Initializer(HeNormal());
NN.Compile(Loss::cross_entropy, new Optimizer(SGD(learning_rate)));
for (int e = 0, time = clock(); e < epochs; e++) {
int score[2] = { 0, };
float **_input = new float*[batch_size];
float **output = new float*[batch_size];
double loss[2] = { NN.Fit(NN.Shuffle(x_train, number_training), NN.Shuffle(y_train, number_training), number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };
for (int h = 0; h < batch_size; h++) {
output[h] = new float[number_nodes[1]];
}
for (int h = 0, i = 0; i < number_training + number_test; i++) {
_input[h] = x_data[i];
if (++h == batch_size || i == number_training + number_test - 1) {
NN.Predict(_input, output, h);
for (int argmax, index = i - h + 1; --h >= 0;) {
double max = 0;
for (int j = 0; j < number_nodes[1]; j++) {
if (j == 0 || max < output[h][j]) {
max = output[h][argmax = j];
}
}
score[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];
}
h = 0;
}
}
printf("loss: %.4f / %.4f accuracy: %.4f / %.4f step %d %.2f sec\n", loss[0], loss[1], 1.0 * score[0] / number_training, 1.0 * score[1] / number_test, e + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
for (int h = 0; h < batch_size; h++) {
delete[] output[h];
}
delete[] _input;
delete[] output;
}
for (int i = 0; i < number_training + number_test; i++) {
delete[] x_data[i];
delete[] y_data[i];
}
delete[] x_data;
delete[] y_data;
}
|
#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include "Neural_Networks.h"
using namespace std;
void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {
ifstream file(training_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
}
file.open(training_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
}
file.open(test_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
}
file.open(test_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
}
}
int main() {
int batch_size = 128;
int epochs = 20;
int number_threads = 6;
int number_training = 60000;
int number_test = 10000;
int number_nodes[] = { 784, 10 };
float **x_data = new float*[number_training + number_test];
float **y_data = new float*[number_training + number_test];
float **x_train = x_data;
float **y_train = y_data;
float **x_test = &x_data[number_training];
float **y_test = &y_data[number_training];
double learning_rate = 0.5;
string path;
Neural_Networks NN = Neural_Networks();
cout << "path where MNIST handwritten digits dataset is : ";
getline(cin, path);
for (int h = 0; h < number_training + number_test; h++) {
x_data[h] = new float[number_nodes[0]];
y_data[h] = new float[number_nodes[1]];
}
Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, x_data, y_data);
srand(2);
omp_set_num_threads(number_threads);
NN.Add( 1, 28, 28);
NN.Add(24, 24, 24)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(24, 12, 12);
NN.Add(48, 8, 8)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(48, 4, 4);
NN.Add(512)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(number_nodes[1])->Activation(Activation::softmax);
NN.Connect(1, 0, "W,kernel(5x5)")->Initializer(HeNormal());
NN.Connect(2, 1, "P,max");
NN.Connect(3, 2, "W,kernel(5x5)")->Initializer(HeNormal());
NN.Connect(4, 3, "P,max");
NN.Connect(5, 4, "W")->Initializer(HeNormal());
NN.Connect(6, 5, "W")->Initializer(HeNormal());
NN.Compile(Loss::cross_entropy, Optimizer(SGD(learning_rate)));
for (int e = 0, time = clock(); e < epochs; e++) {
int score[2] = { 0, };
float **_input = new float*[batch_size];
float **output = new float*[batch_size];
double loss[2] = { NN.Fit(x_train, y_train, number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };
for (int h = 0; h < batch_size; h++) {
output[h] = new float[number_nodes[1]];
}
for (int h = 0, i = 0; i < number_training + number_test; i++) {
_input[h] = x_data[i];
if (++h == batch_size || i == number_training + number_test - 1) {
NN.Predict(_input, output, h);
for (int argmax, index = i - h + 1; --h >= 0;) {
double max = 0;
for (int j = 0; j < number_nodes[1]; j++) {
if (j == 0 || max < output[h][j]) {
max = output[h][argmax = j];
}
}
score[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];
}
h = 0;
}
}
printf("loss: %.4f / %.4f accuracy: %.4f / %.4f step %d %.2f sec\n", loss[0], loss[1], 1.0 * score[0] / number_training, 1.0 * score[1] / number_test, e + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
delete[] output;
}
for (int i = 0; i < number_training + number_test; i++) {
delete[] x_data[i];
delete[] y_data[i];
}
delete[] x_data;
delete[] y_data;
}
|
Update main.cpp
|
Update main.cpp
|
C++
|
mit
|
paperrune/Neural-Networks,paperrune/Neural-Networks
|
2475afad21e8728d399eea3b588a4fb747ff445f
|
Hybrid/Testing/Cxx/TestCubeAxes3.cxx
|
Hybrid/Testing/Cxx/TestCubeAxes3.cxx
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestCubeAxes3.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This tests the spider plot capabilities in VTK.
#include "vtkBYUReader.h"
#include "vtkCamera.h"
#include "vtkCubeAxesActor.h"
#include "vtkLight.h"
#include "vtkLODActor.h"
#include "vtkNew.h"
#include "vtkOutlineFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyDataNormals.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
//----------------------------------------------------------------------------
int TestCubeAxes3( int argc, char * argv [] )
{
vtkNew<vtkBYUReader> fohe;
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/teapot.g");
fohe->SetGeometryFileName(fname);
delete [] fname;
vtkNew<vtkPolyDataNormals> normals;
normals->SetInputConnection(fohe->GetOutputPort());
vtkNew<vtkPolyDataMapper> foheMapper;
foheMapper->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkLODActor> foheActor;
foheActor->SetMapper(foheMapper.GetPointer());
vtkNew<vtkOutlineFilter> outline;
outline->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkPolyDataMapper> mapOutline;
mapOutline->SetInputConnection(outline->GetOutputPort());
vtkNew<vtkActor> outlineActor;
outlineActor->SetMapper(mapOutline.GetPointer());
outlineActor->GetProperty()->SetColor(0.0 ,0.0 ,0.0);
vtkNew<vtkCamera> camera;
camera->SetClippingRange(1.60187, 20.0842);
camera->SetFocalPoint(0.21406, 1.5, 0.0);
camera->SetPosition(11.63, 6.32, 5.77);
camera->SetViewUp(0.180325, 0.549245, -0.815974);
vtkNew<vtkLight> light;
light->SetFocalPoint(0.21406, 1.5, 0.0);
light->SetPosition(8.3761, 4.94858, 4.12505);
vtkNew<vtkRenderer> ren2;
ren2->SetActiveCamera(camera.GetPointer());
ren2->AddLight(light.GetPointer());
vtkNew<vtkRenderWindow> renWin;
renWin->SetMultiSamples(0);
renWin->AddRenderer(ren2.GetPointer());
renWin->SetWindowName("VTK - Cube Axes custom range");
renWin->SetSize(600, 600);
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin.GetPointer());
ren2->AddViewProp(foheActor.GetPointer());
ren2->AddViewProp(outlineActor.GetPointer());
ren2->SetBackground(0.1, 0.2, 0.4);
normals->Update();
vtkNew<vtkCubeAxesActor> axes2;
axes2->SetBounds(normals->GetOutput()->GetBounds());
axes2->SetXAxisRange(20, 300);
axes2->SetYAxisRange(-0.01, 0.01);
axes2->SetCamera(ren2->GetActiveCamera());
axes2->SetXLabelFormat("%6.1f");
axes2->SetYLabelFormat("%6.1f");
axes2->SetZLabelFormat("%6.1f");
axes2->SetFlyModeToClosestTriad();
axes2->DrawXGridlinesOn();
axes2->DrawYGridlinesOn();
axes2->DrawZGridlinesOn();
ren2->AddViewProp(axes2.GetPointer());
renWin->Render();
int retVal = vtkRegressionTestImage( renWin.GetPointer() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestCubeAxes3.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This example illustrates how one may explicitly specify the range of each
// axes that's used to define the prop, while displaying data with a different
// set of bounds (unlike cubeAxes2.tcl). This example allows you to separate
// the notion of extent of the axes in physical space (bounds) and the extent
// of the values it represents. In other words, you can have the ticks and
// labels show a different range.
#include "vtkBYUReader.h"
#include "vtkCamera.h"
#include "vtkCubeAxesActor.h"
#include "vtkLight.h"
#include "vtkLODActor.h"
#include "vtkNew.h"
#include "vtkOutlineFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyDataNormals.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
//----------------------------------------------------------------------------
int TestCubeAxes3( int argc, char * argv [] )
{
vtkNew<vtkBYUReader> fohe;
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/teapot.g");
fohe->SetGeometryFileName(fname);
delete [] fname;
vtkNew<vtkPolyDataNormals> normals;
normals->SetInputConnection(fohe->GetOutputPort());
vtkNew<vtkPolyDataMapper> foheMapper;
foheMapper->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkLODActor> foheActor;
foheActor->SetMapper(foheMapper.GetPointer());
vtkNew<vtkOutlineFilter> outline;
outline->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkPolyDataMapper> mapOutline;
mapOutline->SetInputConnection(outline->GetOutputPort());
vtkNew<vtkActor> outlineActor;
outlineActor->SetMapper(mapOutline.GetPointer());
outlineActor->GetProperty()->SetColor(0.0 ,0.0 ,0.0);
vtkNew<vtkCamera> camera;
camera->SetClippingRange(1.60187, 20.0842);
camera->SetFocalPoint(0.21406, 1.5, 0.0);
camera->SetPosition(11.63, 6.32, 5.77);
camera->SetViewUp(0.180325, 0.549245, -0.815974);
vtkNew<vtkLight> light;
light->SetFocalPoint(0.21406, 1.5, 0.0);
light->SetPosition(8.3761, 4.94858, 4.12505);
vtkNew<vtkRenderer> ren2;
ren2->SetActiveCamera(camera.GetPointer());
ren2->AddLight(light.GetPointer());
vtkNew<vtkRenderWindow> renWin;
renWin->SetMultiSamples(0);
renWin->AddRenderer(ren2.GetPointer());
renWin->SetWindowName("VTK - Cube Axes custom range");
renWin->SetSize(600, 600);
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin.GetPointer());
ren2->AddViewProp(foheActor.GetPointer());
ren2->AddViewProp(outlineActor.GetPointer());
ren2->SetBackground(0.1, 0.2, 0.4);
normals->Update();
vtkNew<vtkCubeAxesActor> axes2;
axes2->SetBounds(normals->GetOutput()->GetBounds());
axes2->SetXAxisRange(20, 300);
axes2->SetYAxisRange(-0.01, 0.01);
axes2->SetCamera(ren2->GetActiveCamera());
axes2->SetXLabelFormat("%6.1f");
axes2->SetYLabelFormat("%6.1f");
axes2->SetZLabelFormat("%6.1f");
axes2->SetFlyModeToClosestTriad();
axes2->DrawXGridlinesOn();
axes2->DrawYGridlinesOn();
axes2->DrawZGridlinesOn();
ren2->AddViewProp(axes2.GetPointer());
renWin->Render();
int retVal = vtkRegressionTestImage( renWin.GetPointer() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
|
Revise test comments.
|
Revise test comments.
Change-Id: I8ac872057a26273b90d7b198db23f75a2be2672c
|
C++
|
bsd-3-clause
|
biddisco/VTK,collects/VTK,collects/VTK,msmolens/VTK,keithroe/vtkoptix,msmolens/VTK,collects/VTK,hendradarwin/VTK,candy7393/VTK,candy7393/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,sumedhasingla/VTK,hendradarwin/VTK,candy7393/VTK,msmolens/VTK,johnkit/vtk-dev,spthaolt/VTK,demarle/VTK,candy7393/VTK,keithroe/vtkoptix,jmerkow/VTK,collects/VTK,demarle/VTK,cjh1/VTK,berendkleinhaneveld/VTK,gram526/VTK,candy7393/VTK,keithroe/vtkoptix,hendradarwin/VTK,candy7393/VTK,johnkit/vtk-dev,demarle/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,cjh1/VTK,cjh1/VTK,mspark93/VTK,sankhesh/VTK,mspark93/VTK,sankhesh/VTK,cjh1/VTK,msmolens/VTK,SimVascular/VTK,berendkleinhaneveld/VTK,gram526/VTK,spthaolt/VTK,msmolens/VTK,demarle/VTK,aashish24/VTK-old,gram526/VTK,msmolens/VTK,jmerkow/VTK,jmerkow/VTK,SimVascular/VTK,jmerkow/VTK,spthaolt/VTK,SimVascular/VTK,berendkleinhaneveld/VTK,biddisco/VTK,keithroe/vtkoptix,aashish24/VTK-old,keithroe/vtkoptix,SimVascular/VTK,hendradarwin/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,demarle/VTK,ashray/VTK-EVM,gram526/VTK,cjh1/VTK,jmerkow/VTK,biddisco/VTK,biddisco/VTK,hendradarwin/VTK,daviddoria/PointGraphsPhase1,mspark93/VTK,SimVascular/VTK,sumedhasingla/VTK,collects/VTK,msmolens/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,aashish24/VTK-old,johnkit/vtk-dev,keithroe/vtkoptix,gram526/VTK,hendradarwin/VTK,gram526/VTK,jmerkow/VTK,biddisco/VTK,johnkit/vtk-dev,mspark93/VTK,aashish24/VTK-old,mspark93/VTK,jmerkow/VTK,daviddoria/PointGraphsPhase1,sumedhasingla/VTK,gram526/VTK,sumedhasingla/VTK,demarle/VTK,berendkleinhaneveld/VTK,sumedhasingla/VTK,sankhesh/VTK,aashish24/VTK-old,keithroe/vtkoptix,demarle/VTK,spthaolt/VTK,SimVascular/VTK,ashray/VTK-EVM,sankhesh/VTK,sumedhasingla/VTK,johnkit/vtk-dev,daviddoria/PointGraphsPhase1,sankhesh/VTK,biddisco/VTK,spthaolt/VTK,msmolens/VTK,sumedhasingla/VTK,spthaolt/VTK,demarle/VTK,biddisco/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,hendradarwin/VTK,mspark93/VTK,berendkleinhaneveld/VTK,mspark93/VTK,spthaolt/VTK,sumedhasingla/VTK,candy7393/VTK,collects/VTK,aashish24/VTK-old,mspark93/VTK,candy7393/VTK,ashray/VTK-EVM,SimVascular/VTK,cjh1/VTK,jmerkow/VTK,SimVascular/VTK,gram526/VTK,keithroe/vtkoptix,ashray/VTK-EVM,sankhesh/VTK,sankhesh/VTK,johnkit/vtk-dev,sankhesh/VTK
|
6da448d34273b0685c7d3a9dda72edd6f4bdd60b
|
crc_test.cpp
|
crc_test.cpp
|
#include "unit_tests.h"
#include "universal_crc.h"
//------------- tests for CRC_Type_helper -------------
int test_crc_type_helper_uint8(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (1-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (2-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (3-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (4-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (5-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (6-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (7-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (8-1)/8 >::value_type) != sizeof(uint8_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint16(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (9 -1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (10-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (11-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (12-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (13-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (14-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (15-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (16-1)/8 >::value_type) != sizeof(uint16_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint32(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (17-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (18-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (19-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (20-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (21-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (22-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (23-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (24-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (25-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (26-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (27-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (28-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (29-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (30-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (31-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (32-1)/8 >::value_type) != sizeof(uint32_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint64(struct test_info_t *test_info)
{
TEST_INIT;
//Template CRC_Type_helper default is uint64_t
if( sizeof(CRC_Type_helper<100>::value_type) != sizeof(uint64_t) )
return TEST_BROKEN;
return TEST_PASSED;
}
//------------- tests for Universal_CRC methods -------------
int test_universal_crc_name(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<1, 0, 0, true, true, 0> ucrc;
if( ucrc.name != "" )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_name_2(struct test_info_t *test_info)
{
TEST_INIT;
const char* name = "some_name";
Universal_CRC<1, 0, 0, true, true, 0> ucrc(name);
if( ucrc.name != name )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_bits(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<1, 0, 0, true, true, 0> ucrc_1;
if( ucrc_1.get_bits() != 1 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_poly(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<16, 1234, 0, true, true, 0> ucrc;
if( ucrc.get_poly() != 1234 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_init(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<16, 0, 1234, true, true, 0> ucrc;
if( ucrc.get_init() != 1234 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_xor_out(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<16, 0, 0, true, false, 4321> ucrc;
if( ucrc.get_xor_out() != 4321 )
return TEST_BROKEN;
return TEST_PASSED;
}
ptest_func tests[] =
{
//CRC_Type_Helper
test_crc_type_helper_uint8,
test_crc_type_helper_uint16,
test_crc_type_helper_uint32,
test_crc_type_helper_uint64,
//Universal_CRC methods
test_universal_crc_name,
test_universal_crc_name_2,
test_universal_crc_get_bits,
test_universal_crc_get_poly,
test_universal_crc_get_init,
test_universal_crc_get_xor_out
};
int main(void)
{
RUN_TESTS(tests);
return 0;
}
|
#include "unit_tests.h"
#include "universal_crc.h"
//------------- tests for CRC_Type_helper -------------
int test_crc_type_helper_uint8(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (1-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (2-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (3-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (4-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (5-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (6-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (7-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (8-1)/8 >::value_type) != sizeof(uint8_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint16(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (9 -1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (10-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (11-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (12-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (13-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (14-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (15-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (16-1)/8 >::value_type) != sizeof(uint16_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint32(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (17-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (18-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (19-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (20-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (21-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (22-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (23-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (24-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (25-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (26-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (27-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (28-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (29-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (30-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (31-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (32-1)/8 >::value_type) != sizeof(uint32_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint64(struct test_info_t *test_info)
{
TEST_INIT;
//Template CRC_Type_helper default is uint64_t
if( sizeof(CRC_Type_helper<100>::value_type) != sizeof(uint64_t) )
return TEST_BROKEN;
return TEST_PASSED;
}
//------------- tests for Universal_CRC methods -------------
int test_universal_crc_name(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<1, 0, 0, true, true, 0> ucrc;
if( ucrc.name != "" )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_name_2(struct test_info_t *test_info)
{
TEST_INIT;
const char* name = "some_name";
Universal_CRC<1, 0, 0, true, true, 0> ucrc(name);
if( ucrc.name != name )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_bits(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<1, 0, 0, true, true, 0> ucrc_1;
if( ucrc_1.get_bits() != 1 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_poly(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<16, 1234, 0, true, true, 0> ucrc;
if( ucrc.get_poly() != 1234 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_init(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<16, 0, 1234, true, true, 0> ucrc;
if( ucrc.get_init() != 1234 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_xor_out(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<16, 0, 0, true, false, 4321> ucrc;
if( ucrc.get_xor_out() != 4321 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_ref_in(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<16, 0, 0, true, false, 4321> ucrc;
if( ucrc.get_ref_in() != true )
return TEST_BROKEN;
return TEST_PASSED;
}
ptest_func tests[] =
{
//CRC_Type_Helper
test_crc_type_helper_uint8,
test_crc_type_helper_uint16,
test_crc_type_helper_uint32,
test_crc_type_helper_uint64,
//Universal_CRC methods
test_universal_crc_name,
test_universal_crc_name_2,
test_universal_crc_get_bits,
test_universal_crc_get_poly,
test_universal_crc_get_init,
test_universal_crc_get_xor_out,
test_universal_crc_get_ref_in
};
int main(void)
{
RUN_TESTS(tests);
return 0;
}
|
add test for get_ref_in()
|
add test for get_ref_in()
|
C++
|
bsd-3-clause
|
KoynovStas/CRC_CPP_Template,KoynovStas/CRC_CPP_Template
|
f327b0147f279eb2582762620632d7941c1f20e7
|
crc_test.cpp
|
crc_test.cpp
|
#include "unit_tests.h"
#include "crc_t.h"
//------------- tests for CRC_t methods -------------
int test_crc_t_name(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc;
if( crc.name != "CRC-32" )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_name_2(struct test_info_t *test_info)
{
TEST_INIT;
const char* name = "some_name";
CRC_t crc(name);
if( crc.name != name )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_bits(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_bits() != 1 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_poly(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 123, 0, true, true, 0);
if( crc.get_poly() != 123 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_init(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 1234, true, true, 0);
if( crc.get_init() != 1234 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_xor_out(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 1000);
if( crc.get_xor_out() != 1000 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_ref_in(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_ref_in() != true )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_ref_out(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_ref_out() != true )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_set_bits(struct test_info_t *test_info)
{
TEST_INIT;
int i, res;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_bits() != 1 )
return TEST_BROKEN;
if( crc.set_bits(0) != -1 )
return TEST_BROKEN;
// 1..64
for( i = 1; i <= 64; ++i)
{
res = crc.set_bits(i);
if( res != 0 )
return TEST_BROKEN;
if( crc.get_bits() != i )
return TEST_BROKEN;
}
//more 64
for( i = 65; i <= 256; ++i)
{
if( crc.set_bits(i) != -1 )
return TEST_BROKEN;
}
return TEST_PASSED;
}
//------------- tests for Calculate CRC -------------
//width=3 poly=0x3 init=0x7 refin=true refout=true xorout=0x0 check=0x6 name="CRC-3/ROHC"
int test_crc3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(3, 0x3, 0x7, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x6 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc4(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(4, 0x3, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xE )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=4 poly=0x3 init=0x0 refin=true refout=true xorout=0x0 check=0x7 name="CRC-4/ITU"
int test_crc4_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(4, 0x3, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x7 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x09 init=0x09 refin=false refout=false xorout=0x00 check=0x00 name="CRC-5/EPC"
int test_crc5(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x09, 0x09, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x0 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x15 init=0x00 refin=true refout=true xorout=0x00 check=0x07 name="CRC-5/ITU"
int test_crc5_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x15, 0x00, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x07 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x05 init=0x1f refin=true refout=true xorout=0x1f check=0x19 name="CRC-5/USB"
int test_crc5_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x05, 0x1f, true, true, 0x1f);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x19 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x27 init=0x3f refin=false refout=false xorout=0x00 check=0x0d name="CRC-6/CDMA2000-A"
int test_crc6(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x27, 0x3f, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x0d )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x07 init=0x3f refin=false refout=false xorout=0x00 check=0x3b name="CRC-6/CDMA2000-B"
int test_crc6_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x07, 0x3f, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x3b )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x19 init=0x00 refin=true refout=true xorout=0x00 check=0x26 name="CRC-6/DARC"
int test_crc6_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x19, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x26 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x03 init=0x00 refin=true refout=true xorout=0x00 check=0x06 name="CRC-6/ITU"
int test_crc6_4(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x03, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x06 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=7 poly=0x09 init=0x00 refin=false refout=false xorout=0x00 check=0x75 name="CRC-7"
int test_crc7(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(7, 0x09, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x75 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=7 poly=0x4f init=0x7f refin=true refout=true xorout=0x00 check=0x53 name="CRC-7/ROHC"
int test_crc7_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(7, 0x4f, 0x7f, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x53 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc8(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x31, 0xFF, false, false, 0x00);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xF7 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=8 poly=0x07 init=0x00 refin=false refout=false xorout=0x00 check=0xf4 name="CRC-8"
int test_crc8_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x07, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xF4 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=8 poly=0x9b init=0xff refin=false refout=false xorout=0x00 check=0xda name="CRC-8/CDMA2000"
int test_crc8_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x9b, 0xff, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xDA )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=8 poly=0x39 init=0x00 refin=true refout=true xorout=0x00 check=0x15 name="CRC-8/DARC"
int test_crc8_4(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x39, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x15 )
return TEST_BROKEN;
return TEST_PASSED;
}
ptest_func tests[] =
{
//CRC_t methods
test_crc_t_name,
test_crc_t_name_2,
test_crc_t_get_bits,
test_crc_t_get_poly,
test_crc_t_get_init,
test_crc_t_get_xor_out,
test_crc_t_get_ref_in,
test_crc_t_get_ref_out,
test_crc_t_set_bits,
//CRC
test_crc3,
test_crc4,
test_crc4_2,
test_crc5,
test_crc5_2,
test_crc5_3,
test_crc6,
test_crc6_2,
test_crc6_3,
test_crc6_4,
test_crc7,
test_crc7_2,
test_crc8,
test_crc8_2,
test_crc8_3,
test_crc8_4,
};
int main(void)
{
RUN_TESTS(tests);
return 0;
}
|
#include "unit_tests.h"
#include "crc_t.h"
//------------- tests for CRC_t methods -------------
int test_crc_t_name(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc;
if( crc.name != "CRC-32" )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_name_2(struct test_info_t *test_info)
{
TEST_INIT;
const char* name = "some_name";
CRC_t crc(name);
if( crc.name != name )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_bits(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_bits() != 1 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_poly(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 123, 0, true, true, 0);
if( crc.get_poly() != 123 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_init(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 1234, true, true, 0);
if( crc.get_init() != 1234 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_xor_out(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 1000);
if( crc.get_xor_out() != 1000 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_ref_in(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_ref_in() != true )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_ref_out(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_ref_out() != true )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_set_bits(struct test_info_t *test_info)
{
TEST_INIT;
int i, res;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_bits() != 1 )
return TEST_BROKEN;
if( crc.set_bits(0) != -1 )
return TEST_BROKEN;
// 1..64
for( i = 1; i <= 64; ++i)
{
res = crc.set_bits(i);
if( res != 0 )
return TEST_BROKEN;
if( crc.get_bits() != i )
return TEST_BROKEN;
}
//more 64
for( i = 65; i <= 256; ++i)
{
if( crc.set_bits(i) != -1 )
return TEST_BROKEN;
}
return TEST_PASSED;
}
//------------- tests for Calculate CRC -------------
//width=3 poly=0x3 init=0x7 refin=true refout=true xorout=0x0 check=0x6 name="CRC-3/ROHC"
int test_crc3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(3, 0x3, 0x7, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x6 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc4(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(4, 0x3, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xE )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=4 poly=0x3 init=0x0 refin=true refout=true xorout=0x0 check=0x7 name="CRC-4/ITU"
int test_crc4_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(4, 0x3, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x7 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x09 init=0x09 refin=false refout=false xorout=0x00 check=0x00 name="CRC-5/EPC"
int test_crc5(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x09, 0x09, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x0 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x15 init=0x00 refin=true refout=true xorout=0x00 check=0x07 name="CRC-5/ITU"
int test_crc5_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x15, 0x00, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x07 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x05 init=0x1f refin=true refout=true xorout=0x1f check=0x19 name="CRC-5/USB"
int test_crc5_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x05, 0x1f, true, true, 0x1f);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x19 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x27 init=0x3f refin=false refout=false xorout=0x00 check=0x0d name="CRC-6/CDMA2000-A"
int test_crc6(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x27, 0x3f, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x0d )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x07 init=0x3f refin=false refout=false xorout=0x00 check=0x3b name="CRC-6/CDMA2000-B"
int test_crc6_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x07, 0x3f, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x3b )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x19 init=0x00 refin=true refout=true xorout=0x00 check=0x26 name="CRC-6/DARC"
int test_crc6_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x19, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x26 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x03 init=0x00 refin=true refout=true xorout=0x00 check=0x06 name="CRC-6/ITU"
int test_crc6_4(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x03, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x06 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=7 poly=0x09 init=0x00 refin=false refout=false xorout=0x00 check=0x75 name="CRC-7"
int test_crc7(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(7, 0x09, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x75 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=7 poly=0x4f init=0x7f refin=true refout=true xorout=0x00 check=0x53 name="CRC-7/ROHC"
int test_crc7_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(7, 0x4f, 0x7f, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x53 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc8(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x31, 0xFF, false, false, 0x00);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xF7 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=8 poly=0x07 init=0x00 refin=false refout=false xorout=0x00 check=0xf4 name="CRC-8"
int test_crc8_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x07, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xF4 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=8 poly=0x9b init=0xff refin=false refout=false xorout=0x00 check=0xda name="CRC-8/CDMA2000"
int test_crc8_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x9b, 0xff, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xDA )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=8 poly=0x39 init=0x00 refin=true refout=true xorout=0x00 check=0x15 name="CRC-8/DARC"
int test_crc8_4(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x39, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x15 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=8 poly=0xd5 init=0x00 refin=false refout=false xorout=0x00 check=0xbc name="CRC-8/DVB-S2"
int test_crc8_5(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0xd5, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xBC )
return TEST_BROKEN;
return TEST_PASSED;
}
ptest_func tests[] =
{
//CRC_t methods
test_crc_t_name,
test_crc_t_name_2,
test_crc_t_get_bits,
test_crc_t_get_poly,
test_crc_t_get_init,
test_crc_t_get_xor_out,
test_crc_t_get_ref_in,
test_crc_t_get_ref_out,
test_crc_t_set_bits,
//CRC
test_crc3,
test_crc4,
test_crc4_2,
test_crc5,
test_crc5_2,
test_crc5_3,
test_crc6,
test_crc6_2,
test_crc6_3,
test_crc6_4,
test_crc7,
test_crc7_2,
test_crc8,
test_crc8_2,
test_crc8_3,
test_crc8_4,
test_crc8_5,
};
int main(void)
{
RUN_TESTS(tests);
return 0;
}
|
add test to calculate the CRC-8/DVB-S2
|
add test to calculate the CRC-8/DVB-S2
|
C++
|
bsd-3-clause
|
KoynovStas/CRC_CPP_Class,KoynovStas/CRC_CPP_Class
|
ed67f908296f1e57b8cd3ac09351190a8094c527
|
Bubble-Sort/BS.cpp
|
Bubble-Sort/BS.cpp
|
#include <iostream>
#include <array>
using namespace std;
/* // code below is learning `dangling pointer`
int* bubbleSort(){
int * arr = new int[3]; // avoid dangling pointer
for (int i =0 ; i <3; i++) arr[i] = i+1;
return arr;
}
int main(){
int* arr = bubbleSort();
for (int i = 0; i <3; i++){
cout << *(arr+i) << endl;
}
delete [] arr;
return 0;
}
*/
struct node {
int data;
node * next;
};
class list {
private:
node * head, * tail;
node * createnode(int i){
node * temp = new node;
temp->data = i;
temp->next = NULL;
return temp;
};
public:
list() { // construct function
head = NULL;
}
list(int i,...) {
//https://www.cprogramming.com/tutorial/lesson17.html
va_list args;
va_start (args,i);
int s = sizeof(args)/sizeof(long); // it should be long type
node * first = new node;
first->data = i;
first->next = NULL;
head = first;
node * temp = head;
for (int ind = 0; ind < s; ind++) {
temp->next = createnode(va_arg(args,int));
temp = temp->next;
};
};
int show() {
node * temp = this->head;
do{
cout << temp->data << endl;
temp = temp->next;
}while(temp != NULL);
};
};
int main(){
list a = list(1,2,3,4);
a.show();
}
|
#include <iostream>
#include <array>
using namespace std;
/* // code below is learning `dangling pointer`
int* bubbleSort(){
int * arr = new int[3]; // avoid dangling pointer
for (int i =0 ; i <3; i++) arr[i] = i+1;
return arr;
}
int main(){
int* arr = bubbleSort();
for (int i = 0; i <3; i++){
cout << *(arr+i) << endl;
}
delete [] arr;
return 0;
}
*/
struct node {
int data;
node * next;
node * last;
};
class list {
private:
node * createnode(int i){
node * temp = new node;
temp->data = i;
temp->next = NULL;
temp->last = NULL;
return temp;
};
public:
node * head, * tail;
list() { // construct function
head = NULL;
}
list(int i,...) {
//https://www.cprogramming.com/tutorial/lesson17.html
va_list args;
va_start (args,i);
int s = sizeof(args)/sizeof(int);
node * first = createnode(i);
head = first;
node * temp = head;
for (int ind = 0; ind < 5; ind++) { // need to solve this problems
int thisarg = va_arg(args,int);
if (thisarg != NULL){
temp->next = createnode(thisarg);
node * buffer = temp;
temp = temp->next;
temp->last = buffer;
};
};
temp->next = NULL;
};
int show() {
node * temp = this->head;
do{
cout << temp->data << endl;
temp = temp->next;
}while(temp != NULL);
};
};
int bubbleSort(list * lis) {
int flag = 0;
node * temp = lis->head;
do {
flag = 0;
while(temp->next != NULL){
if (temp->next->data < temp->data) {
flag = 1;
node * buffer = temp->next->next;
temp->next->next = temp;
temp->next->last = temp->last;
temp->last->next = temp->next;
temp->last = temp->next;
temp->next = buffer;
}else{
temp = temp->next;
};
};
temp = lis->head;
}while(flag != 0);
}
int main(){
//list a = list(1,2,3,4);
//a.show();
list b = list(2,3,44,5,33,23);
b.show();
bubbleSort(&b);
b.show();
}
|
fix and finish
|
fix and finish
|
C++
|
apache-2.0
|
ccqpein/Arithmetic-Exercises,ccqpein/Arithmetic-Exercises,ccqpein/Arithmetic-Exercises,ccqpein/Arithmetic-Exercises,ccqpein/Arithmetic-Exercises,ccqpein/Arithmetic-Exercises,ccqpein/Arithmetic-Exercises
|
2e37a86957c222972811928696f874bc1284cbbf
|
src/cert/x509/x509self.cpp
|
src/cert/x509/x509self.cpp
|
/*
* PKCS #10/Self Signed Cert Creation
* (C) 1999-2008 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/x509self.h>
#include <botan/x509_ext.h>
#include <botan/x509_ca.h>
#include <botan/der_enc.h>
#include <botan/oids.h>
#include <botan/pipe.h>
#include <memory>
namespace Botan {
namespace {
/*
* Shared setup for self-signed items
*/
MemoryVector<byte> shared_setup(const X509_Cert_Options& opts,
const Private_Key& key)
{
opts.sanity_check();
Pipe key_encoder;
key_encoder.start_msg();
X509::encode(key, key_encoder, RAW_BER);
key_encoder.end_msg();
return key_encoder.read_all();
}
/*
* Load information from the X509_Cert_Options
*/
void load_info(const X509_Cert_Options& opts, X509_DN& subject_dn,
AlternativeName& subject_alt)
{
subject_dn.add_attribute("X520.CommonName", opts.common_name);
subject_dn.add_attribute("X520.Country", opts.country);
subject_dn.add_attribute("X520.State", opts.state);
subject_dn.add_attribute("X520.Locality", opts.locality);
subject_dn.add_attribute("X520.Organization", opts.organization);
subject_dn.add_attribute("X520.OrganizationalUnit", opts.org_unit);
subject_dn.add_attribute("X520.SerialNumber", opts.serial_number);
subject_alt = AlternativeName(opts.email, opts.uri, opts.dns, opts.ip);
subject_alt.add_othername(OIDS::lookup("PKIX.XMPPAddr"),
opts.xmpp, UTF8_STRING);
}
}
namespace X509 {
/*
* Create a new self-signed X.509 certificate
*/
X509_Certificate create_self_signed_cert(const X509_Cert_Options& opts,
const Private_Key& key,
const std::string& hash_fn,
RandomNumberGenerator& rng)
{
AlgorithmIdentifier sig_algo;
X509_DN subject_dn;
AlternativeName subject_alt;
MemoryVector<byte> pub_key = shared_setup(opts, key);
std::auto_ptr<PK_Signer> signer(choose_sig_format(key, hash_fn, sig_algo));
load_info(opts, subject_dn, subject_alt);
Key_Constraints constraints;
if(opts.is_CA)
constraints = Key_Constraints(KEY_CERT_SIGN | CRL_SIGN);
else
constraints = find_constraints(key, opts.constraints);
Extensions extensions;
extensions.add(
new Cert_Extension::Basic_Constraints(opts.is_CA, opts.path_limit),
true);
extensions.add(new Cert_Extension::Key_Usage(constraints), true);
extensions.add(new Cert_Extension::Subject_Key_ID(pub_key));
extensions.add(
new Cert_Extension::Subject_Alternative_Name(subject_alt));
extensions.add(
new Cert_Extension::Extended_Key_Usage(opts.ex_constraints));
return X509_CA::make_cert(signer.get(), rng, sig_algo, pub_key,
opts.start, opts.end,
subject_dn, subject_dn,
extensions);
}
/*
* Create a PKCS #10 certificate request
*/
PKCS10_Request create_cert_req(const X509_Cert_Options& opts,
const Private_Key& key,
const std::string& hash_fn,
RandomNumberGenerator& rng)
{
AlgorithmIdentifier sig_algo;
X509_DN subject_dn;
AlternativeName subject_alt;
MemoryVector<byte> pub_key = shared_setup(opts, key);
std::auto_ptr<PK_Signer> signer(choose_sig_format(key, hash_fn, sig_algo));
load_info(opts, subject_dn, subject_alt);
const u32bit PKCS10_VERSION = 0;
Extensions extensions;
extensions.add(
new Cert_Extension::Basic_Constraints(opts.is_CA, opts.path_limit));
extensions.add(
new Cert_Extension::Key_Usage(
opts.is_CA ? Key_Constraints(KEY_CERT_SIGN | CRL_SIGN) :
find_constraints(key, opts.constraints)
)
);
extensions.add(
new Cert_Extension::Extended_Key_Usage(opts.ex_constraints));
extensions.add(
new Cert_Extension::Subject_Alternative_Name(subject_alt));
DER_Encoder tbs_req;
tbs_req.start_cons(SEQUENCE)
.encode(PKCS10_VERSION)
.encode(subject_dn)
.raw_bytes(pub_key)
.start_explicit(0);
if(opts.challenge != "")
{
ASN1_String challenge(opts.challenge, DIRECTORY_STRING);
tbs_req.encode(
Attribute("PKCS9.ChallengePassword",
DER_Encoder().encode(challenge).get_contents()
)
);
}
tbs_req.encode(
Attribute("PKCS9.ExtensionRequest",
DER_Encoder()
.start_cons(SEQUENCE)
.encode(extensions)
.end_cons()
.get_contents()
)
)
.end_explicit()
.end_cons();
DataSource_Memory source(
X509_Object::make_signed(signer.get(),
rng,
sig_algo,
tbs_req.get_contents())
);
return PKCS10_Request(source);
}
}
}
|
/*
* PKCS #10/Self Signed Cert Creation
* (C) 1999-2008 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/x509self.h>
#include <botan/x509_ext.h>
#include <botan/x509_ca.h>
#include <botan/der_enc.h>
#include <botan/oids.h>
#include <botan/pipe.h>
#include <memory>
namespace Botan {
namespace {
/*
* Load information from the X509_Cert_Options
*/
void load_info(const X509_Cert_Options& opts, X509_DN& subject_dn,
AlternativeName& subject_alt)
{
subject_dn.add_attribute("X520.CommonName", opts.common_name);
subject_dn.add_attribute("X520.Country", opts.country);
subject_dn.add_attribute("X520.State", opts.state);
subject_dn.add_attribute("X520.Locality", opts.locality);
subject_dn.add_attribute("X520.Organization", opts.organization);
subject_dn.add_attribute("X520.OrganizationalUnit", opts.org_unit);
subject_dn.add_attribute("X520.SerialNumber", opts.serial_number);
subject_alt = AlternativeName(opts.email, opts.uri, opts.dns, opts.ip);
subject_alt.add_othername(OIDS::lookup("PKIX.XMPPAddr"),
opts.xmpp, UTF8_STRING);
}
}
namespace X509 {
/*
* Create a new self-signed X.509 certificate
*/
X509_Certificate create_self_signed_cert(const X509_Cert_Options& opts,
const Private_Key& key,
const std::string& hash_fn,
RandomNumberGenerator& rng)
{
AlgorithmIdentifier sig_algo;
X509_DN subject_dn;
AlternativeName subject_alt;
opts.sanity_check();
MemoryVector<byte> pub_key = X509::BER_encode(key);
std::auto_ptr<PK_Signer> signer(choose_sig_format(key, hash_fn, sig_algo));
load_info(opts, subject_dn, subject_alt);
Key_Constraints constraints;
if(opts.is_CA)
constraints = Key_Constraints(KEY_CERT_SIGN | CRL_SIGN);
else
constraints = find_constraints(key, opts.constraints);
Extensions extensions;
extensions.add(
new Cert_Extension::Basic_Constraints(opts.is_CA, opts.path_limit),
true);
extensions.add(new Cert_Extension::Key_Usage(constraints), true);
extensions.add(new Cert_Extension::Subject_Key_ID(pub_key));
extensions.add(
new Cert_Extension::Subject_Alternative_Name(subject_alt));
extensions.add(
new Cert_Extension::Extended_Key_Usage(opts.ex_constraints));
return X509_CA::make_cert(signer.get(), rng, sig_algo, pub_key,
opts.start, opts.end,
subject_dn, subject_dn,
extensions);
}
/*
* Create a PKCS #10 certificate request
*/
PKCS10_Request create_cert_req(const X509_Cert_Options& opts,
const Private_Key& key,
const std::string& hash_fn,
RandomNumberGenerator& rng)
{
AlgorithmIdentifier sig_algo;
X509_DN subject_dn;
AlternativeName subject_alt;
opts.sanity_check();
MemoryVector<byte> pub_key = X509::BER_encode(key);
std::auto_ptr<PK_Signer> signer(choose_sig_format(key, hash_fn, sig_algo));
load_info(opts, subject_dn, subject_alt);
const u32bit PKCS10_VERSION = 0;
Extensions extensions;
extensions.add(
new Cert_Extension::Basic_Constraints(opts.is_CA, opts.path_limit));
extensions.add(
new Cert_Extension::Key_Usage(
opts.is_CA ? Key_Constraints(KEY_CERT_SIGN | CRL_SIGN) :
find_constraints(key, opts.constraints)
)
);
extensions.add(
new Cert_Extension::Extended_Key_Usage(opts.ex_constraints));
extensions.add(
new Cert_Extension::Subject_Alternative_Name(subject_alt));
DER_Encoder tbs_req;
tbs_req.start_cons(SEQUENCE)
.encode(PKCS10_VERSION)
.encode(subject_dn)
.raw_bytes(pub_key)
.start_explicit(0);
if(opts.challenge != "")
{
ASN1_String challenge(opts.challenge, DIRECTORY_STRING);
tbs_req.encode(
Attribute("PKCS9.ChallengePassword",
DER_Encoder().encode(challenge).get_contents()
)
);
}
tbs_req.encode(
Attribute("PKCS9.ExtensionRequest",
DER_Encoder()
.start_cons(SEQUENCE)
.encode(extensions)
.end_cons()
.get_contents()
)
)
.end_explicit()
.end_cons();
DataSource_Memory source(
X509_Object::make_signed(signer.get(),
rng,
sig_algo,
tbs_req.get_contents())
);
return PKCS10_Request(source);
}
}
}
|
Use X509::BER_encode. Saves 12 lines. Nice
|
Use X509::BER_encode. Saves 12 lines. Nice
|
C++
|
bsd-2-clause
|
randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,randombit/botan,webmaster128/botan,randombit/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,webmaster128/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan
|
fb2e9b95f4923521f874f8ea0ea6a355e909dc52
|
src/mem/packet.cc
|
src/mem/packet.cc
|
/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Steve Reinhardt
*/
/**
* @file
* Definition of the Packet Class, a packet is a transaction occuring
* between a single level of the memory heirarchy (ie L1->L2).
*/
#include <iostream>
#include <cstring>
#include "base/cprintf.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "mem/packet.hh"
using namespace std;
// The one downside to bitsets is that static initializers can get ugly.
#define SET1(a1) (1 << (a1))
#define SET2(a1, a2) (SET1(a1) | SET1(a2))
#define SET3(a1, a2, a3) (SET2(a1, a2) | SET1(a3))
#define SET4(a1, a2, a3, a4) (SET3(a1, a2, a3) | SET1(a4))
#define SET5(a1, a2, a3, a4, a5) (SET4(a1, a2, a3, a4) | SET1(a5))
#define SET6(a1, a2, a3, a4, a5, a6) (SET5(a1, a2, a3, a4, a5) | SET1(a6))
const MemCmd::CommandInfo
MemCmd::commandInfo[] =
{
/* InvalidCmd */
{ 0, InvalidCmd, "InvalidCmd" },
/* ReadReq */
{ SET3(IsRead, IsRequest, NeedsResponse), ReadResp, "ReadReq" },
/* ReadResp */
{ SET3(IsRead, IsResponse, HasData), InvalidCmd, "ReadResp" },
/* ReadRespWithInvalidate */
{ SET4(IsRead, IsResponse, HasData, IsInvalidate),
InvalidCmd, "ReadRespWithInvalidate" },
/* WriteReq */
{ SET5(IsWrite, NeedsExclusive, IsRequest, NeedsResponse, HasData),
WriteResp, "WriteReq" },
/* WriteResp */
{ SET3(IsWrite, NeedsExclusive, IsResponse), InvalidCmd, "WriteResp" },
/* Writeback */
{ SET4(IsWrite, NeedsExclusive, IsRequest, HasData),
InvalidCmd, "Writeback" },
/* SoftPFReq */
{ SET4(IsRead, IsRequest, IsSWPrefetch, NeedsResponse),
SoftPFResp, "SoftPFReq" },
/* HardPFReq */
{ SET4(IsRead, IsRequest, IsHWPrefetch, NeedsResponse),
HardPFResp, "HardPFReq" },
/* SoftPFResp */
{ SET4(IsRead, IsResponse, IsSWPrefetch, HasData),
InvalidCmd, "SoftPFResp" },
/* HardPFResp */
{ SET4(IsRead, IsResponse, IsHWPrefetch, HasData),
InvalidCmd, "HardPFResp" },
/* WriteInvalidateReq */
{ SET6(IsWrite, NeedsExclusive, IsInvalidate,
IsRequest, HasData, NeedsResponse),
WriteInvalidateResp, "WriteInvalidateReq" },
/* WriteInvalidateResp */
{ SET3(IsWrite, NeedsExclusive, IsResponse),
InvalidCmd, "WriteInvalidateResp" },
/* UpgradeReq */
{ SET4(IsInvalidate, NeedsExclusive, IsRequest, NeedsResponse),
UpgradeResp, "UpgradeReq" },
/* UpgradeResp */
{ SET2(NeedsExclusive, IsResponse),
InvalidCmd, "UpgradeResp" },
/* ReadExReq */
{ SET5(IsRead, NeedsExclusive, IsInvalidate, IsRequest, NeedsResponse),
ReadExResp, "ReadExReq" },
/* ReadExResp */
{ SET4(IsRead, NeedsExclusive, IsResponse, HasData),
InvalidCmd, "ReadExResp" },
/* LoadLockedReq: note that we use plain ReadResp as response, so that
* we can also use ReadRespWithInvalidate when needed */
{ SET4(IsRead, IsLocked, IsRequest, NeedsResponse),
ReadResp, "LoadLockedReq" },
/* StoreCondReq */
{ SET6(IsWrite, NeedsExclusive, IsLocked,
IsRequest, NeedsResponse, HasData),
StoreCondResp, "StoreCondReq" },
/* StoreCondResp */
{ SET4(IsWrite, NeedsExclusive, IsLocked, IsResponse),
InvalidCmd, "StoreCondResp" },
/* SwapReq -- for Swap ldstub type operations */
{ SET6(IsRead, IsWrite, NeedsExclusive, IsRequest, HasData, NeedsResponse),
SwapResp, "SwapReq" },
/* SwapResp -- for Swap ldstub type operations */
{ SET5(IsRead, IsWrite, NeedsExclusive, IsResponse, HasData),
InvalidCmd, "SwapResp" },
/* IntReq -- for interrupts */
{ SET4(IsWrite, IsRequest, NeedsResponse, HasData),
MessageReq, "MessageReq" },
/* IntResp -- for interrupts */
{ SET2(IsWrite, IsResponse), MessageResp, "MessageResp" },
/* NetworkNackError -- nacked at network layer (not by protocol) */
{ SET2(IsResponse, IsError), InvalidCmd, "NetworkNackError" },
/* InvalidDestError -- packet dest field invalid */
{ SET2(IsResponse, IsError), InvalidCmd, "InvalidDestError" },
/* BadAddressError -- memory address invalid */
{ SET2(IsResponse, IsError), InvalidCmd, "BadAddressError" },
/* PrintReq */
{ SET2(IsRequest, IsPrint), InvalidCmd, "PrintReq" }
};
bool
Packet::checkFunctional(Printable *obj, Addr addr, int size, uint8_t *data)
{
Addr func_start = getAddr();
Addr func_end = getAddr() + getSize() - 1;
Addr val_start = addr;
Addr val_end = val_start + size - 1;
if (func_start > val_end || val_start > func_end) {
// no intersection
return false;
}
// check print first since it doesn't require data
if (isPrint()) {
dynamic_cast<PrintReqState*>(senderState)->printObj(obj);
return false;
}
// if there's no data, there's no need to look further
if (!data) {
return false;
}
// offset of functional request into supplied value (could be
// negative if partial overlap)
int offset = func_start - val_start;
if (isRead()) {
if (func_start >= val_start && func_end <= val_end) {
allocate();
memcpy(getPtr<uint8_t>(), data + offset, getSize());
makeResponse();
return true;
} else {
// In this case the timing packet only partially satisfies
// the request, so we would need more information to make
// this work. Like bytes valid in the packet or
// something, so the request could continue and get this
// bit of possibly newer data along with the older data
// not written to yet.
panic("Memory value only partially satisfies the functional "
"request. Now what?");
}
} else if (isWrite()) {
if (offset >= 0) {
memcpy(data + offset, getPtr<uint8_t>(),
(min(func_end, val_end) - func_start) + 1);
} else {
// val_start > func_start
memcpy(data, getPtr<uint8_t>() - offset,
(min(func_end, val_end) - val_start) + 1);
}
} else {
panic("Don't know how to handle command %s\n", cmdString());
}
// keep going with request by default
return false;
}
void
Packet::print(ostream &o, const int verbosity, const string &prefix) const
{
ccprintf(o, "%s[%x:%x] %s\n", prefix,
getAddr(), getAddr() + getSize() - 1, cmdString());
}
Packet::PrintReqState::PrintReqState(ostream &_os, int _verbosity)
: curPrefixPtr(new string("")), os(_os), verbosity(_verbosity)
{
labelStack.push_back(LabelStackEntry("", curPrefixPtr));
}
Packet::PrintReqState::~PrintReqState()
{
labelStack.pop_back();
assert(labelStack.empty());
delete curPrefixPtr;
}
Packet::PrintReqState::
LabelStackEntry::LabelStackEntry(const string &_label, string *_prefix)
: label(_label), prefix(_prefix), labelPrinted(false)
{
}
void
Packet::PrintReqState::pushLabel(const string &lbl, const string &prefix)
{
labelStack.push_back(LabelStackEntry(lbl, curPrefixPtr));
curPrefixPtr = new string(*curPrefixPtr);
*curPrefixPtr += prefix;
}
void
Packet::PrintReqState::popLabel()
{
delete curPrefixPtr;
curPrefixPtr = labelStack.back().prefix;
labelStack.pop_back();
assert(!labelStack.empty());
}
void
Packet::PrintReqState::printLabels()
{
if (!labelStack.back().labelPrinted) {
LabelStack::iterator i = labelStack.begin();
LabelStack::iterator end = labelStack.end();
while (i != end) {
if (!i->labelPrinted) {
ccprintf(os, "%s%s\n", *(i->prefix), i->label);
i->labelPrinted = true;
}
i++;
}
}
}
void
Packet::PrintReqState::printObj(Printable *obj)
{
printLabels();
obj->print(os, verbosity, curPrefix());
}
|
/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Steve Reinhardt
*/
/**
* @file
* Definition of the Packet Class, a packet is a transaction occuring
* between a single level of the memory heirarchy (ie L1->L2).
*/
#include <iostream>
#include <cstring>
#include "base/cprintf.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "mem/packet.hh"
using namespace std;
// The one downside to bitsets is that static initializers can get ugly.
#define SET1(a1) (1 << (a1))
#define SET2(a1, a2) (SET1(a1) | SET1(a2))
#define SET3(a1, a2, a3) (SET2(a1, a2) | SET1(a3))
#define SET4(a1, a2, a3, a4) (SET3(a1, a2, a3) | SET1(a4))
#define SET5(a1, a2, a3, a4, a5) (SET4(a1, a2, a3, a4) | SET1(a5))
#define SET6(a1, a2, a3, a4, a5, a6) (SET5(a1, a2, a3, a4, a5) | SET1(a6))
const MemCmd::CommandInfo
MemCmd::commandInfo[] =
{
/* InvalidCmd */
{ 0, InvalidCmd, "InvalidCmd" },
/* ReadReq */
{ SET3(IsRead, IsRequest, NeedsResponse), ReadResp, "ReadReq" },
/* ReadResp */
{ SET3(IsRead, IsResponse, HasData), InvalidCmd, "ReadResp" },
/* ReadRespWithInvalidate */
{ SET4(IsRead, IsResponse, HasData, IsInvalidate),
InvalidCmd, "ReadRespWithInvalidate" },
/* WriteReq */
{ SET5(IsWrite, NeedsExclusive, IsRequest, NeedsResponse, HasData),
WriteResp, "WriteReq" },
/* WriteResp */
{ SET3(IsWrite, NeedsExclusive, IsResponse), InvalidCmd, "WriteResp" },
/* Writeback */
{ SET4(IsWrite, NeedsExclusive, IsRequest, HasData),
InvalidCmd, "Writeback" },
/* SoftPFReq */
{ SET4(IsRead, IsRequest, IsSWPrefetch, NeedsResponse),
SoftPFResp, "SoftPFReq" },
/* HardPFReq */
{ SET4(IsRead, IsRequest, IsHWPrefetch, NeedsResponse),
HardPFResp, "HardPFReq" },
/* SoftPFResp */
{ SET4(IsRead, IsResponse, IsSWPrefetch, HasData),
InvalidCmd, "SoftPFResp" },
/* HardPFResp */
{ SET4(IsRead, IsResponse, IsHWPrefetch, HasData),
InvalidCmd, "HardPFResp" },
/* WriteInvalidateReq */
{ SET6(IsWrite, NeedsExclusive, IsInvalidate,
IsRequest, HasData, NeedsResponse),
WriteInvalidateResp, "WriteInvalidateReq" },
/* WriteInvalidateResp */
{ SET3(IsWrite, NeedsExclusive, IsResponse),
InvalidCmd, "WriteInvalidateResp" },
/* UpgradeReq */
{ SET4(IsInvalidate, NeedsExclusive, IsRequest, NeedsResponse),
UpgradeResp, "UpgradeReq" },
/* UpgradeResp */
{ SET2(NeedsExclusive, IsResponse),
InvalidCmd, "UpgradeResp" },
/* ReadExReq */
{ SET5(IsRead, NeedsExclusive, IsInvalidate, IsRequest, NeedsResponse),
ReadExResp, "ReadExReq" },
/* ReadExResp */
{ SET4(IsRead, NeedsExclusive, IsResponse, HasData),
InvalidCmd, "ReadExResp" },
/* LoadLockedReq: note that we use plain ReadResp as response, so that
* we can also use ReadRespWithInvalidate when needed */
{ SET4(IsRead, IsLocked, IsRequest, NeedsResponse),
ReadResp, "LoadLockedReq" },
/* StoreCondReq */
{ SET6(IsWrite, NeedsExclusive, IsLocked,
IsRequest, NeedsResponse, HasData),
StoreCondResp, "StoreCondReq" },
/* StoreCondResp */
{ SET4(IsWrite, NeedsExclusive, IsLocked, IsResponse),
InvalidCmd, "StoreCondResp" },
/* SwapReq -- for Swap ldstub type operations */
{ SET6(IsRead, IsWrite, NeedsExclusive, IsRequest, HasData, NeedsResponse),
SwapResp, "SwapReq" },
/* SwapResp -- for Swap ldstub type operations */
{ SET5(IsRead, IsWrite, NeedsExclusive, IsResponse, HasData),
InvalidCmd, "SwapResp" },
/* IntReq -- for interrupts */
{ SET4(IsWrite, IsRequest, NeedsResponse, HasData),
MessageResp, "MessageReq" },
/* IntResp -- for interrupts */
{ SET2(IsWrite, IsResponse), InvalidCmd, "MessageResp" },
/* NetworkNackError -- nacked at network layer (not by protocol) */
{ SET2(IsResponse, IsError), InvalidCmd, "NetworkNackError" },
/* InvalidDestError -- packet dest field invalid */
{ SET2(IsResponse, IsError), InvalidCmd, "InvalidDestError" },
/* BadAddressError -- memory address invalid */
{ SET2(IsResponse, IsError), InvalidCmd, "BadAddressError" },
/* PrintReq */
{ SET2(IsRequest, IsPrint), InvalidCmd, "PrintReq" }
};
bool
Packet::checkFunctional(Printable *obj, Addr addr, int size, uint8_t *data)
{
Addr func_start = getAddr();
Addr func_end = getAddr() + getSize() - 1;
Addr val_start = addr;
Addr val_end = val_start + size - 1;
if (func_start > val_end || val_start > func_end) {
// no intersection
return false;
}
// check print first since it doesn't require data
if (isPrint()) {
dynamic_cast<PrintReqState*>(senderState)->printObj(obj);
return false;
}
// if there's no data, there's no need to look further
if (!data) {
return false;
}
// offset of functional request into supplied value (could be
// negative if partial overlap)
int offset = func_start - val_start;
if (isRead()) {
if (func_start >= val_start && func_end <= val_end) {
allocate();
memcpy(getPtr<uint8_t>(), data + offset, getSize());
makeResponse();
return true;
} else {
// In this case the timing packet only partially satisfies
// the request, so we would need more information to make
// this work. Like bytes valid in the packet or
// something, so the request could continue and get this
// bit of possibly newer data along with the older data
// not written to yet.
panic("Memory value only partially satisfies the functional "
"request. Now what?");
}
} else if (isWrite()) {
if (offset >= 0) {
memcpy(data + offset, getPtr<uint8_t>(),
(min(func_end, val_end) - func_start) + 1);
} else {
// val_start > func_start
memcpy(data, getPtr<uint8_t>() - offset,
(min(func_end, val_end) - val_start) + 1);
}
} else {
panic("Don't know how to handle command %s\n", cmdString());
}
// keep going with request by default
return false;
}
void
Packet::print(ostream &o, const int verbosity, const string &prefix) const
{
ccprintf(o, "%s[%x:%x] %s\n", prefix,
getAddr(), getAddr() + getSize() - 1, cmdString());
}
Packet::PrintReqState::PrintReqState(ostream &_os, int _verbosity)
: curPrefixPtr(new string("")), os(_os), verbosity(_verbosity)
{
labelStack.push_back(LabelStackEntry("", curPrefixPtr));
}
Packet::PrintReqState::~PrintReqState()
{
labelStack.pop_back();
assert(labelStack.empty());
delete curPrefixPtr;
}
Packet::PrintReqState::
LabelStackEntry::LabelStackEntry(const string &_label, string *_prefix)
: label(_label), prefix(_prefix), labelPrinted(false)
{
}
void
Packet::PrintReqState::pushLabel(const string &lbl, const string &prefix)
{
labelStack.push_back(LabelStackEntry(lbl, curPrefixPtr));
curPrefixPtr = new string(*curPrefixPtr);
*curPrefixPtr += prefix;
}
void
Packet::PrintReqState::popLabel()
{
delete curPrefixPtr;
curPrefixPtr = labelStack.back().prefix;
labelStack.pop_back();
assert(!labelStack.empty());
}
void
Packet::PrintReqState::printLabels()
{
if (!labelStack.back().labelPrinted) {
LabelStack::iterator i = labelStack.begin();
LabelStack::iterator end = labelStack.end();
while (i != end) {
if (!i->labelPrinted) {
ccprintf(os, "%s%s\n", *(i->prefix), i->label);
i->labelPrinted = true;
}
i++;
}
}
}
void
Packet::PrintReqState::printObj(Printable *obj)
{
printLabels();
obj->print(os, verbosity, curPrefix());
}
|
Fix the flags for interrupt response messages.
|
X86: Fix the flags for interrupt response messages.
|
C++
|
bsd-3-clause
|
andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin
|
5d3509342f54d9b194e4a96985b2017a8661fdde
|
src/messenger.cpp
|
src/messenger.cpp
|
#include "stdafx.h"
#include <dukat/messenger.h>
namespace dukat
{
void Messenger::trigger(const Message& message)
{
if (subscriptions.count(message.event))
{
for (auto r : subscriptions[message.event])
{
r->receive(message);
}
}
}
void Messenger::subscribe(Recipient * recipient, Event ev)
{
if (subscriptions.count(ev) == 0)
{
subscriptions[ev] = std::list<Recipient*>();
}
subscriptions[ev].push_back(recipient);
}
void Messenger::subscribe(Recipient * recipient, const std::vector<Event>& events)
{
std::for_each(events.begin(), events.end(), [&](const Event& e) { subscribe(recipient, e); });
}
void Messenger::subscribe_all(Recipient* recipient)
{
for (auto it = Events::None; it != Events::Any; ++it)
{
subscribe(recipient, it);
}
}
void Messenger::do_unsubscribe(Recipient* recipient, std::list<Recipient*>& list)
{
for (auto it = list.begin(); it != list.end(); ++it)
{
if (*it == recipient)
{
list.erase(it);
break;
}
}
}
void Messenger::unsubscribe(Recipient* recipient, Event ev)
{
if (subscriptions.count(ev))
do_unsubscribe(recipient, subscriptions[ev]);
}
void Messenger::unsubscribe(Recipient* recipient, const std::vector<Event>& events)
{
std::for_each(events.begin(), events.end(), [&](const Event& e) { unsubscribe(recipient, e); });
}
void Messenger::unsubscribe_all(Recipient* recipient)
{
for (auto it = subscriptions.begin(); it != subscriptions.end(); ++it)
do_unsubscribe(recipient, it->second);
}
}
|
#include "stdafx.h"
#include <dukat/messenger.h>
namespace dukat
{
void Messenger::trigger(const Message& message)
{
if (subscriptions.count(message.event))
{
for (auto r : subscriptions[message.event])
{
r->receive(message);
}
}
}
void Messenger::subscribe(Recipient* recipient, Event ev)
{
if (subscriptions.count(ev) == 0)
subscriptions[ev] = std::list<Recipient*>();
auto& list = subscriptions[ev];
auto it = std::find(list.begin(), list.end(), recipient);
if (it == list.end())
list.push_back(recipient);
}
void Messenger::subscribe(Recipient * recipient, const std::vector<Event>& events)
{
std::for_each(events.begin(), events.end(), [&](const Event& e) { subscribe(recipient, e); });
}
void Messenger::subscribe_all(Recipient* recipient)
{
for (auto it = Events::None; it != Events::Any; ++it)
subscribe(recipient, it);
}
void Messenger::do_unsubscribe(Recipient* recipient, std::list<Recipient*>& list)
{
for (auto it = list.begin(); it != list.end(); ++it)
{
if (*it == recipient)
{
list.erase(it);
break;
}
}
}
void Messenger::unsubscribe(Recipient* recipient, Event ev)
{
if (subscriptions.count(ev))
do_unsubscribe(recipient, subscriptions[ev]);
}
void Messenger::unsubscribe(Recipient* recipient, const std::vector<Event>& events)
{
std::for_each(events.begin(), events.end(), [&](const Event& e) { unsubscribe(recipient, e); });
}
void Messenger::unsubscribe_all(Recipient* recipient)
{
for (auto it = subscriptions.begin(); it != subscriptions.end(); ++it)
do_unsubscribe(recipient, it->second);
}
}
|
Fix to messenger logic
|
Fix to messenger logic
|
C++
|
mit
|
bdamer/dukat,bdamer/dukat
|
7c215105928f7b6ba7a1fe939799ad666fc83639
|
src/myaccount.cpp
|
src/myaccount.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 "myaccount.h"
#include "objects/adminaccount.h"
#include "objects/skaffarierror.h"
#include "utils/language.h"
#include "utils/skaffariconfig.h"
#include "objects/helpentry.h"
#include <Cutelyst/Plugins/Utils/Validator> // includes the main validator
#include <Cutelyst/Plugins/Utils/Validators> // includes all validator rules
#include <Cutelyst/Plugins/Utils/ValidatorResult> // includes the validator result
#include <Cutelyst/Plugins/StatusMessage>
#include <Cutelyst/Plugins/Authentication/authentication.h>
#include <QTimeZone>
MyAccount::MyAccount(QObject *parent) : Controller(parent)
{
}
MyAccount::~MyAccount()
{
}
void MyAccount::index(Context *c)
{
AuthenticationUser user = Authentication::user(c);
SkaffariError e(c);
AdminAccount aac = AdminAccount::get(c, &e, user.id().toULong());
if (aac.isValid()) {
auto req = c->req();
if (req->isPost()) {
static Validator v({
new ValidatorConfirmed(QStringLiteral("password")),
new ValidatorMin(QStringLiteral("password"), QMetaType::QString, SkaffariConfig::admPwMinlength()),
new ValidatorInteger(QStringLiteral("maxdisplay")),
new ValidatorBetween(QStringLiteral("maxdisplay"), QMetaType::UInt, 0, 255),
new ValidatorInteger(QStringLiteral("warnlevel")),
new ValidatorBetween(QStringLiteral("warnlevel"), QMetaType::UInt, 0, 100),
new ValidatorIn(QStringLiteral("lang"), Language::supportedLangsList())
});
ValidatorResult vr = v.validate(c, Validator::FillStashOnError);
if (vr) {
SkaffariError e(c);
if (AdminAccount::update(c, &e, &aac, &user, req->bodyParameters())) {
c->setStash(QStringLiteral("status_msg"), c->translate("MyAccount", "Your account has been updated."));
} else {
c->setStash(QStringLiteral("error_msg"), e.errorText());
}
}
}
QHash<QString,HelpEntry> help;
help.insert(QStringLiteral("created"), HelpEntry(c->translate("MyAccount", "Created"), c->translate("MyAccount", "Date and time your account has been created.")));
help.insert(QStringLiteral("updated"), HelpEntry(c->translate("MyAccount", "Updated"), c->translate("MyAccount", "Date and time your account has been updated the last time.")));
help.insert(QStringLiteral("password"), HelpEntry(c->translate("MyAccount", "New password"), c->translate("MyAccount", "Specify a new password with a minimum length of %n character(s). Leave the input field blank to not change the password.", "", SkaffariConfig::accPwMinlength())));
help.insert(QStringLiteral("password_confirmation"), HelpEntry(c->translate("MyAccount", "Confirm new password"), c->translate("MyAccount", "Confirm your new password by entering it again.")));
help.insert(QStringLiteral("maxdisplay"), HelpEntry(c->translate("MyAccount", "Max display"), c->translate("MyAccount", "Set the number of results you want to load in paginated lists like the account list (minimum 15, maximum 255")));
help.insert(QStringLiteral("warnlevel"), HelpEntry(c->translate("MyAccount", "Warn level"), c->translate("MyAccount", "Set the percentage limit that will show warnings on number of accounts and quota usage.")));
help.insert(QStringLiteral("lang"), HelpEntry(c->translate("MyAccount", "Language"), c->translate("MyAccount", "Select one of the supported languages to display Skaffari localized.")));
help.insert(QStringLiteral("tz"), HelpEntry(c->translate("MyAccount", "Time zone"), c->translate("MyAccount", "Select your time zone to display localized date and time values.")));
c->stash({
{QStringLiteral("template"), QStringLiteral("myaccount/index.html")},
{QStringLiteral("site_title"), c->translate("MyAccount", "My account")},
{QStringLiteral("adminaccount"), QVariant::fromValue<AdminAccount>(aac)},
{QStringLiteral("langs"), QVariant::fromValue<QVector<Language>>(Language::supportedLangs())},
{QStringLiteral("timezones"), QVariant::fromValue<QList<QByteArray>>(QTimeZone::availableTimeZoneIds())},
{QStringLiteral("help"), QVariant::fromValue<QHash<QString,HelpEntry>>(help)}
});
} else {
c->setStash(QStringLiteral("not_found_text"), c->translate("MyAccount", "There is no admin account with database ID %1.").arg(user.id()));
c->setStash(QStringLiteral("template"), QStringLiteral("404.html"));
c->res()->setStatus(404);
}
}
#include "moc_myaccount.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 "myaccount.h"
#include "objects/adminaccount.h"
#include "objects/skaffarierror.h"
#include "utils/language.h"
#include "utils/skaffariconfig.h"
#include "objects/helpentry.h"
#include <Cutelyst/Plugins/Utils/Validator> // includes the main validator
#include <Cutelyst/Plugins/Utils/Validators> // includes all validator rules
#include <Cutelyst/Plugins/Utils/ValidatorResult> // includes the validator result
#include <Cutelyst/Plugins/StatusMessage>
#include <Cutelyst/Plugins/Authentication/authentication.h>
#include <QTimeZone>
MyAccount::MyAccount(QObject *parent) : Controller(parent)
{
}
MyAccount::~MyAccount()
{
}
void MyAccount::index(Context *c)
{
AuthenticationUser user = Authentication::user(c);
SkaffariError e(c);
AdminAccount aac = AdminAccount::get(c, &e, user.id().toULong());
if (aac.isValid()) {
auto req = c->req();
if (req->isPost()) {
static Validator v({
new ValidatorConfirmed(QStringLiteral("password")),
new ValidatorMin(QStringLiteral("password"), QMetaType::QString, SkaffariConfig::admPwMinlength()),
new ValidatorBetween(QStringLiteral("maxdisplay"), QMetaType::UShort, 0, 255),
new ValidatorBetween(QStringLiteral("warnlevel"), QMetaType::UShort, 0, 100),
new ValidatorIn(QStringLiteral("lang"), Language::supportedLangsList())
});
ValidatorResult vr = v.validate(c, Validator::FillStashOnError);
if (vr) {
SkaffariError e(c);
if (AdminAccount::update(c, &e, &aac, &user, req->bodyParameters())) {
c->setStash(QStringLiteral("status_msg"), c->translate("MyAccount", "Your account has been updated."));
} else {
c->setStash(QStringLiteral("error_msg"), e.errorText());
}
}
}
QHash<QString,HelpEntry> help;
help.insert(QStringLiteral("created"), HelpEntry(c->translate("MyAccount", "Created"), c->translate("MyAccount", "Date and time your account was created.")));
help.insert(QStringLiteral("updated"), HelpEntry(c->translate("MyAccount", "Updated"), c->translate("MyAccount", "Date and time your account was last updated.")));
help.insert(QStringLiteral("password"), HelpEntry(c->translate("MyAccount", "New password"), c->translate("MyAccount", "Enter a new password with a minimum length of %n character(s) or leave the field blank to avoid changing the password.", "", SkaffariConfig::accPwMinlength())));
help.insert(QStringLiteral("password_confirmation"), HelpEntry(c->translate("MyAccount", "Confirm new password"), c->translate("MyAccount", "Confirm your new password by entering it again.")));
help.insert(QStringLiteral("maxdisplay"), HelpEntry(c->translate("MyAccount", "Max display"), c->translate("MyAccount", "Set the number of results you want to load in paginated lists like the account list (minimum 15, maximum 255")));
help.insert(QStringLiteral("warnlevel"), HelpEntry(c->translate("MyAccount", "Warn level"), c->translate("MyAccount", "Set the percentage limit that will show warnings on number of accounts and quota usage.")));
help.insert(QStringLiteral("lang"), HelpEntry(c->translate("MyAccount", "Language"), c->translate("MyAccount", "Select one of the supported languages.")));
help.insert(QStringLiteral("tz"), HelpEntry(c->translate("MyAccount", "Time zone"), c->translate("MyAccount", "Select your time zone to enter and display date and time values appropriately.")));
c->stash({
{QStringLiteral("template"), QStringLiteral("myaccount/index.html")},
{QStringLiteral("site_title"), c->translate("MyAccount", "My account")},
{QStringLiteral("adminaccount"), QVariant::fromValue<AdminAccount>(aac)},
{QStringLiteral("langs"), QVariant::fromValue<QVector<Language>>(Language::supportedLangs())},
{QStringLiteral("timezones"), QVariant::fromValue<QList<QByteArray>>(QTimeZone::availableTimeZoneIds())},
{QStringLiteral("help"), QVariant::fromValue<QHash<QString,HelpEntry>>(help)}
});
} else {
c->setStash(QStringLiteral("not_found_text"), c->translate("MyAccount", "There is no admin account with database ID %1.").arg(user.id()));
c->setStash(QStringLiteral("template"), QStringLiteral("404.html"));
c->res()->setStatus(404);
}
}
#include "moc_myaccount.cpp"
|
check translatable strings (#7)
|
MyAccount: check translatable strings (#7)
|
C++
|
agpl-3.0
|
Huessenbergnetz/Skaffari,Huessenbergnetz/Skaffari,Buschtrommel/Skaffari,Buschtrommel/Skaffari,Buschtrommel/Skaffari,Huessenbergnetz/Skaffari,Huessenbergnetz/Skaffari,Buschtrommel/Skaffari,Huessenbergnetz/Skaffari,Huessenbergnetz/Skaffari,Buschtrommel/Skaffari
|
35ecf8815be97dbca765b940ad22d6d91dd09fa6
|
src/Simulation/BFER/Iterative/BFER_ite.cpp
|
src/Simulation/BFER/Iterative/BFER_ite.cpp
|
#include "Tools/Exception/exception.hpp"
#include "Factory/Module/Coset/Coset.hpp"
#include "BFER_ite.hpp"
using namespace aff3ct;
using namespace aff3ct::simulation;
template <typename B, typename R, typename Q>
BFER_ite<B,R,Q>
::BFER_ite(const factory::BFER_ite::parameters ¶ms)
: BFER<B,R,Q>(params),
params(params),
source (params.n_threads, nullptr),
crc (params.n_threads, nullptr),
codec (params.n_threads, nullptr),
modem (params.n_threads, nullptr),
channel (params.n_threads, nullptr),
quantizer (params.n_threads, nullptr),
coset_real (params.n_threads, nullptr),
coset_bit (params.n_threads, nullptr),
interleaver_core(params.n_threads, nullptr),
interleaver_bit (params.n_threads, nullptr),
interleaver_llr (params.n_threads, nullptr),
rd_engine_seed(params.n_threads)
{
for (auto tid = 0; tid < params.n_threads; tid++)
rd_engine_seed[tid].seed(params.local_seed + tid);
this->modules["source" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["crc" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["codec" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["encoder" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["modem" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["channel" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["quantizer" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["coset_real" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["decoder_siso" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["decoder_siho" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["coset_bit" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["interleaver_bit"] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["interleaver_llr"] = std::vector<module::Module*>(params.n_threads, nullptr);
}
template <typename B, typename R, typename Q>
BFER_ite<B,R,Q>
::~BFER_ite()
{
}
template <typename B, typename R, typename Q>
void BFER_ite<B,R,Q>
::__build_communication_chain(const int tid)
{
// build the objects
source [tid] = build_source (tid);
crc [tid] = build_crc (tid);
codec [tid] = build_codec (tid);
modem [tid] = build_modem (tid);
channel [tid] = build_channel (tid);
quantizer [tid] = build_quantizer (tid);
coset_real [tid] = build_coset_real (tid);
coset_bit [tid] = build_coset_bit (tid);
interleaver_core[tid] = build_interleaver(tid);
interleaver_bit [tid] = factory::Interleaver::build<B>(*interleaver_core[tid]);
interleaver_llr [tid] = factory::Interleaver::build<Q>(*interleaver_core[tid]);
this->modules["source" ][tid] = source [tid];
this->modules["crc" ][tid] = crc [tid];
this->modules["codec" ][tid] = codec [tid];
this->modules["encoder" ][tid] = codec [tid]->get_encoder();
this->modules["modem" ][tid] = modem [tid];
this->modules["channel" ][tid] = channel [tid];
this->modules["quantizer" ][tid] = quantizer [tid];
this->modules["coset_real" ][tid] = coset_real [tid];
this->modules["decoder_siso" ][tid] = codec [tid]->get_decoder_siso();
this->modules["decoder_siho" ][tid] = codec [tid]->get_decoder_siho();
this->modules["coset_bit" ][tid] = coset_bit [tid];
this->modules["interleaver_bit"][tid] = interleaver_bit[tid];
this->modules["interleaver_llr"][tid] = interleaver_llr[tid];
this->monitor[tid]->add_handler_check(std::bind(&module::Codec_SISO_SIHO<B,Q>::reset, codec[tid]));
interleaver_core[tid]->init();
if (interleaver_core[tid]->is_uniform())
this->monitor[tid]->add_handler_check(std::bind(&tools::Interleaver_core<>::refresh,
this->interleaver_core[tid]));
if (this->params.err_track_enable && interleaver_core[tid]->is_uniform())
this->dumper[tid]->register_data(interleaver_core[tid]->get_lut(), "itl", false, {});
if (this->params.err_track_enable)
this->dumper[tid]->register_data(this->channel[tid]->get_noise(), "chn", true, {});
}
template <typename B, typename R, typename Q>
void BFER_ite<B,R,Q>
::_launch()
{
// set current sigma
for (auto tid = 0; tid < this->params.n_threads; tid++)
{
this->channel[tid]->set_sigma(this->sigma);
this->modem [tid]->set_sigma(this->sigma);
this->codec [tid]->set_sigma(this->sigma);
}
}
template <typename B, typename R, typename Q>
void BFER_ite<B,R,Q>
::release_objects()
{
const auto nthr = params.n_threads;
for (auto i = 0; i < nthr; i++) if (source [i] != nullptr) { delete source [i]; source [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (crc [i] != nullptr) { delete crc [i]; crc [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (codec [i] != nullptr) { delete codec [i]; codec [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (interleaver_bit [i] != nullptr) { delete interleaver_bit [i]; interleaver_bit [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (interleaver_llr [i] != nullptr) { delete interleaver_llr [i]; interleaver_llr [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (interleaver_core[i] != nullptr) { delete interleaver_core[i]; interleaver_core[i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (modem [i] != nullptr) { delete modem [i]; modem [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (channel [i] != nullptr) { delete channel [i]; channel [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (quantizer [i] != nullptr) { delete quantizer [i]; quantizer [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (coset_real [i] != nullptr) { delete coset_real [i]; coset_real [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (coset_bit [i] != nullptr) { delete coset_bit [i]; coset_bit [i] = nullptr; }
BFER<B,R,Q>::release_objects();
}
template <typename B, typename R, typename Q>
module::Source<B>* BFER_ite<B,R,Q>
::build_source(const int tid)
{
const auto seed_src = rd_engine_seed[tid]();
auto params_src = params.src->clone();
params_src->seed = seed_src;
auto s = params_src->template build<B>();
delete params_src;
return s;
}
template <typename B, typename R, typename Q>
module::CRC<B>* BFER_ite<B,R,Q>
::build_crc(const int tid)
{
return params.crc->template build<B>();
}
template <typename B, typename R, typename Q>
module::Codec_SISO_SIHO<B,Q>* BFER_ite<B,R,Q>
::build_codec(const int tid)
{
const auto seed_enc = rd_engine_seed[tid]();
auto params_cdc = params.cdc->clone();
params_cdc->enc->seed = seed_enc;
auto crc = this->params.crc->type == "NO" ? nullptr : this->crc[tid];
auto c = params_cdc->template build<B,Q>(crc);
delete params_cdc;
return c;
}
template <typename B, typename R, typename Q>
tools ::Interleaver_core<>* BFER_ite<B,R,Q>
::build_interleaver(const int tid)
{
const auto seed_itl = rd_engine_seed[tid]();
auto params_itl = params.itl->clone();
params_itl->core->seed = params.itl->core->uniform ? seed_itl : params.itl->core->seed;
if (params.err_track_revert)
params_itl->core->path = params.err_track_path + "_" + std::to_string(this->snr_b) + ".itl";
auto i = params_itl->core->template build<>();
delete params_itl;
return i;
}
template <typename B, typename R, typename Q>
module::Modem<B,R,Q>* BFER_ite<B,R,Q>
::build_modem(const int tid)
{
return params.mdm->template build<B,R,Q>();
}
template <typename B, typename R, typename Q>
module::Channel<R>* BFER_ite<B,R,Q>
::build_channel(const int tid)
{
const auto seed_chn = rd_engine_seed[tid]();
auto params_chn = params.chn->clone();
params_chn->seed = seed_chn;
auto c = params_chn->template build<R>();
delete params_chn;
return c;
}
template <typename B, typename R, typename Q>
module::Quantizer<R,Q>* BFER_ite<B,R,Q>
::build_quantizer(const int tid)
{
return params.qnt->template build<R,Q>();
}
template <typename B, typename R, typename Q>
module::Coset<B,Q>* BFER_ite<B,R,Q>
::build_coset_real(const int tid)
{
factory::Coset::parameters cst_params;
cst_params.size = params.cdc->N_cw;
cst_params.n_frames = params.src->n_frames;
return cst_params.template build_real<B,Q>();
}
template <typename B, typename R, typename Q>
module::Coset<B,B>* BFER_ite<B,R,Q>
::build_coset_bit(const int tid)
{
factory::Coset::parameters cst_params;
cst_params.size = params.coded_monitoring ? params.cdc->N_cw : params.cdc->K;
cst_params.n_frames = params.src->n_frames;
return cst_params.template build_bit<B,B>();
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::simulation::BFER_ite<B_8,R_8,Q_8>;
template class aff3ct::simulation::BFER_ite<B_16,R_16,Q_16>;
template class aff3ct::simulation::BFER_ite<B_32,R_32,Q_32>;
template class aff3ct::simulation::BFER_ite<B_64,R_64,Q_64>;
#else
template class aff3ct::simulation::BFER_ite<B,R,Q>;
#endif
// ==================================================================================== explicit template instantiation
|
#include "Tools/Exception/exception.hpp"
#include "Factory/Module/Coset/Coset.hpp"
#include "BFER_ite.hpp"
using namespace aff3ct;
using namespace aff3ct::simulation;
template <typename B, typename R, typename Q>
BFER_ite<B,R,Q>
::BFER_ite(const factory::BFER_ite::parameters ¶ms)
: BFER<B,R,Q>(params),
params(params),
source (params.n_threads, nullptr),
crc (params.n_threads, nullptr),
codec (params.n_threads, nullptr),
modem (params.n_threads, nullptr),
channel (params.n_threads, nullptr),
quantizer (params.n_threads, nullptr),
coset_real (params.n_threads, nullptr),
coset_bit (params.n_threads, nullptr),
interleaver_core(params.n_threads, nullptr),
interleaver_bit (params.n_threads, nullptr),
interleaver_llr (params.n_threads, nullptr),
rd_engine_seed(params.n_threads)
{
for (auto tid = 0; tid < params.n_threads; tid++)
rd_engine_seed[tid].seed(params.local_seed + tid);
this->modules["source" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["crc" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["codec" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["encoder" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["modem" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["channel" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["quantizer" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["coset_real" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["decoder_siso" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["decoder_siho" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["coset_bit" ] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["interleaver_bit"] = std::vector<module::Module*>(params.n_threads, nullptr);
this->modules["interleaver_llr"] = std::vector<module::Module*>(params.n_threads, nullptr);
}
template <typename B, typename R, typename Q>
BFER_ite<B,R,Q>
::~BFER_ite()
{
}
template <typename B, typename R, typename Q>
void BFER_ite<B,R,Q>
::__build_communication_chain(const int tid)
{
// build the objects
source [tid] = build_source (tid);
crc [tid] = build_crc (tid);
codec [tid] = build_codec (tid);
modem [tid] = build_modem (tid);
channel [tid] = build_channel (tid);
quantizer [tid] = build_quantizer (tid);
coset_real [tid] = build_coset_real (tid);
coset_bit [tid] = build_coset_bit (tid);
interleaver_core[tid] = build_interleaver(tid);
interleaver_bit [tid] = factory::Interleaver::build<B>(*interleaver_core[tid]);
interleaver_llr [tid] = factory::Interleaver::build<Q>(*interleaver_core[tid]);
this->modules["source" ][tid] = source [tid];
this->modules["crc" ][tid] = crc [tid];
this->modules["codec" ][tid] = codec [tid];
this->modules["encoder" ][tid] = codec [tid]->get_encoder();
this->modules["modem" ][tid] = modem [tid];
this->modules["channel" ][tid] = channel [tid];
this->modules["quantizer" ][tid] = quantizer [tid];
this->modules["coset_real" ][tid] = coset_real [tid];
this->modules["decoder_siso" ][tid] = codec [tid]->get_decoder_siso();
this->modules["coset_bit" ][tid] = coset_bit [tid];
this->modules["interleaver_bit"][tid] = interleaver_bit[tid];
this->modules["interleaver_llr"][tid] = interleaver_llr[tid];
if (dynamic_cast<module::Decoder*>(codec[tid]->get_decoder_siso()) !=
dynamic_cast<module::Decoder*>(codec[tid]->get_decoder_siho()))
this->modules["decoder_siho"][tid] = codec[tid]->get_decoder_siho();
this->monitor[tid]->add_handler_check(std::bind(&module::Codec_SISO_SIHO<B,Q>::reset, codec[tid]));
interleaver_core[tid]->init();
if (interleaver_core[tid]->is_uniform())
this->monitor[tid]->add_handler_check(std::bind(&tools::Interleaver_core<>::refresh,
this->interleaver_core[tid]));
if (this->params.err_track_enable && interleaver_core[tid]->is_uniform())
this->dumper[tid]->register_data(interleaver_core[tid]->get_lut(), "itl", false, {});
if (this->params.err_track_enable)
this->dumper[tid]->register_data(this->channel[tid]->get_noise(), "chn", true, {});
}
template <typename B, typename R, typename Q>
void BFER_ite<B,R,Q>
::_launch()
{
// set current sigma
for (auto tid = 0; tid < this->params.n_threads; tid++)
{
this->channel[tid]->set_sigma(this->sigma);
this->modem [tid]->set_sigma(this->sigma);
this->codec [tid]->set_sigma(this->sigma);
}
}
template <typename B, typename R, typename Q>
void BFER_ite<B,R,Q>
::release_objects()
{
const auto nthr = params.n_threads;
for (auto i = 0; i < nthr; i++) if (source [i] != nullptr) { delete source [i]; source [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (crc [i] != nullptr) { delete crc [i]; crc [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (codec [i] != nullptr) { delete codec [i]; codec [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (interleaver_bit [i] != nullptr) { delete interleaver_bit [i]; interleaver_bit [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (interleaver_llr [i] != nullptr) { delete interleaver_llr [i]; interleaver_llr [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (interleaver_core[i] != nullptr) { delete interleaver_core[i]; interleaver_core[i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (modem [i] != nullptr) { delete modem [i]; modem [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (channel [i] != nullptr) { delete channel [i]; channel [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (quantizer [i] != nullptr) { delete quantizer [i]; quantizer [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (coset_real [i] != nullptr) { delete coset_real [i]; coset_real [i] = nullptr; }
for (auto i = 0; i < nthr; i++) if (coset_bit [i] != nullptr) { delete coset_bit [i]; coset_bit [i] = nullptr; }
BFER<B,R,Q>::release_objects();
}
template <typename B, typename R, typename Q>
module::Source<B>* BFER_ite<B,R,Q>
::build_source(const int tid)
{
const auto seed_src = rd_engine_seed[tid]();
auto params_src = params.src->clone();
params_src->seed = seed_src;
auto s = params_src->template build<B>();
delete params_src;
return s;
}
template <typename B, typename R, typename Q>
module::CRC<B>* BFER_ite<B,R,Q>
::build_crc(const int tid)
{
return params.crc->template build<B>();
}
template <typename B, typename R, typename Q>
module::Codec_SISO_SIHO<B,Q>* BFER_ite<B,R,Q>
::build_codec(const int tid)
{
const auto seed_enc = rd_engine_seed[tid]();
auto params_cdc = params.cdc->clone();
params_cdc->enc->seed = seed_enc;
auto crc = this->params.crc->type == "NO" ? nullptr : this->crc[tid];
auto c = params_cdc->template build<B,Q>(crc);
delete params_cdc;
return c;
}
template <typename B, typename R, typename Q>
tools ::Interleaver_core<>* BFER_ite<B,R,Q>
::build_interleaver(const int tid)
{
const auto seed_itl = rd_engine_seed[tid]();
auto params_itl = params.itl->clone();
params_itl->core->seed = params.itl->core->uniform ? seed_itl : params.itl->core->seed;
if (params.err_track_revert)
params_itl->core->path = params.err_track_path + "_" + std::to_string(this->snr_b) + ".itl";
auto i = params_itl->core->template build<>();
delete params_itl;
return i;
}
template <typename B, typename R, typename Q>
module::Modem<B,R,Q>* BFER_ite<B,R,Q>
::build_modem(const int tid)
{
return params.mdm->template build<B,R,Q>();
}
template <typename B, typename R, typename Q>
module::Channel<R>* BFER_ite<B,R,Q>
::build_channel(const int tid)
{
const auto seed_chn = rd_engine_seed[tid]();
auto params_chn = params.chn->clone();
params_chn->seed = seed_chn;
auto c = params_chn->template build<R>();
delete params_chn;
return c;
}
template <typename B, typename R, typename Q>
module::Quantizer<R,Q>* BFER_ite<B,R,Q>
::build_quantizer(const int tid)
{
return params.qnt->template build<R,Q>();
}
template <typename B, typename R, typename Q>
module::Coset<B,Q>* BFER_ite<B,R,Q>
::build_coset_real(const int tid)
{
factory::Coset::parameters cst_params;
cst_params.size = params.cdc->N_cw;
cst_params.n_frames = params.src->n_frames;
return cst_params.template build_real<B,Q>();
}
template <typename B, typename R, typename Q>
module::Coset<B,B>* BFER_ite<B,R,Q>
::build_coset_bit(const int tid)
{
factory::Coset::parameters cst_params;
cst_params.size = params.coded_monitoring ? params.cdc->N_cw : params.cdc->K;
cst_params.n_frames = params.src->n_frames;
return cst_params.template build_bit<B,B>();
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::simulation::BFER_ite<B_8,R_8,Q_8>;
template class aff3ct::simulation::BFER_ite<B_16,R_16,Q_16>;
template class aff3ct::simulation::BFER_ite<B_32,R_32,Q_32>;
template class aff3ct::simulation::BFER_ite<B_64,R_64,Q_64>;
#else
template class aff3ct::simulation::BFER_ite<B,R,Q>;
#endif
// ==================================================================================== explicit template instantiation
|
Fix bad display in the statistics.
|
Fix bad display in the statistics.
|
C++
|
mit
|
aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct
|
74b167ebeda5b49537273eff0527695ea6b5c68a
|
src/module-forward.cc
|
src/module-forward.cc
|
/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
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 "module.hh"
#include "agent.hh"
#include "transaction.hh"
#include "etchosts.hh"
#include <sstream>
#include <sofia-sip/sip_status.h>
using namespace ::std;
static char const *compute_branch(nta_agent_t *sa, msg_t *msg, sip_t const *sip, char const *string_server);
class ForwardModule: public Module, ModuleToolbox {
public:
ForwardModule(Agent *ag);
virtual void onDeclare(GenericStruct * module_config);
virtual void onLoad(Agent *agent, const GenericStruct *root);
virtual void onRequest(shared_ptr<SipEvent> &ev);
virtual void onResponse(shared_ptr<SipEvent> &ev);
~ForwardModule();
private:
url_t* overrideDest(shared_ptr<SipEvent> &ev, url_t* dest);
void checkRecordRoutes(shared_ptr<SipEvent> &ev, url_t *dest);
bool isLooping(shared_ptr<SipEvent> &ev, const char * branch);
unsigned int countVia(shared_ptr<SipEvent> &ev);
su_home_t mHome;
sip_route_t *mOutRoute;
bool mRewriteReqUri;
string mPreferredRoute;
static ModuleInfo<ForwardModule> sInfo;
};
ModuleInfo<ForwardModule> ForwardModule::sInfo("Forward", "This module executes the basic routing task of SIP requests and pass them to the transport layer. "
"It must always be enabled.");
ForwardModule::ForwardModule(Agent *ag) :
Module(ag) {
su_home_init(&mHome);
mOutRoute = NULL;
}
ForwardModule::~ForwardModule() {
su_home_deinit(&mHome);
}
void ForwardModule::onDeclare(GenericStruct * module_config) {
ConfigItemDescriptor items[] = { { String, "route", "A sip uri where to send all requests", "" }, { Boolean, "rewrite-req-uri", "Rewrite request-uri's host and port according to above route", "false" }, config_item_end };
module_config->addChildrenValues(items);
}
void ForwardModule::onLoad(Agent *agent, const GenericStruct *module_config) {
string route = module_config->get<ConfigString>("route")->read();
mRewriteReqUri = module_config->get<ConfigBoolean>("rewrite-req-uri")->read();
if (route.size() > 0) {
mOutRoute = sip_route_make(&mHome, route.c_str());
if (mOutRoute == NULL || mOutRoute->r_url->url_host == NULL) {
LOGF("Bad route parameter '%s' in configuration of Forward module", route.c_str());
}
}
stringstream ss;
ss << agent->getPublicIp() << ":" << agent->getPort();
mPreferredRoute = ss.str();
}
url_t* ForwardModule::overrideDest(shared_ptr<SipEvent> &ev, url_t *dest) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
if (mOutRoute) {
dest = mOutRoute->r_url;
if (mRewriteReqUri) {
ms->getSip()->sip_request->rq_url->url_host = mOutRoute->r_url->url_host;
ms->getSip()->sip_request->rq_url->url_port = mOutRoute->r_url->url_port;
}
}
return dest;
}
/* the goal of this method is to check whether we added ourself to the record route, and handle a possible
transport change by adding a new record-route with transport updated.
Typically, if we transfer an INVITE from TCP to UDP, we should find two consecutive record-route, first one with UDP, and second one with TCP
so that further request from both sides are sent to the appropriate transport of flexisip, and also we don't ask to a UDP only equipment to route to TCP.
*/
void ForwardModule::checkRecordRoutes(shared_ptr<SipEvent> &ev, url_t *dest) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
sip_record_route_t *rr = ms->getSip()->sip_record_route;
char last_transport[16] = { 0 };
char next_transport[16] = { 0 };
if (rr) {
if (getAgent()->isUs(rr->r_url, false)) {
if (!url_param(rr->r_url->url_params, "transport", last_transport, sizeof(last_transport))) {
strncpy(last_transport, "UDP", sizeof(last_transport));
}
if (!url_param(dest->url_params, "transport", next_transport, sizeof(next_transport))) {
strncpy(next_transport, "UDP", sizeof(next_transport));
}
if (strcasecmp(next_transport, last_transport) != 0) {
addRecordRoute(ms->getHome(), getAgent(), ms->getMsg(), ms->getSip(), next_transport);
}
}
}
}
void ForwardModule::onRequest(shared_ptr<SipEvent> &ev) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
url_t* dest = NULL;
sip_t *sip = ms->getSip();
msg_t *msg = ms->getMsg();
// Check max forwards
if (sip->sip_max_forwards != NULL && sip->sip_max_forwards->mf_count <= countVia(ev)) {
LOGD("Too Many Hops");
ev->reply(ms, SIP_483_TOO_MANY_HOPS, SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
return;
}
switch (sip->sip_request->rq_method) {
case sip_method_invite:
LOGD("This is an invite");
break;
case sip_method_register:
LOGD("This is a register");
case sip_method_ack:
default:
break;
}
dest = sip->sip_request->rq_url;
// removes top route headers if they matches us
while (sip->sip_route != NULL && getAgent()->isUs(sip->sip_route->r_url)) {
sip_route_remove(msg, sip);
}
if (sip->sip_route != NULL) {
/*forward to this route*/
dest = sip->sip_route->r_url;
}
/* workaround bad sip uris with two @ that results in host part being "something@somewhere" */
if (strchr(dest->url_host, '@') != 0) {
ev->reply(ms, SIP_400_BAD_REQUEST, SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
return;
}
dest = overrideDest(ev, dest);
string ip;
if (EtcHostsResolver::get()->resolve(dest->url_host, &ip)) {
LOGD("Found %s in /etc/hosts", dest->url_host);
/* duplication dest because we don't want to modify the message with our name resolution result*/
dest = url_hdup(ms->getHome(), dest);
dest->url_host = ip.c_str();
}
// Compute branch, output branch=XXXXX
char const * branchStr = compute_branch(getSofiaAgent(), msg, sip, mPreferredRoute.c_str());
// Check looping
if (isLooping(ev, branchStr + 7)) {
ev->reply(ms, SIP_482_LOOP_DETECTED, SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
} else if (getAgent()->isUs(dest->url_host, dest->url_port, false)) {
ms->log("Skipping forwarding of request to us %s:\n%s", url_as_string(ms->getHome(), dest));
ev->terminateProcessing();
} else {
checkRecordRoutes(ev, dest);
ev->send(ms, (url_string_t*) dest, NTATAG_BRANCH_KEY(branchStr), TAG_END());
}
}
unsigned int ForwardModule::countVia(shared_ptr<SipEvent> &ev) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
uint32_t via_count = 0;
for (sip_via_t *via = ms->getSip()->sip_via; via != NULL; via = via->v_next)
++via_count;
return via_count;
}
bool ForwardModule::isLooping(shared_ptr<SipEvent> &ev, const char * branch) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
for (sip_via_t *via = ms->getSip()->sip_via; via != NULL; via = via->v_next) {
if (via->v_branch != NULL && strcmp(via->v_branch, branch) == 0) {
LOGD("Loop detected: %s", via->v_branch);
return true;
}
}
return false;
}
void ForwardModule::onResponse(shared_ptr<SipEvent> &ev) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
ev->send(ms, (url_string_t*) NULL, TAG_END());
}
#include <sofia-sip/su_md5.h>
static char const *compute_branch(nta_agent_t *sa, msg_t *msg, sip_t const *sip, char const *string_server) {
su_md5_t md5[1];
uint8_t digest[SU_MD5_DIGEST_SIZE];
char branch[(SU_MD5_DIGEST_SIZE * 8 + 4) / 5 + 1];
sip_route_t const *r;
su_md5_init(md5);
su_md5_str0update(md5, string_server);
//su_md5_str0update(md5, port);
url_update(md5, sip->sip_request->rq_url);
if (sip->sip_call_id) {
su_md5_str0update(md5, sip->sip_call_id->i_id);
}
if (sip->sip_from) {
url_update(md5, sip->sip_from->a_url);
su_md5_stri0update(md5, sip->sip_from->a_tag);
}
if (sip->sip_to) {
url_update(md5, sip->sip_to->a_url);
/* XXX - some broken implementations include To tag in CANCEL */
/* su_md5_str0update(md5, sip->sip_to->a_tag); */
}
if (sip->sip_cseq) {
uint32_t cseq = htonl(sip->sip_cseq->cs_seq);
su_md5_update(md5, &cseq, sizeof(cseq));
}
for (r = sip->sip_route; r; r = r->r_next)
url_update(md5, r->r_url);
su_md5_digest(md5, digest);
msg_random_token(branch, sizeof(branch) - 1, digest, sizeof(digest));
return su_sprintf(msg_home(msg), "branch=z9hG4bK.%s", branch);
}
|
/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
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 "module.hh"
#include "agent.hh"
#include "transaction.hh"
#include "etchosts.hh"
#include <sstream>
#include <sofia-sip/sip_status.h>
using namespace ::std;
static char const *compute_branch(nta_agent_t *sa, msg_t *msg, sip_t const *sip, char const *string_server);
class ForwardModule: public Module, ModuleToolbox {
public:
ForwardModule(Agent *ag);
virtual void onDeclare(GenericStruct * module_config);
virtual void onLoad(Agent *agent, const GenericStruct *root);
virtual void onRequest(shared_ptr<SipEvent> &ev);
virtual void onResponse(shared_ptr<SipEvent> &ev);
~ForwardModule();
private:
url_t* overrideDest(shared_ptr<SipEvent> &ev, url_t* dest);
void checkRecordRoutes(shared_ptr<SipEvent> &ev, url_t *dest);
bool isLooping(shared_ptr<SipEvent> &ev, const char * branch);
unsigned int countVia(shared_ptr<SipEvent> &ev);
su_home_t mHome;
sip_route_t *mOutRoute;
bool mRewriteReqUri;
string mPreferredRoute;
static ModuleInfo<ForwardModule> sInfo;
};
ModuleInfo<ForwardModule> ForwardModule::sInfo("Forward", "This module executes the basic routing task of SIP requests and pass them to the transport layer. "
"It must always be enabled.");
ForwardModule::ForwardModule(Agent *ag) :
Module(ag) {
su_home_init(&mHome);
mOutRoute = NULL;
}
ForwardModule::~ForwardModule() {
su_home_deinit(&mHome);
}
void ForwardModule::onDeclare(GenericStruct * module_config) {
ConfigItemDescriptor items[] = { { String, "route", "A sip uri where to send all requests", "" }, { Boolean, "rewrite-req-uri", "Rewrite request-uri's host and port according to above route", "false" }, config_item_end };
module_config->addChildrenValues(items);
}
void ForwardModule::onLoad(Agent *agent, const GenericStruct *module_config) {
string route = module_config->get<ConfigString>("route")->read();
mRewriteReqUri = module_config->get<ConfigBoolean>("rewrite-req-uri")->read();
if (route.size() > 0) {
mOutRoute = sip_route_make(&mHome, route.c_str());
if (mOutRoute == NULL || mOutRoute->r_url->url_host == NULL) {
LOGF("Bad route parameter '%s' in configuration of Forward module", route.c_str());
}
}
stringstream ss;
ss << agent->getPublicIp() << ":" << agent->getPort();
mPreferredRoute = ss.str();
}
url_t* ForwardModule::overrideDest(shared_ptr<SipEvent> &ev, url_t *dest) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
if (mOutRoute) {
dest = mOutRoute->r_url;
if (mRewriteReqUri) {
ms->getSip()->sip_request->rq_url->url_host = mOutRoute->r_url->url_host;
ms->getSip()->sip_request->rq_url->url_port = mOutRoute->r_url->url_port;
}
}
return dest;
}
/* the goal of this method is to check whether we added ourself to the record route, and handle a possible
transport change by adding a new record-route with transport updated.
Typically, if we transfer an INVITE from TCP to UDP, we should find two consecutive record-route, first one with UDP, and second one with TCP
so that further request from both sides are sent to the appropriate transport of flexisip, and also we don't ask to a UDP only equipment to route to TCP.
*/
void ForwardModule::checkRecordRoutes(shared_ptr<SipEvent> &ev, url_t *dest) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
sip_record_route_t *rr = ms->getSip()->sip_record_route;
char last_transport[16] = { 0 };
char next_transport[16] = { 0 };
if (rr) {
if (getAgent()->isUs(rr->r_url, false)) {
if (!url_param(rr->r_url->url_params, "transport", last_transport, sizeof(last_transport))) {
strncpy(last_transport, "UDP", sizeof(last_transport));
}
if (!url_param(dest->url_params, "transport", next_transport, sizeof(next_transport))) {
strncpy(next_transport, "UDP", sizeof(next_transport));
}
if (strcasecmp(next_transport, last_transport) != 0) {
addRecordRoute(ms->getHome(), getAgent(), ms->getMsg(), ms->getSip(), next_transport);
}
}
}
}
void ForwardModule::onRequest(shared_ptr<SipEvent> &ev) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
url_t* dest = NULL;
sip_t *sip = ms->getSip();
msg_t *msg = ms->getMsg();
// Check max forwards
if (sip->sip_max_forwards != NULL && sip->sip_max_forwards->mf_count <= countVia(ev)) {
LOGD("Too Many Hops");
ev->reply(ms, SIP_483_TOO_MANY_HOPS, SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
return;
}
switch (sip->sip_request->rq_method) {
case sip_method_invite:
LOGD("This is an invite");
break;
case sip_method_register:
LOGD("This is a register");
case sip_method_ack:
default:
break;
}
dest = sip->sip_request->rq_url;
// removes top route headers if they matches us
while (sip->sip_route != NULL && getAgent()->isUs(sip->sip_route->r_url)) {
sip_route_remove(msg, sip);
}
if (sip->sip_route != NULL) {
/*forward to this route*/
dest = sip->sip_route->r_url;
}
/* workaround bad sip uris with two @ that results in host part being "something@somewhere" */
if (strchr(dest->url_host, '@') != 0) {
ev->reply(ms, SIP_400_BAD_REQUEST, SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
return;
}
dest = overrideDest(ev, dest);
string ip;
if (EtcHostsResolver::get()->resolve(dest->url_host, &ip)) {
LOGD("Found %s in /etc/hosts", dest->url_host);
/* duplication dest because we don't want to modify the message with our name resolution result*/
dest = url_hdup(ms->getHome(), dest);
dest->url_host = ip.c_str();
}
// Compute branch, output branch=XXXXX
char const * branchStr = compute_branch(getSofiaAgent(), msg, sip, mPreferredRoute.c_str());
// Check looping
if (isLooping(ev, branchStr + 7)) {
ev->reply(ms, SIP_482_LOOP_DETECTED, SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
} else if (getAgent()->isUs(dest->url_host, dest->url_port, false)) {
ms->log("Skipping forwarding of request to us %s", url_as_string(ms->getHome(), dest));
ev->terminateProcessing();
} else {
checkRecordRoutes(ev, dest);
ev->send(ms, (url_string_t*) dest, NTATAG_BRANCH_KEY(branchStr), TAG_END());
}
}
unsigned int ForwardModule::countVia(shared_ptr<SipEvent> &ev) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
uint32_t via_count = 0;
for (sip_via_t *via = ms->getSip()->sip_via; via != NULL; via = via->v_next)
++via_count;
return via_count;
}
bool ForwardModule::isLooping(shared_ptr<SipEvent> &ev, const char * branch) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
for (sip_via_t *via = ms->getSip()->sip_via; via != NULL; via = via->v_next) {
if (via->v_branch != NULL && strcmp(via->v_branch, branch) == 0) {
LOGD("Loop detected: %s", via->v_branch);
return true;
}
}
return false;
}
void ForwardModule::onResponse(shared_ptr<SipEvent> &ev) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
ev->send(ms, (url_string_t*) NULL, TAG_END());
}
#include <sofia-sip/su_md5.h>
static char const *compute_branch(nta_agent_t *sa, msg_t *msg, sip_t const *sip, char const *string_server) {
su_md5_t md5[1];
uint8_t digest[SU_MD5_DIGEST_SIZE];
char branch[(SU_MD5_DIGEST_SIZE * 8 + 4) / 5 + 1];
sip_route_t const *r;
su_md5_init(md5);
su_md5_str0update(md5, string_server);
//su_md5_str0update(md5, port);
url_update(md5, sip->sip_request->rq_url);
if (sip->sip_call_id) {
su_md5_str0update(md5, sip->sip_call_id->i_id);
}
if (sip->sip_from) {
url_update(md5, sip->sip_from->a_url);
su_md5_stri0update(md5, sip->sip_from->a_tag);
}
if (sip->sip_to) {
url_update(md5, sip->sip_to->a_url);
/* XXX - some broken implementations include To tag in CANCEL */
/* su_md5_str0update(md5, sip->sip_to->a_tag); */
}
if (sip->sip_cseq) {
uint32_t cseq = htonl(sip->sip_cseq->cs_seq);
su_md5_update(md5, &cseq, sizeof(cseq));
}
for (r = sip->sip_route; r; r = r->r_next)
url_update(md5, r->r_url);
su_md5_digest(md5, digest);
msg_random_token(branch, sizeof(branch) - 1, digest, sizeof(digest));
return su_sprintf(msg_home(msg), "branch=z9hG4bK.%s", branch);
}
|
Fix invalid log
|
Fix invalid log
|
C++
|
agpl-3.0
|
BelledonneCommunications/flexisip,biddyweb/flexisip,gale320/flexisip,biddyweb/flexisip,gale320/flexisip,biddyweb/flexisip,BelledonneCommunications/flexisip,biddyweb/flexisip,gale320/flexisip,gale320/flexisip,BelledonneCommunications/flexisip,BelledonneCommunications/flexisip
|
a55b7c3fd3e8bec41a46d75413bf5f2ba8efad1b
|
src/modules/bspwm.cpp
|
src/modules/bspwm.cpp
|
#include <thread>
#include <vector>
#include <sstream>
#include <sys/socket.h>
#include "config.hpp"
#include "lemonbuddy.hpp"
#include "bar.hpp"
#include "modules/bspwm.hpp"
#include "utils/config.hpp"
#include "utils/io.hpp"
#include "utils/memory.hpp"
#include "utils/string.hpp"
using namespace modules;
using namespace bspwm;
#define DEFAULT_WS_ICON "workspace_icon-default"
#define DEFAULT_WS_LABEL "%icon% %name%"
std::string get_socket_path()
{
std::string socket_path = BSPWM_SOCKET_PATH;
const char *env_bs = std::getenv("BSPWM_SOCKET");
if (env_bs != nullptr)
socket_path = std::string(env_bs);
return socket_path;
}
bspwm::payload_t generate_payload(std::string command)
{
bspwm::payload_t payload;
size_t size = sizeof(payload.data);
int offset = 0, chars = 0;
for (auto &&sub: string::split(command, ' ')) {
chars = snprintf(payload.data + offset, size - offset, "%s%c", sub.c_str(), 0);
payload.len += chars;
offset += chars;
}
return payload;
}
bool send_payload(int fd, bspwm::payload_t payload)
{
int bytes = 0;
if ((bytes = send(fd, payload.data, payload.len, 0)) == -1)
log_debug("bspwm: Failed sending message to socket");
return bytes > 0;
}
int create_subscriber()
{
int socket_fd = -1;
std::string socket_path = get_socket_path();
if ((socket_fd = io::socket::open(socket_path)) == -1)
throw ModuleError("bspwm: Could not connect to socket: "+ socket_path);
if (!send_payload(socket_fd, generate_payload("subscribe report")))
throw ModuleError("bspwm: Failed to subscribe to bspwm changes");
return socket_fd;
}
BspwmModule::BspwmModule(std::string name_, std::string monitor)
: EventModule(name_)
, monitor(monitor)
{
this->formatter->add(DEFAULT_FORMAT, TAG_LABEL_STATE, { TAG_LABEL_STATE }, { TAG_LABEL_MODE });
if (this->formatter->has(TAG_LABEL_STATE)) {
this->state_labels.insert(std::make_pair(WORKSPACE_ACTIVE, drawtypes::get_optional_config_label(name(), "label-active", DEFAULT_WS_LABEL)));
this->state_labels.insert(std::make_pair(WORKSPACE_OCCUPIED, drawtypes::get_optional_config_label(name(), "label-occupied", DEFAULT_WS_LABEL)));
this->state_labels.insert(std::make_pair(WORKSPACE_URGENT, drawtypes::get_optional_config_label(name(), "label-urgent", DEFAULT_WS_LABEL)));
this->state_labels.insert(std::make_pair(WORKSPACE_EMPTY, drawtypes::get_optional_config_label(name(), "label-empty", DEFAULT_WS_LABEL)));
this->state_labels.insert(std::make_pair(WORKSPACE_DIMMED, drawtypes::get_optional_config_label(name(), "label-dimmed")));
}
if (this->formatter->has(TAG_LABEL_MODE)) {
this->mode_labels.insert(std::make_pair(MODE_LAYOUT_MONOCLE, drawtypes::get_optional_config_label(name(), "label-monocle")));
this->mode_labels.insert(std::make_pair(MODE_LAYOUT_TILED, drawtypes::get_optional_config_label(name(), "label-tiled")));
this->mode_labels.insert(std::make_pair(MODE_STATE_FULLSCREEN, drawtypes::get_optional_config_label(name(), "label-fullscreen")));
this->mode_labels.insert(std::make_pair(MODE_STATE_FLOATING, drawtypes::get_optional_config_label(name(), "label-floating")));
this->mode_labels.insert(std::make_pair(MODE_NODE_LOCKED, drawtypes::get_optional_config_label(name(), "label-locked")));
this->mode_labels.insert(std::make_pair(MODE_NODE_STICKY, drawtypes::get_optional_config_label(name(), "label-sticky")));
this->mode_labels.insert(std::make_pair(MODE_NODE_PRIVATE, drawtypes::get_optional_config_label(name(), "label-private")));
}
this->icons = std::make_unique<drawtypes::IconMap>();
this->icons->add(DEFAULT_WS_ICON, std::make_unique<drawtypes::Icon>(config::get<std::string>(name(), DEFAULT_WS_ICON, "")));
for (auto workspace : config::get_list<std::string>(name(), "workspace_icon", {})) {
auto vec = string::split(workspace, ';');
if (vec.size() == 2) this->icons->add(vec[0], std::make_unique<drawtypes::Icon>(vec[1]));
}
}
BspwmModule::~BspwmModule()
{
if (this->socket_fd > -1)
close(this->socket_fd);
}
void BspwmModule::start()
{
this->socket_fd = create_subscriber();
this->EventModule<BspwmModule>::start();
}
bool BspwmModule::has_event()
{
if (io::poll(this->socket_fd, POLLHUP, 0)) {
close(this->socket_fd);
this->logger->warning("bspwm: Reconnecting to socket...");
this->socket_fd = create_subscriber();
}
return io::poll(this->socket_fd, POLLIN, 100);
}
bool BspwmModule::update()
{
auto bytes_read = 0;
auto data = io::readline(this->socket_fd, bytes_read);
if (bytes_read <= 0 || data.empty() || data == this->prev_data)
return false;
this->prev_data = data;
unsigned long n, m;
while ((n = data.find("\n")) != std::string::npos)
data.erase(n);
if (data.empty())
return false;
const auto prefix = std::string(BSPWM_STATUS_PREFIX);
if (data.compare(0, prefix.length(), prefix) != 0) {
this->logger->error("bspwm: Received unknown status -> "+ data);
return false;
}
const auto needle_active = "M"+ this->monitor +":";
const auto needle_inactive = "m"+ this->monitor +":";
// Cut out the relevant section for the current monitor
if ((n = data.find(prefix + needle_active)) != std::string::npos) {
if ((m = data.find(":m")) != std::string::npos) data = data.substr(n, m);
} else if ((n = data.find(prefix + needle_inactive)) != std::string::npos) {
if ((m = data.find(":M")) != std::string::npos) data = data.substr(n, m);
} else if ((n = data.find(needle_active)) != std::string::npos) {
data.erase(0, n);
} else if ((n = data.find(needle_inactive)) != std::string::npos) {
data.erase(0, n);
}
if (data.compare(0, prefix.length(), prefix) == 0)
data.erase(0, 1);
log_trace2(this->logger, data);
this->modes.clear();
this->workspaces.clear();
bool monitor_focused = true;
int workspace_n = 0;
for (auto &&tag : string::split(data, ':')) {
if (tag.empty()) continue;
auto value = tag.size() > 0 ? tag.substr(1) : "";
auto workspace_flag = WORKSPACE_NONE;
auto mode_flag = MODE_NONE;
switch (tag[0]) {
case 'm': monitor_focused = false; break;
case 'M': monitor_focused = true; break;
case 'F': workspace_flag = WORKSPACE_ACTIVE; break;
case 'O': workspace_flag = WORKSPACE_ACTIVE; break;
case 'o': workspace_flag = WORKSPACE_OCCUPIED; break;
case 'U': workspace_flag = WORKSPACE_URGENT; break;
case 'u': workspace_flag = WORKSPACE_URGENT; break;
case 'f': workspace_flag = WORKSPACE_EMPTY; break;
case 'L':
switch (value[0]) {
case 0: break;
case 'M': mode_flag = MODE_LAYOUT_MONOCLE; break;
case 'T': mode_flag = MODE_LAYOUT_TILED; break;
default: this->logger->warning("bspwm: Undefined L => "+ value);
}
break;
case 'T':
switch (value[0]) {
case 0: break;
case 'T': break;
case '=': mode_flag = MODE_STATE_FULLSCREEN; break;
case 'F': mode_flag = MODE_STATE_FLOATING; break;
default: this->logger->warning("bspwm: Undefined T => "+ value);
}
break;
case 'G':
repeat(value.length())
{
switch (value[repeat_i]) {
case 0: break;
case 'L': mode_flag = MODE_NODE_LOCKED; break;
case 'S': mode_flag = MODE_NODE_STICKY; break;
case 'P': mode_flag = MODE_NODE_PRIVATE; break;
default: this->logger->warning("bspwm: Undefined G => "+ value.substr(repeat_i, 1));
}
if (mode_flag != MODE_NONE && !this->mode_labels.empty())
this->modes.emplace_back(&this->mode_labels.find(mode_flag)->second);
}
continue;
default: this->logger->warning("bspwm: Undefined tag => "+ tag.substr(0, 1));
}
if (workspace_flag != WORKSPACE_NONE && this->formatter->has(TAG_LABEL_STATE)) {
std::unique_ptr<drawtypes::Icon> &icon = this->icons->get(value, DEFAULT_WS_ICON);
std::unique_ptr<drawtypes::Label> label = this->state_labels.find(workspace_flag)->second->clone();
if (!monitor_focused)
label->replace_defined_values(this->state_labels.find(WORKSPACE_DIMMED)->second);
label->replace_token("%name%", value);
label->replace_token("%icon%", icon->text);
label->replace_token("%index%", std::to_string(++workspace_n));
this->workspaces.emplace_back(std::make_unique<Workspace>(workspace_flag, std::move(label)));
}
if (mode_flag != MODE_NONE && !this->mode_labels.empty())
this->modes.emplace_back(&this->mode_labels.find(mode_flag)->second);
}
if (!monitor_focused) this->modes.clear();
return true;
}
bool BspwmModule::build(Builder *builder, std::string tag)
{
if (tag != TAG_LABEL_STATE)
return false;
int workspace_n = 0;
for (auto &&ws : this->workspaces) {
if (!ws.get()->label->text.empty())
builder->cmd(Cmd::LEFT_CLICK, std::string(EVENT_CLICK) + std::to_string(++workspace_n));
builder->node(ws.get()->label);
if (ws->flag == WORKSPACE_ACTIVE && this->formatter->has(TAG_LABEL_MODE)) {
for (auto &&mode : this->modes)
builder->node(mode->get());
}
if (!ws.get()->label->text.empty())
builder->cmd_close(true);
}
return true;
}
bool BspwmModule::handle_command(std::string cmd)
{
if (cmd.find(EVENT_CLICK) == std::string::npos || cmd.length() <= std::strlen(EVENT_CLICK))
return false;
std::stringstream payload_s;
payload_s
<< "desktop -f "
<< this->monitor
<< ":^"
<< std::atoi(cmd.substr(std::strlen(EVENT_CLICK)).c_str());
int payload_fd;
std::string socket_path = get_socket_path();
if ((payload_fd = io::socket::open(socket_path)) == -1)
this->logger->error("bspwm: Failed to open socket: "+ socket_path);
else if (!send_payload(payload_fd, generate_payload(payload_s.str())))
this->logger->error("bspwm: Failed to change desktop");
close(payload_fd);
return true;
}
|
#include <thread>
#include <vector>
#include <sstream>
#include <sys/socket.h>
#include "config.hpp"
#include "lemonbuddy.hpp"
#include "bar.hpp"
#include "modules/bspwm.hpp"
#include "utils/config.hpp"
#include "utils/io.hpp"
#include "utils/memory.hpp"
#include "utils/string.hpp"
using namespace modules;
using namespace bspwm;
#define DEFAULT_WS_ICON "workspace_icon-default"
#define DEFAULT_WS_LABEL "%icon% %name%"
std::string get_socket_path()
{
std::string socket_path = BSPWM_SOCKET_PATH;
const char *env_bs = std::getenv("BSPWM_SOCKET");
if (env_bs != nullptr)
socket_path = std::string(env_bs);
return socket_path;
}
bspwm::payload_t generate_payload(std::string command)
{
bspwm::payload_t payload;
size_t size = sizeof(payload.data);
int offset = 0, chars = 0;
for (auto &&sub: string::split(command, ' ')) {
chars = snprintf(payload.data + offset, size - offset, "%s%c", sub.c_str(), 0);
payload.len += chars;
offset += chars;
}
return payload;
}
bool send_payload(int fd, bspwm::payload_t payload)
{
int bytes = 0;
if ((bytes = send(fd, payload.data, payload.len, 0)) == -1)
log_debug("bspwm: Failed sending message to socket");
return bytes > 0;
}
int create_subscriber()
{
int socket_fd = -1;
std::string socket_path = get_socket_path();
if ((socket_fd = io::socket::open(socket_path)) == -1)
throw ModuleError("bspwm: Could not connect to socket: "+ socket_path);
if (!send_payload(socket_fd, generate_payload("subscribe report")))
throw ModuleError("bspwm: Failed to subscribe to bspwm changes");
return socket_fd;
}
BspwmModule::BspwmModule(std::string name_, std::string monitor)
: EventModule(name_)
, monitor(monitor)
{
this->formatter->add(DEFAULT_FORMAT, TAG_LABEL_STATE, { TAG_LABEL_STATE }, { TAG_LABEL_MODE });
if (this->formatter->has(TAG_LABEL_STATE)) {
this->state_labels.insert(std::make_pair(WORKSPACE_ACTIVE, drawtypes::get_optional_config_label(name(), "label-active", DEFAULT_WS_LABEL)));
this->state_labels.insert(std::make_pair(WORKSPACE_OCCUPIED, drawtypes::get_optional_config_label(name(), "label-occupied", DEFAULT_WS_LABEL)));
this->state_labels.insert(std::make_pair(WORKSPACE_URGENT, drawtypes::get_optional_config_label(name(), "label-urgent", DEFAULT_WS_LABEL)));
this->state_labels.insert(std::make_pair(WORKSPACE_EMPTY, drawtypes::get_optional_config_label(name(), "label-empty", DEFAULT_WS_LABEL)));
this->state_labels.insert(std::make_pair(WORKSPACE_DIMMED, drawtypes::get_optional_config_label(name(), "label-dimmed")));
}
if (this->formatter->has(TAG_LABEL_MODE)) {
this->mode_labels.insert(std::make_pair(MODE_LAYOUT_MONOCLE, drawtypes::get_optional_config_label(name(), "label-monocle")));
this->mode_labels.insert(std::make_pair(MODE_LAYOUT_TILED, drawtypes::get_optional_config_label(name(), "label-tiled")));
this->mode_labels.insert(std::make_pair(MODE_STATE_FULLSCREEN, drawtypes::get_optional_config_label(name(), "label-fullscreen")));
this->mode_labels.insert(std::make_pair(MODE_STATE_FLOATING, drawtypes::get_optional_config_label(name(), "label-floating")));
this->mode_labels.insert(std::make_pair(MODE_NODE_LOCKED, drawtypes::get_optional_config_label(name(), "label-locked")));
this->mode_labels.insert(std::make_pair(MODE_NODE_STICKY, drawtypes::get_optional_config_label(name(), "label-sticky")));
this->mode_labels.insert(std::make_pair(MODE_NODE_PRIVATE, drawtypes::get_optional_config_label(name(), "label-private")));
}
this->icons = std::make_unique<drawtypes::IconMap>();
this->icons->add(DEFAULT_WS_ICON, std::make_unique<drawtypes::Icon>(config::get<std::string>(name(), DEFAULT_WS_ICON, "")));
for (auto workspace : config::get_list<std::string>(name(), "workspace_icon", {})) {
auto vec = string::split(workspace, ';');
if (vec.size() == 2) this->icons->add(vec[0], std::make_unique<drawtypes::Icon>(vec[1]));
}
}
BspwmModule::~BspwmModule()
{
if (this->socket_fd > -1)
close(this->socket_fd);
}
void BspwmModule::start()
{
this->socket_fd = create_subscriber();
this->EventModule<BspwmModule>::start();
}
bool BspwmModule::has_event()
{
if (io::poll(this->socket_fd, POLLHUP, 0)) {
close(this->socket_fd);
this->logger->warning("bspwm: Reconnecting to socket...");
this->socket_fd = create_subscriber();
}
return io::poll(this->socket_fd, POLLIN, 100);
}
bool BspwmModule::update()
{
auto bytes_read = 0;
auto data = io::readline(this->socket_fd, bytes_read);
if (bytes_read <= 0 || data.empty() || data == this->prev_data)
return false;
this->prev_data = data;
unsigned long pos;
while ((pos = data.find("\n")) != std::string::npos)
data.erase(pos);
if (data.empty())
return false;
const auto prefix = std::string(BSPWM_STATUS_PREFIX);
if (data.compare(0, prefix.length(), prefix) != 0) {
this->logger->error("bspwm: Received unknown status -> "+ data);
return false;
}
// Extract the string for the defined monitor
const auto needle_active = ":M"+ this->monitor +":";
const auto needle_inactive = ":m"+ this->monitor +":";
if ((pos = data.find(prefix)) != std::string::npos)
data = data.replace(pos, prefix.length(), ":");
if ((pos = data.find(needle_active)) != std::string::npos)
data.erase(0, pos+1);
if ((pos = data.find(needle_inactive)) != std::string::npos)
data.erase(0, pos+1);
if ((pos = data.find(":m", 1)) != std::string::npos)
data.erase(pos);
if ((pos = data.find(":M", 1)) != std::string::npos)
data.erase(pos);
log_trace2(this->logger, data);
this->modes.clear();
this->workspaces.clear();
bool monitor_focused = true;
int workspace_n = 0;
for (auto &&tag : string::split(data, ':')) {
if (tag.empty()) continue;
auto value = tag.size() > 0 ? tag.substr(1) : "";
auto workspace_flag = WORKSPACE_NONE;
auto mode_flag = MODE_NONE;
switch (tag[0]) {
case 'm': monitor_focused = false; break;
case 'M': monitor_focused = true; break;
case 'F': workspace_flag = WORKSPACE_ACTIVE; break;
case 'O': workspace_flag = WORKSPACE_ACTIVE; break;
case 'o': workspace_flag = WORKSPACE_OCCUPIED; break;
case 'U': workspace_flag = WORKSPACE_URGENT; break;
case 'u': workspace_flag = WORKSPACE_URGENT; break;
case 'f': workspace_flag = WORKSPACE_EMPTY; break;
case 'L':
switch (value[0]) {
case 0: break;
case 'M': mode_flag = MODE_LAYOUT_MONOCLE; break;
case 'T': mode_flag = MODE_LAYOUT_TILED; break;
default: this->logger->warning("bspwm: Undefined L => "+ value);
}
break;
case 'T':
switch (value[0]) {
case 0: break;
case 'T': break;
case '=': mode_flag = MODE_STATE_FULLSCREEN; break;
case 'F': mode_flag = MODE_STATE_FLOATING; break;
default: this->logger->warning("bspwm: Undefined T => "+ value);
}
break;
case 'G':
repeat(value.length())
{
switch (value[repeat_i]) {
case 0: break;
case 'L': mode_flag = MODE_NODE_LOCKED; break;
case 'S': mode_flag = MODE_NODE_STICKY; break;
case 'P': mode_flag = MODE_NODE_PRIVATE; break;
default: this->logger->warning("bspwm: Undefined G => "+ value.substr(repeat_i, 1));
}
if (mode_flag != MODE_NONE && !this->mode_labels.empty())
this->modes.emplace_back(&this->mode_labels.find(mode_flag)->second);
}
continue;
default: this->logger->warning("bspwm: Undefined tag => "+ tag.substr(0, 1));
}
if (workspace_flag != WORKSPACE_NONE && this->formatter->has(TAG_LABEL_STATE)) {
std::unique_ptr<drawtypes::Icon> &icon = this->icons->get(value, DEFAULT_WS_ICON);
std::unique_ptr<drawtypes::Label> label = this->state_labels.find(workspace_flag)->second->clone();
if (!monitor_focused)
label->replace_defined_values(this->state_labels.find(WORKSPACE_DIMMED)->second);
label->replace_token("%name%", value);
label->replace_token("%icon%", icon->text);
label->replace_token("%index%", std::to_string(++workspace_n));
this->workspaces.emplace_back(std::make_unique<Workspace>(workspace_flag, std::move(label)));
}
if (mode_flag != MODE_NONE && !this->mode_labels.empty())
this->modes.emplace_back(&this->mode_labels.find(mode_flag)->second);
}
if (!monitor_focused) this->modes.clear();
return true;
}
bool BspwmModule::build(Builder *builder, std::string tag)
{
if (tag != TAG_LABEL_STATE)
return false;
int workspace_n = 0;
for (auto &&ws : this->workspaces) {
if (!ws.get()->label->text.empty())
builder->cmd(Cmd::LEFT_CLICK, std::string(EVENT_CLICK) + std::to_string(++workspace_n));
builder->node(ws.get()->label);
if (ws->flag == WORKSPACE_ACTIVE && this->formatter->has(TAG_LABEL_MODE)) {
for (auto &&mode : this->modes)
builder->node(mode->get());
}
if (!ws.get()->label->text.empty())
builder->cmd_close(true);
}
return true;
}
bool BspwmModule::handle_command(std::string cmd)
{
if (cmd.find(EVENT_CLICK) == std::string::npos || cmd.length() <= std::strlen(EVENT_CLICK))
return false;
std::stringstream payload_s;
payload_s
<< "desktop -f "
<< this->monitor
<< ":^"
<< std::atoi(cmd.substr(std::strlen(EVENT_CLICK)).c_str());
int payload_fd;
std::string socket_path = get_socket_path();
if ((payload_fd = io::socket::open(socket_path)) == -1)
this->logger->error("bspwm: Failed to open socket: "+ socket_path);
else if (!send_payload(payload_fd, generate_payload(payload_s.str())))
this->logger->error("bspwm: Failed to change desktop");
close(payload_fd);
return true;
}
|
Handle report strings with 3+ monitors
|
fix(bspwm): Handle report strings with 3+ monitors
Fixes jaagr/lemonbuddy#54
|
C++
|
mit
|
jaagr/lemonbuddy,jaagr/polybar,jaagr/lemonbuddy,jaagr/polybar,jaagr/polybar,jaagr/lemonbuddy
|
20b511d890daf23a500e3d7106650641919c462c
|
src/nghttp2/Stock.cxx
|
src/nghttp2/Stock.cxx
|
/*
* Copyright 2007-2019 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 "Stock.hxx"
#include "Client.hxx"
#include "fs/Factory.hxx"
#include "event/TimerEvent.hxx"
#include "event/net/ConnectSocket.hxx"
#include "net/SocketAddress.hxx"
#include "net/ToString.hxx"
#include "io/Logger.hxx"
#include "util/djbhash.h"
#include "util/StringBuffer.hxx"
#include "AllocatorPtr.hxx"
#include <string>
#include <string.h>
namespace NgHttp2 {
class Stock::Item final
: public boost::intrusive::unordered_set_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>,
ConnectSocketHandler, ConnectionHandler
{
Stock &stock;
const std::string key;
SocketFilterFactory *const filter_factory;
std::unique_ptr<ClientConnection> connection;
struct GetRequest final
: boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>,
Cancellable {
Item &item;
StockGetHandler &handler;
GetRequest(Item &_item,
const StopwatchPtr &, // TODO
StockGetHandler &_handler,
CancellablePointer &cancel_ptr) noexcept
:item(_item), handler(_handler)
{
cancel_ptr = *this;
}
/* virtual methods from class Cancellable */
void Cancel() noexcept override {
item.CancelGetRequest(*this);
}
};
boost::intrusive::list<GetRequest,
boost::intrusive::constant_time_size<false>> get_requests;
CancellablePointer connect_cancel;
ConnectSocket connect_operation;
TimerEvent idle_timer;
FdType fd_type;
public:
template<typename K>
Item(Stock &_stock, EventLoop &event_loop, K &&_key,
SocketFilterFactory *_filter_factory) noexcept;
auto &GetEventLoop() const noexcept {
return idle_timer.GetEventLoop();
}
const std::string &GetKey() const noexcept {
return key;
}
void Start(SocketAddress bind_address,
SocketAddress address,
Event::Duration timeout) noexcept;
void AddGetHandler(AllocatorPtr alloc,
const StopwatchPtr &parent_stopwatch,
StockGetHandler &handler,
CancellablePointer &cancel_ptr) noexcept;
private:
void OnIdleTimer() noexcept;
void CancelGetRequest(GetRequest &request) noexcept;
void Cancel() noexcept;
void AbortConnectError(std::exception_ptr e) noexcept {
assert(!connection);
assert(!get_requests.empty());
get_requests.clear_and_dispose([&e](GetRequest *request){
request->handler.OnNgHttp2StockError(e);
});
stock.DeleteItem(this);
}
/* virtual methods from class ConnectSocketHandler */
void OnSocketConnectSuccess(UniqueSocketDescriptor &&fd) noexcept override;
void OnSocketConnectError(std::exception_ptr e) noexcept override {
AbortConnectError(std::move(e));
}
/* virtual methods from class ConnectionHandler */
void OnNgHttp2ConnectionIdle() noexcept override;
void OnNgHttp2ConnectionError(std::exception_ptr e) noexcept override;
void OnNgHttp2ConnectionClosed() noexcept override;
};
template<typename K>
Stock::Item::Item(Stock &_stock, EventLoop &event_loop, K &&_key,
SocketFilterFactory *_filter_factory) noexcept
:stock(_stock), key(std::forward<K>(_key)),
filter_factory(_filter_factory),
connect_operation(event_loop, *this),
idle_timer(event_loop, BIND_THIS_METHOD(OnIdleTimer))
{
}
void
Stock::Item::Start(SocketAddress bind_address,
SocketAddress address,
Event::Duration timeout) noexcept
{
const int address_family = address.GetFamily();
fd_type = address_family == AF_LOCAL
? FD_SOCKET
: FD_TCP;
(void)bind_address; // TODO
connect_operation.Connect(address, timeout);
}
void
Stock::Item::AddGetHandler(AllocatorPtr alloc,
const StopwatchPtr &parent_stopwatch,
StockGetHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
if (connection) {
assert(!connect_operation.IsPending());
idle_timer.Schedule(std::chrono::minutes(1));
handler.OnNgHttp2StockReady(*connection);
} else {
auto *request = alloc.New<GetRequest>(*this, parent_stopwatch,
handler, cancel_ptr);
get_requests.push_back(*request);
}
}
void
Stock::Item::CancelGetRequest(GetRequest &request) noexcept
{
assert(!get_requests.empty());
get_requests.erase_and_dispose(get_requests.iterator_to(request),
[](GetRequest *r) { r->~GetRequest(); });
if (get_requests.empty())
Cancel();
}
void
Stock::Item::Cancel() noexcept
{
assert(get_requests.empty());
if (connect_operation.IsPending()) {
assert(!connection);
connect_cancel.Cancel();
} else {
// TODO cancel SSL handshake?
}
stock.DeleteItem(this);
}
void
Stock::Item::OnSocketConnectSuccess(UniqueSocketDescriptor &&fd) noexcept
{
assert(!get_requests.empty());
assert(!connection);
NgHttp2::ConnectionHandler &handler = *this;
connection = std::make_unique<ClientConnection>(GetEventLoop(),
std::move(fd), fd_type,
filter_factory != nullptr
? filter_factory->CreateFilter()
: nullptr,
handler);
auto &c = *connection;
get_requests.clear_and_dispose([&c](GetRequest *request){
request->handler.OnNgHttp2StockReady(c);
});
}
void
Stock::Item::OnNgHttp2ConnectionIdle() noexcept
{
assert(connection);
assert(get_requests.empty());
idle_timer.Schedule(std::chrono::minutes(1));
}
void
Stock::Item::OnNgHttp2ConnectionError(std::exception_ptr e) noexcept
{
assert(connection);
assert(get_requests.empty());
LogConcat(1, key.c_str(), e);
stock.DeleteItem(this);
}
void
Stock::Item::OnNgHttp2ConnectionClosed() noexcept
{
assert(connection);
assert(get_requests.empty());
stock.DeleteItem(this);
}
void
Stock::Item::OnIdleTimer() noexcept
{
assert(connection);
assert(get_requests.empty());
if (connection->IsIdle())
stock.DeleteItem(this);
else
idle_timer.Schedule(std::chrono::minutes(1));
}
inline size_t
Stock::ItemHash::operator()(const char *key) const noexcept
{
return djb_hash_string(key);
}
inline size_t
Stock::ItemHash::operator()(const Item &item) const noexcept
{
return djb_hash_string(item.GetKey().c_str());
}
inline bool
Stock::ItemEqual::operator()(const char *a, const Item &b) const noexcept
{
return a == b.GetKey();
}
inline bool
Stock::ItemEqual::operator()(const Item &a, const Item &b) const noexcept
{
return a.GetKey() == b.GetKey();
}
Stock::Stock() noexcept
:items(Set::bucket_traits(buckets, N_BUCKETS))
{
}
Stock::~Stock() noexcept = default;
static StringBuffer<1024>
MakeKey(SocketAddress bind_address, SocketAddress address) noexcept
{
StringBuffer<1024> buffer;
char *p = buffer.data();
const auto end = buffer + buffer.capacity();
if (!bind_address.IsNull()) {
if (ToString(p, end - p - 1, bind_address))
p += strlen(p);
*p++ = '>';
}
if (ToString(p, end - p, address))
p += strlen(p);
*p = 0;
return buffer;
}
void
Stock::Get(EventLoop &event_loop,
AllocatorPtr alloc, const StopwatchPtr &parent_stopwatch,
const char *name,
SocketAddress bind_address,
SocketAddress address,
Event::Duration timeout,
SocketFilterFactory *filter_factory,
StockGetHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
const char *key;
StringBuffer<1024> key_buffer;
if (name != nullptr)
key = name;
else {
key_buffer = MakeKey(bind_address, address);
key = key_buffer.c_str();
}
Set::insert_commit_data hint;
auto i = items.insert_check(key, ItemHash(), ItemEqual(), hint);
Item *item;
if (i.second) {
item = new Item(*this, event_loop, key, filter_factory);
items.insert_commit(*item, hint);
} else
item = &*i.first;
item->AddGetHandler(alloc, parent_stopwatch, handler, cancel_ptr);
if (i.second)
item->Start(bind_address, address, timeout);
}
inline void
Stock::DeleteItem(Item *item) noexcept
{
items.erase(items.iterator_to(*item));
delete item;
}
} // namespace NgHttp2
|
/*
* Copyright 2007-2019 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 "Stock.hxx"
#include "Client.hxx"
#include "fs/Factory.hxx"
#include "event/TimerEvent.hxx"
#include "event/net/ConnectSocket.hxx"
#include "net/SocketAddress.hxx"
#include "net/ToString.hxx"
#include "io/Logger.hxx"
#include "util/djbhash.h"
#include "util/StringBuffer.hxx"
#include "AllocatorPtr.hxx"
#include <string>
#include <string.h>
namespace NgHttp2 {
class Stock::Item final
: public boost::intrusive::unordered_set_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>,
ConnectSocketHandler, ConnectionHandler
{
Stock &stock;
const std::string key;
SocketFilterFactory *const filter_factory;
std::unique_ptr<ClientConnection> connection;
struct GetRequest final
: boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>,
Cancellable {
Item &item;
StockGetHandler &handler;
GetRequest(Item &_item,
const StopwatchPtr &, // TODO
StockGetHandler &_handler,
CancellablePointer &cancel_ptr) noexcept
:item(_item), handler(_handler)
{
cancel_ptr = *this;
}
/* virtual methods from class Cancellable */
void Cancel() noexcept override {
item.CancelGetRequest(*this);
}
};
boost::intrusive::list<GetRequest,
boost::intrusive::constant_time_size<false>> get_requests;
CancellablePointer connect_cancel;
ConnectSocket connect_operation;
TimerEvent idle_timer;
FdType fd_type;
public:
template<typename K>
Item(Stock &_stock, EventLoop &event_loop, K &&_key,
SocketFilterFactory *_filter_factory) noexcept;
auto &GetEventLoop() const noexcept {
return idle_timer.GetEventLoop();
}
const std::string &GetKey() const noexcept {
return key;
}
void Start(SocketAddress bind_address,
SocketAddress address,
Event::Duration timeout) noexcept;
void AddGetHandler(AllocatorPtr alloc,
const StopwatchPtr &parent_stopwatch,
StockGetHandler &handler,
CancellablePointer &cancel_ptr) noexcept;
private:
void OnIdleTimer() noexcept;
void CancelGetRequest(GetRequest &request) noexcept;
void Cancel() noexcept;
void AbortConnectError(std::exception_ptr e) noexcept {
assert(!connection);
assert(!get_requests.empty());
get_requests.clear_and_dispose([&e](GetRequest *request){
request->handler.OnNgHttp2StockError(e);
});
stock.DeleteItem(this);
}
/* virtual methods from class ConnectSocketHandler */
void OnSocketConnectSuccess(UniqueSocketDescriptor &&fd) noexcept override;
void OnSocketConnectError(std::exception_ptr e) noexcept override {
AbortConnectError(std::move(e));
}
/* virtual methods from class ConnectionHandler */
void OnNgHttp2ConnectionIdle() noexcept override;
void OnNgHttp2ConnectionError(std::exception_ptr e) noexcept override;
void OnNgHttp2ConnectionClosed() noexcept override;
};
template<typename K>
Stock::Item::Item(Stock &_stock, EventLoop &event_loop, K &&_key,
SocketFilterFactory *_filter_factory) noexcept
:stock(_stock), key(std::forward<K>(_key)),
filter_factory(_filter_factory),
connect_operation(event_loop, *this),
idle_timer(event_loop, BIND_THIS_METHOD(OnIdleTimer))
{
}
void
Stock::Item::Start(SocketAddress bind_address,
SocketAddress address,
Event::Duration timeout) noexcept
{
const int address_family = address.GetFamily();
fd_type = address_family == AF_LOCAL
? FD_SOCKET
: FD_TCP;
(void)bind_address; // TODO
connect_operation.Connect(address, timeout);
}
void
Stock::Item::AddGetHandler(AllocatorPtr alloc,
const StopwatchPtr &parent_stopwatch,
StockGetHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
if (connection) {
assert(!connect_operation.IsPending());
idle_timer.Schedule(std::chrono::minutes(1));
handler.OnNgHttp2StockReady(*connection);
} else {
auto *request = alloc.New<GetRequest>(*this, parent_stopwatch,
handler, cancel_ptr);
get_requests.push_back(*request);
}
}
void
Stock::Item::CancelGetRequest(GetRequest &request) noexcept
{
assert(!get_requests.empty());
get_requests.erase_and_dispose(get_requests.iterator_to(request),
[](GetRequest *r) { r->~GetRequest(); });
if (get_requests.empty())
Cancel();
}
void
Stock::Item::Cancel() noexcept
{
assert(get_requests.empty());
if (connect_operation.IsPending()) {
assert(!connection);
connect_cancel.Cancel();
} else {
// TODO cancel SSL handshake?
}
stock.DeleteItem(this);
}
void
Stock::Item::OnSocketConnectSuccess(UniqueSocketDescriptor &&fd) noexcept
{
assert(!get_requests.empty());
assert(!connection);
NgHttp2::ConnectionHandler &handler = *this;
connection = std::make_unique<ClientConnection>(GetEventLoop(),
std::move(fd), fd_type,
filter_factory != nullptr
? filter_factory->CreateFilter()
: nullptr,
handler);
auto &c = *connection;
get_requests.clear_and_dispose([&c](GetRequest *request){
request->handler.OnNgHttp2StockReady(c);
});
}
void
Stock::Item::OnNgHttp2ConnectionIdle() noexcept
{
assert(connection);
assert(get_requests.empty());
idle_timer.Schedule(std::chrono::minutes(1));
}
void
Stock::Item::OnNgHttp2ConnectionError(std::exception_ptr e) noexcept
{
assert(connection);
assert(get_requests.empty());
LogConcat(1, key.c_str(), e);
stock.DeleteItem(this);
}
void
Stock::Item::OnNgHttp2ConnectionClosed() noexcept
{
assert(connection);
assert(get_requests.empty());
stock.DeleteItem(this);
}
void
Stock::Item::OnIdleTimer() noexcept
{
assert(connection);
assert(get_requests.empty());
if (connection->IsIdle())
stock.DeleteItem(this);
else
idle_timer.Schedule(std::chrono::minutes(1));
}
inline size_t
Stock::ItemHash::operator()(const char *key) const noexcept
{
return djb_hash_string(key);
}
inline size_t
Stock::ItemHash::operator()(const Item &item) const noexcept
{
return djb_hash_string(item.GetKey().c_str());
}
inline bool
Stock::ItemEqual::operator()(const char *a, const Item &b) const noexcept
{
return a == b.GetKey();
}
inline bool
Stock::ItemEqual::operator()(const Item &a, const Item &b) const noexcept
{
return a.GetKey() == b.GetKey();
}
Stock::Stock() noexcept
:items(Set::bucket_traits(buckets, N_BUCKETS))
{
}
Stock::~Stock() noexcept = default;
static StringBuffer<1024>
MakeKey(SocketAddress bind_address, SocketAddress address,
SocketFilterFactory *filter_factory) noexcept
{
StringBuffer<1024> buffer;
char *p = buffer.data();
const auto end = buffer + buffer.capacity();
if (!bind_address.IsNull()) {
if (ToString(p, end - p - 1, bind_address))
p += strlen(p);
*p++ = '>';
}
if (ToString(p, end - p, address))
p += strlen(p);
if (filter_factory != nullptr && p + 2 < end) {
*p++ = '|';
const char *id = filter_factory->GetFilterId();
if (id != nullptr) {
auto length = std::min<size_t>(strlen(id), end - p - 1);
p = (char *)mempcpy(p, id, length);
}
}
*p = 0;
return buffer;
}
void
Stock::Get(EventLoop &event_loop,
AllocatorPtr alloc, const StopwatchPtr &parent_stopwatch,
const char *name,
SocketAddress bind_address,
SocketAddress address,
Event::Duration timeout,
SocketFilterFactory *filter_factory,
StockGetHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
const char *key;
StringBuffer<1024> key_buffer;
if (name != nullptr)
key = name;
else {
key_buffer = MakeKey(bind_address, address, filter_factory);
key = key_buffer.c_str();
}
Set::insert_commit_data hint;
auto i = items.insert_check(key, ItemHash(), ItemEqual(), hint);
Item *item;
if (i.second) {
item = new Item(*this, event_loop, key, filter_factory);
items.insert_commit(*item, hint);
} else
item = &*i.first;
item->AddGetHandler(alloc, parent_stopwatch, handler, cancel_ptr);
if (i.second)
item->Start(bind_address, address, timeout);
}
inline void
Stock::DeleteItem(Item *item) noexcept
{
items.erase(items.iterator_to(*item));
delete item;
}
} // namespace NgHttp2
|
add SSL filter to hashtable key
|
nghttp2/Stock: add SSL filter to hashtable key
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
0d0d649a3064ec736ce03ca23673fec2802305b8
|
src/notary/Client.cpp
|
src/notary/Client.cpp
|
// Copyright (c) 2018 The Open-Transactions developers
// 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 "Client.hpp"
#define OT_METHOD "opentxs::notary::Client::"
namespace opentxs::notary
{
Client::Client(
const opentxs::api::client::Manager& client,
const opentxs::api::server::Manager& server,
const int network)
: client_(client)
, server_(server)
, network_(network)
, client_reason_(client_.Factory().PasswordPrompt("Notary operation"))
, server_reason_(client_.Factory().PasswordPrompt("Notary operation"))
, server_nym_callback_(network::zeromq::ListenCallback::Factory(
std::bind(&Client::server_nym_updated, this, std::placeholders::_1)))
, server_nym_subscriber_(
server_.ZeroMQ().SubscribeSocket(server_nym_callback_))
{
const auto started =
server_nym_subscriber_->Start(server_.Endpoints().NymDownload());
OT_ASSERT(started)
test_nym();
migrate_contract();
set_address_type();
client_.OTX().StartIntroductionServer(server_.NymID());
client_.OTX().PublishServerContract(
server_.NymID(), client_.OTX().IntroductionServer(), server_.ID());
}
void Client::import_nym() const
{
const auto serverNym =
server_.Wallet().Nym(server_.NymID(), server_reason_);
OT_ASSERT(serverNym)
proto::HDPath path{};
const auto havePath = serverNym->Path(path);
OT_ASSERT(havePath)
const auto seedID = Identifier::Factory(path.root());
OTPassword words{}, passphrase{};
words.setPassword(server_.Seeds().Words(server_reason_, seedID->str()));
passphrase.setPassword(
server_.Seeds().Passphrase(server_reason_, seedID->str()));
const auto imported =
client_.Seeds().ImportSeed(words, passphrase, client_reason_);
OT_ASSERT(imported == seedID->str())
OT_ASSERT(2 == path.child_size())
// TODO const auto index = path.child(1);
// TODO OT_ASSERT(0 == index)
{
#if OT_CRYPTO_SUPPORTED_KEY_HD
NymParameters nymParameters(proto::CREDTYPE_HD);
nymParameters.SetSeed(seedID->str());
nymParameters.SetNym(0);
nymParameters.SetDefault(false);
#else
NymParameters nymParameters(proto::CREDTYPE_LEGACY);
#endif
auto clientNym = client_.Wallet().Nym(nymParameters, client_reason_);
OT_ASSERT(clientNym)
OT_ASSERT(clientNym->CompareID(server_.NymID()))
}
}
void Client::migrate_contract() const
{
const auto serverContract =
server_.Wallet().Server(server_.ID(), server_reason_);
OT_ASSERT(serverContract)
auto clientContract = client_.Wallet().Server(
serverContract->PublicContract(), client_reason_);
OT_ASSERT(clientContract)
}
void Client::migrate_nym() const
{
const auto serverNym =
server_.Wallet().Nym(server_.NymID(), server_reason_);
OT_ASSERT(serverNym)
auto clientNym =
client_.Wallet().mutable_Nym(server_.NymID(), client_reason_);
clientNym.SetContactData(serverNym->Claims().Serialize(), client_reason_);
}
void Client::server_nym_updated(const network::zeromq::Message& message) const
{
if (1 > message.Body().size()) {
LogOutput(OT_METHOD)(__FUNCTION__)(": Missing nym ID.").Flush();
return;
}
const auto& frame = message.Body_at(0);
const auto id = Identifier::Factory(frame);
if (server_.NymID() == id) { migrate_nym(); }
}
void Client::set_address_type() const
{
if (network_ != client_.ZMQ().DefaultAddressType()) {
bool notUsed{false};
client_.Config().Set_long(
String::Factory("Connection"),
String::Factory("preferred_address_type"),
network_,
notUsed);
client_.Config().Save();
}
}
void Client::test_nym() const
{
const auto clientNym =
client_.Wallet().Nym(server_.NymID(), client_reason_);
if (false == bool(clientNym)) { import_nym(); }
migrate_nym();
}
} // namespace opentxs::notary
|
// Copyright (c) 2018 The Open-Transactions developers
// 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 "Client.hpp"
#define OT_METHOD "opentxs::notary::Client::"
namespace opentxs::notary
{
Client::Client(
const opentxs::api::client::Manager& client,
const opentxs::api::server::Manager& server,
const int network)
: client_(client)
, server_(server)
, network_(network)
, client_reason_(client_.Factory().PasswordPrompt("Notary operation"))
, server_reason_(client_.Factory().PasswordPrompt("Notary operation"))
, server_nym_callback_(network::zeromq::ListenCallback::Factory(
std::bind(&Client::server_nym_updated, this, std::placeholders::_1)))
, server_nym_subscriber_(
server_.ZeroMQ().SubscribeSocket(server_nym_callback_))
{
const auto started =
server_nym_subscriber_->Start(server_.Endpoints().NymDownload());
OT_ASSERT(started)
test_nym();
migrate_contract();
set_address_type();
client_.OTX().StartIntroductionServer(server_.NymID());
client_.OTX().PublishServerContract(
server_.NymID(), client_.OTX().IntroductionServer(), server_.ID());
}
void Client::import_nym() const
{
const auto serverNym =
server_.Wallet().Nym(server_.NymID(), server_reason_);
OT_ASSERT(serverNym)
proto::HDPath path{};
const auto havePath = serverNym->Path(path);
OT_ASSERT(havePath)
const auto seedID = Identifier::Factory(path.root());
OTPassword words{}, passphrase{};
words.setPassword(server_.Seeds().Words(server_reason_, seedID->str()));
passphrase.setPassword(
server_.Seeds().Passphrase(server_reason_, seedID->str()));
const auto imported =
client_.Seeds().ImportSeed(words, passphrase, client_reason_);
OT_ASSERT(imported == seedID->str())
OT_ASSERT(2 == path.child_size())
// TODO const auto index = path.child(1);
// TODO OT_ASSERT(0 == index)
{
#if OT_CRYPTO_SUPPORTED_KEY_HD
NymParameters nymParameters(proto::CREDTYPE_HD);
nymParameters.SetSeed(seedID->str());
nymParameters.SetNym(0);
nymParameters.SetDefault(false);
#else
NymParameters nymParameters(proto::CREDTYPE_LEGACY);
#endif
auto clientNym =
client_.Wallet().Nym(client_reason_, "", nymParameters);
OT_ASSERT(clientNym)
OT_ASSERT(clientNym->CompareID(server_.NymID()))
}
}
void Client::migrate_contract() const
{
const auto serverContract =
server_.Wallet().Server(server_.ID(), server_reason_);
OT_ASSERT(serverContract)
auto clientContract = client_.Wallet().Server(
serverContract->PublicContract(), client_reason_);
OT_ASSERT(clientContract)
}
void Client::migrate_nym() const
{
const auto serverNym =
server_.Wallet().Nym(server_.NymID(), server_reason_);
OT_ASSERT(serverNym)
auto clientNym =
client_.Wallet().mutable_Nym(server_.NymID(), client_reason_);
clientNym.SetContactData(serverNym->Claims().Serialize(), client_reason_);
}
void Client::server_nym_updated(const network::zeromq::Message& message) const
{
if (1 > message.Body().size()) {
LogOutput(OT_METHOD)(__FUNCTION__)(": Missing nym ID.").Flush();
return;
}
const auto& frame = message.Body_at(0);
const auto id = Identifier::Factory(frame);
if (server_.NymID() == id) { migrate_nym(); }
}
void Client::set_address_type() const
{
if (network_ != client_.ZMQ().DefaultAddressType()) {
bool notUsed{false};
client_.Config().Set_long(
String::Factory("Connection"),
String::Factory("preferred_address_type"),
network_,
notUsed);
client_.Config().Save();
}
}
void Client::test_nym() const
{
const auto clientNym =
client_.Wallet().Nym(server_.NymID(), client_reason_);
if (false == bool(clientNym)) { import_nym(); }
migrate_nym();
}
} // namespace opentxs::notary
|
Update for opentxs api change
|
Update for opentxs api change
|
C++
|
agpl-3.0
|
Open-Transactions/opentxs-notary
|
dbb307b4ec0bc2ef2b7fa76e02f629d49323f9ac
|
src/pool/pool.hxx
|
src/pool/pool.hxx
|
/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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.
*/
/*
* Memory pool.
*/
#ifndef BENG_PROXY_POOL_HXX
#define BENG_PROXY_POOL_HXX
#include "trace.h"
#include "util/Compiler.h"
#include <type_traits>
#include <utility>
#include <new>
#ifndef NDEBUG
#include <assert.h>
#endif
#include <stddef.h>
#include <stdbool.h>
struct pool;
class SlicePool;
struct AllocatorStats;
class PoolPtr;
class PoolLeakDetector;
struct pool_mark_state {
/**
* The area that was current when the mark was set.
*/
struct linear_pool_area *area;
/**
* The area before #area. This is used to dispose areas that were
* inserted before the current area due to a large allocation.
*/
struct linear_pool_area *prev;
/**
* The position within the current area when the mark was set.
*/
size_t position;
#ifndef NDEBUG
/**
* Used in an assertion: if the pool was empty before pool_mark(),
* it must be empty again after pool_rewind().
*/
bool was_empty;
#endif
};
template<typename T> struct ConstBuffer;
struct StringView;
void
pool_recycler_clear() noexcept;
gcc_malloc gcc_returns_nonnull
struct pool *
pool_new_libc(struct pool *parent, const char *name) noexcept;
gcc_malloc gcc_returns_nonnull
struct pool *
pool_new_linear(struct pool *parent, const char *name,
size_t initial_size) noexcept;
PoolPtr
pool_new_slice(struct pool *parent, const char *name,
SlicePool *slice_pool) noexcept;
#ifdef NDEBUG
#define pool_set_major(pool)
#else
void
pool_set_major(struct pool *pool) noexcept;
#endif
void
pool_ref_impl(struct pool *pool TRACE_ARGS_DECL) noexcept;
#define pool_ref(pool) pool_ref_impl(pool TRACE_ARGS)
#define pool_ref_fwd(pool) pool_ref_impl(pool TRACE_ARGS_FWD)
unsigned
pool_unref_impl(struct pool *pool TRACE_ARGS_DECL) noexcept;
#define pool_unref(pool) pool_unref_impl(pool TRACE_ARGS)
#define pool_unref_fwd(pool) pool_unref_impl(pool TRACE_ARGS_FWD)
class LinearPool {
struct pool &p;
public:
LinearPool(struct pool &parent, const char *name,
size_t initial_size) noexcept
:p(*pool_new_linear(&parent, name, initial_size)) {}
~LinearPool() noexcept {
gcc_unused auto ref = pool_unref(&p);
#ifndef NDEBUG
assert(ref == 0);
#endif
}
struct pool &get() noexcept {
return p;
}
operator struct pool &() noexcept {
return p;
}
operator struct pool *() noexcept {
return &p;
}
};
/**
* Returns the total size of all allocations in this pool.
*/
gcc_pure
size_t
pool_netto_size(const struct pool *pool) noexcept;
/**
* Returns the total amount of memory allocated by this pool.
*/
gcc_pure
size_t
pool_brutto_size(const struct pool *pool) noexcept;
/**
* Returns the total size of this pool and all of its descendants
* (recursively).
*/
gcc_pure
size_t
pool_recursive_netto_size(const struct pool *pool) noexcept;
gcc_pure
size_t
pool_recursive_brutto_size(const struct pool *pool) noexcept;
/**
* Returns the total size of all descendants of this pool (recursively).
*/
gcc_pure
size_t
pool_children_netto_size(const struct pool *pool) noexcept;
gcc_pure
size_t
pool_children_brutto_size(const struct pool *pool) noexcept;
AllocatorStats
pool_children_stats(const struct pool &pool) noexcept;
void
pool_dump_tree(const struct pool &pool) noexcept;
class ScopePoolRef {
struct pool &pool;
#ifdef TRACE
const char *const file;
unsigned line;
#endif
public:
explicit ScopePoolRef(struct pool &_pool TRACE_ARGS_DECL_) noexcept
:pool(_pool)
TRACE_ARGS_INIT
{
pool_ref_fwd(&_pool);
}
ScopePoolRef(const ScopePoolRef &) = delete;
~ScopePoolRef() noexcept {
pool_unref_fwd(&pool);
}
operator struct pool &() noexcept {
return pool;
}
operator struct pool *() noexcept {
return &pool;
}
};
#ifdef NDEBUG
static inline void
pool_trash(gcc_unused struct pool *pool) noexcept
{
}
static inline void
pool_commit() noexcept
{
}
static inline void
pool_attach(gcc_unused struct pool *pool, gcc_unused const void *p,
gcc_unused const char *name) noexcept
{
}
static inline void
pool_attach_checked(gcc_unused struct pool *pool, gcc_unused const void *p,
gcc_unused const char *name) noexcept
{
}
static inline void
pool_detach(gcc_unused struct pool *pool, gcc_unused const void *p) noexcept
{
}
#else
void
pool_trash(struct pool *pool) noexcept;
void
pool_commit() noexcept;
bool
pool_contains(const struct pool &pool, const void *ptr, size_t size) noexcept;
/**
* Register a #PoolLeakDetector to the pool.
*/
void
pool_register_leak_detector(struct pool &pool, PoolLeakDetector &ld) noexcept;
/**
* Attach an opaque object to the pool. It must be detached before
* the pool is destroyed. This is used in debugging mode to track
* whether all external objects have been destroyed.
*/
void
pool_attach(struct pool *pool, const void *p, const char *name) noexcept;
/**
* Same as pool_attach(), but checks if the object is already
* registered.
*/
void
pool_attach_checked(struct pool *pool, const void *p,
const char *name) noexcept;
void
pool_detach(struct pool *pool, const void *p) noexcept;
#endif
void
pool_mark(struct pool *pool, struct pool_mark_state *mark) noexcept;
void
pool_rewind(struct pool *pool, const struct pool_mark_state *mark) noexcept;
class AutoRewindPool {
struct pool &pool;
pool_mark_state mark;
public:
AutoRewindPool(struct pool &_pool) noexcept:pool(_pool) {
pool_mark(&pool, &mark);
}
AutoRewindPool(const AutoRewindPool &) = delete;
~AutoRewindPool() noexcept {
pool_rewind(&pool, &mark);
}
};
gcc_malloc gcc_returns_nonnull
void *
p_malloc_impl(struct pool *pool, size_t size TRACE_ARGS_DECL) noexcept;
#define p_malloc(pool, size) p_malloc_impl(pool, size TRACE_ARGS)
#define p_malloc_fwd(pool, size) p_malloc_impl(pool, size TRACE_ARGS_FWD)
void
p_free(struct pool *pool, const void *ptr) noexcept;
gcc_malloc gcc_returns_nonnull
void *
p_memdup_impl(struct pool *pool, const void *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_memdup(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS)
#define p_memdup_fwd(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strdup_impl(struct pool *pool, const char *src TRACE_ARGS_DECL) noexcept;
#define p_strdup(pool, src) p_strdup_impl(pool, src TRACE_ARGS)
#define p_strdup_fwd(pool, src) p_strdup_impl(pool, src TRACE_ARGS_FWD)
static inline const char *
p_strdup_checked(struct pool *pool, const char *s) noexcept
{
return s == NULL ? NULL : p_strdup(pool, s);
}
gcc_malloc gcc_returns_nonnull
char *
p_strdup_lower_impl(struct pool *pool, const char *src
TRACE_ARGS_DECL) noexcept;
#define p_strdup_lower(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS)
#define p_strdup_lower_fwd(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strndup_impl(struct pool *pool, const char *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_strndup(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS)
#define p_strndup_fwd(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strndup_lower_impl(struct pool *pool, const char *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_strndup_lower(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS)
#define p_strndup_lower_fwd(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull gcc_printf(2, 3)
char *
p_sprintf(struct pool *pool, const char *fmt, ...) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strcat(struct pool *pool, const char *s, ...) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strncat(struct pool *pool, const char *s, size_t length, ...) noexcept;
template<typename T>
gcc_malloc gcc_returns_nonnull
T *
PoolAlloc(pool &p) noexcept
{
#if CLANG_OR_GCC_VERSION(5,0)
static_assert(std::is_trivially_default_constructible<T>::value,
"Must be trivially constructible");
#else
static_assert(std::has_trivial_default_constructor<T>::value,
"Must be trivially constructible");
#endif
return (T *)p_malloc(&p, sizeof(T));
}
template<typename T>
gcc_malloc gcc_returns_nonnull
T *
PoolAlloc(pool &p, size_t n) noexcept
{
#if CLANG_OR_GCC_VERSION(5,0)
static_assert(std::is_trivially_default_constructible<T>::value,
"Must be trivially constructible");
#else
static_assert(std::has_trivial_default_constructor<T>::value,
"Must be trivially constructible");
#endif
return (T *)p_malloc(&p, sizeof(T) * n);
}
template<>
gcc_malloc gcc_returns_nonnull
inline void *
PoolAlloc<void>(pool &p, size_t n) noexcept
{
return p_malloc(&p, n);
}
template<typename T, typename... Args>
gcc_malloc gcc_returns_nonnull
T *
NewFromPool(pool &p, Args&&... args)
{
void *t = p_malloc(&p, sizeof(T));
return ::new(t) T(std::forward<Args>(args)...);
}
template<typename T>
void
DeleteFromPool(struct pool &pool, T *t) noexcept
{
t->~T();
p_free(&pool, t);
}
/**
* A disposer for boost::intrusive that invokes the DeleteFromPool()
* on the given pointer.
*/
class PoolDisposer {
struct pool &p;
public:
explicit PoolDisposer(struct pool &_p) noexcept:p(_p) {}
template<typename T>
void operator()(T *t) noexcept {
DeleteFromPool(p, t);
}
};
template<typename T>
void
DeleteUnrefPool(struct pool &pool, T *t) noexcept
{
DeleteFromPool(pool, t);
pool_unref(&pool);
}
template<typename T>
void
DeleteUnrefTrashPool(struct pool &pool, T *t) noexcept
{
pool_trash(&pool);
DeleteUnrefPool(pool, t);
}
gcc_malloc gcc_returns_nonnull
char *
p_strdup_impl(struct pool &pool, StringView src TRACE_ARGS_DECL) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strdup_lower_impl(struct pool &pool, StringView src
TRACE_ARGS_DECL) noexcept;
/**
* Concatenate all strings and return a newly allocated
* null-terminated string.
*/
char *
StringConcat(struct pool &pool, ConstBuffer<StringView> src) noexcept;
#endif
|
/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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.
*/
/*
* Memory pool.
*/
#ifndef BENG_PROXY_POOL_HXX
#define BENG_PROXY_POOL_HXX
#include "trace.h"
#include "util/Compiler.h"
#include <type_traits>
#include <utility>
#include <new>
#ifndef NDEBUG
#include <assert.h>
#endif
#include <stddef.h>
#include <stdbool.h>
struct pool;
class SlicePool;
struct AllocatorStats;
class PoolPtr;
class PoolLeakDetector;
struct pool_mark_state {
/**
* The area that was current when the mark was set.
*/
struct linear_pool_area *area;
/**
* The area before #area. This is used to dispose areas that were
* inserted before the current area due to a large allocation.
*/
struct linear_pool_area *prev;
/**
* The position within the current area when the mark was set.
*/
size_t position;
#ifndef NDEBUG
/**
* Used in an assertion: if the pool was empty before pool_mark(),
* it must be empty again after pool_rewind().
*/
bool was_empty;
#endif
};
template<typename T> struct ConstBuffer;
struct StringView;
void
pool_recycler_clear() noexcept;
gcc_malloc gcc_returns_nonnull
struct pool *
pool_new_libc(struct pool *parent, const char *name) noexcept;
gcc_malloc gcc_returns_nonnull
struct pool *
pool_new_linear(struct pool *parent, const char *name,
size_t initial_size) noexcept;
PoolPtr
pool_new_slice(struct pool *parent, const char *name,
SlicePool *slice_pool) noexcept;
#ifdef NDEBUG
#define pool_set_major(pool)
#else
void
pool_set_major(struct pool *pool) noexcept;
#endif
void
pool_ref_impl(struct pool *pool TRACE_ARGS_DECL) noexcept;
#define pool_ref(pool) pool_ref_impl(pool TRACE_ARGS)
#define pool_ref_fwd(pool) pool_ref_impl(pool TRACE_ARGS_FWD)
unsigned
pool_unref_impl(struct pool *pool TRACE_ARGS_DECL) noexcept;
#define pool_unref(pool) pool_unref_impl(pool TRACE_ARGS)
#define pool_unref_fwd(pool) pool_unref_impl(pool TRACE_ARGS_FWD)
class LinearPool {
struct pool &p;
public:
LinearPool(struct pool &parent, const char *name,
size_t initial_size) noexcept
:p(*pool_new_linear(&parent, name, initial_size)) {}
~LinearPool() noexcept {
gcc_unused auto ref = pool_unref(&p);
#ifndef NDEBUG
assert(ref == 0);
#endif
}
struct pool &get() noexcept {
return p;
}
operator struct pool &() noexcept {
return p;
}
operator struct pool *() noexcept {
return &p;
}
};
/**
* Returns the total size of all allocations in this pool.
*/
gcc_pure
size_t
pool_netto_size(const struct pool *pool) noexcept;
/**
* Returns the total amount of memory allocated by this pool.
*/
gcc_pure
size_t
pool_brutto_size(const struct pool *pool) noexcept;
/**
* Returns the total size of this pool and all of its descendants
* (recursively).
*/
gcc_pure
size_t
pool_recursive_netto_size(const struct pool *pool) noexcept;
gcc_pure
size_t
pool_recursive_brutto_size(const struct pool *pool) noexcept;
/**
* Returns the total size of all descendants of this pool (recursively).
*/
gcc_pure
size_t
pool_children_netto_size(const struct pool *pool) noexcept;
gcc_pure
size_t
pool_children_brutto_size(const struct pool *pool) noexcept;
AllocatorStats
pool_children_stats(const struct pool &pool) noexcept;
void
pool_dump_tree(const struct pool &pool) noexcept;
class ScopePoolRef {
struct pool &pool;
#ifdef TRACE
const char *const file;
unsigned line;
#endif
public:
explicit ScopePoolRef(struct pool &_pool TRACE_ARGS_DECL_) noexcept
:pool(_pool)
TRACE_ARGS_INIT
{
pool_ref_fwd(&_pool);
}
ScopePoolRef(const ScopePoolRef &) = delete;
~ScopePoolRef() noexcept {
pool_unref_fwd(&pool);
}
operator struct pool &() noexcept {
return pool;
}
operator struct pool *() noexcept {
return &pool;
}
};
#ifdef NDEBUG
static inline void
pool_trash(gcc_unused struct pool *pool) noexcept
{
}
static inline void
pool_commit() noexcept
{
}
static inline void
pool_attach(gcc_unused struct pool *pool, gcc_unused const void *p,
gcc_unused const char *name) noexcept
{
}
static inline void
pool_attach_checked(gcc_unused struct pool *pool, gcc_unused const void *p,
gcc_unused const char *name) noexcept
{
}
static inline void
pool_detach(gcc_unused struct pool *pool, gcc_unused const void *p) noexcept
{
}
#else
void
pool_trash(struct pool *pool) noexcept;
void
pool_commit() noexcept;
bool
pool_contains(const struct pool &pool, const void *ptr, size_t size) noexcept;
/**
* Register a #PoolLeakDetector to the pool.
*/
void
pool_register_leak_detector(struct pool &pool, PoolLeakDetector &ld) noexcept;
/**
* Attach an opaque object to the pool. It must be detached before
* the pool is destroyed. This is used in debugging mode to track
* whether all external objects have been destroyed.
*/
void
pool_attach(struct pool *pool, const void *p, const char *name) noexcept;
/**
* Same as pool_attach(), but checks if the object is already
* registered.
*/
void
pool_attach_checked(struct pool *pool, const void *p,
const char *name) noexcept;
void
pool_detach(struct pool *pool, const void *p) noexcept;
#endif
void
pool_mark(struct pool *pool, struct pool_mark_state *mark) noexcept;
void
pool_rewind(struct pool *pool, const struct pool_mark_state *mark) noexcept;
class AutoRewindPool {
struct pool *const pool;
pool_mark_state mark;
public:
AutoRewindPool(struct pool &_pool) noexcept:pool(&_pool) {
pool_mark(pool, &mark);
}
/**
* @param result_pool the pool where the caller's result will be
* put, and it must outlive this object; therefore, if it is the
* same pool as #_pool, this class is a no-op
*/
AutoRewindPool(struct pool &_pool, struct pool &result_pool) noexcept
:pool(&_pool != &result_pool ? &_pool : nullptr) {
if (pool != nullptr)
pool_mark(pool, &mark);
}
AutoRewindPool(const AutoRewindPool &) = delete;
~AutoRewindPool() noexcept {
if (pool != nullptr)
pool_rewind(pool, &mark);
}
};
gcc_malloc gcc_returns_nonnull
void *
p_malloc_impl(struct pool *pool, size_t size TRACE_ARGS_DECL) noexcept;
#define p_malloc(pool, size) p_malloc_impl(pool, size TRACE_ARGS)
#define p_malloc_fwd(pool, size) p_malloc_impl(pool, size TRACE_ARGS_FWD)
void
p_free(struct pool *pool, const void *ptr) noexcept;
gcc_malloc gcc_returns_nonnull
void *
p_memdup_impl(struct pool *pool, const void *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_memdup(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS)
#define p_memdup_fwd(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strdup_impl(struct pool *pool, const char *src TRACE_ARGS_DECL) noexcept;
#define p_strdup(pool, src) p_strdup_impl(pool, src TRACE_ARGS)
#define p_strdup_fwd(pool, src) p_strdup_impl(pool, src TRACE_ARGS_FWD)
static inline const char *
p_strdup_checked(struct pool *pool, const char *s) noexcept
{
return s == NULL ? NULL : p_strdup(pool, s);
}
gcc_malloc gcc_returns_nonnull
char *
p_strdup_lower_impl(struct pool *pool, const char *src
TRACE_ARGS_DECL) noexcept;
#define p_strdup_lower(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS)
#define p_strdup_lower_fwd(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strndup_impl(struct pool *pool, const char *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_strndup(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS)
#define p_strndup_fwd(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strndup_lower_impl(struct pool *pool, const char *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_strndup_lower(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS)
#define p_strndup_lower_fwd(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull gcc_printf(2, 3)
char *
p_sprintf(struct pool *pool, const char *fmt, ...) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strcat(struct pool *pool, const char *s, ...) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strncat(struct pool *pool, const char *s, size_t length, ...) noexcept;
template<typename T>
gcc_malloc gcc_returns_nonnull
T *
PoolAlloc(pool &p) noexcept
{
#if CLANG_OR_GCC_VERSION(5,0)
static_assert(std::is_trivially_default_constructible<T>::value,
"Must be trivially constructible");
#else
static_assert(std::has_trivial_default_constructor<T>::value,
"Must be trivially constructible");
#endif
return (T *)p_malloc(&p, sizeof(T));
}
template<typename T>
gcc_malloc gcc_returns_nonnull
T *
PoolAlloc(pool &p, size_t n) noexcept
{
#if CLANG_OR_GCC_VERSION(5,0)
static_assert(std::is_trivially_default_constructible<T>::value,
"Must be trivially constructible");
#else
static_assert(std::has_trivial_default_constructor<T>::value,
"Must be trivially constructible");
#endif
return (T *)p_malloc(&p, sizeof(T) * n);
}
template<>
gcc_malloc gcc_returns_nonnull
inline void *
PoolAlloc<void>(pool &p, size_t n) noexcept
{
return p_malloc(&p, n);
}
template<typename T, typename... Args>
gcc_malloc gcc_returns_nonnull
T *
NewFromPool(pool &p, Args&&... args)
{
void *t = p_malloc(&p, sizeof(T));
return ::new(t) T(std::forward<Args>(args)...);
}
template<typename T>
void
DeleteFromPool(struct pool &pool, T *t) noexcept
{
t->~T();
p_free(&pool, t);
}
/**
* A disposer for boost::intrusive that invokes the DeleteFromPool()
* on the given pointer.
*/
class PoolDisposer {
struct pool &p;
public:
explicit PoolDisposer(struct pool &_p) noexcept:p(_p) {}
template<typename T>
void operator()(T *t) noexcept {
DeleteFromPool(p, t);
}
};
template<typename T>
void
DeleteUnrefPool(struct pool &pool, T *t) noexcept
{
DeleteFromPool(pool, t);
pool_unref(&pool);
}
template<typename T>
void
DeleteUnrefTrashPool(struct pool &pool, T *t) noexcept
{
pool_trash(&pool);
DeleteUnrefPool(pool, t);
}
gcc_malloc gcc_returns_nonnull
char *
p_strdup_impl(struct pool &pool, StringView src TRACE_ARGS_DECL) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strdup_lower_impl(struct pool &pool, StringView src
TRACE_ARGS_DECL) noexcept;
/**
* Concatenate all strings and return a newly allocated
* null-terminated string.
*/
char *
StringConcat(struct pool &pool, ConstBuffer<StringView> src) noexcept;
#endif
|
add constructor overload with second pool
|
pool/AutoRewindPool: add constructor overload with second pool
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
d4c550abd0216822f22c38dab03985a1197f923b
|
src/nova_renderer.cpp
|
src/nova_renderer.cpp
|
/*!
* \author ddubois
* \date 03-Sep-18.
*/
#include <future>
#include "nova_renderer.hpp"
#include "glslang/MachineIndependent/Initialize.h"
#include "loading/shaderpack/shaderpack_loading.hpp"
#if defined(NOVA_WINDOWS)
#include "render_engine/dx12/dx12_render_engine.hpp"
#endif
#include "debugging/renderdoc.hpp"
#include "render_engine/vulkan/vulkan_render_engine.hpp"
#include <minitrace/minitrace.h>
namespace nova::renderer {
std::unique_ptr<nova_renderer> nova_renderer::instance;
nova_renderer::nova_renderer(const settings_options& settings)
: render_settings(settings), task_scheduler(1, nova::ttl::empty_queue_behavior::YIELD) {
mtr_init("trace.json");
MTR_META_PROCESS_NAME("NovaRenderer");
MTR_META_THREAD_NAME("Main");
MTR_SCOPE("Init", "nova_renderer::nova_renderer");
if(settings.debug.renderdoc.enabled) {
MTR_SCOPE("Init", "LoadRenderdoc");
render_doc = load_renderdoc(settings.debug.renderdoc.renderdoc_dll_path);
if(render_doc != nullptr) {
render_doc->SetCaptureFilePathTemplate(settings.debug.renderdoc.capture_path.c_str());
RENDERDOC_InputButton capture_key[] = {eRENDERDOC_Key_F12, eRENDERDOC_Key_PrtScrn};
render_doc->SetCaptureKeys(capture_key, 1);
render_doc->SetCaptureOptionU32(eRENDERDOC_Option_AllowFullscreen, 1U);
render_doc->SetCaptureOptionU32(eRENDERDOC_Option_AllowVSync, 1U);
render_doc->SetCaptureOptionU32(eRENDERDOC_Option_VerifyMapWrites, 1U);
render_doc->SetCaptureOptionU32(eRENDERDOC_Option_SaveAllInitials, 1U);
render_doc->SetCaptureOptionU32(eRENDERDOC_Option_APIValidation, 1U);
}
}
switch(settings.api) {
case graphics_api::dx12:
#if defined(NOVA_WINDOWS)
{
MTR_SCOPE("Init", "InitDirectX12RenderEngine");
engine = std::make_unique<dx12_render_engine>(render_settings, &task_scheduler);
} break;
#else
NOVA_LOG(WARN) << "You selected the DX12 graphics API, but your system doesn't support it. Defaulting to Vulkan";
[[fallthrough]];
#endif
case graphics_api::vulkan:
MTR_SCOPE("Init", "InitVulkanRenderEngine");
engine = std::make_unique<vulkan_render_engine>(render_settings, &task_scheduler);
}
}
nova_renderer::~nova_renderer() { mtr_shutdown(); }
nova_settings& nova_renderer::get_settings() { return render_settings; }
void nova_renderer::execute_frame() const {
MTR_SCOPE("RenderLoop", "execute_frame");
engine->render_frame();
mtr_flush();
}
void nova_renderer::load_shaderpack(const std::string& shaderpack_name) const {
MTR_SCOPE("ShaderpackLoading", "load_shaderpack");
glslang::InitializeProcess();
const shaderpack_data shaderpack_data = load_shaderpack_data(fs::path(shaderpack_name));
engine->set_shaderpack(shaderpack_data);
NOVA_LOG(INFO) << "Shaderpack " << shaderpack_name << " loaded successfully";
}
render_engine* nova_renderer::get_engine() const { return engine.get(); }
nova_renderer* nova_renderer::get_instance() { return instance.get(); }
nova_renderer* nova_renderer::initialize(const settings_options& settings) {
return (instance = std::make_unique<nova_renderer>(settings)).get();
}
void nova_renderer::deinitialize() { instance = nullptr; }
nova::ttl::task_scheduler& nova_renderer::get_task_scheduler() { return task_scheduler; }
} // namespace nova::renderer
|
/*!
* \author ddubois
* \date 03-Sep-18.
*/
#include <array>
#include <future>
#include "nova_renderer.hpp"
#include "glslang/MachineIndependent/Initialize.h"
#include "loading/shaderpack/shaderpack_loading.hpp"
#if defined(NOVA_WINDOWS)
#include "render_engine/dx12/dx12_render_engine.hpp"
#endif
#include "debugging/renderdoc.hpp"
#include "render_engine/vulkan/vulkan_render_engine.hpp"
#include <minitrace/minitrace.h>
namespace nova::renderer {
std::unique_ptr<nova_renderer> nova_renderer::instance;
nova_renderer::nova_renderer(const settings_options& settings)
: render_settings(settings), task_scheduler(1, nova::ttl::empty_queue_behavior::YIELD) {
mtr_init("trace.json");
MTR_META_PROCESS_NAME("NovaRenderer");
MTR_META_THREAD_NAME("Main");
MTR_SCOPE("Init", "nova_renderer::nova_renderer");
if(settings.debug.renderdoc.enabled) {
MTR_SCOPE("Init", "LoadRenderdoc");
render_doc = load_renderdoc(settings.debug.renderdoc.renderdoc_dll_path);
if(render_doc != nullptr) {
render_doc->SetCaptureFilePathTemplate(settings.debug.renderdoc.capture_path.c_str());
std::array<RENDERDOC_InputButton> capture_key = {eRENDERDOC_Key_F12, eRENDERDOC_Key_PrtScrn};
render_doc->SetCaptureKeys(capture_key.data(), 1);
render_doc->SetCaptureOptionU32(eRENDERDOC_Option_AllowFullscreen, 1U);
render_doc->SetCaptureOptionU32(eRENDERDOC_Option_AllowVSync, 1U);
render_doc->SetCaptureOptionU32(eRENDERDOC_Option_VerifyMapWrites, 1U);
render_doc->SetCaptureOptionU32(eRENDERDOC_Option_SaveAllInitials, 1U);
render_doc->SetCaptureOptionU32(eRENDERDOC_Option_APIValidation, 1U);
}
}
switch(settings.api) {
case graphics_api::dx12:
#if defined(NOVA_WINDOWS)
{
MTR_SCOPE("Init", "InitDirectX12RenderEngine");
engine = std::make_unique<dx12_render_engine>(render_settings, &task_scheduler);
} break;
#else
NOVA_LOG(WARN) << "You selected the DX12 graphics API, but your system doesn't support it. Defaulting to Vulkan";
[[fallthrough]];
#endif
case graphics_api::vulkan:
MTR_SCOPE("Init", "InitVulkanRenderEngine");
engine = std::make_unique<vulkan_render_engine>(render_settings, &task_scheduler);
}
}
nova_renderer::~nova_renderer() { mtr_shutdown(); }
nova_settings& nova_renderer::get_settings() { return render_settings; }
void nova_renderer::execute_frame() const {
MTR_SCOPE("RenderLoop", "execute_frame");
engine->render_frame();
mtr_flush();
}
void nova_renderer::load_shaderpack(const std::string& shaderpack_name) const {
MTR_SCOPE("ShaderpackLoading", "load_shaderpack");
glslang::InitializeProcess();
const shaderpack_data shaderpack_data = load_shaderpack_data(fs::path(shaderpack_name));
engine->set_shaderpack(shaderpack_data);
NOVA_LOG(INFO) << "Shaderpack " << shaderpack_name << " loaded successfully";
}
render_engine* nova_renderer::get_engine() const { return engine.get(); }
nova_renderer* nova_renderer::get_instance() { return instance.get(); }
nova_renderer* nova_renderer::initialize(const settings_options& settings) {
return (instance = std::make_unique<nova_renderer>(settings)).get();
}
void nova_renderer::deinitialize() { instance = nullptr; }
nova::ttl::task_scheduler& nova_renderer::get_task_scheduler() { return task_scheduler; }
} // namespace nova::renderer
|
Use std::array over c array
|
Use std::array over c array
|
C++
|
lgpl-2.1
|
DethRaid/vulkan-mod,DethRaid/vulkan-mod,DethRaid/vulkan-mod
|
0e9ecff508f015937ee4814ec1513b6bb5308f2b
|
src/qc-adaptor.cc
|
src/qc-adaptor.cc
|
/*
* ============================================================================
*
* Filename: qc-adaptor.cc
* Description: Trim adaptor read-through from reads
* License: LGPL-3+
* Author: Kevin Murray, [email protected]
*
* ============================================================================
*/
/* Copyright (c) 2015 Kevin Murray
*
* This program 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 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <yaml-cpp/yaml.h>
#include <seqan/modifier.h>
#include <seqan/align.h>
#include "qc-adaptor.hh"
namespace qcpp
{
AdaptorTrimPE::
AdaptorTrimPE(const std::string &name, int min_overlap,
const QualityEncoding &encoding):
ReadProcessor(name, encoding),
_num_pairs_trimmed(0),
_num_pairs_joined(0),
_min_overlap(min_overlap)
{
}
void
AdaptorTrimPE::
process_read_pair(ReadPair &the_read_pair)
{
seqan::Align<std::string, seqan::ArrayGaps> aligner;
std::string r2_rc = the_read_pair.second.sequence;
int score = 0;
seqan::reverseComplement(r2_rc);
resize(rows(aligner), 2);
assignSource(row(aligner, 0), the_read_pair.first.sequence);
assignSource(row(aligner, 1), r2_rc);
score = seqan::globalAlignment(aligner,
seqan::Score<int, seqan::Simple>(1, -3, -3, -3),
seqan::AlignConfig<true, true, true, true>());
std::string &r1_seq = the_read_pair.first.sequence;
std::string &r2_seq = the_read_pair.second.sequence;
std::string &r1_qual = the_read_pair.first.quality;
std::string &r2_qual = the_read_pair.second.quality;
if (score >= _min_overlap) {
size_t r1_len = the_read_pair.first.size();
size_t r2_len = the_read_pair.second.size();
ssize_t read_len_diff = r1_len - r2_len;
size_t r1_start = toViewPosition(row(aligner, 0), 0);
size_t r2_start = toViewPosition(row(aligner, 1), 0);
// Complement R2, as we use it to correct R1 below or concatenation it
// to R1 if it's the read needs merging.
seqan::complement(r2_seq);
if (r1_start >= r2_start - read_len_diff) {
// Adaptor read-through, trim R1, remove R2.
size_t new_len = r1_len - read_len_diff - r1_start;
new_len = new_len > r1_seq.size() ? r1_seq.size() : new_len;
for (size_t i = 0; i < new_len; i++) {
size_t r2_pos = new_len - i - 1;
if (r1_qual[i] < r2_qual[r2_pos]) {
r1_seq[i] = r2_seq[r2_pos];
r1_qual[i] = r2_qual[r2_pos];
}
}
// Trim the read to its new length
r1_seq.erase(new_len);
r1_qual.erase(new_len);
// Remove R2, as it's just duplicated
r2_seq.erase();
r2_qual.erase();
_num_pairs_trimmed++;
} else {
// Read-through into acutal read, needs merging
size_t overlap_starts = r2_start;
size_t overlap_size = r1_len - r2_start;
// If R1 base is lower quality than R2, use the base from R2
for (size_t i = 0; i < overlap_size; i++) {
size_t r1_pos = overlap_starts + i;
size_t r2_pos = r2_len - i - 1;
if (r1_qual[r1_pos] < r2_qual[r2_pos]) {
r1_seq[r1_pos] = r2_seq[r2_pos];
r1_qual[r1_pos] = r2_qual[r2_pos];
}
}
// Remove the overlap from the read
r2_seq.erase(overlap_starts - read_len_diff);
r2_qual.erase(overlap_starts - read_len_diff);
// Reverse the second read, so we can append it directly to the
// first read
std::reverse(r2_seq.begin(), r2_seq.end());
std::reverse(r2_qual.begin(), r2_qual.end());
// Append to form one psuedo read
r1_seq += r2_seq;
r1_qual += r2_qual;
// Remove the second read from the read pair, so it doesn't get
// printed.
r2_seq.erase();
r2_qual.erase();
_num_pairs_joined++;
}
}
_num_reads += 2;
}
void
AdaptorTrimPE::
add_stats_from(ReadProcessor *other_ptr)
{
AdaptorTrimPE &other = *reinterpret_cast<AdaptorTrimPE *>(other_ptr);
_num_reads += other._num_reads;
_num_pairs_trimmed += other._num_pairs_trimmed;
_num_pairs_joined += other._num_pairs_joined;
}
std::string
AdaptorTrimPE::
yaml_report()
{
std::ostringstream ss;
YAML::Emitter yml;
float percent_trimmed = (_num_pairs_trimmed * 2 / (float) _num_reads ) * 100;
float percent_merged = (_num_pairs_joined * 2 / (float) _num_reads ) * 100;
yml << YAML::BeginSeq;
yml << YAML::BeginMap;
yml << YAML::Key << "AdaptorTrimPE"
<< YAML::Value
<< YAML::BeginMap
<< YAML::Key << "name"
<< YAML::Value << _name
<< YAML::Key << "parameters"
<< YAML::Value << YAML::BeginMap
<< YAML::Key << "quality_encoding"
<< YAML::Value << _encoding.name
<< YAML::Key << "min_overlap"
<< YAML::Value << _min_overlap
<< YAML::EndMap
<< YAML::Key << "output"
<< YAML::Value << YAML::BeginMap
<< YAML::Key << "num_reads"
<< YAML::Value << _num_reads
<< YAML::Key << "num_trimmed"
<< YAML::Value << (_num_pairs_trimmed * 2)
<< YAML::Key << "num_merged"
<< YAML::Value << (_num_pairs_joined * 2)
<< YAML::Key << "percent_trimmed"
<< YAML::Value << percent_trimmed
<< YAML::Key << "percent_merged"
<< YAML::Value << percent_merged
<< YAML::EndMap
<< YAML::EndMap;
yml << YAML::EndMap;
yml << YAML::EndSeq;
ss << yml.c_str() << "\n";
return ss.str();
}
} // namespace qcpp
|
/*
* ============================================================================
*
* Filename: qc-adaptor.cc
* Description: Trim adaptor read-through from reads
* License: LGPL-3+
* Author: Kevin Murray, [email protected]
*
* ============================================================================
*/
/* Copyright (c) 2015 Kevin Murray
*
* This program 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 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <yaml-cpp/yaml.h>
#include <seqan/modifier.h>
#include <seqan/align.h>
#include "qc-adaptor.hh"
namespace qcpp
{
AdaptorTrimPE::
AdaptorTrimPE(const std::string &name, int min_overlap,
const QualityEncoding &encoding):
ReadProcessor(name, encoding),
_num_pairs_trimmed(0),
_num_pairs_joined(0),
_min_overlap(min_overlap)
{
}
void
AdaptorTrimPE::
process_read_pair(ReadPair &the_read_pair)
{
seqan::Align<std::string, seqan::ArrayGaps> aligner;
std::string r2_rc = the_read_pair.second.sequence;
int score = 0;
seqan::reverseComplement(r2_rc);
resize(rows(aligner), 2);
assignSource(row(aligner, 0), the_read_pair.first.sequence);
assignSource(row(aligner, 1), r2_rc);
score = seqan::globalAlignment(aligner,
seqan::Score<int, seqan::Simple>(1, -3, -3, -3),
seqan::AlignConfig<true, true, true, true>());
std::string &r1_seq = the_read_pair.first.sequence;
std::string &r2_seq = the_read_pair.second.sequence;
std::string &r1_qual = the_read_pair.first.quality;
std::string &r2_qual = the_read_pair.second.quality;
if (score >= _min_overlap) {
size_t r1_len = the_read_pair.first.size();
size_t r2_len = the_read_pair.second.size();
ssize_t read_len_diff = r1_len - r2_len;
ssize_t r1_start = toViewPosition(row(aligner, 0), 0);
ssize_t r2_start = toViewPosition(row(aligner, 1), 0);
// Complement R2, as we use it to correct R1 below or concatenation it
// to R1 if it's the read needs merging.
seqan::complement(r2_seq);
if (r1_start >= r2_start - read_len_diff) {
// Adaptor read-through, trim R1, remove R2.
size_t new_len = r1_len - read_len_diff - r1_start;
new_len = new_len > r1_seq.size() ? r1_seq.size() : new_len;
for (size_t i = 0; i < new_len; i++) {
size_t r2_pos = new_len - i - 1;
if (r1_qual[i] < r2_qual[r2_pos]) {
r1_seq[i] = r2_seq[r2_pos];
r1_qual[i] = r2_qual[r2_pos];
}
}
// Trim the read to its new length
r1_seq.erase(new_len);
r1_qual.erase(new_len);
// Remove R2, as it's just duplicated
r2_seq.erase();
r2_qual.erase();
_num_pairs_trimmed++;
} else {
// Read-through into acutal read, needs merging
size_t overlap_starts = r2_start;
size_t overlap_size = r1_len - r2_start;
// If R1 base is lower quality than R2, use the base from R2
for (size_t i = 0; i < overlap_size; i++) {
size_t r1_pos = overlap_starts + i;
size_t r2_pos = r2_len - i - 1;
if (r1_qual[r1_pos] < r2_qual[r2_pos]) {
r1_seq[r1_pos] = r2_seq[r2_pos];
r1_qual[r1_pos] = r2_qual[r2_pos];
}
}
// Remove the overlap from the read
r2_seq.erase(overlap_starts - read_len_diff);
r2_qual.erase(overlap_starts - read_len_diff);
// Reverse the second read, so we can append it directly to the
// first read
std::reverse(r2_seq.begin(), r2_seq.end());
std::reverse(r2_qual.begin(), r2_qual.end());
// Append to form one psuedo read
r1_seq += r2_seq;
r1_qual += r2_qual;
// Remove the second read from the read pair, so it doesn't get
// printed.
r2_seq.erase();
r2_qual.erase();
_num_pairs_joined++;
}
}
_num_reads += 2;
}
void
AdaptorTrimPE::
add_stats_from(ReadProcessor *other_ptr)
{
AdaptorTrimPE &other = *reinterpret_cast<AdaptorTrimPE *>(other_ptr);
_num_reads += other._num_reads;
_num_pairs_trimmed += other._num_pairs_trimmed;
_num_pairs_joined += other._num_pairs_joined;
}
std::string
AdaptorTrimPE::
yaml_report()
{
std::ostringstream ss;
YAML::Emitter yml;
float percent_trimmed = (_num_pairs_trimmed * 2 / (float) _num_reads ) * 100;
float percent_merged = (_num_pairs_joined * 2 / (float) _num_reads ) * 100;
yml << YAML::BeginSeq;
yml << YAML::BeginMap;
yml << YAML::Key << "AdaptorTrimPE"
<< YAML::Value
<< YAML::BeginMap
<< YAML::Key << "name"
<< YAML::Value << _name
<< YAML::Key << "parameters"
<< YAML::Value << YAML::BeginMap
<< YAML::Key << "quality_encoding"
<< YAML::Value << _encoding.name
<< YAML::Key << "min_overlap"
<< YAML::Value << _min_overlap
<< YAML::EndMap
<< YAML::Key << "output"
<< YAML::Value << YAML::BeginMap
<< YAML::Key << "num_reads"
<< YAML::Value << _num_reads
<< YAML::Key << "num_trimmed"
<< YAML::Value << (_num_pairs_trimmed * 2)
<< YAML::Key << "num_merged"
<< YAML::Value << (_num_pairs_joined * 2)
<< YAML::Key << "percent_trimmed"
<< YAML::Value << percent_trimmed
<< YAML::Key << "percent_merged"
<< YAML::Value << percent_merged
<< YAML::EndMap
<< YAML::EndMap;
yml << YAML::EndMap;
yml << YAML::EndSeq;
ss << yml.c_str() << "\n";
return ss.str();
}
} // namespace qcpp
|
Fix sign-comparison bug in AdaptorTrimPE
|
Fix sign-comparison bug in AdaptorTrimPE
|
C++
|
mpl-2.0
|
kdmurray91/libqcpp,kdmurray91/libqcpp,kdmurray91/libqcpp,kdmurray91/libqcpp,kdmurray91/libqcpp
|
5a1f2db8da6a098e41760ca77965ed0083ad636e
|
src/oldreader_api.cpp
|
src/oldreader_api.cpp
|
#include "oldreader_api.h"
#include <cstring>
#include <curl/curl.h>
#include <json.h>
#include <vector>
#include "config.h"
#include "strprintf.h"
#include "utils.h"
#define OLDREADER_LOGIN "https://theoldreader.com/accounts/ClientLogin"
#define OLDREADER_API_PREFIX "http://theoldreader.com/reader/api/0/"
#define OLDREADER_FEED_PREFIX "http://theoldreader.com/reader/atom/"
#define OLDREADER_OUTPUT_SUFFIX "?output=json"
#define OLDREADER_SUBSCRIPTION_LIST \
OLDREADER_API_PREFIX "subscription/list" OLDREADER_OUTPUT_SUFFIX
#define OLDREADER_API_MARK_ALL_READ_URL OLDREADER_API_PREFIX "mark-all-as-read"
#define OLDREADER_API_EDIT_TAG_URL OLDREADER_API_PREFIX "edit-tag"
#define OLDREADER_API_TOKEN_URL OLDREADER_API_PREFIX "token"
// for reference, see https://github.com/theoldreader/api
namespace newsboat {
oldreader_api::oldreader_api(configcontainer* c)
: remote_api(c)
{
// TODO
}
oldreader_api::~oldreader_api()
{
// TODO
}
bool oldreader_api::authenticate()
{
auth = retrieve_auth();
LOG(level::DEBUG, "oldreader_api::authenticate: Auth = %s", auth);
return auth != "";
}
static size_t
my_write_data(void* buffer, size_t size, size_t nmemb, void* userp)
{
std::string* pbuf = static_cast<std::string*>(userp);
pbuf->append(static_cast<const char*>(buffer), size * nmemb);
return size * nmemb;
}
std::string oldreader_api::retrieve_auth()
{
CURL* handle = curl_easy_init();
credentials cred = get_credentials("oldreader", "The Old Reader");
if (cred.user.empty() || cred.pass.empty()) {
return "";
}
char* username = curl_easy_escape(handle, cred.user.c_str(), 0);
char* password = curl_easy_escape(handle, cred.pass.c_str(), 0);
std::string postcontent = strprintf::fmt(
"service=reader&Email=%s&Passwd=%s&source=%s%2F%s&accountType="
"HOSTED_OR_GOOGLE&continue=http://www.google.com/",
username,
password,
PROGRAM_NAME,
PROGRAM_VERSION);
curl_free(username);
curl_free(password);
std::string result;
utils::set_common_curl_options(handle, cfg);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postcontent.c_str());
curl_easy_setopt(handle, CURLOPT_URL, OLDREADER_LOGIN);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
std::vector<std::string> lines = utils::tokenize(result);
for (const auto& line : lines) {
LOG(level::DEBUG,
"oldreader_api::retrieve_auth: line = %s",
line);
if (line.substr(0, 5) == "Auth=") {
std::string auth = line.substr(5, line.length() - 5);
return auth;
}
}
return "";
}
std::vector<tagged_feedurl> oldreader_api::get_subscribed_urls()
{
std::vector<tagged_feedurl> urls;
curl_slist* custom_headers{};
CURL* handle = curl_easy_init();
std::string result;
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
utils::set_common_curl_options(handle, cfg);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_URL, OLDREADER_SUBSCRIPTION_LIST);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(level::DEBUG,
"oldreader_api::get_subscribed_urls: document = %s",
result);
json_object* reply = json_tokener_parse(result.c_str());
if (reply == nullptr) {
LOG(level::ERROR,
"oldreader_api::get_subscribed_urls: failed to parse "
"response as JSON.");
return urls;
}
json_object* subscription_obj{};
json_object_object_get_ex(reply, "subscriptions", &subscription_obj);
struct array_list* subscriptions =
json_object_get_array(subscription_obj);
int len = array_list_length(subscriptions);
for (int i = 0; i < len; i++) {
std::vector<std::string> tags;
json_object* sub =
json_object_array_get_idx(subscription_obj, i);
json_object* node{};
json_object_object_get_ex(sub, "id", &node);
const char* id = json_object_get_string(node);
json_object_object_get_ex(sub, "title", &node);
const char* title = json_object_get_string(node);
// Ignore URLs where ID start with given prefix - those never
// load, always returning 404 and annoying people
const char* prefix = "tor/sponsored/";
if (strncmp(id, prefix, strlen(prefix)) != 0) {
tags.push_back(std::string("~") + title);
json_object_object_get_ex(sub, "categories", &node);
struct array_list* categories =
json_object_get_array(node);
#if JSON_C_MAJOR_VERSION == 0 && JSON_C_MINOR_VERSION < 13
for (int i = 0; i < array_list_length(categories);
i++) {
#else
for (size_t i = 0; i < array_list_length(categories);
i++) {
#endif
json_object* cat =
json_object_array_get_idx(node, i);
json_object* label_node{};
json_object_object_get_ex(
cat, "label", &label_node);
const char* label =
json_object_get_string(label_node);
tags.push_back(std::string(label));
}
auto url = strprintf::fmt("%s%s?n=%u",
OLDREADER_FEED_PREFIX,
id,
cfg->get_configvalue_as_int(
"oldreader-min-items"));
urls.push_back(tagged_feedurl(url, tags));
}
}
json_object_put(reply);
return urls;
}
void oldreader_api::add_custom_headers(curl_slist** custom_headers)
{
if (auth_header.empty()) {
auth_header = strprintf::fmt(
"Authorization: GoogleLogin auth=%s", auth);
}
LOG(level::DEBUG,
"oldreader_api::add_custom_headers header = %s",
auth_header);
*custom_headers =
curl_slist_append(*custom_headers, auth_header.c_str());
}
bool oldreader_api::mark_all_read(const std::string& feedurl)
{
std::string real_feedurl = feedurl.substr(strlen(OLDREADER_FEED_PREFIX),
feedurl.length() - strlen(OLDREADER_FEED_PREFIX));
std::vector<std::string> elems = utils::tokenize(real_feedurl, "?");
try {
real_feedurl = utils::unescape_url(elems[0]);
} catch (const std::runtime_error& e) {
LOG(level::DEBUG,
"oldreader_api::mark_all_read: Failed to "
"unescape_url(%s): "
"%s",
elems[0],
e.what());
return false;
}
std::string token = get_new_token();
std::string postcontent =
strprintf::fmt("s=%s&T=%s", real_feedurl, token);
std::string result =
post_content(OLDREADER_API_MARK_ALL_READ_URL, postcontent);
return result == "OK";
}
bool oldreader_api::mark_article_read(const std::string& guid, bool read)
{
std::string token = get_new_token();
return mark_article_read_with_token(guid, read, token);
}
bool oldreader_api::mark_article_read_with_token(const std::string& guid,
bool read,
const std::string& token)
{
std::string postcontent;
if (read) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/read&r=user/-/state/"
"com.google/kept-unread&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/read&a=user/-/state/"
"com.google/kept-unread&a=user/-/state/com.google/"
"tracking-kept-unread&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(OLDREADER_API_EDIT_TAG_URL, postcontent);
LOG(level::DEBUG,
"oldreader_api::mark_article_read_with_token: postcontent = %s "
"result = %s",
postcontent,
result);
return result == "OK";
}
std::string oldreader_api::get_new_token()
{
CURL* handle = curl_easy_init();
std::string result;
curl_slist* custom_headers{};
utils::set_common_curl_options(handle, cfg);
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_URL, OLDREADER_API_TOKEN_URL);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(level::DEBUG, "oldreader_api::get_new_token: token = %s", result);
return result;
}
bool oldreader_api::update_article_flags(const std::string& oldflags,
const std::string& newflags,
const std::string& guid)
{
std::string star_flag = cfg->get_configvalue("oldreader-flag-star");
std::string share_flag = cfg->get_configvalue("oldreader-flag-share");
bool success = true;
if (star_flag.length() > 0) {
if (strchr(oldflags.c_str(), star_flag[0]) == nullptr &&
strchr(newflags.c_str(), star_flag[0]) != nullptr) {
success = star_article(guid, true);
} else if (strchr(oldflags.c_str(), star_flag[0]) != nullptr &&
strchr(newflags.c_str(), star_flag[0]) == nullptr) {
success = star_article(guid, false);
}
}
if (share_flag.length() > 0) {
if (strchr(oldflags.c_str(), share_flag[0]) == nullptr &&
strchr(newflags.c_str(), share_flag[0]) != nullptr) {
success = share_article(guid, true);
} else if (strchr(oldflags.c_str(), share_flag[0]) != nullptr &&
strchr(newflags.c_str(), share_flag[0]) == nullptr) {
success = share_article(guid, false);
}
}
return success;
}
bool oldreader_api::star_article(const std::string& guid, bool star)
{
std::string token = get_new_token();
std::string postcontent;
if (star) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/starred&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/starred&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(OLDREADER_API_EDIT_TAG_URL, postcontent);
return result == "OK";
}
bool oldreader_api::share_article(const std::string& guid, bool share)
{
std::string token = get_new_token();
std::string postcontent;
if (share) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/broadcast&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/broadcast&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(OLDREADER_API_EDIT_TAG_URL, postcontent);
return result == "OK";
}
std::string oldreader_api::post_content(const std::string& url,
const std::string& postdata)
{
std::string result;
curl_slist* custom_headers{};
CURL* handle = curl_easy_init();
utils::set_common_curl_options(handle, cfg);
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postdata.c_str());
curl_easy_setopt(handle, CURLOPT_URL, url.c_str());
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(level::DEBUG,
"oldreader_api::post_content: url = %s postdata = %s result = "
"%s",
url,
postdata,
result);
return result;
}
} // namespace newsboat
|
#include "oldreader_api.h"
#include <cstring>
#include <curl/curl.h>
#include <json.h>
#include <vector>
#include "config.h"
#include "strprintf.h"
#include "utils.h"
#define OLDREADER_LOGIN "https://theoldreader.com/accounts/ClientLogin"
#define OLDREADER_API_PREFIX "https://theoldreader.com/reader/api/0/"
#define OLDREADER_FEED_PREFIX "https://theoldreader.com/reader/atom/"
#define OLDREADER_OUTPUT_SUFFIX "?output=json"
#define OLDREADER_SUBSCRIPTION_LIST \
OLDREADER_API_PREFIX "subscription/list" OLDREADER_OUTPUT_SUFFIX
#define OLDREADER_API_MARK_ALL_READ_URL OLDREADER_API_PREFIX "mark-all-as-read"
#define OLDREADER_API_EDIT_TAG_URL OLDREADER_API_PREFIX "edit-tag"
#define OLDREADER_API_TOKEN_URL OLDREADER_API_PREFIX "token"
// for reference, see https://github.com/theoldreader/api
namespace newsboat {
oldreader_api::oldreader_api(configcontainer* c)
: remote_api(c)
{
// TODO
}
oldreader_api::~oldreader_api()
{
// TODO
}
bool oldreader_api::authenticate()
{
auth = retrieve_auth();
LOG(level::DEBUG, "oldreader_api::authenticate: Auth = %s", auth);
return auth != "";
}
static size_t
my_write_data(void* buffer, size_t size, size_t nmemb, void* userp)
{
std::string* pbuf = static_cast<std::string*>(userp);
pbuf->append(static_cast<const char*>(buffer), size * nmemb);
return size * nmemb;
}
std::string oldreader_api::retrieve_auth()
{
CURL* handle = curl_easy_init();
credentials cred = get_credentials("oldreader", "The Old Reader");
if (cred.user.empty() || cred.pass.empty()) {
return "";
}
char* username = curl_easy_escape(handle, cred.user.c_str(), 0);
char* password = curl_easy_escape(handle, cred.pass.c_str(), 0);
std::string postcontent = strprintf::fmt(
"service=reader&Email=%s&Passwd=%s&source=%s%2F%s&accountType="
"HOSTED_OR_GOOGLE&continue=http://www.google.com/",
username,
password,
PROGRAM_NAME,
PROGRAM_VERSION);
curl_free(username);
curl_free(password);
std::string result;
utils::set_common_curl_options(handle, cfg);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postcontent.c_str());
curl_easy_setopt(handle, CURLOPT_URL, OLDREADER_LOGIN);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
std::vector<std::string> lines = utils::tokenize(result);
for (const auto& line : lines) {
LOG(level::DEBUG,
"oldreader_api::retrieve_auth: line = %s",
line);
if (line.substr(0, 5) == "Auth=") {
std::string auth = line.substr(5, line.length() - 5);
return auth;
}
}
return "";
}
std::vector<tagged_feedurl> oldreader_api::get_subscribed_urls()
{
std::vector<tagged_feedurl> urls;
curl_slist* custom_headers{};
CURL* handle = curl_easy_init();
std::string result;
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
utils::set_common_curl_options(handle, cfg);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_URL, OLDREADER_SUBSCRIPTION_LIST);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(level::DEBUG,
"oldreader_api::get_subscribed_urls: document = %s",
result);
json_object* reply = json_tokener_parse(result.c_str());
if (reply == nullptr) {
LOG(level::ERROR,
"oldreader_api::get_subscribed_urls: failed to parse "
"response as JSON.");
return urls;
}
json_object* subscription_obj{};
json_object_object_get_ex(reply, "subscriptions", &subscription_obj);
struct array_list* subscriptions =
json_object_get_array(subscription_obj);
int len = array_list_length(subscriptions);
for (int i = 0; i < len; i++) {
std::vector<std::string> tags;
json_object* sub =
json_object_array_get_idx(subscription_obj, i);
json_object* node{};
json_object_object_get_ex(sub, "id", &node);
const char* id = json_object_get_string(node);
json_object_object_get_ex(sub, "title", &node);
const char* title = json_object_get_string(node);
// Ignore URLs where ID start with given prefix - those never
// load, always returning 404 and annoying people
const char* prefix = "tor/sponsored/";
if (strncmp(id, prefix, strlen(prefix)) != 0) {
tags.push_back(std::string("~") + title);
json_object_object_get_ex(sub, "categories", &node);
struct array_list* categories =
json_object_get_array(node);
#if JSON_C_MAJOR_VERSION == 0 && JSON_C_MINOR_VERSION < 13
for (int i = 0; i < array_list_length(categories);
i++) {
#else
for (size_t i = 0; i < array_list_length(categories);
i++) {
#endif
json_object* cat =
json_object_array_get_idx(node, i);
json_object* label_node{};
json_object_object_get_ex(
cat, "label", &label_node);
const char* label =
json_object_get_string(label_node);
tags.push_back(std::string(label));
}
auto url = strprintf::fmt("%s%s?n=%u",
OLDREADER_FEED_PREFIX,
id,
cfg->get_configvalue_as_int(
"oldreader-min-items"));
urls.push_back(tagged_feedurl(url, tags));
}
}
json_object_put(reply);
return urls;
}
void oldreader_api::add_custom_headers(curl_slist** custom_headers)
{
if (auth_header.empty()) {
auth_header = strprintf::fmt(
"Authorization: GoogleLogin auth=%s", auth);
}
LOG(level::DEBUG,
"oldreader_api::add_custom_headers header = %s",
auth_header);
*custom_headers =
curl_slist_append(*custom_headers, auth_header.c_str());
}
bool oldreader_api::mark_all_read(const std::string& feedurl)
{
std::string real_feedurl = feedurl.substr(strlen(OLDREADER_FEED_PREFIX),
feedurl.length() - strlen(OLDREADER_FEED_PREFIX));
std::vector<std::string> elems = utils::tokenize(real_feedurl, "?");
try {
real_feedurl = utils::unescape_url(elems[0]);
} catch (const std::runtime_error& e) {
LOG(level::DEBUG,
"oldreader_api::mark_all_read: Failed to "
"unescape_url(%s): "
"%s",
elems[0],
e.what());
return false;
}
std::string token = get_new_token();
std::string postcontent =
strprintf::fmt("s=%s&T=%s", real_feedurl, token);
std::string result =
post_content(OLDREADER_API_MARK_ALL_READ_URL, postcontent);
return result == "OK";
}
bool oldreader_api::mark_article_read(const std::string& guid, bool read)
{
std::string token = get_new_token();
return mark_article_read_with_token(guid, read, token);
}
bool oldreader_api::mark_article_read_with_token(const std::string& guid,
bool read,
const std::string& token)
{
std::string postcontent;
if (read) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/read&r=user/-/state/"
"com.google/kept-unread&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/read&a=user/-/state/"
"com.google/kept-unread&a=user/-/state/com.google/"
"tracking-kept-unread&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(OLDREADER_API_EDIT_TAG_URL, postcontent);
LOG(level::DEBUG,
"oldreader_api::mark_article_read_with_token: postcontent = %s "
"result = %s",
postcontent,
result);
return result == "OK";
}
std::string oldreader_api::get_new_token()
{
CURL* handle = curl_easy_init();
std::string result;
curl_slist* custom_headers{};
utils::set_common_curl_options(handle, cfg);
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_URL, OLDREADER_API_TOKEN_URL);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(level::DEBUG, "oldreader_api::get_new_token: token = %s", result);
return result;
}
bool oldreader_api::update_article_flags(const std::string& oldflags,
const std::string& newflags,
const std::string& guid)
{
std::string star_flag = cfg->get_configvalue("oldreader-flag-star");
std::string share_flag = cfg->get_configvalue("oldreader-flag-share");
bool success = true;
if (star_flag.length() > 0) {
if (strchr(oldflags.c_str(), star_flag[0]) == nullptr &&
strchr(newflags.c_str(), star_flag[0]) != nullptr) {
success = star_article(guid, true);
} else if (strchr(oldflags.c_str(), star_flag[0]) != nullptr &&
strchr(newflags.c_str(), star_flag[0]) == nullptr) {
success = star_article(guid, false);
}
}
if (share_flag.length() > 0) {
if (strchr(oldflags.c_str(), share_flag[0]) == nullptr &&
strchr(newflags.c_str(), share_flag[0]) != nullptr) {
success = share_article(guid, true);
} else if (strchr(oldflags.c_str(), share_flag[0]) != nullptr &&
strchr(newflags.c_str(), share_flag[0]) == nullptr) {
success = share_article(guid, false);
}
}
return success;
}
bool oldreader_api::star_article(const std::string& guid, bool star)
{
std::string token = get_new_token();
std::string postcontent;
if (star) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/starred&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/starred&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(OLDREADER_API_EDIT_TAG_URL, postcontent);
return result == "OK";
}
bool oldreader_api::share_article(const std::string& guid, bool share)
{
std::string token = get_new_token();
std::string postcontent;
if (share) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/broadcast&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/broadcast&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(OLDREADER_API_EDIT_TAG_URL, postcontent);
return result == "OK";
}
std::string oldreader_api::post_content(const std::string& url,
const std::string& postdata)
{
std::string result;
curl_slist* custom_headers{};
CURL* handle = curl_easy_init();
utils::set_common_curl_options(handle, cfg);
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postdata.c_str());
curl_easy_setopt(handle, CURLOPT_URL, url.c_str());
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(level::DEBUG,
"oldreader_api::post_content: url = %s postdata = %s result = "
"%s",
url,
postdata,
result);
return result;
}
} // namespace newsboat
|
Use https for theoldreader.com URLs
|
Use https for theoldreader.com URLs
|
C++
|
mit
|
der-lyse/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat,newsboat/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat
|
bb53a499eeaf81a9513c1db205196a0e0a3d5d38
|
src/razors-v2.cpp
|
src/razors-v2.cpp
|
#include "estd.hpp"
#include "hstd.hpp"
#include "inlineshaders.hpp"
#include "razors-common.hpp"
#include "razorsV2.hpp"
#include "../gl3companion/glresource_types.hpp"
#include "../gl3companion/glinlines.hpp"
#include "../gl3texture/quad.hpp"
#include "../gl3texture/renderer.hpp"
#include <cmath>
static const double TAU =
6.28318530717958647692528676655900576839433879875021;
class RazorsV2
{};
RazorsV2Resource makeRazorsV2()
{
return estd::make_unique<RazorsV2>();
}
struct Rect {
float x;
float y;
float width;
float height;
};
struct QuadDefinerParams {
Rect coords;
Rect uvcoords;
};
static
size_t quadDefiner(BufferResource const& elementBuffer,
BufferResource const arrays[],
void const* data)
{
auto params = static_cast<QuadDefinerParams const*> (data);
auto& coords = params->coords;
auto& uvcoords = params->uvcoords;
size_t indicesCount = define2dQuadIndices(elementBuffer);
define2dQuadBuffer(arrays[0],
coords.x, coords.y,
coords.width, coords.height);
define2dQuadBuffer(arrays[1],
uvcoords.x, uvcoords.y,
uvcoords.width, uvcoords.height);
return indicesCount;
}
static void debug_texture(uint32_t* pixels, int width, int height, int depth,
void const* data)
{
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
pixels[i + j * width] = 0xFF408080;
}
}
}
void draw(RazorsV2& self, double ms)
{
auto resolution = viewport();
auto transparentWhite = [](float alpha) -> std::vector<float> {
return { alpha*1.0f, alpha*1.0f, alpha*1.0f, alpha };
};
#if 0
auto grey = [](float value) -> std::vector<float> {
// of course this is not real grey, need to go through
// the standard gamma + color correction instead
return { value, value, value, 1.0f };
};
#endif
auto scaleTransform = [](float scale) -> std::vector<float> {
return std::vector<float> {
scale, 0.01f, 0.0f, 0.0f,
-0.01f, scale, 0.0f, 0.0f,
0.0f, 0.0f, scale, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f,
};
};
auto quad = [](Rect coords, Rect uvcoords) -> GeometryDef {
auto geometry = GeometryDef {};
geometry.arrayCount = 2;
geometry.data.resize(sizeof(QuadDefinerParams));
auto params = new (&geometry.data.front()) QuadDefinerParams;
*params = {
.coords = coords,
.uvcoords = uvcoords,
};
geometry.definer = quadDefiner;
return geometry;
};
auto fullscreenQuad = [quad]() -> GeometryDef {
return quad(Rect { -1.f, -1.f, 2.0f, 2.0f }, Rect {0.f, 0.f, 1.f, 1.f });
};
auto identityMatrix = []() -> std::vector<float> {
return {
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
};
auto projector = [=](TextureDef const& texture,
float scale, std::pair<GLint, GLint> viewport) -> RenderObjectDef {
return RenderObjectDef {
.inputs = ProgramInputs {
{
{ "position", 2 },
{ "texcoord", 2 },
},
{
{
"tex", texture
}
},
{
ProgramInputs::FloatInput { .name = "g_color", .values = transparentWhite(0.9998f)},
ProgramInputs::FloatInput { .name = "transform", .values = scaleTransform(scale), .last_row = 3 },
ProgramInputs::FloatInput { .name = "iResolution", .values = { (float) viewport.first, (float) viewport.second, 0.0 } },
},
{},
},
.geometry = fullscreenQuad()
};
};
auto seedTexture = TextureDef {
{},
256,
256,
12,
(TextureDefFn) seed_texture,
};
auto debugTexture = TextureDef {
{},
256,
256,
0,
debug_texture,
};
auto seed = RenderObjectDef {
.inputs = ProgramInputs {
{
{ "position", 2 }, { "texcoord", 2 }
},
{
{ .name = "tex", seedTexture },
},
{
{ .name = "depth", .values = { (float)(0.5 * (1.0 + sin(TAU * ms / 3000.0))) } } ,
{ .name = "transform", .values = identityMatrix(), .last_row = 3 },
{ .name = "g_color", .values = transparentWhite(0.06f) },
},
{},
},
.geometry = fullscreenQuad(),
};
auto vertexShader = [](std::string content) -> VertexShaderDef {
return VertexShaderDef { .source = content };
};
auto fragmentShader = [](std::string content) -> FragmentShaderDef {
return FragmentShaderDef { .source = content };
};
static auto output = makeFrameSeries();
static auto previousFrame = TextureDef {
.width = 512,
.height = 512,
};
static auto resultFrame = TextureDef {
.width = 1024,
.height = 1024,
};
auto const clearFragments = FragmentOperationsDef {
FragmentOperationsDef::CLEAR, {}
};
auto const blendFragments = FragmentOperationsDef {
FragmentOperationsDef::BLEND_PREMULTIPLIED_ALPHA, {}
};
auto const clearAndBlendFragments = FragmentOperationsDef {
FragmentOperationsDef::CLEAR | FragmentOperationsDef::BLEND_PREMULTIPLIED_ALPHA, {}
};
auto const seedProgram = ProgramDef {
.vertexShader = vertexShader(seedVS),
.fragmentShader = fragmentShader(seedFS),
};
auto const projectorProgram = ProgramDef {
.vertexShader = vertexShader(defaultVS),
.fragmentShader = fragmentShader(projectorFS),
};
beginFrame(*output);
previousFrame = drawManyIntoTexture
(*output, previousFrame, clearAndBlendFragments,
projectorProgram, {
projector(resultFrame, 0.990f + 0.010f * sin(TAU * ms / 5000.0), resolution),
});
previousFrame = drawManyIntoTexture
(*output, previousFrame, blendFragments, seedProgram, {
seed,
});
resultFrame = drawManyIntoTexture
(*output, resultFrame, clearFragments, projectorProgram,
{ projector(previousFrame, 1.004f, resolution) });
drawMany(*output, clearFragments, projectorProgram,
{ projector(resultFrame, 1.0f, resolution) });
}
|
#include "estd.hpp"
#include "hstd.hpp"
#include "inlineshaders.hpp"
#include "razors-common.hpp"
#include "razorsV2.hpp"
#include "../gl3companion/glresource_types.hpp"
#include "../gl3companion/glinlines.hpp"
#include "../gl3texture/quad.hpp"
#include "../gl3texture/renderer.hpp"
#include <cmath>
static const double TAU =
6.28318530717958647692528676655900576839433879875021;
class RazorsV2
{};
RazorsV2Resource makeRazorsV2()
{
return estd::make_unique<RazorsV2>();
}
struct Rect {
float x;
float y;
float width;
float height;
};
struct QuadDefinerParams {
Rect coords;
Rect uvcoords;
};
static
size_t quadDefiner(BufferResource const& elementBuffer,
BufferResource const arrays[],
void const* data)
{
auto params = static_cast<QuadDefinerParams const*> (data);
auto& coords = params->coords;
auto& uvcoords = params->uvcoords;
size_t indicesCount = define2dQuadIndices(elementBuffer);
define2dQuadBuffer(arrays[0],
coords.x, coords.y,
coords.width, coords.height);
define2dQuadBuffer(arrays[1],
uvcoords.x, uvcoords.y,
uvcoords.width, uvcoords.height);
return indicesCount;
}
void draw(RazorsV2& self, double ms)
{
auto resolution = viewport();
auto transparentWhite = [](float alpha) -> std::vector<float> {
return { alpha*1.0f, alpha*1.0f, alpha*1.0f, alpha };
};
#if 0
auto grey = [](float value) -> std::vector<float> {
// of course this is not real grey, need to go through
// the standard gamma + color correction instead
return { value, value, value, 1.0f };
};
#endif
auto scaleTransform = [](float scale) -> std::vector<float> {
return std::vector<float> {
scale, 0.01f, 0.0f, 0.0f,
-0.01f, scale, 0.0f, 0.0f,
0.0f, 0.0f, scale, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f,
};
};
auto quad = [](Rect coords, Rect uvcoords) -> GeometryDef {
auto geometry = GeometryDef {};
geometry.arrayCount = 2;
geometry.data.resize(sizeof(QuadDefinerParams));
auto params = new (&geometry.data.front()) QuadDefinerParams;
*params = {
.coords = coords,
.uvcoords = uvcoords,
};
geometry.definer = quadDefiner;
return geometry;
};
auto fullscreenQuad = [quad]() -> GeometryDef {
return quad(Rect { -1.f, -1.f, 2.0f, 2.0f }, Rect {0.f, 0.f, 1.f, 1.f });
};
auto identityMatrix = []() -> std::vector<float> {
return {
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
};
auto projector = [=](TextureDef const& texture,
float scale, std::pair<GLint, GLint> viewport) -> RenderObjectDef {
return RenderObjectDef {
.inputs = ProgramInputs {
{
{ "position", 2 },
{ "texcoord", 2 },
},
{
{
"tex", texture
}
},
{
ProgramInputs::FloatInput { .name = "g_color", .values = transparentWhite(0.9998f)},
ProgramInputs::FloatInput { .name = "transform", .values = scaleTransform(scale), .last_row = 3 },
ProgramInputs::FloatInput { .name = "iResolution", .values = { (float) viewport.first, (float) viewport.second, 0.0 } },
},
{},
},
.geometry = fullscreenQuad()
};
};
auto seed = RenderObjectDef {
.inputs = ProgramInputs {
{
{ "position", 2 }, { "texcoord", 2 }
},
{
{
.name = "tex", TextureDef {
{},
256,
256,
12,
(TextureDefFn) seed_texture,
}
},
},
{
{ .name = "depth", .values = { (float)(0.5 * (1.0 + sin(TAU * ms / 3000.0))) } } ,
{ .name = "transform", .values = identityMatrix(), .last_row = 3 },
{ .name = "g_color", .values = transparentWhite(0.06f) },
},
{},
},
.geometry = fullscreenQuad(),
};
auto vertexShader = [](std::string content) -> VertexShaderDef {
return VertexShaderDef { .source = content };
};
auto fragmentShader = [](std::string content) -> FragmentShaderDef {
return FragmentShaderDef { .source = content };
};
static auto output = makeFrameSeries();
static auto previousFrame = TextureDef {
.width = 512,
.height = 512,
};
static auto resultFrame = TextureDef {
.width = 1024,
.height = 1024,
};
auto const clearFragments = FragmentOperationsDef {
FragmentOperationsDef::CLEAR, {}
};
auto const blendFragments = FragmentOperationsDef {
FragmentOperationsDef::BLEND_PREMULTIPLIED_ALPHA, {}
};
auto const clearAndBlendFragments = FragmentOperationsDef {
FragmentOperationsDef::CLEAR | FragmentOperationsDef::BLEND_PREMULTIPLIED_ALPHA, {}
};
auto const seedProgram = ProgramDef {
.vertexShader = vertexShader(seedVS),
.fragmentShader = fragmentShader(seedFS),
};
auto const projectorProgram = ProgramDef {
.vertexShader = vertexShader(defaultVS),
.fragmentShader = fragmentShader(projectorFS),
};
beginFrame(*output);
previousFrame = drawManyIntoTexture
(*output, previousFrame, clearAndBlendFragments,
projectorProgram, {
projector(resultFrame, 0.990f + 0.010f * sin(TAU * ms / 5000.0), resolution),
});
previousFrame = drawManyIntoTexture
(*output, previousFrame, blendFragments, seedProgram, {
seed,
});
resultFrame = drawManyIntoTexture
(*output, resultFrame, clearFragments, projectorProgram,
{ projector(previousFrame, 1.004f, resolution) });
drawMany(*output, clearFragments, projectorProgram,
{ projector(resultFrame, 1.0f, resolution) });
}
|
remove unused symbols
|
remove unused symbols
|
C++
|
mit
|
uucidl/exp.rendering-api,uucidl/exp.rendering-api,uucidl/exp.rendering-api
|
713c7df486311a4b57ea319937e24cbb53043fdf
|
src/model_builder.cpp
|
src/model_builder.cpp
|
#include "model_builder.hpp"
#include "model_basic_primitives.hpp"
#include "model_msh_save.hpp"
#include "model_scene.hpp"
#include "synced_cout.hpp"
#include <algorithm>
#include <iterator>
#include <string_view>
#include <tuple>
#include <fmt/format.h>
#include <gsl/gsl>
#include <tbb/tbb.h>
using namespace std::literals;
namespace model {
namespace {
template<typename Type>
void merge_containers(std::vector<Type>& into, std::vector<Type>& from) noexcept
{
into.insert(into.end(), std::make_move_iterator(from.begin()),
std::make_move_iterator(from.end()));
from.clear();
}
auto lod_suffix(const Lod lod) -> std::string_view
{
switch (lod) {
case Lod::zero:
return ""sv;
case Lod::one:
return "_lod1"sv;
case Lod::two:
return "_lod2"sv;
case Lod::three:
return "_lod3"sv;
case Lod::lowres:
return "_lowres"sv;
default:
std::terminate();
}
}
auto collision_flags_string(const Collision_flags flags) -> std::string
{
if (flags == Collision_flags::all) return ""s;
std::string str;
if (are_flags_set(flags, Collision_flags::soldier)) str += "s"sv;
if (are_flags_set(flags, Collision_flags::vehicle)) str += "v"sv;
if (are_flags_set(flags, Collision_flags::building)) str += "b"sv;
if (are_flags_set(flags, Collision_flags::terrain)) str += "t"sv;
if (are_flags_set(flags, Collision_flags::ordnance)) str += "o"sv;
if (are_flags_set(flags, Collision_flags::flyer)) str += "f"sv;
return str;
}
auto insert_scene_material(scene::Scene& scene, scene::Material material) -> std::size_t
{
if (auto it = std::find(scene.materials.begin(), scene.materials.end(), material);
it != scene.materials.end()) {
return static_cast<std::size_t>(std::distance(scene.materials.begin(), it));
}
const auto index = scene.materials.size();
scene.materials.emplace_back(std::move(material));
return index;
}
auto make_primitive_visualization_geometry(const Collision_primitive_type type,
const glm::vec3 size) -> scene::Geometry
{
const auto [indices, positions, normals, texcoords] = [type] {
using namespace primitives;
const auto as_spans = [](const auto&... args) {
return std::make_tuple(gsl::make_span(args)...);
};
switch (type) {
case Collision_primitive_type::sphere:
return as_spans(sphere_indices, sphere_vertex_positions, sphere_vertex_normals,
sphere_vertex_texcoords);
case Collision_primitive_type::cylinder:
return as_spans(cylinder_indices, cylinder_vertex_positions,
cylinder_vertex_normals, cylinder_vertex_texcoords);
case Collision_primitive_type::cube:
return as_spans(cube_indices, cube_vertex_positions, cube_vertex_normals,
cube_vertex_texcoords);
default:
std::terminate();
}
}();
scene::Geometry geometry{
.topology = primitives::primitive_topology,
.indices = Indices{std::cbegin(indices), std::cend(indices)},
.vertices = Vertices{static_cast<std::size_t>(positions.size()),
{.positions = true, .normals = true, .texcoords = true}}};
std::transform(std::cbegin(positions), std::cend(positions),
geometry.vertices.positions.get(),
[size](const auto pos) { return pos * size; });
std::copy(std::cbegin(normals), std::cend(normals), geometry.vertices.normals.get());
std::copy(std::cbegin(texcoords), std::cend(texcoords),
geometry.vertices.texcoords.get());
return geometry;
}
auto positions_to_vertices(const std::vector<glm::vec3>& positions) -> Vertices
{
Vertices vertices{positions.size(), {.positions = true}};
std::copy(std::cbegin(positions), std::cend(positions), vertices.positions.get());
return vertices;
}
auto create_scene(Model model) -> scene::Scene
{
scene::Scene scene{.name = std::move(model.name)};
scene.materials.push_back({.name = "default_material"});
if (model.bones.empty()) {
scene.nodes.push_back({.name = "root"s,
.parent = ""s,
.material_index = 0,
.type = scene::Node_type::null});
}
for (auto& bone : model.bones) {
scene.nodes.push_back({.name = std::move(bone.name),
.parent = std::move(bone.parent),
.material_index = 0,
.type = scene::Node_type::null,
.transform = bone.transform});
}
int name_counter = 0;
for (auto& part : model.parts) {
if (part.material.attached_light) {
scene.attached_lights.push_back(
{.node = part.name.value(),
.light = std::move(part.material.attached_light.value())});
}
scene.nodes.push_back(
{.name = part.name ? std::move(*part.name)
: fmt::format("mesh_part{}{}"sv, ++name_counter,
lod_suffix(part.lod)),
.parent = std::move(part.parent),
.material_index = insert_scene_material(
scene, scene::Material{.name = part.material.name.value_or(""s),
.diffuse_colour = part.material.diffuse_colour,
.specular_colour = part.material.specular_colour,
.specular_exponent = part.material.specular_exponent,
.flags = part.material.flags,
.rendertype = part.material.type,
.params = part.material.params,
.textures = std::move(part.material.textures)}),
.type = scene::Node_type::geometry,
.lod = part.lod,
.geometry = scene::Geometry{.topology = part.primitive_topology,
.indices = std::move(part.indices),
.vertices = std::move(part.vertices),
.bone_map = std::move(part.bone_map)}});
}
name_counter = 0;
for (auto& mesh : model.collision_meshes) {
scene.nodes.push_back(
{.name = fmt::format("collision_-{}-mesh{}"sv,
collision_flags_string(mesh.flags), ++name_counter),
.parent = scene.nodes.front().name, // take the dangerous assumption that the
// first node we added is root
.material_index = 0,
.type = scene::Node_type::collision,
.geometry =
scene::Geometry{.topology = mesh.primitive_topology,
.indices = std::move(mesh.indices),
.vertices = positions_to_vertices(mesh.positions)}});
}
for (auto& prim : model.collision_primitives) {
scene.nodes.push_back(
{.name =
fmt::format("p_-{}-{}"sv, prim.name, collision_flags_string(prim.flags)),
.parent = std::move(prim.parent),
.material_index = 0,
.type = scene::Node_type::collision_primitive,
.transform = prim.transform,
.geometry = make_primitive_visualization_geometry(prim.type, prim.size),
.collision = scene::Collision{.type = prim.type, .size = prim.size}});
}
for (auto& cloth : model.cloths) {
scene.nodes.push_back(
{.name = std::move(cloth.name),
.parent = std::move(cloth.parent),
.material_index = 0,
.type = scene::Node_type::cloth_geometry,
.transform = cloth.transform,
.cloth_geometry = scene::Cloth_geometry{
.texture_name = std::move(cloth.texture_name),
.vertices = std::move(cloth.vertices),
.indices = std::move(cloth.indices),
.fixed_points = std::move(cloth.fixed_points),
.fixed_weights = std::move(cloth.fixed_weights),
.stretch_constraints = std::move(cloth.stretch_constraints),
.cross_constraints = std::move(cloth.cross_constraints),
.bend_constraints = std::move(cloth.bend_constraints),
.collision = std::move(cloth.collision),
}});
}
name_counter = 0;
for (auto& material : scene.materials) {
if (!material.name.empty()) continue;
material.name = fmt::format("material{}"sv, ++name_counter);
}
for (const auto& node : scene.nodes) {
scene.softskin |= node.geometry ? node.geometry->vertices.softskinned : false;
scene.vertex_lighting |=
node.geometry ? node.geometry->vertices.static_lighting : false;
}
scene::reverse_pretransforms(scene);
scene::recreate_aabbs(scene);
return scene;
}
void save_model(Model model, File_saver& file_saver, const Game_version game_version)
{
msh::save_scene(create_scene(std::move(model)), file_saver, game_version);
}
}
Vertices::Vertices(const std::size_t size, const Create_flags flags) : size{size}
{
if (flags.positions) positions = std::make_unique<glm::vec3[]>(size);
if (flags.normals) normals = std::make_unique<glm::vec3[]>(size);
if (flags.tangents) tangents = std::make_unique<glm::vec3[]>(size);
if (flags.bitangents) bitangents = std::make_unique<glm::vec3[]>(size);
if (flags.colors) colors = std::make_unique<glm::vec4[]>(size);
if (flags.texcoords) texcoords = std::make_unique<glm::vec2[]>(size);
if (flags.bones) bones = std::make_unique<glm::u8vec3[]>(size);
if (flags.weights) weights = std::make_unique<glm::vec3[]>(size);
}
void Model::merge_with(Model other) noexcept
{
merge_containers(this->bones, other.bones);
merge_containers(this->parts, other.parts);
merge_containers(this->collision_meshes, other.collision_meshes);
merge_containers(this->collision_primitives, other.collision_primitives);
merge_containers(this->cloths, other.cloths);
}
void Models_builder::integrate(Model model) noexcept
{
std::lock_guard lock{_mutex};
if (const auto it = std::find_if(
_models.begin(), _models.end(),
[&](const auto& other) noexcept { return (model.name == other.name); });
it != _models.end()) {
it->merge_with(std::move(model));
}
else {
_models.emplace_back(std::move(model));
}
}
void Models_builder::save_models(File_saver& file_saver,
const Game_version game_version) noexcept
{
std::lock_guard lock{_mutex};
(void)(file_saver, game_version);
tbb::parallel_for_each(_models, [&](Model& model) {
save_model(std::move(model), file_saver, game_version);
});
_models.clear();
}
}
|
#include "model_builder.hpp"
#include "model_basic_primitives.hpp"
#include "model_msh_save.hpp"
#include "model_scene.hpp"
#include "synced_cout.hpp"
#include <algorithm>
#include <iterator>
#include <string_view>
#include <tuple>
#include <fmt/format.h>
#include <gsl/gsl>
#include <tbb/tbb.h>
using namespace std::literals;
namespace model {
namespace {
template<typename Type>
void merge_containers(std::vector<Type>& into, std::vector<Type>& from) noexcept
{
into.insert(into.end(), std::make_move_iterator(from.begin()),
std::make_move_iterator(from.end()));
from.clear();
}
auto lod_suffix(const Lod lod) -> std::string_view
{
switch (lod) {
case Lod::zero:
return ""sv;
case Lod::one:
return "_lod1"sv;
case Lod::two:
return "_lod2"sv;
case Lod::three:
return "_lod3"sv;
case Lod::lowres:
return "_lowres"sv;
default:
std::terminate();
}
}
auto collision_flags_string(const Collision_flags flags) -> std::string
{
if (flags == Collision_flags::all) return ""s;
std::string str;
if (are_flags_set(flags, Collision_flags::soldier)) str += "s"sv;
if (are_flags_set(flags, Collision_flags::vehicle)) str += "v"sv;
if (are_flags_set(flags, Collision_flags::building)) str += "b"sv;
if (are_flags_set(flags, Collision_flags::terrain)) str += "t"sv;
if (are_flags_set(flags, Collision_flags::ordnance)) str += "o"sv;
if (are_flags_set(flags, Collision_flags::flyer)) str += "f"sv;
return str;
}
auto insert_scene_material(scene::Scene& scene, scene::Material material) -> std::size_t
{
if (auto it = std::find(scene.materials.begin(), scene.materials.end(), material);
it != scene.materials.end()) {
return static_cast<std::size_t>(std::distance(scene.materials.begin(), it));
}
const auto index = scene.materials.size();
scene.materials.emplace_back(std::move(material));
return index;
}
auto make_primitive_visualization_geometry(const Collision_primitive_type type,
const glm::vec3 size) -> scene::Geometry
{
const auto [indices, positions, normals, texcoords] = [type] {
using namespace primitives;
const auto as_spans = [](const auto&... args) {
return std::make_tuple(gsl::make_span(args)...);
};
switch (type) {
case Collision_primitive_type::sphere:
return as_spans(sphere_indices, sphere_vertex_positions, sphere_vertex_normals,
sphere_vertex_texcoords);
case Collision_primitive_type::cylinder:
return as_spans(cylinder_indices, cylinder_vertex_positions,
cylinder_vertex_normals, cylinder_vertex_texcoords);
case Collision_primitive_type::cube:
return as_spans(cube_indices, cube_vertex_positions, cube_vertex_normals,
cube_vertex_texcoords);
default:
std::terminate();
}
}();
scene::Geometry geometry{
.topology = primitives::primitive_topology,
.indices = Indices{std::cbegin(indices), std::cend(indices)},
.vertices = Vertices{static_cast<std::size_t>(positions.size()),
{.positions = true, .normals = true, .texcoords = true}}};
std::transform(std::cbegin(positions), std::cend(positions),
geometry.vertices.positions.get(),
[size](const auto pos) { return pos * size; });
std::copy(std::cbegin(normals), std::cend(normals), geometry.vertices.normals.get());
std::copy(std::cbegin(texcoords), std::cend(texcoords),
geometry.vertices.texcoords.get());
return geometry;
}
auto positions_to_vertices(const std::vector<glm::vec3>& positions) -> Vertices
{
Vertices vertices{positions.size(), {.positions = true}};
std::copy(std::cbegin(positions), std::cend(positions), vertices.positions.get());
return vertices;
}
auto create_scene(Model model) -> scene::Scene
{
scene::Scene scene{.name = std::move(model.name)};
scene.materials.push_back({.name = "default_material"});
if (model.bones.empty()) {
scene.nodes.push_back({.name = "root"s,
.parent = ""s,
.material_index = 0,
.type = scene::Node_type::null});
}
for (auto& bone : model.bones) {
scene.nodes.push_back({.name = std::move(bone.name),
.parent = std::move(bone.parent),
.material_index = 0,
.type = scene::Node_type::null,
.transform = bone.transform});
}
int name_counter = 0;
for (auto& part : model.parts) {
if (part.material.attached_light) {
scene.attached_lights.push_back(
{.node = part.name.value(),
.light = std::move(part.material.attached_light.value())});
}
scene.nodes.push_back(
{.name = part.name ? std::move(*part.name)
: fmt::format("mesh_part{}{}"sv, ++name_counter,
lod_suffix(part.lod)),
.parent = std::move(part.parent),
.material_index = insert_scene_material(
scene, scene::Material{.name = part.material.name.value_or(""s),
.diffuse_colour = part.material.diffuse_colour,
.specular_colour = part.material.specular_colour,
.specular_exponent = part.material.specular_exponent,
.flags = part.material.flags,
.rendertype = part.material.type,
.params = part.material.params,
.textures = std::move(part.material.textures)}),
.type = scene::Node_type::geometry,
.lod = part.lod,
.geometry = scene::Geometry{.topology = part.primitive_topology,
.indices = std::move(part.indices),
.vertices = std::move(part.vertices),
.bone_map = std::move(part.bone_map)}});
}
name_counter = 0;
for (auto& mesh : model.collision_meshes) {
scene.nodes.push_back(
{.name = fmt::format("collision_-{}-mesh{}"sv,
collision_flags_string(mesh.flags), ++name_counter),
.parent = scene.nodes.front().name, // take the dangerous assumption that the
// first node we added is root
.material_index = 0,
.type = scene::Node_type::collision,
.geometry =
scene::Geometry{.topology = mesh.primitive_topology,
.indices = std::move(mesh.indices),
.vertices = positions_to_vertices(mesh.positions)}});
}
for (auto& prim : model.collision_primitives) {
scene.nodes.push_back(
{.name =
fmt::format("p_-{}-{}"sv, collision_flags_string(prim.flags), prim.name),
.parent = std::move(prim.parent),
.material_index = 0,
.type = scene::Node_type::collision_primitive,
.transform = prim.transform,
.geometry = make_primitive_visualization_geometry(prim.type, prim.size),
.collision = scene::Collision{.type = prim.type, .size = prim.size}});
}
for (auto& cloth : model.cloths) {
scene.nodes.push_back(
{.name = std::move(cloth.name),
.parent = std::move(cloth.parent),
.material_index = 0,
.type = scene::Node_type::cloth_geometry,
.transform = cloth.transform,
.cloth_geometry = scene::Cloth_geometry{
.texture_name = std::move(cloth.texture_name),
.vertices = std::move(cloth.vertices),
.indices = std::move(cloth.indices),
.fixed_points = std::move(cloth.fixed_points),
.fixed_weights = std::move(cloth.fixed_weights),
.stretch_constraints = std::move(cloth.stretch_constraints),
.cross_constraints = std::move(cloth.cross_constraints),
.bend_constraints = std::move(cloth.bend_constraints),
.collision = std::move(cloth.collision),
}});
}
name_counter = 0;
for (auto& material : scene.materials) {
if (!material.name.empty()) continue;
material.name = fmt::format("material{}"sv, ++name_counter);
}
for (const auto& node : scene.nodes) {
scene.softskin |= node.geometry ? node.geometry->vertices.softskinned : false;
scene.vertex_lighting |=
node.geometry ? node.geometry->vertices.static_lighting : false;
}
scene::reverse_pretransforms(scene);
scene::recreate_aabbs(scene);
return scene;
}
void save_model(Model model, File_saver& file_saver, const Game_version game_version)
{
msh::save_scene(create_scene(std::move(model)), file_saver, game_version);
}
}
Vertices::Vertices(const std::size_t size, const Create_flags flags) : size{size}
{
if (flags.positions) positions = std::make_unique<glm::vec3[]>(size);
if (flags.normals) normals = std::make_unique<glm::vec3[]>(size);
if (flags.tangents) tangents = std::make_unique<glm::vec3[]>(size);
if (flags.bitangents) bitangents = std::make_unique<glm::vec3[]>(size);
if (flags.colors) colors = std::make_unique<glm::vec4[]>(size);
if (flags.texcoords) texcoords = std::make_unique<glm::vec2[]>(size);
if (flags.bones) bones = std::make_unique<glm::u8vec3[]>(size);
if (flags.weights) weights = std::make_unique<glm::vec3[]>(size);
}
void Model::merge_with(Model other) noexcept
{
merge_containers(this->bones, other.bones);
merge_containers(this->parts, other.parts);
merge_containers(this->collision_meshes, other.collision_meshes);
merge_containers(this->collision_primitives, other.collision_primitives);
merge_containers(this->cloths, other.cloths);
}
void Models_builder::integrate(Model model) noexcept
{
std::lock_guard lock{_mutex};
if (const auto it = std::find_if(
_models.begin(), _models.end(),
[&](const auto& other) noexcept { return (model.name == other.name); });
it != _models.end()) {
it->merge_with(std::move(model));
}
else {
_models.emplace_back(std::move(model));
}
}
void Models_builder::save_models(File_saver& file_saver,
const Game_version game_version) noexcept
{
std::lock_guard lock{_mutex};
(void)(file_saver, game_version);
tbb::parallel_for_each(_models, [&](Model& model) {
save_model(std::move(model), file_saver, game_version);
});
_models.clear();
}
}
|
fix collision primitve naming
|
fix collision primitve naming
|
C++
|
mit
|
SleepKiller/swbf-unmunge
|
b62e8a6773668a6c56358ae1e6f48d12d7e0bddf
|
src/phml/reach.cc
|
src/phml/reach.cc
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#include "reach.hh"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include <boost/ptr_container/ptr_set.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "db/input-port-loader.h"
#include "db/output-port-loader.h"
#include "db/reach-driver.h"
#include "db/scope-loader.h"
#include "db/span-loader.h"
#include "reduction.hh"
using std::cerr;
using std::endl;
using std::make_pair;
using std::multimap;
using std::set;
using std::string;
using std::pair;
namespace flint {
namespace phml {
namespace {
class Scope {
public:
Scope(const Scope &) = delete;
Scope &operator=(const Scope &) = delete;
Scope(boost::uuids::uuid uuid, boost::uuids::uuid module_id)
: uuid_(uuid),
module_id_(module_id),
label_()
{
}
Scope(boost::uuids::uuid uuid, boost::uuids::uuid module_id, string label)
: uuid_(uuid),
module_id_(module_id),
label_(label)
{
}
const boost::uuids::uuid &uuid() const {return uuid_;}
const boost::uuids::uuid &module_id() const {return module_id_;}
const string &label() const {return label_;}
// comparison wrt module_id_ & uuid_ (but not label_)
bool operator<(const Scope &other) const {
if (module_id_ < other.module_id_) return true;
if (module_id_ == other.module_id_ &&
uuid_ < other.uuid_) return true;
return false;
}
private:
boost::uuids::uuid uuid_;
boost::uuids::uuid module_id_;
string label_;
};
class Port {
public:
Port(boost::uuids::uuid module_id, int port_id, int physical_quantity_id,
char pq_type, Reduction reduction)
: module_id_(module_id),
port_id_(port_id),
physical_quantity_id_(physical_quantity_id),
pq_type_(pq_type)
, reduction_(reduction)
{
}
const boost::uuids::uuid &module_id() const {return module_id_;}
int port_id() const {return port_id_;}
int physical_quantity_id() const {return physical_quantity_id_;}
char pq_type() const {return pq_type_;}
Reduction reduction() const {return reduction_;}
private:
boost::uuids::uuid module_id_;
int port_id_;
int physical_quantity_id_;
char pq_type_;
Reduction reduction_;
};
class Node {
public:
Node(boost::uuids::uuid uuid, int port_id) : uuid_(uuid), port_id_(port_id) {}
const boost::uuids::uuid &uuid() const {return uuid_;}
int port_id() const {return port_id_;}
bool operator<(const Node &other) const {
if (uuid_ < other.uuid_) return true;
if (uuid_ == other.uuid_ &&
port_id_ < other.port_id_) return true;
return false;
}
private:
boost::uuids::uuid uuid_;
int port_id_;
};
class InputPortHandler {
public:
InputPortHandler(const InputPortHandler &) = delete;
InputPortHandler &operator=(const InputPortHandler &) = delete;
explicit InputPortHandler(std::multimap<boost::uuids::uuid, Port> *ports)
: ports_(ports)
{
}
bool Handle(boost::uuids::uuid uuid, int port_id, int pq_id,
char pq_type, Reduction reduction)
{
ports_->emplace(std::make_pair(uuid, Port(uuid, port_id, pq_id, pq_type, reduction)));
return true;
}
private:
std::multimap<boost::uuids::uuid, Port> *ports_;
};
bool LoadInputPorts(sqlite3 *db, std::multimap<boost::uuids::uuid, Port> *ports)
{
std::unique_ptr<db::InputPortLoader> loader(new db::InputPortLoader(db));
std::unique_ptr<InputPortHandler> handler(new InputPortHandler(ports));
return loader->Load(handler.get());
}
class OutputPortHandler {
public:
OutputPortHandler(const OutputPortHandler &) = delete;
OutputPortHandler &operator=(const OutputPortHandler &) = delete;
explicit OutputPortHandler(std::map<Node, Port> *ports)
: ports_(ports)
{
}
bool Handle(boost::uuids::uuid uuid, int port_id, int pq_id, char pq_type) {
Node node(uuid, port_id);
// reduction makes little sense for output port, so just call it unspecified
ports_->emplace(std::make_pair(node, Port(uuid, port_id, pq_id, pq_type, Reduction::kUnspecified)));
return true;
}
private:
std::map<Node, Port> *ports_;
};
bool LoadOutputPorts(sqlite3 *db, std::map<Node, Port> *ports)
{
std::unique_ptr<db::OutputPortLoader> loader(new db::OutputPortLoader(db));
std::unique_ptr<OutputPortHandler> handler(new OutputPortHandler(ports));
return loader->Load(handler.get());
}
typedef boost::ptr_set<Scope> ScopeSet;
typedef multimap<boost::uuids::uuid, ScopeSet::iterator> Mmap;
typedef std::unordered_map<boost::uuids::uuid,
ScopeSet::iterator,
boost::hash<boost::uuids::uuid>
> Umap;
class ScopeHandler {
public:
ScopeHandler(const ScopeHandler &) = delete;
ScopeHandler &operator=(const ScopeHandler &) = delete;
ScopeHandler(ScopeSet *scopes, Mmap *mmap, Umap *umap)
: scopes_(scopes),
mmap_(mmap),
umap_(umap)
{}
bool Handle(boost::uuids::uuid uuid, boost::uuids::uuid space_id, const char *label) {
pair<ScopeSet::iterator, bool> p;
if (label) {
p = scopes_->insert(new Scope(uuid, space_id, string(label)));
} else {
p = scopes_->insert(new Scope(uuid, space_id));
}
if (!p.second) {
cerr << "duplicate entry of scope: " << uuid << endl;
return false;
}
mmap_->insert(make_pair(space_id, p.first));
umap_->insert(make_pair(uuid, p.first));
return true;
}
private:
ScopeSet *scopes_;
Mmap *mmap_;
Umap *umap_;
};
bool LoadScopes(sqlite3 *db, ScopeSet *scopes, Mmap *mmap, Umap *umap)
{
std::unique_ptr<db::ScopeLoader> loader(new db::ScopeLoader(db));
std::unique_ptr<ScopeHandler> handler(new ScopeHandler(scopes, mmap, umap));
return loader->Load(handler.get());
}
class SpanHandler {
public:
SpanHandler(const SpanHandler &) = delete;
SpanHandler &operator=(const SpanHandler &) = delete;
explicit SpanHandler(multimap<Node, Node> *spans) : spans_(spans) {}
bool Handle(boost::uuids::uuid tail_uuid, int tail_port_id,
boost::uuids::uuid head_uuid, int head_port_id) {
// reverse direction: from head to tail
spans_->insert(make_pair(Node(head_uuid, head_port_id),
Node(tail_uuid, tail_port_id)));
return true;
}
private:
multimap<Node, Node> *spans_;
};
bool LoadEdges(sqlite3 *db, multimap<Node, Node> *edges)
{
std::unique_ptr<db::SpanLoader> loader(new db::SpanLoader(db));
std::unique_ptr<SpanHandler> handler(new SpanHandler(edges));
return loader->Load(handler.get());
}
void Lookup(const Node &p, multimap<Node, Node> &edges, set<Node> *q)
{
pair<multimap<Node, Node>::iterator, multimap<Node, Node>::iterator> r;
r = edges.equal_range(p);
if (r.first == r.second) {
q->insert(p);
return;
}
set<Node> s;
for (multimap<Node, Node>::iterator it=r.first;it!=r.second;++it) {
const Node &tail = it->second;
s.insert(tail);
}
for (set<Node>::const_iterator it=s.begin();it!=s.end();++it) {
Lookup(*it, edges, q);
}
}
void PrintIncompatiblePorts(const Port &from, const Port &to)
{
cerr << " from" << endl
<< " port-id: " << from.port_id() << endl
<< " module-id: " << from.module_id() << endl
<< " to" << endl
<< " port-id: " << to.port_id() << endl
<< " module-id: " << to.module_id() << endl;
}
} // namespace
bool Reach(sqlite3 *db)
{
std::multimap<boost::uuids::uuid, Port> inports;
if (!LoadInputPorts(db, &inports)) return false;
std::map<Node, Port> outports;
if (!LoadOutputPorts(db, &outports)) return false;
ScopeSet scopes;
Mmap mmap;
Umap umap;
if (!LoadScopes(db, &scopes, &mmap, &umap)) return false;
multimap<Node, Node> edges;
if (!LoadEdges(db, &edges)) return false;
std::unique_ptr<db::ReachDriver> driver(new db::ReachDriver(db));
// trace from each input-port
for (auto it=inports.cbegin();it!=inports.cend();++it) {
const boost::uuids::uuid &module_id = it->first;
const Port &inport = it->second;
pair<Mmap::iterator, Mmap::iterator> r;
r = mmap.equal_range(module_id);
for (Mmap::iterator rit=r.first;rit!=r.second;++rit) {
const boost::uuids::uuid &uuid = rit->second->uuid();
Node p(uuid, inport.port_id());
set<Node> t;
Lookup(p, edges, &t);
for (set<Node>::const_iterator tit=t.begin();tit!=t.end();++tit) {
const Node &o = *tit;
if (o.port_id() <= 0) {
cerr << "invalid port-id of edge: " << o.port_id() << endl;
return false;
}
// find corresponding output-port
Umap::const_iterator uit = umap.find(o.uuid());
if (uit == umap.end()) {
cerr << "missing node with uuid: " << o.uuid() << endl;
return false;
}
const boost::uuids::uuid &om = uit->second->module_id();
Node ok(om, o.port_id());
std::map<Node, Port>::const_iterator oit = outports.find(ok);
if (oit == outports.end()) {
cerr << "lost without corresponding edge or output-port" << endl;
cerr << " port-id: " << o.port_id() << endl;
cerr << " module-id: " << uit->second->module_id() << endl;
cerr << " uuid: " << uit->second->uuid() << endl;
if (!uit->second->label().empty()) cerr << " label: " << uit->second->label() << endl;
return false;
}
// check if PQ types of both sides are compatible
if (inport.pq_type() == 's') {
switch (oit->second.pq_type()) {
case 'x':
cerr << "found invalid edge from a state to a static-parameter" << endl;
PrintIncompatiblePorts(inport, oit->second);
return false;
case 'v':
cerr << "found invalid edge from a variable-parameter to a static-parameter" << endl;
PrintIncompatiblePorts(inport, oit->second);
return false;
}
}
if (!driver->Save(tit->uuid(), oit->second.physical_quantity_id(),
uuid, inport.physical_quantity_id(),
inport.reduction()))
return false;
}
}
}
return true;
}
}
}
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#include "reach.hh"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "db/input-port-loader.h"
#include "db/output-port-loader.h"
#include "db/reach-driver.h"
#include "db/scope-loader.h"
#include "db/span-loader.h"
#include "reduction.hh"
using std::cerr;
using std::endl;
using std::make_pair;
using std::multimap;
using std::set;
using std::string;
using std::pair;
namespace flint {
namespace phml {
namespace {
class Scope {
public:
Scope(const Scope &) = delete;
Scope &operator=(const Scope &) = delete;
Scope(boost::uuids::uuid uuid, boost::uuids::uuid module_id)
: uuid_(uuid),
module_id_(module_id),
label_()
{
}
Scope(boost::uuids::uuid uuid, boost::uuids::uuid module_id, string label)
: uuid_(uuid),
module_id_(module_id),
label_(label)
{
}
const boost::uuids::uuid &uuid() const {return uuid_;}
const boost::uuids::uuid &module_id() const {return module_id_;}
const string &label() const {return label_;}
// comparison wrt module_id_ & uuid_ (but not label_)
bool operator<(const Scope &other) const {
if (module_id_ < other.module_id_) return true;
if (module_id_ == other.module_id_ &&
uuid_ < other.uuid_) return true;
return false;
}
private:
boost::uuids::uuid uuid_;
boost::uuids::uuid module_id_;
string label_;
};
class Port {
public:
Port(boost::uuids::uuid module_id, int port_id, int physical_quantity_id,
char pq_type, Reduction reduction)
: module_id_(module_id),
port_id_(port_id),
physical_quantity_id_(physical_quantity_id),
pq_type_(pq_type)
, reduction_(reduction)
{
}
const boost::uuids::uuid &module_id() const {return module_id_;}
int port_id() const {return port_id_;}
int physical_quantity_id() const {return physical_quantity_id_;}
char pq_type() const {return pq_type_;}
Reduction reduction() const {return reduction_;}
private:
boost::uuids::uuid module_id_;
int port_id_;
int physical_quantity_id_;
char pq_type_;
Reduction reduction_;
};
class Node {
public:
Node(boost::uuids::uuid uuid, int port_id) : uuid_(uuid), port_id_(port_id) {}
const boost::uuids::uuid &uuid() const {return uuid_;}
int port_id() const {return port_id_;}
bool operator<(const Node &other) const {
if (uuid_ < other.uuid_) return true;
if (uuid_ == other.uuid_ &&
port_id_ < other.port_id_) return true;
return false;
}
private:
boost::uuids::uuid uuid_;
int port_id_;
};
class InputPortHandler {
public:
InputPortHandler(const InputPortHandler &) = delete;
InputPortHandler &operator=(const InputPortHandler &) = delete;
explicit InputPortHandler(std::multimap<boost::uuids::uuid, Port> *ports)
: ports_(ports)
{
}
bool Handle(boost::uuids::uuid uuid, int port_id, int pq_id,
char pq_type, Reduction reduction)
{
ports_->emplace(std::make_pair(uuid, Port(uuid, port_id, pq_id, pq_type, reduction)));
return true;
}
private:
std::multimap<boost::uuids::uuid, Port> *ports_;
};
bool LoadInputPorts(sqlite3 *db, std::multimap<boost::uuids::uuid, Port> *ports)
{
std::unique_ptr<db::InputPortLoader> loader(new db::InputPortLoader(db));
std::unique_ptr<InputPortHandler> handler(new InputPortHandler(ports));
return loader->Load(handler.get());
}
class OutputPortHandler {
public:
OutputPortHandler(const OutputPortHandler &) = delete;
OutputPortHandler &operator=(const OutputPortHandler &) = delete;
explicit OutputPortHandler(std::map<Node, Port> *ports)
: ports_(ports)
{
}
bool Handle(boost::uuids::uuid uuid, int port_id, int pq_id, char pq_type) {
Node node(uuid, port_id);
// reduction makes little sense for output port, so just call it unspecified
ports_->emplace(std::make_pair(node, Port(uuid, port_id, pq_id, pq_type, Reduction::kUnspecified)));
return true;
}
private:
std::map<Node, Port> *ports_;
};
bool LoadOutputPorts(sqlite3 *db, std::map<Node, Port> *ports)
{
std::unique_ptr<db::OutputPortLoader> loader(new db::OutputPortLoader(db));
std::unique_ptr<OutputPortHandler> handler(new OutputPortHandler(ports));
return loader->Load(handler.get());
}
typedef std::set<Scope> ScopeSet;
typedef multimap<boost::uuids::uuid, ScopeSet::iterator> Mmap;
typedef std::unordered_map<boost::uuids::uuid,
ScopeSet::iterator,
boost::hash<boost::uuids::uuid>
> Umap;
class ScopeHandler {
public:
ScopeHandler(const ScopeHandler &) = delete;
ScopeHandler &operator=(const ScopeHandler &) = delete;
ScopeHandler(ScopeSet *scopes, Mmap *mmap, Umap *umap)
: scopes_(scopes),
mmap_(mmap),
umap_(umap)
{}
bool Handle(boost::uuids::uuid uuid, boost::uuids::uuid space_id, const char *label) {
pair<ScopeSet::iterator, bool> p;
if (label) {
p = scopes_->emplace(uuid, space_id, string(label));
} else {
p = scopes_->emplace(uuid, space_id);
}
if (!p.second) {
cerr << "duplicate entry of scope: " << uuid << endl;
return false;
}
mmap_->insert(make_pair(space_id, p.first));
umap_->insert(make_pair(uuid, p.first));
return true;
}
private:
ScopeSet *scopes_;
Mmap *mmap_;
Umap *umap_;
};
bool LoadScopes(sqlite3 *db, ScopeSet *scopes, Mmap *mmap, Umap *umap)
{
std::unique_ptr<db::ScopeLoader> loader(new db::ScopeLoader(db));
std::unique_ptr<ScopeHandler> handler(new ScopeHandler(scopes, mmap, umap));
return loader->Load(handler.get());
}
class SpanHandler {
public:
SpanHandler(const SpanHandler &) = delete;
SpanHandler &operator=(const SpanHandler &) = delete;
explicit SpanHandler(multimap<Node, Node> *spans) : spans_(spans) {}
bool Handle(boost::uuids::uuid tail_uuid, int tail_port_id,
boost::uuids::uuid head_uuid, int head_port_id) {
// reverse direction: from head to tail
spans_->insert(make_pair(Node(head_uuid, head_port_id),
Node(tail_uuid, tail_port_id)));
return true;
}
private:
multimap<Node, Node> *spans_;
};
bool LoadEdges(sqlite3 *db, multimap<Node, Node> *edges)
{
std::unique_ptr<db::SpanLoader> loader(new db::SpanLoader(db));
std::unique_ptr<SpanHandler> handler(new SpanHandler(edges));
return loader->Load(handler.get());
}
void Lookup(const Node &p, multimap<Node, Node> &edges, set<Node> *q)
{
pair<multimap<Node, Node>::iterator, multimap<Node, Node>::iterator> r;
r = edges.equal_range(p);
if (r.first == r.second) {
q->insert(p);
return;
}
set<Node> s;
for (multimap<Node, Node>::iterator it=r.first;it!=r.second;++it) {
const Node &tail = it->second;
s.insert(tail);
}
for (set<Node>::const_iterator it=s.begin();it!=s.end();++it) {
Lookup(*it, edges, q);
}
}
void PrintIncompatiblePorts(const Port &from, const Port &to)
{
cerr << " from" << endl
<< " port-id: " << from.port_id() << endl
<< " module-id: " << from.module_id() << endl
<< " to" << endl
<< " port-id: " << to.port_id() << endl
<< " module-id: " << to.module_id() << endl;
}
} // namespace
bool Reach(sqlite3 *db)
{
std::multimap<boost::uuids::uuid, Port> inports;
if (!LoadInputPorts(db, &inports)) return false;
std::map<Node, Port> outports;
if (!LoadOutputPorts(db, &outports)) return false;
ScopeSet scopes;
Mmap mmap;
Umap umap;
if (!LoadScopes(db, &scopes, &mmap, &umap)) return false;
multimap<Node, Node> edges;
if (!LoadEdges(db, &edges)) return false;
std::unique_ptr<db::ReachDriver> driver(new db::ReachDriver(db));
// trace from each input-port
for (auto it=inports.cbegin();it!=inports.cend();++it) {
const boost::uuids::uuid &module_id = it->first;
const Port &inport = it->second;
pair<Mmap::iterator, Mmap::iterator> r;
r = mmap.equal_range(module_id);
for (Mmap::iterator rit=r.first;rit!=r.second;++rit) {
const boost::uuids::uuid &uuid = rit->second->uuid();
Node p(uuid, inport.port_id());
set<Node> t;
Lookup(p, edges, &t);
for (set<Node>::const_iterator tit=t.begin();tit!=t.end();++tit) {
const Node &o = *tit;
if (o.port_id() <= 0) {
cerr << "invalid port-id of edge: " << o.port_id() << endl;
return false;
}
// find corresponding output-port
Umap::const_iterator uit = umap.find(o.uuid());
if (uit == umap.end()) {
cerr << "missing node with uuid: " << o.uuid() << endl;
return false;
}
const boost::uuids::uuid &om = uit->second->module_id();
Node ok(om, o.port_id());
std::map<Node, Port>::const_iterator oit = outports.find(ok);
if (oit == outports.end()) {
cerr << "lost without corresponding edge or output-port" << endl;
cerr << " port-id: " << o.port_id() << endl;
cerr << " module-id: " << uit->second->module_id() << endl;
cerr << " uuid: " << uit->second->uuid() << endl;
if (!uit->second->label().empty()) cerr << " label: " << uit->second->label() << endl;
return false;
}
// check if PQ types of both sides are compatible
if (inport.pq_type() == 's') {
switch (oit->second.pq_type()) {
case 'x':
cerr << "found invalid edge from a state to a static-parameter" << endl;
PrintIncompatiblePorts(inport, oit->second);
return false;
case 'v':
cerr << "found invalid edge from a variable-parameter to a static-parameter" << endl;
PrintIncompatiblePorts(inport, oit->second);
return false;
}
}
if (!driver->Save(tit->uuid(), oit->second.physical_quantity_id(),
uuid, inport.physical_quantity_id(),
inport.reduction()))
return false;
}
}
}
return true;
}
}
}
|
Replace boost::ptr_set with std::set
|
Replace boost::ptr_set with std::set
|
C++
|
mit
|
flintproject/Flint,flintproject/Flint
|
dc702f4fd61c1828f87509a09bf5609568ed89fc
|
src/packet_writer.cpp
|
src/packet_writer.cpp
|
/*
* Copyright (c) 2017, Matias Fontanini
* 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
* 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.
*
*/
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <string.h>
#include <tins/packet_writer.h>
#include <tins/packet.h>
#include <tins/pdu.h>
#include <tins/exceptions.h>
using std::string;
namespace Tins {
PacketWriter::PacketWriter(const string& file_name, LinkType lt) {
init(file_name, lt);
}
PacketWriter::~PacketWriter() {
if (dumper_ && handle_) {
pcap_dump_close(dumper_);
pcap_close(handle_);
}
}
void PacketWriter::write(PDU& pdu) {
timeval tv;
#ifndef _WIN32
gettimeofday(&tv, 0);
#else
// fixme
tv = timeval();
#endif
write(pdu, tv);
}
void PacketWriter::write(Packet& packet) {
timeval tv;
tv.tv_sec = packet.timestamp().seconds();
tv.tv_usec = packet.timestamp().microseconds();
write(*packet.pdu(), tv);
}
void PacketWriter::write(PDU& pdu, const struct timeval& tv) {
PDU::serialization_type buffer = pdu.serialize();
struct pcap_pkthdr header;
memset(&header, 0, sizeof(header));
header.ts = tv;
header.caplen = static_cast<bpf_u_int32>(buffer.size());
header.len = static_cast<bpf_u_int32>(buffer.size());
pcap_dump((u_char*)dumper_, &header, &buffer[0]);
}
void PacketWriter::init(const string& file_name, int link_type) {
handle_ = pcap_open_dead(link_type, 65535);
if (!handle_) {
throw pcap_open_failed();
}
dumper_ = pcap_dump_open(handle_, file_name.c_str());
if (!dumper_) {
pcap_close(handle_);
throw pcap_error(pcap_geterr(handle_));
}
}
} // Tins
|
/*
* Copyright (c) 2017, Matias Fontanini
* 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
* 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.
*
*/
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <string.h>
#include <tins/packet_writer.h>
#include <tins/packet.h>
#include <tins/pdu.h>
#include <tins/exceptions.h>
using std::string;
namespace Tins {
PacketWriter::PacketWriter(const string& file_name, LinkType lt) {
init(file_name, lt);
}
PacketWriter::~PacketWriter() {
if (dumper_ && handle_) {
pcap_dump_close(dumper_);
pcap_close(handle_);
}
}
void PacketWriter::write(PDU& pdu) {
timeval tv;
#ifndef _WIN32
gettimeofday(&tv, 0);
#else
// fixme
tv = timeval();
#endif
write(pdu, tv);
}
void PacketWriter::write(Packet& packet) {
timeval tv;
tv.tv_sec = packet.timestamp().seconds();
tv.tv_usec = packet.timestamp().microseconds();
write(*packet.pdu(), tv);
}
void PacketWriter::write(PDU& pdu, const struct timeval& tv) {
struct pcap_pkthdr header;
memset(&header, 0, sizeof(header));
header.ts = tv;
header.len = static_cast<bpf_u_int32>(pdu.advertised_size());
PDU::serialization_type buffer = pdu.serialize();
header.caplen = static_cast<bpf_u_int32>(buffer.size());
pcap_dump((u_char*)dumper_, &header, &buffer[0]);
}
void PacketWriter::init(const string& file_name, int link_type) {
handle_ = pcap_open_dead(link_type, 65535);
if (!handle_) {
throw pcap_open_failed();
}
dumper_ = pcap_dump_open(handle_, file_name.c_str());
if (!dumper_) {
pcap_close(handle_);
throw pcap_error(pcap_geterr(handle_));
}
}
} // Tins
|
use advertised_size to determine frame length
|
use advertised_size to determine frame length
|
C++
|
bsd-2-clause
|
mfontanini/libtins,mfontanini/libtins,UlfWetzker/libtins,UlfWetzker/libtins
|
d2e56a5e9237dc9d597c0bb984bbe77ac348f63d
|
src/parser/uparser.hh
|
src/parser/uparser.hh
|
/*! \file uparser.hh
*******************************************************************************
File: uparser.h\n
Definition of the UParser class used to make flex/bison reentrant.
This file is part of
%URBI Kernel, version __kernelversion__\n
(c) Jean-Christophe Baillie, 2004-2005.
Permission to use, copy, modify, and redistribute this software for
non-commercial use is hereby granted.
This software is provided "as is" without warranty of any kind,
either expressed or implied, including but not limited to the
implied warranties of fitness for a particular purpose.
For more information, comments, bug reports: http://www.urbiforge.net
**************************************************************************** */
#ifndef PARSER_UPARSER_HH
# define PARSER_UPARSER_HH
# include <list>
# include <memory>
# include <string>
# include "parser/fwd.hh"
# include "parser/utoken.hh"
namespace parser
{
//! UParser uses 'flex' and 'bison' as scanner/parser
/*! The choice of flex/bison is detailed in the comment on the UServer class.
The main concern is about reentrancy, which is not necessary in most
cases but would become a problem with a multithreaded server.
*/
class UParser
{
public:
typedef yy::parser parser_type;
typedef parser_type::token_type token_type;
typedef parser_type::semantic_type semantic_type;
typedef parser_type::location_type location_type;
UParser ();
/// Parse the command from a buffer.
/// \return yyparse's result (0 on success).
int parse (const std::string& code);
/// Parse the command from a TWEAST.
/// \param t the Tweast to process. Emptied as it is used.
/// \return yyparse's result (0 on success).
/// \note Recursive calls are forbidden.
int parse (parser::Tweast& t);
/// The TWEAST currently analyzed (if there is one).
parser::Tweast* tweast_;
/// Parse a file.
/// \return yyparse's result (0 on success).
int parse_file (const std::string& fn);
/// \{
/// The type of AST node returned by the parser.
typedef ast::Nary ast_type;
/// The latest AST read by parse().
inline ast_type* ast_get ();
/// Return the AST and reset \a ast_.
inline std::auto_ptr<ast_type> ast_take ();
/// Same as \a ast_take, but assert the result.
inline std::auto_ptr<ast_type> ast_xtake ();
/// Set \a ast_.
inline void ast_set (ast_type* ast);
private:
/// The resulting AST.
ast_type* ast_;
/// \}
public:
/// Declare an error at \a l about \a msg.
void error (const location_type& l, const std::string& msg);
/// Warn at \a l about \a msg.
void warn (const location_type& l, const std::string& msg);
/// Push all warning and error messages in \b target.
/// If errors were pushed, the ast is deleted and set to 0.
void process_errors(ast_type* target);
private:
// Give access to loc_.
friend int parser_type::parse ();
friend YY_DECL;
/// Errors and warnings.
typedef std::list<std::string> messages_type;
/// List of parse error messages.
messages_type errors_;
/// List of warnings.
messages_type warnings_;
/// Push a warning or an error.
void message_push(messages_type& msgs,
const yy::parser::location_type& l,
const std::string& msg);
/// Run the parse.
int parse_ (std::istream& source);
/// The current location.
location_type loc_;
/// A stack of locations to support #push/#pop.
std::stack<yy::location> synclines_;
};
/*--------------------------.
| Free-standing functions. |
`--------------------------*/
/// Parse \a cmd, and return a UParser that holds the result and the
/// errors. Admittedly, we could avoid using UParser at all and
/// return a tuple, maybe in another step.
UParser parse(const std::string& cmd);
/// Parse a Tweast and return the (desugared) AST.
UParser::ast_type* parse(Tweast& t);
/// Parse a file.
/// \see parse().
UParser parse_file(const std::string& file);
}
# include "parser/uparser.hxx"
#endif // !PARSER_UPARSER_HH
|
/*! \file uparser.hh
*******************************************************************************
File: uparser.h\n
Definition of the UParser class used to make flex/bison reentrant.
This file is part of
%URBI Kernel, version __kernelversion__\n
(c) Jean-Christophe Baillie, 2004-2005.
Permission to use, copy, modify, and redistribute this software for
non-commercial use is hereby granted.
This software is provided "as is" without warranty of any kind,
either expressed or implied, including but not limited to the
implied warranties of fitness for a particular purpose.
For more information, comments, bug reports: http://www.urbiforge.net
**************************************************************************** */
#ifndef PARSER_UPARSER_HH
# define PARSER_UPARSER_HH
# include <list>
# include <memory>
# include <string>
# include "parser/fwd.hh"
# include "parser/utoken.hh"
namespace parser
{
class UParser
{
public:
typedef yy::parser parser_type;
typedef parser_type::token_type token_type;
typedef parser_type::semantic_type semantic_type;
typedef parser_type::location_type location_type;
UParser ();
/// Parse the command from a buffer.
/// \return yyparse's result (0 on success).
int parse (const std::string& code);
/// Parse the command from a TWEAST.
/// \param t the Tweast to process. Emptied as it is used.
/// \return yyparse's result (0 on success).
/// \note Recursive calls are forbidden.
int parse (parser::Tweast& t);
/// The TWEAST currently analyzed (if there is one).
parser::Tweast* tweast_;
/// Parse a file.
/// \return yyparse's result (0 on success).
int parse_file (const std::string& fn);
/// \{
/// The type of AST node returned by the parser.
typedef ast::Nary ast_type;
/// The latest AST read by parse().
inline ast_type* ast_get ();
/// Return the AST and reset \a ast_.
inline std::auto_ptr<ast_type> ast_take ();
/// Same as \a ast_take, but assert the result.
inline std::auto_ptr<ast_type> ast_xtake ();
/// Set \a ast_.
inline void ast_set (ast_type* ast);
private:
/// The resulting AST.
ast_type* ast_;
/// \}
public:
/// Declare an error at \a l about \a msg.
void error (const location_type& l, const std::string& msg);
/// Warn at \a l about \a msg.
void warn (const location_type& l, const std::string& msg);
/// Push all warning and error messages in \b target.
/// If errors were pushed, the ast is deleted and set to 0.
void process_errors(ast_type* target);
private:
// Give access to loc_.
friend int parser_type::parse ();
friend YY_DECL;
/// Errors and warnings.
typedef std::list<std::string> messages_type;
/// List of parse error messages.
messages_type errors_;
/// List of warnings.
messages_type warnings_;
/// Push a warning or an error.
void message_push(messages_type& msgs,
const yy::parser::location_type& l,
const std::string& msg);
/// Run the parse.
int parse_ (std::istream& source);
/// The current location.
location_type loc_;
/// A stack of locations to support #push/#pop.
std::stack<yy::location> synclines_;
};
/*--------------------------.
| Free-standing functions. |
`--------------------------*/
/// Parse \a cmd, and return a UParser that holds the result and the
/// errors. Admittedly, we could avoid using UParser at all and
/// return a tuple, maybe in another step.
UParser parse(const std::string& cmd);
/// Parse a Tweast and return the (desugared) AST.
UParser::ast_type* parse(Tweast& t);
/// Parse a file.
/// \see parse().
UParser parse_file(const std::string& file);
}
# include "parser/uparser.hxx"
#endif // !PARSER_UPARSER_HH
|
Remove dead comment.
|
Remove dead comment.
* src/parser/uparser.hh: here.
|
C++
|
bsd-3-clause
|
urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi
|
c60d03831f0eecaf25d2bf97b27884ad1c646a78
|
src/policy_newest.cpp
|
src/policy_newest.cpp
|
/*
The MIT License (MIT)
Copyright (c) 2014 Antonio SJ Musumeci <[email protected]>
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 <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <string>
#include <vector>
#include "policy.hpp"
using std::string;
using std::vector;
using std::size_t;
static
int
_newest(const vector<string> &basepaths,
const string &fusepath,
vector<string> &paths)
{
time_t newest;
const char *neweststr;
newest = 0;
neweststr = NULL;
for(size_t i = 0, ei = basepaths.size(); i != ei; i++)
{
int rv;
struct stat st;
const char *basepath;
string fullpath;
basepath = basepaths[i].c_str();
fullpath = fs::path::make(basepath,fusepath);
rv = ::lstat(fullpath.c_str(),&st);
if(rv == 0 && st.st_mtime > newest)
{
newest = st.st_mtime;
neweststr = basepath;
}
}
if(neweststr == NULL)
return (errno=ENOENT,-1);
paths.push_back(neweststr);
return 0;
}
namespace mergerfs
{
int
Policy::Func::newest(const Category::Enum::Type type,
const vector<string> &basepaths,
const string &fusepath,
const size_t minfreespace,
vector<string> &paths)
{
return _newest(basepaths,fusepath,paths);
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2014 Antonio SJ Musumeci <[email protected]>
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 <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <string>
#include <vector>
#include <limits>
#include "policy.hpp"
using std::string;
using std::vector;
using std::size_t;
static
int
_newest(const vector<string> &basepaths,
const string &fusepath,
vector<string> &paths)
{
time_t newest = std::numeric_limits<time_t>::min();
const char *neweststr = NULL;
for(size_t i = 0, ei = basepaths.size(); i != ei; i++)
{
int rv;
struct stat st;
const char *basepath;
string fullpath;
basepath = basepaths[i].c_str();
fullpath = fs::path::make(basepath,fusepath);
rv = ::lstat(fullpath.c_str(),&st);
if(rv == 0 && st.st_mtime >= newest)
{
newest = st.st_mtime;
neweststr = basepath;
}
}
if(neweststr == NULL)
return (errno=ENOENT,-1);
paths.push_back(neweststr);
return 0;
}
namespace mergerfs
{
int
Policy::Func::newest(const Category::Enum::Type type,
const vector<string> &basepaths,
const string &fusepath,
const size_t minfreespace,
vector<string> &paths)
{
return _newest(basepaths,fusepath,paths);
}
}
|
use gte rather than gt for mtime comparisons. fixes #91
|
use gte rather than gt for mtime comparisons. fixes #91
|
C++
|
isc
|
tolotos-rgu/mergerfs,tolotos-rgu/mergerfs
|
c263c971b01d95eeea23f8597f162af17b2daf6c
|
src/pSmartCar.cpp
|
src/pSmartCar.cpp
|
/*
* pSmartCar.cpp
*
* Author: petel__
* Copyright (c) 2014-2016 HKUST SmartCar Team
* Refer to LICENSE for details
*
*/
#include "pSmartCar.h"
#include <pResource.h>
using namespace std;
using namespace libsc;
using namespace libutil;
Button::Config getButtonConfig(const uint8_t id)
{
Button::Config config;
config.id = id;
config.is_active_low = true;
config.listener = pSmartCar::onClickListener;
config.listener_trigger = Button::Config::Trigger::kDown;
return config;
}
pPid::PidParam pSmartCar::getPidConfig(pSmartCar::PidType type)
{
pPid::PidParam param;
switch (type)
{
case 0:
param.kPFunc = function<float (float)>
(
[](float error)
{
if (ABS(error) < 0.3f)
return 0.0f;
else
return pResource::configTable.kAngleKp * sin(error * DegToRad);
}
);
param.kI = &pResource::configTable.kAngleKi;
param.kD = &pResource::configTable.kAngleKd;
param.setPoint = &pResource::configTable.kIdealAngle;
param.ignoreRange = 0.5f;
param.max = 500;
param.min = -500;
break;
case 1:
param.kP = &pResource::configTable.kDirectionKp;
param.kI = &pResource::configTable.kDirectionKi;
param.kD = &pResource::configTable.kDirectionKd;
param.setPoint = &m_direction;
param.ignoreRange = 25.0f;
param.max = 200;
param.min = -200;
break;
case 2:
param.kP = &pResource::configTable.kSpeedKp;
param.kI = &pResource::configTable.kSpeedKi;
param.kD = &pResource::configTable.kSpeedKd;
param.setPoint = &m_speed;
param.ignoreRange = 0.0f;
param.max = 500;
param.min = -500;
}
return param;
}
pSmartCar::pSmartCar(void)
:
m_state(),
m_direction(0.0f),
m_speed(0.0f),
m_loop(),
m_angle(pAngle::Config(pResource::configTable.kAccelTruthVal, pResource::configTable.kCgHeightInM)),
m_motors{ pMotor(pMotor::Config(1, 0, true, false, leftMotorMapping)),
pMotor(pMotor::Config(0, 1, false, true, rightMotorMapping)) },
m_lcd(MiniLcd::Config(0, -1, 30)),
m_buttons{ Button(getButtonConfig(0)),
Button(getButtonConfig(1)),
Button(getButtonConfig(2)) },
m_grapher(),
m_motorEnabled(false),
m_pidControllers{ pPid(getPidConfig(PidType::Angle)),
pPid(getPidConfig(PidType::Direction)),
pPid(getPidConfig(PidType::Speed)) },
m_pidOutputVal{ 0 },
m_filter(pResource::configTable.kKalmanKq, pResource::configTable.kKalmanKr, 0, 0.5),
m_oldSpeedPidOuput(0),
m_smoothCounter(0),
m_smoothIncrement(0)
{
System::Init();
addAllRoutineToLoop();
addVariablesToGrapher();
reset();
}
void pSmartCar::reset(void)
{
m_direction = 0.0f;
m_speed = 0.0f;
m_motors[0].reset();
m_motors[1].reset();
m_lcd.clear();
}
void pSmartCar::run(void)
{
m_loop.start();
}
void pSmartCar::updatePid(const float val, PidType type)
{
m_pidOutputVal[type] = m_pidControllers[type].getOutput(val);
}
pSmartCar::State &pSmartCar::State::operator=(const pSmartCar::State &other)
{
this->angle = other.angle;
this->dAngle = other.dAngle;
this->dX = other.dX;
this->dYaw = other.dYaw;
return *this;
}
void pSmartCar::onClickListener(const uint8_t id)
{
switch (id)
{
default:
assert(false);
// no break
case 0:
pResource::m_instance->setMotorsEnabled(pResource::m_instance->m_motorEnabled = !pResource::m_instance->m_motorEnabled);
break;
case 1:
pResource::m_instance->m_motors[0].reset();
DelayMsByTicks(250);
for (int16_t i = 50; i < 500; i++)
{
pResource::m_instance->m_motors[0].setPower(i);
DelayMsByTicks(100);
pResource::m_instance->m_motors[0].update();
if (ABS(pResource::m_instance->m_motors[0].getEncoderCount()) >= 100)
{
pResource::configTable.kLeftMotorDeadMarginPos = i;
break;
}
}
pResource::m_instance->m_motors[0].setPower(0);
DelayMsByTicks(1000);
pResource::m_instance->m_motors[0].reset();
for (int16_t i = -50; i > -500; i--)
{
pResource::m_instance->m_motors[0].setPower(i);
DelayMsByTicks(100);
pResource::m_instance->m_motors[0].update();
if (ABS(pResource::m_instance->m_motors[0].getEncoderCount()) >= 100)
{
pResource::configTable.kLeftMotorDeadMarginNag = i;
break;
}
}
pResource::m_instance->saveConfig();
pResource::m_instance->m_motors[0].setPower(0);
break;
case 2:
pResource::m_instance->m_motors[1].reset();
DelayMsByTicks(250);
for (int16_t i = 50; i < 500; i++)
{
pResource::m_instance->m_motors[1].setPower(i);
DelayMsByTicks(100);
pResource::m_instance->m_motors[1].update();
if (ABS(pResource::m_instance->m_motors[1].getEncoderCount()) >= 100)
{
pResource::configTable.kRightMotorDeadMarginPos = i;
break;
}
}
pResource::m_instance->m_motors[1].setPower(0);
DelayMsByTicks(1000);
pResource::m_instance->m_motors[1].reset();
for (int16_t i = -50; i > -500; i--)
{
pResource::m_instance->m_motors[1].setPower(i);
DelayMsByTicks(100);
pResource::m_instance->m_motors[1].update();
if (ABS(pResource::m_instance->m_motors[1].getEncoderCount()) >= 100)
{
pResource::configTable.kRightMotorDeadMarginNag = i;
break;
}
}
pResource::m_instance->m_motors[1].setPower(0);
pResource::m_instance->saveConfig();
break;
}
}
float pSmartCar::leftMotorMapping(const float val)
{
if (val == 0.0f)
return 0.0f;
else if (val > 0.0f)
return (val + pResource::configTable.kLeftMotorDeadMarginPos);
else
return (val - pResource::configTable.kLeftMotorDeadMarginNag);
}
float pSmartCar::rightMotorMapping(const float val)
{
if (val == 0.0f)
return 0.0f;
else if (val > 0.0f)
return (val + pResource::configTable.kRightMotorDeadMarginPos);
else
return (val - pResource::configTable.kRightMotorDeadMarginNag);
}
void pSmartCar::setMotorsEnabled(const bool enabled)
{
m_motorEnabled = enabled;
m_motors[0].setEnabled(enabled);
m_motors[1].setEnabled(enabled);
}
|
/*
* pSmartCar.cpp
*
* Author: petel__
* Copyright (c) 2014-2016 HKUST SmartCar Team
* Refer to LICENSE for details
*
*/
#include "pSmartCar.h"
#include <pResource.h>
using namespace std;
using namespace libsc;
using namespace libutil;
Button::Config getButtonConfig(const uint8_t id)
{
Button::Config config;
config.id = id;
config.is_active_low = true;
config.listener = pSmartCar::onClickListener;
config.listener_trigger = Button::Config::Trigger::kDown;
return config;
}
pPid::PidParam pSmartCar::getPidConfig(pSmartCar::PidType type)
{
pPid::PidParam param;
switch (type)
{
case 0:
param.kPFunc = function<float (float)>
(
[](float error)
{
if (ABS(error) < 0.3f)
return 0.0f;
else
return pResource::configTable.kAngleKp * sin(error * DegToRad);
}
);
param.kI = &pResource::configTable.kAngleKi;
param.kD = &pResource::configTable.kAngleKd;
param.setPoint = &pResource::configTable.kIdealAngle;
param.ignoreRange = 0.5f;
param.max = 500;
param.min = -500;
break;
case 1:
param.kP = &pResource::configTable.kDirectionKp;
param.kI = &pResource::configTable.kDirectionKi;
param.kD = &pResource::configTable.kDirectionKd;
param.setPoint = &m_direction;
param.ignoreRange = 10.0f;
param.max = 200;
param.min = -200;
break;
case 2:
param.kP = &pResource::configTable.kSpeedKp;
param.kI = &pResource::configTable.kSpeedKi;
param.kD = &pResource::configTable.kSpeedKd;
param.setPoint = &m_speed;
param.ignoreRange = 15.0f;
param.max = 500;
param.min = -500;
}
return param;
}
pSmartCar::pSmartCar(void)
:
m_state(),
m_direction(0.0f),
m_speed(0.0f),
m_loop(),
m_angle(pAngle::Config(pResource::configTable.kAccelTruthVal, pResource::configTable.kCgHeightInM)),
m_motors{ pMotor(pMotor::Config(1, 0, true, false, leftMotorMapping)),
pMotor(pMotor::Config(0, 1, false, true, rightMotorMapping)) },
m_lcd(MiniLcd::Config(0, -1, 30)),
m_buttons{ Button(getButtonConfig(0)),
Button(getButtonConfig(1)),
Button(getButtonConfig(2)) },
m_grapher(),
m_motorEnabled(false),
m_pidControllers{ pPid(getPidConfig(PidType::Angle)),
pPid(getPidConfig(PidType::Direction)),
pPid(getPidConfig(PidType::Speed)) },
m_pidOutputVal{ 0 },
m_filter(pResource::configTable.kKalmanKq, pResource::configTable.kKalmanKr, 0, 0.5),
m_oldSpeedPidOuput(0),
m_smoothCounter(0),
m_smoothIncrement(0)
{
System::Init();
addAllRoutineToLoop();
addVariablesToGrapher();
reset();
}
void pSmartCar::reset(void)
{
m_direction = 0.0f;
m_speed = 0.0f;
m_motors[0].reset();
m_motors[1].reset();
m_lcd.clear();
}
void pSmartCar::run(void)
{
m_loop.start();
}
void pSmartCar::updatePid(const float val, PidType type)
{
m_pidOutputVal[type] = m_pidControllers[type].getOutput(val);
}
pSmartCar::State &pSmartCar::State::operator=(const pSmartCar::State &other)
{
this->angle = other.angle;
this->dAngle = other.dAngle;
this->dX = other.dX;
this->dYaw = other.dYaw;
return *this;
}
void pSmartCar::onClickListener(const uint8_t id)
{
switch (id)
{
default:
assert(false);
// no break
case 0:
pResource::m_instance->setMotorsEnabled(pResource::m_instance->m_motorEnabled = !pResource::m_instance->m_motorEnabled);
break;
case 1:
pResource::m_instance->m_motors[0].reset();
DelayMsByTicks(250);
for (int16_t i = 50; i < 500; i++)
{
pResource::m_instance->m_motors[0].setPower(i);
DelayMsByTicks(100);
pResource::m_instance->m_motors[0].update();
if (ABS(pResource::m_instance->m_motors[0].getEncoderCount()) >= 100)
{
pResource::configTable.kLeftMotorDeadMarginPos = i;
break;
}
}
pResource::m_instance->m_motors[0].setPower(0);
DelayMsByTicks(1000);
pResource::m_instance->m_motors[0].reset();
for (int16_t i = -50; i > -500; i--)
{
pResource::m_instance->m_motors[0].setPower(i);
DelayMsByTicks(100);
pResource::m_instance->m_motors[0].update();
if (ABS(pResource::m_instance->m_motors[0].getEncoderCount()) >= 100)
{
pResource::configTable.kLeftMotorDeadMarginNag = i;
break;
}
}
pResource::m_instance->saveConfig();
pResource::m_instance->m_motors[0].setPower(0);
break;
case 2:
pResource::m_instance->m_motors[1].reset();
DelayMsByTicks(250);
for (int16_t i = 50; i < 500; i++)
{
pResource::m_instance->m_motors[1].setPower(i);
DelayMsByTicks(100);
pResource::m_instance->m_motors[1].update();
if (ABS(pResource::m_instance->m_motors[1].getEncoderCount()) >= 100)
{
pResource::configTable.kRightMotorDeadMarginPos = i;
break;
}
}
pResource::m_instance->m_motors[1].setPower(0);
DelayMsByTicks(1000);
pResource::m_instance->m_motors[1].reset();
for (int16_t i = -50; i > -500; i--)
{
pResource::m_instance->m_motors[1].setPower(i);
DelayMsByTicks(100);
pResource::m_instance->m_motors[1].update();
if (ABS(pResource::m_instance->m_motors[1].getEncoderCount()) >= 100)
{
pResource::configTable.kRightMotorDeadMarginNag = i;
break;
}
}
pResource::m_instance->m_motors[1].setPower(0);
pResource::m_instance->saveConfig();
break;
}
}
float pSmartCar::leftMotorMapping(const float val)
{
if (val == 0.0f)
return 0.0f;
else if (val > 0.0f)
return (val + pResource::configTable.kLeftMotorDeadMarginPos);
else
return (val - pResource::configTable.kLeftMotorDeadMarginNag);
}
float pSmartCar::rightMotorMapping(const float val)
{
if (val == 0.0f)
return 0.0f;
else if (val > 0.0f)
return (val + pResource::configTable.kRightMotorDeadMarginPos);
else
return (val - pResource::configTable.kRightMotorDeadMarginNag);
}
void pSmartCar::setMotorsEnabled(const bool enabled)
{
m_motorEnabled = enabled;
m_motors[0].setEnabled(enabled);
m_motors[1].setEnabled(enabled);
}
|
change pid controllers' setting
|
change pid controllers' setting
|
C++
|
mit
|
hkust-smartcar/Magnetic16-T1,hkust-smartcar/Magnetic16,hkust-smartcar/Magnetic16,hkust-smartcar/Magnetic16-T1
|
81c19ebc5f94af2bbc2e3334142aa6792f41c3e7
|
LargeBarrelAnalysisExtended/main.cpp
|
LargeBarrelAnalysisExtended/main.cpp
|
/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file main.cpp
*/
#include <DBHandler/HeaderFiles/DBHandler.h>
#include <JPetManager/JPetManager.h>
#include <JPetTaskLoader/JPetTaskLoader.h>
#include "TaskA.h"
#include "SignalFinder.h"
#include "PhysicalDescriptor.h"
#include "HitFinder.h"
#include "TimeCalibLoader.h"
#include "TaskC.h"
#include "TaskD.h"
#include "TaskE.h"
using namespace std;
int main(int argc, char* argv[])
{
DB::SERVICES::DBHandler::createDBConnection("../DBConfig/configDB.cfg");
JPetManager& manager = JPetManager::getManager();
manager.parseCmdLine(argc, argv);
// Here create all analysis modules to be used:
manager.registerTask([]() {
return new JPetTaskLoader("hld",
"tslot.raw",
new TaskA("TaskA: Unp to Timewindow",
"Process unpacked HLD file into a tree of JPetTimeWindow objects")
);
});
manager.registerTask([]() {
return new JPetTaskLoader("tslot.raw", "tslot.raw",
new TimeCalibLoader("Apply time corrections from prepared calibrations",
"Apply time corrections from prepared calibrations"));
});
manager.registerTask([]() {
return new JPetTaskLoader("tslot.raw",
"raw.sig",
new SignalFinder("SignalFinder: Create Raw Sigs",
"Create Raw Signals, optionallh draw TOTs per THR",
true)
);
});
manager.registerTask([]() {
return new JPetTaskLoader("phys_sig", "hits",
new HitFinder("Module: Pair signals",
"Create hits from physical signals from both ends of scintilators"));
});
//manager.registerTask([]() {
//return new JPetTaskLoader("raw.sig", "phys.hit",
//new TaskC("Module C: Pair signals",
//"Create hits from pairs of signals"));
//});
// manager.registerTask([](){
// return new JPetTaskLoader("phys.hit", "phys.hit.means",
// new TaskD("Module D: Make histograms for hits",
// "Only make timeDiff histos and produce mean timeDiff value for each threshold and slot to be used by the next module"));
// });
// manager.registerTask([](){
// return new JPetTaskLoader("phys.hit.means", "phys.hit.coincplots",
// new TaskE("Module E: Filter hits",
// "Pass only hits with time diffrerence close to the peak"));
// });
manager.run();
}
|
/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file main.cpp
*/
#include <DBHandler/HeaderFiles/DBHandler.h>
#include <JPetManager/JPetManager.h>
#include <JPetTaskLoader/JPetTaskLoader.h>
#include "TaskA.h"
#include "SignalFinder.h"
#include "PhysicalDescriptor.h"
#include "HitFinder.h"
#include "TimeCalibLoader.h"
#include "TaskC.h"
#include "TaskD.h"
#include "TaskE.h"
using namespace std;
int main(int argc, char* argv[])
{
DB::SERVICES::DBHandler::createDBConnection("../DBConfig/configDB.cfg");
JPetManager& manager = JPetManager::getManager();
manager.parseCmdLine(argc, argv);
// Here create all analysis modules to be used:
manager.registerTask([]() {
return new JPetTaskLoader("hld",
"tslot.raw",
new TaskA("TaskA: Unp to Timewindow",
"Process unpacked HLD file into a tree of JPetTimeWindow objects")
);
});
manager.registerTask([]() {
return new JPetTaskLoader("tslot.raw", "tslot.raw",
new TimeCalibLoader("Apply time corrections from prepared calibrations",
"Apply time corrections from prepared calibrations"));
});
manager.registerTask([]() {
return new JPetTaskLoader("tslot.raw",
"raw.sig",
new SignalFinder("SignalFinder: Create Raw Sigs",
"Create Raw Signals, optional draw TOTs per THR",
true)
);
});
manager.registerTask([]() {
return new JPetTaskLoader("phys_sig", "hits",
new HitFinder("Module: Pair signals",
"Create hits from physical signals from both ends of scintilators"));
});
//manager.registerTask([]() {
//return new JPetTaskLoader("raw.sig", "phys.hit",
//new TaskC("Module C: Pair signals",
//"Create hits from pairs of signals"));
//});
// manager.registerTask([](){
// return new JPetTaskLoader("phys.hit", "phys.hit.means",
// new TaskD("Module D: Make histograms for hits",
// "Only make timeDiff histos and produce mean timeDiff value for each threshold and slot to be used by the next module"));
// });
// manager.registerTask([](){
// return new JPetTaskLoader("phys.hit.means", "phys.hit.coincplots",
// new TaskE("Module E: Filter hits",
// "Pass only hits with time diffrerence close to the peak"));
// });
manager.run();
}
|
Correct comments in main.cpp
|
Correct comments in main.cpp
TESTS ARE NOT PASSING
|
C++
|
apache-2.0
|
JPETTomography/j-pet-framework-examples,JPETTomography/j-pet-framework-examples,JPETTomography/j-pet-framework-examples,JPETTomography/j-pet-framework-examples
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.