text
stringlengths 54
60.6k
|
|---|
<commit_before>efb0840c-2e4e-11e5-8d64-28cfe91dbc4b<commit_msg>efb7f630-2e4e-11e5-bbb4-28cfe91dbc4b<commit_after>efb7f630-2e4e-11e5-bbb4-28cfe91dbc4b<|endoftext|>
|
<commit_before>8431fc6c-2d15-11e5-af21-0401358ea401<commit_msg>8431fc6d-2d15-11e5-af21-0401358ea401<commit_after>8431fc6d-2d15-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>80df6c63-2d3d-11e5-971b-c82a142b6f9b<commit_msg>81705e21-2d3d-11e5-9be6-c82a142b6f9b<commit_after>81705e21-2d3d-11e5-9be6-c82a142b6f9b<|endoftext|>
|
<commit_before>2fe096ba-ad5b-11e7-9e61-ac87a332f658<commit_msg>roselyn added more bugs<commit_after>30470f3d-ad5b-11e7-b65e-ac87a332f658<|endoftext|>
|
<commit_before>#include <omp.h>
#include "evaluate_circuit.h"
// Input: ./qflex.x I J K fidelity circuit_filename ordering_filename \
// grid_filename [initial_conf] [final_conf]
//
// Example:
// $ ./qflex.x 11 12 2 0.005 ./circuits/ben_11_16_0.txt \
// ./ordering/bristlecone_48.txt ./grid/bristlecone_48.txt
int main(int argc, char** argv) {
// Reading input.
if (argc < 8) throw std::logic_error("ERROR: Not enough arguments.");
int current_arg = 1;
qflex::QflexInput input;
input.I = atoi(argv[current_arg++]);
input.J = atoi(argv[current_arg++]);
input.K = atoi(argv[current_arg++]);
input.fidelity = atof(argv[current_arg++]);
// Creating streams for input files.
std::string circuit_filename = std::string(argv[current_arg++]);
auto circuit_data = std::ifstream(circuit_filename);
if (!circuit_data.good()) {
std::cout << "Cannot open circuit data file: " << circuit_filename
<< std::endl;
assert(circuit_data.good());
}
input.circuit_data = &circuit_data;
std::string ordering_filename = std::string(argv[current_arg++]);
auto ordering_data = std::ifstream(ordering_filename);
if (!ordering_data.good()) {
std::cout << "Cannot open ordering data file: " << ordering_filename
<< std::endl;
assert(ordering_data.good());
}
input.ordering_data = &ordering_data;
std::string grid_filename = std::string(argv[current_arg++]);
auto grid_data = std::ifstream(grid_filename);
if (!grid_data.good()) {
std::cout << "Cannot open grid data file: " << grid_filename << std::endl;
assert(grid_data.good());
}
input.grid_data = &grid_data;
// Setting initial and final circuit states.
if (argc > current_arg) {
input.initial_state = std::string(argv[current_arg++]);
}
if (argc > current_arg) {
input.final_state_A = std::string(argv[current_arg++]);
}
// Evaluating circuit.
std::vector<std::pair<std::string, std::complex<double>>> amplitudes =
qflex::EvaluateCircuit(&input);
// Printing output.
for (int c = 0; c < amplitudes.size(); ++c) {
const auto& state = amplitudes[c].first;
const auto& amplitude = amplitudes[c].second;
std::cout << input.initial_state << " --> " << state << ": "
<< std::real(amplitude) << " " << std::imag(amplitude)
<< std::endl;
}
return 0;
}
<commit_msg>Changed example in main.cpp<commit_after>#include <omp.h>
#include "evaluate_circuit.h"
// Input: ./qflex.x I J K fidelity circuit_filename ordering_filename \
// grid_filename [initial_conf] [final_conf]
//
// Example:
// $ ./qflex.x 11 12 2 0.005 ./circuits/bristlecone_48_1-40-1_0.txt \
// ./ordering/bristlecone_48.txt ./grid/bristlecone_48.txt
int main(int argc, char** argv) {
// Reading input.
if (argc < 8) throw std::logic_error("ERROR: Not enough arguments.");
int current_arg = 1;
qflex::QflexInput input;
input.I = atoi(argv[current_arg++]);
input.J = atoi(argv[current_arg++]);
input.K = atoi(argv[current_arg++]);
input.fidelity = atof(argv[current_arg++]);
// Creating streams for input files.
std::string circuit_filename = std::string(argv[current_arg++]);
auto circuit_data = std::ifstream(circuit_filename);
if (!circuit_data.good()) {
std::cout << "Cannot open circuit data file: " << circuit_filename
<< std::endl;
assert(circuit_data.good());
}
input.circuit_data = &circuit_data;
std::string ordering_filename = std::string(argv[current_arg++]);
auto ordering_data = std::ifstream(ordering_filename);
if (!ordering_data.good()) {
std::cout << "Cannot open ordering data file: " << ordering_filename
<< std::endl;
assert(ordering_data.good());
}
input.ordering_data = &ordering_data;
std::string grid_filename = std::string(argv[current_arg++]);
auto grid_data = std::ifstream(grid_filename);
if (!grid_data.good()) {
std::cout << "Cannot open grid data file: " << grid_filename << std::endl;
assert(grid_data.good());
}
input.grid_data = &grid_data;
// Setting initial and final circuit states.
if (argc > current_arg) {
input.initial_state = std::string(argv[current_arg++]);
}
if (argc > current_arg) {
input.final_state_A = std::string(argv[current_arg++]);
}
// Evaluating circuit.
std::vector<std::pair<std::string, std::complex<double>>> amplitudes =
qflex::EvaluateCircuit(&input);
// Printing output.
for (int c = 0; c < amplitudes.size(); ++c) {
const auto& state = amplitudes[c].first;
const auto& amplitude = amplitudes[c].second;
std::cout << input.initial_state << " --> " << state << ": "
<< std::real(amplitude) << " " << std::imag(amplitude)
<< std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>9f294770-327f-11e5-ba04-9cf387a8033e<commit_msg>9f2f418c-327f-11e5-86b8-9cf387a8033e<commit_after>9f2f418c-327f-11e5-86b8-9cf387a8033e<|endoftext|>
|
<commit_before>818f8b0f-2e4f-11e5-a9ac-28cfe91dbc4b<commit_msg>81973fd4-2e4f-11e5-bf4c-28cfe91dbc4b<commit_after>81973fd4-2e4f-11e5-bf4c-28cfe91dbc4b<|endoftext|>
|
<commit_before>b56e205c-2e4f-11e5-8218-28cfe91dbc4b<commit_msg>b58b641e-2e4f-11e5-9413-28cfe91dbc4b<commit_after>b58b641e-2e4f-11e5-9413-28cfe91dbc4b<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <list>
#include "opencv.hpp"
using namespace cv;
using namespace std;
static const double PI = 3.1415926536;
struct Options
{
int threshold;
};
struct Star
{
double x, y;
double r;
Star(double x, double y, double r)
{
this->x = x;
this->y = y;
this->r = r;
}
};
struct Blob
{
double x, y;
double S;
};
Blob operator+(const Blob & l, const Blob & r)
{
Blob q;
q.S = l.S + r.S;
q.x = (l.S*l.x + r.S*r.x) / q.S;
q.y = (l.S*l.y + r.S*r.y) / q.S;
}
Blob & operator+=(Blob & blob, const Blob & x)
{
double S = blob.S + x.S;
blob.x = (blob.S*blob.x + x.S*x.x) / S;
blob.y = (blob.S*blob.y + x.S*x.y) / S;
}
bool operator<(const Star & l, const Star & r)
{
if (l.r < r.r)
return true;
if (l.r > r.r)
return false;
return (l.x < r.x);
}
typedef vector<Star> Stars;
typedef vector<Blob> Blobs;
void die(const string & msg)
{
cerr << "Error: " << msg << endl;
exit(1);
}
inline double sqr(double x)
{
return x*x;
}
inline double min3(double x, double y, double z)
{
return (x < y) ? ((x < z) ? x : z) : ((y < z) ? y : z);
}
void getTransform(Stars & xs, Stars & ys)
{
}
struct ScanItem
{
Blob blob;
int l, r;
ScanItem(int _l, int _r, const Blob & _b)
: l(_l), r(_r), blob(_b)
{}
};
void findBlobs(const Mat & mat, Blobs & blobs)
{
/*
namedWindow("foo");
imshow("foo", mat);
waitKey(1000);
*/
cout << "depth: " << mat.depth() << ", type: " << mat.type() << ", chans: " << mat.channels() << endl;
list<ScanItem> scan, newscan;
for (int y = 0; y < mat.rows; ++y)
{
const uint8_t * row = mat.ptr<uint8_t>(y);
list<ScanItem>::iterator it = scan.begin();
int l = 0;
for (int x = 0; x < mat.cols; ++x)
{
// skip blanks
while (it != scan.end() && it->r < x)
{
blobs.push_back(it->blob);
++it;
}
// find the end of the white segment
while (x < mat.cols && row[x])
++x;
// if white segment found
if (row[l])
{
cout << "rowscan at " << l << ".." << x << "," << y << endl;
Blob cur = {(x+l-1)/2.0, y, x-l};
while (it != scan.end() && it->l < x)
{
cur += it->blob;
++it;
}
newscan.push_back(ScanItem(l,x-1,cur));
}
l = ++x;
}
scan = newscan;
}
for (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it)
{
blobs.push_back(it->blob);
}
}
void getStars(const vector<string> & fn, vector<Stars *> & stars, const Options & opt)
{
stars.clear();
for (vector<string>::const_iterator it = fn.begin(); it != fn.end(); ++it)
{
cout << " * " << *it << ": ";
// load the image
Mat image = imread(*it, CV_LOAD_IMAGE_GRAYSCALE);
Mat srcimg;
resize(image, srcimg, Size(0,0), 0.25, 0.25);
threshold(srcimg, image, opt.threshold, 255, THRESH_BINARY);
// find the blobs
Blobs blobs;
findBlobs(image, blobs);
// traverse the blobs
Stars * st = new vector<Star>();
for (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it)
{
st->push_back(Star(it->x, it->y, sqrt(it->S / PI)));
}
cout << st->size() << " stars" << endl;
stars.push_back(st);
}
}
int main(int argc, char ** argv)
{
char ** end = argv + argc;
++argv; // skip the name of the executable
// some default options
Options opt;
opt.threshold = 128;
// get the options
while (argv < end)
{
// end of options
if (**argv != '-')
break;
string opt = *argv++;
// no options will follow
if (opt == "--")
break;
die("unknown option " + opt);
}
// get the list of images
vector<string> imgNames;
while (argv < end)
imgNames.push_back(*argv++);
// perform some sanity checks
if (imgNames.size() < 2)
die("no point in aligning less than two images");
// find stars on each image
cout << "Finding stars..." << endl;
vector<Stars *> stars;
getStars(imgNames, stars, opt); // allocates stars
// sort each vector by star size
for (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)
{
sort((*it)->rbegin(), (*it)->rend());
}
// align the stars
getTransform(*stars[0], *stars[1]);
// free the memory
for (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)
{
delete *it;
}
return 0;
}
<commit_msg>Blob += fixed.<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <list>
#include "opencv.hpp"
using namespace cv;
using namespace std;
static const double PI = 3.1415926536;
struct Options
{
int threshold;
};
struct Star
{
double x, y;
double r;
Star(double x, double y, double r)
{
this->x = x;
this->y = y;
this->r = r;
}
};
struct Blob
{
double x, y;
double S;
};
Blob operator+(const Blob & l, const Blob & r)
{
Blob q;
q.S = l.S + r.S;
q.x = (l.S*l.x + r.S*r.x) / q.S;
q.y = (l.S*l.y + r.S*r.y) / q.S;
}
Blob & operator+=(Blob & blob, const Blob & x)
{
double S = blob.S + x.S;
blob.x = (blob.S*blob.x + x.S*x.x) / S;
blob.y = (blob.S*blob.y + x.S*x.y) / S;
blob.S = S;
}
bool operator<(const Star & l, const Star & r)
{
if (l.r < r.r)
return true;
if (l.r > r.r)
return false;
return (l.x < r.x);
}
typedef vector<Star> Stars;
typedef vector<Blob> Blobs;
void die(const string & msg)
{
cerr << "Error: " << msg << endl;
exit(1);
}
inline double sqr(double x)
{
return x*x;
}
inline double min3(double x, double y, double z)
{
return (x < y) ? ((x < z) ? x : z) : ((y < z) ? y : z);
}
void getTransform(Stars & xs, Stars & ys)
{
}
struct ScanItem
{
Blob blob;
int l, r;
ScanItem(int _l, int _r, const Blob & _b)
: l(_l), r(_r), blob(_b)
{}
};
void findBlobs(const Mat & mat, Blobs & blobs)
{
/*
namedWindow("foo");
imshow("foo", mat);
waitKey(1000);
*/
cout << "depth: " << mat.depth() << ", type: " << mat.type() << ", chans: " << mat.channels() << endl;
list<ScanItem> scan, newscan;
for (int y = 0; y < mat.rows; ++y)
{
const uint8_t * row = mat.ptr<uint8_t>(y);
list<ScanItem>::iterator it = scan.begin();
int l = 0;
for (int x = 0; x < mat.cols; ++x)
{
// skip blanks
while (it != scan.end() && it->r < x)
{
blobs.push_back(it->blob);
++it;
}
// find the end of the white segment
while (x < mat.cols && row[x])
++x;
// if white segment found
if (row[l])
{
cout << "rowscan at " << l << ".." << x << "," << y << endl;
Blob cur = {(x+l-1)/2.0, y, x-l};
while (it != scan.end() && it->l < x)
{
cur += it->blob;
++it;
}
newscan.push_back(ScanItem(l,x-1,cur));
}
l = ++x;
}
scan = newscan;
}
for (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it)
{
blobs.push_back(it->blob);
}
}
void getStars(const vector<string> & fn, vector<Stars *> & stars, const Options & opt)
{
stars.clear();
for (vector<string>::const_iterator it = fn.begin(); it != fn.end(); ++it)
{
cout << " * " << *it << ": ";
// load the image
Mat image = imread(*it, CV_LOAD_IMAGE_GRAYSCALE);
Mat srcimg;
resize(image, srcimg, Size(0,0), 0.25, 0.25);
threshold(srcimg, image, opt.threshold, 255, THRESH_BINARY);
// find the blobs
Blobs blobs;
findBlobs(image, blobs);
// traverse the blobs
Stars * st = new vector<Star>();
for (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it)
{
st->push_back(Star(it->x, it->y, sqrt(it->S / PI)));
}
cout << st->size() << " stars" << endl;
stars.push_back(st);
}
}
int main(int argc, char ** argv)
{
char ** end = argv + argc;
++argv; // skip the name of the executable
// some default options
Options opt;
opt.threshold = 128;
// get the options
while (argv < end)
{
// end of options
if (**argv != '-')
break;
string opt = *argv++;
// no options will follow
if (opt == "--")
break;
die("unknown option " + opt);
}
// get the list of images
vector<string> imgNames;
while (argv < end)
imgNames.push_back(*argv++);
// perform some sanity checks
if (imgNames.size() < 2)
die("no point in aligning less than two images");
// find stars on each image
cout << "Finding stars..." << endl;
vector<Stars *> stars;
getStars(imgNames, stars, opt); // allocates stars
// sort each vector by star size
for (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)
{
sort((*it)->rbegin(), (*it)->rend());
}
// align the stars
getTransform(*stars[0], *stars[1]);
// free the memory
for (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)
{
delete *it;
}
return 0;
}
<|endoftext|>
|
<commit_before>d236bba3-2d3c-11e5-840d-c82a142b6f9b<commit_msg>d299b47a-2d3c-11e5-8d2e-c82a142b6f9b<commit_after>d299b47a-2d3c-11e5-8d2e-c82a142b6f9b<|endoftext|>
|
<commit_before>53703a3d-2e4f-11e5-a2cd-28cfe91dbc4b<commit_msg>5376fdcc-2e4f-11e5-a6fc-28cfe91dbc4b<commit_after>5376fdcc-2e4f-11e5-a6fc-28cfe91dbc4b<|endoftext|>
|
<commit_before>3403efac-5216-11e5-ba26-6c40088e03e4<commit_msg>340a7368-5216-11e5-be59-6c40088e03e4<commit_after>340a7368-5216-11e5-be59-6c40088e03e4<|endoftext|>
|
<commit_before>ba90a6f4-35ca-11e5-8876-6c40088e03e4<commit_msg>ba97432e-35ca-11e5-9850-6c40088e03e4<commit_after>ba97432e-35ca-11e5-9850-6c40088e03e4<|endoftext|>
|
<commit_before>4ba0bec6-5216-11e5-97f2-6c40088e03e4<commit_msg>4ba85026-5216-11e5-ad8c-6c40088e03e4<commit_after>4ba85026-5216-11e5-ad8c-6c40088e03e4<|endoftext|>
|
<commit_before>62ccb492-5216-11e5-934a-6c40088e03e4<commit_msg>62d3480a-5216-11e5-951c-6c40088e03e4<commit_after>62d3480a-5216-11e5-951c-6c40088e03e4<|endoftext|>
|
<commit_before>c3a8f034-35ca-11e5-91f5-6c40088e03e4<commit_msg>c3af5e24-35ca-11e5-aa61-6c40088e03e4<commit_after>c3af5e24-35ca-11e5-aa61-6c40088e03e4<|endoftext|>
|
<commit_before>b8244cc2-35ca-11e5-92a9-6c40088e03e4<commit_msg>b82b1fd4-35ca-11e5-aaad-6c40088e03e4<commit_after>b82b1fd4-35ca-11e5-aaad-6c40088e03e4<|endoftext|>
|
<commit_before>b3c202a8-327f-11e5-972e-9cf387a8033e<commit_msg>b3c7dc78-327f-11e5-84fb-9cf387a8033e<commit_after>b3c7dc78-327f-11e5-84fb-9cf387a8033e<|endoftext|>
|
<commit_before>e8af0307-327f-11e5-8f3b-9cf387a8033e<commit_msg>e8b4e4e3-327f-11e5-9d79-9cf387a8033e<commit_after>e8b4e4e3-327f-11e5-9d79-9cf387a8033e<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <clocale>
#include <iomanip>
#include <locale>
#include <codecvt>
#include <iomanip>
#pragma execution_character_set("utf-8")
int main(int argc, char *argv[])
{
std::setlocale(LC_ALL, "Japanese");
for (int i = 1; i >= 0 ; ++i)
{
if (argv[i] == nullptr) break;
std::string fileName = argv[i];
std::basic_ofstream<char32_t> ofs;
ofs.imbue(std::locale(std::locale(""), new std::codecvt_utf8<char32_t>));
std::basic_ifstream<char32_t> ifs;
ifs.imbue(std::locale(std::locale(""), new std::codecvt_utf8<char32_t>));
std::string outFile = argv[i];
outFile += ".pre";
ofs.open( "buff" , std::ios::out);
ifs.open( argv[i] , std::ios::in);
char32_t wc;
//Bom削除
if (ifs.get() < 0x0080 )
{
ifs.seekg(0);
}
bool StringMode = false;
while ( !ifs.eof() )
{
wc = ifs.get();
if (ifs.eof()) break;
if (wc < 0x0080)
{
if (wc == 0x0022)
{
//文字リテラル中はそのままにする
if (StringMode) StringMode = false;
else StringMode = true;
}
ofs.put(wc);
}
else if (wc < 0xFFFF)//3バイト
{
if (StringMode)
{
ofs.put(wc);
}
else {
ofs.put('U');
ofs.put('C');
ofs.put('N');
int n = wc / 16 / 16 / 16;
if (n < 10) ofs.put(0x30 + n);
else ofs.put(0x41 + n - 10);
n = wc / 16 / 16 % 16;
if (n < 10) ofs.put(0x30 + n);
else ofs.put(0x41 + n - 10);
n = wc / 16 % 16;
if (n < 10) ofs.put(0x30 + n);
else ofs.put(0x41 + n - 10);
n = wc % 16;
if (n < 10) ofs.put(0x30 + n);
else ofs.put(0x41 + n - 10);
}
}
}
ofs.close();
ifs.close();
//WindowsAPI
rename( fileName.c_str() , outFile.c_str() );
rename( "buff", fileName.c_str());
}
return 0;
}<commit_msg>変更前のファイルの扱いを変更.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <clocale>
#include <iomanip>
#include <locale>
#include <codecvt>
#include <iomanip>
#include <Windows.h>
#pragma execution_character_set("utf-8")
int main(int argc, char *argv[])
{
//Windows専用
CreateDirectoryA("backup",NULL);
for (int i = 1; i >= 0 ; ++i)
{
if (argv[i] == nullptr) break;
std::string fileName = argv[i];
std::basic_ofstream<char32_t> ofs;
ofs.imbue(std::locale(std::locale(""), new std::codecvt_utf8<char32_t>));
std::basic_ifstream<char32_t> ifs;
ifs.imbue(std::locale(std::locale(""), new std::codecvt_utf8<char32_t>));
std::string outFile = argv[i];
int num = outFile.find_last_of('\\');
outFile.insert(num, "\\backup");
ofs.open( "buff" , std::ios::out);
ifs.open( argv[i] , std::ios::in);
char32_t wc;
//Bom削除
if (ifs.get() < 0x0080 )
{
ifs.seekg(0);
}
bool StringMode = false;
while ( !ifs.eof() )
{
wc = ifs.get();
if (ifs.eof()) break;
if (wc < 0x0080)
{
if (wc == 0x0022)
{
//文字リテラル中はそのままにする
if (StringMode) StringMode = false;
else StringMode = true;
}
ofs.put(wc);
}
else if (wc < 0xFFFF)//3バイト
{
if (StringMode)
{
ofs.put(wc);
}
else {
ofs.put('U');
ofs.put('C');
ofs.put('N');
int n = wc / 16 / 16 / 16;
if (n < 10) ofs.put(0x30 + n);
else ofs.put(0x41 + n - 10);
n = wc / 16 / 16 % 16;
if (n < 10) ofs.put(0x30 + n);
else ofs.put(0x41 + n - 10);
n = wc / 16 % 16;
if (n < 10) ofs.put(0x30 + n);
else ofs.put(0x41 + n - 10);
n = wc % 16;
if (n < 10) ofs.put(0x30 + n);
else ofs.put(0x41 + n - 10);
}
}
}
ofs.close();
ifs.close();
//環境依存?
//元ファイルをbackupフォルダに移動
rename( fileName.c_str() , outFile.c_str() );
rename("buff", fileName.c_str());
}
return 0;
}<|endoftext|>
|
<commit_before>afa3c4f5-ad5a-11e7-845a-ac87a332f658<commit_msg>Finished?<commit_after>b0199f1e-ad5a-11e7-8f5e-ac87a332f658<|endoftext|>
|
<commit_before>7602280c-2d53-11e5-baeb-247703a38240<commit_msg>7602a8c2-2d53-11e5-baeb-247703a38240<commit_after>7602a8c2-2d53-11e5-baeb-247703a38240<|endoftext|>
|
<commit_before>83000d99-2d15-11e5-af21-0401358ea401<commit_msg>83000d9a-2d15-11e5-af21-0401358ea401<commit_after>83000d9a-2d15-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>ca69b8de-327f-11e5-af9c-9cf387a8033e<commit_msg>ca7440cc-327f-11e5-bf80-9cf387a8033e<commit_after>ca7440cc-327f-11e5-bf80-9cf387a8033e<|endoftext|>
|
<commit_before>d8acfb6c-35ca-11e5-a5ac-6c40088e03e4<commit_msg>Final commit :sunglasses:<commit_after>#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>f5650987-2e4e-11e5-818c-28cfe91dbc4b<commit_msg>f56f64ca-2e4e-11e5-a515-28cfe91dbc4b<commit_after>f56f64ca-2e4e-11e5-a515-28cfe91dbc4b<|endoftext|>
|
<commit_before>c08d152e-ad5c-11e7-a03a-ac87a332f658<commit_msg>lets try again<commit_after>c123f968-ad5c-11e7-a022-ac87a332f658<|endoftext|>
|
<commit_before>5bf67450-2d16-11e5-af21-0401358ea401<commit_msg>5bf67451-2d16-11e5-af21-0401358ea401<commit_after>5bf67451-2d16-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>#include <iostream>
#include "matrix.hpp"
int main() {
std::vector<double> vector1{2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8};
std::vector<double> vector2{1, 1, -1, 3};
matrix<double, 4, 4> m1{2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8};
nvector<double, 4> b{1, 1, -1, 3};
std::cout << "Information about A:" << std::endl;
auto data = m1.data();
for (auto i = data.begin(); i != data.end(); ++i) {
std::cout << *i << " ";
}
std::cout << std::endl;
std::cout << "Information about b:" << std::endl;
std::cout << "b has " << b.size() << " rows" << std::endl;
for (auto i = b.begin(); i != b.end(); ++i) {
std::cout << *i << " ";
}
std::cout << std::endl;
auto x = gaussian_no_pivoting(m1, b);
auto y = gaussian_partial_pivoting(m1, b);
std::cout << "x is: (" << x[0] << ", " << x[1] << ", " << x[2] << ", " << x[3] << ")" << std::endl;
std::cout << "y is: (" << y[0] << ", " << y[1] << ", " << y[2] << ", " << y[3] << ")" << std::endl;
}<commit_msg>Had to change the template classes because we need to instantiate matrices of different sizes at runtime (random matrices).<commit_after>#include <iostream>
#include "matrix.hpp"
int main() {
std::vector<double> vector1{2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8};
std::vector<double> vector2{1, 1, -1, 3};
matrix<double> m1(4, 4, {2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8});
nvector<double> b(4, {1, 1, -1, 3});
std::cout << "Information about A:" << std::endl;
auto data = m1.data();
for (auto i = data.begin(); i != data.end(); ++i) {
std::cout << *i << " ";
}
std::cout << std::endl;
std::cout << "Information about b:" << std::endl;
std::cout << "b has " << b.size() << " rows" << std::endl;
for (auto i = b.begin(); i != b.end(); ++i) {
std::cout << *i << " ";
}
std::cout << std::endl;
auto x = gaussian_no_pivoting(m1, b);
auto y = gaussian_partial_pivoting(m1, b);
std::cout << "x is: (" << x[0] << ", " << x[1] << ", " << x[2] << ", " << x[3] << ")" << std::endl;
std::cout << "y is: (" << y[0] << ", " << y[1] << ", " << y[2] << ", " << y[3] << ")" << std::endl;
}<|endoftext|>
|
<commit_before>83000e4f-2d15-11e5-af21-0401358ea401<commit_msg>83000e50-2d15-11e5-af21-0401358ea401<commit_after>83000e50-2d15-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>8ef73a50-35ca-11e5-b58f-6c40088e03e4<commit_msg>8efe96cc-35ca-11e5-9008-6c40088e03e4<commit_after>8efe96cc-35ca-11e5-9008-6c40088e03e4<|endoftext|>
|
<commit_before>b49ad4ae-2e4f-11e5-bc6a-28cfe91dbc4b<commit_msg>b4a13bfa-2e4f-11e5-a890-28cfe91dbc4b<commit_after>b4a13bfa-2e4f-11e5-a890-28cfe91dbc4b<|endoftext|>
|
<commit_before>b731a3b6-35ca-11e5-8a9b-6c40088e03e4<commit_msg>b7384476-35ca-11e5-8f4a-6c40088e03e4<commit_after>b7384476-35ca-11e5-8f4a-6c40088e03e4<|endoftext|>
|
<commit_before>#include <iostream>
int main() {
std::cout << "Hello, world. " << std::endl;
return 0;
}
<commit_msg> * Changed to exclamation mark<commit_after>#include <iostream>
int main() {
std::cout << "Hello, world! " << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>8e9fac00-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac01-2d14-11e5-af21-0401358ea401<commit_after>8e9fac01-2d14-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>9771c921-2747-11e6-8c5a-e0f84713e7b8<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>97827f7d-2747-11e6-8556-e0f84713e7b8<|endoftext|>
|
<commit_before>ee83b9e8-327f-11e5-8456-9cf387a8033e<commit_msg>ee8a2d5c-327f-11e5-913e-9cf387a8033e<commit_after>ee8a2d5c-327f-11e5-913e-9cf387a8033e<|endoftext|>
|
<commit_before>3de69d80-5216-11e5-bad7-6c40088e03e4<commit_msg>3dee7f14-5216-11e5-bee7-6c40088e03e4<commit_after>3dee7f14-5216-11e5-bee7-6c40088e03e4<|endoftext|>
|
<commit_before>3a9bc8f0-2e4f-11e5-b4ad-28cfe91dbc4b<commit_msg>3aa2a1a3-2e4f-11e5-964e-28cfe91dbc4b<commit_after>3aa2a1a3-2e4f-11e5-964e-28cfe91dbc4b<|endoftext|>
|
<commit_before>0ca27d22-585b-11e5-bff2-6c40088e03e4<commit_msg>0ca9fc1c-585b-11e5-8bd6-6c40088e03e4<commit_after>0ca9fc1c-585b-11e5-8bd6-6c40088e03e4<|endoftext|>
|
<commit_before>eb234611-313a-11e5-a848-3c15c2e10482<commit_msg>eb296147-313a-11e5-bdef-3c15c2e10482<commit_after>eb296147-313a-11e5-bdef-3c15c2e10482<|endoftext|>
|
<commit_before>115a6cc0-ad5d-11e7-b866-ac87a332f658<commit_msg>roselyn broke it<commit_after>11cc02eb-ad5d-11e7-8627-ac87a332f658<|endoftext|>
|
<commit_before>64f7f108-5216-11e5-990c-6c40088e03e4<commit_msg>64fea464-5216-11e5-8c30-6c40088e03e4<commit_after>64fea464-5216-11e5-8c30-6c40088e03e4<|endoftext|>
|
<commit_before>7a38e219-2e4f-11e5-8908-28cfe91dbc4b<commit_msg>7a403fc2-2e4f-11e5-8a1a-28cfe91dbc4b<commit_after>7a403fc2-2e4f-11e5-8a1a-28cfe91dbc4b<|endoftext|>
|
<commit_before>8dd25711-ad59-11e7-a8b1-ac87a332f658<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>8e6e3f38-ad59-11e7-85fe-ac87a332f658<|endoftext|>
|
<commit_before>// Demolition Man Verbal Morality Statute Monitor
// Created by Tony DiCola (tony@tonydicola.com)
// Released under an MIT license (http://opensource.org/licenses/MIT).
// Main application.
#include <algorithm>
#include <csignal>
#include <cstdint>
#include <stdexcept>
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
#include <wiringPi.h>
#include "Adafruit_Thermal.h"
#include "AlsaError.h"
#include "AlsaSink.h"
#include "AlsaSource.h"
#include "DemoManMonitor.h"
#include "PocketSphinxKWS.h"
using namespace std;
#define ALARM_FILE "alarm_movie_padded.raw"
#define RECORD_HW "plughw:0,0"
#define PLAYBACK_HW "plughw:1,0"
#define KEYWORD_FILE "keywords.txt"
#define PRINTER_PORT "/dev/ttyAMA0"
#define QUIET_PIN 0
bool shouldRun = true;
void setQuietMode(DemoManMonitor& monitor, bool quietMode) {
monitor.setQuietMode(quietMode);
if (quietMode) {
cout << "Quiet mode enabled." << endl;
}
else {
cout << "Quiet mode disabled." << endl;
}
}
int main(int argc, char* argv[]) {
try {
cout << "Demolition Man Verbal Morality Statute Monitor" << endl;
cout << "Loading..." << endl;
// Signal handler to catch ctrl-c in the main loop and shut down gracefully (i.e. call destructors).
signal(SIGINT, [](int param){ shouldRun = false; });
// Initialize wiringPi library and quiet switch input.
wiringPiSetup () ;
pinMode(QUIET_PIN, INPUT);
bool quietSwitch = (digitalRead(QUIET_PIN) == HIGH);
// Initialize printer.
Adafruit_Thermal printer(PRINTER_PORT);
printer.begin();
// Load alarm raw audio.
ifstream input(ALARM_FILE, ios::in | ios::binary);
input.seekg (0, input.end);
size_t length = input.tellg();
input.seekg (0, input.beg);
vector<uint8_t> alarm(length);
input.read((char*)alarm.data(), length);
// Initialize audio sink and source.
AlsaSink sink;
sink.open(PLAYBACK_HW, 44100, 1, SND_PCM_FORMAT_S16_LE);
AlsaSource source;
source.open(RECORD_HW, 16000, 1, SND_PCM_FORMAT_S16_LE);
// Initialize keyword spotter.
PocketSphinxKWS spotter;
spotter.initialize(PocketSphinxKWS::parseConfig(argc, argv), KEYWORD_FILE);
// Initialize main logic.
DemoManMonitor monitor(8000, &printer, &source, &sink, &spotter, &alarm);
setQuietMode(monitor, quietSwitch);
cout << "Listening... (press Ctrl-C to stop)" << endl;
while (shouldRun) {
// Check quite mode switch and update state.
bool newQuietSwitch = (digitalRead(QUIET_PIN) == HIGH);
if (newQuietSwitch != quietSwitch) {
quietSwitch = newQuietSwitch;
setQuietMode(monitor, quietSwitch);
}
// Update main logic state.
monitor.update();
}
}
catch (AlsaError ex) {
cerr << "ALSA ERROR " << ex.message << " (" << ex.code << ") while calling: " << ex.what() << endl;
return 1;
}
catch (exception ex) {
cerr << "ERROR: " << ex.what() << endl;
return 1;
}
return 0;
}
<commit_msg>LED test<commit_after>// Demolition Man Verbal Morality Statute Monitor
// Created by Tony DiCola (tony@tonydicola.com)
// Released under an MIT license (http://opensource.org/licenses/MIT).
// Main application.
#include <algorithm>
#include <csignal>
#include <cstdint>
#include <stdexcept>
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
#include <wiringPi.h>
#include "Adafruit_Thermal.h"
#include "AlsaError.h"
#include "AlsaSink.h"
#include "AlsaSource.h"
#include "DemoManMonitor.h"
#include "PocketSphinxKWS.h"
using namespace std;
#define ALARM_FILE "alarm_movie_padded.raw"
#define RECORD_HW "plughw:0,0"
#define PLAYBACK_HW "plughw:1,0"
#define KEYWORD_FILE "keywords.txt"
#define PRINTER_PORT "/dev/ttyAMA0"
#define QUIET_PIN 0
#define LED_PIN 4
bool shouldRun = true;
void setQuietMode(DemoManMonitor& monitor, bool quietMode) {
monitor.setQuietMode(quietMode);
if (quietMode) {
cout << "Quiet mode enabled." << endl;
}
else {
cout << "Quiet mode disabled." << endl;
}
}
int main(int argc, char* argv[]) {
try {
cout << "Demolition Man Verbal Morality Statute Monitor" << endl;
cout << "Loading..." << endl;
// Signal handler to catch ctrl-c in the main loop and shut down gracefully (i.e. call destructors).
signal(SIGINT, [](int param){ shouldRun = false; });
// Initialize wiringPi library and quiet switch input.
wiringPiSetup () ;
pinMode(QUIET_PIN, INPUT);
bool quietSwitch = (digitalRead(QUIET_PIN) == HIGH);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
// Initialize printer.
Adafruit_Thermal printer(PRINTER_PORT);
printer.begin();
// Load alarm raw audio.
ifstream input(ALARM_FILE, ios::in | ios::binary);
input.seekg (0, input.end);
size_t length = input.tellg();
input.seekg (0, input.beg);
vector<uint8_t> alarm(length);
input.read((char*)alarm.data(), length);
// Initialize audio sink and source.
AlsaSink sink;
sink.open(PLAYBACK_HW, 44100, 1, SND_PCM_FORMAT_S16_LE);
AlsaSource source;
source.open(RECORD_HW, 16000, 1, SND_PCM_FORMAT_S16_LE);
// Initialize keyword spotter.
PocketSphinxKWS spotter;
spotter.initialize(PocketSphinxKWS::parseConfig(argc, argv), KEYWORD_FILE);
// Initialize main logic.
DemoManMonitor monitor(8000, &printer, &source, &sink, &spotter, &alarm);
setQuietMode(monitor, quietSwitch);
cout << "Listening... (press Ctrl-C to stop)" << endl;
while (shouldRun) {
// Check quite mode switch and update state.
bool newQuietSwitch = (digitalRead(QUIET_PIN) == HIGH);
if (newQuietSwitch != quietSwitch) {
quietSwitch = newQuietSwitch;
setQuietMode(monitor, quietSwitch);
}
// Update main logic state.
monitor.update();
}
digitalWrite(LED_PIN, LOW);
}
catch (AlsaError ex) {
cerr << "ALSA ERROR " << ex.message << " (" << ex.code << ") while calling: " << ex.what() << endl;
return 1;
}
catch (exception ex) {
cerr << "ERROR: " << ex.what() << endl;
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>a4a7bb85-2e4f-11e5-8769-28cfe91dbc4b<commit_msg>a4af1514-2e4f-11e5-82cc-28cfe91dbc4b<commit_after>a4af1514-2e4f-11e5-82cc-28cfe91dbc4b<|endoftext|>
|
<commit_before>8431fbcf-2d15-11e5-af21-0401358ea401<commit_msg>8431fbd0-2d15-11e5-af21-0401358ea401<commit_after>8431fbd0-2d15-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>8f597523-2e4f-11e5-846d-28cfe91dbc4b<commit_msg>8f6073e3-2e4f-11e5-b5ff-28cfe91dbc4b<commit_after>8f6073e3-2e4f-11e5-b5ff-28cfe91dbc4b<|endoftext|>
|
<commit_before>99246b99-327f-11e5-a59b-9cf387a8033e<commit_msg>992a579c-327f-11e5-aa11-9cf387a8033e<commit_after>992a579c-327f-11e5-aa11-9cf387a8033e<|endoftext|>
|
<commit_before>b73bf5e1-4b02-11e5-9ea9-28cfe9171a43<commit_msg>Tuesday, turns out it was tuesday<commit_after>b748a380-4b02-11e5-911f-28cfe9171a43<|endoftext|>
|
<commit_before>cc2de4d7-327f-11e5-81c3-9cf387a8033e<commit_msg>cc346bd1-327f-11e5-93ac-9cf387a8033e<commit_after>cc346bd1-327f-11e5-93ac-9cf387a8033e<|endoftext|>
|
<commit_before>/*Published under The MIT License (MIT)
See LICENSE*/
// Christopher Hernandez
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "colony.h"
int _length;
int _width;
int _gens;
double calculateAvgTime(double** times) {
double total = 0;
for(int j = 0; j < _length; j++) {
for(int i = 0; i < _width; i++) {
total += times[j][i]; // add up all times
}
}
return total / (_length * _width); // sum / n = avg
}
int main(int argc, char** argv) {
clock_t begin = clock();
_length = atoi(argv[1]);
_width = atoi(argv[2]);
_gens = atoi(argv[3]);
bool print = true;
if (argv[4]) { // if 4th parameter exists don't print
if (std::strncmp(argv[4],"--no-print", 10) == 0) {
print = false;
}
}
// Create colony
Colony c(_length, _width, _gens);
for (int i = 0; i < _gens; i++) {
if (print) {
system("clear"); // clear console
c.printGrid();
c.evolve();
system("sleep .1"); // give console time to catch up
} else {
c.evolve();
}
}
clock_t end = clock(); // end gen time
double elapsed = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "Average timestep: " << calculateAvgTime(c.getTimes()) << std::endl;
std::cout << "Total Time: " << elapsed << std::endl;
return 0;
}
<commit_msg>strncmp not part of std lib<commit_after>/*Published under The MIT License (MIT)
See LICENSE*/
// Christopher Hernandez
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "colony.h"
int _length;
int _width;
int _gens;
double calculateAvgTime(double** times) {
double total = 0;
for(int j = 0; j < _length; j++) {
for(int i = 0; i < _width; i++) {
total += times[j][i]; // add up all times
}
}
return total / (_length * _width); // sum / n = avg
}
int main(int argc, char** argv) {
clock_t begin = clock();
_length = atoi(argv[1]);
_width = atoi(argv[2]);
_gens = atoi(argv[3]);
bool print = true;
if (argv[4]) { // if 4th parameter exists don't print
if (strncmp(argv[4],"--no-print", 10) == 0) {
print = false;
}
}
// Create colony
Colony c(_length, _width, _gens);
for (int i = 0; i < _gens; i++) {
if (print) {
system("clear"); // clear console
c.printGrid();
c.evolve();
system("sleep .1"); // give console time to catch up
} else {
c.evolve();
}
}
clock_t end = clock(); // end gen time
double elapsed = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "Average timestep: " << calculateAvgTime(c.getTimes()) << std::endl;
std::cout << "Total Time: " << elapsed << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <thread>
#if qPlatform_POSIX
#include <unistd.h>
#include <fstream>
#elif qPlatform_Windows
#include <Windows.h>
#endif
#include "../Characters/SDKString.h"
#include "../Characters/Format.h"
#include "../Characters/String_Constant.h"
#include "../Characters/String2Int.h"
#include "../Containers/Set.h"
#if qPlatform_POSIX
#include "../Execution/ErrNoException.h"
#elif qPlatform_Windows
#include "../Execution/Platform/Windows/Exception.h"
#endif
#include "../Memory/SmallStackBuffer.h"
#include "../IO/FileSystem/BinaryFileInputStream.h"
#include "../Streams/BasicBinaryInputOutputStream.h"
#include "../Streams/TextInputStreamBinaryAdapter.h"
#include "SystemConfiguration.h"
#if qPlatform_POSIX
#include "../DataExchange/INI/Reader.h"
#include "../Execution/ProcessRunner.h"
#include "../Streams/iostream/FStreamSupport.h"
#endif
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Configuration;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Streams;
using Characters::String_Constant;
using Characters::SDKChar;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
***************** Configuration::SystemConfiguration::CPU **********************
********************************************************************************
*/
unsigned int SystemConfiguration::CPU::GetNumberOfSockets () const
{
Set<unsigned int> socketIds;
for (auto i : fCores) {
socketIds.Add (i.fSocketID);
}
return static_cast<unsigned int> (socketIds.size ());
}
/*
********************************************************************************
*************** Configuration::GetSystemConfiguration_CPU **********************
********************************************************************************
*/
SystemConfiguration::CPU Configuration::GetSystemConfiguration_CPU ()
{
using CPU = SystemConfiguration::CPU;
CPU result;
#if qPlatform_POSIX
{
using Streams::TextInputStreamBinaryAdapter;
using IO::FileSystem::BinaryFileInputStream;
using Characters::String2Int;
const String_Constant kProcCPUInfoFileName_ { L"/proc/cpuinfo" };
CPU::CoreDetails coreDetails;
// Note - /procfs files always unseekable
for (String line : TextInputStreamBinaryAdapter (BinaryFileInputStream::mk (kProcCPUInfoFileName_, BinaryFileInputStream::eNotSeekable)).ReadLines ()) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"***in Configuration::GetSystemConfiguration_CPU capture_ line=%s", line.c_str ());
#endif
static const String_Constant kModelNameLabel_ { L"model name : " };
//static const String_Constant kProcessorIDLabel_ { L"processor : " };
static const String_Constant kSocketIDLabel_ { L"physical id : " }; // a bit of a guess?
if (line.StartsWith (kModelNameLabel_)) {
coreDetails.fModelName = line.SubString (kModelNameLabel_.length ()).Trim ();
}
else if (line.StartsWith (kSocketIDLabel_)) {
unsigned int socketID = String2Int<unsigned int> (line.SubString (kSocketIDLabel_.length ()).Trim ());
coreDetails.fSocketID = socketID;
}
if (line.Trim ().empty ()) {
// ends each socket
result.fCores.Append (coreDetails);
coreDetails = CPU::CoreDetails ();
}
}
if (coreDetails.fSocketID != 0 or not coreDetails.fModelName.empty ()) {
result.fCores.Append (coreDetails);
}
}
#elif qPlatform_Windows
SYSTEM_INFO sysInfo; // GetNativeSystemInfo cannot fail so no need to initialize data
::GetNativeSystemInfo (&sysInfo);
//unclear if this is count of logical or physical cores, or how to compute the other.
//@todo - fix as above for POSIX... maybe ask Sterl? But for now KISS
//
// Can use https://msdn.microsoft.com/en-us/library/hskdteyh%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396
// __cpuid
// to find this information (at least modelname string.
//
for (DWORD i = 0; i < sysInfo.dwNumberOfProcessors; ++i) {
result.fCores.Append (CPU::CoreDetails ());
}
#endif
return result;
}
/*
********************************************************************************
************** Configuration::GetSystemConfiguration_Memory ********************
********************************************************************************
*/
SystemConfiguration::Memory Configuration::GetSystemConfiguration_Memory ()
{
using Memory = SystemConfiguration::Memory;
Memory result;
#if qPlatform_POSIX
result.fPageSize = ::sysconf (_SC_PAGESIZE);
result.fTotalPhysicalRAM = ::sysconf (_SC_PHYS_PAGES) * result.fPageSize;
#elif qPlatform_Windows
SYSTEM_INFO sysInfo;
::GetNativeSystemInfo (&sysInfo);
result.fPageSize = sysInfo.dwPageSize;
MEMORYSTATUSEX memStatus;
memStatus.dwLength = sizeof (memStatus);
Verify (::GlobalMemoryStatusEx (&memStatus));
result.fTotalPhysicalRAM = memStatus.ullTotalPhys;
result.fTotalVirtualRAM = memStatus.ullTotalVirtual;
#endif
return result;
}
/*
********************************************************************************
******** Configuration::GetSystemConfiguration_OperatingSystem *****************
********************************************************************************
*/
SystemConfiguration::OperatingSystem Configuration::GetSystemConfiguration_OperatingSystem ()
{
using OperatingSystem = SystemConfiguration::OperatingSystem;
static const OperatingSystem kCachedResult_ = []() ->OperatingSystem {
OperatingSystem tmp;
#if qPlatform_POSIX
tmp.fTokenName = String_Constant (L"Unix");
try {
tmp.fTokenName = Execution::ProcessRunner (L"uname").Run (String ()).Trim ();
}
catch (...)
{
DbgTrace ("Failure running uname");
}
try {
ifstream s;
Streams::iostream::OpenInputFileStream (&s, L"/etc/os-release");
DataExchange::INI::Profile p = DataExchange::INI::Reader ().ReadProfile (s);
tmp.fShortPrettyName = p.fUnnamedSection.fProperties.LookupValue (L"NAME");
tmp.fPrettyNameWithMajorVersion = p.fUnnamedSection.fProperties.LookupValue (L"PRETTY_NAME");
}
catch (...)
{
DbgTrace ("Failure reading /etc/os-release");
}
if (tmp.fShortPrettyName.empty ())
{
tmp.fShortPrettyName = tmp.fTokenName;
}
if (tmp.fPrettyNameWithMajorVersion.empty ())
{
tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
}
if (tmp.fRFC1945CompatProductTokenWithVersion.empty ())
{
tmp.fRFC1945CompatProductTokenWithVersion = tmp.fShortPrettyName.Trim ().ReplaceAll (L" ", L"-");
if (not tmp.fMajorMinorVersionString.empty ()) {
tmp.fRFC1945CompatProductTokenWithVersion += L"/" + tmp.fMajorMinorVersionString;
}
}
//
// @todo FIX/FIND BETTER WAY!
//
//http://docs.oracle.com/cd/E36784_01/html/E36874/sysconf-3c.html
// Quite uncertain - this is not a good reference
// --LGP 2014-10-18
//
tmp.fBits = ::sysconf (_SC_V6_LP64_OFF64) == _POSIX_V6_LP64_OFF64 ? 64 : 32;
#elif qPlatform_Windows
tmp.fTokenName = String_Constant (L"Windows");
/*
* Microslop declares this deprecated, but then fails to provide a reasonable alternative.
*
* Sigh.
*
* http://msdn.microsoft.com/en-us/library/windows/desktop/ms724429(v=vs.85).aspx - GetFileVersionInfo (kernel32.dll)
* is a painful, and stupid alternative.
*/
DISABLE_COMPILER_MSC_WARNING_START(4996)
OSVERSIONINFOEX osvi;
memset(&osvi, 0, sizeof (osvi));
osvi.dwOSVersionInfoSize = sizeof (osvi);
Verify (::GetVersionEx (reinterpret_cast<LPOSVERSIONINFO> (&osvi)));
DISABLE_COMPILER_MSC_WARNING_END(4996)
if (osvi.dwMajorVersion == 6)
{
if (osvi.dwMinorVersion == 0) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows Vista") : String_Constant (L"Windows Server 2008");
}
else if (osvi.dwMinorVersion == 1) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 7") : String_Constant (L"Windows Server 2008 R2");
}
else if (osvi.dwMinorVersion == 2) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 8") : String_Constant (L"Windows Server 2012");
}
else if (osvi.dwMinorVersion == 3) {
if (osvi.wProductType == VER_NT_WORKSTATION)
tmp.fShortPrettyName = String_Constant (L"Windows 8.1");
}
}
if (tmp.fShortPrettyName.empty ())
{
tmp.fShortPrettyName = Characters::Format (L"Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
}
tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
tmp.fMajorMinorVersionString = Characters::Format (L"%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
tmp.fRFC1945CompatProductTokenWithVersion = Characters::Format (L"Windows/%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
if (sizeof (void*) == 4)
{
tmp.fBits = 32;
//IsWow64Process is not available on all supported versions of Windows.
//Use GetModuleHandle to get a handle to the DLL that contains the function
//and GetProcAddress to get a pointer to the function if available.
typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
if(NULL != fnIsWow64Process) {
BOOL isWOW64 = false;
(void)fnIsWow64Process (GetCurrentProcess(), &isWOW64);
if (isWOW64) {
tmp.fBits = 64;
}
}
}
else {
// In windows, a 64 bit app cannot run on 32-bit windows
Assert (sizeof (void*) == 8);
tmp.fBits = 64;
}
#else
AssertNotImplemented ();
#endif
return tmp;
} ();
return kCachedResult_;
}
/*
********************************************************************************
***************** GetSystemConfiguration_ComputerNames *************************
********************************************************************************
*/
#if 0 && qPlatform_POSIX
// ALTERNATE APPROACH TO CONSIDER
string name;
{
struct addrinfo* res;
struct addrinfo hints;
memset(&hints, '\0', sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
int e = getaddrinfo(nullptr, nullptr, &hints, &res);
if (e != 0) {
//printf("failure %s\n", gai_strerror (e));
return String ();
}
int sock = -1;
for (struct addrinfo* r = res; r != NULL; r = r->ai_next) {
name = r->ai_canonname ;
break;
}
freeaddrinfo(res);
}
return String::FromSDKString (name);
#endif
SystemConfiguration::ComputerNames Configuration::GetSystemConfiguration_ComputerNames ()
{
using ComputerNames = SystemConfiguration::ComputerNames;
ComputerNames result;
#if qPlatform_POSIX
char nameBuf[1024];
Execution::ThrowErrNoIfNegative (gethostname (nameBuf, NEltsOf (nameBuf)));
nameBuf[NEltsOf (nameBuf) - 1] = '\0'; // http://linux.die.net/man/2/gethostname says not necessarily nul-terminated
result.fHostname = String::FromNarrowSDKString (nameBuf);
#elif qPlatform_Windows
constexpr COMPUTER_NAME_FORMAT kUseNameFormat_ = ComputerNameNetBIOS; // total WAG -- LGP 2014-10-10
DWORD dwSize = 0;
(void) ::GetComputerNameEx (kUseNameFormat_, nullptr, &dwSize);
Memory::SmallStackBuffer<SDKChar> buf(dwSize);
Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetComputerNameEx (kUseNameFormat_, buf, &dwSize));
result.fHostname = String::FromSDKString (buf);
#else
AssertNotImplemented ();
#endif
return result;
}
/*
********************************************************************************
****************** SystemConfiguration GetSystemConfiguration ******************
********************************************************************************
*/
inline SystemConfiguration GetSystemConfiguration ()
{
return SystemConfiguration {
GetSystemConfiguration_CPU (),
GetSystemConfiguration_Memory (),
GetSystemConfiguration_OperatingSystem (),
GetSystemConfiguration_ComputerNames ()
};
}
<commit_msg>fixed missing namespace in definition<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <thread>
#if qPlatform_POSIX
#include <unistd.h>
#include <fstream>
#elif qPlatform_Windows
#include <Windows.h>
#endif
#include "../Characters/SDKString.h"
#include "../Characters/Format.h"
#include "../Characters/String_Constant.h"
#include "../Characters/String2Int.h"
#include "../Containers/Set.h"
#if qPlatform_POSIX
#include "../Execution/ErrNoException.h"
#elif qPlatform_Windows
#include "../Execution/Platform/Windows/Exception.h"
#endif
#include "../Memory/SmallStackBuffer.h"
#include "../IO/FileSystem/BinaryFileInputStream.h"
#include "../Streams/BasicBinaryInputOutputStream.h"
#include "../Streams/TextInputStreamBinaryAdapter.h"
#include "SystemConfiguration.h"
#if qPlatform_POSIX
#include "../DataExchange/INI/Reader.h"
#include "../Execution/ProcessRunner.h"
#include "../Streams/iostream/FStreamSupport.h"
#endif
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Configuration;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Streams;
using Characters::String_Constant;
using Characters::SDKChar;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
***************** Configuration::SystemConfiguration::CPU **********************
********************************************************************************
*/
unsigned int SystemConfiguration::CPU::GetNumberOfSockets () const
{
Set<unsigned int> socketIds;
for (auto i : fCores) {
socketIds.Add (i.fSocketID);
}
return static_cast<unsigned int> (socketIds.size ());
}
/*
********************************************************************************
*************** Configuration::GetSystemConfiguration_CPU **********************
********************************************************************************
*/
SystemConfiguration::CPU Configuration::GetSystemConfiguration_CPU ()
{
using CPU = SystemConfiguration::CPU;
CPU result;
#if qPlatform_POSIX
{
using Streams::TextInputStreamBinaryAdapter;
using IO::FileSystem::BinaryFileInputStream;
using Characters::String2Int;
const String_Constant kProcCPUInfoFileName_ { L"/proc/cpuinfo" };
CPU::CoreDetails coreDetails;
// Note - /procfs files always unseekable
for (String line : TextInputStreamBinaryAdapter (BinaryFileInputStream::mk (kProcCPUInfoFileName_, BinaryFileInputStream::eNotSeekable)).ReadLines ()) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"***in Configuration::GetSystemConfiguration_CPU capture_ line=%s", line.c_str ());
#endif
static const String_Constant kModelNameLabel_ { L"model name : " };
//static const String_Constant kProcessorIDLabel_ { L"processor : " };
static const String_Constant kSocketIDLabel_ { L"physical id : " }; // a bit of a guess?
if (line.StartsWith (kModelNameLabel_)) {
coreDetails.fModelName = line.SubString (kModelNameLabel_.length ()).Trim ();
}
else if (line.StartsWith (kSocketIDLabel_)) {
unsigned int socketID = String2Int<unsigned int> (line.SubString (kSocketIDLabel_.length ()).Trim ());
coreDetails.fSocketID = socketID;
}
if (line.Trim ().empty ()) {
// ends each socket
result.fCores.Append (coreDetails);
coreDetails = CPU::CoreDetails ();
}
}
if (coreDetails.fSocketID != 0 or not coreDetails.fModelName.empty ()) {
result.fCores.Append (coreDetails);
}
}
#elif qPlatform_Windows
SYSTEM_INFO sysInfo; // GetNativeSystemInfo cannot fail so no need to initialize data
::GetNativeSystemInfo (&sysInfo);
//unclear if this is count of logical or physical cores, or how to compute the other.
//@todo - fix as above for POSIX... maybe ask Sterl? But for now KISS
//
// Can use https://msdn.microsoft.com/en-us/library/hskdteyh%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396
// __cpuid
// to find this information (at least modelname string.
//
for (DWORD i = 0; i < sysInfo.dwNumberOfProcessors; ++i) {
result.fCores.Append (CPU::CoreDetails ());
}
#endif
return result;
}
/*
********************************************************************************
************** Configuration::GetSystemConfiguration_Memory ********************
********************************************************************************
*/
SystemConfiguration::Memory Configuration::GetSystemConfiguration_Memory ()
{
using Memory = SystemConfiguration::Memory;
Memory result;
#if qPlatform_POSIX
result.fPageSize = ::sysconf (_SC_PAGESIZE);
result.fTotalPhysicalRAM = ::sysconf (_SC_PHYS_PAGES) * result.fPageSize;
#elif qPlatform_Windows
SYSTEM_INFO sysInfo;
::GetNativeSystemInfo (&sysInfo);
result.fPageSize = sysInfo.dwPageSize;
MEMORYSTATUSEX memStatus;
memStatus.dwLength = sizeof (memStatus);
Verify (::GlobalMemoryStatusEx (&memStatus));
result.fTotalPhysicalRAM = memStatus.ullTotalPhys;
result.fTotalVirtualRAM = memStatus.ullTotalVirtual;
#endif
return result;
}
/*
********************************************************************************
******** Configuration::GetSystemConfiguration_OperatingSystem *****************
********************************************************************************
*/
SystemConfiguration::OperatingSystem Configuration::GetSystemConfiguration_OperatingSystem ()
{
using OperatingSystem = SystemConfiguration::OperatingSystem;
static const OperatingSystem kCachedResult_ = []() ->OperatingSystem {
OperatingSystem tmp;
#if qPlatform_POSIX
tmp.fTokenName = String_Constant (L"Unix");
try {
tmp.fTokenName = Execution::ProcessRunner (L"uname").Run (String ()).Trim ();
}
catch (...)
{
DbgTrace ("Failure running uname");
}
try {
ifstream s;
Streams::iostream::OpenInputFileStream (&s, L"/etc/os-release");
DataExchange::INI::Profile p = DataExchange::INI::Reader ().ReadProfile (s);
tmp.fShortPrettyName = p.fUnnamedSection.fProperties.LookupValue (L"NAME");
tmp.fPrettyNameWithMajorVersion = p.fUnnamedSection.fProperties.LookupValue (L"PRETTY_NAME");
}
catch (...)
{
DbgTrace ("Failure reading /etc/os-release");
}
if (tmp.fShortPrettyName.empty ())
{
tmp.fShortPrettyName = tmp.fTokenName;
}
if (tmp.fPrettyNameWithMajorVersion.empty ())
{
tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
}
if (tmp.fRFC1945CompatProductTokenWithVersion.empty ())
{
tmp.fRFC1945CompatProductTokenWithVersion = tmp.fShortPrettyName.Trim ().ReplaceAll (L" ", L"-");
if (not tmp.fMajorMinorVersionString.empty ()) {
tmp.fRFC1945CompatProductTokenWithVersion += L"/" + tmp.fMajorMinorVersionString;
}
}
//
// @todo FIX/FIND BETTER WAY!
//
//http://docs.oracle.com/cd/E36784_01/html/E36874/sysconf-3c.html
// Quite uncertain - this is not a good reference
// --LGP 2014-10-18
//
tmp.fBits = ::sysconf (_SC_V6_LP64_OFF64) == _POSIX_V6_LP64_OFF64 ? 64 : 32;
#elif qPlatform_Windows
tmp.fTokenName = String_Constant (L"Windows");
/*
* Microslop declares this deprecated, but then fails to provide a reasonable alternative.
*
* Sigh.
*
* http://msdn.microsoft.com/en-us/library/windows/desktop/ms724429(v=vs.85).aspx - GetFileVersionInfo (kernel32.dll)
* is a painful, and stupid alternative.
*/
DISABLE_COMPILER_MSC_WARNING_START(4996)
OSVERSIONINFOEX osvi;
memset(&osvi, 0, sizeof (osvi));
osvi.dwOSVersionInfoSize = sizeof (osvi);
Verify (::GetVersionEx (reinterpret_cast<LPOSVERSIONINFO> (&osvi)));
DISABLE_COMPILER_MSC_WARNING_END(4996)
if (osvi.dwMajorVersion == 6)
{
if (osvi.dwMinorVersion == 0) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows Vista") : String_Constant (L"Windows Server 2008");
}
else if (osvi.dwMinorVersion == 1) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 7") : String_Constant (L"Windows Server 2008 R2");
}
else if (osvi.dwMinorVersion == 2) {
tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 8") : String_Constant (L"Windows Server 2012");
}
else if (osvi.dwMinorVersion == 3) {
if (osvi.wProductType == VER_NT_WORKSTATION)
tmp.fShortPrettyName = String_Constant (L"Windows 8.1");
}
}
if (tmp.fShortPrettyName.empty ())
{
tmp.fShortPrettyName = Characters::Format (L"Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
}
tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
tmp.fMajorMinorVersionString = Characters::Format (L"%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
tmp.fRFC1945CompatProductTokenWithVersion = Characters::Format (L"Windows/%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
if (sizeof (void*) == 4)
{
tmp.fBits = 32;
//IsWow64Process is not available on all supported versions of Windows.
//Use GetModuleHandle to get a handle to the DLL that contains the function
//and GetProcAddress to get a pointer to the function if available.
typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
if(NULL != fnIsWow64Process) {
BOOL isWOW64 = false;
(void)fnIsWow64Process (GetCurrentProcess(), &isWOW64);
if (isWOW64) {
tmp.fBits = 64;
}
}
}
else {
// In windows, a 64 bit app cannot run on 32-bit windows
Assert (sizeof (void*) == 8);
tmp.fBits = 64;
}
#else
AssertNotImplemented ();
#endif
return tmp;
} ();
return kCachedResult_;
}
/*
********************************************************************************
***************** GetSystemConfiguration_ComputerNames *************************
********************************************************************************
*/
#if 0 && qPlatform_POSIX
// ALTERNATE APPROACH TO CONSIDER
string name;
{
struct addrinfo* res;
struct addrinfo hints;
memset(&hints, '\0', sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
int e = getaddrinfo(nullptr, nullptr, &hints, &res);
if (e != 0) {
//printf("failure %s\n", gai_strerror (e));
return String ();
}
int sock = -1;
for (struct addrinfo* r = res; r != NULL; r = r->ai_next) {
name = r->ai_canonname ;
break;
}
freeaddrinfo(res);
}
return String::FromSDKString (name);
#endif
SystemConfiguration::ComputerNames Configuration::GetSystemConfiguration_ComputerNames ()
{
using ComputerNames = SystemConfiguration::ComputerNames;
ComputerNames result;
#if qPlatform_POSIX
char nameBuf[1024];
Execution::ThrowErrNoIfNegative (gethostname (nameBuf, NEltsOf (nameBuf)));
nameBuf[NEltsOf (nameBuf) - 1] = '\0'; // http://linux.die.net/man/2/gethostname says not necessarily nul-terminated
result.fHostname = String::FromNarrowSDKString (nameBuf);
#elif qPlatform_Windows
constexpr COMPUTER_NAME_FORMAT kUseNameFormat_ = ComputerNameNetBIOS; // total WAG -- LGP 2014-10-10
DWORD dwSize = 0;
(void) ::GetComputerNameEx (kUseNameFormat_, nullptr, &dwSize);
Memory::SmallStackBuffer<SDKChar> buf(dwSize);
Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetComputerNameEx (kUseNameFormat_, buf, &dwSize));
result.fHostname = String::FromSDKString (buf);
#else
AssertNotImplemented ();
#endif
return result;
}
/*
********************************************************************************
****************** SystemConfiguration GetSystemConfiguration ******************
********************************************************************************
*/
inline SystemConfiguration Configuration::GetSystemConfiguration ()
{
return SystemConfiguration {
GetSystemConfiguration_CPU (),
GetSystemConfiguration_Memory (),
GetSystemConfiguration_OperatingSystem (),
GetSystemConfiguration_ComputerNames ()
};
}
<|endoftext|>
|
<commit_before>/**
* For use with the Arduino/Genuino IDE
*
* Program controlling motors
*
* License information:
* The MIT License (MIT)
*
* 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
* he 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 <Stepper.h>
enum EMotor {
MOTOR_ALL,
MOTOR_ONE,
MOTOR_TWO,
MOTOR_THREE
};
// Number of steps (signals) required to do a 360° rotation (?)
const int steps_per_revolution = 200;
// Motor1 pins 1 to 4
const int m1_p1 = 10;
const int m1_p2 = 11;
const int m1_p3 = 12;
const int m1_p4 = 13;
// Motor2 pins 5 to 8
const int m2_p1 = 5;
const int m2_p2 = 6;
const int m2_p3 = 7;
const int m2_p4 = 8;
// Motor3 pins 9 to 12
const int m3_p1 = 9;
const int m3_p2 = 10;
const int m3_p3 = 11;
const int m3_p4 = 12;
// Button input, pin 13
const int buttonPin = 2;
// Button pressed(1) or released(0)?
// int savedButtonState = 0;
int aperatureActive = 0;
unsigned int timeDuration = 0;
// This the approx.(!) time in milliseconds after the aperature closes automatically
// TODO: Is there a time library or can we use C time?
const int automaticCollapseMS = 10000;
// These variables define the amount the motor works, it's kinda like RPM, think 1 revolution = 360°
// don't know for sure how this is linked to the Stepper constructor paramter1 so be careful testing this!
const int motor1AM = 10;
const int motor2AM = 10;
const int motor3AM = 10;
Stepper motor1(steps_per_revolution, m1_p1, m1_p2, m1_p3, m1_p4);
Stepper motor2(steps_per_revolution, m2_p1, m2_p2, m2_p3, m2_p4);
Stepper motor3(steps_per_revolution, m3_p1, m3_p2, m3_p3, m3_p4);
void SetMotorSpeed(EMotor motor, unsigned int speed) {
switch (motor) {
case MOTOR_ONE:
motor1.setSpeed(speed);
break;
case MOTOR_TWO:
motor2.setSpeed(speed);
break;
case MOTOR_THREE:
motor3.setSpeed(speed);
break;
case MOTOR_ALL:
motor1.setSpeed(speed);
motor2.setSpeed(speed);
motor3.setSpeed(speed);
break;
}
}
// @revolutions = positive amounts move the motorknob forwards, negative amounts backwards
// remember that .step() is blocking, so if we want to move all motors at once we need a different approach/function
// with revolution deltas
void MoveMotor(EMotor motor, int revolutions) {
switch (motor) {
case MOTOR_ONE:
motor1.step(revolutions);
break;
case MOTOR_TWO:
motor2.step(revolutions);
break;
case MOTOR_THREE:
motor3.step(revolutions);
break;
case MOTOR_ALL:
motor1.step(revolutions);
motor2.step(revolutions);
motor3.step(revolutions);
break;
}
}
void setup() {
// Setup the button pin as input
pinMode(buttonPin, INPUT);
// Set the motor speed for all motor, change if necessary calling each one seperately
SetMotorSpeed(MOTOR_ALL, 60); // Check C++98 enum?
Serial.begin(9600);
Serial.print("Program starting");
}
void loop() {
int currentButtonState = digitalRead(buttonPin);
if (aperatureActive == 0 && currentButtonState == 1) {
// Someone pressed the button while the aperature was inactive, start rolling out..
// Step the motors
// Remember: For now this moves the motors one after another.. see MoveMotor comments
MoveMotor(MOTOR_ONE, motor1AM);
MoveMotor(MOTOR_TWO, motor2AM);
MoveMotor(MOTOR_THREE, motor3AM);
// Save the state
aperatureActive = 1;
}
else if (aperatureActive == 1 && currentButtonState == 1) {
// The aperature was active and the button was pressed, roll in
// Step the motors backwards, so we start with motor 3
MoveMotor(MOTOR_THREE, -1 * motor3AM);
MoveMotor(MOTOR_TWO, -1 * motor2AM);
MoveMotor(MOTOR_ONE, -1 * motor1AM);
// Save the state
aperatureActive = 0;
// Set time to null
timeDuration = 0;
}
else if (aperatureActive == 1 && timeDuration >= automaticCollapseMS) {
// Automatic collapse after time duration, roll in
// Step the motors backwards, so we start with motor 3
MoveMotor(MOTOR_THREE, -1 * motor3AM);
MoveMotor(MOTOR_TWO, -1 * motor2AM);
MoveMotor(MOTOR_ONE, -1 * motor1AM);
// Save the state
aperatureActive = 0;
// Set time to null
timeDuration = 0;
}
else if (aperatureActive == 1) {
delay(1); // Delay for a milliseconds
timeDuration = timeDuration + 1; // And save that
}
else {
// Aperature is not doing anything, Sleep to preserve power?
delay(1);
Serial.print("No action");
}
}
<commit_msg>awdawdadw<commit_after>/**
* For use with the Arduino/Genuino IDE
*
* Program controlling motors
*
* License information:
* The MIT License (MIT)
*
* 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
* he 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 <Stepper.h>
enum EMotor {
MOTOR_ALL,
MOTOR_ONE,
MOTOR_TWO,
MOTOR_THREE
};
// Number of steps (signals) required to do a 360° rotation (?)
const int steps_per_revolution = 200;
// Motor1 pins 1 to 4
const int m1_p1 = 10;
const int m1_p2 = 11;
const int m1_p3 = 12;
const int m1_p4 = 13;
// Motor2 pins 5 to 8
const int m2_p1 = 5;
const int m2_p2 = 6;
const int m2_p3 = 7;
const int m2_p4 = 8;
// Motor3 pins 9 to 12
const int m3_p1 = 9;
const int m3_p2 = 10;
const int m3_p3 = 11;
const int m3_p4 = 12;
// Button input, pin 13
const int buttonPin = 2;
// Button pressed(1) or released(0)?
// int savedButtonState = 0;
int aperatureActive = 0;
unsigned int timeDuration = 0;
// This the approx.(!) time in milliseconds after the aperature closes automatically
// TODO: Is there a time library or can we use C time?
const int automaticCollapseMS = 10000;
// These variables define the amount the motor works, it's kinda like RPM, think 1 revolution = 360°
// don't know for sure how this is linked to the Stepper constructor paramter1 so be careful testing this!
const int motor1AM = 10;
const int motor2AM = 10;
const int motor3AM = 10;
Stepper motor1(steps_per_revolution, m1_p1, m1_p2, m1_p3, m1_p4);
Stepper motor2(steps_per_revolution, m2_p1, m2_p2, m2_p3, m2_p4);
Stepper motor3(steps_per_revolution, m3_p1, m3_p2, m3_p3, m3_p4);
void SetMotorSpeed(EMotor motor, unsigned int speed) {
switch (motor) {
case MOTOR_ONE:
motor1.setSpeed(speed);
break;
case MOTOR_TWO:
motor2.setSpeed(speed);
break;
case MOTOR_THREE:
motor3.setSpeed(speed);
break;
case MOTOR_ALL:
motor1.setSpeed(speed);
motor2.setSpeed(speed);
motor3.setSpeed(speed);
break;
}
}
// @revolutions = positive amounts move the motorknob forwards, negative amounts backwards
// remember that .step() is blocking, so if we want to move all motors at once we need a different approach/function
// with revolution deltas
void MoveMotor(EMotor motor, int revolutions) {
switch (motor) {
case MOTOR_ONE:
motor1.step(revolutions);
break;
case MOTOR_TWO:
motor2.step(revolutions);
break;
case MOTOR_THREE:
motor3.step(revolutions);
break;
case MOTOR_ALL:
motor1.step(revolutions);
motor2.step(revolutions);
motor3.step(revolutions);
break;
}
}
void setup() {
// Setup the button pin as input
pinMode(buttonPin, INPUT);
// Set the motor speed for all motor, change if necessary calling each one seperately
SetMotorSpeed(MOTOR_ALL, 60); // Check C++98 enum?
Serial.begin(9600);
Serial.print("Program starting");
}
void loop() {
int currentButtonState = digitalRead(buttonPin);
if (aperatureActive == 0 && digitalRead(buttonPin) == HIGH) {
Serial.print("Button pressed, starting motors forward");
// Someone pressed the button while the aperature was inactive, start rolling out..
// Step the motors
// Remember: For now this moves the motors one after another.. see MoveMotor comments
MoveMotor(MOTOR_ONE, motor1AM);
MoveMotor(MOTOR_TWO, motor2AM);
MoveMotor(MOTOR_THREE, motor3AM);
// Save the state
aperatureActive = 1;
}
else if (aperatureActive == 1 && digitalRead(buttonPin)== HIGH) {
Serial.print("Button pressed, starting motors backwards");
// The aperature was active and the button was pressed, roll in
// Step the motors backwards, so we start with motor 3
MoveMotor(MOTOR_THREE, -1 * motor3AM);
MoveMotor(MOTOR_TWO, -1 * motor2AM);
MoveMotor(MOTOR_ONE, -1 * motor1AM);
// Save the state
aperatureActive = 0;
// Set time to null
timeDuration = 0;
}
else if (aperatureActive == 1 && timeDuration >= automaticCollapseMS) {
Serial.print("Time run out, starting motors backwards");
// Automatic collapse after time duration, roll in
// Step the motors backwards, so we start with motor 3
MoveMotor(MOTOR_THREE, -1 * motor3AM);
MoveMotor(MOTOR_TWO, -1 * motor2AM);
MoveMotor(MOTOR_ONE, -1 * motor1AM);
// Save the state
aperatureActive = 0;
// Set time to null
timeDuration = 0;
}
else if (aperatureActive == 1) {
delay(1); // Delay for a milliseconds
timeDuration = timeDuration + 1; // And save that
}
else {
// Aperature is not doing anything, Sleep to preserve power?
delay(1);
}
}
<|endoftext|>
|
<commit_before>01243bf3-2e4f-11e5-93fd-28cfe91dbc4b<commit_msg>012d1cf5-2e4f-11e5-ac58-28cfe91dbc4b<commit_after>012d1cf5-2e4f-11e5-ac58-28cfe91dbc4b<|endoftext|>
|
<commit_before>3f6c98ca-2e4f-11e5-8bb9-28cfe91dbc4b<commit_msg>3f7326e1-2e4f-11e5-85b2-28cfe91dbc4b<commit_after>3f7326e1-2e4f-11e5-85b2-28cfe91dbc4b<|endoftext|>
|
<commit_before>81cf0dee-2d15-11e5-af21-0401358ea401<commit_msg>81cf0def-2d15-11e5-af21-0401358ea401<commit_after>81cf0def-2d15-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <stack>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
using namespace std;
vector<string> getFiles(string filePath)
{
const char* DIR_PATH = filePath.c_str();
vector<string> directories;
DIR *dir = opendir(DIR_PATH);
struct dirent *entry = readdir(dir);
while (entry != NULL)
{
if (entry->d_type == DT_DIR) {
if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {
} else {
directories.push_back(filePath + "/" + entry->d_name);
}
}
entry = readdir(dir);
}
closedir(dir);
return directories;
}
int main(void)
{
string searchedDir = "/home/simon/Plocha/Simon";
stack<string> actDir;
actDir.push(searchedDir);
string actSearchedDir;
vector<string> dirFound;
string newString = searchedDir;
int dirCount = 0;
while(actDir.size() > 0) {
actSearchedDir = actDir.top();actDir.pop();
cout << actSearchedDir << endl;
dirFound = getFiles(actSearchedDir.c_str());
for(unsigned i = 0; i < dirFound.size(); i++) {
if(!dirFound.empty()) {
newString = dirFound.at(i);
//cout << newString << endl;
actDir.push(newString);
} else {
break;
}
}
dirCount++;
}
cout << "Bylo nalezeno celkem " << dirCount-1 << " složek";
return 0;
}
<commit_msg>Formální dodělávky<commit_after>#include <iostream>
#include <vector>
#include <stack>
#include <dirent.h>
#include <string.h>
using namespace std;
/*
* The function returns directories found in directory.
* First parameter is path where you want to find directories.
* You can also use double slashes like this ...../dir/dir//dir. Not reomanded!
*/
vector<string> getDirs(string dirPath)
{
// Converting path to const char* because the function opendir is programmed in c
// and c methods parameters accepts only const char* so I must convert it.
const char* DIR_PATH = dirPath.c_str();
// Declaration of dynamic array that contains found directories by path.
vector<string> directories;
// Call a function to try to open the dir by path.
// If it doesnt exists the function will return segmentation error.
DIR *dir = opendir(DIR_PATH);
// Then try to read the dir
struct dirent *entry = readdir(dir);
// While dir has a directory.
while (entry != NULL)
{
// If type of stream is directory.
if (entry->d_type == DT_DIR) {
// If the "directory" name is not ".." or ".".
if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {
} else {
// push the actual dir path PLUS actual directory to the dynamic array.
directories.push_back(dirPath + "/" + entry->d_name);
}
}
entry = readdir(dir);
}
// Close the dir.
closedir(dir);
return directories;
}
int main(void)
{
// A root path where you want to start searching.
string searchedDir = "/home/simon/Plocha/Simon";
stack<string> actDir;
actDir.push(searchedDir);
string actSearchedDir;
vector<string> dirFound;
int dirCount = 0;
while(actDir.size() > 0) {
actSearchedDir = actDir.top();actDir.pop();
cout << actSearchedDir << endl;
dirFound = getDirs(actSearchedDir.c_str());
for(unsigned i = 0; i < dirFound.size(); i++) {
if(!dirFound.empty()) {
actDir.push(dirFound.at(i));
} else {
break;
}
}
dirCount++;
}
cout << "Bylo nalezeno celkem " << dirCount-1 << " složek";
return 0;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include "nomlib/graphics/TrueTypeFont.hpp"
namespace nom {
TrueTypeFont::TrueTypeFont ( void )
{
NOM_LOG_TRACE ( NOM );
this->font = nullptr;
this->coords = Coords ( 0, 0, 0, 0 );
this->color = Color4u ( 0, 0, 0 );
this->text_buffer = "\0";
this->text_style = FontStyle::Regular; // default text styling effect
this->text_alignment = TextAlignment::MiddleLeft;
this->rendering = RenderStyle::Solid; // Fast, but ugly
this->style_options = 0;
this->filename = "\0";
this->font_size = 12;
this->use_cache = false;
}
TrueTypeFont::~TrueTypeFont ( void )
{
NOM_LOG_TRACE ( NOM );
}
IFont::SharedPtr TrueTypeFont::clone ( void ) const
{
return IFont::SharedPtr ( new TrueTypeFont ( *this ), priv::Free_TrueTypeFont );
}
bool TrueTypeFont::valid ( void ) const
{
if ( this->font.get() != nullptr )
{
return true;
}
else
{
return false;
}
}
const std::string& TrueTypeFont::getText ( void ) const
{
return this->text_buffer;
}
int32 TrueTypeFont::getFontWidth ( void ) const
{
return this->coords.width;
}
int32 TrueTypeFont::getFontHeight ( void ) const
{
return this->coords.height;
}
IFont::FontStyle TrueTypeFont::getFontStyle ( void ) const
{
return this->text_style;
}
const Color4u& TrueTypeFont::getColor ( void ) const
{
return this->color;
}
const Coords& TrueTypeFont::getPosition ( void ) const
{
return this->coords;
}
uint32 TrueTypeFont::getNewline ( void ) const
{
// Not implemented
return 0;
}
uint32 TrueTypeFont::getSpacing ( void ) const
{
// Not implemented
return 0;
}
IFont::TextAlignment TrueTypeFont::getTextJustification ( void ) const
{
return this->text_alignment;
}
void TrueTypeFont::setColor ( const Color4u& color )
{
this->color = color;
}
void TrueTypeFont::setPosition ( const Coords& coords )
{
this->coords.x = coords.x;
this->coords.y = coords.y;
}
void TrueTypeFont::setFontSize ( int32 point_size )
{
int32 original_font_size = this->font_size;
this->font_size = point_size;
if ( this->rebuild() == false )
{
NOM_LOG_ERR ( NOM, "Could not set new font size." );
this->font_size = original_font_size;
return;
}
}
void TrueTypeFont::setFontStyle ( int32 style, uint8 options )
{
switch ( style )
{
default: break;
case FontStyle::Regular:
{
TTF_SetFontStyle ( this->font.get(), TTF_STYLE_NORMAL );
}
break;
case FontStyle::Bold:
{
TTF_SetFontStyle ( this->font.get(), TTF_STYLE_BOLD );
}
break;
case FontStyle::Italic:
{
TTF_SetFontStyle ( this->font.get(), TTF_STYLE_ITALIC );
}
break;
case FontStyle::Underlined:
{
TTF_SetFontStyle ( this->font.get(), TTF_STYLE_UNDERLINE );
}
break;
/// Text effect utilizing alpha channels for the appearance of gray text
case FontStyle::Faded:
{
this->text_style = FontStyle::Faded;
this->style_options = options;
break;
}
}
}
int32 TrueTypeFont::getFontOutline ( void ) const
{
return TTF_GetFontOutline ( this->font.get() );
}
void TrueTypeFont::setFontOutline ( int32 depth )
{
TTF_SetFontOutline ( this->font.get(), depth );
}
IFont::RenderStyle TrueTypeFont::getRenderingStyle ( void ) const
{
return this->rendering;
}
void TrueTypeFont::setRenderingStyle ( IFont::RenderStyle style )
{
this->rendering = style;
}
void TrueTypeFont::setText ( const std::string& text )
{
if ( text.length() < 1 ) return;
this->text_buffer = text;
// Update the width & height of text string, if we can
if ( TTF_SizeText ( this->font.get(), this->text_buffer.c_str(), &this->coords.width, &this->coords.height ) == -1 )
{
NOM_LOG_ERR ( NOM, "Failed to set font width & height." );
}
}
void TrueTypeFont::setSpacing ( uint32 spaces )
{
// Not implemented
}
void TrueTypeFont::setTextJustification ( IFont::TextAlignment alignment )
{
this->text_alignment = alignment;
}
bool TrueTypeFont::load ( const std::string& filename, const Color4u& colorkey,
bool use_cache
)
{
this->font = std::shared_ptr<TTF_Font> ( TTF_OpenFont ( filename.c_str(), this->font_size ), nom::priv::TTF_FreeFont );
if ( this->valid() == false )
{
NOM_LOG_ERR ( NOM, "Could not load TTF file: " + filename );
return false;
}
// Store the new filename & caching choice for future reference; primarily
// used when rebuilding font metrics, such as when we change the font point
// size or load a new font.
this->filename = filename;
this->use_cache = use_cache;
return true;
}
void TrueTypeFont::update ( void )
{
// Update display coordinates
this->font_buffer.set_position ( Point2i ( this->coords.x, this->coords.y ) );
// Update the rendered text surface here for drawing
if ( this->getText().c_str() == nullptr ) return;
if ( this->rendering == RenderStyle::Shaded ) // Moderate-quality
{
this->font_buffer.initialize ( TTF_RenderText_Shaded
(
this->font.get(),
this->getText().c_str(),
SDL_COLOR(this->color),
// TODO; implement me -- a second color
// possibility means needing two colors in
// class
SDL_COLOR ( Color4u ( 97, 97, 97 ) )
)
);
}
else if ( this->rendering == RenderStyle::Blended ) // Highest-quality
{
this->font_buffer.initialize ( TTF_RenderText_Blended
(
this->font.get(),
this->getText().c_str(),
SDL_COLOR(this->color)
)
);
}
else // Low-quality rendering (the default)
{
this->font_buffer.initialize ( TTF_RenderText_Solid
(
this->font.get(),
this->getText().c_str(),
SDL_COLOR(this->color)
)
);
}
if ( this->text_style == FontStyle::Faded )
{
this->font_buffer.set_alpha ( this->style_options );
}
}
void TrueTypeFont::draw ( SDL_Renderer* target ) const
{
if ( this->font_buffer.valid() )
{
this->font_buffer.draw ( target );
}
}
void TrueTypeFont::draw ( const Window& target ) const
{
if ( this->font_buffer.valid() )
{
this->font_buffer.draw ( target.renderer() );
}
}
bool TrueTypeFont::rebuild ( void )
{
if ( this->load ( this->filename, NOM_COLOR4U_BLACK, this->use_cache ) == false )
{
NOM_LOG_ERR ( NOM, "Could not rebuild font metrics." );
return false;
}
return true;
}
namespace priv {
void Free_TrueTypeFont ( TrueTypeFont* ptr )
{
// Do nothing custom deleter
//
// FIXME; this is a known bug (memory leak).
}
} // namespace priv
} // namespace nom
<commit_msg>TrueTypeFont: Add additional validity checks<commit_after>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include "nomlib/graphics/TrueTypeFont.hpp"
namespace nom {
TrueTypeFont::TrueTypeFont ( void )
{
NOM_LOG_TRACE ( NOM );
this->font = nullptr;
this->coords = Coords ( 0, 0, 0, 0 );
this->color = Color4u ( 0, 0, 0 );
this->text_buffer = "\0";
this->text_style = FontStyle::Regular; // default text styling effect
this->text_alignment = TextAlignment::MiddleLeft;
this->rendering = RenderStyle::Solid; // Fast, but ugly
this->style_options = 0;
this->filename = "\0";
this->font_size = 12;
this->use_cache = false;
}
TrueTypeFont::~TrueTypeFont ( void )
{
NOM_LOG_TRACE ( NOM );
}
IFont::SharedPtr TrueTypeFont::clone ( void ) const
{
return IFont::SharedPtr ( new TrueTypeFont ( *this ), priv::Free_TrueTypeFont );
}
bool TrueTypeFont::valid ( void ) const
{
if ( this->font.get() != nullptr )
{
return true;
}
else
{
return false;
}
}
const std::string& TrueTypeFont::getText ( void ) const
{
return this->text_buffer;
}
int32 TrueTypeFont::getFontWidth ( void ) const
{
return this->coords.width;
}
int32 TrueTypeFont::getFontHeight ( void ) const
{
return this->coords.height;
}
IFont::FontStyle TrueTypeFont::getFontStyle ( void ) const
{
return this->text_style;
}
const Color4u& TrueTypeFont::getColor ( void ) const
{
return this->color;
}
const Coords& TrueTypeFont::getPosition ( void ) const
{
return this->coords;
}
uint32 TrueTypeFont::getNewline ( void ) const
{
// Not implemented
return 0;
}
uint32 TrueTypeFont::getSpacing ( void ) const
{
// Not implemented
return 0;
}
IFont::TextAlignment TrueTypeFont::getTextJustification ( void ) const
{
return this->text_alignment;
}
void TrueTypeFont::setColor ( const Color4u& color )
{
this->color = color;
}
void TrueTypeFont::setPosition ( const Coords& coords )
{
this->coords.x = coords.x;
this->coords.y = coords.y;
}
void TrueTypeFont::setFontSize ( int32 point_size )
{
int32 original_font_size = this->font_size;
this->font_size = point_size;
if ( this->rebuild() == false )
{
NOM_LOG_ERR ( NOM, "Could not set new font size." );
this->font_size = original_font_size;
return;
}
}
void TrueTypeFont::setFontStyle ( int32 style, uint8 options )
{
switch ( style )
{
default: break;
case FontStyle::Regular:
{
TTF_SetFontStyle ( this->font.get(), TTF_STYLE_NORMAL );
}
break;
case FontStyle::Bold:
{
TTF_SetFontStyle ( this->font.get(), TTF_STYLE_BOLD );
}
break;
case FontStyle::Italic:
{
TTF_SetFontStyle ( this->font.get(), TTF_STYLE_ITALIC );
}
break;
case FontStyle::Underlined:
{
TTF_SetFontStyle ( this->font.get(), TTF_STYLE_UNDERLINE );
}
break;
/// Text effect utilizing alpha channels for the appearance of gray text
case FontStyle::Faded:
{
this->text_style = FontStyle::Faded;
this->style_options = options;
break;
}
}
}
int32 TrueTypeFont::getFontOutline ( void ) const
{
return TTF_GetFontOutline ( this->font.get() );
}
void TrueTypeFont::setFontOutline ( int32 depth )
{
TTF_SetFontOutline ( this->font.get(), depth );
}
IFont::RenderStyle TrueTypeFont::getRenderingStyle ( void ) const
{
return this->rendering;
}
void TrueTypeFont::setRenderingStyle ( IFont::RenderStyle style )
{
this->rendering = style;
}
void TrueTypeFont::setText ( const std::string& text )
{
if ( text.length() < 1 ) return;
this->text_buffer = text;
// Font is not valid -- TTF_SizeText will crash if we go further
if ( ! this->valid() ) return;
// Update the width & height of text string, if we can
if ( TTF_SizeText ( this->font.get(), this->text_buffer.c_str(), &this->coords.width, &this->coords.height ) == -1 )
{
NOM_LOG_ERR ( NOM, "Failed to set font width & height." );
}
}
void TrueTypeFont::setSpacing ( uint32 spaces )
{
// Not implemented
}
void TrueTypeFont::setTextJustification ( IFont::TextAlignment alignment )
{
this->text_alignment = alignment;
}
bool TrueTypeFont::load ( const std::string& filename, const Color4u& colorkey,
bool use_cache
)
{
this->font = std::shared_ptr<TTF_Font> ( TTF_OpenFont ( filename.c_str(), this->font_size ), nom::priv::TTF_FreeFont );
if ( this->valid() == false )
{
NOM_LOG_ERR ( NOM, "Could not load TTF file: " + filename );
return false;
}
// Store the new filename & caching choice for future reference; primarily
// used when rebuilding font metrics, such as when we change the font point
// size or load a new font.
this->filename = filename;
this->use_cache = use_cache;
return true;
}
void TrueTypeFont::update ( void )
{
// Font is not valid -- nothing to draw
if ( ! this->valid() ) return;
// No text string set -- nothing to draw
if ( this->getText().length() < 1 ) return;
// Update display coordinates
this->font_buffer.set_position ( Point2i ( this->coords.x, this->coords.y ) );
// Update the rendered text surface here for drawing
if ( this->rendering == RenderStyle::Shaded ) // Moderate-quality
{
this->font_buffer.initialize ( TTF_RenderText_Shaded
(
this->font.get(),
this->getText().c_str(),
SDL_COLOR(this->color),
// TODO; implement me -- a second color
// possibility means needing two colors in
// class
SDL_COLOR ( Color4u ( 97, 97, 97 ) )
)
);
}
else if ( this->rendering == RenderStyle::Blended ) // Highest-quality
{
this->font_buffer.initialize ( TTF_RenderText_Blended
(
this->font.get(),
this->getText().c_str(),
SDL_COLOR(this->color)
)
);
}
else // Low-quality rendering (the default)
{
this->font_buffer.initialize ( TTF_RenderText_Solid
(
this->font.get(),
this->getText().c_str(),
SDL_COLOR(this->color)
)
);
}
if ( this->text_style == FontStyle::Faded )
{
this->font_buffer.set_alpha ( this->style_options );
}
}
void TrueTypeFont::draw ( SDL_Renderer* target ) const
{
if ( this->font_buffer.valid() )
{
this->font_buffer.draw ( target );
}
}
void TrueTypeFont::draw ( const Window& target ) const
{
if ( this->font_buffer.valid() )
{
this->font_buffer.draw ( target.renderer() );
}
}
bool TrueTypeFont::rebuild ( void )
{
if ( this->load ( this->filename, NOM_COLOR4U_BLACK, this->use_cache ) == false )
{
NOM_LOG_ERR ( NOM, "Could not rebuild font metrics." );
return false;
}
return true;
}
namespace priv {
void Free_TrueTypeFont ( TrueTypeFont* ptr )
{
// Do nothing custom deleter
//
// FIXME; this is a known bug (memory leak).
}
} // namespace priv
} // namespace nom
<|endoftext|>
|
<commit_before><commit_msg>only one constructor with defaults<commit_after><|endoftext|>
|
<commit_before>#include "mainwindow.hxx"
#include <QApplication>
#include <windows.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
<commit_msg>minor source code cleanup<commit_after>#include "mainwindow.hxx"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
<|endoftext|>
|
<commit_before>AliAnalysisTaskElectronEfficiencyV2* AddTask_rbailhac_ElectronEfficiencyV2_PbPb(Bool_t getFromAlien = kFALSE,
TString cFileName ="Config_rbailhac_ElectronEfficiencyV2_PbPb.C",
UInt_t trigger = AliVEvent::kINT7,
Int_t rejpileup = 1,
const Int_t CenMin = 0,
const Int_t CenMax = 10,
const Float_t PtMin = 0.2,
const Float_t PtMax = 10.0,
const Float_t EtaMin = -0.8,
const Float_t EtaMax = +0.8,
const Bool_t UsePtVec = kTRUE,
const Bool_t DoULSLS = kTRUE,
const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;",
const std::string resolutionFilename ="",
const std::string cocktailFilename ="",
const std::string centralityFilename ="",
const TString outname = "LMEE.root")
{
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_rbailhac_test", "No analysis manager found.");
return 0;
}
//Base Directory for GRID / LEGO Train
TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";
if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/r/rbailhac/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) ){
configBasePath=Form("%s/",gSystem->pwd());
}
TString configFilePath(configBasePath+cFileName);
std::cout << "Configpath: " << configFilePath << std::endl;
if (!gROOT->GetListOfGlobalFunctions()->FindObject("Config_rbailhac_ElectronEfficiencyV2_PbPb")) {
printf("Load macro now\n");
gROOT->LoadMacro(configFilePath.Data());
}
// trigger
TString triggername = "NULL";
if(trigger == (UInt_t)AliVEvent::kINT7) triggername = "kINT7";
else if(trigger == (UInt_t)AliVEvent::kCentral) triggername = "kCentral";
else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral";
else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers";
else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral)) triggername = "kCombinedCentral";
else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral)) triggername = "kCombinedSemiCentral";
// generators
TString suffixgen = "";
if(generators.Contains("Pythia CC") && (generators.Contains("Pythia BB") || generators.Contains("Pythia B"))) suffixgen = "_CC_BB";
else if(generators.Contains("Pythia CC")) suffixgen = "_CC";
else if(generators.Contains("Pythia BB") || generators.Contains("Pythia B")) suffixgen = "_BB";
else if(generators.Contains("pizero_0")) suffixgen = "_LF";
else suffixgen = "";
// generator index
TString suffixgenID = "";
std::vector<UInt_t> genID;
const Int_t ngenID = (Int_t)gROOT->ProcessLine("GetGenID()");
if(ngenID > 0) {
for (unsigned int i = 0; i < ngenID+1; ++i){
UInt_t valuegenID = (UInt_t)(gROOT->ProcessLine(Form("GetGenID(%d)",i)));
genID.push_back(valuegenID);
suffixgenID += valuegenID;
}
}
//create task and add it to the manager (MB)
TString appendix;
appendix += TString::Format("Cen%d_%d_%s_%s_%s_Pileup%d",CenMin,CenMax,triggername.Data(),suffixgen.Data(),suffixgenID.Data(),rejpileup);
printf("appendix %s\n", appendix.Data());
//##########################################################
//############################################################
// Creating an instance of the task
AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2_%s",appendix.Data()));
gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal);
// #########################################################
// #########################################################
// Set TOF correction
// if(tofcor){
// SetEtaCorrectionTOFRMS(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta);
// SetEtaCorrectionTOFMean(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta);
//}
// #########################################################
// #########################################################
// Event selection. Is the same for all the different cutsettings
task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC.
task->SetTriggerMask(trigger);
task->SetEventFilter((reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("GetEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,rejpileup,"V0M")))));
// #########################################################
// #########################################################
// Set minimum and maximum values of generated tracks. Only used to save computing power.
// Do not set here your analysis pt-cuts
task->SetMinPtGen(0.1);
task->SetMaxPtGen(1e+10);
task->SetMinEtaGen(-1.5);
task->SetMaxEtaGen(+1.5);
// #########################################################
// #########################################################
// Set minimum and maximum values for pairing
task->SetKinematicCuts(PtMin, PtMax, EtaMin, EtaMax);
// #########################################################
// #########################################################
// Set Binning single variables
if (UsePtVec == true) {
const Int_t Npt = 68;
Double_t pte[Npt] = {0.00,0.10,0.11,0.12,0.13,0.14,0.15,0.155,0.16,0.165,0.17,0.175,0.18,0.185,0.19,0.195,0.20,0.205,0.21,0.215,0.22,0.225,0.23,0.235,0.24,0.245,0.25,0.255,0.26,0.265,0.27,0.275,0.28,0.285,0.29,0.295,0.30,0.32,0.34,0.36,0.38,0.40,0.43,0.46,0.49,0.52,0.55,0.60,0.65,0.70,0.75,0.80,0.90,1.00,1.10,1.20,1.40,1.60,1.80,2.00,2.40,2.80,3.20,3.70,4.50,6.00,8.00,12.0};
std::vector<double> v_pte(pte,std::end(pte));
task->SetPtBins(v_pte);
}
else task->SetPtBinsLinear (0, 10, 100);
task->SetEtaBinsLinear (-1.,1.,20); // 40 before
task->SetPhiBinsLinear (0, TMath::TwoPi(), 36); // 90 before
task->SetThetaBinsLinear(0, TMath::TwoPi(), 60);
// pair variables
const Int_t Nmee = 150;
Double_t mee[Nmee] = {};
for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.09 GeV/c2, every 0.01 GeV/c2
for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2
std::vector<double> v_mee(mee,std::end(mee));
const Int_t NpTee = 130;
Double_t pTee[NpTee] = {};
for(Int_t i=0 ;i<20 ;i++) pTee[i] = 0.005 * (i- 0) + 0.0;//from 0 to 0.095 GeV/c, every 0.005 GeV/c
for(Int_t i=20 ;i<119 ;i++) pTee[i] = 0.1 * (i- 20) + 0.1;//from 0.1 to 9.9 GeV/c, evety 0.1 GeV/c
for(Int_t i=119;i<NpTee;i++) pTee[i] = 1.0 * (i-119) + 10.0;//from 10 to 20 GeV/c, evety 1.0 GeV/c
std::vector<double> v_pTee(pTee,std::end(pTee));
task->SetMassBins(v_mee);
task->SetPairPtBins(v_pTee);
//task->SetPhiVBinsLinear(0, TMath::Pi(), 100);
//task->SetFillPhiV(kTRUE);
// #########################################################
// #########################################################
//task->SetSmearGenerated(kFALSE); // cross check smearing the MC at single level and filling resolution maps
// Resolution File, If resoFilename = "" no correction is applied
task->SetResolutionFile(resolutionFilename);
task->SetResolutionFileFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + resolutionFilename);
task->SetResolutionDeltaPtBinsLinear (-10., 2., (Int_t)gROOT->ProcessLine("GetNbinsDeltaMom()"));
task->SetResolutionRelPtBinsLinear (0., 2., (Int_t)gROOT->ProcessLine("GetNbinsRelMom()"));
task->SetResolutionEtaBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaEta()"));
task->SetResolutionPhiBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaPhi()"));
task->SetResolutionThetaBinsLinear(-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaTheta()"));
//###########################################################
//############################################################
// Set MCSignal and Cutsetting to fill the support histograms
task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting
// #########################################################
// #########################################################
// Set centrality correction. If resoFilename = "" no correction is applied
task->SetCentralityFile(centralityFilename);
// #########################################################
// #########################################################
// Pairing related config
task->SetDoPairing(kTRUE);
task->SetULSandLS(DoULSLS);
//#####################################################
//######################################################
// Generators
cout<<"Efficiency based on MC generators: " << generators <<endl;
TString generatorsPair=generators;
task->SetGeneratorMCSignalName(generatorsPair);
task->SetGeneratorULSSignalName(generators);
//#################################################
//#################################################
// generator ID to select pile-up or not
if(ngenID > 0) {
task->SetGeneratorMCSignalIndex(genID);
task->SetGeneratorULSSignalIndex(genID);
task->SetCheckGenID(kTRUE);
}
//###############################################
//##############################################
task->SetCocktailWeighting(cocktailFilename);
task->SetCocktailWeightingFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + cocktailFilename);
// #########################################################
// #########################################################
// Add MCSignals. Can be set to see differences of:
// e.g. secondaries and primaries. or primaries from charm and resonances
gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name
gROOT->ProcessLine(Form("AddPairMCSignal(%s)" ,task->GetName()));//not task itself, task name
// #########################################################
// #########################################################
// Adding cutsettings
// Cuts
// Number of cuts
const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()");
//add dielectron analysis with different cuts to the task
for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_rbailhac_ElectronEfficiencyV2_PbPb(%d)",i)));
task->AddTrackCuts(filter);
}
//########################################
//########################################
TString outlistname = Form("efficiency_%s",appendix.Data());
const TString fileName = outname;
mgr->AddTask(task);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data())));
return task;
}
<commit_msg>Add PID MC post calibration<commit_after>AliAnalysisTaskElectronEfficiencyV2* AddTask_rbailhac_ElectronEfficiencyV2_PbPb(Bool_t getFromAlien = kFALSE,
TString cFileName ="Config_rbailhac_ElectronEfficiencyV2_PbPb.C",
UInt_t trigger = AliVEvent::kINT7,
Int_t rejpileup = 1,
const Int_t CenMin = 0,
const Int_t CenMax = 10,
const Float_t PtMin = 0.2,
const Float_t PtMax = 10.0,
const Float_t EtaMin = -0.8,
const Float_t EtaMax = +0.8,
const Bool_t UsePtVec = kTRUE,
const Bool_t DoULSLS = kTRUE,
const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;",
const std::string resolutionFilename ="",
const std::string cocktailFilename ="",
const std::string centralityFilename ="",
TString calibFileName = "",
const TString outname = "LMEE.root")
{
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_rbailhac_test", "No analysis manager found.");
return 0;
}
//Base Directory for GRID / LEGO Train
TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";
if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/r/rbailhac/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) ){
configBasePath=Form("%s/",gSystem->pwd());
}
TString configFilePath(configBasePath+cFileName);
std::cout << "Configpath: " << configFilePath << std::endl;
if (!gROOT->GetListOfGlobalFunctions()->FindObject("Config_rbailhac_ElectronEfficiencyV2_PbPb")) {
printf("Load macro now\n");
gROOT->LoadMacro(configFilePath.Data());
}
// trigger
TString triggername = "NULL";
if(trigger == (UInt_t)AliVEvent::kINT7) triggername = "kINT7";
else if(trigger == (UInt_t)AliVEvent::kCentral) triggername = "kCentral";
else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral";
else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers";
else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral)) triggername = "kCombinedCentral";
else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral)) triggername = "kCombinedSemiCentral";
// generators
TString suffixgen = "";
if(generators.Contains("Pythia CC") && (generators.Contains("Pythia BB") || generators.Contains("Pythia B"))) suffixgen = "_CC_BB";
else if(generators.Contains("Pythia CC")) suffixgen = "_CC";
else if(generators.Contains("Pythia BB") || generators.Contains("Pythia B")) suffixgen = "_BB";
else if(generators.Contains("pizero_0")) suffixgen = "_LF";
else suffixgen = "";
// generator index
TString suffixgenID = "";
std::vector<UInt_t> genID;
const Int_t ngenID = (Int_t)gROOT->ProcessLine("GetGenID()");
if(ngenID > 0) {
for (unsigned int i = 0; i < ngenID+1; ++i){
UInt_t valuegenID = (UInt_t)(gROOT->ProcessLine(Form("GetGenID(%d)",i)));
genID.push_back(valuegenID);
suffixgenID += valuegenID;
}
}
//create task and add it to the manager (MB)
TString appendix;
appendix += TString::Format("Cen%d_%d_%s_%s_%s_Pileup%d",CenMin,CenMax,triggername.Data(),suffixgen.Data(),suffixgenID.Data(),rejpileup);
printf("appendix %s\n", appendix.Data());
//##########################################################
//############################################################
// Creating an instance of the task
AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2_%s",appendix.Data()));
gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal);
// #########################################################
// #########################################################
// Set TOF correction
// if(tofcor){
// SetEtaCorrectionTOFRMS(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta);
// SetEtaCorrectionTOFMean(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta);
//}
// #########################################################
// #########################################################
// Event selection. Is the same for all the different cutsettings
task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC.
task->SetTriggerMask(trigger);
task->SetEventFilter((reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("GetEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,rejpileup,"V0M")))));
// #########################################################
// #########################################################
// Set minimum and maximum values of generated tracks. Only used to save computing power.
// Do not set here your analysis pt-cuts
task->SetMinPtGen(0.1);
task->SetMaxPtGen(1e+10);
task->SetMinEtaGen(-1.5);
task->SetMaxEtaGen(+1.5);
// #########################################################
// #########################################################
// Set minimum and maximum values for pairing
task->SetKinematicCuts(PtMin, PtMax, EtaMin, EtaMax);
// #########################################################
// #########################################################
// Set Binning single variables
if (UsePtVec == true) {
const Int_t Npt = 68;
Double_t pte[Npt] = {0.00,0.10,0.11,0.12,0.13,0.14,0.15,0.155,0.16,0.165,0.17,0.175,0.18,0.185,0.19,0.195,0.20,0.205,0.21,0.215,0.22,0.225,0.23,0.235,0.24,0.245,0.25,0.255,0.26,0.265,0.27,0.275,0.28,0.285,0.29,0.295,0.30,0.32,0.34,0.36,0.38,0.40,0.43,0.46,0.49,0.52,0.55,0.60,0.65,0.70,0.75,0.80,0.90,1.00,1.10,1.20,1.40,1.60,1.80,2.00,2.40,2.80,3.20,3.70,4.50,6.00,8.00,12.0};
std::vector<double> v_pte(pte,std::end(pte));
task->SetPtBins(v_pte);
}
else task->SetPtBinsLinear (0, 10, 100);
task->SetEtaBinsLinear (-1.,1.,20); // 40 before
task->SetPhiBinsLinear (0, TMath::TwoPi(), 36); // 90 before
task->SetThetaBinsLinear(0, TMath::TwoPi(), 60);
// pair variables
const Int_t Nmee = 150;
Double_t mee[Nmee] = {};
for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.09 GeV/c2, every 0.01 GeV/c2
for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2
std::vector<double> v_mee(mee,std::end(mee));
const Int_t NpTee = 130;
Double_t pTee[NpTee] = {};
for(Int_t i=0 ;i<20 ;i++) pTee[i] = 0.005 * (i- 0) + 0.0;//from 0 to 0.095 GeV/c, every 0.005 GeV/c
for(Int_t i=20 ;i<119 ;i++) pTee[i] = 0.1 * (i- 20) + 0.1;//from 0.1 to 9.9 GeV/c, evety 0.1 GeV/c
for(Int_t i=119;i<NpTee;i++) pTee[i] = 1.0 * (i-119) + 10.0;//from 10 to 20 GeV/c, evety 1.0 GeV/c
std::vector<double> v_pTee(pTee,std::end(pTee));
task->SetMassBins(v_mee);
task->SetPairPtBins(v_pTee);
//task->SetPhiVBinsLinear(0, TMath::Pi(), 100);
//task->SetFillPhiV(kTRUE);
// #########################################################
// #########################################################
//task->SetSmearGenerated(kFALSE); // cross check smearing the MC at single level and filling resolution maps
// Resolution File, If resoFilename = "" no correction is applied
task->SetResolutionFile(resolutionFilename);
task->SetResolutionFileFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + resolutionFilename);
task->SetResolutionDeltaPtBinsLinear (-10., 2., (Int_t)gROOT->ProcessLine("GetNbinsDeltaMom()"));
task->SetResolutionRelPtBinsLinear (0., 2., (Int_t)gROOT->ProcessLine("GetNbinsRelMom()"));
task->SetResolutionEtaBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaEta()"));
task->SetResolutionPhiBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaPhi()"));
task->SetResolutionThetaBinsLinear(-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaTheta()"));
//###########################################################
//############################################################
// Set MCSignal and Cutsetting to fill the support histograms
task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting
// #########################################################
// #########################################################
// Set centrality correction. If resoFilename = "" no correction is applied
task->SetCentralityFile(centralityFilename);
// #########################################################
// #########################################################
// Pairing related config
task->SetDoPairing(kTRUE);
task->SetULSandLS(DoULSLS);
//#####################################################
//######################################################
// Generators
cout<<"Efficiency based on MC generators: " << generators <<endl;
TString generatorsPair=generators;
task->SetGeneratorMCSignalName(generatorsPair);
task->SetGeneratorULSSignalName(generators);
//#################################################
//#################################################
// generator ID to select pile-up or not
if(ngenID > 0) {
task->SetGeneratorMCSignalIndex(genID);
task->SetGeneratorULSSignalIndex(genID);
task->SetCheckGenID(kTRUE);
}
//###############################################
//##############################################
task->SetCocktailWeighting(cocktailFilename);
task->SetCocktailWeightingFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + cocktailFilename);
// #########################################################
// #########################################################
// Add MCSignals. Can be set to see differences of:
// e.g. secondaries and primaries. or primaries from charm and resonances
gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name
gROOT->ProcessLine(Form("AddPairMCSignal(%s)" ,task->GetName()));//not task itself, task name
// #########################################################
// #########################################################
// PID postcalibration
TH3D *hs_mean_ITS_El = 0x0;
TH3D *hs_width_ITS_El = 0x0;
TH3D *hs_mean_TOF_El = 0x0;
TH3D *hs_width_TOF_El = 0x0;
// PID post-calibration
TFile *rootfile = 0x0;
if(calibFileName.Contains("MC")){
printf("reading : %s for PID calibration\n",calibFileName.Data());
rootfile = TFile::Open(calibFileName,"READ");
hs_mean_ITS_El = (TH3D*)rootfile->Get("h3mean_ITS");
hs_width_ITS_El = (TH3D*)rootfile->Get("h3width_ITS");
hs_mean_TOF_El = (TH3D*)rootfile->Get("h3mean_TOF");
hs_width_TOF_El = (TH3D*)rootfile->Get("h3width_TOF");
if(hs_mean_ITS_El) {
cout<<"Adding mean ITS PID correction" <<endl;
task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, hs_mean_ITS_El, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);
}
if(hs_mean_TOF_El) {
cout<<"Adding mean TOF PID correction" <<endl;
task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, hs_mean_TOF_El, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);
}
if(hs_width_ITS_El) {
cout<<"Adding width ITS PID correction" <<endl;
task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, hs_width_ITS_El, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);
}
if(hs_width_TOF_El) {
cout<<"Adding width TOF PID correction" <<endl;
task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, hs_width_TOF_El, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);
}
}
// #########################################################
// #########################################################
// Adding cutsettings
// Cuts
// Number of cuts
const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()");
//add dielectron analysis with different cuts to the task
for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_rbailhac_ElectronEfficiencyV2_PbPb(%d)",i)));
task->AddTrackCuts(filter);
}
//########################################
//########################################
TString outlistname = Form("efficiency_%s",appendix.Data());
const TString fileName = outname;
mgr->AddTask(task);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data())));
return task;
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "InterfaceOrientationMaterial.h"
#include "MooseMesh.h"
template<>
InputParameters validParams<InterfaceOrientationMaterial>()
{
InputParameters params = validParams<Material>();
params.addParam<Real>("anisotropy_strength", 0.04, "Strength of the anisotropy (typically < 0.05)");
params.addParam<unsigned int>("mode_number", 6, "Mode number for anisotropy");
params.addParam<Real>("reference_angle", 90, "Reference angle for defining anistropy in degrees");
params.addParam<Real>("eps_bar", 0.01, "Average value of the interface parameter epsilon");
params.addRequiredCoupledVar("op", "Order parameter defining the solid phase");
return params;
}
InterfaceOrientationMaterial::InterfaceOrientationMaterial(const InputParameters & parameters) :
Material(parameters),
_delta(getParam<Real>("anisotropy_strength")),
_j(getParam<unsigned int>("mode_number")),
_theta0(getParam<Real>("reference_angle")),
_eps_bar(getParam<Real>("eps_bar")),
_eps(declareProperty<Real>("eps")),
_deps(declareProperty<Real>("deps")),
_depsdgrad_op(declareProperty<RealGradient>("depsdgrad_op")),
_ddepsdgrad_op(declareProperty<RealGradient>("ddepsdgrad_op")),
_op(coupledValue("op")),
_grad_op(coupledGradient("op"))
{
// this currently only works in 2D simulations
if (_mesh.dimension() != 2)
mooseError("InterfaceOrientationMaterial requires a two-dimensional mesh.");
}
void
InterfaceOrientationMaterial::computeQpProperties()
{
Real cutoff = 0.99999;
// cosine of the gradient orientation angle
Real n;
if (_grad_op[_qp].norm() == 0)
n = 0;
else
n = _grad_op[_qp](0) / _grad_op[_qp].norm();
if (n > cutoff)
n = cutoff;
if (n < -cutoff)
n = -cutoff;
const Real angle = std::acos(n);
// Compute derivative of angle wrt n
const Real dangledn = - 1.0 / std::sqrt(1.0 - n * n);
// Compute derivative of n with respect to grad_op
RealGradient dndgrad_op;
if (_grad_op[_qp].norm_sq() == 0)
dndgrad_op = 0;
else
{
dndgrad_op(0) = _grad_op[_qp](1) * _grad_op[_qp](1);
dndgrad_op(1) = - _grad_op[_qp](0) * _grad_op[_qp](1);
dndgrad_op /= (_grad_op[_qp].norm_sq() * _grad_op[_qp].norm());
}
// Calculate interfacial parameter epsilon and its derivatives
_eps[_qp]= _eps_bar * (_delta * std::cos(_j * (angle - _theta0 * libMesh::pi/180.0)) + 1.0);
_deps[_qp]= - _eps_bar * _delta * _delta * std::sin(_j * (angle - _theta0 * libMesh::pi/180.0));
Real d2eps = - _eps_bar * _delta * _delta * _delta * std::cos(_j * (angle - _theta0 * libMesh::pi/180.0));
// Compute derivatives of epsilon and its derivative wrt grad_op
_depsdgrad_op[_qp] = _deps[_qp] * dangledn * dndgrad_op;
_ddepsdgrad_op[_qp] = d2eps * dangledn * dndgrad_op;
}
<commit_msg>Fix angle sign and derivative (#6893)<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "InterfaceOrientationMaterial.h"
#include "MooseMesh.h"
#include "MathUtils.h"
template<>
InputParameters validParams<InterfaceOrientationMaterial>()
{
InputParameters params = validParams<Material>();
params.addParam<Real>("anisotropy_strength", 0.04, "Strength of the anisotropy (typically < 0.05)");
params.addParam<unsigned int>("mode_number", 6, "Mode number for anisotropy");
params.addParam<Real>("reference_angle", 90, "Reference angle for defining anistropy in degrees");
params.addParam<Real>("eps_bar", 0.01, "Average value of the interface parameter epsilon");
params.addRequiredCoupledVar("op", "Order parameter defining the solid phase");
return params;
}
InterfaceOrientationMaterial::InterfaceOrientationMaterial(const InputParameters & parameters) :
Material(parameters),
_delta(getParam<Real>("anisotropy_strength")),
_j(getParam<unsigned int>("mode_number")),
_theta0(getParam<Real>("reference_angle")),
_eps_bar(getParam<Real>("eps_bar")),
_eps(declareProperty<Real>("eps")),
_deps(declareProperty<Real>("deps")),
_depsdgrad_op(declareProperty<RealGradient>("depsdgrad_op")),
_ddepsdgrad_op(declareProperty<RealGradient>("ddepsdgrad_op")),
_op(coupledValue("op")),
_grad_op(coupledGradient("op"))
{
// this currently only works in 2D simulations
if (_mesh.dimension() != 2)
mooseError("InterfaceOrientationMaterial requires a two-dimensional mesh.");
}
void
InterfaceOrientationMaterial::computeQpProperties()
{
Real cutoff = 0.99999;
// cosine of the gradient orientation angle
Real n;
if (_grad_op[_qp].norm_sq() == 0)
n = 0;
else
n = _grad_op[_qp](0) / _grad_op[_qp].norm();
if (n > cutoff)
n = cutoff;
if (n < -cutoff)
n = -cutoff;
const Real angle = std::acos(n) * MathUtils::sign(_grad_op[_qp](1));
// Compute derivative of angle wrt n
const Real dangledn = - MathUtils::sign(_grad_op[_qp](1)) / std::sqrt(1.0 - n * n);
// Compute derivative of n with respect to grad_op
RealGradient dndgrad_op;
if (_grad_op[_qp].norm_sq() == 0)
dndgrad_op = 0;
else
{
dndgrad_op(0) = _grad_op[_qp](1) * _grad_op[_qp](1);
dndgrad_op(1) = - _grad_op[_qp](0) * _grad_op[_qp](1);
dndgrad_op /= (_grad_op[_qp].norm_sq() * _grad_op[_qp].norm());
}
// Calculate interfacial parameter epsilon and its derivatives
_eps[_qp]= _eps_bar * (_delta * std::cos(_j * (angle - _theta0 * libMesh::pi/180.0)) + 1.0);
_deps[_qp]= - _eps_bar * _delta * _j * std::sin(_j * (angle - _theta0 * libMesh::pi/180.0));
Real d2eps = - _eps_bar * _delta * _j * _j * std::cos(_j * (angle - _theta0 * libMesh::pi/180.0));
// Compute derivatives of epsilon and its derivative wrt grad_op
_depsdgrad_op[_qp] = _deps[_qp] * dangledn * dndgrad_op;
_ddepsdgrad_op[_qp] = d2eps * dangledn * dndgrad_op;
}
<|endoftext|>
|
<commit_before>#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include "io.hh"
#include "conf.hh"
#include "LM.hh"
using namespace std;
using namespace fsalm;
int main(int argc, char* argv[]) {
conf::Config config;
config("usage: strscore [OPTION...] ARPAFILE INPUT OUTPUT\n")
('h', "help", "", "", "display help");
config.default_parse(argc, argv);
if (config.arguments.size() != 3) config.print_help(stderr, 1);
string arpafname = config.arguments[0];
string infname = config.arguments[1];
string outfname = config.arguments[2];
LM lm;
lm.read_arpa(io::Stream(arpafname, "r").file, true);
lm.trim();
ifstream infile(infname);
if (!infile) {
cerr << "Something went wrong opening the input file." << endl;
exit(0);
}
ofstream outfile(outfname);
if (!outfile) {
cerr << "Something went wrong opening the output file." << endl;
exit(0);
}
int count;
string line, lstr;
while (getline(infile, line)) {
stringstream ss(line);
ss >> count;
ss >> lstr;
float total_prob = 0.0;
int node_id = lm.empty_node_id();
for (int i=0; i<lstr.length(); i++) {
int sym = lm.symbol_map().index(lstr.substr(i, 1));
float curr_prob = 0.0;
node_id = lm.walk(node_id, sym, &curr_prob);
total_prob += curr_prob;
}
total_prob *= log(10.0); // Convert from log10 (ARPA default) to ln
outfile << total_prob << "\t" << lstr << endl;
}
infile.close();
outfile.close();
exit(1);
}
<commit_msg>Normalize the scores.<commit_after>#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include <utility>
#include "defs.hh"
#include "io.hh"
#include "conf.hh"
#include "LM.hh"
using namespace std;
using namespace fsalm;
int main(int argc, char* argv[]) {
conf::Config config;
config("usage: strscore [OPTION...] ARPAFILE INPUT OUTPUT\n")
('h', "help", "", "", "display help");
config.default_parse(argc, argv);
if (config.arguments.size() != 3) config.print_help(stderr, 1);
string arpafname = config.arguments[0];
string infname = config.arguments[1];
string outfname = config.arguments[2];
LM lm;
lm.read_arpa(io::Stream(arpafname, "r").file, true);
lm.trim();
ifstream infile(infname);
if (!infile) {
cerr << "Something went wrong opening the input file." << endl;
exit(0);
}
ofstream outfile(outfname);
if (!outfile) {
cerr << "Something went wrong opening the output file." << endl;
exit(0);
}
int count;
string line, lstr;
vector<pair<string, float> > scores;
float normalizer = SMALL_LP;
while (getline(infile, line)) {
stringstream ss(line);
ss >> count;
ss >> lstr;
float total_prob = 0.0;
int node_id = lm.empty_node_id();
for (int i=0; i<lstr.length(); i++) {
int sym = lm.symbol_map().index(lstr.substr(i, 1));
float curr_prob = 0.0;
node_id = lm.walk(node_id, sym, &curr_prob);
total_prob += curr_prob;
}
total_prob *= log(10.0); // Convert from log10 (ARPA default) to ln
normalizer = add_log_domain_probs(normalizer, total_prob);
scores.push_back(make_pair(lstr, total_prob));
}
for (auto it=scores.begin(); it != scores.end(); ++it)
outfile << it->second-normalizer << "\t" << it->first << endl;
infile.close();
outfile.close();
exit(1);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Library
Module: PolyMap.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
//
// Methods for polygon mapper
//
#include "PolyMap.hh"
vlPolyMapper::vlPolyMapper()
{
this->Input = 0;
this->Verts = 0;
this->Lines = 0;
this->Polys = 0;
this->Strips = 0;
this->VertsVisibility = 1;
this->LinesVisibility = 1;
this->PolysVisibility = 1;
this->StripsVisibility = 1;
}
vlPolyMapper::~vlPolyMapper()
{
if ( this->Input != 0 )
{
this->Input->UnRegister((void *)this);
}
}
void vlPolyMapper::SetInput(vlPolyData *in)
{
if (in != this->Input )
{
this->Input = in;
this->Input->Register((void *)this);
this->Modified();
}
}
vlPolyData* vlPolyMapper::GetInput()
{
return this->Input;
}
//
// Return bounding box of data
//
float *vlPolyMapper::GetBounds()
{
static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};
if ( ! this->Input )
return bounds;
else
{
this->Input->Update();
return this->Input->GetBounds();
}
}
//
// Receives from Actor -> maps data to primitives
//
void vlPolyMapper::Render(vlRenderer *ren)
{
vlPointData *pd;
vlRGBArray *colors;
vlScalars *scalars;
int i;
char forceBuild = 0;
//
// make sure that we've been properly initialized
//
if ( ! this->Input )
{
vlErrorMacro(<< "No input!\n");
return;
}
else
this->Input->Update();
if ( ! this->LookupTable ) this->LookupTable = new vlLookupTable;
this->LookupTable->Build();
if ( ! this->Polys )
{
forceBuild = 1;
this->Verts = ren->GetPrimitive("points");
this->Lines = ren->GetPrimitive("lines");
this->Polys = ren->GetPrimitive("polygons");
this->Strips = ren->GetPrimitive("triangle_strips");
}
//
// Now send data down to primitives and draw it
//
if ( forceBuild || this->Input->GetMTime() > this->BuildTime ||
this->LookupTable->GetMTime() > this->BuildTime )
{
//
// create colors
//
if ( this->ScalarsVisible && (pd=this->Input->GetPointData()) &&
(scalars=pd->GetScalars()) )
{
colors = new vlRGBArray;
colors->Initialize (this->Input->NumberOfPoints());
this->LookupTable->SetTableRange(this->ScalarRange);
for (i=0; i<this->Input->NumberOfPoints(); i++)
{
colors->SetColor(i,this->LookupTable->MapValue(scalars->GetScalar(i)));
}
}
else
{
colors = 0;
}
//
// Cause primitives to build themselves
//
this->Verts->Build(this->Input,colors);
this->Lines->Build(this->Input,colors);
this->Polys->Build(this->Input,colors);
this->Strips->Build(this->Input,colors);
this->BuildTime.Modified();
}
if ( this->VertsVisibility ) this->Verts->Draw(ren);
if ( this->LinesVisibility ) this->Lines->Draw(ren);
if ( this->PolysVisibility ) this->Polys->Draw(ren);
if ( this->StripsVisibility ) this->Strips->Draw(ren);
}
void vlPolyMapper::PrintSelf(ostream& os, vlIndent indent)
{
if (this->ShouldIPrint(vlPolyMapper::GetClassName()))
{
vlMapper::PrintSelf(os,indent);
if ( this->Input )
{
os << indent << "Input: (" << this->Input << ")\n";
}
else
{
os << indent << "Input: (none)\n";
}
os << indent << "Vertex Visibility: " << (this->VertsVisibility ? "On\n" : "Off\n");
os << indent << "Line Visibility: " << (this->LinesVisibility ? "On\n" : "Off\n");
os << indent << "Polygon Visibility: " << (this->PolysVisibility ? "On\n" : "Off\n");
os << indent << "Triangle Strip Visibility: " << (this->StripsVisibility ? "On\n" : "Off\n");
}
}
<commit_msg>Fixed some allocation problems<commit_after>/*=========================================================================
Program: Visualization Library
Module: PolyMap.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
//
// Methods for polygon mapper
//
#include "PolyMap.hh"
vlPolyMapper::vlPolyMapper()
{
this->Input = 0;
this->Verts = 0;
this->Lines = 0;
this->Polys = 0;
this->Strips = 0;
this->VertsVisibility = 1;
this->LinesVisibility = 1;
this->PolysVisibility = 1;
this->StripsVisibility = 1;
}
vlPolyMapper::~vlPolyMapper()
{
if ( this->Input != 0 )
{
this->Input->UnRegister((void *)this);
}
}
void vlPolyMapper::SetInput(vlPolyData *in)
{
if (in != this->Input )
{
this->Input = in;
this->Input->Register((void *)this);
this->Modified();
}
}
vlPolyData* vlPolyMapper::GetInput()
{
return this->Input;
}
//
// Return bounding box of data
//
float *vlPolyMapper::GetBounds()
{
static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};
if ( ! this->Input )
return bounds;
else
{
this->Input->Update();
return this->Input->GetBounds();
}
}
//
// Receives from Actor -> maps data to primitives
//
void vlPolyMapper::Render(vlRenderer *ren)
{
vlPointData *pd;
vlRGBArray *colors;
vlScalars *scalars;
int i;
char forceBuild = 0;
//
// make sure that we've been properly initialized
//
if ( ! this->Input )
{
vlErrorMacro(<< "No input!\n");
return;
}
else
this->Input->Update();
if ( ! this->LookupTable ) this->LookupTable = new vlLookupTable;
this->LookupTable->Build();
//
// Now send data down to primitives and draw it
//
if ( forceBuild || this->Input->GetMTime() > this->BuildTime ||
this->LookupTable->GetMTime() > this->BuildTime )
{
//
// create colors
//
if ( this->ScalarsVisible && (pd=this->Input->GetPointData()) &&
(scalars=pd->GetScalars()) )
{
colors = new vlRGBArray;
colors->Initialize (this->Input->NumberOfPoints());
this->LookupTable->SetTableRange(this->ScalarRange);
for (i=0; i<this->Input->NumberOfPoints(); i++)
{
colors->SetColor(i,this->LookupTable->MapValue(scalars->GetScalar(i)));
}
}
else
{
colors = 0;
}
if (this->VertsVisibility && this->Input->NumberOfVerts())
{
if (!this->Verts) this->Verts = ren->GetPrimitive("points");
this->Verts->Build(this->Input,colors);
}
if ( this->LinesVisibility && this->Input->NumberOfLines())
{
if (!this->Lines) this->Lines = ren->GetPrimitive("lines");
this->Lines->Build(this->Input,colors);
}
if ( this->PolysVisibility && this->Input->NumberOfPolys())
{
if (!this->Polys) this->Polys = ren->GetPrimitive("polygons");
this->Polys->Build(this->Input,colors);
}
if ( this->StripsVisibility && this->Input->NumberOfStrips())
{
if (!this->Strips) this->Strips = ren->GetPrimitive("triangle_strips");
this->Strips->Build(this->Input,colors);
}
this->BuildTime.Modified();
}
// draw the primitives
if (this->VertsVisibility && this->Input->NumberOfVerts())
{
this->Verts->Draw(ren);
}
if ( this->LinesVisibility && this->Input->NumberOfLines())
{
this->Lines->Draw(ren);
}
if ( this->PolysVisibility && this->Input->NumberOfPolys())
{
this->Polys->Draw(ren);
}
if ( this->StripsVisibility && this->Input->NumberOfStrips())
{
this->Strips->Draw(ren);
}
}
void vlPolyMapper::PrintSelf(ostream& os, vlIndent indent)
{
if (this->ShouldIPrint(vlPolyMapper::GetClassName()))
{
vlMapper::PrintSelf(os,indent);
if ( this->Input )
{
os << indent << "Input: (" << this->Input << ")\n";
}
else
{
os << indent << "Input: (none)\n";
}
os << indent << "Vertex Visibility: " << (this->VertsVisibility ? "On\n" : "Off\n");
os << indent << "Line Visibility: " << (this->LinesVisibility ? "On\n" : "Off\n");
os << indent << "Polygon Visibility: " << (this->PolysVisibility ? "On\n" : "Off\n");
os << indent << "Triangle Strip Visibility: " << (this->StripsVisibility ? "On\n" : "Off\n");
}
}
<|endoftext|>
|
<commit_before>#include "PWSfileV1V2.h"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
PWSfileV1V2::PWSfileV1V2(const CMyString &filename, RWmode mode, VERSION version)
: PWSfile(filename,mode)
{
m_curversion = version;
m_IV = m_ipthing;
}
PWSfileV1V2::~PWSfileV1V2()
{
}
// Used to warn pre-2.0 users, and to identify the database as 2.x:
static const CMyString V2ItemName(" !!!Version 2 File Format!!! "
"Please upgrade to PasswordSafe 2.0"
" or later");
// Used to specify the exact version
static const CMyString VersionString("2.0");
static const CMyString AltVersionString("pre-2.0");
int PWSfileV1V2::WriteV2Header()
{
CItemData header;
// Fill out with V2-specific info
// To make a dictionary attack a little harder, we make the length
// of the first record (Name) variable, by appending variable length randomness
// to the fixed string
// OOPS - can't do this yet, since previous versions (pre-2.14) read the name
// (in ReadV2Header)
// and compare it directly to VersionString to check version - a small
// mistake that would cause a pre-2.14 executable to barf reading a database
// written by 2.14 and later.
// #idef-ing this out, while correcting the code
// in ReadV2Header. Perhaps this can be fixed a year from now?
#ifdef BREAK_PRE_2_14_COMPATIBILITY
unsigned int rlen = RangeRand(62) + 2; // 64 is a trade-off...
char *rbuf = new char[rlen];
GetRandomData(rbuf, rlen-1);
rbuf[rlen-1] = '\0'; // although zero may be there before - who cares?
CMyString rname(V2ItemName);
rname += rbuf;
delete[] rbuf;
header.SetName(rname, _T(""));
#else
header.SetName(V2ItemName, _T(""));
#endif /* BREAK_PRE_2_14_COMPATIBILITY */
header.SetPassword(VersionString);
header.SetNotes(m_prefString);
// need to fallback to V17, since the record
// won't be readable otherwise!
VERSION sv = m_curversion;
m_curversion = V17;
int status = WriteRecord(header);
// restore after writing V17-format header
m_curversion = sv;
return status;
}
int PWSfileV1V2::ReadV2Header()
{
CItemData header;
// need to fallback to V17, since the header
// is always written in this format
VERSION sv = m_curversion;
m_curversion = V17;
int status = ReadRecord(header);
// restore after reading V17-format header
m_curversion = sv;
if (status == SUCCESS) {
const CMyString version = header.GetPassword();
// Compare to AltVersionString due to silly mistake
// "2.0" as well as "pre-2.0" are actually 2.0. sigh.
status = (version == VersionString || version == AltVersionString)
? SUCCESS : WRONG_VERSION;
}
if (status == SUCCESS)
m_prefString = header.GetNotes();
return status;
}
int PWSfileV1V2::Open(const CMyString &passkey)
{
int status = SUCCESS;
ASSERT(m_curversion == V17 || m_curversion == V20);
m_passkey = passkey;
LPCTSTR passstr = LPCTSTR(m_passkey);
if (m_rw == Write) {
#ifdef UNICODE
m_fd = _wfopen((LPCTSTR)m_filename, _T("wb") );
#else
m_fd = fopen((LPCTSTR)m_filename, _T("wb") );
#endif
if (m_fd == NULL)
return CANT_OPEN_FILE;
// Following used to verify passkey against file's passkey
unsigned char randstuff[StuffSize];
unsigned char randhash[20]; // HashSize
GetRandomData( randstuff, 8 );
randstuff[8] = randstuff[9] = '\0';
GenRandhash(m_passkey, randstuff, randhash);
fwrite(randstuff, 1, 8, m_fd);
fwrite(randhash, 1, 20, m_fd);
GetRandomData(m_salt, SaltLength);
fwrite(m_salt, 1, SaltLength, m_fd);
GetRandomData( m_ipthing, 8);
fwrite(m_ipthing, 1, 8, m_fd);
m_fish = BlowFish::MakeBlowFish((const unsigned char *)passstr,
m_passkey.GetLength(),
m_salt, SaltLength);
if (m_curversion == V20) {
status = WriteV2Header();
}
} else { // open for read
#ifdef UNICODE
m_fd = _wfopen((LPCTSTR) m_filename, _T("rb"));
#else
m_fd = fopen((LPCTSTR) m_filename, _T("rb"));
#endif
if (m_fd == NULL)
return CANT_OPEN_FILE;
status = CheckPassword(m_filename, m_passkey, m_fd);
if (status != SUCCESS) {
Close();
return status;
}
fread(m_salt, 1, SaltLength, m_fd);
fread(m_ipthing, 1, 8, m_fd);
m_fish = BlowFish::MakeBlowFish((const unsigned char *)passstr,
m_passkey.GetLength(),
m_salt, SaltLength);
if (m_curversion == V20)
status = ReadV2Header();
} // read mode
return status;
}
int PWSfileV1V2::Close()
{
return PWSfile::Close();
}
int PWSfileV1V2::CheckPassword(const CMyString &filename,
const CMyString &passkey, FILE *a_fd)
{
FILE *fd = a_fd;
if (fd == NULL) {
#ifdef UNICODE
fd = _wfopen((LPCTSTR) filename, _T("rb"));
#else
fd = fopen((LPCTSTR) filename, _T("rb"));
#endif
}
if (fd == NULL)
return CANT_OPEN_FILE;
unsigned char randstuff[StuffSize];
unsigned char randhash[20]; // HashSize
fread(randstuff, 1, 8, fd);
randstuff[8] = randstuff[9] = '\0'; // Gross fugbix
fread(randhash, 1, 20, fd);
if (a_fd == NULL) // if we opened the file, we close it...
fclose(fd);
unsigned char temphash[20]; // HashSize
GenRandhash(passkey, randstuff, temphash);
if (0 != ::memcmp((char*)randhash,
(char*)temphash,
20)) {// HashSize
return WRONG_PASSWORD;
} else {
return SUCCESS;
}
}
int PWSfileV1V2::WriteRecord(const CItemData &item)
{
ASSERT(m_fd != NULL);
ASSERT(m_curversion != UNKNOWN_VERSION);
int status = SUCCESS;
switch (m_curversion) {
case V17: {
// 1.x programs totally ignore the type byte, hence safe to write it
// (no need for two WriteCBC functions)
// Note that 2.0 format still requires that the header be in this format,
// So that old programs reading new databases won't crash,
// This introduces a small security issue, in that the header is known text,
// making the password susceptible to a dictionary attack on the first block,
// rather than the hash^n in the beginning of the file.
// we can help minimize this here by writing a random byte in the "type"
// byte of the first block.
CMyString name = item.GetName();
// If name field already exists - use it. This is for the 2.0 header, as well as for files
// that were imported and re-exported.
if (name.IsEmpty()) {
// The name in 1.7 consists of title + SPLTCHR + username
// DEFUSERNAME was used in previous versions, but 2.0 converts this upon import
// so it is not an issue here.
// Prepend 2.0 group field to name, if not empty
// i.e. group "finances" name "broker" -> "finances.broker"
CMyString group = item.GetGroup();
CMyString title = item.GetTitle();
if (!group.IsEmpty()) {
group += _T(".");
group += title;
title = group;
}
name = title;
name += SPLTCHR;
name += item.GetUser();
}
unsigned char dummy_type;
GetRandomData(&dummy_type, 1);
WriteCBC(dummy_type, name);
WriteCBC(CItemData::PASSWORD, item.GetPassword());
WriteCBC(CItemData::NOTES, item.GetNotes());
}
break;
case V20: {
{
uuid_array_t uuid_array;
item.GetUUID(uuid_array);
WriteCBC(CItemData::UUID, uuid_array, sizeof(uuid_array));
}
WriteCBC(CItemData::GROUP, item.GetGroup());
WriteCBC(CItemData::TITLE, item.GetTitle());
WriteCBC(CItemData::USER, item.GetUser());
WriteCBC(CItemData::PASSWORD, item.GetPassword());
WriteCBC(CItemData::NOTES, item.GetNotes());
WriteCBC(CItemData::END, _T(""));
}
break;
default:
ASSERT(0);
status = UNSUPPORTED_VERSION;
}
return status;
}
static void ExtractAutoTypeCmd(CMyString ¬esStr, CMyString &autotypeStr)
{
CString instr(notesStr);
int left = instr.Find(_T("autotype:"));
if (left == -1) {
autotypeStr = _T("");
} else {
CString tmp(notesStr);
tmp = tmp.Mid(left+9); // throw out everything left of "autotype:"
instr = instr.Left(left);
int right = tmp.FindOneOf(_T("\r\n"));
if (right != -1) {
instr += tmp.Right(right);
tmp = tmp.Left(right);
}
autotypeStr = CMyString(tmp);
notesStr = CMyString(instr);
}
}
static void ExtractURL(CMyString ¬esStr, CMyString &outurl)
{
CString instr(notesStr);
// Extract first instance of (http|https|ftp)://[^ \t\r\n]+
int left = instr.Find(_T("http://"));
if (left == -1)
left = instr.Find(_T("https://"));
if (left == -1)
left = instr.Find(_T("ftp://"));
if (left == -1) {
outurl = _T("");
} else {
CString url(instr);
instr = notesStr.Left(left);
url = url.Mid(left); // throw out everything left of URL
int right = url.FindOneOf(_T(" \t\r\n"));
if (right != -1) {
instr += url.Right(right);
url = url.Left(right);
}
outurl = CMyString(url);
notesStr = CMyString(instr);
}
}
int PWSfileV1V2::ReadRecord(CItemData &item)
{
ASSERT(m_fd != NULL);
ASSERT(m_curversion != UNKNOWN_VERSION);
CMyString tempdata;
int numread = 0;
unsigned char type;
// We do a double cast because the LPCTSTR cast operator is overridden by the CString class
// to access the pointer we need,
// but we in fact need it as an unsigned char. Grrrr.
switch (m_curversion) {
case V17: {
// type is meaningless, but why write two versions of ReadCBC?
numread += ReadCBC(type, tempdata);
item.SetName(tempdata, m_defusername);
numread += ReadCBC(type, tempdata);
item.SetPassword(tempdata);
numread += ReadCBC(type, tempdata);
item.SetNotes(tempdata);
// No UUID, so we create one here
item.CreateUUID();
// No Group - currently leave empty
return (numread > 0) ? SUCCESS : END_OF_FILE;
}
case V20: {
int emergencyExit = 255; // to avoid endless loop.
int fieldLen; // zero means end of file reached
bool endFound = false; // set to true when record end detected - happy end
do {
fieldLen = ReadCBC(type, tempdata);
if (fieldLen > 0) {
numread += fieldLen;
switch (type) {
case CItemData::TITLE:
item.SetTitle(tempdata); break;
case CItemData::USER:
item.SetUser(tempdata); break;
case CItemData::PASSWORD:
item.SetPassword(tempdata); break;
case CItemData::NOTES: {
CMyString autotypeStr, URLStr;
ExtractAutoTypeCmd(tempdata, autotypeStr);
ExtractURL(tempdata, URLStr);
item.SetNotes(tempdata);
if (!autotypeStr.IsEmpty())
item.SetAutoType(autotypeStr);
if (!URLStr.IsEmpty())
item.SetURL(URLStr);
break;
}
case CItemData::END:
endFound = true; break;
case CItemData::UUID: {
LPCTSTR ptr = LPCTSTR(tempdata);
uuid_array_t uuid_array;
for (int i = 0; i < sizeof(uuid_array); i++)
uuid_array[i] = (unsigned char)ptr[i];
item.SetUUID(uuid_array); break;
}
case CItemData::GROUP:
item.SetGroup(tempdata); break;
// just silently ignore fields we don't support.
// this is forward compatability...
case CItemData::CTIME:
case CItemData::ATIME:
case CItemData::LTIME:
case CItemData::POLICY:
default:
// XXX Set a flag here so user can be warned that
// XXX we read a file format we don't fully support
break;
} // switch
} // if (fieldLen > 0)
} while (!endFound && fieldLen > 0 && --emergencyExit > 0);
return (numread > 0) ? SUCCESS : END_OF_FILE;
}
default:
ASSERT(0);
return UNSUPPORTED_VERSION;
}
}
<commit_msg>Remerge autottype & htp into Notes for v1v2 WriteRecord<commit_after>#include "PWSfileV1V2.h"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
PWSfileV1V2::PWSfileV1V2(const CMyString &filename, RWmode mode, VERSION version)
: PWSfile(filename,mode)
{
m_curversion = version;
m_IV = m_ipthing;
}
PWSfileV1V2::~PWSfileV1V2()
{
}
// Used to warn pre-2.0 users, and to identify the database as 2.x:
static const CMyString V2ItemName(" !!!Version 2 File Format!!! "
"Please upgrade to PasswordSafe 2.0"
" or later");
// Used to specify the exact version
static const CMyString VersionString("2.0");
static const CMyString AltVersionString("pre-2.0");
int PWSfileV1V2::WriteV2Header()
{
CItemData header;
// Fill out with V2-specific info
// To make a dictionary attack a little harder, we make the length
// of the first record (Name) variable, by appending variable length randomness
// to the fixed string
// OOPS - can't do this yet, since previous versions (pre-2.14) read the name
// (in ReadV2Header)
// and compare it directly to VersionString to check version - a small
// mistake that would cause a pre-2.14 executable to barf reading a database
// written by 2.14 and later.
// #idef-ing this out, while correcting the code
// in ReadV2Header. Perhaps this can be fixed a year from now?
#ifdef BREAK_PRE_2_14_COMPATIBILITY
unsigned int rlen = RangeRand(62) + 2; // 64 is a trade-off...
char *rbuf = new char[rlen];
GetRandomData(rbuf, rlen-1);
rbuf[rlen-1] = '\0'; // although zero may be there before - who cares?
CMyString rname(V2ItemName);
rname += rbuf;
delete[] rbuf;
header.SetName(rname, _T(""));
#else
header.SetName(V2ItemName, _T(""));
#endif /* BREAK_PRE_2_14_COMPATIBILITY */
header.SetPassword(VersionString);
header.SetNotes(m_prefString);
// need to fallback to V17, since the record
// won't be readable otherwise!
VERSION sv = m_curversion;
m_curversion = V17;
int status = WriteRecord(header);
// restore after writing V17-format header
m_curversion = sv;
return status;
}
int PWSfileV1V2::ReadV2Header()
{
CItemData header;
// need to fallback to V17, since the header
// is always written in this format
VERSION sv = m_curversion;
m_curversion = V17;
int status = ReadRecord(header);
// restore after reading V17-format header
m_curversion = sv;
if (status == SUCCESS) {
const CMyString version = header.GetPassword();
// Compare to AltVersionString due to silly mistake
// "2.0" as well as "pre-2.0" are actually 2.0. sigh.
status = (version == VersionString || version == AltVersionString)
? SUCCESS : WRONG_VERSION;
}
if (status == SUCCESS)
m_prefString = header.GetNotes();
return status;
}
int PWSfileV1V2::Open(const CMyString &passkey)
{
int status = SUCCESS;
ASSERT(m_curversion == V17 || m_curversion == V20);
m_passkey = passkey;
LPCTSTR passstr = LPCTSTR(m_passkey);
if (m_rw == Write) {
#ifdef UNICODE
m_fd = _wfopen((LPCTSTR)m_filename, _T("wb") );
#else
m_fd = fopen((LPCTSTR)m_filename, _T("wb") );
#endif
if (m_fd == NULL)
return CANT_OPEN_FILE;
// Following used to verify passkey against file's passkey
unsigned char randstuff[StuffSize];
unsigned char randhash[20]; // HashSize
GetRandomData( randstuff, 8 );
randstuff[8] = randstuff[9] = '\0';
GenRandhash(m_passkey, randstuff, randhash);
fwrite(randstuff, 1, 8, m_fd);
fwrite(randhash, 1, 20, m_fd);
GetRandomData(m_salt, SaltLength);
fwrite(m_salt, 1, SaltLength, m_fd);
GetRandomData( m_ipthing, 8);
fwrite(m_ipthing, 1, 8, m_fd);
m_fish = BlowFish::MakeBlowFish((const unsigned char *)passstr,
m_passkey.GetLength(),
m_salt, SaltLength);
if (m_curversion == V20) {
status = WriteV2Header();
}
} else { // open for read
#ifdef UNICODE
m_fd = _wfopen((LPCTSTR) m_filename, _T("rb"));
#else
m_fd = fopen((LPCTSTR) m_filename, _T("rb"));
#endif
if (m_fd == NULL)
return CANT_OPEN_FILE;
status = CheckPassword(m_filename, m_passkey, m_fd);
if (status != SUCCESS) {
Close();
return status;
}
fread(m_salt, 1, SaltLength, m_fd);
fread(m_ipthing, 1, 8, m_fd);
m_fish = BlowFish::MakeBlowFish((const unsigned char *)passstr,
m_passkey.GetLength(),
m_salt, SaltLength);
if (m_curversion == V20)
status = ReadV2Header();
} // read mode
return status;
}
int PWSfileV1V2::Close()
{
return PWSfile::Close();
}
int PWSfileV1V2::CheckPassword(const CMyString &filename,
const CMyString &passkey, FILE *a_fd)
{
FILE *fd = a_fd;
if (fd == NULL) {
#ifdef UNICODE
fd = _wfopen((LPCTSTR) filename, _T("rb"));
#else
fd = fopen((LPCTSTR) filename, _T("rb"));
#endif
}
if (fd == NULL)
return CANT_OPEN_FILE;
unsigned char randstuff[StuffSize];
unsigned char randhash[20]; // HashSize
fread(randstuff, 1, 8, fd);
randstuff[8] = randstuff[9] = '\0'; // Gross fugbix
fread(randhash, 1, 20, fd);
if (a_fd == NULL) // if we opened the file, we close it...
fclose(fd);
unsigned char temphash[20]; // HashSize
GenRandhash(passkey, randstuff, temphash);
if (0 != ::memcmp((char*)randhash,
(char*)temphash,
20)) {// HashSize
return WRONG_PASSWORD;
} else {
return SUCCESS;
}
}
static CMyString ReMergeNotes(const CItemData &item)
{
CMyString notes = item.GetNotes();
const CMyString url(item.GetURL());
if (!url.IsEmpty()) {
notes += _T("\r\n"); notes += url;
}
const CMyString at(item.GetAutoType());
if (!at.IsEmpty()) {
notes += _T("\r\nautotype:");
notes += at;
}
return notes;
}
int PWSfileV1V2::WriteRecord(const CItemData &item)
{
ASSERT(m_fd != NULL);
ASSERT(m_curversion != UNKNOWN_VERSION);
int status = SUCCESS;
switch (m_curversion) {
case V17: {
// 1.x programs totally ignore the type byte, hence safe to write it
// (no need for two WriteCBC functions)
// Note that 2.0 format still requires that the header be in this format,
// So that old programs reading new databases won't crash,
// This introduces a small security issue, in that the header is known text,
// making the password susceptible to a dictionary attack on the first block,
// rather than the hash^n in the beginning of the file.
// we can help minimize this here by writing a random byte in the "type"
// byte of the first block.
CMyString name = item.GetName();
// If name field already exists - use it. This is for the 2.0 header, as well as for files
// that were imported and re-exported.
if (name.IsEmpty()) {
// The name in 1.7 consists of title + SPLTCHR + username
// DEFUSERNAME was used in previous versions, but 2.0 converts this upon import
// so it is not an issue here.
// Prepend 2.0 group field to name, if not empty
// i.e. group "finances" name "broker" -> "finances.broker"
CMyString group = item.GetGroup();
CMyString title = item.GetTitle();
if (!group.IsEmpty()) {
group += _T(".");
group += title;
title = group;
}
name = title;
name += SPLTCHR;
name += item.GetUser();
}
unsigned char dummy_type;
GetRandomData(&dummy_type, 1);
WriteCBC(dummy_type, name);
WriteCBC(CItemData::PASSWORD, item.GetPassword());
WriteCBC(CItemData::NOTES, ReMergeNotes(item));
}
break;
case V20: {
{
uuid_array_t uuid_array;
item.GetUUID(uuid_array);
WriteCBC(CItemData::UUID, uuid_array, sizeof(uuid_array));
}
WriteCBC(CItemData::GROUP, item.GetGroup());
WriteCBC(CItemData::TITLE, item.GetTitle());
WriteCBC(CItemData::USER, item.GetUser());
WriteCBC(CItemData::PASSWORD, item.GetPassword());
WriteCBC(CItemData::NOTES, ReMergeNotes(item));
WriteCBC(CItemData::END, _T(""));
}
break;
default:
ASSERT(0);
status = UNSUPPORTED_VERSION;
}
return status;
}
static void ExtractAutoTypeCmd(CMyString ¬esStr, CMyString &autotypeStr)
{
CString instr(notesStr);
int left = instr.Find(_T("autotype:"));
if (left == -1) {
autotypeStr = _T("");
} else {
CString tmp(notesStr);
tmp = tmp.Mid(left+9); // throw out everything left of "autotype:"
instr = instr.Left(left);
int right = tmp.FindOneOf(_T("\r\n"));
if (right != -1) {
instr += tmp.Right(right);
tmp = tmp.Left(right);
}
autotypeStr = CMyString(tmp);
notesStr = CMyString(instr);
}
}
static void ExtractURL(CMyString ¬esStr, CMyString &outurl)
{
CString instr(notesStr);
// Extract first instance of (http|https|ftp)://[^ \t\r\n]+
int left = instr.Find(_T("http://"));
if (left == -1)
left = instr.Find(_T("https://"));
if (left == -1)
left = instr.Find(_T("ftp://"));
if (left == -1) {
outurl = _T("");
} else {
CString url(instr);
instr = notesStr.Left(left);
url = url.Mid(left); // throw out everything left of URL
int right = url.FindOneOf(_T(" \t\r\n"));
if (right != -1) {
instr += url.Right(right);
url = url.Left(right);
}
outurl = CMyString(url);
notesStr = CMyString(instr);
}
}
int PWSfileV1V2::ReadRecord(CItemData &item)
{
ASSERT(m_fd != NULL);
ASSERT(m_curversion != UNKNOWN_VERSION);
CMyString tempdata;
int numread = 0;
unsigned char type;
// We do a double cast because the LPCTSTR cast operator is overridden by the CString class
// to access the pointer we need,
// but we in fact need it as an unsigned char. Grrrr.
switch (m_curversion) {
case V17: {
// type is meaningless, but why write two versions of ReadCBC?
numread += ReadCBC(type, tempdata);
item.SetName(tempdata, m_defusername);
numread += ReadCBC(type, tempdata);
item.SetPassword(tempdata);
numread += ReadCBC(type, tempdata);
item.SetNotes(tempdata);
// No UUID, so we create one here
item.CreateUUID();
// No Group - currently leave empty
return (numread > 0) ? SUCCESS : END_OF_FILE;
}
case V20: {
int emergencyExit = 255; // to avoid endless loop.
int fieldLen; // zero means end of file reached
bool endFound = false; // set to true when record end detected - happy end
do {
fieldLen = ReadCBC(type, tempdata);
if (fieldLen > 0) {
numread += fieldLen;
switch (type) {
case CItemData::TITLE:
item.SetTitle(tempdata); break;
case CItemData::USER:
item.SetUser(tempdata); break;
case CItemData::PASSWORD:
item.SetPassword(tempdata); break;
case CItemData::NOTES: {
CMyString autotypeStr, URLStr;
ExtractAutoTypeCmd(tempdata, autotypeStr);
ExtractURL(tempdata, URLStr);
item.SetNotes(tempdata);
if (!autotypeStr.IsEmpty())
item.SetAutoType(autotypeStr);
if (!URLStr.IsEmpty())
item.SetURL(URLStr);
break;
}
case CItemData::END:
endFound = true; break;
case CItemData::UUID: {
LPCTSTR ptr = LPCTSTR(tempdata);
uuid_array_t uuid_array;
for (int i = 0; i < sizeof(uuid_array); i++)
uuid_array[i] = (unsigned char)ptr[i];
item.SetUUID(uuid_array); break;
}
case CItemData::GROUP:
item.SetGroup(tempdata); break;
// just silently ignore fields we don't support.
// this is forward compatability...
case CItemData::CTIME:
case CItemData::ATIME:
case CItemData::LTIME:
case CItemData::POLICY:
default:
// XXX Set a flag here so user can be warned that
// XXX we read a file format we don't fully support
break;
} // switch
} // if (fieldLen > 0)
} while (!endFound && fieldLen > 0 && --emergencyExit > 0);
return (numread > 0) ? SUCCESS : END_OF_FILE;
}
default:
ASSERT(0);
return UNSUPPORTED_VERSION;
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Controls.cpp
*
* Contains the yaw_controller() and depth_controller functions
******************************************************************************/
#include "Mapper.h"
/******************************************************************************
* float yaw_controller()
*
* Takes in readings from the IMU and returns a value between -1 and 1 (-100% -
* +100%) that the port and starboard thrusters should run at
******************************************************************************/
/*
float yaw_controller(bno055, yaw_pid)
{
// control output //
if( bno055.yaw < 180 ) // AUV is pointed right
{
// u[2] is negative
motor_percent = yaw_pid.kp*(yaw_pid.err)
+ yaw_pid.kd*(bno055.r)+ yaw_pid.ki*yaw_pid.i_err; // yaw controller
}
else // AUV is pointed left
{
// u[2] is positive
motor_percent = yaw_pid.kp*(yaw_pid.err)
+ yaw_pid.kd*(bno055.r)
+ yaw_pid.ki*yaw_pid.i_err; // yaw controller
}
// saturate yaw controller //
if( u[2] > YAW_SAT )
{
motor_percent=YAW_SAT;
}
else if( motor_percent < -YAW_SAT )
{
motor_percent = -YAW_SAT;
}
yaw_pid.i_err += yaw_pid.err*DT;
// set current yaw to be the old yaw //
yaw_pid.oldyaw = bno055.yaw;
return motor_percent;
}
*/
/******************************************************************************
* float depth_controller(float range)
*
* Takes a range-from-bottom reading from the laser range-finder code and
* returns a value between -1 and 1 (-100% - +100%) that the vertical thruster
* should run at
******************************************************************************/
/*
float depth_controller(float range)
{
float vert_percent; // vertical thruster output in a percentage
float depth_sum_error = 0; // accumulated range error for integral control
float range_current;
float range_old;
float
// accumulated range error for integral control //
depth_sum_error += range - depth_pid.setpoint;
if( range > depth_pid.setpoint )
{
vert_percent = depth_pid.kp*(range-depth_pid.setpoint)
+ depth_pid.ki*(depth_sum_error)
+ depth_pid.kd*((range_current-range_old)/DT);
}
else
{
// shut off vertical thruster //
vert_percent = 0;
}
// saturate depth controller //
if( vert_percent > DEPTH_SAT )
{
vert_percent = DEPTH_SAT;
}
else if( vert_percent < -DEPTH_SAT )
{
vert_percent = -DEPTH_SAT;
}
// set current depth to be the old depth //
depth_pid.old = depth_pid.current;
return vert_percent;
}
*/
<commit_msg>Uncommented Yaw Controller<commit_after>/******************************************************************************
* Controls.cpp
*
* Contains the yaw_controller() and depth_controller functions
******************************************************************************/
#include "Mapper.h"
/******************************************************************************
* float yaw_controller()
*
* Takes in readings from the IMU and returns a value between -1 and 1 (-100% -
* +100%) that the port and starboard thrusters should run at
******************************************************************************/
float yaw_controller(bno055, yaw_pid)
{
// control output //
if( bno055.yaw < 180 ) // AUV is pointed right
{
// u[2] is negative
motor_percent = yaw_pid.kp*(yaw_pid.err)
+ yaw_pid.kd*(bno055.r)+ yaw_pid.ki*yaw_pid.i_err; // yaw controller
}
else // AUV is pointed left
{
// u[2] is positive
motor_percent = yaw_pid.kp*(yaw_pid.err) + yaw_pid.kd*(bno055.r)
+ yaw_pid.ki*yaw_pid.i_err; // yaw controller
}
// saturate yaw controller //
if( u[2] > YAW_SAT )
{
motor_percent=YAW_SAT;
}
else if( motor_percent < -YAW_SAT )
{
motor_percent = -YAW_SAT;
}
yaw_pid.i_err += yaw_pid.err*DT;
// set current yaw to be the old yaw //
yaw_pid.oldyaw = bno055.yaw;
return motor_percent;
}
/******************************************************************************
* float depth_controller(float range)
*
* Takes a range-from-bottom reading from the laser range-finder code and
* returns a value between -1 and 1 (-100% - +100%) that the vertical thruster
* should run at
******************************************************************************/
/*
float depth_controller(float range)
{
float vert_percent; // vertical thruster output in a percentage
float depth_sum_error = 0; // accumulated range error for integral control
float range_current;
float range_old;
float
// accumulated range error for integral control //
depth_sum_error += range - depth_pid.setpoint;
if( range > depth_pid.setpoint )
{
vert_percent = depth_pid.kp*(range-depth_pid.setpoint)
+ depth_pid.ki*(depth_sum_error)
+ depth_pid.kd*((range_current-range_old)/DT);
}
else
{
// shut off vertical thruster //
vert_percent = 0;
}
// saturate depth controller //
if( vert_percent > DEPTH_SAT )
{
vert_percent = DEPTH_SAT;
}
else if( vert_percent < -DEPTH_SAT )
{
vert_percent = -DEPTH_SAT;
}
// set current depth to be the old depth //
depth_pid.old = depth_pid.current;
return vert_percent;
}
*/
<|endoftext|>
|
<commit_before><commit_msg>remove unused variable "rep".<commit_after><|endoftext|>
|
<commit_before>#include "util.hh"
#include <string>
using namespace std;
internal_error::internal_error() : message("unknown internal error") {}
internal_error::internal_error(string msg) : message("internal error: " + msg) {}
string internal_error::get_message() {
return message;
}
user_error::user_error() : message("unknown user error") {}
user_error::user_error(string msg) : message("user error: " + msg) {}
string user_error::get_message() {
return message;
}
<commit_msg>bugfix<commit_after>#include "util.hh"
using namespace util;
#include <string>
using namespace std;
internal_error::internal_error() : message("unknown internal error") {}
internal_error::internal_error(string msg) : message("internal error: " + msg) {}
string internal_error::get_message() {
return message;
}
user_error::user_error() : message("unknown user error") {}
user_error::user_error(string msg) : message("user error: " + msg) {}
string user_error::get_message() {
return message;
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <cassert>
#include <functional>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <sstream>
#include <grpc/grpc.h>
#include <grpc/support/histogram.h>
#include <grpc/support/log.h>
#include <gflags/gflags.h>
#include <grpc++/async_unary_call.h>
#include <grpc++/client_context.h>
#include <grpc++/status.h>
#include "test/core/util/grpc_profiler.h"
#include "test/cpp/util/create_test_channel.h"
#include "test/cpp/qps/qpstest.pb.h"
DEFINE_bool(enable_ssl, false, "Whether to use ssl/tls.");
DEFINE_int32(server_port, 0, "Server port.");
DEFINE_string(server_host, "127.0.0.1", "Server host.");
DEFINE_int32(client_threads, 4, "Number of client threads.");
// We have a configurable number of channels for sending RPCs.
// RPCs are sent round-robin on the available channels by the
// various threads. Interesting cases are 1 global channel or
// 1 per-thread channel, but we can support any number.
// The channels are assigned round-robin on an RPC by RPC basis
// rather than just at initialization time in order to also measure the
// impact of cache thrashing caused by channel changes. This is an issue
// if you are not in one of the above "interesting cases"
DEFINE_int32(client_channels, 4, "Number of client channels.");
DEFINE_int32(num_rpcs, 1000, "Number of RPCs per thread.");
DEFINE_int32(payload_size, 1, "Payload size in bytes");
// Alternatively, specify parameters for test as a workload so that multiple
// tests are initiated back-to-back. This is convenient for keeping a borg
// allocation consistent. This is a space-separated list of
// [threads channels num_rpcs payload_size ]*
DEFINE_string(workload, "", "Workload parameters");
using grpc::ChannelInterface;
using grpc::CreateTestChannel;
using grpc::testing::ServerStats;
using grpc::testing::SimpleRequest;
using grpc::testing::SimpleResponse;
using grpc::testing::StatsRequest;
using grpc::testing::TestService;
// In some distros, gflags is in the namespace google, and in some others,
// in gflags. This hack is enabling us to find both.
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;
static double now() {
gpr_timespec tv = gpr_now();
return 1e9 * tv.tv_sec + tv.tv_nsec;
}
class ClientRpcContext {
public:
ClientRpcContext() {}
virtual ~ClientRpcContext() {}
virtual bool operator()() = 0; // do next state, return false if steps done
static void *tag(ClientRpcContext *c) { return reinterpret_cast<void *>(c); }
static ClientRpcContext *detag(void *t) {
return reinterpret_cast<ClientRpcContext *>(t);
}
virtual void report_stats(gpr_histogram *hist) = 0;
};
template <class RequestType, class ResponseType>
class ClientRpcContextUnaryImpl : public ClientRpcContext {
public:
ClientRpcContextUnaryImpl(
const RequestType &req,
std::function<
std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>(
grpc::ClientContext *, const RequestType &, void *)> start_req,
std::function<void(grpc::Status, ResponseType *)> on_done)
: context_(),
req_(req),
response_(),
next_state_(&ClientRpcContextUnaryImpl::ReqSent),
callback_(on_done),
start_(now()),
response_reader_(
start_req(&context_, req_, ClientRpcContext::tag(this))) {}
~ClientRpcContextUnaryImpl() GRPC_OVERRIDE {}
bool operator()() GRPC_OVERRIDE { return (this->*next_state_)(); }
void report_stats(gpr_histogram *hist) GRPC_OVERRIDE {
gpr_histogram_add(hist, now() - start_);
}
private:
bool ReqSent() {
next_state_ = &ClientRpcContextUnaryImpl::RespDone;
response_reader_->Finish(&response_, &status_, ClientRpcContext::tag(this));
return true;
}
bool RespDone() {
next_state_ = &ClientRpcContextUnaryImpl::DoCallBack;
return false;
}
bool DoCallBack() {
callback_(status_, &response_);
return false;
}
grpc::ClientContext context_;
RequestType req_;
ResponseType response_;
bool (ClientRpcContextUnaryImpl::*next_state_)();
std::function<void(grpc::Status, ResponseType *)> callback_;
grpc::Status status_;
double start_;
std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>
response_reader_;
};
static void RunTest(const int client_threads, const int client_channels,
const int num_rpcs, const int payload_size) {
gpr_log(GPR_INFO,
"QPS test with parameters\n"
"enable_ssl = %d\n"
"client_channels = %d\n"
"client_threads = %d\n"
"num_rpcs = %d\n"
"payload_size = %d\n"
"server_host:server_port = %s:%d\n\n",
FLAGS_enable_ssl, client_channels, client_threads, num_rpcs,
payload_size, FLAGS_server_host.c_str(), FLAGS_server_port);
std::ostringstream oss;
oss << FLAGS_server_host << ":" << FLAGS_server_port;
class ClientChannelInfo {
public:
explicit ClientChannelInfo(const grpc::string &server)
: channel_(CreateTestChannel(server, FLAGS_enable_ssl)),
stub_(TestService::NewStub(channel_)) {}
ChannelInterface *get_channel() { return channel_.get(); }
TestService::Stub *get_stub() { return stub_.get(); }
private:
std::shared_ptr<ChannelInterface> channel_;
std::unique_ptr<TestService::Stub> stub_;
};
std::vector<ClientChannelInfo> channels;
for (int i = 0; i < client_channels; i++) {
channels.push_back(ClientChannelInfo(oss.str()));
}
std::vector<std::thread> threads; // Will add threads when ready to execute
std::vector<::gpr_histogram *> thread_stats(client_threads);
TestService::Stub *stub_stats = channels[0].get_stub();
grpc::ClientContext context_stats_begin;
StatsRequest stats_request;
ServerStats server_stats_begin;
stats_request.set_test_num(0);
grpc::Status status_beg = stub_stats->CollectServerStats(
&context_stats_begin, stats_request, &server_stats_begin);
grpc_profiler_start("qps_client_async.prof");
auto CheckDone = [=](grpc::Status s, SimpleResponse *response) {
GPR_ASSERT(s.IsOk() && (response->payload().type() ==
grpc::testing::PayloadType::COMPRESSABLE) &&
(response->payload().body().length() ==
static_cast<size_t>(payload_size)));
};
for (int i = 0; i < client_threads; i++) {
gpr_histogram *hist = gpr_histogram_create(0.01, 60e9);
GPR_ASSERT(hist != NULL);
thread_stats[i] = hist;
threads.push_back(std::thread(
[hist, client_threads, client_channels, num_rpcs, payload_size,
&channels, &CheckDone](int channel_num) {
using namespace std::placeholders;
SimpleRequest request;
request.set_response_type(grpc::testing::PayloadType::COMPRESSABLE);
request.set_response_size(payload_size);
grpc::CompletionQueue cli_cq;
int rpcs_sent = 0;
while (rpcs_sent < num_rpcs) {
rpcs_sent++;
TestService::Stub *stub = channels[channel_num].get_stub();
grpc::ClientContext context;
auto start_req = std::bind(&TestService::Stub::AsyncUnaryCall, stub,
_1, _2, &cli_cq, _3);
new ClientRpcContextUnaryImpl<SimpleRequest, SimpleResponse>(
request, start_req, CheckDone);
void *got_tag;
bool ok;
// Need to call 2 next for every 1 RPC (1 for req done, 1 for resp
// done)
cli_cq.Next(&got_tag, &ok);
if (!ok) break;
ClientRpcContext *ctx = ClientRpcContext::detag(got_tag);
if ((*ctx)() == false) {
// call the callback and then delete it
(*ctx)();
delete ctx;
}
cli_cq.Next(&got_tag, &ok);
if (!ok) break;
ctx = ClientRpcContext::detag(got_tag);
if ((*ctx)() == false) {
// call the callback and then delete it
ctx->report_stats(hist);
(*ctx)();
delete ctx;
}
// Now do runtime round-robin assignment of the next
// channel number
channel_num += client_threads;
channel_num %= client_channels;
}
},
i % client_channels));
}
gpr_histogram *hist = gpr_histogram_create(0.01, 60e9);
GPR_ASSERT(hist != NULL);
for (auto &t : threads) {
t.join();
}
grpc_profiler_stop();
for (int i = 0; i < client_threads; i++) {
gpr_histogram *h = thread_stats[i];
gpr_log(GPR_INFO, "latency at thread %d (50/90/95/99/99.9): %f/%f/%f/%f/%f",
i, gpr_histogram_percentile(h, 50), gpr_histogram_percentile(h, 90),
gpr_histogram_percentile(h, 95), gpr_histogram_percentile(h, 99),
gpr_histogram_percentile(h, 99.9));
gpr_histogram_merge(hist, h);
gpr_histogram_destroy(h);
}
gpr_log(
GPR_INFO,
"latency across %d threads with %d channels and %d payload "
"(50/90/95/99/99.9): %f / %f / %f / %f / %f",
client_threads, client_channels, payload_size,
gpr_histogram_percentile(hist, 50), gpr_histogram_percentile(hist, 90),
gpr_histogram_percentile(hist, 95), gpr_histogram_percentile(hist, 99),
gpr_histogram_percentile(hist, 99.9));
gpr_histogram_destroy(hist);
grpc::ClientContext context_stats_end;
ServerStats server_stats_end;
grpc::Status status_end = stub_stats->CollectServerStats(
&context_stats_end, stats_request, &server_stats_end);
double elapsed = server_stats_end.time_now() - server_stats_begin.time_now();
int total_rpcs = client_threads * num_rpcs;
double utime = server_stats_end.time_user() - server_stats_begin.time_user();
double stime =
server_stats_end.time_system() - server_stats_begin.time_system();
gpr_log(GPR_INFO,
"Elapsed time: %.3f\n"
"RPC Count: %d\n"
"QPS: %.3f\n"
"System time: %.3f\n"
"User time: %.3f\n"
"Resource usage: %.1f%%\n",
elapsed, total_rpcs, total_rpcs / elapsed, stime, utime,
(stime + utime) / elapsed * 100.0);
}
int main(int argc, char **argv) {
grpc_init();
ParseCommandLineFlags(&argc, &argv, true);
GPR_ASSERT(FLAGS_server_port);
if (FLAGS_workload.length() == 0) {
RunTest(FLAGS_client_threads, FLAGS_client_channels, FLAGS_num_rpcs,
FLAGS_payload_size);
} else {
std::istringstream workload(FLAGS_workload);
int client_threads, client_channels, num_rpcs, payload_size;
workload >> client_threads;
while (!workload.eof()) {
workload >> client_channels >> num_rpcs >> payload_size;
RunTest(client_threads, client_channels, num_rpcs, payload_size);
workload >> client_threads;
}
gpr_log(GPR_INFO, "Done with specified workload.");
}
grpc_shutdown();
return 0;
}
<commit_msg><:: -> < ::<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <cassert>
#include <functional>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <sstream>
#include <grpc/grpc.h>
#include <grpc/support/histogram.h>
#include <grpc/support/log.h>
#include <gflags/gflags.h>
#include <grpc++/async_unary_call.h>
#include <grpc++/client_context.h>
#include <grpc++/status.h>
#include "test/core/util/grpc_profiler.h"
#include "test/cpp/util/create_test_channel.h"
#include "test/cpp/qps/qpstest.pb.h"
DEFINE_bool(enable_ssl, false, "Whether to use ssl/tls.");
DEFINE_int32(server_port, 0, "Server port.");
DEFINE_string(server_host, "127.0.0.1", "Server host.");
DEFINE_int32(client_threads, 4, "Number of client threads.");
// We have a configurable number of channels for sending RPCs.
// RPCs are sent round-robin on the available channels by the
// various threads. Interesting cases are 1 global channel or
// 1 per-thread channel, but we can support any number.
// The channels are assigned round-robin on an RPC by RPC basis
// rather than just at initialization time in order to also measure the
// impact of cache thrashing caused by channel changes. This is an issue
// if you are not in one of the above "interesting cases"
DEFINE_int32(client_channels, 4, "Number of client channels.");
DEFINE_int32(num_rpcs, 1000, "Number of RPCs per thread.");
DEFINE_int32(payload_size, 1, "Payload size in bytes");
// Alternatively, specify parameters for test as a workload so that multiple
// tests are initiated back-to-back. This is convenient for keeping a borg
// allocation consistent. This is a space-separated list of
// [threads channels num_rpcs payload_size ]*
DEFINE_string(workload, "", "Workload parameters");
using grpc::ChannelInterface;
using grpc::CreateTestChannel;
using grpc::testing::ServerStats;
using grpc::testing::SimpleRequest;
using grpc::testing::SimpleResponse;
using grpc::testing::StatsRequest;
using grpc::testing::TestService;
// In some distros, gflags is in the namespace google, and in some others,
// in gflags. This hack is enabling us to find both.
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;
static double now() {
gpr_timespec tv = gpr_now();
return 1e9 * tv.tv_sec + tv.tv_nsec;
}
class ClientRpcContext {
public:
ClientRpcContext() {}
virtual ~ClientRpcContext() {}
virtual bool operator()() = 0; // do next state, return false if steps done
static void *tag(ClientRpcContext *c) { return reinterpret_cast<void *>(c); }
static ClientRpcContext *detag(void *t) {
return reinterpret_cast<ClientRpcContext *>(t);
}
virtual void report_stats(gpr_histogram *hist) = 0;
};
template <class RequestType, class ResponseType>
class ClientRpcContextUnaryImpl : public ClientRpcContext {
public:
ClientRpcContextUnaryImpl(
const RequestType &req,
std::function<
std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>(
grpc::ClientContext *, const RequestType &, void *)> start_req,
std::function<void(grpc::Status, ResponseType *)> on_done)
: context_(),
req_(req),
response_(),
next_state_(&ClientRpcContextUnaryImpl::ReqSent),
callback_(on_done),
start_(now()),
response_reader_(
start_req(&context_, req_, ClientRpcContext::tag(this))) {}
~ClientRpcContextUnaryImpl() GRPC_OVERRIDE {}
bool operator()() GRPC_OVERRIDE { return (this->*next_state_)(); }
void report_stats(gpr_histogram *hist) GRPC_OVERRIDE {
gpr_histogram_add(hist, now() - start_);
}
private:
bool ReqSent() {
next_state_ = &ClientRpcContextUnaryImpl::RespDone;
response_reader_->Finish(&response_, &status_, ClientRpcContext::tag(this));
return true;
}
bool RespDone() {
next_state_ = &ClientRpcContextUnaryImpl::DoCallBack;
return false;
}
bool DoCallBack() {
callback_(status_, &response_);
return false;
}
grpc::ClientContext context_;
RequestType req_;
ResponseType response_;
bool (ClientRpcContextUnaryImpl::*next_state_)();
std::function<void(grpc::Status, ResponseType *)> callback_;
grpc::Status status_;
double start_;
std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>
response_reader_;
};
static void RunTest(const int client_threads, const int client_channels,
const int num_rpcs, const int payload_size) {
gpr_log(GPR_INFO,
"QPS test with parameters\n"
"enable_ssl = %d\n"
"client_channels = %d\n"
"client_threads = %d\n"
"num_rpcs = %d\n"
"payload_size = %d\n"
"server_host:server_port = %s:%d\n\n",
FLAGS_enable_ssl, client_channels, client_threads, num_rpcs,
payload_size, FLAGS_server_host.c_str(), FLAGS_server_port);
std::ostringstream oss;
oss << FLAGS_server_host << ":" << FLAGS_server_port;
class ClientChannelInfo {
public:
explicit ClientChannelInfo(const grpc::string &server)
: channel_(CreateTestChannel(server, FLAGS_enable_ssl)),
stub_(TestService::NewStub(channel_)) {}
ChannelInterface *get_channel() { return channel_.get(); }
TestService::Stub *get_stub() { return stub_.get(); }
private:
std::shared_ptr<ChannelInterface> channel_;
std::unique_ptr<TestService::Stub> stub_;
};
std::vector<ClientChannelInfo> channels;
for (int i = 0; i < client_channels; i++) {
channels.push_back(ClientChannelInfo(oss.str()));
}
std::vector<std::thread> threads; // Will add threads when ready to execute
std::vector< ::gpr_histogram *> thread_stats(client_threads);
TestService::Stub *stub_stats = channels[0].get_stub();
grpc::ClientContext context_stats_begin;
StatsRequest stats_request;
ServerStats server_stats_begin;
stats_request.set_test_num(0);
grpc::Status status_beg = stub_stats->CollectServerStats(
&context_stats_begin, stats_request, &server_stats_begin);
grpc_profiler_start("qps_client_async.prof");
auto CheckDone = [=](grpc::Status s, SimpleResponse *response) {
GPR_ASSERT(s.IsOk() && (response->payload().type() ==
grpc::testing::PayloadType::COMPRESSABLE) &&
(response->payload().body().length() ==
static_cast<size_t>(payload_size)));
};
for (int i = 0; i < client_threads; i++) {
gpr_histogram *hist = gpr_histogram_create(0.01, 60e9);
GPR_ASSERT(hist != NULL);
thread_stats[i] = hist;
threads.push_back(std::thread(
[hist, client_threads, client_channels, num_rpcs, payload_size,
&channels, &CheckDone](int channel_num) {
using namespace std::placeholders;
SimpleRequest request;
request.set_response_type(grpc::testing::PayloadType::COMPRESSABLE);
request.set_response_size(payload_size);
grpc::CompletionQueue cli_cq;
int rpcs_sent = 0;
while (rpcs_sent < num_rpcs) {
rpcs_sent++;
TestService::Stub *stub = channels[channel_num].get_stub();
grpc::ClientContext context;
auto start_req = std::bind(&TestService::Stub::AsyncUnaryCall, stub,
_1, _2, &cli_cq, _3);
new ClientRpcContextUnaryImpl<SimpleRequest, SimpleResponse>(
request, start_req, CheckDone);
void *got_tag;
bool ok;
// Need to call 2 next for every 1 RPC (1 for req done, 1 for resp
// done)
cli_cq.Next(&got_tag, &ok);
if (!ok) break;
ClientRpcContext *ctx = ClientRpcContext::detag(got_tag);
if ((*ctx)() == false) {
// call the callback and then delete it
(*ctx)();
delete ctx;
}
cli_cq.Next(&got_tag, &ok);
if (!ok) break;
ctx = ClientRpcContext::detag(got_tag);
if ((*ctx)() == false) {
// call the callback and then delete it
ctx->report_stats(hist);
(*ctx)();
delete ctx;
}
// Now do runtime round-robin assignment of the next
// channel number
channel_num += client_threads;
channel_num %= client_channels;
}
},
i % client_channels));
}
gpr_histogram *hist = gpr_histogram_create(0.01, 60e9);
GPR_ASSERT(hist != NULL);
for (auto &t : threads) {
t.join();
}
grpc_profiler_stop();
for (int i = 0; i < client_threads; i++) {
gpr_histogram *h = thread_stats[i];
gpr_log(GPR_INFO, "latency at thread %d (50/90/95/99/99.9): %f/%f/%f/%f/%f",
i, gpr_histogram_percentile(h, 50), gpr_histogram_percentile(h, 90),
gpr_histogram_percentile(h, 95), gpr_histogram_percentile(h, 99),
gpr_histogram_percentile(h, 99.9));
gpr_histogram_merge(hist, h);
gpr_histogram_destroy(h);
}
gpr_log(
GPR_INFO,
"latency across %d threads with %d channels and %d payload "
"(50/90/95/99/99.9): %f / %f / %f / %f / %f",
client_threads, client_channels, payload_size,
gpr_histogram_percentile(hist, 50), gpr_histogram_percentile(hist, 90),
gpr_histogram_percentile(hist, 95), gpr_histogram_percentile(hist, 99),
gpr_histogram_percentile(hist, 99.9));
gpr_histogram_destroy(hist);
grpc::ClientContext context_stats_end;
ServerStats server_stats_end;
grpc::Status status_end = stub_stats->CollectServerStats(
&context_stats_end, stats_request, &server_stats_end);
double elapsed = server_stats_end.time_now() - server_stats_begin.time_now();
int total_rpcs = client_threads * num_rpcs;
double utime = server_stats_end.time_user() - server_stats_begin.time_user();
double stime =
server_stats_end.time_system() - server_stats_begin.time_system();
gpr_log(GPR_INFO,
"Elapsed time: %.3f\n"
"RPC Count: %d\n"
"QPS: %.3f\n"
"System time: %.3f\n"
"User time: %.3f\n"
"Resource usage: %.1f%%\n",
elapsed, total_rpcs, total_rpcs / elapsed, stime, utime,
(stime + utime) / elapsed * 100.0);
}
int main(int argc, char **argv) {
grpc_init();
ParseCommandLineFlags(&argc, &argv, true);
GPR_ASSERT(FLAGS_server_port);
if (FLAGS_workload.length() == 0) {
RunTest(FLAGS_client_threads, FLAGS_client_channels, FLAGS_num_rpcs,
FLAGS_payload_size);
} else {
std::istringstream workload(FLAGS_workload);
int client_threads, client_channels, num_rpcs, payload_size;
workload >> client_threads;
while (!workload.eof()) {
workload >> client_channels >> num_rpcs >> payload_size;
RunTest(client_threads, client_channels, num_rpcs, payload_size);
workload >> client_threads;
}
gpr_log(GPR_INFO, "Done with specified workload.");
}
grpc_shutdown();
return 0;
}
<|endoftext|>
|
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DefaultScanResult.h>
#include <stingray/scanner/DefaultServiceNetworkInfo.h>
#include <stingray/scanner/LcnList.h>
#include <stingray/scanner/OtherTransportInfoEntry.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DefaultDVBTTransport.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::Alarm);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::app::AppChannelPtr>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelListAutoRemover);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanResult);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultServiceNetworkInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(GenreChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LcnList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(OtherTransportInfoEntry);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTTransport);
#endif
}
}}
<commit_msg>Refactored IServiceNetworkInfoEntry passing and storing - removed redundant IServiceNetworkInfo. Fixed dependent code.<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/Scheduler.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DefaultScanResult.h>
#include <stingray/scanner/LcnList.h>
#include <stingray/scanner/OtherTransportInfoEntry.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DefaultDVBTTransport.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::Alarm);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::app::AppChannelPtr>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelListAutoRemover);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanResult);
TOOLKIT_REGISTER_CLASS_EXPLICIT(GenreChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LcnList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(OtherTransportInfoEntry);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTTransport);
#endif
}
}}
<|endoftext|>
|
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/RecordErrors.h>
#include <stingray/app/activation_manager/ActivationIntent.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/ca/BasicSubscriptionLease.h>
#include <stingray/ca/BissConditionalAccess.h>
#include <stingray/ca/DreSubscription.h>
#include <stingray/ca/SubscriptionBundle.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp3/Mp3MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/SubstreamDescriptors.h>
#include <stingray/mpeg/ContentDescription.h>
#include <stingray/mpeg/PvrDescription.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/net/NetworkConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/EmuScanPerformerFactory.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/CertificateRevocationList.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/pushvod/pushvod_emu/PushVODEmulationMovie.h>
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBBandInfo.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegSubstreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DefaultScanPerformerFactory.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/LybidScanPerformerFactory.h>
#include <stingray/scanner/StreamableServiceMetaInfo.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/TricolorScanPerformerFactory.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/AutoCreatedListMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/StatisticChannelInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/time/BuiltinTimeSourceId.h>
#include <stingray/time/TDTTimeSourceId.h>
#include <stingray/time/TransportsTimeSourceObtainer.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbc/DVBCTransport.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSubscriptionRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::SimpleRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionLease);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BissSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Provider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Subscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SubscriptionBundle);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SatIpClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::ContentDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::PvrDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<NetworkConfigurationStatus>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuScanPerformerFactory);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::CertificateRevocationList);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(PushVODEmulationMovie);
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(StreamableServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AutoCreatedListMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::StatisticChannelInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BuiltinTimeSourceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TDTTimeSourceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TransportTimeOffset);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<commit_msg>update factory classes<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/RecordErrors.h>
#include <stingray/app/activation_manager/ActivationIntent.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/ca/BasicSubscriptionLease.h>
#include <stingray/ca/BissConditionalAccess.h>
#include <stingray/ca/DreSubscription.h>
#include <stingray/ca/SubscriptionBundle.h>
#include <stingray/crypto/SoftwareCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp3/Mp3MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/SubstreamDescriptors.h>
#include <stingray/mpeg/ContentDescription.h>
#include <stingray/mpeg/PvrDescription.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/net/NetworkConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/EmuScanPerformerFactory.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/pushvod/pushvod_emu/PushVODEmulationMovie.h>
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBBandInfo.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegSubstreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DefaultScanPerformerFactory.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/LybidScanPerformerFactory.h>
#include <stingray/scanner/StreamableServiceMetaInfo.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/TricolorScanPerformerFactory.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/AutoCreatedListMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/StatisticChannelInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/time/BuiltinTimeSourceId.h>
#include <stingray/time/TDTTimeSourceId.h>
#include <stingray/time/TransportsTimeSourceObtainer.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbc/DVBCTransport.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSubscriptionRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::SimpleRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionLease);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BissSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Provider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Subscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SubscriptionBundle);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SoftwareCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SatIpClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::ContentDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::PvrDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<NetworkConfigurationStatus>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuScanPerformerFactory);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(PushVODEmulationMovie);
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(StreamableServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AutoCreatedListMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::StatisticChannelInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BuiltinTimeSourceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TDTTimeSourceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TransportTimeOffset);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: editxml.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: cl $ $Date: 2001-07-20 13:49:51 $
*
* 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 EXPRESSED 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 _SVX_EDITXML_HXX
#define _SVX_EDITXML_HXX
class EditEngine;
class SvStream;
struct ESelection;
/** this function exports the selected content of an edit engine into a xml stream*/
extern void SvxWriteXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel );
/** this function imports xml from the stream into the selected of an edit engine */
extern void SvxReadXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel );
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1654); FILE MERGED 2005/09/05 14:25:03 rt 1.2.1654.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: editxml.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:13:22 $
*
* 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 _SVX_EDITXML_HXX
#define _SVX_EDITXML_HXX
class EditEngine;
class SvStream;
struct ESelection;
/** this function exports the selected content of an edit engine into a xml stream*/
extern void SvxWriteXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel );
/** this function imports xml from the stream into the selected of an edit engine */
extern void SvxReadXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel );
#endif
<|endoftext|>
|
<commit_before><commit_msg>fix warnings in glog symbolize<commit_after><|endoftext|>
|
<commit_before><commit_msg>From Olivier: - in TPad::x3d: delete fViewer3D, if it exists, before creating a new 3D<commit_after><|endoftext|>
|
<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
* @file iutest_tap_printer_listener_tests.cpp
* @brief TAPPrintListener test
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2014, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
//======================================================================
// include
#include "iutest.hpp"
#include "../include/listener/iutest_tap_printer.hpp"
#include "iutest_logger_tests.hpp"
#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_STRINGSTREAM && IUTEST_HAS_ASSERTION_RETURN
# define TAP_TEST 1
#else
# define TAP_TEST 0
#endif
#if TAP_TEST
class FileIO : public ::iutest::StringStreamFile
{
public:
static ::std::string s_io;
virtual void Close()
{
s_io += ss.str();
}
};
::std::string FileIO::s_io;
IUTEST_FILESYSTEM_INSTANTIATE(FileIO);
const char tap_test_str[] =
"# Foo started.\n"
"ok 1 - Ok\n"
"# Foo ended.\n"
"1..1\n"
"# Bar started.\n"
"ok 1 # SKIP - DISABLED_Ng\n"
"# Bar ended.\n"
"1..1\n"
;
IUTEST(Foo, Ok)
{
IUTEST_SUCCEED() << "not show.";
}
IUTEST(Bar, DISABLED_Ng)
{
IUTEST_FAIL() << "show failed.\n test.";
}
#endif
#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
#if TAP_TEST
IUTEST_INIT(&argc, argv);
#if defined(OUTPUTXML)
// 失敗テストを含むので xml 出力しない
::iutest::IUTEST_FLAG(output) = NULL;
#endif
#if !defined(IUTEST_USE_GTEST)
::iutest::TAPFileGeneratorListener::SetUp();
#endif
{
if( IUTEST_RUN_ALL_TESTS() != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST)
IUTEST_EXPECT_STREQ(tap_test_str, FileIO::s_io.c_str());
FileIO::s_io.clear();
#endif
if( ::iutest::UnitTest::GetInstance()->Failed() ) return 1;
}
{
::iutest::IUTEST_FLAG(filter) = "*Hoge*";
::iutest::IUTEST_FLAG(also_run_disabled_tests) = false;
if( IUTEST_RUN_ALL_TESTS() != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_ASSERTION_RETURN
IUTEST_EXPECT_STRIN("*Hoge*", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);
FileIO::s_io.clear();
#endif
}
{
::iutest::IUTEST_FLAG(filter) = NULL;
::iutest::IUTEST_FLAG(also_run_disabled_tests) = true;
if( IUTEST_RUN_ALL_TESTS() == 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_ASSERTION_RETURN
IUTEST_EXPECT_STRIN("not ok", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);
IUTEST_EXPECT_STRIN("show failed., test.", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);
FileIO::s_io.clear();
#endif
}
printf("*** Successful ***\n");
#else
(void)argc;
(void)argv;
printf("*** TAP_TEST=0 ***\n");
#endif
return 0;
}
<commit_msg>update r749<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
* @file iutest_tap_printer_listener_tests.cpp
* @brief TAPPrintListener test
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2014, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
//======================================================================
// include
#include "iutest.hpp"
#include "../include/listener/iutest_tap_printer.hpp"
#include "iutest_logger_tests.hpp"
#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_STRINGSTREAM && IUTEST_HAS_ASSERTION_RETURN
# define TAP_TEST 1
#else
# define TAP_TEST 0
#endif
#if TAP_TEST
class FileIO : public ::iutest::StringStreamFile
{
public:
static ::std::string s_io;
virtual void Close()
{
s_io += ss.str();
}
};
::std::string FileIO::s_io;
IUTEST_FILESYSTEM_INSTANTIATE(FileIO);
const char tap_test_str[] =
"# Foo started.\n"
"ok 1 - Ok\n"
"# Foo ended.\n"
"1..1\n"
"# Bar started.\n"
"ok 1 # SKIP - DISABLED_Ng\n"
"# Bar ended.\n"
"1..1\n"
;
IUTEST(Foo, Ok)
{
IUTEST_SUCCEED() << "not show.";
}
IUTEST(Bar, DISABLED_Ng)
{
IUTEST_FAIL() << "show failed.\n test.";
}
#endif
#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
#if TAP_TEST
IUTEST_INIT(&argc, argv);
// xml 出力しない
::iutest::IUTEST_FLAG(output) = NULL;
#if !defined(IUTEST_USE_GTEST)
::iutest::TAPFileGeneratorListener::SetUp();
#endif
{
if( IUTEST_RUN_ALL_TESTS() != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST)
IUTEST_EXPECT_STREQ(tap_test_str, FileIO::s_io.c_str());
FileIO::s_io.clear();
#endif
if( ::iutest::UnitTest::GetInstance()->Failed() ) return 1;
}
{
::iutest::IUTEST_FLAG(filter) = "*Hoge*";
::iutest::IUTEST_FLAG(also_run_disabled_tests) = false;
if( IUTEST_RUN_ALL_TESTS() != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_ASSERTION_RETURN
IUTEST_EXPECT_STRIN("*Hoge*", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);
FileIO::s_io.clear();
#endif
}
{
::iutest::IUTEST_FLAG(filter) = NULL;
::iutest::IUTEST_FLAG(also_run_disabled_tests) = true;
if( IUTEST_RUN_ALL_TESTS() == 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_ASSERTION_RETURN
IUTEST_EXPECT_STRIN("not ok", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);
IUTEST_EXPECT_STRIN("show failed., test.", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);
FileIO::s_io.clear();
#endif
}
printf("*** Successful ***\n");
#else
(void)argc;
(void)argv;
printf("*** TAP_TEST=0 ***\n");
#endif
return 0;
}
<|endoftext|>
|
<commit_before>#include "benchmark/benchmark_api.h"
#include "test_configs.h"
#include "test_utils.h"
#include<algorithm>
#include<deque>
#include<list>
#include<vector>
// TODO: reverse, rotate, shuffle, lower_bound, upper_bound
// uninitialized_fill, uninitialized_copy
// change data type (int, double, class { int, int }, and compare
// algorithms.
#ifndef NDEBUG
#include<iostream>
template<typename T>
std::ostream& operator<<(std::ostream& os,const std::vector<T>& v)
{
for(typename std::vector<T>::const_iterator i = v.begin(); i!= v.end(); ++i)
os<<*i<<' ';
os<< "\n";
return os;
}
#endif
template<typename V>
void BM_sort_std(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_random(v);
while (state.KeepRunning()) {
std::sort(v.begin(), v.end());
}
state.SetComplexityN(N);
}
// Sort (a sequence in ascending order) in ascending order.
template<typename V>
void BM_sort_std_ascending(benchmark::State& state) {
int N = state.range(0);
using T = typename V::value_type;
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
std::sort(v.begin(), v.end(), std::less<T>());
}
state.SetComplexityN(N);
}
// Sort (a sequence in ascending order) in descending order.
template<typename V>
void BM_sort_std_descending(benchmark::State& state) {
int N = state.range(0);
using T = typename V::value_type;
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
std::sort(v.begin(), v.end(), std::greater<T>());
}
state.SetComplexityN(N);
}
template<typename V>
void BM_sort_stable(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_random(v);
while (state.KeepRunning()) {
std::stable_sort(v.begin(), v.end());
}
state.SetComplexityN(N);
}
template<typename V>
void BM_search_linear(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
// searching for all the elements.
for (int i = 0; i < N; ++i) {
auto j = std::find(v.begin(), v.end(), i);
benchmark::DoNotOptimize(j);
assert(std::distance(v.begin(), j) == i); // j is the i-th element in v
}
}
state.SetComplexityN(N);
}
template<typename V>
void BM_search_binary(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
// searching for all the elements.
for (int i = 0; i < N; ++i) {
auto j = std::lower_bound(v.begin(), v.end(), i);
benchmark::DoNotOptimize(j);
assert(std::distance(v.begin(), j) == i); // j is the i-th element in v
}
}
state.SetComplexityN(N);
}
static const int MSize = L1;
#define COMPLEXITY_BENCHMARK_GEN_T(T) \
COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::vector<T>, MSize); \
COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::list<T>, MSize); \
COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::deque<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::list<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::deque<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_sort_std, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_sort_std_ascending, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_sort_std_descending, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_sort_stable, std::vector<T>, MSize);
// TODO: Find a better name for TYPED_BENCHMARK
COMPLEXITY_BENCHMARK_GEN_T(int)
//COMPLEXITY_BENCHMARK_GEN_T(double)
COMPLEXITY_BENCHMARK_GEN_T(aggregate)
BENCHMARK_MAIN()
<commit_msg>adding sorting of std::list with the help of a vector<commit_after>#include "benchmark/benchmark_api.h"
#include "test_configs.h"
#include "test_utils.h"
#include<algorithm>
#include<deque>
#include<list>
#include<vector>
// TODO: reverse, rotate, shuffle, lower_bound, upper_bound
// uninitialized_fill, uninitialized_copy
// change data type (int, double, class { int, int }, and compare
// algorithms.
#ifndef NDEBUG
#include<iostream>
template<typename T>
std::ostream& operator<<(std::ostream& os,const std::vector<T>& v)
{
for(typename std::vector<T>::const_iterator i = v.begin(); i!= v.end(); ++i)
os<<*i<<' ';
os<< "\n";
return os;
}
#endif
template<typename V>
void BM_sort_std(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_random(v);
while (state.KeepRunning()) {
std::sort(v.begin(), v.end());
}
state.SetComplexityN(N);
}
template<typename V>
void BM_sort_std_list_with_vector(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_random(v);
using T = typename V::value_type;
// Copy the contents into a vector
while (state.KeepRunning()) {
std::vector<T> vec(v.begin(), v.end());
// Sort the vector
std::sort(vec.begin(), vec.end());
// Put the item back in the list
v.assign(vec.begin(), vec.end());
}
state.SetComplexityN(N);
}
// Sort (a sequence in ascending order) in ascending order.
template<typename V>
void BM_sort_std_ascending(benchmark::State& state) {
int N = state.range(0);
using T = typename V::value_type;
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
std::sort(v.begin(), v.end(), std::less<T>());
}
state.SetComplexityN(N);
}
// Sort (a sequence in ascending order) in descending order.
template<typename V>
void BM_sort_std_descending(benchmark::State& state) {
int N = state.range(0);
using T = typename V::value_type;
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
std::sort(v.begin(), v.end(), std::greater<T>());
}
state.SetComplexityN(N);
}
template<typename V>
void BM_sort_stable(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_random(v);
while (state.KeepRunning()) {
std::stable_sort(v.begin(), v.end());
}
state.SetComplexityN(N);
}
template<typename V>
void BM_search_linear(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
// searching for all the elements.
for (int i = 0; i < N; ++i) {
auto j = std::find(v.begin(), v.end(), i);
benchmark::DoNotOptimize(j);
assert(std::distance(v.begin(), j) == i); // j is the i-th element in v
}
}
state.SetComplexityN(N);
}
template<typename V>
void BM_search_binary(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
// searching for all the elements.
for (int i = 0; i < N; ++i) {
auto j = std::lower_bound(v.begin(), v.end(), i);
benchmark::DoNotOptimize(j);
assert(std::distance(v.begin(), j) == i); // j is the i-th element in v
}
}
state.SetComplexityN(N);
}
static const int MSize = L1;
#define COMPLEXITY_BENCHMARK_GEN_T(T) \
COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::vector<T>, MSize); \
COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::list<T>, MSize); \
COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::deque<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::list<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::deque<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_sort_std, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_sort_std_ascending, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_sort_std_descending, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_sort_stable, std::vector<T>, MSize);
// TODO: Find a better name for TYPED_BENCHMARK
COMPLEXITY_BENCHMARK_GEN_T(int)
//COMPLEXITY_BENCHMARK_GEN_T(double)
COMPLEXITY_BENCHMARK_GEN_T(aggregate)
COMPLEXITY_BENCHMARK_GEN(BM_sort_std_list_with_vector, std::list<int>, MSize);
COMPLEXITY_BENCHMARK_GEN(BM_sort_std_list_with_vector, std::list<aggregate>, MSize);
BENCHMARK_MAIN()
<|endoftext|>
|
<commit_before>#pragma once
#include <iostream>
#include <unordered_map>
#include <map>
#include <tuple>
#include <type_traits>
#include "base/header.hpp"
#include "base/function_traits.hpp"
#include "base/thread_pool.hpp"
#include "base/logger.hpp"
#include "base/singleton.hpp"
#include "base/serialize_util.hpp"
#include "connection.hpp"
namespace czrpc
{
namespace server
{
class invoker_function
{
public:
using function_t = std::function<void(const message_ptr&, message_ptr&)>;
invoker_function() = default;
invoker_function(const function_t& func) : func_(func) {}
void operator()(const std::string& call_id, const std::string& message_name,
const std::string& body, const connection_ptr& conn)
{
try
{
message_ptr out_message;
func_(serialize_util::singleton::get()->deserialize(message_name, body), out_message);
std::string in_message_name = out_message->GetDescriptor()->full_name();
std::string in_body = serialize_util::singleton::get()->serialize(out_message);
if (!in_message_name.empty() && !in_body.empty())
{
conn->async_write(response_content{ call_id, in_message_name, in_body });
}
}
catch (std::exception& e)
{
log_warn(e.what());
conn->disconnect();
}
}
private:
function_t func_ = nullptr;
};
class invoker_function_raw
{
public:
using function_t = std::function<void(const std::string&, std::string&)>;
invoker_function_raw() = default;
invoker_function_raw(const function_t& func) : func_(func) {}
void operator()(const std::string& call_id, const std::string& body, const connection_ptr& conn)
{
try
{
std::string out_body;
func_(body, out_body);
if (!out_body.empty())
{
conn->async_write(response_content{ call_id, "", out_body });
}
}
catch (std::exception& e)
{
log_warn(e.what());
conn->disconnect();
}
}
private:
function_t func_ = nullptr;
};
class router
{
DEFINE_SINGLETON(router);
public:
router() = default;
void multithreaded(std::size_t num)
{
threadpool_.init_thread_num(num);
}
void stop()
{
threadpool_.stop();
}
template<typename Function>
void bind(const std::string& protocol, const Function& func)
{
bind_non_member_func(protocol, func);
}
template<typename Function, typename Self>
void bind(const std::string& protocol, const Function& func, Self* self)
{
bind_member_func(protocol, func, self);
}
void unbind(const std::string& protocol)
{
std::lock_guard<std::mutex> lock(map_mutex_);
invoker_map_.erase(protocol);
}
bool is_bind(const std::string& protocol)
{
std::lock_guard<std::mutex> lock(map_mutex_);
auto iter = invoker_map_.find(protocol);
if (iter != invoker_map_.end())
{
return true;
}
return false;
}
template<typename Function>
void bind_raw(const std::string& protocol, const Function& func)
{
bind_non_member_func_raw(protocol, func);
}
template<typename Function, typename Self>
void bind_raw(const std::string& protocol, const Function& func, Self* self)
{
bind_member_func_raw(protocol, func, self);
}
void unbind_raw(const std::string& protocol)
{
std::lock_guard<std::mutex> lock(raw_map_mutex_);
invoker_raw_map_.erase(protocol);
}
bool is_bind_raw(const std::string& protocol)
{
std::lock_guard<std::mutex> lock(raw_map_mutex_);
auto iter = invoker_raw_map_.find(protocol);
if (iter != invoker_raw_map_.end())
{
return true;
}
return false;
}
bool route(const request_content& content, const client_flag& flag, const connection_ptr& conn)
{
if (flag.type == client_type::rpc_client)
{
if (flag.mode == serialize_mode::serialize)
{
std::lock_guard<std::mutex> lock(map_mutex_);
auto iter = invoker_map_.find(content.protocol);
if (iter == invoker_map_.end())
{
return false;
}
threadpool_.add_task(iter->second, content.call_id, content.message_name, content.body, conn);
}
else if (flag.mode == serialize_mode::non_serialize)
{
std::lock_guard<std::mutex> lock(raw_map_mutex_);
auto iter = invoker_raw_map_.find(content.protocol);
if (iter == invoker_raw_map_.end())
{
return false;
}
threadpool_.add_task(iter->second, content.call_id, content.body, conn);
}
else
{
log_warn("Invaild serialize mode: {}", static_cast<unsigned int>(flag.mode));
return false;
}
}
else if (flag.type == client_type::pub_client)
{
threadpool_.add_task(pub_coming_helper_, content.protocol, content.body, flag.mode);
}
else if (flag.type == client_type::sub_client)
{
threadpool_.add_task(sub_coming_helper_, content.protocol, content.body, conn);
}
else
{
log_warn("Invaild client type: {}", static_cast<unsigned int>(flag.type));
return false;
}
return true;
}
private:
template<typename Function>
static typename std::enable_if<std::is_void<typename std::result_of<Function(const message_ptr&)>::type>::value>::type
call(const Function& func, const message_ptr& in_message, message_ptr&)
{
func(in_message);
}
template<typename Function>
static typename std::enable_if<!std::is_void<typename std::result_of<Function(const message_ptr&)>::type>::value>::type
call(const Function& func, const message_ptr& in_message, message_ptr& out_message)
{
out_message = func(in_message);
}
template<typename Function, typename Self>
static typename std::enable_if<std::is_void<typename std::result_of<Function(Self, const message_ptr&)>::type>::value>::type
call_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr&)
{
(*self.*func)(in_message);
}
template<typename Function, typename Self>
static typename std::enable_if<!std::is_void<typename std::result_of<Function(Self, const message_ptr&)>::type>::value>::type
call_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr& out_message)
{
out_message = (*self.*func)(in_message);
}
template<typename Function>
static typename std::enable_if<std::is_void<typename std::result_of<Function(const std::string&)>::type>::value>::type
call_raw(const Function& func, const std::string& body, std::string&)
{
func(body);
}
template<typename Function>
static typename std::enable_if<!std::is_void<typename std::result_of<Function(const std::string&)>::type>::value>::type
call_raw(const Function& func, const std::string& body, std::string& out_body)
{
out_body = func(body);
}
template<typename Function, typename Self>
static typename std::enable_if<std::is_void<typename std::result_of<Function(Self, const std::string&)>::type>::value>::type
call_member_raw(const Function& func, Self* self, const std::string& body, std::string&)
{
(*self.*func)(body);
}
template<typename Function, typename Self>
static typename std::enable_if<!std::is_void<typename std::result_of<Function(Self, const std::string&)>::type>::value>::type
call_member_raw(const Function& func, Self* self, const std::string& body, std::string& out_body)
{
out_body = (*self.*func)(body);
}
private:
template<typename Function>
class invoker
{
public:
static void apply(const Function& func, const message_ptr& in_message, message_ptr& out_message)
{
try
{
call(func, in_message, out_message);
}
catch (std::exception& e)
{
log_warn(e.what());
}
}
template<typename Self>
static void apply_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr& out_message)
{
try
{
call_member(func, self, in_message, out_message);
}
catch (std::exception& e)
{
log_warn(e.what());
}
}
};
template<typename Function>
class invoker_raw
{
public:
static void apply(const Function& func, const std::string& body, std::string& out_body)
{
try
{
call_raw(func, body, out_body);
}
catch (std::exception& e)
{
log_warn(e.what());
}
}
template<typename Self>
static void apply_member(const Function& func, Self* self, const std::string& body, std::string& out_body)
{
try
{
call_member_raw(func, self, body, out_body);
}
catch (std::exception& e)
{
log_warn(e.what());
}
}
};
struct pub_coming_helper
{
void operator()(const std::string& topic_name, const std::string& body, serialize_mode mode)
{
router::singleton::get()->publisher_coming_(topic_name, body, mode);
}
};
struct sub_coming_helper
{
void operator()(const std::string& topic_name, const std::string& body, const connection_ptr& conn)
{
router::singleton::get()->subscriber_coming_(topic_name, body, conn);
}
};
private:
template<typename Function>
void bind_non_member_func(const std::string& protocol, const Function& func)
{
std::lock_guard<std::mutex> lock(map_mutex_);
invoker_map_[protocol] = { std::bind(&invoker<Function>::apply, func,
std::placeholders::_1, std::placeholders::_2) };
}
template<typename Function, typename Self>
void bind_member_func(const std::string& protocol, const Function& func, Self* self)
{
std::lock_guard<std::mutex> lock(map_mutex_);
invoker_map_[protocol] = { std::bind(&invoker<Function>::template apply_member<Self>, func, self,
std::placeholders::_1, std::placeholders::_2) };
}
template<typename Function>
void bind_non_member_func_raw(const std::string& protocol, const Function& func)
{
std::lock_guard<std::mutex> lock(raw_map_mutex_);
invoker_raw_map_[protocol] = { std::bind(&invoker_raw<Function>::apply, func,
std::placeholders::_1, std::placeholders::_2) };
}
template<typename Function, typename Self>
void bind_member_func_raw(const std::string& protocol, const Function& func, Self* self)
{
std::lock_guard<std::mutex> lock(raw_map_mutex_);
invoker_raw_map_[protocol] = { std::bind(&invoker_raw<Function>::template apply_member<Self>, func, self,
std::placeholders::_1, std::placeholders::_2) };
}
public:
using pub_comming_callback = std::function<void(const std::string&, const std::string&, serialize_mode)>;
using sub_comming_callback = std::function<void(const std::string&, const std::string&, const connection_ptr&)>;
pub_comming_callback publisher_coming_ = nullptr;
sub_comming_callback subscriber_coming_ = nullptr;
private:
thread_pool threadpool_;
std::unordered_map<std::string, invoker_function> invoker_map_;
std::unordered_map<std::string, invoker_function_raw> invoker_raw_map_;
std::mutex map_mutex_;
std::mutex raw_map_mutex_;
pub_coming_helper pub_coming_helper_;
sub_coming_helper sub_coming_helper_;
};
}
}
<commit_msg>update router<commit_after>#pragma once
#include <iostream>
#include <unordered_map>
#include <map>
#include <tuple>
#include <type_traits>
#include "base/header.hpp"
#include "base/function_traits.hpp"
#include "base/thread_pool.hpp"
#include "base/logger.hpp"
#include "base/singleton.hpp"
#include "base/serialize_util.hpp"
#include "connection.hpp"
namespace czrpc
{
namespace server
{
class invoker_function
{
public:
using function_t = std::function<void(const message_ptr&, message_ptr&)>;
invoker_function() = default;
invoker_function(const function_t& func) : func_(func) {}
void operator()(const std::string& call_id, const std::string& message_name,
const std::string& body, const connection_ptr& conn)
{
try
{
message_ptr out_message;
func_(serialize_util::singleton::get()->deserialize(message_name, body), out_message);
std::string in_message_name = out_message->GetDescriptor()->full_name();
std::string in_body = serialize_util::singleton::get()->serialize(out_message);
if (!in_message_name.empty() && !in_body.empty())
{
conn->async_write(response_content{ call_id, in_message_name, in_body });
}
}
catch (std::exception& e)
{
log_warn(e.what());
conn->disconnect();
}
}
private:
function_t func_ = nullptr;
};
class invoker_function_raw
{
public:
using function_t = std::function<void(const std::string&, std::string&)>;
invoker_function_raw() = default;
invoker_function_raw(const function_t& func) : func_(func) {}
void operator()(const std::string& call_id, const std::string& body, const connection_ptr& conn)
{
try
{
std::string out_body;
func_(body, out_body);
if (!out_body.empty())
{
conn->async_write(response_content{ call_id, "", out_body });
}
}
catch (std::exception& e)
{
log_warn(e.what());
conn->disconnect();
}
}
private:
function_t func_ = nullptr;
};
class router
{
DEFINE_SINGLETON(router);
public:
router() = default;
void multithreaded(std::size_t num)
{
threadpool_.init_thread_num(num);
}
void stop()
{
threadpool_.stop();
}
template<typename Function>
void bind(const std::string& protocol, const Function& func)
{
bind_non_member_func(protocol, func);
}
template<typename Function, typename Self>
void bind(const std::string& protocol, const Function& func, Self* self)
{
bind_member_func(protocol, func, self);
}
void unbind(const std::string& protocol)
{
std::lock_guard<std::mutex> lock(map_mutex_);
invoker_map_.erase(protocol);
}
bool is_bind(const std::string& protocol)
{
std::lock_guard<std::mutex> lock(map_mutex_);
auto iter = invoker_map_.find(protocol);
if (iter != invoker_map_.end())
{
return true;
}
return false;
}
template<typename Function>
void bind_raw(const std::string& protocol, const Function& func)
{
bind_non_member_func_raw(protocol, func);
}
template<typename Function, typename Self>
void bind_raw(const std::string& protocol, const Function& func, Self* self)
{
bind_member_func_raw(protocol, func, self);
}
void unbind_raw(const std::string& protocol)
{
std::lock_guard<std::mutex> lock(raw_map_mutex_);
invoker_raw_map_.erase(protocol);
}
bool is_bind_raw(const std::string& protocol)
{
std::lock_guard<std::mutex> lock(raw_map_mutex_);
auto iter = invoker_raw_map_.find(protocol);
if (iter != invoker_raw_map_.end())
{
return true;
}
return false;
}
bool route(const request_content& content, const client_flag& flag, const connection_ptr& conn)
{
if (flag.type == client_type::rpc_client)
{
if (flag.mode == serialize_mode::serialize)
{
std::lock_guard<std::mutex> lock(map_mutex_);
auto iter = invoker_map_.find(content.protocol);
if (iter == invoker_map_.end())
{
return false;
}
threadpool_.add_task(iter->second, content.call_id, content.message_name, content.body, conn);
}
else if (flag.mode == serialize_mode::non_serialize)
{
std::lock_guard<std::mutex> lock(raw_map_mutex_);
auto iter = invoker_raw_map_.find(content.protocol);
if (iter == invoker_raw_map_.end())
{
return false;
}
threadpool_.add_task(iter->second, content.call_id, content.body, conn);
}
else
{
log_warn("Invaild serialize mode: {}", static_cast<unsigned int>(flag.mode));
return false;
}
}
else if (flag.type == client_type::pub_client)
{
threadpool_.add_task(pub_coming_helper_, content.protocol, content.body, flag.mode);
}
else if (flag.type == client_type::sub_client)
{
threadpool_.add_task(sub_coming_helper_, content.protocol, content.body, conn);
}
else
{
log_warn("Invaild client type: {}", static_cast<unsigned int>(flag.type));
return false;
}
return true;
}
private:
template<typename Function>
static typename std::enable_if<std::is_void<typename std::result_of<Function(const message_ptr&)>::type>::value>::type
call(const Function& func, const message_ptr& in_message, message_ptr&)
{
func(in_message);
}
template<typename Function>
static typename std::enable_if<!std::is_void<typename std::result_of<Function(const message_ptr&)>::type>::value>::type
call(const Function& func, const message_ptr& in_message, message_ptr& out_message)
{
out_message = func(in_message);
}
template<typename Function, typename Self>
static typename std::enable_if<std::is_void<typename std::result_of<Function(Self, const message_ptr&)>::type>::value>::type
call_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr&)
{
(*self.*func)(in_message);
}
template<typename Function, typename Self>
static typename std::enable_if<!std::is_void<typename std::result_of<Function(Self, const message_ptr&)>::type>::value>::type
call_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr& out_message)
{
out_message = (*self.*func)(in_message);
}
template<typename Function>
static typename std::enable_if<std::is_void<typename std::result_of<Function(const std::string&)>::type>::value>::type
call_raw(const Function& func, const std::string& body, std::string&)
{
func(body);
}
template<typename Function>
static typename std::enable_if<!std::is_void<typename std::result_of<Function(const std::string&)>::type>::value>::type
call_raw(const Function& func, const std::string& body, std::string& out_body)
{
out_body = func(body);
}
template<typename Function, typename Self>
static typename std::enable_if<std::is_void<typename std::result_of<Function(Self, const std::string&)>::type>::value>::type
call_member_raw(const Function& func, Self* self, const std::string& body, std::string&)
{
(*self.*func)(body);
}
template<typename Function, typename Self>
static typename std::enable_if<!std::is_void<typename std::result_of<Function(Self, const std::string&)>::type>::value>::type
call_member_raw(const Function& func, Self* self, const std::string& body, std::string& out_body)
{
out_body = (*self.*func)(body);
}
private:
template<typename Function>
class invoker
{
public:
static void apply(const Function& func, const message_ptr& in_message, message_ptr& out_message)
{
try
{
call(func, in_message, out_message);
}
catch (std::exception& e)
{
log_warn(e.what());
}
}
template<typename Self>
static void apply_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr& out_message)
{
try
{
call_member(func, self, in_message, out_message);
}
catch (std::exception& e)
{
log_warn(e.what());
}
}
};
template<typename Function>
class invoker_raw
{
public:
static void apply(const Function& func, const std::string& body, std::string& out_body)
{
try
{
call_raw(func, body, out_body);
}
catch (std::exception& e)
{
log_warn(e.what());
}
}
template<typename Self>
static void apply_member(const Function& func, Self* self, const std::string& body, std::string& out_body)
{
try
{
call_member_raw(func, self, body, out_body);
}
catch (std::exception& e)
{
log_warn(e.what());
}
}
};
struct pub_coming_helper
{
void operator()(const std::string& topic_name, const std::string& body, serialize_mode mode)
{
router::singleton::get()->publisher_coming_(topic_name, body, mode);
}
};
struct sub_coming_helper
{
void operator()(const std::string& topic_name, const std::string& body, const connection_ptr& conn)
{
router::singleton::get()->subscriber_coming_(topic_name, body, conn);
}
};
private:
template<typename Function>
void bind_non_member_func(const std::string& protocol, const Function& func)
{
std::lock_guard<std::mutex> lock(map_mutex_);
invoker_map_.emplace(protocol, invoker_function{ std::bind(&invoker<Function>::apply,
func, std::placeholders::_1, std::placeholders::_2) });
}
template<typename Function, typename Self>
void bind_member_func(const std::string& protocol, const Function& func, Self* self)
{
std::lock_guard<std::mutex> lock(map_mutex_);
invoker_map_.emplace(protocol, invoker_function{ std::bind(&invoker<Function>::template apply_member<Self>,
func, self, std::placeholders::_1, std::placeholders::_2) });
}
template<typename Function>
void bind_non_member_func_raw(const std::string& protocol, const Function& func)
{
std::lock_guard<std::mutex> lock(raw_map_mutex_);
invoker_raw_map_.emplace(protocol, invoker_function_raw{ std::bind(&invoker_raw<Function>::apply,
func, std::placeholders::_1, std::placeholders::_2) });
}
template<typename Function, typename Self>
void bind_member_func_raw(const std::string& protocol, const Function& func, Self* self)
{
std::lock_guard<std::mutex> lock(raw_map_mutex_);
invoker_raw_map_.emplace(protocol, invoker_function_raw{ std::bind(&invoker_raw<Function>::template apply_member<Self>,
func, self, std::placeholders::_1, std::placeholders::_2) });
}
public:
using pub_comming_callback = std::function<void(const std::string&, const std::string&, serialize_mode)>;
using sub_comming_callback = std::function<void(const std::string&, const std::string&, const connection_ptr&)>;
pub_comming_callback publisher_coming_ = nullptr;
sub_comming_callback subscriber_coming_ = nullptr;
private:
thread_pool threadpool_;
std::unordered_map<std::string, invoker_function> invoker_map_;
std::unordered_map<std::string, invoker_function_raw> invoker_raw_map_;
std::mutex map_mutex_;
std::mutex raw_map_mutex_;
pub_coming_helper pub_coming_helper_;
sub_coming_helper sub_coming_helper_;
};
}
}
<|endoftext|>
|
<commit_before>#include "d2stringtablewidget.h"
#include <QProgressDialog>
#include <QKeyEvent>
#include <QListWidgetItem>
#include <QAction>
#ifndef QT_NO_DEBUG
#include <QDebug>
#endif
D2StringTableWidget::D2StringTableWidget(QWidget *parent) : QTableWidget(parent), _displayRowHex(false), _addToRowValue(true)
{
setStyleSheet("QTableWidget::item:!active { selection-background-color: #999999 }");
horizontalHeader()->
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
setSectionsClickable
#else
setClickable
#endif
(false);
}
void D2StringTableWidget::keyPressEvent(QKeyEvent *keyEvent)
{
switch (keyEvent->key())
{
#ifndef Q_OS_MAC
case Qt::Key_Enter: // Return (usual Enter) or Enter (on the numpad)
#endif
case Qt::Key_Return: // starts editing of the current selected cell
if (state() != QAbstractItemView::EditingState)
emit itemDoubleClicked(currentItem());
break;
// in-place edit
#ifdef Q_OS_MAC
case Qt::Key_Enter:
#else
case Qt::Key_F2:
#endif
editInPlace();
break;
case Qt::Key_Home: // Home or Ctrl+Home goes to the first cell
if (keyEvent->modifiers() == Qt::NoModifier || keyEvent->modifiers() == Qt::ControlModifier)
setCurrentCell(0, 0, QItemSelectionModel::ClearAndSelect);
break;
case Qt::Key_End: // End or Ctrl+End goes to the last cell
if (keyEvent->modifiers() == Qt::NoModifier || keyEvent->modifiers() == Qt::ControlModifier)
setCurrentCell(rowCount() - 1, 1, QItemSelectionModel::ClearAndSelect);
break;
default:
QTableWidget::keyPressEvent(keyEvent);
break;
}
}
void D2StringTableWidget::deleteItems(bool isClear)
{
QList<QTableWidgetSelectionRange> ranges(selectedRanges());
int elementsToDelete = 0;
for (int i = 0; i < ranges.size(); i++)
elementsToDelete += ranges.at(i).rowCount();
// deleting rows is a long process, so progress dialog is shown
QProgressDialog progress(tr("Deleting selected rows..."), tr("Cancel"), 0, elementsToDelete, this);
progress.setWindowModality(Qt::WindowModal);
for (int i = 0, rowShift = 0; i < ranges.size(); ++i)
{
const QTableWidgetSelectionRange &range = ranges.at(i);
if (isClear) // Only Delete pressed, clears selected items
{
for (int j = range.topRow(); j <= range.bottomRow(); ++j)
for (int k = range.leftColumn(); k <= range.rightColumn(); ++k)
item(j, k)->setText(QString());
}
else // Shift+Delete pressed, removes selected rows
{
for (int k = 0; k < range.rowCount(); ++k)
{
progress.setValue((i + 1) * k);
if (progress.wasCanceled())
return;
removeRow(range.topRow() - rowShift);
}
rowShift += range.rowCount();
emit currentCellChanged(currentRow(), 0, 0, 0);
}
}
progress.setValue(elementsToDelete);
if (!isClear)
changeRowHeaderDisplay();
}
void D2StringTableWidget::createRowAt(int row)
{
insertRow(row);
setItem(row, 0, new QTableWidgetItem);
setItem(row, 1, new QTableWidgetItem);
setCurrentCell(row, 0, QItemSelectionModel::ClearAndSelect);
emit currentCellChanged(row, 0, 0, 0);
}
void D2StringTableWidget::createNewEntry(int row, const QString &key, const QString &val)
{
setItem(row, 0, new QTableWidgetItem(key.isEmpty() || key == "\"" ? QString() : key.split('\"', QString::SkipEmptyParts).at(0)));
setItem(row, 1, new QTableWidgetItem(val.isEmpty() || val == "\"" ? QString() : val.split('\"', QString::SkipEmptyParts).at(0)));
}
void D2StringTableWidget::mousePressEvent(QMouseEvent *mouseEvent)
{
emit tableGotFocus(parentWidget());
QTableWidget::mousePressEvent(mouseEvent);
if (mouseEvent->button() == Qt::RightButton)
editInPlace();
}
void D2StringTableWidget::clearBackground()
{
// without blocking cells will become green again immediately
blockSignals(true);
foreach (QTableWidgetItem *item, _editedItems)
item->setBackground(QBrush(Qt::white));
blockSignals(false);
_editedItems.clear();
}
void D2StringTableWidget::dropEvent(QDropEvent *event)
{
QTableWidgetItem *firstDroppedItem = itemAt(event->pos());
QList<QTableWidgetItem *> droppedItems;
QStringList oldTexts;
QTableWidgetSelectionRange range = qobject_cast<QTableWidget *>(event->source())->selectedRanges().at(0);
for (int i = 0, rows = range.bottomRow() - range.topRow(), cols = range.rightColumn() - range.leftColumn(); i <= rows; ++i)
{
for (int j = 0; j <= cols; ++j)
{
QTableWidgetItem *anItem = item(firstDroppedItem->row() + i, firstDroppedItem->column() + j);
droppedItems += anItem;
oldTexts += anItem->text();
}
}
QTableWidget::dropEvent(event);
for (int i = 0; i < droppedItems.size(); ++i)
{
QTableWidgetItem *anItem = droppedItems.at(i);
if (anItem->text() != oldTexts.at(i))
emit itemWasDropped(anItem);
}
}
void D2StringTableWidget::toggleDisplayHex(bool toggled)
{
_displayRowHex = toggled;
changeRowHeaderDisplay();
}
void D2StringTableWidget::changeRowNumberingTo1(bool toggled)
{
_addToRowValue = toggled;
changeRowHeaderDisplay();
}
void D2StringTableWidget::changeRowHeaderDisplay()
{
QStringList rowLabels;
for (int i = 0; i < rowCount(); ++i)
{
int row = i + _addToRowValue;
QString rowText = QString::number(row);
if (_displayRowHex)
rowText += QString(" (0x%2)").arg(row, 0, 16);
#ifdef Q_OS_MAC
rowText += " "; // fixes slight text truncation
#endif
rowLabels += rowText;
}
setVerticalHeaderLabels(rowLabels);
}
<commit_msg>fix crash on saving when edited row was removed<commit_after>#include "d2stringtablewidget.h"
#include <QProgressDialog>
#include <QKeyEvent>
#include <QListWidgetItem>
#include <QAction>
#ifndef QT_NO_DEBUG
#include <QDebug>
#endif
D2StringTableWidget::D2StringTableWidget(QWidget *parent) : QTableWidget(parent), _displayRowHex(false), _addToRowValue(true)
{
setStyleSheet("QTableWidget::item:!active { selection-background-color: #999999 }");
horizontalHeader()->
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
setSectionsClickable
#else
setClickable
#endif
(false);
}
void D2StringTableWidget::keyPressEvent(QKeyEvent *keyEvent)
{
switch (keyEvent->key())
{
#ifndef Q_OS_MAC
case Qt::Key_Enter: // Return (usual Enter) or Enter (on the numpad)
#endif
case Qt::Key_Return: // starts editing of the current selected cell
if (state() != QAbstractItemView::EditingState)
emit itemDoubleClicked(currentItem());
break;
// in-place edit
#ifdef Q_OS_MAC
case Qt::Key_Enter:
#else
case Qt::Key_F2:
#endif
editInPlace();
break;
case Qt::Key_Home: // Home or Ctrl+Home goes to the first cell
if (keyEvent->modifiers() == Qt::NoModifier || keyEvent->modifiers() == Qt::ControlModifier)
setCurrentCell(0, 0, QItemSelectionModel::ClearAndSelect);
break;
case Qt::Key_End: // End or Ctrl+End goes to the last cell
if (keyEvent->modifiers() == Qt::NoModifier || keyEvent->modifiers() == Qt::ControlModifier)
setCurrentCell(rowCount() - 1, 1, QItemSelectionModel::ClearAndSelect);
break;
default:
QTableWidget::keyPressEvent(keyEvent);
break;
}
}
void D2StringTableWidget::deleteItems(bool isClear)
{
QList<QTableWidgetSelectionRange> ranges(selectedRanges());
int elementsToDelete = 0;
for (int i = 0; i < ranges.size(); i++)
elementsToDelete += ranges.at(i).rowCount();
// deleting rows is a long process, so progress dialog is shown
QProgressDialog progress(tr("Deleting selected rows..."), tr("Cancel"), 0, elementsToDelete, this);
progress.setWindowModality(Qt::WindowModal);
for (int i = 0, rowShift = 0; i < ranges.size(); ++i)
{
const QTableWidgetSelectionRange &range = ranges.at(i);
if (isClear) // Only Delete pressed, clears selected items
{
for (int j = range.topRow(); j <= range.bottomRow(); ++j)
for (int k = range.leftColumn(); k <= range.rightColumn(); ++k)
item(j, k)->setText(QString());
}
else // Shift+Delete pressed, removes selected rows
{
for (int k = 0; k < range.rowCount(); ++k)
{
progress.setValue((i + 1) * k);
if (progress.wasCanceled())
return;
int row = range.topRow() - rowShift;
removeRow(row);
_editedItems.remove(qMakePair<int, int>(row, 0));
_editedItems.remove(qMakePair<int, int>(row, 1));
}
rowShift += range.rowCount();
emit currentCellChanged(currentRow(), 0, 0, 0);
}
}
progress.setValue(elementsToDelete);
if (!isClear)
changeRowHeaderDisplay();
}
void D2StringTableWidget::createRowAt(int row)
{
insertRow(row);
setItem(row, 0, new QTableWidgetItem);
setItem(row, 1, new QTableWidgetItem);
setCurrentCell(row, 0, QItemSelectionModel::ClearAndSelect);
emit currentCellChanged(row, 0, 0, 0);
}
void D2StringTableWidget::createNewEntry(int row, const QString &key, const QString &val)
{
setItem(row, 0, new QTableWidgetItem(key.isEmpty() || key == "\"" ? QString() : key.split('\"', QString::SkipEmptyParts).at(0)));
setItem(row, 1, new QTableWidgetItem(val.isEmpty() || val == "\"" ? QString() : val.split('\"', QString::SkipEmptyParts).at(0)));
}
void D2StringTableWidget::mousePressEvent(QMouseEvent *mouseEvent)
{
emit tableGotFocus(parentWidget());
QTableWidget::mousePressEvent(mouseEvent);
if (mouseEvent->button() == Qt::RightButton)
editInPlace();
}
void D2StringTableWidget::clearBackground()
{
// without blocking cells will become green again immediately
blockSignals(true);
foreach (QTableWidgetItem *item, _editedItems)
item->setBackground(QBrush(Qt::white));
blockSignals(false);
_editedItems.clear();
}
void D2StringTableWidget::dropEvent(QDropEvent *event)
{
QTableWidgetItem *firstDroppedItem = itemAt(event->pos());
QList<QTableWidgetItem *> droppedItems;
QStringList oldTexts;
QTableWidgetSelectionRange range = qobject_cast<QTableWidget *>(event->source())->selectedRanges().at(0);
for (int i = 0, rows = range.bottomRow() - range.topRow(), cols = range.rightColumn() - range.leftColumn(); i <= rows; ++i)
{
for (int j = 0; j <= cols; ++j)
{
QTableWidgetItem *anItem = item(firstDroppedItem->row() + i, firstDroppedItem->column() + j);
droppedItems += anItem;
oldTexts += anItem->text();
}
}
QTableWidget::dropEvent(event);
for (int i = 0; i < droppedItems.size(); ++i)
{
QTableWidgetItem *anItem = droppedItems.at(i);
if (anItem->text() != oldTexts.at(i))
emit itemWasDropped(anItem);
}
}
void D2StringTableWidget::toggleDisplayHex(bool toggled)
{
_displayRowHex = toggled;
changeRowHeaderDisplay();
}
void D2StringTableWidget::changeRowNumberingTo1(bool toggled)
{
_addToRowValue = toggled;
changeRowHeaderDisplay();
}
void D2StringTableWidget::changeRowHeaderDisplay()
{
QStringList rowLabels;
for (int i = 0; i < rowCount(); ++i)
{
int row = i + _addToRowValue;
QString rowText = QString::number(row);
if (_displayRowHex)
rowText += QString(" (0x%2)").arg(row, 0, 16);
#ifdef Q_OS_MAC
rowText += " "; // fixes slight text truncation
#endif
rowLabels += rowText;
}
setVerticalHeaderLabels(rowLabels);
}
<|endoftext|>
|
<commit_before>#include <csignal>
#include "bvs/bvs.h"
BVS::BVS* bvs;
BVS::Logger logger("Daemon");
void mainSignal(int sig);
void shutdownFunction();
int testLogger();
int testConfig();
/** BVSD namespace, contains only the bvs daemon. */
namespace BVSD
{
/** BVS framework's command line daemon.
* This is a simple command line daemon. It serves as a client to the BVS
* framework. It is also intended as a sample client.
*
* It is interactive, you can use the following commands by just entering them
* on the command line and then pressing enter (short versions are also
* available, enter 'help<enter>' to see them):
*
* @li \c run run system until paused.
* @li \c continue same as run
* @li \c step advance system by one step.
* @li \c pause pause(stop) system.
* @li \c test call test functions.
* @li \c quit shutdown system and quit.
* @li \c help show help.
*/
class BVSD
{
};
}
/** Main function, creates interactive loop. */
int main(int argc, char** argv)
{
signal(SIGINT, mainSignal);
LOG(2, "starting!");
bvs = new BVS::BVS(argc, argv, &shutdownFunction);
LOG(2, "loading modules!");
bvs->loadModules();
LOG(2, "connecting modules!");
bvs->connectAllModules();
LOG(2, "starting!");
bvs->start();
bvs->run();
std::string input;
while (input != "q" && input != "quit")
{
std::getline(std::cin, input);
if (input == "r" || input == "run" || input == "c" || input == "continue")
{
LOG(2, "RUN!!!");
bvs->run();
}
else if (input.empty() || input == "s" || input == "step")
{
LOG(2, "STEP!!!");
bvs->step();
}
else if (input == "p" || input == "pause")
{
LOG(2, "PAUSING!!!");
bvs->pause();
}
else if (input == "t" || input == "test")
{
testLogger();
testConfig();
}
else if (input.substr(0,2) == "hs" || input.substr(0, 7) == "hotswap")
{
size_t delimiter = input.find_first_of(" ");
input.erase(0, delimiter+1);
if (input.empty() || delimiter==std::string::npos) std::cout << "ERROR: no module ID given!" << std::endl;
else bvs->hotSwap(input);
}
else if (input == "q" || input == "quit")
{
LOG(2, "quitting...");
bvs->quit();
LOG(2, "finished!");
}
else if (input == "h" || input == "help")
{
std::cout << "usage:" << std::endl;
std::cout << " r|run run system until paused" << std::endl;
std::cout << " c|continue same as run" << std::endl;
std::cout << " s|step advance system by one step" << std::endl;
std::cout << " p|pause pause(stop) system" << std::endl;
std::cout << " hs|hotswap <arg> HotSwap(TM) <moduleID>" << std::endl;
std::cout << " t|test call test functions" << std::endl;
std::cout << " q|quit shutdown system and quit" << std::endl;
std::cout << " h|help show help" << std::endl;
}
else
{
std::cout << ">>> unknown command: " << input << std::endl << ">>> for help press 'h<enter>'!" << std::endl;
}
}
delete bvs;
return 0;
}
void mainSignal(int sig)
{
LOG(1,"Catched signal: " << sig << " (Ctrl-C), quitting!");
signal(SIGINT, SIG_DFL);
bvs->quit();
exit(0);
}
void shutdownFunction()
{
LOG(1,"daemon exit caused by bvs shutdown request!");
bvs->quit();
exit(0);
}
/** Performs some logger tests.
* This functions performs some tests on the logger system. Nothing fancy, can
* be studied to gain some insight into using the logger system.
*/
int testLogger()
{
LOG(0, "to CLI FILE");
bvs->disableLogConsole();
LOG(0, "to FILE only");
BVS::Logger file("FILE LOG", 3, BVS::Logger::TO_FILE);
file.out(0) << "FILE ONLY" << std::endl;
bvs->enableLogConsole();
BVS::Logger cli("CLI LOG", 3, BVS::Logger::TO_CLI);
cli.out(0) << "CLI ONLY" << std::endl;
bvs->disableLogConsole();
bvs->disableLogFile();
LOG(0, "NOOP");
bvs->enableLogConsole();
LOG(0, "to CLI");
bvs->disableLogConsole();
bvs->enableLogFile("BVSLog.txt", true);
LOG(0, "to FILE AGAIN");
bvs->enableLogConsole();
BVS::Logger both("to BOTH", 0, BVS::Logger::TO_CLI_AND_FILE);
both.out(0) << "to CLI AND FILE" << std::endl;
return 0;
}
/** Performs some config tests.
* This functions performs some tests on the config system. Nothing fancy, can
* be studied to gain some insight into using the config system.
*/
int testConfig()
{
LOG(0, "testing...");
int i;
std::string s;
bool b;
bvs->config.getValue("BVS.logVerbosity", i, 0)
.getValue("BVS.logFile", s, std::string("default"))
.getValue("BVS.logSystem", b, false);
LOG(0, "Getting int: " << i);
LOG(0, "Getting string: " << s);
LOG(0, "Getting bool: " << b);
i = bvs->config.getValue<int>("BVS.logVerbosity", 0);
s = bvs->config.getValue<std::string>("BVS.logFile", std::string("default"));
b = bvs->config.getValue<bool>("BVS.logSystem", false);
LOG(0, "Getting int directly: " << i);
LOG(0, "Getting string directly: " << s);
LOG(0, "Getting bool directly: " << b);
std::string empty;
bvs->config.getValue("this.option.does.not.exist", empty, std::string("empty"));
LOG(0, "This should be 'empty': " << empty);
std::vector<std::string> list;
bvs->config.getValue("BVS.modules", list);
LOG(0, "List: BVS.modules");
int count = 0;
for (auto& it : list)
{
(void) it;
(void) count;
LOG(0, count++ << ": " << it);
}
return 0;
}
<commit_msg>daemon: small fixes for main loop and shutdown<commit_after>#include <csignal>
#include "bvs/bvs.h"
BVS::BVS* bvs;
BVS::Logger logger("Daemon");
void mainSignal(int sig);
void shutdownFunction();
int testLogger();
int testConfig();
/** BVSD namespace, contains only the bvs daemon. */
namespace BVSD
{
/** BVS framework's command line daemon.
* This is a simple command line daemon. It serves as a client to the BVS
* framework. It is also intended as a sample client.
*
* It is interactive, you can use the following commands by just entering them
* on the command line and then pressing enter (short versions are also
* available, enter 'help<enter>' to see them):
*
* @li \c run run system until paused.
* @li \c continue same as run
* @li \c step advance system by one step.
* @li \c pause pause(stop) system.
* @li \c test call test functions.
* @li \c quit shutdown system and quit.
* @li \c help show help.
*/
class BVSD
{
};
}
/** Main function, creates interactive loop. */
int main(int argc, char** argv)
{
signal(SIGINT, mainSignal);
LOG(2, "starting!");
bvs = new BVS::BVS(argc, argv, &shutdownFunction);
LOG(2, "loading modules!");
bvs->loadModules();
LOG(2, "connecting modules!");
bvs->connectAllModules();
LOG(2, "starting!");
bvs->start();
bvs->run();
std::string input;
while (true)
{
std::getline(std::cin, input);
if (input == "r" || input == "run" || input == "c" || input == "continue")
{
LOG(2, "RUN!!!");
bvs->run();
}
else if (input.empty() || input == "s" || input == "step")
{
LOG(2, "STEP!!!");
bvs->step();
}
else if (input == "p" || input == "pause")
{
LOG(2, "PAUSING!!!");
bvs->pause();
}
else if (input == "t" || input == "test")
{
testLogger();
testConfig();
}
else if (input.substr(0,2) == "hs" || input.substr(0, 7) == "hotswap")
{
size_t delimiter = input.find_first_of(" ");
input.erase(0, delimiter+1);
if (input.empty() || delimiter==std::string::npos) std::cout << "ERROR: no module ID given!" << std::endl;
else bvs->hotSwap(input);
}
else if (input == "q" || input == "quit")
{
LOG(2, "quitting...");
bvs->quit();
LOG(2, "finished!");
break;
}
else if (input == "h" || input == "help")
{
std::cout << "usage:" << std::endl;
std::cout << " r|run run system until paused" << std::endl;
std::cout << " c|continue same as run" << std::endl;
std::cout << " s|step advance system by one step" << std::endl;
std::cout << " p|pause pause(stop) system" << std::endl;
std::cout << " hs|hotswap <arg> HotSwap(TM) <moduleID>" << std::endl;
std::cout << " t|test call test functions" << std::endl;
std::cout << " q|quit shutdown system and quit" << std::endl;
std::cout << " h|help show help" << std::endl;
}
else
{
std::cout << ">>> unknown command: " << input << std::endl << ">>> for help press 'h<enter>'!" << std::endl;
}
}
delete bvs;
return 0;
}
void mainSignal(int sig)
{
LOG(1,"Catched signal: " << sig << " (Ctrl-C), quitting!");
signal(SIGINT, SIG_DFL);
bvs->quit();
delete bvs;
exit(0);
}
void shutdownFunction()
{
LOG(1,"daemon exit caused by bvs shutdown request!");
bvs->quit();
delete bvs;
exit(0);
}
/** Performs some logger tests.
* This functions performs some tests on the logger system. Nothing fancy, can
* be studied to gain some insight into using the logger system.
*/
int testLogger()
{
LOG(0, "to CLI FILE");
bvs->disableLogConsole();
LOG(0, "to FILE only");
BVS::Logger file("FILE LOG", 3, BVS::Logger::TO_FILE);
file.out(0) << "FILE ONLY" << std::endl;
bvs->enableLogConsole();
BVS::Logger cli("CLI LOG", 3, BVS::Logger::TO_CLI);
cli.out(0) << "CLI ONLY" << std::endl;
bvs->disableLogConsole();
bvs->disableLogFile();
LOG(0, "NOOP");
bvs->enableLogConsole();
LOG(0, "to CLI");
bvs->disableLogConsole();
bvs->enableLogFile("BVSLog.txt", true);
LOG(0, "to FILE AGAIN");
bvs->enableLogConsole();
BVS::Logger both("to BOTH", 0, BVS::Logger::TO_CLI_AND_FILE);
both.out(0) << "to CLI AND FILE" << std::endl;
return 0;
}
/** Performs some config tests.
* This functions performs some tests on the config system. Nothing fancy, can
* be studied to gain some insight into using the config system.
*/
int testConfig()
{
LOG(0, "testing...");
int i;
std::string s;
bool b;
bvs->config.getValue("BVS.logVerbosity", i, 0)
.getValue("BVS.logFile", s, std::string("default"))
.getValue("BVS.logSystem", b, false);
LOG(0, "Getting int: " << i);
LOG(0, "Getting string: " << s);
LOG(0, "Getting bool: " << b);
i = bvs->config.getValue<int>("BVS.logVerbosity", 0);
s = bvs->config.getValue<std::string>("BVS.logFile", std::string("default"));
b = bvs->config.getValue<bool>("BVS.logSystem", false);
LOG(0, "Getting int directly: " << i);
LOG(0, "Getting string directly: " << s);
LOG(0, "Getting bool directly: " << b);
std::string empty;
bvs->config.getValue("this.option.does.not.exist", empty, std::string("empty"));
LOG(0, "This should be 'empty': " << empty);
std::vector<std::string> list;
bvs->config.getValue("BVS.modules", list);
LOG(0, "List: BVS.modules");
int count = 0;
for (auto& it : list)
{
(void) it;
(void) count;
LOG(0, count++ << ": " << it);
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "stdio.h"
#include "BVS.h"
int main(int argc, char** argv)
{
// start BVS
BVS bvs(argc, argv);
bvs.enableLogFile("BVSLog.txt");
BVSLogger logger("BVSDaemon");
LOG(2, "starting!");
//LOG(2, "dump all config options!");
//bvs.config.showOptionStore();
LOG(2, "loading Modules!");
bvs.loadModules();
LOG(2, "run!");
//bvs.run();
//std::string s = "core.list";
//std::vector<int> foo;
//bvs.config.getValue(s, foo);
//for (auto it : foo)
//{
//std::cout << foo[it] << std::endl;
//}
return 0;
}
<commit_msg>daemon: remove comments<commit_after>#include "stdio.h"
#include "BVS.h"
int main(int argc, char** argv)
{
// start BVS
BVS bvs(argc, argv);
bvs.enableLogFile("BVSLog.txt");
BVSLogger logger("BVSDaemon");
LOG(2, "starting!");
//LOG(2, "dump all config options!");
//bvs.config.showOptionStore();
LOG(2, "loading Modules!");
bvs.loadModules();
LOG(2, "run!");
//bvs.run();
return 0;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2016 *
* *
* 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/newhorizons/rendering/renderablemodelprojection.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/time.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/opengl/textureunit.h>
namespace {
const std::string _loggerCat = "RenderableModelProjection";
const std::string keySource = "Rotation.Source";
const std::string keyDestination = "Rotation.Destination";
const std::string keyBody = "Body";
const std::string keyGeometry = "Geometry";
const std::string keyTextureColor = "Textures.Color";
const std::string keyTextureProject = "Textures.Project";
const std::string keyTextureDefault = "Textures.Default";
}
namespace openspace {
RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _colorTexturePath("colorTexture", "Color Texture")
, _rotation("rotation", "Rotation", glm::vec3(0.f), glm::vec3(0.f), glm::vec3(360.f))
, _programObject(nullptr)
, _fboProgramObject(nullptr)
, _baseTexture(nullptr)
, _geometry(nullptr)
, _performShading("performShading", "Perform Shading", true)
{
std::string name;
bool success = dictionary.getValue(SceneGraphNode::KeyName, name);
ghoul_assert(success, "Name was not passed to RenderableModelProjection");
ghoul::Dictionary geometryDictionary;
success = dictionary.getValue(keyGeometry, geometryDictionary);
if (success) {
using modelgeometry::ModelGeometry;
geometryDictionary.setValue(SceneGraphNode::KeyName, name);
_geometry = std::unique_ptr<ModelGeometry>(
ModelGeometry::createFromDictionary(geometryDictionary)
);
}
std::string texturePath = "";
success = dictionary.getValue(keyTextureColor, texturePath);
if (success)
_colorTexturePath = absPath(texturePath);
success = dictionary.getValue(keyTextureDefault, texturePath);
if (success)
_defaultProjImage = absPath(texturePath);
addPropertySubOwner(_geometry.get());
addProperty(_projectionFading);
addProperty(_colorTexturePath);
_colorTexturePath.onChange(std::bind(&RenderableModelProjection::loadTextures, this));
dictionary.getValue(keySource, _source);
dictionary.getValue(keyDestination, _destination);
dictionary.getValue(keyBody, _target);
if (_target != "")
setBody(_target);
bool completeSuccess = true;
completeSuccess &= initializeProjectionSettings(dictionary);
openspace::SpiceManager::ref().addFrame(_target, _source);
setBoundingSphere(pss(1.f, 9.f));
addProperty(_performShading);
addProperty(_performProjection);
addProperty(_clearAllProjections);
addProperty(_rotation);
success = initializeParser(dictionary);
ghoul_assert(success, "");
}
bool RenderableModelProjection::isReady() const {
bool ready = true;
ready &= (_programObject != nullptr);
ready &= (_baseTexture != nullptr);
ready &= (_projectionTexture != nullptr);
return ready;
}
bool RenderableModelProjection::initialize() {
bool completeSuccess = true;
RenderEngine& renderEngine = OsEng.renderEngine();
_programObject = renderEngine.buildRenderProgram("ModelShader",
"${MODULE_NEWHORIZONS}/shaders/renderableModel_vs.glsl",
"${MODULE_NEWHORIZONS}/shaders/renderableModel_fs.glsl");
_fboProgramObject = ghoul::opengl::ProgramObject::Build("ProjectionPass",
"${MODULE_NEWHORIZONS}/shaders/renderableModelProjection_vs.glsl",
"${MODULE_NEWHORIZONS}/shaders/renderableModelProjection_fs.glsl");
_fboProgramObject->setIgnoreUniformLocationError(
ghoul::opengl::ProgramObject::IgnoreError::Yes
);
completeSuccess &= loadTextures();
completeSuccess &= ProjectionComponent::initialize();
completeSuccess &= _geometry->initialize(this);
completeSuccess &= !_source.empty();
completeSuccess &= !_destination.empty();
return completeSuccess;
}
bool RenderableModelProjection::deinitialize() {
if (_geometry)
_geometry->deinitialize();
_geometry = nullptr;
_baseTexture = nullptr;
ProjectionComponent::deinitialize();
OsEng.renderEngine().removeRenderProgram(_programObject);
_programObject = nullptr;
return true;
}
void RenderableModelProjection::render(const RenderData& data) {
if (_clearAllProjections)
clearAllProjections();
_camScaling = data.camera.scaling();
if (_capture && _performProjection)
project();
_programObject->activate();
attitudeParameters(_time);
_imageTimes.clear();
_programObject->setUniform("_performShading", _performShading);
_programObject->setUniform("sun_pos", _sunPosition.vec3());
_programObject->setUniform("ViewProjection", data.camera.viewProjectionMatrix());
_programObject->setUniform("ModelTransform", _transform);
_programObject->setUniform("_projectionFading", _projectionFading);
setPscUniforms(*_programObject, data.camera, data.position);
_geometry->setUniforms(*_programObject);
ghoul::opengl::TextureUnit unit[2];
unit[0].activate();
_baseTexture->bind();
_programObject->setUniform("baseTexture", unit[0]);
unit[1].activate();
_projectionTexture->bind();
_programObject->setUniform("projectionTexture", unit[1]);
_geometry->render();
_programObject->deactivate();
}
void RenderableModelProjection::update(const UpdateData& data) {
if (_programObject->isDirty())
_programObject->rebuildFromFile();
if (_fboProgramObject->isDirty())
_fboProgramObject->rebuildFromFile();
_time = data.time;
if (openspace::ImageSequencer::ref().isReady() && _performProjection) {
openspace::ImageSequencer::ref().updateSequencer(_time);
_capture = openspace::ImageSequencer::ref().getImagePaths(
_imageTimes, _projecteeID, _instrumentID
);
}
// set spice-orientation in accordance to timestamp
if (!_source.empty()) {
_stateMatrix = SpiceManager::ref().positionTransformMatrix(
_source, _destination, _time
);
}
double lt;
glm::dvec3 p =
openspace::SpiceManager::ref().targetPosition(
"SUN", _target, "GALACTIC", {}, _time, lt
);
_sunPosition = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);
}
void RenderableModelProjection::imageProjectGPU(
std::shared_ptr<ghoul::opengl::Texture> projectionTexture)
{
ProjectionComponent::imageProjectBegin();
_fboProgramObject->activate();
ghoul::opengl::TextureUnit unitFbo;
unitFbo.activate();
projectionTexture->bind();
_fboProgramObject->setUniform("projectionTexture", unitFbo);
_fboProgramObject->setUniform("ProjectorMatrix", _projectorMatrix);
_fboProgramObject->setUniform("ModelTransform", _transform);
_fboProgramObject->setUniform("_scaling", _camScaling);
_fboProgramObject->setUniform("boresight", _boresight);
_geometry->setUniforms(*_fboProgramObject);
_geometry->render();
_fboProgramObject->deactivate();
ProjectionComponent::imageProjectEnd();
}
void RenderableModelProjection::attitudeParameters(double time) {
try {
_stateMatrix = SpiceManager::ref().positionTransformMatrix(_source, _destination, time);
_instrumentMatrix = SpiceManager::ref().positionTransformMatrix(_instrumentID, _destination, time);
}
catch (const SpiceManager::SpiceException& e) {
return;
}
_transform = glm::mat4(1);
glm::mat4 rotPropX = glm::rotate(
_transform,
glm::radians(static_cast<float>(_rotation.value().x)),
glm::vec3(1, 0, 0)
);
glm::mat4 rotPropY = glm::rotate(
_transform,
glm::radians(static_cast<float>(_rotation.value().y)),
glm::vec3(0, 1, 0)
);
glm::mat4 rotPropZ = glm::rotate(
_transform,
glm::radians(static_cast<float>(_rotation.value().z)),
glm::vec3(0, 0, 1)
);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
_transform[i][j] = static_cast<float>(_stateMatrix[i][j]);
}
}
_transform = _transform * rotPropX * rotPropY * rotPropZ;
glm::dvec3 boresight;
try {
SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView(_instrumentID);
boresight = std::move(res.boresightVector);
} catch (const SpiceManager::SpiceException& e) {
return;
}
double lightTime;
glm::dvec3 p =
SpiceManager::ref().targetPosition(_projectorID, _projecteeID, _destination, _aberration, time, lightTime);
psc position = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);
position[3] += (3 + _camScaling[1]);
glm::vec3 cpos = position.vec3();
_projectorMatrix = computeProjectorMatrix(cpos, boresight, _up, _instrumentMatrix,
_fovy, _aspectRatio, _nearPlane, _farPlane, _boresight
);
}
void RenderableModelProjection::project() {
for (auto img : _imageTimes) {
attitudeParameters(img.startTime);
imageProjectGPU(loadProjectionTexture(img.path));
}
_capture = false;
}
bool RenderableModelProjection::loadTextures() {
_baseTexture = nullptr;
if (_colorTexturePath.value() != "") {
_baseTexture = std::move(
ghoul::io::TextureReader::ref().loadTexture(absPath(_colorTexturePath))
);
if (_baseTexture) {
LDEBUG("Loaded texture from '" << absPath(_colorTexturePath) << "'");
_baseTexture->uploadTexture();
_baseTexture->setFilter(ghoul::opengl::Texture::FilterMode::Linear);
}
}
return _baseTexture != nullptr;
}
} // namespace openspace
<commit_msg>Reenable up-vector definition in RenderableModelProjection<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2016 *
* *
* 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/newhorizons/rendering/renderablemodelprojection.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/time.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/opengl/textureunit.h>
namespace {
const std::string _loggerCat = "RenderableModelProjection";
const std::string keySource = "Rotation.Source";
const std::string keyDestination = "Rotation.Destination";
const std::string keyBody = "Body";
const std::string keyGeometry = "Geometry";
const std::string keyTextureColor = "Textures.Color";
const std::string keyTextureProject = "Textures.Project";
const std::string keyTextureDefault = "Textures.Default";
}
namespace openspace {
RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _colorTexturePath("colorTexture", "Color Texture")
, _rotation("rotation", "Rotation", glm::vec3(0.f), glm::vec3(0.f), glm::vec3(360.f))
, _programObject(nullptr)
, _fboProgramObject(nullptr)
, _baseTexture(nullptr)
, _geometry(nullptr)
, _performShading("performShading", "Perform Shading", true)
{
std::string name;
bool success = dictionary.getValue(SceneGraphNode::KeyName, name);
ghoul_assert(success, "Name was not passed to RenderableModelProjection");
ghoul::Dictionary geometryDictionary;
success = dictionary.getValue(keyGeometry, geometryDictionary);
if (success) {
using modelgeometry::ModelGeometry;
geometryDictionary.setValue(SceneGraphNode::KeyName, name);
_geometry = std::unique_ptr<ModelGeometry>(
ModelGeometry::createFromDictionary(geometryDictionary)
);
}
std::string texturePath = "";
success = dictionary.getValue(keyTextureColor, texturePath);
if (success)
_colorTexturePath = absPath(texturePath);
success = dictionary.getValue(keyTextureDefault, texturePath);
if (success)
_defaultProjImage = absPath(texturePath);
addPropertySubOwner(_geometry.get());
addProperty(_projectionFading);
addProperty(_colorTexturePath);
_colorTexturePath.onChange(std::bind(&RenderableModelProjection::loadTextures, this));
dictionary.getValue(keySource, _source);
dictionary.getValue(keyDestination, _destination);
dictionary.getValue(keyBody, _target);
if (_target != "")
setBody(_target);
bool completeSuccess = true;
completeSuccess &= initializeProjectionSettings(dictionary);
openspace::SpiceManager::ref().addFrame(_target, _source);
setBoundingSphere(pss(1.f, 9.f));
addProperty(_performShading);
addProperty(_performProjection);
addProperty(_clearAllProjections);
addProperty(_rotation);
success = initializeParser(dictionary);
ghoul_assert(success, "");
}
bool RenderableModelProjection::isReady() const {
bool ready = true;
ready &= (_programObject != nullptr);
ready &= (_baseTexture != nullptr);
ready &= (_projectionTexture != nullptr);
return ready;
}
bool RenderableModelProjection::initialize() {
bool completeSuccess = true;
RenderEngine& renderEngine = OsEng.renderEngine();
_programObject = renderEngine.buildRenderProgram("ModelShader",
"${MODULE_NEWHORIZONS}/shaders/renderableModel_vs.glsl",
"${MODULE_NEWHORIZONS}/shaders/renderableModel_fs.glsl");
_fboProgramObject = ghoul::opengl::ProgramObject::Build("ProjectionPass",
"${MODULE_NEWHORIZONS}/shaders/renderableModelProjection_vs.glsl",
"${MODULE_NEWHORIZONS}/shaders/renderableModelProjection_fs.glsl");
_fboProgramObject->setIgnoreUniformLocationError(
ghoul::opengl::ProgramObject::IgnoreError::Yes
);
completeSuccess &= loadTextures();
completeSuccess &= ProjectionComponent::initialize();
completeSuccess &= _geometry->initialize(this);
completeSuccess &= !_source.empty();
completeSuccess &= !_destination.empty();
return completeSuccess;
}
bool RenderableModelProjection::deinitialize() {
if (_geometry)
_geometry->deinitialize();
_geometry = nullptr;
_baseTexture = nullptr;
ProjectionComponent::deinitialize();
OsEng.renderEngine().removeRenderProgram(_programObject);
_programObject = nullptr;
return true;
}
void RenderableModelProjection::render(const RenderData& data) {
if (_clearAllProjections)
clearAllProjections();
_camScaling = data.camera.scaling();
_up = data.camera.lookUpVectorCameraSpace();
if (_capture && _performProjection)
project();
_programObject->activate();
attitudeParameters(_time);
_imageTimes.clear();
_programObject->setUniform("_performShading", _performShading);
_programObject->setUniform("sun_pos", _sunPosition.vec3());
_programObject->setUniform("ViewProjection", data.camera.viewProjectionMatrix());
_programObject->setUniform("ModelTransform", _transform);
_programObject->setUniform("_projectionFading", _projectionFading);
setPscUniforms(*_programObject, data.camera, data.position);
_geometry->setUniforms(*_programObject);
ghoul::opengl::TextureUnit unit[2];
unit[0].activate();
_baseTexture->bind();
_programObject->setUniform("baseTexture", unit[0]);
unit[1].activate();
_projectionTexture->bind();
_programObject->setUniform("projectionTexture", unit[1]);
_geometry->render();
_programObject->deactivate();
}
void RenderableModelProjection::update(const UpdateData& data) {
if (_programObject->isDirty())
_programObject->rebuildFromFile();
if (_fboProgramObject->isDirty())
_fboProgramObject->rebuildFromFile();
_time = data.time;
if (openspace::ImageSequencer::ref().isReady() && _performProjection) {
openspace::ImageSequencer::ref().updateSequencer(_time);
_capture = openspace::ImageSequencer::ref().getImagePaths(
_imageTimes, _projecteeID, _instrumentID
);
}
// set spice-orientation in accordance to timestamp
if (!_source.empty()) {
_stateMatrix = SpiceManager::ref().positionTransformMatrix(
_source, _destination, _time
);
}
double lt;
glm::dvec3 p =
openspace::SpiceManager::ref().targetPosition(
"SUN", _target, "GALACTIC", {}, _time, lt
);
_sunPosition = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);
}
void RenderableModelProjection::imageProjectGPU(
std::shared_ptr<ghoul::opengl::Texture> projectionTexture)
{
ProjectionComponent::imageProjectBegin();
_fboProgramObject->activate();
ghoul::opengl::TextureUnit unitFbo;
unitFbo.activate();
projectionTexture->bind();
_fboProgramObject->setUniform("projectionTexture", unitFbo);
_fboProgramObject->setUniform("ProjectorMatrix", _projectorMatrix);
_fboProgramObject->setUniform("ModelTransform", _transform);
_fboProgramObject->setUniform("_scaling", _camScaling);
_fboProgramObject->setUniform("boresight", _boresight);
_geometry->setUniforms(*_fboProgramObject);
_geometry->render();
_fboProgramObject->deactivate();
ProjectionComponent::imageProjectEnd();
}
void RenderableModelProjection::attitudeParameters(double time) {
try {
_stateMatrix = SpiceManager::ref().positionTransformMatrix(_source, _destination, time);
_instrumentMatrix = SpiceManager::ref().positionTransformMatrix(_instrumentID, _destination, time);
}
catch (const SpiceManager::SpiceException& e) {
return;
}
_transform = glm::mat4(1);
glm::mat4 rotPropX = glm::rotate(
_transform,
glm::radians(static_cast<float>(_rotation.value().x)),
glm::vec3(1, 0, 0)
);
glm::mat4 rotPropY = glm::rotate(
_transform,
glm::radians(static_cast<float>(_rotation.value().y)),
glm::vec3(0, 1, 0)
);
glm::mat4 rotPropZ = glm::rotate(
_transform,
glm::radians(static_cast<float>(_rotation.value().z)),
glm::vec3(0, 0, 1)
);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
_transform[i][j] = static_cast<float>(_stateMatrix[i][j]);
}
}
_transform = _transform * rotPropX * rotPropY * rotPropZ;
glm::dvec3 boresight;
try {
SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView(_instrumentID);
boresight = std::move(res.boresightVector);
} catch (const SpiceManager::SpiceException& e) {
return;
}
double lightTime;
glm::dvec3 p =
SpiceManager::ref().targetPosition(_projectorID, _projecteeID, _destination, _aberration, time, lightTime);
psc position = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);
position[3] += (3 + _camScaling[1]);
glm::vec3 cpos = position.vec3();
_projectorMatrix = computeProjectorMatrix(cpos, boresight, _up, _instrumentMatrix,
_fovy, _aspectRatio, _nearPlane, _farPlane, _boresight
);
}
void RenderableModelProjection::project() {
for (auto img : _imageTimes) {
attitudeParameters(img.startTime);
imageProjectGPU(loadProjectionTexture(img.path));
}
_capture = false;
}
bool RenderableModelProjection::loadTextures() {
_baseTexture = nullptr;
if (_colorTexturePath.value() != "") {
_baseTexture = std::move(
ghoul::io::TextureReader::ref().loadTexture(absPath(_colorTexturePath))
);
if (_baseTexture) {
LDEBUG("Loaded texture from '" << absPath(_colorTexturePath) << "'");
_baseTexture->uploadTexture();
_baseTexture->setFilter(ghoul::opengl::Texture::FilterMode::Linear);
}
}
return _baseTexture != nullptr;
}
} // namespace openspace
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/obstacle/onboard/async_fusion_subnode.h"
#include <unordered_map>
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/common/time/timer.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/subnode_helper.h"
namespace apollo {
namespace perception {
using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::adapter::AdapterManager;
bool AsyncFusionSubnode::InitInternal() {
RegistAllAlgorithm();
AdapterManager::Init(FLAGS_perception_adapter_config_filename);
CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized.";
AdapterManager::AddChassisCallback(&AsyncFusionSubnode::OnChassis, this);
CHECK(shared_data_manager_ != nullptr);
fusion_.reset(BaseFusionRegisterer::GetInstanceByName(FLAGS_onboard_fusion));
if (fusion_ == nullptr) {
AERROR << "Failed to get fusion instance: " << FLAGS_onboard_fusion;
return false;
}
if (!fusion_->Init()) {
AERROR << "Failed to init fusion:" << FLAGS_onboard_fusion;
return false;
}
radar_object_data_ = dynamic_cast<RadarObjectData *>(
shared_data_manager_->GetSharedData("RadarObjectData"));
if (radar_object_data_ == nullptr) {
AWARN << "Failed to get RadarObjectData.";
}
camera_object_data_ = dynamic_cast<CameraObjectData *>(
shared_data_manager_->GetSharedData("CameraObjectData"));
if (camera_object_data_ == nullptr) {
AWARN << "Failed to get CameraObjectData.";
}
lane_shared_data_ = dynamic_cast<LaneSharedData *>(
shared_data_manager_->GetSharedData("LaneSharedData"));
if (lane_shared_data_ == nullptr) {
AERROR << "failed to get shared data instance: LaneSharedData ";
return false;
}
fusion_data_ = dynamic_cast<FusionSharedData *>(
shared_data_manager_->GetSharedData("FusionSharedData"));
if (fusion_data_ == nullptr) {
AWARN << "Failed to get FusionSharedData.";
}
if (!InitOutputStream()) {
AERROR << "Failed to init output stream.";
return false;
}
AINFO << "Init AsyncFusionSubnode succ. Using fusion:" << fusion_->name();
return true;
}
bool AsyncFusionSubnode::InitOutputStream() {
// expect reserve_ format:
// pub_driven_event_id:n
// lidar_output_stream : event_id=n&sink_type=m&sink_name=x
// radar_output_stream : event_id=n&sink_type=m&sink_name=x
std::unordered_map<std::string, std::string> reserve_field_map;
if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {
AERROR << "Failed to parse reserve string: " << reserve_;
return false;
}
auto radar_iter = reserve_field_map.find("radar_event_id");
if (radar_iter == reserve_field_map.end()) {
AWARN << "Failed to find radar_event_id:" << reserve_;
AINFO << "radar_event_id will be set -1";
radar_event_id_ = -1;
} else {
radar_event_id_ = static_cast<EventID>(atoi((radar_iter->second).c_str()));
}
auto camera_iter = reserve_field_map.find("camera_event_id");
if (camera_iter == reserve_field_map.end()) {
AWARN << "Failed to find camera_event_id:" << reserve_;
AINFO << "camera_event_id will be set -1";
camera_event_id_ = -1;
} else {
camera_event_id_ =
static_cast<EventID>(atoi((camera_iter->second).c_str()));
}
auto lane_iter = reserve_field_map.find("lane_event_id");
if (lane_iter == reserve_field_map.end()) {
AWARN << "Failed to find camera_event_id:" << reserve_;
AINFO << "camera_event_id will be set -1";
lane_event_id_ = -1;
} else {
lane_event_id_ = static_cast<EventID>(atoi((lane_iter->second).c_str()));
}
return true;
}
Status AsyncFusionSubnode::ProcEvents() {
for (auto event_meta : sub_meta_events_) {
std::vector<Event> events;
if (!SubscribeEvents(event_meta, &events)) {
AERROR << "event meta id:" << event_meta.event_id << " "
<< event_meta.from_node << " " << event_meta.to_node;
return Status(ErrorCode::PERCEPTION_ERROR, "Subscribe event fail.");
}
if (events.empty()) {
usleep(500);
continue;
}
apollo::common::time::Timer timer;
timer.Start();
Process(event_meta, events);
ADEBUG << "time elapsed for async fusion process " << timer.End("");
// public obstacle message
PerceptionObstacles obstacles;
if (GeneratePbMsg(&obstacles)) {
// Assume FLU coordinate system
if (FLAGS_use_navigation_mode) {
for (auto obstacle : obstacles.perception_obstacle()) {
obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +
chassis_speed_mps_);
}
}
common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
}
AINFO << "Publish 3d perception fused msg. timestamp:"
<< GLOG_TIMESTAMP(timestamp_) << " obj_cnt:" << objects_.size();
}
return Status::OK();
}
void AsyncFusionSubnode::PublishDataAndEvent(
const double ×tamp, const std::string &device_id,
const SharedDataPtr<FusionItem> &data) {
CommonSharedDataKey key(timestamp, device_id);
fusion_data_->Add(key, data);
for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
const EventMeta &event_meta = pub_meta_events_[idx];
Event event;
event.event_id = event_meta.event_id;
event.timestamp = timestamp;
event.reserve = device_id;
event_manager_->Publish(event);
}
}
Status AsyncFusionSubnode::Process(const EventMeta &event_meta,
const std::vector<Event> &events) {
const std::string &device_id = events[0].reserve;
// const double timestamp = events[0].timestamp;
std::vector<SensorObjects> sensor_objs;
if (!BuildSensorObjs(events, &sensor_objs)) {
AERROR << "Failed to build_sensor_objs";
error_code_ = common::PERCEPTION_ERROR_PROCESS;
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to build_sensor_objs.");
}
PERF_BLOCK_START();
objects_.clear();
// if (!fusion_->Fuse(sensor_objs, &objects_)) {
// AWARN << "Failed to call fusion plugin."
// << " event_meta: [" << event_meta.to_string()
// << "] event_cnt:" << events.size() << " event_0: ["
// << events[0].to_string() << "]";
// error_code_ = common::PERCEPTION_ERROR_PROCESS;
// return Status(ErrorCode::PERCEPTION_ERROR,
// "Failed to call fusion plugin.");
// }
if (event_meta.event_id == radar_event_id_) {
PERF_BLOCK_END("fusion_radar");
} else if (event_meta.event_id == camera_event_id_) {
PERF_BLOCK_END("fusion_camera");
}
if (objects_.size() > 0 && FLAGS_publish_fusion_event) {
SharedDataPtr<FusionItem> fusion_item_ptr(new FusionItem);
fusion_item_ptr->timestamp = objects_[0]->latest_tracked_time;
for (auto obj : objects_) {
ObjectPtr objclone(new Object());
objclone->clone(*obj);
fusion_item_ptr->obstacles.push_back(objclone);
}
AINFO << "publishing event for timestamp deviceid and size of fusion object"
<< fusion_item_ptr->timestamp << " " << device_id << " "
<< fusion_item_ptr->obstacles.size();
PublishDataAndEvent(fusion_item_ptr->timestamp, device_id, fusion_item_ptr);
}
// publishing result to pnc
for (auto sensor_obj : sensor_objs) {
PublishPerceptionPb(sensor_obj);
}
error_code_ = common::OK;
return Status::OK();
}
void AsyncFusionSubnode::PublishPerceptionPb(
const SensorObjects &sensor_objects) {
AINFO << "Camera publish perception pb data";
PerceptionObstacles obstacles;
// Header
common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
"perception_obstacle", &obstacles);
common::Header *header = obstacles.mutable_header();
header->set_lidar_timestamp(0);
// use timestamp in nanoseconds
header->set_camera_timestamp(sensor_objects.timestamp * 1e9);
header->set_radar_timestamp(0);
obstacles.set_error_code(sensor_objects.error_code);
// generate lane marker protobuf messages
LaneMarkers *lane_markers = obstacles.mutable_lane_marker();
LaneObjectsToLaneMarkerProto(*(sensor_objects.lane_objects), lane_markers);
// Serialize each Object
for (const auto &obj : sensor_objects.objects) {
PerceptionObstacle *obstacle = obstacles.add_perception_obstacle();
obj->Serialize(obstacle);
}
// Relative speed of objects + latest ego car speed in X
for (auto obstacle : obstacles.perception_obstacle()) {
obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +
chassis_.speed_mps());
}
common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
ADEBUG << "Camera Obstacles: " << obstacles.ShortDebugString();
}
bool AsyncFusionSubnode::SubscribeEvents(const EventMeta &event_meta,
std::vector<Event> *events) const {
Event event;
// blocking call for each of these events
while (event_manager_->Subscribe(event_meta.event_id, &event, true)) {
AINFO << "starting subscribing event " << event_meta.event_id;
events->push_back(event);
}
return true;
}
bool AsyncFusionSubnode::BuildSensorObjs(
const std::vector<Event> &events,
std::vector<SensorObjects> *multi_sensor_objs) {
PERF_FUNCTION();
for (auto event : events) {
std::shared_ptr<SensorObjects> sensor_objects;
if (!GetSharedData(event, &sensor_objects)) {
return false;
}
// Make sure timestamp and type are filled.
sensor_objects->timestamp = event.timestamp;
if (event.event_id == radar_event_id_) {
sensor_objects->sensor_type = SensorType::RADAR;
} else if (event.event_id == camera_event_id_) {
sensor_objects->sensor_type = SensorType::CAMERA;
} else {
AERROR << "Event id is not supported. event:" << event.to_string();
return false;
}
sensor_objects->sensor_id = GetSensorType(sensor_objects->sensor_type);
multi_sensor_objs->push_back(*sensor_objects);
ADEBUG << "get sensor objs:" << sensor_objects->ToString();
}
return true;
}
bool AsyncFusionSubnode::GetSharedData(const Event &event,
std::shared_ptr<SensorObjects> *objs) {
double timestamp = event.timestamp;
const std::string &device_id = event.reserve;
std::string data_key;
if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {
AERROR << "Failed to produce shared data key. EventID:" << event.event_id
<< " timestamp:" << timestamp << " device_id:" << device_id;
return false;
}
bool get_data_succ = false;
if (event.event_id == radar_event_id_ && radar_object_data_ != nullptr) {
get_data_succ = radar_object_data_->Get(data_key, objs);
} else if (event.event_id == camera_event_id_ &&
camera_object_data_ != nullptr) {
get_data_succ = camera_object_data_->Get(data_key, objs);
// trying to get lane shared data as well
Event lane_event;
if (event_manager_->Subscribe(lane_event_id_, &lane_event, false)) {
get_data_succ =
lane_shared_data_->Get(data_key, &((*objs)->lane_objects));
AINFO << "getting lane data successfully for data key " << data_key;
}
} else {
AERROR << "Event id is not supported. event:" << event.to_string();
return false;
}
if (!get_data_succ) {
AERROR << "Failed to get shared data. event:" << event.to_string();
return false;
}
return true;
}
bool AsyncFusionSubnode::GeneratePbMsg(PerceptionObstacles *obstacles) {
common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
FLAGS_obstacle_module_name, obstacles);
common::Header *header = obstacles->mutable_header();
header->set_lidar_timestamp(timestamp_ * 1e9); // in ns
header->set_camera_timestamp(0);
header->set_radar_timestamp(0);
obstacles->set_error_code(error_code_);
for (const auto &obj : objects_) {
PerceptionObstacle *obstacle = obstacles->add_perception_obstacle();
obj->Serialize(obstacle);
}
ADEBUG << "PerceptionObstacles: " << obstacles->ShortDebugString();
return true;
}
void AsyncFusionSubnode::RegistAllAlgorithm() {
RegisterFactoryAsyncFusion();
}
void AsyncFusionSubnode::OnChassis(const Chassis &chassis) {
ADEBUG << "Received chassis data: run chassis callback.";
chassis_.CopyFrom(chassis);
chassis_speed_mps_ = chassis.speed_mps();
}
} // namespace perception
} // namespace apollo
<commit_msg>fix perception slow bug<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/obstacle/onboard/async_fusion_subnode.h"
#include <unordered_map>
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/common/time/timer.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/subnode_helper.h"
namespace apollo {
namespace perception {
using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::adapter::AdapterManager;
bool AsyncFusionSubnode::InitInternal() {
RegistAllAlgorithm();
AdapterManager::Init(FLAGS_perception_adapter_config_filename);
CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized.";
AdapterManager::AddChassisCallback(&AsyncFusionSubnode::OnChassis, this);
CHECK(shared_data_manager_ != nullptr);
fusion_.reset(BaseFusionRegisterer::GetInstanceByName(FLAGS_onboard_fusion));
if (fusion_ == nullptr) {
AERROR << "Failed to get fusion instance: " << FLAGS_onboard_fusion;
return false;
}
if (!fusion_->Init()) {
AERROR << "Failed to init fusion:" << FLAGS_onboard_fusion;
return false;
}
radar_object_data_ = dynamic_cast<RadarObjectData *>(
shared_data_manager_->GetSharedData("RadarObjectData"));
if (radar_object_data_ == nullptr) {
AWARN << "Failed to get RadarObjectData.";
}
camera_object_data_ = dynamic_cast<CameraObjectData *>(
shared_data_manager_->GetSharedData("CameraObjectData"));
if (camera_object_data_ == nullptr) {
AWARN << "Failed to get CameraObjectData.";
}
lane_shared_data_ = dynamic_cast<LaneSharedData *>(
shared_data_manager_->GetSharedData("LaneSharedData"));
if (lane_shared_data_ == nullptr) {
AERROR << "failed to get shared data instance: LaneSharedData ";
return false;
}
fusion_data_ = dynamic_cast<FusionSharedData *>(
shared_data_manager_->GetSharedData("FusionSharedData"));
if (fusion_data_ == nullptr) {
AWARN << "Failed to get FusionSharedData.";
}
if (!InitOutputStream()) {
AERROR << "Failed to init output stream.";
return false;
}
AINFO << "Init AsyncFusionSubnode succ. Using fusion:" << fusion_->name();
return true;
}
bool AsyncFusionSubnode::InitOutputStream() {
// expect reserve_ format:
// pub_driven_event_id:n
// lidar_output_stream : event_id=n&sink_type=m&sink_name=x
// radar_output_stream : event_id=n&sink_type=m&sink_name=x
std::unordered_map<std::string, std::string> reserve_field_map;
if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {
AERROR << "Failed to parse reserve string: " << reserve_;
return false;
}
auto radar_iter = reserve_field_map.find("radar_event_id");
if (radar_iter == reserve_field_map.end()) {
AWARN << "Failed to find radar_event_id:" << reserve_;
AINFO << "radar_event_id will be set -1";
radar_event_id_ = -1;
} else {
radar_event_id_ = static_cast<EventID>(atoi((radar_iter->second).c_str()));
}
auto camera_iter = reserve_field_map.find("camera_event_id");
if (camera_iter == reserve_field_map.end()) {
AWARN << "Failed to find camera_event_id:" << reserve_;
AINFO << "camera_event_id will be set -1";
camera_event_id_ = -1;
} else {
camera_event_id_ =
static_cast<EventID>(atoi((camera_iter->second).c_str()));
}
auto lane_iter = reserve_field_map.find("lane_event_id");
if (lane_iter == reserve_field_map.end()) {
AWARN << "Failed to find camera_event_id:" << reserve_;
AINFO << "camera_event_id will be set -1";
lane_event_id_ = -1;
} else {
lane_event_id_ = static_cast<EventID>(atoi((lane_iter->second).c_str()));
}
return true;
}
Status AsyncFusionSubnode::ProcEvents() {
for (auto event_meta : sub_meta_events_) {
std::vector<Event> events;
if (event_meta.event_id == lane_event_id_) {
continue;
}
if (!SubscribeEvents(event_meta, &events)) {
AERROR << "event meta id:" << event_meta.event_id << " "
<< event_meta.from_node << " " << event_meta.to_node;
return Status(ErrorCode::PERCEPTION_ERROR, "Subscribe event fail.");
}
if (events.empty()) {
usleep(500);
continue;
}
apollo::common::time::Timer timer;
timer.Start();
Process(event_meta, events);
ADEBUG << "time elapsed for async fusion process " << timer.End("");
// public obstacle message
PerceptionObstacles obstacles;
if (GeneratePbMsg(&obstacles)) {
// Assume FLU coordinate system
if (FLAGS_use_navigation_mode) {
for (auto obstacle : obstacles.perception_obstacle()) {
obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +
chassis_speed_mps_);
}
}
common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
}
AINFO << "Publish 3d perception fused msg. timestamp:"
<< GLOG_TIMESTAMP(timestamp_) << " obj_cnt:" << objects_.size();
}
return Status::OK();
}
void AsyncFusionSubnode::PublishDataAndEvent(
const double ×tamp, const std::string &device_id,
const SharedDataPtr<FusionItem> &data) {
CommonSharedDataKey key(timestamp, device_id);
bool fusion_succ = fusion_data_->Add(key, data);
if (!fusion_succ) {
AERROR <<"fusion shared data addkey failure";
}
ADEBUG << "adding key in fusion shared data " << key.ToString();
for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
const EventMeta &event_meta = pub_meta_events_[idx];
Event event;
event.event_id = event_meta.event_id;
event.timestamp = timestamp;
event.reserve = device_id;
event_manager_->Publish(event);
}
}
Status AsyncFusionSubnode::Process(const EventMeta &event_meta,
const std::vector<Event> &events) {
const std::string &device_id = events[0].reserve;
// const double timestamp = events[0].timestamp;
std::vector<SensorObjects> sensor_objs;
if (!BuildSensorObjs(events, &sensor_objs)) {
AERROR << "Failed to build_sensor_objs";
error_code_ = common::PERCEPTION_ERROR_PROCESS;
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to build_sensor_objs.");
}
PERF_BLOCK_START();
objects_.clear();
/*
if (!fusion_->Fuse(sensor_objs, &objects_)) {
AWARN << "Failed to call fusion plugin."
<< " event_meta: [" << event_meta.to_string()
<< "] event_cnt:" << events.size() << " event_0: ["
<< events[0].to_string() << "]";
error_code_ = common::PERCEPTION_ERROR_PROCESS;
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to call fusion plugin.");
}*/
if (event_meta.event_id == radar_event_id_) {
PERF_BLOCK_END("fusion_radar");
} else if (event_meta.event_id == camera_event_id_) {
PERF_BLOCK_END("fusion_camera");
}
if (objects_.size() > 0 && FLAGS_publish_fusion_event) {
SharedDataPtr<FusionItem> fusion_item_ptr(new FusionItem);
fusion_item_ptr->timestamp = objects_[0]->latest_tracked_time;
for (auto obj : objects_) {
ObjectPtr objclone(new Object());
objclone->clone(*obj);
fusion_item_ptr->obstacles.push_back(objclone);
}
AINFO << "publishing event for timestamp deviceid and size of fusion object"
<< fusion_item_ptr->timestamp << " " << device_id << " "
<< fusion_item_ptr->obstacles.size();
PublishDataAndEvent(fusion_item_ptr->timestamp, device_id, fusion_item_ptr);
}
// publishing result to pnc
if (event_meta.event_id == camera_event_id_) {
for (auto sensor_obj : sensor_objs) {
PublishPerceptionPb(sensor_obj);
}
}
error_code_ = common::OK;
return Status::OK();
}
void AsyncFusionSubnode::PublishPerceptionPb(
const SensorObjects &sensor_objects) {
AINFO << "Camera publish perception pb data";
PerceptionObstacles obstacles;
// Header
common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
"perception_obstacle", &obstacles);
common::Header *header = obstacles.mutable_header();
header->set_lidar_timestamp(0);
// use timestamp in nanoseconds
header->set_camera_timestamp(sensor_objects.timestamp * 1e9);
header->set_radar_timestamp(0);
obstacles.set_error_code(sensor_objects.error_code);
// generate lane marker protobuf messages
LaneMarkers *lane_markers = obstacles.mutable_lane_marker();
LaneObjectsToLaneMarkerProto(*(sensor_objects.lane_objects), lane_markers);
// Serialize each Object
for (const auto &obj : sensor_objects.objects) {
PerceptionObstacle *obstacle = obstacles.add_perception_obstacle();
obj->Serialize(obstacle);
}
// Relative speed of objects + latest ego car speed in X
for (auto obstacle : obstacles.perception_obstacle()) {
obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +
chassis_.speed_mps());
}
common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
ADEBUG << "Camera Obstacles: " << obstacles.ShortDebugString();
}
bool AsyncFusionSubnode::SubscribeEvents(const EventMeta &event_meta,
std::vector<Event> *events) const {
Event event;
// blocking call for each of these events
while (event_manager_->Subscribe(event_meta.event_id, &event, true)) {
ADEBUG << "starting subscribing event " << event_meta.event_id;
// events->push_back(event);
}
// only obtain latest event from a sensor queue
if (event.event_id !=0 && event.timestamp !=0.0) {
events->push_back(event);
}
return true;
}
bool AsyncFusionSubnode::BuildSensorObjs(
const std::vector<Event> &events,
std::vector<SensorObjects> *multi_sensor_objs) {
PERF_FUNCTION();
for (auto event : events) {
std::shared_ptr<SensorObjects> sensor_objects;
if (!GetSharedData(event, &sensor_objects)) {
return false;
}
// Make sure timestamp and type are filled.
sensor_objects->timestamp = event.timestamp;
if (event.event_id == radar_event_id_) {
sensor_objects->sensor_type = SensorType::RADAR;
} else if (event.event_id == camera_event_id_) {
sensor_objects->sensor_type = SensorType::CAMERA;
} else {
AERROR << "Event id is not supported. event:" << event.to_string();
return false;
}
sensor_objects->sensor_id = GetSensorType(sensor_objects->sensor_type);
multi_sensor_objs->push_back(*sensor_objects);
ADEBUG << "get sensor objs:" << sensor_objects->ToString();
}
return true;
}
bool AsyncFusionSubnode::GetSharedData(const Event &event,
std::shared_ptr<SensorObjects> *objs) {
double timestamp = event.timestamp;
const std::string &device_id = event.reserve;
std::string data_key;
if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {
AERROR << "Failed to produce shared data key. EventID:" << event.event_id
<< " timestamp:" << timestamp << " device_id:" << device_id;
return false;
}
bool get_data_succ = false;
if (event.event_id == radar_event_id_ && radar_object_data_ != nullptr) {
get_data_succ = radar_object_data_->Get(data_key, objs);
} else if (event.event_id == camera_event_id_ &&
camera_object_data_ != nullptr) {
get_data_succ = camera_object_data_->Get(data_key, objs);
// trying to get lane shared data as well
Event lane_event;
if (event_manager_->Subscribe(lane_event_id_, &lane_event, false)) {
get_data_succ =
lane_shared_data_->Get(data_key, &((*objs)->lane_objects));
AINFO << "getting lane data successfully for data key " << data_key;
}
} else {
AERROR << "Event id is not supported. event:" << event.to_string();
return false;
}
if (!get_data_succ) {
AERROR << "Failed to get shared data. event:" << event.to_string();
return false;
}
return true;
}
bool AsyncFusionSubnode::GeneratePbMsg(PerceptionObstacles *obstacles) {
common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
FLAGS_obstacle_module_name, obstacles);
common::Header *header = obstacles->mutable_header();
header->set_lidar_timestamp(timestamp_ * 1e9); // in ns
header->set_camera_timestamp(0);
header->set_radar_timestamp(0);
obstacles->set_error_code(error_code_);
for (const auto &obj : objects_) {
PerceptionObstacle *obstacle = obstacles->add_perception_obstacle();
obj->Serialize(obstacle);
}
ADEBUG << "PerceptionObstacles: " << obstacles->ShortDebugString();
return true;
}
void AsyncFusionSubnode::RegistAllAlgorithm() {
RegisterFactoryAsyncFusion();
}
void AsyncFusionSubnode::OnChassis(const Chassis &chassis) {
ADEBUG << "Received chassis data: run chassis callback.";
chassis_.CopyFrom(chassis);
chassis_speed_mps_ = chassis.speed_mps();
}
} // namespace perception
} // namespace apollo
<|endoftext|>
|
<commit_before>#include "entity_system.h"
#include "enumerate.h"
#include <entt.hpp>
#include "components/basic_info.h"
#include "components/computed_values.h"
#include "components/faction.h"
#include "components/graphics.h"
#include "components/guild.h"
#include "components/hotbar.h"
#include "components/inventory.h"
#include "components/item.h"
#include "components/level.h"
#include "components/life.h"
#include "components/magic.h"
#include "components/npc.h"
#include "components/owner.h"
#include "components/position.h"
#include "components/skills.h"
#include "components/stamina.h"
#include "components/stats.h"
#include "components/status_effects.h"
#include "components/wishlist.h"
EntitySystem::EntitySystem(std::chrono::milliseconds maxTimePerUpdate) : maxTimePerUpdate(maxTimePerUpdate) {
logger = Core::CLog::GetLogger(Core::log_type::NETWORK).lock();
}
EntitySystem::~EntitySystem() {
work_queue.kill();
}
void EntitySystem::add_task(std::function<void(RoseCommon::Registry&, std::chrono::milliseconds)>&& task) {
work_queue.push_back(std::move(task));
}
void EntitySystem::update(std::chrono::milliseconds dt) {
auto start = Core::Time::GetTickCount();
for (auto [res, task] = work_queue.pop_front(); res;) {
std::lock_guard<std::mutex> lock(access);
task(registry, dt);
const std::chrono::milliseconds diff = std::chrono::duration_cast<std::chrono::milliseconds>(Core::Time::GetTickCount() - start);
if (diff >= maxTimePerUpdate) {
logger->warn("Stopping after {}ms, {} tasks remaining", maxTimePerUpdate.count(), work_queue.size());
break;
}
auto [tmp_res, tmp_task] = work_queue.pop_front();
res = tmp_res;
task = std::move(tmp_task);
}
}
RoseCommon::Entity EntitySystem::load_character(uint32_t charId, bool platinium) {
using namespace Component;
auto conn = Core::connectionPool.getConnection(Core::osirose);
Core::CharacterTable characters{};
Core::InventoryTable inventoryTable{};
Core::SkillTable skillsTable{};
Core::WishTable wish{};
auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))
.from(characters).where(characters.id == charId));
if (static_cast<long>(charRes.front().count) != 1L) {
return entt::null;
}
const auto& charRow = charRes.front();
entt::prototype prototype(registry);
auto& basicInfo = prototype.set<BasicInfo>();
basicInfo.name = charRow.name;
basicInfo.id = idManager.get_free_id();
basicInfo.tag = basicInfo.id;
basicInfo.teamId = basicInfo.id;
basicInfo.job = charRow.job;
basicInfo.statPoints = charRow.stat_points;
basicInfo.skillPoints = charRow.skill_points;
basicInfo.pkFlag = charRow.pk_flag;
auto& computedValues = prototype.set<ComputedValues>();
computedValues.command = RoseCommon::Command::STOP;
computedValues.isOnMap.store(false);
computedValues.moveMode = RoseCommon::MoveMode::WALK;
computedValues.runSpeed = 0;
computedValues.atkSpeed = 0;
computedValues.weightRate = 0;
auto& faction = prototype.set<Faction>();
faction.id = charRow.factionid;
faction.rank = charRow.faction_rank;
faction.fame = charRow.fame;
faction.factionFame[0] = charRow.faction_fame1;
faction.factionFame[1] = charRow.faction_fame2;
faction.points[0] = charRow.faction_points1;
faction.points[1] = charRow.faction_points2;
faction.points[2] = charRow.faction_points3;
auto& graphics = prototype.set<Graphics>();
graphics.face = charRow.face;
graphics.hair = charRow.hair;
graphics.race = charRow.race;
auto& guild = prototype.set<Guild>();
guild.id = charRow.clanid;
guild.contribution = charRow.clan_contribution;
guild.rank = charRow.clan_rank;
prototype.set<Hotbar>();
auto invRes =
conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId));
auto& inventory = prototype.set<Inventory>();
auto& level = prototype.set<Level>();
level.xp = charRow.exp;
level.level = charRow.level;
level.penaltyXp = charRow.penalty_exp;
auto& life = prototype.set<Life>();
life.hp = charRow.maxHp / 3; // you only get 30% of your health when login in
life.maxHp = charRow.maxHp;
auto& magic = prototype.set<Magic>();
magic.mp = charRow.maxMp / 3;
magic.maxMp = charRow.maxMp;
auto& pos = prototype.set<Position>();
pos.x = charRow.x;
pos.y = charRow.y;
pos.z = 0;
pos.spawn = charRow.reviveMap;
auto skillRes =
conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId));
auto& skills = prototype.set<Skills>();
for (const auto& [i, row] : Core::enumerate(skillRes)) {
skills[i].set_id(row.id);
skills[i].set_level(row.level);
}
auto& stamina = prototype.set<Stamina>();
stamina.stamina = charRow.stamina;
auto& stats = prototype.set<Stats>();
stats.str = charRow.str;
stats.dex = charRow.dex;
stats.int_ = charRow.int_;
stats.con = charRow.con;
stats.charm = charRow.charm;
stats.sense = charRow.sense;
stats.bodySize = 100;
stats.headSize = 100;
prototype.set<StatusEffects>();
auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId));
auto& wishlist = prototype.set<Wishlist>();
for (const auto& row : wishRes) {
if (row.slot >= RoseCommon::MAX_WISHLIST) {
continue;
}
// TODO: add load_item from database (from row??)
}
std::lock_guard<std::mutex> lock(access);
return prototype();
}
void EntitySystem::save_character(RoseCommon::Entity character) const {
}
RoseCommon::Entity EntitySystem::create_item(uint8_t type, uint16_t id) {
using namespace Component;
entt::prototype prototype(registry);
const auto &itemDb = ItemDatabase::getInstance();
if (!itemDb.hasItemDef(type, id)) {
return entt::null;
}
const auto def = itemDb.getItemDef(type, id);
auto& item = prototype.set<Item>();
item.type = type;
item.id = id;
item.isCreated = false;
item.life = 1000;
item.hasSocket = false;
item.isAppraised = false;
item.refine = 0;
item.count = 0;
item.gemOpt = 0;
std::lock_guard<std::mutex> lock(access);
return prototype();
}
<commit_msg>Update entity_system.cpp<commit_after>#include "entity_system.h"
#include "enumerate.h"
#include <entt.hpp>
#include "components/basic_info.h"
#include "components/computed_values.h"
#include "components/faction.h"
#include "components/graphics.h"
#include "components/guild.h"
#include "components/hotbar.h"
#include "components/inventory.h"
#include "components/item.h"
#include "components/level.h"
#include "components/life.h"
#include "components/magic.h"
#include "components/npc.h"
#include "components/owner.h"
#include "components/position.h"
#include "components/skills.h"
#include "components/stamina.h"
#include "components/stats.h"
#include "components/status_effects.h"
#include "components/wishlist.h"
EntitySystem::EntitySystem(std::chrono::milliseconds maxTimePerUpdate) : maxTimePerUpdate(maxTimePerUpdate) {
logger = Core::CLog::GetLogger(Core::log_type::NETWORK).lock();
}
EntitySystem::~EntitySystem() {
work_queue.kill();
}
void EntitySystem::add_task(std::function<void(RoseCommon::Registry&, std::chrono::milliseconds)>&& task) {
work_queue.push_back(std::move(task));
}
void EntitySystem::update(std::chrono::milliseconds dt) {
auto start = Core::Time::GetTickCount();
for (auto [res, task] = work_queue.pop_front(); res;) {
std::lock_guard<std::mutex> lock(access);
task(registry, dt);
const std::chrono::milliseconds diff = std::chrono::duration_cast<std::chrono::milliseconds>(Core::Time::GetTickCount() - start);
if (diff >= maxTimePerUpdate) {
logger->warn("Stopping after {}ms, {} tasks remaining", maxTimePerUpdate.count(), work_queue.size());
break;
}
auto [tmp_res, tmp_task] = work_queue.pop_front();
res = tmp_res;
task = std::move(tmp_task);
}
}
RoseCommon::Entity EntitySystem::load_character(uint32_t charId, bool platinium) {
using namespace Component;
auto conn = Core::connectionPool.getConnection(Core::osirose);
Core::CharacterTable characters{};
Core::InventoryTable inventoryTable{};
Core::SkillTable skillsTable{};
Core::WishTable wish{};
auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))
.from(characters).where(characters.id == charId));
if (static_cast<long>(charRes.front().count) != 1L) {
return entt::null;
}
const auto& charRow = charRes.front();
entt::prototype prototype(registry);
auto& basicInfo = prototype.set<BasicInfo>();
basicInfo.name = charRow.name;
basicInfo.id = idManager.get_free_id();
basicInfo.tag = basicInfo.id;
basicInfo.teamId = basicInfo.id;
basicInfo.job = charRow.job;
basicInfo.statPoints = charRow.stat_points;
basicInfo.skillPoints = charRow.skill_points;
basicInfo.pkFlag = charRow.pk_flag;
auto& computedValues = prototype.set<ComputedValues>();
computedValues.command = RoseCommon::Command::STOP;
computedValues.isOnMap.store(false);
computedValues.moveMode = RoseCommon::MoveMode::WALK;
computedValues.runSpeed = 0;
computedValues.atkSpeed = 0;
computedValues.weightRate = 0;
auto& faction = prototype.set<Faction>();
faction.id = charRow.factionid;
faction.rank = charRow.faction_rank;
faction.fame = charRow.fame;
faction.factionFame[0] = charRow.faction_fame1;
faction.factionFame[1] = charRow.faction_fame2;
faction.points[0] = charRow.faction_points1;
faction.points[1] = charRow.faction_points2;
faction.points[2] = charRow.faction_points3;
auto& graphics = prototype.set<Graphics>();
graphics.face = charRow.face;
graphics.hair = charRow.hair;
graphics.race = charRow.race;
auto& guild = prototype.set<Guild>();
guild.id = charRow.clanid;
guild.contribution = charRow.clan_contribution;
guild.rank = charRow.clan_rank;
prototype.set<Hotbar>();
auto invRes =
conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId));
auto& inventory = prototype.set<Inventory>();
auto& level = prototype.set<Level>();
level.xp = charRow.exp;
level.level = charRow.level;
level.penaltyXp = charRow.penalty_exp;
auto& life = prototype.set<Life>();
life.hp = charRow.maxHp / 3; // you only get 30% of your health when login in
life.maxHp = charRow.maxHp;
auto& magic = prototype.set<Magic>();
magic.mp = charRow.maxMp / 3;
magic.maxMp = charRow.maxMp;
auto& pos = prototype.set<Position>();
pos.x = charRow.x;
pos.y = charRow.y;
pos.z = 0;
pos.spawn = charRow.reviveMap;
auto skillRes =
conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId));
auto& skills = prototype.set<Skills>();
for (const auto& [i, row] : Core::enumerate(skillRes)) {
skills[i].set_id(row.id);
skills[i].set_level(row.level);
}
auto& stamina = prototype.set<Stamina>();
stamina.stamina = charRow.stamina;
auto& stats = prototype.set<Stats>();
stats.str = charRow.str;
stats.dex = charRow.dex;
stats.int_ = charRow.int_;
stats.con = charRow.con;
stats.charm = charRow.charm;
stats.sense = charRow.sense;
stats.bodySize = 100;
stats.headSize = 100;
prototype.set<StatusEffects>();
auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId));
auto& wishlist = prototype.set<Wishlist>();
for (const auto& row : wishRes) {
if (row.slot >= RoseCommon::MAX_WISHLIST) {
continue;
}
// TODO: add load_item from database (from row??)
}
std::lock_guard<std::mutex> lock(access);
return prototype();
}
void EntitySystem::save_character(RoseCommon::Entity character) const {
}
RoseCommon::Entity EntitySystem::create_item(uint8_t type, uint16_t id) {
using namespace Component;
entt::prototype prototype(registry);
const auto &itemDb = RoseCommon::ItemDatabase::getInstance();
if (!itemDb.hasItemDef(type, id)) {
return entt::null;
}
const auto& def = itemDb.getItemDef(type, id);
auto& item = prototype.set<Item>();
item.type = type;
item.id = id;
item.isCreated = false;
item.life = 1000;
item.hasSocket = false;
item.isAppraised = false;
item.refine = 0;
item.count = 0;
item.gemOpt = 0;
prototype.set<RoseCommon::ItemDatabase::ItemDef>(def);
std::lock_guard<std::mutex> lock(access);
return prototype();
}
<|endoftext|>
|
<commit_before>#include "Serial.hpp"
#include <stdexcept>
using namespace TurtlebotLibrary;
SerialPort::SerialPort()
{
this->port = nullptr;
this->baud = 0;
this->opened = false;
this->handle = INVALID_SERIAL_PORT_HANDLE;
}
SerialPort::SerialPort(const char *port, int baud)
{
this->port = port;
this->baud = baud;
this->opened = false;
this->handle = INVALID_SERIAL_PORT_HANDLE;
}
SerialPort::~SerialPort()
{
this->Close();
}
bool SerialPort::IsOpen() const
{
return this->opened;
}
const char * SerialPort::GetPort() const
{
return this->port;
}
int SerialPort::GetBaud() const
{
return this->baud;
}
void SerialPort::SetPortName(const char *portname)
{
this->port = portname;
}
void SerialPort::SetBaud(int baudrate)
{
this->baud = baudrate;
}
#ifdef _WIN32
bool SerialPort::Open()
{
DCB dcb;
COMMTIMEOUTS commTO;
if (!this->port)
return false;
handle = CreateFile(
port,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_FLAG_WRITE_THROUGH,
0
);
if (handle == INVALID_HANDLE_VALUE)
return false;
memset(&dcb, 0, sizeof(DCB));
if (!GetCommState(handle, &dcb))
{
CloseHandle(handle);
return false;
}
dcb.BaudRate = baud;
dcb.fParity = FALSE;
dcb.StopBits = ONESTOPBIT;
dcb.ByteSize = 8;
dcb.DCBlength = sizeof(dcb);
if (!SetCommState(handle, &dcb))
{
CloseHandle(handle);
return false;
}
memset(&commTO, 0, sizeof(COMMTIMEOUTS));
commTO.ReadIntervalTimeout = MAXDWORD;
if (!SetCommTimeouts(handle, &commTO))
{
CloseHandle(handle);
return INVALID_HANDLE_VALUE;
}
this->opened = true;
return true;
}
void SerialPort::Close()
{
if (this->opened)
CloseHandle(handle);
this->opened = false;
}
int SerialPort::WriteData(const void *data, int size_bytes)
{
DWORD bytesWritten;
if (handle == INVALID_HANDLE_VALUE)
return -1;
if (!WriteFile(handle, data, size_bytes, &bytesWritten, nullptr))
return -1;
return bytesWritten;
}
int SerialPort::ReadData(void *data, int max_size_bytes)
{
DWORD bytesRead;
if (handle == INVALID_HANDLE_VALUE)
return -1;
if (!ReadFile(handle, data, max_size_bytes, &bytesRead, nullptr))
return -1;
return bytesRead;
}
#else
bool SerialPort::Open()
{
struct termios serialPortProperties;
if (!this->port)
return false;
handle = open(port, O_RDWR | O_NOCTTY);
if (handle < 0)
return false;
memset(&serialPortProperties, 0, sizeof(struct termios));
tcgetattr(handle, &serialPortProperties);
cfsetospeed(&serialPortProperties, baud);
cfsetispeed(&serialPortProperties, baud);
serialPortProperties.c_cflag = (serialPortProperties.c_cflag & ~CSIZE) | CS8;
serialPortProperties.c_cflag &= ~(PARENB | PARODD);
serialPortProperties.c_cflag &= ~CSTOPB;
tcflush(handle, TCIFLUSH);
tcsetattr(handle, TCSANOW, &serialPortProperties);
this->opened = true;
return true;
}
void SerialPort::Close()
{
if (handle > 0)
close(handle);
}
int SerialPort::WriteData(const void *data, int size_bytes)
{
if (handle < 0)
return -1;
return write(handle, data, size_bytes);
}
int SerialPort::ReadData(void *data, int max_size_bytes)
{
if (handle < 0)
return -1;
return read(handle, data, max_size_bytes);
}
#endif<commit_msg>Port fixes for serial port destructor to linux.<commit_after>#include "Serial.hpp"
#include <stdexcept>
using namespace TurtlebotLibrary;
SerialPort::SerialPort()
{
this->port = nullptr;
this->baud = 0;
this->opened = false;
this->handle = INVALID_SERIAL_PORT_HANDLE;
}
SerialPort::SerialPort(const char *port, int baud)
{
this->port = port;
this->baud = baud;
this->opened = false;
this->handle = INVALID_SERIAL_PORT_HANDLE;
}
SerialPort::~SerialPort()
{
this->Close();
}
bool SerialPort::IsOpen() const
{
return this->opened;
}
const char * SerialPort::GetPort() const
{
return this->port;
}
int SerialPort::GetBaud() const
{
return this->baud;
}
void SerialPort::SetPortName(const char *portname)
{
this->port = portname;
}
void SerialPort::SetBaud(int baudrate)
{
this->baud = baudrate;
}
#ifdef _WIN32
bool SerialPort::Open()
{
DCB dcb;
COMMTIMEOUTS commTO;
if (!this->port)
return false;
handle = CreateFile(
port,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_FLAG_WRITE_THROUGH,
0
);
if (handle == INVALID_HANDLE_VALUE)
return false;
memset(&dcb, 0, sizeof(DCB));
if (!GetCommState(handle, &dcb))
{
CloseHandle(handle);
return false;
}
dcb.BaudRate = baud;
dcb.fParity = FALSE;
dcb.StopBits = ONESTOPBIT;
dcb.ByteSize = 8;
dcb.DCBlength = sizeof(dcb);
if (!SetCommState(handle, &dcb))
{
CloseHandle(handle);
return false;
}
memset(&commTO, 0, sizeof(COMMTIMEOUTS));
commTO.ReadIntervalTimeout = MAXDWORD;
if (!SetCommTimeouts(handle, &commTO))
{
CloseHandle(handle);
return false;
}
this->opened = true;
return true;
}
void SerialPort::Close()
{
if (this->opened)
CloseHandle(handle);
this->opened = false;
}
int SerialPort::WriteData(const void *data, int size_bytes)
{
DWORD bytesWritten;
if (handle == INVALID_HANDLE_VALUE)
return -1;
if (!WriteFile(handle, data, size_bytes, &bytesWritten, nullptr))
return -1;
return bytesWritten;
}
int SerialPort::ReadData(void *data, int max_size_bytes)
{
DWORD bytesRead;
if (handle == INVALID_HANDLE_VALUE)
return -1;
if (!ReadFile(handle, data, max_size_bytes, &bytesRead, nullptr))
return -1;
return bytesRead;
}
#else
bool SerialPort::Open()
{
struct termios serialPortProperties;
if (!this->port)
return false;
handle = open(port, O_RDWR | O_NOCTTY);
if (handle < 0)
return false;
memset(&serialPortProperties, 0, sizeof(struct termios));
tcgetattr(handle, &serialPortProperties);
cfsetospeed(&serialPortProperties, baud);
cfsetispeed(&serialPortProperties, baud);
serialPortProperties.c_cflag = (serialPortProperties.c_cflag & ~CSIZE) | CS8;
serialPortProperties.c_cflag &= ~(PARENB | PARODD);
serialPortProperties.c_cflag &= ~CSTOPB;
tcflush(handle, TCIFLUSH);
tcsetattr(handle, TCSANOW, &serialPortProperties);
this->opened = true;
return true;
}
void SerialPort::Close()
{
if (this->opened)
close(handle);
this->opened = false;
}
int SerialPort::WriteData(const void *data, int size_bytes)
{
if (handle < 0)
return -1;
return write(handle, data, size_bytes);
}
int SerialPort::ReadData(void *data, int max_size_bytes)
{
if (handle < 0)
return -1;
return read(handle, data, max_size_bytes);
}
#endif<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/container/obstacles/obstacle_clusters.h"
#include <algorithm>
#include <limits>
#include "modules/prediction/common/road_graph.h"
namespace apollo {
namespace prediction {
using ::apollo::hdmap::LaneInfo;
std::unordered_map<std::string, LaneGraph> ObstacleClusters::lane_graphs_;
std::unordered_map<std::string, std::vector<LaneObstacle>>
ObstacleClusters::lane_obstacles_;
std::unordered_map<std::string, StopSign>
ObstacleClusters::lane_id_stop_sign_map_;
void ObstacleClusters::Clear() {
lane_graphs_.clear();
lane_obstacles_.clear();
lane_id_stop_sign_map_.clear();
}
void ObstacleClusters::Init() { Clear(); }
const LaneGraph& ObstacleClusters::GetLaneGraph(
const double start_s, const double length,
std::shared_ptr<const LaneInfo> lane_info_ptr) {
std::string lane_id = lane_info_ptr->id().id();
if (lane_graphs_.find(lane_id) != lane_graphs_.end()) {
// If this lane_segment has been used for constructing LaneGraph,
// fetch the previously saved LaneGraph, modify its start_s,
// then return this (save the time to construct the entire LaneGraph).
LaneGraph* lane_graph = &lane_graphs_[lane_id];
for (int i = 0; i < lane_graph->lane_sequence_size(); ++i) {
LaneSequence* lane_seq_ptr = lane_graph->mutable_lane_sequence(i);
if (lane_seq_ptr->lane_segment_size() == 0) {
continue;
}
LaneSegment* first_lane_seg_ptr = lane_seq_ptr->mutable_lane_segment(0);
if (first_lane_seg_ptr->lane_id() != lane_id) {
continue;
}
first_lane_seg_ptr->set_start_s(start_s);
}
} else {
// If this lane_segment has not been used for constructing LaneGraph,
// construct the LaneGraph and return.
RoadGraph road_graph(start_s, length, lane_info_ptr);
LaneGraph lane_graph;
road_graph.BuildLaneGraph(&lane_graph);
lane_graphs_[lane_id] = std::move(lane_graph);
}
return lane_graphs_[lane_id];
}
LaneGraph ObstacleClusters::GetLaneGraphWithoutMemorizing(
const double start_s, const double length,
std::shared_ptr<const LaneInfo> lane_info_ptr) {
RoadGraph road_graph(start_s, length, lane_info_ptr);
LaneGraph lane_graph;
road_graph.BuildLaneGraph(&lane_graph);
return lane_graph;
}
void ObstacleClusters::AddObstacle(
const int obstacle_id,
const std::string& lane_id,
const double lane_s,
const double lane_l) {
LaneObstacle lane_obstacle;
lane_obstacle.set_obstacle_id(obstacle_id);
lane_obstacle.set_lane_id(lane_id);
lane_obstacle.set_lane_s(lane_s);
lane_obstacle.set_lane_l(lane_l);
lane_obstacles_[lane_id].push_back(std::move(lane_obstacle));
}
void ObstacleClusters::SortObstacles() {
for (auto iter = lane_obstacles_.begin();
iter != lane_obstacles_.end(); ++iter) {
std::sort(iter->second.begin(), iter->second.end(),
[](const LaneObstacle& obs0, const LaneObstacle& obs1) -> bool {
return obs0.lane_s() < obs1.lane_s();
});
}
}
bool ObstacleClusters::ForwardNearbyObstacle(
const LaneSequence& lane_sequence,
const int obstacle_id,
const double obstacle_s,
const double obstacle_l,
NearbyObstacle* const nearby_obstacle_ptr) {
double accumulated_s = 0.0;
for (const LaneSegment& lane_segment : lane_sequence.lane_segment()) {
std::string lane_id = lane_segment.lane_id();
double lane_length = lane_segment.total_length();
if (lane_obstacles_.find(lane_id) == lane_obstacles_.end() ||
lane_obstacles_[lane_id].empty()) {
accumulated_s += lane_length;
continue;
}
for (const LaneObstacle& lane_obstacle : lane_obstacles_[lane_id]) {
if (lane_obstacle.obstacle_id() == obstacle_id) {
continue;
}
double relative_s = accumulated_s + lane_obstacle.lane_s() - obstacle_s;
double relative_l = lane_obstacle.lane_l() - obstacle_l;
if (relative_s > 0.0) {
nearby_obstacle_ptr->set_id(lane_obstacle.obstacle_id());
nearby_obstacle_ptr->set_s(relative_s);
nearby_obstacle_ptr->set_l(relative_l);
return true;
}
}
}
return false;
}
bool ObstacleClusters::BackwardNearbyObstacle(
const LaneSequence& lane_sequence,
const int obstacle_id,
const double obstacle_s,
const double obstacle_l,
NearbyObstacle* const nearby_obstacle_ptr) {
if (lane_sequence.lane_segment_size() == 0) {
AERROR << "Empty lane sequence found.";
return false;
}
const LaneSegment& lane_segment = lane_sequence.lane_segment(0);
std::string lane_id = lane_segment.lane_id();
// Search current lane
if (lane_obstacles_.find(lane_id) != lane_obstacles_.end() &&
!lane_obstacles_[lane_id].empty()) {
for (std::size_t i = lane_obstacles_[lane_id].size() - 1; i >= 0; --i) {
const LaneObstacle& lane_obstacle = lane_obstacles_[lane_id][i];
if (lane_obstacle.obstacle_id() == obstacle_id) {
continue;
}
double relative_s = lane_obstacle.lane_s() - obstacle_s;
double relative_l = lane_obstacle.lane_l() - obstacle_l;
if (relative_s < 0.0) {
nearby_obstacle_ptr->set_id(lane_obstacle.obstacle_id());
nearby_obstacle_ptr->set_s(relative_s);
nearby_obstacle_ptr->set_l(relative_l);
return true;
}
}
}
// Search backward lanes
std::shared_ptr<const LaneInfo> lane_info_ptr =
PredictionMap::LaneById(lane_id);
bool found_one_behind = false;
double relative_s = -std::numeric_limits<double>::infinity();
double relative_l = 0.0;
for (const auto& predecessor_lane_id :
lane_info_ptr->lane().predecessor_id()) {
std::string lane_id = predecessor_lane_id.id();
if (lane_obstacles_.find(lane_id) == lane_obstacles_.end() ||
lane_obstacles_[lane_id].empty()) {
continue;
}
std::shared_ptr<const LaneInfo> pred_lane_info_ptr =
PredictionMap::LaneById(predecessor_lane_id.id());
const LaneObstacle& backward_obs = lane_obstacles_[lane_id].back();
double delta_s = backward_obs.lane_s() -
(obstacle_s + pred_lane_info_ptr->total_length());
found_one_behind = true;
if (delta_s > relative_s) {
relative_s = delta_s;
relative_l = backward_obs.lane_l() - obstacle_l;
nearby_obstacle_ptr->set_id(backward_obs.obstacle_id());
nearby_obstacle_ptr->set_s(relative_s);
nearby_obstacle_ptr->set_l(relative_l);
}
}
return found_one_behind;
}
StopSign ObstacleClusters::QueryStopSignByLaneId(const std::string& lane_id) {
StopSign stop_sign;
// Find the stop_sign by lane_id in the hashtable
if (lane_id_stop_sign_map_.find(lane_id) != lane_id_stop_sign_map_.end()) {
return lane_id_stop_sign_map_[lane_id];
}
std::shared_ptr<const LaneInfo> lane_info_ptr =
PredictionMap::LaneById(lane_id);
CHECK_NOTNULL(lane_info_ptr);
for (const auto &overlap_id : lane_info_ptr->lane().overlap_id()) {
auto overlap_info_ptr = PredictionMap::OverlapById(overlap_id.id());
if (overlap_info_ptr == nullptr) {
continue;
}
for (const auto &object : overlap_info_ptr->overlap().object()) {
// find the overlap with stop_sign
if (object.has_stop_sign_overlap_info()) {
for (const auto &obj : overlap_info_ptr->overlap().object()) {
// find the obj of in the overlap
if (obj.has_lane_overlap_info()) {
if (!stop_sign.has_lane_s() ||
stop_sign.lane_s() > obj.lane_overlap_info().start_s()) {
stop_sign.set_stop_sign_id(object.id().id());
stop_sign.set_lane_id(lane_id);
stop_sign.set_lane_s(obj.lane_overlap_info().start_s());
lane_id_stop_sign_map_[lane_id] = stop_sign;
}
}
}
}
}
}
return lane_id_stop_sign_map_[lane_id];
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: fix infinite loop on search curr_lane<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/container/obstacles/obstacle_clusters.h"
#include <algorithm>
#include <limits>
#include "modules/prediction/common/road_graph.h"
namespace apollo {
namespace prediction {
using ::apollo::hdmap::LaneInfo;
std::unordered_map<std::string, LaneGraph> ObstacleClusters::lane_graphs_;
std::unordered_map<std::string, std::vector<LaneObstacle>>
ObstacleClusters::lane_obstacles_;
std::unordered_map<std::string, StopSign>
ObstacleClusters::lane_id_stop_sign_map_;
void ObstacleClusters::Clear() {
lane_graphs_.clear();
lane_obstacles_.clear();
lane_id_stop_sign_map_.clear();
}
void ObstacleClusters::Init() { Clear(); }
const LaneGraph& ObstacleClusters::GetLaneGraph(
const double start_s, const double length,
std::shared_ptr<const LaneInfo> lane_info_ptr) {
std::string lane_id = lane_info_ptr->id().id();
if (lane_graphs_.find(lane_id) != lane_graphs_.end()) {
// If this lane_segment has been used for constructing LaneGraph,
// fetch the previously saved LaneGraph, modify its start_s,
// then return this (save the time to construct the entire LaneGraph).
LaneGraph* lane_graph = &lane_graphs_[lane_id];
for (int i = 0; i < lane_graph->lane_sequence_size(); ++i) {
LaneSequence* lane_seq_ptr = lane_graph->mutable_lane_sequence(i);
if (lane_seq_ptr->lane_segment_size() == 0) {
continue;
}
LaneSegment* first_lane_seg_ptr = lane_seq_ptr->mutable_lane_segment(0);
if (first_lane_seg_ptr->lane_id() != lane_id) {
continue;
}
first_lane_seg_ptr->set_start_s(start_s);
}
} else {
// If this lane_segment has not been used for constructing LaneGraph,
// construct the LaneGraph and return.
RoadGraph road_graph(start_s, length, lane_info_ptr);
LaneGraph lane_graph;
road_graph.BuildLaneGraph(&lane_graph);
lane_graphs_[lane_id] = std::move(lane_graph);
}
return lane_graphs_[lane_id];
}
LaneGraph ObstacleClusters::GetLaneGraphWithoutMemorizing(
const double start_s, const double length,
std::shared_ptr<const LaneInfo> lane_info_ptr) {
RoadGraph road_graph(start_s, length, lane_info_ptr);
LaneGraph lane_graph;
road_graph.BuildLaneGraph(&lane_graph);
return lane_graph;
}
void ObstacleClusters::AddObstacle(
const int obstacle_id,
const std::string& lane_id,
const double lane_s,
const double lane_l) {
LaneObstacle lane_obstacle;
lane_obstacle.set_obstacle_id(obstacle_id);
lane_obstacle.set_lane_id(lane_id);
lane_obstacle.set_lane_s(lane_s);
lane_obstacle.set_lane_l(lane_l);
lane_obstacles_[lane_id].push_back(std::move(lane_obstacle));
}
void ObstacleClusters::SortObstacles() {
for (auto iter = lane_obstacles_.begin();
iter != lane_obstacles_.end(); ++iter) {
std::sort(iter->second.begin(), iter->second.end(),
[](const LaneObstacle& obs0, const LaneObstacle& obs1) -> bool {
return obs0.lane_s() < obs1.lane_s();
});
}
}
bool ObstacleClusters::ForwardNearbyObstacle(
const LaneSequence& lane_sequence,
const int obstacle_id,
const double obstacle_s,
const double obstacle_l,
NearbyObstacle* const nearby_obstacle_ptr) {
double accumulated_s = 0.0;
for (const LaneSegment& lane_segment : lane_sequence.lane_segment()) {
std::string lane_id = lane_segment.lane_id();
double lane_length = lane_segment.total_length();
if (lane_obstacles_.find(lane_id) == lane_obstacles_.end() ||
lane_obstacles_[lane_id].empty()) {
accumulated_s += lane_length;
continue;
}
for (const LaneObstacle& lane_obstacle : lane_obstacles_[lane_id]) {
if (lane_obstacle.obstacle_id() == obstacle_id) {
continue;
}
double relative_s = accumulated_s + lane_obstacle.lane_s() - obstacle_s;
double relative_l = lane_obstacle.lane_l() - obstacle_l;
if (relative_s > 0.0) {
nearby_obstacle_ptr->set_id(lane_obstacle.obstacle_id());
nearby_obstacle_ptr->set_s(relative_s);
nearby_obstacle_ptr->set_l(relative_l);
return true;
}
}
}
return false;
}
bool ObstacleClusters::BackwardNearbyObstacle(
const LaneSequence& lane_sequence,
const int obstacle_id,
const double obstacle_s,
const double obstacle_l,
NearbyObstacle* const nearby_obstacle_ptr) {
if (lane_sequence.lane_segment_size() == 0) {
AERROR << "Empty lane sequence found.";
return false;
}
const LaneSegment& lane_segment = lane_sequence.lane_segment(0);
std::string lane_id = lane_segment.lane_id();
// Search current lane
if (lane_obstacles_.find(lane_id) != lane_obstacles_.end() &&
!lane_obstacles_[lane_id].empty()) {
for (int i = static_cast<int>(lane_obstacles_[lane_id].size()) - 1;
i >= 0; --i) {
const LaneObstacle& lane_obstacle = lane_obstacles_[lane_id][i];
if (lane_obstacle.obstacle_id() == obstacle_id) {
continue;
}
double relative_s = lane_obstacle.lane_s() - obstacle_s;
double relative_l = lane_obstacle.lane_l() - obstacle_l;
if (relative_s < 0.0) {
nearby_obstacle_ptr->set_id(lane_obstacle.obstacle_id());
nearby_obstacle_ptr->set_s(relative_s);
nearby_obstacle_ptr->set_l(relative_l);
return true;
}
}
}
// Search backward lanes
std::shared_ptr<const LaneInfo> lane_info_ptr =
PredictionMap::LaneById(lane_id);
bool found_one_behind = false;
double relative_s = -std::numeric_limits<double>::infinity();
double relative_l = 0.0;
for (const auto& predecessor_lane_id :
lane_info_ptr->lane().predecessor_id()) {
std::string lane_id = predecessor_lane_id.id();
if (lane_obstacles_.find(lane_id) == lane_obstacles_.end() ||
lane_obstacles_[lane_id].empty()) {
continue;
}
std::shared_ptr<const LaneInfo> pred_lane_info_ptr =
PredictionMap::LaneById(predecessor_lane_id.id());
const LaneObstacle& backward_obs = lane_obstacles_[lane_id].back();
double delta_s = backward_obs.lane_s() -
(obstacle_s + pred_lane_info_ptr->total_length());
found_one_behind = true;
if (delta_s > relative_s) {
relative_s = delta_s;
relative_l = backward_obs.lane_l() - obstacle_l;
nearby_obstacle_ptr->set_id(backward_obs.obstacle_id());
nearby_obstacle_ptr->set_s(relative_s);
nearby_obstacle_ptr->set_l(relative_l);
}
}
return found_one_behind;
}
StopSign ObstacleClusters::QueryStopSignByLaneId(const std::string& lane_id) {
StopSign stop_sign;
// Find the stop_sign by lane_id in the hashtable
if (lane_id_stop_sign_map_.find(lane_id) != lane_id_stop_sign_map_.end()) {
return lane_id_stop_sign_map_[lane_id];
}
std::shared_ptr<const LaneInfo> lane_info_ptr =
PredictionMap::LaneById(lane_id);
CHECK_NOTNULL(lane_info_ptr);
for (const auto &overlap_id : lane_info_ptr->lane().overlap_id()) {
auto overlap_info_ptr = PredictionMap::OverlapById(overlap_id.id());
if (overlap_info_ptr == nullptr) {
continue;
}
for (const auto &object : overlap_info_ptr->overlap().object()) {
// find the overlap with stop_sign
if (object.has_stop_sign_overlap_info()) {
for (const auto &obj : overlap_info_ptr->overlap().object()) {
// find the obj of in the overlap
if (obj.has_lane_overlap_info()) {
if (!stop_sign.has_lane_s() ||
stop_sign.lane_s() > obj.lane_overlap_info().start_s()) {
stop_sign.set_stop_sign_id(object.id().id());
stop_sign.set_lane_id(lane_id);
stop_sign.set_lane_s(obj.lane_overlap_info().start_s());
lane_id_stop_sign_map_[lane_id] = stop_sign;
}
}
}
}
}
}
return lane_id_stop_sign_map_[lane_id];
}
} // namespace prediction
} // namespace apollo
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 Pavlo Lavrenenko
*
* 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 <Shader.h>
#include <unordered_map>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <vector>
#include <memory>
#ifdef GRAPHENE_DEBUG
#include <iostream>
#endif
namespace Graphene {
GLuint Shader::activeProgram = 0;
Shader::Shader(const std::string& name) {
std::ifstream file(name, std::ios::binary);
if (!file.good()) {
throw std::runtime_error("Failed to open `" + name + "'");
}
file.seekg(0, std::ios::end);
int sourceLength = file.tellg();
file.seekg(0, std::ios::beg);
std::unique_ptr<char[]> source(new char[sourceLength]);
file.read(source.get(), sourceLength);
file.close();
this->source = std::string(source.get(), sourceLength);
this->buildShader();
}
void Shader::buildShader() {
std::vector<GLuint> shaders;
std::unordered_map<std::string, GLenum> shaderTypes = {
{ "#define TYPE_VERTEX\n", GL_VERTEX_SHADER },
{ "#define TYPE_FRAGMENT\n", GL_FRAGMENT_SHADER }
};
for (auto& shaderType: shaderTypes) {
std::stringstream modifiedSource;
modifiedSource << shaderType.first;
modifiedSource << this->source;
shaders.push_back(this->compile(modifiedSource.str(), shaderType.second));
}
this->program = this->link(shaders);
}
GLuint Shader::compile(const std::string& source, GLenum type) {
GLuint shader = glCreateShader(type);
const char* sourceStrings = source.c_str();
glShaderSource(shader, 1, &sourceStrings, nullptr);
glCompileShader(shader);
GLint infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
std::unique_ptr<GLchar[]> infoLog;
if (infoLogLength > 0) { // ATI workaround, successful compilation
infoLog.reset(new GLchar[infoLogLength]);
glGetShaderInfoLog(shader, infoLogLength, nullptr, infoLog.get());
}
GLint compileStatus;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus);
if (compileStatus == GL_FALSE) {
glDeleteShader(shader);
std::stringstream errorMessage;
errorMessage << "Failed to compile shader\n" << infoLog.get();
throw std::runtime_error(errorMessage.str());
}
#ifdef GRAPHENE_DEBUG
if (infoLogLength > 0) {
std::cout << "Shader compiled\n" << infoLog.get() << std::endl;
}
#endif
return shader;
}
GLuint Shader::link(const std::vector<GLuint>& shaders) {
GLuint program = glCreateProgram();
for (auto& shader: shaders) {
glAttachShader(program, shader);
glDeleteShader(shader);
}
glLinkProgram(program);
GLint infoLogLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
std::unique_ptr<GLchar[]> infoLog;
if (infoLogLength > 0) { // ATI workaround, successful linking
infoLog.reset(new GLchar[infoLogLength]);
glGetProgramInfoLog(program, infoLogLength, nullptr, infoLog.get());
}
GLint linkStatus;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_FALSE) {
glDeleteProgram(program);
std::stringstream errorMessage;
errorMessage << "Failed to link shader\n" << infoLog.get();
throw std::runtime_error(errorMessage.str());
}
#ifdef GRAPHENE_DEBUG
if (infoLogLength > 0) {
std::cout << "Shader linked\n" << infoLog.get() << std::endl;
}
#endif
return program;
}
} // namespace Graphene
<commit_msg>Fix shader compilation output<commit_after>/*
* Copyright (c) 2013 Pavlo Lavrenenko
*
* 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 <Shader.h>
#include <unordered_map>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <vector>
#include <memory>
#ifdef GRAPHENE_DEBUG
#include <iostream>
#endif
namespace Graphene {
GLuint Shader::activeProgram = 0;
Shader::Shader(const std::string& name) {
std::ifstream file(name, std::ios::binary);
if (!file.good()) {
throw std::runtime_error("Failed to open `" + name + "'");
}
file.seekg(0, std::ios::end);
int sourceLength = file.tellg();
file.seekg(0, std::ios::beg);
std::unique_ptr<char[]> source(new char[sourceLength]);
file.read(source.get(), sourceLength);
file.close();
this->source = std::string(source.get(), sourceLength);
this->buildShader();
}
void Shader::buildShader() {
std::vector<GLuint> shaders;
std::unordered_map<std::string, GLenum> shaderTypes = {
{ "#define TYPE_VERTEX\n", GL_VERTEX_SHADER },
{ "#define TYPE_FRAGMENT\n", GL_FRAGMENT_SHADER }
};
for (auto& shaderType: shaderTypes) {
std::stringstream modifiedSource;
modifiedSource << shaderType.first;
modifiedSource << this->source;
shaders.push_back(this->compile(modifiedSource.str(), shaderType.second));
}
this->program = this->link(shaders);
}
GLuint Shader::compile(const std::string& source, GLenum type) {
GLuint shader = glCreateShader(type);
const char* sourceStrings = source.c_str();
glShaderSource(shader, 1, &sourceStrings, nullptr);
glCompileShader(shader);
GLint infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
std::unique_ptr<GLchar[]> infoLog;
if (infoLogLength > 1) {
infoLog.reset(new GLchar[infoLogLength]);
glGetShaderInfoLog(shader, infoLogLength, nullptr, infoLog.get());
#ifdef GRAPHENE_DEBUG
std::cout << "Shader compiled\n" << infoLog.get() << std::endl;
#endif
}
GLint compileStatus;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus);
if (compileStatus == GL_FALSE) {
glDeleteShader(shader);
std::stringstream errorMessage;
errorMessage << "Failed to compile shader\n" << infoLog.get();
throw std::runtime_error(errorMessage.str());
}
return shader;
}
GLuint Shader::link(const std::vector<GLuint>& shaders) {
GLuint program = glCreateProgram();
for (auto& shader: shaders) {
glAttachShader(program, shader);
glDeleteShader(shader);
}
glLinkProgram(program);
GLint infoLogLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
std::unique_ptr<GLchar[]> infoLog;
if (infoLogLength > 1) {
infoLog.reset(new GLchar[infoLogLength]);
glGetProgramInfoLog(program, infoLogLength, nullptr, infoLog.get());
#ifdef GRAPHENE_DEBUG
std::cout << "Shader linked\n" << infoLog.get() << std::endl;
#endif
}
GLint linkStatus;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_FALSE) {
glDeleteProgram(program);
std::stringstream errorMessage;
errorMessage << "Failed to link shader\n" << infoLog.get();
throw std::runtime_error(errorMessage.str());
}
return program;
}
} // namespace Graphene
<|endoftext|>
|
<commit_before>#include <string>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include "client.h"
using namespace std;
namespace rpc {
void Future::wait() {
Pthread_mutex_lock(&ready_m_);
while (!ready_) {
Pthread_cond_wait(&ready_cond_, &ready_m_);
}
Pthread_mutex_unlock(&ready_m_);
}
void Future::notify_ready() {
Pthread_mutex_lock(&ready_m_);
ready_ = true;
Pthread_cond_signal(&ready_cond_);
Pthread_mutex_unlock(&ready_m_);
if (attr_.callback != NULL) {
attr_.callback->run(this);
// automatically cleanup the callback
delete attr_.callback;
attr_.callback = NULL;
}
}
Client::Client(PollMgr* pollmgr): pollmgr_(pollmgr), sock_(-1), status_(NEW), bmark_(NULL) {
Pthread_mutex_init(&pending_fu_m_, NULL);
Pthread_mutex_init(&out_m_, NULL);
}
Client::~Client() {
invalidate_pending_futures();
Pthread_mutex_destroy(&pending_fu_m_);
Pthread_mutex_destroy(&out_m_);
//Log::debug("rpc::Client: destroyed");
}
void Client::invalidate_pending_futures() {
list<Future*> futures;
Pthread_mutex_lock(&pending_fu_m_);
while (pending_fu_.empty() == false) {
futures.push_back(pending_fu_.begin()->second);
pending_fu_.erase(pending_fu_.begin());
}
Pthread_mutex_unlock(&pending_fu_m_);
for (list<Future*>::iterator it = futures.begin(); it != futures.end(); ++it) {
Future* fu = *it;
if (fu != NULL) {
fu->error_code_ = ENOTCONN;
fu->notify_ready();
// since we removed it from pending_fu_
fu->release();
}
}
}
void Client::close() {
if (status_ == CONNECTED) {
pollmgr_->remove(this);
::close(sock_);
status_ = CLOSED;
invalidate_pending_futures();
}
status_ = CLOSED;
}
int Client::connect(const char* addr) {
string addr_str(addr);
size_t idx = addr_str.find(":");
if (idx == string::npos) {
Log::error("rpc::Client: bad connect address: %s", addr);
errno = EINVAL;
return -1;
}
string host = addr_str.substr(0, idx);
string port = addr_str.substr(idx + 1);
struct addrinfo hints, *result, *rp;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; // ipv4
hints.ai_socktype = SOCK_STREAM; // tcp
int r = getaddrinfo(host.c_str(), port.c_str(), &hints, &result);
if (r != 0) {
Log::error("rpc::Client: getaddrinfo(): %s", gai_strerror(r));
return -1;
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
sock_ = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock_ == -1) {
continue;
}
const int yes = 1;
verify(setsockopt(sock_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == 0);
verify(setsockopt(sock_, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == 0);
if (::connect(sock_, rp->ai_addr, rp->ai_addrlen) == 0) {
break;
}
::close(sock_);
sock_ = -1;
}
freeaddrinfo(result);
if (rp == NULL) {
// failed to connect
Log::error("rpc::Client: connect(): %s", strerror(errno));
return -1;
}
verify(set_nonblocking(sock_, true) == 0);
Log::info("rpc::Client: connected to %s", addr);
status_ = CONNECTED;
pollmgr_->add(this);
return 0;
}
void Client::handle_error() {
close();
}
void Client::handle_write() {
if (status_ != CONNECTED) {
return;
}
Pthread_mutex_lock(&out_m_);
out_.write_to_fd(sock_);
if (out_.empty()) {
pollmgr_->update_mode(this, Pollable::READ);
}
Pthread_mutex_unlock(&out_m_);
}
void Client::handle_read() {
if (status_ != CONNECTED) {
return;
}
int bytes_read = in_.read_from_fd(sock_);
if (bytes_read == 0) {
return;
}
for (;;) {
i32 packet_size;
int n_peek = in_.peek(&packet_size, sizeof(i32));
if (n_peek == sizeof(i32) && in_.content_size_gt(packet_size + sizeof(i32) - 1)) {
// consume the packet size
verify(in_.read(&packet_size, sizeof(i32)) == sizeof(i32));
i64 reply_xid;
i32 error_code;
in_ >> reply_xid >> error_code;
Pthread_mutex_lock(&pending_fu_m_);
map<i64, Future*>::iterator it = pending_fu_.find(reply_xid);
if (it != pending_fu_.end()) {
Future* fu = it->second;
verify(fu->xid_ == reply_xid);
pending_fu_.erase(it);
Pthread_mutex_unlock(&pending_fu_m_);
fu->error_code_ = error_code;
fu->reply_.read_from_marshal(in_, packet_size - sizeof(reply_xid) - sizeof(error_code));
fu->notify_ready();
// since we removed it from pending_fu_
fu->release();
}
} else {
// packet incomplete or no more packets to process
break;
}
}
}
int Client::poll_mode() {
int mode = Pollable::READ;
Pthread_mutex_lock(&out_m_);
if (!out_.empty()) {
mode |= Pollable::WRITE;
}
Pthread_mutex_unlock(&out_m_);
return mode;
}
Future* Client::begin_request(i32 rpc_id, const FutureAttr& attr /* =... */) {
Pthread_mutex_lock(&out_m_);
if (status_ != CONNECTED) {
if (attr.callback != NULL) {
delete attr.callback;
}
return NULL;
}
Future* fu = new Future(xid_counter_.next(), attr);
Pthread_mutex_lock(&pending_fu_m_);
pending_fu_[fu->xid_] = fu;
pending_fu_.size();
Pthread_mutex_unlock(&pending_fu_m_);
// check if the client gets closed in the meantime
if (status_ != CONNECTED) {
Pthread_mutex_lock(&pending_fu_m_);
map<i64, Future*>::iterator it = pending_fu_.find(fu->xid_);
if (it != pending_fu_.end()) {
it->second->release();
pending_fu_.erase(it);
}
Pthread_mutex_unlock(&pending_fu_m_);
return NULL;
}
bmark_ = out_.set_bookmark(sizeof(i32)); // will fill packet size later
*this << fu->xid_;
*this << rpc_id;
// one ref is already in pending_fu_
return (Future *) fu->ref_copy();
}
void Client::end_request() {
// set reply size in packet
if (bmark_ != NULL) {
i32 request_size = out_.get_write_counter_and_reset();
out_.write_bookmark(bmark_, &request_size);
delete bmark_;
bmark_ = NULL;
}
if (!out_.empty()) {
pollmgr_->update_mode(this, Pollable::READ | Pollable::WRITE);
}
Pthread_mutex_unlock(&out_m_);
}
ClientPool::ClientPool(PollMgr* pollmgr /* =? */) {
Pthread_mutex_init(&m_, NULL);
if (pollmgr == NULL) {
pollmgr_ = new PollMgr(1);
} else {
pollmgr_ = (PollMgr *) pollmgr->ref_copy();
}
}
ClientPool::~ClientPool() {
for (map<string, Client*>::iterator it = cache_.begin(); it != cache_.end(); ++it) {
it->second->close_and_release();
}
pollmgr_->release();
Pthread_mutex_destroy(&m_);
}
Client* ClientPool::get_client(const string& addr) {
Client* cl = NULL;
Pthread_mutex_lock(&m_);
map<string, Client*>::iterator it = cache_.find(addr);
if (it != cache_.end()) {
cl = it->second;
} else {
cl = new Client(this->pollmgr_);
if (cl->connect(addr.c_str()) != 0) {
// connect failure
cl->close_and_release();
cl = NULL;
} else {
// connect success
cache_[addr] = cl;
}
}
Pthread_mutex_unlock(&m_);
return cl;
}
}
<commit_msg>minor update<commit_after>#include <string>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include "client.h"
using namespace std;
namespace rpc {
void Future::wait() {
Pthread_mutex_lock(&ready_m_);
while (!ready_) {
Pthread_cond_wait(&ready_cond_, &ready_m_);
}
Pthread_mutex_unlock(&ready_m_);
}
void Future::notify_ready() {
Pthread_mutex_lock(&ready_m_);
ready_ = true;
Pthread_cond_signal(&ready_cond_);
Pthread_mutex_unlock(&ready_m_);
if (attr_.callback != NULL) {
attr_.callback->run(this);
// automatically cleanup the callback
delete attr_.callback;
attr_.callback = NULL;
}
}
Client::Client(PollMgr* pollmgr): pollmgr_(pollmgr), sock_(-1), status_(NEW), bmark_(NULL) {
Pthread_mutex_init(&pending_fu_m_, NULL);
Pthread_mutex_init(&out_m_, NULL);
}
Client::~Client() {
invalidate_pending_futures();
Pthread_mutex_destroy(&pending_fu_m_);
Pthread_mutex_destroy(&out_m_);
//Log::debug("rpc::Client: destroyed");
}
void Client::invalidate_pending_futures() {
list<Future*> futures;
Pthread_mutex_lock(&pending_fu_m_);
while (pending_fu_.empty() == false) {
futures.push_back(pending_fu_.begin()->second);
pending_fu_.erase(pending_fu_.begin());
}
Pthread_mutex_unlock(&pending_fu_m_);
for (list<Future*>::iterator it = futures.begin(); it != futures.end(); ++it) {
Future* fu = *it;
if (fu != NULL) {
fu->error_code_ = ENOTCONN;
fu->notify_ready();
// since we removed it from pending_fu_
fu->release();
}
}
}
void Client::close() {
if (status_ == CONNECTED) {
pollmgr_->remove(this);
::close(sock_);
status_ = CLOSED;
invalidate_pending_futures();
}
status_ = CLOSED;
}
int Client::connect(const char* addr) {
string addr_str(addr);
size_t idx = addr_str.find(":");
if (idx == string::npos) {
Log::error("rpc::Client: bad connect address: %s", addr);
errno = EINVAL;
return -1;
}
string host = addr_str.substr(0, idx);
string port = addr_str.substr(idx + 1);
struct addrinfo hints, *result, *rp;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; // ipv4
hints.ai_socktype = SOCK_STREAM; // tcp
int r = getaddrinfo(host.c_str(), port.c_str(), &hints, &result);
if (r != 0) {
Log::error("rpc::Client: getaddrinfo(): %s", gai_strerror(r));
return -1;
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
sock_ = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock_ == -1) {
continue;
}
const int yes = 1;
verify(setsockopt(sock_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == 0);
verify(setsockopt(sock_, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == 0);
if (::connect(sock_, rp->ai_addr, rp->ai_addrlen) == 0) {
break;
}
::close(sock_);
sock_ = -1;
}
freeaddrinfo(result);
if (rp == NULL) {
// failed to connect
Log::error("rpc::Client: connect(): %s", strerror(errno));
return -1;
}
verify(set_nonblocking(sock_, true) == 0);
Log::info("rpc::Client: connected to %s", addr);
status_ = CONNECTED;
pollmgr_->add(this);
return 0;
}
void Client::handle_error() {
close();
}
void Client::handle_write() {
if (status_ != CONNECTED) {
return;
}
Pthread_mutex_lock(&out_m_);
out_.write_to_fd(sock_);
if (out_.empty()) {
pollmgr_->update_mode(this, Pollable::READ);
}
Pthread_mutex_unlock(&out_m_);
}
void Client::handle_read() {
if (status_ != CONNECTED) {
return;
}
int bytes_read = in_.read_from_fd(sock_);
if (bytes_read == 0) {
return;
}
for (;;) {
i32 packet_size;
int n_peek = in_.peek(&packet_size, sizeof(i32));
if (n_peek == sizeof(i32) && in_.content_size_gt(packet_size + sizeof(i32) - 1)) {
// consume the packet size
verify(in_.read(&packet_size, sizeof(i32)) == sizeof(i32));
i64 reply_xid;
i32 error_code;
in_ >> reply_xid >> error_code;
Pthread_mutex_lock(&pending_fu_m_);
map<i64, Future*>::iterator it = pending_fu_.find(reply_xid);
if (it != pending_fu_.end()) {
Future* fu = it->second;
verify(fu->xid_ == reply_xid);
pending_fu_.erase(it);
Pthread_mutex_unlock(&pending_fu_m_);
fu->error_code_ = error_code;
fu->reply_.read_from_marshal(in_, packet_size - sizeof(reply_xid) - sizeof(error_code));
fu->notify_ready();
// since we removed it from pending_fu_
fu->release();
}
} else {
// packet incomplete or no more packets to process
break;
}
}
}
int Client::poll_mode() {
int mode = Pollable::READ;
Pthread_mutex_lock(&out_m_);
if (!out_.empty()) {
mode |= Pollable::WRITE;
}
Pthread_mutex_unlock(&out_m_);
return mode;
}
Future* Client::begin_request(i32 rpc_id, const FutureAttr& attr /* =... */) {
Pthread_mutex_lock(&out_m_);
if (status_ != CONNECTED) {
if (attr.callback != NULL) {
delete attr.callback;
}
return NULL;
}
Future* fu = new Future(xid_counter_.next(), attr);
Pthread_mutex_lock(&pending_fu_m_);
pending_fu_[fu->xid_] = fu;
pending_fu_.size();
Pthread_mutex_unlock(&pending_fu_m_);
// check if the client gets closed in the meantime
if (status_ != CONNECTED) {
Pthread_mutex_lock(&pending_fu_m_);
map<i64, Future*>::iterator it = pending_fu_.find(fu->xid_);
if (it != pending_fu_.end()) {
it->second->release();
pending_fu_.erase(it);
}
Pthread_mutex_unlock(&pending_fu_m_);
return NULL;
}
bmark_ = out_.set_bookmark(sizeof(i32)); // will fill packet size later
*this << fu->xid_;
*this << rpc_id;
// one ref is already in pending_fu_
return (Future *) fu->ref_copy();
}
void Client::end_request() {
// set reply size in packet
if (bmark_ != NULL) {
i32 request_size = out_.get_write_counter_and_reset();
out_.write_bookmark(bmark_, &request_size);
delete bmark_;
bmark_ = NULL;
}
if (!out_.empty()) {
pollmgr_->update_mode(this, Pollable::READ | Pollable::WRITE);
}
Pthread_mutex_unlock(&out_m_);
}
ClientPool::ClientPool(PollMgr* pollmgr /* =? */) {
Pthread_mutex_init(&m_, NULL);
if (pollmgr == NULL) {
pollmgr_ = new PollMgr(1);
} else {
pollmgr_ = (PollMgr *) pollmgr->ref_copy();
}
}
ClientPool::~ClientPool() {
for (map<string, Client*>::iterator it = cache_.begin(); it != cache_.end(); ++it) {
it->second->close_and_release();
}
pollmgr_->release();
Pthread_mutex_destroy(&m_);
}
Client* ClientPool::get_client(const string& addr) {
Client* cl = NULL;
Pthread_mutex_lock(&m_);
map<string, Client*>::iterator it = cache_.find(addr);
if (it != cache_.end()) {
cl = it->second;
} else {
cl = new Client(this->pollmgr_);
if (cl->connect(addr.c_str()) != 0) {
// connect failure
cl->close_and_release();
cl = NULL;
} else {
// connect success
cache_.insert(make_pair(addr, cl));
}
}
Pthread_mutex_unlock(&m_);
return cl;
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include "IR.h"
/*
save mem
save reg
mem node sets
reg values
*/
void emit_int32_t(std::ofstream& f, int32_t data) {
f.write((char*)&data,sizeof(data));
}
void emit_int_set(std::ofstream& f, int_set_t& s) {
emit_int32_t(f, RES_INT_SET);
emit_int32_t(f, s.size());
for (auto& i: s) {
emit_int32_t(f, i);
}
}
void emit_node_item(std::ofstream& f, std::vector<int_set_t>& ni) {
emit_int32_t(f, RES_NODE_ITEM);
emit_int32_t(f, ni.size());
for (auto& i: ni) {
emit_int_set(f, i);
}
}
void emit_node_set(std::ofstream& f, node_set_t& ns) {
emit_int32_t(f, RES_NODE_SET);
emit_int32_t(f, ns.size());
for (auto& i: ns) {
emit_int32_t(f, i.first);
emit_node_item(f, i.second);
}
}
void emit_value(std::ofstream& f, value_t& v) {
emit_int32_t(f, RES_VALUE);
emit_int_set(f, v.simple_type);
emit_node_set(f, v.node_set);
}
void save_result(std::ofstream& f, int32_t iter_count, std::vector<node_set_t>& mem, std::vector<value_t>& reg) {
emit_int32_t(f, iter_count);
emit_int32_t(f, mem.size());
emit_int32_t(f, reg.size());
for (auto& i: mem) {
emit_node_set(f, i);
}
for (auto& i: reg) {
emit_value(f, i);
}
}
void save_result_file(const char* name, int32_t iter_count, std::vector<node_set_t>& mem, std::vector<value_t>& reg) {
//std::cout << "save result to: " << name << "\n";
std::ofstream fout(name, std::ios::out | std::ios::binary);
save_result(fout, iter_count, mem, reg);
fout.close();
}
<commit_msg>save node set values in key order<commit_after>#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include "IR.h"
/*
save mem
save reg
mem node sets
reg values
*/
void emit_int32_t(std::ofstream& f, int32_t data) {
f.write((char*)&data,sizeof(data));
}
void emit_int_set(std::ofstream& f, int_set_t& s) {
emit_int32_t(f, RES_INT_SET);
emit_int32_t(f, s.size());
for (auto& i: s) {
emit_int32_t(f, i);
}
}
void emit_node_item(std::ofstream& f, std::vector<int_set_t>& ni) {
emit_int32_t(f, RES_NODE_ITEM);
emit_int32_t(f, ni.size());
for (auto& i: ni) {
emit_int_set(f, i);
}
}
void emit_node_set(std::ofstream& f, node_set_t& ns) {
emit_int32_t(f, RES_NODE_SET);
emit_int32_t(f, ns.size());
// get sorted key vector
std::vector<int32_t> keys;
keys.reserve (ns.size());
for (auto& it : ns) {
keys.push_back(it.first);
}
std::sort (keys.begin(), keys.end());
// save items in sorted key order
for (auto& i: keys) {
emit_int32_t(f, i);
emit_node_item(f, ns[i]);
}
}
void emit_value(std::ofstream& f, value_t& v) {
emit_int32_t(f, RES_VALUE);
emit_int_set(f, v.simple_type);
emit_node_set(f, v.node_set);
}
void save_result(std::ofstream& f, int32_t iter_count, std::vector<node_set_t>& mem, std::vector<value_t>& reg) {
emit_int32_t(f, iter_count);
emit_int32_t(f, mem.size());
emit_int32_t(f, reg.size());
for (auto& i: mem) {
emit_node_set(f, i);
}
for (auto& i: reg) {
emit_value(f, i);
}
}
void save_result_file(const char* name, int32_t iter_count, std::vector<node_set_t>& mem, std::vector<value_t>& reg) {
//std::cout << "save result to: " << name << "\n";
std::ofstream fout(name, std::ios::out | std::ios::binary);
save_result(fout, iter_count, mem, reg);
fout.close();
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <deque>
#include <thread>
#include <string.h>
#include <curl/curl.h>
#include <evcollect/evcollect.h>
#include <evcollect/util/logging.h>
#include <evcollect/util/base64.h>
#include <evcollect/util/time.h>
#include <evcollect/util/return_code.h>
namespace evcollect {
namespace plugin_eventql {
class EventQLTarget {
public:
static const size_t kDefaultHTTPTimeoutMicros = 30 * kMicrosPerSecond;
static const size_t kDefaultMaxQueueLength = 8192;
EventQLTarget(
const std::string& hostname,
uint16_t port);
~EventQLTarget();
void addRoute(
const std::string& event_name_match,
const std::string& target);
void setHTTPTimeout(uint64_t usecs);
void setMaxQueueLength(size_t queue_len);
void setAuthToken(const std::string& auth_token);
void setCredentials(
const std::string& username,
const std::string& password);
ReturnCode emitEvent(const EventData& event);
ReturnCode startUploadThread();
void stopUploadThread();
protected:
struct TargetTable {
std::string database;
std::string table;
};
struct EnqueuedEvent {
std::string database;
std::string table;
std::string data;
};
struct EventRouting {
std::string event_name_match;
std::string target;
};
ReturnCode enqueueEvent(const EnqueuedEvent& event);
bool awaitEvent(EnqueuedEvent* event);
ReturnCode uploadEvent(const EnqueuedEvent& event);
std::string hostname_;
uint16_t port_;
std::string username_;
std::string password_;
std::string auth_token_;
std::deque<EnqueuedEvent> queue_;
mutable std::mutex mutex_;
mutable std::condition_variable cv_;
size_t queue_max_length_;
std::thread thread_;
bool thread_running_;
bool thread_shutdown_;
std::vector<EventRouting> routes_;
CURL* curl_;
uint64_t http_timeout_;
};
EventQLTarget::EventQLTarget(
const std::string& hostname,
uint16_t port) :
hostname_(hostname),
port_(port),
queue_max_length_(kDefaultMaxQueueLength),
thread_running_(false),
curl_(nullptr),
http_timeout_(kDefaultHTTPTimeoutMicros) {
curl_ = curl_easy_init();
}
EventQLTarget::~EventQLTarget() {
if (curl_) {
curl_easy_cleanup(curl_);
}
}
void EventQLTarget::addRoute(
const std::string& event_name_match,
const std::string& target) {
EventRouting r;
r.event_name_match = event_name_match;
r.target = target;
routes_.emplace_back(r);
}
void EventQLTarget::setAuthToken(const std::string& auth_token) {
auth_token_ = auth_token;
}
void EventQLTarget::setCredentials(
const std::string& username,
const std::string& password) {
username_ = username;
password_ = password;
}
void EventQLTarget::setHTTPTimeout(uint64_t usecs) {
http_timeout_ = usecs;
}
void EventQLTarget::setMaxQueueLength(size_t queue_len) {
queue_max_length_ = queue_len;
}
ReturnCode EventQLTarget::emitEvent(const EventData& event) {
for (const auto& route : routes_) {
if (route.event_name_match != event.event_name) {
continue;
}
auto target = StringUtil::split(route.target, "/");
if (target.size() != 2) {
return ReturnCode::error(
"EINVAL",
"invalid target specification. " \
"format is: database/table");
}
EnqueuedEvent e;
e.database = target[0];
e.table = target[1];
e.data = event.event_data;
auto rc = enqueueEvent(e);
if (!rc.isSuccess()) {
return rc;
}
}
return ReturnCode::success();
}
ReturnCode EventQLTarget::enqueueEvent(const EnqueuedEvent& event) {
std::unique_lock<std::mutex> lk(mutex_);
while (queue_.size() >= queue_max_length_) {
cv_.wait(lk);
}
queue_.emplace_back(event);
cv_.notify_all();
return ReturnCode::success();
}
bool EventQLTarget::awaitEvent(EnqueuedEvent* event) {
std::unique_lock<std::mutex> lk(mutex_);
if (queue_.size() == 0) {
cv_.wait(lk);
}
if (queue_.size() == 0) {
return false;
} else {
*event = queue_.front();
queue_.pop_front();
cv_.notify_all();
return true;
}
}
ReturnCode EventQLTarget::startUploadThread() {
if (thread_running_) {
return ReturnCode::error("RTERROR", "upload thread is already running");
}
auto upload_thread = [this] () {
while (true) {
{
std::unique_lock<std::mutex> lk(mutex_);
if (thread_shutdown_) {
return;
}
}
EnqueuedEvent ev;
if (!awaitEvent(&ev)) {
continue;
}
auto rc = uploadEvent(ev);
if (!rc.isSuccess()) {
logError(
"error while uploading event to $0/$1: $2",
ev.database,
ev.table,
rc.getMessage());
}
}
};
std::unique_lock<std::mutex> lk(mutex_);
thread_running_ = true;
thread_shutdown_ = false;
thread_ = std::thread(upload_thread);
return ReturnCode::success();
}
void EventQLTarget::stopUploadThread() {
if (!thread_running_) {
return;
}
thread_shutdown_ = true;
cv_.notify_all();
thread_.join();
thread_running_ = false;
}
namespace {
size_t curl_write_cb(void* data, size_t size, size_t nmemb, std::string* s) {
size_t pos = s->size();
size_t len = pos + size * nmemb;
s->resize(len);
memcpy((char*) s->data() + pos, data, size * nmemb);
return size * nmemb;
}
}
ReturnCode EventQLTarget::uploadEvent(const EnqueuedEvent& ev) {
auto url = StringUtil::format(
"http://$0:$1/api/v1/tables/insert",
hostname_,
port_);
std::string body;
body += "[{ ";
body += StringUtil::format(
"\"database\": \"$0\",",
StringUtil::jsonEscape(ev.database));
body += StringUtil::format(
"\"table\": \"$0\"",
StringUtil::jsonEscape(ev.table));
body += "\"data\":" + ev.data;
body += "}]";
if (!curl_) {
return ReturnCode::error("EIO", "curl_init() failed");
}
struct curl_slist* req_headers = NULL;
req_headers = curl_slist_append(
req_headers,
"Content-Type: application/json; charset=utf-8");
if (!auth_token_.empty()) {
auto hdr = "Authorization: Token " + auth_token_;
req_headers = curl_slist_append(req_headers, hdr.c_str());
}
if (!username_.empty() || !password_.empty()) {
std::string hdr = "Authorization: Basic ";
hdr += Base64::encode(username_ + ":" + password_);
req_headers = curl_slist_append(req_headers, hdr.c_str());
}
std::string res_body;
curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_, CURLOPT_TIMEOUT_MS, http_timeout_ / kMicrosPerMilli);
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curl_write_cb);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &res_body);
CURLcode curl_res = curl_easy_perform(curl_);
curl_slist_free_all(req_headers);
if (curl_res != CURLE_OK) {
return ReturnCode::error(
"EIO",
"http request failed: %s",
curl_easy_strerror(curl_res));
}
long http_res_code = 0;
curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &http_res_code);
switch (http_res_code) {
case 201:
return ReturnCode::success();
case 400:
return ReturnCode::error(
"EINVAL",
"http error: %li -- %.*s",
http_res_code,
res_body.size(),
res_body.data());
case 403:
case 401:
return ReturnCode::error(
"EACCESS",
"auth error: %li -- %.*s",
http_res_code,
res_body.size(),
res_body.data());
default:
return ReturnCode::error(
"EIO",
"http error: %li -- %.*s",
http_res_code,
res_body.size(),
res_body.data());
}
}
bool pluginAttach(
evcollect_ctx_t* ctx,
evcollect_plugin_cfg_t* cfg,
void** userdata) {
}
bool pluginEmitEvent(
evcollect_ctx_t* ctx,
void* userdata,
const evcollect_event_t* event) {
}
//ReturnCode EventQLPlugin::pluginAttach(
// const PropertyList& config,
// void** userdata) {
// std::string hostname = "localhost";
// uint16_t port = 9175;
//
// std::string hostname_opt;
// if (config.get("port", &hostname_opt)) {
// hostname = hostname_opt;
// }
//
// std::string port_opt;
// if (config.get("port", &port_opt)) {
// try {
// port = std::stoul(port_opt);
// } catch (...) {
// return ReturnCode::error("EINVAL", "invalid port");
// }
// }
//
// std::unique_ptr<EventQLTarget> target(new EventQLTarget(hostname, port));
//
// std::string username;
// std::string password;
// config.get("username", &username);
// config.get("password", &password);
// if (!username.empty() || !password.empty()) {
// target->setCredentials(username, password);
// }
//
// std::string auth_token;
// if (config.get("auth_token", &auth_token)) {
// target->setAuthToken(auth_token);
// }
//
// std::string http_timeout_opt;
// if (config.get("http_timeout", &http_timeout_opt)) {
// uint64_t http_timeout;
// try {
// http_timeout = std::stoull(http_timeout_opt);
// } catch (...) {
// return ReturnCode::error("EINVAL", "invalid value for http_timeout");
// }
// target->setHTTPTimeout(http_timeout);
// }
//
// std::string queue_maxlen_opt;
// if (config.get("queue_maxlen", &queue_maxlen_opt)) {
// uint64_t queue_maxlen;
// try {
// queue_maxlen = std::stoull(queue_maxlen_opt);
// } catch (...) {
// return ReturnCode::error("EINVAL", "invalid value for queue_maxlen");
// }
// target->setMaxQueueLength(queue_maxlen);
// }
//
// std::vector<std::vector<std::string>> route_cfg;
// config.get("route", &route_cfg);
// for (const auto& route : route_cfg) {
// if (route.size() != 2) {
// return ReturnCode::error(
// "EINVAL",
// "invalid number of arguments to route. " \
// "format is: route <event> <target>");
// }
//
// target->addRoute(route[0], route[1]);
// }
//
// target->startUploadThread();
// *userdata = target.release();
// return ReturnCode::success();
//}
//
//void EventQLPlugin::pluginDetach(void* userdata) {
// auto target = static_cast<EventQLTarget*>(userdata);
// target->stopUploadThread();
// delete target;
//}
//
//ReturnCode EventQLPlugin::pluginEmitEvent(
// void* userdata,
// const EventData& evdata) {
// auto target = static_cast<EventQLTarget*>(userdata);
// return target->emitEvent(evdata);
//}
} // namespace plugins_eventql
} // namespace evcollect
bool __evcollect_plugin_init(evcollect_ctx_t* ctx) {
evcollect_output_plugin_register(
ctx,
"output",
&evcollect::plugin_eventql::pluginEmitEvent);
return true;
}
<commit_msg>fixes compile error<commit_after>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <deque>
#include <thread>
#include <condition_variable>
#include <string.h>
#include <curl/curl.h>
#include <evcollect/evcollect.h>
#include <evcollect/util/logging.h>
#include <evcollect/util/base64.h>
#include <evcollect/util/time.h>
#include <evcollect/util/return_code.h>
namespace evcollect {
namespace plugin_eventql {
class EventQLTarget {
public:
static const size_t kDefaultHTTPTimeoutMicros = 30 * kMicrosPerSecond;
static const size_t kDefaultMaxQueueLength = 8192;
EventQLTarget(
const std::string& hostname,
uint16_t port);
~EventQLTarget();
void addRoute(
const std::string& event_name_match,
const std::string& target);
void setHTTPTimeout(uint64_t usecs);
void setMaxQueueLength(size_t queue_len);
void setAuthToken(const std::string& auth_token);
void setCredentials(
const std::string& username,
const std::string& password);
ReturnCode emitEvent(const EventData& event);
ReturnCode startUploadThread();
void stopUploadThread();
protected:
struct TargetTable {
std::string database;
std::string table;
};
struct EnqueuedEvent {
std::string database;
std::string table;
std::string data;
};
struct EventRouting {
std::string event_name_match;
std::string target;
};
ReturnCode enqueueEvent(const EnqueuedEvent& event);
bool awaitEvent(EnqueuedEvent* event);
ReturnCode uploadEvent(const EnqueuedEvent& event);
std::string hostname_;
uint16_t port_;
std::string username_;
std::string password_;
std::string auth_token_;
std::deque<EnqueuedEvent> queue_;
mutable std::mutex mutex_;
mutable std::condition_variable cv_;
size_t queue_max_length_;
std::thread thread_;
bool thread_running_;
bool thread_shutdown_;
std::vector<EventRouting> routes_;
CURL* curl_;
uint64_t http_timeout_;
};
EventQLTarget::EventQLTarget(
const std::string& hostname,
uint16_t port) :
hostname_(hostname),
port_(port),
queue_max_length_(kDefaultMaxQueueLength),
thread_running_(false),
curl_(nullptr),
http_timeout_(kDefaultHTTPTimeoutMicros) {
curl_ = curl_easy_init();
}
EventQLTarget::~EventQLTarget() {
if (curl_) {
curl_easy_cleanup(curl_);
}
}
void EventQLTarget::addRoute(
const std::string& event_name_match,
const std::string& target) {
EventRouting r;
r.event_name_match = event_name_match;
r.target = target;
routes_.emplace_back(r);
}
void EventQLTarget::setAuthToken(const std::string& auth_token) {
auth_token_ = auth_token;
}
void EventQLTarget::setCredentials(
const std::string& username,
const std::string& password) {
username_ = username;
password_ = password;
}
void EventQLTarget::setHTTPTimeout(uint64_t usecs) {
http_timeout_ = usecs;
}
void EventQLTarget::setMaxQueueLength(size_t queue_len) {
queue_max_length_ = queue_len;
}
ReturnCode EventQLTarget::emitEvent(const EventData& event) {
for (const auto& route : routes_) {
if (route.event_name_match != event.event_name) {
continue;
}
auto target = StringUtil::split(route.target, "/");
if (target.size() != 2) {
return ReturnCode::error(
"EINVAL",
"invalid target specification. " \
"format is: database/table");
}
EnqueuedEvent e;
e.database = target[0];
e.table = target[1];
e.data = event.event_data;
auto rc = enqueueEvent(e);
if (!rc.isSuccess()) {
return rc;
}
}
return ReturnCode::success();
}
ReturnCode EventQLTarget::enqueueEvent(const EnqueuedEvent& event) {
std::unique_lock<std::mutex> lk(mutex_);
while (queue_.size() >= queue_max_length_) {
cv_.wait(lk);
}
queue_.emplace_back(event);
cv_.notify_all();
return ReturnCode::success();
}
bool EventQLTarget::awaitEvent(EnqueuedEvent* event) {
std::unique_lock<std::mutex> lk(mutex_);
if (queue_.size() == 0) {
cv_.wait(lk);
}
if (queue_.size() == 0) {
return false;
} else {
*event = queue_.front();
queue_.pop_front();
cv_.notify_all();
return true;
}
}
ReturnCode EventQLTarget::startUploadThread() {
if (thread_running_) {
return ReturnCode::error("RTERROR", "upload thread is already running");
}
auto upload_thread = [this] () {
while (true) {
{
std::unique_lock<std::mutex> lk(mutex_);
if (thread_shutdown_) {
return;
}
}
EnqueuedEvent ev;
if (!awaitEvent(&ev)) {
continue;
}
auto rc = uploadEvent(ev);
if (!rc.isSuccess()) {
logError(
"error while uploading event to $0/$1: $2",
ev.database,
ev.table,
rc.getMessage());
}
}
};
std::unique_lock<std::mutex> lk(mutex_);
thread_running_ = true;
thread_shutdown_ = false;
thread_ = std::thread(upload_thread);
return ReturnCode::success();
}
void EventQLTarget::stopUploadThread() {
if (!thread_running_) {
return;
}
thread_shutdown_ = true;
cv_.notify_all();
thread_.join();
thread_running_ = false;
}
namespace {
size_t curl_write_cb(void* data, size_t size, size_t nmemb, std::string* s) {
size_t pos = s->size();
size_t len = pos + size * nmemb;
s->resize(len);
memcpy((char*) s->data() + pos, data, size * nmemb);
return size * nmemb;
}
}
ReturnCode EventQLTarget::uploadEvent(const EnqueuedEvent& ev) {
auto url = StringUtil::format(
"http://$0:$1/api/v1/tables/insert",
hostname_,
port_);
std::string body;
body += "[{ ";
body += StringUtil::format(
"\"database\": \"$0\",",
StringUtil::jsonEscape(ev.database));
body += StringUtil::format(
"\"table\": \"$0\"",
StringUtil::jsonEscape(ev.table));
body += "\"data\":" + ev.data;
body += "}]";
if (!curl_) {
return ReturnCode::error("EIO", "curl_init() failed");
}
struct curl_slist* req_headers = NULL;
req_headers = curl_slist_append(
req_headers,
"Content-Type: application/json; charset=utf-8");
if (!auth_token_.empty()) {
auto hdr = "Authorization: Token " + auth_token_;
req_headers = curl_slist_append(req_headers, hdr.c_str());
}
if (!username_.empty() || !password_.empty()) {
std::string hdr = "Authorization: Basic ";
hdr += Base64::encode(username_ + ":" + password_);
req_headers = curl_slist_append(req_headers, hdr.c_str());
}
std::string res_body;
curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_, CURLOPT_TIMEOUT_MS, http_timeout_ / kMicrosPerMilli);
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curl_write_cb);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &res_body);
CURLcode curl_res = curl_easy_perform(curl_);
curl_slist_free_all(req_headers);
if (curl_res != CURLE_OK) {
return ReturnCode::error(
"EIO",
"http request failed: %s",
curl_easy_strerror(curl_res));
}
long http_res_code = 0;
curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &http_res_code);
switch (http_res_code) {
case 201:
return ReturnCode::success();
case 400:
return ReturnCode::error(
"EINVAL",
"http error: %li -- %.*s",
http_res_code,
res_body.size(),
res_body.data());
case 403:
case 401:
return ReturnCode::error(
"EACCESS",
"auth error: %li -- %.*s",
http_res_code,
res_body.size(),
res_body.data());
default:
return ReturnCode::error(
"EIO",
"http error: %li -- %.*s",
http_res_code,
res_body.size(),
res_body.data());
}
}
bool pluginAttach(
evcollect_ctx_t* ctx,
evcollect_plugin_cfg_t* cfg,
void** userdata) {
}
bool pluginEmitEvent(
evcollect_ctx_t* ctx,
void* userdata,
const evcollect_event_t* event) {
}
//ReturnCode EventQLPlugin::pluginAttach(
// const PropertyList& config,
// void** userdata) {
// std::string hostname = "localhost";
// uint16_t port = 9175;
//
// std::string hostname_opt;
// if (config.get("port", &hostname_opt)) {
// hostname = hostname_opt;
// }
//
// std::string port_opt;
// if (config.get("port", &port_opt)) {
// try {
// port = std::stoul(port_opt);
// } catch (...) {
// return ReturnCode::error("EINVAL", "invalid port");
// }
// }
//
// std::unique_ptr<EventQLTarget> target(new EventQLTarget(hostname, port));
//
// std::string username;
// std::string password;
// config.get("username", &username);
// config.get("password", &password);
// if (!username.empty() || !password.empty()) {
// target->setCredentials(username, password);
// }
//
// std::string auth_token;
// if (config.get("auth_token", &auth_token)) {
// target->setAuthToken(auth_token);
// }
//
// std::string http_timeout_opt;
// if (config.get("http_timeout", &http_timeout_opt)) {
// uint64_t http_timeout;
// try {
// http_timeout = std::stoull(http_timeout_opt);
// } catch (...) {
// return ReturnCode::error("EINVAL", "invalid value for http_timeout");
// }
// target->setHTTPTimeout(http_timeout);
// }
//
// std::string queue_maxlen_opt;
// if (config.get("queue_maxlen", &queue_maxlen_opt)) {
// uint64_t queue_maxlen;
// try {
// queue_maxlen = std::stoull(queue_maxlen_opt);
// } catch (...) {
// return ReturnCode::error("EINVAL", "invalid value for queue_maxlen");
// }
// target->setMaxQueueLength(queue_maxlen);
// }
//
// std::vector<std::vector<std::string>> route_cfg;
// config.get("route", &route_cfg);
// for (const auto& route : route_cfg) {
// if (route.size() != 2) {
// return ReturnCode::error(
// "EINVAL",
// "invalid number of arguments to route. " \
// "format is: route <event> <target>");
// }
//
// target->addRoute(route[0], route[1]);
// }
//
// target->startUploadThread();
// *userdata = target.release();
// return ReturnCode::success();
//}
//
//void EventQLPlugin::pluginDetach(void* userdata) {
// auto target = static_cast<EventQLTarget*>(userdata);
// target->stopUploadThread();
// delete target;
//}
//
//ReturnCode EventQLPlugin::pluginEmitEvent(
// void* userdata,
// const EventData& evdata) {
// auto target = static_cast<EventQLTarget*>(userdata);
// return target->emitEvent(evdata);
//}
} // namespace plugins_eventql
} // namespace evcollect
bool __evcollect_plugin_init(evcollect_ctx_t* ctx) {
evcollect_output_plugin_register(
ctx,
"output",
&evcollect::plugin_eventql::pluginEmitEvent);
return true;
}
<|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: postgis.cc 44 2005-04-22 18:53:54Z pavlenko $
#include <string>
#include <algorithm>
#include <set>
#include <sstream>
#include <iomanip>
#include <boost/lexical_cast.hpp>
#include "connection_manager.hpp"
#include "postgis.hpp"
DATASOURCE_PLUGIN(postgis_datasource)
const std::string postgis_datasource::GEOMETRY_COLUMNS="geometry_columns";
const std::string postgis_datasource::SPATIAL_REF_SYS="spatial_ref_system";
using std::clog;
using std::endl;
using boost::lexical_cast;
using boost::bad_lexical_cast;
using boost::shared_ptr;
postgis_datasource::postgis_datasource(parameters const& params)
: datasource (params),
table_(params.get("table")),
type_(datasource::Vector),
extent_initialized_(false),
desc_(params.get("type")),
creator_(params.get("host"),
params.get("port"),
params.get("dbname"),
params.get("user"),
params.get("password"))
{
unsigned initial_size;
unsigned max_size;
try
{
initial_size = boost::lexical_cast<unsigned>(params_.get("initial_size"));
}
catch (bad_lexical_cast& )
{
initial_size = 1;
}
try
{
max_size = boost::lexical_cast<unsigned>(params_.get("max_size"));
}
catch (bad_lexical_cast&)
{
max_size = 10;
}
ConnectionManager *mgr=ConnectionManager::instance();
mgr->registerPool(creator_, initial_size, max_size);
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::string table_name=table_from_sql(table_);
std::ostringstream s;
s << "select f_geometry_column,srid,type from ";
s << GEOMETRY_COLUMNS <<" where f_table_name='" << table_name<<"'";
shared_ptr<ResultSet> rs=conn->executeQuery(s.str());
if (rs->next())
{
try
{
srid_ = lexical_cast<int>(rs->getValue("srid"));
desc_.set_srid(srid_);
}
catch (bad_lexical_cast &ex)
{
clog << ex.what() << endl;
}
geometryColumn_=rs->getValue("f_geometry_column");
std::string postgisType=rs->getValue("type");
}
rs->close();
// collect attribute desc
s.str("");
s << "select * from "<<table_<<" limit 1";
rs=conn->executeQuery(s.str());
if (rs->next())
{
int count = rs->getNumFields();
for (int i=0;i<count;++i)
{
std::string fld_name=rs->getFieldName(i);
int length = rs->getFieldLength(i);
int type_oid = rs->getTypeOID(i);
switch (type_oid)
{
case 21: // int2
case 23: // int4
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer,false,length));
break;
case 700: // float4
case 701: // float8
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double,false,length));
case 1042: // bpchar
case 1043: // varchar
case 25: // text
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
break;
default: // shouldn't get here
#ifdef MAPNIK_DEBUG
clog << "unknown type_oid="<<type_oid<<endl;
#endif
break;
}
}
}
}
}
}
std::string const postgis_datasource::name_="postgis";
std::string postgis_datasource::name()
{
return name_;
}
int postgis_datasource::type() const
{
return type_;
}
layer_descriptor postgis_datasource::get_descriptor() const
{
return desc_;
}
std::string postgis_datasource::table_from_sql(const std::string& sql)
{
std::string table_name(sql);
transform(table_name.begin(),table_name.end(),table_name.begin(),tolower);
std::string::size_type idx=table_name.rfind("from");
if (idx!=std::string::npos)
{
idx=table_name.find_first_not_of(" ",idx+4);
table_name=table_name.substr(idx);
idx=table_name.find_first_of(" )");
return table_name.substr(0,idx);
}
return table_name;
}
featureset_ptr postgis_datasource::features(const query& q) const
{
Envelope<double> const& box=q.get_bbox();
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::ostringstream s;
s << "select asbinary("<<geometryColumn_<<") as geom";
std::set<std::string> const& props=q.property_names();
std::set<std::string>::const_iterator pos=props.begin();
std::set<std::string>::const_iterator end=props.end();
while (pos != end)
{
s <<",\""<<*pos<<"\"";
++pos;
}
s << " from " << table_<<" where "<<geometryColumn_<<" && setSRID('BOX3D(";
s << std::setprecision(16);
s << box.minx() << " " << box.miny() << ",";
s << box.maxx() << " " << box.maxy() << ")'::box3d,"<<srid_<<")";
#ifdef MAPNIK_DEBUG
std::clog << s.str() << "\n";
#endif
shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);
return featureset_ptr(new postgis_featureset(rs,props.size()));
}
}
return featureset_ptr();
}
featureset_ptr postgis_datasource::features_at_point(coord2d const& pt) const
{
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::ostringstream s;
s << "select asbinary(" << geometryColumn_ << ") as geom";
std::vector<attribute_descriptor>::const_iterator itr = desc_.get_descriptors().begin();
std::vector<attribute_descriptor>::const_iterator end = desc_.get_descriptors().end();
unsigned size=0;
while (itr != end)
{
s <<",\""<< itr->get_name() << "\"";
++itr;
++size;
}
s << " from " << table_<<" where "<<geometryColumn_<<" && setSRID('BOX3D(";
s << std::setprecision(16);
s << pt.x << " " << pt.y << ",";
s << pt.x << " " << pt.y << ")'::box3d,"<<srid_<<")";
#ifdef MAPNIK_DEBUG
std::clog << s.str() << "\n";
#endif
shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);
return featureset_ptr(new postgis_featureset(rs, size));
}
}
return featureset_ptr();
}
Envelope<double> postgis_datasource::envelope() const
{
if (extent_initialized_) return extent_;
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
std::ostringstream s;
std::string table_name = table_from_sql(table_);
if (params_.get("estimate_extent") == "true")
{
s << "select xmin(ext),ymin(ext),xmax(ext),ymax(ext)"
<< " from (select estimated_extent('"
<< table_name <<"','"
<< geometryColumn_ << "') as ext) as tmp";
}
else
{
s << "select xmin(ext),ymin(ext),xmax(ext),ymax(ext)"
<< " from (select extent(" <<geometryColumn_<< ") as ext from "
<< table_name << ") as tmp";
}
shared_ptr<ResultSet> rs=conn->executeQuery(s.str());
if (rs->next())
{
try
{
double lox=lexical_cast<double>(rs->getValue(0));
double loy=lexical_cast<double>(rs->getValue(1));
double hix=lexical_cast<double>(rs->getValue(2));
double hiy=lexical_cast<double>(rs->getValue(3));
extent_.init(lox,loy,hix,hiy);
extent_initialized_ = true;
}
catch (bad_lexical_cast &ex)
{
clog << ex.what() << endl;
}
}
rs->close();
}
}
return extent_;
}
postgis_datasource::~postgis_datasource() {}
<commit_msg>append namespace to 'transform' to support buiding with STLport.<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: postgis.cc 44 2005-04-22 18:53:54Z pavlenko $
#include <string>
#include <algorithm>
#include <set>
#include <sstream>
#include <iomanip>
#include <boost/lexical_cast.hpp>
#include "connection_manager.hpp"
#include "postgis.hpp"
DATASOURCE_PLUGIN(postgis_datasource)
const std::string postgis_datasource::GEOMETRY_COLUMNS="geometry_columns";
const std::string postgis_datasource::SPATIAL_REF_SYS="spatial_ref_system";
using std::clog;
using std::endl;
using boost::lexical_cast;
using boost::bad_lexical_cast;
using boost::shared_ptr;
postgis_datasource::postgis_datasource(parameters const& params)
: datasource (params),
table_(params.get("table")),
type_(datasource::Vector),
extent_initialized_(false),
desc_(params.get("type")),
creator_(params.get("host"),
params.get("port"),
params.get("dbname"),
params.get("user"),
params.get("password"))
{
unsigned initial_size;
unsigned max_size;
try
{
initial_size = boost::lexical_cast<unsigned>(params_.get("initial_size"));
}
catch (bad_lexical_cast& )
{
initial_size = 1;
}
try
{
max_size = boost::lexical_cast<unsigned>(params_.get("max_size"));
}
catch (bad_lexical_cast&)
{
max_size = 10;
}
ConnectionManager *mgr=ConnectionManager::instance();
mgr->registerPool(creator_, initial_size, max_size);
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::string table_name=table_from_sql(table_);
std::ostringstream s;
s << "select f_geometry_column,srid,type from ";
s << GEOMETRY_COLUMNS <<" where f_table_name='" << table_name<<"'";
shared_ptr<ResultSet> rs=conn->executeQuery(s.str());
if (rs->next())
{
try
{
srid_ = lexical_cast<int>(rs->getValue("srid"));
desc_.set_srid(srid_);
}
catch (bad_lexical_cast &ex)
{
clog << ex.what() << endl;
}
geometryColumn_=rs->getValue("f_geometry_column");
std::string postgisType=rs->getValue("type");
}
rs->close();
// collect attribute desc
s.str("");
s << "select * from "<<table_<<" limit 1";
rs=conn->executeQuery(s.str());
if (rs->next())
{
int count = rs->getNumFields();
for (int i=0;i<count;++i)
{
std::string fld_name=rs->getFieldName(i);
int length = rs->getFieldLength(i);
int type_oid = rs->getTypeOID(i);
switch (type_oid)
{
case 21: // int2
case 23: // int4
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer,false,length));
break;
case 700: // float4
case 701: // float8
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double,false,length));
case 1042: // bpchar
case 1043: // varchar
case 25: // text
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
break;
default: // shouldn't get here
#ifdef MAPNIK_DEBUG
clog << "unknown type_oid="<<type_oid<<endl;
#endif
break;
}
}
}
}
}
}
std::string const postgis_datasource::name_="postgis";
std::string postgis_datasource::name()
{
return name_;
}
int postgis_datasource::type() const
{
return type_;
}
layer_descriptor postgis_datasource::get_descriptor() const
{
return desc_;
}
std::string postgis_datasource::table_from_sql(const std::string& sql)
{
std::string table_name(sql);
std::transform(table_name.begin(),table_name.end(),table_name.begin(),tolower);
std::string::size_type idx=table_name.rfind("from");
if (idx!=std::string::npos)
{
idx=table_name.find_first_not_of(" ",idx+4);
table_name=table_name.substr(idx);
idx=table_name.find_first_of(" )");
return table_name.substr(0,idx);
}
return table_name;
}
featureset_ptr postgis_datasource::features(const query& q) const
{
Envelope<double> const& box=q.get_bbox();
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::ostringstream s;
s << "select asbinary("<<geometryColumn_<<") as geom";
std::set<std::string> const& props=q.property_names();
std::set<std::string>::const_iterator pos=props.begin();
std::set<std::string>::const_iterator end=props.end();
while (pos != end)
{
s <<",\""<<*pos<<"\"";
++pos;
}
s << " from " << table_<<" where "<<geometryColumn_<<" && setSRID('BOX3D(";
s << std::setprecision(16);
s << box.minx() << " " << box.miny() << ",";
s << box.maxx() << " " << box.maxy() << ")'::box3d,"<<srid_<<")";
#ifdef MAPNIK_DEBUG
std::clog << s.str() << "\n";
#endif
shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);
return featureset_ptr(new postgis_featureset(rs,props.size()));
}
}
return featureset_ptr();
}
featureset_ptr postgis_datasource::features_at_point(coord2d const& pt) const
{
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::ostringstream s;
s << "select asbinary(" << geometryColumn_ << ") as geom";
std::vector<attribute_descriptor>::const_iterator itr = desc_.get_descriptors().begin();
std::vector<attribute_descriptor>::const_iterator end = desc_.get_descriptors().end();
unsigned size=0;
while (itr != end)
{
s <<",\""<< itr->get_name() << "\"";
++itr;
++size;
}
s << " from " << table_<<" where "<<geometryColumn_<<" && setSRID('BOX3D(";
s << std::setprecision(16);
s << pt.x << " " << pt.y << ",";
s << pt.x << " " << pt.y << ")'::box3d,"<<srid_<<")";
#ifdef MAPNIK_DEBUG
std::clog << s.str() << "\n";
#endif
shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);
return featureset_ptr(new postgis_featureset(rs, size));
}
}
return featureset_ptr();
}
Envelope<double> postgis_datasource::envelope() const
{
if (extent_initialized_) return extent_;
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
std::ostringstream s;
std::string table_name = table_from_sql(table_);
if (params_.get("estimate_extent") == "true")
{
s << "select xmin(ext),ymin(ext),xmax(ext),ymax(ext)"
<< " from (select estimated_extent('"
<< table_name <<"','"
<< geometryColumn_ << "') as ext) as tmp";
}
else
{
s << "select xmin(ext),ymin(ext),xmax(ext),ymax(ext)"
<< " from (select extent(" <<geometryColumn_<< ") as ext from "
<< table_name << ") as tmp";
}
shared_ptr<ResultSet> rs=conn->executeQuery(s.str());
if (rs->next())
{
try
{
double lox=lexical_cast<double>(rs->getValue(0));
double loy=lexical_cast<double>(rs->getValue(1));
double hix=lexical_cast<double>(rs->getValue(2));
double hiy=lexical_cast<double>(rs->getValue(3));
extent_.init(lox,loy,hix,hiy);
extent_initialized_ = true;
}
catch (bad_lexical_cast &ex)
{
clog << ex.what() << endl;
}
}
rs->close();
}
}
return extent_;
}
postgis_datasource::~postgis_datasource() {}
<|endoftext|>
|
<commit_before>/**
* A class which is responsible for storing words or phrases in a efficient
* way. These vocabularies can be used for several NLP applications.
*
* @date 1 April, 2015
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2015 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include "../../ml/nlp/vocabulary.h"
#include <algorithm>
#include <cassert>
// Application dependencies.
// END Includes. /////////////////////////////////////////////////////
void Vocabulary::add( const std::string & entity ) {
// Checking the preconditions.
assert( !entity.empty() && !contains(entity) );
mStorage.push_back(entity);
}
bool Vocabulary::contains( const std::string & entity ) const {
return ( std::find(mStorage.begin(),mStorage.end(),entity)
!= mStorage.end() );
}
std::size_t Vocabulary::get( const std::string & entity ) const {
std::vector<std::string>::const_iterator it;
std::size_t index;
it = std::find(mStorage.begin(),mStorage.end(),entity);
index = std::distance(mStorage.begin(),it);
return ( index );
}
std::size_t Vocabulary::size( void ) const {
return ( mStorage.size() );
}
<commit_msg>Fix vocabulary includes.<commit_after>/**
* A class which is responsible for storing words or phrases in a efficient
* way. These vocabularies can be used for several NLP applications.
*
* @date 1 April, 2015
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2015 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <algorithm>
#include <cassert>
// Application dependencies.
#include <ias/ml/nlp/vocabulary.h>
// END Includes. /////////////////////////////////////////////////////
void Vocabulary::add( const std::string & entity ) {
// Checking the preconditions.
assert( !entity.empty() && !contains(entity) );
mStorage.push_back(entity);
}
bool Vocabulary::contains( const std::string & entity ) const {
return ( std::find(mStorage.begin(),mStorage.end(),entity)
!= mStorage.end() );
}
std::size_t Vocabulary::get( const std::string & entity ) const {
std::vector<std::string>::const_iterator it;
std::size_t index;
it = std::find(mStorage.begin(),mStorage.end(),entity);
index = std::distance(mStorage.begin(),it);
return ( index );
}
std::size_t Vocabulary::size( void ) const {
return ( mStorage.size() );
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <hash.h>
#include <uint256.h>
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
/** All alphanumeric characters except for "0", "I", "O", and "l" */
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
int length = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
int size = strlen(psz) * 733 /1000 + 1; // log(58) / log(256), rounded up.
std::vector<unsigned char> b256(size);
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == nullptr)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
int i = 0;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); (carry != 0 || i < length) && (it != b256.rend()); ++it, ++i) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
length = i;
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin() + (size - length);
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
int length = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up.
std::vector<unsigned char> b58(size);
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
int i = 0;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin() + (size - length);
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(vch.data(), vch.data() + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, ensure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(vchData.data(), pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(vchData.data(), vchTemp.data() + nVersionBytes, vchData.size());
memory_cleanse(vchTemp.data(), vchTemp.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
/** base58-encoded Chaincoin addresses.
* Public-key-hash-addresses have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* Script-hash-addresses have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CBitcoinAddress : public CBase58Data {
public:
bool Set(const CKeyID &id);
bool Set(const CScriptID &id);
bool Set(const CTxDestination &dest);
bool IsValid() const;
bool IsValid(const CChainParams ¶ms) const;
CBitcoinAddress() {}
CBitcoinAddress(const CTxDestination &dest) { Set(dest); }
CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); }
CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); }
CTxDestination Get() const;
bool GetKeyID(CKeyID &keyID) const;
bool IsScript() const;
};
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress* addr;
public:
explicit CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // namespace
bool CBitcoinAddress::Set(const CKeyID& id)
{
SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CTxDestination& dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool CBitcoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CBitcoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CBitcoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, vchData.data(), 20);
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
{
if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return false;
uint160 id;
memcpy(&id, vchData.data(), 20);
keyID = CKeyID(id);
return true;
}
bool CBitcoinAddress::IsScript() const
{
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
void CBitcoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CBitcoinSecret::GetKey()
{
CKey ret;
assert(vchData.size() >= 32);
ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CBitcoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
return fExpectedFormat && fCorrectVersion;
}
bool CBitcoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CBitcoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
std::string EncodeDestination(const CTxDestination& dest)
{
CBitcoinAddress addr(dest);
if (!addr.IsValid()) return "";
return addr.ToString();
}
CTxDestination DecodeDestination(const std::string& str)
{
return CBitcoinAddress(str).Get();
}
bool IsValidDestinationString(const std::string& str, const CChainParams& params)
{
return CBitcoinAddress(str).IsValid(params);
}
bool IsValidDestinationString(const std::string& str)
{
return CBitcoinAddress(str).IsValid();
}
<commit_msg>Remove unused GetKeyID and IsScript methods from CBitcoinAddress<commit_after>// Copyright (c) 2014-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <hash.h>
#include <uint256.h>
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
/** All alphanumeric characters except for "0", "I", "O", and "l" */
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
int length = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
int size = strlen(psz) * 733 /1000 + 1; // log(58) / log(256), rounded up.
std::vector<unsigned char> b256(size);
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == nullptr)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
int i = 0;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); (carry != 0 || i < length) && (it != b256.rend()); ++it, ++i) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
length = i;
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin() + (size - length);
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
int length = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up.
std::vector<unsigned char> b58(size);
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
int i = 0;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin() + (size - length);
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(vch.data(), vch.data() + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, ensure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(vchData.data(), pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(vchData.data(), vchTemp.data() + nVersionBytes, vchData.size());
memory_cleanse(vchTemp.data(), vchTemp.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
/** base58-encoded Chaincoin addresses.
* Public-key-hash-addresses have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* Script-hash-addresses have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CBitcoinAddress : public CBase58Data {
public:
bool Set(const CKeyID &id);
bool Set(const CScriptID &id);
bool Set(const CTxDestination &dest);
bool IsValid() const;
bool IsValid(const CChainParams ¶ms) const;
CBitcoinAddress() {}
CBitcoinAddress(const CTxDestination &dest) { Set(dest); }
CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); }
CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); }
CTxDestination Get() const;
};
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress* addr;
public:
explicit CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // namespace
bool CBitcoinAddress::Set(const CKeyID& id)
{
SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CTxDestination& dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool CBitcoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CBitcoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CBitcoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, vchData.data(), 20);
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
void CBitcoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CBitcoinSecret::GetKey()
{
CKey ret;
assert(vchData.size() >= 32);
ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CBitcoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
return fExpectedFormat && fCorrectVersion;
}
bool CBitcoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CBitcoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
std::string EncodeDestination(const CTxDestination& dest)
{
CBitcoinAddress addr(dest);
if (!addr.IsValid()) return "";
return addr.ToString();
}
CTxDestination DecodeDestination(const std::string& str)
{
return CBitcoinAddress(str).Get();
}
bool IsValidDestinationString(const std::string& str, const CChainParams& params)
{
return CBitcoinAddress(str).IsValid(params);
}
bool IsValidDestinationString(const std::string& str)
{
return CBitcoinAddress(str).IsValid();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-09T04:01:32";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<commit_msg>Update WebRTC code version (2021-01-11T04:01:55).<commit_after>/*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-11T04:01:55";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>#ifndef LUABIND_SCOPE_HPP_INCLUDED
#define LUABIND_SCOPE_HPP_INCLUDED
#include <vector>
#include <string>
#include <stack>
#include <luabind/detail/ref.hpp>
namespace luabind
{
namespace detail
{
struct scoped_sequence;
struct scoped_object
{
scoped_object()
{
}
virtual ~scoped_object() {}
virtual void commit(lua_State*) const = 0;
virtual scoped_object* clone() const = 0;
scoped_sequence operator,(const scoped_object& rhs) const;
};
struct scoped_sequence : scoped_object
{
scoped_sequence(scoped_object* a, scoped_object* b)
{
this->objects.push_back(a);
this->objects.push_back(b);
}
scoped_sequence() {}
virtual ~scoped_sequence()
{
for (std::vector<scoped_object*>
::const_iterator i = this->objects.begin()
; i != this->objects.end()
; ++i)
{
scoped_object* ptr = *i;
delete ptr;
}
}
scoped_sequence& operator,(const scoped_object& rhs)
{
objects.push_back(rhs.clone());
return *this;
}
virtual scoped_object* clone() const
{
scoped_sequence* copy = new scoped_sequence();
copy->objects.swap(this->objects);
return copy;
}
virtual void commit(lua_State* L) const
{
for (std::vector<scoped_object*>
::const_iterator i = this->objects.begin()
; i != this->objects.end()
; ++i)
{
scoped_object* ptr = *i;
ptr->commit(L);
}
}
mutable std::vector<scoped_object*> objects;
};
inline scoped_sequence scoped_object::operator,(const scoped_object& rhs) const
{
return scoped_sequence(this->clone(), rhs.clone());
}
}
/*
def(..),
def(..)
function_obj1, function_obj2
function_obj1.push_back(function_obj2.doclone());
*/
struct scope_stack
{
std::stack<int> scopes;
static int gc(lua_State* L)
{
scope_stack* scopes = static_cast<scope_stack*>(
lua_touserdata(L, -1)
);
assert(scopes->scopes.size() == 1);
int top = scopes->scopes.top();
scopes->scopes.pop();
detail::unref(L, top);
scopes->~scope_stack();
return 0;
}
static int top(lua_State* L)
{
lua_pushstring(L, "__luabind_scope_stack");
lua_gettable(L, LUA_REGISTRYINDEX);
scope_stack* scopes = static_cast<scope_stack*>(
lua_touserdata(L, -1)
);
lua_pop(L, 1);
return scopes->scopes.top();
}
static void push(lua_State* L)
{
lua_pushstring(L, "__luabind_scope_stack");
lua_gettable(L, LUA_REGISTRYINDEX);
scope_stack* scopes = static_cast<scope_stack*>(
lua_touserdata(L, -1)
);
lua_pop(L, 1);
return scopes->scopes.push(detail::ref(L));
}
static void pop(lua_State* L)
{
lua_pushstring(L, "__luabind_scope_stack");
lua_gettable(L, LUA_REGISTRYINDEX);
scope_stack* scopes = static_cast<scope_stack*>(
lua_touserdata(L, -1)
);
lua_pop(L, 1);
int n = scopes->scopes.top();
scopes->scopes.pop();
detail::unref(L, n);
}
};
class scope : public detail::scoped_object
{
public:
static void init(lua_State* L)
{
lua_pushstring(L, "__luabind_scope_stack");
lua_gettable(L, LUA_REGISTRYINDEX);
scope_stack* scopes = static_cast<scope_stack*>(
lua_touserdata(L, -1)
);
lua_pop(L, 1);
if (scopes == 0)
{
scopes = static_cast<scope_stack*>(
lua_newuserdata(L, sizeof(scope_stack))
);
lua_pushstring(L, "__luabind_scope_stack");
lua_pushvalue(L, -2);
lua_settable(L, LUA_REGISTRYINDEX);
new (scopes) scope_stack();
lua_pushvalue(L, LUA_GLOBALSINDEX);
scopes->scopes.push(detail::ref(L));
lua_newtable(L);
lua_pushstring(L, "__gc");
lua_pushcclosure(L, scope_stack::gc, 0);
lua_settable(L, -3);
lua_setmetatable(L, -2);
lua_pop(L, 1);
}
}
scope(lua_State* L, const char* name)
: m_state(L)
, m_name(name)
{
init(L);
}
scope(const char* name)
: m_state(0)
, m_name(name)
{
}
virtual ~scope()
{
for (std::vector<scoped_object*>
::const_iterator i = m_children.begin()
; i != m_children.end()
; ++i)
{
scoped_object* ptr = *i;
delete ptr;
}
}
scope& operator[](const detail::scoped_object& x)
{
m_children.push_back(x.clone());
if (m_state)
{
this->commit(m_state);
for (std::vector<scoped_object*>
::const_iterator i = m_children.begin()
; i != m_children.end()
; ++i)
{
scoped_object* ptr = *i;
delete ptr;
}
m_children.clear();
}
return *this;
}
virtual detail::scoped_object* clone() const
{
std::vector<detail::scoped_object*> tmp;
tmp.swap(this->m_children);
scope* copy = new scope(*this);
copy->m_children.swap(tmp);
return copy;
}
virtual void commit(lua_State* L) const
{
init(L);
detail::getref(L, scope_stack::top(L)); // get current scope
lua_pushstring(L, m_name.c_str());
lua_gettable(L, -2);
lua_remove(L, -2); // remove scope
if (lua_isnil(L, -1))
{
lua_pop(L, 1);
lua_newtable(L);
detail::getref(L, scope_stack::top(L));
lua_pushstring(L, m_name.c_str());
lua_pushvalue(L, -3);
lua_settable(L, -3);
lua_pop(L, 1);
}
scope_stack::push(L);
for (std::vector<detail::scoped_object*>
::const_iterator i = m_children.begin()
; i != m_children.end()
; ++i)
{
scoped_object* ptr = *i;
ptr->commit(L);
}
scope_stack::pop(L);
}
private:
mutable std::vector<scoped_object*> m_children;
lua_State* m_state;
std::string m_name;
};
typedef scope namespace_;
}
/*
scope dwarf("dwarf");
dwarf
[
def(..),
def(..),
class<vec3>("vec3")
.def(constructor<float,float,float>())
.def(self + self)
.def(self - self)
.def(self == self)
,
def("getDirection", &get_direction),
def("getPosition", &get_position)
];
dwarf
[
def(..)
];
dwarf.commit(L);
*/
#endif
<commit_msg>*** empty log message ***<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef LUABIND_SCOPE_HPP_INCLUDED
#define LUABIND_SCOPE_HPP_INCLUDED
#include <vector>
#include <string>
#include <stack>
#include <luabind/detail/ref.hpp>
namespace luabind
{
namespace detail
{
struct scoped_sequence;
struct scoped_object
{
scoped_object()
{
}
virtual ~scoped_object() {}
virtual void commit(lua_State*) const = 0;
virtual scoped_object* clone() const = 0;
scoped_sequence operator,(const scoped_object& rhs) const;
};
struct scoped_sequence : scoped_object
{
scoped_sequence(scoped_object* a, scoped_object* b)
{
this->objects.push_back(a);
this->objects.push_back(b);
}
scoped_sequence() {}
virtual ~scoped_sequence()
{
for (std::vector<scoped_object*>
::const_iterator i = this->objects.begin()
; i != this->objects.end()
; ++i)
{
scoped_object* ptr = *i;
delete ptr;
}
}
scoped_sequence& operator,(const scoped_object& rhs)
{
objects.push_back(rhs.clone());
return *this;
}
virtual scoped_object* clone() const
{
scoped_sequence* copy = new scoped_sequence();
copy->objects.swap(this->objects);
return copy;
}
virtual void commit(lua_State* L) const
{
for (std::vector<scoped_object*>
::const_iterator i = this->objects.begin()
; i != this->objects.end()
; ++i)
{
scoped_object* ptr = *i;
ptr->commit(L);
}
}
mutable std::vector<scoped_object*> objects;
};
inline scoped_sequence scoped_object::operator,(const scoped_object& rhs) const
{
return scoped_sequence(this->clone(), rhs.clone());
}
}
struct scope_stack
{
std::stack<int> scopes;
static int gc(lua_State* L)
{
scope_stack* scopes = static_cast<scope_stack*>(
lua_touserdata(L, -1)
);
assert(scopes->scopes.size() == 1);
int top = scopes->scopes.top();
scopes->scopes.pop();
detail::unref(L, top);
scopes->~scope_stack();
return 0;
}
static int top(lua_State* L)
{
lua_pushstring(L, "__luabind_scope_stack");
lua_gettable(L, LUA_REGISTRYINDEX);
scope_stack* scopes = static_cast<scope_stack*>(
lua_touserdata(L, -1)
);
lua_pop(L, 1);
return scopes->scopes.top();
}
static void push(lua_State* L)
{
lua_pushstring(L, "__luabind_scope_stack");
lua_gettable(L, LUA_REGISTRYINDEX);
scope_stack* scopes = static_cast<scope_stack*>(
lua_touserdata(L, -1)
);
lua_pop(L, 1);
return scopes->scopes.push(detail::ref(L));
}
static void pop(lua_State* L)
{
lua_pushstring(L, "__luabind_scope_stack");
lua_gettable(L, LUA_REGISTRYINDEX);
scope_stack* scopes = static_cast<scope_stack*>(
lua_touserdata(L, -1)
);
lua_pop(L, 1);
int n = scopes->scopes.top();
scopes->scopes.pop();
detail::unref(L, n);
}
};
class scope : public detail::scoped_object
{
public:
static void init(lua_State* L)
{
lua_pushstring(L, "__luabind_scope_stack");
lua_gettable(L, LUA_REGISTRYINDEX);
scope_stack* scopes = static_cast<scope_stack*>(
lua_touserdata(L, -1)
);
lua_pop(L, 1);
if (scopes == 0)
{
scopes = static_cast<scope_stack*>(
lua_newuserdata(L, sizeof(scope_stack))
);
lua_pushstring(L, "__luabind_scope_stack");
lua_pushvalue(L, -2);
lua_settable(L, LUA_REGISTRYINDEX);
new (scopes) scope_stack();
lua_pushvalue(L, LUA_GLOBALSINDEX);
scopes->scopes.push(detail::ref(L));
lua_newtable(L);
lua_pushstring(L, "__gc");
lua_pushcclosure(L, scope_stack::gc, 0);
lua_settable(L, -3);
lua_setmetatable(L, -2);
lua_pop(L, 1);
}
}
scope(lua_State* L, const char* name)
: m_state(L)
, m_name(name)
{
init(L);
}
scope(const char* name)
: m_state(0)
, m_name(name)
{
}
virtual ~scope()
{
for (std::vector<scoped_object*>
::const_iterator i = m_children.begin()
; i != m_children.end()
; ++i)
{
scoped_object* ptr = *i;
delete ptr;
}
}
scope& operator[](const detail::scoped_object& x)
{
m_children.push_back(x.clone());
if (m_state)
{
this->commit(m_state);
for (std::vector<scoped_object*>
::const_iterator i = m_children.begin()
; i != m_children.end()
; ++i)
{
scoped_object* ptr = *i;
delete ptr;
}
m_children.clear();
}
return *this;
}
virtual detail::scoped_object* clone() const
{
std::vector<detail::scoped_object*> tmp;
tmp.swap(this->m_children);
scope* copy = new scope(*this);
copy->m_children.swap(tmp);
return copy;
}
virtual void commit(lua_State* L) const
{
init(L);
detail::getref(L, scope_stack::top(L)); // get current scope
lua_pushstring(L, m_name.c_str());
lua_gettable(L, -2);
lua_remove(L, -2); // remove scope
if (lua_isnil(L, -1))
{
lua_pop(L, 1);
lua_newtable(L);
detail::getref(L, scope_stack::top(L));
lua_pushstring(L, m_name.c_str());
lua_pushvalue(L, -3);
lua_settable(L, -3);
lua_pop(L, 1);
}
scope_stack::push(L);
for (std::vector<detail::scoped_object*>
::const_iterator i = m_children.begin()
; i != m_children.end()
; ++i)
{
scoped_object* ptr = *i;
ptr->commit(L);
}
scope_stack::pop(L);
}
private:
mutable std::vector<scoped_object*> m_children;
lua_State* m_state;
std::string m_name;
};
typedef scope namespace_;
}
#endif // LUABIND_SCOPE_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrBackendSurface.h"
#include "GrClip.h"
#include "GrContext.h"
#include "GrContextPriv.h"
#include "GrRenderTargetContext.h"
#include "GrTexture.h"
#include "GrTextureAdjuster.h"
#include "SkBitmapCache.h"
#include "SkImage_Gpu.h"
#include "SkImage_GpuBase.h"
#include "SkReadPixelsRec.h"
SkImage_GpuBase::SkImage_GpuBase(sk_sp<GrContext> context, int width, int height, uint32_t uniqueID,
SkAlphaType at, SkBudgeted budgeted, sk_sp<SkColorSpace> cs)
: INHERITED(width, height, uniqueID)
, fContext(std::move(context))
, fAlphaType(at)
, fBudgeted(budgeted)
, fColorSpace(std::move(cs)) {}
SkImage_GpuBase::~SkImage_GpuBase() {}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool SkImage_GpuBase::ValidateBackendTexture(GrContext* ctx, const GrBackendTexture& tex,
GrPixelConfig* config, SkColorType ct, SkAlphaType at,
sk_sp<SkColorSpace> cs) {
if (!tex.isValid()) {
return false;
}
// TODO: Create a SkImageColorInfo struct for color, alpha, and color space so we don't need to
// create a fake image info here.
SkImageInfo info = SkImageInfo::Make(1, 1, ct, at, cs);
if (!SkImageInfoIsValid(info)) {
return false;
}
return ctx->contextPriv().caps()->validateBackendTexture(tex, ct, config);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool SkImage_GpuBase::getROPixels(SkBitmap* dst, SkColorSpace*, CachingHint chint) const {
if (!fContext->contextPriv().resourceProvider()) {
// DDL TODO: buffer up the readback so it occurs when the DDL is drawn?
return false;
}
// The SkColorSpace parameter "dstColorSpace" is really just a hint about how/where the bitmap
// will be used. The client doesn't expect that we convert to that color space, it's intended
// for codec-backed images, to drive our decoding heuristic. In theory we *could* read directly
// into that color space (to save the client some effort in whatever they're about to do), but
// that would make our use of the bitmap cache incorrect (or much less efficient, assuming we
// rolled the dstColorSpace into the key).
const auto desc = SkBitmapCacheDesc::Make(this);
if (SkBitmapCache::Find(desc, dst)) {
SkASSERT(dst->isImmutable());
SkASSERT(dst->getPixels());
return true;
}
SkBitmapCache::RecPtr rec = nullptr;
SkPixmap pmap;
if (kAllow_CachingHint == chint) {
rec = SkBitmapCache::Alloc(desc, this->onImageInfo(), &pmap);
if (!rec) {
return false;
}
} else {
if (!dst->tryAllocPixels(this->onImageInfo()) || !dst->peekPixels(&pmap)) {
return false;
}
}
sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext(
this->asTextureProxyRef(),
fColorSpace);
if (!sContext) {
return false;
}
if (!sContext->readPixels(pmap.info(), pmap.writable_addr(), pmap.rowBytes(), 0, 0)) {
return false;
}
if (rec) {
SkBitmapCache::Add(std::move(rec), dst);
this->notifyAddedToRasterCache();
}
return true;
}
sk_sp<SkImage> SkImage_GpuBase::onMakeSubset(const SkIRect& subset) const {
sk_sp<GrSurfaceProxy> proxy = this->asTextureProxyRef();
GrSurfaceDesc desc;
desc.fWidth = subset.width();
desc.fHeight = subset.height();
desc.fConfig = proxy->config();
sk_sp<GrSurfaceContext> sContext(fContext->contextPriv().makeDeferredSurfaceContext(
desc, proxy->origin(), GrMipMapped::kNo, SkBackingFit::kExact, fBudgeted));
if (!sContext) {
return nullptr;
}
if (!sContext->copy(proxy.get(), subset, SkIPoint::Make(0, 0))) {
return nullptr;
}
// MDB: this call is okay bc we know 'sContext' was kExact
return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID,
fAlphaType, sContext->asTextureProxyRef(),
fColorSpace, fBudgeted);
}
static void apply_premul(const SkImageInfo& info, void* pixels, size_t rowBytes) {
switch (info.colorType()) {
case kRGBA_8888_SkColorType:
case kBGRA_8888_SkColorType:
break;
default:
return; // nothing to do
}
// SkColor is not necesarily RGBA or BGRA, but it is one of them on little-endian,
// and in either case, the alpha-byte is always in the same place, so we can safely call
// SkPreMultiplyColor()
//
SkColor* row = (SkColor*)pixels;
for (int y = 0; y < info.height(); ++y) {
for (int x = 0; x < info.width(); ++x) {
row[x] = SkPreMultiplyColor(row[x]);
}
row = (SkColor*)((char*)(row)+rowBytes);
}
}
bool SkImage_GpuBase::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRB,
int srcX, int srcY, CachingHint) const {
if (!fContext->contextPriv().resourceProvider()) {
// DDL TODO: buffer up the readback so it occurs when the DDL is drawn?
return false;
}
if (!SkImageInfoValidConversion(dstInfo, this->onImageInfo())) {
return false;
}
SkReadPixelsRec rec(dstInfo, dstPixels, dstRB, srcX, srcY);
if (!rec.trim(this->width(), this->height())) {
return false;
}
// TODO: this seems to duplicate code in GrTextureContext::onReadPixels and
// GrRenderTargetContext::onReadPixels
uint32_t flags = 0;
if (kUnpremul_SkAlphaType == rec.fInfo.alphaType() && kPremul_SkAlphaType == fAlphaType) {
// let the GPU perform this transformation for us
flags = GrContextPriv::kUnpremul_PixelOpsFlag;
}
sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext(
this->asTextureProxyRef(), fColorSpace);
if (!sContext) {
return false;
}
if (!sContext->readPixels(rec.fInfo, rec.fPixels, rec.fRowBytes, rec.fX, rec.fY, flags)) {
return false;
}
// do we have to manually fix-up the alpha channel?
// src dst
// unpremul premul fix manually
// premul unpremul done by kUnpremul_PixelOpsFlag
// all other combos need to change.
//
// Should this be handled by Ganesh? todo:?
//
if (kPremul_SkAlphaType == rec.fInfo.alphaType() && kUnpremul_SkAlphaType == fAlphaType) {
apply_premul(rec.fInfo, rec.fPixels, rec.fRowBytes);
}
return true;
}
sk_sp<GrTextureProxy> SkImage_GpuBase::asTextureProxyRef(GrContext* context,
const GrSamplerState& params,
SkColorSpace* dstColorSpace,
sk_sp<SkColorSpace>* texColorSpace,
SkScalar scaleAdjust[2]) const {
if (context->uniqueID() != fContext->uniqueID()) {
SkASSERT(0);
return nullptr;
}
GrTextureAdjuster adjuster(fContext.get(), this->asTextureProxyRef(), fAlphaType,
this->uniqueID(), fColorSpace.get());
return adjuster.refTextureProxyForParams(params, dstColorSpace, texColorSpace, scaleAdjust);
}
GrBackendTexture SkImage_GpuBase::onGetBackendTexture(bool flushPendingGrContextIO,
GrSurfaceOrigin* origin) const {
sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef();
SkASSERT(proxy);
if (!fContext->contextPriv().resourceProvider() && !proxy->isInstantiated()) {
// This image was created with a DDL context and cannot be instantiated.
return GrBackendTexture();
}
if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) {
return GrBackendTexture(); // invalid
}
GrTexture* texture = proxy->peekTexture();
if (texture) {
if (flushPendingGrContextIO) {
fContext->contextPriv().prepareSurfaceForExternalIO(proxy.get());
}
if (origin) {
*origin = proxy->origin();
}
return texture->getBackendTexture();
}
return GrBackendTexture(); // invalid
}
GrTexture* SkImage_GpuBase::onGetTexture() const {
GrTextureProxy* proxy = this->peekProxy();
if (!proxy) {
return nullptr;
}
sk_sp<GrTextureProxy> proxyRef = this->asTextureProxyRef();
if (!fContext->contextPriv().resourceProvider() && !proxyRef->isInstantiated()) {
// This image was created with a DDL context and cannot be instantiated.
return nullptr;
}
if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) {
return nullptr;
}
return proxy->peekTexture();
}
sk_sp<SkImage> SkImage_GpuBase::onMakeColorSpace(sk_sp<SkColorSpace> target) const {
auto xform = GrColorSpaceXformEffect::Make(fColorSpace.get(), fAlphaType,
target.get(), fAlphaType);
if (!xform) {
return sk_ref_sp(const_cast<SkImage_GpuBase*>(this));
}
sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef();
sk_sp<GrRenderTargetContext> renderTargetContext(
fContext->contextPriv().makeDeferredRenderTargetContext(
SkBackingFit::kExact, this->width(), this->height(), proxy->config(), nullptr));
if (!renderTargetContext) {
return nullptr;
}
GrPaint paint;
paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
paint.addColorTextureProcessor(std::move(proxy), SkMatrix::I());
paint.addColorFragmentProcessor(std::move(xform));
const SkRect rect = SkRect::MakeIWH(this->width(), this->height());
renderTargetContext->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(), rect);
if (!renderTargetContext->asTextureProxy()) {
return nullptr;
}
// MDB: this call is okay bc we know 'renderTargetContext' was exact
return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID,
fAlphaType, renderTargetContext->asTextureProxyRef(),
std::move(target), fBudgeted);
}
bool SkImage_GpuBase::onIsValid(GrContext* context) const {
// The base class has already checked that context isn't abandoned (if it's not nullptr)
if (fContext->abandoned()) {
return false;
}
if (context && context != fContext.get()) {
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
sk_sp<GrTexture> SkPromiseImageHelper::getTexture(GrResourceProvider* resourceProvider,
GrPixelConfig config) {
// Releases the promise helper if there are no outstanding hard refs. This means that we
// don't have any ReleaseProcs waiting to be called so we will need to do a fulfill.
if (fReleaseHelper && fReleaseHelper->weak_expired()) {
this->resetReleaseHelper();
}
sk_sp<GrTexture> tex;
if (!fReleaseHelper) {
fFulfillProc(fContext, &fBackendTex);
fBackendTex.fConfig = config;
if (!fBackendTex.isValid()) {
// Even though the GrBackendTexture is not valid, we must call the release
// proc to keep our contract of always calling Fulfill and Release in pairs.
fReleaseProc(fContext);
return sk_sp<GrTexture>();
}
tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership);
if (!tex) {
// Even though the GrBackendTexture is not valid, we must call the release
// proc to keep our contract of always calling Fulfill and Release in pairs.
fReleaseProc(fContext);
return sk_sp<GrTexture>();
}
fReleaseHelper = new SkPromiseReleaseProcHelper(fReleaseProc, fContext, fDoneHelper);
// Take a weak ref
fReleaseHelper->weak_ref();
} else {
SkASSERT(fBackendTex.isValid());
tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership);
if (!tex) {
// We weren't able to make a texture here, but since we are in this branch
// of the calls (promiseHelper.fReleaseHelper is valid) there is already a
// texture out there which will call the release proc so we don't need to
// call it here.
return sk_sp<GrTexture>();
}
SkAssertResult(fReleaseHelper->try_ref());
}
SkASSERT(tex);
// Pass the hard ref off to the texture
tex->setRelease(sk_sp<GrReleaseProcHelper>(fReleaseHelper));
return tex;
}
<commit_msg>Fix bug with makeColorSpace of GPU images with non-renderable configs<commit_after>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrBackendSurface.h"
#include "GrClip.h"
#include "GrContext.h"
#include "GrContextPriv.h"
#include "GrRenderTargetContext.h"
#include "GrTexture.h"
#include "GrTextureAdjuster.h"
#include "SkBitmapCache.h"
#include "SkImage_Gpu.h"
#include "SkImage_GpuBase.h"
#include "SkReadPixelsRec.h"
SkImage_GpuBase::SkImage_GpuBase(sk_sp<GrContext> context, int width, int height, uint32_t uniqueID,
SkAlphaType at, SkBudgeted budgeted, sk_sp<SkColorSpace> cs)
: INHERITED(width, height, uniqueID)
, fContext(std::move(context))
, fAlphaType(at)
, fBudgeted(budgeted)
, fColorSpace(std::move(cs)) {}
SkImage_GpuBase::~SkImage_GpuBase() {}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool SkImage_GpuBase::ValidateBackendTexture(GrContext* ctx, const GrBackendTexture& tex,
GrPixelConfig* config, SkColorType ct, SkAlphaType at,
sk_sp<SkColorSpace> cs) {
if (!tex.isValid()) {
return false;
}
// TODO: Create a SkImageColorInfo struct for color, alpha, and color space so we don't need to
// create a fake image info here.
SkImageInfo info = SkImageInfo::Make(1, 1, ct, at, cs);
if (!SkImageInfoIsValid(info)) {
return false;
}
return ctx->contextPriv().caps()->validateBackendTexture(tex, ct, config);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool SkImage_GpuBase::getROPixels(SkBitmap* dst, SkColorSpace*, CachingHint chint) const {
if (!fContext->contextPriv().resourceProvider()) {
// DDL TODO: buffer up the readback so it occurs when the DDL is drawn?
return false;
}
// The SkColorSpace parameter "dstColorSpace" is really just a hint about how/where the bitmap
// will be used. The client doesn't expect that we convert to that color space, it's intended
// for codec-backed images, to drive our decoding heuristic. In theory we *could* read directly
// into that color space (to save the client some effort in whatever they're about to do), but
// that would make our use of the bitmap cache incorrect (or much less efficient, assuming we
// rolled the dstColorSpace into the key).
const auto desc = SkBitmapCacheDesc::Make(this);
if (SkBitmapCache::Find(desc, dst)) {
SkASSERT(dst->isImmutable());
SkASSERT(dst->getPixels());
return true;
}
SkBitmapCache::RecPtr rec = nullptr;
SkPixmap pmap;
if (kAllow_CachingHint == chint) {
rec = SkBitmapCache::Alloc(desc, this->onImageInfo(), &pmap);
if (!rec) {
return false;
}
} else {
if (!dst->tryAllocPixels(this->onImageInfo()) || !dst->peekPixels(&pmap)) {
return false;
}
}
sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext(
this->asTextureProxyRef(),
fColorSpace);
if (!sContext) {
return false;
}
if (!sContext->readPixels(pmap.info(), pmap.writable_addr(), pmap.rowBytes(), 0, 0)) {
return false;
}
if (rec) {
SkBitmapCache::Add(std::move(rec), dst);
this->notifyAddedToRasterCache();
}
return true;
}
sk_sp<SkImage> SkImage_GpuBase::onMakeSubset(const SkIRect& subset) const {
sk_sp<GrSurfaceProxy> proxy = this->asTextureProxyRef();
GrSurfaceDesc desc;
desc.fWidth = subset.width();
desc.fHeight = subset.height();
desc.fConfig = proxy->config();
sk_sp<GrSurfaceContext> sContext(fContext->contextPriv().makeDeferredSurfaceContext(
desc, proxy->origin(), GrMipMapped::kNo, SkBackingFit::kExact, fBudgeted));
if (!sContext) {
return nullptr;
}
if (!sContext->copy(proxy.get(), subset, SkIPoint::Make(0, 0))) {
return nullptr;
}
// MDB: this call is okay bc we know 'sContext' was kExact
return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID,
fAlphaType, sContext->asTextureProxyRef(),
fColorSpace, fBudgeted);
}
static void apply_premul(const SkImageInfo& info, void* pixels, size_t rowBytes) {
switch (info.colorType()) {
case kRGBA_8888_SkColorType:
case kBGRA_8888_SkColorType:
break;
default:
return; // nothing to do
}
// SkColor is not necesarily RGBA or BGRA, but it is one of them on little-endian,
// and in either case, the alpha-byte is always in the same place, so we can safely call
// SkPreMultiplyColor()
//
SkColor* row = (SkColor*)pixels;
for (int y = 0; y < info.height(); ++y) {
for (int x = 0; x < info.width(); ++x) {
row[x] = SkPreMultiplyColor(row[x]);
}
row = (SkColor*)((char*)(row)+rowBytes);
}
}
bool SkImage_GpuBase::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRB,
int srcX, int srcY, CachingHint) const {
if (!fContext->contextPriv().resourceProvider()) {
// DDL TODO: buffer up the readback so it occurs when the DDL is drawn?
return false;
}
if (!SkImageInfoValidConversion(dstInfo, this->onImageInfo())) {
return false;
}
SkReadPixelsRec rec(dstInfo, dstPixels, dstRB, srcX, srcY);
if (!rec.trim(this->width(), this->height())) {
return false;
}
// TODO: this seems to duplicate code in GrTextureContext::onReadPixels and
// GrRenderTargetContext::onReadPixels
uint32_t flags = 0;
if (kUnpremul_SkAlphaType == rec.fInfo.alphaType() && kPremul_SkAlphaType == fAlphaType) {
// let the GPU perform this transformation for us
flags = GrContextPriv::kUnpremul_PixelOpsFlag;
}
sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext(
this->asTextureProxyRef(), fColorSpace);
if (!sContext) {
return false;
}
if (!sContext->readPixels(rec.fInfo, rec.fPixels, rec.fRowBytes, rec.fX, rec.fY, flags)) {
return false;
}
// do we have to manually fix-up the alpha channel?
// src dst
// unpremul premul fix manually
// premul unpremul done by kUnpremul_PixelOpsFlag
// all other combos need to change.
//
// Should this be handled by Ganesh? todo:?
//
if (kPremul_SkAlphaType == rec.fInfo.alphaType() && kUnpremul_SkAlphaType == fAlphaType) {
apply_premul(rec.fInfo, rec.fPixels, rec.fRowBytes);
}
return true;
}
sk_sp<GrTextureProxy> SkImage_GpuBase::asTextureProxyRef(GrContext* context,
const GrSamplerState& params,
SkColorSpace* dstColorSpace,
sk_sp<SkColorSpace>* texColorSpace,
SkScalar scaleAdjust[2]) const {
if (context->uniqueID() != fContext->uniqueID()) {
SkASSERT(0);
return nullptr;
}
GrTextureAdjuster adjuster(fContext.get(), this->asTextureProxyRef(), fAlphaType,
this->uniqueID(), fColorSpace.get());
return adjuster.refTextureProxyForParams(params, dstColorSpace, texColorSpace, scaleAdjust);
}
GrBackendTexture SkImage_GpuBase::onGetBackendTexture(bool flushPendingGrContextIO,
GrSurfaceOrigin* origin) const {
sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef();
SkASSERT(proxy);
if (!fContext->contextPriv().resourceProvider() && !proxy->isInstantiated()) {
// This image was created with a DDL context and cannot be instantiated.
return GrBackendTexture();
}
if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) {
return GrBackendTexture(); // invalid
}
GrTexture* texture = proxy->peekTexture();
if (texture) {
if (flushPendingGrContextIO) {
fContext->contextPriv().prepareSurfaceForExternalIO(proxy.get());
}
if (origin) {
*origin = proxy->origin();
}
return texture->getBackendTexture();
}
return GrBackendTexture(); // invalid
}
GrTexture* SkImage_GpuBase::onGetTexture() const {
GrTextureProxy* proxy = this->peekProxy();
if (!proxy) {
return nullptr;
}
sk_sp<GrTextureProxy> proxyRef = this->asTextureProxyRef();
if (!fContext->contextPriv().resourceProvider() && !proxyRef->isInstantiated()) {
// This image was created with a DDL context and cannot be instantiated.
return nullptr;
}
if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) {
return nullptr;
}
return proxy->peekTexture();
}
sk_sp<SkImage> SkImage_GpuBase::onMakeColorSpace(sk_sp<SkColorSpace> target) const {
auto xform = GrColorSpaceXformEffect::Make(fColorSpace.get(), fAlphaType,
target.get(), fAlphaType);
if (!xform) {
return sk_ref_sp(const_cast<SkImage_GpuBase*>(this));
}
sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef();
sk_sp<GrRenderTargetContext> renderTargetContext(
fContext->contextPriv().makeDeferredRenderTargetContextWithFallback(
SkBackingFit::kExact, this->width(), this->height(), proxy->config(), nullptr));
if (!renderTargetContext) {
return nullptr;
}
GrPaint paint;
paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
paint.addColorTextureProcessor(std::move(proxy), SkMatrix::I());
paint.addColorFragmentProcessor(std::move(xform));
const SkRect rect = SkRect::MakeIWH(this->width(), this->height());
renderTargetContext->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(), rect);
if (!renderTargetContext->asTextureProxy()) {
return nullptr;
}
// MDB: this call is okay bc we know 'renderTargetContext' was exact
return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID,
fAlphaType, renderTargetContext->asTextureProxyRef(),
std::move(target), fBudgeted);
}
bool SkImage_GpuBase::onIsValid(GrContext* context) const {
// The base class has already checked that context isn't abandoned (if it's not nullptr)
if (fContext->abandoned()) {
return false;
}
if (context && context != fContext.get()) {
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
sk_sp<GrTexture> SkPromiseImageHelper::getTexture(GrResourceProvider* resourceProvider,
GrPixelConfig config) {
// Releases the promise helper if there are no outstanding hard refs. This means that we
// don't have any ReleaseProcs waiting to be called so we will need to do a fulfill.
if (fReleaseHelper && fReleaseHelper->weak_expired()) {
this->resetReleaseHelper();
}
sk_sp<GrTexture> tex;
if (!fReleaseHelper) {
fFulfillProc(fContext, &fBackendTex);
fBackendTex.fConfig = config;
if (!fBackendTex.isValid()) {
// Even though the GrBackendTexture is not valid, we must call the release
// proc to keep our contract of always calling Fulfill and Release in pairs.
fReleaseProc(fContext);
return sk_sp<GrTexture>();
}
tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership);
if (!tex) {
// Even though the GrBackendTexture is not valid, we must call the release
// proc to keep our contract of always calling Fulfill and Release in pairs.
fReleaseProc(fContext);
return sk_sp<GrTexture>();
}
fReleaseHelper = new SkPromiseReleaseProcHelper(fReleaseProc, fContext, fDoneHelper);
// Take a weak ref
fReleaseHelper->weak_ref();
} else {
SkASSERT(fBackendTex.isValid());
tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership);
if (!tex) {
// We weren't able to make a texture here, but since we are in this branch
// of the calls (promiseHelper.fReleaseHelper is valid) there is already a
// texture out there which will call the release proc so we don't need to
// call it here.
return sk_sp<GrTexture>();
}
SkAssertResult(fReleaseHelper->try_ref());
}
SkASSERT(tex);
// Pass the hard ref off to the texture
tex->setRelease(sk_sp<GrReleaseProcHelper>(fReleaseHelper));
return tex;
}
<|endoftext|>
|
<commit_before>#include "Trie.hpp"
#include "Stack2.hpp"
#include "Pair.hpp"
#include <string.h>
#include <iostream>
TrieNode::TrieNode(): parent_(0), value_(0), key_(0)
{
memset(index_, 0, sizeof(TrieNode*)*53);
}
bool TrieNode::operator<(const TrieNode & b) const
{
return (b.value_ < this->value_);
}
std::ostream& TrieNode::toStream(std::ostream& oOut)
{
oOut << key_;
oOut << ":";
oOut << value_;
return oOut;
}
std::ostream& operator<<(std::ostream& oOut, TrieNode & iObj) { return iObj.toStream(oOut); }
Trie::Trie(): size_(0) {}
void Trie::insert(const char * iWord)
{
TrieNode * p = &root_;
while (*iWord!=0)
{
char i = hash(*iWord);
if ( p->index_[i] )
{
p = p->index_[i];
}
else
{
TrieNode * node = new TrieNode();
node->key_ = *iWord;
node->parent_ = p;
p->index_[i] = node;
p = node;
++size_;
}
++iWord;
}
if (p->value_==0)
list_.pushBack(p);
++(p->value_);
}
void Trie::frequencies(int iTop) const
{
printf("\tTrie_size= %i\n", size_);
printf("\tMemory_space= %i\n", size_*sizeof(TrieNode));
list_.sort2();
//std::cout << list_ << std::endl;
LinkedListIterator<TrieNode*> it = list_.getIterator();
int i = 0;
for (; i<iTop && !it.end(); ++i, ++it)
{
const TrieNode * p = *it;
char s[64];
memset(s,0,64);
char * q = s;
int freq = p->value_;
while (p!=&root_)
{
*q=p->key_;
++q;
p = p->parent_;
}
// we have to reverse the string before printing it
reverse_string(s, get_string_size(s));
printf("\t%i\t%s\n", freq, s);
}
}
char Trie::hash(char c)
{
if (c>64 && c<91)
return c-65;
else if (c>96 && c<123)
return c-71;
return 52;
}
void Trie::reverse_string(char * s, int n) const
{
char * e = s+n-1;
char t;
for (; s<e; ++s, --e)
{
t = *s;
*s = *e;
*e = t;
}
return;
}
int Trie::get_string_size(char * s) const
{
char * p = s;
while(*p)
++p;
return (p-s);
}
int Trie::get_tree_high() const
{
typedef Pair<const TrieNode*, int> Dub;
Stack2< Dub > stack;
int max = 0;
int cur = 0;
const TrieNode* p = 0;
stack.push( Dub(&root_,cur) );
while( !stack.empty() )
{
Dub d = stack.getTop();
stack.pop();
p = d.first();
cur = d.second();
if (cur>max)
{
max=cur;
}
for (int i=52; i>=0; --i)
{
if ( p->index_[i] )
{
stack.push( Dub(p->index_[i], cur+1) );
}
}
}
return max;
}
<commit_msg>Added cstdio include<commit_after>#include "Trie.hpp"
#include "Stack2.hpp"
#include "Pair.hpp"
#include <cstring>
#include <cstdio>
#include <iostream>
TrieNode::TrieNode(): parent_(0), value_(0), key_(0)
{
memset(index_, 0, sizeof(TrieNode*)*53);
}
bool TrieNode::operator<(const TrieNode & b) const
{
return (b.value_ < this->value_);
}
std::ostream& TrieNode::toStream(std::ostream& oOut)
{
oOut << key_;
oOut << ":";
oOut << value_;
return oOut;
}
std::ostream& operator<<(std::ostream& oOut, TrieNode & iObj) { return iObj.toStream(oOut); }
Trie::Trie(): size_(0) {}
void Trie::insert(const char * iWord)
{
TrieNode * p = &root_;
while (*iWord!=0)
{
char i = hash(*iWord);
if ( p->index_[i] )
{
p = p->index_[i];
}
else
{
TrieNode * node = new TrieNode();
node->key_ = *iWord;
node->parent_ = p;
p->index_[i] = node;
p = node;
++size_;
}
++iWord;
}
if (p->value_==0)
list_.pushBack(p);
++(p->value_);
}
void Trie::frequencies(int iTop) const
{
printf("\tTrie_size= %i\n", size_);
printf("\tMemory_space= %i\n", size_*sizeof(TrieNode));
list_.sort2();
//std::cout << list_ << std::endl;
LinkedListIterator<TrieNode*> it = list_.getIterator();
int i = 0;
for (; i<iTop && !it.end(); ++i, ++it)
{
const TrieNode * p = *it;
char s[64];
memset(s,0,64);
char * q = s;
int freq = p->value_;
while (p!=&root_)
{
*q=p->key_;
++q;
p = p->parent_;
}
// we have to reverse the string before printing it
reverse_string(s, get_string_size(s));
printf("\t%i\t%s\n", freq, s);
}
}
char Trie::hash(char c)
{
if (c>64 && c<91)
return c-65;
else if (c>96 && c<123)
return c-71;
return 52;
}
void Trie::reverse_string(char * s, int n) const
{
char * e = s+n-1;
char t;
for (; s<e; ++s, --e)
{
t = *s;
*s = *e;
*e = t;
}
return;
}
int Trie::get_string_size(char * s) const
{
char * p = s;
while(*p)
++p;
return (p-s);
}
int Trie::get_tree_high() const
{
typedef Pair<const TrieNode*, int> Dub;
Stack2< Dub > stack;
int max = 0;
int cur = 0;
const TrieNode* p = 0;
stack.push( Dub(&root_,cur) );
while( !stack.empty() )
{
Dub d = stack.getTop();
stack.pop();
p = d.first();
cur = d.second();
if (cur>max)
{
max=cur;
}
for (int i=52; i>=0; --i)
{
if ( p->index_[i] )
{
stack.push( Dub(p->index_[i], cur+1) );
}
}
}
return max;
}
<|endoftext|>
|
<commit_before>/*
Copyright © 2003 Richard Lärkäng
Copyright © 2003 Jason Kivlighn <jkivlighn@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>
*/
#include "mx2importer.h"
#include <klocale.h>
#include <kdebug.h>
#include <QFile>
#include <QStringList>
#include <QTextStream>
#include "datablocks/recipe.h"
MX2Importer::MX2Importer()
{}
void MX2Importer::parseFile( const QString& filename )
{
QFile file( filename );
kDebug() << "loading file: " << filename ;
if ( file.open( QIODevice::ReadOnly ) ) {
kDebug() << "file opened" ;
QDomDocument doc;
//hopefully a temporary hack, since MasterCook creates invalid xml declarations
QTextStream stream( &file );
QString all_data = stream.readAll();
if ( all_data.startsWith( "<?xml" ) )
all_data.remove( 0, all_data.indexOf( "?>" ) + 2 );
QString error;
int line;
int column;
if ( !doc.setContent( all_data, &error, &line, &column ) ) {
kDebug() << QString( "error: \"%1\" at line %2, column %3" ).arg( error ).arg( line ).arg( column ) ;
setErrorMsg( i18n( "\"%1\" at line %2, column %3. This may not be a *.mx2 file.", error, line, column ) );
return ;
}
QDomElement mx2 = doc.documentElement();
// TODO Check if there are changes between versions
if ( mx2.tagName() != "mx2" /*|| mx2.attribute("source") != "MasterCook 5.0"*/ ) {
setErrorMsg( i18n( "This file does not appear to be a *.mx2 file" ) );
return ;
}
QDomNodeList l = mx2.childNodes();
for ( int i = 0; i < l.count(); i++ ) {
QDomElement el = l.item( i ).toElement();
if ( el.tagName() == "RcpE" ) {
Recipe recipe;
recipe.title = el.attribute( "name" );
Element author( el.attribute( "author" ) );
recipe.authorList.append( author );
readRecipe( el.childNodes(), &recipe );
add
( recipe );
}
}
}
else
setErrorMsg( i18n( "Unable to open file." ) );
}
MX2Importer::~MX2Importer()
{
}
void MX2Importer::readRecipe( const QDomNodeList& l, Recipe *recipe )
{
for ( int i = 0; i < l.count(); i++ ) {
QDomElement el = l.item( i ).toElement();
QString tagName = el.tagName();
if ( tagName == "Serv" ) {
recipe->yield.amount = el.attribute( "qty" ).toInt();
recipe->yield.type = i18n("servings");
}
else if ( tagName == "PrpT" )
recipe->prepTime = QTime::fromString( el.attribute( "elapsed" ), "h:mm" );
else if ( tagName == "CatS" ) {
QDomNodeList categories = el.childNodes();
for ( int j = 0; j < categories.count(); j++ ) {
QDomElement c = categories.item( j ).toElement();
if ( c.tagName() == "CatT" ) {
if ( c.text().length() > 0 ) {
Element cat( c.text().trimmed() );
recipe->categoryList.append( cat );
}
}
}
}
else if ( tagName == "IngR" ) {
Ingredient new_ing( el.attribute( "name" ),
el.attribute( "qty" ).toDouble(),
Unit( el.attribute( "unit" ), el.attribute( "qty" ).toDouble() ) );
if ( el.hasChildNodes() ) {
QDomNodeList iChilds = el.childNodes();
for ( int j = 0; j < iChilds.count(); j++ ) {
QDomElement iChild = iChilds.item( j ).toElement();
if ( iChild.tagName() == "IPrp" )
new_ing.prepMethodList.append( Element(iChild.text().trimmed()) );
else if ( iChild.tagName() == "INtI" )
; // TODO: What does it mean?... ingredient nutrient info?
}
}
recipe->ingList.append( new_ing );
}
else if ( tagName == "DirS" ) {
QStringList directions;
QDomNodeList dirs = el.childNodes();
for ( int j = 0; j < dirs.count(); j++ ) {
QDomElement dir = dirs.item( j ).toElement();
if ( dir.tagName() == "DirT" )
directions.append( dir.text().trimmed() );
}
QString directionsText;
// TODO This is copied from RecipeML, maybe a QStringList
// for directions in Recipe instead?
if ( directions.count() > 1 ) {
for ( int i = 1; i <= directions.count(); i++ ) {
if ( i != 1 ) {
directionsText += "\n\n";
}
QString sWith = QString( "%1. " ).arg( i );
QString text = directions[ i - 1 ];
if ( !text.trimmed().startsWith( sWith ) )
directionsText += sWith;
directionsText += text;
}
}
else
directionsText = directions[ 0 ];
recipe->instructions = directionsText;
}
else if ( tagName == "SrvI" ) {
// Don't know what to do with it, for now add it to directions
// btw lets hope this is read after the directions
recipe->instructions += "\n\n" + el.text().trimmed();
}
else if ( tagName == "Note" ) {
// Don't know what to do with it, for now add it to directions
// btw lets hope this is read after the directions
recipe->instructions += "\n\n" + el.text().trimmed();
}
else if ( tagName == "Nutr" ) {
//example: <Nutr>Per Serving (excluding unknown items): 51 Calories; 6g Fat (99.5% calories from fat); trace Protein; trace Carbohydrate; 0g Dietary Fiber; 16mg Cholesterol; 137mg Sodium. Exchanges: 1 Fat.</Nutr>
// Don't know what to do with it, for now add it to directions
// btw lets hope this is read after the directions
recipe->instructions += "\n\n" + el.text().trimmed();
}
/* tags to check for (example follows:
<Srce>SARA'S SECRETS with Sara Moulton - (Show # SS-1B43) - from the TV FOOD NETWORK</Srce>
<AltS label="Formatted for MC7" source="07-11-2003 by Joe Comiskey - Mad's Recipe Emporium"/>
*/
// TODO Have i missed some tag?
}
}
<commit_msg>Read ranges and fractions from mx2 files.<commit_after>/*
Copyright © 2003 Richard Lärkäng
Copyright © 2003 Jason Kivlighn <jkivlighn@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>
*/
#include "mx2importer.h"
#include <klocale.h>
#include <kdebug.h>
#include <QFile>
#include <QStringList>
#include <QTextStream>
#include "datablocks/mixednumber.h"
#include "datablocks/recipe.h"
MX2Importer::MX2Importer()
{}
void MX2Importer::parseFile( const QString& filename )
{
QFile file( filename );
kDebug() << "loading file: " << filename ;
if ( file.open( QIODevice::ReadOnly ) ) {
kDebug() << "file opened" ;
QDomDocument doc;
//hopefully a temporary hack, since MasterCook creates invalid xml declarations
QTextStream stream( &file );
QString all_data = stream.readAll();
if ( all_data.startsWith( "<?xml" ) )
all_data.remove( 0, all_data.indexOf( "?>" ) + 2 );
QString error;
int line;
int column;
if ( !doc.setContent( all_data, &error, &line, &column ) ) {
kDebug() << QString( "error: \"%1\" at line %2, column %3" ).arg( error ).arg( line ).arg( column ) ;
setErrorMsg( i18n( "\"%1\" at line %2, column %3. This may not be a *.mx2 file.", error, line, column ) );
return ;
}
QDomElement mx2 = doc.documentElement();
// TODO Check if there are changes between versions
if ( mx2.tagName() != "mx2" /*|| mx2.attribute("source") != "MasterCook 5.0"*/ ) {
setErrorMsg( i18n( "This file does not appear to be a *.mx2 file" ) );
return ;
}
QDomNodeList l = mx2.childNodes();
for ( int i = 0; i < l.count(); i++ ) {
QDomElement el = l.item( i ).toElement();
if ( el.tagName() == "RcpE" ) {
Recipe recipe;
recipe.title = el.attribute( "name" );
Element author( el.attribute( "author" ) );
recipe.authorList.append( author );
readRecipe( el.childNodes(), &recipe );
add
( recipe );
}
}
}
else
setErrorMsg( i18n( "Unable to open file." ) );
}
MX2Importer::~MX2Importer()
{
}
void MX2Importer::readRecipe( const QDomNodeList& l, Recipe *recipe )
{
for ( int i = 0; i < l.count(); i++ ) {
QDomElement el = l.item( i ).toElement();
QString tagName = el.tagName();
if ( tagName == "Serv" ) {
recipe->yield.amount = el.attribute( "qty" ).toInt();
recipe->yield.type = i18n("servings");
}
else if ( tagName == "PrpT" )
recipe->prepTime = QTime::fromString( el.attribute( "elapsed" ), "h:mm" );
else if ( tagName == "CatS" ) {
QDomNodeList categories = el.childNodes();
for ( int j = 0; j < categories.count(); j++ ) {
QDomElement c = categories.item( j ).toElement();
if ( c.tagName() == "CatT" ) {
if ( c.text().length() > 0 ) {
Element cat( c.text().trimmed() );
recipe->categoryList.append( cat );
}
}
}
}
else if ( tagName == "IngR" ) {
double quantity1=0, quantity2=0, offset=0;
bool ok;
QStringList qtyStrList = el.attribute( "qty" ).split( " " );
if ( !qtyStrList.isEmpty() ) {
quantity1 = MixedNumber::fromString( qtyStrList.first(), &ok, false ).toDouble();
if ( !ok )
quantity1 = 0;
if ( qtyStrList.constBegin() != qtyStrList.constEnd() )
quantity2 = MixedNumber::fromString( qtyStrList.last(), &ok, false ).toDouble();
if ( !ok )
quantity2 = 0;
}
offset = quantity2 - quantity1;
Ingredient new_ing( el.attribute( "name" ),
quantity1,
Unit( el.attribute( "unit" ), quantity1 ) );
new_ing.amount_offset = offset;
if ( el.hasChildNodes() ) {
QDomNodeList iChilds = el.childNodes();
for ( int j = 0; j < iChilds.count(); j++ ) {
QDomElement iChild = iChilds.item( j ).toElement();
if ( iChild.tagName() == "IPrp" )
new_ing.prepMethodList.append( Element(iChild.text().trimmed()) );
else if ( iChild.tagName() == "INtI" )
; // TODO: What does it mean?... ingredient nutrient info?
}
}
recipe->ingList.append( new_ing );
}
else if ( tagName == "DirS" ) {
QStringList directions;
QDomNodeList dirs = el.childNodes();
for ( int j = 0; j < dirs.count(); j++ ) {
QDomElement dir = dirs.item( j ).toElement();
if ( dir.tagName() == "DirT" )
directions.append( dir.text().trimmed() );
}
QString directionsText;
// TODO This is copied from RecipeML, maybe a QStringList
// for directions in Recipe instead?
if ( directions.count() > 1 ) {
for ( int i = 1; i <= directions.count(); i++ ) {
if ( i != 1 ) {
directionsText += "\n\n";
}
QString sWith = QString( "%1. " ).arg( i );
QString text = directions[ i - 1 ];
if ( !text.trimmed().startsWith( sWith ) )
directionsText += sWith;
directionsText += text;
}
}
else
directionsText = directions[ 0 ];
recipe->instructions = directionsText;
}
else if ( tagName == "SrvI" ) {
// Don't know what to do with it, for now add it to directions
// btw lets hope this is read after the directions
recipe->instructions += "\n\n" + el.text().trimmed();
}
else if ( tagName == "Note" ) {
// Don't know what to do with it, for now add it to directions
// btw lets hope this is read after the directions
recipe->instructions += "\n\n" + el.text().trimmed();
}
else if ( tagName == "Nutr" ) {
//example: <Nutr>Per Serving (excluding unknown items): 51 Calories; 6g Fat (99.5% calories from fat); trace Protein; trace Carbohydrate; 0g Dietary Fiber; 16mg Cholesterol; 137mg Sodium. Exchanges: 1 Fat.</Nutr>
// Don't know what to do with it, for now add it to directions
// btw lets hope this is read after the directions
recipe->instructions += "\n\n" + el.text().trimmed();
}
/* tags to check for (example follows:
<Srce>SARA'S SECRETS with Sara Moulton - (Show # SS-1B43) - from the TV FOOD NETWORK</Srce>
<AltS label="Formatted for MC7" source="07-11-2003 by Joe Comiskey - Mad's Recipe Emporium"/>
*/
// TODO Have i missed some tag?
}
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "ServerJob.h"
#include "Basics/MutexLocker.h"
#include "Cluster/ClusterInfo.h"
#include "Cluster/HeartbeatThread.h"
#include "Dispatcher/DispatcherQueue.h"
#include "Logger/Logger.h"
#include "RestServer/DatabaseFeature.h"
#include "V8/v8-utils.h"
#include "V8Server/V8Context.h"
#include "V8Server/V8DealerFeature.h"
#include "VocBase/server.h"
#include "VocBase/vocbase.h"
#include <iostream>
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::rest;
static arangodb::Mutex ExecutorLock;
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new db server job
////////////////////////////////////////////////////////////////////////////////
ServerJob::ServerJob(HeartbeatThread* heartbeat)
: Job("HttpServerJob"),
_heartbeat(heartbeat),
_shutdown(0),
_abandon(false) {}
////////////////////////////////////////////////////////////////////////////////
/// @brief destructs a db server job
////////////////////////////////////////////////////////////////////////////////
ServerJob::~ServerJob() {}
void ServerJob::work() {
LOG(TRACE) << "starting plan update handler";
if (_shutdown != 0) {
return;
}
_heartbeat->setReady();
bool result;
{
// only one plan change at a time
MUTEX_LOCKER(mutexLocker, ExecutorLock);
result = execute();
}
_heartbeat->removeDispatchedJob(result);
}
bool ServerJob::cancel() { return false; }
void ServerJob::cleanup(DispatcherQueue* queue) {
queue->removeJob(this);
delete this;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief execute job
////////////////////////////////////////////////////////////////////////////////
bool ServerJob::execute() {
// default to system database
DatabaseFeature* database = dynamic_cast<DatabaseFeature*>(
ApplicationServer::lookupFeature("Database"));
TRI_vocbase_t* const vocbase = database->vocbase();
if (vocbase == nullptr) {
std::cout << "+++++++++++++ oops ++++++++++++++" << std::endl;
// database is gone
return false;
}
TRI_DEFER(TRI_ReleaseVocBase(vocbase));
V8Context* context = V8DealerFeature::DEALER->enterContext(vocbase, true);
if (context == nullptr) {
return false;
}
bool ok = true;
auto isolate = context->_isolate;
try {
v8::HandleScope scope(isolate);
// execute script inside the context
auto file = TRI_V8_ASCII_STRING("handle-plan-change");
auto content =
TRI_V8_ASCII_STRING("require('@arangodb/cluster').handlePlanChange();");
v8::Handle<v8::Value> res = TRI_ExecuteJavaScriptString(
isolate, isolate->GetCurrentContext(), content, file, false);
if (res->IsBoolean() && res->IsTrue()) {
LOG(ERR) << "An error occurred whilst executing the handlePlanChange in "
"JavaScript.";
ok = false; // The heartbeat thread will notice this!
}
// invalidate our local cache, even if an error occurred
ClusterInfo::instance()->flush();
} catch (...) {
}
V8DealerFeature::DEALER->exitContext(context);
return ok;
}
<commit_msg>Use vocbase.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "ServerJob.h"
#include "Basics/MutexLocker.h"
#include "Cluster/ClusterInfo.h"
#include "Cluster/HeartbeatThread.h"
#include "Dispatcher/DispatcherQueue.h"
#include "Logger/Logger.h"
#include "RestServer/DatabaseFeature.h"
#include "V8/v8-utils.h"
#include "V8Server/V8Context.h"
#include "V8Server/V8DealerFeature.h"
#include "VocBase/server.h"
#include "VocBase/vocbase.h"
#include <iostream>
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::rest;
static arangodb::Mutex ExecutorLock;
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new db server job
////////////////////////////////////////////////////////////////////////////////
ServerJob::ServerJob(HeartbeatThread* heartbeat)
: Job("HttpServerJob"),
_heartbeat(heartbeat),
_shutdown(0),
_abandon(false) {}
////////////////////////////////////////////////////////////////////////////////
/// @brief destructs a db server job
////////////////////////////////////////////////////////////////////////////////
ServerJob::~ServerJob() {}
void ServerJob::work() {
LOG(TRACE) << "starting plan update handler";
if (_shutdown != 0) {
return;
}
_heartbeat->setReady();
bool result;
{
// only one plan change at a time
MUTEX_LOCKER(mutexLocker, ExecutorLock);
result = execute();
}
_heartbeat->removeDispatchedJob(result);
}
bool ServerJob::cancel() { return false; }
void ServerJob::cleanup(DispatcherQueue* queue) {
queue->removeJob(this);
delete this;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief execute job
////////////////////////////////////////////////////////////////////////////////
bool ServerJob::execute() {
// default to system database
DatabaseFeature* database = dynamic_cast<DatabaseFeature*>(
ApplicationServer::lookupFeature("Database"));
TRI_vocbase_t* const vocbase = database->vocbase();
if (vocbase == nullptr) {
std::cout << "+++++++++++++ oops ++++++++++++++" << std::endl;
// database is gone
return false;
}
TRI_UseVocBase(vocbase);
TRI_DEFER(TRI_ReleaseVocBase(vocbase));
V8Context* context = V8DealerFeature::DEALER->enterContext(vocbase, true);
if (context == nullptr) {
return false;
}
bool ok = true;
auto isolate = context->_isolate;
try {
v8::HandleScope scope(isolate);
// execute script inside the context
auto file = TRI_V8_ASCII_STRING("handle-plan-change");
auto content =
TRI_V8_ASCII_STRING("require('@arangodb/cluster').handlePlanChange();");
v8::Handle<v8::Value> res = TRI_ExecuteJavaScriptString(
isolate, isolate->GetCurrentContext(), content, file, false);
if (res->IsBoolean() && res->IsTrue()) {
LOG(ERR) << "An error occurred whilst executing the handlePlanChange in "
"JavaScript.";
ok = false; // The heartbeat thread will notice this!
}
// invalidate our local cache, even if an error occurred
ClusterInfo::instance()->flush();
} catch (...) {
}
V8DealerFeature::DEALER->exitContext(context);
return ok;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.