text stringlengths 54 60.6k |
|---|
<commit_before>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define BUFSIZE 121
#define FILENAME "Testfile"
#define TEST_FILENAME "Testfile2"
#define PORT 10038
#define PAKSIZE 128
#define ACK 0
#define NAK 1
using namespace std;
bool gremlin(Packet * pack, int corruptProb, int lossProb);
bool init(int argc, char** argv);
bool loadFile();
bool sendFile();
bool getFile();
char * recvPkt();
bool isvpack(unsigned char * p);
Packet createPacket(int index);
bool sendPacket();
bool isAck();
void handleAck();
void handleNak(int& x);
int seqNum;
int s;
int probCorrupt;
int probLoss;
string hs;
short int port;
char * file;
unsigned char* window[16]; //packet window
int windowBase; //used to determine position in window of arriving packets
int length;
struct sockaddr_in a;
struct sockaddr_in sa;
socklen_t salen;
string fstr;
bool dropPck;
Packet p;
int delayT;
unsigned char b[BUFSIZE];
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
if(sendto(s, "GET Testfile", BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
getFile();
return 0;
}
bool init(int argc, char** argv) {
windowBase = 0; //initialize windowBase
s = 0;
hs = string("131.204.14.") + argv[1]; /* Needs to be updated? Might be a string like "tux175.engr.auburn.edu." */
port = 10038; /* Can be any port within 10038-10041, inclusive. */
char* delayTStr = argv[2];
delayT = boost::lexical_cast<int>(delayTStr);
/*if(!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}*/
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY); //why does this always give us 0?
a.sin_port = htons(0);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0){
cout << "Socket binding failed. (socket s, address a)" << endl;
return false;
}
memset((char *)&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
inet_pton(AF_INET, hs.c_str(), &(sa.sin_addr));
cout << endl;
cout << "Server address (inet mode): " << inet_ntoa(sa.sin_addr) << endl;
cout << "Port: " << ntohs(sa.sin_port) << endl;
cout << endl << endl;
/*fstr = string(file);
cout << "File: " << endl << fstr << endl << endl;*/
seqNum = 0;
dropPck = false;
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
bool sendFile() {
for(int x = 0; x <= length / BUFSIZE; x++) {
p = createPacket(x);
if(!sendPacket()) continue;
if(isAck()) {
handleAck();
} else {
handleNak(x);
}
memset(b, 0, BUFSIZE);
}
return true;
}
Packet createPacket(int index){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(index * BUFSIZE + BUFSIZE > length) {
mstr[length - (index * BUFSIZE)] = '\0';
}
return Packet (seqNum, mstr.c_str());
}
bool sendPacket(){
int pc = probCorrupt; int pl = probLoss;
if((dropPck = gremlin(&p, pc, pl)) == false){
if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
} else return false;
}
bool isAck() {
recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&sa, &salen);
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool gremlin(Packet * pack, int corruptProb, int lossProb){
bool dropPacket = false;
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
if(r <= (lossProb)){
dropPacket = true;
cout << "Dropped!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
else seqNum = (seqNum) ? false : true;
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
cout << "Message: " << pack->getDataBuffer() << endl;
return dropPacket;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[6];
memcpy(css, &p[1], 6);
css[5] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[7], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == seqNum) return false;
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
int rlen;
int ack;
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&sa, &salen);
/* Begin Window Loading */
int tempSeqNum = boost::lexical_cast<int>(packet[0]);
int properIndex = tempSeqNum - windowBase;
window[properIndex] = packet;
cout << "Packet loaded into window" << endl;
char* tempTest = new char[6];
memcpy(tempTest, &window[1], 0);
tempTest[5] = '\0';
cout << "The Checksum pulled from client window: " << tempTest[0] << endl;
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
if(isvpack(packet)) {
ack = ACK;
seqNum++;
windowBase++; //increment base of window //FIXME
file << dataPull;
file.flush();
} else {
ack = NAK;
}
cout << "Sent response: ";
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet pk (seqNum++, reinterpret_cast<const char *>(dataPull));
pk.setCheckSum(boost::lexical_cast<int>(css));
pk.setAckNack(ack);
if(packet[6] == '1') usleep(delayT*1000);
if(sendto(s, pk.str(), PAKSIZE, 0, (struct sockaddr *)&sa, salen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
<commit_msg>Make windowBase increment with proper-ish timing<commit_after>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define BUFSIZE 121
#define FILENAME "Testfile"
#define TEST_FILENAME "Testfile2"
#define PORT 10038
#define PAKSIZE 128
#define ACK 0
#define NAK 1
using namespace std;
bool gremlin(Packet * pack, int corruptProb, int lossProb);
bool init(int argc, char** argv);
bool loadFile();
bool sendFile();
bool getFile();
char * recvPkt();
bool isvpack(unsigned char * p);
Packet createPacket(int index);
bool sendPacket();
bool isAck();
void handleAck();
void handleNak(int& x);
int seqNum;
int s;
int probCorrupt;
int probLoss;
string hs;
short int port;
char * file;
unsigned char* window[16]; //packet window
int windowBase; //used to determine position in window of arriving packets
int length;
struct sockaddr_in a;
struct sockaddr_in sa;
socklen_t salen;
string fstr;
bool dropPck;
Packet p;
int delayT;
unsigned char b[BUFSIZE];
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
if(sendto(s, "GET Testfile", BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
getFile();
return 0;
}
bool init(int argc, char** argv) {
windowBase = 0; //initialize windowBase
s = 0;
hs = string("131.204.14.") + argv[1]; /* Needs to be updated? Might be a string like "tux175.engr.auburn.edu." */
port = 10038; /* Can be any port within 10038-10041, inclusive. */
char* delayTStr = argv[2];
delayT = boost::lexical_cast<int>(delayTStr);
/*if(!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}*/
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY); //why does this always give us 0?
a.sin_port = htons(0);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0){
cout << "Socket binding failed. (socket s, address a)" << endl;
return false;
}
memset((char *)&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
inet_pton(AF_INET, hs.c_str(), &(sa.sin_addr));
cout << endl;
cout << "Server address (inet mode): " << inet_ntoa(sa.sin_addr) << endl;
cout << "Port: " << ntohs(sa.sin_port) << endl;
cout << endl << endl;
/*fstr = string(file);
cout << "File: " << endl << fstr << endl << endl;*/
seqNum = 0;
dropPck = false;
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
bool sendFile() {
for(int x = 0; x <= length / BUFSIZE; x++) {
p = createPacket(x);
if(!sendPacket()) continue;
if(isAck()) {
handleAck();
} else {
handleNak(x);
}
memset(b, 0, BUFSIZE);
}
return true;
}
Packet createPacket(int index){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(index * BUFSIZE + BUFSIZE > length) {
mstr[length - (index * BUFSIZE)] = '\0';
}
return Packet (seqNum, mstr.c_str());
}
bool sendPacket(){
int pc = probCorrupt; int pl = probLoss;
if((dropPck = gremlin(&p, pc, pl)) == false){
if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
} else return false;
}
bool isAck() {
recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&sa, &salen);
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool gremlin(Packet * pack, int corruptProb, int lossProb){
bool dropPacket = false;
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
if(r <= (lossProb)){
dropPacket = true;
cout << "Dropped!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
else seqNum = (seqNum) ? false : true;
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
cout << "Message: " << pack->getDataBuffer() << endl;
return dropPacket;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[6];
memcpy(css, &p[1], 6);
css[5] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[7], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == seqNum) return false;
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
int rlen;
int ack;
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&sa, &salen);
/* Begin Window Loading */
int tempSeqNum = boost::lexical_cast<int>(packet[0]);
int properIndex = tempSeqNum - windowBase;
window[properIndex] = packet;
cout << "Packet loaded into window" << endl;
char* tempTest = new char[6];
memcpy(tempTest, &window[1], 0);
tempTest[5] = '\0';
cout << "The Checksum pulled from client window: " << tempTest[0] << endl;
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
if(isvpack(packet)) {
ack = ACK;
if(boost::lexical_cast<int>(packet[0]) == windowBase) windowBase++; //increment base of window //FIXME
file << dataPull;
file.flush();
} else {
ack = NAK;
}
cout << "Sent response: ";
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
if(packet[6] == '1') usleep(delayT*1000);
if(sendto(s, boost::lexical_cast<char>(windowBase), PAKSIZE, 0, (struct sockaddr *)&sa, salen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
<|endoftext|> |
<commit_before><commit_msg>Free transactions is unsupported yet.<commit_after><|endoftext|> |
<commit_before>#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
#include <random>
TEST(ProbDistributionsLkjCov, testIdentity) {
std::random_device rd;
std::mt19937 mt(rd());
unsigned int K = 4;
Eigen::MatrixXd Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
double eta = rd() / static_cast<double>(RAND_MAX) + 0.5;
double f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f, stan::math::lkj_corr_log(Sigma, eta));
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f, stan::math::lkj_corr_log(Sigma, eta));
}
TEST(ProbDistributionsLkjCov, testHalf) {
std::random_device rd;
std::mt19937 mt(rd());
unsigned int K = 4;
Eigen::MatrixXd Sigma(K, K);
Sigma.setConstant(0.5);
Sigma.diagonal().setOnes();
double eta = rd() / static_cast<double>(RAND_MAX) + 0.5;
double f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f + (eta - 1.0) * log(0.3125),
stan::math::lkj_corr_log(Sigma, eta));
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f, stan::math::lkj_corr_log(Sigma, eta));
}
TEST(ProbDistributionsLkjCov, Sigma) {
std::random_device rd;
std::mt19937 mt(rd());
unsigned int K = 4;
Eigen::MatrixXd Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
double eta = rd() / static_cast<double>(RAND_MAX) + 0.5;
EXPECT_NO_THROW(stan::math::lkj_corr_log(Sigma, eta));
EXPECT_THROW(stan::math::lkj_corr_log(Sigma, -eta), std::domain_error);
Sigma = Sigma * -1.0;
EXPECT_THROW(stan::math::lkj_corr_log(Sigma, eta), std::domain_error);
Sigma = Sigma * (0.0 / 0.0);
EXPECT_THROW(stan::math::lkj_corr_log(Sigma, eta), std::domain_error);
}
<commit_msg>Test lkj_cov_lpdf.<commit_after>#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
TEST(ProbDistributionsLkjCov, testIdentity) {
boost::random::mt19937 rng;
unsigned int K = 4;
Eigen::MatrixXd Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
double mu = 0;
Eigen::VectorXd muV = Eigen::VectorXd::Zero(K);
double sd = 1;
Eigen::VectorXd sdV = Eigen::VectorXd::Ones(K);
double eta = stan::math::uniform_rng(0.5, 1.5, rng);
double f = stan::math::do_lkj_constant(eta, K)
+ K * stan::math::lognormal_lpdf(1, 0, 1);
EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, mu, sd, eta));
EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, muV, sdV, eta));
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K)
+ K * stan::math::lognormal_lpdf(1, 0, 1);
EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, mu, sd, eta));
EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, muV, sdV, eta));
}
TEST(ProbDistributionsLkjCov, testHalf) {
boost::random::mt19937 rng;
unsigned int K = 4;
Eigen::MatrixXd Sigma(K, K);
Sigma.setConstant(0.5);
Sigma.diagonal().setOnes();
double mu = 0;
Eigen::VectorXd muV = Eigen::VectorXd::Zero(K);
double sd = 1;
Eigen::VectorXd sdV = Eigen::VectorXd::Ones(K);
double eta = stan::math::uniform_rng(0.5, 1.5, rng);
double f = stan::math::do_lkj_constant(eta, K)
+ K * stan::math::lognormal_lpdf(1, 0, 1)
+ (eta - 1.0) * log(0.3125);
EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, mu, sd, eta));
EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, muV, sdV, eta));
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K)
+ K * stan::math::lognormal_lpdf(1, 0, 1);
EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, mu, sd, eta));
EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, muV, sdV, eta));
}
TEST(ProbDistributionsLkjCov, ErrorChecks) {
boost::random::mt19937 rng;
unsigned int K = 4;
Eigen::MatrixXd Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
double mu = 0;
Eigen::VectorXd muV = Eigen::VectorXd::Zero(K);
double sd = 1;
Eigen::VectorXd sdV = Eigen::VectorXd::Ones(K);
double eta = stan::math::uniform_rng(0.5, 1.5, rng);
EXPECT_NO_THROW(stan::math::lkj_cov_lpdf(Sigma, mu, sd, eta));
// Error checks for non vectorized version.
EXPECT_NO_THROW(stan::math::lkj_cov_lpdf(Sigma, -1, sd, eta));
EXPECT_THROW(
stan::math::lkj_cov_lpdf(Sigma, stan::math::NOT_A_NUMBER, sd, eta),
std::domain_error);
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, stan::math::INFTY, sd, eta),
std::domain_error);
EXPECT_THROW(
stan::math::lkj_cov_lpdf(Sigma, stan::math::NEGATIVE_INFTY, sd, eta),
std::domain_error);
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, mu, -1, eta), std::domain_error);
EXPECT_THROW(
stan::math::lkj_cov_lpdf(Sigma, mu, stan::math::NOT_A_NUMBER, eta),
std::domain_error);
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, mu, stan::math::INFTY, eta),
std::domain_error);
EXPECT_THROW(
stan::math::lkj_cov_lpdf(Sigma, mu, stan::math::NEGATIVE_INFTY, eta),
std::domain_error);
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, mu, sd, -1), std::domain_error);
EXPECT_THROW(
stan::math::lkj_cov_lpdf(Sigma, muV, sd, stan::math::NOT_A_NUMBER),
std::domain_error);
EXPECT_NO_THROW(stan::math::lkj_cov_lpdf(Sigma, mu, sd, stan::math::INFTY));
EXPECT_THROW(
stan::math::lkj_cov_lpdf(Sigma, mu, sd, stan::math::NEGATIVE_INFTY),
std::domain_error);
// Vectorized.
Eigen::VectorXd muV1 = -muV;
EXPECT_NO_THROW(stan::math::lkj_cov_lpdf(Sigma, muV1, sdV, eta));
muV1 = stan::math::NOT_A_NUMBER * muV;
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV1, sdV, eta),
std::domain_error);
muV1 = stan::math::INFTY * muV;
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV1, sdV, eta),
std::domain_error);
muV1 = stan::math::NEGATIVE_INFTY * muV;
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV1, sdV, eta),
std::domain_error);
Eigen::VectorXd sdV1 = -sdV;
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV1, eta),
std::domain_error);
sdV1 = stan::math::NOT_A_NUMBER * sdV;
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV1, eta),
std::domain_error);
sdV1 = stan::math::INFTY * sdV;
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV1, eta),
std::domain_error);
sdV1 = stan::math::NEGATIVE_INFTY * sdV;
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV1, eta),
std::domain_error);
EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV, -1),
std::domain_error);
EXPECT_THROW(
stan::math::lkj_cov_lpdf(Sigma, muV, sdV, stan::math::NOT_A_NUMBER),
std::domain_error);
EXPECT_NO_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV, stan::math::INFTY));
EXPECT_THROW(
stan::math::lkj_cov_lpdf(Sigma, muV, sdV, stan::math::NEGATIVE_INFTY),
std::domain_error);
}
<|endoftext|> |
<commit_before><commit_msg>création d'une classe Weather<commit_after><|endoftext|> |
<commit_before><commit_msg>mapper: Support association property removes<commit_after><|endoftext|> |
<commit_before><commit_msg>Add all current work to main<commit_after><|endoftext|> |
<commit_before><commit_msg>refactor code<commit_after><|endoftext|> |
<commit_before><commit_msg>Second Change Hot Fix for Block 850242 <commit_after><|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "shadingengine.h"
// appleseed.renderer headers.
#include "renderer/kernel/aov/shadingfragmentstack.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingfragment.h"
#include "renderer/kernel/shading/shadingray.h"
#include "renderer/kernel/shading/shadingresult.h"
#include "renderer/modeling/environment/environment.h"
#include "renderer/modeling/environmentshader/environmentshader.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/input/source.h"
#include "renderer/modeling/material/material.h"
#include "renderer/modeling/object/object.h"
#include "renderer/modeling/scene/assembly.h"
#include "renderer/modeling/scene/assemblyinstance.h"
#include "renderer/modeling/scene/objectinstance.h"
#include "renderer/modeling/scene/scene.h"
#ifdef WITH_OSL
#include "renderer/modeling/shadergroup/shadergroup.h"
#endif
#include "renderer/modeling/surfaceshader/diagnosticsurfaceshader.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
using namespace foundation;
using namespace std;
namespace renderer
{
//
// ShadingEngine class implementation.
//
ShadingEngine::ShadingEngine(const ParamArray& params)
{
create_diagnostic_surface_shader(params);
}
void ShadingEngine::create_diagnostic_surface_shader(const ParamArray& params)
{
if (params.dictionaries().exist("override_shading"))
{
m_diagnostic_surface_shader =
DiagnosticSurfaceShaderFactory().create(
"__diagnostic_surface_shader",
params.child("override_shading"));
}
}
void ShadingEngine::shade_hit_point(
SamplingContext& sampling_context,
const PixelContext& pixel_context,
const ShadingContext& shading_context,
const ShadingPoint& shading_point,
ShadingResult& shading_result) const
{
// Retrieve the material of the intersected surface.
const Material* material = shading_point.get_material();
// Compute the alpha channel of the main output.
if (material && material->get_alpha_map())
{
// There is an alpha map: evaluate it.
material->get_alpha_map()->evaluate(
shading_context.get_texture_cache(),
shading_point.get_uv(0),
shading_result.m_main.m_alpha);
}
else
{
// No alpha map: solid sample.
shading_result.m_main.m_alpha = Alpha(1.0f);
}
#ifdef WITH_OSL
// Apply OSL transparency.
if (material && material->get_osl_surface() && material->get_osl_surface()->has_transparency())
{
Alpha alpha;
shading_context.execute_osl_transparency(
*material->get_osl_surface(),
shading_point,
alpha);
shading_result.m_main.m_alpha *= alpha;
}
#endif
if (shading_result.m_main.m_alpha[0] > 0.0f || material->shade_alpha_cutouts())
{
// Use the diagnostic surface shader if there is one.
const SurfaceShader* surface_shader = m_diagnostic_surface_shader.get();
if (surface_shader == 0)
{
if (material == 0)
{
// The intersected surface has no material: return solid pink.
shading_result.set_main_to_opaque_pink_linear_rgba();
shading_result.set_aovs_to_transparent_black_linear_rgba();
return;
}
// Use the surface shader of the intersected surface.
surface_shader = material->get_surface_shader();
if (surface_shader == 0)
{
// The intersected surface has no surface shader: return solid pink.
shading_result.set_main_to_opaque_pink_linear_rgba();
shading_result.set_aovs_to_transparent_black_linear_rgba();
return;
}
}
// Execute the surface shader.
surface_shader->evaluate(
sampling_context,
pixel_context,
shading_context,
shading_point,
shading_result);
// Set AOVs.
shading_result.set_entity_aov(shading_point.get_assembly());
shading_result.set_entity_aov(shading_point.get_assembly_instance());
shading_result.set_entity_aov(shading_point.get_object());
shading_result.set_entity_aov(shading_point.get_object_instance());
if (material)
shading_result.set_entity_aov(*material);
shading_result.set_entity_aov(*surface_shader);
}
else
{
// Alpha is zero: shade as transparent black.
shading_result.set_main_to_transparent_black_linear_rgba();
shading_result.set_aovs_to_transparent_black_linear_rgba();
}
}
void ShadingEngine::shade_environment(
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const ShadingPoint& shading_point,
ShadingResult& shading_result) const
{
// Retrieve the environment shader of the scene.
const EnvironmentShader* environment_shader =
shading_point.get_scene().get_environment()->get_environment_shader();
if (environment_shader)
{
// There is an environment shader: execute it.
InputEvaluator input_evaluator(shading_context.get_texture_cache());
const ShadingRay& ray = shading_point.get_ray();
const Vector3d direction = normalize(ray.m_dir);
environment_shader->evaluate(
input_evaluator,
direction,
shading_result);
// Set environment shader AOV.
shading_result.set_entity_aov(*environment_shader);
}
else
{
// No environment shader: shade as transparent black.
shading_result.set_main_to_transparent_black_linear_rgba();
shading_result.set_aovs_to_transparent_black_linear_rgba();
}
}
} // namespace renderer
<commit_msg>added an assertion to clear a potential bug reported by static analysis.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "shadingengine.h"
// appleseed.renderer headers.
#include "renderer/kernel/aov/shadingfragmentstack.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingfragment.h"
#include "renderer/kernel/shading/shadingray.h"
#include "renderer/kernel/shading/shadingresult.h"
#include "renderer/modeling/environment/environment.h"
#include "renderer/modeling/environmentshader/environmentshader.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/input/source.h"
#include "renderer/modeling/material/material.h"
#include "renderer/modeling/object/object.h"
#include "renderer/modeling/scene/assembly.h"
#include "renderer/modeling/scene/assemblyinstance.h"
#include "renderer/modeling/scene/objectinstance.h"
#include "renderer/modeling/scene/scene.h"
#ifdef WITH_OSL
#include "renderer/modeling/shadergroup/shadergroup.h"
#endif
#include "renderer/modeling/surfaceshader/diagnosticsurfaceshader.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
using namespace foundation;
using namespace std;
namespace renderer
{
//
// ShadingEngine class implementation.
//
ShadingEngine::ShadingEngine(const ParamArray& params)
{
create_diagnostic_surface_shader(params);
}
void ShadingEngine::create_diagnostic_surface_shader(const ParamArray& params)
{
if (params.dictionaries().exist("override_shading"))
{
m_diagnostic_surface_shader =
DiagnosticSurfaceShaderFactory().create(
"__diagnostic_surface_shader",
params.child("override_shading"));
}
}
void ShadingEngine::shade_hit_point(
SamplingContext& sampling_context,
const PixelContext& pixel_context,
const ShadingContext& shading_context,
const ShadingPoint& shading_point,
ShadingResult& shading_result) const
{
// Retrieve the material of the intersected surface.
const Material* material = shading_point.get_material();
// Compute the alpha channel of the main output.
if (material && material->get_alpha_map())
{
// There is an alpha map: evaluate it.
material->get_alpha_map()->evaluate(
shading_context.get_texture_cache(),
shading_point.get_uv(0),
shading_result.m_main.m_alpha);
}
else
{
// No material or no alpha map: solid sample.
shading_result.m_main.m_alpha = Alpha(1.0f);
}
#ifdef WITH_OSL
// Apply OSL transparency.
if (material && material->get_osl_surface() && material->get_osl_surface()->has_transparency())
{
Alpha alpha;
shading_context.execute_osl_transparency(
*material->get_osl_surface(),
shading_point,
alpha);
shading_result.m_main.m_alpha *= alpha;
}
#endif
// At this point, we can't have a fully transparent sample and yet have no material.
assert(shading_result.m_main.m_alpha[0] > 0.0f || material);
// Shade the sample if it isn't fully transparent.
if (shading_result.m_main.m_alpha[0] > 0.0f || material->shade_alpha_cutouts())
{
// Use the diagnostic surface shader if there is one.
const SurfaceShader* surface_shader = m_diagnostic_surface_shader.get();
if (surface_shader == 0)
{
if (material == 0)
{
// The intersected surface has no material: return solid pink.
shading_result.set_main_to_opaque_pink_linear_rgba();
shading_result.set_aovs_to_transparent_black_linear_rgba();
return;
}
// Use the surface shader of the intersected surface.
surface_shader = material->get_surface_shader();
if (surface_shader == 0)
{
// The intersected surface has no surface shader: return solid pink.
shading_result.set_main_to_opaque_pink_linear_rgba();
shading_result.set_aovs_to_transparent_black_linear_rgba();
return;
}
}
// Execute the surface shader.
surface_shader->evaluate(
sampling_context,
pixel_context,
shading_context,
shading_point,
shading_result);
// Set AOVs.
shading_result.set_entity_aov(shading_point.get_assembly());
shading_result.set_entity_aov(shading_point.get_assembly_instance());
shading_result.set_entity_aov(shading_point.get_object());
shading_result.set_entity_aov(shading_point.get_object_instance());
if (material)
shading_result.set_entity_aov(*material);
shading_result.set_entity_aov(*surface_shader);
}
else
{
// Alpha is zero: shade as transparent black.
shading_result.set_main_to_transparent_black_linear_rgba();
shading_result.set_aovs_to_transparent_black_linear_rgba();
}
}
void ShadingEngine::shade_environment(
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const ShadingPoint& shading_point,
ShadingResult& shading_result) const
{
// Retrieve the environment shader of the scene.
const EnvironmentShader* environment_shader =
shading_point.get_scene().get_environment()->get_environment_shader();
if (environment_shader)
{
// There is an environment shader: execute it.
InputEvaluator input_evaluator(shading_context.get_texture_cache());
const ShadingRay& ray = shading_point.get_ray();
const Vector3d direction = normalize(ray.m_dir);
environment_shader->evaluate(
input_evaluator,
direction,
shading_result);
// Set environment shader AOV.
shading_result.set_entity_aov(*environment_shader);
}
else
{
// No environment shader: shade as transparent black.
shading_result.set_main_to_transparent_black_linear_rgba();
shading_result.set_aovs_to_transparent_black_linear_rgba();
}
}
} // namespace renderer
<|endoftext|> |
<commit_before>#pragma once
#include <sstream>
#include <type_traits>
#include "blackhole/attribute.hpp"
#include "blackhole/detail/traits/supports/stream_push.hpp"
#include "blackhole/utils/lazy.hpp"
namespace blackhole {
namespace aux {
//! \brief Converts various types to log event attributes.
/*! Helper hierarchy of template classes that allows to pass objects of user
* defined classes as attribute in main logging macro. To make this possible,
* user defined class must have fully defined stream push `operator<<`.
* The logic is as follows: if the object can be implicitly converted to the
* `attribute::value_t` object, then that convertion is used.
* Otherwise the library would check via SFINAE if the custom class has defined
* stream push `operator<<` and, if yes - uses it.
* Otherwise static assert with human-readable message is triggered.
*/
template<typename T, class = void>
struct conv;
template<typename T>
struct conv<T, typename std::enable_if<
attribute::is_constructible<T>::value>::type
>
{
static attribute::value_t from(T&& value) {
return attribute::value_t(std::forward<T>(value));
}
};
template<typename T>
struct conv<T, typename std::enable_if<
!attribute::is_constructible<T>::value &&
traits::supports::stream_push<T>::value>::type
>
{
static attribute::value_t from(T&& value) {
std::ostringstream stream;
stream << value;
return attribute::value_t(stream.str());
}
};
template<typename T>
struct conv<T, typename std::enable_if<
!attribute::is_constructible<T>::value &&
!traits::supports::stream_push<T>::value>::type
>
{
static attribute::value_t from(T&&) {
static_assert(lazy_false<T>::value, "stream operator<< is not defined for type `T`");
return attribute::value_t();
}
};
} // namespace aux
} // namespace blackhole
<commit_msg>[Code Style] And again.<commit_after>#pragma once
#include <sstream>
#include <type_traits>
#include "blackhole/attribute.hpp"
#include "blackhole/detail/traits/supports/stream_push.hpp"
#include "blackhole/utils/lazy.hpp"
namespace blackhole {
namespace aux {
/*!
* Converts various types to log event attributes.
*
* Helper hierarchy of template classes that allows to pass objects of user
* defined classes as attribute in tha main logging macro.
* To make this possible, user defined class must have fully defined stream
* push `operator<<`.
* The logic is as follows: if the object can be implicitly converted to
* the `attribute::value_t` object, then that convertion is used.
* Otherwise the library would check via SFINAE if the custom class has defined
* stream push `operator<<` and, if yes - uses it.
* Otherwise static assert with human-readable message is triggered.
*/
template<typename T, class = void>
struct conv;
template<typename T>
struct conv<T, typename std::enable_if<
attribute::is_constructible<T>::value>::type
>
{
static attribute::value_t from(T&& value) {
return attribute::value_t(std::forward<T>(value));
}
};
template<typename T>
struct conv<T, typename std::enable_if<
!attribute::is_constructible<T>::value &&
traits::supports::stream_push<T>::value>::type
>
{
static attribute::value_t from(T&& value) {
std::ostringstream stream;
stream << value;
return attribute::value_t(stream.str());
}
};
template<typename T>
struct conv<T, typename std::enable_if<
!attribute::is_constructible<T>::value &&
!traits::supports::stream_push<T>::value>::type
>
{
static attribute::value_t from(T&&) {
static_assert(lazy_false<T>::value, "stream operator<< is not defined for type `T`");
return attribute::value_t();
}
};
} // namespace aux
} // namespace blackhole
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
#include <TFile.h>
#include <TTree.h>
#include <TChain.h>
#include <TVectorD.h>
#include <TF1.h>
#include "R.h"
#include "Units.h"
using namespace GeFiCa;
void R::SOR2(int idx,bool elec)
{
if (fIsFixed[idx])return ;
double density=fImpurity[idx]*Qe;
double h2=fdC1m[idx];
double h3=fdC1p[idx];
double tmp=(+density/epsilon*(h2+h3)*0.5+1/fC1[idx]*(fPotential[idx+1]-fPotential[idx-1])
+fPotential[idx+1]/h2+fPotential[idx-1]/h3)/(1/h2+1/h3);
//fPotential[idx]=Csor*(tmp-fPotential[idx])+fPotential[idx];
double oldP=fPotential[idx];
tmp=Csor*(tmp-oldP)+oldP;
}
//_____________________________________________________________________________
//
void R::SOR4(int idx)
{
if (fIsFixed[idx])return;
double density=fImpurity[idx]*1.6e-19;
double h2=fdC1m[idx];
double h3=fdC1p[idx];
double h1=h2;
double xp2,xm2,xm1,xp1;
xm1=fPotential[idx-1];
xp1=fPotential[idx+1];
if(idx>1)xm2=fPotential[idx-2];
else {SOR2(idx,0);return; }
if(idx<n-2)xp2=fPotential[idx+2];
else {SOR2(idx,0);return;}
double tmp=(-1/12*xp2+4/3*xp1+4/3*xm1-1/12*xm2-density/epsilon*h1*h1)*2/5;
fPotential[idx]=Csor*(tmp-fPotential[idx])+fPotential[idx];
fE1[idx]=(fPotential[idx+1]-fPotential[idx-1])/(h2+h3);
}
<commit_msg>depleted check fixed<commit_after>#include <iostream>
using namespace std;
#include <TFile.h>
#include <TTree.h>
#include <TChain.h>
#include <TVectorD.h>
#include <TF1.h>
#include "R.h"
#include "Units.h"
using namespace GeFiCa;
void R::SOR2(int idx,bool elec)
{
if (fIsFixed[idx])return ;
double density=fImpurity[idx]*Qe;
double h2=fdC1m[idx];
double h3=fdC1p[idx];
double p2=fPotential[idx-1];
double p3=fPotential[idx+1];
double tmp=(+density/epsilon*(h2+h3)*0.5+1/fC1[idx]*(p3-p2)
+p3/h2+p2/h3)/(1/h2+1/h3);
//find minmium and maxnium of all five grid, the new one should not go overthem.
//find min
double min=p2;
double max=p2;
if(min>p3)min=p3;
//find max
if(max<p3)max=p3;
//if tmp is greater or smaller than max and min, set tmp to it.
//fPotential[idx]=Csor*(tmp-fPotential[idx])+fPotential[idx];
double oldP=fPotential[idx];
tmp=Csor*(tmp-oldP)+oldP;
if(tmp<min)
{
fPotential[idx]=min;
fIsDepleted[idx]=false;
}
else if(tmp>max)
{
fPotential[idx]=max;
fIsDepleted[idx]=false;
}
else
fIsDepleted[idx]=true;
if(fIsDepleted[idx]||!NotImpurityPotential)
{
//over relax
fPotential[idx]=tmp;
}
}
//_____________________________________________________________________________
//
void R::SOR4(int idx)
{
if (fIsFixed[idx])return;
double density=fImpurity[idx]*1.6e-19;
double h2=fdC1m[idx];
double h3=fdC1p[idx];
double h1=h2;
double xp2,xm2,xm1,xp1;
xm1=fPotential[idx-1];
xp1=fPotential[idx+1];
if(idx>1)xm2=fPotential[idx-2];
else {SOR2(idx,0);return; }
if(idx<n-2)xp2=fPotential[idx+2];
else {SOR2(idx,0);return;}
double tmp=(-1/12*xp2+4/3*xp1+4/3*xm1-1/12*xm2-density/epsilon*h1*h1)*2/5;
fPotential[idx]=Csor*(tmp-fPotential[idx])+fPotential[idx];
fE1[idx]=(fPotential[idx+1]-fPotential[idx-1])/(h2+h3);
}
<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2022 *
* *
* 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 <modules/skybrowser/include/targetbrowserpair.h>
#include <modules/skybrowser/include/renderableskytarget.h>
#include <modules/skybrowser/include/screenspaceskybrowser.h>
#include <modules/skybrowser/include/utility.h>
#include <modules/skybrowser/include/wwtdatahandler.h>
#include <modules/skybrowser/skybrowsermodule.h>
#include <openspace/camera/camera.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/moduleengine.h>
#include <openspace/navigation/navigationhandler.h>
#include <openspace/rendering/screenspacerenderable.h>
#include <openspace/scripting/scriptengine.h>
#include <ghoul/misc/assert.h>
#include <glm/gtc/constants.hpp>
#include <functional>
#include <chrono>
namespace {
void aimTargetGalactic(std::string id, glm::dvec3 direction) {
glm::dvec3 positionCelestial = glm::normalize(direction) *
openspace::skybrowser::CelestialSphereRadius;
std::string script = fmt::format(
"openspace.setPropertyValueSingle('Scene.{}.Translation.Position', {});",
id, ghoul::to_string(positionCelestial)
);
openspace::global::scriptEngine->queueScript(
script,
openspace::scripting::ScriptEngine::RemoteScripting::Yes
);
}
} // namespace
namespace openspace {
TargetBrowserPair::TargetBrowserPair(SceneGraphNode* targetNode,
ScreenSpaceSkyBrowser* browser)
: _browser(browser)
, _targetNode(targetNode)
{
ghoul_assert(browser, "Sky browser is null pointer");
ghoul_assert(targetNode, "Sky target is null pointer");
_targetRenderable = dynamic_cast<RenderableSkyTarget*>(_targetNode->renderable());
}
void TargetBrowserPair::setImageOrder(int i, int order) {
_browser->setImageOrder(i, order);
}
void TargetBrowserPair::startFinetuningTarget() {
_startTargetPosition = _targetNode->worldPosition();
}
// The fine tune of the target is a way to "drag and drop" the target with click
// drag on the sky browser window. This is to be able to drag the target around when it
// has a very small field of view
void TargetBrowserPair::fineTuneTarget(const glm::vec2& translation) {
glm::dvec2 percentage = glm::dvec2(translation);
glm::dvec3 right = _targetRenderable->rightVector() * percentage.x;
glm::dvec3 up = _targetRenderable->upVector() * percentage.y;
glm::dvec3 newPosition = _startTargetPosition - (right - up);
aimTargetGalactic(
_targetNode->identifier(),
newPosition
);
}
void TargetBrowserPair::synchronizeAim() {
if (!_targetAnimation.isAnimating() && _browser->isInitialized()) {
_browser->setEquatorialAim(targetDirectionEquatorial());
_browser->setTargetRoll(targetRoll());
_targetRenderable->setVerticalFov(_browser->verticalFov());
}
}
void TargetBrowserPair::setEnabled(bool enable) {
_browser->setEnabled(enable);
_targetRenderable->property("Enabled")->set(enable);
}
bool TargetBrowserPair::isEnabled() const {
return _targetRenderable->isEnabled() || _browser->isEnabled();
}
void TargetBrowserPair::initialize() {
_targetRenderable->setColor(_browser->borderColor());
glm::vec2 dim = _browser->screenSpaceDimensions();
_targetRenderable->setRatio(dim.x / dim.y);
_browser->updateBorderColor();
_browser->hideChromeInterface();
_browser->setIsInitialized(true);
}
glm::ivec3 TargetBrowserPair::borderColor() const {
return _browser->borderColor();
}
glm::dvec2 TargetBrowserPair::targetDirectionEquatorial() const {
glm::dvec3 cartesian = skybrowser::galacticToEquatorial(
glm::normalize(_targetNode->worldPosition())
);
return skybrowser::cartesianToSpherical(cartesian);
}
glm::dvec3 TargetBrowserPair::targetDirectionGalactic() const {
return glm::normalize(_targetNode->worldPosition());
}
std::string TargetBrowserPair::browserGuiName() const {
return _browser->guiName();
}
std::string TargetBrowserPair::browserId() const {
return _browser->identifier();
}
std::string TargetBrowserPair::targetRenderableId() const {
return _targetRenderable->identifier();
}
std::string TargetBrowserPair::targetNodeId() const {
return _targetNode->identifier();
}
double TargetBrowserPair::verticalFov() const {
return _browser->verticalFov();
}
std::vector<int> TargetBrowserPair::selectedImages() const {
return _browser->selectedImages();
}
ghoul::Dictionary TargetBrowserPair::dataAsDictionary() const {
glm::dvec2 spherical = targetDirectionEquatorial();
glm::dvec3 cartesian = skybrowser::sphericalToCartesian(spherical);
ghoul::Dictionary res;
res.setValue("id", browserId());
res.setValue("name", browserGuiName());
res.setValue("fov", static_cast<double>(verticalFov()));
res.setValue("ra", spherical.x);
res.setValue("dec", spherical.y);
res.setValue("roll", targetRoll());
res.setValue("color", borderColor());
res.setValue("cartesianDirection", cartesian);
res.setValue("ratio", static_cast<double>(_browser->browserRatio()));
res.setValue("isFacingCamera", isFacingCamera());
res.setValue("isUsingRae", isUsingRadiusAzimuthElevation());
res.setValue("selectedImages", selectedImages());
res.setValue("scale", static_cast<double>(_browser->scale()));
res.setValue("opacities", _browser->opacities());
res.setValue("borderRadius", _browser->borderRadius());
std::vector<std::pair<std::string, glm::dvec3>> copies = displayCopies();
std::vector<std::pair<std::string, bool>> showCopies = _browser->showDisplayCopies();
ghoul::Dictionary copiesData;
for (size_t i = 0; i < copies.size(); i++) {
ghoul::Dictionary copy;
copy.setValue("position", copies[i].second);
copy.setValue("show", showCopies[i].second);
copy.setValue("idShowProperty", showCopies[i].first);
copiesData.setValue(copies[i].first, copy);
}
// Set table for the current target
res.setValue("displayCopies", copiesData);
return res;
}
void TargetBrowserPair::selectImage(const ImageData& image, int i) {
// Load image into browser
_browser->selectImage(image.imageUrl, i);
// If the image has coordinates, move the target
if (image.hasCelestialCoords) {
// Animate the target to the image coordinate position
glm::dvec3 galactic = skybrowser::equatorialToGalactic(image.equatorialCartesian);
startAnimation(galactic * skybrowser::CelestialSphereRadius, image.fov);
}
}
void TargetBrowserPair::addImageLayerToWwt(const std::string& url, int i) {
_browser->addImageLayerToWwt(url, i);
}
void TargetBrowserPair::removeSelectedImage(int i) {
_browser->removeSelectedImage(i);
}
void TargetBrowserPair::loadImageCollection(const std::string& collection) {
_browser->loadImageCollection(collection);
}
void TargetBrowserPair::setImageOpacity(int i, float opacity) {
_browser->setImageOpacity(i, opacity);
}
void TargetBrowserPair::hideChromeInterface() {
_browser->hideChromeInterface();
}
void TargetBrowserPair::sendIdToBrowser() const {
_browser->setIdInBrowser();
}
std::vector<std::pair<std::string, glm::dvec3>> TargetBrowserPair::displayCopies() const {
return _browser->displayCopies();
}
void TargetBrowserPair::setVerticalFov(double vfov) {
_browser->setVerticalFov(vfov);
_targetRenderable->setVerticalFov(vfov);
}
void TargetBrowserPair::setEquatorialAim(const glm::dvec2& aim) {
aimTargetGalactic(
_targetNode->identifier(),
skybrowser::equatorialToGalactic(skybrowser::sphericalToCartesian(aim))
);
_browser->setEquatorialAim(aim);
}
void TargetBrowserPair::setBorderColor(const glm::ivec3& color) {
_targetRenderable->setColor(color);
_browser->setBorderColor(color);
}
void TargetBrowserPair::setBorderRadius(double radius) {
_browser->setBorderRadius(radius);
_targetRenderable->setBorderRadius(radius);
}
void TargetBrowserPair::setBrowserRatio(float ratio) {
_browser->setRatio(ratio);
_targetRenderable->setRatio(ratio);
}
void TargetBrowserPair::setVerticalFovWithScroll(float scroll) {
double fov = _browser->setVerticalFovWithScroll(scroll);
_targetRenderable->setVerticalFov(fov);
}
void TargetBrowserPair::setImageCollectionIsLoaded(bool isLoaded) {
_browser->setImageCollectionIsLoaded(isLoaded);
}
void TargetBrowserPair::applyRoll() {
_targetRenderable->applyRoll();
}
void TargetBrowserPair::incrementallyAnimateToCoordinate() {
// Animate the target before the field of view starts to animate
if (_targetAnimation.isAnimating()) {
aimTargetGalactic(_targetNode->identifier(), _targetAnimation.newValue());
}
else if (!_targetAnimation.isAnimating() && _targetIsAnimating) {
// Set the finished position
aimTargetGalactic(_targetNode->identifier(), _targetAnimation.newValue());
_fovAnimation.start();
_targetIsAnimating = false;
}
if (_fovAnimation.isAnimating()) {
_browser->setVerticalFov(_fovAnimation.newValue());
_targetRenderable->setVerticalFov(_browser->verticalFov());
}
}
void TargetBrowserPair::startFading(float goal, float fadeTime) {
const std::string script = fmt::format(
"openspace.setPropertyValueSingle('Scene.{0}.Renderable.Fade', {2}, {3});"
"openspace.setPropertyValueSingle('ScreenSpace.{1}.Fade', {2}, {3});",
_targetNode->identifier(), _browser->identifier(), goal, fadeTime
);
global::scriptEngine->queueScript(
script,
scripting::ScriptEngine::RemoteScripting::Yes
);
}
void TargetBrowserPair::stopAnimations() {
_fovAnimation.stop();
_targetAnimation.stop();
}
void TargetBrowserPair::startAnimation(glm::dvec3 galacticCoords, double fovEnd) {
SkyBrowserModule* module = global::moduleEngine->module<SkyBrowserModule>();
double fovSpeed = module->browserAnimationSpeed();
// The speed is given degrees /sec
double fovTime = abs(_browser->verticalFov() - fovEnd) / fovSpeed;
// Fov animation
_fovAnimation = skybrowser::Animation(_browser->verticalFov(), fovEnd, fovTime);
// Target animation
glm::dvec3 start = glm::normalize(_targetNode->worldPosition()) *
skybrowser::CelestialSphereRadius;
double targetSpeed = module->targetAnimationSpeed();
double angle = skybrowser::angleBetweenVectors(start, galacticCoords);
_targetAnimation = skybrowser::Animation(start, galacticCoords, angle / targetSpeed);
_targetAnimation.start();
_targetIsAnimating = true;
}
void TargetBrowserPair::centerTargetOnScreen() {
// Get camera direction in celestial spherical coordinates
glm::dvec3 viewDirection = skybrowser::cameraDirectionGalactic();
// Keep the current fov
double currentFov = verticalFov();
startAnimation(viewDirection, currentFov);
}
double TargetBrowserPair::targetRoll() const {
// To remove the lag effect when moving the camera while having a locked
// target, send the locked coordinates to wwt
glm::dvec3 normal = glm::normalize(
_targetNode->worldPosition() -
global::navigationHandler->camera()->positionVec3()
);
glm::dvec3 right = _targetRenderable->rightVector();
glm::dvec3 up = glm::normalize(glm::cross(right, normal));
return skybrowser::targetRoll(up, normal);
}
bool TargetBrowserPair::isFacingCamera() const {
return _browser->isFacingCamera();
}
bool TargetBrowserPair::isUsingRadiusAzimuthElevation() const {
return _browser->isUsingRaeCoords();
}
ScreenSpaceSkyBrowser* TargetBrowserPair::browser() const {
return _browser;
}
} // namespace openspace
<commit_msg>Add target node id to skybrowser topic<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2022 *
* *
* 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 <modules/skybrowser/include/targetbrowserpair.h>
#include <modules/skybrowser/include/renderableskytarget.h>
#include <modules/skybrowser/include/screenspaceskybrowser.h>
#include <modules/skybrowser/include/utility.h>
#include <modules/skybrowser/include/wwtdatahandler.h>
#include <modules/skybrowser/skybrowsermodule.h>
#include <openspace/camera/camera.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/moduleengine.h>
#include <openspace/navigation/navigationhandler.h>
#include <openspace/rendering/screenspacerenderable.h>
#include <openspace/scripting/scriptengine.h>
#include <ghoul/misc/assert.h>
#include <glm/gtc/constants.hpp>
#include <functional>
#include <chrono>
namespace {
void aimTargetGalactic(std::string id, glm::dvec3 direction) {
glm::dvec3 positionCelestial = glm::normalize(direction) *
openspace::skybrowser::CelestialSphereRadius;
std::string script = fmt::format(
"openspace.setPropertyValueSingle('Scene.{}.Translation.Position', {});",
id, ghoul::to_string(positionCelestial)
);
openspace::global::scriptEngine->queueScript(
script,
openspace::scripting::ScriptEngine::RemoteScripting::Yes
);
}
} // namespace
namespace openspace {
TargetBrowserPair::TargetBrowserPair(SceneGraphNode* targetNode,
ScreenSpaceSkyBrowser* browser)
: _browser(browser)
, _targetNode(targetNode)
{
ghoul_assert(browser, "Sky browser is null pointer");
ghoul_assert(targetNode, "Sky target is null pointer");
_targetRenderable = dynamic_cast<RenderableSkyTarget*>(_targetNode->renderable());
}
void TargetBrowserPair::setImageOrder(int i, int order) {
_browser->setImageOrder(i, order);
}
void TargetBrowserPair::startFinetuningTarget() {
_startTargetPosition = _targetNode->worldPosition();
}
// The fine tune of the target is a way to "drag and drop" the target with click
// drag on the sky browser window. This is to be able to drag the target around when it
// has a very small field of view
void TargetBrowserPair::fineTuneTarget(const glm::vec2& translation) {
glm::dvec2 percentage = glm::dvec2(translation);
glm::dvec3 right = _targetRenderable->rightVector() * percentage.x;
glm::dvec3 up = _targetRenderable->upVector() * percentage.y;
glm::dvec3 newPosition = _startTargetPosition - (right - up);
aimTargetGalactic(
_targetNode->identifier(),
newPosition
);
}
void TargetBrowserPair::synchronizeAim() {
if (!_targetAnimation.isAnimating() && _browser->isInitialized()) {
_browser->setEquatorialAim(targetDirectionEquatorial());
_browser->setTargetRoll(targetRoll());
_targetRenderable->setVerticalFov(_browser->verticalFov());
}
}
void TargetBrowserPair::setEnabled(bool enable) {
_browser->setEnabled(enable);
_targetRenderable->property("Enabled")->set(enable);
}
bool TargetBrowserPair::isEnabled() const {
return _targetRenderable->isEnabled() || _browser->isEnabled();
}
void TargetBrowserPair::initialize() {
_targetRenderable->setColor(_browser->borderColor());
glm::vec2 dim = _browser->screenSpaceDimensions();
_targetRenderable->setRatio(dim.x / dim.y);
_browser->updateBorderColor();
_browser->hideChromeInterface();
_browser->setIsInitialized(true);
}
glm::ivec3 TargetBrowserPair::borderColor() const {
return _browser->borderColor();
}
glm::dvec2 TargetBrowserPair::targetDirectionEquatorial() const {
glm::dvec3 cartesian = skybrowser::galacticToEquatorial(
glm::normalize(_targetNode->worldPosition())
);
return skybrowser::cartesianToSpherical(cartesian);
}
glm::dvec3 TargetBrowserPair::targetDirectionGalactic() const {
return glm::normalize(_targetNode->worldPosition());
}
std::string TargetBrowserPair::browserGuiName() const {
return _browser->guiName();
}
std::string TargetBrowserPair::browserId() const {
return _browser->identifier();
}
std::string TargetBrowserPair::targetRenderableId() const {
return _targetRenderable->identifier();
}
std::string TargetBrowserPair::targetNodeId() const {
return _targetNode->identifier();
}
double TargetBrowserPair::verticalFov() const {
return _browser->verticalFov();
}
std::vector<int> TargetBrowserPair::selectedImages() const {
return _browser->selectedImages();
}
ghoul::Dictionary TargetBrowserPair::dataAsDictionary() const {
glm::dvec2 spherical = targetDirectionEquatorial();
glm::dvec3 cartesian = skybrowser::sphericalToCartesian(spherical);
ghoul::Dictionary res;
res.setValue("id", browserId());
res.setValue("targetId", targetNodeId());
res.setValue("name", browserGuiName());
res.setValue("fov", static_cast<double>(verticalFov()));
res.setValue("ra", spherical.x);
res.setValue("dec", spherical.y);
res.setValue("roll", targetRoll());
res.setValue("color", borderColor());
res.setValue("cartesianDirection", cartesian);
res.setValue("ratio", static_cast<double>(_browser->browserRatio()));
res.setValue("isFacingCamera", isFacingCamera());
res.setValue("isUsingRae", isUsingRadiusAzimuthElevation());
res.setValue("selectedImages", selectedImages());
res.setValue("scale", static_cast<double>(_browser->scale()));
res.setValue("opacities", _browser->opacities());
res.setValue("borderRadius", _browser->borderRadius());
std::vector<std::pair<std::string, glm::dvec3>> copies = displayCopies();
std::vector<std::pair<std::string, bool>> showCopies = _browser->showDisplayCopies();
ghoul::Dictionary copiesData;
for (size_t i = 0; i < copies.size(); i++) {
ghoul::Dictionary copy;
copy.setValue("position", copies[i].second);
copy.setValue("show", showCopies[i].second);
copy.setValue("idShowProperty", showCopies[i].first);
copiesData.setValue(copies[i].first, copy);
}
// Set table for the current target
res.setValue("displayCopies", copiesData);
return res;
}
void TargetBrowserPair::selectImage(const ImageData& image, int i) {
// Load image into browser
_browser->selectImage(image.imageUrl, i);
// If the image has coordinates, move the target
if (image.hasCelestialCoords) {
// Animate the target to the image coordinate position
glm::dvec3 galactic = skybrowser::equatorialToGalactic(image.equatorialCartesian);
startAnimation(galactic * skybrowser::CelestialSphereRadius, image.fov);
}
}
void TargetBrowserPair::addImageLayerToWwt(const std::string& url, int i) {
_browser->addImageLayerToWwt(url, i);
}
void TargetBrowserPair::removeSelectedImage(int i) {
_browser->removeSelectedImage(i);
}
void TargetBrowserPair::loadImageCollection(const std::string& collection) {
_browser->loadImageCollection(collection);
}
void TargetBrowserPair::setImageOpacity(int i, float opacity) {
_browser->setImageOpacity(i, opacity);
}
void TargetBrowserPair::hideChromeInterface() {
_browser->hideChromeInterface();
}
void TargetBrowserPair::sendIdToBrowser() const {
_browser->setIdInBrowser();
}
std::vector<std::pair<std::string, glm::dvec3>> TargetBrowserPair::displayCopies() const {
return _browser->displayCopies();
}
void TargetBrowserPair::setVerticalFov(double vfov) {
_browser->setVerticalFov(vfov);
_targetRenderable->setVerticalFov(vfov);
}
void TargetBrowserPair::setEquatorialAim(const glm::dvec2& aim) {
aimTargetGalactic(
_targetNode->identifier(),
skybrowser::equatorialToGalactic(skybrowser::sphericalToCartesian(aim))
);
_browser->setEquatorialAim(aim);
}
void TargetBrowserPair::setBorderColor(const glm::ivec3& color) {
_targetRenderable->setColor(color);
_browser->setBorderColor(color);
}
void TargetBrowserPair::setBorderRadius(double radius) {
_browser->setBorderRadius(radius);
_targetRenderable->setBorderRadius(radius);
}
void TargetBrowserPair::setBrowserRatio(float ratio) {
_browser->setRatio(ratio);
_targetRenderable->setRatio(ratio);
}
void TargetBrowserPair::setVerticalFovWithScroll(float scroll) {
double fov = _browser->setVerticalFovWithScroll(scroll);
_targetRenderable->setVerticalFov(fov);
}
void TargetBrowserPair::setImageCollectionIsLoaded(bool isLoaded) {
_browser->setImageCollectionIsLoaded(isLoaded);
}
void TargetBrowserPair::applyRoll() {
_targetRenderable->applyRoll();
}
void TargetBrowserPair::incrementallyAnimateToCoordinate() {
// Animate the target before the field of view starts to animate
if (_targetAnimation.isAnimating()) {
aimTargetGalactic(_targetNode->identifier(), _targetAnimation.newValue());
}
else if (!_targetAnimation.isAnimating() && _targetIsAnimating) {
// Set the finished position
aimTargetGalactic(_targetNode->identifier(), _targetAnimation.newValue());
_fovAnimation.start();
_targetIsAnimating = false;
}
if (_fovAnimation.isAnimating()) {
_browser->setVerticalFov(_fovAnimation.newValue());
_targetRenderable->setVerticalFov(_browser->verticalFov());
}
}
void TargetBrowserPair::startFading(float goal, float fadeTime) {
const std::string script = fmt::format(
"openspace.setPropertyValueSingle('Scene.{0}.Renderable.Fade', {2}, {3});"
"openspace.setPropertyValueSingle('ScreenSpace.{1}.Fade', {2}, {3});",
_targetNode->identifier(), _browser->identifier(), goal, fadeTime
);
global::scriptEngine->queueScript(
script,
scripting::ScriptEngine::RemoteScripting::Yes
);
}
void TargetBrowserPair::stopAnimations() {
_fovAnimation.stop();
_targetAnimation.stop();
}
void TargetBrowserPair::startAnimation(glm::dvec3 galacticCoords, double fovEnd) {
SkyBrowserModule* module = global::moduleEngine->module<SkyBrowserModule>();
double fovSpeed = module->browserAnimationSpeed();
// The speed is given degrees /sec
double fovTime = abs(_browser->verticalFov() - fovEnd) / fovSpeed;
// Fov animation
_fovAnimation = skybrowser::Animation(_browser->verticalFov(), fovEnd, fovTime);
// Target animation
glm::dvec3 start = glm::normalize(_targetNode->worldPosition()) *
skybrowser::CelestialSphereRadius;
double targetSpeed = module->targetAnimationSpeed();
double angle = skybrowser::angleBetweenVectors(start, galacticCoords);
_targetAnimation = skybrowser::Animation(start, galacticCoords, angle / targetSpeed);
_targetAnimation.start();
_targetIsAnimating = true;
}
void TargetBrowserPair::centerTargetOnScreen() {
// Get camera direction in celestial spherical coordinates
glm::dvec3 viewDirection = skybrowser::cameraDirectionGalactic();
// Keep the current fov
double currentFov = verticalFov();
startAnimation(viewDirection, currentFov);
}
double TargetBrowserPair::targetRoll() const {
// To remove the lag effect when moving the camera while having a locked
// target, send the locked coordinates to wwt
glm::dvec3 normal = glm::normalize(
_targetNode->worldPosition() -
global::navigationHandler->camera()->positionVec3()
);
glm::dvec3 right = _targetRenderable->rightVector();
glm::dvec3 up = glm::normalize(glm::cross(right, normal));
return skybrowser::targetRoll(up, normal);
}
bool TargetBrowserPair::isFacingCamera() const {
return _browser->isFacingCamera();
}
bool TargetBrowserPair::isUsingRadiusAzimuthElevation() const {
return _browser->isUsingRaeCoords();
}
ScreenSpaceSkyBrowser* TargetBrowserPair::browser() const {
return _browser;
}
} // namespace openspace
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <string>
#include <functional>
#include <unordered_map>
#include <list>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <map>
#if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 49
#include <regex>
#endif
#include <vector>
#include <fstream>
#include <future>
#define BUF_SIZE 4096
#define MAX_LISTEN 128
namespace Cappuccino{
namespace Log{
static int LogLevel = 0;
static void debug(std::string msg){
if(LogLevel >= 1){
std::cout << msg << std::endl;
}
}
static void info(std::string msg){
if(LogLevel >= 2){
std::cout << msg << std::endl;
}
}
};
class Request;
class Response;
struct {
int port = 1204;
int sockfd = 0;
int sessionfd = 0;
fd_set mask1fds, mask2fds;
std::shared_ptr<std::string> view_root;
std::shared_ptr<std::string> static_root;
std::map<std::string,
std::function<Response(std::unique_ptr<Request>)>
> routes;
} context;
namespace signal_utils{
void signal_handler(int signal){
close(context.sessionfd);
close(context.sockfd);
exit(0);
}
void signal_handler_child(int SignalName){
while(waitpid(-1,NULL,WNOHANG)>0){}
signal(SIGCHLD, signal_utils::signal_handler_child);
}
void init_signal(){
if(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){
exit(1);
}
if(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){
exit(1);
}
}
}
namespace utils{
std::vector<std::string> split(const std::string& str, std::string delim) noexcept{
std::vector<std::string> result;
std::string::size_type pos = 0;
while(pos != std::string::npos ){
std::string::size_type p = str.find(delim, pos);
if(p == std::string::npos){
result.push_back(str.substr(pos));
break;
}else{
result.push_back(str.substr(pos, p - pos));
}
pos = p + delim.size();
}
return result;
}
};
void init_socket(){
struct sockaddr_in server;
if((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
exit(EXIT_FAILURE);
}
memset( &server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(context.port);
char opt = 1;
setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char));
int temp = 1;
if(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR,
&temp, sizeof(int))){
}
if (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) {
exit(EXIT_FAILURE);
}
if(listen(context.sockfd, MAX_LISTEN) < 0) {
exit(EXIT_FAILURE);
}
FD_ZERO(&context.mask1fds);
FD_SET(context.sockfd, &context.mask1fds);
}
using namespace std;
void option(int argc, char *argv[]) noexcept{
char result;
while((result = getopt(argc,argv,"dp:")) != -1){
switch(result){
case 'd':
Log::LogLevel = 1;
break;
case 'p':
context.port = atoi(optarg);
break;
}
}
}
class Request{
map<string, string> headerset;
map<string, string> paramset;
public:
Request(string method, string url,string protocol):
method(move(method)),
url(move(url)),
protocol(move(protocol))
{}
const string method;
const string url;
const string protocol;
void addHeader(string key,string value){
headerset[key] = move(value);
}
void addParams(string key,string value){
paramset[key] = move(value);
}
string header(string key){
if(headerset.find(key) == headerset.end())
return "INVALID";
return headerset[key];
}
string params(string key){
if(paramset.find(key) == paramset.end())
return "INVALID";
return paramset[key];
}
};
class Response{
int status;
string message;
public:
Response(int st,string msg){
status = st;
message = msg;
}
Response(string msg){
message = msg;
}
operator string(){
return to_string(status) + " / " + message;
}
};
string createResponse(char* req) noexcept{
auto lines = utils::split(string(req), "\n");
if(lines.empty())
return Response(400, "Bad Request");
auto tops = utils::split(lines[0], " ");
if(tops.size() < 3)
return Response(401, "Bad Request");
auto request = unique_ptr<Request>(new Request(tops[0],tops[1],tops[2]));
if(context.routes.find(tops[1]) != context.routes.end()){
return context.routes[tops[1]](move(request));
}
return Response( 404, "Not found");
}
string receiveProcess(int sessionfd){
char buf[BUF_SIZE] = {};
char method[BUF_SIZE] = {};
char url[BUF_SIZE] = {};
char protocol[BUF_SIZE] = {};
if (recv(sessionfd, buf, sizeof(buf), 0) < 0) {
exit(EXIT_FAILURE);
}
do{
if(strstr(buf, "\r\n")){
break;
}
if (strlen(buf) >= sizeof(buf)) {
memset(&buf, 0, sizeof(buf));
}
}while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0);
return createResponse(buf);
}
string openFile(string aFilename){
auto filename = aFilename;
std::ifstream ifs( filename, std::ios::in | std::ios::binary);
if(ifs.fail()){
throw std::runtime_error("No such file or directory \""+ filename +"\"\n");
}
ifs.seekg( 0, std::ios::end);
auto pos = ifs.tellg();
ifs.seekg( 0, std::ios::beg);
std::vector<char> buf(pos);
ifs.read(buf.data(), pos);
return string(buf.begin(), buf.end());;
}
time_t client_info[FD_SETSIZE];
void load(string directory, string filename) noexcept{
if(filename == "." || filename == "..") return;
if(filename!="")
directory += "/" + filename;
DIR* dir = opendir(directory.c_str());
if(dir != NULL){
struct dirent* dent;
dent = readdir(dir);
while(dent!=NULL){
dent = readdir(dir);
if(dent!=NULL)
load(directory, string(dent->d_name));
}
closedir(dir);
}else{
// auto static_file = Cappuccino::FileLoader(directory);
// static_file.preload();
context.routes.insert( make_pair(
directory +"/" + filename,
[directory,filename](std::unique_ptr<Request> request) -> Cappuccino::Response{
return Cappuccino::Response(openFile(directory +"/" + filename));
}
));
}
}
void load_static_files() noexcept{
load(*context.static_root,"");
}
void run(){
context.view_root = make_shared<string>("");
context.static_root = make_shared<string>("public");
init_socket();
signal_utils::init_signal();
load_static_files();
int cd[FD_SETSIZE];
struct sockaddr_in client;
int fd;
struct timeval tv;
for(int i = 0;i < FD_SETSIZE; i++){
cd[i] = 0;
}
while(1) {
tv.tv_sec = 0;
tv.tv_usec = 0;
memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds));
int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv);
if(select_result < 1) {
for(fd = 0; fd < FD_SETSIZE; fd++) {
if(cd[fd] == 1) {
close(fd);
FD_CLR(fd, &context.mask1fds);
cd[fd] = 0;
}
}
continue;
}
for(fd = 0; fd < FD_SETSIZE; fd++){
if(FD_ISSET(fd,&context.mask2fds)) {
if(fd == context.sockfd) {
memset( &client, 0, sizeof(client));
int len = sizeof(client);
int clientfd = accept(context.sockfd, (struct sockaddr *)&client,(socklen_t *) &len);
FD_SET(clientfd, &context.mask1fds);
}else {
if(cd[fd] == 1) {
close(fd);
FD_CLR(fd, &context.mask1fds);
cd[fd] = 0;
} else {
string response = receiveProcess(fd);
write(fd, response.c_str(), receiveProcess(fd).size());
cd[fd] = 1;
}
}
}
}
}
}
void Cappuccino(int argc, char *argv[]) {
option(argc, argv);
}
};
namespace Cocoa{
class App{};
};
<commit_msg>[Add] API file set response.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <string>
#include <functional>
#include <unordered_map>
#include <list>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <map>
#if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 49
#include <regex>
#endif
#include <vector>
#include <fstream>
#include <future>
#define BUF_SIZE 4096
#define MAX_LISTEN 128
namespace Cappuccino{
namespace Log{
static int LogLevel = 0;
static void debug(std::string msg){
if(LogLevel >= 1){
std::cout << msg << std::endl;
}
}
static void info(std::string msg){
if(LogLevel >= 2){
std::cout << msg << std::endl;
}
}
};
class Request;
class Response;
struct {
int port = 1204;
int sockfd = 0;
int sessionfd = 0;
fd_set mask1fds, mask2fds;
std::shared_ptr<std::string> view_root;
std::shared_ptr<std::string> static_root;
std::map<std::string,
std::function<Response(std::unique_ptr<Request>)>
> routes;
} context;
namespace signal_utils{
void signal_handler(int signal){
close(context.sessionfd);
close(context.sockfd);
exit(0);
}
void signal_handler_child(int SignalName){
while(waitpid(-1,NULL,WNOHANG)>0){}
signal(SIGCHLD, signal_utils::signal_handler_child);
}
void init_signal(){
if(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){
exit(1);
}
if(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){
exit(1);
}
}
}
namespace utils{
std::vector<std::string> split(const std::string& str, std::string delim) noexcept{
std::vector<std::string> result;
std::string::size_type pos = 0;
while(pos != std::string::npos ){
std::string::size_type p = str.find(delim, pos);
if(p == std::string::npos){
result.push_back(str.substr(pos));
break;
}else{
result.push_back(str.substr(pos, p - pos));
}
pos = p + delim.size();
}
return result;
}
};
void init_socket(){
struct sockaddr_in server;
if((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
exit(EXIT_FAILURE);
}
memset( &server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(context.port);
char opt = 1;
setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char));
int temp = 1;
if(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR,
&temp, sizeof(int))){
}
if (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) {
exit(EXIT_FAILURE);
}
if(listen(context.sockfd, MAX_LISTEN) < 0) {
exit(EXIT_FAILURE);
}
FD_ZERO(&context.mask1fds);
FD_SET(context.sockfd, &context.mask1fds);
}
using namespace std;
void option(int argc, char *argv[]) noexcept{
char result;
while((result = getopt(argc,argv,"dp:")) != -1){
switch(result){
case 'd':
Log::LogLevel = 1;
break;
case 'p':
context.port = atoi(optarg);
break;
}
}
}
class Request{
map<string, string> headerset;
map<string, string> paramset;
public:
Request(string method, string url,string protocol):
method(move(method)),
url(move(url)),
protocol(move(protocol))
{}
const string method;
const string url;
const string protocol;
void addHeader(string key,string value){
headerset[key] = move(value);
}
void addParams(string key,string value){
paramset[key] = move(value);
}
string header(string key){
if(headerset.find(key) == headerset.end())
return "INVALID";
return headerset[key];
}
string params(string key){
if(paramset.find(key) == paramset.end())
return "INVALID";
return paramset[key];
}
};
class Response{
int status;
string message;
public:
Response(int st,string msg){
status = st;
message = msg;
}
Response(string msg){
message = msg;
}
Response* file(string file){
}
operator string(){
return to_string(status) + " / " + message;
}
};
string createResponse(char* req) noexcept{
auto lines = utils::split(string(req), "\n");
if(lines.empty())
return Response(400, "Bad Request");
auto tops = utils::split(lines[0], " ");
if(tops.size() < 3)
return Response(401, "Bad Request");
auto request = unique_ptr<Request>(new Request(tops[0],tops[1],tops[2]));
if(context.routes.find(tops[1]) != context.routes.end()){
return context.routes[tops[1]](move(request));
}
return Response( 404, "Not found");
}
string receiveProcess(int sessionfd){
char buf[BUF_SIZE] = {};
char method[BUF_SIZE] = {};
char url[BUF_SIZE] = {};
char protocol[BUF_SIZE] = {};
if (recv(sessionfd, buf, sizeof(buf), 0) < 0) {
exit(EXIT_FAILURE);
}
do{
if(strstr(buf, "\r\n")){
break;
}
if (strlen(buf) >= sizeof(buf)) {
memset(&buf, 0, sizeof(buf));
}
}while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0);
return createResponse(buf);
}
string openFile(string aFilename){
auto filename = aFilename;
std::ifstream ifs( filename, std::ios::in | std::ios::binary);
if(ifs.fail()){
throw std::runtime_error("No such file or directory \""+ filename +"\"\n");
}
ifs.seekg( 0, std::ios::end);
auto pos = ifs.tellg();
ifs.seekg( 0, std::ios::beg);
std::vector<char> buf(pos);
ifs.read(buf.data(), pos);
return string(buf.begin(), buf.end());;
}
time_t client_info[FD_SETSIZE];
void load(string directory, string filename) noexcept{
if(filename == "." || filename == "..") return;
if(filename!="")
directory += "/" + filename;
DIR* dir = opendir(directory.c_str());
if(dir != NULL){
struct dirent* dent;
dent = readdir(dir);
while(dent!=NULL){
dent = readdir(dir);
if(dent!=NULL)
load(directory, string(dent->d_name));
}
closedir(dir);
}else{
context.routes.insert( make_pair(
directory +"/" + filename,
[directory,filename](std::unique_ptr<Request> request) -> Cappuccino::Response{
return *Cappuccino::Response(200,"OK").file(openFile(directory +"/" + filename));
}
));
}
}
void load_static_files() noexcept{
load(*context.static_root,"");
}
void run(){
context.view_root = make_shared<string>("");
context.static_root = make_shared<string>("public");
init_socket();
signal_utils::init_signal();
load_static_files();
int cd[FD_SETSIZE];
struct sockaddr_in client;
int fd;
struct timeval tv;
for(int i = 0;i < FD_SETSIZE; i++){
cd[i] = 0;
}
while(1) {
tv.tv_sec = 0;
tv.tv_usec = 0;
memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds));
int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv);
if(select_result < 1) {
for(fd = 0; fd < FD_SETSIZE; fd++) {
if(cd[fd] == 1) {
close(fd);
FD_CLR(fd, &context.mask1fds);
cd[fd] = 0;
}
}
continue;
}
for(fd = 0; fd < FD_SETSIZE; fd++){
if(FD_ISSET(fd,&context.mask2fds)) {
if(fd == context.sockfd) {
memset( &client, 0, sizeof(client));
int len = sizeof(client);
int clientfd = accept(context.sockfd, (struct sockaddr *)&client,(socklen_t *) &len);
FD_SET(clientfd, &context.mask1fds);
}else {
if(cd[fd] == 1) {
close(fd);
FD_CLR(fd, &context.mask1fds);
cd[fd] = 0;
} else {
string response = receiveProcess(fd);
write(fd, response.c_str(), receiveProcess(fd).size());
cd[fd] = 1;
}
}
}
}
}
}
void Cappuccino(int argc, char *argv[]) {
option(argc, argv);
}
};
namespace Cocoa{
class App{};
};
<|endoftext|> |
<commit_before>// Copyright (C) 2011 The Libphonenumber 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.
// Author: Philippe Liard
#include "phonenumbers/stringutil.h"
#include <string>
#include <vector>
#include <gtest/gtest.h>
using std::string;
using std::vector;
namespace i18n {
namespace phonenumbers {
// Test operator+(const string&, int).
TEST(StringUtilTest, OperatorPlus) {
EXPECT_EQ("hello10", string("hello") + 10);
}
// Test SimpleItoa implementation.
TEST(StringUtilTest, SimpleItoa) {
EXPECT_EQ("10", SimpleItoa(10));
}
TEST(StringUtilTest, HasPrefixString) {
EXPECT_TRUE(HasPrefixString("hello world", "hello"));
EXPECT_FALSE(HasPrefixString("hello world", "hellO"));
}
TEST(StringUtilTest, FindNthWithEmptyString) {
EXPECT_EQ(string::npos, FindNth("", 'a', 1));
}
TEST(StringUtilTest, FindNthWithNNegative) {
EXPECT_EQ(string::npos, FindNth("hello world", 'o', -1));
}
TEST(StringUtilTest, FindNthWithNTooHigh) {
EXPECT_EQ(string::npos, FindNth("hello world", 'o', 3));
}
TEST(StringUtilTest, FindNth) {
EXPECT_EQ(7, FindNth("hello world", 'o', 2));
}
TEST(StringUtilTest, SplitStringUsingWithEmptyString) {
vector<string> result;
SplitStringUsing("", ":", &result);
EXPECT_EQ(0, result.size());
}
TEST(StringUtilTest, SplitStringUsingWithEmptyDelimiter) {
vector<string> result;
SplitStringUsing("hello", "", &result);
EXPECT_EQ(0, result.size());
}
TEST(StringUtilTest, SplitStringUsing) {
vector<string> result;
SplitStringUsing(":hello:world:", ":", &result);
EXPECT_EQ(2, result.size());
EXPECT_EQ("hello", result[0]);
EXPECT_EQ("world", result[1]);
}
TEST(StringUtilTest, SplitStringUsingIgnoresEmptyToken) {
vector<string> result;
SplitStringUsing("hello::world", ":", &result);
EXPECT_EQ(2, result.size());
EXPECT_EQ("hello", result[0]);
EXPECT_EQ("world", result[1]);
}
// Test TryStripPrefixString.
TEST(StringUtilTest, TryStripPrefixString) {
string s;
EXPECT_TRUE(TryStripPrefixString("hello world", "hello", &s));
EXPECT_EQ(" world", s);
s.clear();
EXPECT_FALSE(TryStripPrefixString("hello world", "helloa", &s));
s.clear();
EXPECT_TRUE(TryStripPrefixString("hello world", "", &s));
EXPECT_EQ("hello world", s);
s.clear();
EXPECT_FALSE(TryStripPrefixString("", "hello", &s));
s.clear();
}
// Test HasSuffixString.
TEST(StringUtilTest, HasSuffixString) {
EXPECT_TRUE(HasSuffixString("hello world", "hello world"));
EXPECT_TRUE(HasSuffixString("hello world", "world"));
EXPECT_FALSE(HasSuffixString("hello world", "world!"));
EXPECT_TRUE(HasSuffixString("hello world", ""));
EXPECT_FALSE(HasSuffixString("", "hello"));
}
// Test safe_strto32.
TEST(StringUtilTest, safe_strto32) {
int32 n;
safe_strto32("0", &n);
EXPECT_EQ(0, n);
safe_strto32("16", &n);
EXPECT_EQ(16, n);
safe_strto32("2147483647", &n);
EXPECT_EQ(2147483647, n);
safe_strto32("-2147483648", &n);
EXPECT_EQ(-2147483648LL, n);
}
// Test safe_strtou64.
TEST(StringUtilTest, safe_strtou64) {
uint64 n;
safe_strtou64("0", &n);
EXPECT_EQ(0U, n);
safe_strtou64("16", &n);
EXPECT_EQ(16U, n);
safe_strtou64("18446744073709551615UL", &n);
EXPECT_EQ(18446744073709551615ULL, n);
}
// Test strrmm.
TEST(StringUtilTest, strrmm) {
string input("hello");
strrmm(&input, "");
EXPECT_EQ(input, input);
string empty;
strrmm(&empty, "");
EXPECT_EQ("", empty);
strrmm(&empty, "aa");
EXPECT_EQ("", empty);
strrmm(&input, "h");
EXPECT_EQ("ello", input);
strrmm(&input, "el");
EXPECT_EQ("o", input);
}
// Test GlobalReplaceSubstring.
TEST(StringUtilTest, GlobalReplaceSubstring) {
string input("hello");
EXPECT_EQ(0, GlobalReplaceSubstring("aaa", "", &input));
EXPECT_EQ("hello", input);
EXPECT_EQ(0, GlobalReplaceSubstring("", "aaa", &input));
EXPECT_EQ("hello", input);
EXPECT_EQ(0, GlobalReplaceSubstring("", "", &input));
EXPECT_EQ("hello", input);
EXPECT_EQ(0, GlobalReplaceSubstring("aaa", "bbb", &input));
EXPECT_EQ("hello", input);
EXPECT_EQ(1, GlobalReplaceSubstring("o", "o world", &input));
ASSERT_EQ("hello world", input);
EXPECT_EQ(2, GlobalReplaceSubstring("o", "O", &input));
EXPECT_EQ("hellO wOrld", input);
}
// Test the StringHolder class.
TEST(StringUtilTest, StringHolder) {
// Test with C string.
static const char cstring[] = "aaa";
StringHolder sh1(cstring);
EXPECT_EQ(cstring, sh1.GetCString());
EXPECT_EQ(NULL, sh1.GetString());
// Test with std::string.
string s = "bbb";
StringHolder sh2(s);
EXPECT_EQ(NULL, sh2.GetCString());
EXPECT_EQ(&s, sh2.GetString());
// Test GetLength().
string s2 = "hello";
StringHolder sh3(s2);
EXPECT_EQ(5U, sh3.Length());
// Test with uint64.
StringHolder sh4(42);
EXPECT_TRUE(sh4.GetCString() == NULL);
EXPECT_EQ(2U, sh4.Length());
EXPECT_EQ("42", *sh4.GetString());
}
// Test the operator+=(string& lhs, const StringHolder& rhs) implementation.
TEST(StringUtilTest, OperatorPlusEquals) {
// Test with a const char* string to append.
string s = "h";
static const char append1[] = "ello";
s += StringHolder(append1); // force StringHolder usage
EXPECT_EQ("hello", s);
// Test with a std::string to append.
s = "h";
string append2 = "ello";
s += StringHolder(append2); // force StringHolder usage
EXPECT_EQ("hello", s);
}
// Test the StrCat implementations
TEST(StringUtilTest, StrCat) {
string s;
// Test with 2 arguments.
s = StrCat("a", "b");
EXPECT_EQ("ab", s);
// Test with 3 arguments.
s = StrCat("a", "b", "c");
EXPECT_EQ("abc", s);
// Test with 4 arguments.
s = StrCat("a", "b", "c", "d");
EXPECT_EQ("abcd", s);
// Test with 5 arguments.
s = StrCat("a", "b", "c", "d", "e");
EXPECT_EQ("abcde", s);
// Test with 6 arguments.
s = StrCat("a", "b", "c", "d", "e", "f");
EXPECT_EQ("abcdef", s);
// Test with 7 arguments.
s = StrCat("a", "b", "c", "d", "e", "f", "g");
EXPECT_EQ("abcdefg", s);
// Test with 8 arguments.
s = StrCat("a", "b", "c", "d", "e", "f", "g", "h");
EXPECT_EQ("abcdefgh", s);
// Test with 9 arguments.
s = StrCat("a", "b", "c", "d", "e", "f", "g", "h", "i");
EXPECT_EQ("abcdefghi", s);
// Test with 11 arguments.
s = StrCat("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
EXPECT_EQ("abcdefghijk", s);
}
// Test the StrAppend implementations.
TEST(StringUtilTest, StrAppend) {
string s;
// Test with 1 argument.
StrAppend(&s, "a");
ASSERT_EQ("a", s);
// Test with 2 arguments.
StrAppend(&s, "b", "c");
ASSERT_EQ("abc", s);
// Test with 3 arguments.
StrAppend(&s, "d", "e", "f");
ASSERT_EQ("abcdef", s);
// Test with 4 arguments.
StrAppend(&s, "g", "h", "i", "j");
ASSERT_EQ("abcdefghij", s);
// Test with 5 arguments.
StrAppend(&s, "k", "l", "m", "n", "o");
ASSERT_EQ("abcdefghijklmno", s);
// Test with int argument.
StrAppend(&s, 42);
ASSERT_EQ("abcdefghijklmno42", s);
}
} // namespace phonenumbers
} // namespace i18n
<commit_msg>CPP: Fix stringutil_test literal types<commit_after>// Copyright (C) 2011 The Libphonenumber 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.
// Author: Philippe Liard
#include "phonenumbers/stringutil.h"
#include <string>
#include <vector>
#include <gtest/gtest.h>
using std::string;
using std::vector;
namespace i18n {
namespace phonenumbers {
// Test operator+(const string&, int).
TEST(StringUtilTest, OperatorPlus) {
EXPECT_EQ("hello10", string("hello") + 10);
}
// Test SimpleItoa implementation.
TEST(StringUtilTest, SimpleItoa) {
EXPECT_EQ("10", SimpleItoa(10));
}
TEST(StringUtilTest, HasPrefixString) {
EXPECT_TRUE(HasPrefixString("hello world", "hello"));
EXPECT_FALSE(HasPrefixString("hello world", "hellO"));
}
TEST(StringUtilTest, FindNthWithEmptyString) {
EXPECT_EQ(string::npos, FindNth("", 'a', 1));
}
TEST(StringUtilTest, FindNthWithNNegative) {
EXPECT_EQ(string::npos, FindNth("hello world", 'o', -1));
}
TEST(StringUtilTest, FindNthWithNTooHigh) {
EXPECT_EQ(string::npos, FindNth("hello world", 'o', 3));
}
TEST(StringUtilTest, FindNth) {
EXPECT_EQ(7U, FindNth("hello world", 'o', 2));
}
TEST(StringUtilTest, SplitStringUsingWithEmptyString) {
vector<string> result;
SplitStringUsing("", ":", &result);
EXPECT_EQ(0U, result.size());
}
TEST(StringUtilTest, SplitStringUsingWithEmptyDelimiter) {
vector<string> result;
SplitStringUsing("hello", "", &result);
EXPECT_EQ(0U, result.size());
}
TEST(StringUtilTest, SplitStringUsing) {
vector<string> result;
SplitStringUsing(":hello:world:", ":", &result);
EXPECT_EQ(2U, result.size());
EXPECT_EQ("hello", result[0]);
EXPECT_EQ("world", result[1]);
}
TEST(StringUtilTest, SplitStringUsingIgnoresEmptyToken) {
vector<string> result;
SplitStringUsing("hello::world", ":", &result);
EXPECT_EQ(2U, result.size());
EXPECT_EQ("hello", result[0]);
EXPECT_EQ("world", result[1]);
}
// Test TryStripPrefixString.
TEST(StringUtilTest, TryStripPrefixString) {
string s;
EXPECT_TRUE(TryStripPrefixString("hello world", "hello", &s));
EXPECT_EQ(" world", s);
s.clear();
EXPECT_FALSE(TryStripPrefixString("hello world", "helloa", &s));
s.clear();
EXPECT_TRUE(TryStripPrefixString("hello world", "", &s));
EXPECT_EQ("hello world", s);
s.clear();
EXPECT_FALSE(TryStripPrefixString("", "hello", &s));
s.clear();
}
// Test HasSuffixString.
TEST(StringUtilTest, HasSuffixString) {
EXPECT_TRUE(HasSuffixString("hello world", "hello world"));
EXPECT_TRUE(HasSuffixString("hello world", "world"));
EXPECT_FALSE(HasSuffixString("hello world", "world!"));
EXPECT_TRUE(HasSuffixString("hello world", ""));
EXPECT_FALSE(HasSuffixString("", "hello"));
}
// Test safe_strto32.
TEST(StringUtilTest, safe_strto32) {
int32 n;
safe_strto32("0", &n);
EXPECT_EQ(0, n);
safe_strto32("16", &n);
EXPECT_EQ(16, n);
safe_strto32("2147483647", &n);
EXPECT_EQ(2147483647, n);
safe_strto32("-2147483648", &n);
EXPECT_EQ(-2147483648LL, n);
}
// Test safe_strtou64.
TEST(StringUtilTest, safe_strtou64) {
uint64 n;
safe_strtou64("0", &n);
EXPECT_EQ(0U, n);
safe_strtou64("16", &n);
EXPECT_EQ(16U, n);
safe_strtou64("18446744073709551615UL", &n);
EXPECT_EQ(18446744073709551615ULL, n);
}
// Test strrmm.
TEST(StringUtilTest, strrmm) {
string input("hello");
strrmm(&input, "");
EXPECT_EQ(input, input);
string empty;
strrmm(&empty, "");
EXPECT_EQ("", empty);
strrmm(&empty, "aa");
EXPECT_EQ("", empty);
strrmm(&input, "h");
EXPECT_EQ("ello", input);
strrmm(&input, "el");
EXPECT_EQ("o", input);
}
// Test GlobalReplaceSubstring.
TEST(StringUtilTest, GlobalReplaceSubstring) {
string input("hello");
EXPECT_EQ(0, GlobalReplaceSubstring("aaa", "", &input));
EXPECT_EQ("hello", input);
EXPECT_EQ(0, GlobalReplaceSubstring("", "aaa", &input));
EXPECT_EQ("hello", input);
EXPECT_EQ(0, GlobalReplaceSubstring("", "", &input));
EXPECT_EQ("hello", input);
EXPECT_EQ(0, GlobalReplaceSubstring("aaa", "bbb", &input));
EXPECT_EQ("hello", input);
EXPECT_EQ(1, GlobalReplaceSubstring("o", "o world", &input));
ASSERT_EQ("hello world", input);
EXPECT_EQ(2, GlobalReplaceSubstring("o", "O", &input));
EXPECT_EQ("hellO wOrld", input);
}
// Test the StringHolder class.
TEST(StringUtilTest, StringHolder) {
// Test with C string.
static const char cstring[] = "aaa";
StringHolder sh1(cstring);
EXPECT_EQ(cstring, sh1.GetCString());
EXPECT_EQ(NULL, sh1.GetString());
// Test with std::string.
string s = "bbb";
StringHolder sh2(s);
EXPECT_EQ(NULL, sh2.GetCString());
EXPECT_EQ(&s, sh2.GetString());
// Test GetLength().
string s2 = "hello";
StringHolder sh3(s2);
EXPECT_EQ(5U, sh3.Length());
// Test with uint64.
StringHolder sh4(42);
EXPECT_TRUE(sh4.GetCString() == NULL);
EXPECT_EQ(2U, sh4.Length());
EXPECT_EQ("42", *sh4.GetString());
}
// Test the operator+=(string& lhs, const StringHolder& rhs) implementation.
TEST(StringUtilTest, OperatorPlusEquals) {
// Test with a const char* string to append.
string s = "h";
static const char append1[] = "ello";
s += StringHolder(append1); // force StringHolder usage
EXPECT_EQ("hello", s);
// Test with a std::string to append.
s = "h";
string append2 = "ello";
s += StringHolder(append2); // force StringHolder usage
EXPECT_EQ("hello", s);
}
// Test the StrCat implementations
TEST(StringUtilTest, StrCat) {
string s;
// Test with 2 arguments.
s = StrCat("a", "b");
EXPECT_EQ("ab", s);
// Test with 3 arguments.
s = StrCat("a", "b", "c");
EXPECT_EQ("abc", s);
// Test with 4 arguments.
s = StrCat("a", "b", "c", "d");
EXPECT_EQ("abcd", s);
// Test with 5 arguments.
s = StrCat("a", "b", "c", "d", "e");
EXPECT_EQ("abcde", s);
// Test with 6 arguments.
s = StrCat("a", "b", "c", "d", "e", "f");
EXPECT_EQ("abcdef", s);
// Test with 7 arguments.
s = StrCat("a", "b", "c", "d", "e", "f", "g");
EXPECT_EQ("abcdefg", s);
// Test with 8 arguments.
s = StrCat("a", "b", "c", "d", "e", "f", "g", "h");
EXPECT_EQ("abcdefgh", s);
// Test with 9 arguments.
s = StrCat("a", "b", "c", "d", "e", "f", "g", "h", "i");
EXPECT_EQ("abcdefghi", s);
// Test with 11 arguments.
s = StrCat("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
EXPECT_EQ("abcdefghijk", s);
}
// Test the StrAppend implementations.
TEST(StringUtilTest, StrAppend) {
string s;
// Test with 1 argument.
StrAppend(&s, "a");
ASSERT_EQ("a", s);
// Test with 2 arguments.
StrAppend(&s, "b", "c");
ASSERT_EQ("abc", s);
// Test with 3 arguments.
StrAppend(&s, "d", "e", "f");
ASSERT_EQ("abcdef", s);
// Test with 4 arguments.
StrAppend(&s, "g", "h", "i", "j");
ASSERT_EQ("abcdefghij", s);
// Test with 5 arguments.
StrAppend(&s, "k", "l", "m", "n", "o");
ASSERT_EQ("abcdefghijklmno", s);
// Test with int argument.
StrAppend(&s, 42);
ASSERT_EQ("abcdefghijklmno42", s);
}
} // namespace phonenumbers
} // namespace i18n
<|endoftext|> |
<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "precomp.hpp"
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <android/log.h>
#include "media/NdkMediaCodec.h"
#include "media/NdkMediaExtractor.h"
#define INPUT_TIMEOUT_MS 2000
#define COLOR_FormatYUV420Planar 19
#define COLOR_FormatYUV420SemiPlanar 21
using namespace cv;
#define TAG "NativeCodec"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
static inline void deleter_AMediaExtractor(AMediaExtractor *extractor) {
AMediaExtractor_delete(extractor);
}
static inline void deleter_AMediaCodec(AMediaCodec *codec) {
AMediaCodec_stop(codec);
AMediaCodec_delete(codec);
}
static inline void deleter_AMediaFormat(AMediaFormat *format) {
AMediaFormat_delete(format);
}
class AndroidMediaNdkCapture : public IVideoCapture
{
public:
AndroidMediaNdkCapture():
sawInputEOS(false), sawOutputEOS(false),
frameWidth(0), frameHeight(0), colorFormat(0) {}
std::shared_ptr<AMediaExtractor> mediaExtractor;
std::shared_ptr<AMediaCodec> mediaCodec;
bool sawInputEOS;
bool sawOutputEOS;
int32_t frameWidth;
int32_t frameHeight;
int32_t colorFormat;
std::vector<uint8_t> buffer;
~AndroidMediaNdkCapture() { cleanUp(); }
bool decodeFrame() {
while (!sawInputEOS || !sawOutputEOS) {
if (!sawInputEOS) {
auto bufferIndex = AMediaCodec_dequeueInputBuffer(mediaCodec.get(), INPUT_TIMEOUT_MS);
LOGV("input buffer %zd", bufferIndex);
if (bufferIndex >= 0) {
size_t bufferSize;
auto inputBuffer = AMediaCodec_getInputBuffer(mediaCodec.get(), bufferIndex, &bufferSize);
auto sampleSize = AMediaExtractor_readSampleData(mediaExtractor.get(), inputBuffer, bufferSize);
if (sampleSize < 0) {
sampleSize = 0;
sawInputEOS = true;
LOGV("EOS");
}
auto presentationTimeUs = AMediaExtractor_getSampleTime(mediaExtractor.get());
AMediaCodec_queueInputBuffer(mediaCodec.get(), bufferIndex, 0, sampleSize,
presentationTimeUs, sawInputEOS ? AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM : 0);
AMediaExtractor_advance(mediaExtractor.get());
}
}
if (!sawOutputEOS) {
AMediaCodecBufferInfo info;
auto bufferIndex = AMediaCodec_dequeueOutputBuffer(mediaCodec.get(), &info, 0);
if (bufferIndex >= 0) {
size_t bufferSize = 0;
auto mediaFormat = std::shared_ptr<AMediaFormat>(AMediaCodec_getOutputFormat(mediaCodec.get()), deleter_AMediaFormat);
AMediaFormat_getInt32(mediaFormat.get(), AMEDIAFORMAT_KEY_WIDTH, &frameWidth);
AMediaFormat_getInt32(mediaFormat.get(), AMEDIAFORMAT_KEY_HEIGHT, &frameHeight);
AMediaFormat_getInt32(mediaFormat.get(), AMEDIAFORMAT_KEY_COLOR_FORMAT, &colorFormat);
uint8_t* codecBuffer = AMediaCodec_getOutputBuffer(mediaCodec.get(), bufferIndex, &bufferSize);
buffer = std::vector<uint8_t>(codecBuffer, codecBuffer + bufferSize);
LOGV("colorFormat: %d", colorFormat);
LOGV("buffer size: %zu", bufferSize);
LOGV("width (frame): %d", frameWidth);
LOGV("height (frame): %d", frameHeight);
if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM)
{
LOGV("output EOS");
sawOutputEOS = true;
}
if ((size_t)frameWidth * frameHeight * 3 / 2 > bufferSize)
{
if (bufferSize == 3110400 && frameWidth == 1920 && frameHeight == 1088)
{
frameHeight = 1080;
LOGV("Buffer size is too small, force using height = %d", frameHeight);
}
else if(bufferSize == 3110400 && frameWidth == 1088 && frameHeight == 1920)
{
frameWidth = 1080;
LOGV("Buffer size is too small, force using width = %d", frameWidth);
}
else
{
LOGE("Buffer size is too small. Frame is ignored. Enable verbose logging to see actual values of parameters");
return false;
}
}
AMediaCodec_releaseOutputBuffer(mediaCodec.get(), bufferIndex, info.size != 0);
return true;
} else if (bufferIndex == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
LOGV("output buffers changed");
} else if (bufferIndex == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
auto format = AMediaCodec_getOutputFormat(mediaCodec.get());
LOGV("format changed to: %s", AMediaFormat_toString(format));
AMediaFormat_delete(format);
} else if (bufferIndex == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
LOGV("no output buffer right now");
} else {
LOGV("unexpected info code: %zd", bufferIndex);
}
}
}
return false;
}
bool isOpened() const CV_OVERRIDE { return mediaCodec.get() != nullptr; }
int getCaptureDomain() CV_OVERRIDE { return CAP_ANDROID; }
bool grabFrame() CV_OVERRIDE
{
// clear the previous frame
buffer.clear();
return decodeFrame();
}
bool retrieveFrame(int, OutputArray out) CV_OVERRIDE
{
if (buffer.empty()) {
return false;
}
Mat yuv(frameHeight + frameHeight/2, frameWidth, CV_8UC1, buffer.data());
if (colorFormat == COLOR_FormatYUV420Planar) {
cv::cvtColor(yuv, out, cv::COLOR_YUV2BGR_YV12);
} else if (colorFormat == COLOR_FormatYUV420SemiPlanar) {
cv::cvtColor(yuv, out, cv::COLOR_YUV2BGR_NV21);
} else {
LOGE("Unsupported video format: %d", colorFormat);
return false;
}
return true;
}
double getProperty(int property_id) const CV_OVERRIDE
{
switch (property_id)
{
case CV_CAP_PROP_FRAME_WIDTH: return frameWidth;
case CV_CAP_PROP_FRAME_HEIGHT: return frameHeight;
}
return 0;
}
bool setProperty(int /* property_id */, double /* value */) CV_OVERRIDE
{
return false;
}
bool initCapture(const char * filename)
{
struct stat statBuffer;
if (stat(filename, &statBuffer) != 0) {
LOGE("failed to stat file: %s (%s)", filename, strerror(errno));
return false;
}
int fd = open(filename, O_RDONLY);
if (fd < 0) {
LOGE("failed to open file: %s %d (%s)", filename, fd, strerror(errno));
return false;
}
mediaExtractor = std::shared_ptr<AMediaExtractor>(AMediaExtractor_new(), deleter_AMediaExtractor);
if (!mediaExtractor) {
return false;
}
media_status_t err = AMediaExtractor_setDataSourceFd(mediaExtractor.get(), fd, 0, statBuffer.st_size);
close(fd);
if (err != AMEDIA_OK) {
LOGV("setDataSource error: %d", err);
return false;
}
int numtracks = AMediaExtractor_getTrackCount(mediaExtractor.get());
LOGV("input has %d tracks", numtracks);
for (int i = 0; i < numtracks; i++) {
auto format = std::shared_ptr<AMediaFormat>(AMediaExtractor_getTrackFormat(mediaExtractor.get(), i), deleter_AMediaFormat);
if (!format) {
continue;
}
const char *s = AMediaFormat_toString(format.get());
LOGV("track %d format: %s", i, s);
const char *mime;
if (!AMediaFormat_getString(format.get(), AMEDIAFORMAT_KEY_MIME, &mime)) {
LOGV("no mime type");
} else if (!strncmp(mime, "video/", 6)) {
int32_t trackWidth, trackHeight;
AMediaFormat_getInt32(format.get(), AMEDIAFORMAT_KEY_WIDTH, &trackWidth);
AMediaFormat_getInt32(format.get(), AMEDIAFORMAT_KEY_HEIGHT, &trackHeight);
LOGV("width (track): %d", trackWidth);
LOGV("height (track): %d", trackHeight);
if (AMediaExtractor_selectTrack(mediaExtractor.get(), i) != AMEDIA_OK) {
continue;
}
mediaCodec = std::shared_ptr<AMediaCodec>(AMediaCodec_createDecoderByType(mime), deleter_AMediaCodec);
if (!mediaCodec) {
continue;
}
if (AMediaCodec_configure(mediaCodec.get(), format.get(), NULL, NULL, 0) != AMEDIA_OK) {
continue;
}
sawInputEOS = false;
sawOutputEOS = false;
if (AMediaCodec_start(mediaCodec.get()) != AMEDIA_OK) {
continue;
}
return true;
}
}
return false;
}
void cleanUp() {
sawInputEOS = true;
sawOutputEOS = true;
frameWidth = 0;
frameHeight = 0;
colorFormat = 0;
}
};
/****************** Implementation of interface functions ********************/
Ptr<IVideoCapture> cv::createAndroidCapture_file(const std::string &filename) {
Ptr<AndroidMediaNdkCapture> res = makePtr<AndroidMediaNdkCapture>();
if (res && res->initCapture(filename.c_str()))
return res;
return Ptr<IVideoCapture>();
}
<commit_msg>#22214 and #22198<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "precomp.hpp"
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <android/log.h>
#include "media/NdkMediaCodec.h"
#include "media/NdkMediaExtractor.h"
#define INPUT_TIMEOUT_MS 2000
#define COLOR_FormatYUV420Planar 19
#define COLOR_FormatYUV420SemiPlanar 21
using namespace cv;
#define TAG "NativeCodec"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
static inline void deleter_AMediaExtractor(AMediaExtractor *extractor) {
AMediaExtractor_delete(extractor);
}
static inline void deleter_AMediaCodec(AMediaCodec *codec) {
AMediaCodec_stop(codec);
AMediaCodec_delete(codec);
}
static inline void deleter_AMediaFormat(AMediaFormat *format) {
AMediaFormat_delete(format);
}
class AndroidMediaNdkCapture : public IVideoCapture
{
public:
AndroidMediaNdkCapture():
sawInputEOS(false), sawOutputEOS(false),
frameStride(0), frameWidth(0), frameHeight(0), colorFormat(0),
videoWidth(0), videoHeight(0),
videoFrameCount(0),
videoRotation(0), videoRotationCode(-1),
videoOrientationAuto(false) {}
std::shared_ptr<AMediaExtractor> mediaExtractor;
std::shared_ptr<AMediaCodec> mediaCodec;
bool sawInputEOS;
bool sawOutputEOS;
int32_t frameStride;
int32_t frameWidth;
int32_t frameHeight;
int32_t colorFormat;
int32_t videoWidth;
int32_t videoHeight;
float videoFrameRate;
int32_t videoFrameCount;
int32_t videoRotation;
int32_t videoRotationCode;
bool videoOrientationAuto;
std::vector<uint8_t> buffer;
Mat frame;
~AndroidMediaNdkCapture() { cleanUp(); }
bool decodeFrame() {
while (!sawInputEOS || !sawOutputEOS) {
if (!sawInputEOS) {
auto bufferIndex = AMediaCodec_dequeueInputBuffer(mediaCodec.get(), INPUT_TIMEOUT_MS);
LOGV("input buffer %zd", bufferIndex);
if (bufferIndex >= 0) {
size_t bufferSize;
auto inputBuffer = AMediaCodec_getInputBuffer(mediaCodec.get(), bufferIndex, &bufferSize);
auto sampleSize = AMediaExtractor_readSampleData(mediaExtractor.get(), inputBuffer, bufferSize);
if (sampleSize < 0) {
sampleSize = 0;
sawInputEOS = true;
LOGV("EOS");
}
auto presentationTimeUs = AMediaExtractor_getSampleTime(mediaExtractor.get());
AMediaCodec_queueInputBuffer(mediaCodec.get(), bufferIndex, 0, sampleSize,
presentationTimeUs, sawInputEOS ? AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM : 0);
AMediaExtractor_advance(mediaExtractor.get());
}
}
if (!sawOutputEOS) {
AMediaCodecBufferInfo info;
auto bufferIndex = AMediaCodec_dequeueOutputBuffer(mediaCodec.get(), &info, 0);
if (bufferIndex >= 0) {
size_t bufferSize = 0;
auto mediaFormat = std::shared_ptr<AMediaFormat>(AMediaCodec_getOutputFormat(mediaCodec.get()), deleter_AMediaFormat);
AMediaFormat_getInt32(mediaFormat.get(), AMEDIAFORMAT_KEY_WIDTH, &frameWidth);
AMediaFormat_getInt32(mediaFormat.get(), AMEDIAFORMAT_KEY_STRIDE, &frameStride);
AMediaFormat_getInt32(mediaFormat.get(), AMEDIAFORMAT_KEY_HEIGHT, &frameHeight);
AMediaFormat_getInt32(mediaFormat.get(), AMEDIAFORMAT_KEY_COLOR_FORMAT, &colorFormat);
uint8_t* codecBuffer = AMediaCodec_getOutputBuffer(mediaCodec.get(), bufferIndex, &bufferSize);
buffer = std::vector<uint8_t>(codecBuffer, codecBuffer + bufferSize);
LOGV("colorFormat: %d", colorFormat);
LOGV("buffer size: %zu", bufferSize);
LOGV("width (frame): %d", frameWidth);
LOGV("stride (frame): %d", frameStride);
LOGV("height (frame): %d", frameHeight);
if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM)
{
LOGV("output EOS");
sawOutputEOS = true;
}
AMediaCodec_releaseOutputBuffer(mediaCodec.get(), bufferIndex, info.size != 0);
return true;
} else if (bufferIndex == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
LOGV("output buffers changed");
} else if (bufferIndex == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
auto format = AMediaCodec_getOutputFormat(mediaCodec.get());
LOGV("format changed to: %s", AMediaFormat_toString(format));
AMediaFormat_delete(format);
} else if (bufferIndex == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
LOGV("no output buffer right now");
} else {
LOGV("unexpected info code: %zd", bufferIndex);
}
}
}
return false;
}
bool isOpened() const CV_OVERRIDE { return mediaCodec.get() != nullptr; }
int getCaptureDomain() CV_OVERRIDE { return CAP_ANDROID; }
bool grabFrame() CV_OVERRIDE
{
// clear the previous frame
buffer.clear();
return decodeFrame();
}
bool retrieveFrame(int, OutputArray out) CV_OVERRIDE
{
if (buffer.empty()) {
return false;
}
Mat yuv(frameHeight + frameHeight/2, frameStride, CV_8UC1, buffer.data());
if (colorFormat == COLOR_FormatYUV420Planar) {
cv::cvtColor(yuv, frame, cv::COLOR_YUV2BGR_YV12);
} else if (colorFormat == COLOR_FormatYUV420SemiPlanar) {
cv::cvtColor(yuv, frame, cv::COLOR_YUV2BGR_NV21);
} else {
LOGE("Unsupported video format: %d", colorFormat);
return false;
}
Mat croppedFrame = frame(Rect(0, 0, videoWidth, videoHeight));
out.assign(croppedFrame);
if (videoOrientationAuto && -1 != videoRotationCode) {
cv::rotate(out, out, videoRotationCode);
}
return true;
}
double getProperty(int property_id) const CV_OVERRIDE
{
switch (property_id)
{
case CV_CAP_PROP_FRAME_WIDTH:
return (( videoOrientationAuto &&
(cv::ROTATE_90_CLOCKWISE == videoRotationCode || cv::ROTATE_90_COUNTERCLOCKWISE == videoRotationCode))
? videoHeight : videoWidth);
case CV_CAP_PROP_FRAME_HEIGHT:
return (( videoOrientationAuto &&
(cv::ROTATE_90_CLOCKWISE == videoRotationCode || cv::ROTATE_90_COUNTERCLOCKWISE == videoRotationCode))
? videoWidth : videoHeight);
case CV_CAP_PROP_FPS: return videoFrameRate;
case CV_CAP_PROP_FRAME_COUNT: return videoFrameCount;
case CAP_PROP_ORIENTATION_META: return videoRotation;
case CAP_PROP_ORIENTATION_AUTO: return videoOrientationAuto ? 1 : 0;
}
return 0;
}
bool setProperty(int property_id, double value) CV_OVERRIDE
{
switch (property_id)
{
case CAP_PROP_ORIENTATION_AUTO: {
videoOrientationAuto = value != 0 ? true : false;
return true;
}
}
return false;
}
bool initCapture(const char * filename)
{
struct stat statBuffer;
if (stat(filename, &statBuffer) != 0) {
LOGE("failed to stat file: %s (%s)", filename, strerror(errno));
return false;
}
int fd = open(filename, O_RDONLY);
if (fd < 0) {
LOGE("failed to open file: %s %d (%s)", filename, fd, strerror(errno));
return false;
}
mediaExtractor = std::shared_ptr<AMediaExtractor>(AMediaExtractor_new(), deleter_AMediaExtractor);
if (!mediaExtractor) {
return false;
}
media_status_t err = AMediaExtractor_setDataSourceFd(mediaExtractor.get(), fd, 0, statBuffer.st_size);
close(fd);
if (err != AMEDIA_OK) {
LOGV("setDataSource error: %d", err);
return false;
}
int numtracks = AMediaExtractor_getTrackCount(mediaExtractor.get());
LOGV("input has %d tracks", numtracks);
for (int i = 0; i < numtracks; i++) {
auto format = std::shared_ptr<AMediaFormat>(AMediaExtractor_getTrackFormat(mediaExtractor.get(), i), deleter_AMediaFormat);
if (!format) {
continue;
}
const char *s = AMediaFormat_toString(format.get());
LOGV("track %d format: %s", i, s);
const char *mime;
if (!AMediaFormat_getString(format.get(), AMEDIAFORMAT_KEY_MIME, &mime)) {
LOGV("no mime type");
} else if (!strncmp(mime, "video/", 6)) {
int32_t trackWidth, trackHeight, fps, frameCount = 0, rotation = 0;
AMediaFormat_getInt32(format.get(), AMEDIAFORMAT_KEY_WIDTH, &trackWidth);
AMediaFormat_getInt32(format.get(), AMEDIAFORMAT_KEY_HEIGHT, &trackHeight);
AMediaFormat_getInt32(format.get(), AMEDIAFORMAT_KEY_FRAME_RATE, &fps);
#if __ANDROID_API__ >= 28
AMediaFormat_getInt32(format.get(), AMEDIAFORMAT_KEY_ROTATION, &rotation);
LOGV("rotation (track): %d", rotation);
#endif
#if __ANDROID_API__ >= 29
AMediaFormat_getInt32(format.get(), AMEDIAFORMAT_KEY_FRAME_COUNT, &frameCount);
#endif
LOGV("width (track): %d", trackWidth);
LOGV("height (track): %d", trackHeight);
if (AMediaExtractor_selectTrack(mediaExtractor.get(), i) != AMEDIA_OK) {
continue;
}
mediaCodec = std::shared_ptr<AMediaCodec>(AMediaCodec_createDecoderByType(mime), deleter_AMediaCodec);
if (!mediaCodec) {
continue;
}
if (AMediaCodec_configure(mediaCodec.get(), format.get(), NULL, NULL, 0) != AMEDIA_OK) {
continue;
}
sawInputEOS = false;
sawOutputEOS = false;
if (AMediaCodec_start(mediaCodec.get()) != AMEDIA_OK) {
continue;
}
videoWidth = trackWidth;
videoHeight = trackHeight;
videoFrameRate = fps;
videoFrameCount = frameCount;
videoRotation = rotation;
switch(videoRotation) {
case 90:
videoRotationCode = cv::ROTATE_90_CLOCKWISE;
break;
case 180:
videoRotationCode = cv::ROTATE_180;
break;
case 270:
videoRotationCode = cv::ROTATE_90_COUNTERCLOCKWISE;
break;
default:
videoRotationCode = -1;
break;
}
return true;
}
}
return false;
}
void cleanUp() {
sawInputEOS = true;
sawOutputEOS = true;
frameStride = 0;
frameWidth = 0;
frameHeight = 0;
colorFormat = 0;
videoWidth = 0;
videoHeight = 0;
videoFrameRate = 0;
videoFrameCount = 0;
videoRotation = 0;
videoRotationCode = -1;
}
};
/****************** Implementation of interface functions ********************/
Ptr<IVideoCapture> cv::createAndroidCapture_file(const std::string &filename) {
Ptr<AndroidMediaNdkCapture> res = makePtr<AndroidMediaNdkCapture>();
if (res && res->initCapture(filename.c_str()))
return res;
return Ptr<IVideoCapture>();
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE EventCategorizerToolsTests
#include <boost/test/unit_test.hpp>
#include "EventCategorizerTools.h"
#include "JPetHit/JPetHit.h"
BOOST_AUTO_TEST_SUITE(TOFSuite)
BOOST_AUTO_TEST_CASE(checkHitOrder)
{
JPetHit firstHit;
firstHit.setTime(500.0);
JPetHit secondHit;
secondHit.setTime(100);
double tof = EventCategorizerTools::calculateTOF(firstHit, secondHit);
BOOST_REQUIRE_CLOSE( tof, 9999, 0.100);
}
BOOST_AUTO_TEST_CASE(checkTOFsignNegative)
{
JPetHit firstHit;
firstHit.setTime(100);
JPetBarrelSlot firstSlot(1, true, "first", 10, 1);
firstHit.setBarrelSlot( firstSlot );
JPetHit secondHit;
secondHit.setTime(500);
JPetBarrelSlot secondSlot(2, true, "second", 30, 2);
secondHit.setBarrelSlot(secondSlot);
double tof = EventCategorizerTools::calculateTOF(firstHit, secondHit);
BOOST_REQUIRE_LT( tof, 0 );
}
BOOST_AUTO_TEST_CASE(checkTOFsignPositive)
{
JPetHit firstHit;
firstHit.setTime(100);
JPetBarrelSlot firstSlot(1, true, "first", 30, 1);
firstHit.setBarrelSlot( firstSlot );
JPetHit secondHit;
secondHit.setTime(500);
JPetBarrelSlot secondSlot(2, true, "second", 10, 2);
secondHit.setBarrelSlot(secondSlot);
double tof = EventCategorizerTools::calculateTOF(firstHit, secondHit);
BOOST_REQUIRE_GT( tof, 0 );
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(AnnihilationPointSuite )
BOOST_AUTO_TEST_CASE(pointAtCenter)
{
JPetHit firstHit;
firstHit.setTime(300);
firstHit.setPos(5,5,0);
JPetBarrelSlot firstSlot(1, true, "first", 45, 1);
firstHit.setBarrelSlot( firstSlot );
JPetHit secondHit;
secondHit.setTime(300);
secondHit.setPos(-5,-5,0);
JPetBarrelSlot secondSlot(2, true, "second", 225, 2);
secondHit.setBarrelSlot(secondSlot);
Point3D point = EventCategorizerTools::calculateAnnihilationPoint(firstHit, secondHit);
BOOST_REQUIRE_CLOSE(point.x, 0, 0.001);
BOOST_REQUIRE_CLOSE(point.y, 0, 0.001);
BOOST_REQUIRE_CLOSE(point.z, 0, 0.001);
}
BOOST_AUTO_TEST_CASE(pointAt0x_5y_0z)
{
JPetHit firstHit;
firstHit.setTime(1333/2.0);
firstHit.setPos(0,45,0);
JPetBarrelSlot firstSlot(1, true, "first", 90, 1);
firstHit.setBarrelSlot( firstSlot );
JPetHit secondHit;
secondHit.setTime(1667/2);
secondHit.setPos(0,-45,0);
JPetBarrelSlot secondSlot(2, true, "second", 270, 2);
secondHit.setBarrelSlot(secondSlot);
Point3D point = EventCategorizerTools::calculateAnnihilationPoint(firstHit, secondHit);
BOOST_REQUIRE_CLOSE(point.x, 0, 0.1);
BOOST_REQUIRE_CLOSE(point.y, 5.0, 0.5);
BOOST_REQUIRE_CLOSE(point.z, 0, 0.1);
}
BOOST_AUTO_TEST_CASE(pointAt0x_m5y_0z)
{
JPetHit firstHit;
firstHit.setTime(1333/2.0);
firstHit.setPos(0,-45,0);
JPetBarrelSlot firstSlot(1, true, "first", 270, 1);
firstHit.setBarrelSlot( firstSlot );
JPetHit secondHit;
secondHit.setTime(1667/2);
secondHit.setPos(0,45,0);
JPetBarrelSlot secondSlot(2, true, "second", 90, 2);
secondHit.setBarrelSlot(secondSlot);
Point3D point = EventCategorizerTools::calculateAnnihilationPoint(firstHit, secondHit);
BOOST_REQUIRE_CLOSE(point.x, 0, 0.1);
BOOST_REQUIRE_CLOSE(point.y, -5.0, 0.5);
BOOST_REQUIRE_CLOSE(point.z, 0, 0.1);
}
BOOST_AUTO_TEST_SUITE_END()<commit_msg>Add line at the end of file, fix suite name<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE EventCategorizerToolsTests
#include <boost/test/unit_test.hpp>
#include "EventCategorizerTools.h"
#include "JPetHit/JPetHit.h"
BOOST_AUTO_TEST_SUITE(TOFSuite)
BOOST_AUTO_TEST_CASE(checkHitOrder)
{
JPetHit firstHit;
firstHit.setTime(500.0);
JPetHit secondHit;
secondHit.setTime(100);
double tof = EventCategorizerTools::calculateTOF(firstHit, secondHit);
BOOST_REQUIRE_CLOSE( tof, 9999, 0.100);
}
BOOST_AUTO_TEST_CASE(checkTOFsignNegative)
{
JPetHit firstHit;
firstHit.setTime(100);
JPetBarrelSlot firstSlot(1, true, "first", 10, 1);
firstHit.setBarrelSlot( firstSlot );
JPetHit secondHit;
secondHit.setTime(500);
JPetBarrelSlot secondSlot(2, true, "second", 30, 2);
secondHit.setBarrelSlot(secondSlot);
double tof = EventCategorizerTools::calculateTOF(firstHit, secondHit);
BOOST_REQUIRE_LT( tof, 0 );
}
BOOST_AUTO_TEST_CASE(checkTOFsignPositive)
{
JPetHit firstHit;
firstHit.setTime(100);
JPetBarrelSlot firstSlot(1, true, "first", 30, 1);
firstHit.setBarrelSlot( firstSlot );
JPetHit secondHit;
secondHit.setTime(500);
JPetBarrelSlot secondSlot(2, true, "second", 10, 2);
secondHit.setBarrelSlot(secondSlot);
double tof = EventCategorizerTools::calculateTOF(firstHit, secondHit);
BOOST_REQUIRE_GT( tof, 0 );
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(AnnihilationPointSuite)
BOOST_AUTO_TEST_CASE(pointAtCenter)
{
JPetHit firstHit;
firstHit.setTime(300);
firstHit.setPos(5,5,0);
JPetBarrelSlot firstSlot(1, true, "first", 45, 1);
firstHit.setBarrelSlot( firstSlot );
JPetHit secondHit;
secondHit.setTime(300);
secondHit.setPos(-5,-5,0);
JPetBarrelSlot secondSlot(2, true, "second", 225, 2);
secondHit.setBarrelSlot(secondSlot);
Point3D point = EventCategorizerTools::calculateAnnihilationPoint(firstHit, secondHit);
BOOST_REQUIRE_CLOSE(point.x, 0, 0.001);
BOOST_REQUIRE_CLOSE(point.y, 0, 0.001);
BOOST_REQUIRE_CLOSE(point.z, 0, 0.001);
}
BOOST_AUTO_TEST_CASE(pointAt0x_5y_0z)
{
JPetHit firstHit;
firstHit.setTime(1333/2.0);
firstHit.setPos(0,45,0);
JPetBarrelSlot firstSlot(1, true, "first", 90, 1);
firstHit.setBarrelSlot( firstSlot );
JPetHit secondHit;
secondHit.setTime(1667/2);
secondHit.setPos(0,-45,0);
JPetBarrelSlot secondSlot(2, true, "second", 270, 2);
secondHit.setBarrelSlot(secondSlot);
Point3D point = EventCategorizerTools::calculateAnnihilationPoint(firstHit, secondHit);
BOOST_REQUIRE_CLOSE(point.x, 0, 0.1);
BOOST_REQUIRE_CLOSE(point.y, 5.0, 0.5);
BOOST_REQUIRE_CLOSE(point.z, 0, 0.1);
}
BOOST_AUTO_TEST_CASE(pointAt0x_m5y_0z)
{
JPetHit firstHit;
firstHit.setTime(1333/2.0);
firstHit.setPos(0,-45,0);
JPetBarrelSlot firstSlot(1, true, "first", 270, 1);
firstHit.setBarrelSlot( firstSlot );
JPetHit secondHit;
secondHit.setTime(1667/2);
secondHit.setPos(0,45,0);
JPetBarrelSlot secondSlot(2, true, "second", 90, 2);
secondHit.setBarrelSlot(secondSlot);
Point3D point = EventCategorizerTools::calculateAnnihilationPoint(firstHit, secondHit);
BOOST_REQUIRE_CLOSE(point.x, 0, 0.1);
BOOST_REQUIRE_CLOSE(point.y, -5.0, 0.5);
BOOST_REQUIRE_CLOSE(point.z, 0, 0.1);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "acmacs-chart-2/chart.hh"
//#include "draw.hh"
#include "vaccines.hh"
// ----------------------------------------------------------------------
static inline acmacs::PointStyle& point_style_for(acmacs::PointStyle&& aStyle, hidb::Vaccines::PassageType pt)
{
switch (pt) {
case hidb::Vaccines::Egg:
aStyle.aspect = AspectEgg;
aStyle.rotation = NoRotation;
break;
case hidb::Vaccines::Cell:
aStyle.aspect = AspectNormal;
aStyle.rotation = NoRotation;
break;
case hidb::Vaccines::Reassortant:
aStyle.aspect = AspectEgg;
aStyle.rotation = RotationReassortant;
break;
case hidb::Vaccines::PassageTypeSize:
break;
}
return aStyle;
}
Vaccines::Vaccines(const acmacs::chart::Chart& aChart)
: mVaccinesOfChart{hidb::vaccines(aChart)}
{
for (size_t vaccines_of_chart_index = 0; vaccines_of_chart_index < mVaccinesOfChart.size(); ++vaccines_of_chart_index) {
auto update = [&](hidb::Vaccines::PassageType pt) {
if (!mVaccinesOfChart[vaccines_of_chart_index].empty(pt)) {
mEntries.emplace_back(vaccines_of_chart_index, pt, point_style_for(acmacs::PointStyle(), pt));
}
};
hidb::Vaccines::for_each_passage_type(update);
}
} // Vaccines::Vaccines
// ----------------------------------------------------------------------
std::string Vaccines::report(const hidb::Vaccines::ReportConfig& config) const
{
std::string result;
for (const auto& entry: mEntries) {
if (*entry.style.shown) {
const auto& vacc = mVaccinesOfChart[entry.vaccines_of_chart_index];
const std::string s = vacc.report(entry.passage_type, config, entry.antigen_no);
if (!s.empty())
result += std::string(config.indent_, ' ') + vacc.type() + " " + vacc.name() + " " + acmacs::to_string(*entry.style.fill) + '\n' + s;
}
}
return result;
} // Vaccines::report
// ----------------------------------------------------------------------
std::vector<size_t> Vaccines::indices() const
{
std::vector<size_t> ind;
for (const auto& entry: mEntries) {
if (*entry.style.shown) {
if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, entry.antigen_no); vacc)
ind.push_back(vacc->chart_antigen_index);
}
}
return ind;
} // Vaccines::indices
// ----------------------------------------------------------------------
std::vector<size_t> Vaccines::indices(const VaccineMatchData& aMatchData) const
{
std::vector<size_t> ind;
for (const auto& entry: mEntries) {
// std::cerr << "Vaccine vaccines_of_chart_index: " << entry.vaccines_of_chart_index << " entry.antigen_no: " << entry.antigen_no << " size for " << entry.passage_type << ": " << mVaccinesOfChart[entry.vaccines_of_chart_index].size_for_passage_type(entry.passage_type) << '\n';
if (entry.match(mVaccinesOfChart, aMatchData)) {
// std::cerr << "Vaccine entry.antigen_no: " << entry.antigen_no << " size for " << entry.passage_type << ": " << mVaccinesOfChart[entry.vaccines_of_chart_index].size_for_passage_type(entry.passage_type) << '\n';
if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, aMatchData.no() /* entry.antigen_no */); vacc) {
// std::cerr << "Vaccine " << vacc->chart_antigen_index << " size for " << entry.passage_type << ": " << mVaccinesOfChart[entry.vaccines_of_chart_index].size_for_passage_type(entry.passage_type) << '\n';
ind.push_back(vacc->chart_antigen_index);
}
}
}
return ind;
} // Vaccines::indices
// ----------------------------------------------------------------------
void Vaccines::plot(ChartDraw& aChartDraw) const
{
for (const auto& entry: mEntries) {
if (*entry.style.shown) {
if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, entry.antigen_no); vacc)
aChartDraw.modify(vacc->chart_antigen_index, entry.style, PointDrawingOrder::Raise);
}
}
} // Vaccines::plot
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>formatting fix<commit_after>#include "acmacs-chart-2/chart.hh"
//#include "draw.hh"
#include "vaccines.hh"
// ----------------------------------------------------------------------
static inline acmacs::PointStyle& point_style_for(acmacs::PointStyle&& aStyle, hidb::Vaccines::PassageType pt)
{
switch (pt) {
case hidb::Vaccines::Egg:
aStyle.aspect = AspectEgg;
aStyle.rotation = NoRotation;
break;
case hidb::Vaccines::Cell:
aStyle.aspect = AspectNormal;
aStyle.rotation = NoRotation;
break;
case hidb::Vaccines::Reassortant:
aStyle.aspect = AspectEgg;
aStyle.rotation = RotationReassortant;
break;
case hidb::Vaccines::PassageTypeSize:
break;
}
return aStyle;
}
Vaccines::Vaccines(const acmacs::chart::Chart& aChart)
: mVaccinesOfChart{hidb::vaccines(aChart)}
{
for (size_t vaccines_of_chart_index = 0; vaccines_of_chart_index < mVaccinesOfChart.size(); ++vaccines_of_chart_index) {
auto update = [&](hidb::Vaccines::PassageType pt) {
if (!mVaccinesOfChart[vaccines_of_chart_index].empty(pt)) {
mEntries.emplace_back(vaccines_of_chart_index, pt, point_style_for(acmacs::PointStyle(), pt));
}
};
hidb::Vaccines::for_each_passage_type(update);
}
} // Vaccines::Vaccines
// ----------------------------------------------------------------------
std::string Vaccines::report(const hidb::Vaccines::ReportConfig& config) const
{
std::string result;
for (const auto& entry: mEntries) {
if (*entry.style.shown) {
const auto& vacc = mVaccinesOfChart[entry.vaccines_of_chart_index];
const std::string s = vacc.report(entry.passage_type, config, entry.antigen_no);
if (!s.empty())
result += fmt::format("{:{}c}{} {} {}\n{}", ' ', config.indent_, vacc.type(), vacc.name(), entry.style.fill, s);
}
}
return result;
} // Vaccines::report
// ----------------------------------------------------------------------
std::vector<size_t> Vaccines::indices() const
{
std::vector<size_t> ind;
for (const auto& entry: mEntries) {
if (*entry.style.shown) {
if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, entry.antigen_no); vacc)
ind.push_back(vacc->chart_antigen_index);
}
}
return ind;
} // Vaccines::indices
// ----------------------------------------------------------------------
std::vector<size_t> Vaccines::indices(const VaccineMatchData& aMatchData) const
{
std::vector<size_t> ind;
for (const auto& entry: mEntries) {
// std::cerr << "Vaccine vaccines_of_chart_index: " << entry.vaccines_of_chart_index << " entry.antigen_no: " << entry.antigen_no << " size for " << entry.passage_type << ": " << mVaccinesOfChart[entry.vaccines_of_chart_index].size_for_passage_type(entry.passage_type) << '\n';
if (entry.match(mVaccinesOfChart, aMatchData)) {
// std::cerr << "Vaccine entry.antigen_no: " << entry.antigen_no << " size for " << entry.passage_type << ": " << mVaccinesOfChart[entry.vaccines_of_chart_index].size_for_passage_type(entry.passage_type) << '\n';
if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, aMatchData.no() /* entry.antigen_no */); vacc) {
// std::cerr << "Vaccine " << vacc->chart_antigen_index << " size for " << entry.passage_type << ": " << mVaccinesOfChart[entry.vaccines_of_chart_index].size_for_passage_type(entry.passage_type) << '\n';
ind.push_back(vacc->chart_antigen_index);
}
}
}
return ind;
} // Vaccines::indices
// ----------------------------------------------------------------------
void Vaccines::plot(ChartDraw& aChartDraw) const
{
for (const auto& entry: mEntries) {
if (*entry.style.shown) {
if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, entry.antigen_no); vacc)
aChartDraw.modify(vacc->chart_antigen_index, entry.style, PointDrawingOrder::Raise);
}
}
} // Vaccines::plot
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include <algorithm>
#include <functional>
#include <iomanip>
#include "hidb.hh"
#include "variant-id.hh"
#include "vaccines.hh"
// ----------------------------------------------------------------------
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#endif
static std::map<std::string, std::vector<hidb::Vaccine>> sVaccines = {
{"A(H1N1)", {
{"CALIFORNIA/7/2009", hidb::Vaccine::Previous},
{"MICHIGAN/45/2015", hidb::Vaccine::Current},
}},
{"A(H3N2)", {
{"BRISBANE/10/2007", hidb::Vaccine::Previous},
{"PERTH/16/2009", hidb::Vaccine::Previous},
{"VICTORIA/361/2011", hidb::Vaccine::Previous},
{"TEXAS/50/2012", hidb::Vaccine::Previous},
{"SWITZERLAND/9715293/2013", hidb::Vaccine::Previous},
{"HONG KONG/4801/2014", hidb::Vaccine::Current},
{"SAITAMA/103/2014", hidb::Vaccine::Surrogate},
{"HONG KONG/7295/2014", hidb::Vaccine::Surrogate},
}},
{"BVICTORIA", {
{"MALAYSIA/2506/2004", hidb::Vaccine::Previous},
{"BRISBANE/60/2008", hidb::Vaccine::Current},
{"PARIS/1762/2009", hidb::Vaccine::Current},
{"SOUTH AUSTRALIA/81/2012", hidb::Vaccine::Surrogate},
}},
{"BYAMAGATA", {
{"FLORIDA/4/2006", hidb::Vaccine::Previous},
{"WISCONSIN/1/2010", hidb::Vaccine::Previous},
{"MASSACHUSETTS/2/2012", hidb::Vaccine::Previous},
{"PHUKET/3073/2013", hidb::Vaccine::Current},
}},
};
#pragma GCC diagnostic pop
// ----------------------------------------------------------------------
std::string hidb::Vaccine::type_as_string(hidb::Vaccine::Type aType)
{
switch (aType) {
case Previous:
return "previous";
case Current:
return "current";
case Surrogate:
return "surrogate";
}
return {};
} // hidb::Vaccine::type_as_string
// ----------------------------------------------------------------------
hidb::Vaccine::Type hidb::Vaccine::type_from_string(std::string aType)
{
if (aType == "previous")
return Previous;
else if (aType == "current")
return Current;
else if (aType == "surrogate")
return Surrogate;
return Previous;
} // hidb::Vaccine::type_from_string
// ----------------------------------------------------------------------
const std::vector<hidb::Vaccine>& hidb::vaccines(std::string aSubtype, std::string aLineage)
{
return sVaccines.at(aSubtype + aLineage);
} // hidb::vaccines
// ----------------------------------------------------------------------
const std::vector<hidb::Vaccine>& hidb::vaccines(const Chart& aChart)
{
return vaccines(aChart.chart_info().virus_type(), aChart.lineage());
} // hidb::vaccines
// ----------------------------------------------------------------------
std::string hidb::Vaccine::type_as_string() const
{
return type_as_string(type);
} // hidb::Vaccine::type_as_string
// ----------------------------------------------------------------------
inline bool hidb::Vaccines::Entry::operator < (const hidb::Vaccines::Entry& a) const
{
const auto a_nt = a.antigen_data->number_of_tables(), t_nt = antigen_data->number_of_tables();
return t_nt == a_nt ? most_recent_table_date > a.most_recent_table_date : t_nt > a_nt;
}
// ----------------------------------------------------------------------
bool hidb::Vaccines::HomologousSerum::operator < (const hidb::Vaccines::HomologousSerum& a) const
{
bool result = true;
if (serum->serum_species() == "SHEEP") { // avoid using sheep serum as homologous (NIMR)
result = false;
}
else {
const auto s_nt = a.serum_data->number_of_tables(), t_nt = serum_data->number_of_tables();
result = t_nt == s_nt ? most_recent_table_date > a.most_recent_table_date : t_nt > s_nt;
}
return result;
} // hidb::Vaccines::HomologousSerum::operator <
// ----------------------------------------------------------------------
size_t hidb::Vaccines::HomologousSerum::number_of_tables() const
{
return serum_data->number_of_tables();
} // hidb::Vaccines::HomologousSerum::number_of_tables
// ----------------------------------------------------------------------
std::string hidb::Vaccines::report(size_t aIndent) const
{
std::ostringstream out;
if (!empty()) {
out << std::string(aIndent, ' ') << "Vaccine " << type_as_string() << ' ' << mNameType.name << std::endl;
for_each_passage_type([&](PassageType pt) { out << this->report(pt, aIndent + 2); });
}
return out.str();
} // hidb::Vaccines::report
// ----------------------------------------------------------------------
std::string hidb::Vaccines::report(PassageType aPassageType, size_t aIndent, size_t aMark) const
{
std::ostringstream out;
const std::string indent(aIndent, ' ');
auto entry_report = [&](size_t aNo, const auto& entry, bool aMarkIt) {
out << indent << (aMarkIt ? ">>" : " ") << std::setw(2) << aNo << ' ' << entry.antigen->full_name() << " tables:" << entry.antigen_data->number_of_tables() << " recent:" << entry.antigen_data->most_recent_table().table_id() << std::endl;
for (const auto& hs: entry.homologous_sera)
out << indent << " " << hs.serum->serum_id() << ' ' << hs.serum->annotations().join() << " tables:" << hs.serum_data->number_of_tables() << " recent:" << hs.serum_data->most_recent_table().table_id() << std::endl;
};
const auto& entry = mEntries[aPassageType];
if (!entry.empty()) {
out << indent << passage_type_name(aPassageType) << " (" << entry.size() << ')' << std::endl;
for (size_t no = 0; no < entry.size(); ++no)
entry_report(no, entry[no], aMark == no);
}
return out.str();
} // hidb::Vaccines::report
// ----------------------------------------------------------------------
void hidb::vaccines_for_name(Vaccines& aVaccines, std::string aName, const Chart& aChart, const hidb::HiDb& aHiDb)
{
std::vector<size_t> by_name;
aChart.antigens().find_by_name(aName, by_name);
for (size_t ag_no: by_name) {
try {
const auto& ag = static_cast<const Antigen&>(aChart.antigen(ag_no));
// std::cerr << ag.full_name() << std::endl;
const auto& data = aHiDb.find_antigen_of_chart(ag);
std::vector<hidb::Vaccines::HomologousSerum> homologous_sera;
for (const auto* sd: aHiDb.find_homologous_sera(data)) {
const size_t sr_no = aChart.sera().find_by_name_for_exact_matching(hidb::name_for_exact_matching(sd->data()));
// std::cerr << " " << sd->data().name_for_exact_matching() << " " << (serum ? "Y" : "N") << std::endl;
if (sr_no != static_cast<size_t>(-1))
homologous_sera.emplace_back(sr_no, static_cast<const Serum*>(&aChart.serum(sr_no)), sd, aHiDb.charts()[sd->most_recent_table().table_id()].chart_info().date());
}
aVaccines.add(ag_no, ag, &data, std::move(homologous_sera), aHiDb.charts()[data.most_recent_table().table_id()].chart_info().date());
}
catch (hidb::HiDb::NotFound&) {
}
}
aVaccines.sort();
} // hidb::vaccines_for_name
// ----------------------------------------------------------------------
hidb::Vaccines* hidb::find_vaccines_in_chart(std::string aName, const Chart& aChart, const hidb::HiDb& aHiDb)
{
Vaccines* result = new Vaccines(Vaccine(aName, hidb::Vaccine::Previous));
vaccines_for_name(*result, aName, aChart, aHiDb);
return result;
} // find_vaccines_in_chart
// ----------------------------------------------------------------------
void hidb::vaccines(VaccinesOfChart& aVaccinesOfChart, const Chart& aChart, const hidb::HiDb& aHiDb)
{
for (const auto& name_type: vaccines(aChart)) {
aVaccinesOfChart.emplace_back(name_type);
vaccines_for_name(aVaccinesOfChart.back(), name_type.name, aChart, aHiDb);
}
} // hidb::vaccines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
std::string hidb::VaccinesOfChart::report(size_t aIndent) const
{
std::string result;
for (const auto& v: *this)
result += v.report(aIndent);
return result;
} // hidb::VaccinesOfChart::report
// ----------------------------------------------------------------------
// void hidb::VaccinesOfChart::remove(std::string aName, std::string aType, std::string aPassageType)
// {
// for (auto& v: *this) {
// if (v.match(aName, aType))
// v.remove(aPassageType);
// }
// erase(std::remove_if(begin(), end(), std::mem_fn<bool() const>(&hidb::Vaccines::empty)), end());
// } // hidb::VaccinesOfChart::remove
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>vaccine list updated (B/Vic)<commit_after>#include <algorithm>
#include <functional>
#include <iomanip>
#include "hidb.hh"
#include "variant-id.hh"
#include "vaccines.hh"
// ----------------------------------------------------------------------
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#endif
static std::map<std::string, std::vector<hidb::Vaccine>> sVaccines = {
{"A(H1N1)", {
{"CALIFORNIA/7/2009", hidb::Vaccine::Previous},
{"MICHIGAN/45/2015", hidb::Vaccine::Current},
}},
{"A(H3N2)", {
{"BRISBANE/10/2007", hidb::Vaccine::Previous},
{"PERTH/16/2009", hidb::Vaccine::Previous},
{"VICTORIA/361/2011", hidb::Vaccine::Previous},
{"TEXAS/50/2012", hidb::Vaccine::Previous},
{"SWITZERLAND/9715293/2013", hidb::Vaccine::Previous},
{"HONG KONG/4801/2014", hidb::Vaccine::Current},
{"SAITAMA/103/2014", hidb::Vaccine::Surrogate},
{"HONG KONG/7295/2014", hidb::Vaccine::Surrogate},
}},
{"BVICTORIA", {
{"MALAYSIA/2506/2004", hidb::Vaccine::Previous},
{"BRISBANE/60/2008", hidb::Vaccine::Current},
{"PARIS/1762/2009", hidb::Vaccine::Current},
{"SOUTH AUSTRALIA/81/2012", hidb::Vaccine::Surrogate},
{"IRELAND/3154/2016", hidb::Vaccine::Surrogate},
}},
{"BYAMAGATA", {
{"FLORIDA/4/2006", hidb::Vaccine::Previous},
{"WISCONSIN/1/2010", hidb::Vaccine::Previous},
{"MASSACHUSETTS/2/2012", hidb::Vaccine::Previous},
{"PHUKET/3073/2013", hidb::Vaccine::Current},
}},
};
#pragma GCC diagnostic pop
// ----------------------------------------------------------------------
std::string hidb::Vaccine::type_as_string(hidb::Vaccine::Type aType)
{
switch (aType) {
case Previous:
return "previous";
case Current:
return "current";
case Surrogate:
return "surrogate";
}
return {};
} // hidb::Vaccine::type_as_string
// ----------------------------------------------------------------------
hidb::Vaccine::Type hidb::Vaccine::type_from_string(std::string aType)
{
if (aType == "previous")
return Previous;
else if (aType == "current")
return Current;
else if (aType == "surrogate")
return Surrogate;
return Previous;
} // hidb::Vaccine::type_from_string
// ----------------------------------------------------------------------
const std::vector<hidb::Vaccine>& hidb::vaccines(std::string aSubtype, std::string aLineage)
{
return sVaccines.at(aSubtype + aLineage);
} // hidb::vaccines
// ----------------------------------------------------------------------
const std::vector<hidb::Vaccine>& hidb::vaccines(const Chart& aChart)
{
return vaccines(aChart.chart_info().virus_type(), aChart.lineage());
} // hidb::vaccines
// ----------------------------------------------------------------------
std::string hidb::Vaccine::type_as_string() const
{
return type_as_string(type);
} // hidb::Vaccine::type_as_string
// ----------------------------------------------------------------------
inline bool hidb::Vaccines::Entry::operator < (const hidb::Vaccines::Entry& a) const
{
const auto a_nt = a.antigen_data->number_of_tables(), t_nt = antigen_data->number_of_tables();
return t_nt == a_nt ? most_recent_table_date > a.most_recent_table_date : t_nt > a_nt;
}
// ----------------------------------------------------------------------
bool hidb::Vaccines::HomologousSerum::operator < (const hidb::Vaccines::HomologousSerum& a) const
{
bool result = true;
if (serum->serum_species() == "SHEEP") { // avoid using sheep serum as homologous (NIMR)
result = false;
}
else {
const auto s_nt = a.serum_data->number_of_tables(), t_nt = serum_data->number_of_tables();
result = t_nt == s_nt ? most_recent_table_date > a.most_recent_table_date : t_nt > s_nt;
}
return result;
} // hidb::Vaccines::HomologousSerum::operator <
// ----------------------------------------------------------------------
size_t hidb::Vaccines::HomologousSerum::number_of_tables() const
{
return serum_data->number_of_tables();
} // hidb::Vaccines::HomologousSerum::number_of_tables
// ----------------------------------------------------------------------
std::string hidb::Vaccines::report(size_t aIndent) const
{
std::ostringstream out;
if (!empty()) {
out << std::string(aIndent, ' ') << "Vaccine " << type_as_string() << ' ' << mNameType.name << std::endl;
for_each_passage_type([&](PassageType pt) { out << this->report(pt, aIndent + 2); });
}
return out.str();
} // hidb::Vaccines::report
// ----------------------------------------------------------------------
std::string hidb::Vaccines::report(PassageType aPassageType, size_t aIndent, size_t aMark) const
{
std::ostringstream out;
const std::string indent(aIndent, ' ');
auto entry_report = [&](size_t aNo, const auto& entry, bool aMarkIt) {
out << indent << (aMarkIt ? ">>" : " ") << std::setw(2) << aNo << ' ' << entry.antigen->full_name() << " tables:" << entry.antigen_data->number_of_tables() << " recent:" << entry.antigen_data->most_recent_table().table_id() << std::endl;
for (const auto& hs: entry.homologous_sera)
out << indent << " " << hs.serum->serum_id() << ' ' << hs.serum->annotations().join() << " tables:" << hs.serum_data->number_of_tables() << " recent:" << hs.serum_data->most_recent_table().table_id() << std::endl;
};
const auto& entry = mEntries[aPassageType];
if (!entry.empty()) {
out << indent << passage_type_name(aPassageType) << " (" << entry.size() << ')' << std::endl;
for (size_t no = 0; no < entry.size(); ++no)
entry_report(no, entry[no], aMark == no);
}
return out.str();
} // hidb::Vaccines::report
// ----------------------------------------------------------------------
void hidb::vaccines_for_name(Vaccines& aVaccines, std::string aName, const Chart& aChart, const hidb::HiDb& aHiDb)
{
std::vector<size_t> by_name;
aChart.antigens().find_by_name(aName, by_name);
for (size_t ag_no: by_name) {
try {
const auto& ag = static_cast<const Antigen&>(aChart.antigen(ag_no));
// std::cerr << ag.full_name() << std::endl;
const auto& data = aHiDb.find_antigen_of_chart(ag);
std::vector<hidb::Vaccines::HomologousSerum> homologous_sera;
for (const auto* sd: aHiDb.find_homologous_sera(data)) {
const size_t sr_no = aChart.sera().find_by_name_for_exact_matching(hidb::name_for_exact_matching(sd->data()));
// std::cerr << " " << sd->data().name_for_exact_matching() << " " << (serum ? "Y" : "N") << std::endl;
if (sr_no != static_cast<size_t>(-1))
homologous_sera.emplace_back(sr_no, static_cast<const Serum*>(&aChart.serum(sr_no)), sd, aHiDb.charts()[sd->most_recent_table().table_id()].chart_info().date());
}
aVaccines.add(ag_no, ag, &data, std::move(homologous_sera), aHiDb.charts()[data.most_recent_table().table_id()].chart_info().date());
}
catch (hidb::HiDb::NotFound&) {
}
}
aVaccines.sort();
} // hidb::vaccines_for_name
// ----------------------------------------------------------------------
hidb::Vaccines* hidb::find_vaccines_in_chart(std::string aName, const Chart& aChart, const hidb::HiDb& aHiDb)
{
Vaccines* result = new Vaccines(Vaccine(aName, hidb::Vaccine::Previous));
vaccines_for_name(*result, aName, aChart, aHiDb);
return result;
} // find_vaccines_in_chart
// ----------------------------------------------------------------------
void hidb::vaccines(VaccinesOfChart& aVaccinesOfChart, const Chart& aChart, const hidb::HiDb& aHiDb)
{
for (const auto& name_type: vaccines(aChart)) {
aVaccinesOfChart.emplace_back(name_type);
vaccines_for_name(aVaccinesOfChart.back(), name_type.name, aChart, aHiDb);
}
} // hidb::vaccines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
std::string hidb::VaccinesOfChart::report(size_t aIndent) const
{
std::string result;
for (const auto& v: *this)
result += v.report(aIndent);
return result;
} // hidb::VaccinesOfChart::report
// ----------------------------------------------------------------------
// void hidb::VaccinesOfChart::remove(std::string aName, std::string aType, std::string aPassageType)
// {
// for (auto& v: *this) {
// if (v.match(aName, aType))
// v.remove(aPassageType);
// }
// erase(std::remove_if(begin(), end(), std::mem_fn<bool() const>(&hidb::Vaccines::empty)), end());
// } // hidb::VaccinesOfChart::remove
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 Shanghai Jiao Tong University.
* 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.
*
* For more about this software visit:
*
* http://ipads.se.sjtu.edu.cn/projects/wukong
*
*/
#pragma once
#pragma GCC diagnostic warning "-fpermissive"
#include <iostream> // std::cout
#include <fstream> // std::ifstream
#include <vector>
using namespace std;
#include "timer.hpp"
#include "assertion.hpp"
#ifdef HAS_RDMA
#include "rdmaio.hpp"
using namespace rdmaio;
class RDMA {
public:
enum MemType { CPU, GPU };
struct MemoryRegion {
char *mem;
uint64_t sz;
MemType type;
};
class RDMA_Device {
static const uint64_t RDMA_CTRL_PORT = 19344;
public:
RdmaCtrl* ctrl = NULL;
// currently we only support one cpu and one gpu mr in mrs!
RDMA_Device(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string ipfn) {
// record IPs of ndoes
vector<string> ipset;
ifstream ipfile(ipfn);
string ip;
// get first nnodes IPs
for (int i = 0; i < nnodes; i++) {
ipfile >> ip;
ipset.push_back(ip);
}
// init device and create QPs
ctrl = new RdmaCtrl(nid, ipset, RDMA_CTRL_PORT, true); // enable single context
ctrl->query_devinfo();
ctrl->open_device();
for (auto mr : mrs) {
switch (mr.type) {
case RDMA::MemType::CPU:
ctrl->set_connect_mr(mr.mem, mr.sz);
ctrl->register_connect_mr();//single
break;
case RDMA::MemType::GPU:
#ifdef USE_GPU
ctrl->set_connect_mr_gpu(mr.mem, mr.sz);
ctrl->register_connect_mr_gpu();
break;
#else
logstream(LOG_ERROR) << "GPU mode is not enabled." << LOG_endl;
ASSERT(false);
#endif
}
}
ctrl->start_server();
for (uint j = 0; j < nthds; ++j) {
for (uint i = 0; i < nnodes; ++i) {
// FIXME: statically use 1 device and 1 port
//
// devID: [0, #devs), portID: (0, #ports]
// 0: always choose the 1st (RDMA) device
// 1: always choose the 1st (RDMA) port
Qp *qp = ctrl->create_rc_qp(j, i, 0, 1);
ASSERT(qp != NULL);
}
}
// connect all QPs
while (1) {
int connected = 0;
for (uint j = 0; j < nthds; ++j) {
for (uint i = 0; i < nnodes; ++i) {
Qp *qp = ctrl->get_rc_qp(j, i);
if (qp->inited_) // has connected
connected ++;
else if (qp->connect_rc())
connected ++;
}
}
if (connected == nthds * nnodes) break; // done
}
}
#ifdef USE_GPU
// (sync) GPUDirect RDMA Write (w/ completion)
int GPURdmaWrite(int tid, int nid, char *local_gpu, uint64_t sz, uint64_t off, bool to_gpu = false) {
Qp* qp = ctrl->get_rc_qp(tid, nid);
int flags = IBV_SEND_SIGNALED;
qp->rc_post_send_gpu(IBV_WR_RDMA_WRITE, local_gpu, sz, off, flags, to_gpu);
qp->poll_completion();
return 0;
}
#endif
// (sync) RDMA Read (w/ completion)
int RdmaRead(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
Qp* qp = ctrl->get_rc_qp(tid, nid);
// sweep remaining completion events (due to selective RDMA writes)
if (!qp->first_send())
qp->poll_completion();
qp->rc_post_send(IBV_WR_RDMA_READ, local, sz, off, IBV_SEND_SIGNALED);
qp->poll_completion();
return 0;
}
// (sync) RDMA Write (w/ completion)
int RdmaWrite(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
Qp* qp = ctrl->get_rc_qp(tid, nid);
int flags = IBV_SEND_SIGNALED;
qp->rc_post_send(IBV_WR_RDMA_WRITE, local, sz, off, flags);
qp->poll_completion();
return 0;
}
// (blind) RDMA Write (w/o completion)
int RdmaWriteNonSignal(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
Qp* qp = ctrl->get_rc_qp(tid, nid);
int flags = 0;
qp->rc_post_send(IBV_WR_RDMA_WRITE, local, sz, off, flags);
return 0;
}
// (adaptive) RDMA Write (w/o completion)
int RdmaWriteSelective(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
Qp* qp = ctrl->get_rc_qp(tid, nid);
int flags = (qp->first_send() ? IBV_SEND_SIGNALED : 0);
qp->rc_post_send(IBV_WR_RDMA_WRITE, local, sz, off, flags);
if (qp->need_poll()) // sweep all completion (batch)
qp->poll_completion();
return 0;
}
};
public:
RDMA_Device *dev = NULL;
RDMA() { }
~RDMA() { if (dev != NULL) delete dev; }
void init_dev(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string ipfn) {
dev = new RDMA_Device(nnodes, nthds, nid, mrs, ipfn);
}
inline static bool has_rdma() { return true; }
static RDMA &get_rdma() {
static RDMA rdma;
return rdma;
}
};
void RDMA_init(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string ipfn) {
uint64_t t = timer::get_usec();
// init RDMA device
RDMA &rdma = RDMA::get_rdma();
rdma.init_dev(nnodes, nthds, nid, mrs, ipfn);
t = timer::get_usec() - t;
logstream(LOG_INFO) << "initializing RMDA done (" << t / 1000 << " ms)" << LOG_endl;
}
#else
class RDMA {
class RDMA_Device {
public:
RDMA_Device(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string fname) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
ASSERT(false);
}
int RdmaRead(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
ASSERT(false);
return 0;
}
int RdmaWrite(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
ASSERT(false);
return 0;
}
int RdmaWriteNonSignal(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
ASSERT(false);
return 0;
}
int RdmaWriteSelective(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
ASSERT(false);
return 0;
}
};
public:
RDMA_Device *dev = NULL;
RDMA() { }
~RDMA() { }
void init_dev(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string ipfn) {
dev = new RDMA_Device(nnodes, nthds, nid, mrs, ipfn);
}
inline static bool has_rdma() { return false; }
static RDMA &get_rdma() {
static RDMA rdma;
return rdma;
}
};
void RDMA_init(int nnodes, int nthds, int nid, char *mem_cpu, uint64_t sz_cpu, vector<RDMA::MemoryRegion> &mrs, string ipfn) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
}
#endif
<commit_msg>Resolve bug to support build without RDMA<commit_after>/*
* Copyright (c) 2016 Shanghai Jiao Tong University.
* 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.
*
* For more about this software visit:
*
* http://ipads.se.sjtu.edu.cn/projects/wukong
*
*/
#pragma once
#pragma GCC diagnostic warning "-fpermissive"
#include <iostream> // std::cout
#include <fstream> // std::ifstream
#include <vector>
using namespace std;
#include "timer.hpp"
#include "assertion.hpp"
#ifdef HAS_RDMA
#include "rdmaio.hpp"
using namespace rdmaio;
class RDMA {
public:
enum MemType { CPU, GPU };
struct MemoryRegion {
char *mem;
uint64_t sz;
MemType type;
};
class RDMA_Device {
static const uint64_t RDMA_CTRL_PORT = 19344;
public:
RdmaCtrl* ctrl = NULL;
// currently we only support one cpu and one gpu mr in mrs!
RDMA_Device(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string ipfn) {
// record IPs of ndoes
vector<string> ipset;
ifstream ipfile(ipfn);
string ip;
// get first nnodes IPs
for (int i = 0; i < nnodes; i++) {
ipfile >> ip;
ipset.push_back(ip);
}
// init device and create QPs
ctrl = new RdmaCtrl(nid, ipset, RDMA_CTRL_PORT, true); // enable single context
ctrl->query_devinfo();
ctrl->open_device();
for (auto mr : mrs) {
switch (mr.type) {
case RDMA::MemType::CPU:
ctrl->set_connect_mr(mr.mem, mr.sz);
ctrl->register_connect_mr();//single
break;
case RDMA::MemType::GPU:
#ifdef USE_GPU
ctrl->set_connect_mr_gpu(mr.mem, mr.sz);
ctrl->register_connect_mr_gpu();
break;
#else
logstream(LOG_ERROR) << "GPU mode is not enabled." << LOG_endl;
ASSERT(false);
#endif
}
}
ctrl->start_server();
for (uint j = 0; j < nthds; ++j) {
for (uint i = 0; i < nnodes; ++i) {
// FIXME: statically use 1 device and 1 port
//
// devID: [0, #devs), portID: (0, #ports]
// 0: always choose the 1st (RDMA) device
// 1: always choose the 1st (RDMA) port
Qp *qp = ctrl->create_rc_qp(j, i, 0, 1);
ASSERT(qp != NULL);
}
}
// connect all QPs
while (1) {
int connected = 0;
for (uint j = 0; j < nthds; ++j) {
for (uint i = 0; i < nnodes; ++i) {
Qp *qp = ctrl->get_rc_qp(j, i);
if (qp->inited_) // has connected
connected ++;
else if (qp->connect_rc())
connected ++;
}
}
if (connected == nthds * nnodes) break; // done
}
}
#ifdef USE_GPU
// (sync) GPUDirect RDMA Write (w/ completion)
int GPURdmaWrite(int tid, int nid, char *local_gpu, uint64_t sz, uint64_t off, bool to_gpu = false) {
Qp* qp = ctrl->get_rc_qp(tid, nid);
int flags = IBV_SEND_SIGNALED;
qp->rc_post_send_gpu(IBV_WR_RDMA_WRITE, local_gpu, sz, off, flags, to_gpu);
qp->poll_completion();
return 0;
}
#endif
// (sync) RDMA Read (w/ completion)
int RdmaRead(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
Qp* qp = ctrl->get_rc_qp(tid, nid);
// sweep remaining completion events (due to selective RDMA writes)
if (!qp->first_send())
qp->poll_completion();
qp->rc_post_send(IBV_WR_RDMA_READ, local, sz, off, IBV_SEND_SIGNALED);
qp->poll_completion();
return 0;
}
// (sync) RDMA Write (w/ completion)
int RdmaWrite(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
Qp* qp = ctrl->get_rc_qp(tid, nid);
int flags = IBV_SEND_SIGNALED;
qp->rc_post_send(IBV_WR_RDMA_WRITE, local, sz, off, flags);
qp->poll_completion();
return 0;
}
// (blind) RDMA Write (w/o completion)
int RdmaWriteNonSignal(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
Qp* qp = ctrl->get_rc_qp(tid, nid);
int flags = 0;
qp->rc_post_send(IBV_WR_RDMA_WRITE, local, sz, off, flags);
return 0;
}
// (adaptive) RDMA Write (w/o completion)
int RdmaWriteSelective(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
Qp* qp = ctrl->get_rc_qp(tid, nid);
int flags = (qp->first_send() ? IBV_SEND_SIGNALED : 0);
qp->rc_post_send(IBV_WR_RDMA_WRITE, local, sz, off, flags);
if (qp->need_poll()) // sweep all completion (batch)
qp->poll_completion();
return 0;
}
};
public:
RDMA_Device *dev = NULL;
RDMA() { }
~RDMA() { if (dev != NULL) delete dev; }
void init_dev(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string ipfn) {
dev = new RDMA_Device(nnodes, nthds, nid, mrs, ipfn);
}
inline static bool has_rdma() { return true; }
static RDMA &get_rdma() {
static RDMA rdma;
return rdma;
}
};
void RDMA_init(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string ipfn) {
uint64_t t = timer::get_usec();
// init RDMA device
RDMA &rdma = RDMA::get_rdma();
rdma.init_dev(nnodes, nthds, nid, mrs, ipfn);
t = timer::get_usec() - t;
logstream(LOG_INFO) << "initializing RMDA done (" << t / 1000 << " ms)" << LOG_endl;
}
#else
class RDMA {
enum MemType { CPU, GPU };
struct MemoryRegion {
char *mem;
uint64_t sz;
MemType type;
};
class RDMA_Device {
public:
RDMA_Device(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string fname) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
ASSERT(false);
}
int RdmaRead(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
ASSERT(false);
return 0;
}
int RdmaWrite(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
ASSERT(false);
return 0;
}
int RdmaWriteNonSignal(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
ASSERT(false);
return 0;
}
int RdmaWriteSelective(int tid, int nid, char *local, uint64_t sz, uint64_t off) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
ASSERT(false);
return 0;
}
};
public:
RDMA_Device *dev = NULL;
RDMA() { }
~RDMA() { }
void init_dev(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string ipfn) {
dev = new RDMA_Device(nnodes, nthds, nid, mrs, ipfn);
}
inline static bool has_rdma() { return false; }
static RDMA &get_rdma() {
static RDMA rdma;
return rdma;
}
};
void RDMA_init(int nnodes, int nthds, int nid, vector<RDMA::MemoryRegion> &mrs, string ipfn) {
logstream(LOG_INFO) << "This system is compiled without RDMA support." << LOG_endl;
}
#endif
<|endoftext|> |
<commit_before>#include <cmd_classbook_delete_record_handler.h>
#include <QJsonArray>
#include <QSqlError>
#include <QUuid>
CmdClassbookDeleteRecordHandler::CmdClassbookDeleteRecordHandler(){
m_vInputs.push_back(CmdInputDef("classbookid").required().integer_().description("id for classbook article"));
}
QString CmdClassbookDeleteRecordHandler::cmd(){
return "classbook_delete_record";
}
bool CmdClassbookDeleteRecordHandler::accessUnauthorized(){
return false;
}
bool CmdClassbookDeleteRecordHandler::accessUser(){
return false;
}
bool CmdClassbookDeleteRecordHandler::accessTester(){
return false;
}
bool CmdClassbookDeleteRecordHandler::accessAdmin(){
return true;
}
const QVector<CmdInputDef> &CmdClassbookDeleteRecordHandler::inputs(){
return m_vInputs;
};
QString CmdClassbookDeleteRecordHandler::description(){
return "Delete a article with a given classbookid";
}
QStringList CmdClassbookDeleteRecordHandler::errors(){
QStringList list;
return list;
}
void CmdClassbookDeleteRecordHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){
QSqlDatabase db = *(pWebSocketServer->database());
int classbookid = obj["classbookid"].toInt();
//DELETE Record IF haven't childs
QSqlQuery query(db);
if(classbookid !=0){
query.prepare("SELECT id FROM classbook WHERE parentid=:classbookid");
query.bindValue(":classbookid", classbookid);
query.exec();
if (query.next()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "Could not delete, because childs exists. Please remove childs first."));
return;
}
//Delete record in classbook
query.prepare("DELETE FROM classbook WHERE id=:classbookid");
query.bindValue(":classbookid", classbookid);
query.exec();
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Errors::DatabaseError(query.lastError().text()));
return;
}
//Delete record's localization
/*query.prepare("DELETE FROM classbook WHERE id=:classbookid");
query.bindValue(":classbookid", classbookid);
query.exec();
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Errors::DatabaseError(query.lastError().text()));
return;
}*/
}
QJsonObject jsonResponse;
jsonResponse["cmd"] = QJsonValue(cmd());
jsonResponse["m"] = QJsonValue(m);
jsonResponse["result"] = QJsonValue("DONE");
pWebSocketServer->sendMessage(pClient, jsonResponse);
}
<commit_msg>Add delete localization for delete record hendler<commit_after>#include <cmd_classbook_delete_record_handler.h>
#include <QJsonArray>
#include <QSqlError>
#include <QUuid>
CmdClassbookDeleteRecordHandler::CmdClassbookDeleteRecordHandler(){
m_vInputs.push_back(CmdInputDef("classbookid").required().integer_().description("id for classbook article"));
}
QString CmdClassbookDeleteRecordHandler::cmd(){
return "classbook_delete_record";
}
bool CmdClassbookDeleteRecordHandler::accessUnauthorized(){
return false;
}
bool CmdClassbookDeleteRecordHandler::accessUser(){
return false;
}
bool CmdClassbookDeleteRecordHandler::accessTester(){
return false;
}
bool CmdClassbookDeleteRecordHandler::accessAdmin(){
return true;
}
const QVector<CmdInputDef> &CmdClassbookDeleteRecordHandler::inputs(){
return m_vInputs;
};
QString CmdClassbookDeleteRecordHandler::description(){
return "Delete a article with a given classbookid";
}
QStringList CmdClassbookDeleteRecordHandler::errors(){
QStringList list;
return list;
}
void CmdClassbookDeleteRecordHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){
QSqlDatabase db = *(pWebSocketServer->database());
int classbookid = obj["classbookid"].toInt();
//DELETE Record IF haven't childs
QSqlQuery query(db);
if(classbookid !=0){
query.prepare("SELECT id FROM classbook WHERE parentid=:classbookid");
query.bindValue(":classbookid", classbookid);
query.exec();
if (query.next()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "Could not delete, because childs exists. Please remove childs first."));
return;
}
//Delete record in classbook
query.prepare("DELETE FROM classbook WHERE id=:classbookid");
query.bindValue(":classbookid", classbookid);
query.exec();
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Errors::DatabaseError(query.lastError().text()));
return;
}
//Delete record's localization
query.prepare("DELETE FROM classbook_localization WHERE classbookid=:classbookid");
query.bindValue(":classbookid", classbookid);
query.exec();
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Errors::DatabaseError(query.lastError().text()));
return;
}
}
QJsonObject jsonResponse;
jsonResponse["cmd"] = QJsonValue(cmd());
jsonResponse["m"] = QJsonValue(m);
jsonResponse["result"] = QJsonValue("DONE");
pWebSocketServer->sendMessage(pClient, jsonResponse);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dbinteraction.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2003-03-19 17:53:08 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBAUI_INTERACTION_HXX_
#define _DBAUI_INTERACTION_HXX_
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_AUTHENTICATIONREQUEST_HPP_
#include <com/sun/star/ucb/AuthenticationRequest.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_PARAMETERSREQUEST_HPP_
#include <com/sun/star/sdb/ParametersRequest.hpp>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
namespace dbtools
{
class SQLExceptionInfo;
}
//.........................................................................
namespace dbaui
{
//.........................................................................
//=========================================================================
//= OInteractionHandler
//=========================================================================
typedef ::cppu::WeakImplHelper2 < ::com::sun::star::lang::XServiceInfo
, ::com::sun::star::task::XInteractionHandler
> OInteractionHandler_Base;
/** implements an <type scope="com.sun.star.task">XInteractionHandler</type> for
database related interaction requests.
<p/>
Supported interaction requests by now (specified by an exception: The appropriate exception
has to be returned by the getRequest method of the object implementing the
<type scope="com.sun.star.task">XInteractionRequest</type> interface.
<ul>
<li><b><type scope="com.sun.star.sdbc">SQLException</type></b>: requests to display a
standard error dialog for the (maybe chained) exception given</li>
</ul>
*/
class OInteractionHandler
:public OInteractionHandler_Base
,public OModuleClient // want to use resources
{
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
m_xORB;
public:
OInteractionHandler(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
// XServiceInfo
DECLARE_SERVICE_INFO_STATIC();
// XInteractionHandler
virtual void SAL_CALL handle( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& Request ) throw(::com::sun::star::uno::RuntimeException);
protected:
/// handle SQLExceptions (and derived classes)
void implHandle(
const ::dbtools::SQLExceptionInfo& _rSqlInfo,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >& _rContinuations);
/// handle authentication requests
void implHandle(
const ::com::sun::star::ucb::AuthenticationRequest& _rAuthRequest,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >& _rContinuations);
/// handle parameter requests
void implHandle(
const ::com::sun::star::sdb::ParametersRequest& _rParamRequest,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >& _rContinuations);
/// known continuation types
enum Continuation
{
APPROVE,
DISAPPROVE,
RETRY,
ABORT,
SUPPLY_AUTHENTICATION,
SUPPLY_PARAMETERS
};
/** check if a given continuation sequence contains a given continuation type<p/>
@return the index within <arg>_rContinuations</arg> of the first occurence of a continuation
of the requested type, -1 of no such continuation exists
*/
sal_Int32 getContinuation(
Continuation _eCont,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >& _rContinuations);
};
//.........................................................................
} // namespace dbaui
//.........................................................................
#endif // _DBAUI_INTERACTION_HXX_
<commit_msg>INTEGRATION: CWS insight01 (1.3.64); FILE MERGED 2003/11/26 12:22:47 oj 1.3.64.1: #111075# ongoing work<commit_after>/*************************************************************************
*
* $RCSfile: dbinteraction.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2004-08-02 16:23:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBAUI_INTERACTION_HXX_
#define _DBAUI_INTERACTION_HXX_
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_AUTHENTICATIONREQUEST_HPP_
#include <com/sun/star/ucb/AuthenticationRequest.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_PARAMETERSREQUEST_HPP_
#include <com/sun/star/sdb/ParametersRequest.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_DOCUMENTSAVEREQUEST_HPP_
#include <com/sun/star/sdb/DocumentSaveRequest.hpp>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
namespace dbtools
{
class SQLExceptionInfo;
}
//.........................................................................
namespace dbaui
{
//.........................................................................
//=========================================================================
//= OInteractionHandler
//=========================================================================
typedef ::cppu::WeakImplHelper2 < ::com::sun::star::lang::XServiceInfo
, ::com::sun::star::task::XInteractionHandler
> OInteractionHandler_Base;
/** implements an <type scope="com.sun.star.task">XInteractionHandler</type> for
database related interaction requests.
<p/>
Supported interaction requests by now (specified by an exception: The appropriate exception
has to be returned by the getRequest method of the object implementing the
<type scope="com.sun.star.task">XInteractionRequest</type> interface.
<ul>
<li><b><type scope="com.sun.star.sdbc">SQLException</type></b>: requests to display a
standard error dialog for the (maybe chained) exception given</li>
</ul>
*/
class OInteractionHandler
:public OInteractionHandler_Base
,public OModuleClient // want to use resources
{
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
m_xORB;
public:
OInteractionHandler(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
// XServiceInfo
DECLARE_SERVICE_INFO_STATIC();
// XInteractionHandler
virtual void SAL_CALL handle( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& Request ) throw(::com::sun::star::uno::RuntimeException);
protected:
/// handle SQLExceptions (and derived classes)
void implHandle(
const ::dbtools::SQLExceptionInfo& _rSqlInfo,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >& _rContinuations);
/// handle authentication requests
void implHandle(
const ::com::sun::star::ucb::AuthenticationRequest& _rAuthRequest,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >& _rContinuations);
/// handle parameter requests
void implHandle(
const ::com::sun::star::sdb::ParametersRequest& _rParamRequest,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >& _rContinuations);
/// handle document save requests
void implHandle(
const ::com::sun::star::sdb::DocumentSaveRequest& _rParamRequest,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >& _rContinuations);
/// known continuation types
enum Continuation
{
APPROVE,
DISAPPROVE,
RETRY,
ABORT,
SUPPLY_AUTHENTICATION,
SUPPLY_PARAMETERS,
SUPPLY_DOCUMENTSAVE
};
/** check if a given continuation sequence contains a given continuation type<p/>
@return the index within <arg>_rContinuations</arg> of the first occurence of a continuation
of the requested type, -1 of no such continuation exists
*/
sal_Int32 getContinuation(
Continuation _eCont,
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >& _rContinuations);
};
//.........................................................................
} // namespace dbaui
//.........................................................................
#endif // _DBAUI_INTERACTION_HXX_
<|endoftext|> |
<commit_before><commit_msg>add more tests<commit_after><|endoftext|> |
<commit_before>//
// Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "angle_gl.h"
#include "compiler/translator/BuiltInFunctionEmulator.h"
#include "compiler/translator/BuiltInFunctionEmulatorGLSL.h"
#include "compiler/translator/SymbolTable.h"
#include "compiler/translator/VersionGLSL.h"
void InitBuiltInFunctionEmulatorForGLSLWorkarounds(BuiltInFunctionEmulator *emu, sh::GLenum shaderType)
{
// we use macros here instead of function definitions to work around more GLSL
// compiler bugs, in particular on NVIDIA hardware on Mac OSX. Macros are
// problematic because if the argument has side-effects they will be repeatedly
// evaluated. This is unlikely to show up in real shaders, but is something to
// consider.
TType *float1 = new TType(EbtFloat);
TType *float2 = new TType(EbtFloat, 2);
TType *float3 = new TType(EbtFloat, 3);
TType *float4 = new TType(EbtFloat, 4);
if (shaderType == GL_FRAGMENT_SHADER)
{
emu->addEmulatedFunction(EOpCos, float1, "webgl_emu_precision float webgl_cos_emu(webgl_emu_precision float a) { return cos(a); }");
emu->addEmulatedFunction(EOpCos, float2, "webgl_emu_precision vec2 webgl_cos_emu(webgl_emu_precision vec2 a) { return cos(a); }");
emu->addEmulatedFunction(EOpCos, float3, "webgl_emu_precision vec3 webgl_cos_emu(webgl_emu_precision vec3 a) { return cos(a); }");
emu->addEmulatedFunction(EOpCos, float4, "webgl_emu_precision vec4 webgl_cos_emu(webgl_emu_precision vec4 a) { return cos(a); }");
}
emu->addEmulatedFunction(EOpDistance, float1, float1, "#define webgl_distance_emu(x, y) ((x) >= (y) ? (x) - (y) : (y) - (x))");
emu->addEmulatedFunction(EOpDot, float1, float1, "#define webgl_dot_emu(x, y) ((x) * (y))");
emu->addEmulatedFunction(EOpLength, float1, "#define webgl_length_emu(x) ((x) >= 0.0 ? (x) : -(x))");
emu->addEmulatedFunction(EOpNormalize, float1, "#define webgl_normalize_emu(x) ((x) == 0.0 ? 0.0 : ((x) > 0.0 ? 1.0 : -1.0))");
emu->addEmulatedFunction(EOpReflect, float1, float1, "#define webgl_reflect_emu(I, N) ((I) - 2.0 * (N) * (I) * (N))");
}
// Emulate built-in functions missing from GLSL 1.30 and higher
void InitBuiltInFunctionEmulatorForGLSLMissingFunctions(BuiltInFunctionEmulator *emu, sh::GLenum shaderType,
int targetGLSLVersion)
{
// Emulate packUnorm2x16 and unpackUnorm2x16 (GLSL 4.10)
if (targetGLSLVersion < GLSL_VERSION_410)
{
TType *float2 = new TType(EbtFloat, 2);
TType *uint1 = new TType(EbtUInt);
emu->addEmulatedFunction(EOpPackUnorm2x16, float2,
"uint webgl_packUnorm2x16_emu(vec2 v)\n"
"{\n"
" int x = int(round(clamp(v.x, 0.0, 1.0) * 65535.0));\n"
" int y = int(round(clamp(v.y, 0.0, 1.0) * 65535.0));\n"
" return uint((y << 16) | (x & 0xFFFF));\n"
"}\n");
emu->addEmulatedFunction(EOpUnpackUnorm2x16, uint1,
"vec2 webgl_unpackUnorm2x16_emu(uint u)\n"
"{\n"
" float x = float(u & 0xFFFFu) / 65535.0;\n"
" float y = float(u >> 16) / 65535.0;\n"
" return vec2(x, y);\n"
"}\n");
}
// Emulate packSnorm2x16, packHalf2x16, unpackSnorm2x16, and unpackHalf2x16 (GLSL 4.20)
// by using floatBitsToInt, floatBitsToUint, intBitsToFloat, and uintBitsToFloat (GLSL 3.30).
if (targetGLSLVersion >= GLSL_VERSION_330 && targetGLSLVersion < GLSL_VERSION_420)
{
TType *float2 = new TType(EbtFloat, 2);
TType *uint1 = new TType(EbtUInt);
emu->addEmulatedFunction(EOpPackSnorm2x16, float2,
"uint webgl_packSnorm2x16_emu(vec2 v)\n"
"{\n"
" int x = int(round(clamp(v.x, -1.0, 1.0) * 32767.0));\n"
" int y = int(round(clamp(v.y, -1.0, 1.0) * 32767.0));\n"
" return uint((y << 16) | (x & 0xFFFF));\n"
"}\n");
emu->addEmulatedFunction(EOpUnpackSnorm2x16, uint1,
"float webgl_fromSnorm(uint x)\n"
"{\n"
" int xi = (int(x) & 0x7FFF) - (int(x) & 0x8000);\n"
" return clamp(float(xi) / 32767.0, -1.0, 1.0);\n"
"}\n"
"\n"
"vec2 webgl_unpackSnorm2x16_emu(uint u)\n"
"{\n"
" uint y = (u >> 16);\n"
" uint x = u;\n"
" return vec2(webgl_fromSnorm(x), webgl_fromSnorm(y));\n"
"}\n");
// Functions uint webgl_f32tof16(float val) and float webgl_f16tof32(uint val) are
// based on the OpenGL redbook Appendix Session "Floating-Point Formats Used in OpenGL".
emu->addEmulatedFunction(EOpPackHalf2x16, float2,
"uint webgl_f32tof16(float val)\n"
"{\n"
" uint f32 = floatBitsToUint(val);\n"
" uint f16 = 0u;\n"
" uint sign = (f32 >> 16) & 0x8000u;\n"
" int exponent = int((f32 >> 23) & 0xFFu) - 127;\n"
" uint mantissa = f32 & 0x007FFFFFu;\n"
" if (exponent == 128)\n"
" {\n"
" // Infinity or NaN\n"
" // NaN bits that are masked out by 0x3FF get discarded.\n"
" // This can turn some NaNs to infinity, but this is allowed by the spec.\n"
" f16 = sign | (0x1Fu << 10);\n"
" f16 |= (mantissa & 0x3FFu);\n"
" }\n"
" else if (exponent > 15)\n"
" {\n"
" // Overflow - flush to Infinity\n"
" f16 = sign | (0x1Fu << 10);\n"
" }\n"
" else if (exponent > -15)\n"
" {\n"
" // Representable value\n"
" exponent += 15;\n"
" mantissa >>= 13;\n"
" f16 = sign | uint(exponent << 10) | mantissa;\n"
" }\n"
" else\n"
" {\n"
" f16 = sign;\n"
" }\n"
" return f16;\n"
"}\n"
"\n"
"uint webgl_packHalf2x16_emu(vec2 v)\n"
"{\n"
" uint x = webgl_f32tof16(v.x);\n"
" uint y = webgl_f32tof16(v.y);\n"
" return (y << 16) | x;\n"
"}\n");
emu->addEmulatedFunction(EOpUnpackHalf2x16, uint1,
"float webgl_f16tof32(uint val)\n"
"{\n"
" uint sign = (val & 0x8000u) << 16;\n"
" int exponent = int((val & 0x7C00u) >> 10);\n"
" uint mantissa = val & 0x03FFu;\n"
" float f32 = 0.0;\n"
" if(exponent == 0)\n"
" {\n"
" if (mantissa != 0u)\n"
" {\n"
" const float scale = 1.0 / (1 << 24);\n"
" f32 = scale * mantissa;\n"
" }\n"
" }\n"
" else if (exponent == 31)\n"
" {\n"
" return uintBitsToFloat(sign | 0x7F800000u | mantissa);\n"
" }\n"
" else\n"
" {\n"
" exponent -= 15;\n"
" float scale;\n"
" if(exponent < 0)\n"
" {\n"
" scale = 1.0 / (1 << -exponent);\n"
" }\n"
" else\n"
" {\n"
" scale = 1 << exponent;\n"
" }\n"
" float decimal = 1.0 + float(mantissa) / float(1 << 10);\n"
" f32 = scale * decimal;\n"
" }\n"
"\n"
" if (sign != 0u)\n"
" {\n"
" f32 = -f32;\n"
" }\n"
"\n"
" return f32;\n"
"}\n"
"\n"
"vec2 webgl_unpackHalf2x16_emu(uint u)\n"
"{\n"
" uint y = (u >> 16);\n"
" uint x = u & 0xFFFFu;\n"
" return vec2(webgl_f16tof32(x), webgl_f16tof32(y));\n"
"}\n");
}
}
<commit_msg>Use the type cache for the types used in the emulated GLSL functions.<commit_after>//
// Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "angle_gl.h"
#include "compiler/translator/BuiltInFunctionEmulator.h"
#include "compiler/translator/BuiltInFunctionEmulatorGLSL.h"
#include "compiler/translator/Cache.h"
#include "compiler/translator/SymbolTable.h"
#include "compiler/translator/VersionGLSL.h"
void InitBuiltInFunctionEmulatorForGLSLWorkarounds(BuiltInFunctionEmulator *emu, sh::GLenum shaderType)
{
// we use macros here instead of function definitions to work around more GLSL
// compiler bugs, in particular on NVIDIA hardware on Mac OSX. Macros are
// problematic because if the argument has side-effects they will be repeatedly
// evaluated. This is unlikely to show up in real shaders, but is something to
// consider.
const TType *float1 = TCache::getType(EbtFloat);
const TType *float2 = TCache::getType(EbtFloat, 2);
const TType *float3 = TCache::getType(EbtFloat, 3);
const TType *float4 = TCache::getType(EbtFloat, 4);
if (shaderType == GL_FRAGMENT_SHADER)
{
emu->addEmulatedFunction(EOpCos, float1, "webgl_emu_precision float webgl_cos_emu(webgl_emu_precision float a) { return cos(a); }");
emu->addEmulatedFunction(EOpCos, float2, "webgl_emu_precision vec2 webgl_cos_emu(webgl_emu_precision vec2 a) { return cos(a); }");
emu->addEmulatedFunction(EOpCos, float3, "webgl_emu_precision vec3 webgl_cos_emu(webgl_emu_precision vec3 a) { return cos(a); }");
emu->addEmulatedFunction(EOpCos, float4, "webgl_emu_precision vec4 webgl_cos_emu(webgl_emu_precision vec4 a) { return cos(a); }");
}
emu->addEmulatedFunction(EOpDistance, float1, float1, "#define webgl_distance_emu(x, y) ((x) >= (y) ? (x) - (y) : (y) - (x))");
emu->addEmulatedFunction(EOpDot, float1, float1, "#define webgl_dot_emu(x, y) ((x) * (y))");
emu->addEmulatedFunction(EOpLength, float1, "#define webgl_length_emu(x) ((x) >= 0.0 ? (x) : -(x))");
emu->addEmulatedFunction(EOpNormalize, float1, "#define webgl_normalize_emu(x) ((x) == 0.0 ? 0.0 : ((x) > 0.0 ? 1.0 : -1.0))");
emu->addEmulatedFunction(EOpReflect, float1, float1, "#define webgl_reflect_emu(I, N) ((I) - 2.0 * (N) * (I) * (N))");
}
// Emulate built-in functions missing from GLSL 1.30 and higher
void InitBuiltInFunctionEmulatorForGLSLMissingFunctions(BuiltInFunctionEmulator *emu, sh::GLenum shaderType,
int targetGLSLVersion)
{
// Emulate packUnorm2x16 and unpackUnorm2x16 (GLSL 4.10)
if (targetGLSLVersion < GLSL_VERSION_410)
{
const TType *float2 = TCache::getType(EbtFloat, 2);
const TType *uint1 = TCache::getType(EbtUInt);
emu->addEmulatedFunction(EOpPackUnorm2x16, float2,
"uint webgl_packUnorm2x16_emu(vec2 v)\n"
"{\n"
" int x = int(round(clamp(v.x, 0.0, 1.0) * 65535.0));\n"
" int y = int(round(clamp(v.y, 0.0, 1.0) * 65535.0));\n"
" return uint((y << 16) | (x & 0xFFFF));\n"
"}\n");
emu->addEmulatedFunction(EOpUnpackUnorm2x16, uint1,
"vec2 webgl_unpackUnorm2x16_emu(uint u)\n"
"{\n"
" float x = float(u & 0xFFFFu) / 65535.0;\n"
" float y = float(u >> 16) / 65535.0;\n"
" return vec2(x, y);\n"
"}\n");
}
// Emulate packSnorm2x16, packHalf2x16, unpackSnorm2x16, and unpackHalf2x16 (GLSL 4.20)
// by using floatBitsToInt, floatBitsToUint, intBitsToFloat, and uintBitsToFloat (GLSL 3.30).
if (targetGLSLVersion >= GLSL_VERSION_330 && targetGLSLVersion < GLSL_VERSION_420)
{
const TType *float2 = TCache::getType(EbtFloat, 2);
const TType *uint1 = TCache::getType(EbtUInt);
emu->addEmulatedFunction(EOpPackSnorm2x16, float2,
"uint webgl_packSnorm2x16_emu(vec2 v)\n"
"{\n"
" int x = int(round(clamp(v.x, -1.0, 1.0) * 32767.0));\n"
" int y = int(round(clamp(v.y, -1.0, 1.0) * 32767.0));\n"
" return uint((y << 16) | (x & 0xFFFF));\n"
"}\n");
emu->addEmulatedFunction(EOpUnpackSnorm2x16, uint1,
"float webgl_fromSnorm(uint x)\n"
"{\n"
" int xi = (int(x) & 0x7FFF) - (int(x) & 0x8000);\n"
" return clamp(float(xi) / 32767.0, -1.0, 1.0);\n"
"}\n"
"\n"
"vec2 webgl_unpackSnorm2x16_emu(uint u)\n"
"{\n"
" uint y = (u >> 16);\n"
" uint x = u;\n"
" return vec2(webgl_fromSnorm(x), webgl_fromSnorm(y));\n"
"}\n");
// Functions uint webgl_f32tof16(float val) and float webgl_f16tof32(uint val) are
// based on the OpenGL redbook Appendix Session "Floating-Point Formats Used in OpenGL".
emu->addEmulatedFunction(EOpPackHalf2x16, float2,
"uint webgl_f32tof16(float val)\n"
"{\n"
" uint f32 = floatBitsToUint(val);\n"
" uint f16 = 0u;\n"
" uint sign = (f32 >> 16) & 0x8000u;\n"
" int exponent = int((f32 >> 23) & 0xFFu) - 127;\n"
" uint mantissa = f32 & 0x007FFFFFu;\n"
" if (exponent == 128)\n"
" {\n"
" // Infinity or NaN\n"
" // NaN bits that are masked out by 0x3FF get discarded.\n"
" // This can turn some NaNs to infinity, but this is allowed by the spec.\n"
" f16 = sign | (0x1Fu << 10);\n"
" f16 |= (mantissa & 0x3FFu);\n"
" }\n"
" else if (exponent > 15)\n"
" {\n"
" // Overflow - flush to Infinity\n"
" f16 = sign | (0x1Fu << 10);\n"
" }\n"
" else if (exponent > -15)\n"
" {\n"
" // Representable value\n"
" exponent += 15;\n"
" mantissa >>= 13;\n"
" f16 = sign | uint(exponent << 10) | mantissa;\n"
" }\n"
" else\n"
" {\n"
" f16 = sign;\n"
" }\n"
" return f16;\n"
"}\n"
"\n"
"uint webgl_packHalf2x16_emu(vec2 v)\n"
"{\n"
" uint x = webgl_f32tof16(v.x);\n"
" uint y = webgl_f32tof16(v.y);\n"
" return (y << 16) | x;\n"
"}\n");
emu->addEmulatedFunction(EOpUnpackHalf2x16, uint1,
"float webgl_f16tof32(uint val)\n"
"{\n"
" uint sign = (val & 0x8000u) << 16;\n"
" int exponent = int((val & 0x7C00u) >> 10);\n"
" uint mantissa = val & 0x03FFu;\n"
" float f32 = 0.0;\n"
" if(exponent == 0)\n"
" {\n"
" if (mantissa != 0u)\n"
" {\n"
" const float scale = 1.0 / (1 << 24);\n"
" f32 = scale * mantissa;\n"
" }\n"
" }\n"
" else if (exponent == 31)\n"
" {\n"
" return uintBitsToFloat(sign | 0x7F800000u | mantissa);\n"
" }\n"
" else\n"
" {\n"
" exponent -= 15;\n"
" float scale;\n"
" if(exponent < 0)\n"
" {\n"
" scale = 1.0 / (1 << -exponent);\n"
" }\n"
" else\n"
" {\n"
" scale = 1 << exponent;\n"
" }\n"
" float decimal = 1.0 + float(mantissa) / float(1 << 10);\n"
" f32 = scale * decimal;\n"
" }\n"
"\n"
" if (sign != 0u)\n"
" {\n"
" f32 = -f32;\n"
" }\n"
"\n"
" return f32;\n"
"}\n"
"\n"
"vec2 webgl_unpackHalf2x16_emu(uint u)\n"
"{\n"
" uint y = (u >> 16);\n"
" uint x = u & 0xFFFFu;\n"
" return vec2(webgl_f16tof32(x), webgl_f16tof32(y));\n"
"}\n");
}
}
<|endoftext|> |
<commit_before>/* 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.
==============================================================================*/
#include <array>
#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/matrix.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
namespace tensorflow {
namespace {
constexpr std::array<DataType, 7> kEinsumTypes = {
{DT_INT32, DT_HALF, DT_BFLOAT16, DT_FLOAT, DT_DOUBLE, DT_COMPLEX64,
DT_COMPLEX128}};
// Kernel which compiles XlaEinsum, an einsum op accepting two inputs.
class XlaEinsumOp : public XlaOpKernel {
public:
explicit XlaEinsumOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("equation", &equation_));
}
~XlaEinsumOp() override = default;
void Compile(XlaOpKernelContext* ctx) override {
xla::XlaOp lhs = ctx->Input(0);
if (equation_.find(',') == equation_.npos) {
ctx->SetOutput(0, xla::Einsum(lhs, equation_));
} else {
xla::XlaOp rhs = ctx->Input(1);
ctx->SetOutput(0, xla::Einsum(lhs, rhs, equation_));
}
}
private:
string equation_;
TF_DISALLOW_COPY_AND_ASSIGN(XlaEinsumOp);
};
REGISTER_XLA_OP(Name("XlaEinsum").TypeConstraint("T", kEinsumTypes),
XlaEinsumOp);
REGISTER_XLA_OP(Name("Einsum").TypeConstraint("T", kEinsumTypes),
MlirXlaOpKernel);
} // namespace
} // namespace tensorflow
<commit_msg>[tf2xla] Add DT_INT64 to kEinsumTypes<commit_after>/* 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.
==============================================================================*/
#include <array>
#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/matrix.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
namespace tensorflow {
namespace {
constexpr std::array<DataType, 9> kEinsumTypes = {
{DT_INT32, DT_INT64, DT_UINT64, DT_HALF, DT_BFLOAT16, DT_FLOAT, DT_DOUBLE,
DT_COMPLEX64, DT_COMPLEX128}};
// Kernel which compiles XlaEinsum, an einsum op accepting two inputs.
class XlaEinsumOp : public XlaOpKernel {
public:
explicit XlaEinsumOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("equation", &equation_));
}
~XlaEinsumOp() override = default;
void Compile(XlaOpKernelContext* ctx) override {
xla::XlaOp lhs = ctx->Input(0);
if (equation_.find(',') == equation_.npos) {
ctx->SetOutput(0, xla::Einsum(lhs, equation_));
} else {
xla::XlaOp rhs = ctx->Input(1);
ctx->SetOutput(0, xla::Einsum(lhs, rhs, equation_));
}
}
private:
string equation_;
TF_DISALLOW_COPY_AND_ASSIGN(XlaEinsumOp);
};
REGISTER_XLA_OP(Name("XlaEinsum").TypeConstraint("T", kEinsumTypes),
XlaEinsumOp);
REGISTER_XLA_OP(Name("Einsum").TypeConstraint("T", kEinsumTypes),
MlirXlaOpKernel);
} // namespace
} // namespace tensorflow
<|endoftext|> |
<commit_before>#include "aquila/global.h"
#include "aquila/source/ArrayData.h"
#include "aquila/transform/Dft.h"
#include <unittestpp.h>
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <vector>
SUITE(Dft)
{
TEST(Delta)
{
const std::size_t SIZE = 8;
Aquila::SampleType testArray[SIZE] = {1, 0, 0, 0, 0, 0, 0, 0};
Aquila::ArrayData<> data(testArray, SIZE, 22050);
Aquila::Dft fft(SIZE);
Aquila::SpectrumType spectrum = fft.fft(data.toArray());
double absSpectrum[SIZE] = {0};
std::transform(std::begin(spectrum), std::end(spectrum), absSpectrum, [] (Aquila::ComplexType x) {
return std::abs(x);
});
double expected[SIZE] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
CHECK_ARRAY_CLOSE(expected, absSpectrum, SIZE, 0.0001);
}
TEST(ConstSignal)
{
const std::size_t SIZE = 8;
Aquila::SampleType testArray[SIZE] = {1, 1, 1, 1, 1, 1, 1, 1};
Aquila::ArrayData<> data(testArray, SIZE, 22050);
Aquila::Dft fft(SIZE);
Aquila::SpectrumType spectrum = fft.fft(data.toArray());
double absSpectrum[SIZE] = {0};
std::transform(std::begin(spectrum), std::end(spectrum), absSpectrum, [] (Aquila::ComplexType x) {
return std::abs(x);
});
double expected[SIZE] = {SIZE * 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
CHECK_ARRAY_CLOSE(expected, absSpectrum, SIZE, 0.0001);
}
TEST(DeltaInverse)
{
const std::size_t SIZE = 8;
Aquila::ComplexType spectrum[SIZE] = {SIZE, 0, 0, 0, 0, 0, 0, 0};
Aquila::SampleType output[SIZE];
Aquila::Dft fft(SIZE);
fft.ifft(spectrum, output);
double expected[SIZE] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
CHECK_ARRAY_CLOSE(expected, output, SIZE, 0.0001);
}
TEST(ConstInverse)
{
const std::size_t SIZE = 8;
Aquila::ComplexType spectrum[SIZE] = {1, 1, 1, 1, 1, 1, 1, 1};
Aquila::SampleType output[SIZE];
Aquila::Dft fft(SIZE);
fft.ifft(spectrum, output);
double expected[SIZE] = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
CHECK_ARRAY_CLOSE(expected, output, SIZE, 0.0001);
}
}
<commit_msg>Updated IDFT tests.<commit_after>#include "aquila/global.h"
#include "aquila/source/ArrayData.h"
#include "aquila/transform/Dft.h"
#include <unittestpp.h>
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <vector>
SUITE(Dft)
{
TEST(Delta)
{
const std::size_t SIZE = 8;
Aquila::SampleType testArray[SIZE] = {1, 0, 0, 0, 0, 0, 0, 0};
Aquila::ArrayData<> data(testArray, SIZE, 22050);
Aquila::Dft fft(SIZE);
Aquila::SpectrumType spectrum = fft.fft(data.toArray());
double absSpectrum[SIZE] = {0};
std::transform(std::begin(spectrum), std::end(spectrum), absSpectrum, [] (Aquila::ComplexType x) {
return std::abs(x);
});
double expected[SIZE] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
CHECK_ARRAY_CLOSE(expected, absSpectrum, SIZE, 0.0001);
}
TEST(ConstSignal)
{
const std::size_t SIZE = 8;
Aquila::SampleType testArray[SIZE] = {1, 1, 1, 1, 1, 1, 1, 1};
Aquila::ArrayData<> data(testArray, SIZE, 22050);
Aquila::Dft fft(SIZE);
Aquila::SpectrumType spectrum = fft.fft(data.toArray());
double absSpectrum[SIZE] = {0};
std::transform(std::begin(spectrum), std::end(spectrum), absSpectrum, [] (Aquila::ComplexType x) {
return std::abs(x);
});
double expected[SIZE] = {SIZE * 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
CHECK_ARRAY_CLOSE(expected, absSpectrum, SIZE, 0.0001);
}
TEST(DeltaInverse)
{
const std::size_t SIZE = 8;
Aquila::ComplexType s[SIZE] = {SIZE, 0, 0, 0, 0, 0, 0, 0};
Aquila::SpectrumType spectrum(s, s + SIZE);
Aquila::SampleType output[SIZE];
Aquila::Dft fft(SIZE);
fft.ifft(spectrum, output);
double expected[SIZE] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
CHECK_ARRAY_CLOSE(expected, output, SIZE, 0.0001);
}
TEST(ConstInverse)
{
const std::size_t SIZE = 8;
Aquila::ComplexType s[SIZE] = {1, 1, 1, 1, 1, 1, 1, 1};
Aquila::SpectrumType spectrum(s, s + SIZE);
Aquila::SampleType output[SIZE];
Aquila::Dft fft(SIZE);
fft.ifft(spectrum, output);
double expected[SIZE] = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
CHECK_ARRAY_CLOSE(expected, output, SIZE, 0.0001);
}
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRasterWidget.h"
SkRasterWidget::SkRasterWidget(SkDebugger *debugger) : QWidget() {
fBitmap.setConfig(SkBitmap::kARGB_8888_Config, 800, 800);
fBitmap.allocPixels();
fBitmap.eraseColor(SK_ColorTRANSPARENT);
fDevice = new SkDevice(fBitmap);
fDebugger = debugger;
fCanvas = new SkCanvas(fDevice);
this->setStyleSheet("QWidget {background-color: white; border: 1px solid #cccccc;}");
}
SkRasterWidget::~SkRasterWidget() {
SkSafeUnref(fCanvas);
SkSafeUnref(fDevice);
}
void SkRasterWidget::resizeEvent(QResizeEvent* event) {
fBitmap.setConfig(SkBitmap::kARGB_8888_Config, event->size().width(), event->size().height());
fBitmap.allocPixels();
fBitmap.eraseColor(SK_ColorTRANSPARENT);
SkSafeUnref(fCanvas);
SkSafeUnref(fDevice);
fDevice = new SkDevice(fBitmap);
fCanvas = new SkCanvas(fDevice);
fDebugger->resize(event->size().width(), event->size().height());
this->update();
}
void SkRasterWidget::paintEvent(QPaintEvent* event) {
if (!this->isHidden()) {
fDebugger->draw(fCanvas);
QPainter painter(this);
QStyleOption opt;
opt.init(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);
QPoint origin(0,0);
QImage image((uchar *)fBitmap.getPixels(), fBitmap.width(),
fBitmap.height(), QImage::Format_ARGB32_Premultiplied);
painter.drawImage(origin, image);
painter.end();
emit drawComplete();
}
}
<commit_msg>fix swapped bitmap channels on Mac for debugger<commit_after>
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRasterWidget.h"
SkRasterWidget::SkRasterWidget(SkDebugger *debugger) : QWidget() {
fBitmap.setConfig(SkBitmap::kARGB_8888_Config, 800, 800);
fBitmap.allocPixels();
fBitmap.eraseColor(SK_ColorTRANSPARENT);
fDevice = new SkDevice(fBitmap);
fDebugger = debugger;
fCanvas = new SkCanvas(fDevice);
this->setStyleSheet("QWidget {background-color: white; border: 1px solid #cccccc;}");
}
SkRasterWidget::~SkRasterWidget() {
SkSafeUnref(fCanvas);
SkSafeUnref(fDevice);
}
void SkRasterWidget::resizeEvent(QResizeEvent* event) {
fBitmap.setConfig(SkBitmap::kARGB_8888_Config, event->size().width(), event->size().height());
fBitmap.allocPixels();
fBitmap.eraseColor(SK_ColorTRANSPARENT);
SkSafeUnref(fCanvas);
SkSafeUnref(fDevice);
fDevice = new SkDevice(fBitmap);
fCanvas = new SkCanvas(fDevice);
fDebugger->resize(event->size().width(), event->size().height());
this->update();
}
void SkRasterWidget::paintEvent(QPaintEvent* event) {
if (!this->isHidden()) {
fDebugger->draw(fCanvas);
QPainter painter(this);
QStyleOption opt;
opt.init(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);
QPoint origin(0,0);
QImage image((uchar *)fBitmap.getPixels(), fBitmap.width(),
fBitmap.height(), QImage::Format_ARGB32_Premultiplied);
#if SK_R32_SHIFT == 0
painter.drawImage(origin, image.rgbSwapped());
#else
painter.drawImage(origin, image);
#endif
painter.end();
emit drawComplete();
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// $Id: testsuite.cpp,v 1.3 2006/11/03 18:03:00 db Exp $
//
// Test suite for Visual Leak Detector
//
////////////////////////////////////////////////////////////////////////////////
#include <cassert>
#include <cstdio>
#include <windows.h>
#include <vld.h>
enum action_e {
a_calloc,
a_comalloc,
a_getprocmalloc,
a_heapalloc,
a_icomalloc,
a_malloc,
a_new,
numactions
};
#define CRTDLLNAME "msvcr80d.dll" // Name of the debug C Runtime Library DLL on this system
#define MAXALLOC 1000 // Maximum number of allocations of each type to perform, per thread
#define MAXBLOCKS (MAXALLOC * numactions) // Total maximum number of allocations, per thread
#define MAXDEPTH 10 // Maximum depth of the allocation call stack
#define MAXSIZE 64 // Maximum block size to allocate
#define MINSIZE 16 // Minimum block size to allocate
#define NUMTHREADS 64 // Number of threads to run simultaneously
#define ONCEINAWHILE 10 // Free a random block approx. once every...
typedef struct blockholder_s {
action_e action;
PVOID block;
BOOL leak;
} blockholder_t;
typedef void* (__cdecl *free_t) (void* mem);
typedef void* (__cdecl *malloc_t) (size_t size);
typedef struct threadcontext_s {
UINT index;
BOOL leaky;
DWORD seed;
BOOL terminated;
} threadcontext_t;
__declspec(thread) blockholder_t blocks [MAXBLOCKS];
__declspec(thread) ULONG counts [numactions] = { 0 };
__declspec(thread) free_t pfree = NULL;
__declspec(thread) IMalloc *imalloc = NULL;
__declspec(thread) malloc_t pmalloc = NULL;
__declspec(thread) HANDLE threadheap;
__declspec(thread) ULONG total_allocs = 0;
ULONG random (ULONG max)
{
FLOAT d;
FLOAT r;
ULONG v;
r = ((FLOAT)rand()) / ((FLOAT)RAND_MAX);
r *= ((FLOAT)max);
d = r - ((ULONG)r);
if (d >= 0.5) {
v = ((ULONG)r) + 1;
}
else {
v = (ULONG)r;
}
return v;
}
VOID allocateblock (action_e action, SIZE_T size)
{
HMODULE crt;
ULONG index;
LPCSTR name;
PVOID *pblock;
HRESULT status;
// Find the first unused index.
for (index = 0; index < MAXBLOCKS; index++) {
if (blocks[index].block == NULL) {
break;
}
}
blocks[index].action = action;
// Now do the randomized allocation.
pblock = &blocks[index].block;
switch (action) {
case a_calloc:
name = "calloc";
*pblock = calloc(1, size);
break;
case a_comalloc:
name = "CoTaskMemAlloc";
*pblock = CoTaskMemAlloc(size);
break;
case a_getprocmalloc:
name = "GetProcAddress";
if (pmalloc == NULL) {
crt = LoadLibrary(CRTDLLNAME);
assert(crt != NULL);
pmalloc = (malloc_t)GetProcAddress(crt, "malloc");
assert(pmalloc != NULL);
}
*pblock = pmalloc(size);
break;
case a_heapalloc:
name = "HeapAlloc";
if (threadheap == NULL) {
threadheap = HeapCreate(0x0, 0, 0);
}
*pblock = HeapAlloc(threadheap, 0x0, size);
break;
case a_icomalloc:
name = "IMalloc";
if (imalloc == NULL) {
status = CoGetMalloc(1, &imalloc);
assert(status == S_OK);
}
*pblock = imalloc->Alloc(size);
break;
case a_malloc:
name = "malloc";
*pblock = malloc(size);
break;
case a_new:
name = "new";
*pblock = new BYTE [size];
break;
default:
assert(FALSE);
}
counts[action]++;
total_allocs++;
strncpy_s((char*)*pblock, size, name, _TRUNCATE);
}
VOID freeblock (ULONG index)
{
PVOID block;
HMODULE crt;
block = blocks[index].block;
switch (blocks[index].action) {
case a_calloc:
free(block);
break;
case a_comalloc:
CoTaskMemFree(block);
break;
case a_getprocmalloc:
if (pfree == NULL) {
crt = GetModuleHandle(CRTDLLNAME);
assert(crt != NULL);
pfree = (free_t)GetProcAddress(crt, "free");
assert(pfree != NULL);
}
pfree(block);
break;
case a_heapalloc:
HeapFree(threadheap, 0x0, block);
break;
case a_icomalloc:
imalloc->Free(block);
break;
case a_malloc:
free(block);
break;
case a_new:
delete [] block;
break;
default:
assert(FALSE);
}
blocks[index].block = NULL;
counts[blocks[index].action]--;
total_allocs--;
}
VOID recursivelyallocate (UINT depth, action_e action, SIZE_T size)
{
if (depth == 0) {
allocateblock(action, size);
}
else {
recursivelyallocate(depth - 1, action, size);
}
}
DWORD __stdcall runtestsuite (LPVOID param)
{
action_e action;
USHORT action_index;
BOOL allocate_more = TRUE;
threadcontext_t *context = (threadcontext_t*)param;
UINT depth;
ULONG index;
BOOL leak_selected;
SIZE_T size;
srand(context->seed);
for (index = 0; index < MAXBLOCKS; index++) {
blocks[index].block = NULL;
blocks[index].leak = FALSE;
}
while (allocate_more == TRUE) {
// Select a random allocation action and a random size.
action = (action_e)random(numactions - 1);
size = random(MAXSIZE);
if (size < MINSIZE) {
size = MINSIZE;
}
if (counts[action] == MAXALLOC) {
// We've done enough of this type of allocation. Select another.
continue;
}
// Allocate a block, using recursion to build up a stack of random
// depth.
depth = random(MAXDEPTH);
recursivelyallocate(depth, action, size);
// Every once in a while, free a random block.
if (random(ONCEINAWHILE) == ONCEINAWHILE) {
index = random(total_allocs);
if (blocks[index].block != NULL) {
freeblock(index);
}
}
// See if we have allocated enough blocks using each type of action.
for (action_index = 0; action_index < numactions; action_index++) {
if (counts[action_index] < MAXALLOC) {
allocate_more = TRUE;
break;
}
allocate_more = FALSE;
}
}
if (context->leaky == TRUE) {
// This is the leaky thread. Randomly select one block to be leaked from
// each type of allocation action.
for (action_index = 0; action_index < numactions; action_index++) {
leak_selected = FALSE;
do {
index = random(MAXBLOCKS);
if ((blocks[index].block != NULL) && (blocks[index].action == (action_e)action_index)) {
blocks[index].leak = TRUE;
leak_selected = TRUE;
}
} while (leak_selected == FALSE);
}
}
// Free all blocks except for those marked as leaks.
for (index = 0; index < MAXBLOCKS; index++) {
if ((blocks[index].block != NULL) && (blocks[index].leak == FALSE)) {
freeblock(index);
}
}
// Do a sanity check.
if (context->leaky == TRUE) {
assert(total_allocs == numactions);
}
else {
assert(total_allocs == 0);
}
context->terminated = TRUE;
return 0;
}
int main (int argc, char *argv [])
{
threadcontext_t contexts [NUMTHREADS];
DWORD end;
UINT index;
#define MESSAGESIZE 512
char message [512];
DWORD start;
UINT leakythread;
start = GetTickCount();
srand(start);
// Select a random thread to be the leaker.
leakythread = random(NUMTHREADS - 1);
for (index = 0; index < NUMTHREADS; ++index) {
contexts[index].index = index;
if (index == leakythread) {
contexts[index].leaky = TRUE;
}
contexts[index].seed = random(RAND_MAX);
contexts[index].terminated = FALSE;
CreateThread(NULL, 0, runtestsuite, &contexts[index], 0, NULL);
}
// Wait for all threads to terminate.
for (index = 0; index < NUMTHREADS; ++index) {
while (contexts[index].terminated == FALSE) {
Sleep(10);
}
}
end = GetTickCount();
_snprintf_s(message, 512, _TRUNCATE, "Elapsed Time = %ums\n", end - start);
OutputDebugString(message);
return 0;
}
<commit_msg>Added the thread ID to each thread's context structure.<commit_after>////////////////////////////////////////////////////////////////////////////////
// $Id: testsuite.cpp,v 1.4 2006/11/05 21:05:32 dmouldin Exp $
//
// Test suite for Visual Leak Detector
//
////////////////////////////////////////////////////////////////////////////////
#include <cassert>
#include <cstdio>
#include <windows.h>
#include <vld.h>
enum action_e {
a_calloc,
a_comalloc,
a_getprocmalloc,
a_heapalloc,
a_icomalloc,
a_malloc,
a_new,
numactions
};
#define CRTDLLNAME "msvcr80d.dll" // Name of the debug C Runtime Library DLL on this system
#define MAXALLOC 1000 // Maximum number of allocations of each type to perform, per thread
#define MAXBLOCKS (MAXALLOC * numactions) // Total maximum number of allocations, per thread
#define MAXDEPTH 32 // Maximum depth of the allocation call stack
#define MAXSIZE 64 // Maximum block size to allocate
#define MINSIZE 16 // Minimum block size to allocate
#define NUMTHREADS 64 // Number of threads to run simultaneously
#define ONCEINAWHILE 10 // Free a random block approx. once every...
typedef struct blockholder_s {
action_e action;
PVOID block;
BOOL leak;
} blockholder_t;
typedef void* (__cdecl *free_t) (void* mem);
typedef void* (__cdecl *malloc_t) (size_t size);
typedef struct threadcontext_s {
UINT index;
BOOL leaky;
DWORD seed;
BOOL terminated;
DWORD threadid;
} threadcontext_t;
__declspec(thread) blockholder_t blocks [MAXBLOCKS];
__declspec(thread) ULONG counts [numactions] = { 0 };
__declspec(thread) free_t pfree = NULL;
__declspec(thread) IMalloc *imalloc = NULL;
__declspec(thread) malloc_t pmalloc = NULL;
__declspec(thread) HANDLE threadheap;
__declspec(thread) ULONG total_allocs = 0;
ULONG random (ULONG max)
{
FLOAT d;
FLOAT r;
ULONG v;
r = ((FLOAT)rand()) / ((FLOAT)RAND_MAX);
r *= ((FLOAT)max);
d = r - ((ULONG)r);
if (d >= 0.5) {
v = ((ULONG)r) + 1;
}
else {
v = (ULONG)r;
}
return v;
}
VOID allocateblock (action_e action, SIZE_T size)
{
HMODULE crt;
ULONG index;
LPCSTR name;
PVOID *pblock;
HRESULT status;
// Find the first unused index.
for (index = 0; index < MAXBLOCKS; index++) {
if (blocks[index].block == NULL) {
break;
}
}
blocks[index].action = action;
// Now do the randomized allocation.
pblock = &blocks[index].block;
switch (action) {
case a_calloc:
name = "calloc";
*pblock = calloc(1, size);
break;
case a_comalloc:
name = "CoTaskMemAlloc";
*pblock = CoTaskMemAlloc(size);
break;
case a_getprocmalloc:
name = "GetProcAddress";
if (pmalloc == NULL) {
crt = LoadLibrary(CRTDLLNAME);
assert(crt != NULL);
pmalloc = (malloc_t)GetProcAddress(crt, "malloc");
assert(pmalloc != NULL);
}
*pblock = pmalloc(size);
break;
case a_heapalloc:
name = "HeapAlloc";
if (threadheap == NULL) {
threadheap = HeapCreate(0x0, 0, 0);
}
*pblock = HeapAlloc(threadheap, 0x0, size);
break;
case a_icomalloc:
name = "IMalloc";
if (imalloc == NULL) {
status = CoGetMalloc(1, &imalloc);
assert(status == S_OK);
}
*pblock = imalloc->Alloc(size);
break;
case a_malloc:
name = "malloc";
*pblock = malloc(size);
break;
case a_new:
name = "new";
*pblock = new BYTE [size];
break;
default:
assert(FALSE);
}
counts[action]++;
total_allocs++;
strncpy_s((char*)*pblock, size, name, _TRUNCATE);
}
VOID freeblock (ULONG index)
{
PVOID block;
HMODULE crt;
block = blocks[index].block;
switch (blocks[index].action) {
case a_calloc:
free(block);
break;
case a_comalloc:
CoTaskMemFree(block);
break;
case a_getprocmalloc:
if (pfree == NULL) {
crt = GetModuleHandle(CRTDLLNAME);
assert(crt != NULL);
pfree = (free_t)GetProcAddress(crt, "free");
assert(pfree != NULL);
}
pfree(block);
break;
case a_heapalloc:
HeapFree(threadheap, 0x0, block);
break;
case a_icomalloc:
imalloc->Free(block);
break;
case a_malloc:
free(block);
break;
case a_new:
delete [] block;
break;
default:
assert(FALSE);
}
blocks[index].block = NULL;
counts[blocks[index].action]--;
total_allocs--;
}
VOID recursivelyallocate (UINT depth, action_e action, SIZE_T size)
{
if (depth == 0) {
allocateblock(action, size);
}
else {
recursivelyallocate(depth - 1, action, size);
}
}
DWORD __stdcall runtestsuite (LPVOID param)
{
action_e action;
USHORT action_index;
BOOL allocate_more = TRUE;
threadcontext_t *context = (threadcontext_t*)param;
UINT depth;
ULONG index;
BOOL leak_selected;
SIZE_T size;
srand(context->seed);
for (index = 0; index < MAXBLOCKS; index++) {
blocks[index].block = NULL;
blocks[index].leak = FALSE;
}
while (allocate_more == TRUE) {
// Select a random allocation action and a random size.
action = (action_e)random(numactions - 1);
size = random(MAXSIZE);
if (size < MINSIZE) {
size = MINSIZE;
}
if (counts[action] == MAXALLOC) {
// We've done enough of this type of allocation. Select another.
continue;
}
// Allocate a block, using recursion to build up a stack of random
// depth.
depth = random(MAXDEPTH);
recursivelyallocate(depth, action, size);
// Every once in a while, free a random block.
if (random(ONCEINAWHILE) == ONCEINAWHILE) {
index = random(total_allocs);
if (blocks[index].block != NULL) {
freeblock(index);
}
}
// See if we have allocated enough blocks using each type of action.
for (action_index = 0; action_index < numactions; action_index++) {
if (counts[action_index] < MAXALLOC) {
allocate_more = TRUE;
break;
}
allocate_more = FALSE;
}
}
if (context->leaky == TRUE) {
// This is the leaky thread. Randomly select one block to be leaked from
// each type of allocation action.
for (action_index = 0; action_index < numactions; action_index++) {
leak_selected = FALSE;
do {
index = random(MAXBLOCKS);
if ((blocks[index].block != NULL) && (blocks[index].action == (action_e)action_index)) {
blocks[index].leak = TRUE;
leak_selected = TRUE;
}
} while (leak_selected == FALSE);
}
}
// Free all blocks except for those marked as leaks.
for (index = 0; index < MAXBLOCKS; index++) {
if ((blocks[index].block != NULL) && (blocks[index].leak == FALSE)) {
freeblock(index);
}
}
// Do a sanity check.
if (context->leaky == TRUE) {
assert(total_allocs == numactions);
}
else {
assert(total_allocs == 0);
}
context->terminated = TRUE;
return 0;
}
int main (int argc, char *argv [])
{
threadcontext_t contexts [NUMTHREADS];
DWORD end;
UINT index;
#define MESSAGESIZE 512
char message [512];
DWORD start;
UINT leakythread;
start = GetTickCount();
srand(start);
// Select a random thread to be the leaker.
leakythread = random(NUMTHREADS - 1);
for (index = 0; index < NUMTHREADS; ++index) {
contexts[index].index = index;
if (index == leakythread) {
contexts[index].leaky = TRUE;
}
contexts[index].seed = random(RAND_MAX);
contexts[index].terminated = FALSE;
CreateThread(NULL, 0, runtestsuite, &contexts[index], 0, &contexts[index].threadid);
}
// Wait for all threads to terminate.
for (index = 0; index < NUMTHREADS; ++index) {
while (contexts[index].terminated == FALSE) {
Sleep(10);
}
}
end = GetTickCount();
_snprintf_s(message, 512, _TRUNCATE, "Elapsed Time = %ums\n", end - start);
OutputDebugString(message);
return 0;
}
<|endoftext|> |
<commit_before>/*===================================================================
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 "QmitkTransferFunctionCanvas.h"
#include <itkObject.h>
#include <QColorDialog>
#include <QPainter>
#include <QMouseEvent>
QmitkTransferFunctionCanvas::QmitkTransferFunctionCanvas(QWidget * parent,
Qt::WindowFlags f) :
QWidget(parent, f), m_GrabbedHandle(-1), m_Lower(0.0f), m_Upper(1.0f), m_Min(
0.0f), m_Max(1.0f)
{
setEnabled(false);
setFocusPolicy(Qt::ClickFocus);
m_LineEditAvailable = false;
}
void QmitkTransferFunctionCanvas::paintEvent(QPaintEvent* ev)
{
QWidget::paintEvent(ev);
}
std::pair<int,int> QmitkTransferFunctionCanvas::FunctionToCanvas(
std::pair<vtkFloatingPointType,vtkFloatingPointType> functionPoint)
{
//std::cout<<"F2C.first: "<<(int)((functionPoint.first - m_Lower) / (m_Upper - m_Lower) * width())<<" F2C.second: "<<(int)(height() * (1 - functionPoint.second))<<std::endl;
return std::make_pair((int) ((functionPoint.first - m_Lower) / (m_Upper
- m_Lower) * contentsRect().width()) + contentsRect().x(), (int) (contentsRect().height() * (1 - functionPoint.second)) + contentsRect().y());
}
std::pair<vtkFloatingPointType,vtkFloatingPointType> QmitkTransferFunctionCanvas::CanvasToFunction(
std::pair<int,int> canvasPoint)
{
//std::cout<<"C2F.first: "<<(canvasPoint.first * (m_Upper - m_Lower) / width() + m_Lower)<<" C2F.second: "<<(1.0 - (vtkFloatingPointType)canvasPoint.second / height())<<std::endl;
return std::make_pair((canvasPoint.first - contentsRect().x()) * (m_Upper - m_Lower) / contentsRect().width()
+ m_Lower, 1.0 - (vtkFloatingPointType) (canvasPoint.second - contentsRect().y()) / contentsRect().height());
}
void QmitkTransferFunctionCanvas::mouseDoubleClickEvent(QMouseEvent* mouseEvent)
{
int nearHandle = GetNearHandle(mouseEvent->pos().x(), mouseEvent->pos().y());
if (nearHandle != -1)
{
this->DoubleClickOnHandle(nearHandle);
}
}
/** returns index of a near handle or -1 if none is near
*/
int QmitkTransferFunctionCanvas::GetNearHandle(int /*x*/, int /*y*/,
unsigned int /*maxSquaredDistance*/)
{
return -1;
}
void QmitkTransferFunctionCanvas::mousePressEvent(QMouseEvent* mouseEvent)
{
if (m_LineEditAvailable)
{
m_XEdit->clear();
if(m_YEdit)
m_YEdit->clear();
}
m_GrabbedHandle = GetNearHandle(mouseEvent->pos().x(), mouseEvent->pos().y());
if ( (mouseEvent->button() & Qt::LeftButton) && m_GrabbedHandle == -1)
{
this->AddFunctionPoint(
this->CanvasToFunction(std::make_pair(mouseEvent->pos().x(),
mouseEvent->pos().y())).first,
this->CanvasToFunction(std::make_pair(mouseEvent->x(), mouseEvent->y())).second);
m_GrabbedHandle = GetNearHandle(mouseEvent->pos().x(),
mouseEvent->pos().y());
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if ((mouseEvent->button() & Qt::RightButton) && m_GrabbedHandle != -1 && this->GetFunctionSize() > 1)
{
this->RemoveFunctionPoint(this->GetFunctionX(m_GrabbedHandle));
m_GrabbedHandle = -1;
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
update();
// m_TransferFunction->UpdateVtkFunctions();
}
void QmitkTransferFunctionCanvas::mouseMoveEvent(QMouseEvent* mouseEvent)
{
if (m_GrabbedHandle != -1)
{
std::pair<vtkFloatingPointType,vtkFloatingPointType>
newPos = this->CanvasToFunction(std::make_pair(mouseEvent->x(),
mouseEvent->y()));
// X Clamping
{
// Check with predecessor
if( m_GrabbedHandle > 0 )
if (newPos.first <= this->GetFunctionX(m_GrabbedHandle - 1))
newPos.first = this->GetFunctionX(m_GrabbedHandle);
// Check with sucessor
if( m_GrabbedHandle < this->GetFunctionSize()-1 )
if (newPos.first >= this->GetFunctionX(m_GrabbedHandle + 1))
newPos.first = this->GetFunctionX(m_GrabbedHandle);
// Clamping to histogramm
if (newPos.first < m_Min) newPos.first = m_Min;
else if (newPos.first > m_Max) newPos.first = m_Max;
}
// Y Clamping
{
if (newPos.second < 0.0) newPos.second = 0.0;
else if (newPos.second > 1.0) newPos.second = 1.0;
}
// Move selected point
this->MoveFunctionPoint(m_GrabbedHandle, newPos);
/*
// Search again selected point ??????? should not be required, seems like a legacy workaround/bugfix
// and no longer required
m_GrabbedHandle = -1;
for (int i = 0; i < this->GetFunctionSize(); i++)
{
if (this->GetFunctionX(i) == newPos.first)
{
m_GrabbedHandle = i;
break;
}
}
*/
update();
//if (m_ImmediateUpdate)
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkTransferFunctionCanvas::mouseReleaseEvent(QMouseEvent*)
{
// m_GrabbedHandle = -1;
update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkTransferFunctionCanvas::PaintHistogram(QPainter &p)
{
if(m_Histogram)
{
p.save();
p.setPen(Qt::gray);
int displayWidth = contentsRect().width();
int displayHeight = contentsRect().height();
double windowLeft = m_Lower;
double windowRight = m_Upper;
double step = (windowRight-windowLeft)/double(displayWidth);
double pos = windowLeft;
for (int x = 0; x < displayWidth; x++)
{
double left = pos;
double right = pos + step;
float height = m_Histogram->GetRelativeBin( left , right );
if (height >= 0)
p.drawLine(x, displayHeight*(1-height), x, displayHeight);
pos += step;
}
p.restore();
}
}
void QmitkTransferFunctionCanvas::keyPressEvent(QKeyEvent * e)
{
if( m_GrabbedHandle == -1)
return;
switch(e->key())
{
case Qt::Key_Delete:
if(this->GetFunctionSize() > 1)
{
this->RemoveFunctionPoint(GetFunctionX(m_GrabbedHandle));
m_GrabbedHandle = -1;
}
break;
case Qt::Key_Left:
this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle)-1 , GetFunctionY(m_GrabbedHandle))));
break;
case Qt::Key_Right:
this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle)+1 , GetFunctionY(m_GrabbedHandle))));
break;
case Qt::Key_Up:
this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle) , GetFunctionY(m_GrabbedHandle)+0.001)));
break;
case Qt::Key_Down:
this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle) , GetFunctionY(m_GrabbedHandle)-0.001)));
break;
}
update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
// Update immediatly while changing the transfer function
void QmitkTransferFunctionCanvas::SetImmediateUpdate(bool state)
{
m_ImmediateUpdate = state;
}
<commit_msg>Data members initialised in QmitkTransferFunctionCanvas constructor<commit_after>/*===================================================================
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 "QmitkTransferFunctionCanvas.h"
#include <itkObject.h>
#include <QColorDialog>
#include <QPainter>
#include <QMouseEvent>
QmitkTransferFunctionCanvas::QmitkTransferFunctionCanvas(QWidget * parent,
Qt::WindowFlags f) :
QWidget(parent, f),
m_GrabbedHandle(-1),
m_Lower(0.0),
m_Upper(1.0),
m_Min(0.0),
m_Max(1.0),
m_Histogram(0),
m_ImmediateUpdate(false),
m_Range(0.0f),
m_LineEditAvailable(false),
m_XEdit(0),
m_YEdit(0)
{
setEnabled(false);
setFocusPolicy(Qt::ClickFocus);
}
void QmitkTransferFunctionCanvas::paintEvent(QPaintEvent* ev)
{
QWidget::paintEvent(ev);
}
std::pair<int,int> QmitkTransferFunctionCanvas::FunctionToCanvas(
std::pair<vtkFloatingPointType,vtkFloatingPointType> functionPoint)
{
//std::cout<<"F2C.first: "<<(int)((functionPoint.first - m_Lower) / (m_Upper - m_Lower) * width())<<" F2C.second: "<<(int)(height() * (1 - functionPoint.second))<<std::endl;
return std::make_pair((int) ((functionPoint.first - m_Lower) / (m_Upper
- m_Lower) * contentsRect().width()) + contentsRect().x(), (int) (contentsRect().height() * (1 - functionPoint.second)) + contentsRect().y());
}
std::pair<vtkFloatingPointType,vtkFloatingPointType> QmitkTransferFunctionCanvas::CanvasToFunction(
std::pair<int,int> canvasPoint)
{
//std::cout<<"C2F.first: "<<(canvasPoint.first * (m_Upper - m_Lower) / width() + m_Lower)<<" C2F.second: "<<(1.0 - (vtkFloatingPointType)canvasPoint.second / height())<<std::endl;
return std::make_pair((canvasPoint.first - contentsRect().x()) * (m_Upper - m_Lower) / contentsRect().width()
+ m_Lower, 1.0 - (vtkFloatingPointType) (canvasPoint.second - contentsRect().y()) / contentsRect().height());
}
void QmitkTransferFunctionCanvas::mouseDoubleClickEvent(QMouseEvent* mouseEvent)
{
int nearHandle = GetNearHandle(mouseEvent->pos().x(), mouseEvent->pos().y());
if (nearHandle != -1)
{
this->DoubleClickOnHandle(nearHandle);
}
}
/** returns index of a near handle or -1 if none is near
*/
int QmitkTransferFunctionCanvas::GetNearHandle(int /*x*/, int /*y*/,
unsigned int /*maxSquaredDistance*/)
{
return -1;
}
void QmitkTransferFunctionCanvas::mousePressEvent(QMouseEvent* mouseEvent)
{
if (m_LineEditAvailable)
{
m_XEdit->clear();
if(m_YEdit)
m_YEdit->clear();
}
m_GrabbedHandle = GetNearHandle(mouseEvent->pos().x(), mouseEvent->pos().y());
if ( (mouseEvent->button() & Qt::LeftButton) && m_GrabbedHandle == -1)
{
this->AddFunctionPoint(
this->CanvasToFunction(std::make_pair(mouseEvent->pos().x(),
mouseEvent->pos().y())).first,
this->CanvasToFunction(std::make_pair(mouseEvent->x(), mouseEvent->y())).second);
m_GrabbedHandle = GetNearHandle(mouseEvent->pos().x(),
mouseEvent->pos().y());
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if ((mouseEvent->button() & Qt::RightButton) && m_GrabbedHandle != -1 && this->GetFunctionSize() > 1)
{
this->RemoveFunctionPoint(this->GetFunctionX(m_GrabbedHandle));
m_GrabbedHandle = -1;
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
update();
// m_TransferFunction->UpdateVtkFunctions();
}
void QmitkTransferFunctionCanvas::mouseMoveEvent(QMouseEvent* mouseEvent)
{
if (m_GrabbedHandle != -1)
{
std::pair<vtkFloatingPointType,vtkFloatingPointType>
newPos = this->CanvasToFunction(std::make_pair(mouseEvent->x(),
mouseEvent->y()));
// X Clamping
{
// Check with predecessor
if( m_GrabbedHandle > 0 )
if (newPos.first <= this->GetFunctionX(m_GrabbedHandle - 1))
newPos.first = this->GetFunctionX(m_GrabbedHandle);
// Check with sucessor
if( m_GrabbedHandle < this->GetFunctionSize()-1 )
if (newPos.first >= this->GetFunctionX(m_GrabbedHandle + 1))
newPos.first = this->GetFunctionX(m_GrabbedHandle);
// Clamping to histogramm
if (newPos.first < m_Min) newPos.first = m_Min;
else if (newPos.first > m_Max) newPos.first = m_Max;
}
// Y Clamping
{
if (newPos.second < 0.0) newPos.second = 0.0;
else if (newPos.second > 1.0) newPos.second = 1.0;
}
// Move selected point
this->MoveFunctionPoint(m_GrabbedHandle, newPos);
/*
// Search again selected point ??????? should not be required, seems like a legacy workaround/bugfix
// and no longer required
m_GrabbedHandle = -1;
for (int i = 0; i < this->GetFunctionSize(); i++)
{
if (this->GetFunctionX(i) == newPos.first)
{
m_GrabbedHandle = i;
break;
}
}
*/
update();
//if (m_ImmediateUpdate)
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkTransferFunctionCanvas::mouseReleaseEvent(QMouseEvent*)
{
// m_GrabbedHandle = -1;
update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkTransferFunctionCanvas::PaintHistogram(QPainter &p)
{
if(m_Histogram)
{
p.save();
p.setPen(Qt::gray);
int displayWidth = contentsRect().width();
int displayHeight = contentsRect().height();
double windowLeft = m_Lower;
double windowRight = m_Upper;
double step = (windowRight-windowLeft)/double(displayWidth);
double pos = windowLeft;
for (int x = 0; x < displayWidth; x++)
{
double left = pos;
double right = pos + step;
float height = m_Histogram->GetRelativeBin( left , right );
if (height >= 0)
p.drawLine(x, displayHeight*(1-height), x, displayHeight);
pos += step;
}
p.restore();
}
}
void QmitkTransferFunctionCanvas::keyPressEvent(QKeyEvent * e)
{
if( m_GrabbedHandle == -1)
return;
switch(e->key())
{
case Qt::Key_Delete:
if(this->GetFunctionSize() > 1)
{
this->RemoveFunctionPoint(GetFunctionX(m_GrabbedHandle));
m_GrabbedHandle = -1;
}
break;
case Qt::Key_Left:
this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle)-1 , GetFunctionY(m_GrabbedHandle))));
break;
case Qt::Key_Right:
this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle)+1 , GetFunctionY(m_GrabbedHandle))));
break;
case Qt::Key_Up:
this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle) , GetFunctionY(m_GrabbedHandle)+0.001)));
break;
case Qt::Key_Down:
this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle) , GetFunctionY(m_GrabbedHandle)-0.001)));
break;
}
update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
// Update immediatly while changing the transfer function
void QmitkTransferFunctionCanvas::SetImmediateUpdate(bool state)
{
m_ImmediateUpdate = state;
}
<|endoftext|> |
<commit_before>/*
* writer.cpp
*
* Created on: Nov 26, 2012
* Author: partio
*/
#include "writer.h"
#include "plugin_factory.h"
#include "logger_factory.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
#include "util.h"
#include "timer_factory.h"
#define HIMAN_AUXILIARY_INCLUDE
#include "grib.h"
#include "querydata.h"
#include "neons.h"
#undef HIMAN_AUXILIARY_INCLUDE
using namespace himan::plugin;
writer::writer()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("writer"));
}
bool writer::ToFile(std::shared_ptr<info> theInfo,
std::shared_ptr<const plugin_configuration> conf,
const std::string& theOutputFile)
{
std::unique_ptr<himan::timer> t = std::unique_ptr<himan::timer> (timer_factory::Instance()->GetTimer());
if (conf->StatisticsEnabled())
{
t->Start();
}
namespace fs = boost::filesystem;
bool ret = false;
std::string correctFileName = theOutputFile;
HPFileWriteOption fileWriteOption = conf->FileWriteOption();
HPFileType fileType = conf->OutputFileType();
if ((fileWriteOption == kNeons || fileWriteOption == kMultipleFiles) || correctFileName.empty())
{
correctFileName = util::MakeFileName(fileWriteOption, theInfo);
}
fs::path pathname(correctFileName);
if (!pathname.parent_path().empty() && !fs::is_directory(pathname.parent_path()))
{
fs::create_directories(pathname.parent_path());
}
switch (fileType)
{
case kGRIB:
case kGRIB1:
case kGRIB2:
{
std::shared_ptr<grib> theGribWriter = std::dynamic_pointer_cast<grib> (plugin_factory::Instance()->Plugin("grib"));
correctFileName += ".grib";
if (fileType == kGRIB2)
{
correctFileName += "2";
}
ret = theGribWriter->ToFile(theInfo, correctFileName, fileType, fileWriteOption);
break;
}
case kQueryData:
{
std::shared_ptr<querydata> theWriter = std::dynamic_pointer_cast<querydata> (plugin_factory::Instance()->Plugin("querydata"));
correctFileName += ".fqd";
ret = theWriter->ToFile(theInfo, correctFileName, fileWriteOption);
break;
}
case kNetCDF:
break;
// Must have this or compiler complains
default:
throw std::runtime_error(ClassName() + ": Invalid file type: " + HPFileTypeToString.at(fileType));
break;
}
if (ret && fileWriteOption == kNeons)
{
std::shared_ptr<neons> n = std::dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons"));
// Save file information to neons
ret = n->Save(theInfo, correctFileName);
if (!ret)
{
itsLogger->Warning("Saving file information to neons failed");
// unlink(correctFileName.c_str());
}
}
if (conf->StatisticsEnabled())
{
t->Stop();
conf->Statistics()->AddToWritingTime(t->GetTime());
}
return ret;
}
<commit_msg>Writing results to cache and clearing grid contents if cache is not used<commit_after>/*
* writer.cpp
*
* Created on: Nov 26, 2012
* Author: partio
*/
#include "writer.h"
#include "plugin_factory.h"
#include "logger_factory.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
#include "util.h"
#include "timer_factory.h"
#define HIMAN_AUXILIARY_INCLUDE
#include "grib.h"
#include "querydata.h"
#include "neons.h"
#include "cache.h"
#undef HIMAN_AUXILIARY_INCLUDE
using namespace himan::plugin;
writer::writer()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("writer"));
}
bool writer::ToFile(std::shared_ptr<info> theInfo,
std::shared_ptr<const plugin_configuration> conf,
const std::string& theOutputFile)
{
std::unique_ptr<himan::timer> t = std::unique_ptr<himan::timer> (timer_factory::Instance()->GetTimer());
if (conf->StatisticsEnabled())
{
t->Start();
}
std::shared_ptr<cache> c = std::dynamic_pointer_cast<plugin::cache> (plugin_factory::Instance()->Plugin("cache"));
bool activeOnly = (conf->FileWriteOption() == kSingleFile) ? false : true;
if (conf->UseCache())
{
c->Insert(theInfo, activeOnly);
}
namespace fs = boost::filesystem;
bool ret = false;
std::string correctFileName = theOutputFile;
HPFileWriteOption fileWriteOption = conf->FileWriteOption();
HPFileType fileType = conf->OutputFileType();
if ((fileWriteOption == kNeons || fileWriteOption == kMultipleFiles) || correctFileName.empty())
{
correctFileName = util::MakeFileName(fileWriteOption, theInfo);
}
fs::path pathname(correctFileName);
if (!pathname.parent_path().empty() && !fs::is_directory(pathname.parent_path()))
{
fs::create_directories(pathname.parent_path());
}
switch (fileType)
{
case kGRIB:
case kGRIB1:
case kGRIB2:
{
std::shared_ptr<grib> theGribWriter = std::dynamic_pointer_cast<grib> (plugin_factory::Instance()->Plugin("grib"));
correctFileName += ".grib";
if (fileType == kGRIB2)
{
correctFileName += "2";
}
ret = theGribWriter->ToFile(theInfo, correctFileName, fileType, fileWriteOption);
break;
}
case kQueryData:
{
std::shared_ptr<querydata> theWriter = std::dynamic_pointer_cast<querydata> (plugin_factory::Instance()->Plugin("querydata"));
correctFileName += ".fqd";
ret = theWriter->ToFile(theInfo, correctFileName, fileWriteOption);
break;
}
case kNetCDF:
break;
// Must have this or compiler complains
default:
throw std::runtime_error(ClassName() + ": Invalid file type: " + HPFileTypeToString.at(fileType));
break;
}
if (ret && fileWriteOption == kNeons)
{
std::shared_ptr<neons> n = std::dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons"));
// Save file information to neons
ret = n->Save(theInfo, correctFileName);
if (!ret)
{
itsLogger->Warning("Saving file information to neons failed");
// unlink(correctFileName.c_str());
}
}
if (!conf->UseCache())
{
theInfo->Grid()->Data()->Clear();
}
if (conf->StatisticsEnabled())
{
t->Stop();
conf->Statistics()->AddToWritingTime(t->GetTime());
}
return ret;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
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 "ArgParse.h"
#include "LLVMCompat.h"
#include "llvm/Support/Path.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Frontend/CompilerInstance.h"
const std::string sHipify = "[HIPIFY] ", sConflict = "conflict: ", sError = "error: ", sWarning = "warning: ";
namespace llcompat {
void PrintStackTraceOnErrorSignal() {
// The signature of PrintStackTraceOnErrorSignal changed in llvm 3.9. We don't support
// anything older than 3.8, so let's specifically detect the one old version we support.
#if (LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR == 8)
llvm::sys::PrintStackTraceOnErrorSignal();
#else
llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
#endif
}
ct::Replacements &getReplacements(ct::RefactoringTool &Tool, StringRef file) {
#if LLVM_VERSION_MAJOR > 3
// getReplacements() now returns a map from filename to Replacements - so create an entry
// for this source file and return a reference to it.
return Tool.getReplacements()[file];
#else
return Tool.getReplacements();
#endif
}
void insertReplacement(ct::Replacements &replacements, const ct::Replacement &rep) {
#if LLVM_VERSION_MAJOR > 3
// New clang added error checking to Replacements, and *insists* that you explicitly check it.
llvm::consumeError(replacements.add(rep));
#else
// In older versions, it's literally an std::set<Replacement>
replacements.insert(rep);
#endif
}
void EnterPreprocessorTokenStream(clang::Preprocessor &_pp, const clang::Token *start, size_t len, bool DisableMacroExpansion) {
#if (LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR == 8)
_pp.EnterTokenStream(start, len, false, DisableMacroExpansion);
#else
#if (LLVM_VERSION_MAJOR < 9)
_pp.EnterTokenStream(clang::ArrayRef<clang::Token>{start, len}, DisableMacroExpansion);
#else
_pp.EnterTokenStream(clang::ArrayRef<clang::Token>{start, len}, DisableMacroExpansion, false);
#endif
#endif
}
clang::SourceLocation getBeginLoc(const clang::Stmt *stmt) {
#if LLVM_VERSION_MAJOR < 8
return stmt->getLocStart();
#else
return stmt->getBeginLoc();
#endif
}
clang::SourceLocation getBeginLoc(const clang::TypeLoc &typeLoc) {
#if LLVM_VERSION_MAJOR < 8
return typeLoc.getLocStart();
#else
return typeLoc.getBeginLoc();
#endif
}
clang::SourceLocation getEndLoc(const clang::Stmt *stmt) {
#if LLVM_VERSION_MAJOR < 8
return stmt->getLocEnd();
#else
return stmt->getEndLoc();
#endif
}
clang::SourceLocation getEndLoc(const clang::TypeLoc &typeLoc) {
#if LLVM_VERSION_MAJOR < 8
return typeLoc.getLocEnd();
#else
return typeLoc.getEndLoc();
#endif
}
std::error_code real_path(const Twine &path, SmallVectorImpl<char> &output,
bool expand_tilde) {
#if LLVM_VERSION_MAJOR < 5
output.clear();
std::string s = path.str();
output.append(s.begin(), s.end());
if (sys::path::is_relative(path)) {
return sys::fs::make_absolute(output);
}
return std::error_code();
#else
return sys::fs::real_path(path, output, expand_tilde);
#endif
}
bool pragma_once_outside_header() {
#if LLVM_VERSION_MAJOR < 4
return false;
#else
return true;
#endif
}
bool canCompileHostAndDeviceInOneJob() {
#if LLVM_VERSION_MAJOR >= 9 && defined(_WIN32)
return true;
#else
return false;
#endif
}
void RetainExcludedConditionalBlocks(clang::CompilerInstance &CI) {
#if LLVM_VERSION_MAJOR > 9
clang::PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
PPOpts.RetainExcludedConditionalBlocks = !SkipExcludedPPConditionalBlocks;
#endif
}
bool CheckCompatibility() {
#if LLVM_VERSION_MAJOR < 10
if (SkipExcludedPPConditionalBlocks) {
llvm::errs() << "\n" << sHipify << sWarning << "Option '" << SkipExcludedPPConditionalBlocks.ArgStr.str() << "' is supported starting from LLVM version 10.0\n";
}
#endif
return true;
}
clang::SourceLocation getEndOfExpansionRangeForLoc(const clang::SourceManager &SM, const clang::SourceLocation &loc) {
#if LLVM_VERSION_MAJOR > 6
return SM.getExpansionRange(loc).getEnd();
#else
return SM.getExpansionRange(loc).second;
#endif
}
} // namespace llcompat
<commit_msg>[HIPIFY][Win][fix] canCompileHostAndDeviceInOneJob is true only for LLVM >= 10<commit_after>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
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 "ArgParse.h"
#include "LLVMCompat.h"
#include "llvm/Support/Path.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Frontend/CompilerInstance.h"
const std::string sHipify = "[HIPIFY] ", sConflict = "conflict: ", sError = "error: ", sWarning = "warning: ";
namespace llcompat {
void PrintStackTraceOnErrorSignal() {
// The signature of PrintStackTraceOnErrorSignal changed in llvm 3.9. We don't support
// anything older than 3.8, so let's specifically detect the one old version we support.
#if (LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR == 8)
llvm::sys::PrintStackTraceOnErrorSignal();
#else
llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
#endif
}
ct::Replacements &getReplacements(ct::RefactoringTool &Tool, StringRef file) {
#if LLVM_VERSION_MAJOR > 3
// getReplacements() now returns a map from filename to Replacements - so create an entry
// for this source file and return a reference to it.
return Tool.getReplacements()[file];
#else
return Tool.getReplacements();
#endif
}
void insertReplacement(ct::Replacements &replacements, const ct::Replacement &rep) {
#if LLVM_VERSION_MAJOR > 3
// New clang added error checking to Replacements, and *insists* that you explicitly check it.
llvm::consumeError(replacements.add(rep));
#else
// In older versions, it's literally an std::set<Replacement>
replacements.insert(rep);
#endif
}
void EnterPreprocessorTokenStream(clang::Preprocessor &_pp, const clang::Token *start, size_t len, bool DisableMacroExpansion) {
#if (LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR == 8)
_pp.EnterTokenStream(start, len, false, DisableMacroExpansion);
#else
#if (LLVM_VERSION_MAJOR < 9)
_pp.EnterTokenStream(clang::ArrayRef<clang::Token>{start, len}, DisableMacroExpansion);
#else
_pp.EnterTokenStream(clang::ArrayRef<clang::Token>{start, len}, DisableMacroExpansion, false);
#endif
#endif
}
clang::SourceLocation getBeginLoc(const clang::Stmt *stmt) {
#if LLVM_VERSION_MAJOR < 8
return stmt->getLocStart();
#else
return stmt->getBeginLoc();
#endif
}
clang::SourceLocation getBeginLoc(const clang::TypeLoc &typeLoc) {
#if LLVM_VERSION_MAJOR < 8
return typeLoc.getLocStart();
#else
return typeLoc.getBeginLoc();
#endif
}
clang::SourceLocation getEndLoc(const clang::Stmt *stmt) {
#if LLVM_VERSION_MAJOR < 8
return stmt->getLocEnd();
#else
return stmt->getEndLoc();
#endif
}
clang::SourceLocation getEndLoc(const clang::TypeLoc &typeLoc) {
#if LLVM_VERSION_MAJOR < 8
return typeLoc.getLocEnd();
#else
return typeLoc.getEndLoc();
#endif
}
std::error_code real_path(const Twine &path, SmallVectorImpl<char> &output,
bool expand_tilde) {
#if LLVM_VERSION_MAJOR < 5
output.clear();
std::string s = path.str();
output.append(s.begin(), s.end());
if (sys::path::is_relative(path)) {
return sys::fs::make_absolute(output);
}
return std::error_code();
#else
return sys::fs::real_path(path, output, expand_tilde);
#endif
}
bool pragma_once_outside_header() {
#if LLVM_VERSION_MAJOR < 4
return false;
#else
return true;
#endif
}
bool canCompileHostAndDeviceInOneJob() {
#if LLVM_VERSION_MAJOR > 9 && defined(_WIN32)
return true;
#else
return false;
#endif
}
void RetainExcludedConditionalBlocks(clang::CompilerInstance &CI) {
#if LLVM_VERSION_MAJOR > 9
clang::PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
PPOpts.RetainExcludedConditionalBlocks = !SkipExcludedPPConditionalBlocks;
#endif
}
bool CheckCompatibility() {
#if LLVM_VERSION_MAJOR < 10
if (SkipExcludedPPConditionalBlocks) {
llvm::errs() << "\n" << sHipify << sWarning << "Option '" << SkipExcludedPPConditionalBlocks.ArgStr.str() << "' is supported starting from LLVM version 10.0\n";
}
#endif
return true;
}
clang::SourceLocation getEndOfExpansionRangeForLoc(const clang::SourceManager &SM, const clang::SourceLocation &loc) {
#if LLVM_VERSION_MAJOR > 6
return SM.getExpansionRange(loc).getEnd();
#else
return SM.getExpansionRange(loc).second;
#endif
}
} // namespace llcompat
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/threading/thread_local.h"
#include <windows.h>
#include "base/logging.h"
namespace base {
namespace internal {
// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
slot = TlsAlloc();
CHECK_NE(slot, TLS_OUT_OF_INDEXES);
}
// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
if (!TlsFree(slot)) {
NOTREACHED() << "Failed to deallocate tls slot with TlsFree().";
}
}
// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
return TlsGetValue(slot);
}
// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
if (!TlsSetValue(slot, value)) {
DLOG(FATAL) << "Failed to TlsSetValue().";
}
}
} // namespace internal
} // namespace base
<commit_msg>Revert log change to thread_local_win to fix an internal compiler error when doing official Chrome builds.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/threading/thread_local.h"
#include <windows.h>
#include "base/logging.h"
namespace base {
namespace internal {
// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
slot = TlsAlloc();
CHECK_NE(slot, TLS_OUT_OF_INDEXES);
}
// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
if (!TlsFree(slot)) {
NOTREACHED() << "Failed to deallocate tls slot with TlsFree().";
}
}
// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
return TlsGetValue(slot);
}
// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
if (!TlsSetValue(slot, value)) {
LOG(FATAL) << "Failed to TlsSetValue().";
}
}
} // namespace internal
} // namespace base
<|endoftext|> |
<commit_before>#include "GraphReader.h"
#include <json/json.hpp>
#include <fstream>
#include "Graph.h"
namespace pathfind
{
GraphReader::GraphReader(const std::string& path) : _path(path)
{
}
std::unique_ptr<Graph> GraphReader::Read()
{
// Load json file
nlohmann::json json = nlohmann::json(std::ifstream(_path));
// Create graph from nodes
auto graph = std::make_unique<Graph>();
for (auto& node : json["nodes"])
{
graph->_nodes.push_back(GraphNode{ node["id"], Vector3(node["x"], node["y"], node["z"]), {} });
}
// Fill in edge pointers
std::size_t i = 0;
for (auto& node : json["nodes"])
{
auto& edges = graph->_nodes[i++].edges;
for (auto& edge : node["edges"])
{
auto edgeIndex = edge[0].get<std::size_t>();
auto distance = edge[1].get<std::size_t>();
edges.push_back({ &graph->_nodes[edgeIndex], distance });
}
}
return graph;
}
}
<commit_msg>Linux compile fix<commit_after>#include "GraphReader.h"
#include <json/json.hpp>
#include <fstream>
#include "Graph.h"
namespace pathfind
{
GraphReader::GraphReader(const std::string& path) : _path(path)
{
}
std::unique_ptr<Graph> GraphReader::Read()
{
// Load json file
nlohmann::json json = nlohmann::json::parse(std::ifstream(_path));
// Create graph from nodes
auto graph = std::make_unique<Graph>();
for (auto& node : json["nodes"])
{
graph->_nodes.push_back(GraphNode{ node["id"], Vector3(node["x"], node["y"], node["z"]), {} });
}
// Fill in edge pointers
std::size_t i = 0;
for (auto& node : json["nodes"])
{
auto& edges = graph->_nodes[i++].edges;
for (auto& edge : node["edges"])
{
auto edgeIndex = edge[0].get<std::size_t>();
auto distance = edge[1].get<std::size_t>();
edges.push_back({ &graph->_nodes[edgeIndex], distance });
}
}
return graph;
}
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <cassert>
#include "sphere.h"
namespace pt {
Sphere::Sphere(const glm::vec3 ¢er, const float radius) : center(center), radius(radius) {}
bool Sphere::intersect(Ray &ray, DifferentialGeometry &dg) const {
const float a = glm::dot(ray.dir, ray.dir);
const float b = 2.0 * glm::dot(ray.dir, ray.origin);
const float c = glm::dot(ray.origin, ray.origin) - radius * radius;
const float discrim = b * b - c;
if (discrim > 0.f){
float t = (-b - std::sqrt(discrim)) / (2.0 * a);
if (t > ray.t_min && t < ray.t_max){
ray.t_max = t;
dg.point = ray.origin + ray.dir * t;
dg.normal = glm::normalize(dg.point - center);
return true;
} else {
t = (-b + std::sqrt(discrim)) / (2.0 * a);
if (t > ray.t_min && t < ray.t_max){
ray.t_max = t;
dg.point = ray.origin + ray.dir * t;
dg.normal = glm::normalize(dg.point - center);
return true;
}
}
}
return false;
}
}
<commit_msg>Fix discriminant in sphere intersect<commit_after>#include <cmath>
#include "sphere.h"
namespace pt {
Sphere::Sphere(const glm::vec3 ¢er, const float radius) : center(center), radius(radius) {}
bool Sphere::intersect(Ray &ray, DifferentialGeometry &dg) const {
const float a = glm::dot(ray.dir, ray.dir);
const float b = 2.0 * glm::dot(ray.dir, ray.origin);
const float c = glm::dot(ray.origin, ray.origin) - radius * radius;
const float discrim = b * b - 4.0 * a * c;
if (discrim > 0.f){
float t = (-b - std::sqrt(discrim)) / (2.0 * a);
if (t > ray.t_min && t < ray.t_max){
ray.t_max = t;
dg.point = ray.origin + ray.dir * t;
dg.normal = glm::normalize(dg.point - center);
return true;
} else {
t = (-b + std::sqrt(discrim)) / (2.0 * a);
if (t > ray.t_min && t < ray.t_max){
ray.t_max = t;
dg.point = ray.origin + ray.dir * t;
dg.normal = glm::normalize(dg.point - center);
return true;
}
}
}
return false;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "generic/glyphcache.hxx"
#include <string.h>
RawBitmap::RawBitmap()
: mnAllocated(0)
{}
RawBitmap::~RawBitmap()
{}
// used by 90 and 270 degree rotations on 8 bit deep bitmaps
static void ImplRotate8_90( unsigned char* p1, const unsigned char* p2,
int xmax, int ymax, int dx, int dy, int nPad )
{
for( int y = ymax; --y >= 0; p2 += dy )
{
for( int x = xmax; --x >= 0; p2 += dx )
*(p1++) = *p2;
for( int i = nPad; --i >= 0; )
*(p1++) = 0;
}
}
// used by inplace 180 degree rotation on 8 bit deep bitmaps
static void ImplRotate8_180( unsigned char* p1, int xmax, int ymax, int nPad )
{
unsigned char* p2 = p1 + ymax * (xmax + nPad);
for( int y = ymax/2; --y >= 0; )
{
p2 -= nPad;
for( int x = xmax; --x >= 0; )
{
unsigned char cTmp = *(--p2);
*p2 = *p1;
*(p1++) = cTmp;
}
p1 += nPad;
}
// reverse middle line
p2 -= nPad;
while( p1 < p2 )
{
unsigned char cTmp = *(--p2);
*p2 = *p1;
*(p1++) = cTmp;
}
}
// used by 90 or 270 degree rotations on 1 bit deep bitmaps
static void ImplRotate1_90( unsigned char* p1, const unsigned char* p2,
int xmax, int ymax, int dx, int nShift, int nDeltaShift, int nPad )
{
for( int y = ymax; --y >= 0; )
{
unsigned nTemp = 1;
const unsigned char* p20 = p2;
for( int x = xmax; --x >= 0; p2 += dx )
{
// build bitwise and store when byte finished
nTemp += nTemp + ((*p2 >> nShift) & 1);
if( nTemp >= 0x100U )
{
*(p1++) = (unsigned char)nTemp;
nTemp = 1;
}
}
p2 = p20;
// store left aligned remainder if needed
if( nTemp > 1 )
{
for(; nTemp < 0x100U; nTemp += nTemp ) ;
*(p1++) = (unsigned char)nTemp;
}
// pad scanline with zeroes
for( int i = nPad; --i >= 0;)
*(p1++) = 0;
// increase/decrease shift, but keep bound inside 0 to 7
nShift += nDeltaShift;
if( nShift != (nShift & 7) )
p2 -= nDeltaShift;
nShift &= 7;
}
}
// used by 180 degrees rotations on 1 bit deep bitmaps
static void ImplRotate1_180( unsigned char* p1, const unsigned char* p2,
int xmax, int ymax, int nPad )
{
--p2;
for( int y = ymax; --y >= 0; )
{
p2 -= nPad;
unsigned nTemp = 1;
unsigned nInp = (0x100 + *p2) >> (-xmax & 7);
for( int x = xmax; --x >= 0; )
{
// build bitwise and store when byte finished
nTemp += nTemp + (nInp & 1);
if( nTemp >= 0x100 )
{
*(p1++) = (unsigned char)nTemp;
nTemp = 1;
}
// update input byte if needed (and available)
if( (nInp >>= 1) <= 1 && ((y != 0) || (x != 0)) )
nInp = 0x100 + *(--p2);
}
// store left aligned remainder if needed
if( nTemp > 1 )
{
for(; nTemp < 0x100; nTemp += nTemp ) ;
*(p1++) = (unsigned char)nTemp;
}
// scanline pad is already clean
p1 += nPad;
}
}
bool RawBitmap::Rotate( int nAngle )
{
sal_uLong nNewScanlineSize = 0;
sal_uLong nNewHeight = 0;
sal_uLong nNewWidth = 0;
// do inplace rotation or prepare double buffered rotation
switch( nAngle )
{
case 0: // nothing to do
case 3600:
return true;
default: // non rectangular angles not allowed
return false;
case 1800: // rotate by 180 degrees
mnXOffset = -(mnXOffset + mnWidth);
mnYOffset = -(mnYOffset + mnHeight);
if( mnBitCount == 8 )
{
ImplRotate8_180( mpBits.get(), mnWidth, mnHeight, mnScanlineSize-mnWidth );
return true;
}
nNewWidth = mnWidth;
nNewHeight = mnHeight;
nNewScanlineSize = mnScanlineSize;
break;
case +900: // left by 90 degrees
case -900:
case 2700: // right by 90 degrees
nNewWidth = mnHeight;
nNewHeight = mnWidth;
if( mnBitCount==1 )
nNewScanlineSize = (nNewWidth + 7) / 8;
else
nNewScanlineSize = (nNewWidth + 3) & -4;
break;
}
unsigned int nBufSize = nNewHeight * nNewScanlineSize;
unsigned char* pBuf = new unsigned char[ nBufSize ];
if( !pBuf )
return false;
memset( pBuf, 0, nBufSize );
int i;
// dispatch non-inplace rotations
switch( nAngle )
{
case 1800: // rotate by 180 degrees
// we know we only need to deal with 1 bit depth
ImplRotate1_180( pBuf, mpBits.get() + mnHeight * mnScanlineSize,
mnWidth, mnHeight, mnScanlineSize - (mnWidth + 7) / 8 );
break;
case +900: // rotate left by 90 degrees
i = mnXOffset;
mnXOffset = mnYOffset;
mnYOffset = -nNewHeight - i;
if( mnBitCount == 8 )
ImplRotate8_90( pBuf, mpBits.get() + mnWidth - 1,
nNewWidth, nNewHeight, +mnScanlineSize, -1-mnHeight*mnScanlineSize,
nNewScanlineSize - nNewWidth );
else
ImplRotate1_90( pBuf, mpBits.get() + (mnWidth - 1) / 8,
nNewWidth, nNewHeight, +mnScanlineSize,
(-mnWidth & 7), +1, nNewScanlineSize - (nNewWidth + 7) / 8 );
break;
case 2700: // rotate right by 90 degrees
case -900:
i = mnXOffset;
mnXOffset = -(nNewWidth + mnYOffset);
mnYOffset = i;
if( mnBitCount == 8 )
ImplRotate8_90( pBuf, mpBits.get() + mnScanlineSize * (mnHeight-1),
nNewWidth, nNewHeight, -mnScanlineSize, +1+mnHeight*mnScanlineSize,
nNewScanlineSize - nNewWidth );
else
ImplRotate1_90( pBuf, mpBits.get() + mnScanlineSize * (mnHeight-1),
nNewWidth, nNewHeight, -mnScanlineSize,
+7, -1, nNewScanlineSize - (nNewWidth + 7) / 8 );
break;
}
mnWidth = nNewWidth;
mnHeight = nNewHeight;
mnScanlineSize = nNewScanlineSize;
if( nBufSize < mnAllocated )
{
memcpy( mpBits.get(), pBuf, nBufSize );
delete[] pBuf;
}
else
{
mpBits.reset(pBuf);
mnAllocated = nBufSize;
}
return true;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#708636 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "generic/glyphcache.hxx"
#include <string.h>
RawBitmap::RawBitmap()
: mnAllocated(0)
, mnWidth(0)
, mnHeight(0)
, mnScanlineSize(0)
, mnBitCount(0)
, mnXOffset(0)
, mnYOffset(0)
{
}
RawBitmap::~RawBitmap()
{}
// used by 90 and 270 degree rotations on 8 bit deep bitmaps
static void ImplRotate8_90( unsigned char* p1, const unsigned char* p2,
int xmax, int ymax, int dx, int dy, int nPad )
{
for( int y = ymax; --y >= 0; p2 += dy )
{
for( int x = xmax; --x >= 0; p2 += dx )
*(p1++) = *p2;
for( int i = nPad; --i >= 0; )
*(p1++) = 0;
}
}
// used by inplace 180 degree rotation on 8 bit deep bitmaps
static void ImplRotate8_180( unsigned char* p1, int xmax, int ymax, int nPad )
{
unsigned char* p2 = p1 + ymax * (xmax + nPad);
for( int y = ymax/2; --y >= 0; )
{
p2 -= nPad;
for( int x = xmax; --x >= 0; )
{
unsigned char cTmp = *(--p2);
*p2 = *p1;
*(p1++) = cTmp;
}
p1 += nPad;
}
// reverse middle line
p2 -= nPad;
while( p1 < p2 )
{
unsigned char cTmp = *(--p2);
*p2 = *p1;
*(p1++) = cTmp;
}
}
// used by 90 or 270 degree rotations on 1 bit deep bitmaps
static void ImplRotate1_90( unsigned char* p1, const unsigned char* p2,
int xmax, int ymax, int dx, int nShift, int nDeltaShift, int nPad )
{
for( int y = ymax; --y >= 0; )
{
unsigned nTemp = 1;
const unsigned char* p20 = p2;
for( int x = xmax; --x >= 0; p2 += dx )
{
// build bitwise and store when byte finished
nTemp += nTemp + ((*p2 >> nShift) & 1);
if( nTemp >= 0x100U )
{
*(p1++) = (unsigned char)nTemp;
nTemp = 1;
}
}
p2 = p20;
// store left aligned remainder if needed
if( nTemp > 1 )
{
for(; nTemp < 0x100U; nTemp += nTemp ) ;
*(p1++) = (unsigned char)nTemp;
}
// pad scanline with zeroes
for( int i = nPad; --i >= 0;)
*(p1++) = 0;
// increase/decrease shift, but keep bound inside 0 to 7
nShift += nDeltaShift;
if( nShift != (nShift & 7) )
p2 -= nDeltaShift;
nShift &= 7;
}
}
// used by 180 degrees rotations on 1 bit deep bitmaps
static void ImplRotate1_180( unsigned char* p1, const unsigned char* p2,
int xmax, int ymax, int nPad )
{
--p2;
for( int y = ymax; --y >= 0; )
{
p2 -= nPad;
unsigned nTemp = 1;
unsigned nInp = (0x100 + *p2) >> (-xmax & 7);
for( int x = xmax; --x >= 0; )
{
// build bitwise and store when byte finished
nTemp += nTemp + (nInp & 1);
if( nTemp >= 0x100 )
{
*(p1++) = (unsigned char)nTemp;
nTemp = 1;
}
// update input byte if needed (and available)
if( (nInp >>= 1) <= 1 && ((y != 0) || (x != 0)) )
nInp = 0x100 + *(--p2);
}
// store left aligned remainder if needed
if( nTemp > 1 )
{
for(; nTemp < 0x100; nTemp += nTemp ) ;
*(p1++) = (unsigned char)nTemp;
}
// scanline pad is already clean
p1 += nPad;
}
}
bool RawBitmap::Rotate( int nAngle )
{
sal_uLong nNewScanlineSize = 0;
sal_uLong nNewHeight = 0;
sal_uLong nNewWidth = 0;
// do inplace rotation or prepare double buffered rotation
switch( nAngle )
{
case 0: // nothing to do
case 3600:
return true;
default: // non rectangular angles not allowed
return false;
case 1800: // rotate by 180 degrees
mnXOffset = -(mnXOffset + mnWidth);
mnYOffset = -(mnYOffset + mnHeight);
if( mnBitCount == 8 )
{
ImplRotate8_180( mpBits.get(), mnWidth, mnHeight, mnScanlineSize-mnWidth );
return true;
}
nNewWidth = mnWidth;
nNewHeight = mnHeight;
nNewScanlineSize = mnScanlineSize;
break;
case +900: // left by 90 degrees
case -900:
case 2700: // right by 90 degrees
nNewWidth = mnHeight;
nNewHeight = mnWidth;
if( mnBitCount==1 )
nNewScanlineSize = (nNewWidth + 7) / 8;
else
nNewScanlineSize = (nNewWidth + 3) & -4;
break;
}
unsigned int nBufSize = nNewHeight * nNewScanlineSize;
unsigned char* pBuf = new unsigned char[ nBufSize ];
if( !pBuf )
return false;
memset( pBuf, 0, nBufSize );
int i;
// dispatch non-inplace rotations
switch( nAngle )
{
case 1800: // rotate by 180 degrees
// we know we only need to deal with 1 bit depth
ImplRotate1_180( pBuf, mpBits.get() + mnHeight * mnScanlineSize,
mnWidth, mnHeight, mnScanlineSize - (mnWidth + 7) / 8 );
break;
case +900: // rotate left by 90 degrees
i = mnXOffset;
mnXOffset = mnYOffset;
mnYOffset = -nNewHeight - i;
if( mnBitCount == 8 )
ImplRotate8_90( pBuf, mpBits.get() + mnWidth - 1,
nNewWidth, nNewHeight, +mnScanlineSize, -1-mnHeight*mnScanlineSize,
nNewScanlineSize - nNewWidth );
else
ImplRotate1_90( pBuf, mpBits.get() + (mnWidth - 1) / 8,
nNewWidth, nNewHeight, +mnScanlineSize,
(-mnWidth & 7), +1, nNewScanlineSize - (nNewWidth + 7) / 8 );
break;
case 2700: // rotate right by 90 degrees
case -900:
i = mnXOffset;
mnXOffset = -(nNewWidth + mnYOffset);
mnYOffset = i;
if( mnBitCount == 8 )
ImplRotate8_90( pBuf, mpBits.get() + mnScanlineSize * (mnHeight-1),
nNewWidth, nNewHeight, -mnScanlineSize, +1+mnHeight*mnScanlineSize,
nNewScanlineSize - nNewWidth );
else
ImplRotate1_90( pBuf, mpBits.get() + mnScanlineSize * (mnHeight-1),
nNewWidth, nNewHeight, -mnScanlineSize,
+7, -1, nNewScanlineSize - (nNewWidth + 7) / 8 );
break;
}
mnWidth = nNewWidth;
mnHeight = nNewHeight;
mnScanlineSize = nNewScanlineSize;
if( nBufSize < mnAllocated )
{
memcpy( mpBits.get(), pBuf, nBufSize );
delete[] pBuf;
}
else
{
mpBits.reset(pBuf);
mnAllocated = nBufSize;
}
return true;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "decode.hxx"
struct GIFLZWTableEntry
{
GIFLZWTableEntry* pPrev;
GIFLZWTableEntry* pFirst;
sal_uInt8 nData;
};
GIFLZWDecompressor::GIFLZWDecompressor( sal_uInt8 cDataSize ) :
nInputBitsBuf ( 0 ),
nOutBufDataLen ( 0 ),
nInputBitsBufSize ( 0 ),
bEOIFound ( false ),
nDataSize ( cDataSize )
{
pOutBuf = new sal_uInt8[ 4096 ];
nClearCode = 1 << nDataSize;
nEOICode = nClearCode + 1;
nTableSize = nEOICode + 1;
nCodeSize = nDataSize + 1;
nOldCode = 0xffff;
pOutBufData = pOutBuf + 4096;
pTable = new GIFLZWTableEntry[ 4098 ];
for( sal_uInt16 i = 0; i < nTableSize; i++ )
{
pTable[i].pPrev = NULL;
pTable[i].pFirst = pTable + i;
pTable[i].nData = (sal_uInt8) i;
}
}
GIFLZWDecompressor::~GIFLZWDecompressor()
{
delete[] pOutBuf;
delete[] pTable;
}
HPBYTE GIFLZWDecompressor::DecompressBlock( HPBYTE pSrc, sal_uInt8 cBufSize,
sal_uLong& rCount, bool& rEOI )
{
sal_uLong nTargetSize = 4096;
sal_uLong nCount = 0;
HPBYTE pTarget = (HPBYTE) rtl_allocateMemory( nTargetSize );
HPBYTE pTmpTarget = pTarget;
nBlockBufSize = cBufSize;
nBlockBufPos = 0;
pBlockBuf = pSrc;
while( ProcessOneCode() )
{
nCount += nOutBufDataLen;
if( nCount > nTargetSize )
{
sal_uLong nNewSize = nTargetSize << 1;
sal_uLong nOffset = pTmpTarget - pTarget;
HPBYTE pTmp = (HPBYTE) rtl_allocateMemory( nNewSize );
memcpy( pTmp, pTarget, nTargetSize );
rtl_freeMemory( pTarget );
nTargetSize = nNewSize;
pTmpTarget = ( pTarget = pTmp ) + nOffset;
}
memcpy( pTmpTarget, pOutBufData, nOutBufDataLen );
pTmpTarget += nOutBufDataLen;
pOutBufData += nOutBufDataLen;
nOutBufDataLen = 0;
if ( bEOIFound )
break;
}
rCount = nCount;
rEOI = bEOIFound;
return pTarget;
}
void GIFLZWDecompressor::AddToTable( sal_uInt16 nPrevCode, sal_uInt16 nCodeFirstData )
{
GIFLZWTableEntry* pE;
if( nTableSize < 4096 )
{
pE = pTable + nTableSize;
pE->pPrev = pTable + nPrevCode;
pE->pFirst = pE->pPrev->pFirst;
pE->nData = pTable[ nCodeFirstData ].pFirst->nData;
nTableSize++;
if ( ( nTableSize == (sal_uInt16) (1 << nCodeSize) ) && ( nTableSize < 4096 ) )
nCodeSize++;
}
}
bool GIFLZWDecompressor::ProcessOneCode()
{
GIFLZWTableEntry* pE;
sal_uInt16 nCode;
bool bRet = false;
bool bEndOfBlock = false;
while( nInputBitsBufSize < nCodeSize )
{
if( nBlockBufPos >= nBlockBufSize )
{
bEndOfBlock = true;
break;
}
nInputBitsBuf |= ( (sal_uLong) pBlockBuf[ nBlockBufPos++ ] ) << nInputBitsBufSize;
nInputBitsBufSize += 8;
}
if ( !bEndOfBlock )
{
// fetch code from input buffer
nCode = sal::static_int_cast< sal_uInt16 >(
( (sal_uInt16) nInputBitsBuf ) & ( ~( 0xffff << nCodeSize ) ));
nInputBitsBuf >>= nCodeSize;
nInputBitsBufSize = nInputBitsBufSize - nCodeSize;
if ( nCode < nClearCode )
{
if ( nOldCode != 0xffff )
AddToTable( nOldCode, nCode );
}
else if ( ( nCode > nEOICode ) && ( nCode <= nTableSize ) )
{
if ( nCode == nTableSize )
AddToTable( nOldCode, nOldCode );
else
AddToTable( nOldCode, nCode );
}
else
{
if ( nCode == nClearCode )
{
nTableSize = nEOICode + 1;
nCodeSize = nDataSize + 1;
nOldCode = 0xffff;
nOutBufDataLen = 0;
}
else
bEOIFound = true;
return true;
}
nOldCode = nCode;
// write character(/-sequence) of code nCode in the output buffer:
pE = pTable + nCode;
do
{
nOutBufDataLen++;
*(--pOutBufData) = pE->nData;
pE = pE->pPrev;
}
while( pE );
bRet = true;
}
return bRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#708312 Uninitialized pointer field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "decode.hxx"
struct GIFLZWTableEntry
{
GIFLZWTableEntry* pPrev;
GIFLZWTableEntry* pFirst;
sal_uInt8 nData;
};
GIFLZWDecompressor::GIFLZWDecompressor(sal_uInt8 cDataSize)
: pBlockBuf(NULL)
, nInputBitsBuf(0)
, nOutBufDataLen(0)
, nInputBitsBufSize(0)
, bEOIFound(false)
, nDataSize(cDataSize)
, nBlockBufSize(0)
, nBlockBufPos(0)
{
pOutBuf = new sal_uInt8[ 4096 ];
nClearCode = 1 << nDataSize;
nEOICode = nClearCode + 1;
nTableSize = nEOICode + 1;
nCodeSize = nDataSize + 1;
nOldCode = 0xffff;
pOutBufData = pOutBuf + 4096;
pTable = new GIFLZWTableEntry[ 4098 ];
for( sal_uInt16 i = 0; i < nTableSize; i++ )
{
pTable[i].pPrev = NULL;
pTable[i].pFirst = pTable + i;
pTable[i].nData = (sal_uInt8) i;
}
}
GIFLZWDecompressor::~GIFLZWDecompressor()
{
delete[] pOutBuf;
delete[] pTable;
}
HPBYTE GIFLZWDecompressor::DecompressBlock( HPBYTE pSrc, sal_uInt8 cBufSize,
sal_uLong& rCount, bool& rEOI )
{
sal_uLong nTargetSize = 4096;
sal_uLong nCount = 0;
HPBYTE pTarget = (HPBYTE) rtl_allocateMemory( nTargetSize );
HPBYTE pTmpTarget = pTarget;
nBlockBufSize = cBufSize;
nBlockBufPos = 0;
pBlockBuf = pSrc;
while( ProcessOneCode() )
{
nCount += nOutBufDataLen;
if( nCount > nTargetSize )
{
sal_uLong nNewSize = nTargetSize << 1;
sal_uLong nOffset = pTmpTarget - pTarget;
HPBYTE pTmp = (HPBYTE) rtl_allocateMemory( nNewSize );
memcpy( pTmp, pTarget, nTargetSize );
rtl_freeMemory( pTarget );
nTargetSize = nNewSize;
pTmpTarget = ( pTarget = pTmp ) + nOffset;
}
memcpy( pTmpTarget, pOutBufData, nOutBufDataLen );
pTmpTarget += nOutBufDataLen;
pOutBufData += nOutBufDataLen;
nOutBufDataLen = 0;
if ( bEOIFound )
break;
}
rCount = nCount;
rEOI = bEOIFound;
return pTarget;
}
void GIFLZWDecompressor::AddToTable( sal_uInt16 nPrevCode, sal_uInt16 nCodeFirstData )
{
GIFLZWTableEntry* pE;
if( nTableSize < 4096 )
{
pE = pTable + nTableSize;
pE->pPrev = pTable + nPrevCode;
pE->pFirst = pE->pPrev->pFirst;
pE->nData = pTable[ nCodeFirstData ].pFirst->nData;
nTableSize++;
if ( ( nTableSize == (sal_uInt16) (1 << nCodeSize) ) && ( nTableSize < 4096 ) )
nCodeSize++;
}
}
bool GIFLZWDecompressor::ProcessOneCode()
{
GIFLZWTableEntry* pE;
sal_uInt16 nCode;
bool bRet = false;
bool bEndOfBlock = false;
while( nInputBitsBufSize < nCodeSize )
{
if( nBlockBufPos >= nBlockBufSize )
{
bEndOfBlock = true;
break;
}
nInputBitsBuf |= ( (sal_uLong) pBlockBuf[ nBlockBufPos++ ] ) << nInputBitsBufSize;
nInputBitsBufSize += 8;
}
if ( !bEndOfBlock )
{
// fetch code from input buffer
nCode = sal::static_int_cast< sal_uInt16 >(
( (sal_uInt16) nInputBitsBuf ) & ( ~( 0xffff << nCodeSize ) ));
nInputBitsBuf >>= nCodeSize;
nInputBitsBufSize = nInputBitsBufSize - nCodeSize;
if ( nCode < nClearCode )
{
if ( nOldCode != 0xffff )
AddToTable( nOldCode, nCode );
}
else if ( ( nCode > nEOICode ) && ( nCode <= nTableSize ) )
{
if ( nCode == nTableSize )
AddToTable( nOldCode, nOldCode );
else
AddToTable( nOldCode, nCode );
}
else
{
if ( nCode == nClearCode )
{
nTableSize = nEOICode + 1;
nCodeSize = nDataSize + 1;
nOldCode = 0xffff;
nOutBufDataLen = 0;
}
else
bEOIFound = true;
return true;
}
nOldCode = nCode;
// write character(/-sequence) of code nCode in the output buffer:
pE = pTable + nCode;
do
{
nOutBufDataLen++;
*(--pOutBufData) = pE->nData;
pE = pE->pPrev;
}
while( pE );
bRet = true;
}
return bRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef FS_COMMON_HPP
#define FS_COMMON_HPP
#include <memory>
#include <string>
namespace fs {
/**
* @brief Type used for buffers within the filesystem
* subsystem
*/
using buffer_t = std::shared_ptr<uint8_t>;
struct error_t
{
enum token_t {
NO_ERR = 0,
E_IO, // general I/O error
E_MNT,
E_NOENT,
E_NOTDIR,
E_NOTFILE
};
error_t(const token_t tk, const std::string& rsn) noexcept
: token_{tk}
, reason_{rsn}
{}
/**
* @brief Get a human-readable description of the token
*
* @return Description of the token as a {std::string}
*/
const std::string& token() const noexcept;
/**
* @brief Get an explanation for error
*/
const std::string& reason() const noexcept {
return reason_;
}
// returns "description": "reason"
std::string to_string() const noexcept {
return token() + ": " + reason();
}
// returns true when it's an error
operator bool () const noexcept {
return token_ != NO_ERR;
}
private:
const token_t token_;
const std::string& reason_;
}; //< struct error_t
struct Buffer
{
Buffer(error_t e, buffer_t b, size_t l)
: err(e), buffer(b), len(l) {}
// returns true if this buffer is valid
bool is_valid() const noexcept {
return buffer != nullptr;
}
operator bool () const noexcept {
return is_valid();
}
uint8_t* data() {
return buffer.get();
}
size_t size() const noexcept {
return len;
}
// create a std::string from the stored buffer and return it
std::string to_string() const noexcept {
return std::string((char*) buffer.get(), size());
}
error_t err;
buffer_t buffer;
uint64_t len;
};
/** @var no_error: Always returns boolean false when used in expressions */
extern error_t no_error;
} //< namespace fs
#endif //< FS_ERROR_HPP
<commit_msg>Refactored error_t::to_string<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef FS_COMMON_HPP
#define FS_COMMON_HPP
#include <memory>
#include <string>
namespace fs {
/**
* @brief Type used for buffers within the filesystem
* subsystem
*/
using buffer_t = std::shared_ptr<uint8_t>;
struct error_t
{
enum token_t {
NO_ERR = 0,
E_IO, // general I/O error
E_MNT,
E_NOENT,
E_NOTDIR,
E_NOTFILE
};
error_t(const token_t tk, const std::string& rsn) noexcept
: token_{tk}
, reason_{rsn}
{}
/**
* @brief Get a human-readable description of the token
*
* @return Description of the token as a {std::string}
*/
const std::string& token() const noexcept;
/**
* @brief Get an explanation for error
*/
const std::string& reason() const noexcept {
return reason_;
}
/**
* @brief Get a {std::string} representation of this type
*
* Format "description: reason"
*
* @return {std::string} representation of this type
*/
std::string to_string() const {
return token() + ": " + reason();
}
// returns true when it's an error
operator bool () const noexcept {
return token_ != NO_ERR;
}
private:
const token_t token_;
const std::string& reason_;
}; //< struct error_t
struct Buffer
{
Buffer(error_t e, buffer_t b, size_t l)
: err(e), buffer(b), len(l) {}
// returns true if this buffer is valid
bool is_valid() const noexcept {
return buffer != nullptr;
}
operator bool () const noexcept {
return is_valid();
}
uint8_t* data() {
return buffer.get();
}
size_t size() const noexcept {
return len;
}
// create a std::string from the stored buffer and return it
std::string to_string() const noexcept {
return std::string((char*) buffer.get(), size());
}
error_t err;
buffer_t buffer;
uint64_t len;
};
/** @var no_error: Always returns boolean false when used in expressions */
extern error_t no_error;
} //< namespace fs
#endif //< FS_ERROR_HPP
<|endoftext|> |
<commit_before>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP
#include <cassert>
#include <cstdlib>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
#include "lightptr.hpp"
namespace
{
template <typename T>
struct static_store
{
static constexpr auto const max_instances = 8 * sizeof(unsigned);
static void cleanup() { delete [] store_; }
static unsigned memory_map_;
static typename ::std::aligned_storage<sizeof(T),
alignof(T)>::type* store_;
};
template <typename T>
unsigned static_store<T>::memory_map_{unsigned(-1)};
template <typename T>
typename ::std::aligned_storage<sizeof(T), alignof(T)>::type*
static_store<T>::store_{(::std::atexit(static_store<T>::cleanup),
new typename ::std::aligned_storage<sizeof(T),
alignof(T)>::type[static_store<T>::max_instances])};
template <typename T, typename ...A>
inline T* static_new(A&& ...args)
{
using static_store = static_store<T>;
auto const i(__builtin_ffs(static_store::memory_map_) - 1);
//assert(static_store::max_instances != i);
auto p(new (&static_store::store_[i]) T(::std::forward<A>(args)...));
static_store::memory_map_ &= ~(1 << i);
return p;
}
template <typename T>
inline void static_delete(T const* const p)
{
using static_store = static_store<T>;
auto const i(p - static_cast<T const*>(static_cast<void const*>(
static_store::store_)));
//assert(!as_const(static_store::memory_map_)[i]);
static_store::memory_map_ |= 1 << i;
static_cast<T const*>(static_cast<void const*>(
&static_store::store_[i]))->~T();
}
}
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const&) = default;
delegate(delegate&&) = default;
delegate(::std::nullptr_t const) noexcept : delegate() { }
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate(T&& f)
{
*this = ::std::forward<T>(f);
}
delegate& operator=(delegate const&) = default;
delegate& operator=(delegate&& rhs) = default;
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
store_.reset(static_new<functor_type>(::std::forward<T>(f)),
functor_deleter<functor_type>);
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return ::std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; store_.reset(); }
void reset_stub() noexcept { stub_ptr_ = nullptr; }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !stub_ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return stub_ptr_;
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
void* object_ptr_;
stub_ptr_type stub_ptr_{};
light_ptr<void> store_;
template <class T>
static void functor_deleter(void* const p)
{
static_cast<T const*>(p)->~T();
static_delete(static_cast<T const*>(p));
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +
0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // DELEGATE_HPP
<commit_msg>some fixes<commit_after>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP
#include <cassert>
#include <cstdlib>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
#include "lightptr.hpp"
namespace
{
template <typename T, typename A = unsigned>
struct static_store
{
static constexpr auto const max_instances = 8 * sizeof(A);
#ifdef __GNUC__
template <typename U>
static int ffz(U v)
{
return __builtin_ffsll(~v) - 1;
}
#else
template <typename U>
static int ffz(U v)
{
int b{};
for (; (v & 1); ++b)
{
v >>= 1;
}
return b;
}
#endif // __GNUC__
static void cleanup() { delete [] store_; }
static A memory_map_;
static typename ::std::aligned_storage<sizeof(T),
alignof(T)>::type* store_;
};
template <typename T, typename A>
A static_store<T, A>::memory_map_;
template <typename T, typename A>
typename ::std::aligned_storage<sizeof(T), alignof(T)>::type*
static_store<T, A>::store_{(::std::atexit(static_store<T>::cleanup),
new typename ::std::aligned_storage<sizeof(T),
alignof(T)>::type[static_store<T>::max_instances])};
template <typename T, typename ...A>
inline T* static_new(A&& ...args)
{
using static_store = static_store<T>;
auto const i(static_store::ffz(static_store::memory_map_));
//assert((i >= 0) && (static_store::max_instances != i));
auto p(new (&static_store::store_[i]) T(::std::forward<A>(args)...));
static_store::memory_map_ |= 1 << i;
return p;
}
template <typename T>
inline void static_delete(T const* const p)
{
using static_store = static_store<T>;
auto const i(p - static_cast<T const*>(static_cast<void const*>(
static_store::store_)));
//assert(!as_const(static_store::memory_map_)[i]);
static_store::memory_map_ &= ~(1 << i);
static_cast<T const*>(static_cast<void const*>(
&static_store::store_[i]))->~T();
}
}
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const&) = default;
delegate(delegate&&) = default;
delegate(::std::nullptr_t const) noexcept : delegate() { }
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate(T&& f)
{
*this = ::std::forward<T>(f);
}
delegate& operator=(delegate const&) = default;
delegate& operator=(delegate&& rhs) = default;
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
store_.reset(static_new<functor_type>(::std::forward<T>(f)),
functor_deleter<functor_type>);
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return ::std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; store_.reset(); }
void reset_stub() noexcept { stub_ptr_ = nullptr; }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !stub_ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return stub_ptr_;
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
void* object_ptr_;
stub_ptr_type stub_ptr_{};
light_ptr<void> store_;
template <class T>
static void functor_deleter(void* const p)
{
static_cast<T const*>(p)->~T();
static_delete(static_cast<T const*>(p));
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +
0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // DELEGATE_HPP
<|endoftext|> |
<commit_before>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP
#include <cassert>
#include <bitset>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
#include "lightptr.hpp"
namespace
{
template <typename T>
struct static_store
{
static constexpr ::std::size_t const max_instances = 32;
static unsigned memory_map_;
static typename ::std::aligned_storage<sizeof(T),
alignof(T)>::type* store_;
};
template <typename T>
unsigned static_store<T>::memory_map_{unsigned(-1)};
template <typename T>
typename ::std::aligned_storage<sizeof(T), alignof(T)>::type*
static_store<T>::store_{new typename
::std::aligned_storage<sizeof(T), alignof(T)>::type[
static_store<T>::max_instances]};
template <typename T, typename ...A>
inline T* static_new(A&& ...args)
{
using static_store = static_store<T>;
auto const i(__builtin_ffs(static_store::memory_map_) - 1);
//assert(static_store::max_instances != i);
auto p(new (&static_store::store_[i]) T(::std::forward<A>(args)...));
static_store::memory_map_ &= ~(1 << i);
return p;
}
template <typename T>
inline void static_delete(T const* const p)
{
using static_store = static_store<T>;
auto const i(p - static_cast<T const*>(static_cast<void const*>(
static_store::store_)));
//assert(!as_const(static_store::memory_map_)[i]);
static_store::memory_map_ |= 1 << i;
static_cast<T const*>(static_cast<void const*>(
&static_store::store_[i]))->~T();
}
}
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const&) = default;
delegate(delegate&&) = default;
delegate(::std::nullptr_t const) noexcept : delegate() { }
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate(T&& f)
{
*this = ::std::forward<T>(f);
}
delegate& operator=(delegate const&) = default;
delegate& operator=(delegate&& rhs) = default;
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
store_.reset(static_new<functor_type>(::std::forward<T>(f)),
functor_deleter<functor_type>);
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return ::std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; store_.reset(); }
void reset_stub() noexcept { stub_ptr_ = nullptr; }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !stub_ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return stub_ptr_;
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
void* object_ptr_;
stub_ptr_type stub_ptr_{};
light_ptr<void> store_;
template <class T>
static void functor_deleter(void* const p)
{
static_cast<T const*>(p)->~T();
static_delete(static_cast<T const*>(p));
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +
0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // DELEGATE_HPP
<commit_msg>some fixes<commit_after>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP
#include <cassert>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
#include "lightptr.hpp"
namespace
{
template <typename T>
struct static_store
{
static constexpr ::std::size_t const max_instances = 32;
static unsigned memory_map_;
static typename ::std::aligned_storage<sizeof(T),
alignof(T)>::type* store_;
};
template <typename T>
unsigned static_store<T>::memory_map_{unsigned(-1)};
template <typename T>
typename ::std::aligned_storage<sizeof(T), alignof(T)>::type*
static_store<T>::store_{new typename
::std::aligned_storage<sizeof(T), alignof(T)>::type[
static_store<T>::max_instances]};
template <typename T, typename ...A>
inline T* static_new(A&& ...args)
{
using static_store = static_store<T>;
auto const i(__builtin_ffs(static_store::memory_map_) - 1);
//assert(static_store::max_instances != i);
auto p(new (&static_store::store_[i]) T(::std::forward<A>(args)...));
static_store::memory_map_ &= ~(1 << i);
return p;
}
template <typename T>
inline void static_delete(T const* const p)
{
using static_store = static_store<T>;
auto const i(p - static_cast<T const*>(static_cast<void const*>(
static_store::store_)));
//assert(!as_const(static_store::memory_map_)[i]);
static_store::memory_map_ |= 1 << i;
static_cast<T const*>(static_cast<void const*>(
&static_store::store_[i]))->~T();
}
}
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const&) = default;
delegate(delegate&&) = default;
delegate(::std::nullptr_t const) noexcept : delegate() { }
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate(T&& f)
{
*this = ::std::forward<T>(f);
}
delegate& operator=(delegate const&) = default;
delegate& operator=(delegate&& rhs) = default;
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
store_.reset(static_new<functor_type>(::std::forward<T>(f)),
functor_deleter<functor_type>);
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return ::std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; store_.reset(); }
void reset_stub() noexcept { stub_ptr_ = nullptr; }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !stub_ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return stub_ptr_;
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
void* object_ptr_;
stub_ptr_type stub_ptr_{};
light_ptr<void> store_;
template <class T>
static void functor_deleter(void* const p)
{
static_cast<T const*>(p)->~T();
static_delete(static_cast<T const*>(p));
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +
0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // DELEGATE_HPP
<|endoftext|> |
<commit_before>//
// FilteringSpeaker.h
// Clock Signal
//
// Created by Thomas Harte on 15/12/2017.
// Copyright 2017 Thomas Harte. All rights reserved.
//
#ifndef FilteringSpeaker_h
#define FilteringSpeaker_h
#include "../Speaker.hpp"
#include "../../../SignalProcessing/Stepper.hpp"
#include "../../../SignalProcessing/FIRFilter.hpp"
#include "../../../ClockReceiver/ClockReceiver.hpp"
#include "../../../Concurrency/AsyncTaskQueue.hpp"
#include <mutex>
#include <cstring>
#include <cmath>
namespace Outputs {
namespace Speaker {
/*!
The low-pass speaker expects an Outputs::Speaker::SampleSource-derived
template class, and uses the instance supplied to its constructor as the
source of a high-frequency stream of audio which it filters down to a
lower-frequency output.
*/
template <typename T> class LowpassSpeaker: public Speaker {
public:
LowpassSpeaker(T &sample_source) : sample_source_(sample_source) {
sample_source.set_sample_volume_range(32767);
}
// Implemented as per Speaker.
float get_ideal_clock_rate_in_range(float minimum, float maximum) final {
std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_);
// return twice the cut off, if applicable
if( filter_parameters_.high_frequency_cutoff > 0.0f &&
filter_parameters_.input_cycles_per_second >= filter_parameters_.high_frequency_cutoff * 3.0f &&
filter_parameters_.input_cycles_per_second <= filter_parameters_.high_frequency_cutoff * 3.0f)
return filter_parameters_.high_frequency_cutoff * 3.0f;
// return exactly the input rate if possible
if( filter_parameters_.input_cycles_per_second >= minimum &&
filter_parameters_.input_cycles_per_second <= maximum)
return filter_parameters_.input_cycles_per_second;
// if the input rate is lower, return the minimum
if(filter_parameters_.input_cycles_per_second < minimum)
return minimum;
// otherwise, return the maximum
return maximum;
}
// Implemented as per Speaker.
void set_computed_output_rate(float cycles_per_second, int buffer_size) final {
std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_);
filter_parameters_.output_cycles_per_second = cycles_per_second;
filter_parameters_.parameters_are_dirty = true;
output_buffer_.resize(std::size_t(buffer_size));
}
/*!
Sets the clock rate of the input audio.
*/
void set_input_rate(float cycles_per_second) {
std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_);
filter_parameters_.input_cycles_per_second = cycles_per_second;
filter_parameters_.parameters_are_dirty = true;
filter_parameters_.input_rate_changed = true;
}
/*!
Allows a cut-off frequency to be specified for audio. Ordinarily this low-pass speaker
will determine a cut-off based on the output audio rate. A caller can manually select
an alternative cut-off. This allows machines with a low-pass filter on their audio output
path to be explicit about its effect, and get that simulation for free.
*/
void set_high_frequency_cutoff(float high_frequency) {
std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_);
filter_parameters_.high_frequency_cutoff = high_frequency;
filter_parameters_.parameters_are_dirty = true;
}
/*!
Schedules an advancement by the number of cycles specified on the provided queue.
The speaker will advance by obtaining data from the sample source supplied
at construction, filtering it and passing it on to the speaker's delegate if there is one.
*/
void run_for(Concurrency::DeferringAsyncTaskQueue &queue, const Cycles cycles) {
queue.defer([this, cycles] {
run_for(cycles);
});
}
private:
/*!
Advances by the number of cycles specified, obtaining data from the sample source supplied
at construction, filtering it and passing it on to the speaker's delegate if there is one.
*/
void run_for(const Cycles cycles) {
if(!delegate_) return;
std::size_t cycles_remaining = size_t(cycles.as_integral());
if(!cycles_remaining) return;
FilterParameters filter_parameters;
{
std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_);
filter_parameters = filter_parameters_;
filter_parameters_.parameters_are_dirty = false;
filter_parameters_.input_rate_changed = false;
}
if(filter_parameters.parameters_are_dirty) update_filter_coefficients(filter_parameters);
if(filter_parameters.input_rate_changed) {
delegate_->speaker_did_change_input_clock(this);
}
// If input and output rates exactly match, and no additional cut-off has been specified,
// just accumulate results and pass on.
if( filter_parameters.input_cycles_per_second == filter_parameters.output_cycles_per_second &&
filter_parameters.high_frequency_cutoff < 0.0) {
while(cycles_remaining) {
const auto cycles_to_read = std::min(output_buffer_.size() - output_buffer_pointer_, cycles_remaining);
sample_source_.get_samples(cycles_to_read, &output_buffer_[output_buffer_pointer_]);
output_buffer_pointer_ += cycles_to_read;
// announce to delegate if full
if(output_buffer_pointer_ == output_buffer_.size()) {
output_buffer_pointer_ = 0;
did_complete_samples(this, output_buffer_);
}
cycles_remaining -= cycles_to_read;
}
return;
}
// If the output rate is less than the input rate, or an additional cut-off has been specified, use the filter.
if( filter_parameters.input_cycles_per_second > filter_parameters.output_cycles_per_second ||
(filter_parameters.input_cycles_per_second == filter_parameters.output_cycles_per_second && filter_parameters.high_frequency_cutoff >= 0.0)) {
while(cycles_remaining) {
const auto cycles_to_read = std::min(cycles_remaining, input_buffer_.size() - input_buffer_depth_);
sample_source_.get_samples(cycles_to_read, &input_buffer_[input_buffer_depth_]);
cycles_remaining -= cycles_to_read;
input_buffer_depth_ += cycles_to_read;
if(input_buffer_depth_ == input_buffer_.size()) {
output_buffer_[output_buffer_pointer_] = filter_->apply(input_buffer_.data());
output_buffer_pointer_++;
// Announce to delegate if full.
if(output_buffer_pointer_ == output_buffer_.size()) {
output_buffer_pointer_ = 0;
did_complete_samples(this, output_buffer_);
}
// If the next loop around is going to reuse some of the samples just collected, use a memmove to
// preserve them in the correct locations (TODO: use a longer buffer to fix that) and don't skip
// anything. Otherwise skip as required to get to the next sample batch and don't expect to reuse.
const auto steps = stepper_->step();
if(steps < input_buffer_.size()) {
auto *const input_buffer = input_buffer_.data();
std::memmove( input_buffer,
&input_buffer[steps],
sizeof(int16_t) * (input_buffer_.size() - steps));
input_buffer_depth_ -= steps;
} else {
if(steps > input_buffer_.size())
sample_source_.skip_samples(steps - input_buffer_.size());
input_buffer_depth_ = 0;
}
}
}
return;
}
// TODO: input rate is less than output rate
}
T &sample_source_;
std::size_t output_buffer_pointer_ = 0;
std::size_t input_buffer_depth_ = 0;
std::vector<int16_t> input_buffer_;
std::vector<int16_t> output_buffer_;
std::unique_ptr<SignalProcessing::Stepper> stepper_;
std::unique_ptr<SignalProcessing::FIRFilter> filter_;
std::mutex filter_parameters_mutex_;
struct FilterParameters {
float input_cycles_per_second = 0.0f;
float output_cycles_per_second = 0.0f;
float high_frequency_cutoff = -1.0;
bool parameters_are_dirty = true;
bool input_rate_changed = false;
} filter_parameters_;
void update_filter_coefficients(const FilterParameters &filter_parameters) {
float high_pass_frequency = filter_parameters.output_cycles_per_second / 2.0f;
if(filter_parameters.high_frequency_cutoff > 0.0) {
high_pass_frequency = std::min(filter_parameters.high_frequency_cutoff, high_pass_frequency);
}
// Make a guess at a good number of taps.
std::size_t number_of_taps = std::size_t(
ceilf((filter_parameters.input_cycles_per_second + high_pass_frequency) / high_pass_frequency)
);
number_of_taps = (number_of_taps * 2) | 1;
output_buffer_pointer_ = 0;
stepper_ = std::make_unique<SignalProcessing::Stepper>(
uint64_t(filter_parameters.input_cycles_per_second),
uint64_t(filter_parameters.output_cycles_per_second));
filter_ = std::make_unique<SignalProcessing::FIRFilter>(
static_cast<unsigned int>(number_of_taps),
filter_parameters.input_cycles_per_second,
0.0,
high_pass_frequency,
SignalProcessing::FIRFilter::DefaultAttenuation);
input_buffer_.resize(std::size_t(number_of_taps));
input_buffer_depth_ = 0;
}
};
}
}
#endif /* FilteringSpeaker_h */
<commit_msg>Avoids unnecessary filter recalculation.<commit_after>//
// FilteringSpeaker.h
// Clock Signal
//
// Created by Thomas Harte on 15/12/2017.
// Copyright 2017 Thomas Harte. All rights reserved.
//
#ifndef FilteringSpeaker_h
#define FilteringSpeaker_h
#include "../Speaker.hpp"
#include "../../../SignalProcessing/Stepper.hpp"
#include "../../../SignalProcessing/FIRFilter.hpp"
#include "../../../ClockReceiver/ClockReceiver.hpp"
#include "../../../Concurrency/AsyncTaskQueue.hpp"
#include <mutex>
#include <cstring>
#include <cmath>
namespace Outputs {
namespace Speaker {
/*!
The low-pass speaker expects an Outputs::Speaker::SampleSource-derived
template class, and uses the instance supplied to its constructor as the
source of a high-frequency stream of audio which it filters down to a
lower-frequency output.
*/
template <typename T> class LowpassSpeaker: public Speaker {
public:
LowpassSpeaker(T &sample_source) : sample_source_(sample_source) {
sample_source.set_sample_volume_range(32767);
}
// Implemented as per Speaker.
float get_ideal_clock_rate_in_range(float minimum, float maximum) final {
std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_);
// return twice the cut off, if applicable
if( filter_parameters_.high_frequency_cutoff > 0.0f &&
filter_parameters_.input_cycles_per_second >= filter_parameters_.high_frequency_cutoff * 3.0f &&
filter_parameters_.input_cycles_per_second <= filter_parameters_.high_frequency_cutoff * 3.0f)
return filter_parameters_.high_frequency_cutoff * 3.0f;
// return exactly the input rate if possible
if( filter_parameters_.input_cycles_per_second >= minimum &&
filter_parameters_.input_cycles_per_second <= maximum)
return filter_parameters_.input_cycles_per_second;
// if the input rate is lower, return the minimum
if(filter_parameters_.input_cycles_per_second < minimum)
return minimum;
// otherwise, return the maximum
return maximum;
}
// Implemented as per Speaker.
void set_computed_output_rate(float cycles_per_second, int buffer_size) final {
std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_);
if(filter_parameters_.output_cycles_per_second == cycles_per_second && size_t(buffer_size) == output_buffer_.size()) {
return;
}
filter_parameters_.output_cycles_per_second = cycles_per_second;
filter_parameters_.parameters_are_dirty = true;
output_buffer_.resize(std::size_t(buffer_size));
}
/*!
Sets the clock rate of the input audio.
*/
void set_input_rate(float cycles_per_second) {
std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_);
if(filter_parameters_.input_cycles_per_second == cycles_per_second) {
return;
}
filter_parameters_.input_cycles_per_second = cycles_per_second;
filter_parameters_.parameters_are_dirty = true;
filter_parameters_.input_rate_changed = true;
}
/*!
Allows a cut-off frequency to be specified for audio. Ordinarily this low-pass speaker
will determine a cut-off based on the output audio rate. A caller can manually select
an alternative cut-off. This allows machines with a low-pass filter on their audio output
path to be explicit about its effect, and get that simulation for free.
*/
void set_high_frequency_cutoff(float high_frequency) {
std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_);
if(filter_parameters_.high_frequency_cutoff == high_frequency) {
return;
}
filter_parameters_.high_frequency_cutoff = high_frequency;
filter_parameters_.parameters_are_dirty = true;
}
/*!
Schedules an advancement by the number of cycles specified on the provided queue.
The speaker will advance by obtaining data from the sample source supplied
at construction, filtering it and passing it on to the speaker's delegate if there is one.
*/
void run_for(Concurrency::DeferringAsyncTaskQueue &queue, const Cycles cycles) {
queue.defer([this, cycles] {
run_for(cycles);
});
}
private:
/*!
Advances by the number of cycles specified, obtaining data from the sample source supplied
at construction, filtering it and passing it on to the speaker's delegate if there is one.
*/
void run_for(const Cycles cycles) {
if(!delegate_) return;
std::size_t cycles_remaining = size_t(cycles.as_integral());
if(!cycles_remaining) return;
FilterParameters filter_parameters;
{
std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_);
filter_parameters = filter_parameters_;
filter_parameters_.parameters_are_dirty = false;
filter_parameters_.input_rate_changed = false;
}
if(filter_parameters.parameters_are_dirty) update_filter_coefficients(filter_parameters);
if(filter_parameters.input_rate_changed) {
delegate_->speaker_did_change_input_clock(this);
}
// If input and output rates exactly match, and no additional cut-off has been specified,
// just accumulate results and pass on.
if( filter_parameters.input_cycles_per_second == filter_parameters.output_cycles_per_second &&
filter_parameters.high_frequency_cutoff < 0.0) {
while(cycles_remaining) {
const auto cycles_to_read = std::min(output_buffer_.size() - output_buffer_pointer_, cycles_remaining);
sample_source_.get_samples(cycles_to_read, &output_buffer_[output_buffer_pointer_]);
output_buffer_pointer_ += cycles_to_read;
// announce to delegate if full
if(output_buffer_pointer_ == output_buffer_.size()) {
output_buffer_pointer_ = 0;
did_complete_samples(this, output_buffer_);
}
cycles_remaining -= cycles_to_read;
}
return;
}
// If the output rate is less than the input rate, or an additional cut-off has been specified, use the filter.
if( filter_parameters.input_cycles_per_second > filter_parameters.output_cycles_per_second ||
(filter_parameters.input_cycles_per_second == filter_parameters.output_cycles_per_second && filter_parameters.high_frequency_cutoff >= 0.0)) {
while(cycles_remaining) {
const auto cycles_to_read = std::min(cycles_remaining, input_buffer_.size() - input_buffer_depth_);
sample_source_.get_samples(cycles_to_read, &input_buffer_[input_buffer_depth_]);
cycles_remaining -= cycles_to_read;
input_buffer_depth_ += cycles_to_read;
if(input_buffer_depth_ == input_buffer_.size()) {
output_buffer_[output_buffer_pointer_] = filter_->apply(input_buffer_.data());
output_buffer_pointer_++;
// Announce to delegate if full.
if(output_buffer_pointer_ == output_buffer_.size()) {
output_buffer_pointer_ = 0;
did_complete_samples(this, output_buffer_);
}
// If the next loop around is going to reuse some of the samples just collected, use a memmove to
// preserve them in the correct locations (TODO: use a longer buffer to fix that) and don't skip
// anything. Otherwise skip as required to get to the next sample batch and don't expect to reuse.
const auto steps = stepper_->step();
if(steps < input_buffer_.size()) {
auto *const input_buffer = input_buffer_.data();
std::memmove( input_buffer,
&input_buffer[steps],
sizeof(int16_t) * (input_buffer_.size() - steps));
input_buffer_depth_ -= steps;
} else {
if(steps > input_buffer_.size())
sample_source_.skip_samples(steps - input_buffer_.size());
input_buffer_depth_ = 0;
}
}
}
return;
}
// TODO: input rate is less than output rate
}
T &sample_source_;
std::size_t output_buffer_pointer_ = 0;
std::size_t input_buffer_depth_ = 0;
std::vector<int16_t> input_buffer_;
std::vector<int16_t> output_buffer_;
std::unique_ptr<SignalProcessing::Stepper> stepper_;
std::unique_ptr<SignalProcessing::FIRFilter> filter_;
std::mutex filter_parameters_mutex_;
struct FilterParameters {
float input_cycles_per_second = 0.0f;
float output_cycles_per_second = 0.0f;
float high_frequency_cutoff = -1.0;
bool parameters_are_dirty = true;
bool input_rate_changed = false;
} filter_parameters_;
void update_filter_coefficients(const FilterParameters &filter_parameters) {
float high_pass_frequency = filter_parameters.output_cycles_per_second / 2.0f;
if(filter_parameters.high_frequency_cutoff > 0.0) {
high_pass_frequency = std::min(filter_parameters.high_frequency_cutoff, high_pass_frequency);
}
// Make a guess at a good number of taps.
std::size_t number_of_taps = std::size_t(
ceilf((filter_parameters.input_cycles_per_second + high_pass_frequency) / high_pass_frequency)
);
number_of_taps = (number_of_taps * 2) | 1;
output_buffer_pointer_ = 0;
stepper_ = std::make_unique<SignalProcessing::Stepper>(
uint64_t(filter_parameters.input_cycles_per_second),
uint64_t(filter_parameters.output_cycles_per_second));
filter_ = std::make_unique<SignalProcessing::FIRFilter>(
static_cast<unsigned int>(number_of_taps),
filter_parameters.input_cycles_per_second,
0.0,
high_pass_frequency,
SignalProcessing::FIRFilter::DefaultAttenuation);
input_buffer_.resize(std::size_t(number_of_taps));
input_buffer_depth_ = 0;
}
};
}
}
#endif /* FilteringSpeaker_h */
<|endoftext|> |
<commit_before><commit_msg>change pion selections<commit_after><|endoftext|> |
<commit_before><commit_msg>use prefix and suffix in names<commit_after><|endoftext|> |
<commit_before>// $Id$
AliAnalysisTaskEmcalJetHMEC* AddTaskEmcalJetHMEC(
const char *outfilename = "AnalysisOutput.root",
const char *nJets = "Jets",
const char *nTracks = "PicoTracks",
const char *nCaloClusters = "CaloClustersCorr",
const Double_t minPhi = 1.8,
const Double_t maxPhi = 2.74,
const Double_t minEta = -0.3,
const Double_t maxEta = 0.3,
const Double_t minArea = 0.4,
const Int_t EvtMix = 0,
const Double_t TrkBias = 5,
const Double_t ClusBias = 5,
const Double_t TrkEta = 0.9,
const Int_t nmixingTR = 5000,
const Int_t nmixingEV = 5,
UInt_t trigevent = AliVEvent::kAny,
UInt_t mixevent = AliVEvent::kAny,
Bool_t lessSparseAxes = 0,
Bool_t widertrackbin = 0,
UInt_t centbinsize = 1,
const Int_t doEffcorrSW = 0,
const char *branch = "biased",
const char *CentEst = "V0M",
const Short_t runtype = 2, //0 - pp, 1 - pA, 2 - AA
Bool_t embeddingCorrection = kTRUE,
const char * embeddingCorrectionFilename = "alien:///alice/cern.ch/user/r/rehlersi/embeddingCorrection.root",
const char * embeddingCorrectionHistName = "embeddingCorrection"
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEmcalJetHMEC", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEmcalJetHMEC", "This task requires an input event handler");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
TString name(Form("Correlations_%s_%s", nJets, branch));
AliAnalysisTaskEmcalJetHMEC *correlationtask = new AliAnalysisTaskEmcalJetHMEC(name);
correlationtask->SetJetsName(nJets);
correlationtask->SetTracksName(nTracks);
correlationtask->SetCaloClustersName(nCaloClusters);
correlationtask->SetJetPhi(minPhi,maxPhi);
correlationtask->SetJetEta(minEta,maxEta);
correlationtask->SetAreaCut(minArea);
if(EvtMix>0){
correlationtask->SetMixingTracks(EvtMix);
correlationtask->SetEventMixing(1);
correlationtask->SetNMixedTracks(nmixingTR);
correlationtask->SetNMixedEvents(nmixingEV);
}else{
correlationtask->SetEventMixing(EvtMix);
}
correlationtask->SetTrkBias(TrkBias);
correlationtask->SetClusBias(ClusBias);
correlationtask->SetTrkEta(TrkEta);
correlationtask->SetTrigType(trigevent);
correlationtask->SetMixType(mixevent);
correlationtask->SetDoLessSparseAxes(lessSparseAxes);
correlationtask->SetDoWiderTrackBin(widertrackbin);
correlationtask->SetCentBinSize(centbinsize);
correlationtask->SetDoEffCorr(doEffcorrSW);
correlationtask->SetCentralityEstimator(CentEst);
correlationtask->SetRunType(runtype);
if (embeddingCorrection == kTRUE)
{
// Open file containing the correction
TFile * embeddingCorrectionFile = TFile::Open(embeddingCorrectionFilename);
if (!embeddingCorrectionFile || embeddingCorrectionFile->IsZombie()) {
::Error("AddTaskEmcalJetHMEC", Form("Could not open embedding correction file %s", embeddingCorrectionFilename));
return NULL;
}
// Retrieve the histogram containing the correction and save add it to the task.
TH2F * embeddingCorrectionHist = dynamic_cast<TH2F*>(file->Get(embeddingCorrectionHistName));
if (embeddingCorrectionHist) {
::Info("AddTaskEmcalJetHMEC", Form("Embedding correction %s loaded from file %s.", embeddingCorrectionHistName, embeddingCorrectionFilename));
}
else {
::Error("AddTaskEmcalJetHMEC", Form("Embedding correction %s not found in file %s.", embeddingCorrectionHistName, embeddingCorrectionFilename));
return NULL;
}
correlationtask->SetEmbeddingCorrectionHist(embeddingCorrectionHist);
}
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(correlationtask);
// Create containers for input/output
mgr->ConnectInput (correlationtask, 0, mgr->GetCommonInputContainer() );
AliAnalysisDataContainer *cojeth = mgr->CreateContainer(name,
TList::Class(),
AliAnalysisManager::kOutputContainer,
outfilename);
mgr->ConnectOutput(correlationtask,1,cojeth);
return correlationtask;
}
<commit_msg>JetH: Update macro for new jet framework<commit_after>// $Id$
AliAnalysisTaskEmcalJetHMEC* AddTaskEmcalJetHMEC(
const char *outfilename = "AnalysisOutput.root",
const char *nJets = "Jets",
const char *nTracks = "PicoTracks",
const char *nCaloClusters = "CaloClustersCorr",
const Double_t minPhi = 1.8,
const Double_t maxPhi = 2.74,
const Double_t minEta = -0.3,
const Double_t maxEta = 0.3,
const Double_t minArea = 0.4,
const Int_t EvtMix = 0,
const Double_t TrkBias = 5,
const Double_t ClusBias = 5,
const Double_t TrkEta = 0.9,
const Int_t nmixingTR = 5000,
const Int_t nmixingEV = 5,
UInt_t trigevent = AliVEvent::kAny,
UInt_t mixevent = AliVEvent::kAny,
Bool_t lessSparseAxes = 0,
Bool_t widertrackbin = 0,
UInt_t centbinsize = 1,
const Int_t doEffcorrSW = 0,
const char *branch = "biased",
const char *CentEst = "V0M",
const Short_t runtype = 2, //0 - pp, 1 - pA, 2 - AA
Bool_t embeddingCorrection = kFALSE,
const char * embeddingCorrectionFilename = "alien:///alice/cern.ch/user/r/rehlersi/embeddingCorrection.root",
const char * embeddingCorrectionHistName = "embeddingCorrection"
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEmcalJetHMEC", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEmcalJetHMEC", "This task requires an input event handler");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
// Determine cluster and track names
TString trackName(ntracks);
TString clusName(nclusters);
if (trackName == "usedefault") {
if (dataType == kESD) {
trackName = "Tracks";
}
else if (dataType == kAOD) {
trackName = "tracks";
}
else {
trackName = "";
}
}
if (clusName == "usedefault") {
if (dataType == kESD) {
clusName = "CaloClusters";
}
else if (dataType == kAOD) {
clusName = "caloClusters";
}
else {
clusName = "";
}
}
TString name(Form("Correlations_%s_%s", nJets, branch));
Double_t jetRadius = 0.2;
AliAnalysisTaskEmcalJetHMEC *correlationtask = new AliAnalysisTaskEmcalJetHMEC(name);
//correlationtask->SetJetsName(nJets);
//correlationtask->SetTracksName(nTracks);
//correlationtask->SetCaloClustersName(nCaloClusters);
correlationtask->SetJetPhi(minPhi,maxPhi);
correlationtask->SetJetEta(minEta,maxEta);
correlationtask->SetAreaCut(minArea);
if(EvtMix>0){
correlationtask->SetMixingTracks(EvtMix);
correlationtask->SetEventMixing(1);
correlationtask->SetNMixedTracks(nmixingTR);
correlationtask->SetNMixedEvents(nmixingEV);
}else{
correlationtask->SetEventMixing(EvtMix);
}
correlationtask->SetTrkBias(TrkBias);
correlationtask->SetClusBias(ClusBias);
correlationtask->SetTrkEta(TrkEta);
correlationtask->SetTrigType(trigevent);
correlationtask->SetMixType(mixevent);
correlationtask->SetDoLessSparseAxes(lessSparseAxes);
correlationtask->SetDoWiderTrackBin(widertrackbin);
correlationtask->SetCentBinSize(centbinsize);
correlationtask->SetDoEffCorr(doEffcorrSW);
correlationtask->SetCentralityEstimator(CentEst);
correlationtask->SetRunType(runtype);
// Add Containers
// Clusters
AliClusterContainer * clusterContainer = correlationtask->AddClusterContainer(nCaloClusters);
clusterContainer->SetMinE(3);
// Tracks
AliTrackContainer * trackContainer = correlationtask->AddTrackContainer(nTracks);
trackContainer->SetMinPt(3);
trackContainer->SetEtaLimits(-1.0*TrkEta, TrkEta)
// Jets
cout <<"Jet name: " << nJets;
AliJetContainer * jetContainer = correlationtask->AddJetContainer(AliJetContainer::kFullJet,
AliJetContainer::antikt_algorithm,
AliJetContainer::pt_scheme,
jetRadius,
AliJetContainer::kEMCALfid,
trackContainer,
clusterContainer);
if (embeddingCorrection == kTRUE)
{
// Open file containing the correction
TFile * embeddingCorrectionFile = TFile::Open(embeddingCorrectionFilename);
if (!embeddingCorrectionFile || embeddingCorrectionFile->IsZombie()) {
::Error("AddTaskEmcalJetHMEC", Form("Could not open embedding correction file %s", embeddingCorrectionFilename));
return NULL;
}
// Retrieve the histogram containing the correction and save add it to the task.
TH2F * embeddingCorrectionHist = dynamic_cast<TH2F*>(file->Get(embeddingCorrectionHistName));
if (embeddingCorrectionHist) {
::Info("AddTaskEmcalJetHMEC", Form("Embedding correction %s loaded from file %s.", embeddingCorrectionHistName, embeddingCorrectionFilename));
}
else {
::Error("AddTaskEmcalJetHMEC", Form("Embedding correction %s not found in file %s.", embeddingCorrectionHistName, embeddingCorrectionFilename));
return NULL;
}
correlationtask->SetEmbeddingCorrectionHist(embeddingCorrectionHist);
}
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(correlationtask);
// Create containers for input/output
mgr->ConnectInput (correlationtask, 0, mgr->GetCommonInputContainer() );
AliAnalysisDataContainer *cojeth = mgr->CreateContainer(name,
TList::Class(),
AliAnalysisManager::kOutputContainer,
outfilename);
mgr->ConnectOutput(correlationtask,1,cojeth);
return correlationtask;
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include "autopilot_tester.h"
#include <chrono>
TEST_CASE("Offboard takeoff and land", "[multicopter][offboard][nogps]")
{
AutopilotTester tester;
Offboard::PositionNedYaw takeoff_position {0.0f, 0.0f, -2.0f, 0.0f};
tester.connect(connection_url);
tester.wait_until_ready_local_position_only();
tester.store_home();
tester.arm();
std::chrono::seconds goto_timeout = std::chrono::seconds(90);
tester.offboard_goto(takeoff_position, 0.1f, goto_timeout);
tester.offboard_land();
tester.wait_until_disarmed(goto_timeout);
tester.check_home_within(1.0f);
}
TEST_CASE("Offboard position control", "[multicopter][offboard][nogps]")
{
AutopilotTester tester;
Offboard::PositionNedYaw takeoff_position {0.0f, 0.0f, -2.0f, 0.0f};
Offboard::PositionNedYaw setpoint_1 {0.0f, 5.0f, -2.0f, 180.0f};
Offboard::PositionNedYaw setpoint_2 {5.0f, 5.0f, -4.0f, 180.0f};
Offboard::PositionNedYaw setpoint_3 {5.0f, 0.0f, -4.0f, 90.0f};
tester.connect(connection_url);
tester.wait_until_ready_local_position_only();
tester.store_home();
tester.arm();
std::chrono::seconds goto_timeout = std::chrono::seconds(90);
tester.offboard_goto(takeoff_position, 0.1f, goto_timeout);
tester.offboard_goto(setpoint_1, 0.1f, goto_timeout);
tester.offboard_goto(setpoint_2, 0.1f, goto_timeout);
tester.offboard_goto(setpoint_3, 0.1f, goto_timeout);
tester.offboard_goto(takeoff_position, 0.1f, goto_timeout);
tester.offboard_land();
tester.wait_until_disarmed(goto_timeout);
tester.check_home_within(1.0f);
}
<commit_msg>mavsdk_tests: wait even longer<commit_after>/****************************************************************************
*
* Copyright (c) 2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include "autopilot_tester.h"
#include <chrono>
TEST_CASE("Offboard takeoff and land", "[multicopter][offboard][nogps]")
{
AutopilotTester tester;
Offboard::PositionNedYaw takeoff_position {0.0f, 0.0f, -2.0f, 0.0f};
tester.connect(connection_url);
tester.wait_until_ready_local_position_only();
tester.store_home();
tester.arm();
std::chrono::seconds goto_timeout = std::chrono::seconds(90);
tester.offboard_goto(takeoff_position, 0.1f, goto_timeout);
tester.offboard_land();
tester.wait_until_disarmed(std::chrono::seconds(120));
tester.check_home_within(1.0f);
}
TEST_CASE("Offboard position control", "[multicopter][offboard][nogps]")
{
AutopilotTester tester;
Offboard::PositionNedYaw takeoff_position {0.0f, 0.0f, -2.0f, 0.0f};
Offboard::PositionNedYaw setpoint_1 {0.0f, 5.0f, -2.0f, 180.0f};
Offboard::PositionNedYaw setpoint_2 {5.0f, 5.0f, -4.0f, 180.0f};
Offboard::PositionNedYaw setpoint_3 {5.0f, 0.0f, -4.0f, 90.0f};
tester.connect(connection_url);
tester.wait_until_ready_local_position_only();
tester.store_home();
tester.arm();
std::chrono::seconds goto_timeout = std::chrono::seconds(90);
tester.offboard_goto(takeoff_position, 0.1f, goto_timeout);
tester.offboard_goto(setpoint_1, 0.1f, goto_timeout);
tester.offboard_goto(setpoint_2, 0.1f, goto_timeout);
tester.offboard_goto(setpoint_3, 0.1f, goto_timeout);
tester.offboard_goto(takeoff_position, 0.1f, goto_timeout);
tester.offboard_land();
tester.wait_until_disarmed(std::chrono::seconds(120));
tester.check_home_within(1.0f);
}
<|endoftext|> |
<commit_before>#include "tokenizer.hpp"
<commit_msg>Update tokenizer.cpp<commit_after>#include "tokenizer.hpp"
Command userCommand;
userCommand.getSentence();
<|endoftext|> |
<commit_before>#pragma once
#include <tuple>
#include <type_traits>
#include <cmath>
#include <limits>
namespace spn {
//! コンパイル時数値計算 & 比較
template <int M, int N>
struct TValue {
enum { add = M+N,
sub = M-N,
less = (M>N) ? N : M,
great = (M>N) ? M : N,
less_eq = (M<=N) ? 1 : 0,
great_eq = (M>=N) ? 1 : 0,
lesser = (M<N) ? 1 : 0,
greater = (M>N) ? 1 : 0,
equal = M==N ? 1 : 0
};
};
//! bool -> std::true_type or std::false_type
template <int V>
using TFCond = typename std::conditional<V!=0, std::true_type, std::false_type>::type;
//! 2つの定数の演算結果をstd::true_type か std::false_typeで返す
template <int N, int M>
struct NType {
using t_and = TFCond<(N&M)>;
using t_or = TFCond<(N|M)>;
using t_xor = TFCond<(N^M)>;
using t_nand = TFCond<((N&M) ^ 0x01)>;
using less = TFCond<(N<M)>;
using great = TFCond<(N>M)>;
using equal = TFCond<N==M>;
using not_equal = TFCond<N!=M>;
using less_eq = TFCond<(N<=M)>;
using great_eq = TFCond<(N>=M)>;
};
//! 2つのintegral_constant<bool>を論理演算
template <class T0, class T1>
struct TType {
constexpr static int I0 = std::is_same<T0, std::true_type>::value,
I1 = std::is_same<T1, std::true_type>::value;
using t_and = TFCond<I0&I1>;
using t_or = TFCond<I0|I1>;
using t_xor = TFCond<I0^I1>;
using t_nand = TFCond<(I0&I1) ^ 0x01>;
};
//! 要素カウント
#define countof(a) static_cast<int>(sizeof((a))/sizeof((a)[0]))
//! 条件式の評価結果がfalseの場合、マクロ定義した箇所には到達しないことを保証
#define __assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0);
//! 最大値を取得
template <int... N>
struct TMax {
constexpr static int result = 0; };
template <int N0, int... N>
struct TMax<N0, N...> {
constexpr static int result = N0; };
template <int N0, int N1, int... N>
struct TMax<N0, N1, N...> {
constexpr static int result = TValue<N0, TMax<N1, N...>::result>::great; };
//! SFINAEで関数を無効化する際に使うダミー変数
static void* Enabler;
//! コンパイル時定数で数値のN*10乗を計算
template <class T, int N, typename std::enable_if<N==0>::type*& = Enabler>
constexpr T ConstantPow10(T value=1, std::integral_constant<int,N>* =nullptr) {
return value;
}
template <class T, int N, typename std::enable_if<(N<0)>::type*& = Enabler>
constexpr T ConstantPow10(T value=1, std::integral_constant<int,N>* =nullptr) {
return ConstantPow10(value/10, (std::integral_constant<int,N+1>*)nullptr);
}
template <class T, int N, typename std::enable_if<(N>0)>::type*& = Enabler>
constexpr T ConstantPow10(T value=1.f, std::integral_constant<int,N>* =nullptr) {
return ConstantPow10(value*10, (std::integral_constant<int,N-1>*)nullptr);
}
//! std::tupleのハッシュを計算
struct TupleHash {
template <class Tup>
static size_t get(size_t value, const Tup& /*tup*/, std::integral_constant<int,-1>) { return value; }
template <class Tup, int N>
static size_t get(size_t value, const Tup& tup, std::integral_constant<int,N>) {
const auto& t = std::get<N>(tup);
size_t h = std::hash<typename std::decay<decltype(t)>::type>()(t);
value = (value ^ (h<<(h&0x07))) ^ (h>>3);
return get(value, tup, std::integral_constant<int,N-1>());
}
template <class... Ts>
size_t operator()(const std::tuple<Ts...>& tup) const {
return get(0xdeadbeef * 0xdeadbeef, tup, std::integral_constant<int,sizeof...(Ts)-1>());
}
};
//! クラスがwidthフィールドを持っていればintegral_constantでそれを返す
template <class T>
std::integral_constant<int,T::width> _GetWidthT(decltype(T::width)*);
template <class T>
std::integral_constant<int,0> _GetWidthT(...);
template <class T>
decltype(_GetWidthT<T>(nullptr)) GetWidthT();
//! クラスがheightフィールドを持っていればintegral_constantでそれを返す
template <class T>
std::integral_constant<int,T::height> _GetHeightT(decltype(T::height)*);
template <class T>
std::integral_constant<int,0> _GetHeightT(...);
template <class T>
decltype(_GetHeightT<T>(nullptr)) GetHeightT();
//! クラスがwidthとheightフィールドを持っていればintegral_pairでそれを返す
template <class T, T val0, T val1>
using integral_pair = std::pair<std::integral_constant<T, val0>,
std::integral_constant<T, val1>>;
template <class T>
integral_pair<int,T::height, T::width> _GetWidthHeightT(decltype(T::width)*, decltype(T::height)*);
template <class T>
integral_pair<int,0, T::width> _GetWidthHeightT(decltype(T::width)*, ...);
template <class T>
integral_pair<int,0,0> _GetWidthHeightT(...);
template <class T>
decltype(_GetWidthHeightT<T>(nullptr,nullptr)) GetWidthHeightT();
// 値比較(widthメンバ有り)
template <class T, class CMP, int N>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,0,N>) {
for(int i=0 ; i<N ; i++) {
if(!cmp(v0.m[i], v1.m[i]))
return false;
}
return true;
}
// 値比較(width & heightメンバ有り)
template <class T, class CMP, int M, int N>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,M,N>) {
for(int i=0 ; i<M ; i++) {
for(int j=0 ; j<N ; j++) {
if(!cmp(v0.ma[i][j], v1.ma[i][j]))
return false;
}
}
return true;
}
// 値比較(単一値)
template <class T, class CMP>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,0,0>) {
return cmp(v0, v1);
}
//! 絶対値の誤差による等値判定
/*! \param[in] val value to check
\param[in] vExcept target value
\param[in] vEps value threshold */
template <class T, class T2>
bool EqAbs(const T& val, const T& vExcept, T2 vEps = std::numeric_limits<T>::epsilon()) {
auto fnCmp = [vEps](const auto& val, const auto& except){ return std::fabs(except-val) <= vEps; };
return _EqFunc(val, vExcept, fnCmp, decltype(GetWidthHeightT<T>())());
}
template <class T, class... Ts>
bool EqAbsT(const std::tuple<Ts...>& /*tup0*/, const std::tuple<Ts...>& /*tup1*/, const T& /*epsilon*/, std::integral_constant<int,-1>*) {
return true;
}
//! std::tuple全部の要素に対してEqAbsを呼ぶ
template <class T, int N, class... Ts, typename std::enable_if<(N>=0)>::type*& = Enabler>
bool EqAbsT(const std::tuple<Ts...>& tup0, const std::tuple<Ts...>& tup1, const T& epsilon, std::integral_constant<int,N>*) {
return EqAbs(std::get<N>(tup0), std::get<N>(tup1), epsilon)
&& EqAbsT(tup0, tup1, epsilon, (std::integral_constant<int,N-1>*)nullptr);
}
template <class... Ts, class T>
bool EqAbs(const std::tuple<Ts...>& tup0, const std::tuple<Ts...>& tup1, const T& epsilon) {
return EqAbsT<T>(tup0, tup1, epsilon, (std::integral_constant<int,sizeof...(Ts)-1>*)nullptr);
}
//! 浮動少数点数の値がNaNになっているか
template <class T, class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool IsNaN(const T& val) {
return !(val>=T(0)) && !(val<T(0)); }
//! 浮動少数点数の値がNaN又は無限大になっているか
template <class T, class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool IsOutstanding(const T& val) {
auto valA = std::fabs(val);
return valA==std::numeric_limits<float>::infinity() || IsNaN(valA); }
//! std::tupleの要素ごとの距離(EqAbs)比較
template <class T, int NPow>
struct TupleNear {
template <class P>
bool operator()(const P& t0, const P& t1) const {
return EqAbs(t0, t1, spn::ConstantPow10<T,NPow>());
}
};
}
<commit_msg>countofマクロを改良(配列以外を渡すとコンパイルエラー)<commit_after>#pragma once
#include <tuple>
#include <type_traits>
#include <cmath>
#include <limits>
namespace spn {
//! コンパイル時数値計算 & 比較
template <int M, int N>
struct TValue {
enum { add = M+N,
sub = M-N,
less = (M>N) ? N : M,
great = (M>N) ? M : N,
less_eq = (M<=N) ? 1 : 0,
great_eq = (M>=N) ? 1 : 0,
lesser = (M<N) ? 1 : 0,
greater = (M>N) ? 1 : 0,
equal = M==N ? 1 : 0
};
};
//! bool -> std::true_type or std::false_type
template <int V>
using TFCond = typename std::conditional<V!=0, std::true_type, std::false_type>::type;
//! 2つの定数の演算結果をstd::true_type か std::false_typeで返す
template <int N, int M>
struct NType {
using t_and = TFCond<(N&M)>;
using t_or = TFCond<(N|M)>;
using t_xor = TFCond<(N^M)>;
using t_nand = TFCond<((N&M) ^ 0x01)>;
using less = TFCond<(N<M)>;
using great = TFCond<(N>M)>;
using equal = TFCond<N==M>;
using not_equal = TFCond<N!=M>;
using less_eq = TFCond<(N<=M)>;
using great_eq = TFCond<(N>=M)>;
};
//! 2つのintegral_constant<bool>を論理演算
template <class T0, class T1>
struct TType {
constexpr static int I0 = std::is_same<T0, std::true_type>::value,
I1 = std::is_same<T1, std::true_type>::value;
using t_and = TFCond<I0&I1>;
using t_or = TFCond<I0|I1>;
using t_xor = TFCond<I0^I1>;
using t_nand = TFCond<(I0&I1) ^ 0x01>;
};
//! 条件式の評価結果がfalseの場合、マクロ定義した箇所には到達しないことを保証
#define __assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0);
//! 最大値を取得
template <int... N>
struct TMax {
constexpr static int result = 0; };
template <int N0, int... N>
struct TMax<N0, N...> {
constexpr static int result = N0; };
template <int N0, int N1, int... N>
struct TMax<N0, N1, N...> {
constexpr static int result = TValue<N0, TMax<N1, N...>::result>::great; };
//! SFINAEで関数を無効化する際に使うダミー変数
static void* Enabler;
//! コンパイル時定数で数値のN*10乗を計算
template <class T, int N, typename std::enable_if<N==0>::type*& = Enabler>
constexpr T ConstantPow10(T value=1, std::integral_constant<int,N>* =nullptr) {
return value;
}
template <class T, int N, typename std::enable_if<(N<0)>::type*& = Enabler>
constexpr T ConstantPow10(T value=1, std::integral_constant<int,N>* =nullptr) {
return ConstantPow10(value/10, (std::integral_constant<int,N+1>*)nullptr);
}
template <class T, int N, typename std::enable_if<(N>0)>::type*& = Enabler>
constexpr T ConstantPow10(T value=1.f, std::integral_constant<int,N>* =nullptr) {
return ConstantPow10(value*10, (std::integral_constant<int,N-1>*)nullptr);
}
//! std::tupleのハッシュを計算
struct TupleHash {
template <class Tup>
static size_t get(size_t value, const Tup& /*tup*/, std::integral_constant<int,-1>) { return value; }
template <class Tup, int N>
static size_t get(size_t value, const Tup& tup, std::integral_constant<int,N>) {
const auto& t = std::get<N>(tup);
size_t h = std::hash<typename std::decay<decltype(t)>::type>()(t);
value = (value ^ (h<<(h&0x07))) ^ (h>>3);
return get(value, tup, std::integral_constant<int,N-1>());
}
template <class... Ts>
size_t operator()(const std::tuple<Ts...>& tup) const {
return get(0xdeadbeef * 0xdeadbeef, tup, std::integral_constant<int,sizeof...(Ts)-1>());
}
};
//! クラスがwidthフィールドを持っていればintegral_constantでそれを返す
template <class T>
std::integral_constant<int,T::width> _GetWidthT(decltype(T::width)*);
template <class T>
std::integral_constant<int,0> _GetWidthT(...);
template <class T>
decltype(_GetWidthT<T>(nullptr)) GetWidthT();
//! クラスがheightフィールドを持っていればintegral_constantでそれを返す
template <class T>
std::integral_constant<int,T::height> _GetHeightT(decltype(T::height)*);
template <class T>
std::integral_constant<int,0> _GetHeightT(...);
template <class T>
decltype(_GetHeightT<T>(nullptr)) GetHeightT();
//! クラスがwidthとheightフィールドを持っていればintegral_pairでそれを返す
template <class T, T val0, T val1>
using integral_pair = std::pair<std::integral_constant<T, val0>,
std::integral_constant<T, val1>>;
template <class T>
integral_pair<int,T::height, T::width> _GetWidthHeightT(decltype(T::width)*, decltype(T::height)*);
template <class T>
integral_pair<int,0, T::width> _GetWidthHeightT(decltype(T::width)*, ...);
template <class T>
integral_pair<int,0,0> _GetWidthHeightT(...);
template <class T>
decltype(_GetWidthHeightT<T>(nullptr,nullptr)) GetWidthHeightT();
// 値比較(widthメンバ有り)
template <class T, class CMP, int N>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,0,N>) {
for(int i=0 ; i<N ; i++) {
if(!cmp(v0.m[i], v1.m[i]))
return false;
}
return true;
}
// 値比較(width & heightメンバ有り)
template <class T, class CMP, int M, int N>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,M,N>) {
for(int i=0 ; i<M ; i++) {
for(int j=0 ; j<N ; j++) {
if(!cmp(v0.ma[i][j], v1.ma[i][j]))
return false;
}
}
return true;
}
// 値比較(単一値)
template <class T, class CMP>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,0,0>) {
return cmp(v0, v1);
}
//! 絶対値の誤差による等値判定
/*! \param[in] val value to check
\param[in] vExcept target value
\param[in] vEps value threshold */
template <class T, class T2>
bool EqAbs(const T& val, const T& vExcept, T2 vEps = std::numeric_limits<T>::epsilon()) {
auto fnCmp = [vEps](const auto& val, const auto& except){ return std::fabs(except-val) <= vEps; };
return _EqFunc(val, vExcept, fnCmp, decltype(GetWidthHeightT<T>())());
}
template <class T, class... Ts>
bool EqAbsT(const std::tuple<Ts...>& /*tup0*/, const std::tuple<Ts...>& /*tup1*/, const T& /*epsilon*/, std::integral_constant<int,-1>*) {
return true;
}
//! std::tuple全部の要素に対してEqAbsを呼ぶ
template <class T, int N, class... Ts, typename std::enable_if<(N>=0)>::type*& = Enabler>
bool EqAbsT(const std::tuple<Ts...>& tup0, const std::tuple<Ts...>& tup1, const T& epsilon, std::integral_constant<int,N>*) {
return EqAbs(std::get<N>(tup0), std::get<N>(tup1), epsilon)
&& EqAbsT(tup0, tup1, epsilon, (std::integral_constant<int,N-1>*)nullptr);
}
template <class... Ts, class T>
bool EqAbs(const std::tuple<Ts...>& tup0, const std::tuple<Ts...>& tup1, const T& epsilon) {
return EqAbsT<T>(tup0, tup1, epsilon, (std::integral_constant<int,sizeof...(Ts)-1>*)nullptr);
}
//! 浮動少数点数の値がNaNになっているか
template <class T, class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool IsNaN(const T& val) {
return !(val>=T(0)) && !(val<T(0)); }
//! 浮動少数点数の値がNaN又は無限大になっているか
template <class T, class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool IsOutstanding(const T& val) {
auto valA = std::fabs(val);
return valA==std::numeric_limits<float>::infinity() || IsNaN(valA); }
//! std::tupleの要素ごとの距離(EqAbs)比較
template <class T, int NPow>
struct TupleNear {
template <class P>
bool operator()(const P& t0, const P& t1) const {
return EqAbs(t0, t1, spn::ConstantPow10<T,NPow>());
}
};
template <size_t N>
struct GetCountOf_helper {
using type = char [N];
};
template <class T, size_t N>
typename GetCountOf_helper<N>::type& GetCountOf(T (&)[N]);
//! 配列の要素数を取得する (配列でない場合はエラー)
#define countof(e) sizeof(::spn::GetCountOf(e))
template <class T>
char GetCountOfNA(T);
template <class T, size_t N>
typename GetCountOf_helper<N>::type& GetCountOfNA(T (&)[N]);
//! 配列の要素数を取得する (配列でない場合は1が返る)
#define countof_na(e) sizeof(::spn::GetCountOfNA(e))
}
<|endoftext|> |
<commit_before>/*
* newdatasetwidget.cpp
*
* Created on: 26.01.2013
* @author Ralph Schurade
*/
#include "newdatasetwidget.h"
#include "../controls/sliderwithedit.h"
#include "../controls/sliderwitheditint.h"
#include "../controls/selectwithlabel.h"
#include "../roiwidget.h"
#include "../../../data/models.h"
#include "../../../data/vptr.h"
#include "../../../data/writer.h"
#include "../../../data/roiarea.h"
#include "../../../data/datasets/dataset.h"
#include "../../../data/datasets/datasetscalar.h"
#include <QPushButton>
#include <QProgressBar>
NewDatasetWidget::NewDatasetWidget( ROIWidget* roiWidget, QWidget* parent ) :
m_roiWidget( roiWidget )
{
m_layout = new QVBoxLayout();
m_modeSelect = new SelectWithLabel( QString( "mode" ), 1 );
m_modeSelect->insertItem( 0, QString("new") );
m_modeSelect->insertItem( 1, QString("copy") );
m_modeSelect->insertItem( 2, QString("copy with roi selection") );
m_layout->addWidget( m_modeSelect );
connect( m_modeSelect, SIGNAL( currentIndexChanged( int, int ) ), this, SLOT( modeChanged( int ) ) );
m_sourceSelect = new SelectWithLabel( QString( "source dataset" ), 1 );
QList<QVariant>dsl = Models::d()->data( Models::d()->index( 0, (int)Fn::Property::D_DATASET_LIST ), Qt::DisplayRole ).toList();
for ( int k = 0; k < dsl.size(); ++k )
{
if ( VPtr<Dataset>::asPtr( dsl[k] )->properties().get( Fn::Property::D_TYPE ).toInt() == (int)Fn::DatasetType::NIFTI_SCALAR )
{
m_sourceSelect->addItem( VPtr<Dataset>::asPtr( dsl[k] )->properties().get( Fn::Property::D_NAME ).toString(), dsl[k] );
}
}
m_layout->addWidget( m_sourceSelect );
m_sourceSelect->hide();
QHBoxLayout* hLayout = new QHBoxLayout();
m_createDatasetButton = new QPushButton( tr("Create dataset") );
connect( m_createDatasetButton, SIGNAL( clicked() ), this, SLOT( createDataset() ) );
m_createROIButton = new QPushButton( tr("Create roi") );
connect( m_createROIButton, SIGNAL( clicked() ), this, SLOT( createROI() ) );
m_createROIButton->hide();
m_nX = new SliderWithEditInt( QString("nx") );
m_nX->setMin( 1 );
m_nX->setMax( 500 );
m_nX->setValue( 160 );
m_layout->addWidget( m_nX );
m_nY = new SliderWithEditInt( QString("ny") );
m_nY->setMin( 1 );
m_nY->setMax( 500 );
m_nY->setValue( 200 );
m_layout->addWidget( m_nY );
m_nZ = new SliderWithEditInt( QString("nz") );
m_nZ->setMin( 1 );
m_nZ->setMax( 500 );
m_nZ->setValue( 160 );
m_layout->addWidget( m_nZ );
m_dX = new SliderWithEdit( QString("dx") );
m_dX->setMin( 0.1f );
m_dX->setMax( 5.0f );
m_dX->setValue( 1.0f );
m_layout->addWidget( m_dX );
m_dY = new SliderWithEdit( QString("dy") );
m_dY->setMin( 0.1f );
m_dY->setMax( 5.0f );
m_dY->setValue( 1.0f );
m_layout->addWidget( m_dY );
m_dZ = new SliderWithEdit( QString("dz") );
m_dZ->setMin( 0.1f );
m_dZ->setMax( 5.0f );
m_dZ->setValue( 1.0f );
m_layout->addWidget( m_dZ );
hLayout->addStretch();
hLayout->addWidget( m_createROIButton );
hLayout->addWidget( m_createDatasetButton );
m_layout->addLayout( hLayout );
m_layout->addStretch();
setLayout( m_layout );
}
NewDatasetWidget::~NewDatasetWidget()
{
}
void NewDatasetWidget::createDataset()
{
switch( m_modeSelect->getCurrentIndex() )
{
case 0:
{
int nx = m_nX->getValue();
int ny = m_nY->getValue();
int nz = m_nZ->getValue();
float dx = m_dX->getValue();
float dy = m_dY->getValue();
float dz = m_dZ->getValue();
std::vector<float> data( nx * ny * nz );
for( int z = 0; z < nz; ++z )
{
for( int y = 0; y < ny; ++y )
{
for( int x = 0; x < nx; ++x )
{
float val = 255 * ( ( ( x + ( y % 2 ) ) + ( z % 2 ) ) % 2 ) ;
data[ x + y*nx + z*nx*ny ] = val;
}
}
}
data[0] = 255;
int dims[8] = { 3, nx, ny, nz, 1, 1, 1 };
nifti_image* header = nifti_make_new_nim( dims, NIFTI_TYPE_FLOAT32, 1 );
header->dx = dx;
header->dy = dy;
header->dz = dz;
DatasetScalar* out = new DatasetScalar( QDir( "new dataset" ), data, header );
QModelIndex index = Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET );
Models::d()->setData( index, VPtr<Dataset>::asQVariant( out ), Qt::DisplayRole );
break;
}
case 1:
{
DatasetScalar* ds = static_cast<DatasetScalar*>( VPtr<Dataset>::asPtr( m_sourceSelect->getSelectedItemData() ) );
std::vector<float>* data = ds->getData();
std::vector<float> out( data->size() );
float min = ds->properties( "maingl" ).get( Fn::Property::D_SELECTED_MIN ).toFloat();
float max = ds->properties( "maingl" ).get( Fn::Property::D_SELECTED_MAX ).toFloat();
float totalMin = ds->properties( "maingl" ).get( Fn::Property::D_MIN ).toFloat();
float totalMax = ds->properties( "maingl" ).get( Fn::Property::D_MAX ).toFloat();
float lowerThreshold = ds->properties( "maingl" ).get( Fn::Property::D_LOWER_THRESHOLD ).toFloat();
float upperThreshold = ds->properties( "maingl" ).get( Fn::Property::D_UPPER_THRESHOLD ).toFloat();
for ( unsigned int i = 0; i < data->size(); ++i )
{
float value = data->at( i );
if ( value < lowerThreshold || value > upperThreshold )
{
value = 0.0f;
}
else
{
value = ( value - min ) / ( max - min );
value *= totalMax;
}
value = qMax( totalMin, qMin( totalMax, value ) );
out[i] = value;
}
Writer writer( ds, QFileInfo() );
DatasetScalar* dsOut = new DatasetScalar( QDir( "new dataset" ), out, writer.createHeader( 1 ) );
QModelIndex index = Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET );
Models::d()->setData( index, VPtr<Dataset>::asQVariant( dsOut ), Qt::DisplayRole );
break;
}
case 2:
{
DatasetScalar* ds = static_cast<DatasetScalar*>( VPtr<Dataset>::asPtr( m_sourceSelect->getSelectedItemData() ) );
std::vector<float>* data = ds->getData();
std::vector<float> out( data->size() );
copyWithRois( ds, out );
Writer writer( ds, QFileInfo() );
DatasetScalar* dsOut = new DatasetScalar( QDir( "new dataset" ), out, writer.createHeader( 1 ) );
QModelIndex index = Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET );
Models::d()->setData( index, VPtr<Dataset>::asQVariant( dsOut ), Qt::DisplayRole );
break;
}
}
this->hide();
}
void NewDatasetWidget::createROI()
{
DatasetScalar* ds = static_cast<DatasetScalar*>( VPtr<Dataset>::asPtr( m_sourceSelect->getSelectedItemData() ) );
std::vector<float>* data = ds->getData();
std::vector<float> out( data->size() );
switch( m_modeSelect->getCurrentIndex() )
{
case 1:
{
float min = ds->properties( "maingl" ).get( Fn::Property::D_SELECTED_MIN ).toFloat();
float max = ds->properties( "maingl" ).get( Fn::Property::D_SELECTED_MAX ).toFloat();
float totalMin = ds->properties( "maingl" ).get( Fn::Property::D_MIN ).toFloat();
float totalMax = ds->properties( "maingl" ).get( Fn::Property::D_MAX ).toFloat();
float lowerThreshold = ds->properties( "maingl" ).get( Fn::Property::D_LOWER_THRESHOLD ).toFloat();
float upperThreshold = ds->properties( "maingl" ).get( Fn::Property::D_UPPER_THRESHOLD ).toFloat();
for ( unsigned int i = 0; i < data->size(); ++i )
{
float value = data->at( i );
if ( value < lowerThreshold || value > upperThreshold )
{
value = 0.0f;
}
else
{
value = ( value - min ) / ( max - min );
value *= totalMax;
}
value = qMax( totalMin, qMin( totalMax, value ) );
out[i] = value;
}
}
break;
case 2 :
copyWithRois( ds, out );
break;
}
ROIArea* roiOut = new ROIArea( out, ds->properties() );
m_roiWidget->addROIArea( roiOut );
this->hide();
}
void NewDatasetWidget::modeChanged( int mode )
{
switch ( mode )
{
case 0:
m_sourceSelect->hide();
m_nX->show();
m_nY->show();
m_nZ->show();
m_dX->show();
m_dY->show();
m_dZ->show();
m_createROIButton->hide();
break;
case 1:
case 2:
m_sourceSelect->show();
m_nX->hide();
m_nY->hide();
m_nZ->hide();
m_dX->hide();
m_dY->hide();
m_dZ->hide();
m_createROIButton->show();
}
}
QModelIndex NewDatasetWidget::createIndex( int branch, int pos, int column )
{
int row;
QModelIndex parent;
if ( pos == 0 )
{
row = branch;
}
else
{
row = pos - 1;
parent = Models::r()->index( branch, 0 );
}
return Models::r()->index( row, column, parent );
}
void NewDatasetWidget::copyWithRois( DatasetScalar* source, std::vector<float> &target )
{
int numBranches = Models::r()->rowCount( QModelIndex() );
for ( int i = 0; i < numBranches; ++i )
{
copy( i, 0, source, target );
int leafCount = Models::r()->rowCount( createIndex( i, 0, 0 ) );
for ( int k = 0; k < leafCount; ++k )
{
copy( i, k + 1, source, target );
}
}
}
void NewDatasetWidget::copy( int branch, int pos, DatasetScalar* source, std::vector<float> &target )
{
if ( Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_SHAPE ), Qt::DisplayRole ).toInt() > 4 )
{
return;
}
std::vector<float>* s = source->getData();
int ds_nx = source->properties().get( Fn::Property::D_NX ).toInt();
int ds_ny = source->properties().get( Fn::Property::D_NY ).toInt();
int ds_nz = source->properties().get( Fn::Property::D_NZ ).toInt();
float ds_dx = source->properties().get( Fn::Property::D_DX ).toFloat();
float ds_dy = source->properties().get( Fn::Property::D_DY ).toFloat();
float ds_dz = source->properties().get( Fn::Property::D_DZ ).toFloat();
if ( Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_ACTIVE ), Qt::DisplayRole ).toBool() )
{
float x = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_X ), Qt::DisplayRole ).toFloat();
float y = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_Y ), Qt::DisplayRole ).toFloat();
float z = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_Z ), Qt::DisplayRole ).toFloat();
float dx = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_DX ), Qt::DisplayRole ).toFloat() / 2;
float dy = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_DY ), Qt::DisplayRole ).toFloat() / 2;
float dz = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_DZ ), Qt::DisplayRole ).toFloat() / 2;
float xMin = x - dx;
float xMax = x + dx;
float yMin = y - dy;
float yMax = y + dy;
float zMin = z - dz;
float zMax = z + dz;
for ( int iz = 0; iz < ds_nz; ++iz )
{
for ( int iy = 0; iy < ds_ny; ++iy )
{
for ( int ix = 0; ix < ds_nx; ++ix )
{
float vx = (float)ix * ds_dx;
float vy = (float)iy * ds_dy;
float vz = (float)iz * ds_dz;
if ( vx >= xMin && vx <= xMax && vy >= yMin && vy <= yMax && vz >= zMin && vz <= zMax )
{
target[ ix + ds_nx * iy + iz * ds_nx * ds_ny ] = s->at( ix + ds_nx * iy + iz * ds_nx * ds_ny );
}
}
}
}
}
}
<commit_msg>removed debug code<commit_after>/*
* newdatasetwidget.cpp
*
* Created on: 26.01.2013
* @author Ralph Schurade
*/
#include "newdatasetwidget.h"
#include "../controls/sliderwithedit.h"
#include "../controls/sliderwitheditint.h"
#include "../controls/selectwithlabel.h"
#include "../roiwidget.h"
#include "../../../data/models.h"
#include "../../../data/vptr.h"
#include "../../../data/writer.h"
#include "../../../data/roiarea.h"
#include "../../../data/datasets/dataset.h"
#include "../../../data/datasets/datasetscalar.h"
#include <QPushButton>
#include <QProgressBar>
NewDatasetWidget::NewDatasetWidget( ROIWidget* roiWidget, QWidget* parent ) :
m_roiWidget( roiWidget )
{
m_layout = new QVBoxLayout();
m_modeSelect = new SelectWithLabel( QString( "mode" ), 1 );
m_modeSelect->insertItem( 0, QString("new") );
m_modeSelect->insertItem( 1, QString("copy") );
m_modeSelect->insertItem( 2, QString("copy with roi selection") );
m_layout->addWidget( m_modeSelect );
connect( m_modeSelect, SIGNAL( currentIndexChanged( int, int ) ), this, SLOT( modeChanged( int ) ) );
m_sourceSelect = new SelectWithLabel( QString( "source dataset" ), 1 );
QList<QVariant>dsl = Models::d()->data( Models::d()->index( 0, (int)Fn::Property::D_DATASET_LIST ), Qt::DisplayRole ).toList();
for ( int k = 0; k < dsl.size(); ++k )
{
if ( VPtr<Dataset>::asPtr( dsl[k] )->properties().get( Fn::Property::D_TYPE ).toInt() == (int)Fn::DatasetType::NIFTI_SCALAR )
{
m_sourceSelect->addItem( VPtr<Dataset>::asPtr( dsl[k] )->properties().get( Fn::Property::D_NAME ).toString(), dsl[k] );
}
}
m_layout->addWidget( m_sourceSelect );
m_sourceSelect->hide();
QHBoxLayout* hLayout = new QHBoxLayout();
m_createDatasetButton = new QPushButton( tr("Create dataset") );
connect( m_createDatasetButton, SIGNAL( clicked() ), this, SLOT( createDataset() ) );
m_createROIButton = new QPushButton( tr("Create roi") );
connect( m_createROIButton, SIGNAL( clicked() ), this, SLOT( createROI() ) );
m_createROIButton->hide();
m_nX = new SliderWithEditInt( QString("nx") );
m_nX->setMin( 1 );
m_nX->setMax( 500 );
m_nX->setValue( 160 );
m_layout->addWidget( m_nX );
m_nY = new SliderWithEditInt( QString("ny") );
m_nY->setMin( 1 );
m_nY->setMax( 500 );
m_nY->setValue( 200 );
m_layout->addWidget( m_nY );
m_nZ = new SliderWithEditInt( QString("nz") );
m_nZ->setMin( 1 );
m_nZ->setMax( 500 );
m_nZ->setValue( 160 );
m_layout->addWidget( m_nZ );
m_dX = new SliderWithEdit( QString("dx") );
m_dX->setMin( 0.1f );
m_dX->setMax( 5.0f );
m_dX->setValue( 1.0f );
m_layout->addWidget( m_dX );
m_dY = new SliderWithEdit( QString("dy") );
m_dY->setMin( 0.1f );
m_dY->setMax( 5.0f );
m_dY->setValue( 1.0f );
m_layout->addWidget( m_dY );
m_dZ = new SliderWithEdit( QString("dz") );
m_dZ->setMin( 0.1f );
m_dZ->setMax( 5.0f );
m_dZ->setValue( 1.0f );
m_layout->addWidget( m_dZ );
hLayout->addStretch();
hLayout->addWidget( m_createROIButton );
hLayout->addWidget( m_createDatasetButton );
m_layout->addLayout( hLayout );
m_layout->addStretch();
setLayout( m_layout );
}
NewDatasetWidget::~NewDatasetWidget()
{
}
void NewDatasetWidget::createDataset()
{
switch( m_modeSelect->getCurrentIndex() )
{
case 0:
{
int nx = m_nX->getValue();
int ny = m_nY->getValue();
int nz = m_nZ->getValue();
float dx = m_dX->getValue();
float dy = m_dY->getValue();
float dz = m_dZ->getValue();
std::vector<float> data( nx * ny * nz, 0 );
// for( int z = 0; z < nz; ++z )
// {
// for( int y = 0; y < ny; ++y )
// {
// for( int x = 0; x < nx; ++x )
// {
// float val = 255 * ( ( ( x + ( y % 2 ) ) + ( z % 2 ) ) % 2 ) ;
// data[ x + y*nx + z*nx*ny ] = val;
// }
// }
// }
data[0] = 255;
int dims[8] = { 3, nx, ny, nz, 1, 1, 1 };
nifti_image* header = nifti_make_new_nim( dims, NIFTI_TYPE_FLOAT32, 1 );
header->dx = dx;
header->dy = dy;
header->dz = dz;
DatasetScalar* out = new DatasetScalar( QDir( "new dataset" ), data, header );
QModelIndex index = Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET );
Models::d()->setData( index, VPtr<Dataset>::asQVariant( out ), Qt::DisplayRole );
break;
}
case 1:
{
DatasetScalar* ds = static_cast<DatasetScalar*>( VPtr<Dataset>::asPtr( m_sourceSelect->getSelectedItemData() ) );
std::vector<float>* data = ds->getData();
std::vector<float> out( data->size() );
float min = ds->properties( "maingl" ).get( Fn::Property::D_SELECTED_MIN ).toFloat();
float max = ds->properties( "maingl" ).get( Fn::Property::D_SELECTED_MAX ).toFloat();
float totalMin = ds->properties( "maingl" ).get( Fn::Property::D_MIN ).toFloat();
float totalMax = ds->properties( "maingl" ).get( Fn::Property::D_MAX ).toFloat();
float lowerThreshold = ds->properties( "maingl" ).get( Fn::Property::D_LOWER_THRESHOLD ).toFloat();
float upperThreshold = ds->properties( "maingl" ).get( Fn::Property::D_UPPER_THRESHOLD ).toFloat();
for ( unsigned int i = 0; i < data->size(); ++i )
{
float value = data->at( i );
if ( value < lowerThreshold || value > upperThreshold )
{
value = 0.0f;
}
else
{
value = ( value - min ) / ( max - min );
value *= totalMax;
}
value = qMax( totalMin, qMin( totalMax, value ) );
out[i] = value;
}
Writer writer( ds, QFileInfo() );
DatasetScalar* dsOut = new DatasetScalar( QDir( "new dataset" ), out, writer.createHeader( 1 ) );
QModelIndex index = Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET );
Models::d()->setData( index, VPtr<Dataset>::asQVariant( dsOut ), Qt::DisplayRole );
break;
}
case 2:
{
DatasetScalar* ds = static_cast<DatasetScalar*>( VPtr<Dataset>::asPtr( m_sourceSelect->getSelectedItemData() ) );
std::vector<float>* data = ds->getData();
std::vector<float> out( data->size() );
copyWithRois( ds, out );
Writer writer( ds, QFileInfo() );
DatasetScalar* dsOut = new DatasetScalar( QDir( "new dataset" ), out, writer.createHeader( 1 ) );
QModelIndex index = Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET );
Models::d()->setData( index, VPtr<Dataset>::asQVariant( dsOut ), Qt::DisplayRole );
break;
}
}
this->hide();
}
void NewDatasetWidget::createROI()
{
DatasetScalar* ds = static_cast<DatasetScalar*>( VPtr<Dataset>::asPtr( m_sourceSelect->getSelectedItemData() ) );
std::vector<float>* data = ds->getData();
std::vector<float> out( data->size() );
switch( m_modeSelect->getCurrentIndex() )
{
case 1:
{
float min = ds->properties( "maingl" ).get( Fn::Property::D_SELECTED_MIN ).toFloat();
float max = ds->properties( "maingl" ).get( Fn::Property::D_SELECTED_MAX ).toFloat();
float totalMin = ds->properties( "maingl" ).get( Fn::Property::D_MIN ).toFloat();
float totalMax = ds->properties( "maingl" ).get( Fn::Property::D_MAX ).toFloat();
float lowerThreshold = ds->properties( "maingl" ).get( Fn::Property::D_LOWER_THRESHOLD ).toFloat();
float upperThreshold = ds->properties( "maingl" ).get( Fn::Property::D_UPPER_THRESHOLD ).toFloat();
for ( unsigned int i = 0; i < data->size(); ++i )
{
float value = data->at( i );
if ( value < lowerThreshold || value > upperThreshold )
{
value = 0.0f;
}
else
{
value = ( value - min ) / ( max - min );
value *= totalMax;
}
value = qMax( totalMin, qMin( totalMax, value ) );
out[i] = value;
}
}
break;
case 2 :
copyWithRois( ds, out );
break;
}
ROIArea* roiOut = new ROIArea( out, ds->properties() );
m_roiWidget->addROIArea( roiOut );
this->hide();
}
void NewDatasetWidget::modeChanged( int mode )
{
switch ( mode )
{
case 0:
m_sourceSelect->hide();
m_nX->show();
m_nY->show();
m_nZ->show();
m_dX->show();
m_dY->show();
m_dZ->show();
m_createROIButton->hide();
break;
case 1:
case 2:
m_sourceSelect->show();
m_nX->hide();
m_nY->hide();
m_nZ->hide();
m_dX->hide();
m_dY->hide();
m_dZ->hide();
m_createROIButton->show();
}
}
QModelIndex NewDatasetWidget::createIndex( int branch, int pos, int column )
{
int row;
QModelIndex parent;
if ( pos == 0 )
{
row = branch;
}
else
{
row = pos - 1;
parent = Models::r()->index( branch, 0 );
}
return Models::r()->index( row, column, parent );
}
void NewDatasetWidget::copyWithRois( DatasetScalar* source, std::vector<float> &target )
{
int numBranches = Models::r()->rowCount( QModelIndex() );
for ( int i = 0; i < numBranches; ++i )
{
copy( i, 0, source, target );
int leafCount = Models::r()->rowCount( createIndex( i, 0, 0 ) );
for ( int k = 0; k < leafCount; ++k )
{
copy( i, k + 1, source, target );
}
}
}
void NewDatasetWidget::copy( int branch, int pos, DatasetScalar* source, std::vector<float> &target )
{
if ( Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_SHAPE ), Qt::DisplayRole ).toInt() > 4 )
{
return;
}
std::vector<float>* s = source->getData();
int ds_nx = source->properties().get( Fn::Property::D_NX ).toInt();
int ds_ny = source->properties().get( Fn::Property::D_NY ).toInt();
int ds_nz = source->properties().get( Fn::Property::D_NZ ).toInt();
float ds_dx = source->properties().get( Fn::Property::D_DX ).toFloat();
float ds_dy = source->properties().get( Fn::Property::D_DY ).toFloat();
float ds_dz = source->properties().get( Fn::Property::D_DZ ).toFloat();
if ( Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_ACTIVE ), Qt::DisplayRole ).toBool() )
{
float x = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_X ), Qt::DisplayRole ).toFloat();
float y = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_Y ), Qt::DisplayRole ).toFloat();
float z = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_Z ), Qt::DisplayRole ).toFloat();
float dx = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_DX ), Qt::DisplayRole ).toFloat() / 2;
float dy = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_DY ), Qt::DisplayRole ).toFloat() / 2;
float dz = Models::r()->data( createIndex( branch, pos, (int)Fn::Property::D_DZ ), Qt::DisplayRole ).toFloat() / 2;
float xMin = x - dx;
float xMax = x + dx;
float yMin = y - dy;
float yMax = y + dy;
float zMin = z - dz;
float zMax = z + dz;
for ( int iz = 0; iz < ds_nz; ++iz )
{
for ( int iy = 0; iy < ds_ny; ++iy )
{
for ( int ix = 0; ix < ds_nx; ++ix )
{
float vx = (float)ix * ds_dx;
float vy = (float)iy * ds_dy;
float vz = (float)iz * ds_dz;
if ( vx >= xMin && vx <= xMax && vy >= yMin && vy <= yMax && vz >= zMin && vz <= zMax )
{
target[ ix + ds_nx * iy + iz * ds_nx * ds_ny ] = s->at( ix + ds_nx * iy + iz * ds_nx * ds_ny );
}
}
}
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
namespace datavis {
using std::vector;
inline
int flat_size(const vector<int> & size)
{
int fs = 1;
for (auto & s : size)
fs *= s;
return fs;
}
inline
int flat_index(const vector<int> & index, const vector<int> & size)
{
int fi = index[0];
for (unsigned d = 1; d < index.size(); ++d)
{
fi *= size[d];
fi += index[d];
}
return fi;
}
class abstract_array
{
};
template <typename T>
class array : public abstract_array
{
public:
using index_t = vector<int>;
using size_t = vector<int>;
array(size_t size):
m_size(size),
m_data(flat_size(size))
{}
const size_t & size() const { return m_size; }
T & operator()(const index_t & i)
{
auto j = flat_index(i, m_size);
return m_data[j];
}
const T & operator()(const index_t & i) const
{
auto j = flat_index(i, m_size);
return m_data[j];
}
T * data() { return m_data.data(); }
const T * data() const { return m_data.data(); }
private:
size_t m_size;
vector<T> m_data;
};
template <typename T>
class array_region
{
T * m_data = nullptr;
vector<int> m_data_size;
vector<int> m_region_offset;
vector<int> m_region_size;
public:
array_region()
{}
array_region(array<T> & a, const vector<int> & offset, const vector<int> & size):
m_data(a.data()),
m_data_size(a.size()),
m_region_offset(offset),
m_region_size(size)
{}
bool is_valid() const { return m_data != nullptr; }
class iterator
{
T * m_data = nullptr;
vector<int> m_start;
vector<int> m_end;
vector<int> m_stride;
vector<int> m_location;
int m_index;
public:
#if 0
class value_type
{
public:
T & value()
{
return m_data[m_index];
}
int index() const { return m_index; }
private:
friend class iterator;
T * m_data;
int m_index;
vector<int> m_location;
};
#endif
iterator(T * data,
const vector<int> & start,
const vector<int> & end,
const vector<int> & stride,
int start_index):
m_data(data),
m_start(start),
m_end(end),
m_stride(stride),
m_location(start),
m_index(start_index)
{
}
iterator() {}
bool operator==(const iterator & other) const
{
if (m_data != other.m_data)
return false;
if (m_data)
{
return m_index == other.m_index;
}
else
{
return true;
}
}
bool operator!=(const iterator & other) const
{
return !(*this == other);
}
bool is_valid() const
{
return m_data != nullptr;
}
const vector<int> & location() const
{
return m_location;
}
int index() const { return m_index; }
T & value() const
{
return m_data[m_index];
}
iterator & operator++()
{
int n_dim = m_end.size();
int d;
for(d = n_dim - 1; d >= 0; --d)
{
++m_location[d];
if (m_location[d] < m_end[d])
{
m_index += m_stride[d];
break;
}
m_location[d] = m_start[d];
}
// FIXME: Optimize:
if (d < 0)
m_data = nullptr; // Invalidate.
return *this;
}
bool operator<(const iterator & other) const
{
return value() < other.value();
}
iterator & operator*()
{
return *this;
}
};
iterator begin()
{
int n_dim = m_data_size.size();
vector<int> flat_strides(n_dim, 0);
vector<int> stride(n_dim, 0);
stride.back() = 1;
for (int d = n_dim - 1; d >= 0; --d)
{
flat_strides[d] = flat_index(stride, m_data_size);
stride[d] += m_data_size[d] - m_region_size[d];
/*
subspace_size *= m_size[d+1];
dim_stride = dim_stride + subspace_size * (m_size[d] - size[d]);
stride.push_back(dim_stride);
*/
//cout << "stride " << d << " = " << flat_strides[d] << endl;
}
auto & start = m_region_offset;
vector<int> end = m_region_offset;
for (int d = 0; d < m_region_size.size(); ++d)
end[d] += m_region_size[d];
return iterator(m_data,
start,
end,
flat_strides,
flat_index(m_region_offset, m_data_size));
#if 0
vector<int> it_size;
vector<int> it_stride;
for (int d = 0; d < n_dim; ++d)
{
if (m_region_size[d] < 2)
continue;
it_size.push_back(m_region_size[d]);
it_stride.push_back(flat_strides[d]);
}
return iterator(m_data,
it_size,
it_stride,
flat_index(m_region_offset, m_data_size));
#endif
}
iterator end()
{
return iterator();
}
};
template<typename T>
inline
array_region<T>
get_region(array<T> & array, const vector<int> & offset, const vector<int> & size)
{
return array_region<T>(array, offset, size);
}
template<typename T>
inline
array_region<T>
get_all(array<T> & array)
{
return array_region<T>(array, vector<int>(array.size().size(), 0), array.size());
}
}
<commit_msg>data/array: add default constructor<commit_after>#pragma once
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
namespace datavis {
using std::vector;
inline
int flat_size(const vector<int> & size)
{
int fs = 1;
for (auto & s : size)
fs *= s;
return fs;
}
inline
int flat_index(const vector<int> & index, const vector<int> & size)
{
int fi = index[0];
for (unsigned d = 1; d < index.size(); ++d)
{
fi *= size[d];
fi += index[d];
}
return fi;
}
class abstract_array
{
};
template <typename T>
class array : public abstract_array
{
public:
using index_t = vector<int>;
using size_t = vector<int>;
array() {}
array(size_t size):
m_size(size),
m_data(flat_size(size))
{}
const size_t & size() const { return m_size; }
T & operator()(const index_t & i)
{
auto j = flat_index(i, m_size);
return m_data[j];
}
const T & operator()(const index_t & i) const
{
auto j = flat_index(i, m_size);
return m_data[j];
}
T * data() { return m_data.data(); }
const T * data() const { return m_data.data(); }
private:
size_t m_size;
vector<T> m_data;
};
template <typename T>
class array_region
{
T * m_data = nullptr;
vector<int> m_data_size;
vector<int> m_region_offset;
vector<int> m_region_size;
public:
array_region()
{}
array_region(array<T> & a, const vector<int> & offset, const vector<int> & size):
m_data(a.data()),
m_data_size(a.size()),
m_region_offset(offset),
m_region_size(size)
{}
bool is_valid() const { return m_data != nullptr; }
class iterator
{
T * m_data = nullptr;
vector<int> m_start;
vector<int> m_end;
vector<int> m_stride;
vector<int> m_location;
int m_index;
public:
#if 0
class value_type
{
public:
T & value()
{
return m_data[m_index];
}
int index() const { return m_index; }
private:
friend class iterator;
T * m_data;
int m_index;
vector<int> m_location;
};
#endif
iterator(T * data,
const vector<int> & start,
const vector<int> & end,
const vector<int> & stride,
int start_index):
m_data(data),
m_start(start),
m_end(end),
m_stride(stride),
m_location(start),
m_index(start_index)
{
}
iterator() {}
bool operator==(const iterator & other) const
{
if (m_data != other.m_data)
return false;
if (m_data)
{
return m_index == other.m_index;
}
else
{
return true;
}
}
bool operator!=(const iterator & other) const
{
return !(*this == other);
}
bool is_valid() const
{
return m_data != nullptr;
}
const vector<int> & location() const
{
return m_location;
}
int index() const { return m_index; }
T & value() const
{
return m_data[m_index];
}
iterator & operator++()
{
int n_dim = m_end.size();
int d;
for(d = n_dim - 1; d >= 0; --d)
{
++m_location[d];
if (m_location[d] < m_end[d])
{
m_index += m_stride[d];
break;
}
m_location[d] = m_start[d];
}
// FIXME: Optimize:
if (d < 0)
m_data = nullptr; // Invalidate.
return *this;
}
bool operator<(const iterator & other) const
{
return value() < other.value();
}
iterator & operator*()
{
return *this;
}
};
iterator begin()
{
int n_dim = m_data_size.size();
vector<int> flat_strides(n_dim, 0);
vector<int> stride(n_dim, 0);
stride.back() = 1;
for (int d = n_dim - 1; d >= 0; --d)
{
flat_strides[d] = flat_index(stride, m_data_size);
stride[d] += m_data_size[d] - m_region_size[d];
/*
subspace_size *= m_size[d+1];
dim_stride = dim_stride + subspace_size * (m_size[d] - size[d]);
stride.push_back(dim_stride);
*/
//cout << "stride " << d << " = " << flat_strides[d] << endl;
}
auto & start = m_region_offset;
vector<int> end = m_region_offset;
for (int d = 0; d < m_region_size.size(); ++d)
end[d] += m_region_size[d];
return iterator(m_data,
start,
end,
flat_strides,
flat_index(m_region_offset, m_data_size));
#if 0
vector<int> it_size;
vector<int> it_stride;
for (int d = 0; d < n_dim; ++d)
{
if (m_region_size[d] < 2)
continue;
it_size.push_back(m_region_size[d]);
it_stride.push_back(flat_strides[d]);
}
return iterator(m_data,
it_size,
it_stride,
flat_index(m_region_offset, m_data_size));
#endif
}
iterator end()
{
return iterator();
}
};
template<typename T>
inline
array_region<T>
get_region(array<T> & array, const vector<int> & offset, const vector<int> & size)
{
return array_region<T>(array, offset, size);
}
template<typename T>
inline
array_region<T>
get_all(array<T> & array)
{
return array_region<T>(array, vector<int>(array.size().size(), 0), array.size());
}
}
<|endoftext|> |
<commit_before>#include <stinkee_device.h>
#include <stinkee_signal.h>
#include <portaudio.h>
#include <iostream>
namespace {
static const int NUM_CHANNELS = 1;
static const PaSampleFormat SAMPLE_TYPE = paFloat32;
struct CbUserData
{
std::size_t processed;
const stinkee::Signal& signal;
};
int paCallback(const void *input,
void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo *timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData);
} // anonymous namespace
namespace stinkee {
Device::~Device()
{
Pa_Terminate();
}
int Device::init() const
{
PaError rc = Pa_Initialize();
if (rc != paNoError) {
std::cerr << "Failed to initialize portaudio: "
<< Pa_GetErrorText(rc)
<< std::endl;
}
return rc;
}
int Device::process(const Signal& signal) const
{
PaError rc;
CbUserData userData = { 0, signal };
PaStream *audioStream;
rc = Pa_OpenDefaultStream(
&audioStream,
0,
NUM_CHANNELS,
SAMPLE_TYPE,
Signal::SAMPLING_RATE,
paFramesPerBufferUnspecified,
paCallback,
&userData);
if (rc != paNoError) {
std::cerr << "Failed to open output stream: "
<< Pa_GetErrorText(rc)
<< std::endl;
return rc;
}
rc = Pa_StartStream(audioStream);
if (rc != paNoError) {
std::cerr << "Failed to start stream: "
<< Pa_GetErrorText(rc)
<< std::endl;
return rc;
}
Pa_Sleep(1000);
rc = Pa_StopStream(audioStream);
if (rc != paNoError) {
std::cerr << "Failed to stop stream: "
<< Pa_GetErrorText(rc)
<< std::endl;
return rc;
}
rc = Pa_CloseStream(audioStream);
if (rc != paNoError) {
std::cerr << "Failed to close stream: "
<< Pa_GetErrorText(rc)
<< std::endl;
return rc;
}
return 0;
}
} // library namespace
namespace {
int paCallback(const void *input,
void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo *timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData)
{
CbUserData& data = *((CbUserData *)userData);
const std::vector<float> frames = data.signal.frames();
float *out = (float *)output;
for (std::size_t i = 0; i < frameCount; ++i) {
if (data.processed < frames.size()) {
*out = frames[data.processed];
}
else {
*out = 0.0;
}
++out;
++data.processed;
}
return data.processed < frames.size() ? paContinue : paComplete;
}
} // anonymous namespace
<commit_msg>Verify number of frames processed<commit_after>#include <stinkee_device.h>
#include <stinkee_signal.h>
#include <portaudio.h>
#include <cassert>
#include <iostream>
namespace {
static const int NUM_CHANNELS = 1;
static const PaSampleFormat SAMPLE_TYPE = paFloat32;
struct CbUserData
{
std::size_t processed;
const stinkee::Signal& signal;
};
int paCallback(const void *input,
void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo *timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData);
} // anonymous namespace
namespace stinkee {
Device::~Device()
{
Pa_Terminate();
}
int Device::init() const
{
PaError rc = Pa_Initialize();
if (rc != paNoError) {
std::cerr << "Failed to initialize portaudio: "
<< Pa_GetErrorText(rc)
<< std::endl;
}
return rc;
}
int Device::process(const Signal& signal) const
{
PaError rc;
CbUserData userData = { 0, signal };
PaStream *audioStream;
rc = Pa_OpenDefaultStream(
&audioStream,
0,
NUM_CHANNELS,
SAMPLE_TYPE,
Signal::SAMPLING_RATE,
paFramesPerBufferUnspecified,
paCallback,
&userData);
if (rc != paNoError) {
std::cerr << "Failed to open output stream: "
<< Pa_GetErrorText(rc)
<< std::endl;
return rc;
}
rc = Pa_StartStream(audioStream);
if (rc != paNoError) {
std::cerr << "Failed to start stream: "
<< Pa_GetErrorText(rc)
<< std::endl;
return rc;
}
Pa_Sleep(1000);
rc = Pa_StopStream(audioStream);
if (rc != paNoError) {
std::cerr << "Failed to stop stream: "
<< Pa_GetErrorText(rc)
<< std::endl;
return rc;
}
rc = Pa_CloseStream(audioStream);
if (rc != paNoError) {
std::cerr << "Failed to close stream: "
<< Pa_GetErrorText(rc)
<< std::endl;
return rc;
}
assert(userData.processed == signal.frames().size());
return 0;
}
} // library namespace
namespace {
int paCallback(const void *input,
void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo *timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData)
{
CbUserData *data = (CbUserData *)userData;
const std::vector<float>& frames = data->signal.frames();
float *out = (float *)output;
for (std::size_t i = 0; i < frameCount; ++i) {
if (data->processed < frames.size()) {
*out = frames[data->processed++];
}
else {
*out = 0.0;
}
++out;
}
return data->processed < frames.size() ? paContinue : paComplete;
}
} // anonymous namespace
<|endoftext|> |
<commit_before>//===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the clang driver; it is a thin wrapper
// for functionality in the Driver clang library.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Option.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Config/config.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Host.h"
#include "llvm/System/Path.h"
#include "llvm/System/Signals.h"
using namespace clang;
using namespace clang::driver;
class DriverDiagnosticPrinter : public DiagnosticClient {
std::string ProgName;
llvm::raw_ostream &OS;
public:
DriverDiagnosticPrinter(const std::string _ProgName,
llvm::raw_ostream &_OS)
: ProgName(_ProgName),
OS(_OS) {}
virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
const DiagnosticInfo &Info);
};
void DriverDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
const DiagnosticInfo &Info) {
OS << ProgName << ": ";
switch (Level) {
case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
case Diagnostic::Note: OS << "note: "; break;
case Diagnostic::Warning: OS << "warning: "; break;
case Diagnostic::Error: OS << "error: "; break;
case Diagnostic::Fatal: OS << "fatal error: "; break;
}
llvm::SmallString<100> OutStr;
Info.FormatDiagnostic(OutStr);
OS.write(OutStr.begin(), OutStr.size());
OS << '\n';
}
llvm::sys::Path GetExecutablePath(const char *Argv0) {
// This just needs to be some symbol in the binary; C++ doesn't
// allow taking the address of ::main however.
void *P = (void*) (intptr_t) GetExecutablePath;
return llvm::sys::Path::GetMainExecutable(Argv0, P);
}
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
llvm::sys::Path Path = GetExecutablePath(argv[0]);
llvm::OwningPtr<DiagnosticClient>
DiagClient(new DriverDiagnosticPrinter(Path.getBasename(), llvm::errs()));
Diagnostic Diags(DiagClient.get());
llvm::OwningPtr<Driver>
TheDriver(new Driver(Path.getBasename().c_str(), Path.getDirname().c_str(),
llvm::sys::getHostTriple().c_str(),
"a.out", Diags));
llvm::OwningPtr<Compilation> C;
// Handle CCC_ADD_ARGS, a comma separated list of extra arguments.
if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
std::set<std::string> SavedStrings;
std::vector<const char*> StringPointers;
// FIXME: Driver shouldn't take extra initial argument.
StringPointers.push_back(argv[0]);
for (;;) {
const char *Next = strchr(Cur, ',');
if (Next) {
if (Cur != Next) {
const char *P =
SavedStrings.insert(std::string(Cur, Next)).first->c_str();
StringPointers.push_back(P);
}
Cur = Next + 1;
} else {
if (*Cur != '\0') {
const char *P =
SavedStrings.insert(std::string(Cur)).first->c_str();
StringPointers.push_back(P);
}
break;
}
}
StringPointers.insert(StringPointers.end(), argv + 1, argv + argc);
C.reset(TheDriver->BuildCompilation(StringPointers.size(),
&StringPointers[0]));
} else
C.reset(TheDriver->BuildCompilation(argc, argv));
int Res = 0;
if (C.get())
Res = C->Execute();
llvm::llvm_shutdown();
return Res;
}
<commit_msg>Allow CCC_ADD_ARGS to add empty arguments<commit_after>//===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the clang driver; it is a thin wrapper
// for functionality in the Driver clang library.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Option.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Config/config.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Host.h"
#include "llvm/System/Path.h"
#include "llvm/System/Signals.h"
using namespace clang;
using namespace clang::driver;
class DriverDiagnosticPrinter : public DiagnosticClient {
std::string ProgName;
llvm::raw_ostream &OS;
public:
DriverDiagnosticPrinter(const std::string _ProgName,
llvm::raw_ostream &_OS)
: ProgName(_ProgName),
OS(_OS) {}
virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
const DiagnosticInfo &Info);
};
void DriverDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
const DiagnosticInfo &Info) {
OS << ProgName << ": ";
switch (Level) {
case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
case Diagnostic::Note: OS << "note: "; break;
case Diagnostic::Warning: OS << "warning: "; break;
case Diagnostic::Error: OS << "error: "; break;
case Diagnostic::Fatal: OS << "fatal error: "; break;
}
llvm::SmallString<100> OutStr;
Info.FormatDiagnostic(OutStr);
OS.write(OutStr.begin(), OutStr.size());
OS << '\n';
}
llvm::sys::Path GetExecutablePath(const char *Argv0) {
// This just needs to be some symbol in the binary; C++ doesn't
// allow taking the address of ::main however.
void *P = (void*) (intptr_t) GetExecutablePath;
return llvm::sys::Path::GetMainExecutable(Argv0, P);
}
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
llvm::sys::Path Path = GetExecutablePath(argv[0]);
llvm::OwningPtr<DiagnosticClient>
DiagClient(new DriverDiagnosticPrinter(Path.getBasename(), llvm::errs()));
Diagnostic Diags(DiagClient.get());
llvm::OwningPtr<Driver>
TheDriver(new Driver(Path.getBasename().c_str(), Path.getDirname().c_str(),
llvm::sys::getHostTriple().c_str(),
"a.out", Diags));
llvm::OwningPtr<Compilation> C;
// Handle CCC_ADD_ARGS, a comma separated list of extra arguments.
if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
std::set<std::string> SavedStrings;
std::vector<const char*> StringPointers;
// FIXME: Driver shouldn't take extra initial argument.
StringPointers.push_back(argv[0]);
for (;;) {
const char *Next = strchr(Cur, ',');
if (Next) {
const char *P =
SavedStrings.insert(std::string(Cur, Next)).first->c_str();
StringPointers.push_back(P);
Cur = Next + 1;
} else {
if (*Cur != '\0') {
const char *P =
SavedStrings.insert(std::string(Cur)).first->c_str();
StringPointers.push_back(P);
}
break;
}
}
StringPointers.insert(StringPointers.end(), argv + 1, argv + argc);
C.reset(TheDriver->BuildCompilation(StringPointers.size(),
&StringPointers[0]));
} else
C.reset(TheDriver->BuildCompilation(argc, argv));
int Res = 0;
if (C.get())
Res = C->Execute();
llvm::llvm_shutdown();
return Res;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <sstream>
#include <ctime>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>
#include "BaseTestFeature.hpp"
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>
#include <boost/math/constants/constants.hpp>
using namespace std;
using namespace nix;
using namespace valid;
void BaseTestFeature::testValidate() {
Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
valid::Result result = validate(rp);
CPPUNIT_ASSERT(result.getErrors().size() == 0);
CPPUNIT_ASSERT(result.getWarnings().size() == 0);
}
void BaseTestFeature::testId() {
Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
CPPUNIT_ASSERT(rp.id().size() == 36);
tag.deleteFeature(rp.id());
}
void BaseTestFeature::testLinkType(){
Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Tagged);
rp.linkType(nix::LinkType::Untagged);
CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Untagged);
rp.linkType(nix::LinkType::Tagged);
CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Tagged);
rp.linkType(nix::LinkType::Indexed);
CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Indexed);
tag.deleteFeature(rp.id());
}
void BaseTestFeature::testData() {
DataArray a;
Feature f;
CPPUNIT_ASSERT_THROW(tag.createFeature(a, nix::LinkType::Tagged), UninitializedEntity);
CPPUNIT_ASSERT_THROW(f.data(a), UninitializedEntity);
a = block.createDataArray("Test", "array", DataType::Double, {0, 0});
f = tag.createFeature(a, nix::LinkType::Untagged);
f.data(a.name());
block.deleteDataArray(a);
CPPUNIT_ASSERT_THROW(f.data(a), UninitializedEntity);
Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
DataArray da_2 = block.createDataArray("array2", "Test",
DataType::Double, nix::NDSize({ 0 }));
CPPUNIT_ASSERT(rp.data().id() == data_array.id());
rp.data(da_2);
CPPUNIT_ASSERT(rp.data().id() == da_2.id());
block.deleteDataArray(da_2.id());
// make sure link is gone with deleted data array
CPPUNIT_ASSERT(rp.data() == nix::none);
CPPUNIT_ASSERT_THROW(rp.data(""), EmptyString);
tag.deleteFeature(rp.id());
}
void BaseTestFeature::testLinkType2Str() {
CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Tagged) == "Tagged");
CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Untagged) == "Untagged");
CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Indexed) == "Indexed");
}
void BaseTestFeature::testStreamOperator() {
stringstream s1, s2, s3;
s1 << nix::LinkType::Indexed;
CPPUNIT_ASSERT(s1.str() == "LinkType::Indexed");
s2 << nix::LinkType::Tagged;
CPPUNIT_ASSERT(s2.str() == "LinkType::Tagged");
s3 << nix::LinkType::Untagged;
CPPUNIT_ASSERT(s3.str() == "LinkType::Untagged");
}
void BaseTestFeature::testOperator() {
Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
CPPUNIT_ASSERT(rp != none);
rp = none;
CPPUNIT_ASSERT(rp == false);
CPPUNIT_ASSERT(rp == none);
}
<commit_msg>[TestFeature] increase test coverage<commit_after>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <sstream>
#include <ctime>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>
#include "BaseTestFeature.hpp"
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>
#include <boost/math/constants/constants.hpp>
using namespace std;
using namespace nix;
using namespace valid;
void BaseTestFeature::testValidate() {
Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
valid::Result result = validate(rp);
CPPUNIT_ASSERT(result.getErrors().size() == 0);
CPPUNIT_ASSERT(result.getWarnings().size() == 0);
}
void BaseTestFeature::testId() {
Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
CPPUNIT_ASSERT(rp.id().size() == 36);
tag.deleteFeature(rp.id());
}
void BaseTestFeature::testLinkType(){
Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Tagged);
rp.linkType(nix::LinkType::Untagged);
CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Untagged);
rp.linkType(nix::LinkType::Tagged);
CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Tagged);
rp.linkType(nix::LinkType::Indexed);
CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Indexed);
tag.deleteFeature(rp.id());
}
void BaseTestFeature::testData() {
DataArray a;
Feature f;
CPPUNIT_ASSERT_THROW(tag.createFeature(a, nix::LinkType::Tagged), UninitializedEntity);
CPPUNIT_ASSERT_THROW(f.data(a), UninitializedEntity);
a = block.createDataArray("Test", "array", DataType::Double, {0, 0});
f = tag.createFeature(a, nix::LinkType::Untagged);
f.data(a.name());
block.deleteDataArray(a);
CPPUNIT_ASSERT_THROW(f.data(a), UninitializedEntity);
Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
DataArray da_2 = block.createDataArray("array2", "Test",
DataType::Double, nix::NDSize({ 0 }));
CPPUNIT_ASSERT(rp.data().id() == data_array.id());
rp.data(da_2);
CPPUNIT_ASSERT(rp.data().id() == da_2.id());
block.deleteDataArray(da_2.id());
// make sure link is gone with deleted data array
CPPUNIT_ASSERT(rp.data() == nix::none);
CPPUNIT_ASSERT_THROW(rp.data(""), EmptyString);
CPPUNIT_ASSERT_THROW(rp.data("worng_id"), runtime_error);
tag.deleteFeature(rp.id());
}
void BaseTestFeature::testLinkType2Str() {
CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Tagged) == "Tagged");
CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Untagged) == "Untagged");
CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Indexed) == "Indexed");
}
void BaseTestFeature::testStreamOperator() {
stringstream s1, s2, s3;
s1 << nix::LinkType::Indexed;
CPPUNIT_ASSERT(s1.str() == "LinkType::Indexed");
s2 << nix::LinkType::Tagged;
CPPUNIT_ASSERT(s2.str() == "LinkType::Tagged");
s3 << nix::LinkType::Untagged;
CPPUNIT_ASSERT(s3.str() == "LinkType::Untagged");
}
void BaseTestFeature::testOperator() {
Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
CPPUNIT_ASSERT(rp != none);
rp = none;
CPPUNIT_ASSERT(rp == false);
CPPUNIT_ASSERT(rp == none);
}
<|endoftext|> |
<commit_before>/*
* main.cpp
* SimpleChess
*
* Created by Ronak Gajrawala on 12/01/13.
* Copyright (c) 2013 Ronak Gajrawala. All rights reserved.
*/
// #define __CPP_DEBUG__ // If you are debugging. (Currently, this changes very little.)
/**
* @todo Add Castle button.
* @todo Add background music.
* @todo Add undo move button.
*/
#include "main.hpp"
ChessMain() {
File.SetPath("/Users/usandfriends/Documents/Ronak\'s Folder/Programming/C++/My Programs/SimpleChess/SimpleChess/");
Textures.Initialize();
Sounds.Initialize();
while(true) {
if(StartPage.Main()) {
GameWindow.Main();
} else {
Reader.Main();
}
}
EndMain();
}
<commit_msg>Update main.cpp<commit_after>/*
* main.cpp
* SimpleChess
*
* Created by Ronak Gajrawala on 12/01/13.
* Copyright (c) 2013 Ronak Gajrawala. All rights reserved.
*/
// #define __CPP_DEBUG__ // If you are debugging. (Currently, this changes very little.)
/**
* @todo Add Castle button.
* @todo Add background music.
* @todo Add undo move button.
*/
#include "main.hpp"
ChessMain() {
File.SetPath("/Users/usandfriends/Documents/Ronak\'s Folder/Programming/C++/My Programs/SimpleChess/SimpleChess/");
Textures.Initialize();
Sounds.Initialize();
while(true) {
if(StartPage.Main()) {
GameWindow.Main();
} else {
Reader.Main();
}
}
EndMain();
}
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2010 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
Copyright (C) 2017 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/SamsungV0Decompressor.h"
#include "common/Common.h" // for ushort16, uint32, int32
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "io/BitPumpMSB32.h" // for BitPumpMSB32
#include "io/Buffer.h" // for Buffer
#include "io/ByteStream.h" // for ByteStream
#include "io/Endianness.h" // for Endianness, Endianness::li...
#include "tiff/TiffEntry.h" // for TiffEntry
#include "tiff/TiffIFD.h" // for TiffIFD
#include "tiff/TiffTag.h" // for TiffTag, TiffTag::IMAGELENGTH
#include <algorithm> // for max
#include <cassert> // for assert
namespace rawspeed {
SamsungV0Decompressor::SamsungV0Decompressor(const RawImage& image,
const TiffIFD* ifd,
const Buffer* file)
: AbstractSamsungDecompressor(image), raw(ifd), mFile(file) {
const uint32 width = mRaw->dim.x;
const uint32 height = mRaw->dim.y;
if (width == 0 || height == 0 || width < 16 || width > 5546 || height > 3714)
ThrowRDE("Unexpected image dimensions found: (%u; %u)", width, height);
}
void SamsungV0Decompressor::decompress() {
const uint32 width = mRaw->dim.x;
const uint32 height = mRaw->dim.y;
const uint32 offset = raw->getEntry(STRIPOFFSETS)->getU32();
const uint32 count = raw->getEntry(STRIPBYTECOUNTS)->getU32();
uint32 compressed_offset =
raw->getEntry(static_cast<TiffTag>(40976))->getU32();
ByteStream bs(mFile, compressed_offset, count, Endianness::little);
for (uint32 y = 0; y < height; y++) {
uint32 line_offset = offset + bs.getI32();
if (line_offset >= mFile->getSize())
ThrowRDE("Offset outside image file, file probably truncated.");
int len[4];
for (int& i : len)
i = y < 2 ? 7 : 4;
BitPumpMSB32 bits(mFile, line_offset);
int op[4];
auto* img = reinterpret_cast<ushort16*>(mRaw->getData(0, y));
const auto* const past_last = reinterpret_cast<ushort16*>(
mRaw->getData(width - 1, y) + mRaw->getBpp());
ushort16* img_up = reinterpret_cast<ushort16*>(
mRaw->getData(0, std::max(0, static_cast<int>(y) - 1)));
ushort16* img_up2 = reinterpret_cast<ushort16*>(
mRaw->getData(0, std::max(0, static_cast<int>(y) - 2)));
// Image is arranged in groups of 16 pixels horizontally
for (uint32 x = 0; x < width; x += 16) {
bits.fill();
bool dir = !!bits.getBitsNoFill(1);
for (int& i : op)
i = bits.getBitsNoFill(2);
for (int i = 0; i < 4; i++) {
assert(op[i] >= 0 && op[i] <= 3);
switch (op[i]) {
case 3:
len[i] = bits.getBits(4);
break;
case 2:
len[i]--;
break;
case 1:
len[i]++;
break;
default:
// FIXME: it can be zero too.
break;
}
if (len[i] < 0)
ThrowRDE("Bit length less than 0.");
if (len[i] > 16)
ThrowRDE("Bit Length more than 16.");
}
if (dir) {
// Upward prediction
// First we decode even pixels
for (int c = 0; c < 16; c += 2) {
int b = len[c >> 3];
int32 adj = 0;
if (b)
adj = (static_cast<int32>(bits.getBits(b)) << (32 - b) >> (32 - b));
img[c] = adj + img_up[c];
}
// Now we decode odd pixels
// Why on earth upward prediction only looks up 1 line above
// is beyond me, it will hurt compression a deal.
for (int c = 1; c < 16; c += 2) {
int b = len[2 | (c >> 3)];
int32 adj = 0;
if (b)
adj = (static_cast<int32>(bits.getBits(b)) << (32 - b) >> (32 - b));
img[c] = adj + img_up2[c];
}
} else {
// Left to right prediction
// First we decode even pixels
int pred_left = x != 0 ? img[-2] : 128;
for (int c = 0; c < 16; c += 2) {
int b = len[c >> 3];
int32 adj = 0;
if (b)
adj = (static_cast<int32>(bits.getBits(b)) << (32 - b) >> (32 - b));
if (img + c < past_last)
img[c] = adj + pred_left;
}
// Now we decode odd pixels
pred_left = x != 0 ? img[-1] : 128;
for (int c = 1; c < 16; c += 2) {
int b = len[2 | (c >> 3)];
int32 adj = 0;
if (b)
adj = (static_cast<int32>(bits.getBits(b)) << (32 - b) >> (32 - b));
if (img + c < past_last)
img[c] = adj + pred_left;
}
}
img += 16;
img_up += 16;
img_up2 += 16;
}
}
// Swap red and blue pixels to get the final CFA pattern
for (uint32 y = 0; y < height - 1; y += 2) {
auto* topline = reinterpret_cast<ushort16*>(mRaw->getData(0, y));
auto* bottomline = reinterpret_cast<ushort16*>(mRaw->getData(0, y + 1));
for (uint32 x = 0; x < width - 1; x += 2) {
ushort16 temp = topline[1];
topline[1] = bottomline[0];
bottomline[0] = temp;
topline += 2;
bottomline += 2;
}
}
}
} // namespace rawspeed
<commit_msg>SamsungV0Decompressor::decompress(): surely the offsets are unsigned?<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2010 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
Copyright (C) 2017 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/SamsungV0Decompressor.h"
#include "common/Common.h" // for ushort16, uint32, int32
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "io/BitPumpMSB32.h" // for BitPumpMSB32
#include "io/Buffer.h" // for Buffer
#include "io/ByteStream.h" // for ByteStream
#include "io/Endianness.h" // for Endianness, Endianness::li...
#include "tiff/TiffEntry.h" // for TiffEntry
#include "tiff/TiffIFD.h" // for TiffIFD
#include "tiff/TiffTag.h" // for TiffTag, TiffTag::IMAGELENGTH
#include <algorithm> // for max
#include <cassert> // for assert
namespace rawspeed {
SamsungV0Decompressor::SamsungV0Decompressor(const RawImage& image,
const TiffIFD* ifd,
const Buffer* file)
: AbstractSamsungDecompressor(image), raw(ifd), mFile(file) {
const uint32 width = mRaw->dim.x;
const uint32 height = mRaw->dim.y;
if (width == 0 || height == 0 || width < 16 || width > 5546 || height > 3714)
ThrowRDE("Unexpected image dimensions found: (%u; %u)", width, height);
}
void SamsungV0Decompressor::decompress() {
const uint32 width = mRaw->dim.x;
const uint32 height = mRaw->dim.y;
const uint32 offset = raw->getEntry(STRIPOFFSETS)->getU32();
const uint32 count = raw->getEntry(STRIPBYTECOUNTS)->getU32();
uint32 compressed_offset =
raw->getEntry(static_cast<TiffTag>(40976))->getU32();
ByteStream bs(mFile, compressed_offset, count, Endianness::little);
for (uint32 y = 0; y < height; y++) {
uint32 line_offset = offset + bs.getU32();
if (line_offset >= mFile->getSize())
ThrowRDE("Offset outside image file, file probably truncated.");
int len[4];
for (int& i : len)
i = y < 2 ? 7 : 4;
BitPumpMSB32 bits(mFile, line_offset);
int op[4];
auto* img = reinterpret_cast<ushort16*>(mRaw->getData(0, y));
const auto* const past_last = reinterpret_cast<ushort16*>(
mRaw->getData(width - 1, y) + mRaw->getBpp());
ushort16* img_up = reinterpret_cast<ushort16*>(
mRaw->getData(0, std::max(0, static_cast<int>(y) - 1)));
ushort16* img_up2 = reinterpret_cast<ushort16*>(
mRaw->getData(0, std::max(0, static_cast<int>(y) - 2)));
// Image is arranged in groups of 16 pixels horizontally
for (uint32 x = 0; x < width; x += 16) {
bits.fill();
bool dir = !!bits.getBitsNoFill(1);
for (int& i : op)
i = bits.getBitsNoFill(2);
for (int i = 0; i < 4; i++) {
assert(op[i] >= 0 && op[i] <= 3);
switch (op[i]) {
case 3:
len[i] = bits.getBits(4);
break;
case 2:
len[i]--;
break;
case 1:
len[i]++;
break;
default:
// FIXME: it can be zero too.
break;
}
if (len[i] < 0)
ThrowRDE("Bit length less than 0.");
if (len[i] > 16)
ThrowRDE("Bit Length more than 16.");
}
if (dir) {
// Upward prediction
// First we decode even pixels
for (int c = 0; c < 16; c += 2) {
int b = len[c >> 3];
int32 adj = 0;
if (b)
adj = (static_cast<int32>(bits.getBits(b)) << (32 - b) >> (32 - b));
img[c] = adj + img_up[c];
}
// Now we decode odd pixels
// Why on earth upward prediction only looks up 1 line above
// is beyond me, it will hurt compression a deal.
for (int c = 1; c < 16; c += 2) {
int b = len[2 | (c >> 3)];
int32 adj = 0;
if (b)
adj = (static_cast<int32>(bits.getBits(b)) << (32 - b) >> (32 - b));
img[c] = adj + img_up2[c];
}
} else {
// Left to right prediction
// First we decode even pixels
int pred_left = x != 0 ? img[-2] : 128;
for (int c = 0; c < 16; c += 2) {
int b = len[c >> 3];
int32 adj = 0;
if (b)
adj = (static_cast<int32>(bits.getBits(b)) << (32 - b) >> (32 - b));
if (img + c < past_last)
img[c] = adj + pred_left;
}
// Now we decode odd pixels
pred_left = x != 0 ? img[-1] : 128;
for (int c = 1; c < 16; c += 2) {
int b = len[2 | (c >> 3)];
int32 adj = 0;
if (b)
adj = (static_cast<int32>(bits.getBits(b)) << (32 - b) >> (32 - b));
if (img + c < past_last)
img[c] = adj + pred_left;
}
}
img += 16;
img_up += 16;
img_up2 += 16;
}
}
// Swap red and blue pixels to get the final CFA pattern
for (uint32 y = 0; y < height - 1; y += 2) {
auto* topline = reinterpret_cast<ushort16*>(mRaw->getData(0, y));
auto* bottomline = reinterpret_cast<ushort16*>(mRaw->getData(0, y + 1));
for (uint32 x = 0; x < width - 1; x += 2) {
ushort16 temp = topline[1];
topline[1] = bottomline[0];
bottomline[0] = temp;
topline += 2;
bottomline += 2;
}
}
}
} // namespace rawspeed
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: preproc.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 18:32:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ADC_CPP_PREPROC_HXX
#define ADC_CPP_PREPROC_HXX
// USED SERVICES
// BASE CLASSES
// COMPONENTS
#include <deque>
// PARAMETERS
class CharacterSource;
namespace cpp
{
class Token;
class CodeExplorer;
class DefineDescription;
class PreProcessor
{
public:
typedef std::map< udmstri, DefineDescription* > MacroMap;
// LIFECYCLE
PreProcessor();
~PreProcessor();
// OPERATONS
void AssignPartners(
CodeExplorer & o_rCodeExplorer,
CharacterSource & o_rCharSource,
const MacroMap & i_rCurValidDefines );
void Process_Token(
cpp::Token & let_drToken );
void UnblockMacro(
const char * i_sMacroName );
private:
public: // Necessary for instantiation of static variable:
enum E_State
{
plain = 0,
expect_macro_bracket_left,
expect_macro_param,
state_MAX
};
typedef void (PreProcessor::* F_TOKENPROC )(cpp::Token &);
void On_plain( cpp::Token & );
void On_expect_macro_bracket_left( cpp::Token & );
void On_expect_macro_param( cpp::Token & );
private: // Reprivate again:
typedef std::deque< DYN cpp::Token * > TokenQueue;
typedef StringVector List_MacroParams;
bool CheckForDefine(
cpp::Token & let_drToken );
void InterpretMacro();
// DATA
static F_TOKENPROC aTokProcs[state_MAX];
// Referenced extern objects
CodeExplorer * pCppExplorer;
CharacterSource * pSourceText;
const MacroMap * pCurValidDefines;
// internal data
TokenQueue aTokens;
E_State eState;
DefineDescription * pCurMacro;
DYN Token * dpCurMacroName;
List_MacroParams aCurMacroParams;
csv::StreamStr aCurParamText;
intt nBracketInParameterCounter;
StringVector aBlockedMacroNames;
};
} // end namespace cpp
#endif
<commit_msg>INTEGRATION: CWS adc18 (1.2.56); FILE MERGED 2007/10/19 10:37:30 np 1.2.56.1: #i81775#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: preproc.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2007-11-02 17:00:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ADC_CPP_PREPROC_HXX
#define ADC_CPP_PREPROC_HXX
// USED SERVICES
// BASE CLASSES
// COMPONENTS
#include <deque>
// PARAMETERS
class CharacterSource;
namespace cpp
{
class Token;
class CodeExplorer;
class DefineDescription;
class PreProcessor
{
public:
typedef std::map< String, DefineDescription* > MacroMap;
// LIFECYCLE
PreProcessor();
~PreProcessor();
// OPERATONS
void AssignPartners(
CodeExplorer & o_rCodeExplorer,
CharacterSource & o_rCharSource,
const MacroMap & i_rCurValidDefines );
void Process_Token(
cpp::Token & let_drToken );
void UnblockMacro(
const char * i_sMacroName );
private:
public: // Necessary for instantiation of static variable:
enum E_State
{
plain = 0,
expect_macro_bracket_left,
expect_macro_param,
state_MAX
};
typedef void (PreProcessor::* F_TOKENPROC )(cpp::Token &);
void On_plain( cpp::Token & );
void On_expect_macro_bracket_left( cpp::Token & );
void On_expect_macro_param( cpp::Token & );
private: // Reprivate again:
typedef std::deque< DYN cpp::Token * > TokenQueue;
typedef StringVector List_MacroParams;
bool CheckForDefine(
cpp::Token & let_drToken );
void InterpretMacro();
// DATA
static F_TOKENPROC aTokProcs[state_MAX];
// Referenced extern objects
CodeExplorer * pCppExplorer;
CharacterSource * pSourceText;
const MacroMap * pCurValidDefines;
// internal data
TokenQueue aTokens;
E_State eState;
DefineDescription * pCurMacro;
DYN Token * dpCurMacroName;
List_MacroParams aCurMacroParams;
csv::StreamStr aCurParamText;
intt nBracketInParameterCounter;
StringVector aBlockedMacroNames;
};
} // end namespace cpp
#endif
<|endoftext|> |
<commit_before>/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY vincent.acary@inrialpes.fr
*/
#include "NonSmoothSolver.h"
#include "RuntimeException.h"
#include <iterator>
#include <iostream>
using namespace std;
// Private function used to fill in Solver_Options structure numerics_solver_options with current object data,
// only if isSet = true. Else set numerics_solver_options->isSet to false, which means that parameters
// will be read in the default_parameters file during Numerics driver call.
void NonSmoothSolver::fillSolverOptions()
{
numerics_solver_options = new Solver_Options;
if (!isSet)
numerics_solver_options->isSet = 0;
else
{
numerics_solver_options->isSet = 1;
strcpy(numerics_solver_options->solverName, name.c_str());
// No memory allocation for iparam and dparam of numerics_solver_options, just pointer links
}
// Link is required for iparam and dparam even when isSet == 0, since we need to recover output parameters (error ...)
numerics_solver_options->iSize = int_parameters->size();
numerics_solver_options->dSize = double_parameters->size();
numerics_solver_options->iparam = &((*int_parameters)[0]);
numerics_solver_options->dparam = &((*double_parameters)[0]);
}
// Default constructor: build an empty Solver_Options structure
// Parameters will be read in the default input parameters file during Numerics driver call.
NonSmoothSolver::NonSmoothSolver(): name("undefined"), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(false)
{
int_parameters = new IntParameters(NB_PARAM);
double_parameters = new DoubleParameters(NB_PARAM);
fillSolverOptions();
}
// Copy constructor
NonSmoothSolver::NonSmoothSolver(const NonSmoothSolver& newS):
name(newS.getName()), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(newS.isSolverSet())
{
int_parameters = new IntParameters(*newS.getIntParametersPtr());
double_parameters = new DoubleParameters(*newS.getDoubleParametersPtr());
fillSolverOptions();
}
// Constructor from a set of data
NonSmoothSolver::NonSmoothSolver(const std::string& newName, IntParameters& iparam, DoubleParameters& dparam):
name(newName), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(true)
{
int_parameters = new IntParameters(iparam);
double_parameters = new DoubleParameters(dparam);
fillSolverOptions();
}
NonSmoothSolver::NonSmoothSolver(const std::string& newName, IntParameters& iparam, DoubleParameters& dparam, double * dWork, int * iWork):
name(newName), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(true)
{
int_parameters = new IntParameters(iparam);
double_parameters = new DoubleParameters(dparam);
fillSolverOptions();
numerics_solver_options->dWork = dWork;
numerics_solver_options->iWork = iWork;
}
// Construction using XML object
NonSmoothSolver::NonSmoothSolver(NonSmoothSolverXML* solvXML):
name("undefined"), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(true)
{
if (solvXML == NULL)
RuntimeException::selfThrow("NonSmoothSolver, XML constructor, NULL input");
// Read name
name = solvXML->getName();
// Built and read int_parameters and double_parameters
int_parameters = new IntParameters;
double_parameters = new DoubleParameters;
if (!solvXML->hasIparam() || !solvXML->hasDparam())
RuntimeException::selfThrow("NonSmoothSolver, XML constructor, missing input in XML file (int or double vector)");
solvXML->getIParam(*int_parameters);
solvXML->getDParam(*double_parameters);
// if(int_parameters->size()>NB_PARAM || double_parameters->size()>NB_PARAM)
// {
// std::cout << "NonSmoothSolver xml constructor warning: too large number of provided int and/or double parameters. "<< std::endl;
// std::cout << "Some of them might be ignored. Check in the solver documentation to know what are the required parameters." << std::endl;
// }
fillSolverOptions();
}
// Construction by reading in a file (XML)
NonSmoothSolver::NonSmoothSolver(const string& inputFile):
name("undefined"), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(false)
{
}
NonSmoothSolver::~NonSmoothSolver()
{
delete numerics_solver_options;
delete int_parameters;
delete double_parameters;
}
void NonSmoothSolver::display() const
{
cout << "=== Non Smooth Solver based on algorithm of type " << name << " with:" << endl;
if (isSet)
{
cout << "int parameters: " ;
copy(int_parameters->begin(), int_parameters->end(), ostream_iterator<int>(cout, " "));
cout << endl;
cout << "double parameters: " ;
copy(double_parameters->begin(), double_parameters->end(), ostream_iterator<double>(cout, " "));
cout << endl;
}
else
cout << "no user input parameters" << endl;
cout << "===== End of NonSmoothSolver display =====" << endl;
}
void NonSmoothSolver::saveNonSmoothSolverToXML()
{
RuntimeException::selfThrow("NonSmoothSolver, saveNonSmoothSolverToXML: not yet implemented");
}
<commit_msg>uninitialized value (Insure has said)<commit_after>/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY vincent.acary@inrialpes.fr
*/
#include "NonSmoothSolver.h"
#include "RuntimeException.h"
#include <iterator>
#include <iostream>
using namespace std;
// Private function used to fill in Solver_Options structure numerics_solver_options with current object data,
// only if isSet = true. Else set numerics_solver_options->isSet to false, which means that parameters
// will be read in the default_parameters file during Numerics driver call.
void NonSmoothSolver::fillSolverOptions()
{
numerics_solver_options = new Solver_Options;
numerics_solver_options->filterOn = 0;
if (!isSet)
numerics_solver_options->isSet = 0;
else
{
numerics_solver_options->isSet = 1;
strcpy(numerics_solver_options->solverName, name.c_str());
// No memory allocation for iparam and dparam of numerics_solver_options, just pointer links
}
// Link is required for iparam and dparam even when isSet == 0, since we need to recover output parameters (error ...)
numerics_solver_options->iSize = int_parameters->size();
numerics_solver_options->dSize = double_parameters->size();
numerics_solver_options->iparam = &((*int_parameters)[0]);
numerics_solver_options->dparam = &((*double_parameters)[0]);
}
// Default constructor: build an empty Solver_Options structure
// Parameters will be read in the default input parameters file during Numerics driver call.
NonSmoothSolver::NonSmoothSolver(): name("undefined"), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(false)
{
int_parameters = new IntParameters(NB_PARAM);
double_parameters = new DoubleParameters(NB_PARAM);
fillSolverOptions();
}
// Copy constructor
NonSmoothSolver::NonSmoothSolver(const NonSmoothSolver& newS):
name(newS.getName()), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(newS.isSolverSet())
{
int_parameters = new IntParameters(*newS.getIntParametersPtr());
double_parameters = new DoubleParameters(*newS.getDoubleParametersPtr());
fillSolverOptions();
}
// Constructor from a set of data
NonSmoothSolver::NonSmoothSolver(const std::string& newName, IntParameters& iparam, DoubleParameters& dparam):
name(newName), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(true)
{
int_parameters = new IntParameters(iparam);
double_parameters = new DoubleParameters(dparam);
fillSolverOptions();
}
NonSmoothSolver::NonSmoothSolver(const std::string& newName, IntParameters& iparam, DoubleParameters& dparam, double * dWork, int * iWork):
name(newName), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(true)
{
int_parameters = new IntParameters(iparam);
double_parameters = new DoubleParameters(dparam);
fillSolverOptions();
numerics_solver_options->dWork = dWork;
numerics_solver_options->iWork = iWork;
}
// Construction using XML object
NonSmoothSolver::NonSmoothSolver(NonSmoothSolverXML* solvXML):
name("undefined"), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(true)
{
if (solvXML == NULL)
RuntimeException::selfThrow("NonSmoothSolver, XML constructor, NULL input");
// Read name
name = solvXML->getName();
// Built and read int_parameters and double_parameters
int_parameters = new IntParameters;
double_parameters = new DoubleParameters;
if (!solvXML->hasIparam() || !solvXML->hasDparam())
RuntimeException::selfThrow("NonSmoothSolver, XML constructor, missing input in XML file (int or double vector)");
solvXML->getIParam(*int_parameters);
solvXML->getDParam(*double_parameters);
// if(int_parameters->size()>NB_PARAM || double_parameters->size()>NB_PARAM)
// {
// std::cout << "NonSmoothSolver xml constructor warning: too large number of provided int and/or double parameters. "<< std::endl;
// std::cout << "Some of them might be ignored. Check in the solver documentation to know what are the required parameters." << std::endl;
// }
fillSolverOptions();
}
// Construction by reading in a file (XML)
NonSmoothSolver::NonSmoothSolver(const string& inputFile):
name("undefined"), int_parameters(NULL), double_parameters(NULL), numerics_solver_options(NULL), isSet(false)
{
}
NonSmoothSolver::~NonSmoothSolver()
{
delete numerics_solver_options;
delete int_parameters;
delete double_parameters;
}
void NonSmoothSolver::display() const
{
cout << "=== Non Smooth Solver based on algorithm of type " << name << " with:" << endl;
if (isSet)
{
cout << "int parameters: " ;
copy(int_parameters->begin(), int_parameters->end(), ostream_iterator<int>(cout, " "));
cout << endl;
cout << "double parameters: " ;
copy(double_parameters->begin(), double_parameters->end(), ostream_iterator<double>(cout, " "));
cout << endl;
}
else
cout << "no user input parameters" << endl;
cout << "===== End of NonSmoothSolver display =====" << endl;
}
void NonSmoothSolver::saveNonSmoothSolverToXML()
{
RuntimeException::selfThrow("NonSmoothSolver, saveNonSmoothSolverToXML: not yet implemented");
}
<|endoftext|> |
<commit_before>#include "fsbmosf.h"
#include <QGridLayout>
#include <QLabel>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonArray>
#include <QFile>
#include "fsentry.h"
#include "onlinedatamanager.h"
FSBMOSF::FSBMOSF()
{
_dataManager = NULL;
_manager = NULL;
_isAuthenticated = false;
_rootPath = _path = "Projects";
}
FSBMOSF::~FSBMOSF()
{
}
void FSBMOSF::setOnlineDataManager(OnlineDataManager *odm)
{
_dataManager = odm;
_manager = odm->getNetworkAccessManager(OnlineDataManager::OSF);
if (_isAuthenticated == false && _dataManager != NULL && _dataManager->authenticationSuccessful(OnlineDataManager::OSF))
setAuthenticated(true);
}
bool FSBMOSF::requiresAuthentication() const
{
return true;
}
void FSBMOSF::authenticate(const QString &username, const QString &password)
{
_dataManager->setAuthentication(OnlineDataManager::OSF, username, password);
bool success = _dataManager->authenticationSuccessful(OnlineDataManager::OSF);
_settings.sync();
if (success)
{
_settings.setValue("OSFUsername", username);
_settings.setValue("OSFPassword", password);
}
else
{
_settings.remove("OSFUsername");
_settings.remove("OSFPassword");
}
_settings.sync();
setAuthenticated(success);
}
void FSBMOSF::setAuthenticated(bool value)
{
if (value)
{
_isAuthenticated = true;
emit authenticationSuccess();
refresh();
}
else
{
_isAuthenticated = false;
emit authenticationFail("Username and password are not correct. Please try again.");
}
}
bool FSBMOSF::isAuthenticated() const
{
return _isAuthenticated;
}
void FSBMOSF::clearAuthentication()
{
_isAuthenticated = false;
_dataManager->clearAuthentication(OnlineDataManager::OSF);
_entries.clear();
_pathUrls.clear();
setPath(_rootPath);
emit entriesChanged();
_settings.sync();
_settings.remove("OSFUsername");
_settings.remove("OSFPassword");
_settings.sync();
emit authenticationClear();
}
void FSBMOSF::refresh()
{
if (_manager == NULL || _isAuthenticated == false)
return;
emit processingEntries();
_entries.clear();
if (_path == "Projects")
loadProjects();
else {
OnlineNodeData nodeData = _pathUrls[_path];
if (nodeData.isFolder)
loadFilesAndFolders(QUrl(nodeData.contentsPath), nodeData.level + 1);
if (nodeData.isComponent)
loadFilesAndFolders(QUrl(nodeData.childrenPath), nodeData.level + 1);
}
}
FSBMOSF::OnlineNodeData FSBMOSF::currentNodeData()
{
return _pathUrls[_path];
}
void FSBMOSF::loadProjects() {
QUrl url("https://api.osf.io/v2/users/me/nodes/");
//QUrl url("https://test-api.osf.io/v2/users/me/nodes/");
//QUrl url("https://staging2-api.osf.io/v2/users/me/nodes/");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/vnd.api+json");
request.setRawHeader("Accept", "application/vnd.api+json");
QNetworkReply* reply = _manager->get(request);
connect(reply, SIGNAL(finished()), this, SLOT(gotProjects()));
}
void FSBMOSF::gotProjects()
{
QNetworkReply *reply = (QNetworkReply*)this->sender();
if (reply->error() == QNetworkReply::NoError)
{
QByteArray data = reply->readAll();
QString dataString = (QString) data;
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(dataString.toUtf8(), &error);
QJsonObject json = doc.object();
QJsonArray dataArray = json.value("data").toArray();
foreach (const QJsonValue & value, dataArray) {
QJsonObject nodeObject = value.toObject();
QJsonObject attrObj = nodeObject.value("attributes").toObject();
QString category = attrObj.value("category").toString();
if (category != "project")
continue;
OnlineNodeData nodeData;
nodeData.name = attrObj.value("title").toString();
nodeData.isFolder = true;
nodeData.isComponent = true;
nodeData.contentsPath = getRelationshipUrl(nodeObject, "files");
nodeData.childrenPath = getRelationshipUrl(nodeObject, "children");
QJsonObject topLinksObj = nodeObject.value("links").toObject();
nodeData.nodePath = topLinksObj.value("self").toString();
nodeData.level = 1;
nodeData.canCreateFolders = false;
nodeData.canCreateFiles = false;
QString path = _path + "/" + nodeData.name;
_entries.append(createEntry(path, FSEntry::Folder));
_pathUrls[path] = nodeData;
}
}
emit entriesChanged();
reply->deleteLater();
}
void FSBMOSF::loadFilesAndFolders(QUrl url, int level)
{
parseFilesAndFolders(url, level);
}
void FSBMOSF::parseFilesAndFolders(QUrl url, int level)
{
_level = level;
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/vnd.api+json");
request.setRawHeader("Accept", "application/vnd.api+json");
QNetworkReply* reply = _manager->get(request);
connect(reply, SIGNAL(finished()), this, SLOT(gotFilesAndFolders()));
}
void FSBMOSF::gotFilesAndFolders()
{
QNetworkReply *reply = (QNetworkReply*)this->sender();
bool finished = false;
if (reply->error() == QNetworkReply::NoError)
{
QByteArray data = reply->readAll();
QString dataString = (QString) data;
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(dataString.toUtf8(), &error);
QJsonObject json = doc.object();
QJsonArray dataArray = json.value("data").toArray();
foreach (const QJsonValue & value, dataArray) {
QJsonObject nodeObject = value.toObject();
OnlineNodeData nodeData;
nodeData.isComponent = nodeObject.value("type").toString() == "nodes";
FSEntry::EntryType entryType = FSEntry::Other;
QJsonObject attrObj = nodeObject.value("attributes").toObject();
if (nodeData.isComponent == false)
{
QString kind = attrObj.value("kind").toString();
if (kind != "folder" && kind != "file")
continue;
nodeData.name = attrObj.value("name").toString();
if (kind == "folder")
entryType = FSEntry::Folder;
else if (nodeData.name.endsWith(".jasp", Qt::CaseInsensitive))
entryType = FSEntry::JASP;
else if (nodeData.name.endsWith(".csv", Qt::CaseInsensitive))
entryType = FSEntry::CSV;
#ifdef QT_DEBUG
else if (nodeData.name.endsWith(".spss", Qt::CaseInsensitive))
entryType = FSEntry::SPSS;
#endif
else
continue;
}
else
{
entryType = FSEntry::Folder;
nodeData.name = attrObj.value("title").toString();
}
if (entryType == FSEntry::Folder) {
nodeData.contentsPath = getRelationshipUrl(nodeObject, "files");
nodeData.childrenPath = getRelationshipUrl(nodeObject, "children");
QJsonObject topLinksObj = nodeObject.value("links").toObject();
if (nodeData.isComponent)
nodeData.nodePath = topLinksObj.value("self").toString();
else
nodeData.nodePath = topLinksObj.value("info").toString();
nodeData.uploadPath = topLinksObj.value("upload").toString();
nodeData.isFolder = true;
nodeData.canCreateFolders = topLinksObj.contains("new_folder");
nodeData.canCreateFiles = topLinksObj.contains("upload");
if (nodeData.nodePath == "")
nodeData.nodePath = reply->url().toString() + "#folder://" + nodeData.name;
}
else
{
QJsonObject linksObj = nodeObject.value("links").toObject();
nodeData.isFolder = false;
nodeData.uploadPath = linksObj.value("upload").toString();
nodeData.downloadPath = linksObj.value("download").toString();
nodeData.nodePath = linksObj.value("info").toString();
nodeData.canCreateFolders = false;
nodeData.canCreateFiles = false;
}
QString path = _path + "/" + nodeData.name;
nodeData.level = _level;
_entries.append(createEntry(path, entryType));
_pathUrls[path] = nodeData;
}
QJsonObject contentLevelLinks = json.value("links").toObject();
QJsonValue nextContentList = contentLevelLinks.value("next");
if (nextContentList.isNull() == false)
parseFilesAndFolders(QUrl(nextContentList.toString()), _level + 1);
else
finished = true;
}
if (finished)
emit entriesChanged();
reply->deleteLater();
}
QString FSBMOSF::getRelationshipUrl(QJsonObject nodeObject, QString name)
{
QJsonObject relationshipsObj = nodeObject.value("relationships").toObject();
if (relationshipsObj.contains(name) == false)
return "";
QJsonObject filesObj = relationshipsObj.value(name).toObject();
QJsonObject linksObj = filesObj.value("links").toObject();
QJsonObject relatedObj = linksObj.value("related").toObject();
return relatedObj.value("href").toString();
}
FSBMOSF::OnlineNodeData FSBMOSF::getNodeData(QString key)
{
return _pathUrls[key];
}
<commit_msg>Fixes #1113 OSF duplication of folders<commit_after>#include "fsbmosf.h"
#include <QGridLayout>
#include <QLabel>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonArray>
#include <QFile>
#include "fsentry.h"
#include "onlinedatamanager.h"
FSBMOSF::FSBMOSF()
{
_dataManager = NULL;
_manager = NULL;
_isAuthenticated = false;
_rootPath = _path = "Projects";
}
FSBMOSF::~FSBMOSF()
{
}
void FSBMOSF::setOnlineDataManager(OnlineDataManager *odm)
{
_dataManager = odm;
_manager = odm->getNetworkAccessManager(OnlineDataManager::OSF);
if (_isAuthenticated == false && _dataManager != NULL && _dataManager->authenticationSuccessful(OnlineDataManager::OSF))
setAuthenticated(true);
}
bool FSBMOSF::requiresAuthentication() const
{
return true;
}
void FSBMOSF::authenticate(const QString &username, const QString &password)
{
_dataManager->setAuthentication(OnlineDataManager::OSF, username, password);
bool success = _dataManager->authenticationSuccessful(OnlineDataManager::OSF);
_settings.sync();
if (success)
{
_settings.setValue("OSFUsername", username);
_settings.setValue("OSFPassword", password);
}
else
{
_settings.remove("OSFUsername");
_settings.remove("OSFPassword");
}
_settings.sync();
setAuthenticated(success);
}
void FSBMOSF::setAuthenticated(bool value)
{
if (value)
{
_isAuthenticated = true;
emit authenticationSuccess();
refresh();
}
else
{
_isAuthenticated = false;
emit authenticationFail("Username and password are not correct. Please try again.");
}
}
bool FSBMOSF::isAuthenticated() const
{
return _isAuthenticated;
}
void FSBMOSF::clearAuthentication()
{
_isAuthenticated = false;
_dataManager->clearAuthentication(OnlineDataManager::OSF);
_entries.clear();
_pathUrls.clear();
setPath(_rootPath);
emit entriesChanged();
_settings.sync();
_settings.remove("OSFUsername");
_settings.remove("OSFPassword");
_settings.sync();
emit authenticationClear();
}
void FSBMOSF::refresh()
{
if (_manager == NULL || _isAuthenticated == false)
return;
emit processingEntries();
_entries.clear();
if (_path == "Projects")
loadProjects();
else {
OnlineNodeData nodeData = _pathUrls[_path];
if (nodeData.isFolder)
loadFilesAndFolders(QUrl(nodeData.contentsPath), nodeData.level + 1);
if (nodeData.isComponent)
loadFilesAndFolders(QUrl(nodeData.childrenPath), nodeData.level + 1);
}
}
FSBMOSF::OnlineNodeData FSBMOSF::currentNodeData()
{
return _pathUrls[_path];
}
void FSBMOSF::loadProjects() {
QUrl url("https://api.osf.io/v2/users/me/nodes/");
//QUrl url("https://test-api.osf.io/v2/users/me/nodes/");
//QUrl url("https://staging2-api.osf.io/v2/users/me/nodes/");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/vnd.api+json");
request.setRawHeader("Accept", "application/vnd.api+json");
QNetworkReply* reply = _manager->get(request);
connect(reply, SIGNAL(finished()), this, SLOT(gotProjects()));
}
void FSBMOSF::gotProjects()
{
QNetworkReply *reply = (QNetworkReply*)this->sender();
if (reply->error() == QNetworkReply::NoError)
{
QByteArray data = reply->readAll();
QString dataString = (QString) data;
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(dataString.toUtf8(), &error);
QJsonObject json = doc.object();
QJsonArray dataArray = json.value("data").toArray();
if ( dataArray.size() > 0 )
_entries.clear();
foreach (const QJsonValue & value, dataArray) {
QJsonObject nodeObject = value.toObject();
QJsonObject attrObj = nodeObject.value("attributes").toObject();
QString category = attrObj.value("category").toString();
if (category != "project")
continue;
OnlineNodeData nodeData;
nodeData.name = attrObj.value("title").toString();
nodeData.isFolder = true;
nodeData.isComponent = true;
nodeData.contentsPath = getRelationshipUrl(nodeObject, "files");
nodeData.childrenPath = getRelationshipUrl(nodeObject, "children");
QJsonObject topLinksObj = nodeObject.value("links").toObject();
nodeData.nodePath = topLinksObj.value("self").toString();
nodeData.level = 1;
nodeData.canCreateFolders = false;
nodeData.canCreateFiles = false;
QString path = _path + "/" + nodeData.name;
_entries.append(createEntry(path, FSEntry::Folder));
_pathUrls[path] = nodeData;
}
}
emit entriesChanged();
reply->deleteLater();
}
void FSBMOSF::loadFilesAndFolders(QUrl url, int level)
{
parseFilesAndFolders(url, level);
}
void FSBMOSF::parseFilesAndFolders(QUrl url, int level)
{
_level = level;
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/vnd.api+json");
request.setRawHeader("Accept", "application/vnd.api+json");
QNetworkReply* reply = _manager->get(request);
connect(reply, SIGNAL(finished()), this, SLOT(gotFilesAndFolders()));
}
void FSBMOSF::gotFilesAndFolders()
{
QNetworkReply *reply = (QNetworkReply*)this->sender();
bool finished = false;
if (reply->error() == QNetworkReply::NoError)
{
QByteArray data = reply->readAll();
QString dataString = (QString) data;
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(dataString.toUtf8(), &error);
QJsonObject json = doc.object();
QJsonArray dataArray = json.value("data").toArray();
if ( dataArray.size() > 0 )
_entries.clear();
foreach (const QJsonValue & value, dataArray) {
QJsonObject nodeObject = value.toObject();
OnlineNodeData nodeData;
nodeData.isComponent = nodeObject.value("type").toString() == "nodes";
FSEntry::EntryType entryType = FSEntry::Other;
QJsonObject attrObj = nodeObject.value("attributes").toObject();
if (nodeData.isComponent == false)
{
QString kind = attrObj.value("kind").toString();
if (kind != "folder" && kind != "file")
continue;
nodeData.name = attrObj.value("name").toString();
if (kind == "folder")
entryType = FSEntry::Folder;
else if (nodeData.name.endsWith(".jasp", Qt::CaseInsensitive))
entryType = FSEntry::JASP;
else if (nodeData.name.endsWith(".csv", Qt::CaseInsensitive))
entryType = FSEntry::CSV;
#ifdef QT_DEBUG
else if (nodeData.name.endsWith(".spss", Qt::CaseInsensitive))
entryType = FSEntry::SPSS;
#endif
else
continue;
}
else
{
entryType = FSEntry::Folder;
nodeData.name = attrObj.value("title").toString();
}
if (entryType == FSEntry::Folder) {
nodeData.contentsPath = getRelationshipUrl(nodeObject, "files");
nodeData.childrenPath = getRelationshipUrl(nodeObject, "children");
QJsonObject topLinksObj = nodeObject.value("links").toObject();
if (nodeData.isComponent)
nodeData.nodePath = topLinksObj.value("self").toString();
else
nodeData.nodePath = topLinksObj.value("info").toString();
nodeData.uploadPath = topLinksObj.value("upload").toString();
nodeData.isFolder = true;
nodeData.canCreateFolders = topLinksObj.contains("new_folder");
nodeData.canCreateFiles = topLinksObj.contains("upload");
if (nodeData.nodePath == "")
nodeData.nodePath = reply->url().toString() + "#folder://" + nodeData.name;
}
else
{
QJsonObject linksObj = nodeObject.value("links").toObject();
nodeData.isFolder = false;
nodeData.uploadPath = linksObj.value("upload").toString();
nodeData.downloadPath = linksObj.value("download").toString();
nodeData.nodePath = linksObj.value("info").toString();
nodeData.canCreateFolders = false;
nodeData.canCreateFiles = false;
}
QString path = _path + "/" + nodeData.name;
nodeData.level = _level;
_entries.append(createEntry(path, entryType));
_pathUrls[path] = nodeData;
}
QJsonObject contentLevelLinks = json.value("links").toObject();
QJsonValue nextContentList = contentLevelLinks.value("next");
if (nextContentList.isNull() == false)
parseFilesAndFolders(QUrl(nextContentList.toString()), _level + 1);
else
finished = true;
}
if (finished)
emit entriesChanged();
reply->deleteLater();
}
QString FSBMOSF::getRelationshipUrl(QJsonObject nodeObject, QString name)
{
QJsonObject relationshipsObj = nodeObject.value("relationships").toObject();
if (relationshipsObj.contains(name) == false)
return "";
QJsonObject filesObj = relationshipsObj.value(name).toObject();
QJsonObject linksObj = filesObj.value("links").toObject();
QJsonObject relatedObj = linksObj.value("related").toObject();
return relatedObj.value("href").toString();
}
FSBMOSF::OnlineNodeData FSBMOSF::getNodeData(QString key)
{
return _pathUrls[key];
}
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/STRUCTURE/assignBondOrderProcessor.h>
#include <BALL/FORMAT/MOL2File.h>
#include <BALL/KERNEL/system.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"
using namespace std;
using namespace BALL;
int main (int argc, char **argv)
{
// instantiate CommandlineParser object supplying
// - tool name
// - short description
// - version string
// - build date
// - category
CommandlineParser parpars("BondOrderAssigner", "computes bond order assignments for a ligand ", VERSION, String(__DATE__), "Preparation");
// we register an input file parameter
// - CLI switch
// - description
// - Inputfile
// - required
parpars.registerParameter("i", "input mol2-file", INFILE, true);
// we register an output file parameter
// - description
// - Outputfile
// - required
parpars.registerParameter("o", "output mol2-file name for first solution", STRING, true, "", true);
parpars.registerParameter("o_id", "output id", STRING, true, "", true);
parpars.registerParameter("o_dir", "output directory for 2nd to last solution", STRING, true, "", true);
// register String parameter for supplying max number of solutions
parpars.registerParameter("max_sol", "maximal number of assignments solutions to compute", INT, false, 25);
parpars.setParameterRestrictions("max_sol", 0, 100);
// parameter for computing sub-optimal solutions
parpars.registerFlag("non_opt", "compute sub-optimal assignments as well", false);
// option for hydrogen addition
// TODO: test and then release :-)
//parpars.registerFlag("add_hyd", "add hydrogens as well", false);
// choice of penalty table
parpars.registerParameter("scr_pen", "penalty table", STRING, false, "Antechamber");
list<String> ini_files;
ini_files.push_back("Antechamber");
ini_files.push_back("BALL");
parpars.setParameterRestrictions("scr_pen", ini_files);
// the manual
String man = "This tool computes optimal and sub-optimal bond order assignments based on an atomic penalty function for a given ligand in mol2 file format.\n\nOptional parameters are the maximal number of solutions to be computed ('-max_sol'), the penalty table specifiying the atomic penalty rules ('-scr_pen'), a flag indicating if sub-optimal solutions should be computed as well ('-non_opt') and a flag indicating if hydrogens should be computed as well ('-add_hyd').\n\nOutput of this tool is a number of mol2 files each containing one bond order assignment.\n\nTo upload an input file please use the upload tool (Get Data -> Upload File).\n\n**Further information and help** can be found in our wiki http://ball-trac.bioinf.uni-sb.de/wiki/ballaxy/BOAConstructor_Help.\n\nPlease cite the following: Dehof, A.K., Rurainski, A., Bui, Q.B.A., Boecker, S., Lenhof, H.-P. & Hildebrandt, A. (2011). Automated Bond Order Assignment as an Optimization Problem. Bioinformatics, 2011";
parpars.setToolManual(man);
// here we set the types of I/O files, for example sdf is also allowed
parpars.setSupportedFormats("i","mol2");
parpars.setSupportedFormats("o","mol2");
parpars.parse(argc, argv);
// read the input
MOL2File f0;
f0.open(parpars.get("i"));
System system;
f0 >> system;
AssignBondOrderProcessor abop;
// the combination of the following two options causes the computation of all optimal solutions
abop.options.setInteger(AssignBondOrderProcessor::Option::MAX_NUMBER_OF_SOLUTIONS, 0);
abop.options.setBool(AssignBondOrderProcessor::Option::COMPUTE_ALSO_NON_OPTIMAL_SOLUTIONS, false);
if (parpars.has("max_sol"))
{
int max_sol = parpars.get("max_sol").toInt();
//cout << " limit number of solutions to " << max_sol << endl;
abop.options.setInteger(AssignBondOrderProcessor::Option::MAX_NUMBER_OF_SOLUTIONS, String(max_sol).toInt());
}
bool non_opt = false;
if (parpars.has("non_opt"))
{
non_opt = parpars.get("non_opt").toBool();
//if (non_opt)
// cout << " Compute also non-optimal solutions." << endl;
abop.options.setBool(AssignBondOrderProcessor::Option::COMPUTE_ALSO_NON_OPTIMAL_SOLUTIONS, non_opt);
}
if (parpars.has("add_hyd"))
{
bool add_hyd = parpars.get("add_hyd").toBool();
//if (add_hyd)
// cout << " Add hydrogens as well." << endl;
abop.options.setBool(AssignBondOrderProcessor::Option::ADD_HYDROGENS, add_hyd);
}
if (parpars.has("scr_pen"))
{
String penalty_table = parpars.get("scr_pen");
//cout << " Use penalty table " << penalty_table << endl;
if (penalty_table == "Antechamber")
abop.options[AssignBondOrderProcessor::Option::INIFile] = "/bond_lengths/BondOrderGAFF.xml";
else
abop.options[AssignBondOrderProcessor::Option::INIFile] = "/bond_lengths/BondOrder.xml";
}
// set the solver
//abop.options.set(AssignBondOrderProcessor::Option::ALGORITHM, AssignBondOrderProcessor::Algorithm::A_STAR);
abop.options.set(AssignBondOrderProcessor::Option::ALGORITHM, AssignBondOrderProcessor::Algorithm::FPT);
abop.options.dump();
system.apply(abop);
Size num_of_sols = abop.getNumberOfComputedSolutions();
if (num_of_sols == 0)
{
Log << "No valid bond order assignment found!" << endl;
return 1;
}
else
{
//Log << "Found " << num_of_sols << " solutions:" << endl;
for (Size i=0; (i<num_of_sols) && (non_opt || (abop.getTotalPenalty(0)==abop.getTotalPenalty(i))); i++)
{
Log << " Solution " << i << " has penalty " << abop.getTotalPenalty(i) << endl;
// apply the solution
if (abop.apply(i))
{
String outfile_name = (i == 0) ? String(parpars.get("o"))
: String(parpars.get("o_dir")) + "/primary_"
+ String(parpars.get("o_id")) + "_solution" + String(i)
+ "_visible_mol2";
//Log << " Writing solution " << String(i) << " as " << outfile_name << endl;
// GenericMolFile* outfile = MolFileFactory::open(outfile_name, ios::out);
MOL2File outfile(outfile_name, ios::out);
system.beginMolecule()->setProperty("BOA_Constructor_penalty", abop.getTotalPenalty(i));
outfile << system;
outfile.close();
}
}
}
Log << "done." << endl;
return 0;
}
<commit_msg>added file check for tool BondOrderAssigner<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/STRUCTURE/assignBondOrderProcessor.h>
#include <BALL/FORMAT/MOL2File.h>
#include <BALL/KERNEL/system.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"
using namespace std;
using namespace BALL;
int main (int argc, char **argv)
{
// instantiate CommandlineParser object supplying
// - tool name
// - short description
// - version string
// - build date
// - category
CommandlineParser parpars("BondOrderAssigner", "computes bond order assignments for a ligand ", VERSION, String(__DATE__), "Preparation");
// we register an input file parameter
// - CLI switch
// - description
// - Inputfile
// - required
parpars.registerParameter("i", "input mol2-file", INFILE, true);
// we register an output file parameter
// - description
// - Outputfile
// - required
parpars.registerParameter("o", "output mol2-file name for first solution", STRING, true, "", true);
parpars.registerParameter("o_id", "output id", STRING, true, "", true);
parpars.registerParameter("o_dir", "output directory for 2nd to last solution", STRING, true, "", true);
// register String parameter for supplying max number of solutions
parpars.registerParameter("max_sol", "maximal number of assignments solutions to compute", INT, false, 25);
parpars.setParameterRestrictions("max_sol", 0, 100);
// parameter for computing sub-optimal solutions
parpars.registerFlag("non_opt", "compute sub-optimal assignments as well", false);
// option for hydrogen addition
// TODO: test and then release :-)
//parpars.registerFlag("add_hyd", "add hydrogens as well", false);
// choice of penalty table
parpars.registerParameter("scr_pen", "penalty table", STRING, false, "Antechamber");
list<String> ini_files;
ini_files.push_back("Antechamber");
ini_files.push_back("BALL");
parpars.setParameterRestrictions("scr_pen", ini_files);
// the manual
String man = "This tool computes optimal and sub-optimal bond order assignments based on an atomic penalty function for a given ligand in mol2 file format.\n\nOptional parameters are the maximal number of solutions to be computed ('-max_sol'), the penalty table specifiying the atomic penalty rules ('-scr_pen'), a flag indicating if sub-optimal solutions should be computed as well ('-non_opt') and a flag indicating if hydrogens should be computed as well ('-add_hyd').\n\nOutput of this tool is a number of mol2 files each containing one bond order assignment.\n\nTo upload an input file please use the upload tool (Get Data -> Upload File).\n\n**Further information and help** can be found in our wiki http://ball-trac.bioinf.uni-sb.de/wiki/ballaxy/BOAConstructor_Help.\n\nPlease cite the following: Dehof, A.K., Rurainski, A., Bui, Q.B.A., Boecker, S., Lenhof, H.-P. & Hildebrandt, A. (2011). Automated Bond Order Assignment as an Optimization Problem. Bioinformatics, 2011";
parpars.setToolManual(man);
// here we set the types of I/O files, for example sdf is also allowed
parpars.setSupportedFormats("i","mol2");
parpars.setSupportedFormats("o","mol2");
parpars.parse(argc, argv);
// read the input
MOL2File f0;
f0.open(parpars.get("i"));
System system;
f0 >> system;
AssignBondOrderProcessor abop;
// the combination of the following two options causes the computation of all optimal solutions
abop.options.setInteger(AssignBondOrderProcessor::Option::MAX_NUMBER_OF_SOLUTIONS, 0);
abop.options.setBool(AssignBondOrderProcessor::Option::COMPUTE_ALSO_NON_OPTIMAL_SOLUTIONS, false);
if (parpars.has("max_sol"))
{
int max_sol = parpars.get("max_sol").toInt();
//cout << " limit number of solutions to " << max_sol << endl;
abop.options.setInteger(AssignBondOrderProcessor::Option::MAX_NUMBER_OF_SOLUTIONS, String(max_sol).toInt());
}
bool non_opt = false;
if (parpars.has("non_opt"))
{
non_opt = parpars.get("non_opt").toBool();
//if (non_opt)
// cout << " Compute also non-optimal solutions." << endl;
abop.options.setBool(AssignBondOrderProcessor::Option::COMPUTE_ALSO_NON_OPTIMAL_SOLUTIONS, non_opt);
}
if (parpars.has("add_hyd"))
{
bool add_hyd = parpars.get("add_hyd").toBool();
//if (add_hyd)
// cout << " Add hydrogens as well." << endl;
abop.options.setBool(AssignBondOrderProcessor::Option::ADD_HYDROGENS, add_hyd);
}
if (parpars.has("scr_pen"))
{
String penalty_table = parpars.get("scr_pen");
//cout << " Use penalty table " << penalty_table << endl;
if (penalty_table == "Antechamber")
abop.options[AssignBondOrderProcessor::Option::INIFile] = "/bond_lengths/BondOrderGAFF.xml";
else
abop.options[AssignBondOrderProcessor::Option::INIFile] = "/bond_lengths/BondOrder.xml";
}
// set the solver
//abop.options.set(AssignBondOrderProcessor::Option::ALGORITHM, AssignBondOrderProcessor::Algorithm::A_STAR);
abop.options.set(AssignBondOrderProcessor::Option::ALGORITHM, AssignBondOrderProcessor::Algorithm::FPT);
abop.options.dump();
system.apply(abop);
Size num_of_sols = abop.getNumberOfComputedSolutions();
if (num_of_sols == 0)
{
Log << "No valid bond order assignment found!" << endl;
return 1;
}
else
{
//Log << "Found " << num_of_sols << " solutions:" << endl;
for (Size i=0; (i<num_of_sols) && (non_opt || (abop.getTotalPenalty(0)==abop.getTotalPenalty(i))); i++)
{
Log << " Solution " << i << " has penalty " << abop.getTotalPenalty(i) << endl;
// apply the solution
if (abop.apply(i))
{
String outfile_name = (i == 0) ? String(parpars.get("o"))
: String(parpars.get("o_dir")) + "/primary_"
+ String(parpars.get("o_id")) + "_solution" + String(i)
+ "_visible_mol2";
//Log << " Writing solution " << String(i) << " as " << outfile_name << endl;
// GenericMolFile* outfile = MolFileFactory::open(outfile_name, ios::out);
MOL2File outfile(outfile_name, ios::out);
if (outfile.bad())
{
Log.error() << endl << "cannot write file " << outfile_name << endl;
return 2;
}
system.beginMolecule()->setProperty("BOA_Constructor_penalty", abop.getTotalPenalty(i));
outfile << system;
outfile.close();
}
}
}
Log << "done." << endl;
return 0;
}
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: molecularControl.C,v 1.8 2002/12/12 10:57:47 oliver Exp $
#include <BALL/MOLVIEW/GUI/WIDGETS/molecularControl.h>
#include <BALL/MOLVIEW/KERNEL/molecularMessage.h>
#include <BALL/MOLVIEW/GUI/DIALOGS/atomProperties.h>
#include <BALL/KERNEL/system.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
using std::endl;
namespace BALL
{
using namespace VIEW;
namespace MOLVIEW
{
MolecularControl::MolecularControl(QWidget* parent, const char* name)
throw()
: Control(parent, name),
molecular_information_(),
molecular_filter_()
{
}
MolecularControl::~MolecularControl()
throw()
{
}
void MolecularControl::checkMenu(MainControl& main_control)
throw()
{
bool copy_list_filled = (getCopyList_().size() > 0);
// check for paste-slot: enable only if copy_list_ not empty
(main_control.menuBar())->setItemEnabled(paste_id_, copy_list_filled);
// check for clearClipboard-slot: enable only if copy_list_ not empty
(main_control.menuBar())->setItemEnabled(clipboard_id_, copy_list_filled);
// check for cut/copy-slot: enable only if one system selected
bool list_filled = (MainControl::getMainControl(this)->getSelectedSystem() != 0);
// cut, copy, and paste are only available for top level selections
(main_control.menuBar())->setItemEnabled(cut_id_, list_filled);
(main_control.menuBar())->setItemEnabled(copy_id_, list_filled);
}
void MolecularControl::sentSelection()
{
// will be inserted later
Control::sentSelection();
// refill and filter selection
filterSelection_(molecular_filter_);
// sent new selection through tree
MolecularSelectionMessage* message = new MolecularSelectionMessage;
message->setSelection(getSelection());
message->setDeletable(true);
notify_(message);
}
Information& MolecularControl::getInformationVisitor_()
throw()
{
return molecular_information_;
}
void MolecularControl::recurseGeneration_(QListViewItem* item, Composite* composite)
throw()
{
// if the composite is anything but an atom,
// we iterate over all children and recurse
// if (!RTTI::isKindOf<Atom>(*composite))
{
Composite::ChildCompositeReverseIterator it = composite->rbeginChildComposite();
for (; it != composite->rendChildComposite(); ++it)
{
generateListViewItem_(item, &*it);
}
}
}
bool MolecularControl::recurseUpdate_(QListViewItem* item, Composite* composite)
throw()
{
bool tree_updated = false;
// if the composite is anything but an atom,
// we iterate over all children and recurse
// if (!RTTI::isKindOf<Atom>(*composite))
{
Composite::ChildCompositeReverseIterator it = composite->rbeginChildComposite();
for (; it != composite->rendChildComposite(); ++it)
{
tree_updated = (tree_updated || updateListViewItem_(item, &*it));
}
}
return tree_updated;
}
bool MolecularControl::reactToMessages_(Message* message)
throw()
{
bool update = false;
if (RTTI::isKindOf<NewMolecularMessage>(*message))
{
NewMolecularMessage *composite_message = RTTI::castTo<NewMolecularMessage>(*message);
update = addComposite((Composite *)composite_message->getComposite());
}
else if (RTTI::isKindOf<RemovedCompositeMessage>(*message))
{
RemovedCompositeMessage *composite_message = RTTI::castTo<RemovedCompositeMessage>(*message);
update = removeComposite((Composite *)composite_message->getComposite());
}
else if (RTTI::isKindOf<ChangedCompositeMessage>(*message))
{
ChangedCompositeMessage *composite_message = RTTI::castTo<ChangedCompositeMessage>(*message);
update = updateComposite(&(composite_message->getComposite()->getRoot()));
}
else if (RTTI::isKindOf<NewSelectionMessage> (*message))
{
setSelection_(true);
}
return update;
}
void MolecularControl::buildContextMenu(Composite* composite, QListViewItem* item)
throw()
{
Control::buildContextMenu(composite, item);
// build the context menu
if (RTTI::isKindOf<AtomContainer>(*composite))
{
insertContextMenuEntry("check Residue", this, SLOT(checkResidue()), RESIDUE__CHECK);
context_menu_.insertSeparator();
insertContextMenuEntry("cut", this, SLOT(cut()), OBJECT__CUT);
insertContextMenuEntry("copy", this, SLOT(copy()), OBJECT__COPY);
insertContextMenuEntry("paste", this, SLOT(paste()), OBJECT__PASTE);
context_menu_.setItemEnabled(OBJECT__PASTE, getCopyList_().size() > 0);
bool system_selected = (MainControl::getMainControl(this)->getSelectedSystem() != 0);
context_menu_.setItemEnabled(OBJECT__CUT, system_selected);
context_menu_.setItemEnabled(OBJECT__COPY, system_selected);
context_menu_.insertSeparator();
insertContextMenuEntry("build Bonds", this, SLOT(buildBonds()), BONDS__BUILD);
insertContextMenuEntry("remove Bonds", this, SLOT(removeBonds()), BONDS__REMOVE);
context_menu_.insertSeparator();
}
if (RTTI::isKindOf<Atom>(*composite) ||
RTTI::isKindOf<AtomContainer>(*composite))
{
insertContextMenuEntry("select", this, SLOT(select()), SELECT);
insertContextMenuEntry("deselect", this, SLOT(deselect()), DESELECT);
context_menu_.setItemEnabled(SELECT, !composite->isSelected());
context_menu_.setItemEnabled(DESELECT, composite->isSelected());
context_menu_.insertSeparator();
insertContextMenuEntry("center Camera", this, SLOT(centerCamera()), CAMERA__CENTER);
}
if (RTTI::isKindOf<Atom>(*composite))
{
insertContextMenuEntry("atom properties", this, SLOT(atomProperties()), ATOM__PROPERTIES);
}
}
void MolecularControl::atomProperties()
{
AtomProperties as((Atom*)context_composite_, this);
as.exec();
ChangedCompositeMessage* message = new ChangedCompositeMessage;
message->setComposite(context_composite_);
notify_(message);
}
} // namespace MOLVIEW
} // namespace BALL
<commit_msg>added slots for contextmenu<commit_after>// $Id: molecularControl.C,v 1.9 2002/12/12 17:19:15 amoll Exp $
#include <BALL/MOLVIEW/GUI/WIDGETS/molecularControl.h>
#include <BALL/MOLVIEW/KERNEL/molecularMessage.h>
#include <BALL/MOLVIEW/GUI/DIALOGS/atomProperties.h>
#include <BALL/KERNEL/system.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
using std::endl;
namespace BALL
{
using namespace VIEW;
namespace MOLVIEW
{
MolecularControl::MolecularControl(QWidget* parent, const char* name)
throw()
: Control(parent, name),
molecular_information_(),
molecular_filter_()
{
}
MolecularControl::~MolecularControl()
throw()
{
}
void MolecularControl::checkMenu(MainControl& main_control)
throw()
{
bool copy_list_filled = (getCopyList_().size() > 0);
// check for paste-slot: enable only if copy_list_ not empty
(main_control.menuBar())->setItemEnabled(paste_id_, copy_list_filled);
// check for clearClipboard-slot: enable only if copy_list_ not empty
(main_control.menuBar())->setItemEnabled(clipboard_id_, copy_list_filled);
// check for cut/copy-slot: enable only if one system selected
bool list_filled = (MainControl::getMainControl(this)->getSelectedSystem() != 0);
// cut, copy, and paste are only available for top level selections
(main_control.menuBar())->setItemEnabled(cut_id_, list_filled);
(main_control.menuBar())->setItemEnabled(copy_id_, list_filled);
}
void MolecularControl::sentSelection()
{
// will be inserted later
Control::sentSelection();
// refill and filter selection
filterSelection_(molecular_filter_);
// sent new selection through tree
MolecularSelectionMessage* message = new MolecularSelectionMessage;
message->setSelection(getSelection());
message->setDeletable(true);
notify_(message);
}
Information& MolecularControl::getInformationVisitor_()
throw()
{
return molecular_information_;
}
void MolecularControl::recurseGeneration_(QListViewItem* item, Composite* composite)
throw()
{
// if the composite is anything but an atom,
// we iterate over all children and recurse
// if (!RTTI::isKindOf<Atom>(*composite))
{
Composite::ChildCompositeReverseIterator it = composite->rbeginChildComposite();
for (; it != composite->rendChildComposite(); ++it)
{
generateListViewItem_(item, &*it);
}
}
}
bool MolecularControl::recurseUpdate_(QListViewItem* item, Composite* composite)
throw()
{
bool tree_updated = false;
// if the composite is anything but an atom,
// we iterate over all children and recurse
// if (!RTTI::isKindOf<Atom>(*composite))
{
Composite::ChildCompositeReverseIterator it = composite->rbeginChildComposite();
for (; it != composite->rendChildComposite(); ++it)
{
tree_updated = (tree_updated || updateListViewItem_(item, &*it));
}
}
return tree_updated;
}
bool MolecularControl::reactToMessages_(Message* message)
throw()
{
bool update = false;
if (RTTI::isKindOf<NewMolecularMessage>(*message))
{
NewMolecularMessage *composite_message = RTTI::castTo<NewMolecularMessage>(*message);
update = addComposite((Composite *)composite_message->getComposite());
}
else if (RTTI::isKindOf<RemovedCompositeMessage>(*message))
{
RemovedCompositeMessage *composite_message = RTTI::castTo<RemovedCompositeMessage>(*message);
update = removeComposite((Composite *)composite_message->getComposite());
}
else if (RTTI::isKindOf<ChangedCompositeMessage>(*message))
{
ChangedCompositeMessage *composite_message = RTTI::castTo<ChangedCompositeMessage>(*message);
update = updateComposite(&(composite_message->getComposite()->getRoot()));
}
else if (RTTI::isKindOf<NewSelectionMessage> (*message))
{
setSelection_(true);
}
return update;
}
void MolecularControl::buildContextMenu(Composite* composite, QListViewItem* item)
throw()
{
Control::buildContextMenu(composite, item);
// build the context menu
if (RTTI::isKindOf<AtomContainer>(*composite))
{
insertContextMenuEntry("check Residue", this, SLOT(checkResidue()), RESIDUE__CHECK);
context_menu_.insertSeparator();
insertContextMenuEntry("cut", this, SLOT(cut()), OBJECT__CUT);
insertContextMenuEntry("copy", this, SLOT(copy()), OBJECT__COPY);
insertContextMenuEntry("paste", this, SLOT(paste()), OBJECT__PASTE);
context_menu_.setItemEnabled(OBJECT__PASTE, getCopyList_().size() > 0);
bool system_selected = (MainControl::getMainControl(this)->getSelectedSystem() != 0);
context_menu_.setItemEnabled(OBJECT__CUT, system_selected);
context_menu_.setItemEnabled(OBJECT__COPY, system_selected);
context_menu_.insertSeparator();
insertContextMenuEntry("build Bonds", this, SLOT(buildBonds()), BONDS__BUILD);
//insertContextMenuEntry("remove Bonds", this, SLOT(removeBonds()), BONDS__REMOVE);
context_menu_.insertSeparator();
}
if (RTTI::isKindOf<Atom>(*composite) ||
RTTI::isKindOf<AtomContainer>(*composite))
{
insertContextMenuEntry("select", this, SLOT(select()), SELECT);
insertContextMenuEntry("deselect", this, SLOT(deselect()), DESELECT);
context_menu_.setItemEnabled(SELECT, !composite->isSelected());
context_menu_.setItemEnabled(DESELECT, composite->isSelected());
context_menu_.insertSeparator();
insertContextMenuEntry("center Camera", this, SLOT(centerCamera()), CAMERA__CENTER);
}
if (RTTI::isKindOf<Atom>(*composite))
{
insertContextMenuEntry("atom properties", this, SLOT(atomProperties()), ATOM__PROPERTIES);
}
}
void MolecularControl::atomProperties()
{
AtomProperties as((Atom*)context_composite_, this);
as.exec();
ChangedCompositeMessage* message = new ChangedCompositeMessage;
message->setComposite(context_composite_);
notify_(message);
DrawMessage* draw_message = new DrawMessage;
draw_message->setDeletable(true);
draw_message->setComposite(context_composite_);
notify_(draw_message);
SceneMessage *scene_message = new SceneMessage;
scene_message->updateOnly();
scene_message->setDeletable(true);
notify_(scene_message);
}
void MolecularControl::buildBonds()
{
BuildBondsMessage* message = new BuildBondsMessage;
notify_(message);
}
void MolecularControl::centerCamera()
{
CenterCameraMessage* message = new CenterCameraMessage;
notify_(message);
}
void MolecularControl::select()
{
SelectMessage* message = new SelectMessage;
message->select_ = true;
notify_(message);
}
void MolecularControl::deselect()
{
SelectMessage* message = new SelectMessage;
message->select_ = false;
notify_(message);
}
void MolecularControl::checkResidue()
{
CheckResidueMessage* message = new CheckResidueMessage;
notify_(message);
}
} // namespace MOLVIEW
} // namespace BALL
<|endoftext|> |
<commit_before>//===-- AdbClient.cpp -------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Other libraries and framework includes
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/STLExtras.h"
// Project includes
#include "AdbClient.h"
#include <algorithm>
#include <sstream>
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::platform_android;
namespace {
const uint32_t kConnTimeout = 10000; // 10 ms
const char * kOKAY = "OKAY";
const char * kFAIL = "FAIL";
} // namespace
Error
AdbClient::CreateByDeviceID (const char* device_id, AdbClient &adb)
{
DeviceIDList connect_devices;
auto error = adb.GetDevices (connect_devices);
if (error.Fail ())
return error;
if (device_id)
{
auto find_it = std::find(connect_devices.begin (), connect_devices.end (), device_id);
if (find_it == connect_devices.end ())
return Error ("Device \"%s\" not found", device_id);
adb.SetDeviceID (*find_it);
}
else
{
if (connect_devices.size () != 1)
return Error ("Expected a single connected device, got instead %zu", connect_devices.size ());
adb.SetDeviceID (connect_devices.front ());
}
return error;
}
AdbClient::AdbClient (const std::string &device_id)
: m_device_id (device_id)
{
}
void
AdbClient::SetDeviceID (const std::string& device_id)
{
m_device_id = device_id;
}
const std::string&
AdbClient::GetDeviceID() const
{
return m_device_id;
}
Error
AdbClient::Connect ()
{
Error error;
m_conn.Connect ("connect://localhost:5037", &error);
return error;
}
Error
AdbClient::GetDevices (DeviceIDList &device_list)
{
device_list.clear ();
auto error = SendMessage ("host:devices");
if (error.Fail ())
return error;
error = ReadResponseStatus ();
if (error.Fail ())
return error;
std::string in_buffer;
error = ReadMessage (in_buffer);
llvm::StringRef response (in_buffer);
llvm::SmallVector<llvm::StringRef, 4> devices;
response.split (devices, "\n", -1, false);
for (const auto device: devices)
device_list.push_back (device.split ('\t').first);
return error;
}
Error
AdbClient::SetPortForwarding (const uint16_t port)
{
char message[48];
snprintf (message, sizeof (message), "forward:tcp:%d;tcp:%d", port, port);
const auto error = SendDeviceMessage (message);
if (error.Fail ())
return error;
return ReadResponseStatus ();
}
Error
AdbClient::DeletePortForwarding (const uint16_t port)
{
char message[32];
snprintf (message, sizeof (message), "killforward:tcp:%d", port);
const auto error = SendDeviceMessage (message);
if (error.Fail ())
return error;
return ReadResponseStatus ();
}
Error
AdbClient::SendMessage (const std::string &packet)
{
auto error = Connect ();
if (error.Fail ())
return error;
char length_buffer[5];
snprintf (length_buffer, sizeof (length_buffer), "%04zx", packet.size ());
ConnectionStatus status;
m_conn.Write (length_buffer, 4, status, &error);
if (error.Fail ())
return error;
m_conn.Write (packet.c_str (), packet.size (), status, &error);
return error;
}
Error
AdbClient::SendDeviceMessage (const std::string &packet)
{
std::ostringstream msg;
msg << "host-serial:" << m_device_id << ":" << packet;
return SendMessage (msg.str ());
}
Error
AdbClient::ReadMessage (std::string &message)
{
message.clear ();
char buffer[5];
buffer[4] = 0;
Error error;
ConnectionStatus status;
m_conn.Read (buffer, 4, kConnTimeout, status, &error);
if (error.Fail ())
return error;
size_t packet_len = 0;
sscanf (buffer, "%zx", &packet_len);
std::string result (packet_len, 0);
m_conn.Read (&result[0], packet_len, kConnTimeout, status, &error);
if (error.Success ())
result.swap (message);
return error;
}
Error
AdbClient::ReadResponseStatus()
{
char buffer[5];
static const size_t packet_len = 4;
buffer[packet_len] = 0;
Error error;
ConnectionStatus status;
m_conn.Read (buffer, packet_len, kConnTimeout, status, &error);
if (error.Fail ())
return error;
if (strncmp (buffer, kOKAY, packet_len) != 0)
{
if (strncmp (buffer, kFAIL, packet_len) == 0)
{
std::string error_message;
error = ReadMessage (error_message);
if (error.Fail ())
return error;
error.SetErrorString (error_message.c_str ());
}
else
error.SetErrorStringWithFormat ("\"%s\" expected from adb, received: \"%s\"", kOKAY, buffer);
}
return error;
}
<commit_msg>Remove 'z' modifier from printf/sscanf operations in AdbClient - the modifier isn't supported by MS C++ compiler.<commit_after>//===-- AdbClient.cpp -------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Other libraries and framework includes
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/STLExtras.h"
// Project includes
#include "AdbClient.h"
#include <algorithm>
#include <sstream>
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::platform_android;
namespace {
const uint32_t kConnTimeout = 10000; // 10 ms
const char * kOKAY = "OKAY";
const char * kFAIL = "FAIL";
} // namespace
Error
AdbClient::CreateByDeviceID (const char* device_id, AdbClient &adb)
{
DeviceIDList connect_devices;
auto error = adb.GetDevices (connect_devices);
if (error.Fail ())
return error;
if (device_id)
{
auto find_it = std::find(connect_devices.begin (), connect_devices.end (), device_id);
if (find_it == connect_devices.end ())
return Error ("Device \"%s\" not found", device_id);
adb.SetDeviceID (*find_it);
}
else
{
if (connect_devices.size () != 1)
return Error ("Expected a single connected device, got instead %" PRIu64, static_cast<uint64_t>(connect_devices.size ()));
adb.SetDeviceID (connect_devices.front ());
}
return error;
}
AdbClient::AdbClient (const std::string &device_id)
: m_device_id (device_id)
{
}
void
AdbClient::SetDeviceID (const std::string& device_id)
{
m_device_id = device_id;
}
const std::string&
AdbClient::GetDeviceID() const
{
return m_device_id;
}
Error
AdbClient::Connect ()
{
Error error;
m_conn.Connect ("connect://localhost:5037", &error);
return error;
}
Error
AdbClient::GetDevices (DeviceIDList &device_list)
{
device_list.clear ();
auto error = SendMessage ("host:devices");
if (error.Fail ())
return error;
error = ReadResponseStatus ();
if (error.Fail ())
return error;
std::string in_buffer;
error = ReadMessage (in_buffer);
llvm::StringRef response (in_buffer);
llvm::SmallVector<llvm::StringRef, 4> devices;
response.split (devices, "\n", -1, false);
for (const auto device: devices)
device_list.push_back (device.split ('\t').first);
return error;
}
Error
AdbClient::SetPortForwarding (const uint16_t port)
{
char message[48];
snprintf (message, sizeof (message), "forward:tcp:%d;tcp:%d", port, port);
const auto error = SendDeviceMessage (message);
if (error.Fail ())
return error;
return ReadResponseStatus ();
}
Error
AdbClient::DeletePortForwarding (const uint16_t port)
{
char message[32];
snprintf (message, sizeof (message), "killforward:tcp:%d", port);
const auto error = SendDeviceMessage (message);
if (error.Fail ())
return error;
return ReadResponseStatus ();
}
Error
AdbClient::SendMessage (const std::string &packet)
{
auto error = Connect ();
if (error.Fail ())
return error;
char length_buffer[5];
snprintf (length_buffer, sizeof (length_buffer), "%04x", static_cast<int>(packet.size ()));
ConnectionStatus status;
m_conn.Write (length_buffer, 4, status, &error);
if (error.Fail ())
return error;
m_conn.Write (packet.c_str (), packet.size (), status, &error);
return error;
}
Error
AdbClient::SendDeviceMessage (const std::string &packet)
{
std::ostringstream msg;
msg << "host-serial:" << m_device_id << ":" << packet;
return SendMessage (msg.str ());
}
Error
AdbClient::ReadMessage (std::string &message)
{
message.clear ();
char buffer[5];
buffer[4] = 0;
Error error;
ConnectionStatus status;
m_conn.Read (buffer, 4, kConnTimeout, status, &error);
if (error.Fail ())
return error;
int packet_len = 0;
sscanf (buffer, "%x", &packet_len);
std::string result (packet_len, 0);
m_conn.Read (&result[0], packet_len, kConnTimeout, status, &error);
if (error.Success ())
result.swap (message);
return error;
}
Error
AdbClient::ReadResponseStatus()
{
char buffer[5];
static const size_t packet_len = 4;
buffer[packet_len] = 0;
Error error;
ConnectionStatus status;
m_conn.Read (buffer, packet_len, kConnTimeout, status, &error);
if (error.Fail ())
return error;
if (strncmp (buffer, kOKAY, packet_len) != 0)
{
if (strncmp (buffer, kFAIL, packet_len) == 0)
{
std::string error_message;
error = ReadMessage (error_message);
if (error.Fail ())
return error;
error.SetErrorString (error_message.c_str ());
}
else
error.SetErrorStringWithFormat ("\"%s\" expected from adb, received: \"%s\"", kOKAY, buffer);
}
return error;
}
<|endoftext|> |
<commit_before>#include <pcl/filters/voxel_grid.h>
#include <pcl/io/pcd_io.h>
#include <pcl/octree/octree_search.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/registration/icp.h>
#include <pcl_ros/point_cloud.h>
#include <pcl_ros/transforms.h>
#include <ros/publisher.h>
#include <ros/ros.h>
#include <stdlib.h>
#include <string>
pcl::PointCloud<pcl::PointXYZRGB>::Ptr global_map;
ros::Publisher _pointcloud_pub;
ros::Publisher _pointcloud_prob_pub;
tf::TransformListener *tf_listener;
bool firstFrame;
double maxCorrDist;
int maxIter;
pcl::octree::OctreePointCloudSearch<pcl::PointXYZRGB>::Ptr octree;
double searchRadius;
double octree_resolution;
double probability_thresh;
std::list<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> pointcloud_list;
int queue_window_size;
void icp_transform(pcl::PointCloud<pcl::PointXYZRGB>::Ptr input)
{
if (pointcloud_list.size() < queue_window_size)
{
pointcloud_list.push_back(input);
}
if (pointcloud_list.size() == queue_window_size)
{
//Probabilistic calculations here
pcl::PointCloud<pcl::PointXYZRGB>::Ptr local_pc = pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>());
pcl::octree::OctreePointCloudSearch<pcl::PointXYZRGB> local_octree(octree_resolution);
local_octree.setInputCloud(local_pc);
for (auto it = pointcloud_list.begin(); it != pointcloud_list.end(); it++)
{
for (auto point : (**it))
{
//G and B represent the probability, they are the same value
//Add a point to the local octree if we haven't seen it before
if (!local_octree.isVoxelOccupiedAtPoint(point))
{
point.r = 255;
point.g = 0;
point.b = 0;
local_octree.addPointToCloud(point, local_pc);
} else
{
//Increase probability of the point in the voxel if we see it again
int point_idx;
float dist;
local_octree.approxNearestSearch(point, point_idx, dist);
//If the probability is less than the threshold, increase the probability
local_pc->points[point_idx].g = local_pc->points[point_idx].g + (int)(255.0 / queue_window_size);
local_pc->points[point_idx].b = local_pc->points[point_idx].b + (int)(255.0 / queue_window_size);
if (local_pc->points[point_idx].g >= probability_thresh * 255.0
&& !octree->isVoxelOccupiedAtPoint(local_pc->points[point_idx]))
{
//Add the point to the global map if its probability is greater than or equal to the threshold
octree->addPointToCloud(local_pc->points[point_idx], global_map);
}
}
}
}
(*local_pc).header.frame_id = "/odom";
_pointcloud_prob_pub.publish(*local_pc);
//Remove first pointcloud
pointcloud_list.pop_front();
std::cout << "Map size: " << global_map->size() << std::endl;
}
if (firstFrame && !input->points.empty())
{
octree->setInputCloud(global_map);
for (unsigned int i = 0; i < input->size(); ++i)
{
pcl::PointXYZRGB searchPoint(255, 0, 0);
searchPoint.x = input->points[i].x;
searchPoint.y = input->points[i].y;
searchPoint.z = input->points[i].z;
if (!octree->isVoxelOccupiedAtPoint(searchPoint)) {
octree->addPointToCloud(searchPoint, global_map);
}
}
firstFrame = false;
}
}
void frame_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr transformed =
pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>());
tf::StampedTransform transform;
if (tf_listener->waitForTransform("/odom", msg->header.frame_id, ros::Time(0), ros::Duration(5)))
{
tf_listener->lookupTransform("/odom", msg->header.frame_id, ros::Time(0), transform);
pcl_ros::transformPointCloud(*msg, *transformed, transform);
for (auto point : *transformed)
{
point.z = 0;
}
//Convert PointXYZ to PointXYZRGB
pcl::PointCloud<pcl::PointXYZRGB>::Ptr transformed_rgb =
pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>());
pcl::copyPointCloud(*transformed, *transformed_rgb);
icp_transform(transformed_rgb );
_pointcloud_pub.publish(global_map);
} else {
ROS_WARN_STREAM("Could not find transform to odom");
}
}
int main(int argc, char **argv)
{
global_map = pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>());
ros::init(argc, argv, "global_mapper");
ros::NodeHandle nh;
tf_listener = new tf::TransformListener();
std::string topics;
std::list<ros::Subscriber> subs;
ros::NodeHandle pNh("~");
if (!pNh.hasParam("topics"))
ROS_WARN_STREAM("No topics specified for mapper. No map will be generated.");
pNh.getParam("topics", topics);
pNh.getParam("max_correspondence_distance", maxCorrDist);
pNh.getParam("max_iterations", maxIter);
pNh.getParam("search_radius", searchRadius);
pNh.getParam("octree_resolution", octree_resolution);
pNh.getParam("queue_window_size", queue_window_size);
pNh.getParam("probability_thresh", probability_thresh);
if (topics.empty())
ROS_WARN_STREAM("No topics specified for mapper. No map will be generated.");
octree = pcl::octree::OctreePointCloudSearch<pcl::PointXYZRGB>::Ptr(new pcl::octree::OctreePointCloudSearch<pcl::PointXYZRGB>(octree_resolution));
std::istringstream iss(topics);
std::vector<std::string> tokens{ std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>() };
for (auto topic : tokens)
{
ROS_INFO_STREAM("Mapper subscribing to " << topic);
subs.push_back(nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>(topic, 1, boost::bind(frame_callback, _1, topic)));
}
global_map->header.frame_id = "/odom";
_pointcloud_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("/map", 1);
_pointcloud_prob_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("/prob", 1);
firstFrame = true;
ros::spin();
}<commit_msg>Clanged<commit_after>#include <pcl/filters/voxel_grid.h>
#include <pcl/io/pcd_io.h>
#include <pcl/octree/octree_search.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/registration/icp.h>
#include <pcl_ros/point_cloud.h>
#include <pcl_ros/transforms.h>
#include <ros/publisher.h>
#include <ros/ros.h>
#include <stdlib.h>
#include <string>
pcl::PointCloud<pcl::PointXYZRGB>::Ptr global_map;
ros::Publisher _pointcloud_pub;
ros::Publisher _pointcloud_prob_pub;
tf::TransformListener *tf_listener;
bool firstFrame;
double maxCorrDist;
int maxIter;
pcl::octree::OctreePointCloudSearch<pcl::PointXYZRGB>::Ptr octree;
double searchRadius;
double octree_resolution;
double probability_thresh;
std::list<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> pointcloud_list;
int queue_window_size;
void icp_transform(pcl::PointCloud<pcl::PointXYZRGB>::Ptr input)
{
if (pointcloud_list.size() < queue_window_size)
{
pointcloud_list.push_back(input);
}
if (pointcloud_list.size() == queue_window_size)
{
// Probabilistic calculations here
pcl::PointCloud<pcl::PointXYZRGB>::Ptr local_pc =
pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>());
pcl::octree::OctreePointCloudSearch<pcl::PointXYZRGB> local_octree(octree_resolution);
local_octree.setInputCloud(local_pc);
for (auto it = pointcloud_list.begin(); it != pointcloud_list.end(); it++)
{
for (auto point : (**it))
{
// G and B represent the probability, they are the same value
// Add a point to the local octree if we haven't seen it before
if (!local_octree.isVoxelOccupiedAtPoint(point))
{
point.r = 255;
point.g = 0;
point.b = 0;
local_octree.addPointToCloud(point, local_pc);
}
else
{
// Increase probability of the point in the voxel if we see it again
int point_idx;
float dist;
local_octree.approxNearestSearch(point, point_idx, dist);
// If the probability is less than the threshold, increase the probability
local_pc->points[point_idx].g = local_pc->points[point_idx].g + (int)(255.0 / queue_window_size);
local_pc->points[point_idx].b = local_pc->points[point_idx].b + (int)(255.0 / queue_window_size);
if (local_pc->points[point_idx].g >= probability_thresh * 255.0 &&
!octree->isVoxelOccupiedAtPoint(local_pc->points[point_idx]))
{
// Add the point to the global map if its probability is greater than or equal to the threshold
octree->addPointToCloud(local_pc->points[point_idx], global_map);
}
}
}
}
(*local_pc).header.frame_id = "/odom";
_pointcloud_prob_pub.publish(*local_pc);
// Remove first pointcloud
pointcloud_list.pop_front();
std::cout << "Map size: " << global_map->size() << std::endl;
}
if (firstFrame && !input->points.empty())
{
octree->setInputCloud(global_map);
for (unsigned int i = 0; i < input->size(); ++i)
{
pcl::PointXYZRGB searchPoint(255, 0, 0);
searchPoint.x = input->points[i].x;
searchPoint.y = input->points[i].y;
searchPoint.z = input->points[i].z;
if (!octree->isVoxelOccupiedAtPoint(searchPoint))
{
octree->addPointToCloud(searchPoint, global_map);
}
}
firstFrame = false;
}
}
void frame_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr transformed =
pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>());
tf::StampedTransform transform;
if (tf_listener->waitForTransform("/odom", msg->header.frame_id, ros::Time(0), ros::Duration(5)))
{
tf_listener->lookupTransform("/odom", msg->header.frame_id, ros::Time(0), transform);
pcl_ros::transformPointCloud(*msg, *transformed, transform);
for (auto point : *transformed)
{
point.z = 0;
}
// Convert PointXYZ to PointXYZRGB
pcl::PointCloud<pcl::PointXYZRGB>::Ptr transformed_rgb =
pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>());
pcl::copyPointCloud(*transformed, *transformed_rgb);
icp_transform(transformed_rgb);
_pointcloud_pub.publish(global_map);
}
else
{
ROS_WARN_STREAM("Could not find transform to odom");
}
}
int main(int argc, char **argv)
{
global_map = pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>());
ros::init(argc, argv, "global_mapper");
ros::NodeHandle nh;
tf_listener = new tf::TransformListener();
std::string topics;
std::list<ros::Subscriber> subs;
ros::NodeHandle pNh("~");
if (!pNh.hasParam("topics"))
ROS_WARN_STREAM("No topics specified for mapper. No map will be generated.");
pNh.getParam("topics", topics);
pNh.getParam("max_correspondence_distance", maxCorrDist);
pNh.getParam("max_iterations", maxIter);
pNh.getParam("search_radius", searchRadius);
pNh.getParam("octree_resolution", octree_resolution);
pNh.getParam("queue_window_size", queue_window_size);
pNh.getParam("probability_thresh", probability_thresh);
if (topics.empty())
ROS_WARN_STREAM("No topics specified for mapper. No map will be generated.");
octree = pcl::octree::OctreePointCloudSearch<pcl::PointXYZRGB>::Ptr(
new pcl::octree::OctreePointCloudSearch<pcl::PointXYZRGB>(octree_resolution));
std::istringstream iss(topics);
std::vector<std::string> tokens{ std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>() };
for (auto topic : tokens)
{
ROS_INFO_STREAM("Mapper subscribing to " << topic);
subs.push_back(nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>(topic, 1, boost::bind(frame_callback, _1, topic)));
}
global_map->header.frame_id = "/odom";
_pointcloud_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("/map", 1);
_pointcloud_prob_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("/prob", 1);
firstFrame = true;
ros::spin();
}<|endoftext|> |
<commit_before>#include "state.h"
#include <stdlib.h>
using namespace std;
State::State(){
}
/* For instantiation based on a parent search node */
// TODO: Don't think this is needed
State::State(State &parent, Direction dir) {
parent_ = &parent;
world_ = parent.getWorld();
curRobot_ = parent.getRobot();
curBoxes_ = parent.getCurBoxes();
g_ = computeGCost();
h_ = computeHCost();
f_ = g_ + h_;
}
// Initialize a state based upon the individual components
State::State(World &world, int x, int y, vector<Location> &curBoxes, State &parent){
world_ = &world;
parent_ = &parent;
curBoxes_ = curBoxes;
curRobot_ = new Location(x,y);
g_ = computeGCost();
h_ = computeHCost();
f_ = g_ + h_;
}
// Initialize the first state based upon the world configuration
State::State(World &world) {
world_ = new World(world.getMap(), world.getInitRobotLocation(), world.getInitBoxes(), world.getTargetBoxes());
curBoxes_ = *world_->getInitBoxes();
curRobot_ = world_->getInitRobotLocation();
g_ = computeGCost();
h_ = computeHCost();
f_ = g_ + h_;
}
bool State::isGoal(){
return false;
}
bool State::boxLogic(const int i, const Direction dir){
if(curBoxes_[i].adjacent(*curRobot_, dir)){
// Check to make sure you aren't going to push a box into another
if(!freeToMove(curBoxes_[i], dir, i))
return false;
Location test = curBoxes_[i].push(dir);
// Make sure you aren't pushing a box out of bounds
if(test.getX() < 0 || test.getY() < 0
|| test.getX() >= world_->getSizeX() || test.getY() >= world_->getSizeY())
return false;
return true;
} // Robot is adjacent to box i and box i is not adjacent to any other of the boxes
else
return false;
}
// If you wish to ignore a box, sent the vector index as ignore, defaults to -1
bool State::freeToMove(Location &loc, const Direction dir, int ignore){
for(unsigned int j = 0; j < curBoxes_.size(); j++){
// If any other box is adjacent to the pushed box inthe direction, it's not free!
if(j != ignore && loc.adjacent(curBoxes_[j], dir))
return false;
}
return true;
}
/*
* This function returns the possible states from the four different actions (robot up left right down)
*/
vector<State> State::expandState(){
vector<State> expands;
Matrix map = *world_->getMap();
// Flags to ensure we only add one state for each possible action
bool left = false;
bool right = false;
bool up = false;
bool down = false;
// -- Edge Conditions -- //
// Make sure we cannot go off the map
if(curRobot_->getX() == 0){
cout << "Left edge condition trigger!" << endl;
expands.push_back(State(*this, LEFT));
left = true;
}
if(curRobot_->getX() == world_->getSizeX()-1){
cout << "Right edge condition trigger!" << endl;
expands.push_back(State(*this, RIGHT));
right = true;
}
if(curRobot_->getY() == 0){
cout << "Up edge condition trigger!" << endl;
expands.push_back(State(*this, UP));
up = true;
}
if(curRobot_->getY() == world_->getSizeY()-1){
cout << "Down edge condition trigger!" << endl;
expands.push_back(State(*this, DOWN));
down = true;
}
// -- Push Box-- //
vector<Location> newBoxes = curBoxes_;
for(unsigned int i = 0; i < curBoxes_.size(); i++){
// Check to see if we will push any boxes (i.e. we are adjacent)
if(!left && boxLogic(i, LEFT)){
cout << "Pushing left " << i << endl;
newBoxes[i] = curBoxes_[i].push(LEFT);
Location newRob = curRobot_->push(LEFT);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
left = true;
}
if(!right && boxLogic(i, RIGHT)){
cout << "Pushing right " << i << endl;
newBoxes[i] = curBoxes_[i].push(RIGHT);
Location newRob = curRobot_->push(RIGHT);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
right = true;
}
if(!up && boxLogic(i, UP)){
cout << "Pushing up " << i << endl;
newBoxes[i] = curBoxes_[i].push(UP);
Location newRob = curRobot_->push(UP);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
up = true;
}
if(!down && boxLogic(i, DOWN)){
cout << "Pushing down "<< i << endl;
newBoxes[i] = curBoxes_[i].push(DOWN);
Location newRob = curRobot_->push(DOWN);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
down = true;
}
}
// -- Free movement logic -- //
if(!left && freeToMove(*curRobot_, LEFT)){
Location newRob = curRobot_->push(LEFT);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
}
else
cout << "Cannot move left!" << left << endl;
if(!right && freeToMove(*curRobot_, RIGHT)){
Location newRob = curRobot_->push(RIGHT);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
}
else
cout << "Cannot move right!" << right << endl;
if(!up && freeToMove(*curRobot_, UP)){
Location newRob = curRobot_->push(UP);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
}
else
cout << "Cannot move up!" << up << endl;
if(!down && freeToMove(*curRobot_, DOWN)){
Location newRob = curRobot_->push(DOWN);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
}
else
cout << "Cannot move down!"<< down << endl;
return expands;
}
/* Display functions */
void State::printState(const string& name){
cout << "State: " << name << endl;
cout << "G Cost: " << g_ << endl;
cout << "H Cost: " << h_ << endl;
cout << "F Cost: " << f_ << endl;
int mapSizeX = world_->getSizeX();
int mapSizeY = world_->getSizeY();
/* Create temporary map for display purposes only */
Matrix mapTmp;
vector<int> tmp;
for (int x = 0; x < mapSizeX; x++) {
tmp.clear();
for (int y = 0; y < mapSizeY; y++) {
tmp.push_back(EMPTY);
}
mapTmp.push_back(tmp);
}
int robotX = curRobot_->getX();
int robotY = curRobot_->getY();
cout << "Robot position: " << robotX << " " << robotY << endl;
/* Add robot location */
mapTmp.at(robotY).at(robotX) = ROBOT;
/* Add boxes */
int i;
for (i = 0; i < curBoxes_.size(); i++) {
int boxX = curBoxes_.at(i).getX();
int boxY = curBoxes_.at(i).getY();
if(mapTmp.at(boxY).at(boxX) == EMPTY) {
mapTmp.at(boxY).at(boxX) = BOX;
} else {
mapTmp.at(boxY).at(boxX) += BOX;
}
}
for (int x = 0; x < mapSizeX; x++) {
for (int y = 0; y < mapSizeY; y++) {
switch(mapTmp.at(y).at(x)) {
case EMPTY: cout << setw(2) << "-"; break;
case BOX: cout << setw(2) <<"B"; break;
case TARGET: cout << setw(2) <<"T"; break;
case ROBOT: cout << setw(2) <<"S"; break;
case OCCUPIED: cout << setw(2) <<"1"; break;
case BOX+TARGET: cout << setw(2) <<"R"; break;
default: cout << setw(2) <<"U"; break;
}
}
cout << endl;
}
}
/* ---------------------- */
/* Cost functions */
/* ---------------------- */
// Returns the Manhattan Distance between robot and loc
int State::distanceBetween(const Location& loc1, const Location &loc2) const{
//loc1.print();
//loc2.print();
int dX = abs(loc1.getX() - loc2.getX());
int dY = abs(loc1.getY() - loc2.getY());
/*cout << "Cost between: " << endl;
loc1.print("target");
loc2.print("current");
cout << " is " << dX + dY << endl;*/
return dX + dY;
}
// Cost from start to current pos
int State::computeGCost() {
int cost = 0;
// Get the starting spots
vector<Location> inits = *world_->getInitBoxes();
// For each box, compute the distance from the boxes current location and it's starting point
for(unsigned int i = 0; i < world_->getNumberOfBoxes(); i++){
cost += distanceBetween(inits[i], curBoxes_[i]);
}
return cost;
}
// Heuristic Cost
int State::computeHCost() {
int cost = 0;
// Get the starting spots
vector<Location> targets = *world_->getTargetBoxes();
// For each box, compute the distance from the boxes current location and it's target
for(unsigned int i = 0; i < world_->getNumberOfBoxes(); i++){
cost += distanceBetween(targets[i], curBoxes_[i]);
}
return cost;
}
// NOT NEEDED
int State::computeFCost() {}; //TODO: implement this function
void State::setGCost(int g) { g_ = g; };
void State::setHCost(int h) { h_ = h; };
void State::setFCost(int f) { f_ = f; };
/* ---------------------- */
/* Overloaded << operator */
/* ---------------------- */
std::ostream& operator<<(std::ostream& os, const State& state) {
state.getWorld()->printWorld();
//state.getWorld()->printConfig();
return os;
}
/* Overload comparison operator */
bool operator== (State &s1, State &s2) {
/* Compare robot loation */
if (s1.getRobot() != s2.getRobot())
return false;
/* Compare box locations */
std::vector<Location> s1Boxes = s1.getCurBoxes();
std::vector<Location> s2Boxes = s2.getCurBoxes();
for(int i = 0; i < s1Boxes.size(); i++) {
if(s1Boxes.at(i) != s2Boxes.at(i))
return false;
}
/* Compare f, g, and h costs */
if(s1.getFCost() != s2.getFCost())
return false;
if(s1.getGCost() != s2.getGCost())
return false;
if(s1.getHCost() != s2.getHCost())
return false;
/*Compare parent */
if(s1.getParent() != s2.getParent())
return false;
return true;
}
bool operator!= (State &s1, State &s2) {
return !(s1 == s2);
}
<commit_msg>Fixed box push bug<commit_after>#include "state.h"
#include <stdlib.h>
using namespace std;
State::State(){
}
/* For instantiation based on a parent search node */
// TODO: Don't think this is needed
State::State(State &parent, Direction dir) {
parent_ = &parent;
world_ = parent.getWorld();
curRobot_ = parent.getRobot();
curBoxes_ = parent.getCurBoxes();
g_ = computeGCost();
h_ = computeHCost();
f_ = g_ + h_;
}
// Initialize a state based upon the individual components
State::State(World &world, int x, int y, vector<Location> &curBoxes, State &parent){
world_ = &world;
parent_ = &parent;
curBoxes_ = curBoxes;
curRobot_ = new Location(x,y);
g_ = computeGCost();
h_ = computeHCost();
f_ = g_ + h_;
}
// Initialize the first state based upon the world configuration
State::State(World &world) {
world_ = new World(world.getMap(), world.getInitRobotLocation(), world.getInitBoxes(), world.getTargetBoxes());
curBoxes_ = *world_->getInitBoxes();
curRobot_ = world_->getInitRobotLocation();
g_ = computeGCost();
h_ = computeHCost();
f_ = g_ + h_;
}
bool State::isGoal(){
return false;
}
bool State::boxLogic(const int i, const Direction dir){
if(curBoxes_[i].adjacent(*curRobot_, dir)){
// Check to make sure you aren't going to push a box into another
if(!freeToMove(curBoxes_[i], dir, i))
return false;
Location test = curBoxes_[i].push(dir);
// Make sure you aren't pushing a box out of bounds
if(test.getX() < 0 || test.getY() < 0
|| test.getX() >= world_->getSizeX() || test.getY() >= world_->getSizeY())
return false;
return true;
} // Robot is adjacent to box i and box i is not adjacent to any other of the boxes
else
return false;
}
// If you wish to ignore a box, sent the vector index as ignore, defaults to -1
bool State::freeToMove(Location &loc, const Direction dir, int ignore){
for(unsigned int j = 0; j < curBoxes_.size(); j++){
// If any other box is adjacent to the pushed box inthe direction, it's not free!
if(j != ignore && loc.adjacent(curBoxes_[j], dir))
return false;
}
return true;
}
/*
* This function returns the possible states from the four different actions (robot up left right down)
*/
vector<State> State::expandState(){
vector<State> expands;
Matrix map = *world_->getMap();
// Flags to ensure we only add one state for each possible action
bool left = false;
bool right = false;
bool up = false;
bool down = false;
// -- Edge Conditions -- //
// Make sure we cannot go off the map
if(curRobot_->getX() == 0){
cout << "Left edge condition trigger!" << endl;
expands.push_back(State(*this, LEFT));
left = true;
}
if(curRobot_->getX() == world_->getSizeX()-1){
cout << "Right edge condition trigger!" << endl;
expands.push_back(State(*this, RIGHT));
right = true;
}
if(curRobot_->getY() == 0){
cout << "Up edge condition trigger!" << endl;
expands.push_back(State(*this, UP));
up = true;
}
if(curRobot_->getY() == world_->getSizeY()-1){
cout << "Down edge condition trigger!" << endl;
expands.push_back(State(*this, DOWN));
down = true;
}
// -- Push Box-- //
for(unsigned int i = 0; i < curBoxes_.size(); i++){
vector<Location> newBoxes = curBoxes_;
// Check to see if we will push any boxes (i.e. we are adjacent)
if(!left && boxLogic(i, LEFT)){
cout << "Pushing left " << i << endl;
newBoxes[i] = curBoxes_[i].push(LEFT);
Location newRob = curRobot_->push(LEFT);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
left = true;
}
if(!right && boxLogic(i, RIGHT)){
cout << "Pushing right " << i << endl;
newBoxes[i] = curBoxes_[i].push(RIGHT);
Location newRob = curRobot_->push(RIGHT);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
right = true;
}
if(!up && boxLogic(i, UP)){
cout << "Pushing up " << i << endl;
newBoxes[i] = curBoxes_[i].push(UP);
Location newRob = curRobot_->push(UP);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
up = true;
}
if(!down && boxLogic(i, DOWN)){
cout << "Pushing down "<< i << endl;
newBoxes[i] = curBoxes_[i].push(DOWN);
Location newRob = curRobot_->push(DOWN);
State child(*world_, newRob.getX(), newRob.getY(), newBoxes, *this);
expands.push_back(child);
down = true;
}
}
// -- Free movement logic -- //
if(!left && freeToMove(*curRobot_, LEFT)){
Location newRob = curRobot_->push(LEFT);
State child(*world_, newRob.getX(), newRob.getY(), curBoxes_, *this);
expands.push_back(child);
}
else
cout << "Cannot move left!" << left << endl;
if(!right && freeToMove(*curRobot_, RIGHT)){
Location newRob = curRobot_->push(RIGHT);
State child(*world_, newRob.getX(), newRob.getY(), curBoxes_, *this);
expands.push_back(child);
}
else
cout << "Cannot move right!" << right << endl;
if(!up && freeToMove(*curRobot_, UP)){
Location newRob = curRobot_->push(UP);
State child(*world_, newRob.getX(), newRob.getY(), curBoxes_, *this);
expands.push_back(child);
}
else
cout << "Cannot move up!" << up << endl;
if(!down && freeToMove(*curRobot_, DOWN)){
Location newRob = curRobot_->push(DOWN);
State child(*world_, newRob.getX(), newRob.getY(), curBoxes_, *this);
expands.push_back(child);
}
else
cout << "Cannot move down!"<< down << endl;
return expands;
}
/* Display functions */
void State::printState(const string& name){
cout << "State: " << name << endl;
cout << "G Cost: " << g_ << endl;
cout << "H Cost: " << h_ << endl;
cout << "F Cost: " << f_ << endl;
int mapSizeX = world_->getSizeX();
int mapSizeY = world_->getSizeY();
/* Create temporary map for display purposes only */
Matrix mapTmp;
vector<int> tmp;
for (int x = 0; x < mapSizeX; x++) {
tmp.clear();
for (int y = 0; y < mapSizeY; y++) {
tmp.push_back(EMPTY);
}
mapTmp.push_back(tmp);
}
int robotX = curRobot_->getX();
int robotY = curRobot_->getY();
cout << "Robot position: " << robotX << " " << robotY << endl;
/* Add robot location */
mapTmp.at(robotY).at(robotX) = ROBOT;
/* Add boxes */
int i;
for (i = 0; i < curBoxes_.size(); i++) {
int boxX = curBoxes_.at(i).getX();
int boxY = curBoxes_.at(i).getY();
if(mapTmp.at(boxY).at(boxX) == EMPTY) {
mapTmp.at(boxY).at(boxX) = BOX;
} else {
mapTmp.at(boxY).at(boxX) += BOX;
}
}
for (int x = 0; x < mapSizeX; x++) {
for (int y = 0; y < mapSizeY; y++) {
switch(mapTmp.at(y).at(x)) {
case EMPTY: cout << setw(2) << "-"; break;
case BOX: cout << setw(2) <<"B"; break;
case TARGET: cout << setw(2) <<"T"; break;
case ROBOT: cout << setw(2) <<"S"; break;
case OCCUPIED: cout << setw(2) <<"1"; break;
case BOX+TARGET: cout << setw(2) <<"R"; break;
default: cout << setw(2) <<"U"; break;
}
}
cout << endl;
}
}
/* ---------------------- */
/* Cost functions */
/* ---------------------- */
// Returns the Manhattan Distance between robot and loc
int State::distanceBetween(const Location& loc1, const Location &loc2) const{
//loc1.print();
//loc2.print();
int dX = abs(loc1.getX() - loc2.getX());
int dY = abs(loc1.getY() - loc2.getY());
/*cout << "Cost between: " << endl;
loc1.print("target");
loc2.print("current");
cout << " is " << dX + dY << endl;*/
return dX + dY;
}
// Cost from start to current pos
int State::computeGCost() {
int cost = 0;
// Get the starting spots
vector<Location> inits = *world_->getInitBoxes();
// For each box, compute the distance from the boxes current location and it's starting point
for(unsigned int i = 0; i < world_->getNumberOfBoxes(); i++){
cost += distanceBetween(inits[i], curBoxes_[i]);
}
return cost;
}
// Heuristic Cost
int State::computeHCost() {
int cost = 0;
// Get the starting spots
vector<Location> targets = *world_->getTargetBoxes();
// For each box, compute the distance from the boxes current location and it's target
for(unsigned int i = 0; i < world_->getNumberOfBoxes(); i++){
cost += distanceBetween(targets[i], curBoxes_[i]);
}
return cost;
}
// NOT NEEDED
int State::computeFCost() {}; //TODO: implement this function
void State::setGCost(int g) { g_ = g; };
void State::setHCost(int h) { h_ = h; };
void State::setFCost(int f) { f_ = f; };
/* ---------------------- */
/* Overloaded << operator */
/* ---------------------- */
std::ostream& operator<<(std::ostream& os, const State& state) {
state.getWorld()->printWorld();
//state.getWorld()->printConfig();
return os;
}
/* Overload comparison operator */
bool operator== (State &s1, State &s2) {
/* Compare robot loation */
if (s1.getRobot() != s2.getRobot())
return false;
/* Compare box locations */
std::vector<Location> s1Boxes = s1.getCurBoxes();
std::vector<Location> s2Boxes = s2.getCurBoxes();
for(int i = 0; i < s1Boxes.size(); i++) {
if(s1Boxes.at(i) != s2Boxes.at(i))
return false;
}
/* Compare f, g, and h costs */
if(s1.getFCost() != s2.getFCost())
return false;
if(s1.getGCost() != s2.getGCost())
return false;
if(s1.getHCost() != s2.getHCost())
return false;
/*Compare parent */
if(s1.getParent() != s2.getParent())
return false;
return true;
}
bool operator!= (State &s1, State &s2) {
return !(s1 == s2);
}
<|endoftext|> |
<commit_before>#ifndef GENERICPARALLELWORLD_HH
#define GENERICPARALLELWORLD_HH
namespace g4
{
/**
* @brief Generic parallel world that can be built from function objects / lambdas.
*/
class GenericParallelWorld : public G4VUserParallelWorld
{
public:
using handler_type = std::function<void(G4LogicalVolume*)>;
using sd_handler_type = std::function<void()>;
GenericParallelWorld(const G4String& name,
handler_type constructHandler = [](G4LogicalVolume*) {},
sd_handler_type constructSDHandler = []() {}
) :
G4VUserParallelWorld(name),
_constructHandler(constructHandler),
_constructSDHandler(constructSDHandler)
{
}
void Construct() override
{
auto world = GetWorld()->GetLogicalVolume();
_constructHandler(world);
}
void ConstructSD() override
{
_constructSDHandler();
}
private:
handler_type _constructHandler;
sd_handler_type _constructSDHandler;
};
}
#endif // GENERICPARALLELWORLD_HH
<commit_msg>Parallel world headers (??)<commit_after>#ifndef GENERICPARALLELWORLD_HH
#define GENERICPARALLELWORLD_HH
#include <functional>
#include <G4String.hh>
#include <G4VUserParallelWorld.hh>
namespace g4
{
/**
* @brief Generic parallel world that can be built from function objects / lambdas.
*/
class GenericParallelWorld : public G4VUserParallelWorld
{
public:
using handler_type = std::function<void(G4LogicalVolume*)>;
using sd_handler_type = std::function<void()>;
GenericParallelWorld(const G4String& name,
handler_type constructHandler = [](G4LogicalVolume*) {},
sd_handler_type constructSDHandler = []() {}
) :
G4VUserParallelWorld(name),
_constructHandler(constructHandler),
_constructSDHandler(constructSDHandler)
{
}
void Construct() override
{
auto world = GetWorld()->GetLogicalVolume();
_constructHandler(world);
}
void ConstructSD() override
{
_constructSDHandler();
}
private:
handler_type _constructHandler;
sd_handler_type _constructSDHandler;
};
}
#endif // GENERICPARALLELWORLD_HH
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of J.D. Koftinoff Software, Ltd. 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.
*/
#pragma once
#ifndef JDKSAVDECCMCU_BARE_METAL
#if defined( __AVR__ )
#define JDKSAVDECCMCU_ARDUINO 1
#define JDKSAVDECCMCU_BARE_METAL 1
#ifndef JDKSAVDECCMCU_ENABLE_FLOAT
#define JDKSAVDECCMCU_ENABLE_FLOAT 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETWIZNET
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETWIZNET 1
#ifndef JDKSAVDECCMCU_ENABLE_PCAP
#define JDKSAVDECCMCU_ENABLE_PCAP 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_PCAPFILE
#define JDKSAVDECCMCU_ENABLE_PCAPFILE 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETPCAPFILE
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETPCAPFILE 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETLINUX
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETLINUX 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETMACOSX
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETMACOSX 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_MDNSREGISTER
#define JDKSAVDECCMCU_ENABLE_MDNSREGISTER 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETWIN32
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETWIN32 0
#endif
#ifndef JDKSAVDECC_CPP_NO_IOSTREAM
#define JDKSAVDECC_CPP_NO_IOSTREAM
#endif
#ifndef JDKSAVDECC_CPP_NO_STDIO
#define JDKSAVDECC_CPP_NO_STDIO
#endif
#endif
#else
#define JDKSAVDECCMCU_BARE_METAL 0
#endif
#endif
#if JDKSAVDECCMCU_BARE_METAL == 0
#ifndef JDKSAVDECCMCU_ENABLE_FLOAT
#define JDKSAVDECCMCU_ENABLE_FLOAT 1
#endif
#ifndef JDKSAVDECCMCU_ARDUINO
#define JDKSAVDECCMCU_ARDUINO 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETWIZNET
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETWIZNET 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_PCAP
#define JDKSAVDECCMCU_ENABLE_PCAP 1
#endif
#ifndef JDKSAVDECCMCU_ENABLE_PCAPFILE
#define JDKSAVDECCMCU_ENABLE_PCAPFILE 1
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETPCAPFILE
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETPCAPFILE 1
#endif
#if defined( __APPLE__ )
#ifndef JDKSAVDECCMCU_ENABLE_MDNSREGISTER
#define JDKSAVDECCMCU_ENABLE_MDNSREGISTER 1
#endif
#else
#ifndef JDKSAVDECCMCU_ENABLE_MDNSREGISTER
#define JDKSAVDECCMCU_ENABLE_MDNSREGISTER 0
#endif
#endif
#if defined( __linux__ )
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETLINUX 1
#endif
#if defined( __APPLE__ ) && ( JDKSAVDECCMCU_ENABLE_PCAP == 1 )
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETMACOSX 1
#endif
#if defined( _WIN32 ) && ( JDKSAVDECCMCU_ENABLE_PCAP == 1 )
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETWIN32 1
#endif
#endif
#include "jdksavdecc.h"
#include "jdksavdecc_aem_descriptor.h"
namespace JDKSAvdeccMCU
{
}
#if defined( __AVR__ )
#include <SPI.h>
namespace JDKSAvdeccMCU
{
inline jdksavdecc_timestamp_in_milliseconds getTimeInMilliseconds()
{
return millis();
}
}
#elif defined( __APPLE__ ) || defined( __linux__ )
#include <vector>
#include <memory>
#include <sys/time.h>
#include <iostream>
#include <iomanip>
namespace JDKSAvdeccMCU
{
inline jdksavdecc_timestamp_in_milliseconds getTimeInMilliseconds()
{
timeval tv;
gettimeofday( &tv, 0 );
return jdksavdecc_timestamp_in_milliseconds( tv.tv_usec / 1000 )
+ jdksavdecc_timestamp_in_milliseconds( tv.tv_sec * 1000 );
}
}
#elif defined( _WIN32 )
#include <winsock2.h>
#include <WS2tcpip.h>
#include <Windows.h>
#include <vector>
#include <memory>
#include <iostream>
#include <iomanip>
#pragma comment( lib, "Ws2_32.lib" )
namespace JDKSAvdeccMCU
{
inline jdksavdecc_timestamp_in_milliseconds getTimeInMilliseconds()
{
return jdksavdecc_timestamp_in_milliseconds( GetTickCount() );
}
}
#endif
void jdksavdeccmcu_debug_log( const char *str, uint16_t v );
<commit_msg>win32 support for sockets added<commit_after>/*
Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of J.D. Koftinoff Software, Ltd. 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.
*/
#pragma once
#if defined( _WIN32 )
#include <WS2tcpip.h>
#include <Windows.h>
#include <Iphlpapi.h>
#pragma comment (lib,"Ws2_32.lib")
#pragma comment (lib,"Iphlpapi.lib")
#else
#include <sys/time.h>
#endif
#ifndef JDKSAVDECCMCU_BARE_METAL
#if defined( __AVR__ )
#define JDKSAVDECCMCU_ARDUINO 1
#define JDKSAVDECCMCU_BARE_METAL 1
#ifndef JDKSAVDECCMCU_ENABLE_FLOAT
#define JDKSAVDECCMCU_ENABLE_FLOAT 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETWIZNET
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETWIZNET 1
#ifndef JDKSAVDECCMCU_ENABLE_PCAP
#define JDKSAVDECCMCU_ENABLE_PCAP 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_PCAPFILE
#define JDKSAVDECCMCU_ENABLE_PCAPFILE 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETPCAPFILE
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETPCAPFILE 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETLINUX
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETLINUX 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETMACOSX
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETMACOSX 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_MDNSREGISTER
#define JDKSAVDECCMCU_ENABLE_MDNSREGISTER 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETWIN32
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETWIN32 0
#endif
#ifndef JDKSAVDECC_CPP_NO_IOSTREAM
#define JDKSAVDECC_CPP_NO_IOSTREAM
#endif
#ifndef JDKSAVDECC_CPP_NO_STDIO
#define JDKSAVDECC_CPP_NO_STDIO
#endif
#endif
#else
#define JDKSAVDECCMCU_BARE_METAL 0
#endif
#endif
#if JDKSAVDECCMCU_BARE_METAL == 0
#ifndef JDKSAVDECCMCU_ENABLE_FLOAT
#define JDKSAVDECCMCU_ENABLE_FLOAT 1
#endif
#ifndef JDKSAVDECCMCU_ARDUINO
#define JDKSAVDECCMCU_ARDUINO 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETWIZNET
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETWIZNET 0
#endif
#ifndef JDKSAVDECCMCU_ENABLE_PCAP
#define JDKSAVDECCMCU_ENABLE_PCAP 1
#endif
#ifndef JDKSAVDECCMCU_ENABLE_PCAPFILE
#define JDKSAVDECCMCU_ENABLE_PCAPFILE 1
#endif
#ifndef JDKSAVDECCMCU_ENABLE_RAWSOCKETPCAPFILE
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETPCAPFILE 1
#endif
#if defined( __APPLE__ )
#ifndef JDKSAVDECCMCU_ENABLE_MDNSREGISTER
#define JDKSAVDECCMCU_ENABLE_MDNSREGISTER 1
#endif
#else
#ifndef JDKSAVDECCMCU_ENABLE_MDNSREGISTER
#define JDKSAVDECCMCU_ENABLE_MDNSREGISTER 0
#endif
#endif
#if defined( __linux__ )
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETLINUX 1
#endif
#if defined( __APPLE__ ) && ( JDKSAVDECCMCU_ENABLE_PCAP == 1 )
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETMACOSX 1
#endif
#if defined( _WIN32 ) && ( JDKSAVDECCMCU_ENABLE_PCAP == 1 )
#define JDKSAVDECCMCU_ENABLE_RAWSOCKETWIN32 1
#endif
#endif
#include "jdksavdecc.h"
#include "jdksavdecc_aem_descriptor.h"
namespace JDKSAvdeccMCU
{
}
#if defined( __AVR__ )
#include <SPI.h>
namespace JDKSAvdeccMCU
{
inline jdksavdecc_timestamp_in_milliseconds getTimeInMilliseconds()
{
return millis();
}
}
#elif defined( __APPLE__ ) || defined( __linux__ )
#include <vector>
#include <memory>
#include <sys/time.h>
#include <iostream>
#include <iomanip>
namespace JDKSAvdeccMCU
{
inline jdksavdecc_timestamp_in_milliseconds getTimeInMilliseconds()
{
timeval tv;
gettimeofday( &tv, 0 );
return jdksavdecc_timestamp_in_milliseconds( tv.tv_usec / 1000 )
+ jdksavdecc_timestamp_in_milliseconds( tv.tv_sec * 1000 );
}
}
#elif defined( _WIN32 )
#include <winsock2.h>
#include <WS2tcpip.h>
#include <Windows.h>
#include <vector>
#include <memory>
#include <iostream>
#include <iomanip>
#pragma comment( lib, "Ws2_32.lib" )
namespace JDKSAvdeccMCU
{
inline jdksavdecc_timestamp_in_milliseconds getTimeInMilliseconds()
{
return jdksavdecc_timestamp_in_milliseconds( GetTickCount() );
}
}
#endif
void jdksavdeccmcu_debug_log( const char *str, uint16_t v );
<|endoftext|> |
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/discardable_memory.h"
#include <mach/mach.h>
#include "base/logging.h"
namespace base {
namespace {
// The VM subsystem allows tagging of memory and 240-255 is reserved for
// application use (see mach/vm_statistics.h). Pick 252 (after chromium's atomic
// weight of ~52).
const int kDiscardableMemoryTag = VM_MAKE_TAG(252);
} // namespace
// static
bool DiscardableMemory::Supported() {
return true;
}
DiscardableMemory::~DiscardableMemory() {
if (memory_) {
vm_deallocate(mach_task_self(),
reinterpret_cast<vm_address_t>(memory_),
size_);
}
}
bool DiscardableMemory::InitializeAndLock(size_t size) {
DCHECK(!memory_);
size_ = size;
vm_address_t buffer = 0;
kern_return_t ret = vm_allocate(mach_task_self(),
&buffer,
size,
VM_FLAGS_PURGABLE |
VM_FLAGS_ANYWHERE |
kDiscardableMemoryTag);
if (ret != KERN_SUCCESS) {
DLOG(ERROR) << "vm_allocate() failed";
return false;
}
is_locked_ = true;
memory_ = reinterpret_cast<void*>(buffer);
return true;
}
LockDiscardableMemoryStatus DiscardableMemory::Lock() {
DCHECK(!is_locked_);
int state = VM_PURGABLE_NONVOLATILE;
kern_return_t ret = vm_purgable_control(
mach_task_self(),
reinterpret_cast<vm_address_t>(memory_),
VM_PURGABLE_SET_STATE,
&state);
if (ret != KERN_SUCCESS)
return DISCARDABLE_MEMORY_FAILED;
is_locked_ = true;
return state & VM_PURGABLE_EMPTY ? DISCARDABLE_MEMORY_PURGED
: DISCARDABLE_MEMORY_SUCCESS;
}
void DiscardableMemory::Unlock() {
DCHECK(is_locked_);
int state = VM_PURGABLE_VOLATILE | VM_VOLATILE_GROUP_DEFAULT;
kern_return_t ret = vm_purgable_control(
mach_task_self(),
reinterpret_cast<vm_address_t>(memory_),
VM_PURGABLE_SET_STATE,
&state);
if (ret != KERN_SUCCESS)
DLOG(ERROR) << "Failed to unlock memory.";
is_locked_ = false;
}
// static
bool DiscardableMemory::PurgeForTestingSupported() {
return true;
}
// static
void DiscardableMemory::PurgeForTesting() {
int state = 0;
vm_purgable_control(mach_task_self(),
reinterpret_cast<vm_address_t>(0U),
VM_PURGABLE_PURGE_ALL,
&state);
}
} // namespace base
<commit_msg>Remove explicit cast in discardable_memory_mac.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/discardable_memory.h"
#include <mach/mach.h>
#include "base/logging.h"
namespace base {
namespace {
// The VM subsystem allows tagging of memory and 240-255 is reserved for
// application use (see mach/vm_statistics.h). Pick 252 (after chromium's atomic
// weight of ~52).
const int kDiscardableMemoryTag = VM_MAKE_TAG(252);
} // namespace
// static
bool DiscardableMemory::Supported() {
return true;
}
DiscardableMemory::~DiscardableMemory() {
if (memory_) {
vm_deallocate(mach_task_self(),
reinterpret_cast<vm_address_t>(memory_),
size_);
}
}
bool DiscardableMemory::InitializeAndLock(size_t size) {
DCHECK(!memory_);
size_ = size;
vm_address_t buffer = 0;
kern_return_t ret = vm_allocate(mach_task_self(),
&buffer,
size,
VM_FLAGS_PURGABLE |
VM_FLAGS_ANYWHERE |
kDiscardableMemoryTag);
if (ret != KERN_SUCCESS) {
DLOG(ERROR) << "vm_allocate() failed";
return false;
}
is_locked_ = true;
memory_ = reinterpret_cast<void*>(buffer);
return true;
}
LockDiscardableMemoryStatus DiscardableMemory::Lock() {
DCHECK(!is_locked_);
int state = VM_PURGABLE_NONVOLATILE;
kern_return_t ret = vm_purgable_control(
mach_task_self(),
reinterpret_cast<vm_address_t>(memory_),
VM_PURGABLE_SET_STATE,
&state);
if (ret != KERN_SUCCESS)
return DISCARDABLE_MEMORY_FAILED;
is_locked_ = true;
return state & VM_PURGABLE_EMPTY ? DISCARDABLE_MEMORY_PURGED
: DISCARDABLE_MEMORY_SUCCESS;
}
void DiscardableMemory::Unlock() {
DCHECK(is_locked_);
int state = VM_PURGABLE_VOLATILE | VM_VOLATILE_GROUP_DEFAULT;
kern_return_t ret = vm_purgable_control(
mach_task_self(),
reinterpret_cast<vm_address_t>(memory_),
VM_PURGABLE_SET_STATE,
&state);
if (ret != KERN_SUCCESS)
DLOG(ERROR) << "Failed to unlock memory.";
is_locked_ = false;
}
// static
bool DiscardableMemory::PurgeForTestingSupported() {
return true;
}
// static
void DiscardableMemory::PurgeForTesting() {
int state = 0;
vm_purgable_control(mach_task_self(), 0, VM_PURGABLE_PURGE_ALL, &state);
}
} // namespace base
<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_DATA_PROVIDER_SPE10_HH
#define DUNE_STUFF_DATA_PROVIDER_SPE10_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <iostream>
#include <sstream>
#include <memory>
#ifdef HAVE_EIGEN
#include <Eigen/Core>
#endif // HAVE_EIGEN
#include <dune/common/exceptions.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/parametertree.hh>
#include <dune/common/dynmatrix.hh>
#include <dune/common/densevector.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>
namespace Dune {
namespace Stuff {
namespace Data {
namespace Provider {
namespace Spe10 {
namespace Model1 {
template< class DomainFieldImp, int domainDimension, class RangeFieldImp, int rangeDimension >
class Permeability;
template< class DomainFieldImp, class RangeFieldImp >
class Permeability< DomainFieldImp, 2, RangeFieldImp, 1 >
{
public:
typedef DomainFieldImp DomainFieldType;
static const int dimDomain = 2;
typedef RangeFieldImp RangeFieldType;
static const int dimRange = 1;
typedef Permeability< DomainFieldType, dimDomain, RangeFieldType, dimRange > ThisType;
static const std::string id;
class Function
{
public:
Function(const DomainFieldType& lowerLeftX,
const DomainFieldType& lowerLeftY,
const DomainFieldType& upperRightX,
const DomainFieldType& upperRightY,
const unsigned int& numElementsX,
const unsigned int& numElementsY,
const Dune::shared_ptr< const Dune::DynamicMatrix< RangeFieldType > >& data)
: lowerLeftX_(lowerLeftX)
, lowerLeftY_(lowerLeftY)
, upperRightX_(upperRightX)
, upperRightY_(upperRightY)
, numElementsX_(numElementsX)
, numElementsY_(numElementsY)
, data_(data)
{}
template< class DomainVectorType, class RangeVectorType >
void evaluate(const Dune::DenseVector< DomainVectorType >& arg, Dune::DenseVector< RangeVectorType >& ret) const
{
// ensure right dimensions
assert(arg.size() == dimDomain);
assert(ret.size() == dimRange);
// find i and j
unsigned int i = std::floor(numElementsX_*((arg[0] - lowerLeftX_)/(upperRightX_ - lowerLeftX_)));
unsigned int j = std::floor(numElementsY_*((arg[1] - lowerLeftY_)/(upperRightY_ - lowerLeftY_)));
// return
ret[0] = data_->operator[](i)[j];
}
#ifdef HAVE_EIGEN
void evaluate(const Eigen::VectorXd& arg, Eigen::VectorXd& ret) const
{
// ensure right dimensions
assert(arg.rows() == dimDomain);
assert(ret.rows() == dimRange);
// find i and j
unsigned int i = std::floor(numElementsX_*((arg(0) - lowerLeftX_)/(upperRightX_ - lowerLeftX_)));
unsigned int j = std::floor(numElementsY_*((arg(1) - lowerLeftY_)/(upperRightY_ - lowerLeftY_)));
// return
ret(0) = data_->operator[](i)[j];
}
#endif // HAVE_EIGEN
private:
const DomainFieldType lowerLeftX_;
const DomainFieldType lowerLeftY_;
const DomainFieldType upperRightX_;
const DomainFieldType upperRightY_;
const unsigned int numElementsX_;
const unsigned int numElementsY_;
const Dune::shared_ptr< const Dune::DynamicMatrix< RangeFieldType > > data_;
}; // class Function
const Dune::shared_ptr< const Function > create(const Dune::ParameterTree& paramTree,
const std::string prefix = "",
std::ostream& out = Dune::Stuff::Common::Logger().debug()) const
{
// preparations
std::string filename;
DomainFieldType lowerLeftX, lowerLeftY;
DomainFieldType upperRightX, upperRightY;
unsigned int numElementsX, numElementsY;
readAndAssertParamTree(paramTree, filename,
lowerLeftX, lowerLeftY,
upperRightX, upperRightY,
numElementsX, numElementsY);
out << prefix << "reading 'spe10.model1.permeability' from " << filename << "... ";
RangeFieldType* rawData = new RangeFieldType[100*20];
readRawDataFromFile(filename, rawData);
Dune::shared_ptr< Dune::DynamicMatrix< RangeFieldType > >
data = Dune::shared_ptr< Dune::DynamicMatrix< RangeFieldType > >(new Dune::DynamicMatrix< RangeFieldType >(numElementsX, numElementsY, 0.0));
fillDataFromRaw(rawData, *data);
out << "done" << std::endl;
const Dune::shared_ptr< const Function >
function = Dune::shared_ptr< const Function >(new Function(lowerLeftX,
lowerLeftY,
upperRightX,
upperRightY,
numElementsX,
numElementsY,
data));
return function;
} // const Dune::shared_ptr< const Function > create() const
private:
void readAndAssertParamTree(const DSC::ExtendedParameterTree& paramTree,
std::string& filename,
DomainFieldType& lowerLeftX,
DomainFieldType& lowerLeftY,
DomainFieldType& upperRightX,
DomainFieldType& upperRightY,
unsigned int& numElementsX,
unsigned int& numElementsY) const
{
//!TODO no idea what these asserts were supposed to achieve. commented for complete compile fail
// paramTree.assertKey(paramTree, "filename", id);
filename = paramTree.get("filename", "../../../../../data/spe10/model1/spe10_model1_permeability.dat");
// paramTree.assertKey(paramTree, "lowerLeft.0", id);
lowerLeftX = paramTree.get("lowerLeft.0", 0.0);
// paramTree.assertKey(paramTree, "lowerLeft.1", id);
lowerLeftY = paramTree.get("lowerLeft.1", 0.0);
// paramTree.assertKey(paramTree, "upperRight.0", id);
upperRightX = paramTree.get("upperRight.0", 762.0);
// paramTree.assertKey(paramTree, "upperRight.1", id);
upperRightY = paramTree.get("upperRight.1", 15.24);
// paramTree.assertKey(paramTree, "numElements.0", id);
numElementsX = paramTree.get("numElements.0", 100);
// paramTree.assertKey(paramTree, "numElements.1", id);
numElementsY = paramTree.get("numElements.1", 20);
// make sure everything is all right
bool kaboom = false;
std::stringstream msg;
msg << "Error in " << id << ": the following errors were found while reading the Dune::ParameterTree given below!" << std::endl;
if (!(lowerLeftX < upperRightX)) {
kaboom = true;
msg << "- !(lowerLeft.0 < upperRight.0): !(" << lowerLeftX << " < " << upperRightX << ")" << std::endl;
}
if (!(lowerLeftY < upperRightY)) {
kaboom = true;
msg << "- !(lowerLeft.1 < upperRight.1): !(" << lowerLeftY << " < " << upperRightY << ")" << std::endl;
}
if (!(numElementsX > 0)) {
kaboom = true;
msg << "- !(numElements.0 > 0): !(" << numElementsX << " > 0)" << std::endl;
}
if (!(numElementsX <= 100)) {
kaboom = true;
msg << "- !(numElements.0 <= 100): !(" << numElementsX << " <= 100)" << std::endl;
}
if (!(numElementsY <= 20)) {
kaboom = true;
msg << "- !(numElements.Y <= 20): !(" << numElementsY << " <= 20)" << std::endl;
}
// test if we can open the file
const bool can_open(std::ifstream(filename.c_str()).is_open());
if (!can_open) {
kaboom = true;
msg << "- could not open file given by 'filename': '" << filename << "'" << std::endl;
}
// throw up if we have to
if (kaboom) {
msg << "given in the following Dune::ParameterTree:" << std::endl;
paramTree.report(msg);
DUNE_THROW(Dune::InvalidStateException, msg.str());
}
} // void readAndAssertParamTree() const
void readRawDataFromFile(const std::string filename, RangeFieldType* rawData) const
{
std::ifstream file(filename.c_str());
assert(file && "After we checked before, this should really not blow up right now!");
RangeFieldType val;
file >> val;
unsigned int counter = 0;
while (!file.eof()) {
rawData[counter++] = val;
file >> val;
}
file.close();
} // void readRawDataFromFile(const std::string filename, DomainFieldType* rawData) const
void fillDataFromRaw(RangeFieldType* rawData, Dune::DynamicMatrix< RangeFieldType >& data) const
{
unsigned int counter = 0;
for (unsigned int i = 0; i < data.rows(); ++ i) {
for (unsigned int j = 0; j < data.cols(); ++j) {
data[i][j] = rawData[counter];
++counter;
}
}
} // void fillDatFromRaw(RangeFieldType* rawData, Dune::DynamicMatrix< RangeFieldType >& data) const
}; // class Permeability
template< class DomainFieldType, class RangeFieldType >
const std::string Permeability< DomainFieldType, 2, RangeFieldType, 1 >::id = "stuff.data.provider.spe10.model1.permeability";
} // namespace Model1
} // namespace Spe10
} // namespace Provider
} // namespace Data
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_DATA_PROVIDER_SPE10_HH
<commit_msg>[data] removed<commit_after><|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Sven Kaulmann
#ifndef DUNE_STUFF_GRID_STRUCTURED_GRID_FACTORY_HH
#define DUNE_STUFF_GRID_STRUCTURED_GRID_FACTORY_HH
#include <dune/common/unused.hh>
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/grid/utility/structuredgridfactory.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#if HAVE_DUNE_SPGRID
# include <dune/grid/spgrid.hh>
# include <dune/stuff/aliases.hh>
#endif //HAVE_DUNE_SPGRID
namespace Dune {
#if HAVE_DUNE_SPGRID
/** \brief Specialization of the StructuredGridFactory for SPGrid
*
* This allows a SPGrid to be constructed using the
* StructuredGridFactory just like the unstructured Grids. Limitations:
* \li SPGrid does not support simplices
*/
template< class ct, int dim, SPRefinementStrategy strategy, class Comm >
class StructuredGridFactory< SPGrid< ct, dim, strategy, Comm > > {
typedef SPGrid< ct, dim, strategy, Comm > GridType;
typedef typename GridType::ctype ctype;
static const int dimworld = GridType::dimensionworld;
public:
/** \brief Create a structured cube grid
*
* \param lowerLeft Lower left corner of the grid
* \param upperRight Upper right corner of the grid
* \param elements Number of elements in each coordinate direction
*/
static std::shared_ptr<GridType>
createCubeGrid(const FieldVector<ctype,dimworld>& lowerLeft,
const FieldVector<ctype,dimworld>& upperRight,
const array<unsigned int,dim>& elements)
{
Dune::array< int, dim > cells;
for(const auto i : DSC::valueRange(dim))
cells[i] = elements[i];
return std::make_shared<GridType>(lowerLeft, upperRight, cells);
}
/** \brief Create a structured cube grid
*
* \param lowerLeft Lower left corner of the grid
* \param upperRight Upper right corner of the grid
* \param elements Number of elements in each coordinate direction
* \param overlap Size of overlap in each coordinate direction
*/
static std::shared_ptr<GridType>
createCubeGrid(const FieldVector<ctype,dimworld>& lowerLeft,
const FieldVector<ctype,dimworld>& upperRight,
const array<unsigned int,dim>& elements,
const array<unsigned int,dim>& overlap)
{
Dune::array< int, dim > cells;
Dune::array< int, dim > over;
for(const auto i : DSC::valueRange(dim)) {
cells[i] = elements[i];
over[i] = overlap[i];
}
return std::make_shared<GridType>(lowerLeft, upperRight, cells, over);
}
/** \brief Create a structured simplex grid
*
* \param lowerLeft Lower left corner of the grid
* \param upperRight Upper right corner of the grid
* \param elements Number of elements in each coordinate direction
*
* \note Simplices are not supported in SGrid, so this functions
* unconditionally throws a GridError.
*/
static shared_ptr<GridType>
createSimplexGrid(const FieldVector<ctype,dimworld>& lowerLeft,
const FieldVector<ctype,dimworld>& upperRight,
const array<unsigned int,dim>& elements)
{
DUNE_THROW(GridError, className<StructuredGridFactory>()
<< "::createSimplexGrid(): Simplices are not supported "
"by SPGrid.");
}
};
#endif //HAVE_DUNE_SPGRID
/** \brief Specialization of the StructuredGridFactory for SGrid< dim, dimWorld >
*
* This allows a SGrid to be constructed using the
* StructuredGridFactory just like the unstructured Grids. Limitations:
* \li SGrid does not support simplices
*/
template<int dim, int dimworld>
class StructuredGridFactory< SGrid< dim, dimworld > > {
typedef SGrid< dim, dimworld > GridType;
typedef typename GridType::ctype ctype;
public:
/** \brief Create a structured cube grid
*
* \param lowerLeft Lower left corner of the grid
* \param upperRight Upper right corner of the grid
* \param elements Number of elements in each coordinate direction
*/
static shared_ptr< GridType >
createCubeGrid(const FieldVector< ctype, dim >& lowerLeft,
const FieldVector< ctype, dim >& upperRight,
const array< unsigned int, dim >& elements)
{
FieldVector< int, dim > elements_;
std::copy(elements.begin(), elements.end(), elements_.begin());
return shared_ptr< GridType >
(new GridType(elements_, lowerLeft, upperRight));
}
/** \brief Create a structured simplex grid
*
* \param lowerLeft Lower left corner of the grid
* \param upperRight Upper right corner of the grid
* \param elements Number of elements in each coordinate direction
*
* \note Simplices are not supported in SGrid, so this functions
* unconditionally throws a GridError.
*/
static shared_ptr<GridType>
createSimplexGrid(const FieldVector< ctype, dim >& DUNE_UNUSED(lowerLeft),
const FieldVector< ctype, dim>& DUNE_UNUSED(upperRight),
const array< unsigned int,dim >& DUNE_UNUSED(elements))
{
DUNE_THROW(GridError, className< StructuredGridFactory >()
<< "::createSimplexGrid(): Simplices are not supported "
"by SGrid.");
}
};
} // namespace Dune
#endif // DUNE_STUFF_GRID_STRUCTURED_GRID_FACTORY_HH
<commit_msg>[grid] gets rid of unused param warnings in gridfactory<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Sven Kaulmann
#ifndef DUNE_STUFF_GRID_STRUCTURED_GRID_FACTORY_HH
#define DUNE_STUFF_GRID_STRUCTURED_GRID_FACTORY_HH
#include <dune/common/unused.hh>
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/grid/utility/structuredgridfactory.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#if HAVE_DUNE_SPGRID
# include <dune/grid/spgrid.hh>
# include <dune/stuff/aliases.hh>
#endif //HAVE_DUNE_SPGRID
namespace Dune {
#if HAVE_DUNE_SPGRID
/** \brief Specialization of the StructuredGridFactory for SPGrid
*
* This allows a SPGrid to be constructed using the
* StructuredGridFactory just like the unstructured Grids. Limitations:
* \li SPGrid does not support simplices
*/
template< class ct, int dim, SPRefinementStrategy strategy, class Comm >
class StructuredGridFactory< SPGrid< ct, dim, strategy, Comm > > {
typedef SPGrid< ct, dim, strategy, Comm > GridType;
typedef typename GridType::ctype ctype;
static const int dimworld = GridType::dimensionworld;
public:
/** \brief Create a structured cube grid
*
* \param lowerLeft Lower left corner of the grid
* \param upperRight Upper right corner of the grid
* \param elements Number of elements in each coordinate direction
*/
static std::shared_ptr<GridType>
createCubeGrid(const FieldVector<ctype,dimworld>& lowerLeft,
const FieldVector<ctype,dimworld>& upperRight,
const array<unsigned int,dim>& elements)
{
Dune::array< int, dim > cells;
for(const auto i : DSC::valueRange(dim))
cells[i] = elements[i];
return std::make_shared<GridType>(lowerLeft, upperRight, cells);
}
/** \brief Create a structured cube grid
*
* \param lowerLeft Lower left corner of the grid
* \param upperRight Upper right corner of the grid
* \param elements Number of elements in each coordinate direction
* \param overlap Size of overlap in each coordinate direction
*/
static std::shared_ptr<GridType>
createCubeGrid(const FieldVector<ctype,dimworld>& lowerLeft,
const FieldVector<ctype,dimworld>& upperRight,
const array<unsigned int,dim>& elements,
const array<unsigned int,dim>& overlap)
{
Dune::array< int, dim > cells;
Dune::array< int, dim > over;
for(const auto i : DSC::valueRange(dim)) {
cells[i] = elements[i];
over[i] = overlap[i];
}
return std::make_shared<GridType>(lowerLeft, upperRight, cells, over);
}
/** \brief Create a structured simplex grid
*
* \param lowerLeft Lower left corner of the grid
* \param upperRight Upper right corner of the grid
* \param elements Number of elements in each coordinate direction
*
* \note Simplices are not supported in SGrid, so this functions
* unconditionally throws a GridError.
*/
static shared_ptr<GridType>
createSimplexGrid(const FieldVector<ctype,dimworld>& /*lowerLeft*/,
const FieldVector<ctype,dimworld>& /*upperRight*/,
const array<unsigned int,dim>& /*elements*/)
{
DUNE_THROW(GridError, className<StructuredGridFactory>()
<< "::createSimplexGrid(): Simplices are not supported "
"by SPGrid.");
}
};
#endif //HAVE_DUNE_SPGRID
/** \brief Specialization of the StructuredGridFactory for SGrid< dim, dimWorld >
*
* This allows a SGrid to be constructed using the
* StructuredGridFactory just like the unstructured Grids. Limitations:
* \li SGrid does not support simplices
*/
template<int dim, int dimworld>
class StructuredGridFactory< SGrid< dim, dimworld > > {
typedef SGrid< dim, dimworld > GridType;
typedef typename GridType::ctype ctype;
public:
/** \brief Create a structured cube grid
*
* \param lowerLeft Lower left corner of the grid
* \param upperRight Upper right corner of the grid
* \param elements Number of elements in each coordinate direction
*/
static shared_ptr< GridType >
createCubeGrid(const FieldVector< ctype, dim >& lowerLeft,
const FieldVector< ctype, dim >& upperRight,
const array< unsigned int, dim >& elements)
{
FieldVector< int, dim > elements_;
std::copy(elements.begin(), elements.end(), elements_.begin());
return shared_ptr< GridType >
(new GridType(elements_, lowerLeft, upperRight));
}
/** \brief Create a structured simplex grid
*
* \param lowerLeft Lower left corner of the grid
* \param upperRight Upper right corner of the grid
* \param elements Number of elements in each coordinate direction
*
* \note Simplices are not supported in SGrid, so this functions
* unconditionally throws a GridError.
*/
static shared_ptr<GridType>
createSimplexGrid(const FieldVector< ctype, dim >& DUNE_UNUSED(lowerLeft),
const FieldVector< ctype, dim>& DUNE_UNUSED(upperRight),
const array< unsigned int,dim >& DUNE_UNUSED(elements))
{
DUNE_THROW(GridError, className< StructuredGridFactory >()
<< "::createSimplexGrid(): Simplices are not supported "
"by SGrid.");
}
};
} // namespace Dune
#endif // DUNE_STUFF_GRID_STRUCTURED_GRID_FACTORY_HH
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <map>
#include <string>
#include <functional>
#include "function_traits.hpp"
#include "lexical_cast.hpp"
class HttpRouter
{
class token_parser
{
std::vector<std::string> m_v;
static std::vector<std::string> split(std::string& s, char seperator)
{
std::vector<std::string> v;
int pos = 0;
while (true)
{
pos = s.find(seperator, 0);
if (pos == std::string::npos)
{
if (!s.empty())
v.push_back(s);
break;
}
if (pos != 0)
v.push_back(s.substr(0, pos));
s = s.substr(pos + 1, s.length());
}
return v;
}
public:
token_parser(std::string& s, char seperator)
{
m_v = split(s, seperator);
}
public:
template<typename RequestedType>
typename std::decay<RequestedType>::type get()
{
if (m_v.empty())
throw std::runtime_error("unexpected end of input");
try
{
typedef typename std::decay<RequestedType>::type result_type;
auto it = m_v.begin();
result_type result = lexical_cast<typename std::decay<result_type>::type>(*it);
m_v.erase(it);
return result;
}
catch (std::exception& e)
{
throw std::invalid_argument(std::string("invalid argument: ") + e.what());
}
}
bool empty(){ return m_v.empty(); }
};
typedef std::function<void(token_parser &)> invoker_function;
std::map<std::string, invoker_function> map_invokers;
public:
std::function<void(const std::string&)> log;
template<typename Function>
void assign(std::string const & name, Function f) {
return register_nonmenber_impl<Function>(name, f);
}
void remove_function(std::string const& name) {
this->map_invokers.erase(name);
}
void run(std::string & text) const
{
token_parser parser(text, '/');
while (!parser.empty())
{
// read function name
std::string func_name = parser.get<std::string>();
// look up function
auto it = map_invokers.find(func_name);
if (it == map_invokers.end())
throw std::runtime_error("unknown function: " + func_name);
// call the invoker which controls argument parsing
it->second(parser);
}
}
public:
template<class Signature, typename Function>
void register_nonmenber_impl(std::string const & name, Function f)
{
// instantiate and store the invoker by name
this->map_invokers[name] = std::bind(
&invoker<Function, Signature>::template apply<std::tuple<>>,
f,
std::placeholders::_1,
std::tuple<>()
);
}
private:
template<typename Function, class Signature = Function, size_t N = 0, size_t M = function_traits<Signature>::arity>
struct invoker;
template<typename Function, class Signature, size_t N, size_t M>
struct invoker
{
// add an argument to a Fusion cons-list for each parameter type
template<typename Args>
static inline void apply(Function func, token_parser & parser, Args const & args)
{
typedef typename function_traits<Signature>::template args<N>::type arg_type;
HttpRouter::invoker<Function, Signature, N + 1, M>::apply
(func, parser, std::tuple_cat(args, std::make_tuple(parser.get<arg_type>())));
}
};
template<typename Function, class Signature, size_t M>
struct invoker<Function, Signature, M, M>
{
// the argument list is complete, now call the function
template<typename Args>
static inline void apply(Function func, token_parser &, Args const & args)
{
call(func, args);
}
};
template<int...>
struct IndexTuple{};
template<int N, int... Indexes>
struct MakeIndexes : MakeIndexes<N - 1, N - 1, Indexes...>{};
template<int... indexes>
struct MakeIndexes<0, indexes...>
{
typedef IndexTuple<indexes...> type;
};
template<typename F, int ... Indexes, typename ... Args>
static void call_helper(F f, IndexTuple<Indexes...>, std::tuple<Args...> tup)
{
f(std::get<Indexes>(tup)...);
}
template<typename F, typename ... Args>
static void call(F f, std::tuple<Args...> tp)
{
call_helper(f, typename MakeIndexes<sizeof... (Args)>::type(), tp);
}
};
<commit_msg>把split放帮助类中<commit_after>#pragma once
#include <vector>
#include <map>
#include <string>
#include <functional>
#include "function_traits.hpp"
#include "lexical_cast.hpp"
#include "string_utils.hpp"
class HttpRouter
{
class token_parser
{
std::vector<std::string> m_v;
public:
token_parser(std::string& s, char seperator)
{
m_v = StringUtil::split(s, seperator);
}
public:
template<typename RequestedType>
typename std::decay<RequestedType>::type get()
{
if (m_v.empty())
throw std::runtime_error("unexpected end of input");
try
{
typedef typename std::decay<RequestedType>::type result_type;
auto it = m_v.begin();
result_type result = lexical_cast<typename std::decay<result_type>::type>(*it);
m_v.erase(it);
return result;
}
catch (std::exception& e)
{
throw std::invalid_argument(std::string("invalid argument: ") + e.what());
}
}
bool empty(){ return m_v.empty(); }
};
typedef std::function<void(token_parser &)> invoker_function;
std::map<std::string, invoker_function> map_invokers;
public:
std::function<void(const std::string&)> log;
template<typename Function>
void assign(std::string const & name, Function f) {
return register_nonmenber_impl<Function>(name, f);
}
void remove_function(std::string const& name) {
this->map_invokers.erase(name);
}
void run(std::string & text) const
{
token_parser parser(text, '/');
while (!parser.empty())
{
// read function name
std::string func_name = parser.get<std::string>();
// look up function
auto it = map_invokers.find(func_name);
if (it == map_invokers.end())
throw std::runtime_error("unknown function: " + func_name);
// call the invoker which controls argument parsing
it->second(parser);
}
}
public:
template<class Signature, typename Function>
void register_nonmenber_impl(std::string const & name, Function f)
{
// instantiate and store the invoker by name
this->map_invokers[name] = std::bind(
&invoker<Function, Signature>::template apply<std::tuple<>>,
f,
std::placeholders::_1,
std::tuple<>()
);
}
private:
template<typename Function, class Signature = Function, size_t N = 0, size_t M = function_traits<Signature>::arity>
struct invoker;
template<typename Function, class Signature, size_t N, size_t M>
struct invoker
{
// add an argument to a Fusion cons-list for each parameter type
template<typename Args>
static inline void apply(Function func, token_parser & parser, Args const & args)
{
typedef typename function_traits<Signature>::template args<N>::type arg_type;
HttpRouter::invoker<Function, Signature, N + 1, M>::apply
(func, parser, std::tuple_cat(args, std::make_tuple(parser.get<arg_type>())));
}
};
template<typename Function, class Signature, size_t M>
struct invoker<Function, Signature, M, M>
{
// the argument list is complete, now call the function
template<typename Args>
static inline void apply(Function func, token_parser &, Args const & args)
{
call(func, args);
}
};
template<int...>
struct IndexTuple{};
template<int N, int... Indexes>
struct MakeIndexes : MakeIndexes<N - 1, N - 1, Indexes...>{};
template<int... indexes>
struct MakeIndexes<0, indexes...>
{
typedef IndexTuple<indexes...> type;
};
template<typename F, int ... Indexes, typename ... Args>
static void call_helper(F f, IndexTuple<Indexes...>, std::tuple<Args...> tup)
{
f(std::get<Indexes>(tup)...);
}
template<typename F, typename ... Args>
static void call(F f, std::tuple<Args...> tp)
{
call_helper(f, typename MakeIndexes<sizeof... (Args)>::type(), tp);
}
};
<|endoftext|> |
<commit_before>#include <string>
#include <map>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef windows
# include <dlfcn.h>
#else
# include <windows.h>
# define dlopen(x,y) (void*)LoadLibrary(x)
# define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)
# define dlclose(x) FreeLibrary((HMODULE)x)
#endif
#include "js_macros.h"
#include "js_cache.h"
#include "js_common.h"
/**
* Is this file already cached?
*/
bool Cache::isCached(std::string filename) {
struct stat st;
int result = stat(filename.c_str(), &st);
if (result != 0) { return false;
TimeValue::iterator it = modified.find(filename);
if (it == modified.end()) { return false; } /* not seen yet */
if (it->second != st.st_mtime) { /* was modified */
erase(filename);
return false;
}
return true;
}
/**
* Mark filename as "cached"
* */
void Cache::mark(std::string filename) {
struct stat st;
stat(filename.c_str(), &st);
modified[filename] = st.st_mtime;
}
/**
* Remove file from all available caches
*/
void Cache::erase(std::string filename) {
SourceValue::iterator it1 = sources.find(filename);
if (it1 != sources.end()) { sources.erase(it1); }
HandleValue::iterator it2 = handles.find(filename);
if (it2 != handles.end()) {
dlclose(it2->second);
handles.erase(it2);
}
ScriptValue::iterator it3 = scripts.find(filename);
if (it3 != scripts.end()) {
it3->second.Dispose();
scripts.erase(it3);
}
}
/**
* Return source code for a given file
*/
std::string Cache::getSource(std::string filename, bool wrap) {
#ifdef VERBOSE
printf("[getSource] cache try for '%s' .. ", filename.c_str());
#endif
if (isCached(filename)) {
#ifdef VERBOSE
printf("cache hit\n");
#endif
SourceValue::iterator it = sources.find(filename);
return it->second;
} else {
#ifdef VERBOSE
printf("cache miss\n");
#endif
FILE * file = fopen(filename.c_str(), "rb");
if (file == NULL) {
std::string s = "Error reading '";
s += filename;
s += "'";
throw s;
}
mark(filename); /* mark as cached */
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (unsigned int i = 0; i < size;) {
size_t read = fread(&chars[i], 1, size - i, file);
i += read;
}
fclose(file);
std::string source = chars;
delete[] chars;
/* remove shebang line */
if (source.find('#',0) == 0 && source.find('!',1) == 1 ) {
unsigned int pfix = source.find('\n',0);
source.erase(0,pfix);
};
if (wrap) { source = wrapExports(source); }
sources[filename] = source;
return source;
}
}
/**
* Return dlopen handle for a given file
*/
void * Cache::getHandle(std::string filename) {
#ifdef VERBOSE
printf("[getHandle] cache try for '%s' .. ", filename.c_str());
#endif
if (isCached(filename)) {
#ifdef VERBOSE
printf("cache hit\n");
#endif
HandleValue::iterator it = handles.find(filename);
return it->second;
} else {
#ifdef VERBOSE
printf("cache miss\n");
#endif
void * handle = dlopen(filename.c_str(), RTLD_LAZY);
if (!handle) {
std::string error = "Error opening shared library '";
error += filename;
error += "'";
throw error;
}
mark(filename); /* mark as cached */
handles[filename] = handle;
return handle;
}
}
/**
* Return compiled script from a given file
*/
v8::Handle<v8::Script> Cache::getScript(std::string filename, bool wrap) {
#ifdef VERBOSE
printf("[getScript] cache try for '%s' .. ", filename.c_str());
#endif
if (isCached(filename)) {
#ifdef VERBOSE
printf("cache hit\n");
#endif
ScriptValue::iterator it = scripts.find(filename);
return it->second;
} else {
#ifdef VERBOSE
printf("cache miss\n");
#endif
std::string source = getSource(filename, wrap);
v8::Handle<v8::Script> script = v8::Script::Compile(JS_STR(source.c_str()), JS_STR(filename.c_str()));
v8::Persistent<v8::Script> result = v8::Persistent<v8::Script>::New(script);
scripts[filename] = result;
return result;
}
}
/**
* Return exports object for a given file
*/
v8::Handle<v8::Object> Cache::getExports(std::string filename) {
ExportsValue::iterator it = exports.find(filename);
if (it != exports.end()) {
#ifdef VERBOSE
printf("[getExports] using cached exports for '%s'\n", filename.c_str());
#endif
return it->second;
} else {
#ifdef VERBOSE
printf("[getExports] '%s' has no cached exports\n", filename.c_str());
#endif
return v8::Handle<v8::Object>::Handle();
}
}
/**
* Add a single item to exports cache
*/
void Cache::addExports(std::string filename, v8::Handle<v8::Object> obj) {
#ifdef VERBOSE
printf("[addExports] caching exports for '%s'\n", filename.c_str());
#endif
exports[filename] = v8::Persistent<v8::Object>::New(obj);
}
/**
* Remove a cached exports object
*/
void Cache::removeExports(std::string filename) {
#ifdef VERBOSE
printf("[removeExports] removing exports for '%s'\n", filename.c_str());
#endif
ExportsValue::iterator it = exports.find(filename);
if (it != exports.end()) {
it->second.Dispose();
it->second.Clear();
exports.erase(it);
}
}
/**
* Remove all cached exports
*/
void Cache::clearExports() {
ExportsValue::iterator it;
for (it=exports.begin(); it != exports.end(); it++) {
it->second.Dispose();
it->second.Clear();
}
exports.clear();
}
<commit_msg>typo<commit_after>#include <string>
#include <map>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef windows
# include <dlfcn.h>
#else
# include <windows.h>
# define dlopen(x,y) (void*)LoadLibrary(x)
# define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)
# define dlclose(x) FreeLibrary((HMODULE)x)
#endif
#include "js_macros.h"
#include "js_cache.h"
#include "js_common.h"
/**
* Is this file already cached?
*/
bool Cache::isCached(std::string filename) {
struct stat st;
int result = stat(filename.c_str(), &st);
if (result != 0) { return false; }
TimeValue::iterator it = modified.find(filename);
if (it == modified.end()) { return false; } /* not seen yet */
if (it->second != st.st_mtime) { /* was modified */
erase(filename);
return false;
}
return true;
}
/**
* Mark filename as "cached"
* */
void Cache::mark(std::string filename) {
struct stat st;
stat(filename.c_str(), &st);
modified[filename] = st.st_mtime;
}
/**
* Remove file from all available caches
*/
void Cache::erase(std::string filename) {
SourceValue::iterator it1 = sources.find(filename);
if (it1 != sources.end()) { sources.erase(it1); }
HandleValue::iterator it2 = handles.find(filename);
if (it2 != handles.end()) {
dlclose(it2->second);
handles.erase(it2);
}
ScriptValue::iterator it3 = scripts.find(filename);
if (it3 != scripts.end()) {
it3->second.Dispose();
scripts.erase(it3);
}
}
/**
* Return source code for a given file
*/
std::string Cache::getSource(std::string filename, bool wrap) {
#ifdef VERBOSE
printf("[getSource] cache try for '%s' .. ", filename.c_str());
#endif
if (isCached(filename)) {
#ifdef VERBOSE
printf("cache hit\n");
#endif
SourceValue::iterator it = sources.find(filename);
return it->second;
} else {
#ifdef VERBOSE
printf("cache miss\n");
#endif
FILE * file = fopen(filename.c_str(), "rb");
if (file == NULL) {
std::string s = "Error reading '";
s += filename;
s += "'";
throw s;
}
mark(filename); /* mark as cached */
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (unsigned int i = 0; i < size;) {
size_t read = fread(&chars[i], 1, size - i, file);
i += read;
}
fclose(file);
std::string source = chars;
delete[] chars;
/* remove shebang line */
if (source.find('#',0) == 0 && source.find('!',1) == 1 ) {
unsigned int pfix = source.find('\n',0);
source.erase(0,pfix);
};
if (wrap) { source = wrapExports(source); }
sources[filename] = source;
return source;
}
}
/**
* Return dlopen handle for a given file
*/
void * Cache::getHandle(std::string filename) {
#ifdef VERBOSE
printf("[getHandle] cache try for '%s' .. ", filename.c_str());
#endif
if (isCached(filename)) {
#ifdef VERBOSE
printf("cache hit\n");
#endif
HandleValue::iterator it = handles.find(filename);
return it->second;
} else {
#ifdef VERBOSE
printf("cache miss\n");
#endif
void * handle = dlopen(filename.c_str(), RTLD_LAZY);
if (!handle) {
std::string error = "Error opening shared library '";
error += filename;
error += "'";
throw error;
}
mark(filename); /* mark as cached */
handles[filename] = handle;
return handle;
}
}
/**
* Return compiled script from a given file
*/
v8::Handle<v8::Script> Cache::getScript(std::string filename, bool wrap) {
#ifdef VERBOSE
printf("[getScript] cache try for '%s' .. ", filename.c_str());
#endif
if (isCached(filename)) {
#ifdef VERBOSE
printf("cache hit\n");
#endif
ScriptValue::iterator it = scripts.find(filename);
return it->second;
} else {
#ifdef VERBOSE
printf("cache miss\n");
#endif
std::string source = getSource(filename, wrap);
v8::Handle<v8::Script> script = v8::Script::Compile(JS_STR(source.c_str()), JS_STR(filename.c_str()));
v8::Persistent<v8::Script> result = v8::Persistent<v8::Script>::New(script);
scripts[filename] = result;
return result;
}
}
/**
* Return exports object for a given file
*/
v8::Handle<v8::Object> Cache::getExports(std::string filename) {
ExportsValue::iterator it = exports.find(filename);
if (it != exports.end()) {
#ifdef VERBOSE
printf("[getExports] using cached exports for '%s'\n", filename.c_str());
#endif
return it->second;
} else {
#ifdef VERBOSE
printf("[getExports] '%s' has no cached exports\n", filename.c_str());
#endif
return v8::Handle<v8::Object>::Handle();
}
}
/**
* Add a single item to exports cache
*/
void Cache::addExports(std::string filename, v8::Handle<v8::Object> obj) {
#ifdef VERBOSE
printf("[addExports] caching exports for '%s'\n", filename.c_str());
#endif
exports[filename] = v8::Persistent<v8::Object>::New(obj);
}
/**
* Remove a cached exports object
*/
void Cache::removeExports(std::string filename) {
#ifdef VERBOSE
printf("[removeExports] removing exports for '%s'\n", filename.c_str());
#endif
ExportsValue::iterator it = exports.find(filename);
if (it != exports.end()) {
it->second.Dispose();
it->second.Clear();
exports.erase(it);
}
}
/**
* Remove all cached exports
*/
void Cache::clearExports() {
ExportsValue::iterator it;
for (it=exports.begin(); it != exports.end(); it++) {
it->second.Dispose();
it->second.Clear();
}
exports.clear();
}
<|endoftext|> |
<commit_before>#include "kerberos.h"
#include "kerberos_worker.h"
/// KerberosClient
Nan::Persistent<v8::Function> KerberosClient::constructor;
NAN_MODULE_INIT(KerberosClient::Init) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>();
tpl->SetClassName(Nan::New("KerberosClient").ToLocalChecked());
Nan::SetPrototypeMethod(tpl, "step", Step);
Nan::SetPrototypeMethod(tpl, "wrap", WrapData);
Nan::SetPrototypeMethod(tpl, "unwrap", UnwrapData);
v8::Local<v8::ObjectTemplate> itpl = tpl->InstanceTemplate();
itpl->SetInternalFieldCount(1);
Nan::SetAccessor(itpl, Nan::New("username").ToLocalChecked(), KerberosClient::UserNameGetter);
Nan::SetAccessor(itpl, Nan::New("response").ToLocalChecked(), KerberosClient::ResponseGetter);
Nan::SetAccessor(
itpl, Nan::New("responseConf").ToLocalChecked(), KerberosClient::ResponseConfGetter);
Nan::SetAccessor(
itpl, Nan::New("contextComplete").ToLocalChecked(), KerberosClient::ContextCompleteGetter);
constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked());
Nan::Set(target,
Nan::New("KerberosClient").ToLocalChecked(),
Nan::GetFunction(tpl).ToLocalChecked());
}
v8::Local<v8::Object> KerberosClient::NewInstance(krb_client_state* state) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Function> ctor = Nan::New<v8::Function>(KerberosClient::constructor);
v8::Local<v8::Object> object = Nan::NewInstance(ctor).ToLocalChecked();
KerberosClient* class_instance = new KerberosClient(state);
class_instance->Wrap(object);
return scope.Escape(object);
}
KerberosClient::KerberosClient(krb_client_state* state) : _state(state) {}
krb_client_state* KerberosClient::state() const {
return _state;
}
NAN_GETTER(KerberosClient::UserNameGetter) {
KerberosClient* client = Nan::ObjectWrap::Unwrap<KerberosClient>(info.This());
(client->state()->username == NULL)
? info.GetReturnValue().Set(Nan::Null())
: info.GetReturnValue().Set(Nan::New(client->state()->username).ToLocalChecked());
}
NAN_GETTER(KerberosClient::ResponseGetter) {
KerberosClient* client = Nan::ObjectWrap::Unwrap<KerberosClient>(info.This());
(client->state()->response == NULL)
? info.GetReturnValue().Set(Nan::Null())
: info.GetReturnValue().Set(Nan::New(client->state()->response).ToLocalChecked());
}
NAN_GETTER(KerberosClient::ResponseConfGetter) {
KerberosClient* client = Nan::ObjectWrap::Unwrap<KerberosClient>(info.This());
info.GetReturnValue().Set(Nan::New(client->state()->responseConf));
}
NAN_GETTER(KerberosClient::ContextCompleteGetter) {
KerberosClient* client = Nan::ObjectWrap::Unwrap<KerberosClient>(info.This());
info.GetReturnValue().Set(Nan::New(client->state()->context_complete));
}
/// KerberosServer
Nan::Persistent<v8::Function> KerberosServer::constructor;
NAN_MODULE_INIT(KerberosServer::Init) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>();
tpl->SetClassName(Nan::New("KerberosServer").ToLocalChecked());
Nan::SetPrototypeMethod(tpl, "step", Step);
v8::Local<v8::ObjectTemplate> itpl = tpl->InstanceTemplate();
itpl->SetInternalFieldCount(1);
Nan::SetAccessor(itpl, Nan::New("username").ToLocalChecked(), KerberosServer::UserNameGetter);
Nan::SetAccessor(itpl, Nan::New("response").ToLocalChecked(), KerberosServer::ResponseGetter);
Nan::SetAccessor(
itpl, Nan::New("targetName").ToLocalChecked(), KerberosServer::TargetNameGetter);
Nan::SetAccessor(
itpl, Nan::New("contextComplete").ToLocalChecked(), KerberosServer::ContextCompleteGetter);
constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked());
Nan::Set(target,
Nan::New("KerberosServer").ToLocalChecked(),
Nan::GetFunction(tpl).ToLocalChecked());
}
v8::Local<v8::Object> KerberosServer::NewInstance(krb_server_state* state) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Function> ctor = Nan::New<v8::Function>(KerberosServer::constructor);
v8::Local<v8::Object> object = Nan::NewInstance(ctor).ToLocalChecked();
KerberosServer* class_instance = new KerberosServer(state);
class_instance->Wrap(object);
return scope.Escape(object);
}
KerberosServer::KerberosServer(krb_server_state* state) : _state(state) {}
krb_server_state* KerberosServer::state() const {
return _state;
}
NAN_GETTER(KerberosServer::UserNameGetter) {
KerberosServer* server = Nan::ObjectWrap::Unwrap<KerberosServer>(info.This());
(server->_state->username == NULL)
? info.GetReturnValue().Set(Nan::Null())
: info.GetReturnValue().Set(Nan::New((char*)server->_state->username).ToLocalChecked());
}
NAN_GETTER(KerberosServer::ResponseGetter) {
KerberosServer* server = Nan::ObjectWrap::Unwrap<KerberosServer>(info.This());
(server->_state->response == NULL)
? info.GetReturnValue().Set(Nan::Null())
: info.GetReturnValue().Set(Nan::New((char*)server->_state->response).ToLocalChecked());
}
NAN_GETTER(KerberosServer::TargetNameGetter) {
KerberosServer* server = Nan::ObjectWrap::Unwrap<KerberosServer>(info.This());
(server->_state->targetname == NULL)
? info.GetReturnValue().Set(Nan::Null())
: info.GetReturnValue().Set(Nan::New((char*)server->_state->targetname).ToLocalChecked());
}
NAN_GETTER(KerberosServer::ContextCompleteGetter) {
KerberosServer* server = Nan::ObjectWrap::Unwrap<KerberosServer>(info.This());
info.GetReturnValue().Set(Nan::New(server->_state->context_complete));
}
NAN_METHOD(TestMethod) {
std::string string(*Nan::Utf8String(info[0]));
bool shouldError = info[1]->BooleanValue();
Nan::Callback* callback = new Nan::Callback(Nan::To<v8::Function>(info[2]).ToLocalChecked());
KerberosWorker::Run(callback, "kerberos:TestMethod", [=](KerberosWorker::SetOnFinishedHandler onFinished) {
return onFinished([=](KerberosWorker* worker) {
Nan::HandleScope scope;
if (shouldError) {
v8::Local<v8::Value> argv[] = {Nan::Error("an error occurred"), Nan::Null()};
worker->Call(2, argv);
} else {
v8::Local<v8::Value> argv[] = {Nan::Null(), Nan::Null()};
worker->Call(2, argv);
}
});
});
}
NAN_MODULE_INIT(Init) {
// Custom types
KerberosClient::Init(target);
KerberosServer::Init(target);
Nan::Set(target,
Nan::New("initializeClient").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(InitializeClient)).ToLocalChecked());
Nan::Set(target,
Nan::New("initializeServer").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(InitializeServer)).ToLocalChecked());
Nan::Set(target,
Nan::New("principalDetails").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(PrincipalDetails)).ToLocalChecked());
Nan::Set(target,
Nan::New("checkPassword").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(CheckPassword)).ToLocalChecked());
Nan::Set(target,
Nan::New("_testMethod").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(TestMethod)).ToLocalChecked());
}
NODE_MODULE(kerberos, Init)
<commit_msg>test(kerberos): modify `TestMethod` to test optional parameters<commit_after>#include "kerberos.h"
#include "kerberos_worker.h"
/// KerberosClient
Nan::Persistent<v8::Function> KerberosClient::constructor;
NAN_MODULE_INIT(KerberosClient::Init) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>();
tpl->SetClassName(Nan::New("KerberosClient").ToLocalChecked());
Nan::SetPrototypeMethod(tpl, "step", Step);
Nan::SetPrototypeMethod(tpl, "wrap", WrapData);
Nan::SetPrototypeMethod(tpl, "unwrap", UnwrapData);
v8::Local<v8::ObjectTemplate> itpl = tpl->InstanceTemplate();
itpl->SetInternalFieldCount(1);
Nan::SetAccessor(itpl, Nan::New("username").ToLocalChecked(), KerberosClient::UserNameGetter);
Nan::SetAccessor(itpl, Nan::New("response").ToLocalChecked(), KerberosClient::ResponseGetter);
Nan::SetAccessor(
itpl, Nan::New("responseConf").ToLocalChecked(), KerberosClient::ResponseConfGetter);
Nan::SetAccessor(
itpl, Nan::New("contextComplete").ToLocalChecked(), KerberosClient::ContextCompleteGetter);
constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked());
Nan::Set(target,
Nan::New("KerberosClient").ToLocalChecked(),
Nan::GetFunction(tpl).ToLocalChecked());
}
v8::Local<v8::Object> KerberosClient::NewInstance(krb_client_state* state) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Function> ctor = Nan::New<v8::Function>(KerberosClient::constructor);
v8::Local<v8::Object> object = Nan::NewInstance(ctor).ToLocalChecked();
KerberosClient* class_instance = new KerberosClient(state);
class_instance->Wrap(object);
return scope.Escape(object);
}
KerberosClient::KerberosClient(krb_client_state* state) : _state(state) {}
krb_client_state* KerberosClient::state() const {
return _state;
}
NAN_GETTER(KerberosClient::UserNameGetter) {
KerberosClient* client = Nan::ObjectWrap::Unwrap<KerberosClient>(info.This());
(client->state()->username == NULL)
? info.GetReturnValue().Set(Nan::Null())
: info.GetReturnValue().Set(Nan::New(client->state()->username).ToLocalChecked());
}
NAN_GETTER(KerberosClient::ResponseGetter) {
KerberosClient* client = Nan::ObjectWrap::Unwrap<KerberosClient>(info.This());
(client->state()->response == NULL)
? info.GetReturnValue().Set(Nan::Null())
: info.GetReturnValue().Set(Nan::New(client->state()->response).ToLocalChecked());
}
NAN_GETTER(KerberosClient::ResponseConfGetter) {
KerberosClient* client = Nan::ObjectWrap::Unwrap<KerberosClient>(info.This());
info.GetReturnValue().Set(Nan::New(client->state()->responseConf));
}
NAN_GETTER(KerberosClient::ContextCompleteGetter) {
KerberosClient* client = Nan::ObjectWrap::Unwrap<KerberosClient>(info.This());
info.GetReturnValue().Set(Nan::New(client->state()->context_complete));
}
/// KerberosServer
Nan::Persistent<v8::Function> KerberosServer::constructor;
NAN_MODULE_INIT(KerberosServer::Init) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>();
tpl->SetClassName(Nan::New("KerberosServer").ToLocalChecked());
Nan::SetPrototypeMethod(tpl, "step", Step);
v8::Local<v8::ObjectTemplate> itpl = tpl->InstanceTemplate();
itpl->SetInternalFieldCount(1);
Nan::SetAccessor(itpl, Nan::New("username").ToLocalChecked(), KerberosServer::UserNameGetter);
Nan::SetAccessor(itpl, Nan::New("response").ToLocalChecked(), KerberosServer::ResponseGetter);
Nan::SetAccessor(
itpl, Nan::New("targetName").ToLocalChecked(), KerberosServer::TargetNameGetter);
Nan::SetAccessor(
itpl, Nan::New("contextComplete").ToLocalChecked(), KerberosServer::ContextCompleteGetter);
constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked());
Nan::Set(target,
Nan::New("KerberosServer").ToLocalChecked(),
Nan::GetFunction(tpl).ToLocalChecked());
}
v8::Local<v8::Object> KerberosServer::NewInstance(krb_server_state* state) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Function> ctor = Nan::New<v8::Function>(KerberosServer::constructor);
v8::Local<v8::Object> object = Nan::NewInstance(ctor).ToLocalChecked();
KerberosServer* class_instance = new KerberosServer(state);
class_instance->Wrap(object);
return scope.Escape(object);
}
KerberosServer::KerberosServer(krb_server_state* state) : _state(state) {}
krb_server_state* KerberosServer::state() const {
return _state;
}
NAN_GETTER(KerberosServer::UserNameGetter) {
KerberosServer* server = Nan::ObjectWrap::Unwrap<KerberosServer>(info.This());
(server->_state->username == NULL)
? info.GetReturnValue().Set(Nan::Null())
: info.GetReturnValue().Set(Nan::New((char*)server->_state->username).ToLocalChecked());
}
NAN_GETTER(KerberosServer::ResponseGetter) {
KerberosServer* server = Nan::ObjectWrap::Unwrap<KerberosServer>(info.This());
(server->_state->response == NULL)
? info.GetReturnValue().Set(Nan::Null())
: info.GetReturnValue().Set(Nan::New((char*)server->_state->response).ToLocalChecked());
}
NAN_GETTER(KerberosServer::TargetNameGetter) {
KerberosServer* server = Nan::ObjectWrap::Unwrap<KerberosServer>(info.This());
(server->_state->targetname == NULL)
? info.GetReturnValue().Set(Nan::Null())
: info.GetReturnValue().Set(Nan::New((char*)server->_state->targetname).ToLocalChecked());
}
NAN_GETTER(KerberosServer::ContextCompleteGetter) {
KerberosServer* server = Nan::ObjectWrap::Unwrap<KerberosServer>(info.This());
info.GetReturnValue().Set(Nan::New(server->_state->context_complete));
}
NAN_METHOD(TestMethod) {
std::string string(*Nan::Utf8String(info[0]));
bool shouldError = info[1]->BooleanValue();
std::string optionalString;
Nan::Callback* callback;
if (info[2]->IsFunction()) {
callback = new Nan::Callback(Nan::To<v8::Function>(info[2]).ToLocalChecked());
} else {
optionalString = *Nan::Utf8String(info[2]);
callback = new Nan::Callback(Nan::To<v8::Function>(info[3]).ToLocalChecked());
}
KerberosWorker::Run(callback, "kerberos:TestMethod", [=](KerberosWorker::SetOnFinishedHandler onFinished) {
return onFinished([=](KerberosWorker* worker) {
Nan::HandleScope scope;
if (shouldError) {
v8::Local<v8::Value> argv[] = {Nan::Error("an error occurred"), Nan::Null()};
worker->Call(2, argv);
} else {
v8::Local<v8::Value> argv[] = {Nan::Null(), Nan::New(optionalString.c_str()).ToLocalChecked()};
worker->Call(2, argv);
}
});
});
}
NAN_MODULE_INIT(Init) {
// Custom types
KerberosClient::Init(target);
KerberosServer::Init(target);
Nan::Set(target,
Nan::New("initializeClient").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(InitializeClient)).ToLocalChecked());
Nan::Set(target,
Nan::New("initializeServer").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(InitializeServer)).ToLocalChecked());
Nan::Set(target,
Nan::New("principalDetails").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(PrincipalDetails)).ToLocalChecked());
Nan::Set(target,
Nan::New("checkPassword").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(CheckPassword)).ToLocalChecked());
Nan::Set(target,
Nan::New("_testMethod").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(TestMethod)).ToLocalChecked());
}
NODE_MODULE(kerberos, Init)
<|endoftext|> |
<commit_before>/*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLURL.hpp>
#include <xercesc/util/XMLNetAccessor.hpp>
#include <xercesc/util/BinInputStream.hpp>
#include <iostream>
XERCES_CPP_NAMESPACE_USE
inline XERCES_STD_QUALIFIER ostream& operator<<(XERCES_STD_QUALIFIER ostream& os, const XMLCh* xmlStr)
{
char* transcoded = XMLString::transcode(xmlStr);
os << transcoded;
XMLString::release(&transcoded);
return os;
}
void
exercise(BinInputStream& stream)
{
static float percents[] = { 1.0, 0.5, 0.25, 0.1, 0.15, 0.113, 0.333, 0.0015, 0.0013 };
int numPercents = sizeof(percents) / sizeof(float);
const unsigned int bufferMax = 4096;
XMLByte buffer[bufferMax];
int iteration = 0;
unsigned int bytesRead = 0;
do {
// Calculate a percentage of our maximum buffer size, going through
// them round-robin
float percent = percents[iteration % numPercents];
unsigned int bufCnt = (unsigned int)(bufferMax * percent);
// Check to make sure we didn't go out of bounds
if (bufCnt <= 0)
bufCnt = 1;
if (bufCnt > bufferMax)
bufCnt = bufferMax;
// Read bytes into our buffer
bytesRead = stream.readBytes(buffer, bufCnt);
//XERCES_STD_QUALIFIER cerr << "Read " << bytesRead << " bytes into a " << bufCnt << " byte buffer\n";
if (bytesRead > 0)
{
// Write the data to standard out
XERCES_STD_QUALIFIER cout.write((char*)buffer, bytesRead);
}
++iteration;
} while (bytesRead > 0);
}
// ---------------------------------------------------------------------------
// Program entry point
// ---------------------------------------------------------------------------
int
main(int argc, char** argv)
{
// Init the XML platform
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
XERCES_STD_QUALIFIER cout << "Error during platform init! Message:\n"
<< toCatch.getMessage() << XERCES_STD_QUALIFIER endl;
return 1;
}
// Look for our one and only parameter
if (argc != 2)
{
XERCES_STD_QUALIFIER cerr << "Usage: NetAccessorTest url\n"
"\n"
"This test reads data from the given url and writes the result\n"
"to standard output.\n"
"\n"
"A variety of buffer sizes is are used during the test.\n"
"\n"
;
exit(1);
}
// Get the URL
char* url = argv[1];
// Do the test
try
{
XMLURL xmlURL(url);
// Get the netaccessor
XMLNetAccessor* na = XMLPlatformUtils::fgNetAccessor;
if (na == 0)
{
XERCES_STD_QUALIFIER cerr << "No netaccessor is available. Aborting.\n";
exit(2);
}
// Build a binary input stream
BinInputStream* is = na->makeNew(xmlURL);
if (is == 0)
{
XERCES_STD_QUALIFIER cerr << "No binary input stream created. Aborting.\n";
exit(3);
}
// Exercise the inputstream
exercise(*is);
// Delete the is
delete is;
}
catch(const XMLException& toCatch)
{
XERCES_STD_QUALIFIER cout << "Exception during test:\n "
<< toCatch.getMessage()
<< XERCES_STD_QUALIFIER endl;
}
// And call the termination method
XMLPlatformUtils::Terminate();
return 0;
}
<commit_msg>Allow for old iostreams to be able to compile on some platforms.<commit_after>/*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLURL.hpp>
#include <xercesc/util/XMLNetAccessor.hpp>
#include <xercesc/util/BinInputStream.hpp>
#if defined(XERCES_NEW_IOSTREAMS)
#include <iostream>
#else
#include <iostream.h>
#endif
XERCES_CPP_NAMESPACE_USE
inline XERCES_STD_QUALIFIER ostream& operator<<(XERCES_STD_QUALIFIER ostream& os, const XMLCh* xmlStr)
{
char* transcoded = XMLString::transcode(xmlStr);
os << transcoded;
XMLString::release(&transcoded);
return os;
}
void
exercise(BinInputStream& stream)
{
static float percents[] = { 1.0, 0.5, 0.25, 0.1, 0.15, 0.113, 0.333, 0.0015, 0.0013 };
int numPercents = sizeof(percents) / sizeof(float);
const unsigned int bufferMax = 4096;
XMLByte buffer[bufferMax];
int iteration = 0;
unsigned int bytesRead = 0;
do {
// Calculate a percentage of our maximum buffer size, going through
// them round-robin
float percent = percents[iteration % numPercents];
unsigned int bufCnt = (unsigned int)(bufferMax * percent);
// Check to make sure we didn't go out of bounds
if (bufCnt <= 0)
bufCnt = 1;
if (bufCnt > bufferMax)
bufCnt = bufferMax;
// Read bytes into our buffer
bytesRead = stream.readBytes(buffer, bufCnt);
//XERCES_STD_QUALIFIER cerr << "Read " << bytesRead << " bytes into a " << bufCnt << " byte buffer\n";
if (bytesRead > 0)
{
// Write the data to standard out
XERCES_STD_QUALIFIER cout.write((char*)buffer, bytesRead);
}
++iteration;
} while (bytesRead > 0);
}
// ---------------------------------------------------------------------------
// Program entry point
// ---------------------------------------------------------------------------
int
main(int argc, char** argv)
{
// Init the XML platform
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
XERCES_STD_QUALIFIER cout << "Error during platform init! Message:\n"
<< toCatch.getMessage() << XERCES_STD_QUALIFIER endl;
return 1;
}
// Look for our one and only parameter
if (argc != 2)
{
XERCES_STD_QUALIFIER cerr << "Usage: NetAccessorTest url\n"
"\n"
"This test reads data from the given url and writes the result\n"
"to standard output.\n"
"\n"
"A variety of buffer sizes is are used during the test.\n"
"\n"
;
exit(1);
}
// Get the URL
char* url = argv[1];
// Do the test
try
{
XMLURL xmlURL(url);
// Get the netaccessor
XMLNetAccessor* na = XMLPlatformUtils::fgNetAccessor;
if (na == 0)
{
XERCES_STD_QUALIFIER cerr << "No netaccessor is available. Aborting.\n";
exit(2);
}
// Build a binary input stream
BinInputStream* is = na->makeNew(xmlURL);
if (is == 0)
{
XERCES_STD_QUALIFIER cerr << "No binary input stream created. Aborting.\n";
exit(3);
}
// Exercise the inputstream
exercise(*is);
// Delete the is
delete is;
}
catch(const XMLException& toCatch)
{
XERCES_STD_QUALIFIER cout << "Exception during test:\n "
<< toCatch.getMessage()
<< XERCES_STD_QUALIFIER endl;
}
// And call the termination method
XMLPlatformUtils::Terminate();
return 0;
}
<|endoftext|> |
<commit_before>/**
* toolchain-parallax_p8x32a
*
* Copyright 2017 Andrew Countryman <apcountryman@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* \file main.c
* \brief Blink C++ example program.
*/
#include <limits.h>
#include <propeller.h>
#include <stdint.h>
/**
* \brief A LED.
*/
class LED {
public:
/**
* \brief Acquire the pin resources associated with the LED, record their initial
* state, and drive the LED low.
*
* \param[in] pin The pin the LED is connected to. If pin is greater than 31, the
* LED will be non-responsive. Ideally this would result in an
* exception being thrown but that would result in the example being
* too large for the smaller memory models.
*/
LED( unsigned int const pin );
/**
* \brief Release the pin resources associated with the LED, restoring them to
* their prior state.
*/
~LED();
/**
* \brief Toggle the state of the LED.
*/
void toggle( void );
private:
/**
* \brief Default construction prohibited.
*/
LED();
/**
* \brief Copy construction prohibited.
*/
LED( LED const & led );
/**
* \brief Copy assignment prohibited.
*/
LED & operator=( LED const & led );
/**
* \brief Bit mask for interacting with the I/O registers.
*/
uint32_t const mask_;
/**
* \brief The state of the DIRA when it was acquired.
*/
uint32_t const dira_initial_;
/**
* \brief The state of the OUTA when it was acquired.
*/
uint32_t const outa_initial_;
};
LED::LED( unsigned int const pin ) :
mask_( 1 << pin ),
dira_initial_( DIRA ),
outa_initial_( OUTA )
{
// configure the pin as an output, initially driven low
OUTA &= ~mask_;
DIRA |= mask_;
return;
}
LED::~LED()
{
// restore the pin resources to their prior state
if ( dira_initial_ & mask_ ) { DIRA |= mask_; }
else { DIRA &= ~mask_; }
if ( outa_initial_ & mask_ ) { OUTA |= mask_; }
else { OUTA &= ~mask_; }
return;
}
void LED::toggle( void )
{
// toggle the state of the LED
OUTA ^= mask_;
return;
}
/**
* \brief Convert a period in milliseconds to a number of clock ticks.
*
* \param[in] ms The period, in milliseconds, to convert.
*
* \return The number of clock ticks in period.
*/
static uint32_t ms_to_ticks( unsigned int ms )
{
return ( CLKFREQ / 1000U ) * ms;
}
/**
* \brief Blink a LED.
*
* \param[in] led The LED to blink.
* \param[in] n The number of times to blink the LED. If n is 0, the LED will be blinked
* infinitely. If n is greater than UINT_MAX / 2, no LED will be blinked.
* \param[in] period The blinking period in milliseconds. If period is less than 2, no LED
* will be blinked.
*/
static void blink( LED & led, unsigned int n, unsigned int period )
{
// ensure function pre-conditions are met
bool error = n > UINT_MAX / 2 ? true
: period < 2 ? true
: false;
if ( error ) { return; }
// initialize the timing parameters
uint32_t const half_period_ticks = ms_to_ticks( period / 2 );
uint32_t next_cnt = half_period_ticks + CNT;
// blink the LED
for ( unsigned int i = 0; n == 0 || i < 2 * n; ++i ) {
// wait half a period
next_cnt = waitcnt2( next_cnt, half_period_ticks );
// toggle the state of the LED
led.toggle();
} // for
return;
}
/**
* \brief Main loop.
*
* \return N/A, enters an infinite loop once blinking is complete.
*/
int main( void )
{
// create a new scope so that the LED will be destructed when no longer needed
{
// create and configure the LED
LED led( BLINK_PIN );
// blink the LED
blink( led, BLINK_CNT, BLINK_PERIOD );
}
// infinite loop
for ( ;; ) {}
return 0;
}
<commit_msg>Update C++ blink example to use some C++11 features<commit_after>/**
* toolchain-parallax_p8x32a
*
* Copyright 2017 Andrew Countryman <apcountryman@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* \file main.c
* \brief Blink C++ example program.
*/
#include <limits.h>
#include <propeller.h>
#include <stdint.h>
/**
* \brief A LED.
*/
class LED {
public:
/**
* \brief Acquire the pin resources associated with the LED, record their initial
* state, and drive the LED low.
*
* \param[in] pin The pin the LED is connected to. If pin is greater than 31, the
* LED will be non-responsive. Ideally this would result in an
* exception being thrown but that would result in the example being
* too large for the smaller memory models.
*/
LED( unsigned int const pin );
/**
* \brief Release the pin resources associated with the LED, restoring them to
* their prior state.
*/
~LED();
/**
* \brief Copy construction prohibited.
*/
LED( LED const & ) = delete;
/**
* \brief Copy assignment prohibited.
*/
LED & operator=( LED const & ) = delete;
/**
* \brief Move construction prohibited.
*/
LED( LED && ) = delete;
/**
* \brief Move assignment prohibited.
*/
LED & operator=( LED && ) = delete;
/**
* \brief Toggle the state of the LED.
*/
void toggle( void );
private:
/**
* \brief Bit mask for interacting with the I/O registers.
*/
uint32_t const mask_;
/**
* \brief The state of the DIRA when it was acquired.
*/
uint32_t const dira_initial_;
/**
* \brief The state of the OUTA when it was acquired.
*/
uint32_t const outa_initial_;
};
LED::LED( unsigned int const pin ) :
mask_( 1 << pin ),
dira_initial_( DIRA ),
outa_initial_( OUTA )
{
// configure the pin as an output, initially driven low
OUTA &= ~mask_;
DIRA |= mask_;
return;
}
LED::~LED()
{
// restore the pin resources to their prior state
if ( dira_initial_ & mask_ ) { DIRA |= mask_; }
else { DIRA &= ~mask_; }
if ( outa_initial_ & mask_ ) { OUTA |= mask_; }
else { OUTA &= ~mask_; }
return;
}
void LED::toggle( void )
{
// toggle the state of the LED
OUTA ^= mask_;
return;
}
/**
* \brief Convert a period in milliseconds to a number of clock ticks.
*
* \param[in] ms The period, in milliseconds, to convert.
*
* \return The number of clock ticks in period.
*/
static uint32_t ms_to_ticks( unsigned int ms )
{
return ( CLKFREQ / 1000U ) * ms;
}
/**
* \brief Blink a LED.
*
* \param[in] led The LED to blink.
* \param[in] n The number of times to blink the LED. If n is 0, the LED will be blinked
* infinitely. If n is greater than UINT_MAX / 2, no LED will be blinked.
* \param[in] period The blinking period in milliseconds. If period is less than 2, no LED
* will be blinked.
*/
static void blink( LED & led, unsigned int n, unsigned int period )
{
// ensure function pre-conditions are met
bool error = n > UINT_MAX / 2 ? true
: period < 2 ? true
: false;
if ( error ) { return; }
// initialize the timing parameters
uint32_t const half_period_ticks = ms_to_ticks( period / 2 );
uint32_t next_cnt = half_period_ticks + CNT;
// blink the LED
for ( unsigned int i = 0; n == 0 || i < 2 * n; ++i ) {
// wait half a period
next_cnt = waitcnt2( next_cnt, half_period_ticks );
// toggle the state of the LED
led.toggle();
} // for
return;
}
/**
* \brief Main loop.
*
* \return N/A, enters an infinite loop once blinking is complete.
*/
int main( void )
{
// create a new scope so that the LED will be destructed when no longer needed
{
// create and configure the LED
LED led( BLINK_PIN );
// blink the LED
blink( led, BLINK_CNT, BLINK_PERIOD );
}
// infinite loop
for ( ;; ) {}
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef AGG_RENDERER_HPP
#define AGG_RENDERER_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/feature_style_processor.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/label_collision_detector.hpp>
#include <mapnik/placement_finder.hpp>
#include <mapnik/map.hpp>
// agg
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
// boost
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
namespace mapnik {
template <typename T>
class MAPNIK_DECL agg_renderer : public feature_style_processor<agg_renderer<T> >,
private boost::noncopyable
{
public:
agg_renderer(Map const& m, T & pixmap, unsigned offset_x=0, unsigned offset_y=0);
void start_map_processing(Map const& map);
void end_map_processing(Map const& map);
void start_layer_processing(Layer const& lay);
void end_layer_processing(Layer const& lay);
void process(point_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(line_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(line_pattern_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(polygon_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(polygon_pattern_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(raster_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(shield_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(text_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(building_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
private:
T & pixmap_;
unsigned width_;
unsigned height_;
agg::row_ptr_cache<agg::int8u> buf_;
agg::pixfmt_rgba32 pixf_;
CoordTransform t_;
freetype_engine font_engine_;
face_manager<freetype_engine> font_manager_;
label_collision_detector4 detector_;
placement_finder<label_collision_detector4> finder_;
agg::rasterizer_scanline_aa<> ras_;
};
}
#endif //AGG_RENDERER_HPP
<commit_msg> - fixed agg-2.5 build<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef AGG_RENDERER_HPP
#define AGG_RENDERER_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/feature_style_processor.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/label_collision_detector.hpp>
#include <mapnik/placement_finder.hpp>
#include <mapnik/map.hpp>
// agg
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
// boost
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
namespace mapnik {
template <typename T>
class MAPNIK_DECL agg_renderer : public feature_style_processor<agg_renderer<T> >,
private boost::noncopyable
{
public:
agg_renderer(Map const& m, T & pixmap, unsigned offset_x=0, unsigned offset_y=0);
void start_map_processing(Map const& map);
void end_map_processing(Map const& map);
void start_layer_processing(Layer const& lay);
void end_layer_processing(Layer const& lay);
void process(point_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(line_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(line_pattern_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(polygon_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(polygon_pattern_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(raster_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(shield_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(text_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
void process(building_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans);
private:
T & pixmap_;
unsigned width_;
unsigned height_;
agg::rendering_buffer buf_;
agg::pixfmt_rgba32 pixf_;
CoordTransform t_;
freetype_engine font_engine_;
face_manager<freetype_engine> font_manager_;
label_collision_detector4 detector_;
placement_finder<label_collision_detector4> finder_;
agg::rasterizer_scanline_aa<> ras_;
};
}
#endif //AGG_RENDERER_HPP
<|endoftext|> |
<commit_before>//!
//! termcolor
//! ~~~~~~~~~
//!
//! termcolor is a header-only c++ library for printing colored messages
//! to the terminal. Written just for fun with a help of the Force.
//!
//! :copyright: (c) 2013 by Igor Kalnitsky
//! :license: BSD, see LICENSE for details
//!
#ifndef TERMCOLOR_HPP_
#define TERMCOLOR_HPP_
// the following snippet of code detects the current OS and
// defines the appropriate macro that is used to wrap some
// platform specific things
#if defined(_WIN32) || defined(_WIN64)
# define OS_WINDOWS
#elif defined(__APPLE__)
# define OS_MACOS
#elif defined(linux) || defined(__linux) || defined(__CYGWIN__)
# define OS_LINUX
#else
# error unsupported platform
#endif
// This headers provides the `isatty()`/`fileno()` functions,
// which are used for testing whether a standart stream refers
// to the terminal. As for Windows, we also need WinApi funcs
// for changing colors attributes of the terminal.
#if defined(OS_MACOS) || defined(OS_LINUX)
# include <unistd.h>
#elif defined(OS_WINDOWS)
# include <io.h>
# include <windows.h>
#endif
#include <iostream>
#include <cstdio>
namespace termcolor
{
// Forward declaration of the `__internal` namespace.
// All comments are below.
namespace __internal
{
inline FILE* get_standard_stream(const std::ostream& stream);
inline bool is_atty(const std::ostream& stream);
#if defined(OS_WINDOWS)
void win_change_attributes(std::ostream& stream, int foreground, int background=-1);
#endif
}
inline
std::ostream& reset(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[00m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1, -1);
#endif
}
return stream;
}
inline
std::ostream& bold(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[1m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& dark(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[2m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& underline(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[4m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& blink(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[5m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& reverse(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[7m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& concealed(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[8m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& grey(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[30m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
0 // grey (black)
);
#endif
}
return stream;
}
inline
std::ostream& red(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[31m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& green(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[32m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_GREEN
);
#endif
}
return stream;
}
inline
std::ostream& yellow(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[33m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_GREEN | FOREGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& blue(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[34m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_BLUE
);
#endif
}
return stream;
}
inline
std::ostream& magenta(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[35m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& cyan(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[36m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_GREEN
);
#endif
}
return stream;
}
inline
std::ostream& white(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[37m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& on_grey(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[40m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
0 // grey (black)
);
#endif
}
return stream;
}
inline
std::ostream& on_red(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[41m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& on_green(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[42m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN
);
#endif
}
return stream;
}
inline
std::ostream& on_yellow(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[43m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& on_blue(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[44m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_BLUE
);
#endif
}
return stream;
}
inline
std::ostream& on_magenta(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[45m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_BLUE | BACKGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& on_cyan(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[46m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_BLUE
);
#endif
}
return stream;
}
inline
std::ostream& on_white(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[47m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_RED
);
#endif
}
return stream;
}
//! Since C++ hasn't a way to hide something in the header from
//! the outer access, I have to introduce this namespace which
//! is used for internal purpose and should't be access from
//! the user code.
namespace __internal
{
//! Since C++ hasn't a true way to extract stream handler
//! from the a given `std::ostream` object, I have to write
//! this kind of hack.
inline
FILE* get_standard_stream(const std::ostream& stream)
{
if (&stream == &std::cout)
return stdout;
else if ((&stream == &std::cerr) || (&stream == &std::clog))
return stderr;
return nullptr;
}
//! Test whether a given `std::ostream` object refers to
//! a terminal.
inline
bool is_atty(const std::ostream& stream)
{
FILE* std_stream = get_standard_stream(stream);
#if defined(OS_MACOS) || defined(OS_LINUX)
return ::isatty(fileno(std_stream));
#elif defined(OS_WINDOWS)
return ::_isatty(_fileno(std_stream));
#endif
}
#if defined(OS_WINDOWS)
//! Change Windows Terminal colors attribute. If some
//! parameter is `-1` then attribute won't changed.
void win_change_attributes(std::ostream& stream, int foreground, int background)
{
// yeah, i know.. it's ugly, it's windows.
static WORD defaultAttributes = 0;
// get terminal handle
HANDLE hTerminal = INVALID_HANDLE_VALUE;
if (&stream == &std::cout)
hTerminal = GetStdHandle(STD_OUTPUT_HANDLE);
else if (&stream == &std::cerr)
hTerminal = GetStdHandle(STD_ERROR_HANDLE);
// save default terminal attributes if it unsaved
if (!defaultAttributes)
{
CONSOLE_SCREEN_BUFFER_INFO info;
if (!GetConsoleScreenBufferInfo(hTerminal, &info))
return;
defaultAttributes = info.wAttributes;
}
// restore all default settings
if (foreground == -1 && background == -1)
{
SetConsoleTextAttribute(hTerminal, defaultAttributes);
return;
}
// get current settings
CONSOLE_SCREEN_BUFFER_INFO info;
if (!GetConsoleScreenBufferInfo(hTerminal, &info))
return;
if (foreground != -1)
{
info.wAttributes &= ~(info.wAttributes & 0x0F);
info.wAttributes |= static_cast<WORD>(foreground);
}
if (background != -1)
{
info.wAttributes &= ~(info.wAttributes & 0xF0);
info.wAttributes |= static_cast<WORD>(background);
}
SetConsoleTextAttribute(hTerminal, info.wAttributes);
}
#endif // OS_WINDOWS
} // namespace __internal
} // namespace termcolor
#undef OS_WINDOWS
#undef OS_MACOS
#undef OS_LINUX
#endif // TERMCOLOR_HPP_
<commit_msg>Unified support for UNIXes.<commit_after>//!
//! termcolor
//! ~~~~~~~~~
//!
//! termcolor is a header-only c++ library for printing colored messages
//! to the terminal. Written just for fun with a help of the Force.
//!
//! :copyright: (c) 2013 by Igor Kalnitsky
//! :license: BSD, see LICENSE for details
//!
#ifndef TERMCOLOR_HPP_
#define TERMCOLOR_HPP_
// the following snippet of code detects the current OS and
// defines the appropriate macro that is used to wrap some
// platform specific things
#if defined(_WIN32) || defined(_WIN64)
# define OS_WINDOWS
#elif defined(__APPLE__)
# define OS_MACOS
#elif defined(__unix__) || defined(__unix)
# define OS_LINUX
#else
# error unsupported platform
#endif
// This headers provides the `isatty()`/`fileno()` functions,
// which are used for testing whether a standart stream refers
// to the terminal. As for Windows, we also need WinApi funcs
// for changing colors attributes of the terminal.
#if defined(OS_MACOS) || defined(OS_LINUX)
# include <unistd.h>
#elif defined(OS_WINDOWS)
# include <io.h>
# include <windows.h>
#endif
#include <iostream>
#include <cstdio>
namespace termcolor
{
// Forward declaration of the `__internal` namespace.
// All comments are below.
namespace __internal
{
inline FILE* get_standard_stream(const std::ostream& stream);
inline bool is_atty(const std::ostream& stream);
#if defined(OS_WINDOWS)
void win_change_attributes(std::ostream& stream, int foreground, int background=-1);
#endif
}
inline
std::ostream& reset(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[00m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1, -1);
#endif
}
return stream;
}
inline
std::ostream& bold(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[1m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& dark(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[2m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& underline(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[4m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& blink(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[5m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& reverse(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[7m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& concealed(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[8m";
#elif defined(OS_WINDOWS)
#endif
}
return stream;
}
inline
std::ostream& grey(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[30m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
0 // grey (black)
);
#endif
}
return stream;
}
inline
std::ostream& red(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[31m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& green(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[32m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_GREEN
);
#endif
}
return stream;
}
inline
std::ostream& yellow(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[33m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_GREEN | FOREGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& blue(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[34m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_BLUE
);
#endif
}
return stream;
}
inline
std::ostream& magenta(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[35m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& cyan(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[36m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_GREEN
);
#endif
}
return stream;
}
inline
std::ostream& white(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[37m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& on_grey(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[40m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
0 // grey (black)
);
#endif
}
return stream;
}
inline
std::ostream& on_red(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[41m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& on_green(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[42m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN
);
#endif
}
return stream;
}
inline
std::ostream& on_yellow(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[43m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& on_blue(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[44m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_BLUE
);
#endif
}
return stream;
}
inline
std::ostream& on_magenta(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[45m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_BLUE | BACKGROUND_RED
);
#endif
}
return stream;
}
inline
std::ostream& on_cyan(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[46m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_BLUE
);
#endif
}
return stream;
}
inline
std::ostream& on_white(std::ostream& stream)
{
if (__internal::is_atty(stream))
{
#if defined(OS_MACOS) || defined(OS_LINUX)
stream << "\033[47m";
#elif defined(OS_WINDOWS)
__internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_RED
);
#endif
}
return stream;
}
//! Since C++ hasn't a way to hide something in the header from
//! the outer access, I have to introduce this namespace which
//! is used for internal purpose and should't be access from
//! the user code.
namespace __internal
{
//! Since C++ hasn't a true way to extract stream handler
//! from the a given `std::ostream` object, I have to write
//! this kind of hack.
inline
FILE* get_standard_stream(const std::ostream& stream)
{
if (&stream == &std::cout)
return stdout;
else if ((&stream == &std::cerr) || (&stream == &std::clog))
return stderr;
return nullptr;
}
//! Test whether a given `std::ostream` object refers to
//! a terminal.
inline
bool is_atty(const std::ostream& stream)
{
FILE* std_stream = get_standard_stream(stream);
#if defined(OS_MACOS) || defined(OS_LINUX)
return ::isatty(fileno(std_stream));
#elif defined(OS_WINDOWS)
return ::_isatty(_fileno(std_stream));
#endif
}
#if defined(OS_WINDOWS)
//! Change Windows Terminal colors attribute. If some
//! parameter is `-1` then attribute won't changed.
void win_change_attributes(std::ostream& stream, int foreground, int background)
{
// yeah, i know.. it's ugly, it's windows.
static WORD defaultAttributes = 0;
// get terminal handle
HANDLE hTerminal = INVALID_HANDLE_VALUE;
if (&stream == &std::cout)
hTerminal = GetStdHandle(STD_OUTPUT_HANDLE);
else if (&stream == &std::cerr)
hTerminal = GetStdHandle(STD_ERROR_HANDLE);
// save default terminal attributes if it unsaved
if (!defaultAttributes)
{
CONSOLE_SCREEN_BUFFER_INFO info;
if (!GetConsoleScreenBufferInfo(hTerminal, &info))
return;
defaultAttributes = info.wAttributes;
}
// restore all default settings
if (foreground == -1 && background == -1)
{
SetConsoleTextAttribute(hTerminal, defaultAttributes);
return;
}
// get current settings
CONSOLE_SCREEN_BUFFER_INFO info;
if (!GetConsoleScreenBufferInfo(hTerminal, &info))
return;
if (foreground != -1)
{
info.wAttributes &= ~(info.wAttributes & 0x0F);
info.wAttributes |= static_cast<WORD>(foreground);
}
if (background != -1)
{
info.wAttributes &= ~(info.wAttributes & 0xF0);
info.wAttributes |= static_cast<WORD>(background);
}
SetConsoleTextAttribute(hTerminal, info.wAttributes);
}
#endif // OS_WINDOWS
} // namespace __internal
} // namespace termcolor
#undef OS_WINDOWS
#undef OS_MACOS
#undef OS_LINUX
#endif // TERMCOLOR_HPP_
<|endoftext|> |
<commit_before>/*
* The main source of the Beng proxy server.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "tpool.h"
#include "direct.h"
#include "lb_instance.hxx"
#include "lb_setup.hxx"
#include "lb_connection.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "hstock.hxx"
#include "stock.hxx"
#include "failure.hxx"
#include "bulldog.h"
#include "balancer.hxx"
#include "pipe_stock.hxx"
#include "log-glue.h"
#include "lb_config.hxx"
#include "lb_hmonitor.hxx"
#include "ssl_init.hxx"
#include "child_manager.hxx"
#include "thread_pool.hxx"
#include "fb_pool.hxx"
#include "capabilities.hxx"
#include "isolate.hxx"
#include "util/Error.hxx"
#include <daemon/log.h>
#include <daemon/daemonize.h>
#include <assert.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <pthread.h>
#ifdef __linux
#include <sys/prctl.h>
#ifndef PR_SET_NO_NEW_PRIVS
#define PR_SET_NO_NEW_PRIVS 38
#endif
#endif
#include <event.h>
static constexpr cap_value_t cap_keep_list[1] = {
/* keep the NET_RAW capability to be able to to use the socket
option IP_TRANSPARENT */
CAP_NET_RAW,
};
static constexpr struct timeval launch_worker_now = {
0,
10000,
};
static constexpr struct timeval launch_worker_delayed = {
10,
0,
};
static bool is_watchdog;
static pid_t worker_pid;
static struct event launch_worker_event;
static void
worker_callback(int status, void *ctx)
{
struct lb_instance *instance = (struct lb_instance *)ctx;
int exit_status = WEXITSTATUS(status);
if (WIFSIGNALED(status))
fprintf(stderr, "worker %d died from signal %d%s\n",
worker_pid, WTERMSIG(status),
WCOREDUMP(status) ? " (core dumped)" : "");
else if (exit_status == 0)
fprintf(stderr, "worker %d exited with success\n",
worker_pid);
else
fprintf(stderr, "worker %d exited with status %d\n",
worker_pid, exit_status);
worker_pid = 0;
if (!instance->should_exit)
evtimer_add(&launch_worker_event, &launch_worker_delayed);
}
static void
launch_worker_callback(int fd gcc_unused, short event gcc_unused,
void *ctx)
{
assert(is_watchdog);
assert(worker_pid <= 0);
struct lb_instance *instance = (struct lb_instance *)ctx;
/* in libevent 2.0.16, it is necessary to re-add all EV_SIGNAL
events after forking; this bug is not present in 1.4.13 and
2.0.19 */
deinit_signals(instance);
children_event_del();
worker_pid = fork();
if (worker_pid < 0) {
fprintf(stderr, "Failed to fork: %s\n", strerror(errno));
init_signals(instance);
children_event_add();
evtimer_add(&launch_worker_event, &launch_worker_delayed);
return;
}
if (worker_pid == 0) {
event_reinit(instance->event_base);
init_signals(instance);
children_init();
all_listeners_event_add(instance);
enable_all_controls(instance);
/* run monitors only in the worker process */
lb_hmonitor_enable();
return;
}
init_signals(instance);
children_event_add();
child_register(worker_pid, "worker", worker_callback, instance);
}
static void
shutdown_callback(void *ctx)
{
struct lb_instance *instance = (struct lb_instance *)ctx;
if (instance->should_exit)
return;
instance->should_exit = true;
deinit_signals(instance);
thread_pool_stop();
if (is_watchdog && worker_pid > 0)
kill(worker_pid, SIGTERM);
children_shutdown();
thread_pool_join();
thread_pool_deinit();
if (is_watchdog)
evtimer_del(&launch_worker_event);
deinit_all_controls(instance);
while (!instance->connections.empty())
lb_connection_close(&instance->connections.front());
deinit_all_listeners(instance);
lb_hmonitor_deinit();
pool_commit();
if (instance->tcp_stock != nullptr)
hstock_free(instance->tcp_stock);
if (instance->balancer != nullptr)
balancer_free(instance->balancer);
if (instance->pipe_stock != nullptr)
stock_free(instance->pipe_stock);
fb_pool_disable();
pool_commit();
}
static void
reload_event_callback(int fd gcc_unused, short event gcc_unused,
void *ctx)
{
struct lb_instance *instance = (struct lb_instance *)ctx;
daemonize_reopen_logfile();
unsigned n_ssl_sessions = instance->FlushSSLSessionCache(LONG_MAX);
daemon_log(3, "flushed %u SSL sessions\n", n_ssl_sessions);
fb_pool_compress();
}
void
init_signals(struct lb_instance *instance)
{
signal(SIGPIPE, SIG_IGN);
shutdown_listener_init(&instance->shutdown_listener,
shutdown_callback, instance);
event_set(&instance->sighup_event, SIGHUP, EV_SIGNAL|EV_PERSIST,
reload_event_callback, instance);
event_add(&instance->sighup_event, nullptr);
}
void
deinit_signals(struct lb_instance *instance)
{
shutdown_listener_deinit(&instance->shutdown_listener);
event_del(&instance->sighup_event);
}
int main(int argc, char **argv)
{
Error error2;
int ret;
int gcc_unused ref;
static struct lb_instance instance;
#ifdef HAVE_OLD_GTHREAD
/* deprecated in GLib 2.32 */
g_thread_init(nullptr);
#endif
instance.pool = pool_new_libc(nullptr, "global");
tpool_init(instance.pool);
/* configuration */
parse_cmdline(&instance.cmdline, instance.pool, argc, argv);
GError *error = nullptr;
instance.config = lb_config_load(instance.pool,
instance.cmdline.config_path,
&error);
if (instance.config == nullptr) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
return EXIT_FAILURE;
}
if (instance.cmdline.check)
return EXIT_SUCCESS;
/* initialize */
lb_hmonitor_init(instance.pool);
ssl_global_init();
direct_global_init();
instance.event_base = event_init();
fb_pool_init(true);
init_signals(&instance);
/* reduce glibc's thread cancellation overhead */
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr);
children_init();
instance.balancer = balancer_new(*instance.pool);
instance.tcp_stock = tcp_stock_new(instance.pool,
instance.cmdline.tcp_stock_limit);
instance.tcp_balancer = tcp_balancer_new(instance.pool, instance.tcp_stock,
instance.balancer);
instance.pipe_stock = pipe_stock_new(instance.pool);
failure_init();
bulldog_init(instance.cmdline.bulldog_path);
if (!init_all_controls(&instance, &error)) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
return EXIT_FAILURE;
}
if (!init_all_listeners(instance, error2)) {
deinit_all_controls(&instance);
fprintf(stderr, "%s\n", error2.GetMessage());
return EXIT_FAILURE;
}
/* daemonize */
ret = daemonize();
if (ret < 0)
exit(2);
/* launch the access logger */
if (!log_global_init(instance.cmdline.access_logger))
return EXIT_FAILURE;
/* daemonize II */
if (daemon_user_defined(&instance.cmdline.user))
capabilities_pre_setuid();
if (daemon_user_set(&instance.cmdline.user) < 0)
return EXIT_FAILURE;
isolate_from_filesystem();
if (daemon_user_defined(&instance.cmdline.user))
capabilities_post_setuid(cap_keep_list, G_N_ELEMENTS(cap_keep_list));
#ifdef __linux
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
#endif
/* main loop */
if (instance.cmdline.watchdog) {
/* watchdog */
all_listeners_event_del(&instance);
is_watchdog = true;
evtimer_set(&launch_worker_event, launch_worker_callback, &instance);
evtimer_add(&launch_worker_event, &launch_worker_now);
} else {
/* this is already the worker process: enable monitors here */
lb_hmonitor_enable();
}
event_dispatch();
/* cleanup */
children_shutdown();
log_global_deinit();
bulldog_deinit();
failure_deinit();
deinit_all_listeners(&instance);
deinit_all_controls(&instance);
fb_pool_deinit();
event_base_free(instance.event_base);
tpool_deinit();
delete instance.config;
ref = pool_unref(instance.pool);
assert(ref == 0);
pool_commit();
pool_recycler_clear();
ssl_global_deinit();
daemonize_cleanup();
direct_global_deinit();
}
<commit_msg>lb_main: make "instance" non-static<commit_after>/*
* The main source of the Beng proxy server.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "tpool.h"
#include "direct.h"
#include "lb_instance.hxx"
#include "lb_setup.hxx"
#include "lb_connection.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "hstock.hxx"
#include "stock.hxx"
#include "failure.hxx"
#include "bulldog.h"
#include "balancer.hxx"
#include "pipe_stock.hxx"
#include "log-glue.h"
#include "lb_config.hxx"
#include "lb_hmonitor.hxx"
#include "ssl_init.hxx"
#include "child_manager.hxx"
#include "thread_pool.hxx"
#include "fb_pool.hxx"
#include "capabilities.hxx"
#include "isolate.hxx"
#include "util/Error.hxx"
#include <daemon/log.h>
#include <daemon/daemonize.h>
#include <assert.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <pthread.h>
#ifdef __linux
#include <sys/prctl.h>
#ifndef PR_SET_NO_NEW_PRIVS
#define PR_SET_NO_NEW_PRIVS 38
#endif
#endif
#include <event.h>
static constexpr cap_value_t cap_keep_list[1] = {
/* keep the NET_RAW capability to be able to to use the socket
option IP_TRANSPARENT */
CAP_NET_RAW,
};
static constexpr struct timeval launch_worker_now = {
0,
10000,
};
static constexpr struct timeval launch_worker_delayed = {
10,
0,
};
static bool is_watchdog;
static pid_t worker_pid;
static struct event launch_worker_event;
static void
worker_callback(int status, void *ctx)
{
struct lb_instance *instance = (struct lb_instance *)ctx;
int exit_status = WEXITSTATUS(status);
if (WIFSIGNALED(status))
fprintf(stderr, "worker %d died from signal %d%s\n",
worker_pid, WTERMSIG(status),
WCOREDUMP(status) ? " (core dumped)" : "");
else if (exit_status == 0)
fprintf(stderr, "worker %d exited with success\n",
worker_pid);
else
fprintf(stderr, "worker %d exited with status %d\n",
worker_pid, exit_status);
worker_pid = 0;
if (!instance->should_exit)
evtimer_add(&launch_worker_event, &launch_worker_delayed);
}
static void
launch_worker_callback(int fd gcc_unused, short event gcc_unused,
void *ctx)
{
assert(is_watchdog);
assert(worker_pid <= 0);
struct lb_instance *instance = (struct lb_instance *)ctx;
/* in libevent 2.0.16, it is necessary to re-add all EV_SIGNAL
events after forking; this bug is not present in 1.4.13 and
2.0.19 */
deinit_signals(instance);
children_event_del();
worker_pid = fork();
if (worker_pid < 0) {
fprintf(stderr, "Failed to fork: %s\n", strerror(errno));
init_signals(instance);
children_event_add();
evtimer_add(&launch_worker_event, &launch_worker_delayed);
return;
}
if (worker_pid == 0) {
event_reinit(instance->event_base);
init_signals(instance);
children_init();
all_listeners_event_add(instance);
enable_all_controls(instance);
/* run monitors only in the worker process */
lb_hmonitor_enable();
return;
}
init_signals(instance);
children_event_add();
child_register(worker_pid, "worker", worker_callback, instance);
}
static void
shutdown_callback(void *ctx)
{
struct lb_instance *instance = (struct lb_instance *)ctx;
if (instance->should_exit)
return;
instance->should_exit = true;
deinit_signals(instance);
thread_pool_stop();
if (is_watchdog && worker_pid > 0)
kill(worker_pid, SIGTERM);
children_shutdown();
thread_pool_join();
thread_pool_deinit();
if (is_watchdog)
evtimer_del(&launch_worker_event);
deinit_all_controls(instance);
while (!instance->connections.empty())
lb_connection_close(&instance->connections.front());
deinit_all_listeners(instance);
lb_hmonitor_deinit();
pool_commit();
if (instance->tcp_stock != nullptr)
hstock_free(instance->tcp_stock);
if (instance->balancer != nullptr)
balancer_free(instance->balancer);
if (instance->pipe_stock != nullptr)
stock_free(instance->pipe_stock);
fb_pool_disable();
pool_commit();
}
static void
reload_event_callback(int fd gcc_unused, short event gcc_unused,
void *ctx)
{
struct lb_instance *instance = (struct lb_instance *)ctx;
daemonize_reopen_logfile();
unsigned n_ssl_sessions = instance->FlushSSLSessionCache(LONG_MAX);
daemon_log(3, "flushed %u SSL sessions\n", n_ssl_sessions);
fb_pool_compress();
}
void
init_signals(struct lb_instance *instance)
{
signal(SIGPIPE, SIG_IGN);
shutdown_listener_init(&instance->shutdown_listener,
shutdown_callback, instance);
event_set(&instance->sighup_event, SIGHUP, EV_SIGNAL|EV_PERSIST,
reload_event_callback, instance);
event_add(&instance->sighup_event, nullptr);
}
void
deinit_signals(struct lb_instance *instance)
{
shutdown_listener_deinit(&instance->shutdown_listener);
event_del(&instance->sighup_event);
}
int main(int argc, char **argv)
{
Error error2;
int ret;
int gcc_unused ref;
struct lb_instance instance;
#ifdef HAVE_OLD_GTHREAD
/* deprecated in GLib 2.32 */
g_thread_init(nullptr);
#endif
instance.pool = pool_new_libc(nullptr, "global");
tpool_init(instance.pool);
/* configuration */
parse_cmdline(&instance.cmdline, instance.pool, argc, argv);
GError *error = nullptr;
instance.config = lb_config_load(instance.pool,
instance.cmdline.config_path,
&error);
if (instance.config == nullptr) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
return EXIT_FAILURE;
}
if (instance.cmdline.check)
return EXIT_SUCCESS;
/* initialize */
lb_hmonitor_init(instance.pool);
ssl_global_init();
direct_global_init();
instance.event_base = event_init();
fb_pool_init(true);
init_signals(&instance);
/* reduce glibc's thread cancellation overhead */
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr);
children_init();
instance.balancer = balancer_new(*instance.pool);
instance.tcp_stock = tcp_stock_new(instance.pool,
instance.cmdline.tcp_stock_limit);
instance.tcp_balancer = tcp_balancer_new(instance.pool, instance.tcp_stock,
instance.balancer);
instance.pipe_stock = pipe_stock_new(instance.pool);
failure_init();
bulldog_init(instance.cmdline.bulldog_path);
if (!init_all_controls(&instance, &error)) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
return EXIT_FAILURE;
}
if (!init_all_listeners(instance, error2)) {
deinit_all_controls(&instance);
fprintf(stderr, "%s\n", error2.GetMessage());
return EXIT_FAILURE;
}
/* daemonize */
ret = daemonize();
if (ret < 0)
exit(2);
/* launch the access logger */
if (!log_global_init(instance.cmdline.access_logger))
return EXIT_FAILURE;
/* daemonize II */
if (daemon_user_defined(&instance.cmdline.user))
capabilities_pre_setuid();
if (daemon_user_set(&instance.cmdline.user) < 0)
return EXIT_FAILURE;
isolate_from_filesystem();
if (daemon_user_defined(&instance.cmdline.user))
capabilities_post_setuid(cap_keep_list, G_N_ELEMENTS(cap_keep_list));
#ifdef __linux
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
#endif
/* main loop */
if (instance.cmdline.watchdog) {
/* watchdog */
all_listeners_event_del(&instance);
is_watchdog = true;
evtimer_set(&launch_worker_event, launch_worker_callback, &instance);
evtimer_add(&launch_worker_event, &launch_worker_now);
} else {
/* this is already the worker process: enable monitors here */
lb_hmonitor_enable();
}
event_dispatch();
/* cleanup */
children_shutdown();
log_global_deinit();
bulldog_deinit();
failure_deinit();
deinit_all_listeners(&instance);
deinit_all_controls(&instance);
fb_pool_deinit();
event_base_free(instance.event_base);
tpool_deinit();
delete instance.config;
ref = pool_unref(instance.pool);
assert(ref == 0);
pool_commit();
pool_recycler_clear();
ssl_global_deinit();
daemonize_cleanup();
direct_global_deinit();
}
<|endoftext|> |
<commit_before>// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2019, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// $HeadURL$
//
// Purpose:
// [The purpose of this file]
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************
//************************* System Include Files ****************************
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
using std::string;
#include <map>
#include <list>
#include <vector>
#include <algorithm>
#include <cstring>
//*************************** User Include Files ****************************
#include "StructSimple.hpp"
#include <lib/prof/Struct-Tree.hpp>
using namespace Prof;
#include <lib/binutils/LM.hpp>
#include <lib/binutils/Insn.hpp>
#include <lib/support/diagnostics.h>
#include <lib/support/FileUtil.hpp>
//*************************** Forward Declarations ***************************
//****************************************************************************
//
//****************************************************************************
static const char *
fileBasename(const char *pathname)
{
const char *slash = strrchr(pathname, '/');
const char *basename = (slash ? slash + 1 : pathname);
return basename;
}
// makeStructureSimple: Uses the line map to make structure
Prof::Struct::Stmt*
BAnal::Struct::makeStructureSimple(Prof::Struct::LM* lmStrct,
BinUtil::LM* lm, VMA vma)
{
string procnm, filenm;
SrcFile::ln line = Prof::Struct::Tree::UnknownLine;
lm->findSrcCodeInfo(vma, 0 /*opIdx*/, procnm, filenm, line);
procnm = BinUtil::canonicalizeProcName(procnm);
if (filenm.empty()) {
filenm = Prof::Struct::Tree::UnknownFileNm
+ " [" + FileUtil::basename(lm->name().c_str()) + "]";
}
if (procnm.empty()) {
std::stringstream buf;
buf << Prof::Struct::Tree::UnknownProcNm
<< " 0x" << std::hex << vma << std::dec
<< " [" << FileUtil::basename(lm->name().c_str()) << "]";
procnm = buf.str();
}
Prof::Struct::File* fileStrct = Prof::Struct::File::demand(lmStrct, filenm);
Prof::Struct::Proc* procStrct = Prof::Struct::Proc::demand(fileStrct, procnm,
"", line, line);
VMA begVMA = vma, endVMA = vma + 1;
BinUtil::Insn* insn = lm->findInsn(vma, 0 /*opIdx*/);
if (insn) {
endVMA = insn->endVMA();
}
Prof::Struct::Stmt* stmtStrct = demandStmtStructure(lmStrct, procStrct, line,
begVMA, endVMA);
return stmtStrct;
}
Struct::Stmt*
BAnal::Struct::demandStmtStructure(Prof::Struct::LM* lmStrct,
Prof::Struct::Proc* procStrct,
SrcFile::ln line, VMA begVMA, VMA endVMA)
{
Prof::Struct::Stmt* stmtStrct = procStrct->findStmt(line);
if (stmtStrct) {
if (0) {
// disable: potentially expensive to maintain
lmStrct->eraseStmtIf(stmtStrct);
}
stmtStrct->vmaSet().insert(begVMA, endVMA);
if (0) {
// disable: potentially expensive to maintain
lmStrct->insertStmtIf(stmtStrct);
}
}
else {
// N.B.: calls lmStrct->insertStmtIf()
stmtStrct = new Prof::Struct::Stmt(procStrct, line, line, begVMA, endVMA);
}
return stmtStrct;
}
<commit_msg>remove a dead function fileBasename in StructSimple.cpp<commit_after>// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2019, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// $HeadURL$
//
// Purpose:
// [The purpose of this file]
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************
//************************* System Include Files ****************************
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
using std::string;
#include <map>
#include <list>
#include <vector>
#include <algorithm>
#include <cstring>
//*************************** User Include Files ****************************
#include "StructSimple.hpp"
#include <lib/prof/Struct-Tree.hpp>
using namespace Prof;
#include <lib/binutils/LM.hpp>
#include <lib/binutils/Insn.hpp>
#include <lib/support/diagnostics.h>
#include <lib/support/FileUtil.hpp>
//*************************** Forward Declarations ***************************
//****************************************************************************
//
//****************************************************************************
// makeStructureSimple: Uses the line map to make structure
Prof::Struct::Stmt*
BAnal::Struct::makeStructureSimple(Prof::Struct::LM* lmStrct,
BinUtil::LM* lm, VMA vma)
{
string procnm, filenm;
SrcFile::ln line = Prof::Struct::Tree::UnknownLine;
lm->findSrcCodeInfo(vma, 0 /*opIdx*/, procnm, filenm, line);
procnm = BinUtil::canonicalizeProcName(procnm);
if (filenm.empty()) {
filenm = Prof::Struct::Tree::UnknownFileNm
+ " [" + FileUtil::basename(lm->name().c_str()) + "]";
}
if (procnm.empty()) {
std::stringstream buf;
buf << Prof::Struct::Tree::UnknownProcNm
<< " 0x" << std::hex << vma << std::dec
<< " [" << FileUtil::basename(lm->name().c_str()) << "]";
procnm = buf.str();
}
Prof::Struct::File* fileStrct = Prof::Struct::File::demand(lmStrct, filenm);
Prof::Struct::Proc* procStrct = Prof::Struct::Proc::demand(fileStrct, procnm,
"", line, line);
VMA begVMA = vma, endVMA = vma + 1;
BinUtil::Insn* insn = lm->findInsn(vma, 0 /*opIdx*/);
if (insn) {
endVMA = insn->endVMA();
}
Prof::Struct::Stmt* stmtStrct = demandStmtStructure(lmStrct, procStrct, line,
begVMA, endVMA);
return stmtStrct;
}
Struct::Stmt*
BAnal::Struct::demandStmtStructure(Prof::Struct::LM* lmStrct,
Prof::Struct::Proc* procStrct,
SrcFile::ln line, VMA begVMA, VMA endVMA)
{
Prof::Struct::Stmt* stmtStrct = procStrct->findStmt(line);
if (stmtStrct) {
if (0) {
// disable: potentially expensive to maintain
lmStrct->eraseStmtIf(stmtStrct);
}
stmtStrct->vmaSet().insert(begVMA, endVMA);
if (0) {
// disable: potentially expensive to maintain
lmStrct->insertStmtIf(stmtStrct);
}
}
else {
// N.B.: calls lmStrct->insertStmtIf()
stmtStrct = new Prof::Struct::Stmt(procStrct, line, line, begVMA, endVMA);
}
return stmtStrct;
}
<|endoftext|> |
<commit_before><commit_msg>Use COMPILE_ASSERT instead of DCHECK for compile-time constant checks<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "PassiveAcquisitionWidget.h"
#include "ui_PassiveAcquisitionWidget.h"
#include "AcquisitionClient.h"
#include "ActiveObjects.h"
#include "ConnectionDialog.h"
#include "InterfaceBuilder.h"
#include "StartServerDialog.h"
#include "DataSource.h"
#include "ModuleManager.h"
#include "Pipeline.h"
#include "PipelineManager.h"
#include <pqApplicationCore.h>
#include <pqSettings.h>
#include <vtkSMProxy.h>
#include <vtkCamera.h>
#include <vtkImageData.h>
#include <vtkImageProperty.h>
#include <vtkImageSlice.h>
#include <vtkImageSliceMapper.h>
#include <vtkInteractorStyleRubberBand2D.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkScalarsToColors.h>
#include <vtkTIFFReader.h>
#include <QBuffer>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QJsonValueRef>
#include <QMessageBox>
#include <QNetworkReply>
#include <QPalette>
#include <QProcess>
#include <QPushButton>
#include <QRegExp>
#include <QTimer>
#include <QVBoxLayout>
namespace tomviz {
const char* PASSIVE_ADAPTER =
"tomviz.acquisition.vendors.passive.PassiveWatchSource";
PassiveAcquisitionWidget::PassiveAcquisitionWidget(QWidget* parent)
: QWidget(parent), m_ui(new Ui::PassiveAcquisitionWidget),
m_client(new AcquisitionClient("http://localhost:8080/acquisition", this)),
m_connectParamsWidget(new QWidget), m_watchTimer(new QTimer)
{
m_ui->setupUi(this);
this->setWindowFlags(Qt::Dialog);
readSettings();
connect(m_ui->watchPathLineEdit, &QLineEdit::textChanged, this,
&PassiveAcquisitionWidget::checkEnableWatchButton);
connect(m_ui->connectionsWidget, &ConnectionsWidget::selectionChanged, this,
&PassiveAcquisitionWidget::checkEnableWatchButton);
connect(m_ui->watchButton, &QPushButton::clicked, [this]() {
// Validate the filename regex
if (!this->validateRegex()) {
return;
}
this->m_retryCount = 5;
this->connectToServer();
});
connect(m_ui->stopWatchingButton, &QPushButton::clicked, this,
&PassiveAcquisitionWidget::stopWatching);
connect(m_ui->fileNameRegexLineEdit, &QLineEdit::textChanged, [this]() {
this->setEnabledRegexGroupsWidget(
!m_ui->fileNameRegexLineEdit->text().isEmpty());
});
this->setEnabledRegexGroupsWidget(
!m_ui->fileNameRegexLineEdit->text().isEmpty());
connect(m_ui->regexGroupsWidget, &RegexGroupsWidget::groupsChanged, [this]() {
this->setEnabledRegexGroupsSubstitutionsWidget(
!this->m_ui->regexGroupsWidget->regexGroups().isEmpty());
});
this->setEnabledRegexGroupsSubstitutionsWidget(
!this->m_ui->regexGroupsWidget->regexGroups().isEmpty());
this->checkEnableWatchButton();
// Connect signal to clean up any servers we start.
auto app = QCoreApplication::instance();
connect(app, &QApplication::aboutToQuit, [this]() {
if (this->m_serverProcess != nullptr) {
// First disconnect the error signal as we are about pull the rug from
// under
// the process!
disconnect(this->m_serverProcess, &QProcess::errorOccurred, nullptr,
nullptr);
this->m_serverProcess->terminate();
}
});
// Setup regex error label
auto palette = m_regexErrorLabel.palette();
palette.setColor(m_regexErrorLabel.foregroundRole(), Qt::red);
m_regexErrorLabel.setPalette(palette);
connect(m_ui->fileNameRegexLineEdit, &QLineEdit::textChanged, [this]() {
this->m_ui->formLayout->removeWidget(&m_regexErrorLabel);
this->m_regexErrorLabel.setText("");
});
}
PassiveAcquisitionWidget::~PassiveAcquisitionWidget() = default;
void PassiveAcquisitionWidget::closeEvent(QCloseEvent* event)
{
writeSettings();
event->accept();
}
void PassiveAcquisitionWidget::readSettings()
{
auto settings = pqApplicationCore::instance()->settings();
if (!settings->contains("acquisition/geometry")) {
return;
}
settings->beginGroup("acquisition");
setGeometry(settings->value("passive.geometry").toRect());
m_ui->splitter->restoreState(
settings->value("passive.splitterSizes").toByteArray());
m_ui->watchPathLineEdit->setText(settings->value("watchPath").toString());
m_ui->fileNameRegexLineEdit->setText(
settings->value("fileNameRegex").toString());
settings->endGroup();
}
void PassiveAcquisitionWidget::writeSettings()
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("acquisition");
settings->setValue("passive.geometry", geometry());
settings->setValue("passive.splitterSizes", m_ui->splitter->saveState());
settings->setValue("watchPath", m_ui->watchPathLineEdit->text());
settings->setValue("fileNameRegex", m_ui->fileNameRegexLineEdit->text());
settings->endGroup();
}
void PassiveAcquisitionWidget::connectToServer(bool startServer)
{
if (this->m_retryCount == 0) {
this->displayError("Retry count excceed trying to connect to server.");
return;
}
m_client->setUrl(this->url());
auto request = m_client->connect(this->connectParams());
connect(request, &AcquisitionClientRequest::finished, [this]() {
// Now check that we are connected to server that has the right adapter
// loaded.
auto describeRequest = this->m_client->describe();
connect(describeRequest, &AcquisitionClientRequest::error, this,
&PassiveAcquisitionWidget::onError);
connect(
describeRequest, &AcquisitionClientRequest::finished,
[this](const QJsonValue& result) {
if (!result.isObject()) {
this->onError("Invalid response to describe request:", result);
return;
}
if (result.toObject()["name"] != PASSIVE_ADAPTER) {
this->onError(
"The server is not running the passive acquisition "
"adapter, please restart the server with the correct adapter.",
QJsonValue());
return;
}
// Now we can start watching.
this->watchSource();
});
});
connect(request, &AcquisitionClientRequest::error,
[startServer, this](const QString& errorMessage,
const QJsonValue& errorData) {
auto connection =
this->m_ui->connectionsWidget->selectedConnection();
// If we are getting a connection refused error and we are trying to
// connect
// to localhost, try to start the server.
if (startServer &&
errorData.toInt() == QNetworkReply::ConnectionRefusedError &&
connection->hostName() == "localhost") {
this->startLocalServer();
} else {
this->onError(errorMessage, errorData);
}
});
}
void PassiveAcquisitionWidget::imageReady(QString mimeType, QByteArray result,
int angle)
{
if (mimeType != "image/tiff") {
qDebug() << "image/tiff is the only supported mime type right now.\n"
<< mimeType << "\n";
return;
}
QDir dir(QDir::homePath() + "/tomviz-data");
if (!dir.exists()) {
dir.mkpath(dir.path());
}
QString path = "/tomviz_";
if (angle > 0.0) {
path.append('+');
}
path.append(QString::number(angle, 'g', 2));
path.append(".tiff");
QFile file(dir.path() + path);
file.open(QIODevice::WriteOnly);
file.write(result);
qDebug() << "Data file:" << file.fileName();
file.close();
vtkNew<vtkTIFFReader> reader;
reader->SetFileName(file.fileName().toLatin1());
reader->Update();
m_imageData = reader->GetOutput();
m_imageSlice->GetProperty()->SetInterpolationTypeToNearest();
m_imageSliceMapper->SetInputData(m_imageData.Get());
m_imageSliceMapper->Update();
m_imageSlice->SetMapper(m_imageSliceMapper.Get());
m_renderer->AddViewProp(m_imageSlice.Get());
// If we haven't added it, add our live data source to the pipeline.
if (!m_dataSource) {
m_dataSource = new DataSource(m_imageData);
m_dataSource->setLabel("Live!");
auto pipeline = new Pipeline(m_dataSource);
PipelineManager::instance().addPipeline(pipeline);
ModuleManager::instance().addDataSource(m_dataSource);
pipeline->addDefaultModules(m_dataSource);
} else {
m_dataSource->appendSlice(m_imageData);
}
}
void PassiveAcquisitionWidget::onError(const QString& errorMessage,
const QJsonValue& errorData)
{
auto message = errorMessage;
if (!errorData.toString().isEmpty()) {
message = QString("%1\n%2").arg(message).arg(errorData.toString());
}
this->stopWatching();
this->displayError(message);
}
void PassiveAcquisitionWidget::displayError(const QString& errorMessage)
{
QMessageBox::warning(this, "Acquisition Error", errorMessage,
QMessageBox::Ok);
}
QString PassiveAcquisitionWidget::url() const
{
auto connection = m_ui->connectionsWidget->selectedConnection();
return QString("http://%1:%2/acquisition")
.arg(connection->hostName())
.arg(connection->port());
}
void PassiveAcquisitionWidget::watchSource()
{
this->m_ui->watchButton->setEnabled(false);
this->m_ui->stopWatchingButton->setEnabled(true);
connect(this->m_watchTimer, &QTimer::timeout, this,
[this]() {
auto request = m_client->stem_acquire();
connect(request, &AcquisitionClientImageRequest::finished,
[this](const QString mimeType, const QByteArray& result,
const QJsonObject& meta) {
if (!result.isNull()) {
int angle = 0;
if (meta.contains("angle")) {
angle = meta["angle"].toString().toInt();
}
this->imageReady(mimeType, result, angle);
}
});
connect(request, &AcquisitionClientRequest::error, this,
&PassiveAcquisitionWidget::onError);
},
Qt::UniqueConnection);
this->m_watchTimer->start(1000);
}
QJsonObject PassiveAcquisitionWidget::connectParams()
{
QJsonObject connectParams{
{ "path", m_ui->watchPathLineEdit->text() },
{ "fileNameRegex", m_ui->fileNameRegexLineEdit->text() },
};
auto fileNameRegexGroups = m_ui->regexGroupsWidget->regexGroups();
if (!fileNameRegexGroups.isEmpty()) {
auto groups = QJsonArray::fromStringList(fileNameRegexGroups);
connectParams["fileNameRegexGroups"] = groups;
}
auto regexGroupsSubstitutions =
m_ui->regexGroupsSubstitutionsWidget->substitutions();
if (!regexGroupsSubstitutions.isEmpty()) {
QJsonObject substitutions;
foreach (RegexGroupSubstitution sub, regexGroupsSubstitutions) {
QJsonArray regexToSubs;
if (substitutions.contains(sub.groupName())) {
regexToSubs = substitutions.value(sub.groupName()).toArray();
}
QJsonObject mapping;
mapping[sub.regex()] = sub.substitution();
regexToSubs.append(mapping);
substitutions[sub.groupName()] = regexToSubs;
}
connectParams["groupRegexSubstitutions"] = substitutions;
}
return connectParams;
}
void PassiveAcquisitionWidget::startLocalServer()
{
StartServerDialog dialog;
auto r = dialog.exec();
if (r != QDialog::Accepted) {
return;
}
auto pythonExecutablePath = dialog.pythonExecutablePath();
QStringList arguments;
arguments << "-m"
<< "tomviz"
<< "-a" << PASSIVE_ADAPTER << "-r";
this->m_serverProcess = new QProcess(this);
this->m_serverProcess->setProgram(pythonExecutablePath);
this->m_serverProcess->setArguments(arguments);
connect(this->m_serverProcess, &QProcess::errorOccurred,
[this](QProcess::ProcessError error) {
Q_UNUSED(error);
auto message = QString("Error starting local acquisition: '%1'")
.arg(this->m_serverProcess->errorString());
QMessageBox::warning(this, "Server Start Error", message,
QMessageBox::Ok);
});
connect(this->m_serverProcess, &QProcess::started, [this]() {
// Now try to connect and watch. Note we are not asking for server to be
// started if the connection fails, this is to prevent us getting into a
// connect loop.
QTimer::singleShot(200, [this]() {
this->m_retryCount--;
this->connectToServer(false);
});
});
this->m_serverProcess->start();
}
void PassiveAcquisitionWidget::checkEnableWatchButton()
{
auto path = m_ui->watchPathLineEdit->text();
this->m_ui->watchButton->setEnabled(
!path.isEmpty() &&
this->m_ui->connectionsWidget->selectedConnection() != nullptr);
}
void PassiveAcquisitionWidget::setEnabledRegexGroupsWidget(bool enabled)
{
this->m_ui->regexGroupsLabel->setEnabled(enabled);
this->m_ui->regexGroupsWidget->setEnabled(enabled);
}
void PassiveAcquisitionWidget::setEnabledRegexGroupsSubstitutionsWidget(
bool enabled)
{
this->m_ui->regexGroupsSubstitutionsLabel->setEnabled(enabled);
this->m_ui->regexGroupsSubstitutionsWidget->setEnabled(enabled);
}
void PassiveAcquisitionWidget::stopWatching()
{
this->m_watchTimer->stop();
this->m_ui->stopWatchingButton->setEnabled(false);
this->m_ui->watchButton->setEnabled(true);
}
bool PassiveAcquisitionWidget::validateRegex()
{
auto regExText = m_ui->fileNameRegexLineEdit->text();
if (!regExText.isEmpty()) {
QRegExp regExp(regExText);
if (!regExp.isValid()) {
m_regexErrorLabel.setText(regExp.errorString());
m_ui->formLayout->insertRow(3, "", &m_regexErrorLabel);
return false;
}
}
return true;
}
}
<commit_msg>Add default watch path<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "PassiveAcquisitionWidget.h"
#include "ui_PassiveAcquisitionWidget.h"
#include "AcquisitionClient.h"
#include "ActiveObjects.h"
#include "ConnectionDialog.h"
#include "InterfaceBuilder.h"
#include "StartServerDialog.h"
#include "DataSource.h"
#include "ModuleManager.h"
#include "Pipeline.h"
#include "PipelineManager.h"
#include <pqApplicationCore.h>
#include <pqSettings.h>
#include <vtkSMProxy.h>
#include <vtkCamera.h>
#include <vtkImageData.h>
#include <vtkImageProperty.h>
#include <vtkImageSlice.h>
#include <vtkImageSliceMapper.h>
#include <vtkInteractorStyleRubberBand2D.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkScalarsToColors.h>
#include <vtkTIFFReader.h>
#include <QBuffer>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QJsonValueRef>
#include <QMessageBox>
#include <QNetworkReply>
#include <QPalette>
#include <QProcess>
#include <QPushButton>
#include <QRegExp>
#include <QStandardPaths>
#include <QTimer>
#include <QVBoxLayout>
namespace tomviz {
const char* PASSIVE_ADAPTER =
"tomviz.acquisition.vendors.passive.PassiveWatchSource";
PassiveAcquisitionWidget::PassiveAcquisitionWidget(QWidget* parent)
: QWidget(parent), m_ui(new Ui::PassiveAcquisitionWidget),
m_client(new AcquisitionClient("http://localhost:8080/acquisition", this)),
m_connectParamsWidget(new QWidget), m_watchTimer(new QTimer)
{
m_ui->setupUi(this);
this->setWindowFlags(Qt::Dialog);
// Default to home directory
QStringList locations =
QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
m_ui->watchPathLineEdit->setText(locations[0]);
readSettings();
connect(m_ui->watchPathLineEdit, &QLineEdit::textChanged, this,
&PassiveAcquisitionWidget::checkEnableWatchButton);
connect(m_ui->connectionsWidget, &ConnectionsWidget::selectionChanged, this,
&PassiveAcquisitionWidget::checkEnableWatchButton);
connect(m_ui->watchButton, &QPushButton::clicked, [this]() {
// Validate the filename regex
if (!this->validateRegex()) {
return;
}
this->m_retryCount = 5;
this->connectToServer();
});
connect(m_ui->stopWatchingButton, &QPushButton::clicked, this,
&PassiveAcquisitionWidget::stopWatching);
connect(m_ui->fileNameRegexLineEdit, &QLineEdit::textChanged, [this]() {
this->setEnabledRegexGroupsWidget(
!m_ui->fileNameRegexLineEdit->text().isEmpty());
});
this->setEnabledRegexGroupsWidget(
!m_ui->fileNameRegexLineEdit->text().isEmpty());
connect(m_ui->regexGroupsWidget, &RegexGroupsWidget::groupsChanged, [this]() {
this->setEnabledRegexGroupsSubstitutionsWidget(
!this->m_ui->regexGroupsWidget->regexGroups().isEmpty());
});
this->setEnabledRegexGroupsSubstitutionsWidget(
!this->m_ui->regexGroupsWidget->regexGroups().isEmpty());
this->checkEnableWatchButton();
// Connect signal to clean up any servers we start.
auto app = QCoreApplication::instance();
connect(app, &QApplication::aboutToQuit, [this]() {
if (this->m_serverProcess != nullptr) {
// First disconnect the error signal as we are about pull the rug from
// under
// the process!
disconnect(this->m_serverProcess, &QProcess::errorOccurred, nullptr,
nullptr);
this->m_serverProcess->terminate();
}
});
// Setup regex error label
auto palette = m_regexErrorLabel.palette();
palette.setColor(m_regexErrorLabel.foregroundRole(), Qt::red);
m_regexErrorLabel.setPalette(palette);
connect(m_ui->fileNameRegexLineEdit, &QLineEdit::textChanged, [this]() {
this->m_ui->formLayout->removeWidget(&m_regexErrorLabel);
this->m_regexErrorLabel.setText("");
});
}
PassiveAcquisitionWidget::~PassiveAcquisitionWidget() = default;
void PassiveAcquisitionWidget::closeEvent(QCloseEvent* event)
{
writeSettings();
event->accept();
}
void PassiveAcquisitionWidget::readSettings()
{
auto settings = pqApplicationCore::instance()->settings();
if (!settings->contains("acquisition/passive.geometry")) {
return;
}
settings->beginGroup("acquisition");
setGeometry(settings->value("passive.geometry").toRect());
m_ui->splitter->restoreState(
settings->value("passive.splitterSizes").toByteArray());
auto watchPath = settings->value("watchPath").toString();
if (!watchPath.isEmpty()) {
m_ui->watchPathLineEdit->setText(watchPath);
}
auto fileNameRegex = settings->value("fileNameRegex").toString();
if (!fileNameRegex.isEmpty()) {
m_ui->fileNameRegexLineEdit->setText(fileNameRegex);
}
settings->endGroup();
}
void PassiveAcquisitionWidget::writeSettings()
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("acquisition");
settings->setValue("passive.geometry", geometry());
settings->setValue("passive.splitterSizes", m_ui->splitter->saveState());
settings->setValue("watchPath", m_ui->watchPathLineEdit->text());
settings->setValue("fileNameRegex", m_ui->fileNameRegexLineEdit->text());
settings->endGroup();
}
void PassiveAcquisitionWidget::connectToServer(bool startServer)
{
if (this->m_retryCount == 0) {
this->displayError("Retry count excceed trying to connect to server.");
return;
}
m_client->setUrl(this->url());
auto request = m_client->connect(this->connectParams());
connect(request, &AcquisitionClientRequest::finished, [this]() {
// Now check that we are connected to server that has the right adapter
// loaded.
auto describeRequest = this->m_client->describe();
connect(describeRequest, &AcquisitionClientRequest::error, this,
&PassiveAcquisitionWidget::onError);
connect(
describeRequest, &AcquisitionClientRequest::finished,
[this](const QJsonValue& result) {
if (!result.isObject()) {
this->onError("Invalid response to describe request:", result);
return;
}
if (result.toObject()["name"] != PASSIVE_ADAPTER) {
this->onError(
"The server is not running the passive acquisition "
"adapter, please restart the server with the correct adapter.",
QJsonValue());
return;
}
// Now we can start watching.
this->watchSource();
});
});
connect(request, &AcquisitionClientRequest::error,
[startServer, this](const QString& errorMessage,
const QJsonValue& errorData) {
auto connection =
this->m_ui->connectionsWidget->selectedConnection();
// If we are getting a connection refused error and we are trying to
// connect
// to localhost, try to start the server.
if (startServer &&
errorData.toInt() == QNetworkReply::ConnectionRefusedError &&
connection->hostName() == "localhost") {
this->startLocalServer();
} else {
this->onError(errorMessage, errorData);
}
});
}
void PassiveAcquisitionWidget::imageReady(QString mimeType, QByteArray result,
int angle)
{
if (mimeType != "image/tiff") {
qDebug() << "image/tiff is the only supported mime type right now.\n"
<< mimeType << "\n";
return;
}
QDir dir(QDir::homePath() + "/tomviz-data");
if (!dir.exists()) {
dir.mkpath(dir.path());
}
QString path = "/tomviz_";
if (angle > 0.0) {
path.append('+');
}
path.append(QString::number(angle, 'g', 2));
path.append(".tiff");
QFile file(dir.path() + path);
file.open(QIODevice::WriteOnly);
file.write(result);
qDebug() << "Data file:" << file.fileName();
file.close();
vtkNew<vtkTIFFReader> reader;
reader->SetFileName(file.fileName().toLatin1());
reader->Update();
m_imageData = reader->GetOutput();
m_imageSlice->GetProperty()->SetInterpolationTypeToNearest();
m_imageSliceMapper->SetInputData(m_imageData.Get());
m_imageSliceMapper->Update();
m_imageSlice->SetMapper(m_imageSliceMapper.Get());
m_renderer->AddViewProp(m_imageSlice.Get());
// If we haven't added it, add our live data source to the pipeline.
if (!m_dataSource) {
m_dataSource = new DataSource(m_imageData);
m_dataSource->setLabel("Live!");
auto pipeline = new Pipeline(m_dataSource);
PipelineManager::instance().addPipeline(pipeline);
ModuleManager::instance().addDataSource(m_dataSource);
pipeline->addDefaultModules(m_dataSource);
} else {
m_dataSource->appendSlice(m_imageData);
}
}
void PassiveAcquisitionWidget::onError(const QString& errorMessage,
const QJsonValue& errorData)
{
auto message = errorMessage;
if (!errorData.toString().isEmpty()) {
message = QString("%1\n%2").arg(message).arg(errorData.toString());
}
this->stopWatching();
this->displayError(message);
}
void PassiveAcquisitionWidget::displayError(const QString& errorMessage)
{
QMessageBox::warning(this, "Acquisition Error", errorMessage,
QMessageBox::Ok);
}
QString PassiveAcquisitionWidget::url() const
{
auto connection = m_ui->connectionsWidget->selectedConnection();
return QString("http://%1:%2/acquisition")
.arg(connection->hostName())
.arg(connection->port());
}
void PassiveAcquisitionWidget::watchSource()
{
this->m_ui->watchButton->setEnabled(false);
this->m_ui->stopWatchingButton->setEnabled(true);
connect(this->m_watchTimer, &QTimer::timeout, this,
[this]() {
auto request = m_client->stem_acquire();
connect(request, &AcquisitionClientImageRequest::finished,
[this](const QString mimeType, const QByteArray& result,
const QJsonObject& meta) {
if (!result.isNull()) {
int angle = 0;
if (meta.contains("angle")) {
angle = meta["angle"].toString().toInt();
}
this->imageReady(mimeType, result, angle);
}
});
connect(request, &AcquisitionClientRequest::error, this,
&PassiveAcquisitionWidget::onError);
},
Qt::UniqueConnection);
this->m_watchTimer->start(1000);
}
QJsonObject PassiveAcquisitionWidget::connectParams()
{
QJsonObject connectParams{
{ "path", m_ui->watchPathLineEdit->text() },
{ "fileNameRegex", m_ui->fileNameRegexLineEdit->text() },
};
auto fileNameRegexGroups = m_ui->regexGroupsWidget->regexGroups();
if (!fileNameRegexGroups.isEmpty()) {
auto groups = QJsonArray::fromStringList(fileNameRegexGroups);
connectParams["fileNameRegexGroups"] = groups;
}
auto regexGroupsSubstitutions =
m_ui->regexGroupsSubstitutionsWidget->substitutions();
if (!regexGroupsSubstitutions.isEmpty()) {
QJsonObject substitutions;
foreach (RegexGroupSubstitution sub, regexGroupsSubstitutions) {
QJsonArray regexToSubs;
if (substitutions.contains(sub.groupName())) {
regexToSubs = substitutions.value(sub.groupName()).toArray();
}
QJsonObject mapping;
mapping[sub.regex()] = sub.substitution();
regexToSubs.append(mapping);
substitutions[sub.groupName()] = regexToSubs;
}
connectParams["groupRegexSubstitutions"] = substitutions;
}
return connectParams;
}
void PassiveAcquisitionWidget::startLocalServer()
{
StartServerDialog dialog;
auto r = dialog.exec();
if (r != QDialog::Accepted) {
return;
}
auto pythonExecutablePath = dialog.pythonExecutablePath();
QStringList arguments;
arguments << "-m"
<< "tomviz"
<< "-a" << PASSIVE_ADAPTER << "-r";
this->m_serverProcess = new QProcess(this);
this->m_serverProcess->setProgram(pythonExecutablePath);
this->m_serverProcess->setArguments(arguments);
connect(this->m_serverProcess, &QProcess::errorOccurred,
[this](QProcess::ProcessError error) {
Q_UNUSED(error);
auto message = QString("Error starting local acquisition: '%1'")
.arg(this->m_serverProcess->errorString());
QMessageBox::warning(this, "Server Start Error", message,
QMessageBox::Ok);
});
connect(this->m_serverProcess, &QProcess::started, [this]() {
// Now try to connect and watch. Note we are not asking for server to be
// started if the connection fails, this is to prevent us getting into a
// connect loop.
QTimer::singleShot(200, [this]() {
this->m_retryCount--;
this->connectToServer(false);
});
});
this->m_serverProcess->start();
}
void PassiveAcquisitionWidget::checkEnableWatchButton()
{
auto path = m_ui->watchPathLineEdit->text();
this->m_ui->watchButton->setEnabled(
!path.isEmpty() &&
this->m_ui->connectionsWidget->selectedConnection() != nullptr);
}
void PassiveAcquisitionWidget::setEnabledRegexGroupsWidget(bool enabled)
{
this->m_ui->regexGroupsLabel->setEnabled(enabled);
this->m_ui->regexGroupsWidget->setEnabled(enabled);
}
void PassiveAcquisitionWidget::setEnabledRegexGroupsSubstitutionsWidget(
bool enabled)
{
this->m_ui->regexGroupsSubstitutionsLabel->setEnabled(enabled);
this->m_ui->regexGroupsSubstitutionsWidget->setEnabled(enabled);
}
void PassiveAcquisitionWidget::stopWatching()
{
this->m_watchTimer->stop();
this->m_ui->stopWatchingButton->setEnabled(false);
this->m_ui->watchButton->setEnabled(true);
}
bool PassiveAcquisitionWidget::validateRegex()
{
auto regExText = m_ui->fileNameRegexLineEdit->text();
if (!regExText.isEmpty()) {
QRegExp regExp(regExText);
if (!regExp.isValid()) {
m_regexErrorLabel.setText(regExp.errorString());
m_ui->formLayout->insertRow(3, "", &m_regexErrorLabel);
return false;
}
}
return true;
}
}
<|endoftext|> |
<commit_before>#include <util/singleton.H>
#include <kernel/console.H>
#include <stdarg.h>
static char kernel_printk_buffer[Console::BUFFER_SIZE];
Console::Console() : iv_pos(0), iv_buffer(kernel_printk_buffer)
{
memset(iv_buffer, '\0', Console::BUFFER_SIZE);
}
int Console::putc(int c)
{
if (BUFFER_SIZE > iv_pos)
{
iv_buffer[iv_pos] = c;
iv_pos++;
}
}
class ConsoleTraits
{
public:
enum trait { NONE, HEX, DEC, };
};
template <typename _T, ConsoleTraits::trait _S = ConsoleTraits::NONE>
class ConsoleDisplay
{
public:
static void display(Console& c, _T value) {};
};
template <>
class ConsoleDisplay<char, ConsoleTraits::NONE>
{
public:
static void display(Console&c, char value)
{
c.putc(value);
}
};
template <typename _T>
class ConsoleDisplay<_T, ConsoleTraits::DEC>
{
public:
static void display(Console&c, _T value)
{
if (value == 0)
{
c.putc('0');
}
else if (value < 0)
{
c.putc('-');
value *= -1;
}
else
subdisplay(c, value);
}
static void subdisplay(Console&c, _T value)
{
if (value != 0)
{
subdisplay(c, value / 10);
c.putc('0' + (value % 10));
}
}
};
template<typename _T>
class ConsoleDisplay<_T, ConsoleTraits::HEX>
{
public:
static void display(Console&c, _T value)
{
size_t length = sizeof(_T) * 2;
subdisplay(c, value, length);
}
static void subdisplay(Console&c, _T value, size_t length)
{
if (length == 0) return;
subdisplay(c, value / 16, length-1);
char nibble = value % 16;
if (nibble >= 0x0a)
c.putc('A' + (nibble - 0x0a));
else
c.putc('0' + nibble);
}
};
void printk(const char* str, ...)
{
va_list args;
va_start(args, str);
Console& console = Singleton<Console>::instance();
bool format = false;
int size;
while('\0' != *str)
{
if (('%' == *str) || (format))
switch (*str)
{
case '%':
{
if (format)
{
ConsoleDisplay<char>::display(console, '%');
}
else
{
format = true;
size = 2;
}
break;
}
case 'c':
{
format = false;
ConsoleDisplay<char>
::display(console,
(char)va_arg(args,int));
break;
}
case 'h':
{
size--;
break;
}
case 'l':
{
size++;
break;
}
case 'd': // decimal
{
format = false;
switch(size)
{
case 0:
ConsoleDisplay<char, ConsoleTraits::DEC>
::display(console,
(char)va_arg(args,int));
break;
case 1:
ConsoleDisplay<short, ConsoleTraits::DEC>
::display(console,
(short)va_arg(args,int));
break;
case 2:
case 3:
ConsoleDisplay<int, ConsoleTraits::DEC>
::display(console,
va_arg(args,int));
break;
case 4:
ConsoleDisplay<long, ConsoleTraits::DEC>
::display(console,
va_arg(args,long));
break;
}
break;
}
case 'u': // unsigned decimal
{
format = false;
switch(size)
{
case 0:
ConsoleDisplay<unsigned char, ConsoleTraits::DEC>
::display(console,
(unsigned char)
va_arg(args,unsigned int));
break;
case 1:
ConsoleDisplay<unsigned short, ConsoleTraits::DEC>
::display(console,
(unsigned short)
va_arg(args,unsigned int));
break;
case 2:
case 3:
ConsoleDisplay<unsigned int, ConsoleTraits::DEC>
::display(console,
va_arg(args,unsigned int));
break;
case 4:
ConsoleDisplay<unsigned long, ConsoleTraits::DEC>
::display(console,
va_arg(args,unsigned long));
break;
}
break;
}
case 'x': // unsigned hex
case 'X':
{
format = false;
switch(size)
{
case 0:
ConsoleDisplay<unsigned char, ConsoleTraits::HEX>
::display(console,
(unsigned char)
va_arg(args,unsigned int));
break;
case 1:
ConsoleDisplay<unsigned short, ConsoleTraits::HEX>
::display(console,
(unsigned short)
va_arg(args,unsigned int));
break;
case 2:
case 3:
ConsoleDisplay<unsigned int, ConsoleTraits::HEX>
::display(console,
va_arg(args,unsigned int));
break;
case 4:
ConsoleDisplay<unsigned long, ConsoleTraits::HEX>
::display(console,
va_arg(args,unsigned long));
break;
}
break;
}
case 's': // string
{
format = false;
ConsoleDisplay<char*>::display(console,
(char*)va_arg(args,void*));
break;
}
}
else
ConsoleDisplay<char>::display(console, *str);
str++;
}
va_end(args);
}
<commit_msg>Add %s, %z support in console driver.<commit_after>#include <util/singleton.H>
#include <kernel/console.H>
#include <stdarg.h>
static char kernel_printk_buffer[Console::BUFFER_SIZE];
Console::Console() : iv_pos(0), iv_buffer(kernel_printk_buffer)
{
memset(iv_buffer, '\0', Console::BUFFER_SIZE);
}
int Console::putc(int c)
{
if (BUFFER_SIZE > iv_pos)
{
iv_buffer[iv_pos] = c;
iv_pos++;
}
}
class ConsoleTraits
{
public:
enum trait { NONE, HEX, DEC, };
};
template <typename _T, ConsoleTraits::trait _S = ConsoleTraits::NONE>
class ConsoleDisplay
{
public:
static void display(Console& c, _T value) {};
};
template <ConsoleTraits::trait _S>
class ConsoleDisplay<char*, _S>
{
public:
static void display(Console&c, char* value)
{
while(*value != '\0')
{
c.putc(*value);
value++;
}
}
};
template <>
class ConsoleDisplay<char, ConsoleTraits::NONE>
{
public:
static void display(Console&c, char value)
{
c.putc(value);
}
};
template <typename _T>
class ConsoleDisplay<_T, ConsoleTraits::DEC>
{
public:
static void display(Console&c, _T value)
{
if (value == 0)
{
c.putc('0');
}
else if (value < 0)
{
c.putc('-');
value *= -1;
}
else
subdisplay(c, value);
}
static void subdisplay(Console&c, _T value)
{
if (value != 0)
{
subdisplay(c, value / 10);
c.putc('0' + (value % 10));
}
}
};
template<typename _T>
class ConsoleDisplay<_T, ConsoleTraits::HEX>
{
public:
static void display(Console&c, _T value)
{
size_t length = sizeof(_T) * 2;
subdisplay(c, value, length);
}
static void subdisplay(Console&c, _T value, size_t length)
{
if (length == 0) return;
subdisplay(c, value / 16, length-1);
char nibble = value % 16;
if (nibble >= 0x0a)
c.putc('A' + (nibble - 0x0a));
else
c.putc('0' + nibble);
}
};
void printk(const char* str, ...)
{
va_list args;
va_start(args, str);
Console& console = Singleton<Console>::instance();
bool format = false;
int size;
while('\0' != *str)
{
if (('%' == *str) || (format))
switch (*str)
{
case '%':
{
if (format)
{
ConsoleDisplay<char>::display(console, '%');
format = false;
}
else
{
format = true;
size = 2;
}
break;
}
case 'c':
{
format = false;
ConsoleDisplay<char>
::display(console,
(char)va_arg(args,int));
break;
}
case 'h':
{
size--;
break;
}
case 'l':
{
size++;
break;
}
case 'z': // size_t or ssize_t
{
size = 4;
break;
}
case 'd': // decimal
{
format = false;
switch(size)
{
case 0:
ConsoleDisplay<char, ConsoleTraits::DEC>
::display(console,
(char)va_arg(args,int));
break;
case 1:
ConsoleDisplay<short, ConsoleTraits::DEC>
::display(console,
(short)va_arg(args,int));
break;
case 2:
case 3:
ConsoleDisplay<int, ConsoleTraits::DEC>
::display(console,
va_arg(args,int));
break;
case 4:
ConsoleDisplay<long, ConsoleTraits::DEC>
::display(console,
va_arg(args,long));
break;
}
break;
}
case 'u': // unsigned decimal
{
format = false;
switch(size)
{
case 0:
ConsoleDisplay<unsigned char, ConsoleTraits::DEC>
::display(console,
(unsigned char)
va_arg(args,unsigned int));
break;
case 1:
ConsoleDisplay<unsigned short, ConsoleTraits::DEC>
::display(console,
(unsigned short)
va_arg(args,unsigned int));
break;
case 2:
case 3:
ConsoleDisplay<unsigned int, ConsoleTraits::DEC>
::display(console,
va_arg(args,unsigned int));
break;
case 4:
ConsoleDisplay<unsigned long, ConsoleTraits::DEC>
::display(console,
va_arg(args,unsigned long));
break;
}
break;
}
case 'x': // unsigned hex
case 'X':
{
format = false;
switch(size)
{
case 0:
ConsoleDisplay<unsigned char, ConsoleTraits::HEX>
::display(console,
(unsigned char)
va_arg(args,unsigned int));
break;
case 1:
ConsoleDisplay<unsigned short, ConsoleTraits::HEX>
::display(console,
(unsigned short)
va_arg(args,unsigned int));
break;
case 2:
case 3:
ConsoleDisplay<unsigned int, ConsoleTraits::HEX>
::display(console,
va_arg(args,unsigned int));
break;
case 4:
ConsoleDisplay<unsigned long, ConsoleTraits::HEX>
::display(console,
va_arg(args,unsigned long));
break;
}
break;
}
case 's': // string
{
format = false;
ConsoleDisplay<char*>::display(console,
(char*)va_arg(args,void*));
break;
}
}
else
ConsoleDisplay<char>::display(console, *str);
str++;
}
va_end(args);
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <string.h>
#include "stdsneezy.h"
#include "connect.h"
#define WIZ_KEY_FILE "/mud/prod/lib/IPC_Wiznet"
#define MAIN_PORT 7900
#define BUILD_PORT 8900
#define WIZNET_FORMAT "%s %s"
#define MAX_STRING_LENGTH 4096
#define MAX_INPUT_LENGTH 1024
#define MAX_MSGBUF_LENGTH 2048
int my_ipc_id, other_ipc_id;
key_t keyval;
int qid=-2;
struct mud_msgbuf
{
long mtype;
char mtext[MAX_MSGBUF_LENGTH+1];
};
int openQueue()
{
int oldqid=qid;
if (qid==-2) {
extern int gamePort;
if (gamePort==MAIN_PORT) {
my_ipc_id = MAIN_PORT;
other_ipc_id = BUILD_PORT;
} else {
my_ipc_id = BUILD_PORT;
other_ipc_id = MAIN_PORT;
}
keyval = ftok(WIZ_KEY_FILE, 'm');
}
if ((qid = msgget(keyval, IPC_CREAT|0660)) == -1) {
vlogf(LOG_BUG, "Unable to msgget keyval %d.", keyval);
return -1;
}
if (oldqid!=qid) {
vlogf(LOG_BUG, "msgget successful, qid: %d, keyval: %d", qid, keyval);
oldqid = qid;
}
return 1;
}
void closeQueue()
{
msgctl(qid, IPC_RMID, 0);
vlogf(LOG_BUG, "closeQueue");
}
void mudSendMessage(int mtype, int ctype, const char *arg)
{
struct mud_msgbuf qbuf;
int ret;
if (openQueue()<0)
return;
if (mtype<=0) {
vlogf(LOG_BUG, "invalid mtype, must be > 0, setting to 1");
mtype = 1;
}
snprintf(qbuf.mtext, MAX_MSGBUF_LENGTH, "%d %s", ctype, arg);
qbuf.mtype = mtype;
if ((ret = msgsnd(qid, (struct msgbuf *)&qbuf, strlen(qbuf.mtext)+1, 0)) == -1)
vlogf(LOG_BUG, "mudSendMessage: errno: %d ret: %d", errno, ret);
}
void TBeing::mudMessage(TBeing *ch, int channel, const char *arg)
{
char tbuf[MAX_MSGBUF_LENGTH+1];
snprintf(tbuf, MAX_MSGBUF_LENGTH, "%s: %s", ch->getName(), arg);
mudSendMessage(other_ipc_id, channel, tbuf);
}
void recvTextHandler(const char *str)
{
Descriptor *d;
char arg1[MAX_INPUT_LENGTH], arg2[MAX_INPUT_LENGTH], chname[MAX_INPUT_LENGTH];
char buf[MAX_STRING_LENGTH-1];
// int channel=-1, level=-1;
str = one_argument(str, arg1);
str = one_argument(str, arg2);
str = one_argument(str, chname);
// channel = convertTo<int>(arg1);
// level = convertTo<int>(arg2);
snprintf(buf, MAX_STRING_LENGTH, WIZNET_FORMAT, chname, str);
for (d = descriptor_list; d; d = d->next) {
TBeing *och;
och = d->original ? d->original : d->character;
if (!och)
continue;
if (och->hasWizPower(POWER_WIZNET)) {
och->sendTo(buf);
} else {
}
}
}
void mudRecvMessage()
{
struct mud_msgbuf qbuf;
int ret;
if (openQueue() < 0)
return;
while ((ret = msgrcv(qid, (struct msgbuf *)&qbuf, MAX_MSGBUF_LENGTH, my_ipc_id, IPC_NOWAIT)) > 0)
recvTextHandler(qbuf.mtext);
if (ret==-1 && errno!=ENOMSG)
vlogf(LOG_BUG, "mudRecvMessage: errno: %d ret: %d", errno, ret);
}
<commit_msg>disabled interport mudsendmessage, is locking us up<commit_after>#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <string.h>
#include "stdsneezy.h"
#include "connect.h"
#define WIZ_KEY_FILE "/mud/prod/lib/IPC_Wiznet"
#define MAIN_PORT 7900
#define BUILD_PORT 8900
#define WIZNET_FORMAT "%s %s"
#define MAX_STRING_LENGTH 4096
#define MAX_INPUT_LENGTH 1024
#define MAX_MSGBUF_LENGTH 2048
int my_ipc_id, other_ipc_id;
key_t keyval;
int qid=-2;
struct mud_msgbuf
{
long mtype;
char mtext[MAX_MSGBUF_LENGTH+1];
};
int openQueue()
{
int oldqid=qid;
if (qid==-2) {
extern int gamePort;
if (gamePort==MAIN_PORT) {
my_ipc_id = MAIN_PORT;
other_ipc_id = BUILD_PORT;
} else {
my_ipc_id = BUILD_PORT;
other_ipc_id = MAIN_PORT;
}
keyval = ftok(WIZ_KEY_FILE, 'm');
}
if ((qid = msgget(keyval, IPC_CREAT|0660)) == -1) {
vlogf(LOG_BUG, "Unable to msgget keyval %d.", keyval);
return -1;
}
if (oldqid!=qid) {
vlogf(LOG_BUG, "msgget successful, qid: %d, keyval: %d", qid, keyval);
oldqid = qid;
}
return 1;
}
void closeQueue()
{
msgctl(qid, IPC_RMID, 0);
vlogf(LOG_BUG, "closeQueue");
}
void mudSendMessage(int mtype, int ctype, const char *arg)
{
struct mud_msgbuf qbuf;
int ret;
// this is locking is up
return;
if (openQueue()<0)
return;
if (mtype<=0) {
vlogf(LOG_BUG, "invalid mtype, must be > 0, setting to 1");
mtype = 1;
}
snprintf(qbuf.mtext, MAX_MSGBUF_LENGTH, "%d %s", ctype, arg);
qbuf.mtype = mtype;
if ((ret = msgsnd(qid, (struct msgbuf *)&qbuf, strlen(qbuf.mtext)+1, 0)) == -1)
vlogf(LOG_BUG, "mudSendMessage: errno: %d ret: %d", errno, ret);
}
void TBeing::mudMessage(TBeing *ch, int channel, const char *arg)
{
char tbuf[MAX_MSGBUF_LENGTH+1];
snprintf(tbuf, MAX_MSGBUF_LENGTH, "%s: %s", ch->getName(), arg);
mudSendMessage(other_ipc_id, channel, tbuf);
}
void recvTextHandler(const char *str)
{
Descriptor *d;
char arg1[MAX_INPUT_LENGTH], arg2[MAX_INPUT_LENGTH], chname[MAX_INPUT_LENGTH];
char buf[MAX_STRING_LENGTH-1];
// int channel=-1, level=-1;
str = one_argument(str, arg1);
str = one_argument(str, arg2);
str = one_argument(str, chname);
// channel = convertTo<int>(arg1);
// level = convertTo<int>(arg2);
snprintf(buf, MAX_STRING_LENGTH, WIZNET_FORMAT, chname, str);
for (d = descriptor_list; d; d = d->next) {
TBeing *och;
och = d->original ? d->original : d->character;
if (!och)
continue;
if (och->hasWizPower(POWER_WIZNET)) {
och->sendTo(buf);
} else {
}
}
}
void mudRecvMessage()
{
struct mud_msgbuf qbuf;
int ret;
if (openQueue() < 0)
return;
while ((ret = msgrcv(qid, (struct msgbuf *)&qbuf, MAX_MSGBUF_LENGTH, my_ipc_id, IPC_NOWAIT)) > 0)
recvTextHandler(qbuf.mtext);
if (ret==-1 && errno!=ENOMSG)
vlogf(LOG_BUG, "mudRecvMessage: errno: %d ret: %d", errno, ret);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Daniel Selsam
*/
#include <iostream>
#include "library/tlean_exporter.h"
#include "library/unfold_macros.h"
#include "kernel/quotient/quotient.h"
#include "kernel/for_each_fn.h"
#include "kernel/instantiate.h"
#include "kernel/type_checker.h"
#include "kernel/inductive/inductive.h"
#include "library/module.h"
#include "library/class.h"
#include "library/attribute_manager.h"
namespace lean {
unsigned tlean_exporter::export_name(name const & n) {
auto it = m_name2idx.find(n);
if (it != m_name2idx.end()) {
return it->second;
}
unsigned i;
if (n.is_anonymous()) {
lean_unreachable();
} else if (n.is_string()) {
unsigned p = export_name(n.get_prefix());
i = static_cast<unsigned>(m_name2idx.size());
m_out << i << " #NS " << p << " " << n.get_string() << "\n";
} else {
unsigned p = export_name(n.get_prefix());
i = static_cast<unsigned>(m_name2idx.size());
m_out << i << " #NI " << p << " " << n.get_numeral() << "\n";
}
m_name2idx[n] = i;
return i;
}
unsigned tlean_exporter::export_level(level const & l) {
auto it = m_level2idx.find(l);
if (it != m_level2idx.end())
return it->second;
unsigned i = 0;
unsigned l1, l2, n;
switch (l.kind()) {
case level_kind::Zero:
lean_unreachable();
break;
case level_kind::Succ:
l1 = export_level(succ_of(l));
i = static_cast<unsigned>(m_level2idx.size());
m_out << i << " #US " << l1 << "\n";
break;
case level_kind::Max:
l1 = export_level(max_lhs(l));
l2 = export_level(max_rhs(l));
i = static_cast<unsigned>(m_level2idx.size());
m_out << i << " #UM " << l1 << " " << l2 << "\n";
break;
case level_kind::IMax:
l1 = export_level(imax_lhs(l));
l2 = export_level(imax_rhs(l));
i = static_cast<unsigned>(m_level2idx.size());
m_out << i << " #UIM " << l1 << " " << l2 << "\n";
break;
case level_kind::Param:
n = export_name(param_id(l));
i = static_cast<unsigned>(m_level2idx.size());
m_out << i << " #UP " << n << "\n";
break;
case level_kind::Meta:
throw exception("invalid 'export', universe meta-variables cannot be exported");
}
m_level2idx[l] = i;
return i;
}
void tlean_exporter::export_binder_info(binder_info const & bi) {
if (bi.is_implicit())
m_out << "#BI";
else if (bi.is_strict_implicit())
m_out << "#BS";
else if (bi.is_inst_implicit())
m_out << "#BC";
else
m_out << "#BD";
}
unsigned tlean_exporter::export_binding(expr const & e, char const * k) {
unsigned n = export_name(binding_name(e));
unsigned e1 = export_expr_core(binding_domain(e));
unsigned e2 = export_expr_core(binding_body(e));
unsigned i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " " << k << " ";
export_binder_info(binding_info(e));
m_out << " " << n << " " << e1 << " " << e2 << "\n";
return i;
}
unsigned tlean_exporter::export_const(expr const & e) {
buffer<unsigned> ls;
unsigned n = export_name(const_name(e));
for (level const & l : const_levels(e))
ls.push_back(export_level(l));
unsigned i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " #EC " << n;
for (unsigned l : ls)
m_out << " " << l;
m_out << "\n";
return i;
}
unsigned tlean_exporter::export_expr_core(expr const & e) {
auto it = m_expr2idx.find(e);
if (it != m_expr2idx.end())
return it->second;
unsigned i = 0;
unsigned l, e1, e2;
switch (e.kind()) {
case expr_kind::Var:
i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " #EV " << var_idx(e) << "\n";
break;
case expr_kind::Sort:
l = export_level(sort_level(e));
i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " #ES " << l << "\n";
break;
case expr_kind::Constant:
i = export_const(e);
break;
case expr_kind::App:
e1 = export_expr_core(app_fn(e));
e2 = export_expr_core(app_arg(e));
i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " #EA " << e1 << " " << e2 << "\n";
break;
case expr_kind::Let: {
auto n = export_name(let_name(e));
e1 = export_expr_core(let_type(e));
e2 = export_expr_core(let_value(e));
auto e3 = export_expr_core(let_body(e));
i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " #EZ " << n << " " << e1 << " " << e2 << " " << e3 << "\n";
break;
}
case expr_kind::Lambda:
i = export_binding(e, "#EL");
break;
case expr_kind::Pi:
i = export_binding(e, "#EP");
break;
case expr_kind::Meta:
throw exception("invalid 'export', meta-variables cannot be exported");
case expr_kind::Local:
throw exception("invalid 'export', local constants cannot be exported");
case expr_kind::Macro:
if (macro_def(e).can_textualize()) {
buffer<unsigned> args;
for (unsigned i = 0; i < macro_num_args(e); ++i) {
args.push_back(export_expr_core(macro_arg(e, i)));
}
i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " ";
macro_def(e).textualize(*this);
for (auto const & arg : args) {
m_out << " " << arg << "\n";
}
} else {
type_checker checker(m_env);
if (auto t = macro_def(e).expand(e, checker)) {
return export_expr_core(*t);
} else {
throw exception(sstream() << "found macro that cannot textualize nor expand\n" << e);
}
}
}
m_expr2idx[e] = i;
return i;
}
unsigned tlean_exporter::export_expr(expr const & e) {
return export_expr_core(e);
}
void tlean_exporter::export_definition(declaration const & d) {
auto hints = d.get_hints();
unsigned n = export_name(d.get_name());
auto ps = map2<unsigned>(d.get_univ_params(), [&] (name const & p) { return export_name(p); });
auto t = export_expr(d.get_type());
auto v = export_expr(d.get_value());
m_out << "#DEF " << n << " " << d.is_theorem() << " ";
if (hints.get_kind() == reducibility_hints::kind::Abbreviation) {
m_out << "A ";
} else if (hints.get_kind() == reducibility_hints::kind::Opaque) {
m_out << "O ";
} else {
m_out << hints.get_height() << "." << hints.use_self_opt() << " ";
}
m_out << t << " " << v;
for (unsigned p : ps)
m_out << " " << p;
m_out << "\n";
}
void tlean_exporter::export_axiom(declaration const & d) {
unsigned n = export_name(d.get_name());
auto ps = map2<unsigned>(d.get_univ_params(), [&] (name const & p) { return export_name(p); });
auto t = export_expr(d.get_type());
m_out << "#AX " << n << " " << t;
for (unsigned p : ps)
m_out << " " << p;
m_out << "\n";
}
void tlean_exporter::export_declaration(declaration const & d) {
if (!d.is_trusted()) return;
if (d.is_definition()) {
export_definition(d);
} else {
export_axiom(d);
}
}
void tlean_exporter::export_inductive(inductive::certified_inductive_decl const & cdecl) {
if (!cdecl.is_trusted()) return;
inductive::inductive_decl decl = cdecl.get_decl();
for (auto & p : decl.m_level_params)
export_name(p);
export_name(decl.m_name);
export_expr(decl.m_type);
for (auto & c : decl.m_intro_rules) {
export_name(inductive::intro_rule_name(c));
export_expr(inductive::intro_rule_type(c));
}
m_out << "#IND " << decl.m_num_params << " "
<< export_name(decl.m_name) << " "
<< export_expr(decl.m_type) << " "
<< length(decl.m_intro_rules);
for (auto & c : decl.m_intro_rules) {
// intro rules are stored as local constants, we split them up so that
// the type checkers do not need to implement local constants.
m_out << " " << export_name(inductive::intro_rule_name(c))
<< " " << export_expr(inductive::intro_rule_type(c));
}
for (name const & p : decl.m_level_params)
m_out << " " << export_name(p);
m_out << "\n";
}
tlean_exporter::tlean_exporter(std::ostream & out, environment const & env) : m_out(out), m_env(env) {
m_name2idx[{}] = 0;
m_level2idx[{}] = 0;
}
}
<commit_msg>fix(library/tlean_exporter): add recursion guard (#752)<commit_after>/*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Daniel Selsam
*/
#include <iostream>
#include "library/tlean_exporter.h"
#include "library/unfold_macros.h"
#include "kernel/quotient/quotient.h"
#include "kernel/for_each_fn.h"
#include "kernel/instantiate.h"
#include "kernel/type_checker.h"
#include "kernel/inductive/inductive.h"
#include "library/module.h"
#include "library/class.h"
#include "library/attribute_manager.h"
namespace lean {
static void check_system() { check_system("tlean exporter"); }
unsigned tlean_exporter::export_name(name const & n) {
auto it = m_name2idx.find(n);
if (it != m_name2idx.end()) {
return it->second;
}
unsigned i;
if (n.is_anonymous()) {
lean_unreachable();
} else if (n.is_string()) {
unsigned p = export_name(n.get_prefix());
i = static_cast<unsigned>(m_name2idx.size());
m_out << i << " #NS " << p << " " << n.get_string() << "\n";
} else {
unsigned p = export_name(n.get_prefix());
i = static_cast<unsigned>(m_name2idx.size());
m_out << i << " #NI " << p << " " << n.get_numeral() << "\n";
}
m_name2idx[n] = i;
return i;
}
unsigned tlean_exporter::export_level(level const & l) {
auto it = m_level2idx.find(l);
if (it != m_level2idx.end())
return it->second;
unsigned i = 0;
unsigned l1, l2, n;
switch (l.kind()) {
case level_kind::Zero:
lean_unreachable();
break;
case level_kind::Succ:
l1 = export_level(succ_of(l));
i = static_cast<unsigned>(m_level2idx.size());
m_out << i << " #US " << l1 << "\n";
break;
case level_kind::Max:
l1 = export_level(max_lhs(l));
l2 = export_level(max_rhs(l));
i = static_cast<unsigned>(m_level2idx.size());
m_out << i << " #UM " << l1 << " " << l2 << "\n";
break;
case level_kind::IMax:
l1 = export_level(imax_lhs(l));
l2 = export_level(imax_rhs(l));
i = static_cast<unsigned>(m_level2idx.size());
m_out << i << " #UIM " << l1 << " " << l2 << "\n";
break;
case level_kind::Param:
n = export_name(param_id(l));
i = static_cast<unsigned>(m_level2idx.size());
m_out << i << " #UP " << n << "\n";
break;
case level_kind::Meta:
throw exception("invalid 'export', universe meta-variables cannot be exported");
}
m_level2idx[l] = i;
return i;
}
void tlean_exporter::export_binder_info(binder_info const & bi) {
if (bi.is_implicit())
m_out << "#BI";
else if (bi.is_strict_implicit())
m_out << "#BS";
else if (bi.is_inst_implicit())
m_out << "#BC";
else
m_out << "#BD";
}
unsigned tlean_exporter::export_binding(expr const & e, char const * k) {
unsigned n = export_name(binding_name(e));
unsigned e1 = export_expr(binding_domain(e));
unsigned e2 = export_expr(binding_body(e));
unsigned i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " " << k << " ";
export_binder_info(binding_info(e));
m_out << " " << n << " " << e1 << " " << e2 << "\n";
return i;
}
unsigned tlean_exporter::export_const(expr const & e) {
buffer<unsigned> ls;
unsigned n = export_name(const_name(e));
for (level const & l : const_levels(e))
ls.push_back(export_level(l));
unsigned i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " #EC " << n;
for (unsigned l : ls)
m_out << " " << l;
m_out << "\n";
return i;
}
unsigned tlean_exporter::export_expr(expr const & e) {
auto it = m_expr2idx.find(e);
if (it != m_expr2idx.end())
return it->second;
unsigned i = 0;
unsigned l, e1, e2;
switch (e.kind()) {
case expr_kind::Var:
i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " #EV " << var_idx(e) << "\n";
break;
case expr_kind::Sort:
l = export_level(sort_level(e));
i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " #ES " << l << "\n";
break;
case expr_kind::Constant:
i = export_const(e);
break;
case expr_kind::App:
check_system();
e1 = export_expr(app_fn(e));
e2 = export_expr(app_arg(e));
i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " #EA " << e1 << " " << e2 << "\n";
break;
case expr_kind::Let: {
check_system();
auto n = export_name(let_name(e));
e1 = export_expr(let_type(e));
e2 = export_expr(let_value(e));
auto e3 = export_expr(let_body(e));
i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " #EZ " << n << " " << e1 << " " << e2 << " " << e3 << "\n";
break;
}
case expr_kind::Lambda:
check_system();
i = export_binding(e, "#EL");
break;
case expr_kind::Pi:
check_system();
i = export_binding(e, "#EP");
break;
case expr_kind::Meta:
throw exception("invalid 'export', meta-variables cannot be exported");
case expr_kind::Local:
throw exception("invalid 'export', local constants cannot be exported");
case expr_kind::Macro:
check_system();
if (macro_def(e).can_textualize()) {
buffer<unsigned> args;
for (unsigned i = 0; i < macro_num_args(e); ++i) {
args.push_back(export_expr(macro_arg(e, i)));
}
i = static_cast<unsigned>(m_expr2idx.size());
m_out << i << " ";
macro_def(e).textualize(*this);
for (auto const & arg : args) {
m_out << " " << arg << "\n";
}
} else {
type_checker checker(m_env);
if (auto t = macro_def(e).expand(e, checker)) {
return export_expr(*t);
} else {
throw exception(sstream() << "found macro that cannot textualize nor expand\n" << e);
}
}
}
m_expr2idx[e] = i;
return i;
}
void tlean_exporter::export_definition(declaration const & d) {
auto hints = d.get_hints();
unsigned n = export_name(d.get_name());
auto ps = map2<unsigned>(d.get_univ_params(), [&] (name const & p) { return export_name(p); });
auto t = export_expr(d.get_type());
auto v = export_expr(d.get_value());
m_out << "#DEF " << n << " " << d.is_theorem() << " ";
if (hints.get_kind() == reducibility_hints::kind::Abbreviation) {
m_out << "A ";
} else if (hints.get_kind() == reducibility_hints::kind::Opaque) {
m_out << "O ";
} else {
m_out << hints.get_height() << "." << hints.use_self_opt() << " ";
}
m_out << t << " " << v;
for (unsigned p : ps)
m_out << " " << p;
m_out << "\n";
}
void tlean_exporter::export_axiom(declaration const & d) {
unsigned n = export_name(d.get_name());
auto ps = map2<unsigned>(d.get_univ_params(), [&] (name const & p) { return export_name(p); });
auto t = export_expr(d.get_type());
m_out << "#AX " << n << " " << t;
for (unsigned p : ps)
m_out << " " << p;
m_out << "\n";
}
void tlean_exporter::export_declaration(declaration const & d) {
if (!d.is_trusted()) return;
if (d.is_definition()) {
export_definition(d);
} else {
export_axiom(d);
}
}
void tlean_exporter::export_inductive(inductive::certified_inductive_decl const & cdecl) {
if (!cdecl.is_trusted()) return;
inductive::inductive_decl decl = cdecl.get_decl();
for (auto & p : decl.m_level_params)
export_name(p);
export_name(decl.m_name);
export_expr(decl.m_type);
for (auto & c : decl.m_intro_rules) {
export_name(inductive::intro_rule_name(c));
export_expr(inductive::intro_rule_type(c));
}
m_out << "#IND " << decl.m_num_params << " "
<< export_name(decl.m_name) << " "
<< export_expr(decl.m_type) << " "
<< length(decl.m_intro_rules);
for (auto & c : decl.m_intro_rules) {
// intro rules are stored as local constants, we split them up so that
// the type checkers do not need to implement local constants.
m_out << " " << export_name(inductive::intro_rule_name(c))
<< " " << export_expr(inductive::intro_rule_type(c));
}
for (name const & p : decl.m_level_params)
m_out << " " << export_name(p);
m_out << "\n";
}
tlean_exporter::tlean_exporter(std::ostream & out, environment const & env) : m_out(out), m_env(env) {
m_name2idx[{}] = 0;
m_level2idx[{}] = 0;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtornt.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hr $ $Date: 2007-09-27 08:03:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FMTORNT_HXX
#define _FMTORNT_HXX
#include <com/sun/star/text/HoriOrientation.hpp>
#include <com/sun/star/text/VertOrientation.hpp>
#include <com/sun/star/text/RelOrientation.hpp>
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _SWTYPES_HXX //autogen
#include <swtypes.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
class IntlWrapper;
#define IVER_VERTORIENT_REL ((USHORT)0x0001)
class SW_DLLPUBLIC SwFmtVertOrient: public SfxPoolItem
{
SwTwips nYPos; //Enthaelt _immer_ die aktuelle RelPos.
sal_Int16 eOrient;
sal_Int16 eRelation;
public:
TYPEINFO();
SwFmtVertOrient( SwTwips nY = 0, sal_Int16 eVert = com::sun::star::text::VertOrientation::NONE,
sal_Int16 eRel = com::sun::star::text::RelOrientation::PRINT_AREA );
inline SwFmtVertOrient &operator=( const SwFmtVertOrient &rCpy );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
sal_Int16 GetVertOrient() const { return eOrient; }
sal_Int16 GetRelationOrient() const { return eRelation; }
void SetVertOrient( sal_Int16 eNew ) { eOrient = eNew; }
void SetRelationOrient( sal_Int16 eNew ) { eRelation = eNew; }
SwTwips GetPos() const { return nYPos; }
void SetPos( SwTwips nNew ) { nYPos = nNew; }
};
//SwFmtHoriOrient, wie und woran orientiert --
// sich der FlyFrm in der Hoizontalen ----------
#define IVER_HORIORIENT_TOGGLE ((USHORT)0x0001)
#define IVER_HORIORIENT_REL ((USHORT)0x0002)
class SW_DLLPUBLIC SwFmtHoriOrient: public SfxPoolItem
{
SwTwips nXPos; //Enthaelt _immer_ die aktuelle RelPos.
sal_Int16 eOrient;
sal_Int16 eRelation;
BOOL bPosToggle : 1; // auf geraden Seiten Position spiegeln
public:
TYPEINFO();
SwFmtHoriOrient( SwTwips nX = 0, sal_Int16 eHori = com::sun::star::text::HoriOrientation::NONE,
sal_Int16 eRel = com::sun::star::text::RelOrientation::PRINT_AREA, BOOL bPos = FALSE );
inline SwFmtHoriOrient &operator=( const SwFmtHoriOrient &rCpy );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
sal_Int16 GetHoriOrient() const { return eOrient; }
sal_Int16 GetRelationOrient() const { return eRelation; }
void SetHoriOrient( sal_Int16 eNew ) { eOrient = eNew; }
void SetRelationOrient( sal_Int16 eNew ) { eRelation = eNew; }
SwTwips GetPos() const { return nXPos; }
void SetPos( SwTwips nNew ) { nXPos = nNew; }
BOOL IsPosToggle() const { return bPosToggle; }
void SetPosToggle( BOOL bNew ) { bPosToggle = bNew; }
};
inline SwFmtVertOrient &SwFmtVertOrient::operator=( const SwFmtVertOrient &rCpy )
{
nYPos = rCpy.GetPos();
eOrient = rCpy.GetVertOrient();
eRelation = rCpy.GetRelationOrient();
return *this;
}
inline SwFmtHoriOrient &SwFmtHoriOrient::operator=( const SwFmtHoriOrient &rCpy )
{
nXPos = rCpy.GetPos();
eOrient = rCpy.GetHoriOrient();
eRelation = rCpy.GetRelationOrient();
bPosToggle = rCpy.IsPosToggle();
return *this;
}
inline const SwFmtVertOrient &SwAttrSet::GetVertOrient(BOOL bInP) const
{ return (const SwFmtVertOrient&)Get( RES_VERT_ORIENT,bInP); }
inline const SwFmtHoriOrient &SwAttrSet::GetHoriOrient(BOOL bInP) const
{ return (const SwFmtHoriOrient&)Get( RES_HORI_ORIENT,bInP); }
inline const SwFmtVertOrient &SwFmt::GetVertOrient(BOOL bInP) const
{ return aSet.GetVertOrient(bInP); }
inline const SwFmtHoriOrient &SwFmt::GetHoriOrient(BOOL bInP) const
{ return aSet.GetHoriOrient(bInP); }
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.12.242); FILE MERGED 2008/04/01 15:56:13 thb 1.12.242.3: #i85898# Stripping all external header guards 2008/04/01 12:53:30 thb 1.12.242.2: #i85898# Stripping all external header guards 2008/03/31 16:52:38 rt 1.12.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtornt.hxx,v $
* $Revision: 1.13 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _FMTORNT_HXX
#define _FMTORNT_HXX
#include <com/sun/star/text/HoriOrientation.hpp>
#include <com/sun/star/text/VertOrientation.hpp>
#include <com/sun/star/text/RelOrientation.hpp>
#include "swdllapi.h"
#include <hintids.hxx>
#include <swtypes.hxx>
#include <format.hxx>
#include <svtools/poolitem.hxx>
class IntlWrapper;
#define IVER_VERTORIENT_REL ((USHORT)0x0001)
class SW_DLLPUBLIC SwFmtVertOrient: public SfxPoolItem
{
SwTwips nYPos; //Enthaelt _immer_ die aktuelle RelPos.
sal_Int16 eOrient;
sal_Int16 eRelation;
public:
TYPEINFO();
SwFmtVertOrient( SwTwips nY = 0, sal_Int16 eVert = com::sun::star::text::VertOrientation::NONE,
sal_Int16 eRel = com::sun::star::text::RelOrientation::PRINT_AREA );
inline SwFmtVertOrient &operator=( const SwFmtVertOrient &rCpy );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
sal_Int16 GetVertOrient() const { return eOrient; }
sal_Int16 GetRelationOrient() const { return eRelation; }
void SetVertOrient( sal_Int16 eNew ) { eOrient = eNew; }
void SetRelationOrient( sal_Int16 eNew ) { eRelation = eNew; }
SwTwips GetPos() const { return nYPos; }
void SetPos( SwTwips nNew ) { nYPos = nNew; }
};
//SwFmtHoriOrient, wie und woran orientiert --
// sich der FlyFrm in der Hoizontalen ----------
#define IVER_HORIORIENT_TOGGLE ((USHORT)0x0001)
#define IVER_HORIORIENT_REL ((USHORT)0x0002)
class SW_DLLPUBLIC SwFmtHoriOrient: public SfxPoolItem
{
SwTwips nXPos; //Enthaelt _immer_ die aktuelle RelPos.
sal_Int16 eOrient;
sal_Int16 eRelation;
BOOL bPosToggle : 1; // auf geraden Seiten Position spiegeln
public:
TYPEINFO();
SwFmtHoriOrient( SwTwips nX = 0, sal_Int16 eHori = com::sun::star::text::HoriOrientation::NONE,
sal_Int16 eRel = com::sun::star::text::RelOrientation::PRINT_AREA, BOOL bPos = FALSE );
inline SwFmtHoriOrient &operator=( const SwFmtHoriOrient &rCpy );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
sal_Int16 GetHoriOrient() const { return eOrient; }
sal_Int16 GetRelationOrient() const { return eRelation; }
void SetHoriOrient( sal_Int16 eNew ) { eOrient = eNew; }
void SetRelationOrient( sal_Int16 eNew ) { eRelation = eNew; }
SwTwips GetPos() const { return nXPos; }
void SetPos( SwTwips nNew ) { nXPos = nNew; }
BOOL IsPosToggle() const { return bPosToggle; }
void SetPosToggle( BOOL bNew ) { bPosToggle = bNew; }
};
inline SwFmtVertOrient &SwFmtVertOrient::operator=( const SwFmtVertOrient &rCpy )
{
nYPos = rCpy.GetPos();
eOrient = rCpy.GetVertOrient();
eRelation = rCpy.GetRelationOrient();
return *this;
}
inline SwFmtHoriOrient &SwFmtHoriOrient::operator=( const SwFmtHoriOrient &rCpy )
{
nXPos = rCpy.GetPos();
eOrient = rCpy.GetHoriOrient();
eRelation = rCpy.GetRelationOrient();
bPosToggle = rCpy.IsPosToggle();
return *this;
}
inline const SwFmtVertOrient &SwAttrSet::GetVertOrient(BOOL bInP) const
{ return (const SwFmtVertOrient&)Get( RES_VERT_ORIENT,bInP); }
inline const SwFmtHoriOrient &SwAttrSet::GetHoriOrient(BOOL bInP) const
{ return (const SwFmtHoriOrient&)Get( RES_HORI_ORIENT,bInP); }
inline const SwFmtVertOrient &SwFmt::GetVertOrient(BOOL bInP) const
{ return aSet.GetVertOrient(bInP); }
inline const SwFmtHoriOrient &SwFmt::GetHoriOrient(BOOL bInP) const
{ return aSet.GetHoriOrient(bInP); }
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "treedelegate.h"
#include <QStyleOptionViewItem>
#include <QStyleOptionHeader>
#include <QStylePainter>
#include <QPainter>
#include <QPointer>
#include <QStyle>
class TreeHeader : public QWidget
{
Q_OBJECT
public:
TreeHeader(QWidget* parent = 0) : QWidget(parent) { d.state = QStyle::State_None; }
void setText(const QString& text) { d.text = text; }
void setIcon(const QIcon& icon) { d.icon = icon; }
void setState(QStyle::State state) { d.state = state; }
protected:
void paintEvent(QPaintEvent*)
{
QStyleOptionHeader option;
option.init(this);
option.state = d.state;
option.icon = d.icon;
option.text = d.text;
option.position = QStyleOptionHeader::OnlyOneSection;
QStylePainter painter(this);
painter.drawControl(QStyle::CE_Header, option);
}
private:
struct Private {
QIcon icon;
QString text;
QStyle::State state;
} d;
};
TreeDelegate::TreeDelegate(QObject* parent) : QStyledItemDelegate(parent)
{
}
void TreeDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
if (!index.parent().isValid()) {
static QPointer<TreeHeader> header;
if (!header)
header = new TreeHeader(const_cast<QWidget*>(option.widget));
header->setText(index.data(Qt::DisplayRole).toString());
header->setIcon(index.data(Qt::DecorationRole).value<QIcon>());
header->setState(option.state);
header->setGeometry(option.rect);
painter->translate(option.rect.topLeft());
header->render(painter);
painter->translate(-option.rect.topLeft());
} else {
QStyledItemDelegate::paint(painter, option, index);
}
}
#include "treedelegate.moc"
<commit_msg>Tweak TreeHeader painting<commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "treedelegate.h"
#include <QStyleOptionViewItem>
#include <QStyleOptionHeader>
#include <QStylePainter>
#include <QPainter>
#include <QPointer>
#include <QStyle>
#include <QColor>
class TreeHeader : public QWidget
{
Q_OBJECT
public:
TreeHeader(QWidget* parent = 0) : QWidget(parent) { d.state = QStyle::State_None; }
void setText(const QString& text) { d.text = text; }
void setIcon(const QIcon& icon) { d.icon = icon; }
void setState(QStyle::State state) { d.state = state; }
protected:
void paintEvent(QPaintEvent*)
{
QStyleOptionHeader option;
option.init(this);
option.state = (d.state | QStyle::State_Raised | QStyle::State_Horizontal);
if (d.state & QStyle::State_Selected)
option.state |= (QStyle::State_Sunken | QStyle::State_On);
option.icon = d.icon;
option.text = d.text;
option.position = QStyleOptionHeader::OnlyOneSection;
QStylePainter painter(this);
painter.drawControl(QStyle::CE_Header, option);
}
private:
struct Private {
QIcon icon;
QString text;
QStyle::State state;
} d;
};
TreeDelegate::TreeDelegate(QObject* parent) : QStyledItemDelegate(parent)
{
}
void TreeDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
if (!index.parent().isValid()) {
static QPointer<TreeHeader> header;
if (!header)
header = new TreeHeader(const_cast<QWidget*>(option.widget));
QPalette pal = option.palette;
QVariant fg = index.data(Qt::ForegroundRole);
if (fg.isValid()) {
pal.setColor(QPalette::Text, fg.value<QColor>());
pal.setColor(QPalette::ButtonText, fg.value<QColor>());
pal.setColor(QPalette::WindowText, fg.value<QColor>());
}
header->setPalette(pal);
header->setText(index.data(Qt::DisplayRole).toString());
header->setIcon(index.data(Qt::DecorationRole).value<QIcon>());
header->setState(option.state);
header->setGeometry(option.rect);
painter->translate(option.rect.topLeft());
header->render(painter);
painter->translate(-option.rect.topLeft());
} else {
QStyledItemDelegate::paint(painter, option, index);
}
}
#include "treedelegate.moc"
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "environment.h"
#include <QtCore/QProcess>
#include <QtCore/QDir>
#include <QtCore/QString>
using namespace Utils;
QList<EnvironmentItem> EnvironmentItem::fromStringList(QStringList list)
{
QList<EnvironmentItem> result;
foreach (const QString &string, list) {
int pos = string.indexOf(QLatin1Char('='));
if (pos == -1) {
EnvironmentItem item(string, QString());
item.unset = true;
result.append(item);
} else {
EnvironmentItem item(string.left(pos), string.mid(pos+1));
result.append(item);
}
}
return result;
}
QStringList EnvironmentItem::toStringList(QList<EnvironmentItem> list)
{
QStringList result;
foreach (const EnvironmentItem &item, list) {
if (item.unset)
result << QString(item.name);
else
result << QString(item.name + '=' + item.value);
}
return result;
}
Environment::Environment()
{
}
Environment::Environment(QStringList env)
{
foreach (const QString &s, env) {
int i = s.indexOf("=");
if (i >= 0) {
#ifdef Q_OS_WIN
m_values.insert(s.left(i).toUpper(), s.mid(i+1));
#else
m_values.insert(s.left(i), s.mid(i+1));
#endif
}
}
}
QStringList Environment::toStringList() const
{
QStringList result;
const QMap<QString, QString>::const_iterator end = m_values.constEnd();
for (QMap<QString, QString>::const_iterator it = m_values.constBegin(); it != end; ++it) {
QString entry = it.key();
entry += QLatin1Char('=');
entry += it.value();
result.push_back(entry);
}
return result;
}
void Environment::set(const QString &key, const QString &value)
{
#ifdef Q_OS_WIN
QString _key = key.toUpper();
#else
const QString &_key = key;
#endif
m_values.insert(_key, value);
}
void Environment::unset(const QString &key)
{
#ifdef Q_OS_WIN
QString _key = key.toUpper();
#else
const QString &_key = key;
#endif
m_values.remove(_key);
}
void Environment::appendOrSet(const QString &key, const QString &value, const QString &sep)
{
#ifdef Q_OS_WIN
QString _key = key.toUpper();
#else
const QString &_key = key;
#endif
QMap<QString, QString>::iterator it = m_values.find(key);
if (it == m_values.end()) {
m_values.insert(_key, value);
} else {
// Append unless it is already there
const QString toAppend = sep + value;
if (!it.value().endsWith(toAppend))
it.value().append(toAppend);
}
}
void Environment::prependOrSet(const QString&key, const QString &value, const QString &sep)
{
#ifdef Q_OS_WIN
QString _key = key.toUpper();
#else
const QString &_key = key;
#endif
QMap<QString, QString>::iterator it = m_values.find(key);
if (it == m_values.end()) {
m_values.insert(_key, value);
} else {
// Prepend unless it is already there
const QString toPrepend = value + sep;
if (!it.value().startsWith(toPrepend))
it.value().prepend(toPrepend);
}
}
void Environment::appendOrSetPath(const QString &value)
{
#ifdef Q_OS_WIN
const QChar sep = QLatin1Char(';');
#else
const QChar sep = QLatin1Char(':');
#endif
appendOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value), QString(sep));
}
void Environment::prependOrSetPath(const QString &value)
{
#ifdef Q_OS_WIN
const QChar sep = QLatin1Char(';');
#else
const QChar sep = QLatin1Char(':');
#endif
prependOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value), QString(sep));
}
void Environment::prependOrSetLibrarySearchPath(const QString &value)
{
#ifdef Q_OS_WIN
const QChar sep = QLatin1Char(';');
#else
const QChar sep = QLatin1Char(':');
#endif
#ifdef Q_OS_WIN
const QLatin1String path("PATH");
#elif defined(Q_OS_MAC)
const QLatin1String path("DYLD_LIBRARY_PATH");
#elif defined(Q_OS_UNIX)
const QLatin1String path("LD_LIBRARY_PATH");
#else
return;
#endif
prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
}
Environment Environment::systemEnvironment()
{
return Environment(QProcess::systemEnvironment());
}
void Environment::clear()
{
m_values.clear();
}
QString Environment::searchInPath(const QString &executable,
const QStringList &additionalDirs) const
{
QStringList execs;
execs << executable;
#ifdef Q_OS_WIN
// Check all the executable extensions on windows:
QStringList extensions = value(QLatin1String("PATHEXT")).split(QLatin1Char(';'));
// .exe.bat is legal (and run when starting new.exe), so always go through the complete list once:
foreach (const QString &ext, extensions)
execs << executable + ext.toLower();
#endif
return searchInPath(execs, additionalDirs);
}
QString Environment::searchInPath(const QStringList &executables,
const QStringList &additionalDirs) const
{
foreach (const QString &executable, executables) {
QString exec = expandVariables(executable);
if (exec.isEmpty())
continue;
QFileInfo baseFi(exec);
if (baseFi.isAbsolute() && baseFi.exists())
return QDir::fromNativeSeparators(exec);
// Check in directories:
foreach (const QString &dir, additionalDirs) {
if (dir.isEmpty())
continue;
QFileInfo fi(dir + QLatin1Char('/') + exec);
if (fi.isFile() && fi.isExecutable())
return fi.absoluteFilePath();
}
// Check in path:
const QChar slash = QLatin1Char('/');
if (exec.indexOf(slash) != -1)
continue;
foreach (const QString &p, path()) {
QString fp = p;
fp += slash;
fp += exec;
const QFileInfo fi(fp);
if (fi.exists() && fi.isExecutable() && !fi.isDir())
return fi.absoluteFilePath();
}
}
return QString();
}
QStringList Environment::path() const
{
#ifdef Q_OS_WIN
const QChar sep = QLatin1Char(';');
#else
const QChar sep = QLatin1Char(':');
#endif
return m_values.value(QLatin1String("PATH")).split(sep, QString::SkipEmptyParts);
}
QString Environment::value(const QString &key) const
{
return m_values.value(key);
}
QString Environment::key(Environment::const_iterator it) const
{
return it.key();
}
QString Environment::value(Environment::const_iterator it) const
{
return it.value();
}
Environment::const_iterator Environment::constBegin() const
{
return m_values.constBegin();
}
Environment::const_iterator Environment::constEnd() const
{
return m_values.constEnd();
}
Environment::const_iterator Environment::constFind(const QString &name) const
{
QMap<QString, QString>::const_iterator it = m_values.constFind(name);
if (it == m_values.constEnd())
return constEnd();
else
return it;
}
int Environment::size() const
{
return m_values.size();
}
void Environment::modify(const QList<EnvironmentItem> & list)
{
Environment resultEnvironment = *this;
foreach (const EnvironmentItem &item, list) {
if (item.unset) {
resultEnvironment.unset(item.name);
} else {
// TODO use variable expansion
QString value = item.value;
for (int i=0; i < value.size(); ++i) {
if (value.at(i) == QLatin1Char('$')) {
if ((i + 1) < value.size()) {
const QChar &c = value.at(i+1);
int end = -1;
if (c == '(')
end = value.indexOf(')', i);
else if (c == '{')
end = value.indexOf('}', i);
if (end != -1) {
const QString &name = value.mid(i+2, end-i-2);
Environment::const_iterator it = constFind(name);
if (it != constEnd())
value.replace(i, end-i+1, it.value());
}
}
}
}
resultEnvironment.set(item.name, value);
}
}
*this = resultEnvironment;
}
QList<EnvironmentItem> Environment::diff(const Environment &other) const
{
QMap<QString, QString>::const_iterator thisIt = constBegin();
QMap<QString, QString>::const_iterator otherIt = other.constBegin();
QList<EnvironmentItem> result;
while (thisIt != constEnd() || otherIt != other.constEnd()) {
if (thisIt == constEnd()) {
result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
++otherIt;
} else if (otherIt == constEnd()) {
Utils::EnvironmentItem item(thisIt.key(), QString());
item.unset = true;
result.append(item);
++thisIt;
} else if (thisIt.key() < otherIt.key()) {
Utils::EnvironmentItem item(thisIt.key(), QString());
item.unset = true;
result.append(item);
++thisIt;
} else if (thisIt.key() > otherIt.key()) {
result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
++otherIt;
} else {
result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
++otherIt;
++thisIt;
}
}
return result;
}
bool Environment::hasKey(const QString &key)
{
return m_values.contains(key);
}
bool Environment::operator!=(const Environment &other) const
{
return !(*this == other);
}
bool Environment::operator==(const Environment &other) const
{
return m_values == other.m_values;
}
/** Expand environment variables in a string.
*
* Environment variables are accepted in the following forms:
* $SOMEVAR, ${SOMEVAR} on Unix and %SOMEVAR% on Windows.
* No escapes and quoting are supported.
* If a variable is not found, it is not substituted.
*/
QString Environment::expandVariables(const QString &input) const
{
QString result = input;
#ifdef Q_OS_WIN
for (int vStart = -1, i = 0; i < result.length(); ) {
if (result.at(i++) == QLatin1Char('%')) {
if (vStart > 0) {
const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1).toUpper());
if (it != m_values.constEnd()) {
result.replace(vStart - 1, i - vStart + 1, *it);
i = vStart - 1 + it->length();
vStart = -1;
} else {
vStart = i;
}
} else {
vStart = i;
}
}
}
#else
enum { BASE, OPTIONALVARIABLEBRACE, VARIABLE, BRACEDVARIABLE } state = BASE;
int vStart = -1;
for (int i = 0; i < result.length();) {
QChar c = result.at(i++);
if (state == BASE) {
if (c == QLatin1Char('$'))
state = OPTIONALVARIABLEBRACE;
} else if (state == OPTIONALVARIABLEBRACE) {
if (c == QLatin1Char('{')) {
state = BRACEDVARIABLE;
vStart = i;
} else if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
state = VARIABLE;
vStart = i - 1;
} else {
state = BASE;
}
} else if (state == BRACEDVARIABLE) {
if (c == QLatin1Char('}')) {
const_iterator it = m_values.constFind(result.mid(vStart, i - 1 - vStart));
if (it != constEnd()) {
result.replace(vStart - 2, i - vStart + 2, *it);
i = vStart - 2 + it->length();
}
state = BASE;
}
} else if (state == VARIABLE) {
if (!c.isLetterOrNumber() && c != QLatin1Char('_')) {
const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1));
if (it != constEnd()) {
result.replace(vStart - 1, i - vStart, *it);
i = vStart - 1 + it->length();
}
state = BASE;
}
}
}
if (state == VARIABLE) {
const_iterator it = m_values.constFind(result.mid(vStart));
if (it != constEnd())
result.replace(vStart - 1, result.length() - vStart + 1, *it);
}
#endif
return result;
}
QStringList Environment::expandVariables(const QStringList &variables) const
{
QStringList results;
foreach (const QString & i, variables)
results << expandVariables(i);
return results;
}
<commit_msg>Don't adjust DYLD_LIBRARY_PATH in run environments.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "environment.h"
#include <QtCore/QProcess>
#include <QtCore/QDir>
#include <QtCore/QString>
using namespace Utils;
QList<EnvironmentItem> EnvironmentItem::fromStringList(QStringList list)
{
QList<EnvironmentItem> result;
foreach (const QString &string, list) {
int pos = string.indexOf(QLatin1Char('='));
if (pos == -1) {
EnvironmentItem item(string, QString());
item.unset = true;
result.append(item);
} else {
EnvironmentItem item(string.left(pos), string.mid(pos+1));
result.append(item);
}
}
return result;
}
QStringList EnvironmentItem::toStringList(QList<EnvironmentItem> list)
{
QStringList result;
foreach (const EnvironmentItem &item, list) {
if (item.unset)
result << QString(item.name);
else
result << QString(item.name + '=' + item.value);
}
return result;
}
Environment::Environment()
{
}
Environment::Environment(QStringList env)
{
foreach (const QString &s, env) {
int i = s.indexOf("=");
if (i >= 0) {
#ifdef Q_OS_WIN
m_values.insert(s.left(i).toUpper(), s.mid(i+1));
#else
m_values.insert(s.left(i), s.mid(i+1));
#endif
}
}
}
QStringList Environment::toStringList() const
{
QStringList result;
const QMap<QString, QString>::const_iterator end = m_values.constEnd();
for (QMap<QString, QString>::const_iterator it = m_values.constBegin(); it != end; ++it) {
QString entry = it.key();
entry += QLatin1Char('=');
entry += it.value();
result.push_back(entry);
}
return result;
}
void Environment::set(const QString &key, const QString &value)
{
#ifdef Q_OS_WIN
QString _key = key.toUpper();
#else
const QString &_key = key;
#endif
m_values.insert(_key, value);
}
void Environment::unset(const QString &key)
{
#ifdef Q_OS_WIN
QString _key = key.toUpper();
#else
const QString &_key = key;
#endif
m_values.remove(_key);
}
void Environment::appendOrSet(const QString &key, const QString &value, const QString &sep)
{
#ifdef Q_OS_WIN
QString _key = key.toUpper();
#else
const QString &_key = key;
#endif
QMap<QString, QString>::iterator it = m_values.find(key);
if (it == m_values.end()) {
m_values.insert(_key, value);
} else {
// Append unless it is already there
const QString toAppend = sep + value;
if (!it.value().endsWith(toAppend))
it.value().append(toAppend);
}
}
void Environment::prependOrSet(const QString&key, const QString &value, const QString &sep)
{
#ifdef Q_OS_WIN
QString _key = key.toUpper();
#else
const QString &_key = key;
#endif
QMap<QString, QString>::iterator it = m_values.find(key);
if (it == m_values.end()) {
m_values.insert(_key, value);
} else {
// Prepend unless it is already there
const QString toPrepend = value + sep;
if (!it.value().startsWith(toPrepend))
it.value().prepend(toPrepend);
}
}
void Environment::appendOrSetPath(const QString &value)
{
#ifdef Q_OS_WIN
const QChar sep = QLatin1Char(';');
#else
const QChar sep = QLatin1Char(':');
#endif
appendOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value), QString(sep));
}
void Environment::prependOrSetPath(const QString &value)
{
#ifdef Q_OS_WIN
const QChar sep = QLatin1Char(';');
#else
const QChar sep = QLatin1Char(':');
#endif
prependOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value), QString(sep));
}
void Environment::prependOrSetLibrarySearchPath(const QString &value)
{
#ifdef Q_OS_WIN
const QChar sep = QLatin1Char(';');
#else
const QChar sep = QLatin1Char(':');
#endif
#ifdef Q_OS_WIN
const QLatin1String path("PATH");
#elif defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
const QLatin1String path("LD_LIBRARY_PATH");
#else
// we could set DYLD_LIBRARY_PATH on Mac but it is unnecessary in practice
return;
#endif
prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
}
Environment Environment::systemEnvironment()
{
return Environment(QProcess::systemEnvironment());
}
void Environment::clear()
{
m_values.clear();
}
QString Environment::searchInPath(const QString &executable,
const QStringList &additionalDirs) const
{
QStringList execs;
execs << executable;
#ifdef Q_OS_WIN
// Check all the executable extensions on windows:
QStringList extensions = value(QLatin1String("PATHEXT")).split(QLatin1Char(';'));
// .exe.bat is legal (and run when starting new.exe), so always go through the complete list once:
foreach (const QString &ext, extensions)
execs << executable + ext.toLower();
#endif
return searchInPath(execs, additionalDirs);
}
QString Environment::searchInPath(const QStringList &executables,
const QStringList &additionalDirs) const
{
foreach (const QString &executable, executables) {
QString exec = expandVariables(executable);
if (exec.isEmpty())
continue;
QFileInfo baseFi(exec);
if (baseFi.isAbsolute() && baseFi.exists())
return QDir::fromNativeSeparators(exec);
// Check in directories:
foreach (const QString &dir, additionalDirs) {
if (dir.isEmpty())
continue;
QFileInfo fi(dir + QLatin1Char('/') + exec);
if (fi.isFile() && fi.isExecutable())
return fi.absoluteFilePath();
}
// Check in path:
const QChar slash = QLatin1Char('/');
if (exec.indexOf(slash) != -1)
continue;
foreach (const QString &p, path()) {
QString fp = p;
fp += slash;
fp += exec;
const QFileInfo fi(fp);
if (fi.exists() && fi.isExecutable() && !fi.isDir())
return fi.absoluteFilePath();
}
}
return QString();
}
QStringList Environment::path() const
{
#ifdef Q_OS_WIN
const QChar sep = QLatin1Char(';');
#else
const QChar sep = QLatin1Char(':');
#endif
return m_values.value(QLatin1String("PATH")).split(sep, QString::SkipEmptyParts);
}
QString Environment::value(const QString &key) const
{
return m_values.value(key);
}
QString Environment::key(Environment::const_iterator it) const
{
return it.key();
}
QString Environment::value(Environment::const_iterator it) const
{
return it.value();
}
Environment::const_iterator Environment::constBegin() const
{
return m_values.constBegin();
}
Environment::const_iterator Environment::constEnd() const
{
return m_values.constEnd();
}
Environment::const_iterator Environment::constFind(const QString &name) const
{
QMap<QString, QString>::const_iterator it = m_values.constFind(name);
if (it == m_values.constEnd())
return constEnd();
else
return it;
}
int Environment::size() const
{
return m_values.size();
}
void Environment::modify(const QList<EnvironmentItem> & list)
{
Environment resultEnvironment = *this;
foreach (const EnvironmentItem &item, list) {
if (item.unset) {
resultEnvironment.unset(item.name);
} else {
// TODO use variable expansion
QString value = item.value;
for (int i=0; i < value.size(); ++i) {
if (value.at(i) == QLatin1Char('$')) {
if ((i + 1) < value.size()) {
const QChar &c = value.at(i+1);
int end = -1;
if (c == '(')
end = value.indexOf(')', i);
else if (c == '{')
end = value.indexOf('}', i);
if (end != -1) {
const QString &name = value.mid(i+2, end-i-2);
Environment::const_iterator it = constFind(name);
if (it != constEnd())
value.replace(i, end-i+1, it.value());
}
}
}
}
resultEnvironment.set(item.name, value);
}
}
*this = resultEnvironment;
}
QList<EnvironmentItem> Environment::diff(const Environment &other) const
{
QMap<QString, QString>::const_iterator thisIt = constBegin();
QMap<QString, QString>::const_iterator otherIt = other.constBegin();
QList<EnvironmentItem> result;
while (thisIt != constEnd() || otherIt != other.constEnd()) {
if (thisIt == constEnd()) {
result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
++otherIt;
} else if (otherIt == constEnd()) {
Utils::EnvironmentItem item(thisIt.key(), QString());
item.unset = true;
result.append(item);
++thisIt;
} else if (thisIt.key() < otherIt.key()) {
Utils::EnvironmentItem item(thisIt.key(), QString());
item.unset = true;
result.append(item);
++thisIt;
} else if (thisIt.key() > otherIt.key()) {
result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
++otherIt;
} else {
result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
++otherIt;
++thisIt;
}
}
return result;
}
bool Environment::hasKey(const QString &key)
{
return m_values.contains(key);
}
bool Environment::operator!=(const Environment &other) const
{
return !(*this == other);
}
bool Environment::operator==(const Environment &other) const
{
return m_values == other.m_values;
}
/** Expand environment variables in a string.
*
* Environment variables are accepted in the following forms:
* $SOMEVAR, ${SOMEVAR} on Unix and %SOMEVAR% on Windows.
* No escapes and quoting are supported.
* If a variable is not found, it is not substituted.
*/
QString Environment::expandVariables(const QString &input) const
{
QString result = input;
#ifdef Q_OS_WIN
for (int vStart = -1, i = 0; i < result.length(); ) {
if (result.at(i++) == QLatin1Char('%')) {
if (vStart > 0) {
const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1).toUpper());
if (it != m_values.constEnd()) {
result.replace(vStart - 1, i - vStart + 1, *it);
i = vStart - 1 + it->length();
vStart = -1;
} else {
vStart = i;
}
} else {
vStart = i;
}
}
}
#else
enum { BASE, OPTIONALVARIABLEBRACE, VARIABLE, BRACEDVARIABLE } state = BASE;
int vStart = -1;
for (int i = 0; i < result.length();) {
QChar c = result.at(i++);
if (state == BASE) {
if (c == QLatin1Char('$'))
state = OPTIONALVARIABLEBRACE;
} else if (state == OPTIONALVARIABLEBRACE) {
if (c == QLatin1Char('{')) {
state = BRACEDVARIABLE;
vStart = i;
} else if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
state = VARIABLE;
vStart = i - 1;
} else {
state = BASE;
}
} else if (state == BRACEDVARIABLE) {
if (c == QLatin1Char('}')) {
const_iterator it = m_values.constFind(result.mid(vStart, i - 1 - vStart));
if (it != constEnd()) {
result.replace(vStart - 2, i - vStart + 2, *it);
i = vStart - 2 + it->length();
}
state = BASE;
}
} else if (state == VARIABLE) {
if (!c.isLetterOrNumber() && c != QLatin1Char('_')) {
const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1));
if (it != constEnd()) {
result.replace(vStart - 1, i - vStart, *it);
i = vStart - 1 + it->length();
}
state = BASE;
}
}
}
if (state == VARIABLE) {
const_iterator it = m_values.constFind(result.mid(vStart));
if (it != constEnd())
result.replace(vStart - 1, result.length() - vStart + 1, *it);
}
#endif
return result;
}
QStringList Environment::expandVariables(const QStringList &variables) const
{
QStringList results;
foreach (const QString & i, variables)
results << expandVariables(i);
return results;
}
<|endoftext|> |
<commit_before>#include "search_engine.hpp"
#include "result.hpp"
#include "search_query.hpp"
#include "../storage/country_info.hpp"
#include "../indexer/categories_holder.hpp"
#include "../indexer/search_string_utils.hpp"
#include "../indexer/mercator.hpp"
#include "../indexer/scales.hpp"
#include "../platform/platform.hpp"
#include "../geometry/distance_on_sphere.hpp"
#include "../base/logging.hpp"
#include "../base/stl_add.hpp"
#include "../std/map.hpp"
#include "../std/vector.hpp"
#include "../std/bind.hpp"
namespace search
{
typedef vector<Query::SuggestT> SuggestsContainerT;
class EngineData
{
public:
EngineData(Reader * pCategoriesR, ModelReaderPtr polyR, ModelReaderPtr countryR)
: m_categories(pCategoriesR), m_infoGetter(polyR, countryR)
{
}
CategoriesHolder m_categories;
SuggestsContainerT m_stringsToSuggest;
storage::CountryInfoGetter m_infoGetter;
};
namespace
{
class InitSuggestions
{
// Key - is a string with language.
typedef map<pair<strings::UniString, int8_t>, uint8_t> SuggestMapT;
SuggestMapT m_suggests;
public:
void operator() (CategoriesHolder::Category::Name const & name)
{
if (name.m_prefixLengthToSuggest != CategoriesHolder::Category::EMPTY_PREFIX_LENGTH)
{
strings::UniString const uniName = NormalizeAndSimplifyString(name.m_name);
uint8_t & score = m_suggests[make_pair(uniName, name.m_lang)];
if (score == 0 || score > name.m_prefixLengthToSuggest)
score = name.m_prefixLengthToSuggest;
}
}
void GetSuggests(SuggestsContainerT & cont) const
{
cont.reserve(m_suggests.size());
for (SuggestMapT::const_iterator i = m_suggests.begin(); i != m_suggests.end(); ++i)
cont.push_back(Query::SuggestT(i->first.first, i->second, i->first.second));
}
};
}
Engine::Engine(IndexType const * pIndex, Reader * pCategoriesR,
ModelReaderPtr polyR, ModelReaderPtr countryR,
string const & lang)
: m_readyThread(false),
m_pIndex(pIndex),
m_pData(new EngineData(pCategoriesR, polyR, countryR))
{
InitSuggestions doInit;
m_pData->m_categories.ForEachName(bind<void>(ref(doInit), _1));
doInit.GetSuggests(m_pData->m_stringsToSuggest);
m_pQuery.reset(new Query(pIndex,
&m_pData->m_categories,
&m_pData->m_stringsToSuggest,
&m_pData->m_infoGetter,
RESULTS_COUNT));
m_pQuery->SetPreferredLanguage(lang);
}
Engine::~Engine()
{
}
namespace
{
m2::PointD GetViewportXY(double lat, double lon)
{
return m2::PointD(MercatorBounds::LonToX(lon), MercatorBounds::LatToY(lat));
}
m2::RectD GetViewportRect(double lat, double lon, double radius = 20000)
{
return MercatorBounds::MetresToXY(lon, lat, radius);
}
enum { VIEWPORT_RECT = 0, NEARME_RECT = 1 };
/// Check rects for optimal search (avoid duplicating).
void AnalizeRects(m2::RectD arrRects[2])
{
if (arrRects[NEARME_RECT].IsRectInside(arrRects[VIEWPORT_RECT]))
arrRects[VIEWPORT_RECT].MakeEmpty();
else
{
if (arrRects[VIEWPORT_RECT].IsRectInside(arrRects[NEARME_RECT]) &&
(scales::GetScaleLevel(arrRects[VIEWPORT_RECT]) + Query::m_scaleDepthSearch >= scales::GetUpperScale()))
{
arrRects[NEARME_RECT].MakeEmpty();
}
}
}
}
void Engine::PrepareSearch(m2::RectD const & viewport,
bool hasPt, double lat, double lon)
{
m2::RectD const nearby = (hasPt ? GetViewportRect(lat, lon) : m2::RectD());
// bind does copy of all rects
GetPlatform().RunAsync(bind(&Engine::SetViewportAsync, this, viewport, nearby));
}
void Engine::Search(SearchParams const & params, m2::RectD const & viewport)
{
Platform & p = GetPlatform();
{
threads::MutexGuard guard(m_updateMutex);
m_params = params;
m_viewport = viewport;
}
p.RunAsync(bind(&Engine::SearchAsync, this));
}
void Engine::SetViewportAsync(m2::RectD const & viewport, m2::RectD const & nearby)
{
// First of all - cancel previous query.
m_pQuery->DoCancel();
// Enter to run new search.
threads::MutexGuard searchGuard(m_searchMutex);
m2::RectD arrRects[] = { viewport, nearby };
AnalizeRects(arrRects);
m_pQuery->SetViewport(arrRects, ARRAY_SIZE(arrRects));
}
void Engine::SearchAsync()
{
{
// Avoid many threads waiting in search mutex. One is enough.
threads::MutexGuard readyGuard(m_readyMutex);
if (m_readyThread)
return;
m_readyThread = true;
}
// First of all - cancel previous query.
m_pQuery->DoCancel();
// Enter to run new search.
threads::MutexGuard searchGuard(m_searchMutex);
{
threads::MutexGuard readyGuard(m_readyMutex);
m_readyThread = false;
}
// Get current search params.
SearchParams params;
m2::RectD arrRects[2];
{
threads::MutexGuard updateGuard(m_updateMutex);
params = m_params;
arrRects[VIEWPORT_RECT] = m_viewport;
}
// Initialize query.
bool worldSearch = true;
if (params.m_validPos)
{
m_pQuery->SetPosition(GetViewportXY(params.m_lat, params.m_lon));
arrRects[NEARME_RECT] = GetViewportRect(params.m_lat, params.m_lon);
// Do not search in viewport for "NearMe" mode.
if (params.IsNearMeMode())
{
worldSearch = false;
arrRects[VIEWPORT_RECT].MakeEmpty();
}
else
AnalizeRects(arrRects);
}
else
m_pQuery->NullPosition();
m_pQuery->SetViewport(arrRects, 2);
m_pQuery->SetSearchInWorld(worldSearch);
if (params.IsLanguageValid())
m_pQuery->SetInputLanguage(params.m_inputLanguageCode);
Results res;
try
{
if (params.m_query.empty())
{
if (params.m_validPos)
{
double arrR[] = { 500, 1000, 2000 };
for (size_t i = 0; i < ARRAY_SIZE(arrR); ++i)
{
res.Clear();
m_pQuery->SearchAllInViewport(GetViewportRect(params.m_lat, params.m_lon, arrR[i]), res, 3*RESULTS_COUNT);
if (m_pQuery->IsCanceled() || res.Count() >= 2*RESULTS_COUNT)
break;
}
}
}
else
m_pQuery->Search(params.m_query, res);
}
catch (Query::CancelException const &)
{
}
// Emit results in any way, even if search was canceled.
params.m_callback(res);
// Make additional search in whole mwm when not enough results.
if (!m_pQuery->IsCanceled() && res.Count() < RESULTS_COUNT)
{
try
{
m_pQuery->SearchAdditional(res);
}
catch (Query::CancelException const &)
{
}
params.m_callback(res);
}
}
string Engine::GetCountryFile(m2::PointD const & pt) const
{
return m_pData->m_infoGetter.GetRegionFile(pt);
}
string Engine::GetCountryCode(m2::PointD const & pt) const
{
storage::CountryInfo info;
m_pData->m_infoGetter.GetRegionInfo(pt, info);
return info.m_flag;
}
} // namespace search
<commit_msg>[search] Fixed issue when viewport was close to My Position but results from viewport were not included<commit_after>#include "search_engine.hpp"
#include "result.hpp"
#include "search_query.hpp"
#include "../storage/country_info.hpp"
#include "../indexer/categories_holder.hpp"
#include "../indexer/search_string_utils.hpp"
#include "../indexer/mercator.hpp"
#include "../indexer/scales.hpp"
#include "../platform/platform.hpp"
#include "../geometry/distance_on_sphere.hpp"
#include "../base/logging.hpp"
#include "../base/stl_add.hpp"
#include "../std/map.hpp"
#include "../std/vector.hpp"
#include "../std/bind.hpp"
namespace search
{
typedef vector<Query::SuggestT> SuggestsContainerT;
class EngineData
{
public:
EngineData(Reader * pCategoriesR, ModelReaderPtr polyR, ModelReaderPtr countryR)
: m_categories(pCategoriesR), m_infoGetter(polyR, countryR)
{
}
CategoriesHolder m_categories;
SuggestsContainerT m_stringsToSuggest;
storage::CountryInfoGetter m_infoGetter;
};
namespace
{
class InitSuggestions
{
// Key - is a string with language.
typedef map<pair<strings::UniString, int8_t>, uint8_t> SuggestMapT;
SuggestMapT m_suggests;
public:
void operator() (CategoriesHolder::Category::Name const & name)
{
if (name.m_prefixLengthToSuggest != CategoriesHolder::Category::EMPTY_PREFIX_LENGTH)
{
strings::UniString const uniName = NormalizeAndSimplifyString(name.m_name);
uint8_t & score = m_suggests[make_pair(uniName, name.m_lang)];
if (score == 0 || score > name.m_prefixLengthToSuggest)
score = name.m_prefixLengthToSuggest;
}
}
void GetSuggests(SuggestsContainerT & cont) const
{
cont.reserve(m_suggests.size());
for (SuggestMapT::const_iterator i = m_suggests.begin(); i != m_suggests.end(); ++i)
cont.push_back(Query::SuggestT(i->first.first, i->second, i->first.second));
}
};
}
Engine::Engine(IndexType const * pIndex, Reader * pCategoriesR,
ModelReaderPtr polyR, ModelReaderPtr countryR,
string const & lang)
: m_readyThread(false),
m_pIndex(pIndex),
m_pData(new EngineData(pCategoriesR, polyR, countryR))
{
InitSuggestions doInit;
m_pData->m_categories.ForEachName(bind<void>(ref(doInit), _1));
doInit.GetSuggests(m_pData->m_stringsToSuggest);
m_pQuery.reset(new Query(pIndex,
&m_pData->m_categories,
&m_pData->m_stringsToSuggest,
&m_pData->m_infoGetter,
RESULTS_COUNT));
m_pQuery->SetPreferredLanguage(lang);
}
Engine::~Engine()
{
}
namespace
{
m2::PointD GetViewportXY(double lat, double lon)
{
return m2::PointD(MercatorBounds::LonToX(lon), MercatorBounds::LatToY(lat));
}
m2::RectD GetViewportRect(double lat, double lon, double radius = 20000)
{
return MercatorBounds::MetresToXY(lon, lat, radius);
}
enum { VIEWPORT_RECT = 0, NEARME_RECT = 1 };
/// Check rects for optimal search (avoid duplicating).
void AnalizeRects(m2::RectD arrRects[2])
{
if (arrRects[NEARME_RECT].IsRectInside(arrRects[VIEWPORT_RECT]))
arrRects[VIEWPORT_RECT].MakeEmpty();
else
{
if (arrRects[VIEWPORT_RECT].IsRectInside(arrRects[NEARME_RECT]) &&
(scales::GetScaleLevel(arrRects[VIEWPORT_RECT]) + Query::m_scaleDepthSearch >= scales::GetUpperScale()))
{
arrRects[NEARME_RECT].MakeEmpty();
}
}
}
}
void Engine::PrepareSearch(m2::RectD const & viewport,
bool hasPt, double lat, double lon)
{
m2::RectD const nearby = (hasPt ? GetViewportRect(lat, lon) : m2::RectD());
// bind does copy of all rects
GetPlatform().RunAsync(bind(&Engine::SetViewportAsync, this, viewport, nearby));
}
void Engine::Search(SearchParams const & params, m2::RectD const & viewport)
{
Platform & p = GetPlatform();
{
threads::MutexGuard guard(m_updateMutex);
m_params = params;
m_viewport = viewport;
}
p.RunAsync(bind(&Engine::SearchAsync, this));
}
void Engine::SetViewportAsync(m2::RectD const & viewport, m2::RectD const & nearby)
{
// First of all - cancel previous query.
m_pQuery->DoCancel();
// Enter to run new search.
threads::MutexGuard searchGuard(m_searchMutex);
m2::RectD arrRects[] = { viewport, nearby };
AnalizeRects(arrRects);
m_pQuery->SetViewport(arrRects, ARRAY_SIZE(arrRects));
}
void Engine::SearchAsync()
{
{
// Avoid many threads waiting in search mutex. One is enough.
threads::MutexGuard readyGuard(m_readyMutex);
if (m_readyThread)
return;
m_readyThread = true;
}
// First of all - cancel previous query.
m_pQuery->DoCancel();
// Enter to run new search.
threads::MutexGuard searchGuard(m_searchMutex);
{
threads::MutexGuard readyGuard(m_readyMutex);
m_readyThread = false;
}
// Get current search params.
SearchParams params;
m2::RectD arrRects[2];
{
threads::MutexGuard updateGuard(m_updateMutex);
params = m_params;
arrRects[VIEWPORT_RECT] = m_viewport;
}
// Initialize query.
bool worldSearch = true;
if (params.m_validPos)
{
m_pQuery->SetPosition(GetViewportXY(params.m_lat, params.m_lon));
arrRects[NEARME_RECT] = GetViewportRect(params.m_lat, params.m_lon);
// Do not search in viewport for "NearMe" mode.
if (params.IsNearMeMode())
{
worldSearch = false;
arrRects[VIEWPORT_RECT].MakeEmpty();
}
// Commented out to always get mixed viewport/my position results,
// even when you're looking close to my position
// else
// AnalizeRects(arrRects);
}
else
m_pQuery->NullPosition();
m_pQuery->SetViewport(arrRects, 2);
m_pQuery->SetSearchInWorld(worldSearch);
if (params.IsLanguageValid())
m_pQuery->SetInputLanguage(params.m_inputLanguageCode);
Results res;
try
{
if (params.m_query.empty())
{
if (params.m_validPos)
{
double arrR[] = { 500, 1000, 2000 };
for (size_t i = 0; i < ARRAY_SIZE(arrR); ++i)
{
res.Clear();
m_pQuery->SearchAllInViewport(GetViewportRect(params.m_lat, params.m_lon, arrR[i]), res, 3*RESULTS_COUNT);
if (m_pQuery->IsCanceled() || res.Count() >= 2*RESULTS_COUNT)
break;
}
}
}
else
m_pQuery->Search(params.m_query, res);
}
catch (Query::CancelException const &)
{
}
// Emit results in any way, even if search was canceled.
params.m_callback(res);
// Make additional search in whole mwm when not enough results.
if (!m_pQuery->IsCanceled() && res.Count() < RESULTS_COUNT)
{
try
{
m_pQuery->SearchAdditional(res);
}
catch (Query::CancelException const &)
{
}
params.m_callback(res);
}
}
string Engine::GetCountryFile(m2::PointD const & pt) const
{
return m_pData->m_infoGetter.GetRegionFile(pt);
}
string Engine::GetCountryCode(m2::PointD const & pt) const
{
storage::CountryInfo info;
m_pData->m_infoGetter.GetRegionInfo(pt, info);
return info.m_flag;
}
} // namespace search
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// boost
#include <boost/python/suite/indexing/indexing_suite.hpp>
#include <boost/python/iterator.hpp>
#include <boost/python/call_method.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python.hpp>
#include <boost/scoped_array.hpp>
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/wkb.hpp>
#include "mapnik_value_converter.hpp"
mapnik::geometry_type & (mapnik::Feature::*get_geom1)(unsigned) = &mapnik::Feature::get_geometry;
namespace {
using mapnik::Feature;
using mapnik::geometry_utils;
/*
void feature_add_wkb_geometry(Feature &feature, std::string wkb)
{
geometry_utils::from_wkb(feature, wkb.c_str(), wkb.size(), true);
}
*/
void add_geometry(Feature & feature, std::auto_ptr<mapnik::geometry_type> geom)
{
feature.add_geometry(geom.get());
geom.release();
}
} // end anonymous namespace
namespace boost { namespace python {
// Forward declaration
template <class Container, bool NoProxy, class DerivedPolicies>
class map_indexing_suite2;
namespace detail
{
template <class Container, bool NoProxy>
class final_map_derived_policies
: public map_indexing_suite2<Container,
NoProxy, final_map_derived_policies<Container, NoProxy> > {};
}
template <class Container,bool NoProxy = false,
class DerivedPolicies = detail::final_map_derived_policies<Container, NoProxy> >
class map_indexing_suite2
: public indexing_suite<
Container
, DerivedPolicies
, NoProxy
, true
, typename Container::value_type::second_type
, typename Container::key_type
, typename Container::key_type
>
{
public:
typedef typename Container::value_type value_type;
typedef typename Container::value_type::second_type data_type;
typedef typename Container::key_type key_type;
typedef typename Container::key_type index_type;
typedef typename Container::size_type size_type;
typedef typename Container::difference_type difference_type;
template <class Class>
static void
extension_def(Class& /*cl*/)
{
}
static data_type&
get_item(Container& container, index_type i_)
{
typename Container::iterator i = container.props().find(i_);
if (i == container.end())
{
PyErr_SetString(PyExc_KeyError, "Invalid key");
throw_error_already_set();
}
return i->second;
}
static void
set_item(Container& container, index_type i, data_type const& v)
{
container[i] = v;
}
static void
delete_item(Container& container, index_type i)
{
container.props().erase(i);
}
static size_t
size(Container& container)
{
return container.props().size();
}
static bool
contains(Container& container, key_type const& key)
{
return container.props().find(key) != container.end();
}
static bool
compare_index(Container& container, index_type a, index_type b)
{
return container.props().key_comp()(a, b);
}
static index_type
convert_index(Container& /*container*/, PyObject* i_)
{
extract<key_type const&> i(i_);
if (i.check())
{
return i();
}
else
{
extract<key_type> i(i_);
if (i.check())
return i();
}
PyErr_SetString(PyExc_TypeError, "Invalid index type");
throw_error_already_set();
return index_type();
}
};
template <typename T1, typename T2>
struct std_pair_to_tuple
{
static PyObject* convert(std::pair<T1, T2> const& p)
{
return boost::python::incref(
boost::python::make_tuple(p.first, p.second).ptr());
}
};
template <typename T1, typename T2>
struct std_pair_to_python_converter
{
std_pair_to_python_converter()
{
boost::python::to_python_converter<
std::pair<T1, T2>,
std_pair_to_tuple<T1, T2> >();
}
};
}}
struct UnicodeString_from_python_str
{
UnicodeString_from_python_str()
{
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<UnicodeString>());
}
static void* convertible(PyObject* obj_ptr)
{
if (!(
#if PY_VERSION_HEX >= 0x03000000
PyBytes_Check(obj_ptr)
#else
PyString_Check(obj_ptr)
#endif
|| PyUnicode_Check(obj_ptr)))
return 0;
return obj_ptr;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
char * value=0;
if (PyUnicode_Check(obj_ptr)) {
PyObject *encoded = PyUnicode_AsEncodedString(obj_ptr, "utf8", "replace");
if (encoded) {
#if PY_VERSION_HEX >= 0x03000000
value = PyBytes_AsString(encoded);
#else
value = PyString_AsString(encoded);
#endif
Py_DecRef(encoded);
}
} else {
#if PY_VERSION_HEX >= 0x03000000
value = PyBytes_AsString(obj_ptr);
#else
value = PyString_AsString(obj_ptr);
#endif
}
if (value == 0) boost::python::throw_error_already_set();
void* storage = (
(boost::python::converter::rvalue_from_python_storage<UnicodeString>*)
data)->storage.bytes;
new (storage) UnicodeString(value);
data->convertible = storage;
}
};
void export_feature()
{
using namespace boost::python;
using mapnik::Feature;
implicitly_convertible<int,mapnik::value>();
implicitly_convertible<double,mapnik::value>();
implicitly_convertible<UnicodeString,mapnik::value>();
implicitly_convertible<bool,mapnik::value>();
std_pair_to_python_converter<std::string const,mapnik::value>();
UnicodeString_from_python_str();
class_<Feature,boost::shared_ptr<Feature>,
boost::noncopyable>("Feature",init<int>("Default ctor."))
.def("id",&Feature::id)
.def("__str__",&Feature::to_string)
// .def("add_geometry", &feature_add_wkb_geometry)
.def("add_geometry", add_geometry)
.def("num_geometries",&Feature::num_geometries)
.def("get_geometry", make_function(get_geom1,return_value_policy<reference_existing_object>()))
.def("envelope", &Feature::envelope)
.def(map_indexing_suite2<Feature, true >())
.def("iteritems",iterator<Feature> ())
// TODO define more mapnik::Feature methods
;
}
<commit_msg>resurrect add_geometry_from_wkb functionallity in Feature's python binding<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// boost
#include <boost/python/suite/indexing/indexing_suite.hpp>
#include <boost/python/iterator.hpp>
#include <boost/python/call_method.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python.hpp>
#include <boost/scoped_array.hpp>
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/wkb.hpp>
#include "mapnik_value_converter.hpp"
mapnik::geometry_type & (mapnik::Feature::*get_geom1)(unsigned) = &mapnik::Feature::get_geometry;
namespace {
using mapnik::Feature;
using mapnik::geometry_utils;
void feature_add_geometry_from_wkb(Feature &feature, std::string wkb)
{
geometry_utils::from_wkb(feature, wkb.c_str(), wkb.size(), true);
}
void add_geometry(Feature & feature, std::auto_ptr<mapnik::geometry_type> geom)
{
feature.add_geometry(geom.get());
geom.release();
}
} // end anonymous namespace
namespace boost { namespace python {
// Forward declaration
template <class Container, bool NoProxy, class DerivedPolicies>
class map_indexing_suite2;
namespace detail
{
template <class Container, bool NoProxy>
class final_map_derived_policies
: public map_indexing_suite2<Container,
NoProxy, final_map_derived_policies<Container, NoProxy> > {};
}
template <class Container,bool NoProxy = false,
class DerivedPolicies = detail::final_map_derived_policies<Container, NoProxy> >
class map_indexing_suite2
: public indexing_suite<
Container
, DerivedPolicies
, NoProxy
, true
, typename Container::value_type::second_type
, typename Container::key_type
, typename Container::key_type
>
{
public:
typedef typename Container::value_type value_type;
typedef typename Container::value_type::second_type data_type;
typedef typename Container::key_type key_type;
typedef typename Container::key_type index_type;
typedef typename Container::size_type size_type;
typedef typename Container::difference_type difference_type;
template <class Class>
static void
extension_def(Class& /*cl*/)
{
}
static data_type&
get_item(Container& container, index_type i_)
{
typename Container::iterator i = container.props().find(i_);
if (i == container.end())
{
PyErr_SetString(PyExc_KeyError, "Invalid key");
throw_error_already_set();
}
return i->second;
}
static void
set_item(Container& container, index_type i, data_type const& v)
{
container[i] = v;
}
static void
delete_item(Container& container, index_type i)
{
container.props().erase(i);
}
static size_t
size(Container& container)
{
return container.props().size();
}
static bool
contains(Container& container, key_type const& key)
{
return container.props().find(key) != container.end();
}
static bool
compare_index(Container& container, index_type a, index_type b)
{
return container.props().key_comp()(a, b);
}
static index_type
convert_index(Container& /*container*/, PyObject* i_)
{
extract<key_type const&> i(i_);
if (i.check())
{
return i();
}
else
{
extract<key_type> i(i_);
if (i.check())
return i();
}
PyErr_SetString(PyExc_TypeError, "Invalid index type");
throw_error_already_set();
return index_type();
}
};
template <typename T1, typename T2>
struct std_pair_to_tuple
{
static PyObject* convert(std::pair<T1, T2> const& p)
{
return boost::python::incref(
boost::python::make_tuple(p.first, p.second).ptr());
}
};
template <typename T1, typename T2>
struct std_pair_to_python_converter
{
std_pair_to_python_converter()
{
boost::python::to_python_converter<
std::pair<T1, T2>,
std_pair_to_tuple<T1, T2> >();
}
};
}}
struct UnicodeString_from_python_str
{
UnicodeString_from_python_str()
{
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<UnicodeString>());
}
static void* convertible(PyObject* obj_ptr)
{
if (!(
#if PY_VERSION_HEX >= 0x03000000
PyBytes_Check(obj_ptr)
#else
PyString_Check(obj_ptr)
#endif
|| PyUnicode_Check(obj_ptr)))
return 0;
return obj_ptr;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
char * value=0;
if (PyUnicode_Check(obj_ptr)) {
PyObject *encoded = PyUnicode_AsEncodedString(obj_ptr, "utf8", "replace");
if (encoded) {
#if PY_VERSION_HEX >= 0x03000000
value = PyBytes_AsString(encoded);
#else
value = PyString_AsString(encoded);
#endif
Py_DecRef(encoded);
}
} else {
#if PY_VERSION_HEX >= 0x03000000
value = PyBytes_AsString(obj_ptr);
#else
value = PyString_AsString(obj_ptr);
#endif
}
if (value == 0) boost::python::throw_error_already_set();
void* storage = (
(boost::python::converter::rvalue_from_python_storage<UnicodeString>*)
data)->storage.bytes;
new (storage) UnicodeString(value);
data->convertible = storage;
}
};
void export_feature()
{
using namespace boost::python;
using mapnik::Feature;
implicitly_convertible<int,mapnik::value>();
implicitly_convertible<double,mapnik::value>();
implicitly_convertible<UnicodeString,mapnik::value>();
implicitly_convertible<bool,mapnik::value>();
std_pair_to_python_converter<std::string const,mapnik::value>();
UnicodeString_from_python_str();
class_<Feature,boost::shared_ptr<Feature>,
boost::noncopyable>("Feature",init<int>("Default ctor."))
.def("id",&Feature::id)
.def("__str__",&Feature::to_string)
.def("add_geometry_from_wkb", &feature_add_geometry_from_wkb)
.def("add_geometry", add_geometry)
.def("num_geometries",&Feature::num_geometries)
.def("get_geometry", make_function(get_geom1,return_value_policy<reference_existing_object>()))
.def("envelope", &Feature::envelope)
.def(map_indexing_suite2<Feature, true >())
.def("iteritems",iterator<Feature> ())
// TODO define more mapnik::Feature methods
;
}
<|endoftext|> |
<commit_before>#ifndef _prusaslicer_technologies_h_
#define _prusaslicer_technologies_h_
//=============
// debug techs
//=============
// Shows camera target in the 3D scene
#define ENABLE_SHOW_CAMERA_TARGET 0
// Log debug messages to console when changing selection
#define ENABLE_SELECTION_DEBUG_OUTPUT 0
// Renders a small sphere in the center of the bounding box of the current selection when no gizmo is active
#define ENABLE_RENDER_SELECTION_CENTER 0
// Shows an imgui dialog with render related data
#define ENABLE_RENDER_STATISTICS 0
// Shows an imgui dialog with camera related data
#define ENABLE_CAMERA_STATISTICS 0
// Render the picking pass instead of the main scene (use [T] key to toggle between regular rendering and picking pass only rendering)
#define ENABLE_RENDER_PICKING_PASS 0
// Enable extracting thumbnails from selected gcode and save them as png files
#define ENABLE_THUMBNAIL_GENERATOR_DEBUG 0
// Disable synchronization of unselected instances
#define DISABLE_INSTANCES_SYNCH 0
// Use wxDataViewRender instead of wxDataViewCustomRenderer
#define ENABLE_NONCUSTOM_DATA_VIEW_RENDERING 0
// Enable G-Code viewer statistics imgui dialog
#define ENABLE_GCODE_VIEWER_STATISTICS 0
// Enable G-Code viewer comparison between toolpaths height and width detected from gcode and calculated at gcode generation
#define ENABLE_GCODE_VIEWER_DATA_CHECKING 0
// Enable rendering of objects using environment map
#define ENABLE_ENVIRONMENT_MAP 0
// Enable smoothing of objects normals
#define ENABLE_SMOOTH_NORMALS 0
// Enable rendering markers for options in preview as fixed screen size points
#define ENABLE_FIXED_SCREEN_SIZE_POINT_MARKERS 1
//====================
// 2.3.1.alpha1 techs
//====================
#define ENABLE_2_3_1_ALPHA1 1
// Enable splitting of vertex buffers used to render toolpaths
#define ENABLE_SPLITTED_VERTEX_BUFFER (1 && ENABLE_2_3_1_ALPHA1)
// Enable rendering only starting and final caps for toolpaths
#define ENABLE_REDUCED_TOOLPATHS_SEGMENT_CAPS (1 && ENABLE_SPLITTED_VERTEX_BUFFER)
// Enable reload from disk command for 3mf files
#define ENABLE_RELOAD_FROM_DISK_FOR_3MF (1 && ENABLE_2_3_1_ALPHA1)
// Removes obsolete warning texture code
#define ENABLE_WARNING_TEXTURE_REMOVAL (1 && ENABLE_2_3_1_ALPHA1)
// Enable showing gcode line numbers in previeww horizontal slider
#define ENABLE_GCODE_LINES_ID_IN_H_SLIDER (1 && ENABLE_2_3_1_ALPHA1)
// Enable validation of custom gcode against gcode processor reserved keywords
#define ENABLE_VALIDATE_CUSTOM_GCODE (1 && ENABLE_2_3_1_ALPHA1)
// Enable showing a imgui window containing gcode in preview
#define ENABLE_GCODE_WINDOW (1 && ENABLE_2_3_1_ALPHA1)
// Enable exporting lines M73 for remaining time to next printer stop to gcode
#define ENABLE_EXTENDED_M73_LINES (1 && ENABLE_VALIDATE_CUSTOM_GCODE)
#endif // _prusaslicer_technologies_h_
<commit_msg>Follow-up of 10c3e829178435203286a5843077af6f0467a5fb - Updated version for unpublished techs in Technologies.hpp<commit_after>#ifndef _prusaslicer_technologies_h_
#define _prusaslicer_technologies_h_
//=============
// debug techs
//=============
// Shows camera target in the 3D scene
#define ENABLE_SHOW_CAMERA_TARGET 0
// Log debug messages to console when changing selection
#define ENABLE_SELECTION_DEBUG_OUTPUT 0
// Renders a small sphere in the center of the bounding box of the current selection when no gizmo is active
#define ENABLE_RENDER_SELECTION_CENTER 0
// Shows an imgui dialog with render related data
#define ENABLE_RENDER_STATISTICS 0
// Shows an imgui dialog with camera related data
#define ENABLE_CAMERA_STATISTICS 0
// Render the picking pass instead of the main scene (use [T] key to toggle between regular rendering and picking pass only rendering)
#define ENABLE_RENDER_PICKING_PASS 0
// Enable extracting thumbnails from selected gcode and save them as png files
#define ENABLE_THUMBNAIL_GENERATOR_DEBUG 0
// Disable synchronization of unselected instances
#define DISABLE_INSTANCES_SYNCH 0
// Use wxDataViewRender instead of wxDataViewCustomRenderer
#define ENABLE_NONCUSTOM_DATA_VIEW_RENDERING 0
// Enable G-Code viewer statistics imgui dialog
#define ENABLE_GCODE_VIEWER_STATISTICS 0
// Enable G-Code viewer comparison between toolpaths height and width detected from gcode and calculated at gcode generation
#define ENABLE_GCODE_VIEWER_DATA_CHECKING 0
// Enable rendering of objects using environment map
#define ENABLE_ENVIRONMENT_MAP 0
// Enable smoothing of objects normals
#define ENABLE_SMOOTH_NORMALS 0
// Enable rendering markers for options in preview as fixed screen size points
#define ENABLE_FIXED_SCREEN_SIZE_POINT_MARKERS 1
//====================
// 2.4.0.alpha0 techs
//====================
#define ENABLE_2_4_0_ALPHA0 1
// Enable splitting of vertex buffers used to render toolpaths
#define ENABLE_SPLITTED_VERTEX_BUFFER (1 && ENABLE_2_4_0_ALPHA0)
// Enable rendering only starting and final caps for toolpaths
#define ENABLE_REDUCED_TOOLPATHS_SEGMENT_CAPS (1 && ENABLE_SPLITTED_VERTEX_BUFFER)
// Enable reload from disk command for 3mf files
#define ENABLE_RELOAD_FROM_DISK_FOR_3MF (1 && ENABLE_2_4_0_ALPHA0)
// Removes obsolete warning texture code
#define ENABLE_WARNING_TEXTURE_REMOVAL (1 && ENABLE_2_4_0_ALPHA0)
// Enable showing gcode line numbers in previeww horizontal slider
#define ENABLE_GCODE_LINES_ID_IN_H_SLIDER (1 && ENABLE_2_4_0_ALPHA0)
// Enable validation of custom gcode against gcode processor reserved keywords
#define ENABLE_VALIDATE_CUSTOM_GCODE (1 && ENABLE_2_4_0_ALPHA0)
// Enable showing a imgui window containing gcode in preview
#define ENABLE_GCODE_WINDOW (1 && ENABLE_2_4_0_ALPHA0)
// Enable exporting lines M73 for remaining time to next printer stop to gcode
#define ENABLE_EXTENDED_M73_LINES (1 && ENABLE_VALIDATE_CUSTOM_GCODE)
#endif // _prusaslicer_technologies_h_
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to 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)
#include <libtorrent/sha1_hash.hpp>
#include <boost/python.hpp>
void bind_sha1_hash()
{
using namespace boost::python;
using namespace libtorrent;
class_<sha1_hash>("sha1_hash")
.def(self == self)
.def(self != self)
.def(self < self)
.def(self_ns::str(self))
.def(init<char const*>())
.def("clear", &sha1_hash::clear)
.def("is_all_zeros", &sha1_hash::is_all_zeros)
.def("to_string", &sha1_hash::to_string)
// .def("__getitem__", &sha1_hash::opreator[])
;
scope().attr("big_number") = scope().attr("sha1_hash");
scope().attr("peer_id") = scope().attr("peer_id");
}
<commit_msg>fix typo in python binding<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to 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)
#include <libtorrent/sha1_hash.hpp>
#include <boost/python.hpp>
void bind_sha1_hash()
{
using namespace boost::python;
using namespace libtorrent;
class_<sha1_hash>("sha1_hash")
.def(self == self)
.def(self != self)
.def(self < self)
.def(self_ns::str(self))
.def(init<char const*>())
.def("clear", &sha1_hash::clear)
.def("is_all_zeros", &sha1_hash::is_all_zeros)
.def("to_string", &sha1_hash::to_string)
// .def("__getitem__", &sha1_hash::opreator[])
;
scope().attr("big_number") = scope().attr("sha1_hash");
scope().attr("peer_id") = scope().attr("sha1_hash");
}
<|endoftext|> |
<commit_before>#ifndef _technologies_h_
#define _technologies_h_
//============
// debug techs
//============
// Shows camera target in the 3D scene
#define ENABLE_SHOW_CAMERA_TARGET 0
// Log debug messages to console when changing selection
#define ENABLE_SELECTION_DEBUG_OUTPUT 0
// Renders a small sphere in the center of the bounding box of the current selection when no gizmo is active
#define ENABLE_RENDER_SELECTION_CENTER 0
// Shows an imgui dialog with render related data
#define ENABLE_RENDER_STATISTICS 1
//====================
// 1.42.0.alpha1 techs
//====================
#define ENABLE_1_42_0_ALPHA1 1
// Disable synchronization of unselected instances
#define DISABLE_INSTANCES_SYNCH (0 && ENABLE_1_42_0_ALPHA1)
// Disable imgui dialog for move, rotate and scale gizmos
#define DISABLE_MOVE_ROTATE_SCALE_GIZMOS_IMGUI (1 && ENABLE_1_42_0_ALPHA1)
// Use wxDataViewRender instead of wxDataViewCustomRenderer
#define ENABLE_NONCUSTOM_DATA_VIEW_RENDERING (0 && ENABLE_1_42_0_ALPHA1)
//====================
// 1.42.0.alpha7 techs
//====================
#define ENABLE_1_42_0_ALPHA7 1
// Printbed textures generated from svg files
#define ENABLE_TEXTURES_FROM_SVG (1 && ENABLE_1_42_0_ALPHA7)
//====================
// 1.42.0.alpha8 techs
//====================
#define ENABLE_1_42_0_ALPHA8 1
// Toolbars and Gizmos use icons imported from svg files
#define ENABLE_SVG_ICONS (1 && ENABLE_1_42_0_ALPHA8 && ENABLE_TEXTURES_FROM_SVG)
// Enable saving textures on GPU in compressed format
#define ENABLE_COMPRESSED_TEXTURES 1
// Enable texture max size to be dependent on detected OpenGL version
#define ENABLE_TEXTURES_MAXSIZE_DEPENDENT_ON_OPENGL_VERSION 1
#endif // _technologies_h_
<commit_msg>Disabled debug render statistics dialog<commit_after>#ifndef _technologies_h_
#define _technologies_h_
//============
// debug techs
//============
// Shows camera target in the 3D scene
#define ENABLE_SHOW_CAMERA_TARGET 0
// Log debug messages to console when changing selection
#define ENABLE_SELECTION_DEBUG_OUTPUT 0
// Renders a small sphere in the center of the bounding box of the current selection when no gizmo is active
#define ENABLE_RENDER_SELECTION_CENTER 0
// Shows an imgui dialog with render related data
#define ENABLE_RENDER_STATISTICS 0
//====================
// 1.42.0.alpha1 techs
//====================
#define ENABLE_1_42_0_ALPHA1 1
// Disable synchronization of unselected instances
#define DISABLE_INSTANCES_SYNCH (0 && ENABLE_1_42_0_ALPHA1)
// Disable imgui dialog for move, rotate and scale gizmos
#define DISABLE_MOVE_ROTATE_SCALE_GIZMOS_IMGUI (1 && ENABLE_1_42_0_ALPHA1)
// Use wxDataViewRender instead of wxDataViewCustomRenderer
#define ENABLE_NONCUSTOM_DATA_VIEW_RENDERING (0 && ENABLE_1_42_0_ALPHA1)
//====================
// 1.42.0.alpha7 techs
//====================
#define ENABLE_1_42_0_ALPHA7 1
// Printbed textures generated from svg files
#define ENABLE_TEXTURES_FROM_SVG (1 && ENABLE_1_42_0_ALPHA7)
//====================
// 1.42.0.alpha8 techs
//====================
#define ENABLE_1_42_0_ALPHA8 1
// Toolbars and Gizmos use icons imported from svg files
#define ENABLE_SVG_ICONS (1 && ENABLE_1_42_0_ALPHA8 && ENABLE_TEXTURES_FROM_SVG)
// Enable saving textures on GPU in compressed format
#define ENABLE_COMPRESSED_TEXTURES 1
// Enable texture max size to be dependent on detected OpenGL version
#define ENABLE_TEXTURES_MAXSIZE_DEPENDENT_ON_OPENGL_VERSION 1
#endif // _technologies_h_
<|endoftext|> |
<commit_before>#include <ctime>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include "assert.hpp"
#include "sta_util.hpp"
using std::cout;
using std::endl;
void identify_constant_gen_fanout_helper(const TimingGraph& tg, const NodeId node_id, std::set<NodeId>& const_gen_fanout_nodes);
void identify_clock_gen_fanout_helper(const TimingGraph& tg, const NodeId node_id, std::set<NodeId>& clock_gen_fanout_nodes);
float time_sec(struct timespec start, struct timespec end) {
float time = end.tv_sec - start.tv_sec;
time += (end.tv_nsec - start.tv_nsec) * 1e-9;
return time;
}
void print_histogram(const std::vector<float>& values, int nbuckets) {
nbuckets = std::min(values.size(), (size_t) nbuckets);
int values_per_bucket = ceil((float) values.size() / nbuckets);
std::vector<float> buckets(nbuckets);
//Sum up each bucket
for(size_t i = 0; i < values.size(); i++) {
int ibucket = i / values_per_bucket;
buckets[ibucket] += values[i];
}
//Normalize to get average value
for(int i = 0; i < nbuckets; i++) {
buckets[i] /= values_per_bucket;
}
float max_bucket_val = *std::max_element(buckets.begin(), buckets.end());
//Print the histogram
std::ios_base::fmtflags saved_flags = cout.flags();
std::streamsize prec = cout.precision();
std::streamsize width = cout.width();
std::streamsize int_width = ceil(log10(values.size()));
std::streamsize float_prec = 1;
int histo_char_width = 60;
//cout << "\t" << endl;
for(int i = 0; i < nbuckets; i++) {
cout << std::setw(int_width) << i*values_per_bucket << ":" << std::setw(int_width) << (i+1)*values_per_bucket - 1;
cout << " " << std::scientific << std::setprecision(float_prec) << buckets[i];
cout << " ";
for(int j = 0; j < histo_char_width*(buckets[i]/max_bucket_val); j++) {
cout << "*";
}
cout << endl;
}
cout.flags(saved_flags);
cout.precision(prec);
cout.width(width);
}
float relative_error(float A, float B) {
if (A == B) {
return 0.;
}
if (fabs(B) > fabs(A)) {
return fabs((A - B) / B);
} else {
return fabs((A - B) / A);
}
}
void print_level_histogram(const TimingGraph& tg, int nbuckets) {
cout << "Levels Width Histogram" << endl;
std::vector<float> level_widths;
for(int i = 0; i < tg.num_levels(); i++) {
level_widths.push_back(tg.level(i).size());
}
print_histogram(level_widths, nbuckets);
}
void print_node_fanin_histogram(const TimingGraph& tg, int nbuckets) {
cout << "Node Fan-in Histogram" << endl;
std::vector<float> fanin;
for(NodeId i = 0; i < tg.num_nodes(); i++) {
fanin.push_back(tg.num_node_in_edges(i));
}
std::sort(fanin.begin(), fanin.end(), std::greater<float>());
print_histogram(fanin, nbuckets);
}
void print_node_fanout_histogram(const TimingGraph& tg, int nbuckets) {
cout << "Node Fan-out Histogram" << endl;
std::vector<float> fanout;
for(NodeId i = 0; i < tg.num_nodes(); i++) {
fanout.push_back(tg.num_node_out_edges(i));
}
std::sort(fanout.begin(), fanout.end(), std::greater<float>());
print_histogram(fanout, nbuckets);
}
void print_timing_graph(const TimingGraph& tg) {
for(NodeId node_id = 0; node_id < tg.num_nodes(); node_id++) {
cout << "Node: " << node_id;
cout << " Type: " << tg.node_type(node_id);
cout << " Out Edges: " << tg.num_node_out_edges(node_id);
cout << " is_clk_src: " << tg.node_is_clock_source(node_id);
cout << endl;
for(int out_edge_idx = 0; out_edge_idx < tg.num_node_out_edges(node_id); out_edge_idx++) {
EdgeId edge_id = tg.node_out_edge(node_id, out_edge_idx);
ASSERT(tg.edge_src_node(edge_id) == node_id);
NodeId sink_node_id = tg.edge_sink_node(edge_id);
cout << "\tEdge src node: " << node_id << " sink node: " << sink_node_id << " Delay: " << tg.edge_delay(edge_id).value() << endl;
}
}
}
void print_levelization(const TimingGraph& tg) {
cout << "Num Levels: " << tg.num_levels() << endl;
for(int ilevel = 0; ilevel < tg.num_levels(); ilevel++) {
const auto& level = tg.level(ilevel);
cout << "Level " << ilevel << ": " << level.size() << " nodes" << endl;
cout << "\t";
for(auto node_id : level) {
cout << node_id << " ";
}
cout << endl;
}
}
std::set<NodeId> identify_constant_gen_fanout(const TimingGraph& tg) {
//Walk the timing graph and identify nodes that are in the fanout of a constant generator
std::set<NodeId> const_gen_fanout_nodes;
for(NodeId node_id : tg.primary_inputs()) {
if(tg.node_type(node_id) == TN_Type::CONSTANT_GEN_SOURCE) {
identify_constant_gen_fanout_helper(tg, node_id, const_gen_fanout_nodes);
}
}
return const_gen_fanout_nodes;
}
void identify_constant_gen_fanout_helper(const TimingGraph& tg, const NodeId node_id, std::set<NodeId>& const_gen_fanout_nodes) {
if(const_gen_fanout_nodes.count(node_id) == 0) {
//Haven't seen this node before
const_gen_fanout_nodes.insert(node_id);
for(int edge_idx = 0; edge_idx < tg.num_node_out_edges(node_id); edge_idx++) {
EdgeId edge_id = tg.node_out_edge(node_id, edge_idx);
identify_constant_gen_fanout_helper(tg, tg.edge_sink_node(edge_id), const_gen_fanout_nodes);
}
}
}
std::set<NodeId> identify_clock_gen_fanout(const TimingGraph& tg) {
std::set<NodeId> clock_gen_fanout_nodes;
for(NodeId node_id : tg.primary_inputs()) {
if(tg.node_type(node_id) == TN_Type::CLOCK_SOURCE) {
identify_clock_gen_fanout_helper(tg, node_id, clock_gen_fanout_nodes);
}
}
return clock_gen_fanout_nodes;
}
void identify_clock_gen_fanout_helper(const TimingGraph& tg, const NodeId node_id, std::set<NodeId>& clock_gen_fanout_nodes) {
if(clock_gen_fanout_nodes.count(node_id) == 0) {
//Haven't seen this node before
clock_gen_fanout_nodes.insert(node_id);
for(int edge_idx = 0; edge_idx < tg.num_node_out_edges(node_id); edge_idx++) {
EdgeId edge_id = tg.node_out_edge(node_id, edge_idx);
identify_clock_gen_fanout_helper(tg, tg.edge_sink_node(edge_id), clock_gen_fanout_nodes);
}
}
}
void write_dot_file_setup(std::ostream& os, const TimingGraph& tg, const std::shared_ptr<TimingAnalyzer<SetupHoldAnalysis>> analyzer) {
//Write out a dot file of the timing graph
os << "digraph G {" << endl;
os << "\tnode[shape=record]" << endl;
for(int inode = 0; inode < tg.num_nodes(); inode++) {
os << "\tnode" << inode;
os << "[label=\"";
os << "{#" << inode << " (" << tg.node_type(inode) << ")";
const TimingTags& data_tags = analyzer->setup_data_tags(inode);
if(data_tags.num_tags() > 0) {
os << " | DATA_TAGS";
for(const TimingTag& tag : data_tags) {
os << " | {";
os << "clk: " << tag.clock_domain();
os << " arr: " << tag.arr_time().value();
os << " req: " << tag.req_time().value();
os << " lnch: " << tag.launch_node();
os << "}";
}
}
const TimingTags& clock_tags = analyzer->setup_clock_tags(inode);
if(clock_tags.num_tags() > 0) {
os << " | CLOCK_TAGS";
for(const TimingTag& tag : clock_tags) {
os << " | {";
os << "clk: " << tag.clock_domain();
os << " arr: " << tag.arr_time().value();
os << " req: " << tag.req_time().value();
os << " lnch: " << tag.launch_node();
os << "}";
}
}
os << "}\"]";
os << endl;
}
//Force drawing to be levelized
for(int ilevel = 0; ilevel < tg.num_levels(); ilevel++) {
os << "\t{rank = same;";
for(NodeId node_id : tg.level(ilevel)) {
os << " node" << node_id <<";";
}
os << "}" << endl;
}
for(int ilevel = 0; ilevel < tg.num_levels(); ilevel++) {
for(NodeId node_id : tg.level(ilevel)) {
for(int edge_idx = 0; edge_idx < tg.num_node_out_edges(node_id); edge_idx++) {
EdgeId edge_id = tg.node_out_edge(node_id, edge_idx);
NodeId sink_node_id = tg.edge_sink_node(edge_id);
os << "\tnode" << node_id << " -> node" << sink_node_id;
os << " [ label=\"" << tg.edge_delay(edge_id) << "\" ]";
os << ";" << endl;
}
}
}
os << "}" << endl;
}
void write_dot_file_hold(std::ostream& os, const TimingGraph& tg, const std::shared_ptr<TimingAnalyzer<SetupHoldAnalysis>> analyzer) {
//Write out a dot file of the timing graph
os << "digraph G {" << endl;
os << "\tnode[shape=record]" << endl;
//Declare nodes and annotate tags
for(int inode = 0; inode < tg.num_nodes(); inode++) {
os << "\tnode" << inode;
os << "[label=\"";
os << "{#" << inode << " (" << tg.node_type(inode) << ")";
const TimingTags& data_tags = analyzer->hold_data_tags(inode);
if(data_tags.num_tags() > 0) {
os << " | DATA_TAGS";
for(const TimingTag& tag : data_tags) {
os << " | {";
os << "clk: " << tag.clock_domain();
os << " arr: " << tag.arr_time().value();
os << " req: " << tag.req_time().value();
os << " lnch: " << tag.launch_node();
os << "}";
}
}
const TimingTags& clock_tags = analyzer->hold_clock_tags(inode);
if(clock_tags.num_tags() > 0) {
os << " | CLOCK_TAGS";
for(const TimingTag& tag : clock_tags) {
os << " | {";
os << "clk: " << tag.clock_domain();
os << " arr: " << tag.arr_time().value();
os << " req: " << tag.req_time().value();
os << " lnch: " << tag.launch_node();
os << "}";
}
}
os << "}\"]";
os << endl;
}
//Force drawing to be levelized
for(int ilevel = 0; ilevel < tg.num_levels(); ilevel++) {
os << "\t{rank = same;";
for(NodeId node_id : tg.level(ilevel)) {
os << " node" << node_id <<";";
}
os << "}" << endl;
}
//Add edges with delays annoated
for(int ilevel = 0; ilevel < tg.num_levels(); ilevel++) {
for(NodeId node_id : tg.level(ilevel)) {
for(int edge_idx = 0; edge_idx < tg.num_node_out_edges(node_id); edge_idx++) {
EdgeId edge_id = tg.node_out_edge(node_id, edge_idx);
NodeId sink_node_id = tg.edge_sink_node(edge_id);
os << "\tnode" << node_id << " -> node" << sink_node_id;
os << " [ label=\"" << tg.edge_delay(edge_id) << "\" ]";
os << ";" << endl;
}
}
}
os << "}" << endl;
}
<commit_msg>Improved dot file node formatting<commit_after>#include <ctime>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include "assert.hpp"
#include "sta_util.hpp"
using std::cout;
using std::endl;
void identify_constant_gen_fanout_helper(const TimingGraph& tg, const NodeId node_id, std::set<NodeId>& const_gen_fanout_nodes);
void identify_clock_gen_fanout_helper(const TimingGraph& tg, const NodeId node_id, std::set<NodeId>& clock_gen_fanout_nodes);
float time_sec(struct timespec start, struct timespec end) {
float time = end.tv_sec - start.tv_sec;
time += (end.tv_nsec - start.tv_nsec) * 1e-9;
return time;
}
void print_histogram(const std::vector<float>& values, int nbuckets) {
nbuckets = std::min(values.size(), (size_t) nbuckets);
int values_per_bucket = ceil((float) values.size() / nbuckets);
std::vector<float> buckets(nbuckets);
//Sum up each bucket
for(size_t i = 0; i < values.size(); i++) {
int ibucket = i / values_per_bucket;
buckets[ibucket] += values[i];
}
//Normalize to get average value
for(int i = 0; i < nbuckets; i++) {
buckets[i] /= values_per_bucket;
}
float max_bucket_val = *std::max_element(buckets.begin(), buckets.end());
//Print the histogram
std::ios_base::fmtflags saved_flags = cout.flags();
std::streamsize prec = cout.precision();
std::streamsize width = cout.width();
std::streamsize int_width = ceil(log10(values.size()));
std::streamsize float_prec = 1;
int histo_char_width = 60;
//cout << "\t" << endl;
for(int i = 0; i < nbuckets; i++) {
cout << std::setw(int_width) << i*values_per_bucket << ":" << std::setw(int_width) << (i+1)*values_per_bucket - 1;
cout << " " << std::scientific << std::setprecision(float_prec) << buckets[i];
cout << " ";
for(int j = 0; j < histo_char_width*(buckets[i]/max_bucket_val); j++) {
cout << "*";
}
cout << endl;
}
cout.flags(saved_flags);
cout.precision(prec);
cout.width(width);
}
float relative_error(float A, float B) {
if (A == B) {
return 0.;
}
if (fabs(B) > fabs(A)) {
return fabs((A - B) / B);
} else {
return fabs((A - B) / A);
}
}
void print_level_histogram(const TimingGraph& tg, int nbuckets) {
cout << "Levels Width Histogram" << endl;
std::vector<float> level_widths;
for(int i = 0; i < tg.num_levels(); i++) {
level_widths.push_back(tg.level(i).size());
}
print_histogram(level_widths, nbuckets);
}
void print_node_fanin_histogram(const TimingGraph& tg, int nbuckets) {
cout << "Node Fan-in Histogram" << endl;
std::vector<float> fanin;
for(NodeId i = 0; i < tg.num_nodes(); i++) {
fanin.push_back(tg.num_node_in_edges(i));
}
std::sort(fanin.begin(), fanin.end(), std::greater<float>());
print_histogram(fanin, nbuckets);
}
void print_node_fanout_histogram(const TimingGraph& tg, int nbuckets) {
cout << "Node Fan-out Histogram" << endl;
std::vector<float> fanout;
for(NodeId i = 0; i < tg.num_nodes(); i++) {
fanout.push_back(tg.num_node_out_edges(i));
}
std::sort(fanout.begin(), fanout.end(), std::greater<float>());
print_histogram(fanout, nbuckets);
}
void print_timing_graph(const TimingGraph& tg) {
for(NodeId node_id = 0; node_id < tg.num_nodes(); node_id++) {
cout << "Node: " << node_id;
cout << " Type: " << tg.node_type(node_id);
cout << " Out Edges: " << tg.num_node_out_edges(node_id);
cout << " is_clk_src: " << tg.node_is_clock_source(node_id);
cout << endl;
for(int out_edge_idx = 0; out_edge_idx < tg.num_node_out_edges(node_id); out_edge_idx++) {
EdgeId edge_id = tg.node_out_edge(node_id, out_edge_idx);
ASSERT(tg.edge_src_node(edge_id) == node_id);
NodeId sink_node_id = tg.edge_sink_node(edge_id);
cout << "\tEdge src node: " << node_id << " sink node: " << sink_node_id << " Delay: " << tg.edge_delay(edge_id).value() << endl;
}
}
}
void print_levelization(const TimingGraph& tg) {
cout << "Num Levels: " << tg.num_levels() << endl;
for(int ilevel = 0; ilevel < tg.num_levels(); ilevel++) {
const auto& level = tg.level(ilevel);
cout << "Level " << ilevel << ": " << level.size() << " nodes" << endl;
cout << "\t";
for(auto node_id : level) {
cout << node_id << " ";
}
cout << endl;
}
}
std::set<NodeId> identify_constant_gen_fanout(const TimingGraph& tg) {
//Walk the timing graph and identify nodes that are in the fanout of a constant generator
std::set<NodeId> const_gen_fanout_nodes;
for(NodeId node_id : tg.primary_inputs()) {
if(tg.node_type(node_id) == TN_Type::CONSTANT_GEN_SOURCE) {
identify_constant_gen_fanout_helper(tg, node_id, const_gen_fanout_nodes);
}
}
return const_gen_fanout_nodes;
}
void identify_constant_gen_fanout_helper(const TimingGraph& tg, const NodeId node_id, std::set<NodeId>& const_gen_fanout_nodes) {
if(const_gen_fanout_nodes.count(node_id) == 0) {
//Haven't seen this node before
const_gen_fanout_nodes.insert(node_id);
for(int edge_idx = 0; edge_idx < tg.num_node_out_edges(node_id); edge_idx++) {
EdgeId edge_id = tg.node_out_edge(node_id, edge_idx);
identify_constant_gen_fanout_helper(tg, tg.edge_sink_node(edge_id), const_gen_fanout_nodes);
}
}
}
std::set<NodeId> identify_clock_gen_fanout(const TimingGraph& tg) {
std::set<NodeId> clock_gen_fanout_nodes;
for(NodeId node_id : tg.primary_inputs()) {
if(tg.node_type(node_id) == TN_Type::CLOCK_SOURCE) {
identify_clock_gen_fanout_helper(tg, node_id, clock_gen_fanout_nodes);
}
}
return clock_gen_fanout_nodes;
}
void identify_clock_gen_fanout_helper(const TimingGraph& tg, const NodeId node_id, std::set<NodeId>& clock_gen_fanout_nodes) {
if(clock_gen_fanout_nodes.count(node_id) == 0) {
//Haven't seen this node before
clock_gen_fanout_nodes.insert(node_id);
for(int edge_idx = 0; edge_idx < tg.num_node_out_edges(node_id); edge_idx++) {
EdgeId edge_id = tg.node_out_edge(node_id, edge_idx);
identify_clock_gen_fanout_helper(tg, tg.edge_sink_node(edge_id), clock_gen_fanout_nodes);
}
}
}
void write_dot_file_setup(std::ostream& os, const TimingGraph& tg, const std::shared_ptr<TimingAnalyzer<SetupHoldAnalysis>> analyzer) {
//Write out a dot file of the timing graph
os << "digraph G {" << endl;
os << "\tnode[shape=record]" << endl;
for(int inode = 0; inode < tg.num_nodes(); inode++) {
os << "\tnode" << inode;
os << "[label=\"";
os << "{#" << inode << " (" << tg.node_type(inode) << ")";
const TimingTags& data_tags = analyzer->setup_data_tags(inode);
if(data_tags.num_tags() > 0) {
for(const TimingTag& tag : data_tags) {
os << " | {";
os << "DATA - clk: " << tag.clock_domain();
os << " launch: " << tag.launch_node();
os << "\\n";
os << " arr: " << tag.arr_time().value();
os << " req: " << tag.req_time().value();
os << "}";
}
}
const TimingTags& clock_tags = analyzer->setup_clock_tags(inode);
if(clock_tags.num_tags() > 0) {
for(const TimingTag& tag : clock_tags) {
os << " | {";
os << "CLOCK - clk: " << tag.clock_domain();
os << " launch: " << tag.launch_node();
os << "\\n";
os << " arr: " << tag.arr_time().value();
os << " req: " << tag.req_time().value();
os << "}";
}
}
os << "}\"]";
os << endl;
}
//Force drawing to be levelized
for(int ilevel = 0; ilevel < tg.num_levels(); ilevel++) {
os << "\t{rank = same;";
for(NodeId node_id : tg.level(ilevel)) {
os << " node" << node_id <<";";
}
os << "}" << endl;
}
for(int ilevel = 0; ilevel < tg.num_levels(); ilevel++) {
for(NodeId node_id : tg.level(ilevel)) {
for(int edge_idx = 0; edge_idx < tg.num_node_out_edges(node_id); edge_idx++) {
EdgeId edge_id = tg.node_out_edge(node_id, edge_idx);
NodeId sink_node_id = tg.edge_sink_node(edge_id);
os << "\tnode" << node_id << " -> node" << sink_node_id;
os << " [ label=\"" << tg.edge_delay(edge_id) << "\" ]";
os << ";" << endl;
}
}
}
os << "}" << endl;
}
void write_dot_file_hold(std::ostream& os, const TimingGraph& tg, const std::shared_ptr<TimingAnalyzer<SetupHoldAnalysis>> analyzer) {
//Write out a dot file of the timing graph
os << "digraph G {" << endl;
os << "\tnode[shape=record]" << endl;
//Declare nodes and annotate tags
for(int inode = 0; inode < tg.num_nodes(); inode++) {
os << "\tnode" << inode;
os << "[label=\"";
os << "{#" << inode << " (" << tg.node_type(inode) << ")";
const TimingTags& data_tags = analyzer->hold_data_tags(inode);
if(data_tags.num_tags() > 0) {
for(const TimingTag& tag : data_tags) {
os << " | {";
os << "DATA - clk: " << tag.clock_domain();
os << " launch: " << tag.launch_node();
os << "\\n";
os << " arr: " << tag.arr_time().value();
os << " req: " << tag.req_time().value();
os << "}";
}
}
const TimingTags& clock_tags = analyzer->hold_clock_tags(inode);
if(clock_tags.num_tags() > 0) {
for(const TimingTag& tag : clock_tags) {
os << " | {";
os << "CLOCK - clk: " << tag.clock_domain();
os << " launch: " << tag.launch_node();
os << "\\n";
os << " arr: " << tag.arr_time().value();
os << " req: " << tag.req_time().value();
os << "}";
}
}
os << "}\"]";
os << endl;
}
//Force drawing to be levelized
for(int ilevel = 0; ilevel < tg.num_levels(); ilevel++) {
os << "\t{rank = same;";
for(NodeId node_id : tg.level(ilevel)) {
os << " node" << node_id <<";";
}
os << "}" << endl;
}
//Add edges with delays annoated
for(int ilevel = 0; ilevel < tg.num_levels(); ilevel++) {
for(NodeId node_id : tg.level(ilevel)) {
for(int edge_idx = 0; edge_idx < tg.num_node_out_edges(node_id); edge_idx++) {
EdgeId edge_id = tg.node_out_edge(node_id, edge_idx);
NodeId sink_node_id = tg.edge_sink_node(edge_id);
os << "\tnode" << node_id << " -> node" << sink_node_id;
os << " [ label=\"" << tg.edge_delay(edge_id) << "\" ]";
os << ";" << endl;
}
}
}
os << "}" << endl;
}
<|endoftext|> |
<commit_before>/**
* @file midi.cpp
* @brief Brief description of file.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <list>
#include <jack/jack.h>
#include <jack/midiport.h>
#include <pthread.h>
#include "midi.h"
#include "util/time.h"
#include "globals.h"
/// all ports must be linked into this.
std::list<class MidiPort *> portList;
static jack_client_t *jack=NULL;
static void chkjack(){
if(!jack)
throw "jack not connected";
}
#define DATABUFSIZE 2048
class MidiPort {
public:
MidiPort(bool input,const char *name){
isInput = input;
pthread_mutex_init(&mutex,NULL);
port = jack_port_register(jack,name,
JACK_DEFAULT_MIDI_TYPE,
isInput?JackPortIsInput:JackPortIsOutput,0);
if(!port)
throw "failed to register Jack port";
portList.push_back(this);
ct=0;
rct=0;
}
~MidiPort(){
if(port && jack)
jack_port_unregister(jack,port);
portList.remove(this);
pthread_mutex_destroy(&mutex);
}
void setListener(MidiPortListener *l){
listener = l;
}
// write a single event to the buffer - an event
// consists of a byte count followed by a number of bytes.
void write(uint8_t *data,int len){
if(ct+len+1 >= DATABUFSIZE)
throw "out of space in write buffer";
pthread_mutex_lock(&mutex);
dataBuffer[ct++]=len;
memcpy(dataBuffer+ct,data,len);
ct+=len;
pthread_mutex_unlock(&mutex);
}
private:
bool isInput;
jack_port_t *port;
MidiPort *next;
pthread_mutex_t mutex;
MidiPortListener *listener;
uint8_t dataBuffer[DATABUFSIZE];
int ct,rct;
// returns number of bytes consumed
int processEvent(uint8_t *d){
int chan,key,ctor,vel,val;
uint8_t tp = *d >> 4;
switch(tp){
case 8: // noteoff : (chan key vel --)
chan = *d++ & 0xf;
key = *d++;
vel = *d++;
if(listener)listener->onNoteOff(chan,vel,key);
// TODO
break;
case 9: // noteon : (chan key vel --)
chan = *d++ & 0xf;
key = *d++;
vel = *d++;
if(listener)listener->onNoteOn(chan,vel,key);
// TODO
break;
case 11: // CC : (chan ctor val --)
chan = *d++ & 0xf;
ctor = *d++;
val = *d++;
if(listener)listener->onCC(chan,ctor,val);
// TODO
default:
break;
}
return 3; // jack data is always normalised, it seems
}
public:
// the jack processing callback, called from the jack thread.
static int process(jack_nframes_t nframes, void *arg){
std::list<MidiPort *>::iterator i;
// go through each port, see which are output and have data
// waiting to go, and send it.
for(i=portList.begin();i!=portList.end();++i){
MidiPort *p = *i;
void *buf = jack_port_get_buffer(p->port,nframes);
if(p->isInput){
int ct = jack_midi_get_event_count(buf);
if(ct>0){
pthread_mutex_lock(&p->mutex);
uint8_t *data = p->dataBuffer+p->ct;
if(p->ct < DATABUFSIZE-3){
for(int j=0;j<ct;j++){
jack_midi_event_t in;
jack_midi_event_get(&in,buf,j);
data[0] = in.buffer[0];
data[1] = in.buffer[1];
data[2] = in.buffer[2];
if(p->listener)
p->processEvent(data);
data+=3;
}
}
p->ct = data-p->dataBuffer;
pthread_mutex_unlock(&p->mutex);
}
}else{
jack_midi_clear_buffer(buf);
pthread_mutex_lock(&p->mutex);
uint8_t *data = p->dataBuffer;
int idx=0;
while(idx<p->ct){
// run through the data, processing the events
int len = data[idx++];
jack_midi_event_write(buf,0,data+idx,len);
idx+=len;
}
p->ct=0;
pthread_mutex_unlock(&p->mutex);
}
}
return 0;
}
};
static void jack_shutdown(void *arg){
fprintf(stderr,"Jack terminated the program\n");
exit(1);
}
MidiPort *midiCreateInput(const char *name){
chkjack();
return new MidiPort(true,name);
}
MidiPort *midiCreateOutput(const char *name){
chkjack();
return new MidiPort(false,name);
}
void initMidi(const char *name){
jack = jack_client_open(name,JackNullOption,NULL);
if(!jack)
throw "Jack client open failed";
jack_on_shutdown(jack,jack_shutdown,0);
jack_set_process_callback(jack,MidiPort::process,0);
jack_activate(jack);
}
void shutdownMidi(){
if(jack){
jack_deactivate(jack);
jack_client_close(jack);
jack=NULL;
}
}
void sendNoteOn(MidiPort *p,int chan,int note,int vel){
chkjack();
uint8_t data[3];
data[0]=144+chan;
data[1]=note;
data[2]=vel;
p->write(data,3);
}
void sendNoteOff(MidiPort *p,int chan,int note){
chkjack();
uint8_t data[3];
data[0]=128+chan;
data[1]=note;
data[2]=64;
p->write(data,3);
}
void sendCC(MidiPort *p,int chan,int ctor,int val){
chkjack();
if(ctor>127)ctor=127;
if(val>127)val=127;
if(val<0)val=0;
uint8_t data[3];
data[0]=(0b10110000)+chan;
data[1]=ctor;
data[2]=val;
p->write(data,3);
}
static MidiPort *in,*out;
static float noteEnds[16][128];
void simpleMidiInit(MidiPortListener *l){
initMidi("stumpymusic");
in = midiCreateInput("in");
if(l)
in->setListener(l);
out = midiCreateOutput("out");
for(int c=0;c<16;c++){
for(int i=0;i<128;i++)
noteEnds[c][i]=-1;
}
}
void simpleMidiShutdown(){
for(int c=0;c<16;c++){
for(int i=0;i<128;i++){
if(noteEnds[c][i]>=0)
sendNoteOff(out,c,i);
}
}
sleep(1);
delete in;
delete out;
shutdownMidi();
}
void simpleMidiUpdate(){
for(int c=0;c<16;c++){
for(int i=0;i<128;i++){
if(noteEnds[c][i]>=0){
if(Time::now() >= noteEnds[c][i]){
noteEnds[c][i]=-1;
sendNoteOff(out,c,i);
}
}
}
}
}
void simpleMidiPlay(int chan, int note, int vel,float dur){
printf("PLAY %d, %d, vel %d, dur %f\n",
chan,note,vel,dur);
// oct enforce, octaves based on C
if(gEnforcedOct>-100){
note %=12;
note += (gEnforcedOct+1)*12;
}
if(chan>=0 && chan<16 && note>=0 && note<128){
noteEnds[chan][note] = Time::now()+dur;
sendNoteOn(out,chan,note,vel);
}
}
void simpleMidiCC(int chan, int ctor,int val){
sendCC(out,chan,ctor,val);
}
<commit_msg>time of note end stored as double<commit_after>/**
* @file midi.cpp
* @brief Brief description of file.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <list>
#include <jack/jack.h>
#include <jack/midiport.h>
#include <pthread.h>
#include "midi.h"
#include "util/time.h"
#include "globals.h"
/// all ports must be linked into this.
std::list<class MidiPort *> portList;
static jack_client_t *jack=NULL;
static void chkjack(){
if(!jack)
throw "jack not connected";
}
#define DATABUFSIZE 2048
class MidiPort {
public:
MidiPort(bool input,const char *name){
isInput = input;
pthread_mutex_init(&mutex,NULL);
port = jack_port_register(jack,name,
JACK_DEFAULT_MIDI_TYPE,
isInput?JackPortIsInput:JackPortIsOutput,0);
if(!port)
throw "failed to register Jack port";
portList.push_back(this);
ct=0;
rct=0;
}
~MidiPort(){
if(port && jack)
jack_port_unregister(jack,port);
portList.remove(this);
pthread_mutex_destroy(&mutex);
}
void setListener(MidiPortListener *l){
listener = l;
}
// write a single event to the buffer - an event
// consists of a byte count followed by a number of bytes.
void write(uint8_t *data,int len){
if(ct+len+1 >= DATABUFSIZE)
throw "out of space in write buffer";
pthread_mutex_lock(&mutex);
dataBuffer[ct++]=len;
memcpy(dataBuffer+ct,data,len);
ct+=len;
pthread_mutex_unlock(&mutex);
}
private:
bool isInput;
jack_port_t *port;
MidiPort *next;
pthread_mutex_t mutex;
MidiPortListener *listener;
uint8_t dataBuffer[DATABUFSIZE];
int ct,rct;
// returns number of bytes consumed
int processEvent(uint8_t *d){
int chan,key,ctor,vel,val;
uint8_t tp = *d >> 4;
switch(tp){
case 8: // noteoff : (chan key vel --)
chan = *d++ & 0xf;
key = *d++;
vel = *d++;
if(listener)listener->onNoteOff(chan,vel,key);
// TODO
break;
case 9: // noteon : (chan key vel --)
chan = *d++ & 0xf;
key = *d++;
vel = *d++;
if(listener)listener->onNoteOn(chan,vel,key);
// TODO
break;
case 11: // CC : (chan ctor val --)
chan = *d++ & 0xf;
ctor = *d++;
val = *d++;
if(listener)listener->onCC(chan,ctor,val);
// TODO
default:
break;
}
return 3; // jack data is always normalised, it seems
}
public:
// the jack processing callback, called from the jack thread.
static int process(jack_nframes_t nframes, void *arg){
std::list<MidiPort *>::iterator i;
// go through each port, see which are output and have data
// waiting to go, and send it.
for(i=portList.begin();i!=portList.end();++i){
MidiPort *p = *i;
void *buf = jack_port_get_buffer(p->port,nframes);
if(p->isInput){
int ct = jack_midi_get_event_count(buf);
if(ct>0){
pthread_mutex_lock(&p->mutex);
uint8_t *data = p->dataBuffer+p->ct;
if(p->ct < DATABUFSIZE-3){
for(int j=0;j<ct;j++){
jack_midi_event_t in;
jack_midi_event_get(&in,buf,j);
data[0] = in.buffer[0];
data[1] = in.buffer[1];
data[2] = in.buffer[2];
if(p->listener)
p->processEvent(data);
data+=3;
}
}
p->ct = data-p->dataBuffer;
pthread_mutex_unlock(&p->mutex);
}
}else{
jack_midi_clear_buffer(buf);
pthread_mutex_lock(&p->mutex);
uint8_t *data = p->dataBuffer;
int idx=0;
while(idx<p->ct){
// run through the data, processing the events
int len = data[idx++];
jack_midi_event_write(buf,0,data+idx,len);
idx+=len;
}
p->ct=0;
pthread_mutex_unlock(&p->mutex);
}
}
return 0;
}
};
static void jack_shutdown(void *arg){
fprintf(stderr,"Jack terminated the program\n");
exit(1);
}
MidiPort *midiCreateInput(const char *name){
chkjack();
return new MidiPort(true,name);
}
MidiPort *midiCreateOutput(const char *name){
chkjack();
return new MidiPort(false,name);
}
void initMidi(const char *name){
jack = jack_client_open(name,JackNullOption,NULL);
if(!jack)
throw "Jack client open failed";
jack_on_shutdown(jack,jack_shutdown,0);
jack_set_process_callback(jack,MidiPort::process,0);
jack_activate(jack);
}
void shutdownMidi(){
if(jack){
jack_deactivate(jack);
jack_client_close(jack);
jack=NULL;
}
}
void sendNoteOn(MidiPort *p,int chan,int note,int vel){
chkjack();
uint8_t data[3];
data[0]=144+chan;
data[1]=note;
data[2]=vel;
p->write(data,3);
}
void sendNoteOff(MidiPort *p,int chan,int note){
chkjack();
uint8_t data[3];
data[0]=128+chan;
data[1]=note;
data[2]=64;
p->write(data,3);
}
void sendCC(MidiPort *p,int chan,int ctor,int val){
chkjack();
if(ctor>127)ctor=127;
if(val>127)val=127;
if(val<0)val=0;
uint8_t data[3];
data[0]=(0b10110000)+chan;
data[1]=ctor;
data[2]=val;
p->write(data,3);
}
static MidiPort *in,*out;
static double noteEnds[16][128];
void simpleMidiInit(MidiPortListener *l){
initMidi("stumpymusic");
in = midiCreateInput("in");
if(l)
in->setListener(l);
out = midiCreateOutput("out");
for(int c=0;c<16;c++){
for(int i=0;i<128;i++)
noteEnds[c][i]=-1;
}
}
void simpleMidiShutdown(){
for(int c=0;c<16;c++){
for(int i=0;i<128;i++){
if(noteEnds[c][i]>=0)
sendNoteOff(out,c,i);
}
}
sleep(1);
delete in;
delete out;
shutdownMidi();
}
void simpleMidiUpdate(){
for(int c=0;c<16;c++){
for(int i=0;i<128;i++){
if(noteEnds[c][i]>=0){
if(Time::now() >= noteEnds[c][i]){
noteEnds[c][i]=-1;
sendNoteOff(out,c,i);
}
}
}
}
}
void simpleMidiPlay(int chan, int note, int vel,float dur){
printf("PLAY %d, %d, vel %d, dur %f\n",
chan,note,vel,dur);
// oct enforce, octaves based on C
if(gEnforcedOct>-100){
note %=12;
note += (gEnforcedOct+1)*12;
}
if(chan>=0 && chan<16 && note>=0 && note<128){
noteEnds[chan][note] = Time::now()+dur;
sendNoteOn(out,chan,note,vel);
}
}
void simpleMidiCC(int chan, int ctor,int val){
sendCC(out,chan,ctor,val);
}
<|endoftext|> |
<commit_before><commit_msg>RPC: minor fixes to params<commit_after><|endoftext|> |
<commit_before>#include <cstring>
#include <iostream>
#include <UnitTest++.h>
#include <TestReporter.h> // Part of UnitTest++
#include <tightdb.hpp>
#include <tightdb/utilities.hpp>
#include <vector>
//#define USE_VLD
#if defined(_MSC_VER) && defined(_DEBUG) && defined(USE_VLD)
#include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif
using namespace std;
using namespace UnitTest;
using namespace tightdb;
struct
{
string name;
float time;
} typedef result_t;
vector<result_t> results;
namespace {
bool compare (const result_t &lhs, const result_t &rhs){
return lhs.time > rhs.time;
}
struct CustomTestReporter: TestReporter {
void ReportTestStart(TestDetails const& test)
{
static_cast<void>(test);
// cerr << test.filename << ":" << test.lineNumber << ": Begin " << test.testName << "\n";
}
void ReportFailure(TestDetails const& test, char const* failure)
{
cerr << test.filename << ":" << test.lineNumber << ": error: "
"Failure in " << test.testName << ": " << failure << "\n";
}
void ReportTestFinish(TestDetails const& test, float seconds_elapsed)
{
static_cast<void>(test);
static_cast<void>(seconds_elapsed);
result_t r;
r.name = test.testName;
r.time = seconds_elapsed;
results.push_back(r);
// cerr << test.filename << ":" << test.lineNumber << ": End\n";
}
void ReportSummary(int total_test_count, int failed_test_count, int failure_count, float seconds_elapsed)
{
if (0 < failure_count)
cerr << "FAILURE: " << failed_test_count << " "
"out of " << total_test_count << " tests failed "
"(" << failure_count << " failures).\n";
else
cerr << "Success: " << total_test_count << " tests passed.\n";
const streamsize orig_prec = cerr.precision();
cerr.precision(2);
cerr << "Test time: " << seconds_elapsed << " seconds.\n";
cerr.precision(orig_prec);
cerr << "\nTop 5 time usage:\n";
std::sort(results.begin(), results.end(), compare);
for(size_t t = 0; t < 5; t++) {
cerr << results[t].name << ": " << results[t].time << " s\n";
}
}
};
} // anonymous namespace
int main(int argc, char* argv[])
{
bool const no_error_exit_staus = 2 <= argc && strcmp(argv[1], "--no-error-exitcode") == 0;
#ifdef TIGHTDB_DEBUG
cerr << "Running Debug unit tests\n";
#else
cerr << "Running Release unit tests\n";
#endif
cerr << "TIGHTDB_MAX_LIST_SIZE = " << TIGHTDB_MAX_LIST_SIZE << "\n";
#ifdef TIGHTDB_COMPILER_SSE
cerr << "Compiler supported SSE (auto detect): Yes\n";
#else
cerr << "Compiler supported SSE (auto detect): No\n";
#endif
cerr << "This CPU supports SSE (auto detect): " << (tightdb::cpuid_sse<42>() ? "4.2" : (tightdb::cpuid_sse<30>() ? "3.0" : "None"));
cerr << "\n\n";
CustomTestReporter reporter;
TestRunner runner(reporter);
const int res = runner.RunTestsIf(Test::GetTestList(), 0, True(), 0);
#ifdef _MSC_VER
getchar(); // wait for key
#endif
return no_error_exit_staus ? 0 : res;
}
<commit_msg>aligned unit test durations<commit_after>#include <cstring>
#include <iostream>
#include <UnitTest++.h>
#include <TestReporter.h> // Part of UnitTest++
#include <tightdb.hpp>
#include <tightdb/utilities.hpp>
#include <vector>
//#define USE_VLD
#if defined(_MSC_VER) && defined(_DEBUG) && defined(USE_VLD)
#include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif
using namespace std;
using namespace UnitTest;
using namespace tightdb;
struct
{
string name;
float time;
} typedef result_t;
vector<result_t> results;
namespace {
bool compare (const result_t &lhs, const result_t &rhs){
return lhs.time > rhs.time;
}
struct CustomTestReporter: TestReporter {
void ReportTestStart(TestDetails const& test)
{
static_cast<void>(test);
// cerr << test.filename << ":" << test.lineNumber << ": Begin " << test.testName << "\n";
}
void ReportFailure(TestDetails const& test, char const* failure)
{
cerr << test.filename << ":" << test.lineNumber << ": error: "
"Failure in " << test.testName << ": " << failure << "\n";
}
void ReportTestFinish(TestDetails const& test, float seconds_elapsed)
{
static_cast<void>(test);
static_cast<void>(seconds_elapsed);
result_t r;
r.name = test.testName;
r.time = seconds_elapsed;
results.push_back(r);
// cerr << test.filename << ":" << test.lineNumber << ": End\n";
}
void ReportSummary(int total_test_count, int failed_test_count, int failure_count, float seconds_elapsed)
{
if (0 < failure_count)
cerr << "FAILURE: " << failed_test_count << " "
"out of " << total_test_count << " tests failed "
"(" << failure_count << " failures).\n";
else
cerr << "Success: " << total_test_count << " tests passed.\n";
const streamsize orig_prec = cerr.precision();
cerr.precision(2);
cerr << "Test time: " << seconds_elapsed << " seconds.\n";
cerr.precision(orig_prec);
cerr << "\nTop 5 time usage:\n";
std::sort(results.begin(), results.end(), compare);
for(size_t t = 0; t < 5; t++) {
size_t space = 30 - (results[t].name.size() > 30 ? 30 : results[t].name.size());
cerr << results[t].name << ": " << string(space, ' ').c_str() << results[t].time << " s\n";
}
}
};
} // anonymous namespace
int main(int argc, char* argv[])
{
bool const no_error_exit_staus = 2 <= argc && strcmp(argv[1], "--no-error-exitcode") == 0;
#ifdef TIGHTDB_DEBUG
cerr << "Running Debug unit tests\n";
#else
cerr << "Running Release unit tests\n";
#endif
cerr << "TIGHTDB_MAX_LIST_SIZE = " << TIGHTDB_MAX_LIST_SIZE << "\n";
#ifdef TIGHTDB_COMPILER_SSE
cerr << "Compiler supported SSE (auto detect): Yes\n";
#else
cerr << "Compiler supported SSE (auto detect): No\n";
#endif
cerr << "This CPU supports SSE (auto detect): " << (tightdb::cpuid_sse<42>() ? "4.2" : (tightdb::cpuid_sse<30>() ? "3.0" : "None"));
cerr << "\n\n";
CustomTestReporter reporter;
TestRunner runner(reporter);
const int res = runner.RunTestsIf(Test::GetTestList(), 0, True(), 0);
#ifdef _MSC_VER
getchar(); // wait for key
#endif
return no_error_exit_staus ? 0 : res;
}
<|endoftext|> |
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011,2012 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "lts.hh"
#include "log_null.hh"
#include "history_log.hh"
#include "coverage.hh"
class ltscoverage: public Coverage {
public:
ltscoverage(Log&l,History_log& _h): Coverage(l), prop_count(0), lts(l), hl(_h)
{}
virtual ~ltscoverage() {}
virtual void push() {}
virtual void pop() {}
virtual bool execute(int action) {return true;}
virtual float getCoverage() { return 0.0;}
virtual int fitness(int* actions,int n, float* fitness) { return 0;}
virtual void history(int action, std::vector<int>& props,
Verdict::Verdict verdict)
{
// implementation....
if (action) {
trace.push_back(action);
if (prop.size()<hl.tnames.size()) {
prop.resize(hl.tnames.size());
}
for(unsigned i=0;i<props.size();i++) {
prop[props[i]].push_back(trace.size());
}
} else {
// verdict. Let's create lts.
// We might have props...
for(unsigned i=0;i<props.size();i++) {
prop[props[i]].push_back(trace.size()+1);
}
lts.set_state_cnt(trace.size()+1);
lts.set_action_cnt(hl.anames.size()-1);
lts.set_transition_cnt(trace.size());
lts.set_prop_cnt(hl.tnames.size()-1);
lts.set_initial_state(1);
lts.header_done();
for(unsigned i=1;i<hl.anames.size();i++) {
lts.add_action(i,hl.anames[i]);
}
for(unsigned i=0;i<trace.size();i++) {
std::vector<int> e;
std::vector<int> a;
std::vector<int> s;
a.push_back(trace[i]);
s.push_back(i+2);
lts.add_transitions(i+1,a,e,s,e);
}
for(unsigned i=1;i<prop.size();i++) {
lts.add_prop(&hl.tnames[i],prop[i]);
}
}
}
std::vector<int> trace;
std::vector<std::vector<int> > prop;
int prop_count;
Lts lts;
History_log& hl;
};
int main(int argc,char * const argv[])
{
Log_null log;
std::string file(argv[1]);
History_log hl(log,file);
ltscoverage cov(log,hl);
hl.set_coverage(&cov,NULL);
printf("%s\n",cov.lts.stringify().c_str());
}
<commit_msg>getopt log2lsts<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011,2012 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "lts.hh"
#include "log_null.hh"
#include "history_log.hh"
#include "coverage.hh"
#ifndef DROI
#include <error.h>
#else
void error(int exitval, int dontcare, const char* format, ...)
{
va_list ap;
fprintf(stderr, "fMBT error: ");
va_start(ap, format);
vfprintf(stderr, format, ap);
va_end(ap);
exit(exitval);
}
#endif
class ltscoverage: public Coverage {
public:
ltscoverage(Log&l,History_log& _h): Coverage(l), prop_count(0), lts(l), hl(_h)
{}
virtual ~ltscoverage() {}
virtual void push() {}
virtual void pop() {}
virtual bool execute(int action) {return true;}
virtual float getCoverage() { return 0.0;}
virtual int fitness(int* actions,int n, float* fitness) { return 0;}
virtual void history(int action, std::vector<int>& props,
Verdict::Verdict verdict)
{
// implementation....
if (action) {
trace.push_back(action);
if (prop.size()<hl.tnames.size()) {
prop.resize(hl.tnames.size());
}
for(unsigned i=0;i<props.size();i++) {
prop[props[i]].push_back(trace.size());
}
} else {
// verdict. Let's create lts.
// We might have props...
for(unsigned i=0;i<props.size();i++) {
prop[props[i]].push_back(trace.size()+1);
}
lts.set_state_cnt(trace.size()+1);
lts.set_action_cnt(hl.anames.size()-1);
lts.set_transition_cnt(trace.size());
lts.set_prop_cnt(hl.tnames.size()-1);
lts.set_initial_state(1);
lts.header_done();
for(unsigned i=1;i<hl.anames.size();i++) {
lts.add_action(i,hl.anames[i]);
}
for(unsigned i=0;i<trace.size();i++) {
std::vector<int> e;
std::vector<int> a;
std::vector<int> s;
a.push_back(trace[i]);
s.push_back(i+2);
lts.add_transitions(i+1,a,e,s,e);
}
for(unsigned i=1;i<prop.size();i++) {
lts.add_prop(&hl.tnames[i],prop[i]);
}
}
}
std::vector<int> trace;
std::vector<std::vector<int> > prop;
int prop_count;
Lts lts;
History_log& hl;
};
#include <getopt.h>
#include "config.h"
void print_usage()
{
std::printf(
"Usage: fmbt-log2lsts [options] logfile\n"
"Options:\n"
" -V print version("VERSION")\n"
" -h help\n"
);
}
int main(int argc,char * const argv[])
{
Log_null log;
int c;
static struct option long_opts[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{0, 0, 0, 0}
};
while ((c = getopt_long (argc, argv, "DEL:heil:qCo:V", long_opts, NULL)) != -1)
switch (c)
{
case 'V':
printf("Version: "VERSION"\n");
return 0;
break;
case 'h':
print_usage();
return 0;
default:
return 2;
}
if (optind == argc) {
print_usage();
error(32, 0, "logfile missing.\n");
}
std::string file(argv[optind]);
History_log hl(log,file);
ltscoverage cov(log,hl);
hl.set_coverage(&cov,NULL);
printf("%s\n",cov.lts.stringify().c_str());
}
<|endoftext|> |
<commit_before>// Copyright (C) 2012 Rhys Ulerich
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 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 General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "ar.hpp"
#include <algorithm>
#include <cstdlib>
#include <iterator>
#include <limits>
#include <list>
#include <string>
#include <vector>
#include <octave/oct.h>
#include <octave/oct-map.h>
#include <octave/ov-struct.h>
#include <octave/Cell.h>
/** @file
* A GNU Octave function estimating the best AR(p) model given signal input.
* Compare \ref arsel.cpp.
*/
// Compile-time defaults in the code also appearing in the help message
#define DEFAULT_SUBMEAN true
#define DEFAULT_ABSRHO false
#define DEFAULT_CRITERION "CIC"
#define DEFAULT_MAXORDER 512
#define STRINGIFY(x) STRINGIFY_HELPER(x)
#define STRINGIFY_HELPER(x) #x
DEFUN_DLD(
arsel, args, nargout,
"\tM = arsel (data, submean, absrho, criterion, maxorder)\n"
"\tAutomatically fit autoregressive models to input signals.\n"
"\t\n"
"\tUse ar::burg_method and ar::best_model to fit an autoregressive\n"
"\tprocess for signals contained in the rows of matrix data. Sample\n"
"\tmeans will be subtracted whenever submean is true. Model orders\n"
"\tzero through min(columns(data), maxorder) will be considered.\n"
"\tA structure is returned where each field either contains a result\n"
"\tindexable by the signal number (i.e. the row indices of input matrix\n"
"\tdata) or it contains a single scalar applicable to all signals.\n"
"\t\n"
"\tThe model order will be selected using the specified criterion.\n"
"\tCriteria are specified using the following abbreviations:\n"
"\t AIC - Akaike information criterion\n"
"\t AICC - asymptotically-corrected Akaike information criterion\n"
"\t BIC - consistent criterion BIC\n"
"\t CIC - combined information criterion\n"
"\t FIC - finite information criterion\n"
"\t FSIC - finite sample information criterion\n"
"\t GIC - generalized information criterion\n"
"\t MCC - minimally consistent criterion\n"
"\t\n"
"\tThe number of samples in data (i.e. the number of rows) is returned\n"
"\tin field 'N'. The filter()-ready process parameters are returned\n"
"\tin field 'AR', the sample mean in 'mu', and the innovation variance\n"
"\t\\sigma^2_\\epsilon in 'sigma2eps'. The process output variance\n"
"\t\\sigma^2_\\x and process gain are returned in fields 'sigma2x' and\n"
"\t'gain', respectively. Autocorrelations for lags zero through the\n"
"\tmodel order, inclusive, are returned in field 'autocor'. The raw\n"
"\tsignals are made available for later use in field 'data'.\n"
"\t\n"
"\tGiven the observed autocorrelation structure, a decorrelation time\n"
"\t'T0' is computed by ar::decorrelation_time and used to estimate\n"
"\tthe effective signal variance 'eff_var'. The number of effectively\n"
"\tindependent samples is returned in 'eff_N'. These effective values\n"
"\tare combined to estimate the sampling error (i.e. the standard\n"
"\tdeviation of the sample mean) as field 'mu_sigma'. The absolute\n"
"\tvalue of the autocorrelation function will be used in computing the\n"
"\tdecorrelation times whenever absrho is true.\n"
"\t\n"
"\tFor example, given a *row-vector* of samples 'x', one can fit a\n"
"\tprocess and then simulate a sample realization of length N using\n"
"\t\n"
"\t a = arsel(x);\n"
"\t x = a.mu + filter([1], a.AR{1}, sqrt(a.sigma2eps).*randn(N,1));\n"
"\t\n"
"\tWhen omitted, submean defaults to " STRINGIFY(DEFAULT_SUBMEAN) ".\n"
"\tWhen omitted, absrho defaults to " STRINGIFY(DEFAULT_ABSRHO) ".\n"
"\tWhen omitted, criterion defaults to " STRINGIFY(DEFAULT_CRITERION) ".\n"
"\tWhen omitted, maxorder defaults to " STRINGIFY(DEFAULT_MAXORDER) ".\n"
)
{
using std::size_t;
using std::string;
typedef Matrix::element_type element_type;
typedef std::vector<element_type> vector;
size_t maxorder = DEFAULT_MAXORDER;
string criterion = DEFAULT_CRITERION;
bool absrho = DEFAULT_ABSRHO;
bool submean = DEFAULT_SUBMEAN;
Matrix data;
switch (args.length())
{
case 5: maxorder = args(4).ulong_value();
case 4: criterion = args(3).string_value();
case 3: absrho = args(2).bool_value();
case 2: submean = args(1).bool_value();
case 1: data = args(0).matrix_value();
if (!error_state) break;
default:
error("Invalid call to arsel. See 'help arsel' for usage.");
return octave_value();
case 0:
print_usage();
return octave_value();
}
// Lookup the desired model selection criterion
typedef ar::best_model_function<
ar::Burg,octave_idx_type,vector> best_model_function;
const best_model_function::type best_model
= best_model_function::lookup(criterion, submean);
if (!best_model)
{
error("Unknown model selection criterion provided to arsel.");
return octave_value();
}
const octave_idx_type M = data.rows(); // Number of signals
const octave_idx_type N = data.cols(); // Samples per signal
// Prepare per-signal storage locations to return to caller
Cell _AR (dim_vector(M,1));
Cell _autocor (dim_vector(M,1));
ColumnVector _eff_N (M);
ColumnVector _eff_var (M);
ColumnVector _gain (M);
ColumnVector _mu (M);
ColumnVector _mu_sigma (M);
ColumnVector _sigma2eps(M);
ColumnVector _sigma2x (M);
ColumnVector _T0 (M);
// Prepare vectors to capture burg_method() output
vector params, sigma2e, gain, autocor;
params .reserve(maxorder*(maxorder + 1)/2);
sigma2e.reserve(maxorder + 1);
gain .reserve(maxorder + 1);
autocor.reserve(maxorder + 1);
// Prepare repeatedly-used working storage for burg_method()
vector f, b, Ak, ac;
// Process each signal in turn...
for (octave_idx_type i = 0; i < M; ++i)
{
// Use burg_method to estimate a hierarchy of AR models from input data
params .clear();
sigma2e.clear();
gain .clear();
autocor.clear();
ar::strided_adaptor<const element_type*> signal_begin(&data(i,0), M);
ar::strided_adaptor<const element_type*> signal_end (&data(i,N), M);
ar::burg_method(signal_begin, signal_end, _mu(i), maxorder,
std::back_inserter(params),
std::back_inserter(sigma2e),
std::back_inserter(gain),
std::back_inserter(autocor),
submean, /* output hierarchy? */ true, f, b, Ak, ac);
// Keep only best model per chosen criterion via function pointer
best_model(N, params, sigma2e, gain, autocor);
// Compute decorrelation time from the estimated autocorrelation model
ar::predictor<element_type> p = ar::autocorrelation(
params.begin(), params.end(), gain[0], autocor.begin());
_T0(i) = ar::decorrelation_time(N, p, absrho);
// Filter()-ready process parameters in field 'AR' with leading one
{
RowVector t(params.size() + 1);
t(0) = 1;
std::copy(params.begin(), params.end(), t.fortran_vec() + 1);
_AR(i) = t;
}
// Field 'sigma2eps'
_sigma2eps(i) = sigma2e[0];
// Field 'gain'
_gain(i) = gain[0];
// Field 'sigma2x'
_sigma2x(i) = gain[0]*sigma2e[0];
// Field 'autocor'
{
RowVector t(autocor.size());
std::copy(autocor.begin(), autocor.end(), t.fortran_vec());
_autocor(i) = t;
}
// Field 'eff_var'
// Unbiased effective variance expression from [Trenberth1984]
_eff_var(i) = (N*gain[0]*sigma2e[0]) / (N - _T0(i));
// Field 'eff_N'
_eff_N(i) = N / _T0(i);
// Field 'mu_sigma'
// Variance of the sample mean using effective quantities
_mu_sigma(i) = std::sqrt(_eff_var(i) / _eff_N(i));
// Permit user to interrupt the computations at this time
OCTAVE_QUIT;
}
// Provide no results whenever an error was detected
if (error_state)
{
warning("arsel: error detected; no results returned");
return octave_value_list();
}
// Build map containing return fields
Octave_map retval;
retval.assign("AR", octave_value(_AR));
retval.assign("absrho", octave_value(absrho));
retval.assign("autocor", octave_value(_autocor));
retval.assign("criterion", octave_value(criterion));
retval.assign("data", data);
retval.assign("eff_N", _eff_N);
retval.assign("eff_var", _eff_var);
retval.assign("gain", _gain);
retval.assign("maxorder", octave_value(maxorder));
retval.assign("mu", _mu);
retval.assign("mu_sigma", _mu_sigma);
retval.assign("N", octave_value(N));
retval.assign("sigma2eps", _sigma2eps);
retval.assign("sigma2x", _sigma2x);
retval.assign("submean", octave_value(submean));
retval.assign("T0", _T0);
return octave_value_list(retval);
}
<commit_msg>Progress on autocorrelation sample<commit_after>// Copyright (C) 2012 Rhys Ulerich
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 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 General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "ar.hpp"
#include <algorithm>
#include <cstdlib>
#include <iterator>
#include <limits>
#include <list>
#include <string>
#include <vector>
#include <octave/oct.h>
#include <octave/oct-map.h>
#include <octave/ov-struct.h>
#include <octave/Cell.h>
/** @file
* A GNU Octave function estimating the best AR(p) model given signal input.
* Compare \ref arsel.cpp.
*/
// Compile-time defaults in the code also appearing in the help message
#define DEFAULT_SUBMEAN true
#define DEFAULT_ABSRHO false
#define DEFAULT_CRITERION "CIC"
#define DEFAULT_MAXORDER 512
#define STRINGIFY(x) STRINGIFY_HELPER(x)
#define STRINGIFY_HELPER(x) #x
DEFUN_DLD(
arsel, args, nargout,
"\tM = arsel (data, submean, absrho, criterion, maxorder)\n"
"\tAutomatically fit autoregressive models to input signals.\n"
"\t\n"
"\tUse ar::burg_method and ar::best_model to fit an autoregressive\n"
"\tprocess for signals contained in the rows of matrix data. Sample\n"
"\tmeans will be subtracted whenever submean is true. Model orders\n"
"\tzero through min(columns(data), maxorder) will be considered.\n"
"\tA structure is returned where each field either contains a result\n"
"\tindexable by the signal number (i.e. the row indices of input matrix\n"
"\tdata) or it contains a single scalar applicable to all signals.\n"
"\t\n"
"\tThe model order will be selected using the specified criterion.\n"
"\tCriteria are specified using the following abbreviations:\n"
"\t AIC - Akaike information criterion\n"
"\t AICC - asymptotically-corrected Akaike information criterion\n"
"\t BIC - consistent criterion BIC\n"
"\t CIC - combined information criterion\n"
"\t FIC - finite information criterion\n"
"\t FSIC - finite sample information criterion\n"
"\t GIC - generalized information criterion\n"
"\t MCC - minimally consistent criterion\n"
"\t\n"
"\tThe number of samples in data (i.e. the number of rows) is returned\n"
"\tin field 'N'. The filter()-ready process parameters are returned\n"
"\tin field 'AR', the sample mean in 'mu', and the innovation variance\n"
"\t\\sigma^2_\\epsilon in 'sigma2eps'. The process output variance\n"
"\t\\sigma^2_\\x and process gain are returned in fields 'sigma2x' and\n"
"\t'gain', respectively. Autocorrelations for lags zero through the\n"
"\tmodel order, inclusive, are returned in field 'autocor'. The raw\n"
"\tsignals are made available for later use in field 'data'.\n"
"\t\n"
"\tGiven the observed autocorrelation structure, a decorrelation time\n"
"\t'T0' is computed by ar::decorrelation_time and used to estimate\n"
"\tthe effective signal variance 'eff_var'. The number of effectively\n"
"\tindependent samples is returned in 'eff_N'. These effective values\n"
"\tare combined to estimate the sampling error (i.e. the standard\n"
"\tdeviation of the sample mean) as field 'mu_sigma'. The absolute\n"
"\tvalue of the autocorrelation function will be used in computing the\n"
"\tdecorrelation times whenever absrho is true.\n"
"\t\n"
"\tFor example, given a *row-vector* of samples 'x', one can fit a\n"
"\tprocess and then simulate a sample realization of length M using\n"
"\t\n"
"\t a = arsel(x);\n"
"\t x = a.mu + filter([1], a.AR{1}, sqrt(a.sigma2eps).*randn(1,M));\n"
"\t\n"
// FIXME This example is going in the right direction but incorrect
// "\tContinuing the example, if the Octave signal package has been\n"
// "\tloaded, one can compute the autocorrelation for lags 0:M-1 using\n"
// "\t\n"
// "\t rho = filter([1], a.AR{1}, zeros(1,M), ...\n"
// "\t filtic([1], a.AR{1}, a.autocor{1}(2:end)));\n"
// "\t\n"
"\tWhen omitted, submean defaults to " STRINGIFY(DEFAULT_SUBMEAN) ".\n"
"\tWhen omitted, absrho defaults to " STRINGIFY(DEFAULT_ABSRHO) ".\n"
"\tWhen omitted, criterion defaults to " STRINGIFY(DEFAULT_CRITERION) ".\n"
"\tWhen omitted, maxorder defaults to " STRINGIFY(DEFAULT_MAXORDER) ".\n"
)
{
using std::size_t;
using std::string;
typedef Matrix::element_type element_type;
typedef std::vector<element_type> vector;
size_t maxorder = DEFAULT_MAXORDER;
string criterion = DEFAULT_CRITERION;
bool absrho = DEFAULT_ABSRHO;
bool submean = DEFAULT_SUBMEAN;
Matrix data;
switch (args.length())
{
case 5: maxorder = args(4).ulong_value();
case 4: criterion = args(3).string_value();
case 3: absrho = args(2).bool_value();
case 2: submean = args(1).bool_value();
case 1: data = args(0).matrix_value();
if (!error_state) break;
default:
error("Invalid call to arsel. See 'help arsel' for usage.");
return octave_value();
case 0:
print_usage();
return octave_value();
}
// Lookup the desired model selection criterion
typedef ar::best_model_function<
ar::Burg,octave_idx_type,vector> best_model_function;
const best_model_function::type best_model
= best_model_function::lookup(criterion, submean);
if (!best_model)
{
error("Unknown model selection criterion provided to arsel.");
return octave_value();
}
const octave_idx_type M = data.rows(); // Number of signals
const octave_idx_type N = data.cols(); // Samples per signal
// Prepare per-signal storage locations to return to caller
Cell _AR (dim_vector(M,1));
Cell _autocor (dim_vector(M,1));
ColumnVector _eff_N (M);
ColumnVector _eff_var (M);
ColumnVector _gain (M);
ColumnVector _mu (M);
ColumnVector _mu_sigma (M);
ColumnVector _sigma2eps(M);
ColumnVector _sigma2x (M);
ColumnVector _T0 (M);
// Prepare vectors to capture burg_method() output
vector params, sigma2e, gain, autocor;
params .reserve(maxorder*(maxorder + 1)/2);
sigma2e.reserve(maxorder + 1);
gain .reserve(maxorder + 1);
autocor.reserve(maxorder + 1);
// Prepare repeatedly-used working storage for burg_method()
vector f, b, Ak, ac;
// Process each signal in turn...
for (octave_idx_type i = 0; i < M; ++i)
{
// Use burg_method to estimate a hierarchy of AR models from input data
params .clear();
sigma2e.clear();
gain .clear();
autocor.clear();
ar::strided_adaptor<const element_type*> signal_begin(&data(i,0), M);
ar::strided_adaptor<const element_type*> signal_end (&data(i,N), M);
ar::burg_method(signal_begin, signal_end, _mu(i), maxorder,
std::back_inserter(params),
std::back_inserter(sigma2e),
std::back_inserter(gain),
std::back_inserter(autocor),
submean, /* output hierarchy? */ true, f, b, Ak, ac);
// Keep only best model per chosen criterion via function pointer
best_model(N, params, sigma2e, gain, autocor);
// Compute decorrelation time from the estimated autocorrelation model
ar::predictor<element_type> p = ar::autocorrelation(
params.begin(), params.end(), gain[0], autocor.begin());
_T0(i) = ar::decorrelation_time(N, p, absrho);
// Filter()-ready process parameters in field 'AR' with leading one
{
RowVector t(params.size() + 1);
t(0) = 1;
std::copy(params.begin(), params.end(), t.fortran_vec() + 1);
_AR(i) = t;
}
// Field 'sigma2eps'
_sigma2eps(i) = sigma2e[0];
// Field 'gain'
_gain(i) = gain[0];
// Field 'sigma2x'
_sigma2x(i) = gain[0]*sigma2e[0];
// Field 'autocor'
{
RowVector t(autocor.size());
std::copy(autocor.begin(), autocor.end(), t.fortran_vec());
_autocor(i) = t;
}
// Field 'eff_var'
// Unbiased effective variance expression from [Trenberth1984]
_eff_var(i) = (N*gain[0]*sigma2e[0]) / (N - _T0(i));
// Field 'eff_N'
_eff_N(i) = N / _T0(i);
// Field 'mu_sigma'
// Variance of the sample mean using effective quantities
_mu_sigma(i) = std::sqrt(_eff_var(i) / _eff_N(i));
// Permit user to interrupt the computations at this time
OCTAVE_QUIT;
}
// Provide no results whenever an error was detected
if (error_state)
{
warning("arsel: error detected; no results returned");
return octave_value_list();
}
// Build map containing return fields
Octave_map retval;
retval.assign("AR", octave_value(_AR));
retval.assign("absrho", octave_value(absrho));
retval.assign("autocor", octave_value(_autocor));
retval.assign("criterion", octave_value(criterion));
retval.assign("data", data);
retval.assign("eff_N", _eff_N);
retval.assign("eff_var", _eff_var);
retval.assign("gain", _gain);
retval.assign("maxorder", octave_value(maxorder));
retval.assign("mu", _mu);
retval.assign("mu_sigma", _mu_sigma);
retval.assign("N", octave_value(N));
retval.assign("sigma2eps", _sigma2eps);
retval.assign("sigma2x", _sigma2x);
retval.assign("submean", octave_value(submean));
retval.assign("T0", _T0);
return octave_value_list(retval);
}
<|endoftext|> |
<commit_before>/*
* Map.cpp
*
* Created on: 24/01/2014
* Author: drb
*/
#include "Map.h"
#include <fstream>
namespace map {
Map::Map() {
// TODO Auto-generated constructor stub
this->textures = nullptr;
this->inited = false;
}
Map::~Map() {
// TODO Auto-generated destructor stub
unload();
}
Map::Map(graphics::TextureManager* textures)
{
this->inited = false;
this->textures = nullptr;
this->init(textures);
}
bool Map::init (graphics::TextureManager* textures)
{
this->textures = textures;
this->map = etc::AreaMap();
this->inited = true;
return this->inited;
}
/**
* @brief Load Map file
* @parm file File path to map
*/
void Map::loadMap(std::string file)
{
//std::fstream fs;
//fs.open(file.c_str());
for (int x = 0; x < 500; x++) {
for (int y = 0; y < 500; y++) {
MapTile* tile;
SDL_Rect pos;
pos.x = x * 32;
pos.y = y * 32;
pos.h = 32;
pos.w = 32;
SDL_Point cor;
cor.x = 16;
cor.y = 16;
tile = new MapTile( this->textures->getTexture("grass") , pos, (x % 4 + y % 2) % 4 , 0 , cor , (SDL_RendererFlip)(y % 2));
tile->setAdjustCamera(true);
this->maptiles.push_back(tile);
this->map.insert(tile);
}
}
//fs.close();
}
void Map::unloadMap()
{
for (auto tile : this->maptiles)
{
delete tile;
}
this->maptiles.clear();
}
void Map::unload()
{
unloadMap();
}
void Map::render (const Ldouble& delta, SDL_Renderer* renderer , etc::Camera& camera)
{
auto tiles = this->map.getSpritesFromArea(camera.getViewport());
for (auto tile : tiles) {
tile->render(delta , renderer , camera);
}
}
void Map::update (const Ldouble& delta)
{
}
} /* namespace map */
<commit_msg>Map loading from file<commit_after>/*
* Map.cpp
*
* Created on: 24/01/2014
* Author: drb
*/
#include "Map.h"
#include <fstream>
#include "../etc/string.h"
#if __GNUC__
#include <SDL2/SDL.h>
#else
#include "SDL.h"
#endif
namespace map {
Map::Map() {
// TODO Auto-generated constructor stub
this->textures = nullptr;
this->inited = false;
}
Map::~Map() {
// TODO Auto-generated destructor stub
unload();
}
Map::Map(graphics::TextureManager* textures)
{
this->inited = false;
this->textures = nullptr;
this->init(textures);
}
bool Map::init (graphics::TextureManager* textures)
{
this->textures = textures;
this->map = etc::AreaMap();
this->inited = true;
return this->inited;
}
/**
* @brief Load Map file
* @parm file File path to map
*/
void Map::loadMap(std::string file)
{
std::fstream fs;
fs.open(file.c_str());
std::string line;
while ( ! fs.eof() )
{
std::getline( fs , line );
// # are comments
if (etc::startswith( line , "#" ) )
continue;
auto seg = etc::split(line, ",");
SDL_Rect pt;
std::string tex;
int tex_index = 0;
SDL_RendererFlip flip;
//Texture name
tex = seg[2];
//Texture Map index
tex_index = atoi( seg[3].c_str() );
//Texture flip
flip = (SDL_RendererFlip)atoi( seg[4].c_str() );
//Position
//X
pt.x = atoi( seg[0].c_str() );
//Y
pt.y = atoi( seg[1].c_str() );
SDL_Rect* size = this->textures->getTexture(tex)->getSprite(tex_index);
pt.w = size->w;
pt.h = size->h;
MapTile* tile;
SDL_Point cor; //center of rotation
cor.x = pt.w/2; cor.y = pt.h/2;
tile = new MapTile( this->textures->getTexture(tex)
, pt
, tex_index
, 0.0
, cor
, flip );
tile->setAdjustCamera(true);
this->maptiles.push_back(tile);
this->map.insert(tile);
}
fs.close();
}
void Map::unloadMap()
{
for (auto tile : this->maptiles)
{
delete tile;
}
this->maptiles.clear();
}
void Map::unload()
{
unloadMap();
}
void Map::render (const Ldouble& delta, SDL_Renderer* renderer , etc::Camera& camera)
{
auto tiles = this->map.getSpritesFromArea(camera.getViewport());
for (auto tile : tiles) {
tile->render(delta , renderer , camera);
}
}
void Map::update (const Ldouble& delta)
{
}
} /* namespace map */
<|endoftext|> |
<commit_before>#include <glog/logging.h>
#include <boost/filesystem.hpp>
#include <regex>
#include <dlfcn.h>
#include <iostream>
#include <util.h>
#include <core/core.h>
#include <rules_loader.h>
using namespace boost::filesystem;
namespace {
const std::string dl_symbol = "rules";
std::vector<std::string> so_files(std::string dir) {
VLOG(3) << "loading rules";
std::vector<std::string> files;
std::regex pattern(".*\\.so");
for (directory_iterator iter(dir), end;
iter != end;
++iter)
{
std::string fn = iter->path().filename().string();
if (regex_match(fn, pattern))
{
VLOG(3) << "library found: " << fn;
files.push_back(fn);
}
}
return files;
}
std::shared_ptr<streams_t> load_library(std::string lib) {
void *handle = dlopen(lib.c_str(), RTLD_LAZY);
if (!handle) {
LOG(ERROR) << "error opening " << lib << " " << dlerror();
return nullptr;
}
typedef streams_t* (*rules_t)();
rules_t rules = (rules_t) dlsym(handle, dl_symbol.c_str());
if (!rules) {
LOG(ERROR) << "failed to load symbol: " << dl_symbol;
dlclose(handle);
return nullptr;
}
VLOG(3) << "loading rules from " << lib;
auto stream = rules();
LOG(INFO) << "rules loaded succesfully from " << lib;
dlclose(handle);
return std::shared_ptr<streams_t>(stream);
}
}
std::vector<std::shared_ptr<streams_t>> load_rules(const std::string dir) {
std::vector<std::shared_ptr<streams_t>> rules;
for (const auto & lib : so_files(dir)) {
std::shared_ptr<streams_t> stream = load_library(lib);
if (stream) {
rules.push_back(stream);
}
}
return rules;
}
<commit_msg>Fix issues with lib loading/unloading<commit_after>#include <glog/logging.h>
#include <boost/filesystem.hpp>
#include <regex>
#include <dlfcn.h>
#include <iostream>
#include <util.h>
#include <core/core.h>
#include <rules_loader.h>
using namespace boost::filesystem;
namespace {
const std::string dl_symbol = "rules";
std::vector<std::string> so_files(std::string dir) {
VLOG(3) << "loading rules";
std::vector<std::string> files;
std::regex pattern(".*\\.so");
for (directory_iterator iter(dir), end;
iter != end;
++iter)
{
std::string fn = iter->path().filename().string();
if (regex_match(fn, pattern))
{
VLOG(3) << "library found: " << fn;
files.push_back(fn);
}
}
return files;
}
std::shared_ptr<streams_t> load_library(std::string lib) {
void *handle = dlopen(lib.c_str(), RTLD_NOW);
if (!handle) {
LOG(ERROR) << "error opening " << lib << " " << dlerror();
return nullptr;
}
typedef streams_t* (*rules_t)();
rules_t rules = (rules_t) dlsym(handle, dl_symbol.c_str());
if (!rules) {
LOG(ERROR) << "failed to load symbol: " << dl_symbol;
dlclose(handle);
return nullptr;
}
VLOG(3) << "loading rules from " << lib;
auto stream = rules();
LOG(INFO) << "rules loaded succesfully from " << lib;
//TODO Store lib handle and close it
return std::shared_ptr<streams_t>(stream);
}
}
std::vector<std::shared_ptr<streams_t>> load_rules(const std::string dir) {
std::vector<std::shared_ptr<streams_t>> rules;
for (const auto & lib : so_files(dir)) {
std::shared_ptr<streams_t> stream = load_library(lib);
if (stream) {
rules.push_back(stream);
}
}
return rules;
}
<|endoftext|> |
<commit_before>#include "scopemeasure.h"
#include <cinttypes>
#include <sys/time.h>
namespace newsboat {
ScopeMeasure::ScopeMeasure(const std::string& func, Level ll)
: funcname(func)
, lvl(ll)
{
gettimeofday(&tv1, nullptr);
}
void ScopeMeasure::stopover(const std::string& son)
{
gettimeofday(&tv2, nullptr);
const uint64_t diff =
(((tv2.tv_sec - tv1.tv_sec) * 1000000) + tv2.tv_usec) -
tv1.tv_usec;
LOG(lvl,
"ScopeMeasure: function `%s' (stop over `%s') took %" PRIu64 ".%06"
PRIu64 " s so far",
funcname,
son,
diff / 1000000,
diff % 1000000);
}
ScopeMeasure::~ScopeMeasure()
{
gettimeofday(&tv2, nullptr);
const uint64_t diff =
(((tv2.tv_sec - tv1.tv_sec) * 1000000) + tv2.tv_usec) -
tv1.tv_usec;
LOG(Level::INFO,
"ScopeMeasure: function `%s' took %" PRIu64 ".%06" PRIu64 " s",
funcname,
diff / 1000000,
diff % 1000000);
}
} // namespace newsboat
<commit_msg>ScopeMeasure: Use provided log level instead of hard-coded Level::INFO<commit_after>#include "scopemeasure.h"
#include <cinttypes>
#include <sys/time.h>
namespace newsboat {
ScopeMeasure::ScopeMeasure(const std::string& func, Level ll)
: funcname(func)
, lvl(ll)
{
gettimeofday(&tv1, nullptr);
}
void ScopeMeasure::stopover(const std::string& son)
{
gettimeofday(&tv2, nullptr);
const uint64_t diff =
(((tv2.tv_sec - tv1.tv_sec) * 1000000) + tv2.tv_usec) -
tv1.tv_usec;
LOG(lvl,
"ScopeMeasure: function `%s' (stop over `%s') took %" PRIu64 ".%06"
PRIu64 " s so far",
funcname,
son,
diff / 1000000,
diff % 1000000);
}
ScopeMeasure::~ScopeMeasure()
{
gettimeofday(&tv2, nullptr);
const uint64_t diff =
(((tv2.tv_sec - tv1.tv_sec) * 1000000) + tv2.tv_usec) -
tv1.tv_usec;
LOG(lvl,
"ScopeMeasure: function `%s' took %" PRIu64 ".%06" PRIu64 " s",
funcname,
diff / 1000000,
diff % 1000000);
}
} // namespace newsboat
<|endoftext|> |
<commit_before>/**
* @file
* @author Inmatarian <inmatarian@gmail.com>
* @section LICENSE
* Insert copyright and license information here.
*/
#include <cassert>
#include <SDL.h>
#include "defines.h"
#include "zstring.h"
#include "freezztManager.h"
#include "sdlManager.h"
#include "sdlEventLoop.h"
static void translateSDLKeyToZZT( const SDL_keysym &keysym,
int &keycode,
int &unicode )
{
// most of the SDL unicodes are safe to use as straight zzt keys, though
// we have a few that need filtering out.
using namespace Defines;
switch ( keysym.sym )
{
case SDLK_UP:
keycode = ( keysym.mod & KMOD_SHIFT ) ? Z_ShootUp : Z_Up;
unicode = 0;
break;
case SDLK_DOWN:
keycode = ( keysym.mod & KMOD_SHIFT ) ? Z_ShootDown : Z_Down;
unicode = 0;
break;
case SDLK_LEFT:
keycode = ( keysym.mod & KMOD_SHIFT ) ? Z_ShootLeft : Z_Left;
unicode = 0;
break;
case SDLK_RIGHT:
keycode = ( keysym.mod & KMOD_SHIFT ) ? Z_ShootRight : Z_Right;
unicode = 0;
break;
case SDLK_ESCAPE: keycode = Z_Escape; unicode = 0; break;
case SDLK_RETURN: keycode = Z_Enter; unicode = 0; break;
case SDLK_BACKSPACE: keycode = Z_Backspace; unicode = 0; break;
case SDLK_TAB: keycode = Z_Tab; unicode = 0; break;
case SDLK_HOME: keycode = Z_Home; unicode = 0; break;
case SDLK_END: keycode = Z_End; unicode = 0; break;
case SDLK_PAGEUP: keycode = Z_PageUp; unicode = 0; break;
case SDLK_PAGEDOWN: keycode = Z_PageDown; unicode = 0; break;
case SDLK_INSERT: keycode = Z_Insert; unicode = 0; break;
case SDLK_DELETE: keycode = Z_Delete; unicode = 0; break;
case SDLK_F1: keycode = Z_F1; unicode = 0; break;
case SDLK_F2: keycode = Z_F2; unicode = 0; break;
case SDLK_F3: keycode = Z_F3; unicode = 0; break;
case SDLK_F4: keycode = Z_F4; unicode = 0; break;
case SDLK_F5: keycode = Z_F5; unicode = 0; break;
case SDLK_F6: keycode = Z_F6; unicode = 0; break;
case SDLK_F7: keycode = Z_F7; unicode = 0; break;
case SDLK_F8: keycode = Z_F8; unicode = 0; break;
case SDLK_F9: keycode = Z_F9; unicode = 0; break;
case SDLK_F10: keycode = Z_F10; unicode = 0; break;
case SDLK_F11: keycode = Z_F11; unicode = 0; break;
case SDLK_F12: keycode = Z_F12; unicode = 0; break;
default:
keycode = Z_Unicode;
unicode = keysym.unicode;
break;
}
}
enum {
USERCODE_FRAMEUPDATE = 1
};
// belongs to other thread, don't touch.
static Uint32 update_timer_callback(Uint32 interval, void *param)
{
SDL_UserEvent userevent;
userevent.type = SDL_USEREVENT;
userevent.code = USERCODE_FRAMEUPDATE;
userevent.data1 = 0;
userevent.data2 = 0;
SDL_Event event;
event.type = SDL_USEREVENT;
event.user = userevent;
SDL_PushEvent(&event);
return interval;
}
// ---------------------------------------------------------------------------
class SDLEventLoopPrivate
{
public:
SDLEventLoopPrivate( SDLEventLoop *pSelf )
: pZZTManager( 0 ),
pSDLManager( 0 ),
pPainter( 0 ),
stop( false ),
doFrame( false ),
hasUpdateTimer( false ),
updateTimerID( 0 ),
self( pSelf )
{ /* */ };
void parseEvent( const SDL_Event &event );
public:
FreeZZTManager *pZZTManager;
SDLManager *pSDLManager;
AbstractPainter *pPainter;
bool stop;
bool doFrame;
bool hasUpdateTimer;
SDL_TimerID updateTimerID;
private:
SDLEventLoop *self;
};
void SDLEventLoopPrivate::parseEvent( const SDL_Event &event )
{
switch ( event.type )
{
case SDL_QUIT:
stop = true;
break;
case SDL_KEYDOWN: {
int keycode, unicode;
translateSDLKeyToZZT( event.key.keysym, keycode, unicode );
switch ( keycode )
{
case Defines::Z_F10:
// during development, F10 is the auto-quit key
stop = true;
break;
case Defines::Z_F11:
pSDLManager->toggleFullScreen();
break;
default:
pZZTManager->doKeypress( keycode, unicode );
break;
}
break;
}
case SDL_VIDEORESIZE:
pSDLManager->doResize( event.resize.w, event.resize.h );
break;
case SDL_USEREVENT:
if ( event.user.code == USERCODE_FRAMEUPDATE ) {
doFrame = true;
}
break;
default: break;
}
}
SDLEventLoop::SDLEventLoop()
: d( new SDLEventLoopPrivate(this) )
{
/* */
}
SDLEventLoop::~SDLEventLoop()
{
if (d->hasUpdateTimer) {
SDL_RemoveTimer( d->updateTimerID );
}
delete d;
d = 0;
}
void SDLEventLoop::exec()
{
assert( d->pZZTManager );
d->pZZTManager->begin();
SDL_Event event;
int lastClockUpdate = 0;
while ( !d->stop && !d->pZZTManager->quitting() )
{
SDL_WaitEvent( &event );
d->parseEvent( event );
if (d->stop) break;
while ( SDL_PollEvent( &event ) ) {
d->parseEvent( event );
if (d->stop) break;
}
if (d->doFrame) {
d->pZZTManager->doUpdate();
d->pZZTManager->doPaint( painter() );
d->doFrame = false;
}
}
d->pZZTManager->end();
}
void SDLEventLoop::setZZTManager( FreeZZTManager *manager )
{
d->pZZTManager = manager;
}
FreeZZTManager *SDLEventLoop::zztManager() const
{
return d->pZZTManager;
}
void SDLEventLoop::setSDLManager( SDLManager *manager )
{
d->pSDLManager = manager;
}
SDLManager *SDLEventLoop::sdlManager() const
{
return d->pSDLManager;
}
void SDLEventLoop::setPainter( AbstractPainter *painter )
{
d->pPainter = painter;
}
AbstractPainter *SDLEventLoop::painter() const
{
return d->pPainter;
}
void SDLEventLoop::setFrameLatency( int milliseconds )
{
if (d->hasUpdateTimer) {
SDL_RemoveTimer( d->updateTimerID );
}
d->hasUpdateTimer = true;
d->updateTimerID = SDL_AddTimer(milliseconds, &update_timer_callback, 0);
}
<commit_msg>Upgrayedd Framerate code.<commit_after>/**
* @file
* @author Inmatarian <inmatarian@gmail.com>
* @section LICENSE
* Insert copyright and license information here.
*/
#include <cassert>
#include <SDL.h>
#include <SDL_thread.h>
#include "defines.h"
#include "zstring.h"
#include "freezztManager.h"
#include "sdlManager.h"
#include "sdlEventLoop.h"
static void translateSDLKeyToZZT( const SDL_keysym &keysym,
int &keycode,
int &unicode )
{
// most of the SDL unicodes are safe to use as straight zzt keys, though
// we have a few that need filtering out.
using namespace Defines;
switch ( keysym.sym )
{
case SDLK_UP:
keycode = ( keysym.mod & KMOD_SHIFT ) ? Z_ShootUp : Z_Up;
unicode = 0;
break;
case SDLK_DOWN:
keycode = ( keysym.mod & KMOD_SHIFT ) ? Z_ShootDown : Z_Down;
unicode = 0;
break;
case SDLK_LEFT:
keycode = ( keysym.mod & KMOD_SHIFT ) ? Z_ShootLeft : Z_Left;
unicode = 0;
break;
case SDLK_RIGHT:
keycode = ( keysym.mod & KMOD_SHIFT ) ? Z_ShootRight : Z_Right;
unicode = 0;
break;
case SDLK_ESCAPE: keycode = Z_Escape; unicode = 0; break;
case SDLK_RETURN: keycode = Z_Enter; unicode = 0; break;
case SDLK_BACKSPACE: keycode = Z_Backspace; unicode = 0; break;
case SDLK_TAB: keycode = Z_Tab; unicode = 0; break;
case SDLK_HOME: keycode = Z_Home; unicode = 0; break;
case SDLK_END: keycode = Z_End; unicode = 0; break;
case SDLK_PAGEUP: keycode = Z_PageUp; unicode = 0; break;
case SDLK_PAGEDOWN: keycode = Z_PageDown; unicode = 0; break;
case SDLK_INSERT: keycode = Z_Insert; unicode = 0; break;
case SDLK_DELETE: keycode = Z_Delete; unicode = 0; break;
case SDLK_F1: keycode = Z_F1; unicode = 0; break;
case SDLK_F2: keycode = Z_F2; unicode = 0; break;
case SDLK_F3: keycode = Z_F3; unicode = 0; break;
case SDLK_F4: keycode = Z_F4; unicode = 0; break;
case SDLK_F5: keycode = Z_F5; unicode = 0; break;
case SDLK_F6: keycode = Z_F6; unicode = 0; break;
case SDLK_F7: keycode = Z_F7; unicode = 0; break;
case SDLK_F8: keycode = Z_F8; unicode = 0; break;
case SDLK_F9: keycode = Z_F9; unicode = 0; break;
case SDLK_F10: keycode = Z_F10; unicode = 0; break;
case SDLK_F11: keycode = Z_F11; unicode = 0; break;
case SDLK_F12: keycode = Z_F12; unicode = 0; break;
default:
keycode = Z_Unicode;
unicode = keysym.unicode;
break;
}
}
// ---------
enum {
USERCODE_FRAMEUPDATE = 1,
USERCODE_KEYUPDATE = 2
};
class MutexLocker
{
public:
MutexLocker( SDL_mutex *m ) : mutex(m) { if (mutex) SDL_mutexP(mutex); };
~MutexLocker() { if (mutex) SDL_mutexV(mutex); };
private:
SDL_mutex *mutex;
};
class UpdateThread
{
public:
// GUI THREAD CODE
static void start();
static void stop();
static void setFrameLatency( Sint32 latency );
protected:
// UPDATE THREAD CODE
static void lock();
static void unlock();
static Uint32 update_timer_callback(Uint32 interval, void *param);
static void serviceFrameUpdate( Uint32 interval );
private:
static bool m_started;
static SDL_TimerID m_id;
static SDL_mutex *m_mutex;
static Sint32 m_latency;
static Sint32 m_latencyClock;
};
bool UpdateThread::m_started = false;
SDL_TimerID UpdateThread::m_id = 0;
SDL_mutex *UpdateThread::m_mutex = 0;
Sint32 UpdateThread::m_latency = 27;
Sint32 UpdateThread::m_latencyClock = 0;
void UpdateThread::start()
{
if ( m_started ) return;
m_id = SDL_AddTimer(10, &update_timer_callback, 0);
m_mutex = SDL_CreateMutex();
m_started = true;
}
void UpdateThread::stop()
{
if ( !m_started ) return;
SDL_RemoveTimer( m_id );
SDL_DestroyMutex( m_mutex );
m_mutex = 0;
m_started = false;
}
void UpdateThread::setFrameLatency( Sint32 latency )
{
MutexLocker lock( m_mutex );
m_latency = latency;
m_latencyClock = 0;
}
void UpdateThread::serviceFrameUpdate( Uint32 interval )
{
// Generate a Frame Update event when enough time has passed.
// Drop lost update when too much time has passed.
m_latencyClock += interval;
if ( m_latencyClock < m_latency ) {
return;
}
if ( m_latencyClock >= m_latency * 3 ) {
m_latencyClock = 0;
}
else {
m_latencyClock -= m_latency;
}
SDL_UserEvent userevent;
userevent.type = SDL_USEREVENT;
userevent.code = USERCODE_FRAMEUPDATE;
userevent.data1 = 0;
userevent.data2 = 0;
SDL_Event event;
event.type = SDL_USEREVENT;
event.user = userevent;
SDL_PushEvent(&event);
}
Uint32 UpdateThread::update_timer_callback(Uint32 interval, void *param)
{
serviceFrameUpdate( interval );
return interval;
}
// ---------------------------------------------------------------------------
class SDLEventLoopPrivate
{
public:
SDLEventLoopPrivate( SDLEventLoop *pSelf );
~SDLEventLoopPrivate();
void parseEvent( const SDL_Event &event );
public:
FreeZZTManager *pZZTManager;
SDLManager *pSDLManager;
AbstractPainter *pPainter;
bool stop;
bool doFrame;
private:
SDLEventLoop *self;
};
SDLEventLoopPrivate::SDLEventLoopPrivate( SDLEventLoop *pSelf )
: pZZTManager( 0 ),
pSDLManager( 0 ),
pPainter( 0 ),
stop( false ),
doFrame( false ),
self( pSelf )
{
/* */
}
SDLEventLoopPrivate::~SDLEventLoopPrivate()
{
UpdateThread::stop();
}
void SDLEventLoopPrivate::parseEvent( const SDL_Event &event )
{
switch ( event.type )
{
case SDL_QUIT:
stop = true;
break;
case SDL_KEYDOWN: {
int keycode, unicode;
translateSDLKeyToZZT( event.key.keysym, keycode, unicode );
switch ( keycode )
{
case Defines::Z_F10:
// during development, F10 is the auto-quit key
stop = true;
break;
case Defines::Z_F11:
pSDLManager->toggleFullScreen();
break;
default:
pZZTManager->doKeypress( keycode, unicode );
break;
}
break;
}
case SDL_VIDEORESIZE:
pSDLManager->doResize( event.resize.w, event.resize.h );
break;
case SDL_USEREVENT:
if ( event.user.code == USERCODE_FRAMEUPDATE ) {
doFrame = true;
}
break;
default: break;
}
}
SDLEventLoop::SDLEventLoop()
: d( new SDLEventLoopPrivate(this) )
{
/* */
}
SDLEventLoop::~SDLEventLoop()
{
delete d;
d = 0;
}
void SDLEventLoop::exec()
{
assert( d->pZZTManager );
d->pZZTManager->begin();
UpdateThread::start();
SDL_Event event;
int lastClockUpdate = 0;
while ( !d->stop && !d->pZZTManager->quitting() )
{
SDL_WaitEvent( &event );
d->parseEvent( event );
if (d->stop) break;
while ( SDL_PollEvent( &event ) ) {
d->parseEvent( event );
if (d->stop) break;
}
if (d->doFrame) {
d->pZZTManager->doUpdate();
d->pZZTManager->doPaint( painter() );
d->doFrame = false;
}
}
UpdateThread::stop();
d->pZZTManager->end();
}
void SDLEventLoop::setZZTManager( FreeZZTManager *manager )
{
d->pZZTManager = manager;
}
FreeZZTManager *SDLEventLoop::zztManager() const
{
return d->pZZTManager;
}
void SDLEventLoop::setSDLManager( SDLManager *manager )
{
d->pSDLManager = manager;
}
SDLManager *SDLEventLoop::sdlManager() const
{
return d->pSDLManager;
}
void SDLEventLoop::setPainter( AbstractPainter *painter )
{
d->pPainter = painter;
}
AbstractPainter *SDLEventLoop::painter() const
{
return d->pPainter;
}
void SDLEventLoop::setFrameLatency( int milliseconds )
{
UpdateThread::setFrameLatency( milliseconds );
}
<|endoftext|> |
<commit_before>#include "sound3d.h"
#include <iostream>
using namespace std;
int main() {
sound3d s;
ALCdevice* d = s.get_device();
ALCint num;
alcGetIntegerv(d, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num);
LPALCGETSTRINGISOFT ags = (LPALCGETSTRINGISOFT)(alcGetProcAddress(d, "alcGetStringiSOFT"));
if(!num){
cout << "none" << endl;
}
for(int i = 0; i < num; i++) {
cout << i << ": " << ags(d, ALC_HRTF_SPECIFIER_SOFT, i) << endl;
}
//return 0;
s.load("test.ogg");
s.set_loops(true);
s.set_hrtf(true, 2);
s.set_coords(0, -2, 0);
s.play();
s.set_listener_ori(0,1,0,0,0,1);
for(int x = 0; x < 1000000000; x++) {
}
/*
Sleep(1000);
s.set_coords(2, 2, 0);
Sleep(1000);
s.set_coords(0, 2, 0);
Sleep(1000);
s.set_coords(-2, 0, 0);
Sleep(1000);
s.set_coords(-2, -2, 0);
Sleep(1000);
s.set_coords(0, -2, 0);
Sleep(1000);
s.set_coords(2, -2, 0);
Sleep(1000);
s.set_coords(2, 0, 0);
Sleep(1000);
*/
}
<commit_msg>Removed one extraneous file.<commit_after><|endoftext|> |
<commit_before>/* This is both a sort of unit test, and a demonstration of how to use deadlock
* prevention.
*
* Suggested compilation command:
* c++ -Wall -pedantic -std=c++11 test.cpp -o test -lpthread
*/
#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <stdarg.h>
#include <pthread.h>
#include "locking-container.hpp"
//use this definition if you want the simple test
#define THREAD_TYPE thread
//use this definition if you want the multi-lock test
//#define THREAD_TYPE thread_multi
//(probably better as arguments, but I'm too lazy right now)
#define THREADS 10
#define TIME 30
//(if you set either of these to 'false', the threads will gradually die off)
#define READ_BLOCK true
#define WRITE_BLOCK true
//the data being protected (initialize the 'int' to 'THREADS')
typedef locking_container <int> protected_int;
static protected_int my_data(THREADS);
//(used by 'thread_multi')
static protected_int my_data2;
static null_container multi_lock;
static void send_output(const char *format, ...);
static void *thread(void *nv);
static void *thread_multi(void *nv);
int main()
{
//create some threads
pthread_t threads[THREADS];
for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
send_output("start %li\n", i);
threads[i] = pthread_t();
if (pthread_create(threads + i, NULL, &THREAD_TYPE, (void*) i) != 0) {
send_output("error: %s\n", strerror(errno));
}
}
//wait for them to do some stuff
sleep(TIME);
//the threads exit when the value goes below 0
{
protected_int::proxy write = my_data.get();
//(no clean way to exit if the container can't be locked)
assert(write);
*write = -1;
} //<-- proxy goes out of scope and unlocks 'my_data' here (you can also 'write.clear()')
for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
send_output("?join %li\n", i);
pthread_join(threads[i], NULL);
send_output("+join %li\n", i);
}
}
//a print function that ensures we have exclusive access to the output
static void send_output(const char *format, ...) {
//protect the output file while we're at it
typedef locking_container <FILE*, w_lock> protected_out;
//(this is local so that it can't be involved in a deadlock)
static protected_out stdout2(stdout);
va_list ap;
va_start(ap, format);
//NOTE: authorization isn't important here because it's not possible for the
//caller to lock another container while it holds a lock on 'stdout2';
//deadlocks aren't an issue with respect to 'stdout2'
protected_out::proxy write = stdout2.get();
if (!write) return;
vfprintf(*write, format, ap);
}
//a simple thread for repeatedly accessing the data
static void *thread(void *nv) {
//(cancelation can be messy...)
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;
//get an authorization object, to prevent deadlocks
//NOTE: for the most part you should be able to use any authorization type
//with any lock type, but the behavior will be the stricter of the two
protected_int::auth_type auth(protected_int::new_auth());
long n = (long) nv, counter = 0;
struct timespec wait = { 0, (10 + n) * 10 * 1000 * 1000 };
nanosleep(&wait, NULL);
//loop through reading and writing forever
while (true) {
//read a bunch of times
for (int i = 0; i < THREADS + n; i++) {
send_output("?read %li\n", n);
protected_int::const_proxy read = my_data.get_auth_const(auth, READ_BLOCK);
if (!read) {
send_output("!read %li\n", n);
return NULL;
}
send_output("+read %li (%i) -> %i\n", n, read.last_lock_count(), *read);
send_output("@read %li %i\n", n, !!my_data.get_auth_const(auth, READ_BLOCK));
if (*read < 0) {
send_output("counter %li %i\n", n, counter);
return NULL;
}
//(sort of like a contest, to see how many times each thread reads its own number)
if (*read == n) ++counter;
nanosleep(&wait, NULL);
read.clear();
send_output("-read %li\n", n);
nanosleep(&wait, NULL);
}
//write once
send_output("?write %li\n", n);
protected_int::proxy write = my_data.get_auth(auth, WRITE_BLOCK);
if (!write) {
send_output("!write %li\n", n);
return NULL;
}
send_output("+write %li (%i)\n", n, write.last_lock_count());
send_output("@write %li %i\n", n, !!my_data.get_auth(auth, WRITE_BLOCK));
if (*write < 0) {
send_output("counter %li %i\n", n, counter);
return NULL;
}
*write = n;
nanosleep(&wait, NULL);
write.clear();
send_output("-write %li\n", n);
nanosleep(&wait, NULL);
}
}
//a more complicated thread that requires deadlock prevention, but multiple write locks at once
static void *thread_multi(void *nv) {
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;
protected_int::auth_type auth(protected_int::new_auth());
long n = (long) nv;
struct timespec wait = { 0, (10 + n) * 1 * 1000 * 1000 };
nanosleep(&wait, NULL);
while (true) {
for (int i = 0; i < THREADS + n; i++) {
send_output("?read0 %li\n", n);
protected_int::const_proxy read0 = my_data.get_multi_const(multi_lock, auth);
if (!read0) {
send_output("!read0 %li\n", n);
return NULL;
}
send_output("+read0 %li (%i) -> %i\n", n, read0.last_lock_count(), *read0);
if (*read0 < 0) return NULL;
nanosleep(&wait, NULL);
send_output("?read1 %li\n", n);
protected_int::const_proxy read1 = my_data2.get_multi_const(multi_lock, auth);
if (!read1) {
send_output("!read1 %li\n", n);
//NOTE: due to deadlock prevention, 'auth' will reject a lock if another
//thread is waiting for a write lock for 'multi_lock' because this
//thread already holds a read lock (on 'my_data'). (this could easily
//lead to a deadlock if 'get_multi_const' above blocked.) this isn't a
//catastrophic error, so we just break out of this loop.
break;
}
send_output("+read1 %li (%i) -> %i\n", n, read1.last_lock_count(), *read1);
if (*read1 < 0) return NULL;
nanosleep(&wait, NULL);
read1.clear();
send_output("-read1 %li\n", n);
read0.clear();
send_output("-read0 %li\n", n);
nanosleep(&wait, NULL);
send_output("?write %li\n", n);
protected_int::proxy write = my_data.get_multi(multi_lock, auth);
if (!write) {
send_output("!write %li\n", n);
//(this thread has no locks at this point, so 'get_multi' above should
//simply block if another thread is waiting for (or has) a write lock on
//'multi_lock'. a NULL return is therefore an error.)
return NULL;
}
send_output("+write %li (%i)\n", n, write.last_lock_count());
if (*write < 0) return NULL;
*write = n;
nanosleep(&wait, NULL);
write.clear();
send_output("-write %li\n", n);
nanosleep(&wait, NULL);
}
//get a write lock on 'multi_lock'. this blocks until all other locks have
//been released (provided they were obtained with 'get_multi' or
//'get_multi_const' using 'multi_lock). this is mostly a way to appease
//'auth', because it's preventing deadlocks.
//NOTE: the lock will be rejected without blocking if this thread holds a
//lock on another object, because a deadlock could otherwise happen!
send_output("?multi0 %li\n", n);
null_container::proxy multi = multi_lock.get_auth(auth);
if (!multi) {
send_output("!multi0 %li\n", n);
return NULL;
}
send_output("+multi0 %li\n", n);
//NOTE: you can't use 'get_multi' or 'get_multi_const' while 'multi_lock' is
//locked! this is because 'multi_lock' won't allow new read locks while this
//thread holds a write lock on it.
send_output("?multi1 %li\n", n);
protected_int::proxy write1 = my_data.get_auth(auth);
if (!write1) {
send_output("!multi1 %li\n", n);
return NULL;
}
send_output("+multi1 %li\n", n);
if (*write1 < 0) return NULL;
send_output("?multi2 %li\n", n);
protected_int::proxy write2 = my_data2.get_auth(auth);
if (!write2) {
send_output("!multi2 %li\n", n);
return NULL;
}
send_output("+multi2 %li\n", n);
*write1 = *write2 = 100 + n;
write2.clear();
send_output("-multi2 %li\n", n);
write1.clear();
send_output("-multi1 %li\n", n);
//NOTE: since you can't use 'get_multi' above, 'multi_lock' can't track the
//new locks that are made on 'my_data' and 'my_data2'; therefore,
//'multi_lock' must stay locked until the other locks are released.
//(otherwise, 'multi_lock' could give a write lock to another thread while
//'my_data' or 'my_data2' are still locked.)
multi.clear();
send_output("-multi0 %li\n", n);
}
}
<commit_msg>added a note about multiple write locks in the multi-lock example<commit_after>/* This is both a sort of unit test, and a demonstration of how to use deadlock
* prevention.
*
* Suggested compilation command:
* c++ -Wall -pedantic -std=c++11 test.cpp -o test -lpthread
*/
#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <stdarg.h>
#include <pthread.h>
#include "locking-container.hpp"
//use this definition if you want the simple test
#define THREAD_TYPE thread
//use this definition if you want the multi-lock test
//#define THREAD_TYPE thread_multi
//(probably better as arguments, but I'm too lazy right now)
#define THREADS 10
#define TIME 30
//(if you set either of these to 'false', the threads will gradually die off)
#define READ_BLOCK true
#define WRITE_BLOCK true
//the data being protected (initialize the 'int' to 'THREADS')
typedef locking_container <int> protected_int;
static protected_int my_data(THREADS);
//(used by 'thread_multi')
static protected_int my_data2;
static null_container multi_lock;
static void send_output(const char *format, ...);
static void *thread(void *nv);
static void *thread_multi(void *nv);
int main()
{
//create some threads
pthread_t threads[THREADS];
for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
send_output("start %li\n", i);
threads[i] = pthread_t();
if (pthread_create(threads + i, NULL, &THREAD_TYPE, (void*) i) != 0) {
send_output("error: %s\n", strerror(errno));
}
}
//wait for them to do some stuff
sleep(TIME);
//the threads exit when the value goes below 0
{
protected_int::proxy write = my_data.get();
//(no clean way to exit if the container can't be locked)
assert(write);
*write = -1;
} //<-- proxy goes out of scope and unlocks 'my_data' here (you can also 'write.clear()')
for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
send_output("?join %li\n", i);
pthread_join(threads[i], NULL);
send_output("+join %li\n", i);
}
}
//a print function that ensures we have exclusive access to the output
static void send_output(const char *format, ...) {
//protect the output file while we're at it
typedef locking_container <FILE*, w_lock> protected_out;
//(this is local so that it can't be involved in a deadlock)
static protected_out stdout2(stdout);
va_list ap;
va_start(ap, format);
//NOTE: authorization isn't important here because it's not possible for the
//caller to lock another container while it holds a lock on 'stdout2';
//deadlocks aren't an issue with respect to 'stdout2'
protected_out::proxy write = stdout2.get();
if (!write) return;
vfprintf(*write, format, ap);
}
//a simple thread for repeatedly accessing the data
static void *thread(void *nv) {
//(cancelation can be messy...)
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;
//get an authorization object, to prevent deadlocks
//NOTE: for the most part you should be able to use any authorization type
//with any lock type, but the behavior will be the stricter of the two
protected_int::auth_type auth(protected_int::new_auth());
long n = (long) nv, counter = 0;
struct timespec wait = { 0, (10 + n) * 10 * 1000 * 1000 };
nanosleep(&wait, NULL);
//loop through reading and writing forever
while (true) {
//read a bunch of times
for (int i = 0; i < THREADS + n; i++) {
send_output("?read %li\n", n);
protected_int::const_proxy read = my_data.get_auth_const(auth, READ_BLOCK);
if (!read) {
send_output("!read %li\n", n);
return NULL;
}
send_output("+read %li (%i) -> %i\n", n, read.last_lock_count(), *read);
send_output("@read %li %i\n", n, !!my_data.get_auth_const(auth, READ_BLOCK));
if (*read < 0) {
send_output("counter %li %i\n", n, counter);
return NULL;
}
//(sort of like a contest, to see how many times each thread reads its own number)
if (*read == n) ++counter;
nanosleep(&wait, NULL);
read.clear();
send_output("-read %li\n", n);
nanosleep(&wait, NULL);
}
//write once
send_output("?write %li\n", n);
protected_int::proxy write = my_data.get_auth(auth, WRITE_BLOCK);
if (!write) {
send_output("!write %li\n", n);
return NULL;
}
send_output("+write %li (%i)\n", n, write.last_lock_count());
send_output("@write %li %i\n", n, !!my_data.get_auth(auth, WRITE_BLOCK));
if (*write < 0) {
send_output("counter %li %i\n", n, counter);
return NULL;
}
*write = n;
nanosleep(&wait, NULL);
write.clear();
send_output("-write %li\n", n);
nanosleep(&wait, NULL);
}
}
//a more complicated thread that requires deadlock prevention, but multiple write locks at once
static void *thread_multi(void *nv) {
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;
protected_int::auth_type auth(protected_int::new_auth());
long n = (long) nv;
struct timespec wait = { 0, (10 + n) * 1 * 1000 * 1000 };
nanosleep(&wait, NULL);
while (true) {
for (int i = 0; i < THREADS + n; i++) {
send_output("?read0 %li\n", n);
protected_int::const_proxy read0 = my_data.get_multi_const(multi_lock, auth);
if (!read0) {
send_output("!read0 %li\n", n);
return NULL;
}
send_output("+read0 %li (%i) -> %i\n", n, read0.last_lock_count(), *read0);
if (*read0 < 0) return NULL;
nanosleep(&wait, NULL);
send_output("?read1 %li\n", n);
protected_int::const_proxy read1 = my_data2.get_multi_const(multi_lock, auth);
if (!read1) {
send_output("!read1 %li\n", n);
//NOTE: due to deadlock prevention, 'auth' will reject a lock if another
//thread is waiting for a write lock for 'multi_lock' because this
//thread already holds a read lock (on 'my_data'). (this could easily
//lead to a deadlock if 'get_multi_const' above blocked.) this isn't a
//catastrophic error, so we just break out of this loop.
break;
}
send_output("+read1 %li (%i) -> %i\n", n, read1.last_lock_count(), *read1);
if (*read1 < 0) return NULL;
nanosleep(&wait, NULL);
read1.clear();
send_output("-read1 %li\n", n);
read0.clear();
send_output("-read0 %li\n", n);
nanosleep(&wait, NULL);
send_output("?write %li\n", n);
protected_int::proxy write = my_data.get_multi(multi_lock, auth);
if (!write) {
send_output("!write %li\n", n);
//(this thread has no locks at this point, so 'get_multi' above should
//simply block if another thread is waiting for (or has) a write lock on
//'multi_lock'. a NULL return is therefore an error.)
return NULL;
}
send_output("+write %li (%i)\n", n, write.last_lock_count());
if (*write < 0) return NULL;
*write = n;
nanosleep(&wait, NULL);
write.clear();
send_output("-write %li\n", n);
nanosleep(&wait, NULL);
}
//get a write lock on 'multi_lock'. this blocks until all other locks have
//been released (provided they were obtained with 'get_multi' or
//'get_multi_const' using 'multi_lock). this is mostly a way to appease
//'auth', because it's preventing deadlocks.
//NOTE: the lock will be rejected without blocking if this thread holds a
//lock on another object, because a deadlock could otherwise happen!
send_output("?multi0 %li\n", n);
null_container::proxy multi = multi_lock.get_auth(auth);
if (!multi) {
send_output("!multi0 %li\n", n);
return NULL;
}
send_output("+multi0 %li\n", n);
//NOTE: you can't use 'get_multi' or 'get_multi_const' while 'multi_lock' is
//locked! this is because 'multi_lock' won't allow new read locks while this
//thread holds a write lock on it.
send_output("?multi1 %li\n", n);
protected_int::proxy write1 = my_data.get_auth(auth);
if (!write1) {
send_output("!multi1 %li\n", n);
return NULL;
}
send_output("+multi1 %li\n", n);
if (*write1 < 0) return NULL;
//NOTE: this second write lock is only possible because this thread's write
//lock on 'multi_lock' ensures that nothing else currently holds a lock on
//'my_data2'. in fact, that's the only purpose of using 'multi_lock'!
send_output("?multi2 %li\n", n);
protected_int::proxy write2 = my_data2.get_auth(auth);
if (!write2) {
send_output("!multi2 %li\n", n);
return NULL;
}
send_output("+multi2 %li\n", n);
*write1 = *write2 = 100 + n;
write2.clear();
send_output("-multi2 %li\n", n);
write1.clear();
send_output("-multi1 %li\n", n);
//NOTE: since you can't use 'get_multi' above, 'multi_lock' can't track the
//new locks that are made on 'my_data' and 'my_data2'; therefore,
//'multi_lock' must stay locked until the other locks are released.
//(otherwise, 'multi_lock' could give a write lock to another thread while
//'my_data' or 'my_data2' are still locked.)
multi.clear();
send_output("-multi0 %li\n", n);
}
}
<|endoftext|> |
<commit_before>// -*- mode: c++ -*-
/* Copyright (c) 2013, Eddie Kohler
*
* 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, subject to the conditions
* listed in the Tamer LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Tamer LICENSE file; the license in that file is
* legally binding.
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <tamer/tamer.hh>
#include <tamer/fd.hh>
#include <tamer/bufferedio.hh>
using namespace tamer;
tamed void child(struct sockaddr_in* saddr, socklen_t saddr_len) {
tvars { tamer::fd cfd; int ret; tamer::buffer buf; size_t nwritten;
int write_rounds = 0; int wret = 0; std::string str; }
cfd = tamer::fd::socket(AF_INET, SOCK_STREAM, 0);
twait { cfd.connect((struct sockaddr*) saddr, saddr_len, make_event(ret)); }
while (cfd) {
if (wret == 0) {
twait { cfd.write("Hello\n", 6, nwritten, make_event(wret)); }
if (wret == 0 && nwritten == 6) {
++write_rounds;
if (write_rounds <= 6)
printf("W 0: Hello\n");
}
}
twait { buf.take_until(cfd, '\n', 1024, str, make_event(ret)); }
if (ret != 0) {
printf("W error %s after %d\n", strerror(-ret), write_rounds);
break;
} else if (str.length())
printf("R %d: %s", ret, str.c_str());
}
cfd.close();
}
tamed void parent(tamer::fd& listenfd) {
tvars { tamer::fd cfd; int ret; tamer::buffer buf;
int n = 0; std::string str; }
twait { listenfd.accept(make_event(cfd)); }
while (cfd && n < 6) {
++n;
twait { buf.take_until(cfd, '\n', 1024, str, make_event(ret)); }
assert(ret == 0);
str = "Ret " + str;
twait { cfd.write(str, make_event()); }
}
cfd.shutdown(SHUT_RD);
while (cfd && n < 12) {
++n;
twait { cfd.write("Heh\n", 4, make_event(ret)); }
assert(ret == 0);
}
cfd.close();
listenfd.close();
}
int main(int, char *[]) {
tamer::initialize();
signal(SIGPIPE, SIG_IGN);
tamer::fd listenfd = tamer::tcp_listen(0);
assert(listenfd);
struct sockaddr_in saddr;
socklen_t saddr_len = sizeof(saddr);
int r = getsockname(listenfd.value(), (struct sockaddr*) &saddr, &saddr_len);
assert(r == 0);
pid_t p = fork();
if (p != 0) {
listenfd.close();
child(&saddr, saddr_len);
} else
parent(listenfd);
tamer::loop();
tamer::cleanup();
if (p != 0)
printf("Done\n");
}
<commit_msg>Report write-time error in test.<commit_after>// -*- mode: c++ -*-
/* Copyright (c) 2013, Eddie Kohler
*
* 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, subject to the conditions
* listed in the Tamer LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Tamer LICENSE file; the license in that file is
* legally binding.
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <tamer/tamer.hh>
#include <tamer/fd.hh>
#include <tamer/bufferedio.hh>
using namespace tamer;
tamed void child(struct sockaddr_in* saddr, socklen_t saddr_len) {
tvars { tamer::fd cfd; int ret; tamer::buffer buf; size_t nwritten;
int write_rounds = 0; int wret = 0; std::string str; }
cfd = tamer::fd::socket(AF_INET, SOCK_STREAM, 0);
twait { cfd.connect((struct sockaddr*) saddr, saddr_len, make_event(ret)); }
while (cfd) {
if (wret == 0) {
twait { cfd.write("Hello\n", 6, nwritten, make_event(wret)); }
if (wret == 0 && nwritten == 6) {
++write_rounds;
if (write_rounds <= 6)
printf("W 0: Hello\n");
} else if (wret == 0)
wret = -ECANCELED;
}
twait { buf.take_until(cfd, '\n', 1024, str, make_event(ret)); }
if (ret != 0) {
printf("W error %s after %d\n", strerror(-wret), write_rounds);
break;
} else if (str.length())
printf("R %d: %s", ret, str.c_str());
}
cfd.close();
}
tamed void parent(tamer::fd& listenfd) {
tvars { tamer::fd cfd; int ret; tamer::buffer buf;
int n = 0; std::string str; }
twait { listenfd.accept(make_event(cfd)); }
while (cfd && n < 6) {
++n;
twait { buf.take_until(cfd, '\n', 1024, str, make_event(ret)); }
assert(ret == 0);
str = "Ret " + str;
twait { cfd.write(str, make_event()); }
}
cfd.shutdown(SHUT_RD);
while (cfd && n < 12) {
++n;
twait { cfd.write("Heh\n", 4, make_event(ret)); }
assert(ret == 0);
}
cfd.close();
listenfd.close();
}
int main(int, char *[]) {
tamer::initialize();
signal(SIGPIPE, SIG_IGN);
tamer::fd listenfd = tamer::tcp_listen(0);
assert(listenfd);
struct sockaddr_in saddr;
socklen_t saddr_len = sizeof(saddr);
int r = getsockname(listenfd.value(), (struct sockaddr*) &saddr, &saddr_len);
assert(r == 0);
pid_t p = fork();
if (p != 0) {
listenfd.close();
child(&saddr, saddr_len);
} else
parent(listenfd);
tamer::loop();
tamer::cleanup();
if (p != 0)
printf("Done\n");
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.