hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9cc4f860ef1ddf0221de8f6b434920da9461e773 | 422 | cpp | C++ | src/server/utils/Constants.cpp | HoriaCool/av-app | c625b3b91ead1cddc8fee22edb8269eec5814b7d | [
"MIT"
] | null | null | null | src/server/utils/Constants.cpp | HoriaCool/av-app | c625b3b91ead1cddc8fee22edb8269eec5814b7d | [
"MIT"
] | null | null | null | src/server/utils/Constants.cpp | HoriaCool/av-app | c625b3b91ead1cddc8fee22edb8269eec5814b7d | [
"MIT"
] | null | null | null | #include "Constants.hpp"
std::unique_ptr<Constants> Constants::constants_ = nullptr;
Constants::Constants():
SERVER_ADDRESS("127.0.0.1"),
SERVER_PORT(7000),
BACKLOG_LISTEN(4096),
EPOLL_SIZE_CREATE(255),
EPOLL_TIMEOUT(3000),
EPOLL_MAX_EVENTS(1000)
{
}
Constants::~Constants()
{
}
Constants& Constants::get_instance()
{
if (constants_ == nullptr) {
constants_.reset(new Constants());
}
return *constants_;
} | 15.62963 | 59 | 0.722749 | HoriaCool |
9cc5a3b775b43e52a20fb51d47b06d4232077193 | 11,765 | cc | C++ | build/X86_MESI_Two_Level/python/swig/core.py.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | build/X86_MESI_Two_Level/python/swig/core.py.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | 1 | 2020-08-20T05:53:30.000Z | 2020-08-20T05:53:30.000Z | build/X86_MESI_Two_Level/python/swig/core.py.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
namespace {
const uint8_t data_m5_internal_core[] = {
120,156,197,89,221,115,220,72,17,111,105,215,107,175,237,245,
71,236,216,249,112,18,229,195,201,230,203,134,186,58,56,184,
144,34,177,157,96,72,236,32,251,72,178,119,160,146,53,227,
181,98,173,180,72,179,73,246,202,174,2,124,197,93,81,60,
243,192,3,15,247,192,3,69,241,0,85,60,240,207,65,119,
143,164,93,59,9,21,206,187,197,218,59,59,234,25,245,244,
116,255,250,99,36,15,210,207,40,126,127,104,1,36,95,155,
0,2,255,13,216,5,8,12,168,153,96,72,19,132,5,47,
6,32,58,13,134,24,128,47,0,106,5,144,5,56,192,78,
17,62,45,64,248,129,158,117,49,159,53,248,182,89,21,28,
64,222,67,176,91,100,146,9,237,97,144,3,80,43,193,211,
112,10,138,114,16,94,12,67,52,8,6,126,66,92,249,89,
123,2,210,59,134,160,86,198,89,23,112,214,48,207,154,226,
89,233,104,153,70,249,14,81,6,49,12,95,160,228,35,32,
70,88,138,81,16,163,220,169,128,168,112,103,12,196,24,119,
198,65,140,131,156,128,109,3,196,4,81,80,216,231,181,73,
144,69,240,79,64,237,4,72,252,159,132,3,3,247,135,164,
41,168,77,129,156,2,127,26,106,211,32,38,153,199,73,158,
125,146,58,226,4,83,102,152,50,67,29,49,197,148,89,166,
204,82,71,76,103,11,158,204,23,60,197,195,167,161,118,26,
36,254,159,210,11,226,58,103,160,118,134,23,60,11,181,179,
220,153,131,218,28,119,206,65,237,28,119,206,67,237,60,223,
127,1,106,23,184,99,65,205,2,49,195,43,95,100,202,69,
234,136,89,166,92,98,202,37,234,136,83,76,185,204,148,203,
212,17,167,153,114,133,41,87,168,35,206,48,101,158,41,243,
212,17,103,153,114,149,41,87,169,35,230,152,114,141,41,215,
168,35,206,49,165,202,148,42,117,196,121,166,92,103,202,117,
234,136,11,76,185,193,148,27,220,193,237,220,132,218,77,238,
220,130,218,45,238,220,134,218,109,238,44,64,109,129,204,189,
81,189,132,120,245,255,141,159,170,129,61,69,240,125,41,227,
196,143,66,199,15,183,35,223,164,241,65,106,8,221,30,53,
5,252,150,240,187,68,48,143,129,49,142,232,65,152,239,35,
7,3,240,30,97,146,226,69,1,78,239,27,116,225,23,96,
15,59,69,216,230,1,191,152,206,216,71,224,78,194,30,114,
31,128,61,166,108,60,13,207,65,81,149,24,153,147,140,76,
61,140,55,211,48,226,18,80,236,1,92,118,141,229,86,36,
247,2,75,167,136,234,120,81,44,171,36,177,42,147,216,141,
102,20,171,192,223,82,67,52,232,132,110,67,58,142,26,198,
139,184,233,198,202,87,184,85,85,196,203,23,145,31,42,218,
87,144,168,216,111,170,74,126,183,211,136,68,43,144,106,4,
41,171,76,89,137,227,40,174,146,34,108,106,20,53,205,221,
58,11,208,160,37,170,36,15,55,201,61,108,22,119,162,134,
196,38,172,183,91,139,117,217,248,240,246,118,123,113,171,229,
7,98,241,217,71,223,113,30,175,108,172,58,155,175,34,231,
145,124,41,131,197,102,91,225,212,197,228,149,95,95,164,221,
44,32,225,4,177,66,130,147,138,180,35,131,166,140,105,135,
201,24,45,99,140,26,83,198,121,163,96,76,26,99,134,95,
202,108,69,122,168,100,182,250,107,106,43,51,13,73,104,46,
35,181,157,9,251,220,33,131,84,201,86,100,162,2,89,6,
247,132,122,175,27,112,96,194,103,5,154,176,143,109,17,35,
136,149,219,105,90,71,16,205,106,16,246,209,152,3,100,170,
207,231,152,213,16,179,50,97,15,91,180,98,17,246,49,76,
225,84,36,97,251,162,12,209,24,24,120,225,151,201,137,141,
16,93,246,217,94,9,173,92,204,173,172,209,73,187,17,126,
76,10,182,9,152,213,225,140,26,37,11,77,87,237,216,149,
204,26,168,38,182,234,90,20,106,195,109,251,161,200,12,169,
161,176,237,7,8,5,155,116,200,220,120,90,16,185,249,52,
178,166,23,68,137,134,19,243,182,199,105,34,205,222,110,50,
27,90,149,228,225,155,133,76,60,130,14,66,74,115,36,9,
136,91,175,225,96,147,159,78,19,187,51,108,252,9,52,127,
9,141,95,69,227,235,222,156,89,49,198,141,53,159,244,230,
13,164,30,91,204,144,240,15,208,218,55,224,133,201,110,182,
199,14,142,179,209,70,236,102,123,236,196,52,122,11,12,101,
166,116,244,99,52,37,81,79,224,61,140,15,4,10,206,189,
67,94,201,150,35,131,15,0,34,80,91,23,81,163,225,192,
54,30,160,59,136,149,73,75,20,161,57,139,204,135,200,240,
123,144,34,228,160,128,8,64,137,208,69,209,229,145,60,131,
235,254,134,161,149,186,61,27,92,237,248,73,244,74,123,46,
245,57,114,109,160,138,158,180,215,183,94,72,79,37,23,144,
240,60,106,89,158,27,134,145,178,92,33,44,87,161,103,111,
181,148,76,44,21,89,243,73,149,140,102,159,201,48,147,243,
107,55,165,205,29,13,20,225,123,10,99,198,20,95,176,19,
38,82,161,201,119,34,145,32,157,110,173,75,101,79,208,29,
164,230,136,5,96,68,56,52,149,150,197,121,228,167,247,50,
9,116,4,41,101,32,73,100,176,205,65,201,11,220,36,113,
72,2,166,51,180,104,215,47,221,160,37,153,123,130,252,80,
32,234,106,25,122,30,107,78,145,224,217,62,89,248,48,10,
69,27,101,241,189,15,104,153,83,12,186,10,198,154,138,49,
131,223,178,113,210,24,68,232,13,26,179,166,87,76,129,150,
167,136,25,218,36,176,133,141,212,200,8,188,3,140,16,85,
147,29,156,229,39,160,218,55,168,71,55,219,87,168,153,167,
230,42,53,215,178,45,246,114,159,149,163,251,92,34,222,38,
111,206,43,164,219,200,125,198,57,228,51,99,93,62,115,64,
216,223,227,196,231,23,186,112,95,160,173,70,35,153,167,176,
95,161,49,209,175,104,50,123,8,230,195,110,124,211,162,107,
246,105,18,227,34,54,215,230,147,107,150,70,147,181,227,38,
86,24,117,32,108,209,160,14,76,4,96,123,142,180,220,5,
209,122,23,68,109,139,102,16,62,237,203,212,20,223,165,230,
235,253,85,115,93,171,249,33,241,30,77,49,52,198,216,25,
49,60,2,0,233,126,48,83,248,6,118,218,179,164,240,110,
77,207,98,162,122,26,206,97,238,97,109,83,250,169,232,244,
195,57,76,151,174,89,100,242,7,178,78,137,116,190,93,128,
153,52,171,36,20,246,155,113,244,186,109,69,219,150,130,76,
164,59,243,201,194,124,242,49,6,7,235,110,71,187,105,32,
136,101,147,28,89,59,54,233,64,249,33,94,19,171,149,215,
158,228,192,207,87,142,163,253,88,23,26,78,154,80,208,16,
172,121,51,211,60,71,50,172,54,40,128,245,92,237,195,185,
218,73,236,39,196,120,152,117,94,48,102,209,115,187,52,78,
223,2,105,156,224,243,37,112,73,109,192,111,129,244,137,90,
75,221,148,61,34,243,138,41,154,78,21,198,158,241,214,44,
98,166,104,55,83,183,71,119,104,86,56,57,164,89,5,75,
134,175,186,98,66,30,245,11,105,217,209,237,21,197,220,43,
216,24,239,21,217,139,135,29,131,20,141,30,68,211,216,5,
116,237,118,229,112,124,225,26,163,192,209,88,245,210,18,67,
154,165,67,171,63,239,216,129,226,231,57,99,218,212,150,103,
80,124,151,154,143,114,39,52,50,90,143,4,185,112,52,224,
117,5,118,71,71,139,103,180,90,145,229,27,31,228,36,179,
212,246,2,201,182,230,15,37,163,251,100,253,101,236,72,60,
117,24,32,57,226,125,193,197,37,181,38,217,240,192,52,232,
212,138,231,83,174,221,233,124,82,2,60,151,250,124,254,76,
15,191,195,96,111,112,18,100,44,102,95,246,126,138,26,135,
34,108,151,154,114,187,106,147,81,243,186,231,254,67,86,187,
19,184,141,45,225,222,21,196,150,120,123,153,191,152,153,156,
19,221,114,18,210,141,119,136,202,151,31,103,242,190,236,121,
73,120,7,248,129,131,150,147,97,44,34,143,93,122,115,71,
90,13,217,216,194,115,221,142,223,180,182,3,183,206,250,46,
164,230,124,72,251,88,5,206,210,122,19,191,215,39,129,105,
222,89,150,213,232,40,205,207,13,20,7,86,138,188,19,250,
128,198,94,238,152,105,240,37,91,17,251,53,182,172,46,132,
9,241,161,124,229,104,48,233,152,74,163,110,179,41,67,97,
127,139,38,126,251,144,95,114,249,227,198,117,61,185,47,214,
117,240,136,235,99,101,87,239,248,228,56,70,199,105,244,203,
55,241,88,212,234,205,182,198,174,57,145,59,233,149,62,200,
200,22,13,51,139,234,90,149,195,26,213,96,92,77,106,95,
198,44,134,71,65,213,214,17,242,67,106,22,169,185,159,107,
159,124,73,72,60,209,200,212,0,106,2,242,66,1,15,45,
42,142,218,152,171,6,153,136,19,29,167,179,151,94,110,232,
251,160,143,165,172,236,146,113,214,40,153,229,82,185,163,236,
220,169,42,29,48,234,186,41,213,186,121,8,80,113,212,120,
236,123,113,244,100,169,19,186,91,77,175,231,98,83,189,210,
130,78,105,248,13,196,165,25,97,20,55,220,160,91,98,251,
71,253,208,50,121,114,251,120,226,82,37,228,39,246,97,253,
246,71,218,31,3,63,55,202,164,85,116,192,190,167,34,204,
72,235,205,7,173,208,83,81,252,102,238,121,12,239,145,123,
210,172,83,76,31,140,166,41,103,16,36,31,56,49,247,136,
18,83,70,40,9,17,246,143,147,132,56,178,247,37,2,252,
26,122,152,123,236,31,244,93,76,251,46,164,165,228,127,203,
59,36,209,122,182,7,197,230,235,170,248,184,224,76,232,52,
184,22,89,94,20,98,132,106,17,18,44,33,183,253,80,10,
235,182,197,5,182,229,39,150,187,133,163,174,167,180,25,142,
20,119,180,63,78,52,187,175,40,151,244,124,231,20,99,15,
186,124,45,47,167,187,77,148,251,154,46,132,223,116,183,83,
111,98,222,193,35,132,27,80,36,238,156,22,232,182,102,159,
50,161,94,236,203,183,132,141,255,119,6,252,93,6,172,42,
69,165,78,6,180,233,180,174,115,30,103,186,78,226,91,207,
21,75,143,30,210,196,119,68,191,246,10,77,122,112,72,232,
94,74,254,19,228,242,43,72,15,149,152,234,204,178,137,201,
206,252,102,201,142,120,96,197,190,222,82,205,150,90,246,227,
78,186,19,120,209,107,209,127,138,92,254,208,5,4,72,63,
57,16,134,115,129,15,224,29,185,78,68,43,175,125,181,20,
72,55,108,53,251,163,97,122,60,240,199,99,136,57,197,234,
75,220,173,64,222,11,130,71,126,162,100,136,145,170,63,194,
110,34,151,63,29,67,216,73,108,130,76,196,101,45,181,232,
143,168,159,32,151,175,225,205,56,240,63,22,103,137,148,194,
118,67,17,53,52,90,139,41,173,231,242,254,12,185,252,249,
120,242,78,106,255,90,10,34,111,247,65,44,127,217,146,161,
215,214,98,83,153,173,124,111,55,121,34,227,13,137,169,168,
247,27,160,35,247,95,142,129,13,46,93,90,241,38,74,217,
31,68,212,144,203,223,142,167,97,29,193,98,223,13,252,207,
201,221,58,239,115,188,166,114,250,17,197,62,69,46,127,63,
158,208,52,163,142,176,216,145,222,110,147,222,14,234,76,247,
89,63,116,252,115,228,242,207,227,137,75,175,8,91,97,174,
229,135,65,180,229,6,137,214,180,201,154,238,185,212,191,64,
46,255,234,72,205,133,215,145,87,198,93,180,82,78,163,52,
173,159,180,181,19,155,40,138,242,120,122,156,229,117,156,238,
183,208,252,186,75,111,146,223,185,101,7,94,170,0,248,121,
235,154,219,208,111,84,120,60,125,50,155,232,199,10,252,126,
143,74,73,251,38,53,183,33,171,21,190,71,13,61,102,231,
115,41,231,3,125,58,102,57,98,89,167,120,27,115,224,242,
94,186,49,163,245,177,251,154,252,140,143,132,124,208,226,243,
11,103,123,69,149,246,209,42,238,16,39,50,97,122,160,194,
163,213,125,95,101,44,239,9,17,243,193,103,53,124,137,182,
19,155,59,177,116,197,234,50,31,211,83,218,82,20,42,249,
90,33,177,210,33,62,193,29,35,133,44,127,223,175,175,132,
194,119,195,251,109,37,215,99,129,235,157,68,242,35,92,37,
144,71,70,56,197,115,2,229,196,196,33,159,227,40,199,34,
246,119,246,31,70,37,27,153,159,121,123,81,163,233,7,114,
217,85,146,67,60,21,244,206,242,202,253,79,30,234,55,172,
116,185,166,175,199,179,235,77,251,222,210,234,218,67,103,125,
173,47,177,73,63,165,211,143,215,239,242,211,244,175,176,153,
160,119,82,67,101,99,144,126,199,241,215,28,53,10,102,193,
24,54,198,140,1,252,157,192,223,73,115,116,162,92,44,151,
113,222,200,204,104,25,199,202,70,185,80,54,243,63,99,102,
36,165,234,63,147,191,239,251,199,247,252,7,74,70,115,161,
};
EmbeddedPython embedded_m5_internal_core(
"m5/internal/core.py",
"/home/hongyu/gem5-fy/build/X86_MESI_Two_Level/python/swig/core.py",
"m5.internal.core",
data_m5_internal_core,
2944,
9238);
} // anonymous namespace
| 58.532338 | 72 | 0.663578 | hoho20000000 |
9cc64805b08b83f1f535f937ca62af845be4bfbb | 7,778 | cpp | C++ | 2_Foundations/2_A*Search/14_whileLoopA*.cpp | ptiwari0664/UdacityCplusplusNanoDegree | e937990ed310e01783d335688bfde9c377a71051 | [
"MIT"
] | 1 | 2020-05-07T18:13:27.000Z | 2020-05-07T18:13:27.000Z | 2_Foundations/2_A*Search/14_whileLoopA*.cpp | ptiwari0664/UdacityCplusplusNanoDegree | e937990ed310e01783d335688bfde9c377a71051 | [
"MIT"
] | null | null | null | 2_Foundations/2_A*Search/14_whileLoopA*.cpp | ptiwari0664/UdacityCplusplusNanoDegree | e937990ed310e01783d335688bfde9c377a71051 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm> // for sort
using std::cout;
using std::ifstream;
using std::istringstream;
using std::string;
using std::vector;
using std::abs;
#ifdef WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
enum class State {kEmpty, kObstacle, kClosed, kPath};
std::string get_working_path() {
char cwd[1024];
if (GetCurrentDir(cwd, sizeof(cwd)) != NULL)
return std::string(cwd);
else
return std::string("");
}
std::string CellString(State cell) {
switch(cell) {
case State::kObstacle: return "⛰️ ";
default: return "0 ";
}
}
void PrintBoard(const std::vector<std::vector<State> > board) {
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[i].size(); j++) {
std::cout << CellString(board[i][j]);
}
std::cout << "\n";
}
}
std::vector<State> parseLine(std::string lineIn){
std::istringstream my_stream(lineIn);
char c;
int n;
std::vector<State> row_vec;
while (my_stream >> n >> c && c==',') {
// std::cout << "That stream was successful:" << n << " " << c << "\n";
if(n==0)
row_vec.push_back(State::kEmpty);
else
row_vec.push_back(State::kObstacle);
}
// std::cout << "The stream has failed." << "\n";
return row_vec;
}
std::vector<std::vector <State> > ReadBoardFile(std::string pathIn){
std::ifstream my_file (pathIn.c_str());
std::vector<std::vector <State> > temp_double{};
if (my_file.is_open()) {
std::cout << "The file stream has been created!" << "\n";
std::string line;
std::vector<State> temp{};
while (getline(my_file, line)) {
// std::cout << line << "\n";
temp = parseLine(line);
temp_double.push_back(temp);
}
my_file.close();
}
else
{
std::cout << "File not found in cwd: " << get_working_path();
}
return temp_double;
}
// Helper Function -> Compare the F values of two cells.
bool Compare(const std::vector<int> node1,const std::vector<int> node2){
int node1_fval = node1.at(2) + node1.at(3);
int node2_fval = node2.at(2) + node2.at(3);
if(node1_fval > node2_fval)
return true;
else
return false;
}
/**
* Sort the two-dimensional vector of ints in descending order.
*/
void CellSort(vector<vector<int>> *v) {
std::sort(v->begin(), v->end(), Compare);
}
/**
* Heuristics Function
* @brief: It calculates manhatten distance
*/
int Heuristic(int x1, int y1, int x2, int y2){
return (abs(x2-x1) + abs(y2-y1));
}
void AddToOpen(const int xIn,const int yIn,const int gIn,const int hIn,
vector<vector<int>> &openNodes,
vector<vector<State> > &grid ){
openNodes.push_back(vector<int>{xIn, yIn, gIn, hIn});
grid[xIn][yIn] = State::kClosed;
}
/**
* Implementation of A* search algorithm
*/
std::vector<std::vector<State>> Search(std::vector<std::vector<State> > boardIn,
const std::vector<int> initIn,
const std::vector<int> goalIn){
std::vector<std::vector<int>> opennodes_={};
// Initialize the starting node.
int x = initIn.at(0);
int y = initIn.at(1);
int g = 0;
int h = Heuristic(x, y, goalIn.at(0),goalIn.at(1));
AddToOpen(x, y, g, h, opennodes_, boardIn);
// TODO: while open vector is non empty
while(!opennodes_.empty()){
// TODO: Sort the open list using CellSort, and get the current node.
CellSort(&opennodes_);
// TODO: Get the x and y values from the current node, and set grid[x][y] to kPath.
auto current = opennodes_.back();
opennodes_.pop_back();
x = current[0];
y = current[1];
boardIn[x][y] = State::kPath;
// TODO: Check if you've reached the goal. If so, return grid.
if (x == goalIn.at(0) && goalIn.at(1)) {
return boardIn;
}
// If we're not done, expand search to current node's neighbors. This step will be completed
// in a later quiz.
// ExpandNeighbors
//} // TODO: End while loop
// We've run out of new nodes to explore and haven't found a path.
}
std::cout << "No path found!" << "\n";
return std::vector<vector<State>>{};
}
// --------------------------------------------------------------------------
// Tests
void TestHeuristic() {
cout << "----------------------------------------------------------" << "\n";
cout << "Heuristic Function Test: ";
if (Heuristic(1, 2, 3, 4) != 4) {
cout << "failed" << "\n";
cout << "\n" << "Heuristic(1, 2, 3, 4) = " << Heuristic(1, 2, 3, 4) << "\n";
cout << "Correct result: 4" << "\n";
cout << "\n";
} else if (Heuristic(2, -1, 4, -7) != 8) {
cout << "TestHeuristic Failed" << "\n";
cout << "\n" << "Heuristic(2, -1, 4, -7) = " << Heuristic(2, -1, 4, -7) << "\n";
cout << "Correct result: 8" << "\n";
cout << "\n";
} else {
cout << "passed" << "\n";
}
cout << "----------------------------------------------------------" << "\n";
}
void TestAddToOpen() {
cout << "----------------------------------------------------------" << "\n";
cout << "AddToOpen Function Test: ";
int x = 3;
int y = 0;
int g = 5;
int h = 7;
vector<vector<int>> open{{0, 0, 2, 9}, {1, 0, 2, 2}, {2, 0, 2, 4}};
vector<vector<int>> solution_open = open;
solution_open.push_back(vector<int>{3, 0, 5, 7});
vector<vector<State>> grid{{State::kClosed, State::kObstacle, State::kEmpty, State::kEmpty, State::kEmpty, State::kEmpty},
{State::kClosed, State::kObstacle, State::kEmpty, State::kEmpty, State::kEmpty, State::kEmpty},
{State::kClosed, State::kObstacle, State::kEmpty, State::kEmpty, State::kEmpty, State::kEmpty},
{State::kEmpty, State::kObstacle, State::kEmpty, State::kEmpty, State::kEmpty, State::kEmpty},
{State::kEmpty, State::kEmpty, State::kEmpty, State::kEmpty, State::kObstacle, State::kEmpty}};
vector<vector<State>> solution_grid = grid;
solution_grid[3][0] = State::kClosed;
AddToOpen(x, y, g, h, open, grid);
if (open != solution_open) {
cout << "failed" << "\n";
cout << "\n";
cout << "Your open list is: " << "\n";
//PrintVectorOfVectors(open);
cout << "Solution open list is: " << "\n";
//PrintVectorOfVectors(solution_open);
cout << "\n";
} else if (grid != solution_grid) {
cout << "failed" << "\n";
cout << "\n";
cout << "Your grid is: " << "\n";
//PrintVectorOfVectors(grid);
cout << "\n";
cout << "Solution grid is: " << "\n";
//PrintVectorOfVectors(solution_grid);
cout << "\n";
} else {
cout << "passed" << "\n";
}
cout << "----------------------------------------------------------" << "\n";
return;
}
// --------------------------------------------------------------------------
/**
* Main Function
*/
int main() {
// TODO: Declare "init" and "goal" arrays with values {0, 0} and {4, 5} respectively.
std::vector<int> initPose = {0,0};
std::vector<int> goalPose = {4,5};
std::string path = "files/1.board";
auto board = ReadBoardFile(path);
PrintBoard(board); //Print intial maze
// TODO: Call Search with "board", "init", and "goal". Store the results in the variable "solution".
std::vector<std::vector <State> > solutionBoard = {};
solutionBoard = Search(board,initPose,goalPose);
// TODO: Change the following line to pass "solution" to PrintBoard.
PrintBoard(solutionBoard);
}
| 30.622047 | 124 | 0.541399 | ptiwari0664 |
9cc915b5421dd5e859b9f1164355948533b6582e | 13,620 | hpp | C++ | LearnMetalCPP/metal-cpp-extensions/MetalKit/MTKView.hpp | cgeffect/CGMetalC | 9ecba0964a963ba8c63dcbb254baeb1b8b6114be | [
"MIT"
] | 1 | 2022-01-17T16:16:24.000Z | 2022-01-17T16:16:24.000Z | LearnMetalCPP/metal-cpp-extensions/MetalKit/MTKView.hpp | cgeffect/CGMetalC | 9ecba0964a963ba8c63dcbb254baeb1b8b6114be | [
"MIT"
] | null | null | null | LearnMetalCPP/metal-cpp-extensions/MetalKit/MTKView.hpp | cgeffect/CGMetalC | 9ecba0964a963ba8c63dcbb254baeb1b8b6114be | [
"MIT"
] | null | null | null | /*
*
* Copyright 2020-2021 Apple Inc.
*
* 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.
*/
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
//
// MetalKit/MTKView.hpp
//
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
#pragma once
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
#include "MetalKitPrivate.hpp"
#include <AppKit/AppKit.hpp>
#include <Metal/Metal.hpp>
#include <QuartzCore/QuartzCore.hpp>
#include <CoreGraphics/CGColorSpace.h>
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
namespace MTK
{
class ViewDelegate
{
public:
virtual ~ViewDelegate() { }
virtual void drawInMTKView( class View* pView ) { }
virtual void drawableSizeWillChange( class View* pView, CGSize size ) { }
};
class View : public NS::Referencing< MTK::View, NS::View >
{
public:
static View* alloc();
View* init( CGRect frame, const MTL::Device* pDevice );
View* init( NS::Coder* pCoder );
void setDevice( const MTL::Device* pDevice );
MTL::Device* device() const;
void setDelegate( const MTK::ViewDelegate* pDelegate );
ViewDelegate* delegate() const;
CA::MetalDrawable* currentDrawable() const;
void setFramebufferOnly( bool framebufferOnly );
bool framebufferOnly() const;
void setDepthStencilAttachmentTextureUsage( MTL::TextureUsage textureUsage );
MTL::TextureUsage depthStencilAttachmentTextureUsage() const;
void setMultisampleColorAttachmentTextureUsage( MTL::TextureUsage textureUsage );
MTL::TextureUsage multisampleColorAttachmentTextureUsage() const;
void setPresentsWithTransaction( bool presentsWithTransaction );
bool presentsWithTransaction() const;
void setColorPixelFormat( MTL::PixelFormat colorPixelFormat );
MTL::PixelFormat colorPixelFormat() const;
void setDepthStencilPixelFormat( MTL::PixelFormat colorPixelFormat );
MTL::PixelFormat depthStencilPixelFormat() const;
void setSampleCount( NS::UInteger sampleCount );
NS::UInteger sampleCount() const;
void setClearColor( MTL::ClearColor clearColor );
MTL::ClearColor clearColor() const;
void setClearDepth( double clearDepth );
double clearDepth() const;
void setClearStencil( uint32_t clearStencil );
uint32_t clearStencil() const;
MTL::Texture* depthStencilTexture() const;
MTL::Texture* multisampleColorTexture() const;
void releaseDrawables() const;
MTL::RenderPassDescriptor* currentRenderPassDescriptor() const;
void setPreferredFramesPerSecond( NS::Integer preferredFramesPerSecond );
NS::Integer preferredFramesPerSecond() const;
void setEnableSetNeedsDisplay( bool enableSetNeedsDisplay );
bool enableSetNeedsDisplay() const;
void setAutoresizeDrawable( bool autoresizeDrawable );
bool autoresizeDrawable();
void setDrawableSize( CGSize drawableSize );
CGSize drawableSize() const;
CGSize preferredDrawableSize() const;
MTL::Device* preferredDevice() const;
void setPaused( bool paused );
bool isPaused() const;
void setColorSpace( CGColorSpaceRef colorSpace );
CGColorSpaceRef colorSpace() const;
void draw();
};
}
_NS_INLINE MTK::View* MTK::View::alloc()
{
return NS::Object::alloc< View >( _MTK_PRIVATE_CLS( MTKView ) );
}
_NS_INLINE MTK::View* MTK::View::init( CGRect frame, const MTL::Device* pDevice )
{
return NS::Object::sendMessage< View* >( this, _MTK_PRIVATE_SEL( initWithFrame_device_ ), frame, pDevice );
}
_NS_INLINE MTK::View* MTK::View::init( NS::Coder* pCoder )
{
return NS::Object::sendMessage< View* >( this, _MTK_PRIVATE_SEL( initWithCoder_ ), pCoder );
}
_NS_INLINE void MTK::View::setDevice( const MTL::Device* pDevice )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setDevice_ ), pDevice );
}
_NS_INLINE MTL::Device* MTK::View::device() const
{
return NS::Object::sendMessage< MTL::Device* >( this, _MTK_PRIVATE_SEL( device ) );
}
_NS_INLINE void MTK::View::setDelegate( const MTK::ViewDelegate* pDelegate )
{
// TODO: Same problem as NS::Application::setDelegate.
// Requires a similar soution
NS::Value* pWrapper = NS::Value::value( pDelegate );
// drawInMTKView:
void (*drawDispatch)( NS::Value*, SEL, id ) = []( NS::Value* pSelf, SEL _cmd, id pMTKView ){
auto pDel = reinterpret_cast< MTK::ViewDelegate* >( pSelf->pointerValue() );
pDel->drawInMTKView( (MTK::View *)pMTKView );
};
class_addMethod( (Class)objc_lookUpClass( "NSValue" ), sel_registerName( "drawInMTKView:" ), (IMP)drawDispatch, "v@:@" );
// mtkView:drawableSizeWillChange:
void (*drawableSizeWillChange)( NS::Value*, SEL, View*, CGSize ) = []( NS::Value* pSelf, SEL, View* pMTKView, CGSize size){
auto pDel = reinterpret_cast< MTK::ViewDelegate* >( pSelf->pointerValue() );
pDel->drawableSizeWillChange( pMTKView, size );
};
#if CGFLOAT_IS_DOUBLE
const char* cbparams = "v@:@{CGSize=dd}";
#else
const char* cbparams = "v@:@{CGSize=ff}";
#endif // CGFLOAT_IS_DOUBLE
class_addMethod( (Class)objc_lookUpClass( "NSValue" ), sel_registerName( "mtkView:drawableSizeWillChange:"), (IMP)drawableSizeWillChange, cbparams );
// This circular reference leaks the wrapper object to keep it around for the dispatch to work.
// It may be better to hoist it to the MTK::View as a member.
objc_setAssociatedObject( (id)pWrapper, "mtkviewdelegate_cpp", (id)pWrapper, OBJC_ASSOCIATION_RETAIN_NONATOMIC );
NS::Object::sendMessage< void >( this, sel_registerName( "setDelegate:" ), pWrapper );
}
_NS_INLINE MTK::ViewDelegate* MTK::View::delegate() const
{
NS::Value* pWrapper = NS::Object::sendMessage< NS::Value* >( this, _MTK_PRIVATE_SEL( delegate ) );
if ( pWrapper )
{
return reinterpret_cast< ViewDelegate* >( pWrapper->pointerValue() );
}
return nullptr;
}
_NS_INLINE CA::MetalDrawable* MTK::View::currentDrawable() const
{
return NS::Object::sendMessage< CA::MetalDrawable* >( this, _MTK_PRIVATE_SEL( currentDrawable ) );
}
_NS_INLINE void MTK::View::setFramebufferOnly( bool framebufferOnly )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setFramebufferOnly_ ), framebufferOnly );
}
_NS_INLINE bool MTK::View::framebufferOnly() const
{
return NS::Object::sendMessage< bool >( this, _MTK_PRIVATE_SEL( framebufferOnly ) );
}
_NS_INLINE void MTK::View::setDepthStencilAttachmentTextureUsage( MTL::TextureUsage textureUsage )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setDepthStencilAttachmentTextureUsage_ ), textureUsage );
}
_NS_INLINE MTL::TextureUsage MTK::View::depthStencilAttachmentTextureUsage() const
{
return NS::Object::sendMessage< MTL::TextureUsage >( this, _MTK_PRIVATE_SEL( depthStencilAttachmentTextureUsage ) );
}
_NS_INLINE void MTK::View::setMultisampleColorAttachmentTextureUsage( MTL::TextureUsage textureUsage )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setMultisampleColorAttachmentTextureUsage_ ), textureUsage );
}
_NS_INLINE MTL::TextureUsage MTK::View::multisampleColorAttachmentTextureUsage() const
{
return NS::Object::sendMessage< MTL::TextureUsage >( this, _MTK_PRIVATE_SEL( multisampleColorAttachmentTextureUsage ) );
}
_NS_INLINE void MTK::View::setPresentsWithTransaction( bool presentsWithTransaction )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setPresentsWithTransaction_ ), presentsWithTransaction );
}
_NS_INLINE bool MTK::View::presentsWithTransaction() const
{
return NS::Object::sendMessage< bool >( this, _MTK_PRIVATE_SEL( presentsWithTransaction ) );
}
_NS_INLINE void MTK::View::setColorPixelFormat( MTL::PixelFormat colorPixelFormat )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setColorPixelFormat_ ), colorPixelFormat );
}
_NS_INLINE MTL::PixelFormat MTK::View::colorPixelFormat() const
{
return NS::Object::sendMessage< MTL::PixelFormat >( this, _MTK_PRIVATE_SEL( colorPixelFormat ) );
}
_NS_INLINE void MTK::View::setDepthStencilPixelFormat( MTL::PixelFormat colorPixelFormat )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setDepthStencilPixelFormat_ ), colorPixelFormat );
}
_NS_INLINE MTL::PixelFormat MTK::View::depthStencilPixelFormat() const
{
return NS::Object::sendMessage< MTL::PixelFormat >( this, _MTK_PRIVATE_SEL( depthStencilPixelFormat ) );
}
_NS_INLINE void MTK::View::setSampleCount( NS::UInteger sampleCount )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setSampleCount_), sampleCount );
}
_NS_INLINE NS::UInteger MTK::View::sampleCount() const
{
return NS::Object::sendMessage< NS::UInteger >( this, _MTK_PRIVATE_SEL( sampleCount ) );
}
_NS_INLINE void MTK::View::setClearColor( MTL::ClearColor clearColor )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setClearColor_ ), clearColor );
}
_NS_INLINE MTL::ClearColor MTK::View::clearColor() const
{
return NS::Object::sendMessage< MTL::ClearColor >( this, _MTK_PRIVATE_SEL( clearColor) );
}
_NS_INLINE void MTK::View::setClearDepth( double clearDepth )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setClearDepth_ ), clearDepth );
}
_NS_INLINE double MTK::View::clearDepth() const
{
return NS::Object::sendMessage< double >( this, _MTK_PRIVATE_SEL( clearDepth ) );
}
_NS_INLINE void MTK::View::setClearStencil( uint32_t clearStencil )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setClearStencil_ ), clearStencil );
}
_NS_INLINE uint32_t MTK::View::clearStencil() const
{
return NS::Object::sendMessage< uint32_t >( this, _MTK_PRIVATE_SEL( clearStencil ) );
}
_NS_INLINE MTL::Texture* MTK::View::depthStencilTexture() const
{
return NS::Object::sendMessage< MTL::Texture* >( this, _MTK_PRIVATE_SEL( depthStencilTexture ) );
}
_NS_INLINE MTL::Texture* MTK::View::multisampleColorTexture() const
{
return NS::Object::sendMessage< MTL::Texture* >( this, _MTK_PRIVATE_SEL( multisampleColorTexture ) );
}
_NS_INLINE void MTK::View::releaseDrawables() const
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( releaseDrawables ) );
}
_NS_INLINE MTL::RenderPassDescriptor* MTK::View::currentRenderPassDescriptor() const
{
return NS::Object::sendMessage< MTL::RenderPassDescriptor* >( this, _MTK_PRIVATE_SEL( currentRenderPassDescriptor ) );
}
_NS_INLINE void MTK::View::setPreferredFramesPerSecond( NS::Integer preferredFramesPerSecond )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setPreferredFramesPerSecond_ ), preferredFramesPerSecond );
}
_NS_INLINE NS::Integer MTK::View::preferredFramesPerSecond() const
{
return NS::Object::sendMessage< NS::Integer >( this, _MTK_PRIVATE_SEL( preferredFramesPerSecond ) );
}
_NS_INLINE void MTK::View::setEnableSetNeedsDisplay( bool enableSetNeedsDisplay )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setEnableSetNeedsDisplay_ ), enableSetNeedsDisplay );
}
_NS_INLINE bool MTK::View::enableSetNeedsDisplay() const
{
return NS::Object::sendMessage< bool >( this, _MTK_PRIVATE_SEL( enableSetNeedsDisplay ) );
}
_NS_INLINE void MTK::View::setAutoresizeDrawable( bool autoresizeDrawable )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setAutoresizeDrawable_ ), autoresizeDrawable );
}
_NS_INLINE bool MTK::View::autoresizeDrawable()
{
return NS::Object::sendMessage< bool >( this, _MTK_PRIVATE_SEL( autoresizeDrawable ) );
}
_NS_INLINE void MTK::View::setDrawableSize( CGSize drawableSize )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setDrawableSize_ ), drawableSize );
}
_NS_INLINE CGSize MTK::View::drawableSize() const
{
return NS::Object::sendMessage< CGSize >( this, _MTK_PRIVATE_SEL( drawableSize ) );
}
_NS_INLINE CGSize MTK::View::preferredDrawableSize() const
{
return NS::Object::sendMessage< CGSize >( this, _MTK_PRIVATE_SEL( preferredDrawableSize ) );
}
_NS_INLINE MTL::Device* MTK::View::preferredDevice() const
{
return NS::Object::sendMessage< MTL::Device* >( this, _MTK_PRIVATE_SEL( preferredDevice ) );
}
_NS_INLINE void MTK::View::setPaused( bool paused )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setPaused_ ), paused );
}
_NS_INLINE bool MTK::View::isPaused() const
{
return NS::Object::sendMessage< bool >( this, _MTK_PRIVATE_SEL( isPaused ) );
}
_NS_INLINE void MTK::View::setColorSpace( CGColorSpaceRef colorSpace )
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( setColorspace_), colorSpace );
}
_NS_INLINE CGColorSpaceRef MTK::View::colorSpace() const
{
return NS::Object::sendMessage< CGColorSpaceRef >( this, _MTK_PRIVATE_SEL( colorspace ) );
}
_NS_INLINE void MTK::View::draw()
{
NS::Object::sendMessage< void >( this, _MTK_PRIVATE_SEL( draw ) );
}
| 34.221106 | 159 | 0.700954 | cgeffect |
9ccc1cb8a4d9aa02f32836fe5d7b8ccd388223a4 | 12,278 | hpp | C++ | src/Enzo/enzo_EnzoEquationOfState.hpp | pgrete/enzo-e | 43b1e33db50dbf00ea115ef35b7a4b17aa735342 | [
"BSD-3-Clause"
] | null | null | null | src/Enzo/enzo_EnzoEquationOfState.hpp | pgrete/enzo-e | 43b1e33db50dbf00ea115ef35b7a4b17aa735342 | [
"BSD-3-Clause"
] | 1 | 2019-04-18T15:39:23.000Z | 2019-04-18T15:39:23.000Z | src/Enzo/enzo_EnzoEquationOfState.hpp | aemerick/enzo-e | 5282aa38593c298a894b52f3ab38ae616aaee43c | [
"MIT",
"BSD-3-Clause"
] | null | null | null | // See LICENSE_CELLO file for license and copyright information
/// @file enzo_EnzoEquationOfState.hpp
/// @author Matthew Abruzzo (matthewabruzzo@gmail.com)
/// @date Thurs May 2 2019
/// @brief [\ref Enzo] Implementation of Enzo's Equation Of State
/// abstract base class. It will be subclassed to implement specific types of
/// equations of state.
//#define RAISE_FLOOR_ERROR
#ifndef ENZO_ENZO_EQUATIONOFSTATE_HPP
#define ENZO_ENZO_EQUATIONOFSTATE_HPP
// Among it's EOS-related responsbilities, EnzoEquationOfState, is responsible
// for the application of the Dual Energy Formalism, (when specified for
// non-barotropic equations of state). Currently, implementations of the Dual
// Energy Formalism are expected to more closely resemble implementations in
// Enzo's Runge-Kutta and MHD with Constrained Transport integrators. These
// exhibit 3 main differences from the original conception (implemented in
// Enzo's ppm integrator):
// 1. internal energy is always used to compute pressure. In the original
// conception, pressure could be computed from total energy or
// internal energy (the decision was independent of synchronization).
// 2. Unlike the original conception, both pressure and internal energy are
// not reconstructed separately. Implementations are currently expected
// to just reconstruct pressure and compute internal energy from the
// reconstructed quantities.
// 3. Synchronization of the total and internal energies is a local
// operation that doesn't require knowledge cell neighbors. In the
// original conception, knowledge of the immediate neighbors had been
// required (thus, each synchronization incremented the stale depth).
//
// To allow synchronization to data from neigboring cells, an additional method
// would be required that indicates the staling_rate of the synchronization.
class EnzoEquationOfState : public PUP::able
{
/// @class EnzoEquationOfState
/// @ingroup Enzo
/// @brief [\ref Enzo] Encapsulates equation of state of fluid
public: // interface
/// Create a new EnzoEquationOfState
EnzoEquationOfState() throw()
{}
~EnzoEquationOfState()
{ }
/// Checks the validity of floor values for the EquationOfState
static void check_floor(enzo_float floor){
// if density = 0, NaNs will arise when converting momentum to velocity
// if pressure = 0, then sound speed will be equal to 0 (possibly causing
// time-step calculation problems)
ASSERT("EnzoEquationOfState::check_floor",
"The density and pressure floors must be greater than 0",
floor > 0);
}
/// Applies primitive floor. This function has been factored out to allow for
/// more easily debugging cases when the floor is unnecesarily applied.
inline static enzo_float apply_floor(const enzo_float value,
const enzo_float floor){
enzo_float out;
#ifdef RAISE_FLOOR_ERROR
ASSERT("EnzoEquationOfState", "Should not need to apply primitive floor.",
value >= floor);
out = value;
#else
out = std::max(value,floor);
#endif
return out;
}
/// CHARM++ PUP::able declaration
PUPable_abstract(EnzoEquationOfState);
/// CHARM++ migration constructor for PUP::able
EnzoEquationOfState (CkMigrateMessage *m)
: PUP::able(m)
{ }
/// CHARM++ Pack / Unpack function
void pup (PUP::er &p)
{
PUP::able::pup(p);
}
/// Converts cell-centered integrable primitives to reconstructable primitives
///
/// @param block holds data to be processed
/// @param integrable_group holds field names of integrable primitive values
/// to convert
/// @param reconstructable_group holds field names of reconstructable
/// primitives where the converted values will be stored. There is
/// expected to be significant overlap with the fields stored in
/// integrable_group
/// @param conserved_passive_group contains the names of the fields holding
/// the passively advected scalars in conserved form (note that while the
/// integrable grouping may also contain groups of passive scalar fields,
/// those fields hold the passive scalars in specific form - which are
/// never used in this calculation). These are provided for Grackle's use
/// @param stale_depth indicates the number of field entries from the
/// outermost field value that the region including "stale" values (need
/// to be refreshed) extends over (0 means there are no "stale" values).
///
/// For a barotropic EOS, this nominally does nothing
/// For a non-barotropic EOS, this computes pressure
virtual void reconstructable_from_integrable
(Block *block, Grouping &integrable_group, Grouping &reconstructable_group,
Grouping &conserved_passive_group, int stale_depth) const = 0;
/// @overload
///
/// Provides stale_depth with the default value of 0
void reconstructable_from_integrable(Block *block,
Grouping &integrable_group,
Grouping &reconstructable_group,
Grouping &conserved_passive_group) const
{
reconstructable_from_integrable(block, integrable_group,
reconstructable_group,
conserved_passive_group, 0);
}
/// Converts reconstructable primitives to integrable primitives
///
/// @param block holds data to be processed
/// @param reconstructable_group holds field names of reconstructable
/// primitive values to convert
/// @param integrable_group holds field names of integrable primitives where
/// the converted values will be stored. There is expected to be
/// significant overlap with the fields stored in reconstructable_group
/// @param stale_depth indicates the number of field entries from the
/// outermost field value that the region including "stale" values (need
/// to be refreshed) extends over (0 means there are no "stale" values).
/// @param reconstructed_axis - parameter that optionally indicates that the
/// reconstructable primitives have been reconstructed at face-centers (if
/// the same grouping is used for multiple axes, then the fields are
/// internally stored as cell-centered rather than an array of
/// face-centered quantites). A value of -1 means that they are
/// cell-centered. A value of 0, 1, or 2 means that the fields were
/// reconstructed and they only contain valid values at x, y, or z faces
///
/// For a barotropic EOS, this nominally does nothing
/// For a non-barotropic EOS, this computes specific total energy from
/// pressure. If using the dual energy formalism, it will also compute the
/// internal energy from the pressure
virtual void integrable_from_reconstructable(Block *block,
Grouping &reconstructable_group,
Grouping &integrable_group,
int stale_depth,
int reconstructed_axis) const =0;
/// @overload
///
/// Provides stale_depth with the default value of 0 and assumes that the
/// fields are cell-centered
void integrable_from_reconstructable(Block *block,
Grouping &reconstructable_group,
Grouping &integrable_group) const
{ integrable_from_reconstructable(block, reconstructable_group,
integrable_group, 0, -1); }
/// Computes thermal pressure from integrable quantities
///
/// @param block holds data to be processed
/// @param integrable_group holds field names of integrable primitives to be
/// used to compute thermal pressure
/// @param pressure_name field name where the computed pressure will be
/// stored
/// @param conserved_passive_group contains the names of the fields holding
/// the passively advected scalars in conserved form (note that while the
/// integrable grouping may also contain groups of passive scalar fields,
/// those fields hold the passive scalars in specific form - which are
/// never used in this calculation). These are provided for Grackle's use
/// @param stale_depth indicates the number of field entries from the
/// outermost field value that the region including "stale" values (need
/// to be refreshed) extends over (0 means there are no "stale" values).
///
/// This nominally should wrap EnzoComputePressure. At the time of writing,
/// (Grackle not yet supported), it doesn't actually wrap EnzoComputePressure
virtual void pressure_from_integrable(Block *block,
Grouping &integrable_group,
std::string pressure_name,
Grouping &conserved_passive_group,
int stale_depth) const =0;
/// Computes thermal pressure from reconstructable quantities (nominally
/// after reconstruction)
///
/// @param block holds data to be processed
/// @param reconstructable_group holds field names of reconstructable
/// primitives to be used to compute thermal pressure
/// @param pressure_name field name where the computed pressure will be
/// stored
/// @param stale_depth indicates the number of field entries from the
/// outermost field value that the region including "stale" values (need
/// to be refreshed) extends over (0 means there are no "stale" values).
/// @param reconstructed_axis - parameter that optionally indicates that the
/// reconstructable primitives have been reconstructed at face-centers (if
/// the same grouping is used for multiple axes, then the fields are
/// internally stored as cell-centered rather than an array of
/// face-centered quantites). A value of -1 means that they are
/// cell-centered. A value of 0, 1, or 2 means that the fields were
/// reconstructed and they only contain valid values at x, y, or z faces
///
/// For a non-barotropic EOS, pressure is considered a reconstructable
/// quantity. In that case, if the pressure field in reconstructable_group
/// matches pressure_name, nothing happens. If the field names do not match,
/// then values are simply copied
virtual void pressure_from_reconstructable(Block *block,
Grouping &reconstructable_group,
std::string pressure_name,
int stale_depth,
int reconstructed_axis) const = 0;
/// returns the density floor
virtual enzo_float get_density_floor() const = 0;
/// returns the thermal pressure floor
virtual enzo_float get_pressure_floor() const = 0;
/// applies the pressure floor to the specific total energy field. If using
/// the dual-energy formalism, it is also applied to the internal energy
/// and it synchronize the internal energy and total energy fields. If the
/// EOS is barotropic, this does nothing.
///
/// @param block holds data to be processed
/// @param integrable_group holds field names of integrable primitives to be
/// that will be used to apply the floor (also contains the field upon
/// which the floor will be applied)
/// @param stale_depth indicates the number of field entries from the
/// outermost field value that the region including "stale" values (need
/// to be refreshed) extends over (0 means there are no "stale" values).
///
/// Unlike the initial conception of the dual-energy formalism (or the
/// version used in Enzo's ppm integrator) this assumes that synchronization
/// is a local operation that doesn't require data about neighboring cells
/// (similar to the implementation of the dual energy formalsim in Enzo's
/// Runge Kutta and MHD with Constrained Transport solvers).
virtual void apply_floor_to_energy_and_sync(Block *block,
Grouping &integrable_group,
int stale_depth) const = 0;
/// returns whether the equation of state is barotropic
virtual bool is_barotropic() const = 0;
/// returns adiabatic index - only needs to be a reasonable number of non-
/// barotropic
virtual enzo_float get_gamma() const = 0;
/// returns isothermal sound speed - only needs to be reasonable for a
/// barotropic EOS
virtual enzo_float get_isothermal_sound_speed() const = 0;
/// returns true if the dual energy formalism is being used
virtual bool uses_dual_energy_formalism() const = 0;
};
#endif /* ENZO_ENZO_EQUATIONOFSTATE_HPP */
| 46.157895 | 80 | 0.719254 | pgrete |
9ccff13ede656bdd76019ce4c9eb11978ac10538 | 9,334 | cpp | C++ | src/appleseed/renderer/kernel/texturing/texturestore.cpp | takaiten/appleseed | 653efbc379fd322b717a3002c64510679de80156 | [
"MIT"
] | 1 | 2019-03-18T09:23:10.000Z | 2019-03-18T09:23:10.000Z | src/appleseed/renderer/kernel/texturing/texturestore.cpp | takaiten/appleseed | 653efbc379fd322b717a3002c64510679de80156 | [
"MIT"
] | 2 | 2015-10-26T16:19:06.000Z | 2015-10-26T16:20:22.000Z | src/appleseed/renderer/kernel/texturing/texturestore.cpp | takaiten/appleseed | 653efbc379fd322b717a3002c64510679de80156 | [
"MIT"
] | null | null | null |
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "texturestore.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/modeling/scene/assembly.h"
#include "renderer/modeling/scene/scene.h"
#include "renderer/modeling/texture/texture.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/image/color.h"
#include "foundation/image/colorspace.h"
#include "foundation/image/tile.h"
#include "foundation/utility/api/apistring.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/foreach.h"
#include "foundation/utility/memory.h"
#include "foundation/utility/statistics.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <algorithm>
#include <string>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// TextureStore class implementation.
//
Dictionary TextureStore::get_params_metadata()
{
Dictionary metadata;
metadata.dictionaries().insert(
"max_size",
Dictionary()
.insert("type", "int")
.insert("default", get_default_size())
.insert("label", "Texture Cache Size")
.insert("help", "Texture cache size in bytes"));
return metadata;
}
size_t TextureStore::get_default_size()
{
return 1024 * 1024 * 1024;
}
TextureStore::TextureStore(
const Scene& scene,
const ParamArray& params)
: m_tile_swapper(scene, params)
, m_tile_cache(m_tile_key_hasher, m_tile_swapper)
{
}
StatisticsVector TextureStore::get_statistics() const
{
Statistics stats = make_single_stage_cache_stats(m_tile_cache);
stats.insert_size("peak size", m_tile_swapper.get_peak_memory_size());
return StatisticsVector::make("texture store statistics", stats);
}
//
// TextureStore::TileSwapper class implementation.
//
namespace
{
// Convert a tile from the sRGB color space to the linear RGB color space.
void convert_tile_srgb_to_linear_rgb(Tile& tile)
{
const size_t pixel_count = tile.get_pixel_count();
const size_t channel_count = tile.get_channel_count();
assert(channel_count == 3 || channel_count == 4);
if (channel_count == 3)
{
for (size_t i = 0; i < pixel_count; ++i)
{
Color3f color;
tile.get_pixel(i, color);
tile.set_pixel(i, fast_srgb_to_linear_rgb(color));
}
}
else
{
for (size_t i = 0; i < pixel_count; ++i)
{
Color4f color;
tile.get_pixel(i, color);
color.rgb() = fast_srgb_to_linear_rgb(color.rgb());
tile.set_pixel(i, color);
}
}
}
// Convert a tile from the CIE XYZ color space to the linear RGB color space.
void convert_tile_ciexyz_to_linear_rgb(Tile& tile)
{
const size_t pixel_count = tile.get_pixel_count();
const size_t channel_count = tile.get_channel_count();
assert(channel_count == 3 || channel_count == 4);
if (channel_count == 3)
{
for (size_t i = 0; i < pixel_count; ++i)
{
Color3f color;
tile.get_pixel(i, color);
tile.set_pixel(i, ciexyz_to_linear_rgb(color));
}
}
else
{
for (size_t i = 0; i < pixel_count; ++i)
{
Color4f color;
tile.get_pixel(i, color);
color.rgb() = ciexyz_to_linear_rgb(color.rgb());
tile.set_pixel(i, color);
}
}
}
}
TextureStore::TileSwapper::TileSwapper(
const Scene& scene,
const ParamArray& params)
: m_scene(scene)
, m_params(params)
, m_memory_size(0)
, m_peak_memory_size(0)
{
gather_assemblies(scene.assemblies());
}
void TextureStore::TileSwapper::load(const TileKey& key, TileRecord& record)
{
// Fetch the texture container.
const TextureContainer& textures =
key.m_assembly_uid == ~UniqueID(0)
? m_scene.textures()
: m_assemblies[key.m_assembly_uid]->textures();
// Fetch the texture.
Texture* texture = textures.get_by_uid(key.m_texture_uid);
if (m_params.m_track_tile_loading)
{
RENDERER_LOG_DEBUG(
"loading tile (" FMT_SIZE_T ", " FMT_SIZE_T ") "
"from texture \"%s\"...",
key.get_tile_x(),
key.get_tile_y(),
texture->get_path().c_str());
}
// Load the tile.
record.m_tile = texture->load_tile(key.get_tile_x(), key.get_tile_y());
record.m_owners = 0;
// Convert the tile to the linear RGB color space.
switch (texture->get_color_space())
{
case ColorSpaceLinearRGB:
break;
case ColorSpaceSRGB:
convert_tile_srgb_to_linear_rgb(*record.m_tile);
break;
case ColorSpaceCIEXYZ:
convert_tile_ciexyz_to_linear_rgb(*record.m_tile);
break;
assert_otherwise;
}
// Track the amount of memory used by the tile cache.
m_memory_size += record.m_tile->get_memory_size();
m_peak_memory_size = max(m_peak_memory_size, m_memory_size);
if (m_params.m_track_store_size)
{
if (m_memory_size > m_params.m_memory_limit)
{
RENDERER_LOG_DEBUG(
"texture store size is %s, exceeding capacity %s by %s",
pretty_size(m_memory_size).c_str(),
pretty_size(m_params.m_memory_limit).c_str(),
pretty_size(m_memory_size - m_params.m_memory_limit).c_str());
}
else
{
RENDERER_LOG_DEBUG(
"texture store size is %s, below capacity %s by %s",
pretty_size(m_memory_size).c_str(),
pretty_size(m_params.m_memory_limit).c_str(),
pretty_size(m_params.m_memory_limit - m_memory_size).c_str());
}
}
}
bool TextureStore::TileSwapper::unload(const TileKey& key, TileRecord& record)
{
// Cannot unload tiles that are still in use.
if (atomic_read(&record.m_owners) > 0)
return false;
// Track the amount of memory used by the tile cache.
const size_t tile_memory_size = record.m_tile->get_memory_size();
assert(m_memory_size >= tile_memory_size);
m_memory_size -= tile_memory_size;
// Fetch the texture container.
const TextureContainer& textures =
key.m_assembly_uid == ~UniqueID(0)
? m_scene.textures()
: m_assemblies[key.m_assembly_uid]->textures();
// Fetch the texture.
Texture* texture = textures.get_by_uid(key.m_texture_uid);
if (m_params.m_track_tile_unloading)
{
RENDERER_LOG_DEBUG(
"unloading tile (" FMT_SIZE_T ", " FMT_SIZE_T ") "
"from texture \"%s\"...",
key.get_tile_x(),
key.get_tile_y(),
texture->get_path().c_str());
}
// Unload the tile.
texture->unload_tile(key.get_tile_x(), key.get_tile_y(), record.m_tile);
// Successfully unloaded the tile.
return true;
}
void TextureStore::TileSwapper::gather_assemblies(const AssemblyContainer& assemblies)
{
for (const_each<AssemblyContainer> i = assemblies; i; ++i)
{
m_assemblies[i->get_uid()] = &*i;
gather_assemblies(i->assemblies());
}
}
//
// TextureStore::TileSwapper::Parameters class implementation.
//
TextureStore::TileSwapper::Parameters::Parameters(const ParamArray& params)
: m_memory_limit(params.get_optional<size_t>("max_size", 256 * 1024 * 1024))
, m_track_tile_loading(params.get_optional<bool>("track_tile_loading", false))
, m_track_tile_unloading(params.get_optional<bool>("track_tile_unloading", false))
, m_track_store_size(params.get_optional<bool>("track_store_size", false))
{
assert(m_memory_limit > 0);
}
} // namespace renderer
| 30.603279 | 86 | 0.649132 | takaiten |
9cd08ea0e6139712c43169afa1280bd8e34e557c | 2,076 | cpp | C++ | src/dawn_native/RenderBundle.cpp | shaoboyan/DawnSamplesForMesa | 90bfef5475ebad0a599013d6456cc8c3f8293703 | [
"Apache-2.0"
] | 8 | 2020-09-15T18:33:13.000Z | 2022-02-24T20:46:13.000Z | src/dawn_native/RenderBundle.cpp | shaoboyan/DawnSamplesForMesa | 90bfef5475ebad0a599013d6456cc8c3f8293703 | [
"Apache-2.0"
] | null | null | null | src/dawn_native/RenderBundle.cpp | shaoboyan/DawnSamplesForMesa | 90bfef5475ebad0a599013d6456cc8c3f8293703 | [
"Apache-2.0"
] | 4 | 2020-02-28T03:22:10.000Z | 2022-01-12T19:25:23.000Z | // Copyright 2019 The Dawn Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "dawn_native/RenderBundle.h"
#include "common/BitSetIterator.h"
#include "dawn_native/Commands.h"
#include "dawn_native/Device.h"
#include "dawn_native/RenderBundleEncoder.h"
namespace dawn_native {
RenderBundleBase::RenderBundleBase(RenderBundleEncoderBase* encoder,
const RenderBundleDescriptor* descriptor,
AttachmentState* attachmentState,
PassResourceUsage resourceUsage)
: ObjectBase(encoder->GetDevice()),
mCommands(encoder->AcquireCommands()),
mAttachmentState(attachmentState),
mResourceUsage(std::move(resourceUsage)) {
}
RenderBundleBase::~RenderBundleBase() {
FreeCommands(&mCommands);
}
// static
RenderBundleBase* RenderBundleBase::MakeError(DeviceBase* device) {
return new RenderBundleBase(device, ObjectBase::kError);
}
RenderBundleBase::RenderBundleBase(DeviceBase* device, ErrorTag errorTag)
: ObjectBase(device, errorTag) {
}
CommandIterator* RenderBundleBase::GetCommands() {
return &mCommands;
}
const AttachmentState* RenderBundleBase::GetAttachmentState() const {
ASSERT(!IsError());
return mAttachmentState.Get();
}
const PassResourceUsage& RenderBundleBase::GetResourceUsage() const {
ASSERT(!IsError());
return mResourceUsage;
}
} // namespace dawn_native
| 33.483871 | 80 | 0.679191 | shaoboyan |
9cd31d21fa504db4067e5db4351274e34071f40c | 2,967 | cc | C++ | tests/test_nat_manager.cc | telosprotocol/xkad | f3591d5544bf26ba486cb4a7f141d9500422206e | [
"MIT"
] | 13 | 2019-09-16T13:34:35.000Z | 2020-01-13T08:06:17.000Z | tests/test_nat_manager.cc | telosprotocol/xkad | f3591d5544bf26ba486cb4a7f141d9500422206e | [
"MIT"
] | null | null | null | tests/test_nat_manager.cc | telosprotocol/xkad | f3591d5544bf26ba486cb4a7f141d9500422206e | [
"MIT"
] | null | null | null | // Copyright (c) 2017-2019 Telos Foundation & contributors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string.h>
#include <string>
#include <gtest/gtest.h>
#include "xpbase/base/top_log.h"
#include "xtransport/udp_transport/udp_transport.h"
#include "xtransport/message_manager/multi_message_handler.h"
#include "xpbase/base/top_utils.h"
#define private public
#define protected public
#include "xkad/src/nat_manager.h"
namespace top {
namespace kadmlia {
namespace test {
class TestNatManager : public testing::Test {
public:
static void SetUpTestCase() {
}
static void TearDownTestCase() {
}
virtual void SetUp() {
}
virtual void TearDown() {
}
};
TEST_F(TestNatManager, NatManagerIntf) {
NatManagerIntf* p = new NatManager();
delete p;
p = nullptr;
}
TEST_F(TestNatManager, All) {
ASSERT_NE(nullptr, NatManagerIntf::Instance());
auto manager = std::make_shared<NatManager>();
auto message_handler = std::make_shared<transport::MultiThreadHandler>();
message_handler->Init();
auto transport = std::make_shared<transport::UdpTransport>();
transport->Start("127.0.0.1", 0, message_handler.get());
auto nat_transport = std::make_shared<transport::UdpTransport>();
nat_transport->Start("127.0.0.1", 0, message_handler.get());
// TODO: need first node
{
bool first_node = true;
const std::set<std::pair<std::string, uint16_t>> boot_endpoints{{"127.0.0.1", 9000}};
ASSERT_TRUE(manager->Start(
first_node,
boot_endpoints,
message_handler.get(),
transport.get(),
nat_transport.get()));
}
{
int32_t nat_type;
ASSERT_TRUE(manager->GetLocalNatType(nat_type));
// ASSERT_EQ(kNatTypeUnknown, nat_type); // TODO:
}
{
manager->SetNatTypeAndNotify(kNatTypePublic);
}
{
transport::protobuf::RoutingMessage message;
base::xpacket_t packet;
manager->HandleNatDetectRequest(message, packet);
manager->HandleNatDetectResponse(message, packet);
manager->HandleNatDetectHandshake2Node(message, packet);
manager->HandleNatDetectHandshake2Boot(message, packet);
manager->HandleNatDetectFinish(message, packet);
}
{
auto message = std::make_shared<transport::protobuf::RoutingMessage>();
auto packet = std::make_shared<base::xpacket_t>();
manager->PushMessage(message, packet);
manager->PushMessage(*message, *packet);
// manager->ThreadProc();
}
{
manager->SendNatDetectRequest("1234", 1234);
manager->SendNatDetectFinish("1234", 1234);
}
manager->OnTimerNatDetectTimeout();
manager->ThreadJoin();
manager->ThreadProc();
manager->Stop();
nat_transport->Stop();
transport->Stop();
TOP_DEBUG("stoping all objectes");
manager = nullptr;
nat_transport = nullptr;
transport = nullptr;
message_handler = nullptr;
SleepUs(2 * 1000 * 1000);
TOP_DEBUG("stopped all objectes");
}
} // namespace test
} // namespace kadmlia
} // namespace top
| 22.823077 | 93 | 0.722952 | telosprotocol |
9cd36d372099aa497b0b43abc866ebbe23ca646e | 2,226 | cc | C++ | rtc_base/memory_usage.cc | na-g/webrtc-upstream-tracking | 41b5296405e2cc37b838c2f7490d02130387b294 | [
"BSD-3-Clause"
] | 1 | 2020-12-23T00:34:11.000Z | 2020-12-23T00:34:11.000Z | rtc_base/memory_usage.cc | na-g/webrtc-upstream-tracking | 41b5296405e2cc37b838c2f7490d02130387b294 | [
"BSD-3-Clause"
] | null | null | null | rtc_base/memory_usage.cc | na-g/webrtc-upstream-tracking | 41b5296405e2cc37b838c2f7490d02130387b294 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2017 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 "rtc_base/memory_usage.h"
#if defined(WEBRTC_LINUX)
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#elif defined(WEBRTC_MAC)
#include <mach/mach.h>
#elif defined(WEBRTC_WIN)
// clang-format off
// clang formating would change include order.
#include <windows.h>
#include <psapi.h> // must come after windows.h
// clang-format on
#endif
#include "rtc_base/logging.h"
namespace rtc {
int64_t GetProcessResidentSizeBytes() {
#if defined(WEBRTC_LINUX)
FILE* file = fopen("/proc/self/statm", "r");
if (file == nullptr) {
RTC_LOG(LS_ERROR) << "Failed to open /proc/self/statm";
return -1;
}
int result = -1;
if (fscanf(file, "%*s%d", &result) != 1) {
fclose(file);
RTC_LOG(LS_ERROR) << "Failed to parse /proc/self/statm";
return -1;
}
fclose(file);
return static_cast<int64_t>(result) * sysconf(_SC_PAGESIZE);
#elif defined(WEBRTC_MAC)
task_basic_info_64 info;
mach_msg_type_number_t info_count = TASK_BASIC_INFO_64_COUNT;
if (task_info(mach_task_self(), TASK_BASIC_INFO_64,
reinterpret_cast<task_info_t>(&info),
&info_count) != KERN_SUCCESS) {
RTC_LOG_ERR(LS_ERROR) << "task_info() failed";
return -1;
}
return info.resident_size;
#elif defined(WEBRTC_WIN)
PROCESS_MEMORY_COUNTERS pmc;
if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)) == 0) {
RTC_LOG_ERR(LS_ERROR) << "GetProcessMemoryInfo() failed";
return -1;
}
return pmc.WorkingSetSize;
#elif defined(WEBRTC_FUCHSIA)
RTC_LOG_ERR(LS_ERROR) << "GetProcessResidentSizeBytes() not implemented";
return 0;
#else
// Not implemented yet.
static_assert(false,
"GetProcessVirtualMemoryUsageBytes() platform support not yet "
"implemented.");
#endif
}
} // namespace rtc
| 29.289474 | 79 | 0.698113 | na-g |
9cd3ab918a8bdb44635faacc224abd556b7ac590 | 7,570 | cpp | C++ | source/tapemanager/holotape_wrapper.cpp | skwirl42/robco-processor | eb92ee0d2402403b36b9b796f80c3d46aaed1442 | [
"MIT"
] | null | null | null | source/tapemanager/holotape_wrapper.cpp | skwirl42/robco-processor | eb92ee0d2402403b36b9b796f80c3d46aaed1442 | [
"MIT"
] | 30 | 2020-12-29T13:25:25.000Z | 2021-09-28T12:03:35.000Z | source/tapemanager/holotape_wrapper.cpp | skwirl42/robco-processor | eb92ee0d2402403b36b9b796f80c3d46aaed1442 | [
"MIT"
] | null | null | null | #include "holotape_wrapper.hpp"
#include <stdio.h>
#include <math.h>
#include <filesystem>
holotape_wrapper::holotape_wrapper(const char *filename) : filename(filename), initialized(false)
{
deck = holotape_deck_init();
if (deck)
{
auto result = holotape_insert(deck, filename);
if (result != HOLO_NO_ERROR)
{
fprintf(stderr, "Failed to insert the tape!\n");
return;
}
initialized = true;
}
else
{
fprintf(stderr, "Failed to initialize the deck!\n");
}
}
holotape_wrapper::~holotape_wrapper()
{
holotape_deck_dispose(deck);
}
void holotape_wrapper::append_file(const char *file_to_append)
{
if (!initialized)
{
fprintf(stderr, "Cannot append file %s as the deck is not properly initialized\n", file_to_append);
return;
}
std::filesystem::path file_path(file_to_append);
if (!std::filesystem::exists(file_path) || !std::filesystem::is_regular_file(file_path))
{
fprintf(stderr, "Cannot append \"%s\" because it either doesn't exist, or isn't a regular file\n", file_to_append);
return;
}
auto filename = file_path.filename();
auto filename_string = filename.string();
char filename_buffer[HOLOTAPE_FILE_NAME_MAX + 1];
strncpy(filename_buffer, (const char *)filename_string.c_str(), HOLOTAPE_FILE_NAME_MAX);
for (int i = filename_string.size(); i <= HOLOTAPE_FILE_NAME_MAX; i++)
{
filename_buffer[i] = 0;
}
if (filename_string.size() > HOLOTAPE_FILE_NAME_MAX)
{
fprintf(stderr, "Appended file name has been truncated to %s\n", filename_buffer);
}
FILE* file = 0;
#if defined(_MSC_VER)
file = fopen(file_to_append, "rb");
#else
file = fopen(file_to_append, "r");
#endif
if (file == 0)
{
fprintf(stderr, "Failed to open \"%s\" for appending\n", file_to_append);
return;
}
// Find the first free block on the tape
holotape_rewind(deck);
bool found_block = false;
holotape_status_t read_status = HOLO_NO_ERROR;
do {
read_status = holotape_read(deck);
if (read_status == HOLO_NO_ERROR && deck->block_buffer.block_structure.filename[0] == 0)
{
found_block = true;
break;
}
else if (read_status != HOLO_NO_ERROR && read_status != HOLO_END_OF_TAPE)
{
break;
}
} while(read_status != HOLO_END_OF_TAPE);
if (found_block)
{
holotape_rewind_block(deck);
}
else if (read_status == HOLO_END_OF_TAPE)
{
fprintf(stderr, "No space left on tape\n");
fclose(file);
return;
}
else
{
fprintf(stderr, "Received an error when trying to find an empty block on the tape\n");
fclose(file);
return;
}
memcpy(deck->block_buffer.block_structure.filename, filename_buffer, HOLOTAPE_FILE_NAME_MAX);
auto current_size = std::filesystem::file_size(file_path);
if (current_size > HOLOTAPE_STRUCTURE_BYTE_COUNT)
{
int block_count = current_size / HOLOTAPE_STRUCTURE_BYTE_COUNT;
if ((block_count * HOLOTAPE_STRUCTURE_BYTE_COUNT) < current_size)
{
block_count++;
}
int blocks_remaining = block_count - 1;
while (current_size > 0)
{
size_t read_size = current_size > HOLOTAPE_STRUCTURE_BYTE_COUNT ? HOLOTAPE_STRUCTURE_BYTE_COUNT : current_size;
deck->block_buffer.block_structure.block_bytes.word = read_size + HOLOTAPE_HEADER_SIZE;
deck->block_buffer.block_structure.remaining_blocks_in_file.word = blocks_remaining--;
auto size_read = fread(deck->block_buffer.block_structure.bytes, 1, read_size, file);
if (size_read == read_size)
{
auto status = holotape_write(deck);
if (status != HOLO_NO_ERROR)
{
fprintf(stderr, "Failed to write the appended block\n");
}
}
else
{
fprintf(stderr, "Could not read all bytes from a file (%s) to be appended\n", filename_string.c_str());
}
memset(deck->block_buffer.block_structure.bytes, 0, HOLOTAPE_STRUCTURE_BYTE_COUNT);
current_size -= size_read;
}
}
else
{
deck->block_buffer.block_structure.block_bytes.word = current_size + HOLOTAPE_HEADER_SIZE;
deck->block_buffer.block_structure.remaining_blocks_in_file.word = 0;
auto size_read = fread(deck->block_buffer.block_structure.bytes, 1, current_size, file);
if (size_read == current_size)
{
auto status = holotape_write(deck);
if (status != HOLO_NO_ERROR)
{
fprintf(stderr, "Failed to write the appended block\n");
}
}
else
{
if (feof(file))
{
fprintf(stderr, "Unexpected EOF\n");
}
fprintf(stderr, "Could not read all bytes from a file (%s) to be appended\n", filename_string.c_str());
}
}
fclose(file);
}
void holotape_wrapper::erase()
{
if (!initialized)
{
fprintf(stderr, "Cannot erase the contents of %s as initialization failed\n", filename);
return;
}
// Just blast HOLOTAPE_MAX_BLOCKS blocks of blankness
fprintf(stdout, "Erasing holotape %s\n", filename);
holotape_rewind(deck);
memset(deck->block_buffer.buffer, 0, sizeof(deck->block_buffer.buffer));
for (int i = 0; i < HOLOTAPE_MAX_BLOCKS; i++)
{
auto write_result = holotape_write(deck);
if (write_result != HOLO_NO_ERROR)
{
fprintf(stderr, "Erasing %s failed on block %d\n", filename, i);
break;
}
}
}
void holotape_wrapper::extract(const char *target_directory)
{
if (!initialized)
{
fprintf(stderr, "Cannot extract the contents of %s as initialization failed\n", filename);
return;
}
fprintf(stdout, "Extracting the contents of holotape %s:\n", filename);
holotape_rewind(deck);
// TODO: Duplicate file names may exist - must handle that
}
void holotape_wrapper::list()
{
if (!initialized)
{
fprintf(stderr, "Cannot list the contents of %s as initialization failed\n", filename);
return;
}
fprintf(stdout, "Listing contents of holotape %s:\n", filename);
holotape_rewind(deck);
char name[HOLOTAPE_FILE_NAME_MAX + 1];
name[HOLOTAPE_FILE_NAME_MAX] = 0;
int file_count = 0;
for (int i = 0; i < HOLOTAPE_MAX_BLOCKS; i++)
{
auto read_status = holotape_read(deck);
if (read_status == HOLO_NO_ERROR)
{
// Print the name of the last block of the file. If multiple files with the same name are found,
// it'll print those all out
if (deck->block_buffer.block_structure.remaining_blocks_in_file.word == 0 && deck->block_buffer.block_structure.filename[0] != 0)
{
strncpy(name, deck->block_buffer.block_structure.filename, HOLOTAPE_FILE_NAME_MAX);
fprintf(stdout, "- %s\n", name);
file_count++;
}
}
else
{
fprintf(stderr, "Read failed when listing the contents of holotape %s\n", filename);
return;
}
}
if (file_count == 0)
{
fprintf(stdout, "\nNo files on holotape\n");
}
}
| 30.401606 | 141 | 0.605945 | skwirl42 |
9cd402151df380cb442cc40f43bb2814d6821329 | 2,576 | hpp | C++ | src/libv/ctrl/stated_sequence.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 2 | 2018-04-11T03:07:03.000Z | 2019-03-29T15:24:12.000Z | src/libv/ctrl/stated_sequence.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | null | null | null | src/libv/ctrl/stated_sequence.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 1 | 2021-06-13T06:39:06.000Z | 2021-06-13T06:39:06.000Z | // Project: libv.ctrl, File: src/libv/ctrl/stated_sequence.hpp, Author: Császár Mátyás [Vader]
#pragma once
// ext
#include <boost/container/small_vector.hpp>
// pro
#include <libv/ctrl/duration.hpp>
#include <libv/ctrl/sequence.hpp>
#include <libv/ctrl/time_point.hpp>
// TODO P1: cleanup state_sequence file
namespace libv {
namespace ctrl {
// -------------------------------------------------------------------------------------------------
struct StatedInput {
InputID id;
DigitalInputAction dia;
bool active = false;
};
struct StatedCombination {
boost::container::small_vector<StatedInput, 3> inputs;
bool active = false;
public:
Combination build_combination() const {
Combination result;
for (const StatedInput& input : inputs)
result.add_input(Input{input.id, input.dia});
return result;
}
};
struct StatedSequence {
boost::container::small_vector<StatedCombination, 2> combinations;
size_t checkpoint = 0; // The index of the currently active combination
bool active = false;
StatedSequence(const Sequence& src_sequence) {
for (const Combination& src_combination : src_sequence.combinations) {
StatedCombination& combination = combinations.emplace_back();
for (const Input& src_input : src_combination.inputs) {
StatedInput& input = combination.inputs.emplace_back();
input.id = src_input.id;
input.dia = src_input.dia;
}
}
}
Sequence rebuild_sequence() const {
Sequence result;
for (const StatedCombination& combination : combinations)
result.add_combination(combination.build_combination());
return result;
}
StatedCombination& previous_combination() noexcept {
assert(checkpoint != 0 && "No previous combination");
return combinations[checkpoint == 0 ? 0 : checkpoint - 1];
}
StatedCombination& current_combination() noexcept {
assert(checkpoint < combinations.size() && "No more current combination");
return combinations[checkpoint];
}
const StatedCombination& current_combination() const noexcept {
assert(checkpoint < combinations.size() && "No more current combination");
return combinations[checkpoint];
}
[[nodiscard]] inline bool is_active() const noexcept {
return active;
}
bool is_last_combination() const noexcept {
return checkpoint + 1 == combinations.size();
}
bool is_sequence() const noexcept {
return combinations.size() > 1;
}
bool in_progress() const noexcept {
return checkpoint != 0;
}
};
// -------------------------------------------------------------------------------------------------
} //namespace ctrl
} //namespace libv
| 26.285714 | 100 | 0.677795 | cpplibv |
9cd5384ffebe398ff84c0b67f449184d6f954446 | 843 | cc | C++ | CMC040/cmcfun/time_code.cc | khandy21yo/aplus | 3b4024a2a8315f5dcc78479a24100efa3c4a6504 | [
"MIT"
] | 1 | 2018-10-17T08:53:17.000Z | 2018-10-17T08:53:17.000Z | CMC040/cmcfun/time_code.cc | khandy21yo/aplus | 3b4024a2a8315f5dcc78479a24100efa3c4a6504 | [
"MIT"
] | null | null | null | CMC040/cmcfun/time_code.cc | khandy21yo/aplus | 3b4024a2a8315f5dcc78479a24100efa3c4a6504 | [
"MIT"
] | null | null | null | //! \file
//! \brief Time Aging Function
//!/
#pragma module time_code "V3.6 Calico"
#include <string>
#include "cmcfun.h"
//!
//! \brief Time Aging Function
//!
//! This function will convert a time into a long integer
//! consisting of the number of seconds (since midnight).
//!
//! \returns Returns a long integer containing the number of seconds
//! (since midnight).
//!
//! Example:
//!
//! GOOF_TIME% = TIME_CODE("002030")
//!--
//!/
long time_code(
const std::string &datum)
//!< The passed time in question in the form HHMMSS, or
//! MMSS or SS.
{
long total_time = 0;
int loop;
/*
* Loop through time string
*/
for (loop = 0; loop < datum.size(); loop += 2)
{
/*
* Add on next increment
*/
total_time = total_time * 60 +
(datum[loop] - '0') * 10 +
(datum[loop + 1] - '0');
}
return total_time;
}
| 18.326087 | 68 | 0.614472 | khandy21yo |
9cd63f254f4a993f3fd8e5663d205e5e4bf20748 | 443 | hpp | C++ | include/ct/platform/export.hpp | purpurina-engine/purpurina-frwk | 1df6fc2768f346fd47fd5cc3dd05daa59dea3726 | [
"MIT"
] | null | null | null | include/ct/platform/export.hpp | purpurina-engine/purpurina-frwk | 1df6fc2768f346fd47fd5cc3dd05daa59dea3726 | [
"MIT"
] | null | null | null | include/ct/platform/export.hpp | purpurina-engine/purpurina-frwk | 1df6fc2768f346fd47fd5cc3dd05daa59dea3726 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////
/// Chronotrix Framework
///
/// @todo Copyright notice
///
////////////////////////////////////////////////////////////
#ifndef _CHRONOTRIX_FRWK_PLATFORM_EXPORTS_HPP_
#define _CHRONOTRIX_FRWK_PLATFORM_EXPORTS_HPP_
#include <ct/config/api_export.hpp>
#ifdef CTFK_PLATFORM_EXPORTS
#define CT_PLATFORM_API CT_API_EXPORT
#else
#define CT_PLATFORM_API CT_API_IMPORT
#endif
#endif
| 22.15 | 60 | 0.591422 | purpurina-engine |
9cd77ea37ca0f3dbd1448fc2ac3a2a2f92ef1499 | 1,730 | inl | C++ | thrust/system/detail/generic/advance.inl | nunnikri/rocThrust | 069dea0640bb6fb7de887b292c9bca194f393ed6 | [
"Apache-2.0"
] | 915 | 2020-09-23T01:50:50.000Z | 2022-03-31T17:06:13.000Z | thrust/system/detail/generic/advance.inl | nunnikri/rocThrust | 069dea0640bb6fb7de887b292c9bca194f393ed6 | [
"Apache-2.0"
] | 364 | 2020-09-23T02:41:57.000Z | 2022-03-31T21:54:53.000Z | thrust/system/detail/generic/advance.inl | arvindcheru/rocThrust | 5c3d926b7ebdf0f9efaadf32294740e0d51a8bf7 | [
"Apache-2.0"
] | 149 | 2020-09-24T11:27:24.000Z | 2022-03-26T11:29:50.000Z | /*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/detail/config.h>
#include <thrust/system/detail/generic/advance.h>
#include <thrust/iterator/iterator_traits.h>
THRUST_NAMESPACE_BEGIN
namespace system
{
namespace detail
{
namespace generic
{
namespace detail
{
__thrust_exec_check_disable__
template<typename InputIterator, typename Distance>
__host__ __device__
void advance(InputIterator& i, Distance n, thrust::incrementable_traversal_tag)
{
while(n)
{
++i;
--n;
} // end while
} // end advance()
__thrust_exec_check_disable__
template<typename InputIterator, typename Distance>
__host__ __device__
void advance(InputIterator& i, Distance n, thrust::random_access_traversal_tag)
{
i += n;
} // end advance()
} // end detail
template<typename InputIterator, typename Distance>
__host__ __device__
void advance(InputIterator& i, Distance n)
{
// dispatch on iterator traversal
thrust::system::detail::generic::detail::advance(i, n,
typename thrust::iterator_traversal<InputIterator>::type());
} // end advance()
} // end namespace detail
} // end namespace generic
} // end namespace system
THRUST_NAMESPACE_END
| 25.820896 | 79 | 0.750867 | nunnikri |
9cd7f1b516e9d24ec6b57203118563ae40d917c0 | 5,954 | cpp | C++ | modules/olynin_a_cross_line_and_plane/src/cross_line_and_plane.cpp | Kirill1210/devtools-course-practice | 8de4a2c327bd77064cdbb318fbbbef072988ccbf | [
"CC-BY-4.0"
] | null | null | null | modules/olynin_a_cross_line_and_plane/src/cross_line_and_plane.cpp | Kirill1210/devtools-course-practice | 8de4a2c327bd77064cdbb318fbbbef072988ccbf | [
"CC-BY-4.0"
] | null | null | null | modules/olynin_a_cross_line_and_plane/src/cross_line_and_plane.cpp | Kirill1210/devtools-course-practice | 8de4a2c327bd77064cdbb318fbbbef072988ccbf | [
"CC-BY-4.0"
] | null | null | null | // Copyright 2022 Olynin Alexander
#include "include/cross_line_and_plane.h"
#include <math.h>
#include <iostream>
#include <string>
Line& Line::operator=(const Line& Tmp) {
this->x_1 = Tmp.x_1;
this->y_1 = Tmp.y_1;
this->z_1 = Tmp.z_1;
this->a_x = Tmp.a_x;
this->a_y = Tmp.a_y;
this->a_z = Tmp.a_z;
return *this;
}
void Line::shwLine() {
std::cout << this->x_1 << " ";
std::cout << this->y_1 << " ";
std::cout << this->z_1 << " ";
std::cout << this->a_x << " ";
std::cout << this->a_y << " ";
std::cout << this->a_z << std::endl;
}
Plane& Plane::operator=(const Plane& Tmp) {
this->a = Tmp.a;
this->b = Tmp.b;
this->c = Tmp.c;
this->d = Tmp.d;
return *this;
}
void Plane::shwPlane() {
std::cout << this->a << " ";
std::cout << this->b << " ";
std::cout << this->c << " ";
std::cout << this->d << std::endl;
}
void Space::calculate_params(Line Sline, Plane Splane, double* numerator,
double* denominator) {
/* The function for calculating t = - (D + A*x_1 + B*y_1 + C*z_1) / (A*a_x +
* B*a_y + C*a_z). Returns the numerator and denominator, that are calculated
* separately. If they are both equal to zero, then the line lies in the
* plane. If the denominator is zero and the numerator is not, then the line
* is parallel to the plane. If they are both nonzero, then the straight line
* intersects the plane.
*/
*numerator = Splane.GetD() + Splane.GetA() * Sline.GetX_1() +
Splane.GetB() * Sline.GetY_1() + Splane.GetC() * Sline.GetZ_1();
*denominator = Splane.GetA() * Sline.GetA_x() +
Splane.GetB() * Sline.GetA_y() +
Splane.GetC() * Sline.GetA_z();
}
int Space::Relationship(Line Sline, Plane Splane) {
/* Returns one of the following values:
* 0 - Line doesn't intersect the Plane
* 1 - Line intersects the Plane and has the one common point with the
* Plane 2 - Line is contained in the Plane and has lots common points with
* the Plane
*/
double numerator, denominator;
calculate_params(Sline, Splane, &numerator, &denominator);
if (denominator == 0) {
if (numerator == 0) {
return 2;
} else {
return 0;
}
} else {
return 1;
}
}
void Space::GetPointOfIntersection(Line Sline, Plane Splane, double* common_x,
double* common_y, double* common_z) {
/* Returns following values:
* In the case of line intersects the plane, returns the coordinates
* of the common point.
* In the case line doesn't intersect the plane throws an error.
*/
int relation = Relationship(Sline, Splane);
if (relation == 0) {
const std::string error_type("Line doesn't intersect the Plane");
throw error_type;
} else if (relation == 2) {
const std::string error_type("The Line lies on the Plane");
throw error_type;
}
double numerator, denomirator;
calculate_params(Sline, Splane, &numerator, &denomirator);
double t = -numerator / denomirator;
*common_x = Sline.GetX_1() + Sline.GetA_x() * t;
*common_y = Sline.GetY_1() + Sline.GetA_y() * t;
*common_z = Sline.GetZ_1() + Sline.GetA_z() * t;
}
bool Space::IsPerpendicular(Line Sline, Plane Splane) {
/* Returns one of the following values:
* 0 - Line isn't perpendicular to the Plane
* 1 - Line is perpendicular to the Plane
*/
if ((Sline.GetA_x() == 0 && Sline.GetA_y() == 0 && Sline.GetA_z() == 0) ||
(Splane.GetA() == 0 && Splane.GetB() == 0 && Splane.GetC() == 0)) {
const std::string error_type("The perpendicularity can't be determined");
throw error_type;
}
if (Relationship(Sline, Splane) == 1) {
double accuracy = 0.000001;
if (Splane.GetA() == 0 || Splane.GetB() == 0 || Splane.GetC() == 0) {
if (Splane.GetA() == 0 && Splane.GetB() == 0) {
if (Sline.GetA_x() == 0 && Sline.GetA_y() == 0) {
return true;
} else {
return false;
}
}
if (Splane.GetA() == 0 && Splane.GetC() == 0) {
if (Sline.GetA_x() == 0 && Sline.GetA_z() == 0) {
return true;
} else {
return false;
}
}
if (Splane.GetB() == 0 && Splane.GetC() == 0) {
if (Sline.GetA_y() == 0 && Sline.GetA_z() == 0) {
return true;
} else {
return false;
}
}
if (Splane.GetA() == 0) {
if (Sline.GetA_x() == 0 && (Sline.GetA_y() / Splane.GetB()) -
(Sline.GetA_z() / Splane.GetC()) <
accuracy) {
return true;
} else {
return false;
}
}
if (Splane.GetB() == 0) {
if (Sline.GetA_y() == 0 && (Sline.GetA_x() / Splane.GetA()) -
(Sline.GetA_z() / Splane.GetC()) <
accuracy) {
return true;
} else {
return false;
}
}
if (Splane.GetC() == 0) {
if (Sline.GetA_z() == 0 && (Sline.GetA_x() / Splane.GetA()) -
(Sline.GetA_y() / Splane.GetB()) <
accuracy) {
return true;
} else {
return false;
}
}
} else {
if ((Sline.GetA_x() / Splane.GetA()) - (Sline.GetA_y() / Splane.GetB()) <
accuracy &&
(Sline.GetA_x() / Splane.GetA()) - (Sline.GetA_z() / Splane.GetC()) <
accuracy) {
return true;
} else {
return false;
}
}
} else {
return false;
}
return false;
}
bool Space::IsOblique(Line Sline, Plane Splane) {
/* Returns one of the following values:
* 0 - Line isn't oblique to the Plane
* 1 - Line is oblique to the Plane
*/
if (Relationship(Sline, Splane) == 1) {
return !IsPerpendicular(Sline, Splane);
} else {
return false;
}
}
| 31.172775 | 79 | 0.536782 | Kirill1210 |
9cdd5dda64b7d63b586e9453793c512ccf6feb30 | 5,457 | cpp | C++ | live555/liveMedia/MPEG1or2DemuxedServerMediaSubsession.cpp | SQZhangOwO/videoMonitoring | d0c5890dc161ad13e84d597faed3ef28ad171645 | [
"MIT"
] | 1 | 2020-05-13T19:04:11.000Z | 2020-05-13T19:04:11.000Z | live555/liveMedia/MPEG1or2DemuxedServerMediaSubsession.cpp | SQZhangOwO/videoMonitoring | d0c5890dc161ad13e84d597faed3ef28ad171645 | [
"MIT"
] | 1 | 2021-06-11T06:11:22.000Z | 2021-06-11T06:11:22.000Z | live555/liveMedia/MPEG1or2DemuxedServerMediaSubsession.cpp | SQZhangOwO/videoMonitoring | d0c5890dc161ad13e84d597faed3ef28ad171645 | [
"MIT"
] | 1 | 2018-03-12T14:18:12.000Z | 2018-03-12T14:18:12.000Z | /**********
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 3 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2018 Live Networks, Inc. All rights reserved.
// A 'ServerMediaSubsession' object that creates new, unicast, "RTPSink"s
// on demand, from a MPEG-1 or 2 demuxer.
// Implementation
#include "MPEG1or2DemuxedServerMediaSubsession.hh"
#include "MPEG1or2AudioStreamFramer.hh"
#include "MPEG1or2AudioRTPSink.hh"
#include "MPEG1or2VideoStreamFramer.hh"
#include "MPEG1or2VideoRTPSink.hh"
#include "AC3AudioStreamFramer.hh"
#include "AC3AudioRTPSink.hh"
#include "ByteStreamFileSource.hh"
MPEG1or2DemuxedServerMediaSubsession* MPEG1or2DemuxedServerMediaSubsession
::createNew(MPEG1or2FileServerDemux& demux, u_int8_t streamIdTag,
Boolean reuseFirstSource, Boolean iFramesOnly, double vshPeriod) {
return new MPEG1or2DemuxedServerMediaSubsession(demux, streamIdTag,
reuseFirstSource,
iFramesOnly, vshPeriod);
}
MPEG1or2DemuxedServerMediaSubsession
::MPEG1or2DemuxedServerMediaSubsession(MPEG1or2FileServerDemux& demux,
u_int8_t streamIdTag, Boolean reuseFirstSource,
Boolean iFramesOnly, double vshPeriod)
: OnDemandServerMediaSubsession(demux.envir(), reuseFirstSource),
fOurDemux(demux), fStreamIdTag(streamIdTag),
fIFramesOnly(iFramesOnly), fVSHPeriod(vshPeriod) {
}
MPEG1or2DemuxedServerMediaSubsession::~MPEG1or2DemuxedServerMediaSubsession() {
}
FramedSource* MPEG1or2DemuxedServerMediaSubsession
::createNewStreamSource(unsigned clientSessionId, unsigned& estBitrate) {
FramedSource* es = NULL;
do {
es = fOurDemux.newElementaryStream(clientSessionId, fStreamIdTag);
if (es == NULL) break;
if ((fStreamIdTag&0xF0) == 0xC0 /*MPEG audio*/) {
estBitrate = 128; // kbps, estimate
return MPEG1or2AudioStreamFramer::createNew(envir(), es);
} else if ((fStreamIdTag&0xF0) == 0xE0 /*video*/) {
estBitrate = 500; // kbps, estimate
return MPEG1or2VideoStreamFramer::createNew(envir(), es,
fIFramesOnly, fVSHPeriod);
} else if (fStreamIdTag == 0xBD /*AC-3 audio*/) {
estBitrate = 192; // kbps, estimate
return AC3AudioStreamFramer::createNew(envir(), es, 0x80);
} else { // unknown stream type
break;
}
} while (0);
// An error occurred:
Medium::close(es);
return NULL;
}
RTPSink* MPEG1or2DemuxedServerMediaSubsession
::createNewRTPSink(Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic,
FramedSource* inputSource) {
if ((fStreamIdTag&0xF0) == 0xC0 /*MPEG audio*/) {
return MPEG1or2AudioRTPSink::createNew(envir(), rtpGroupsock);
} else if ((fStreamIdTag&0xF0) == 0xE0 /*video*/) {
return MPEG1or2VideoRTPSink::createNew(envir(), rtpGroupsock);
} else if (fStreamIdTag == 0xBD /*AC-3 audio*/) {
// Get the sampling frequency from the audio source; use it for the RTP frequency:
AC3AudioStreamFramer* audioSource
= (AC3AudioStreamFramer*)inputSource;
return AC3AudioRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic,
audioSource->samplingRate());
} else {
return NULL;
}
}
void MPEG1or2DemuxedServerMediaSubsession
::seekStreamSource(FramedSource* inputSource, double& seekNPT, double /*streamDuration*/, u_int64_t& /*numBytes*/) {
float const dur = duration();
unsigned const size = fOurDemux.fileSize();
unsigned absBytePosition = dur == 0.0 ? 0 : (unsigned)((seekNPT/dur)*size);
// "inputSource" is a 'framer'
// Flush its data, to account for the seek that we're about to do:
if ((fStreamIdTag&0xF0) == 0xC0 /*MPEG audio*/) {
MPEG1or2AudioStreamFramer* framer = (MPEG1or2AudioStreamFramer*)inputSource;
framer->flushInput();
} else if ((fStreamIdTag&0xF0) == 0xE0 /*video*/) {
MPEG1or2VideoStreamFramer* framer = (MPEG1or2VideoStreamFramer*)inputSource;
framer->flushInput();
}
// "inputSource" is a filter; its input source is the original elem stream source:
MPEG1or2DemuxedElementaryStream* elemStreamSource
= (MPEG1or2DemuxedElementaryStream*)(((FramedFilter*)inputSource)->inputSource());
// Next, get the original source demux:
MPEG1or2Demux& sourceDemux = elemStreamSource->sourceDemux();
// and flush its input buffers:
sourceDemux.flushInput();
// Then, get the original input file stream from the source demux:
ByteStreamFileSource* inputFileSource
= (ByteStreamFileSource*)(sourceDemux.inputSource());
// Note: We can make that cast, because we know that the demux was originally
// created from a "ByteStreamFileSource".
// Do the appropriate seek within the input file stream:
inputFileSource->seekToByteAbsolute(absBytePosition);
}
float MPEG1or2DemuxedServerMediaSubsession::duration() const {
return fOurDemux.fileDuration();
}
| 40.422222 | 116 | 0.743266 | SQZhangOwO |
9ce0c211dcdfb32c6cdeefeaf897a99448b654a1 | 2,895 | cc | C++ | modules/csa/src/csa.cc | dgcl/motis | 6b134f80aa3b6445f710418962f1fed9cffda3a0 | [
"MIT"
] | null | null | null | modules/csa/src/csa.cc | dgcl/motis | 6b134f80aa3b6445f710418962f1fed9cffda3a0 | [
"MIT"
] | null | null | null | modules/csa/src/csa.cc | dgcl/motis | 6b134f80aa3b6445f710418962f1fed9cffda3a0 | [
"MIT"
] | null | null | null | #include "motis/csa/csa.h"
#include "motis/core/access/time_access.h"
#include "motis/core/journey/journeys_to_message.h"
#include "motis/module/context/get_schedule.h"
#include "motis/csa/build_csa_timetable.h"
#include "motis/csa/csa_query.h"
#include "motis/csa/csa_statistics.h"
#include "motis/csa/csa_timetable.h"
#include "motis/csa/csa_to_journey.h"
#include "motis/csa/error.h"
#include "motis/csa/run_csa_search.h"
using namespace motis::module;
using namespace motis::routing;
namespace motis::csa {
csa::csa() : module("CSA", "csa") {
param(bridge_zero_duration_connections_, "bridge",
"Bridge zero duration connections (required for GPU CSA)");
param(add_footpath_connections_, "expand_footpaths",
"Add CSA connections representing connection and footpath");
}
csa::~csa() = default;
void csa::init(motis::module::registry& reg) {
timetable_ =
build_csa_timetable(get_sched(), bridge_zero_duration_connections_,
add_footpath_connections_);
reg.register_op("/csa", [&](msg_ptr const& msg) {
#ifdef MOTIS_AVX
return route(msg, implementation_type::CPU_SSE);
#else
return route(msg, implementation_type::CPU);
#endif
});
reg.register_op("/csa/cpu", [&](msg_ptr const& msg) {
return route(msg, implementation_type::CPU);
});
#ifdef MOTIS_AVX
reg.register_op("/csa/cpu/sse", [&](msg_ptr const& msg) {
return route(msg, implementation_type::CPU_SSE);
});
#endif
#ifdef MOTIS_CUDA
reg.register_op("/csa/gpu", [&](msg_ptr const& msg) {
return route(msg, implementation_type::GPU);
});
#endif
}
csa_timetable const* csa::get_timetable() const { return timetable_.get(); }
motis::module::msg_ptr csa::route(motis::module::msg_ptr const& msg,
implementation_type impl_type) const {
auto const req = motis_content(RoutingRequest, msg);
auto const& sched = get_schedule();
auto const response = run_csa_search(
sched, *timetable_, csa_query(sched, req), req->search_type(), impl_type);
message_creator mc;
mc.create_and_finish(
MsgContent_RoutingResponse,
CreateRoutingResponse(
mc,
mc.CreateVector(std::vector<flatbuffers::Offset<Statistics>>{
to_fbs(mc, to_stats_category("csa", response.stats_))}),
mc.CreateVector(utl::to_vec(response.journeys_,
[&](auto const& cj) {
return to_connection(
mc, csa_to_journey(sched, cj));
})),
motis_to_unixtime(sched, response.searched_interval_.begin_),
motis_to_unixtime(sched, response.searched_interval_.end_),
mc.CreateVector(std::vector<flatbuffers::Offset<DirectConnection>>()))
.Union());
return make_msg(mc);
}
} // namespace motis::csa
| 34.058824 | 80 | 0.658031 | dgcl |
9ce402dad80d51f856883a9649414936fe274cc3 | 1,609 | hpp | C++ | src/cpuclassifier/CPULearnColumn.hpp | przestaw/nbc4gpu | 641945ac3974ec9df78a4217ebd133576791c58a | [
"BSD-3-Clause"
] | null | null | null | src/cpuclassifier/CPULearnColumn.hpp | przestaw/nbc4gpu | 641945ac3974ec9df78a4217ebd133576791c58a | [
"BSD-3-Clause"
] | null | null | null | src/cpuclassifier/CPULearnColumn.hpp | przestaw/nbc4gpu | 641945ac3974ec9df78a4217ebd133576791c58a | [
"BSD-3-Clause"
] | null | null | null | //
// Created by mateusz
//
#ifndef NBC4CPU_CPULEARNCOLUMN_HPP
#define NBC4CPU_CPULEARNCOLUMN_HPP
#include <vector>
namespace nbc4cpu {
template <typename ValueType> class CPULearnColumn {
public:
using AvgAndVariance = std::pair<ValueType, ValueType>;
/**
* Constructor
* @param col column of values
*/
CPULearnColumn(std::vector<ValueType> &col);
/**
* Calculates or returns average and standard deviation
* @return average and standard deviation
*/
AvgAndVariance operator()();
private:
AvgAndVariance learn();
bool resSet_;
AvgAndVariance result_;
std::vector<ValueType> &col_;
};
template <typename ValueType>
CPULearnColumn<ValueType>::CPULearnColumn(std::vector<ValueType> &col)
: resSet_(false), col_(col) {}
template <typename ValueType>
typename CPULearnColumn<ValueType>::AvgAndVariance
CPULearnColumn<ValueType>::operator()() {
if (!resSet_) {
result_ = learn();
resSet_ = true;
}
return result_;
}
template <typename ValueType>
typename CPULearnColumn<ValueType>::AvgAndVariance
CPULearnColumn<ValueType>::learn() {
if (col_.empty()) {
throw(" column summary");
}
ValueType avg = 0.0;
for (auto &n : col_) avg += n;
avg = avg / static_cast<ValueType>(col_.size());
ValueType variance = 0.0;
for (auto &n : col_) variance += ((n - avg) * (n - avg));
variance = variance * (1 / static_cast<ValueType>(col_.size() - 1));
return std::make_pair(avg, variance);
}
} // namespace nbc4cpu
#endif // NBC4CPU_CPULEARNCOLUMN_HPP
| 24.014925 | 72 | 0.658794 | przestaw |
9ce627d9e7fdf46b35e06d64c97141b4fdb25a16 | 1,427 | cpp | C++ | Hashing/Check_Array_Subset.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 19 | 2018-12-02T05:59:44.000Z | 2021-07-24T14:11:54.000Z | Hashing/Check_Array_Subset.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | null | null | null | Hashing/Check_Array_Subset.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 13 | 2019-04-25T16:20:00.000Z | 2021-09-06T19:50:04.000Z | //given two arrays ,check whether arr2 is a subset of arr1 or not
/*
1.can be done using binary search also by sorting the arrays and looking for
elements of arr2 in arr1,but it won't handle the case when the arr2 has duplicates
2. using hash
*/
#include<iostream>
#include<vector>
#include<map>
using namespace std;
/*
scan each element and make a hash table keeping the frequency of each element
of arr1 .Start scanning arr2 and for each element found in the hash table check
if the count of that element is greater than equal to 1 or not,if no
that means arr1 doens't conatin that duplicate
*/
bool isSubset(vector<int> arr1, vector<int> arr2){
//create a hash table
map<int, int> h;
for(int i = 0; i<arr1.size(); i++){
//insert each new element in the hash table
if(h.find(arr1[i]) == h.end()){
h[arr1[i]] = 1;
}
//if there is already an instance ,increment its count to signify there is
//a duplicate
else
h[arr1[i]]++;
}
//now starting looking for elements of arr2 in arr1
for (int i = 0; i < arr2.size(); ++i)
{
//when element is not available
if(h.find(arr2[i]) == h.end())
return false;
//when the frequency of current element in arr1 is lesser than in arr2
else if(h[arr2[i]] <= 0)
return false;
else
h[arr2[i]]--;
}
return true;
}
main(){
vector<int> arr1 = {11, 1, 13, 21, 3, 7};
vector<int> arr2 = {11, 11, 3, 7, 1};
cout<<isSubset(arr1,arr2);
}
| 26.425926 | 85 | 0.671338 | susantabiswas |
9ce6cb9e955f3ad60906cdbc93fa03049068f883 | 28,565 | cpp | C++ | sources/fplog.cpp | kr0st/fplog2 | 8e660a2a2f9dbd87a336c2af6cb13a44435acafa | [
"BSD-2-Clause"
] | null | null | null | sources/fplog.cpp | kr0st/fplog2 | 8e660a2a2f9dbd87a336c2af6cb13a44435acafa | [
"BSD-2-Clause"
] | null | null | null | sources/fplog.cpp | kr0st/fplog2 | 8e660a2a2f9dbd87a336c2af6cb13a44435acafa | [
"BSD-2-Clause"
] | null | null | null | #include <fplog.h>
#include <utils.h>
#include <map>
#include <thread>
#include <queue>
#include <sprot.h>
#include <udp_transport.h>
#include <mutex>
#include <queue_controller.h>
#include <rapidjson/rapidjson.h>
#include <rapidjson/allocators.h>
#include <rapidjson/writer.h>
#include <stdarg.h>
#include <piped_sequence.h>
#include <fplog_exceptions.h>
namespace fplog
{
typedef std::map<std::string, std::shared_ptr<Filter_Base>> Filter_Map;
const char* Prio::emergency = "emergency"; //system is unusable
const char* Prio::alert = "alert"; //action must be taken immediately
const char* Prio::critical = "critical"; //critical conditions
const char* Prio::error = "error"; //error conditions
const char* Prio::warning = "warning"; //warning conditions
const char* Prio::notice = "notice"; //normal but significant condition
const char* Prio::info = "info"; //informational
const char* Prio::debug = "debug"; //debug/trace info for developers
const char* Facility::system = "system"; //message from some system component
const char* Facility::user = "user"; //message from user-level component
const char* Facility::security = "security"; //security or authorization related message
const char* Facility::fplog = "fplog"; //message from fplog directly, could inform about log system malfunction
const char* Message::Mandatory_Fields::facility = "facility"; //according to syslog
const char* Message::Mandatory_Fields::priority = "priority"; //same as severity for syslog
const char* Message::Mandatory_Fields::timestamp = "timestamp"; //ISO8601 timestamp with milliseconds and timezone
const char* Message::Mandatory_Fields::hostname = "hostname"; //IP address or any specific sending device id, added by fplogd before sending
const char* Message::Mandatory_Fields::appname = "appname"; //name of application or service using this logging library, needed for fplog IPC
const char* Message::Optional_Fields::text = "text"; //log message text
const char* Message::Optional_Fields::component = "component"; //package name or any logical software component
const char* Message::Optional_Fields::class_name = "class"; //class name if OOP is used
const char* Message::Optional_Fields::method = "method"; //method of a given class if OOP is used or just a function name
const char* Message::Optional_Fields::module = "module"; //source file name
const char* Message::Optional_Fields::line = "line"; //line number in the above mentioned source file
const char* Message::Optional_Fields::options = "options"; //for example encryption method + options when encryption is in use
const char* Message::Optional_Fields::encrypted = "encrypted"; //true/false, if true then Text field contains encrypted JSON values -
//the rest of the log message including the decrypted version of Text field
const char* Message::Optional_Fields::file = "file"; //filename when sending a file inside the log message
const char* Message::Optional_Fields::/*the*/blob = "blob"; //used when attaching binary fields to the message, resulting JSON object will look
//like this: "blob_name":{ "blob":"xckjhKJSHDKDSdJKShdsdsgr=" }
//where "xckjhKJSHDKDSdJKShdsdsgr=" is base64 encoded binary object
const char* Message::Optional_Fields::warning = "warning"; //contains warning for the user in case there was an issue with this specific log message
const char* Message::Optional_Fields::sequence = "sequence"; //sequence number that allows to prevent duplicate messages and also to tell
//which message was first even if timestamps are the same
const char* Message::Optional_Fields::batch = "batch"; //indicator if this message is actually a container for N other shorter messages
Message::Message(const char* prio, const char *facility, const char* format, ...):
msg_()
{
msg_.SetObject();
set_timestamp();
set(Mandatory_Fields::priority, prio ? prio : Prio::debug);
set(Mandatory_Fields::facility, facility ? facility : Facility::user);
if (format)
{
va_list aptr;
va_start(aptr, format);
char buffer[2048] = {0};
vsnprintf(buffer, sizeof(buffer) - 1, format, aptr);
set_text(buffer);
va_end(aptr);
}
}
Message& Message::set_module(std::string& module)
{
return set(Optional_Fields::module, module);
}
Message& Message::set_module(const char* module)
{
return set(Optional_Fields::module, module);
}
Message& Message::set_line(int line)
{
return set(Optional_Fields::line, line);
}
Message& Message::set_text(std::string& text)
{
return set(Optional_Fields::text, text);
}
Message& Message::set_text(const char* text)
{
return set(Optional_Fields::text, text);
}
Message& Message::set_class(std::string& class_name)
{
return set(Optional_Fields::class_name, class_name);
}
Message& Message::set_class(const char* class_name)
{
return set(Optional_Fields::class_name, class_name);
}
Message& Message::set_method(std::string& method)
{
return set(Optional_Fields::method, method);
}
Message& Message::set_method(const char* method)
{
return set(Optional_Fields::method, method);
}
Message& Message::set_sequence(unsigned long long int sequence)
{
return set(Optional_Fields::sequence, sequence);
}
Message& Message::add(rapidjson::Document& param)
{
if (is_valid(param))
{
auto it(msg_.FindMember(param.MemberBegin()->name));
if (it != msg_.MemberEnd())
it->value.CopyFrom(param.MemberBegin()->value, msg_.GetAllocator());
else
msg_.AddMember(param.MemberBegin()->name, param.MemberBegin()->value, msg_.GetAllocator());
}
return *this;
}
Message& Message::add(const std::string& json)
{
rapidjson::GenericDocument<rapidjson::UTF8<>> parsed;
std::unique_ptr<char[]> to_parse(new char[json.size() + 1]);
parsed.ParseInsitu(to_parse.get());
return add(parsed);
}
Message& Message::add_batch(rapidjson::Document& batch)
{
auto it(batch.MemberBegin());
if ((it == batch.MemberEnd()) || !it->value.IsArray())
THROW(fplog::exceptions::Incorrect_Parameter);
it->name.SetString(fplog::Message::Optional_Fields::batch, static_cast<unsigned int>(strlen(fplog::Message::Optional_Fields::batch)));
validate_params_ = false;
try
{
add(batch);
}
catch(std::exception& e)
{
validate_params_ = true;
throw e;
}
catch(fplog::exceptions::Generic_Exception& e)
{
validate_params_ = true;
throw e;
}
validate_params_ = true;
return *this;
}
bool Message::has_batch()
{
for (auto it(msg_.MemberBegin()); it != msg_.MemberEnd(); ++it)
{
if (it->value.IsArray() && (strcmp(it->name.GetString(), fplog::Message::Optional_Fields::batch)) == 0)
return true;
}
return false;
}
rapidjson::Document Message::get_batch()
{
auto it(msg_.FindMember(fplog::Message::Optional_Fields::batch));
rapidjson::Document d;
d.SetObject();
if (it != msg_.MemberEnd())
d.AddMember(it->name, it->value, d.GetAllocator());
return d;
}
bool Message::is_valid(rapidjson::Document& param)
{
if (!validate_params_)
return true;
for(auto it(param.MemberBegin()); it != param.MemberEnd(); ++it)
{
rapidjson::Document d;
d.AddMember(it->name, it->value, d.GetAllocator());
if (!is_valid(d))
return false;
std::string lowercased(it->name.GetString());
generic_util::trim(lowercased);
std::transform(lowercased.begin(), lowercased.end(), lowercased.begin(), ::tolower);
bool invalid(std::find(reserved_names_.begin(), reserved_names_.end(), lowercased) != reserved_names_.end());
if (invalid)
{
set(Optional_Fields::warning, "Some parameters are missing from this log message because they were malformed.");
return false;
}
}
return true;
}
std::string Message::as_string() const
{
rapidjson::StringBuffer s;
rapidjson::Writer<rapidjson::StringBuffer> w(s);
msg_.Accept(w);
return s.GetString();
}
rapidjson::Document Message::as_json()
{
rapidjson::Document msg;
msg.CopyFrom(msg_, msg.GetAllocator());
return msg;
}
Message::Message(const rapidjson::Document& msg)
{
msg_.CopyFrom(msg, msg_.GetAllocator());
}
Message::Message(const std::string& msg)
{
msg_.Parse(msg.c_str());
}
Message& Message::add(const char* param_name, std::string& param)
{
std::string trimmed(param_name);
trim(trimmed);
rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>> v(param.c_str(), msg_.GetAllocator());
rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>> name(trimmed.c_str(), msg_.GetAllocator());
if (param_name && is_valid(trimmed.c_str(), param))
{
auto it(msg_.FindMember(trimmed.c_str()));
if (it == msg_.MemberEnd())
msg_.AddMember(name, v, msg_.GetAllocator());
else
it->value = v;
}
return *this;
}
Message& Message::add(const char* param_name, const char* param)
{
std::string trimmed(param_name);
trim(trimmed);
rapidjson::GenericValue<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> v(param, msg_.GetAllocator());
rapidjson::GenericValue<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> name(trimmed.c_str(), msg_.GetAllocator());
if (param_name && is_valid(trimmed.c_str(), param))
{
auto it(msg_.FindMember(trimmed.c_str()));
if (it == msg_.MemberEnd())
msg_.AddMember(name, v, msg_.GetAllocator());
else
it->value = v;
}
return *this;
}
bool Priority_Filter::should_pass(const Message& msg)
{
Message& m = const_cast<Message&>(msg);
auto it(m.as_json().FindMember(fplog::Message::Mandatory_Fields::priority));
if (it != m.as_json().MemberEnd())
return (prio_.find(it->value.GetString()) != prio_.end());
return false;
}
void Priority_Filter::construct_numeric()
{
prio_numeric_.push_back(Prio::emergency);
prio_numeric_.push_back(Prio::alert);
prio_numeric_.push_back(Prio::critical);
prio_numeric_.push_back(Prio::error);
prio_numeric_.push_back(Prio::warning);
prio_numeric_.push_back(Prio::notice);
prio_numeric_.push_back(Prio::info);
prio_numeric_.push_back(Prio::debug);
}
void Priority_Filter::add_all_above(const char* prio, bool inclusive)
{
//std::cout << "--> add_all_above(" << prio << ")" << std::endl;
std::vector<std::string>::reverse_iterator it(prio_numeric_.rbegin());
for (; it != prio_numeric_.rend(); ++it)
{
//cout << "it = " << *it << std::endl;
if (it->find(std::string(prio)) != std::string::npos)
break;
}
if (it == prio_numeric_.rend())
{
//std::cout << "prio not found!!!" << std::endl;
return;
}
prio_.clear();
if (inclusive)
prio_.insert(prio);
++it;
for (; it != prio_numeric_.rend(); ++it)
{
prio_.insert(*it);
}
}
void Priority_Filter::add_all_below(const char* prio, bool inclusive)
{
std::vector<std::string>::iterator it(prio_numeric_.begin());
for (; it != prio_numeric_.end(); ++it)
if (it->find(std::string(prio)) != std::string::npos)
break;
if (it == prio_numeric_.end())
return;
prio_.clear();
if (inclusive)
prio_.insert(prio);
++it;
for (; it != prio_numeric_.end(); ++it)
{
prio_.insert(*it);
}
}
Message& Message::set_timestamp(const char* timestamp)
{
if (timestamp)
return set(Mandatory_Fields::timestamp, timestamp);
return set(Mandatory_Fields::timestamp, generic_util::get_iso8601_timestamp().c_str());
}
Message& Message::set_file(const char* name)
{
if (name)
return set(Optional_Fields::file, name);
return *this;
}
File::File(const char* prio, const char* name, const void* content, size_t size):
msg_(prio, Facility::user)
{
if (!name)
return;
msg_.set_file(name);
if (size > 0)
{
size_t dest_len = generic_util::base64_encoded_length(size);
buf_ = new char [dest_len + 1];
memset(buf_, 0, dest_len + 1);
generic_util::base64_encode(content, size, buf_, dest_len);
msg_.set_text(buf_);
delete [] buf_;
}
}
Message& Message::add_binary(const char* param_name, const void* buf, size_t buf_size_bytes)
{
if (!param_name || !buf || !buf_size_bytes)
return *this;
rapidjson::Document d;
rapidjson::Document value;
d.SetObject();
value.SetObject();
size_t dest_len = generic_util::base64_encoded_length(buf_size_bytes);
char* base64 = new char [dest_len + 1];
memset(base64, 0, dest_len + 1);
generic_util::base64_encode(buf, buf_size_bytes, base64, dest_len);
rapidjson::Value real_value;
real_value.SetString(base64, static_cast<unsigned int>(strlen(base64)), value.GetAllocator());
value.AddMember(rapidjson::StringRef("blob"), real_value, value.GetAllocator());
d.AddMember(rapidjson::StringRef(param_name), value, d.GetAllocator());
delete [] base64;
validate_params_ = false;
try
{
add(d);
}
catch(std::exception& e)
{
validate_params_ = true;
throw e;
}
catch(fplog::exceptions::Generic_Exception& e)
{
validate_params_ = true;
throw e;
}
validate_params_ = true;
return *this;
}
void Message::one_time_init()
{
reserved_names_.push_back(Mandatory_Fields::appname);
reserved_names_.push_back(Mandatory_Fields::facility);
reserved_names_.push_back(Mandatory_Fields::hostname);
reserved_names_.push_back(Mandatory_Fields::priority);
reserved_names_.push_back(Mandatory_Fields::timestamp);
reserved_names_.push_back(Optional_Fields::blob);
reserved_names_.push_back(Optional_Fields::class_name);
reserved_names_.push_back(Optional_Fields::component);
reserved_names_.push_back(Optional_Fields::encrypted);
reserved_names_.push_back(Optional_Fields::file);
reserved_names_.push_back(Optional_Fields::method);
reserved_names_.push_back(Optional_Fields::line);
reserved_names_.push_back(Optional_Fields::module);
reserved_names_.push_back(Optional_Fields::options);
reserved_names_.push_back(Optional_Fields::text);
reserved_names_.push_back(Optional_Fields::warning);
reserved_names_.push_back(Optional_Fields::sequence);
reserved_names_.push_back(Optional_Fields::batch);
}
std::vector<std::string> Message::reserved_names_;
/************************* fplog client API implementation *************************/
FPLOG_API std::vector<std::string> g_test_results_vector;
class FPLOG_API Fplog_Impl
{
public:
Fplog_Impl():
appname_("noname"),
inited_(false),
own_transport_(true),
test_mode_(false),
stopping_(false),
transport_(0),
mq_reader_(0),
async_logging_(true)
{
Message::one_time_init();
}
~Fplog_Impl()
{
stop_reading_queue();
mq_reader_->join();
std::lock_guard<std::recursive_mutex> lock(mutex_);
delete mq_reader_;
if (inited_ && own_transport_)
delete transport_;
}
const char* get_facility()
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
return thread_log_settings_table_[std::hash<std::thread::id>()(std::this_thread::get_id())].facility_.c_str();
}
void openlog(const char* facility, Filter_Base* filter)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (facility)
thread_log_settings_table_[std::hash<std::thread::id>()(std::this_thread::get_id())].facility_ = facility;
else
return;
if (filter)
add_filter(filter);
}
void initlog(const char* appname, sprot::Basic_Transport_Interface* transport, bool async_logging)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
async_logging_ = async_logging;
if (!mq_reader_)
mq_reader_ = new std::thread(&Fplog_Impl::mq_reader, this);
if (inited_)
return;
if (appname)
appname_ = appname;
else
return;
if (transport)
{
own_transport_ = false;
transport_ = transport;
}
else
{
THROW(fplog::exceptions::Transport_Missing);
}
}
void closelog()
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
std::map<unsigned long long int, Logger_Settings>::iterator it = thread_log_settings_table_.find(std::hash<std::thread::id>()(std::this_thread::get_id()));
if (it != thread_log_settings_table_.end())
thread_log_settings_table_.erase(it);
}
static std::string strip_timestamp_and_sequence(std::string input)
{
generic_util::remove_json_field(fplog::Message::Mandatory_Fields::timestamp, input);
generic_util::remove_json_field(fplog::Message::Optional_Fields::sequence, input);
return input;
}
void write(const Message& m)
{
Message msg(m);
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (stopping_)
return;
msg.set(Message::Mandatory_Fields::appname, appname_);
//std::cout << "logging message: " << msg.as_string() << std::endl;
if (passed_filters(msg))
{
//std::cout << "message passed filters OK" << std::endl;
msg.set_sequence(sequence_number::read_sequence_number());
if (test_mode_)
g_test_results_vector.push_back(strip_timestamp_and_sequence(msg.as_string()));
else
{
if (async_logging_)
{
//std::cout << "message got inside the queue" << std::endl;
mq_.push(new std::string(msg.as_string()));
}
else
{
int send_retries = 12;
while (send_retries > 0)
{
try
{
//std::cout << "preparing to write message directly" << std::endl;
std::string str(msg.as_string());
transport_->write(str.c_str(), str.size(), 400);
break;
}
catch(fplog::exceptions::Generic_Exception& e)
{
//std::cout << "message not sent, err = " << e.what() << std::endl;
send_retries--;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
}
}
}
}
void add_filter(Filter_Base* filter)
{
if (!filter)
return;
std::string filter_id(filter->get_id());
generic_util::trim(filter_id);
if (filter_id.empty())
return;
std::lock_guard<std::recursive_mutex> lock(mutex_);
Logger_Settings settings = Logger_Settings(thread_log_settings_table_[std::hash<std::thread::id>()(std::this_thread::get_id())]);
settings.filter_id_ptr_map[filter_id] = std::shared_ptr<Filter_Base>(filter);
thread_log_settings_table_[std::hash<std::thread::id>()(std::this_thread::get_id())] = settings;
}
void remove_filter(Filter_Base* filter)
{
if (!filter)
return;
std::lock_guard<std::recursive_mutex> lock(mutex_);
Logger_Settings settings(thread_log_settings_table_[std::hash<std::thread::id>()(std::this_thread::get_id())]);
std::string filter_id(filter->get_id());
if (!filter_id.empty())
{
settings.filter_id_ptr_map.erase(settings.filter_id_ptr_map.find(filter_id));
thread_log_settings_table_[std::hash<std::thread::id>()(std::this_thread::get_id())] = settings;
}
}
Filter_Base* find_filter(const char* filter_id)
{
if (!filter_id)
return 0;
std::string filter_id_trimmed(filter_id);
generic_util::trim(filter_id_trimmed);
if (filter_id_trimmed.empty())
return 0;
std::lock_guard<std::recursive_mutex> lock(mutex_);
Logger_Settings settings(thread_log_settings_table_[std::hash<std::thread::id>()(std::this_thread::get_id())]);
std::map<std::string, std::shared_ptr<Filter_Base>>::iterator found(settings.filter_id_ptr_map.find(filter_id_trimmed));
if (found != settings.filter_id_ptr_map.end())
return found->second.get();
return 0;
}
void set_test_mode(bool mode);
void wait_until_queues_are_empty();
void change_config(const sprot::Params& config);
private:
//Shared_Sequence_Number sequence_;
bool inited_;
bool own_transport_;
bool test_mode_;
volatile bool stopping_;
bool async_logging_;
std::string appname_;
Queue_Controller mq_;
std::thread* mq_reader_;
struct Logger_Settings
{
Logger_Settings() : facility_(Facility::user) {}
Filter_Map filter_id_ptr_map;
std::string facility_;
};
std::map<unsigned long long int, Logger_Settings> thread_log_settings_table_;
std::recursive_mutex mutex_;
std::recursive_mutex mq_reader_mutex_;
sprot::Basic_Transport_Interface* transport_;
void stop_reading_queue()
{
stopping_ = true;
std::lock_guard<std::recursive_mutex> lock(mq_reader_mutex_);
}
void mq_reader()
{
std::lock_guard<std::recursive_mutex> queue_lock(mq_reader_mutex_);
while(!stopping_)
{
std::string* str = 0;
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (!mq_.empty() && transport_)
{
str = mq_.front();
mq_.pop();
}
}
std::unique_ptr<std::string> str_ptr(str);
retry:
if (stopping_)
return;
try
{
if (str)
transport_->write(str->c_str(), str->size(), 400);
else
{
if (stopping_)
return;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
catch(fplog::exceptions::Generic_Exception)
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
goto retry;
}
}
}
bool passed_filters(const Message& msg)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
Logger_Settings settings(thread_log_settings_table_[std::hash<std::thread::id>()(std::this_thread::get_id())]);
//std::cout << "--> passed_filters" << std::endl;
if (settings.filter_id_ptr_map.size() == 0)
{
//std::cout << "FALSE <-- passed_filters (no filters in map)" << std::endl;
return false;
}
bool should_pass = true;
for (std::map<std::string, std::shared_ptr<Filter_Base>>::iterator it = settings.filter_id_ptr_map.begin(); it != settings.filter_id_ptr_map.end(); ++it)
{
should_pass = (should_pass && it->second->should_pass(msg));
if (!should_pass)
break;
}
//std::cout << should_pass << " <-- passed_filters" << std::endl;
return should_pass;
}
};
FPLOG_API Fplog_Impl* g_fplog_impl = 0;
std::recursive_mutex g_api_mutex;
void write(const Message& msg)
{
std::lock_guard<std::recursive_mutex> lock(g_api_mutex);
if (!g_fplog_impl)
return;
g_fplog_impl->write(msg);
}
void initlog(const char* appname, sprot::Basic_Transport_Interface* transport, bool async_logging)
{
std::lock_guard<std::recursive_mutex> lock(g_api_mutex);
if (!g_fplog_impl)
g_fplog_impl = new Fplog_Impl();
return g_fplog_impl->initlog(appname, transport, async_logging);
}
void shutdownlog()
{
std::lock_guard<std::recursive_mutex> lock(g_api_mutex);
delete g_fplog_impl;
g_fplog_impl = 0;
}
void openlog(const char* facility, Filter_Base* filter)
{
std::lock_guard<std::recursive_mutex> lock(g_api_mutex);
if (!g_fplog_impl)
return;
return g_fplog_impl->openlog(facility, filter);
}
void closelog()
{
std::lock_guard<std::recursive_mutex> lock(g_api_mutex);
if (!g_fplog_impl)
return;
return g_fplog_impl->closelog();
}
const char* get_facility()
{
std::lock_guard<std::recursive_mutex> lock(g_api_mutex);
if (!g_fplog_impl)
return "";
return g_fplog_impl->get_facility();
}
void add_filter(Filter_Base* filter)
{
std::lock_guard<std::recursive_mutex> lock(g_api_mutex);
if (!g_fplog_impl)
return;
return g_fplog_impl->add_filter(filter);
}
void remove_filter(Filter_Base* filter)
{
std::lock_guard<std::recursive_mutex> lock(g_api_mutex);
if (!g_fplog_impl)
return;
return g_fplog_impl->remove_filter(filter);
}
Filter_Base* find_filter(const char* filter_id)
{
std::lock_guard<std::recursive_mutex> lock(g_api_mutex);
if (!g_fplog_impl)
return 0;
return g_fplog_impl->find_filter(filter_id);
}
void change_config(const sprot::Params& config)
{
std::lock_guard<std::recursive_mutex> lock(g_api_mutex);
if (!g_fplog_impl)
return;
return g_fplog_impl->change_config(config);
}
FPLOG_API void Fplog_Impl::set_test_mode(bool mode)
{
g_test_results_vector.clear(); test_mode_ = mode;
}
FPLOG_API void Fplog_Impl::wait_until_queues_are_empty()
{
int counter = 0;
while (counter < 5)
{
bool q1_empty = true;
{
std::lock_guard<std::recursive_mutex> lock_q1(mutex_);
q1_empty = mq_.empty();
}
if (q1_empty)
{
counter++;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
else
{
counter = 0;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
}
FPLOG_API void Fplog_Impl::change_config(const sprot::Params& config)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
mq_.apply_config(config);
}
#ifdef __linux__
#include <cxxabi.h>
FPLOG_API ::std::string demangle_cpp_name(const char* mangled)
{
int status;
char *realname = abi::__cxa_demangle(mangled, 0, 0, &status);
::std::string res(realname);
free(realname);
return res;
}
#endif
#ifdef __APPLE__
#include <cxxabi.h>
FPLOG_API ::std::string demangle_cpp_name(const char* mangled)
{
int status;
char *realname = abi::__cxa_demangle(mangled, 0, 0, &status);
::std::string res(realname);
free(realname);
return res;
}
#endif
};
| 29.418126 | 167 | 0.605496 | kr0st |
9cecb7651ce9e872fd8bfc6866d52ea763cdbb60 | 3,490 | cc | C++ | src/tests/test_ewaldstatefile.cc | rubengerritsen/xtp | af4db53ca99853280d0e2ddc7f3c41bce8ae6e91 | [
"Apache-2.0"
] | null | null | null | src/tests/test_ewaldstatefile.cc | rubengerritsen/xtp | af4db53ca99853280d0e2ddc7f3c41bce8ae6e91 | [
"Apache-2.0"
] | null | null | null | src/tests/test_ewaldstatefile.cc | rubengerritsen/xtp | af4db53ca99853280d0e2ddc7f3c41bce8ae6e91 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 <libint2/initialize.h>
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE ewald_test
// Standard includes
#include <fstream>
// Third party includes
#include <boost/test/unit_test.hpp>
// Local VOTCA includes
#include "votca/xtp/aomatrix.h"
#include "votca/xtp/background.h"
#include "votca/xtp/convergenceacc.h"
#include "votca/xtp/orbitals.h"
// VOTCA includes
#include <votca/tools/eigenio_matrixmarket.h>
using namespace votca::xtp;
using votca::Index;
BOOST_AUTO_TEST_SUITE(ewald_calculations)
BOOST_AUTO_TEST_CASE(writereadcycle_statefile) {
libint2::initialize();
// Create a fake polar background
std::vector<PolarSegment> backgroundSegments;
PolarSegment seg0("segment0", 0);
PolarSegment seg1("segment1", 1);
seg0.push_back(PolarSite(0, "H", Eigen::Vector3d(1, 1, 1)));
seg0.push_back(PolarSite(1, "H", Eigen::Vector3d(1, 1, 1.5)));
seg1.push_back(PolarSite(0, "H", Eigen::Vector3d(3, 3, 3)));
seg1.push_back(PolarSite(1, "H", Eigen::Vector3d(2.7, 3, 3.7)));
backgroundSegments.push_back(seg0);
backgroundSegments.push_back(seg1);
// Other necessary input
Logger log;
EwaldOptions options;
options.alpha = 1;
options.k_cutoff = 1;
options.r_cutoff = 1;
options.shape = Shape::cube;
options.sharpness = 0.39;
// Create background
Background bg(log, 5 * Eigen::Matrix3d::Identity(), options,
backgroundSegments);
// Write to state file
bg.writeToStateFile("testFile.hdf5");
// Read From state file
Background bg2(log);
bg2.readFromStateFile("testFile.hdf5");
// Compare
bool background_is_equal = (bg == bg2);
BOOST_CHECK(background_is_equal);
libint2::finalize();
}
BOOST_AUTO_TEST_CASE(energy_calc_NaCl){
Index cry_l = 16;
Index N = cry_l * cry_l * cry_l;
Index l = (double)cry_l / 2.0;
std::vector<PolarSegment> backgroundSegments;
for (Index i = 0; i < N; ++i) {
PolarSegment seg("seg", i);
// note element type doesn't matter for the calcul
seg.push_back(PolarSite(0, "H", ))
Index ix = i % cry_l;
Index iy = (i % (cry_l * cry_l)) / cry_l;
Index iz = i / (cry_l * cry_l);
xyz[i][0] = (double)(ix)*0.5;
xyz[i][1] = (double)(iy)*0.5;
xyz[i][2] = (double)(iz)*0.5;
charges[i] = (((ix + iy + iz) % 2) ? 1.0 : -1.0);
}
EwaldOptions options;
options.alpha = 4;
options.r_cutoff = 1.9;
options.k_cutoff = 30;
options.shape = Shape::cube;
options.sharpness = 0.39;
Eigen::Matrix3d cellMatrix;
cellMatrix << l, 0, 0, 0, l, 0, 0, 0, l;
Logger log;
Background bg(log, cellMatrix, options, backgroundSegments);
double energy = bg.interactionEnergy();
}
BOOST_AUTO_TEST_CASE(energy_eval_with_induced_dipoles){
BOOST_CHECK(true);
}
BOOST_AUTO_TEST_CASE(field_eval_with_induced_dipoles){
BOOST_CHECK(true);
}
BOOST_AUTO_TEST_CASE(background_polarization){
BOOST_CHECK(true);
}
BOOST_AUTO_TEST_SUITE_END()
| 26.439394 | 75 | 0.698854 | rubengerritsen |
9ced9cf926b41bafa76ec58895b34753294f1f6a | 2,893 | cpp | C++ | DFNs/PointCloudTransformation/CartesianSystemTransform.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 7 | 2019-02-26T15:09:50.000Z | 2021-09-30T07:39:01.000Z | DFNs/PointCloudTransformation/CartesianSystemTransform.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | null | null | null | DFNs/PointCloudTransformation/CartesianSystemTransform.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 1 | 2020-12-06T12:09:05.000Z | 2020-12-06T12:09:05.000Z | /**
* @author Alessandro Bianco
*/
/**
* @addtogroup DFNs
* @{
*/
#include "CartesianSystemTransform.hpp"
#include <Converters/PointCloudToPclPointCloudConverter.hpp>
#include <Converters/MatToVisualPointFeatureVector3DConverter.hpp>
#include <Macros/YamlcppMacros.hpp>
#include <Errors/Assert.hpp>
#include <stdlib.h>
#include <fstream>
using namespace Converters;
using namespace VisualPointFeatureVector3DWrapper;
using namespace PointCloudWrapper;
using namespace PoseWrapper;
using namespace BaseTypesWrapper;
namespace CDFF
{
namespace DFN
{
namespace PointCloudTransformation
{
CartesianSystemTransform::CartesianSystemTransform()
{
parameters = DEFAULT_PARAMETERS;
parametersHelper.AddParameter<bool>("GeneralParameters", "Placeholder", parameters.placeholder, DEFAULT_PARAMETERS.placeholder);
configurationFilePath = "";
}
CartesianSystemTransform::~CartesianSystemTransform()
{
}
void CartesianSystemTransform::configure()
{
parametersHelper.ReadFile(configurationFilePath);
ValidateParameters();
}
void CartesianSystemTransform::process()
{
AffineTransform inversionTransform = ConvertCloudPoseToInversionTransform(inPose);
ClearPoints(outTransformedPointCloud);
int numberOfPoints = GetNumberOfPoints(inPointCloud);
for(int pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
{
Point3D point;
point.x = GetXCoordinate(inPointCloud, pointIndex);
point.y = GetYCoordinate(inPointCloud, pointIndex);
point.z = GetZCoordinate(inPointCloud, pointIndex);
Point3D transformedPoint = TransformPoint(point, inversionTransform);
AddPoint(outTransformedPointCloud, transformedPoint.x, transformedPoint.y, transformedPoint.z);
}
}
const CartesianSystemTransform::CartesianSystemTransformOptionsSet CartesianSystemTransform::DEFAULT_PARAMETERS
{
/*.placeholder =*/ false
};
CartesianSystemTransform::AffineTransform CartesianSystemTransform::ConvertCloudPoseToInversionTransform(const Pose3D& cloudPoseInSystem)
{
Eigen::Quaternion<float> rotation(GetWRotation(cloudPoseInSystem), GetXRotation(cloudPoseInSystem), GetYRotation(cloudPoseInSystem), GetZRotation(cloudPoseInSystem));
Eigen::Translation<float, 3> translation( GetXPosition(cloudPoseInSystem), GetYPosition(cloudPoseInSystem), GetZPosition(cloudPoseInSystem));
AffineTransform affineTransform = translation * rotation;
return affineTransform;
}
Point3D CartesianSystemTransform::TransformPoint(const Point3D& point, const AffineTransform& affineTransform)
{
Eigen::Vector3f eigenPoint(point.x, point.y, point.z);
Eigen::Vector3f eigenTransformedPoint = affineTransform * eigenPoint;
Point3D transformedPoint;
transformedPoint.x = eigenTransformedPoint.x();
transformedPoint.y = eigenTransformedPoint.y();
transformedPoint.z = eigenTransformedPoint.z();
return transformedPoint;
}
void CartesianSystemTransform::ValidateParameters()
{
}
}
}
}
/** @} */
| 28.087379 | 167 | 0.809886 | H2020-InFuse |
9cf0a1abb81676d79b9818b37977d376ee916340 | 3,705 | cpp | C++ | src/game/client/gameui/BenchmarkDialog.cpp | DeadZoneLuna/csso-src | 6c978ea304ee2df3796bc9c0d2916bac550050d5 | [
"Unlicense"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | src/game/client/gameui/BenchmarkDialog.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | null | null | null | src/game/client/gameui/BenchmarkDialog.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "BenchmarkDialog.h"
#include "EngineInterface.h"
#include "BasePanel.h"
#include "tier1/KeyValues.h"
#include "tier1/convar.h"
#include "filesystem.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/CheckButton.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CBenchmarkDialog::CBenchmarkDialog(vgui::Panel *parent, const char *name) : BaseClass(parent, name)
{
Button *button = new Button(this, "RunButton", "RunButton");
button->SetCommand(new KeyValues("RunBenchmark"));
SetSizeable(false);
SetDeleteSelfOnClose(true);
LoadControlSettings("Resource/BenchmarkDialog.res");
}
//-----------------------------------------------------------------------------
// Purpose: Launches the benchmark
//-----------------------------------------------------------------------------
void CBenchmarkDialog::RunBenchmark()
{
// apply settings
BasePanel()->ApplyOptionsDialogSettings();
// launch the map
engine->ClientCmd_Unrestricted("disconnect\n");
engine->ClientCmd_Unrestricted("wait\n");
engine->ClientCmd_Unrestricted("wait\n");
engine->ClientCmd_Unrestricted("maxplayers 1\n");
engine->ClientCmd_Unrestricted("progress_enable\n");
engine->ClientCmd_Unrestricted("map test_hardware\n");
// close this dialog
Close();
}
//-----------------------------------------------------------------------------
// Purpose: Displays benchmark results
//-----------------------------------------------------------------------------
class CBenchmarkResultsDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CBenchmarkResultsDialog, vgui::Frame );
public:
CBenchmarkResultsDialog( vgui::Panel *parent, const char *name ) : BaseClass( parent, name )
{
SetTitle("#GameUI_BenchmarkResults_Title", true);
SetDeleteSelfOnClose(true);
SetSizeable(false);
m_pUploadCheck = new CheckButton( this, "UploadCheck", "#GameUI_BenchmarkResults_UploadNow" );
LoadControlSettings("Resource/BenchmarkResultsDialog.res");
m_pUploadCheck->SetSelected( true );
MoveToCenterOfScreen();
}
virtual void Activate()
{
BaseClass::Activate();
KeyValues *kv = new KeyValues( "Benchmark" );
if ( kv->LoadFromFile( g_pFullFileSystem, "results/results.txt", "MOD" ) )
{
// get the framerate
char szFrameRate[32];
Q_snprintf( szFrameRate, sizeof(szFrameRate), "%.2f", kv->GetFloat("framerate") );
SetDialogVariable( "framerate", szFrameRate );
}
else
{
Close();
}
kv->deleteThis();
}
void OnKeyCodePressed( KeyCode code )
{
if ( code == KEY_XBUTTON_B )
{
Close();
}
else
{
BaseClass::OnKeyCodePressed(code);
}
}
private:
virtual void OnClose()
{
if ( m_pUploadCheck->IsSelected() )
{
engine->ClientCmd_Unrestricted( "bench_upload\n" );
}
BaseClass::OnClose();
}
vgui::CheckButton *m_pUploadCheck;
};
//-----------------------------------------------------------------------------
// Purpose: Launches the stats dialog
//-----------------------------------------------------------------------------
CON_COMMAND_F( bench_showstatsdialog, "Shows a dialog displaying the most recent benchmark results.", FCVAR_CHEAT )
{
static vgui::DHANDLE<CBenchmarkResultsDialog> g_BenchmarkResultsDialog;
if (!g_BenchmarkResultsDialog.Get())
{
g_BenchmarkResultsDialog = new CBenchmarkResultsDialog( BasePanel(), "BenchmarkResultsDialog" );
}
g_BenchmarkResultsDialog->Activate();
}
| 28.282443 | 115 | 0.586235 | DeadZoneLuna |
9cf2fd822f3e7dd132c6140f1b35a11583a911ae | 162 | hpp | C++ | modules/rallies/script_macros.hpp | r4vn/a3-lair | 164af19221175e712af26db0d8ff7361ae30ba21 | [
"MIT"
] | null | null | null | modules/rallies/script_macros.hpp | r4vn/a3-lair | 164af19221175e712af26db0d8ff7361ae30ba21 | [
"MIT"
] | 3 | 2016-05-28T13:19:27.000Z | 2016-05-28T13:21:45.000Z | modules/rallies/script_macros.hpp | r4vn/a3-lair | 164af19221175e712af26db0d8ff7361ae30ba21 | [
"MIT"
] | null | null | null | // Define module's name
#define MODULE "rallies"
// Load script macros from the main module as it contains essential macros
#include "..\main\script_macros.hpp"
| 27 | 74 | 0.759259 | r4vn |
9cf309ceeba4995322ec7415ac92703647080138 | 4,912 | cpp | C++ | shared/scene/VtxData.cpp | adoug/3D-Graphics-Rendering-Cookbook | dabffed670b8be5a619f0f62b10e0cc8ccdd5a36 | [
"MIT"
] | 399 | 2021-06-03T02:42:20.000Z | 2022-03-27T23:23:15.000Z | shared/scene/VtxData.cpp | adoug/3D-Graphics-Rendering-Cookbook | dabffed670b8be5a619f0f62b10e0cc8ccdd5a36 | [
"MIT"
] | 7 | 2021-07-13T02:36:01.000Z | 2022-03-26T03:46:37.000Z | shared/scene/VtxData.cpp | adoug/3D-Graphics-Rendering-Cookbook | dabffed670b8be5a619f0f62b10e0cc8ccdd5a36 | [
"MIT"
] | 53 | 2021-06-02T20:02:24.000Z | 2022-03-29T15:36:30.000Z | #include "shared/scene/VtxData.h"
#include <algorithm>
#include <assert.h>
#include <stdio.h>
MeshFileHeader loadMeshData(const char* meshFile, MeshData& out)
{
MeshFileHeader header;
FILE* f = fopen(meshFile, "rb");
assert(f); // Did you forget to run "Ch5_Tool05_MeshConvert"?
if (!f)
{
printf("Cannot open %s. Did you forget to run \"Ch5_Tool05_MeshConvert\"?\n", meshFile);
exit(EXIT_FAILURE);
}
if (fread(&header, 1, sizeof(header), f) != sizeof(header))
{
printf("Unable to read mesh file header\n");
exit(EXIT_FAILURE);
}
out.meshes_.resize(header.meshCount);
if (fread(out.meshes_.data(), sizeof(Mesh), header.meshCount, f) != header.meshCount)
{
printf("Could not read mesh descriptors\n");
exit(EXIT_FAILURE);
}
out.boxes_.resize(header.meshCount);
if (fread(out.boxes_.data(), sizeof(BoundingBox), header.meshCount, f) != header.meshCount)
{
printf("Could not read bounding boxes\n");
exit(255);
}
out.indexData_.resize(header.indexDataSize / sizeof(uint32_t));
out.vertexData_.resize(header.vertexDataSize / sizeof(float));
if ((fread(out.indexData_.data(), 1, header.indexDataSize, f) != header.indexDataSize) ||
(fread(out.vertexData_.data(), 1, header.vertexDataSize, f) != header.vertexDataSize))
{
printf("Unable to read index/vertex data\n");
exit(255);
}
fclose(f);
return header;
}
void saveMeshData(const char* fileName, const MeshData& m)
{
FILE *f = fopen(fileName, "wb");
const MeshFileHeader header = {
.magicValue = 0x12345678,
.meshCount = (uint32_t)m.meshes_.size(),
.dataBlockStartOffset = (uint32_t )(sizeof(MeshFileHeader) + m.meshes_.size() * sizeof(Mesh)),
.indexDataSize = (uint32_t)(m.indexData_.size() * sizeof(uint32_t)),
.vertexDataSize = (uint32_t)(m.vertexData_.size() * sizeof(float))
};
fwrite(&header, 1, sizeof(header), f);
fwrite(m.meshes_.data(), sizeof(Mesh), header.meshCount, f);
fwrite(m.boxes_.data(), sizeof(BoundingBox), header.meshCount, f);
fwrite(m.indexData_.data(), 1, header.indexDataSize, f);
fwrite(m.vertexData_.data(), 1, header.vertexDataSize, f);
fclose(f);
}
void saveBoundingBoxes(const char* fileName, const std::vector<BoundingBox>& boxes)
{
FILE* f = fopen(fileName, "wb");
if (!f)
{
printf("Error opening bounding boxes file for writing\n");
exit(255);
}
const uint32_t sz = (uint32_t)boxes.size();
fwrite(&sz, 1, sizeof(sz), f);
fwrite(boxes.data(), sz, sizeof(BoundingBox), f);
fclose(f);
}
void loadBoundingBoxes(const char* fileName, std::vector<BoundingBox>& boxes)
{
FILE* f = fopen(fileName, "rb");
if (!f)
{
printf("Error opening bounding boxes file\n");
exit(255);
}
uint32_t sz;
fread(&sz, 1, sizeof(sz), f);
// TODO: check file size, divide by bounding box size
boxes.resize(sz);
fread(boxes.data(), sz, sizeof(BoundingBox), f);
fclose(f);
}
// Combine a list of meshes to a single mesh container
MeshFileHeader mergeMeshData(MeshData& m, const std::vector<MeshData*> md)
{
uint32_t totalVertexDataSize = 0;
uint32_t totalIndexDataSize = 0;
uint32_t offs = 0;
for (const MeshData* i: md)
{
mergeVectors(m.indexData_, i->indexData_);
mergeVectors(m.vertexData_, i->vertexData_);
mergeVectors(m.meshes_, i->meshes_);
mergeVectors(m.boxes_, i->boxes_);
uint32_t vtxOffset = totalVertexDataSize / 8; /* 8 is the number of per-vertex attributes: position, normal + UV */
for (size_t j = 0 ; j < (uint32_t)i->meshes_.size() ; j++)
// m.vertexCount, m.lodCount and m.streamCount do not change
// m.vertexOffset also does not change, because vertex offsets are local (i.e., baked into the indices)
m.meshes_[offs + j].indexOffset += totalIndexDataSize;
// shift individual indices
for(size_t j = 0 ; j < i->indexData_.size() ; j++)
m.indexData_[totalIndexDataSize + j] += vtxOffset;
offs += (uint32_t)i->meshes_.size();
totalIndexDataSize += (uint32_t)i->indexData_.size();
totalVertexDataSize += (uint32_t)i->vertexData_.size();
}
return MeshFileHeader {
.magicValue = 0x12345678,
.meshCount = (uint32_t)offs,
.dataBlockStartOffset = (uint32_t )(sizeof(MeshFileHeader) + offs * sizeof(Mesh)),
.indexDataSize = static_cast<uint32_t>(totalIndexDataSize * sizeof(uint32_t)),
.vertexDataSize = static_cast<uint32_t>(totalVertexDataSize * sizeof(float))
};
}
void recalculateBoundingBoxes(MeshData& m)
{
m.boxes_.clear();
for (const auto& mesh : m.meshes_)
{
const auto numIndices = mesh.getLODIndicesCount(0);
glm::vec3 vmin(std::numeric_limits<float>::max());
glm::vec3 vmax(std::numeric_limits<float>::lowest());
for (auto i = 0; i != numIndices; i++)
{
auto vtxOffset = m.indexData_[mesh.indexOffset + i] + mesh.vertexOffset;
const float* vf = &m.vertexData_[vtxOffset * kMaxStreams];
vmin = glm::min(vmin, vec3(vf[0], vf[1], vf[2]));
vmax = glm::max(vmax, vec3(vf[0], vf[1], vf[2]));
}
m.boxes_.emplace_back(vmin, vmax);
}
}
| 28.068571 | 118 | 0.692386 | adoug |
9cf83a0859a0d0aee31493fb627c39fb6f6c1a4a | 2,154 | hpp | C++ | qflow/wavefunctions/rbmsymmetricwavefunction.hpp | johanere/qflow | 5453cd5c3230ad7f082adf9ec1aea63ab0a4312a | [
"MIT"
] | 5 | 2019-07-24T21:46:24.000Z | 2021-06-11T18:18:24.000Z | qflow/wavefunctions/rbmsymmetricwavefunction.hpp | johanere/qflow | 5453cd5c3230ad7f082adf9ec1aea63ab0a4312a | [
"MIT"
] | 22 | 2019-02-19T10:49:26.000Z | 2019-07-18T09:42:13.000Z | qflow/wavefunctions/rbmsymmetricwavefunction.hpp | bsamseth/FYS4411 | 72b879e7978364498c48fc855b5df676c205f211 | [
"MIT"
] | 2 | 2020-11-04T15:17:24.000Z | 2021-11-03T16:37:38.000Z | #pragma once
#include "rbmwavefunction.hpp"
#include <algorithm>
#include <cassert>
#include <functional>
#include <vector>
/**
* Class for representing a wavefunction with an symmetric RBM.
*/
class RBMSymmetricWavefunction : public RBMWavefunction
{
public:
const int _f; // Number of degrees of freedom per particle.
// The parameter vector is defined in the superclass.
/**
* Construct a wavefunction RBM.
* @param M number of visible nodes.
* @param N number of hidden nodes.
* @param sigma2 square of the spread parameter $\sigma$.
* @param root_factor default to 1, or set to `GIBBS_FACTOR` to get sqrt(psi).
*/
RBMSymmetricWavefunction(int M,
int N,
int f,
Real sigma2 = 1,
Real root_factor = 1);
/**
* @param k bias index.
* @param system configuration to evaluate for.
* @return 1/psi d(psi)/d(a_k)
*/
Real deriv_a(int k, const System& system) const override;
/**
* @param k first weight index.
* @param l second weight index.
* @param system configuration to evaluate for.
* @return 1/psi d(psi)/d(w_kl)
*/
Real deriv_w(int k, int l, const System& system) const override;
/**
* @param system configuration to evaluate the gradient for.
* @return Gradient of the expected local energy, wrt. all the parameters.
*/
RowVector gradient(const System& system) override;
// The following functions return the index into the full parameter vector which
// point to the specified parameter.
int a(int i) const override;
int b(int j) const override;
int w(int i, int j) const override;
};
inline int RBMSymmetricWavefunction::a(int i) const
{
assert(i >= 0 and i < _M);
return i % _f;
}
inline int RBMSymmetricWavefunction::b(int j) const
{
assert(j >= 0 and j < _N);
return _f + j;
}
inline int RBMSymmetricWavefunction::w(int i, int j) const
{
assert(i >= 0 and i < _M);
assert(j >= 0 and j < _N);
return _f + _N + (i % _f) * _N + j;
}
| 27.974026 | 84 | 0.614206 | johanere |
9cf917d77e652fac3c07471642b499e89961b9d5 | 9,794 | cpp | C++ | tests/eosio.amend_tests.cpp | CALEOS/eosio.contracts | 07b7401f9518794deaff74d6f9547667575f3fcc | [
"MIT"
] | null | null | null | tests/eosio.amend_tests.cpp | CALEOS/eosio.contracts | 07b7401f9518794deaff74d6f9547667575f3fcc | [
"MIT"
] | null | null | null | tests/eosio.amend_tests.cpp | CALEOS/eosio.contracts | 07b7401f9518794deaff74d6f9547667575f3fcc | [
"MIT"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include <eosio/testing/tester.hpp>
#include <eosio/chain/abi_serializer.hpp>
#include <eosio/chain/wast_to_wasm.hpp>
#include <Runtime/Runtime.h>
#include <iomanip>
#include <fc/variant_object.hpp>
#include "contracts.hpp"
#include "test_symbol.hpp"
#include "eosio.amend_tester.hpp"
using namespace eosio::testing;
using namespace eosio;
using namespace eosio::chain;
using namespace eosio::testing;
using namespace fc;
using namespace std;
using mvo = fc::mutable_variant_object;
BOOST_AUTO_TEST_SUITE(eosio_amend_tests)
BOOST_FIXTURE_TEST_CASE( deposit_system, eosio_amend_tester) try {
asset local_sum = get_currency_balance(N(eosio.token), symbol(4, "TLOS"), N(eosio.amend));
for(uint16_t i = 0; i < test_voters.size(); i++) {
auto deposit_info = get_deposit(test_voters[i].value);
BOOST_REQUIRE_EQUAL(true, deposit_info.is_null());
asset sum = asset::from_string("20.0000 TLOS");
auto voter_balance = get_currency_balance(N(eosio.token), symbol(4, "TLOS"), test_voters[i].value);
BOOST_REQUIRE_EQUAL(voter_balance, asset::from_string("200.0000 TLOS"));
std::cout << "transfer " << "1" << " account " << i << std::endl;
transfer(test_voters[i].value, N(eosio.amend), sum, "WPS deposit");
produce_blocks( 2 );
auto contract_balance = get_currency_balance(N(eosio.token), symbol(4, "TLOS"), N(eosio.amend));
BOOST_REQUIRE_EQUAL(contract_balance, local_sum + sum);
local_sum += sum;
deposit_info = get_deposit(test_voters[i].value);
BOOST_REQUIRE_EQUAL(false, deposit_info.is_null());
REQUIRE_MATCHING_OBJECT(deposit_info, mvo()
("owner", test_voters[i].to_string())
("escrow", sum.to_string())
);
std::cout << "transfer " << " 2 " << " account " << i << std::endl;
transfer(test_voters[i].value, N(eosio.amend), sum, "WPS depost");
produce_blocks( 2 );
contract_balance = get_currency_balance(N(eosio.token), symbol(4, "TLOS"), N(eosio.amend));
BOOST_REQUIRE_EQUAL(contract_balance, (local_sum + sum));
local_sum += sum;
deposit_info = get_deposit(test_voters[i].value);
REQUIRE_MATCHING_OBJECT(deposit_info, mvo()
("owner", test_voters[i].to_string())
("escrow", (sum + sum).to_string())
);
asset pre_refund = get_currency_balance(N(eosio.token), symbol(4, "TLOS"), test_voters[i].value);
asset escrow = asset::from_string(get_deposit(test_voters[i].value)["escrow"].as_string());
getdeposit(test_voters[i].value);
local_sum -= escrow;
asset post_refund = get_currency_balance(N(eosio.token), symbol(4, "TLOS"), test_voters[i].value);
BOOST_REQUIRE_EQUAL((pre_refund + escrow), post_refund);
}
} FC_LOG_AND_RETHROW()
BOOST_FIXTURE_TEST_CASE( ballot_id_and_fee, eosio_amend_tester ) try {
register_voters(test_voters, 0, 1, symbol(4, "VOTE"));
insert_default_docs();
auto proposer = test_voters[0];
transfer(N(eosio), proposer.value, asset::from_string("2000.0000 TLOS"), "Blood Money");
transfer(N(eosio), eosio::chain::name("eosio.amend"), asset::from_string("0.0001 TLOS"), "Init Amend env");
auto title = std::string("my ratify test title");
auto cycles = 1;
auto ipfs_location = std::string("32662273CFF99078EC3BFA5E7BBB1C369B1D3884DEDF2AF7D8748DEE080E4B9");
auto receiver = test_voters[0];
int num_proposals = 10;
auto env = get_env();
uint64_t fee = env["fee"].as<uint64_t>();
asset expected_total = core_sym::from_string("0.0001");
signed_transaction trx;
for( int i = 0; i < num_proposals; i++){
std::stringstream ssf;
ssf << std::fixed << std::setprecision(4) << (double(fee)/10000);
asset _fee = core_sym::from_string(ssf.str());
expected_total += _fee;
transfer(proposer, eosio::chain::name("eosio.amend"), _fee, std::string("fee for ratify "+std::to_string(i)));
uint64_t doc_num = i % documents.size();
uint8_t clause_num = i % documents[doc_num]["clauses"].size();
makeproposal(std::string(title+std::to_string(i)), uint64_t(doc_num), uint8_t(clause_num), ipfs_location, proposer);
}
produce_blocks(1);
BOOST_REQUIRE_EXCEPTION(
makeproposal(std::string(title+std::to_string(num_proposals)), uint64_t(documents.size()), uint8_t(0), ipfs_location, proposer),
eosio_assert_message_exception,
eosio_assert_message_is( "Document Not Found" )
);
BOOST_REQUIRE_EXCEPTION(
makeproposal(std::string(title+std::to_string(num_proposals)), uint64_t(0), uint8_t(documents[0]["clauses"].size()), ipfs_location, proposer),
eosio_assert_message_exception,
eosio_assert_message_is( "Deposit not found, please transfer your TLOS fee" )
);
asset saving_balance = get_balance(N(eosio.amend));
BOOST_REQUIRE_EQUAL(saving_balance, expected_total);
for( int i = 0; i < num_proposals; i++){
auto proposal = get_proposal(i);
auto submission = get_submission(i);
auto ballot = get_ballot(i);
// since only wps here, there should be same ids for props and subs
BOOST_REQUIRE_EQUAL(proposal["prop_id"], submission["proposal_id"]);
BOOST_REQUIRE_EQUAL(proposal["info_url"], submission["new_ipfs_urls"].as<vector<std::string>>()[0]);
// prop id and ballot ref id should be same
BOOST_REQUIRE_EQUAL(proposal["prop_id"], ballot["reference_id"]);
// submission should have correct ballot_id
BOOST_REQUIRE_EQUAL(submission["ballot_id"], ballot["ballot_id"]);
}
} FC_LOG_AND_RETHROW()
BOOST_FIXTURE_TEST_CASE( set_environment, eosio_amend_tester ) try {
set_env(111111, 2222, 33333, 1.1, 11.1, 1.2, 11.2);
produce_blocks(1);
// transfer(N(eosio), N(eosio.saving), core_sym::from_string("1.0000"), "memo");
// getdeposit(N(eosio));
auto env = get_env();
REQUIRE_MATCHING_OBJECT(
env,
mvo()
("publisher", eosio::chain::name("eosio.amend"))
("expiration_length", 111111)
("fee", 2222)
("start_delay", 33333)
("threshold_pass_voters", 1.1)
("threshold_pass_votes", 11.1)
("threshold_fee_voters", 1.2)
("threshold_fee_votes", 11.2)
);
insert_default_docs();
name proposer = test_voters[0];
transfer(proposer, eosio::chain::name("eosio.amend"), core_sym::from_string("0.2221"), "ratify 1 fee");
produce_blocks();
BOOST_REQUIRE_EXCEPTION(
makeproposal(
std::string("test ratify 1"),
uint64_t(0),
uint8_t(0),
std::string("32662273CFF99078EC3BFA5E7BBB1C369B1D3884DEDF2AF7D8748DEE080E4B99"),
proposer
),
eosio_assert_message_exception,
eosio_assert_message_is( "Deposit amount is less than fee, please transfer more TLOS" )
);
transfer(proposer, eosio::chain::name("eosio.amend"), core_sym::from_string("0.0001"), "ratify 1 fee diff");
makeproposal(
std::string("test ratify 1"),
uint64_t(0),
uint8_t(0),
std::string("32662273CFF99078EC3BFA5E7BBB1C369B1D3884DEDF2AF7D8748DEE080E4B99"),
proposer
);
} FC_LOG_AND_RETHROW()
BOOST_FIXTURE_TEST_CASE( create_proposal_and_cancel, eosio_amend_tester ) try {
int total_voters = test_voters.size();
name proposer = test_voters[total_voters - 1];
transfer(N(eosio), proposer.value, core_sym::from_string("300.0000"), "Blood Money");
produce_blocks(1);
BOOST_REQUIRE_EQUAL( core_sym::from_string("500.0000"), get_balance( proposer ) );
set_env(uint32_t(2500000), uint64_t(1000000), uint32_t(864000000), double(5), double(66.67), double(4), double(25));
produce_blocks(1);
insert_default_docs();
BOOST_REQUIRE_EXCEPTION(
makeproposal(
std::string("test ratify 1"),
uint64_t(0),
uint8_t(0),
std::string("32662273CFF99078EC3BFA5E7BBB1C369B1D3884DEDF2AF7D8748DEE080E4B99"),
proposer
),
eosio_assert_message_exception, eosio_assert_message_is( "Deposit not found, please transfer your TLOS fee" )
);
transfer(proposer, eosio::chain::name("eosio.amend"), core_sym::from_string("50.0000"), "ratify 1 fee");
BOOST_REQUIRE_EQUAL( core_sym::from_string("450.0000"), get_balance( proposer ) );
produce_blocks(1);
BOOST_REQUIRE_EXCEPTION(
makeproposal(
std::string("test ratify 1"),
uint64_t(0),
uint8_t(0),
std::string("32662273CFF99078EC3BFA5E7BBB1C369B1D3884DEDF2AF7D8748DEE080E4B99"),
proposer
),
eosio_assert_message_exception,
eosio_assert_message_is( "Deposit amount is less than fee, please transfer more TLOS" )
);
transfer(proposer, eosio::chain::name("eosio.amend"), core_sym::from_string("50.0000"), "ratify 1 fee");
BOOST_REQUIRE_EQUAL( core_sym::from_string("400.0000"), get_balance( proposer ) );
produce_blocks(1);
makeproposal(
std::string("test ratify 1"),
uint64_t(0),
uint8_t(0),
std::string("32662273CFF99078EC3BFA5E7BBB1C369B1D3884DEDF2AF7D8748DEE080E4B99"),
proposer
);
produce_blocks(1);
transfer(proposer, eosio::chain::name("eosio.amend"), core_sym::from_string("100.0000"), "amend 2 fee");
BOOST_REQUIRE_EQUAL( core_sym::from_string("300.0000"), get_balance( proposer ) );
makeproposal(
std::string("test amend 2"),
uint64_t(0),
uint8_t(0),
std::string("32662273CFF99078EC3BFA5E7BBB1C369B1D3884DEDF2AF7D8748DEE080E4B99"),
proposer
);
produce_blocks(1);
auto deposit_info = get_deposit(proposer.value);
BOOST_REQUIRE(deposit_info.is_null());
cancelsub(0, proposer);
cancelsub(1, proposer);
BOOST_REQUIRE_EQUAL( core_sym::from_string("300.0000"), get_balance( proposer ) );
BOOST_REQUIRE(get_proposal(0).is_null());
BOOST_REQUIRE(get_proposal(1).is_null());
} FC_LOG_AND_RETHROW()
BOOST_AUTO_TEST_SUITE_END() | 37.381679 | 148 | 0.691444 | CALEOS |
9cfc036a8d2eea4cf0f65b13241d56d1afd6a2c8 | 103 | hpp | C++ | missions/Obsolete/16_A2Free_CTI_CDF_vs_INS.chernarus/enemy/modules/modules.hpp | amlr/Multi-Session-Operations | ebfa0520a151fb27ff79fa74b17548f8560ed0a9 | [
"Apache-2.0"
] | null | null | null | missions/Obsolete/16_A2Free_CTI_CDF_vs_INS.chernarus/enemy/modules/modules.hpp | amlr/Multi-Session-Operations | ebfa0520a151fb27ff79fa74b17548f8560ed0a9 | [
"Apache-2.0"
] | null | null | null | missions/Obsolete/16_A2Free_CTI_CDF_vs_INS.chernarus/enemy/modules/modules.hpp | amlr/Multi-Session-Operations | ebfa0520a151fb27ff79fa74b17548f8560ed0a9 | [
"Apache-2.0"
] | null | null | null | // - Tested
#define MSOFACTIONS
#define RMM_ENEMYPOP
#define RMM_ZORA
// - To Test
#define BIS_WARFARE | 14.714286 | 20 | 0.757282 | amlr |
1400209aec98331e29d05974d4ff32f0f3be3d89 | 2,659 | cpp | C++ | src/utility/pkcs11module.cpp | kaidokert/old-esteid-stack | 0391bbf600556dc8527c4f87eed2c95afc878ab4 | [
"BSD-3-Clause"
] | null | null | null | src/utility/pkcs11module.cpp | kaidokert/old-esteid-stack | 0391bbf600556dc8527c4f87eed2c95afc878ab4 | [
"BSD-3-Clause"
] | null | null | null | src/utility/pkcs11module.cpp | kaidokert/old-esteid-stack | 0391bbf600556dc8527c4f87eed2c95afc878ab4 | [
"BSD-3-Clause"
] | null | null | null | /*!
\file pkcs11module.cpp
\copyright (c) Kaido Kert ( kaidokert@gmail.com )
\licence BSD
\author $Author$
\date $Date$
*/
// Revision $Revision$
#include "precompiled.h"
#include "pkcs11module.h"
pkcs11module::pkcs11module(const char *n) : DynamicLibrary(n) {
pGetFunctionList = (ULONG (*)(void * pInitArgs)) getProc("C_GetFunctionList");
pInitialize = (ULONG (*)(void * pInitArgs))getProc("C_Initialize");
pFinalize = (ULONG (*)(void * pReserved))getProc("C_Finalize");
pGetInfo = (ULONG (*)(CK_INFO * pInfo))getProc("C_GetInfo");
pGetSlotList = (ULONG (*)(BYTE tokenPresent,ULONG *pSlotList,ULONG * pulCount)) getProc("C_GetSlotList");
pGetTokenInfo = (ULONG (*)(ULONG slotID,CK_TOKEN_INFO * pInfo)) getProc("C_GetTokenInfo");
pInitialize(NULL);
}
pkcs11module::~pkcs11module() {
pFinalize(NULL);
}
using std::endl;
using std::vector;
#define LENOF(x) (sizeof(x) / sizeof(*x))
#define GETSTR(x) buf2str((const char*)x,sizeof(x))
std::string pkcs11module::buf2str(const void *in,size_t len) {
std::string tmp((char *)in,len);
if(!*tmp.begin()) tmp.clear();
tmp.erase(tmp.find_last_not_of(" \t")+1);
return tmp;
}
void pkcs11module::test(std::ostream &strm) {
ULONG ret;
CK_INFO inf;
if(0 != (ret = pGetInfo(&inf))) {
strm << "GetInfo failed (code: "<< ret << ")" << endl;
return;
}
strm << "version:" << (int ) inf.cryptokiVersion.major << "." << (int ) inf.cryptokiVersion.minor << endl;
strm << "libver:" << (int) inf.libraryVersion.major << "." << (int) inf.libraryVersion.minor << endl;
strm << "manufacturer: " << GETSTR(inf.manufacturerID) <<
" description:" << GETSTR(inf.libraryDescription) << endl;
ULONG slotCount = 100;
vector<ULONG> arrSlots(100,0);
if (0 != (ret = pGetSlotList(0,&arrSlots[0],&slotCount))) {
strm << "GetSlotList failed (code: " << ret <<")" << endl;
return;
};
arrSlots.resize(slotCount);
strm << "slotcount:" << arrSlots.size() << endl;
for(vector<ULONG>::iterator it = arrSlots.begin(); it != arrSlots.end();it++) {
CK_TOKEN_INFO tInfo;
strm << "slot ID [" << *it << "]" << endl;
if (0!= (ret = pGetTokenInfo(*it,&tInfo))) {
if (ret == 0xE0 || ret == 0x32) //not present
strm << "\t[EMPTY]" << endl;
else
strm << "\tGetTokenInfo failed (code: "<< ret << ")" << endl;
}
else {
if (GETSTR(tInfo.label).length() == 0) continue;
strm << "\tLabel:'" << GETSTR(tInfo.label) << "'"
<< "\tSerial:'" << GETSTR(tInfo.serialNumber) << "'" << endl;
strm << "\tManufacturer:'" << GETSTR(tInfo.manufacturerID) << "'"
<< "\tModel:'" << GETSTR(tInfo.model) << "'"
<< endl;
strm << "\tflags: " << tInfo.flags << endl;
}
}
}
| 33.658228 | 107 | 0.622414 | kaidokert |
1404027145aea84ab887516edc05214c551d2cd2 | 1,189 | hpp | C++ | src/unity/djinni/jni/NativeBlockInfoRecord.hpp | afca1988/florin-core | 318f3a4e2186e817b047b3f3924ba70045b6f312 | [
"MIT"
] | 6 | 2021-05-18T09:09:38.000Z | 2022-03-29T14:50:38.000Z | src/unity/djinni/jni/NativeBlockInfoRecord.hpp | afca1988/florin-core | 318f3a4e2186e817b047b3f3924ba70045b6f312 | [
"MIT"
] | 1 | 2021-12-07T12:30:41.000Z | 2021-12-07T12:30:41.000Z | src/unity/djinni/jni/NativeBlockInfoRecord.hpp | afca1988/florin-core | 318f3a4e2186e817b047b3f3924ba70045b6f312 | [
"MIT"
] | 7 | 2020-08-11T18:00:32.000Z | 2021-03-26T08:58:07.000Z | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from libunity.djinni
#pragma once
#include "block_info_record.hpp"
#include "djinni_support.hpp"
namespace djinni_generated {
class NativeBlockInfoRecord final {
public:
using CppType = ::BlockInfoRecord;
using JniType = jobject;
using Boxed = NativeBlockInfoRecord;
~NativeBlockInfoRecord();
static CppType toCpp(JNIEnv* jniEnv, JniType j);
static ::djinni::LocalRef<JniType> fromCpp(JNIEnv* jniEnv, const CppType& c);
private:
NativeBlockInfoRecord();
friend ::djinni::JniClass<NativeBlockInfoRecord>;
const ::djinni::GlobalRef<jclass> clazz { ::djinni::jniFindClass("com/florin/jniunifiedbackend/BlockInfoRecord") };
const jmethodID jconstructor { ::djinni::jniGetMethodID(clazz.get(), "<init>", "(IJLjava/lang/String;)V") };
const jfieldID field_mHeight { ::djinni::jniGetFieldID(clazz.get(), "mHeight", "I") };
const jfieldID field_mTimeStamp { ::djinni::jniGetFieldID(clazz.get(), "mTimeStamp", "J") };
const jfieldID field_mBlockHash { ::djinni::jniGetFieldID(clazz.get(), "mBlockHash", "Ljava/lang/String;") };
};
} // namespace djinni_generated
| 33.971429 | 119 | 0.721615 | afca1988 |
140617b93cd9b1973782891b68cb92145e932bf7 | 1,980 | cpp | C++ | trainings/2015-08-01-NEERC-Southern-2012/A.cpp | HcPlu/acm-icpc | ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8 | [
"MIT"
] | 9 | 2017-10-07T13:35:45.000Z | 2021-06-07T17:36:55.000Z | trainings/2015-08-01-NEERC-Southern-2012/A.cpp | zhijian-liu/acm-icpc | ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8 | [
"MIT"
] | null | null | null | trainings/2015-08-01-NEERC-Southern-2012/A.cpp | zhijian-liu/acm-icpc | ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8 | [
"MIT"
] | 3 | 2018-04-24T05:27:21.000Z | 2019-04-25T06:06:00.000Z | #include <cstdio>
#include <algorithm>
using namespace std;
const int N = 200005;
long long f[N], a[N], tmp[N];
long long jp0[N], jp1[N], get[N];
int main() {
long long n;
scanf("%I64d", &n);
for (long long i = 1; i <= n; i++) {
scanf("%I64d", &a[i]);
}
sort(a + 1, a + 1 + n);
for (long long i = 1; i <= n; i++) {
tmp[i] = a[i];
}
f[0] = 1;
for (long long i = 0; i <= 100; i++) {
for (long long j = 1; j <= n; j++) {
if (a[j] != 0) {
goto escape;
}
}
break;
escape:;
for (long long j = 0; j <= n + 1; j++) {
get[j] = 0;
}
long long sum0 = 0, sum1 = 0;
for (long long j = 1; j <= n; j++) {
if (a[j] & 1) {
jp1[++sum1] = a[j];
} else {
jp0[++sum0] = a[j];
}
}
long long tw1 = 0, tw0 = 0;
for (long long j = 1; j <= n + 1; j++) {
long long res = (sum1 - tw1) + tw0;
if (res % 2 == 0) {
get[tw0] += f[j - 1];
}
if ((n - res) % 2 == 0) {
get[sum0 + tw1] += f[j - 1];
}
if (a[j] & 1) {
tw1++;
} else {
tw0++;
}
if (a[j] == 0) {
break;
}
}
long long cnt = 0;
for (long long j = 1; j <= sum0; j++) {
a[++cnt] = jp0[j];
}
for (long long j = 1; j <= sum1; j++) {
a[++cnt] = jp1[j];
}
for (long long j = 1; j <= cnt; j++) {
a[j] >>= 1;
}
for (long long j = 0; j <= n + 1; j++) {
f[j] = get[j];
}
}
long long flag = 0;
for (long long i = 2; i <= n; i++) {
flag ^= (tmp[i] - tmp[1]);
}
if (flag == 0) {
f[0]--;
}
printf("%I64d\n", f[0]);
return 0;
}
| 23.294118 | 48 | 0.314646 | HcPlu |
14088337181e28f71947165389469040676042eb | 246 | cpp | C++ | sample/switch/simple/pregen/main.cpp | yuki-nyaa/pg | 5eb30bfd0609f225181c19e1f67035a2c5eb4461 | [
"Apache-2.0"
] | null | null | null | sample/switch/simple/pregen/main.cpp | yuki-nyaa/pg | 5eb30bfd0609f225181c19e1f67035a2c5eb4461 | [
"Apache-2.0"
] | null | null | null | sample/switch/simple/pregen/main.cpp | yuki-nyaa/pg | 5eb30bfd0609f225181c19e1f67035a2c5eb4461 | [
"Apache-2.0"
] | null | null | null | #include"cconfig"
#include"lexer.h"
#include"parser.h"
#include<cstdio>
typedef xxx::Token_Settings TS;
int main(){
FILE* file=fopen("test.txt","r");
xxx::Lexer lexer(file);
xxx::SParser parser(&lexer);
parser.parse();
} | 22.363636 | 38 | 0.638211 | yuki-nyaa |
140a30ed73689b79655ce02287ed377e3a9797a3 | 967 | cpp | C++ | recursion/implementation_based/inversion_count.cpp | Zim95/cpp_proj | b73781be17e818fc778320a7498dc4d021b92ffa | [
"MIT"
] | 2 | 2019-04-22T11:04:59.000Z | 2021-03-01T18:32:25.000Z | recursion/implementation_based/inversion_count.cpp | Zim95/cpp_proj | b73781be17e818fc778320a7498dc4d021b92ffa | [
"MIT"
] | null | null | null | recursion/implementation_based/inversion_count.cpp | Zim95/cpp_proj | b73781be17e818fc778320a7498dc4d021b92ffa | [
"MIT"
] | 1 | 2019-04-18T14:04:38.000Z | 2019-04-18T14:04:38.000Z | /*
INVERSION COUNT
---------------
Given an array:
int a[] = {1, 5, 2, 6, 3, 0, 2};
Find all pairs such that,
a[i] > a[j], for all i<j.
You see its inverted. As according to sorting, if i<j, a[i]<a[j].
*/
#include <iostream>
using namespace std;
int inversionCountMergeSort(int *a, int s, int e) {
// Base case
if(s>=e) {
// End of array return 0 inversions.
return 0;
}
}
// Brute force technique
int inversionCountBruteForce(int *a, int n) {
int inversion_count = 0;
for(int i=0; i<n; i++) {
for(int j=i+1; j<n; j++) {
if((a[i] > a[j]) && i<j) {
inversion_count++;
}
}
}
return inversion_count;
}
int main() {
// int ar[] = {10, 9, 8, 7, 6, 5, 4, -1, -2, 10};
int ar[] = {1, 5, 2, 6, 3, 0};
int n = 6;
int ic = inversionCountBruteForce(ar, n);
cout << "Inversion count: " << ic << endl;
cout << endl;
}
| 21.488889 | 69 | 0.490176 | Zim95 |
140bb32ac23afe1dce642ba8c482876d339c3f6c | 7,624 | hpp | C++ | Blik2D/addon/opencv-3.1.0_for_blik/modules/cudalegacy/src/cuda/fgd.hpp | BonexGu/Blik2D | 8e0592787e5c8e8a28682d0e1826b8223eae5983 | [
"MIT"
] | 13 | 2017-02-22T02:20:06.000Z | 2018-06-06T04:18:03.000Z | Blik2D/addon/opencv-3.1.0_for_blik/modules/cudalegacy/src/cuda/fgd.hpp | BonexGu/Blik2D | 8e0592787e5c8e8a28682d0e1826b8223eae5983 | [
"MIT"
] | null | null | null | Blik2D/addon/opencv-3.1.0_for_blik/modules/cudalegacy/src/cuda/fgd.hpp | BonexGu/Blik2D | 8e0592787e5c8e8a28682d0e1826b8223eae5983 | [
"MIT"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef __FGD_BGFG_COMMON_HPP__
#define __FGD_BGFG_COMMON_HPP__
#include BLIK_OPENCV_U_opencv2__core__cuda_types_hpp //original-code:"opencv2/core/cuda_types.hpp"
namespace fgd
{
struct BGPixelStat
{
public:
#ifdef __CUDACC__
__device__ float& Pbc(int i, int j);
__device__ float& Pbcc(int i, int j);
__device__ unsigned char& is_trained_st_model(int i, int j);
__device__ unsigned char& is_trained_dyn_model(int i, int j);
__device__ float& PV_C(int i, int j, int k);
__device__ float& PVB_C(int i, int j, int k);
template <typename T> __device__ T& V_C(int i, int j, int k);
__device__ float& PV_CC(int i, int j, int k);
__device__ float& PVB_CC(int i, int j, int k);
template <typename T> __device__ T& V1_CC(int i, int j, int k);
template <typename T> __device__ T& V2_CC(int i, int j, int k);
#endif
int rows_;
unsigned char* Pbc_data_;
size_t Pbc_step_;
unsigned char* Pbcc_data_;
size_t Pbcc_step_;
unsigned char* is_trained_st_model_data_;
size_t is_trained_st_model_step_;
unsigned char* is_trained_dyn_model_data_;
size_t is_trained_dyn_model_step_;
unsigned char* ctable_Pv_data_;
size_t ctable_Pv_step_;
unsigned char* ctable_Pvb_data_;
size_t ctable_Pvb_step_;
unsigned char* ctable_v_data_;
size_t ctable_v_step_;
unsigned char* cctable_Pv_data_;
size_t cctable_Pv_step_;
unsigned char* cctable_Pvb_data_;
size_t cctable_Pvb_step_;
unsigned char* cctable_v1_data_;
size_t cctable_v1_step_;
unsigned char* cctable_v2_data_;
size_t cctable_v2_step_;
};
#ifdef __CUDACC__
__device__ __forceinline__ float& BGPixelStat::Pbc(int i, int j)
{
return *((float*)(Pbc_data_ + i * Pbc_step_) + j);
}
__device__ __forceinline__ float& BGPixelStat::Pbcc(int i, int j)
{
return *((float*)(Pbcc_data_ + i * Pbcc_step_) + j);
}
__device__ __forceinline__ unsigned char& BGPixelStat::is_trained_st_model(int i, int j)
{
return *((unsigned char*)(is_trained_st_model_data_ + i * is_trained_st_model_step_) + j);
}
__device__ __forceinline__ unsigned char& BGPixelStat::is_trained_dyn_model(int i, int j)
{
return *((unsigned char*)(is_trained_dyn_model_data_ + i * is_trained_dyn_model_step_) + j);
}
__device__ __forceinline__ float& BGPixelStat::PV_C(int i, int j, int k)
{
return *((float*)(ctable_Pv_data_ + ((k * rows_) + i) * ctable_Pv_step_) + j);
}
__device__ __forceinline__ float& BGPixelStat::PVB_C(int i, int j, int k)
{
return *((float*)(ctable_Pvb_data_ + ((k * rows_) + i) * ctable_Pvb_step_) + j);
}
template <typename T> __device__ __forceinline__ T& BGPixelStat::V_C(int i, int j, int k)
{
return *((T*)(ctable_v_data_ + ((k * rows_) + i) * ctable_v_step_) + j);
}
__device__ __forceinline__ float& BGPixelStat::PV_CC(int i, int j, int k)
{
return *((float*)(cctable_Pv_data_ + ((k * rows_) + i) * cctable_Pv_step_) + j);
}
__device__ __forceinline__ float& BGPixelStat::PVB_CC(int i, int j, int k)
{
return *((float*)(cctable_Pvb_data_ + ((k * rows_) + i) * cctable_Pvb_step_) + j);
}
template <typename T> __device__ __forceinline__ T& BGPixelStat::V1_CC(int i, int j, int k)
{
return *((T*)(cctable_v1_data_ + ((k * rows_) + i) * cctable_v1_step_) + j);
}
template <typename T> __device__ __forceinline__ T& BGPixelStat::V2_CC(int i, int j, int k)
{
return *((T*)(cctable_v2_data_ + ((k * rows_) + i) * cctable_v2_step_) + j);
}
#endif
const int PARTIAL_HISTOGRAM_COUNT = 240;
const int HISTOGRAM_BIN_COUNT = 256;
template <typename PT, typename CT>
void calcDiffHistogram_gpu(cv::cuda::PtrStepSzb prevFrame, cv::cuda::PtrStepSzb curFrame,
unsigned int* hist0, unsigned int* hist1, unsigned int* hist2,
unsigned int* partialBuf0, unsigned int* partialBuf1, unsigned int* partialBuf2,
bool cc20, cudaStream_t stream);
template <typename PT, typename CT>
void calcDiffThreshMask_gpu(cv::cuda::PtrStepSzb prevFrame, cv::cuda::PtrStepSzb curFrame, uchar3 bestThres, cv::cuda::PtrStepSzb changeMask, cudaStream_t stream);
void setBGPixelStat(const BGPixelStat& stat);
template <typename PT, typename CT, typename OT>
void bgfgClassification_gpu(cv::cuda::PtrStepSzb prevFrame, cv::cuda::PtrStepSzb curFrame,
cv::cuda::PtrStepSzb Ftd, cv::cuda::PtrStepSzb Fbd, cv::cuda::PtrStepSzb foreground,
int deltaC, int deltaCC, float alpha2, int N1c, int N1cc, cudaStream_t stream);
template <typename PT, typename CT, typename OT>
void updateBackgroundModel_gpu(cv::cuda::PtrStepSzb prevFrame, cv::cuda::PtrStepSzb curFrame,
cv::cuda::PtrStepSzb Ftd, cv::cuda::PtrStepSzb Fbd, cv::cuda::PtrStepSzb foreground, cv::cuda::PtrStepSzb background,
int deltaC, int deltaCC, float alpha1, float alpha2, float alpha3, int N1c, int N1cc, int N2c, int N2cc, float T,
cudaStream_t stream);
}
#endif // __FGD_BGFG_COMMON_HPP__
| 40.126316 | 167 | 0.663038 | BonexGu |
140d16e26e842de1aa529efdec164f3a531b5563 | 893 | cpp | C++ | src/functions/functionexists.cpp | IngwiePhoenix/IceTea_old | 8a49b7c77bde123da2f4bae830362b0e791f03f4 | [
"BSD-3-Clause"
] | 1 | 2015-01-16T05:00:53.000Z | 2015-01-16T05:00:53.000Z | src/functions/functionexists.cpp | IngwiePhoenix/IceTea_old | 8a49b7c77bde123da2f4bae830362b0e791f03f4 | [
"BSD-3-Clause"
] | null | null | null | src/functions/functionexists.cpp | IngwiePhoenix/IceTea_old | 8a49b7c77bde123da2f4bae830362b0e791f03f4 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2007-2014 Xagasoft, All rights reserved.
*
* This file is part of the Xagasoft Build and is released under the
* terms of the license contained in the file LICENSE.
*/
#include "functionexists.h"
#include <unistd.h>
#include <bu/plugger.h>
PluginInterface3( pluginFunctionExists, exists, FunctionExists, Function,
"Mike Buland", 0, 1 );
FunctionExists::FunctionExists()
{
}
FunctionExists::~FunctionExists()
{
}
Bu::String FunctionExists::getName() const
{
return "exists";
}
Variable FunctionExists::call( Variable &input, VarList lParams )
{
Bu::String sFile;
if( input.getType() != Variable::typeNone )
{
sFile = input.toString();
}
else
{
sFile = lParams.first().toString();
}
if( access( sFile.getStr(), F_OK ) == 0 )
return Variable( true );
else
return Variable( false );
}
| 19.413043 | 73 | 0.646137 | IngwiePhoenix |
14113723e55c1f9d41356700cc656f32488d9989 | 3,963 | hpp | C++ | addons/medical/configs/actions/Medication.hpp | SOCOMD/SOCOMD-MODS-2021 | 834cd5f99831bd456179a1f55f5a91398c29bf57 | [
"MIT"
] | null | null | null | addons/medical/configs/actions/Medication.hpp | SOCOMD/SOCOMD-MODS-2021 | 834cd5f99831bd456179a1f55f5a91398c29bf57 | [
"MIT"
] | null | null | null | addons/medical/configs/actions/Medication.hpp | SOCOMD/SOCOMD-MODS-2021 | 834cd5f99831bd456179a1f55f5a91398c29bf57 | [
"MIT"
] | null | null | null |
class SOCOMD_Morphine {
allowSelfTreatment = 1;
medicRequired = 0;
treatmentTimeSelfCoef = 1; // todo: this isn't used anywhere, remove?
consumeItem = 1;
allowedSelections[] = {"LeftArm", "RightArm", "LeftLeg", "RightLeg"};
treatmentTime = ace_medical_treatment_treatmentTimeAutoinjector;
displayName = "Morphine 10mg/1mL";
displayNameProgress = "Injecting Morphine";
icon = "\z\socomd\addons\data\icon\VPN.paa";
category = "medication";
condition = "SOCOMD_Medical_fnc_vpnMedicationCondition";
callbackStart = "";
callbackProgress = "";
callbackSuccess = "SOCOMD_Medical_fnc_vpnMedicationSuccess";
callbackFailure = "";
items[] = {
"SOCOMD_morphine"
};
animationMedic = "AinvPknlMstpSnonWnonDnon_medic1";
animationMedicProne = "AinvPpneMstpSlayW[wpn]Dnon_medicOther";
animationMedicSelf = "AinvPknlMstpSlayW[wpn]Dnon_medic";
animationMedicSelfProne = "AinvPpneMstpSlayW[wpn]Dnon_medic";
sounds[] = {{"z\ace\addons\medical_treatment\sounds\Inject.ogg",1,1,50}};
litter[] = {{}};
};
class SOCOMD_Epinephrine: SOCOMD_Morphine {
displayName = "Adrenaline 1mg/1mL";
displayNameProgress = "Injecting Adrenaline";
icon = "\z\socomd\addons\data\icon\VPN.paa";
condition = "SOCOMD_Medical_fnc_vpnMedicationCondition";
callbackSuccess = "SOCOMD_Medical_fnc_vpnMedicationSuccess";
requiresAll=true;
items[] = {
"SOCOMD_epinephrine"
};
litter[] = {{}};
};
////////////////////////////////////////////////////////////////////////////////
class Naloxone : SOCOMD_Morphine {
displayName="Naloxone 1.6mg/4mL";
displayNameProgress="Injecting Naloxone";
icon="\z\socomd\addons\data\icon\VPN.paa";
condition = "SOCOMD_Medical_fnc_vpnMedicationCondition";
callbackSuccess = "SOCOMD_Medical_fnc_naloxoneSuccess";
requiresAll=true;
items[] = {
"SOCOMD_naloxone"
};
litter[] = {{}};
};
class Fentanyl: SOCOMD_Morphine{
displayName="Fentanyl 100mcg/2mL";
displayNameProgress="Injecting Fentanyl";
icon = "\z\socomd\addons\data\icon\VPN.paa";
condition = "SOCOMD_Medical_fnc_vpnMedicationCondition";
callbackSuccess = "SOCOMD_Medical_fnc_vpnMedicationSuccess";
requiresAll=true;
items[]={
"SOCOMD_fentanyl"
};
litter[] = {{}};
};
class Ketamine_6mg : SOCOMD_Morphine {
displayName="Ketamine 6mg/2mL";
displayNameProgress="Injecting Ketamine 6mg/2mL";
icon = "\z\socomd\addons\data\icon\VPN.paa";
requiresAll=true;
items[] = {
"SOCOMD_ketamine"
};
callbackStart = "";
callbackProgress = "";
callbackSuccess = "SOCOMD_Medical_fnc_ketamineSuccess";
litter[] = {{}};
};
class Ketamine_200mg : SOCOMD_Morphine {
displayName="Ketamine 200mg/2mL";
displayNameProgress="Injecting Ketamine 200mg/2mL";
icon = "\z\socomd\addons\data\icon\VPN.paa";
requiresAll=true;
items[] = {
"SOCOMD_ketamine"
};
callbackStart = "";
callbackProgress = "";
callbackSuccess = "SOCOMD_Medical_fnc_ketamineSuccess";
litter[] = {{}};
};
////////////////////////////////////////////////////////////////////////////////
class NonVPNMedication : SOCOMD_Morphine {
condition = "";
callbackSuccess = "";
};
class Tetra : NonVPNMedication {
displayName="Tetracycline 250mg";
displayNameProgress="Giving Tetracycline";
icon="\z\socomd\addons\data\icon\tetra.paa";
items[]={
"SOCOMD_tetra"
};
allowedSelections[]={
"Head"
};
};
class Apap : NonVPNMedication {
displayName="Paracetemol 1g";
displayNameProgress="Giving Paracetemol 1g";
icon="\z\socomd\addons\data\icon\apap.paa";
condition = "";
callbackStart = "";
items[] = {
"SOCOMD_Apap"
};
allowedSelections[] = {
"Head"
};
treatmentTime=1;
litter[]={
{"All","",{"SOCOMD_ApapLitter"}}
};
}; | 28.717391 | 80 | 0.634873 | SOCOMD |
14119432f166f74a3bcd2e57b6780d47f200202a | 750 | inl | C++ | src/vk/instance.inl | fur-id/sample | 8c68498ad14cc5f8869df2b9ea4ff2a91be9b558 | [
"MIT"
] | null | null | null | src/vk/instance.inl | fur-id/sample | 8c68498ad14cc5f8869df2b9ea4ff2a91be9b558 | [
"MIT"
] | null | null | null | src/vk/instance.inl | fur-id/sample | 8c68498ad14cc5f8869df2b9ea4ff2a91be9b558 | [
"MIT"
] | null | null | null | #ifndef VKF_INSTANCE
#define VKF_INSTANCE(...)
#endif
VKF_INSTANCE(vkDestroyInstance)
VKF_INSTANCE(vkDestroySurfaceKHR)
VKF_INSTANCE(vkEnumeratePhysicalDevices)
VKF_INSTANCE(vkEnumerateDeviceExtensionProperties)
VKF_INSTANCE(vkGetPhysicalDeviceProperties)
VKF_INSTANCE(vkGetPhysicalDeviceFeatures)
VKF_INSTANCE(vkGetPhysicalDeviceMemoryProperties)
VKF_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties)
VKF_INSTANCE(vkGetPhysicalDeviceSurfaceSupportKHR)
VKF_INSTANCE(vkGetPhysicalDeviceFormatProperties)
VKF_INSTANCE(vkGetPhysicalDeviceSurfaceCapabilitiesKHR)
VKF_INSTANCE(vkGetPhysicalDeviceSurfaceFormatsKHR)
VKF_INSTANCE(vkGetPhysicalDeviceSurfacePresentModesKHR)
VKF_INSTANCE(vkCreateDevice)
VKF_INSTANCE(vkGetDeviceProcAddr)
#undef VKF_INSTANCE
| 37.5 | 55 | 0.918667 | fur-id |
1412688021735020765ca7f682aed3aac9500dcd | 810 | cpp | C++ | shared/src/dpe/painter.cpp | amazingidiot/qastools | 6e3b0532ebc353c79d6df0628ed375e3d3c09d12 | [
"MIT"
] | null | null | null | shared/src/dpe/painter.cpp | amazingidiot/qastools | 6e3b0532ebc353c79d6df0628ed375e3d3c09d12 | [
"MIT"
] | null | null | null | shared/src/dpe/painter.cpp | amazingidiot/qastools | 6e3b0532ebc353c79d6df0628ed375e3d3c09d12 | [
"MIT"
] | null | null | null | /// QasTools: Desktop toolset for the Linux sound system ALSA.
/// \copyright See COPYING file.
#include "painter.hpp"
#include "image_set_meta.hpp"
#include "paint_job.hpp"
namespace dpe
{
Painter::Painter ( unsigned int group_type_n, unsigned int group_variant_n )
: _group_type ( group_type_n )
, _group_variant ( group_variant_n )
{
}
Painter::~Painter () {}
void
Painter::set_group_variant ( unsigned int variant_n )
{
_group_variant = variant_n;
}
int
Painter::check_and_paint ( ::dpe::Paint_Job * pjob_n )
{
int res ( -1 );
if ( pjob_n->meta == 0 ) {
return res;
}
{
const QSize & isize ( pjob_n->meta->size );
if ( ( isize.width () <= 0 ) || ( isize.height () <= 0 ) ) {
return res;
}
}
res = this->paint_image ( pjob_n );
return res;
}
} // namespace dpe
| 18.409091 | 76 | 0.645679 | amazingidiot |
1414acdc46dc9e9630c99450ffdf656655bf251b | 14,094 | cpp | C++ | Sources/simdlib/SimdVmxBgraToYuv.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | 6 | 2017-10-13T04:29:38.000Z | 2018-05-10T13:52:20.000Z | Sources/simdlib/SimdVmxBgraToYuv.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | null | null | null | Sources/simdlib/SimdVmxBgraToYuv.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | null | null | null | /*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2017 Yermalayeu Ihar.
*
* 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 "Simd/SimdMemory.h"
#include "Simd/SimdStore.h"
#include "Simd/SimdConversion.h"
namespace Simd
{
#ifdef SIMD_VMX_ENABLE
namespace Vmx
{
const v128_u8 K8_PERM_BGRA_TO_B0R0 = SIMD_VEC_SETR_EPI8(0x10, 0x00, 0x10, 0x02, 0x10, 0x04, 0x10, 0x06, 0x10, 0x08, 0x10, 0x0A, 0x10, 0x0C, 0x10, 0x0E);
const v128_u8 K8_PERM_BGRA_TO_G010 = SIMD_VEC_SETR_EPI8(0x10, 0x01, 0x10, 0x11, 0x10, 0x05, 0x10, 0x11, 0x10, 0x09, 0x10, 0x11, 0x10, 0x0D, 0x10, 0x11);
template <bool align> SIMD_INLINE void LoadPreparedBgra(const uint8_t * bgra, v128_s16 & b_r, v128_s16 & g_1)
{
v128_u8 _bgra = Load<align>(bgra);
b_r = (v128_s16)vec_perm(_bgra, (v128_u8)K16_0001, K8_PERM_BGRA_TO_B0R0);
g_1 = (v128_s16)vec_perm(_bgra, (v128_u8)K16_0001, K8_PERM_BGRA_TO_G010);
}
const v128_u8 K8_PERM_HADD0 = SIMD_VEC_SETR_EPI8(0x00, 0x01, 0x02, 0x03, 0x08, 0x09, 0x0A, 0x0B, 0x10, 0x11, 0x12, 0x13, 0x18, 0x19, 0x1A, 0x1B);
const v128_u8 K8_PERM_HADD1 = SIMD_VEC_SETR_EPI8(0x04, 0x05, 0x06, 0x07, 0x0C, 0x0D, 0x0E, 0x0F, 0x14, 0x15, 0x16, 0x17, 0x1C, 0x1D, 0x1E, 0x1F);
SIMD_INLINE v128_s16 HorizontalAdd(v128_s16 a, v128_s16 b)
{
return vec_add(vec_perm(a, b, K8_PERM_HADD0), vec_perm(a, b, K8_PERM_HADD1));
}
template <bool align> SIMD_INLINE v128_u16 LoadAndConvertY(const uint8_t * bgra, v128_s16 & b_r, v128_s16 & g_1)
{
v128_s16 _b_r[2], _g_1[2];
LoadPreparedBgra<align>(bgra + 0, _b_r[0], _g_1[0]);
LoadPreparedBgra<align>(bgra + A, _b_r[1], _g_1[1]);
b_r = HorizontalAdd(_b_r[0], _b_r[1]);
g_1 = HorizontalAdd(_g_1[0], _g_1[1]);
return SaturateI16ToU8(vec_add((v128_s16)K16_Y_ADJUST, vec_pack(BgrToY(_b_r[0], _g_1[0]), BgrToY(_b_r[1], _g_1[1]))));
}
template <bool align> SIMD_INLINE v128_u8 LoadAndConvertY(const uint8_t * bgra, v128_s16 b_r[2], v128_s16 g_1[2])
{
return vec_pack(LoadAndConvertY<align>(bgra, b_r[0], g_1[0]), LoadAndConvertY<align>(bgra + DA, b_r[1], g_1[1]));
}
SIMD_INLINE void Average(v128_s16 & a, v128_s16 & b)
{
a = (v128_s16)vec_sr(vec_add(vec_add(a, b), (v128_s16)K16_0002), K16_0002);
}
SIMD_INLINE v128_u16 ConvertU(v128_s16 b_r[2], v128_s16 g_1[2])
{
return SaturateI16ToU8(vec_add((v128_s16)K16_UV_ADJUST, vec_pack(BgrToU(b_r[0], g_1[0]), BgrToU(b_r[1], g_1[1]))));
}
SIMD_INLINE v128_u16 ConvertV(v128_s16 b_r[2], v128_s16 g_1[2])
{
return SaturateI16ToU8(vec_add((v128_s16)K16_UV_ADJUST, vec_pack(BgrToV(b_r[0], g_1[0]), BgrToV(b_r[1], g_1[1]))));
}
template <bool align, bool first> SIMD_INLINE void BgraToYuv420p(const uint8_t * bgra0, size_t bgraStride,
Storer<align> & y0, Storer<align> & y1, Storer<align> & u, Storer<align> & v)
{
const uint8_t * bgra1 = bgra0 + bgraStride;
v128_s16 _b_r[2][2][2], _g_1[2][2][2];
Store<align, first>(y0, LoadAndConvertY<align>(bgra0, _b_r[0][0], _g_1[0][0]));
Store<align, false>(y0, LoadAndConvertY<align>(bgra0 + QA, _b_r[0][1], _g_1[0][1]));
Store<align, first>(y1, LoadAndConvertY<align>(bgra1, _b_r[1][0], _g_1[1][0]));
Store<align, false>(y1, LoadAndConvertY<align>(bgra1 + QA, _b_r[1][1], _g_1[1][1]));
Average(_b_r[0][0][0], _b_r[1][0][0]);
Average(_b_r[0][0][1], _b_r[1][0][1]);
Average(_b_r[0][1][0], _b_r[1][1][0]);
Average(_b_r[0][1][1], _b_r[1][1][1]);
Average(_g_1[0][0][0], _g_1[1][0][0]);
Average(_g_1[0][0][1], _g_1[1][0][1]);
Average(_g_1[0][1][0], _g_1[1][1][0]);
Average(_g_1[0][1][1], _g_1[1][1][1]);
Store<align, first>(u, vec_pack(ConvertU(_b_r[0][0], _g_1[0][0]), ConvertU(_b_r[0][1], _g_1[0][1])));
Store<align, first>(v, vec_pack(ConvertV(_b_r[0][0], _g_1[0][0]), ConvertV(_b_r[0][1], _g_1[0][1])));
}
template <bool align> void BgraToYuv420p(const uint8_t * bgra, size_t width, size_t height, size_t bgraStride, uint8_t * y, size_t yStride,
uint8_t * u, size_t uStride, uint8_t * v, size_t vStride)
{
assert((width%2 == 0) && (height%2 == 0) && (width >= DA) && (height >= 2));
if(align)
{
assert(Aligned(y) && Aligned(yStride) && Aligned(u) && Aligned(uStride));
assert(Aligned(v) && Aligned(vStride) && Aligned(bgra) && Aligned(bgraStride));
}
size_t alignedWidth = AlignLo(width, DA);
const size_t A8 = A*8;
for(size_t row = 0; row < height; row += 2)
{
Storer<align> _y0(y), _y1(y + yStride), _u(u), _v(v);
BgraToYuv420p<align, true>(bgra, bgraStride, _y0, _y1, _u, _v);
for(size_t col = DA, colBgra = A8; col < alignedWidth; col += DA, colBgra += A8)
BgraToYuv420p<align, false>(bgra + colBgra, bgraStride, _y0, _y1, _u, _v);
Flush(_y0, _y1, _u, _v);
if(width != alignedWidth)
{
size_t offset = width - DA;
Storer<false> _y0(y + offset), _y1(y + offset + yStride), _u(u + offset/2), _v(v + offset/2);
BgraToYuv420p<false, true>(bgra + offset*4, bgraStride, _y0, _y1, _u, _v);
Flush(_y0, _y1, _u, _v);
}
y += 2*yStride;
u += uStride;
v += vStride;
bgra += 2*bgraStride;
}
}
void BgraToYuv420p(const uint8_t * bgra, size_t width, size_t height, size_t bgraStride, uint8_t * y, size_t yStride,
uint8_t * u, size_t uStride, uint8_t * v, size_t vStride)
{
if(Aligned(y) && Aligned(yStride) && Aligned(u) && Aligned(uStride)
&& Aligned(v) && Aligned(vStride) && Aligned(bgra) && Aligned(bgraStride))
BgraToYuv420p<true>(bgra, width, height, bgraStride, y, yStride, u, uStride, v, vStride);
else
BgraToYuv420p<false>(bgra, width, height, bgraStride, y, yStride, u, uStride, v, vStride);
}
SIMD_INLINE void Average(v128_s16 a[2][2])
{
a[0][0] = (v128_s16)vec_sr(vec_add(a[0][0], (v128_s16)K16_0001), K16_0001);
a[0][1] = (v128_s16)vec_sr(vec_add(a[0][1], (v128_s16)K16_0001), K16_0001);
a[1][0] = (v128_s16)vec_sr(vec_add(a[1][0], (v128_s16)K16_0001), K16_0001);
a[1][1] = (v128_s16)vec_sr(vec_add(a[1][1], (v128_s16)K16_0001), K16_0001);
}
template <bool align, bool first> SIMD_INLINE void BgraToYuv422p(const uint8_t * bgra, Storer<align> & y, Storer<align> & u, Storer<align> & v)
{
v128_s16 _b_r[2][2], _g_1[2][2];
Store<align, first>(y, LoadAndConvertY<align>(bgra, _b_r[0], _g_1[0]));
Store<align, false>(y, LoadAndConvertY<align>(bgra + QA, _b_r[1], _g_1[1]));
Average(_b_r);
Average(_g_1);
Store<align, first>(u, vec_pack(ConvertU(_b_r[0], _g_1[0]), ConvertU(_b_r[1], _g_1[1])));
Store<align, first>(v, vec_pack(ConvertV(_b_r[0], _g_1[0]), ConvertV(_b_r[1], _g_1[1])));
}
template <bool align> void BgraToYuv422p(const uint8_t * bgra, size_t width, size_t height, size_t bgraStride, uint8_t * y, size_t yStride,
uint8_t * u, size_t uStride, uint8_t * v, size_t vStride)
{
assert((width%2 == 0) && (width >= DA));
if(align)
{
assert(Aligned(y) && Aligned(yStride) && Aligned(u) && Aligned(uStride));
assert(Aligned(v) && Aligned(vStride) && Aligned(bgra) && Aligned(bgraStride));
}
size_t alignedWidth = AlignLo(width, DA);
const size_t A8 = A*8;
for(size_t row = 0; row < height; ++row)
{
Storer<align> _y(y), _u(u), _v(v);
BgraToYuv422p<align, true>(bgra, _y, _u, _v);
for(size_t col = DA, colBgra = A8; col < alignedWidth; col += DA, colBgra += A8)
BgraToYuv422p<align, false>(bgra + colBgra, _y, _u, _v);
Flush(_y, _u, _v);
if(width != alignedWidth)
{
size_t offset = width - DA;
Storer<false> _y(y + offset), _u(u + offset/2), _v(v + offset/2);
BgraToYuv422p<false, true>(bgra + offset*4, _y, _u, _v);
Flush(_y, _u, _v);
}
y += yStride;
u += uStride;
v += vStride;
bgra += bgraStride;
}
}
void BgraToYuv422p(const uint8_t * bgra, size_t width, size_t height, size_t bgraStride, uint8_t * y, size_t yStride,
uint8_t * u, size_t uStride, uint8_t * v, size_t vStride)
{
if(Aligned(y) && Aligned(yStride) && Aligned(u) && Aligned(uStride)
&& Aligned(v) && Aligned(vStride) && Aligned(bgra) && Aligned(bgraStride))
BgraToYuv422p<true>(bgra, width, height, bgraStride, y, yStride, u, uStride, v, vStride);
else
BgraToYuv422p<false>(bgra, width, height, bgraStride, y, yStride, u, uStride, v, vStride);
}
SIMD_INLINE v128_u16 ConvertY(v128_s16 b_r[2], v128_s16 g_1[2])
{
return SaturateI16ToU8(vec_add((v128_s16)K16_Y_ADJUST, vec_pack(BgrToY(b_r[0], g_1[0]), BgrToY(b_r[1], g_1[1]))));
}
template <bool align, bool first> SIMD_INLINE void BgraToYuv444p(const uint8_t * bgra,
Storer<align> & y, Storer<align> & u, Storer<align> & v)
{
v128_s16 _b_r[2][2], _g_1[2][2];
LoadPreparedBgra<align>(bgra + 0, _b_r[0][0], _g_1[0][0]);
LoadPreparedBgra<align>(bgra + A, _b_r[0][1], _g_1[0][1]);
LoadPreparedBgra<align>(bgra + 2*A, _b_r[1][0], _g_1[1][0]);
LoadPreparedBgra<align>(bgra + 3*A, _b_r[1][1], _g_1[1][1]);
Store<align, first>(y, vec_pack(ConvertY(_b_r[0], _g_1[0]), ConvertY(_b_r[1], _g_1[1])));
Store<align, first>(u, vec_pack(ConvertU(_b_r[0], _g_1[0]), ConvertU(_b_r[1], _g_1[1])));
Store<align, first>(v, vec_pack(ConvertV(_b_r[0], _g_1[0]), ConvertV(_b_r[1], _g_1[1])));
}
template <bool align> void BgraToYuv444p(const uint8_t * bgra, size_t width, size_t height, size_t bgraStride, uint8_t * y, size_t yStride,
uint8_t * u, size_t uStride, uint8_t * v, size_t vStride)
{
assert(width >= A);
if(align)
{
assert(Aligned(y) && Aligned(yStride) && Aligned(u) && Aligned(uStride));
assert(Aligned(v) && Aligned(vStride) && Aligned(bgra) && Aligned(bgraStride));
}
size_t alignedWidth = AlignLo(width, A);
for(size_t row = 0; row < height; ++row)
{
Storer<align> _y(y), _u(u), _v(v);
BgraToYuv444p<align, true>(bgra, _y, _u, _v);
for(size_t col = A, colBgra = QA; col < alignedWidth; col += A, colBgra += QA)
BgraToYuv444p<align, false>(bgra + colBgra, _y, _u, _v);
Flush(_y, _u, _v);
if(width != alignedWidth)
{
size_t offset = width - A;
Storer<false> _y(y + offset), _u(u + offset), _v(v + offset);
BgraToYuv444p<false, true>(bgra + offset*4, _y, _u, _v);
Flush(_y, _u, _v);
}
y += yStride;
u += uStride;
v += vStride;
bgra += bgraStride;
}
}
void BgraToYuv444p(const uint8_t * bgra, size_t width, size_t height, size_t bgraStride, uint8_t * y, size_t yStride,
uint8_t * u, size_t uStride, uint8_t * v, size_t vStride)
{
if(Aligned(y) && Aligned(yStride) && Aligned(u) && Aligned(uStride)
&& Aligned(v) && Aligned(vStride) && Aligned(bgra) && Aligned(bgraStride))
BgraToYuv444p<true>(bgra, width, height, bgraStride, y, yStride, u, uStride, v, vStride);
else
BgraToYuv444p<false>(bgra, width, height, bgraStride, y, yStride, u, uStride, v, vStride);
}
}
#endif// SIMD_VMX_ENABLE
}
| 51.065217 | 161 | 0.552008 | aestesis |
1416e2689f95eccc7178d83270eaa1c99dafde70 | 4,280 | cpp | C++ | src/xray/xr_3da/xrGame/PHCollisionDamageReceiver.cpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 8 | 2016-01-25T20:18:51.000Z | 2019-03-06T07:00:04.000Z | src/xray/xr_3da/xrGame/PHCollisionDamageReceiver.cpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | null | null | null | src/xray/xr_3da/xrGame/PHCollisionDamageReceiver.cpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 3 | 2016-02-14T01:20:43.000Z | 2021-02-03T11:19:11.000Z | #include "stdafx.h"
#include "phcollisiondamagereceiver.h"
#include "PhysicsShellHolder.h"
#include "xr_ini.h"
#include "../skeletoncustom.h"
#include "geometry.h"
#include "PhysicsShell.h"
#include "GameMtlLib.h"
#include "Physics.h"
#include "../../xrNetServer/net_utils.h"
#include "xrMessages.h"
#include "CharacterPhysicsSupport.h"
void CPHCollisionDamageReceiver::BoneInsert(u16 id,float k)
{
R_ASSERT2(FindBone(id)==m_controled_bones.end(),"duplicate bone!");
m_controled_bones.push_back(SControledBone(id,k));
}
void CPHCollisionDamageReceiver::Init()
{
CPhysicsShellHolder *sh =PPhysicsShellHolder ();
CKinematics *K =smart_cast<CKinematics*>(sh->Visual());
CInifile *ini=K->LL_UserData();
if(ini->section_exist("collision_damage"))
{
CInifile::Sect& data = ini->r_section("collision_damage");
for (CInifile::SectCIt I=data.Data.begin(); I!=data.Data.end(); I++){
const CInifile::Item& item = *I;
u16 index = K->LL_BoneID(*item.first);
R_ASSERT3(index != BI_NONE, "Wrong bone name", *item.first);
BoneInsert(index,float(atof(*item.second)));
CODEGeom* og= sh->PPhysicsShell()->get_GeomByID(index);
//R_ASSERT3(og, "collision damage bone has no physics collision", *item.first);
if(og)og->add_obj_contact_cb(CollisionCallback);
}
}
}
void CPHCollisionDamageReceiver::CollisionCallback(bool& do_colide,bool bo1,dContact& c,SGameMtl* material_1,SGameMtl* material_2)
{
if(material_1->Flags.test(SGameMtl::flPassable)||material_2->Flags.test(SGameMtl::flPassable))return;
dBodyID b1 = dGeomGetBody(c.geom.g1) ;
dBodyID b2 = dGeomGetBody(c.geom.g2) ;
dxGeomUserData *ud_self = bo1 ? retrieveGeomUserData(c.geom.g1):retrieveGeomUserData(c.geom.g2);
dxGeomUserData *ud_damager = bo1 ? retrieveGeomUserData(c.geom.g2):retrieveGeomUserData(c.geom.g1);
SGameMtl *material_self = bo1 ? material_1:material_2;
SGameMtl *material_damager = bo1 ? material_2:material_1;
VERIFY (ud_self);
CPhysicsShellHolder *o_self = ud_self->ph_ref_object;
CPhysicsShellHolder *o_damager = NULL;if(ud_damager)o_damager=ud_damager->ph_ref_object;
u16 source_id = o_damager ? o_damager->ID():u16(-1);
CPHCollisionDamageReceiver *dr =o_self->PHCollisionDamageReceiver();
VERIFY2(dr,"wrong callback");
float damager_material_factor=material_damager->fBounceDamageFactor;
if(ud_damager&&ud_damager->ph_object&&ud_damager->ph_object->CastType()==CPHObject::tpCharacter)
{
CCharacterPhysicsSupport* phs=o_damager->character_physics_support();
if(phs->IsSpecificDamager())damager_material_factor=phs->BonceDamageFactor();
}
float dfs=(material_self->fBounceDamageFactor+damager_material_factor);
if(fis_zero(dfs)) return;
Fvector dir;dir.set(*(Fvector*)c.geom.normal);
Fvector pos;
pos.sub(*(Fvector*)c.geom.pos,*(Fvector*)dGeomGetPosition(bo1 ? c.geom.g1:c.geom.g2));//it is not true pos in bone space
dr->Hit(source_id,ud_self->bone_id,E_NL(b1,b2,c.geom.normal)*damager_material_factor/dfs,dir,pos);
}
const static float hit_threthhold=5.f;
void CPHCollisionDamageReceiver::Hit(u16 source_id,u16 bone_id,float power,const Fvector& dir,Fvector &pos )
{
DAMAGE_BONES_I i=FindBone(bone_id);
if(i==m_controled_bones.end())return;
power*=i->second;
if(power<hit_threthhold)return;
NET_Packet P;
CPhysicsShellHolder *ph=PPhysicsShellHolder();
SHit HS;
HS.GenHeader(GE_HIT,ph->ID()); // ph->u_EventGen(P,GE_HIT,ph->ID());
HS.whoID = ph->ID(); // P.w_u16 (ph->ID());
HS.weaponID = source_id; // P.w_u16 (source_id);
HS.dir = dir; // P.w_dir (dir);
HS.power = power; // P.w_float (power);
HS.boneID = s16(bone_id); // P.w_s16 (s16(bone_id));
HS.p_in_bone_space = pos; // P.w_vec3 (pos);
HS.impulse = 0.f; // P.w_float (0.f);
HS.hit_type = (ALife::eHitTypeStrike); // P.w_u16 (ALife::eHitTypeStrike);
HS.Write_Packet(P);
ph->u_EventSend(P);
}
void CPHCollisionDamageReceiver::Clear()
{
//CPhysicsShellHolder *sh =PPhysicsShellHolder ();
//xr_map<u16,float>::iterator i=m_controled_bones.begin(),e=m_controled_bones.end();
//for(;e!=i;++i)
//{
// CODEGeom* og= sh->PPhysicsShell()->get_GeomByID(i->first);
// if(og)og->set_obj_contact_cb(NULL);
//}
m_controled_bones.clear();
} | 37.54386 | 130 | 0.716355 | OLR-xray |
1418868ec4b68d94f251135d77501bcb795e3d55 | 992 | hpp | C++ | src/graphics/widgets/charge_props.hpp | svlv/elfield | 612e21dc74a82306cd2a623a54af1412936999e7 | [
"MIT"
] | null | null | null | src/graphics/widgets/charge_props.hpp | svlv/elfield | 612e21dc74a82306cd2a623a54af1412936999e7 | [
"MIT"
] | null | null | null | src/graphics/widgets/charge_props.hpp | svlv/elfield | 612e21dc74a82306cd2a623a54af1412936999e7 | [
"MIT"
] | null | null | null | #pragma once
#include "physics/charge.hpp"
#include <gtkmm/dialog.h>
#include <gtkmm/drawingarea.h>
#include <map>
#include <string>
namespace elfield
{
class charge_props : public Gtk::Dialog
{
public:
explicit charge_props(Gtk::Window& parent, const charge_ptr& charge,
Gtk::Widget& area);
~charge_props() = default;
using widgets_t = std::map<std::string, std::unique_ptr<Gtk::Widget>>;
protected:
void on_response(int response_id) override;
private:
void _on_button_charge_up_click();
void _on_button_charge_down_click();
void _on_button_charge_left_click();
void _on_button_charge_right_click();
void _on_button_value_up_click();
void _on_button_value_down_click();
void _update_entry_x();
void _update_entry_y();
void _update_entry_value();
charge_ptr _charge;
charge_ptr _original;
widgets_t _widgets;
std::reference_wrapper<Gtk::Widget> _drawing_area;
};
} // namespace elfield
| 24.8 | 74 | 0.709677 | svlv |
14198454f9be23e819628f4ee2fb9c2518ef190c | 1,602 | hpp | C++ | src/lib/model/hpp/administrador.hpp | iagoizi/poo-petshop-cpp | 1eb9f6858ed6f55f3c1d07024b18ef67b0533358 | [
"MIT"
] | null | null | null | src/lib/model/hpp/administrador.hpp | iagoizi/poo-petshop-cpp | 1eb9f6858ed6f55f3c1d07024b18ef67b0533358 | [
"MIT"
] | null | null | null | src/lib/model/hpp/administrador.hpp | iagoizi/poo-petshop-cpp | 1eb9f6858ed6f55f3c1d07024b18ef67b0533358 | [
"MIT"
] | null | null | null | #ifndef ADMINISTRADOR_HPP
#define ADMINISTRADOR_HPP
#include "lib.hpp"
#include "vendedor.hpp"
#include "veterinario.hpp"
#include "petshop.hpp"
#include "usuario.hpp"
class Administrador : public Vendedor, public Veterinario
{
public:
Administrador(PetShop *petshop, string nome = "");
~Administrador();
/*Incrementa uma certa quantidade do produto no estoque*/
void reposicaoEstoque(Produto produto, int qtd, string descricao, double preco);
/*Registra que um determinado equipamento foi comprado neste momento*/
void comprarEquipamentos(string equipamento, double preco, int qtd);
/*Cadastra um novo veterinário, o adicionando no vetor de usuários*/
void cadastrarVeterinario(string nome, string usuario, string senha, double salario);
/*Cadastra um novo vendedor, o adicionando no vetor de usuários*/
void cadastrarVendedor(string nome, string usuario, string senha, double salario);
/*Cadastra um novo produto, o adicionando no vetor de produtos cadastrados*/
void cadastrarProduto(string nome, double preco, int quantidade, long id);
/*Cadastra um novo servico, o adicionando no vetor de servicos*/
void cadastrarServico(string nome, double preco, long id);
/*Cadastra um novo vendedor, o adicionando no vetor de usuários*/
void listarFuncionarios();
/*Imprime um relatório com os históricos do sistema*/
void gerarRelatorio();
/*Registra que uma determinada conta foi paga neste exato momento*/
void pagarConta(string descricao, Data dataVencimento, double valor);
};
#endif | 43.297297 | 90 | 0.734082 | iagoizi |
141b1d569f864079780ac39925325414e453a555 | 5,048 | cpp | C++ | src/gui/XML/XMLCircleAttrs.cpp | alicemona/Smala | 6f66c3b4bb111993a6bcf148e84c229fb3fa3534 | [
"BSD-2-Clause"
] | null | null | null | src/gui/XML/XMLCircleAttrs.cpp | alicemona/Smala | 6f66c3b4bb111993a6bcf148e84c229fb3fa3534 | [
"BSD-2-Clause"
] | null | null | null | src/gui/XML/XMLCircleAttrs.cpp | alicemona/Smala | 6f66c3b4bb111993a6bcf148e84c229fb3fa3534 | [
"BSD-2-Clause"
] | null | null | null | /* C++ code produced by gperf version 3.0.3 */
/* Command-line: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/gperf -L C++ -t -N djn_XMLCircleAttrsLookup -Z XMLCircleAttrs_Hash src/gui/XML/XMLCircleAttrs.gperf */
/* Computed positions: -k'2' */
#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \
&& ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \
&& (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \
&& ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \
&& ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \
&& ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \
&& ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \
&& ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \
&& ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \
&& ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \
&& ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \
&& ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \
&& ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \
&& ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \
&& ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \
&& ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \
&& ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \
&& ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \
&& ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \
&& ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \
&& ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \
&& ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \
&& ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126))
/* The character set is not based on ISO-646. */
#error "gperf generated tables don't work with this execution character set. Please report a bug to <bug-gnu-gperf@gnu.org>."
#endif
#line 17 "src/gui/XML/XMLCircleAttrs.gperf"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "../../core/core.h"
#include "../gui-dev.h"
#define register
using namespace djnn;
static int ParseCx (Process**, const char*);
static int ParseCy (Process**, const char*);
static int ParseR (Process**, const char*);
#line 33 "src/gui/XML/XMLCircleAttrs.gperf"
#define TOTAL_KEYWORDS 3
#define MIN_WORD_LENGTH 1
#define MAX_WORD_LENGTH 2
#define MIN_HASH_VALUE 1
#define MAX_HASH_VALUE 3
/* maximum key range = 3, duplicates = 0 */
inline unsigned int
XMLCircleAttrs_Hash::hash (register const char *str, register unsigned int len)
{
static unsigned char asso_values[] =
{
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
1, 0, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4
};
register unsigned int hval = len;
switch (hval)
{
default:
hval += asso_values[(unsigned char)str[1]];
/*FALLTHROUGH*/
case 1:
break;
}
return hval;
}
djn_XMLAttrHandler *
XMLCircleAttrs_Hash::djn_XMLCircleAttrsLookup (register const char *str, register unsigned int len)
{
static djn_XMLAttrHandler wordlist[] =
{
{""},
#line 38 "src/gui/XML/XMLCircleAttrs.gperf"
{"r", &ParseR},
#line 37 "src/gui/XML/XMLCircleAttrs.gperf"
{"cy", &ParseCy},
#line 36 "src/gui/XML/XMLCircleAttrs.gperf"
{"cx", &ParseCx}
};
if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
{
unsigned int key = hash (str, len);
if (key <= MAX_HASH_VALUE)
{
register const char *s = wordlist[key].name;
if (*str == *s && !strcmp (str + 1, s + 1))
return &wordlist[key];
}
}
return 0;
}
#line 39 "src/gui/XML/XMLCircleAttrs.gperf"
struct djn_CircleArgs djn_CircleArgs = {0., 0., 0.};
static int ParseCx(Process** e, const char* v) {
return XML_Utils::djn_XMLParseLength(&djn_CircleArgs.cx, v);
}
static int ParseCy(Process** e, const char* v) {
return XML_Utils::djn_XMLParseLength(&djn_CircleArgs.cy, v);
}
static int ParseR(Process** e, const char* v) {
return XML_Utils::djn_XMLParseLength(&djn_CircleArgs.r, v);
}
| 34.575342 | 207 | 0.443542 | alicemona |
141be00392174277455397f8428485598dca6580 | 2,901 | cpp | C++ | sdl/6821OT_code_bundle/Alien Attack/src/MainMenuState.cpp | numfo/tryme | 596b48160cc1c2377bee05675570f62df4f37d9d | [
"MIT"
] | null | null | null | sdl/6821OT_code_bundle/Alien Attack/src/MainMenuState.cpp | numfo/tryme | 596b48160cc1c2377bee05675570f62df4f37d9d | [
"MIT"
] | null | null | null | sdl/6821OT_code_bundle/Alien Attack/src/MainMenuState.cpp | numfo/tryme | 596b48160cc1c2377bee05675570f62df4f37d9d | [
"MIT"
] | null | null | null | //
// MenuState.cpp
// SDL Game Programming Book
//
// Created by shaun mitchell on 09/02/2013.
// Copyright (c) 2013 shaun mitchell. All rights reserved.
//
#include <iostream>
#include "MainMenuState.h"
#include "TextureManager.h"
#include "Game.h"
#include "MenuButton.h"
#include "PlayState.h"
#include "InputHandler.h"
#include "StateParser.h"
#include <assert.h>
const std::string MainMenuState::s_menuID = "MENU";
// Callbacks
void MainMenuState::s_menuToPlay()
{
TheGame::Instance()->getStateMachine()->changeState(new PlayState());
}
void MainMenuState::s_exitFromMenu()
{
TheGame::Instance()->quit();
}
// end callbacks
void MainMenuState::update()
{
if(TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_SPACE))
{
s_menuToPlay();
}
if(!m_gameObjects.empty())
{
for(int i = 0; i < m_gameObjects.size(); i++)
{
if(m_gameObjects[i] != 0)
{
m_gameObjects[i]->update();
}
}
}
}
void MainMenuState::render()
{
if(m_loadingComplete && !m_gameObjects.empty())
{
for(int i = 0; i < m_gameObjects.size(); i++)
{
m_gameObjects[i]->draw();
}
}
}
bool MainMenuState::onEnter()
{
// parse the state
StateParser stateParser;
stateParser.parseState("assets/attack.xml", s_menuID, &m_gameObjects, &m_textureIDList);
m_callbacks.push_back(0);
m_callbacks.push_back(s_menuToPlay);
m_callbacks.push_back(s_exitFromMenu);
// set the callbacks for menu items
setCallbacks(m_callbacks);
m_loadingComplete = true;
std::cout << "entering MenuState\n";
return true;
}
bool MainMenuState::onExit()
{
m_exiting = true;
// clean the game objects
if(m_loadingComplete && !m_gameObjects.empty())
{
m_gameObjects.back()->clean();
m_gameObjects.pop_back();
}
m_gameObjects.clear();
/* clear the texture manager
for(int i = 0; i < m_textureIDList.size(); i++)
{
TheTextureManager::Instance()->clearFromTextureMap(m_textureIDList[i]);
}
*/
// reset the input handler
TheInputHandler::Instance()->reset();
std::cout << "exiting MenuState\n";
return true;
}
void MainMenuState::setCallbacks(const std::vector<Callback>& callbacks)
{
// go through the game objects
if(!m_gameObjects.empty())
{
for(int i = 0; i < m_gameObjects.size(); i++)
{
// if they are of type MenuButton then assign a callback based on the id passed in from the file
if(dynamic_cast<MenuButton*>(m_gameObjects[i]))
{
MenuButton* pButton = dynamic_cast<MenuButton*>(m_gameObjects[i]);
pButton->setCallback(callbacks[pButton->getCallbackID()]);
}
}
}
}
| 23.208 | 109 | 0.602896 | numfo |
1420eaad71a82a254e9665c9af84f7c391a45be4 | 20,607 | cxx | C++ | src/external/marray/test/dpd_marray_view.cxx | devinamatthews/tensor | 7d979b6624071879383377611cb2fa483b6a3104 | [
"BSD-3-Clause"
] | 86 | 2016-05-30T16:08:24.000Z | 2022-03-30T22:57:35.000Z | src/external/marray/test/dpd_marray_view.cxx | devinamatthews/tensor | 7d979b6624071879383377611cb2fa483b6a3104 | [
"BSD-3-Clause"
] | 41 | 2017-02-02T22:28:17.000Z | 2022-02-22T16:51:14.000Z | src/external/marray/test/dpd_marray_view.cxx | devinamatthews/tensor | 7d979b6624071879383377611cb2fa483b6a3104 | [
"BSD-3-Clause"
] | 26 | 2016-05-30T16:08:33.000Z | 2021-12-29T03:02:30.000Z | #include "gtest/gtest.h"
#include "dpd_marray.hpp"
using namespace std;
using namespace MArray;
template <typename T, unsigned... Sizes>
struct arrays_helper;
template <typename T, unsigned Size1, unsigned Size2>
struct arrays_helper<T, Size1, Size2>
{
typedef array<array<T,Size2>,Size1> type;
};
template <typename T, unsigned Size1, unsigned Size2, unsigned Size3>
struct arrays_helper<T, Size1, Size2, Size3>
{
typedef array<array<array<T,Size3>,Size2>,Size1> type;
};
template <typename T, unsigned... Sizes>
using arrays = typename arrays_helper<T, Sizes...>::type;
static array<dpd_layout,6> layouts =
{{
PREFIX_ROW_MAJOR,
PREFIX_COLUMN_MAJOR,
BLOCKED_ROW_MAJOR,
BLOCKED_COLUMN_MAJOR,
BALANCED_ROW_MAJOR,
BALANCED_COLUMN_MAJOR,
}};
/*
3 2 1 3
1 2 2 4
168 42 11 3 - 126 22 3 0
168 42 10 4 - 126 20 4 0
3 8 24 168 - 0 6 8 72
1 8 24 168 - 0 2 8 72
row col
8 11 - 6 3 - 6 3
8 10 - 6 4 - 2 6
168 88 88
168 80 88
*/
static arrays<unsigned,6,4> perms =
{{{3,2,1,0}, {0,1,2,3}, {3,2,1,0}, {0,1,2,3}, {3,2,1,0}, {0,1,2,3}}};
static arrays<unsigned,8,4> irreps =
{{{1,0,0,0}, {0,1,0,0}, {0,0,1,0}, {1,1,1,0},
{0,0,0,1}, {1,1,0,1}, {1,0,1,1}, {0,1,1,1}}};
static arrays<len_type,8,4> lengths =
{{{1,2,1,3}, {3,2,1,3}, {3,2,2,3}, {1,2,2,3},
{3,2,1,4}, {1,2,1,4}, {1,2,2,4}, {3,2,2,4}}};
static arrays<stride_type,6,8,4> strides =
{{
{{{42,11, 3, 1}, {42,11, 3, 1}, {42,10, 3, 1}, {42,10, 3, 1},
{42,10, 4, 1}, {42,10, 4, 1}, {42,11, 4, 1}, {42,11, 4, 1}}},
{{{ 1, 1, 8,24}, { 1, 3, 8,24}, { 1, 3, 8,24}, { 1, 1, 8,24},
{ 1, 3, 8,24}, { 1, 1, 8,24}, { 1, 1, 8,24}, { 1, 3, 8,24}}},
{{{ 6, 3, 3, 1}, { 6, 3, 3, 1}, {12, 6, 3, 1}, {12, 6, 3, 1},
{ 8, 4, 4, 1}, { 8, 4, 4, 1}, {16, 8, 4, 1}, {16, 8, 4, 1}}},
{{{ 1, 1, 2, 2}, { 1, 3, 6, 6}, { 1, 3, 6,12}, { 1, 1, 2, 4},
{ 1, 3, 6, 6}, { 1, 1, 2, 2}, { 1, 1, 2, 4}, { 1, 3, 6,12}}},
{{{22,11, 3, 1}, {22,11, 3, 1}, {20,10, 3, 1}, {20,10, 3, 1},
{20,10, 4, 1}, {20,10, 4, 1}, {22,11, 4, 1}, {22,11, 4, 1}}},
{{{ 1, 1, 8, 8}, { 1, 3, 8, 8}, { 1, 3, 8,16}, { 1, 1, 8,16},
{ 1, 3, 8, 8}, { 1, 1, 8, 8}, { 1, 1, 8,16}, { 1, 3, 8,16}}}
}};
static arrays<stride_type,6,8> offsets =
{{
{126, 20, 4,152, 0,148,129, 23},
{ 0, 2, 8, 14, 72, 78, 80, 82},
{162,144, 96,132, 0, 24, 80, 32},
{ 0, 42,108, 22,144, 34, 6, 60},
{ 80+66, 80 , 0+4, 0+60+4,
0 , 0+60, 80+66+3, 80 +3},
{ 0 , 0 +2, 88 , 88 +6,
88+48, 88+48+6, 0+24, 0+24+2}
}};
#define CHECK_DPD_MARRAY_VIEW_RESET(v) \
EXPECT_EQ(nullptr, v.data()); \
EXPECT_EQ(0u, v.irrep()); \
EXPECT_EQ(0u, v.num_irreps()); \
EXPECT_EQ((array<unsigned,4>{}), v.permutation()); \
EXPECT_EQ((arrays<len_type,4,8>{}), v.lengths());
#define CHECK_DPD_MARRAY_VIEW(v,d,j) \
SCOPED_TRACE(j); \
EXPECT_EQ(d, v.data()); \
EXPECT_EQ(1u, v.irrep()); \
EXPECT_EQ(2u, v.num_irreps()); \
EXPECT_EQ(perms[j], v.permutation()); \
EXPECT_EQ((arrays<len_type,4,8>{{{3, 1}, {2, 2}, {1, 2}, {3, 4}}}), v.lengths()); \
\
{ \
auto vs = v(1,0,0,0); \
EXPECT_EQ(d + offsets[j][0], vs.data()); \
EXPECT_EQ(lengths[0], vs.lengths()); \
EXPECT_EQ(strides[j][0], vs.strides()); \
} \
\
{ \
auto vs = v({0,1,0,0}); \
EXPECT_EQ(d + offsets[j][1], vs.data()); \
EXPECT_EQ(lengths[1], vs.lengths()); \
EXPECT_EQ(strides[j][1], vs.strides()); \
} \
\
for (unsigned i = 2;i < 8;i++) \
{ \
SCOPED_TRACE(i); \
auto vs = v(irreps[i]); \
EXPECT_EQ(d + offsets[j][i], vs.data()); \
EXPECT_EQ(lengths[i], vs.lengths()); \
EXPECT_EQ(strides[j][i], vs.strides()); \
}
TEST(dpd_marray_view, constructor)
{
double tmp;
double* data = &tmp;
dpd_marray<double,4> v0(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, layouts[0]);
dpd_marray_view<double,4> v1;
CHECK_DPD_MARRAY_VIEW_RESET(v1)
for (unsigned j = 0;j < 6;j++)
{
dpd_marray_view<double,4> v2(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[j]);
CHECK_DPD_MARRAY_VIEW(v2, data, j)
}
dpd_marray_view<double,4> v3(1, 2, arrays<char,4,2>{{{3, 1}, {2, 2}, {1, 2}, {3, 4}}}, data, layouts[0]);
CHECK_DPD_MARRAY_VIEW(v3, data, 0)
dpd_marray_view<double,4> v5(v3);
CHECK_DPD_MARRAY_VIEW(v5, data, 0)
dpd_marray_view<double,4> v51(v0);
CHECK_DPD_MARRAY_VIEW(v51, v0.data(), 0)
dpd_marray_view<double,4> v6(dpd_marray_view<double,4>(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[0]));
CHECK_DPD_MARRAY_VIEW(v6, data, 0)
dpd_marray_view<const double,4> v9;
CHECK_DPD_MARRAY_VIEW_RESET(v9)
for (unsigned j = 0;j < 6;j++)
{
dpd_marray_view<const double,4> v10(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[j]);
CHECK_DPD_MARRAY_VIEW(v10, data, j)
}
dpd_marray_view<const double,4> v11(1, 2, arrays<char,4,2>{{{3, 1}, {2, 2}, {1, 2}, {3, 4}}}, data, layouts[0]);
CHECK_DPD_MARRAY_VIEW(v11, data, 0)
dpd_marray_view<const double,4> v13(v3);
CHECK_DPD_MARRAY_VIEW(v13, data, 0)
dpd_marray_view<const double,4> v131(v0);
CHECK_DPD_MARRAY_VIEW(v131, v0.data(), 0)
dpd_marray_view<const double,4> v14(v11);
CHECK_DPD_MARRAY_VIEW(v14, data, 0)
dpd_marray_view<const double,4> v15(dpd_marray_view<double,4>(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[0]));
CHECK_DPD_MARRAY_VIEW(v15, data, 0)
dpd_marray_view<const double,4> v16(dpd_marray_view<const double,4>(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[0]));
CHECK_DPD_MARRAY_VIEW(v16, data, 0)
}
TEST(dpd_marray_view, reset)
{
double tmp;
double* data = &tmp;
dpd_marray_view<double,4> v1;
dpd_marray_view<const double,4> v2;
dpd_marray_view<double,4> v3(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[0]);
dpd_marray_view<const double,4> v4(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[0]);
dpd_marray<double,4> v0(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, layouts[0]);
CHECK_DPD_MARRAY_VIEW_RESET(v1)
for (unsigned j = 0;j < 6;j++)
{
v1.reset(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[j]);
CHECK_DPD_MARRAY_VIEW(v1, data, j)
}
v1.reset(1, 2, arrays<char,4,2>{{{3, 1}, {2, 2}, {1, 2}, {3, 4}}}, data, layouts[0]);
CHECK_DPD_MARRAY_VIEW(v1, data, 0)
v1.reset(v3);
CHECK_DPD_MARRAY_VIEW(v1, data, 0)
v1.reset(v0);
CHECK_DPD_MARRAY_VIEW(v1, v0.data(), 0)
v1.reset(dpd_marray_view<double,4>(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[0]));
CHECK_DPD_MARRAY_VIEW(v1, data, 0)
v1.reset();
CHECK_DPD_MARRAY_VIEW_RESET(v1)
CHECK_DPD_MARRAY_VIEW_RESET(v2)
for (unsigned j = 0;j < 6;j++)
{
v2.reset(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[j]);
CHECK_DPD_MARRAY_VIEW(v2, data, j)
}
v2.reset(1, 2, arrays<char,4,2>{{{3, 1}, {2, 2}, {1, 2}, {3, 4}}}, data, layouts[0]);
CHECK_DPD_MARRAY_VIEW(v2, data, 0)
v2.reset(v3);
CHECK_DPD_MARRAY_VIEW(v2, data, 0)
v2.reset(v0);
CHECK_DPD_MARRAY_VIEW(v2, v0.data(), 0)
v2.reset(v4);
CHECK_DPD_MARRAY_VIEW(v2, data, 0)
v2.reset(dpd_marray_view<double,4>(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[0]));
CHECK_DPD_MARRAY_VIEW(v2, data, 0)
v2.reset(dpd_marray_view<const double,4>(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[0]));
CHECK_DPD_MARRAY_VIEW(v2, data, 0)
v2.reset();
CHECK_DPD_MARRAY_VIEW_RESET(v2)
}
TEST(dpd_marray_view, permute)
{
double tmp;
double* data = &tmp;
unsigned perm_irreps[8] = {1, 0, 2, 3, 4, 5, 7, 6};
unsigned perm_irreps2[8] = {4, 1, 0, 5, 2, 7, 6, 3};
arrays<unsigned,6,4> perms2 =
{{{2,3,1,0}, {1,0,2,3}, {2,3,1,0}, {1,0,2,3}, {2,3,1,0}, {1,0,2,3}}};
arrays<unsigned,6,4> perms3 =
{{{1,2,0,3}, {2,1,3,0}, {1,2,0,3}, {2,1,3,0}, {1,2,0,3}, {2,1,3,0}}};
for (unsigned j = 0;j < 6;j++)
{
SCOPED_TRACE(j);
dpd_marray_view<double,4> v1(1, 2, {{3, 1}, {2, 2}, {1, 2}, {3, 4}}, data, layouts[j]);
auto v2 = v1.permuted({1, 0, 2, 3});
EXPECT_EQ(data, v2.data());
EXPECT_EQ(1u, v2.irrep());
EXPECT_EQ(2u, v2.num_irreps());
EXPECT_EQ(perms2[j], v2.permutation());
EXPECT_EQ((arrays<len_type,4,8>{{{2, 2}, {3, 1}, {1, 2}, {3, 4}}}), v2.lengths());
for (unsigned i = 0;i < 8;i++)
{
SCOPED_TRACE(i);
std::array<len_type,4> len;
std::array<stride_type,4> stride;
for (unsigned k = 0;k < 4;k++)
{
len[k] = lengths[i][perms2[1][k]];
stride[k] = strides[j][i][perms2[1][k]];
}
auto vs = v2(irreps[perm_irreps[i]]);
EXPECT_EQ(data + offsets[j][i], vs.data());
EXPECT_EQ(len, vs.lengths());
EXPECT_EQ(stride, vs.strides());
}
auto v3 = v1.permuted(std::array<char,4>{1, 0, 2, 3});
EXPECT_EQ(data, v3.data());
EXPECT_EQ(1u, v3.irrep());
EXPECT_EQ(2u, v3.num_irreps());
EXPECT_EQ(perms2[j], v3.permutation());
EXPECT_EQ((arrays<len_type,4,8>{{{2, 2}, {3, 1}, {1, 2}, {3, 4}}}), v3.lengths());
for (unsigned i = 0;i < 8;i++)
{
SCOPED_TRACE(i);
std::array<len_type,4> len;
std::array<stride_type,4> stride;
for (unsigned k = 0;k < 4;k++)
{
len[k] = lengths[i][perms2[1][k]];
stride[k] = strides[j][i][perms2[1][k]];
}
auto vs = v3(irreps[perm_irreps[i]]);
EXPECT_EQ(data + offsets[j][i], vs.data());
EXPECT_EQ(len, vs.lengths());
EXPECT_EQ(stride, vs.strides());
}
v1.permute({1, 0, 2, 3});
EXPECT_EQ(data, v1.data());
EXPECT_EQ(1u, v1.irrep());
EXPECT_EQ(2u, v1.num_irreps());
EXPECT_EQ(perms2[j], v1.permutation());
EXPECT_EQ((arrays<len_type,4,8>{{{2, 2}, {3, 1}, {1, 2}, {3, 4}}}), v1.lengths());
for (unsigned i = 0;i < 8;i++)
{
SCOPED_TRACE(i);
std::array<len_type,4> len;
std::array<stride_type,4> stride;
for (unsigned k = 0;k < 4;k++)
{
len[k] = lengths[i][perms2[1][k]];
stride[k] = strides[j][i][perms2[1][k]];
}
auto vs = v1(irreps[perm_irreps[i]]);
EXPECT_EQ(data + offsets[j][i], vs.data());
EXPECT_EQ(len, vs.lengths());
EXPECT_EQ(stride, vs.strides());
}
v1.permute(std::array<char,4>{2, 0, 3, 1});
EXPECT_EQ(data, v1.data());
EXPECT_EQ(1u, v1.irrep());
EXPECT_EQ(2u, v1.num_irreps());
EXPECT_EQ(perms3[j], v1.permutation());
EXPECT_EQ((arrays<len_type,4,8>{{{1, 2}, {2, 2}, {3, 4}, {3, 1}}}), v1.lengths());
for (unsigned i = 0;i < 8;i++)
{
SCOPED_TRACE(i);
std::array<len_type,4> len;
std::array<stride_type,4> stride;
for (unsigned k = 0;k < 4;k++)
{
len[k] = lengths[i][perms3[1][k]];
stride[k] = strides[j][i][perms3[1][k]];
}
auto vs = v1(irreps[perm_irreps2[i]]);
EXPECT_EQ(data + offsets[j][i], vs.data());
EXPECT_EQ(len, vs.lengths());
EXPECT_EQ(stride, vs.strides());
}
}
}
TEST(dpd_marray_view, transpose)
{
double tmp;
double* data = &tmp;
arrays<unsigned,6,2> perms2 =
{{{0,1}, {1,0}, {0,1}, {1,0}, {0,1}, {1,0}}};
for (unsigned j = 0;j < 6;j++)
{
SCOPED_TRACE(j);
dpd_marray_view<double,2> v1(1, 2, {{3, 1}, {3, 4}}, data, layouts[j]);
auto v2 = v1.transposed();
EXPECT_EQ(data, v2.data());
EXPECT_EQ(1u, v2.irrep());
EXPECT_EQ(2u, v2.num_irreps());
EXPECT_EQ(perms2[j], v2.permutation());
EXPECT_EQ((arrays<len_type,2,8>{{{3, 4}, {3, 1}}}), v2.lengths());
if (j&1)
{
auto v21 = v2(1, 0);
EXPECT_EQ(data + 3, v21.data());
EXPECT_EQ((std::array<len_type,2>{4, 3}), v21.lengths());
EXPECT_EQ((std::array<len_type,2>{3, 1}), v21.strides());
auto v22 = v2(0, 1);
EXPECT_EQ(data + 0, v22.data());
EXPECT_EQ((std::array<len_type,2>{3, 1}), v22.lengths());
EXPECT_EQ((std::array<len_type,2>{1, 1}), v22.strides());
}
else
{
auto v21 = v2(1, 0);
EXPECT_EQ(data + 0, v21.data());
EXPECT_EQ((std::array<len_type,2>{4, 3}), v21.lengths());
EXPECT_EQ((std::array<len_type,2>{1, 4}), v21.strides());
auto v22 = v2(0, 1);
EXPECT_EQ(data + 12, v22.data());
EXPECT_EQ((std::array<len_type,2>{3, 1}), v22.lengths());
EXPECT_EQ((std::array<len_type,2>{1, 3}), v22.strides());
}
auto v3 = v1.T();
EXPECT_EQ(data, v3.data());
EXPECT_EQ(1u, v3.irrep());
EXPECT_EQ(2u, v3.num_irreps());
EXPECT_EQ(perms2[j], v3.permutation());
EXPECT_EQ((arrays<len_type,2,8>{{{3, 4}, {3, 1}}}), v3.lengths());
if (j&1)
{
auto v21 = v3(1, 0);
EXPECT_EQ(data + 3, v21.data());
EXPECT_EQ((std::array<len_type,2>{4, 3}), v21.lengths());
EXPECT_EQ((std::array<len_type,2>{3, 1}), v21.strides());
auto v22 = v3(0, 1);
EXPECT_EQ(data + 0, v22.data());
EXPECT_EQ((std::array<len_type,2>{3, 1}), v22.lengths());
EXPECT_EQ((std::array<len_type,2>{1, 1}), v22.strides());
}
else
{
auto v21 = v3(1, 0);
EXPECT_EQ(data + 0, v21.data());
EXPECT_EQ((std::array<len_type,2>{4, 3}), v21.lengths());
EXPECT_EQ((std::array<len_type,2>{1, 4}), v21.strides());
auto v22 = v3(0, 1);
EXPECT_EQ(data + 12, v22.data());
EXPECT_EQ((std::array<len_type,2>{3, 1}), v22.lengths());
EXPECT_EQ((std::array<len_type,2>{1, 3}), v22.strides());
}
v1.transpose();
EXPECT_EQ(data, v1.data());
EXPECT_EQ(1u, v1.irrep());
EXPECT_EQ(2u, v1.num_irreps());
EXPECT_EQ(perms2[j], v1.permutation());
EXPECT_EQ((arrays<len_type,2,8>{{{3, 4}, {3, 1}}}), v1.lengths());
if (j&1)
{
auto v21 = v1(1, 0);
EXPECT_EQ(data + 3, v21.data());
EXPECT_EQ((std::array<len_type,2>{4, 3}), v21.lengths());
EXPECT_EQ((std::array<len_type,2>{3, 1}), v21.strides());
auto v22 = v1(0, 1);
EXPECT_EQ(data + 0, v22.data());
EXPECT_EQ((std::array<len_type,2>{3, 1}), v22.lengths());
EXPECT_EQ((std::array<len_type,2>{1, 1}), v22.strides());
}
else
{
auto v21 = v1(1, 0);
EXPECT_EQ(data + 0, v21.data());
EXPECT_EQ((std::array<len_type,2>{4, 3}), v21.lengths());
EXPECT_EQ((std::array<len_type,2>{1, 4}), v21.strides());
auto v22 = v1(0, 1);
EXPECT_EQ(data + 12, v22.data());
EXPECT_EQ((std::array<len_type,2>{3, 1}), v22.lengths());
EXPECT_EQ((std::array<len_type,2>{1, 3}), v22.strides());
}
}
}
TEST(dpd_marray_view, block_iteration)
{
arrays<int,2,2> visited;
double tmp;
double* data = &tmp;
for (int l = 0;l < 6;l++)
{
SCOPED_TRACE(l);
dpd_marray_view<double,3> v1(0, 2, {{2, 3}, {1, 2}, {3, 1}}, data, layouts[l]);
dpd_marray_view<const double,3> v2(0, 2, {{2, 3}, {1, 2}, {3, 1}}, data, layouts[l]);
visited = {};
v1.for_each_block(
[&](marray_view<double,3>&& v3, unsigned i, unsigned j, unsigned k)
{
EXPECT_LT(i, 2u);
EXPECT_LT(j, 2u);
EXPECT_LT(k, 2u);
EXPECT_EQ(i^j^k, 0u);
auto v4 = v1(i, j, k);
EXPECT_EQ(v3.data(), v4.data());
EXPECT_EQ(v3.lengths(), v4.lengths());
EXPECT_EQ(v3.strides(), v4.strides());
visited[i][j]++;
});
for (len_type i = 0;i < 2;i++)
{
for (len_type j = 0;j < 2;j++)
{
EXPECT_EQ(visited[i][j], 1);
}
}
visited = {};
v2.for_each_block(
[&](marray_view<const double,3>&& v3, unsigned i, unsigned j, unsigned k)
{
EXPECT_LT(i, 2u);
EXPECT_LT(j, 2u);
EXPECT_LT(k, 2u);
EXPECT_EQ(i^j^k, 0u);
auto v4 = v2(i, j, k);
EXPECT_EQ(v3.data(), v4.data());
EXPECT_EQ(v3.lengths(), v4.lengths());
EXPECT_EQ(v3.strides(), v4.strides());
visited[i][j]++;
});
for (len_type i = 0;i < 2;i++)
{
for (len_type j = 0;j < 2;j++)
{
EXPECT_EQ(visited[i][j], 1);
}
}
}
}
TEST(dpd_marray_view, element_iteration)
{
array<int,31> visited;
double tmp;
double* data = &tmp;
arrays<len_type,3,2> len = {{{2, 3}, {1, 2}, {3, 1}}};
for (int l = 0;l < 6;l++)
{
SCOPED_TRACE(l);
dpd_marray_view<double,3> v1(0, 2, len, data, layouts[l]);
dpd_marray_view<const double,3> v2(0, 2, len, data, layouts[l]);
visited = {};
v1.for_each_element(
[&](double& v, unsigned i, unsigned j, unsigned k, len_type a, len_type b, len_type c)
{
EXPECT_LT(i, 2u);
EXPECT_LT(j, 2u);
EXPECT_LT(k, 2u);
EXPECT_GE(a, 0);
EXPECT_LT(a, len[0][i]);
EXPECT_GE(b, 0);
EXPECT_LT(b, len[1][j]);
EXPECT_GE(c, 0);
EXPECT_LT(c, len[2][k]);
EXPECT_EQ(i^j^k, 0u);
auto v3 = v1(i, j, k);
EXPECT_EQ(&v, &v3(a, b, c));
visited[&v - data]++;
});
for (unsigned i = 0;i < 31;i++)
{
EXPECT_EQ(visited[i], 1);
}
visited = {};
v2.for_each_element(
[&](const double& v, unsigned i, unsigned j, unsigned k, len_type a, len_type b, len_type c)
{
EXPECT_LT(i, 2u);
EXPECT_LT(j, 2u);
EXPECT_LT(k, 2u);
EXPECT_GE(a, 0);
EXPECT_LT(a, len[0][i]);
EXPECT_GE(b, 0);
EXPECT_LT(b, len[1][j]);
EXPECT_GE(c, 0);
EXPECT_LT(c, len[2][k]);
EXPECT_EQ(i^j^k, 0u);
auto v4 = v1(i, j, k);
EXPECT_EQ(&v, &v4(a, b, c));
visited[&v - data]++;
});
for (unsigned i = 0;i < 31;i++)
{
EXPECT_EQ(visited[i], 1);
}
}
}
TEST(dpd_marray_view, swap)
{
double tmp1, tmp2;
double* data1 = &tmp1;
double* data2 = &tmp2;
dpd_marray_view<double,3> v1(1, 2, {{2, 3}, {2, 1}, {5, 3}}, data1, PREFIX_ROW_MAJOR);
dpd_marray_view<double,3> v2(0, 2, {{1, 1}, {6, 3}, {2, 4}}, data2, PREFIX_COLUMN_MAJOR);
v1.swap(v2);
EXPECT_EQ(data2, v1.data());
EXPECT_EQ(0u, v1.irrep());
EXPECT_EQ(2u, v1.num_irreps());
EXPECT_EQ((std::array<unsigned,3>{0, 1, 2}), v1.permutation());
EXPECT_EQ((arrays<len_type,3,8>{{{1, 1}, {6, 3}, {2, 4}}}), v1.lengths());
EXPECT_EQ(data1, v2.data());
EXPECT_EQ(1u, v2.irrep());
EXPECT_EQ(2u, v2.num_irreps());
EXPECT_EQ((std::array<unsigned,3>{2, 1, 0}), v2.permutation());
EXPECT_EQ((arrays<len_type,3,8>{{{2, 3}, {2, 1}, {5, 3}}}), v2.lengths());
swap(v2, v1);
EXPECT_EQ(data1, v1.data());
EXPECT_EQ(1u, v1.irrep());
EXPECT_EQ(2u, v1.num_irreps());
EXPECT_EQ((std::array<unsigned,3>{2, 1, 0}), v1.permutation());
EXPECT_EQ((arrays<len_type,3,8>{{{2, 3}, {2, 1}, {5, 3}}}), v1.lengths());
EXPECT_EQ(data2, v2.data());
EXPECT_EQ(0u, v2.irrep());
EXPECT_EQ(2u, v2.num_irreps());
EXPECT_EQ((std::array<unsigned,3>{0, 1, 2}), v2.permutation());
EXPECT_EQ((arrays<len_type,3,8>{{{1, 1}, {6, 3}, {2, 4}}}), v2.lengths());
}
| 32.400943 | 131 | 0.492211 | devinamatthews |
1421190022f56d2db91673dd915b6b08f0eb4d27 | 1,787 | cpp | C++ | hiro/core/widget/text-edit.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | 38 | 2018-04-05T05:00:05.000Z | 2022-02-06T00:02:02.000Z | hiro/core/widget/text-edit.cpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 1 | 2018-04-29T19:45:14.000Z | 2018-04-29T19:45:14.000Z | hiro/core/widget/text-edit.cpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 8 | 2018-04-16T22:37:46.000Z | 2021-02-10T07:37:03.000Z | #if defined(Hiro_TextEdit)
auto mTextEdit::allocate() -> pObject* {
return new pTextEdit(*this);
}
//
auto mTextEdit::backgroundColor() const -> Color {
return state.backgroundColor;
}
auto mTextEdit::cursor() const -> Cursor {
return state.cursor;
}
auto mTextEdit::doChange() const -> void {
if(state.onChange) return state.onChange();
}
auto mTextEdit::doMove() const -> void {
if(state.onMove) return state.onMove();
}
auto mTextEdit::editable() const -> bool {
return state.editable;
}
auto mTextEdit::foregroundColor() const -> Color {
return state.foregroundColor;
}
auto mTextEdit::onChange(const function<void ()>& callback) -> type& {
state.onChange = callback;
return *this;
}
auto mTextEdit::onMove(const function<void ()>& callback) -> type& {
state.onMove = callback;
return *this;
}
auto mTextEdit::setBackgroundColor(Color color) -> type& {
state.backgroundColor = color;
signal(setBackgroundColor, color);
return *this;
}
auto mTextEdit::setCursor(Cursor cursor) -> type& {
state.cursor = cursor;
signal(setCursor, cursor);
return *this;
}
auto mTextEdit::setEditable(bool editable) -> type& {
state.editable = editable;
signal(setEditable, editable);
return *this;
}
auto mTextEdit::setForegroundColor(Color color) -> type& {
state.foregroundColor = color;
signal(setForegroundColor, color);
return *this;
}
auto mTextEdit::setText(const string& text) -> type& {
state.text = text;
signal(setText, text);
return *this;
}
auto mTextEdit::setWordWrap(bool wordWrap) -> type& {
state.wordWrap = wordWrap;
signal(setWordWrap, wordWrap);
return *this;
}
auto mTextEdit::text() const -> string {
return signal(text);
}
auto mTextEdit::wordWrap() const -> bool {
return state.wordWrap;
}
#endif
| 20.306818 | 70 | 0.698937 | 13824125580 |
14238e18c63c19e81ec2e9c573d3c724ae2686e8 | 1,088 | cc | C++ | leetcode/203_remove_linked_list_elements.cc | norlanliu/algorithm | 1684db2631f259b4de567164b3ee866351e5b1b6 | [
"MIT"
] | null | null | null | leetcode/203_remove_linked_list_elements.cc | norlanliu/algorithm | 1684db2631f259b4de567164b3ee866351e5b1b6 | [
"MIT"
] | null | null | null | leetcode/203_remove_linked_list_elements.cc | norlanliu/algorithm | 1684db2631f259b4de567164b3ee866351e5b1b6 | [
"MIT"
] | null | null | null | /*
* =====================================================================================
*
* Filename: 203_remove_linked_list_elements.cc
*
* Description:
*
* Version: 1.0
* Created: 09/17/2015 09:48:38 AM
* Revision: none
* Compiler: gcc
*
* Author: (Qi Liu), liuqi.edward@gmail.com
* Organization: antq.com
*
* Copyright (c) 2015, Qi Liu.
* All rights reserved.
* =====================================================================================
*/
#include<stdlib.h>
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode new_head(0);
new_head.next = head;
ListNode* old_ptr, * phead = &new_head;
while(phead->next != NULL){
if(phead->next->val == val){
old_ptr = phead->next;
phead->next = old_ptr->next;
delete old_ptr;
}else{
phead = phead->next;
}
}
return new_head.next;
}
};
| 22.666667 | 88 | 0.488051 | norlanliu |
14252f7db5a67bd349e7fb10186b7a225376376c | 7,531 | cc | C++ | tests/mime_test.cc | oktal/restgear | 615281a33eccd9c1d09f274254fd28313b0cd582 | [
"Apache-2.0"
] | 2 | 2015-10-27T11:13:07.000Z | 2016-01-10T02:51:04.000Z | tests/mime_test.cc | oktal/rest | 615281a33eccd9c1d09f274254fd28313b0cd582 | [
"Apache-2.0"
] | null | null | null | tests/mime_test.cc | oktal/rest | 615281a33eccd9c1d09f274254fd28313b0cd582 | [
"Apache-2.0"
] | null | null | null | /*
* SPDX-FileCopyrightText: 2015 Mathieu Stefani
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <gmock/gmock-matchers.h>
#include <gtest/gtest.h>
#include <pistache/http.h>
#include <pistache/mime.h>
#include <locale>
using namespace Pistache::Http;
using namespace Pistache::Http::Mime;
using testing::ThrowsMessage;
TEST(mime_test, basic_test)
{
MediaType m1(Type::Text, Subtype::Plain);
ASSERT_EQ(m1.top(), Type::Text);
ASSERT_EQ(m1.sub(), Subtype::Plain);
ASSERT_EQ(m1.suffix(), Suffix::None);
ASSERT_EQ(m1.toString(), "text/plain");
ASSERT_EQ(m1, MIME(Text, Plain));
ASSERT_NE(m1, MIME(Application, Json));
auto m2 = MIME3(Application, Xhtml, Xml);
ASSERT_EQ(m2.toString(), "application/xhtml+xml");
auto m3 = MIME(Text, Plain);
ASSERT_FALSE(m3.q().has_value());
m3.setQuality(Q::fromFloat(0.7));
ASSERT_EQ(m3.q().value_or(Q(0)), Q(70));
ASSERT_EQ(m3.toString(), "text/plain; q=0.7");
auto m4 = MIME3(Application, Json, Zip);
m4.setQuality(Q::fromFloat(0.79));
ASSERT_EQ(m4.toString(), "application/json+zip; q=0.79");
auto m5 = MIME(Text, Html);
m5.setQuality(Q::fromFloat(1.0));
m5.setParam("charset", "utf-8");
ASSERT_EQ(m5.toString(), "text/html; q=1; charset=utf-8");
}
void parse(const char* str, std::function<void(const MediaType&)> testFunc)
{
auto m1 = MediaType::fromString(std::string(str));
testFunc(m1);
auto m2 = MediaType::fromRaw(str, strlen(str));
testFunc(m2);
MediaType m3(str, MediaType::DoParse);
testFunc(m3);
}
TEST(mime_test, valid_parsing_test)
{
std::locale::global(std::locale(""));
parse("application/json", [](const MediaType& m1) {
ASSERT_EQ(m1, MIME(Application, Json));
ASSERT_FALSE(m1.q().has_value());
});
parse("application/xhtml+xml", [](const MediaType& m2) {
ASSERT_EQ(m2, MediaType(Type::Application, Subtype::Xhtml, Suffix::Xml));
ASSERT_FALSE(m2.q().has_value());
});
parse("application/json; q=0.3", [](const MediaType& m3) {
ASSERT_EQ(m3, MIME(Application, Json));
ASSERT_EQ(m3.q().value_or(Q(0)), Q::fromFloat(0.3));
});
parse("application/xhtml+xml; q=0.7", [](const MediaType& m4) {
ASSERT_EQ(m4.top(), Type::Application);
ASSERT_EQ(m4.sub(), Subtype::Xhtml);
ASSERT_EQ(m4.suffix(), Suffix::Xml);
ASSERT_EQ(m4.q().value_or(Q(0)), Q(70));
});
parse("application/xhtml+xml; q=0.78", [](const MediaType& m5) {
ASSERT_EQ(m5.q().value_or(Q(0)), Q(78));
});
parse("application/vnd.adobe.flash-movie", [](const MediaType& m6) {
ASSERT_EQ(m6.top(), Type::Application);
ASSERT_EQ(m6.sub(), Subtype::Vendor);
ASSERT_EQ(m6.suffix(), Suffix::None);
ASSERT_EQ(m6.rawSub(), "vnd.adobe.flash-movie");
});
parse("application/vnd.mycompany.myapp-v2+json", [](const MediaType& m7) {
ASSERT_EQ(m7.top(), Type::Application);
ASSERT_EQ(m7.sub(), Subtype::Vendor);
ASSERT_EQ(m7.suffix(), Suffix::Json);
ASSERT_EQ(m7.rawSub(), "vnd.mycompany.myapp-v2");
});
parse("application/x-myapp-v1+json", [](const MediaType& m8) {
ASSERT_EQ(m8.top(), Type::Application);
ASSERT_EQ(m8.sub(), Subtype::Ext);
ASSERT_EQ(m8.suffix(), Suffix::Json);
ASSERT_EQ(m8.rawSub(), "x-myapp-v1");
});
parse("audio/x-my-codec", [](const MediaType& m9) {
ASSERT_EQ(m9.top(), Type::Audio);
ASSERT_EQ(m9.sub(), Subtype::Ext);
ASSERT_EQ(m9.suffix(), Suffix::None);
ASSERT_EQ(m9.rawSub(), "x-my-codec");
});
parse("text/html; charset=ISO-8859-4", [](const MediaType& m10) {
ASSERT_EQ(m10, MIME(Text, Html));
ASSERT_FALSE(m10.q().has_value());
auto charset = m10.getParam("charset");
ASSERT_EQ(charset.value_or(""), "ISO-8859-4");
});
parse("text/html; q=0.83; charset=ISO-8859-4", [](const MediaType& m11) {
ASSERT_EQ(m11, MIME(Text, Html));
ASSERT_EQ(m11.q().value_or(Q(0)), Q(83));
ASSERT_EQ(m11.getParam("charset").value_or(""), "ISO-8859-4");
});
std::locale::global(std::locale::classic());
}
TEST(mime_test, invalid_parsing)
{
ASSERT_THROW(MediaType::fromString("applicationjson"), HttpError);
ASSERT_THROW(MediaType::fromString("my/json"), HttpError);
ASSERT_THROW(MediaType::fromString("text/"), HttpError);
ASSERT_THROW(MediaType::fromString("text/plain+"), HttpError);
ASSERT_THROW(MediaType::fromString("video/mp4;"), HttpError);
ASSERT_THROW(MediaType::fromString("image/png; "), HttpError);
ASSERT_THROW(MediaType::fromString("text/plain; q"), HttpError);
ASSERT_THROW(MediaType::fromString("text/plain; q"), HttpError);
ASSERT_THROW(MediaType::fromString("application/xhtml+xml; q=a0.2"),
HttpError);
ASSERT_THROW(MediaType::fromString("application/xhtml+xml; q=0.2b"),
HttpError);
ASSERT_THROW(MediaType::fromString("text/html; q=0.21;"), HttpError);
ASSERT_THROW(MediaType::fromString("text/html; q=0.21; charset"), HttpError);
ASSERT_THROW(MediaType::fromString("text/html; q=0.21; charset="), HttpError);
ASSERT_THROW(
MediaType::fromString("text/html; q=0.21; charset=ISO-8859-4; "),
HttpError);
// From https://github.com/pistacheio/pistache/pull/1077
EXPECT_THAT([] { MediaType::fromString("text/html; q=0."); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=00.0"); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=0.0.0"); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=.0"); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=."); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=1."); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=1.001"); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=.1"); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=0.1234"); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=a"); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=0.a"); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=1.a"); }, ThrowsMessage<HttpError>("Invalid quality factor"));
EXPECT_THAT([] { MediaType::fromString("text/html; q=a.1"); }, ThrowsMessage<HttpError>("Invalid quality factor"));
}
TEST(mime_test, should_parse_case_insensitive_issue_179)
{
parse("Application/Json", [](const Mime::MediaType& mime) {
ASSERT_EQ(mime, MIME(Application, Json));
ASSERT_FALSE(mime.q().has_value());
});
parse("aPpliCAtion/Xhtml+XML", [](const MediaType& mime) {
ASSERT_EQ(mime, MediaType(Type::Application, Subtype::Xhtml, Suffix::Xml));
ASSERT_FALSE(mime.q().has_value());
});
parse("Application/Xhtml+XML; q=0.78", [](const MediaType& mime) {
ASSERT_EQ(mime.q().value_or(Q(0)), Q(78));
});
}
| 38.819588 | 122 | 0.641084 | oktal |
14269b3269526a963734d2a29f6ac774f7277557 | 56 | cpp | C++ | examples/test_library/test.cpp | tomjnixon/arduino-scons-alt | 35f3725def8d515bc1b28d856188ec9dd10b063b | [
"MIT"
] | 1 | 2021-08-30T20:02:34.000Z | 2021-08-30T20:02:34.000Z | examples/test_library/test.cpp | tomjnixon/arduino-scons-alt | 35f3725def8d515bc1b28d856188ec9dd10b063b | [
"MIT"
] | null | null | null | examples/test_library/test.cpp | tomjnixon/arduino-scons-alt | 35f3725def8d515bc1b28d856188ec9dd10b063b | [
"MIT"
] | 1 | 2016-09-20T03:31:11.000Z | 2016-09-20T03:31:11.000Z | #include "test.h"
int get_delay() {
return 1000;
}
| 9.333333 | 17 | 0.607143 | tomjnixon |
14296e7d80698fedb84dc4e5be71095b7f422ff7 | 28,006 | cc | C++ | aslam_cv_cameras/test/test-cameras.cc | shuhannod/aslam_cv2 | 4dd48916b9e5b9d5aa56e28894a04d4a25a87348 | [
"Apache-2.0"
] | 3 | 2019-09-16T02:11:58.000Z | 2020-03-20T22:49:32.000Z | aslam_cv_cameras/test/test-cameras.cc | shuhannod/aslam_cv2 | 4dd48916b9e5b9d5aa56e28894a04d4a25a87348 | [
"Apache-2.0"
] | null | null | null | aslam_cv_cameras/test/test-cameras.cc | shuhannod/aslam_cv2 | 4dd48916b9e5b9d5aa56e28894a04d4a25a87348 | [
"Apache-2.0"
] | 3 | 2020-02-28T14:11:54.000Z | 2022-02-25T08:30:50.000Z | #include <Eigen/Core>
#include <eigen-checks/gtest.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <typeinfo>
#include <aslam/cameras/camera.h>
#include <aslam/cameras/camera-factory.h>
#include <aslam/cameras/camera-pinhole.h>
#include <aslam/cameras/camera-unified-projection.h>
#include <aslam/cameras/distortion.h>
#include <aslam/cameras/distortion-fisheye.h>
#include <aslam/cameras/distortion-radtan.h>
#include <aslam/cameras/distortion-equidistant.h>
#include <aslam/cameras/distortion-null.h>
#include <aslam/cameras/yaml/camera-yaml-serialization.h>
#include <aslam/common/entrypoint.h>
#include <aslam/common/memory.h>
#include <aslam/common/numdiff-jacobian-tester.h>
#include <aslam/common/yaml-serialization.h>
///////////////////////////////////////////////
// Types to test
///////////////////////////////////////////////
template<typename Camera, typename Distortion>
struct CameraDistortion {
typedef Camera CameraType;
typedef Distortion DistortionType;
};
using testing::Types;
typedef Types<CameraDistortion<aslam::PinholeCamera,aslam::FisheyeDistortion>,
CameraDistortion<aslam::UnifiedProjectionCamera,aslam::FisheyeDistortion>,
CameraDistortion<aslam::PinholeCamera,aslam::EquidistantDistortion>,
CameraDistortion<aslam::UnifiedProjectionCamera,aslam::EquidistantDistortion>,
CameraDistortion<aslam::PinholeCamera,aslam::RadTanDistortion>,
CameraDistortion<aslam::UnifiedProjectionCamera,aslam::RadTanDistortion>,
CameraDistortion<aslam::PinholeCamera,aslam::NullDistortion>,
CameraDistortion<aslam::UnifiedProjectionCamera,aslam::NullDistortion>>
Implementations;
///////////////////////////////////////////////
// Test fixture
///////////////////////////////////////////////
template <class CameraDistortion>
class TestCameras : public testing::Test {
public:
typedef typename CameraDistortion::CameraType CameraType;
typedef typename CameraDistortion::DistortionType DistortionType;
protected:
TestCameras() : camera_(CameraType::template createTestCamera<DistortionType>() ) {};
virtual ~TestCameras() {};
typename CameraType::Ptr camera_;
};
TYPED_TEST_CASE(TestCameras, Implementations);
///////////////////////////////////////////////
// Generic test cases (run for all models)
///////////////////////////////////////////////
struct Point3dFunctor : public aslam::common::NumDiffFunctor<2, 3> {
Point3dFunctor(aslam::Camera::ConstPtr camera) : camera_(camera) {
CHECK(camera);
};
virtual ~Point3dFunctor() {};
bool functional(const typename NumDiffFunctor::InputType& x,
typename NumDiffFunctor::ValueType& fvec,
typename NumDiffFunctor::JacobianType* Jout) const {
typename NumDiffFunctor::ValueType out_keypoint;
Eigen::VectorXd dist_coeffs = camera_->getDistortion().getParameters();
aslam::ProjectionResult res = camera_->project3Functional(x, nullptr, &dist_coeffs,
&out_keypoint, Jout, nullptr,
nullptr);
fvec = out_keypoint;
bool success = static_cast<bool>(res);
if(!success) {
LOG(ERROR) << "Point: " << x.transpose() << " does not project: " << res
<< ", keypoint: " << out_keypoint.transpose();
}
return success;
};
aslam::Camera::ConstPtr camera_;
};
TYPED_TEST(TestCameras, JacobianWrtPoint3d) {
for (int i=0; i<10; i++) {
Eigen::Vector3d x = this->camera_->createRandomVisiblePoint(10);
TEST_JACOBIAN_FINITE_DIFFERENCE(Point3dFunctor, x, 1e-6, 1e-5, this->camera_);
}
}
/// Wrapper that brings the distortion function to the form needed by the differentiator.
template<int numIntrinsics>
struct IntrinsicJacobianFunctor : public aslam::common::NumDiffFunctor<2, numIntrinsics> {
IntrinsicJacobianFunctor(aslam::Camera::ConstPtr camera, Eigen::Vector3d point_3d)
: camera_(camera),
point_3d_(point_3d) {
CHECK(camera);
};
virtual ~IntrinsicJacobianFunctor() {};
virtual bool functional(
const typename aslam::common::NumDiffFunctor<2, numIntrinsics>::InputType& x,
typename aslam::common::NumDiffFunctor<2, numIntrinsics>::ValueType& fvec,
typename aslam::common::NumDiffFunctor<2, numIntrinsics>::JacobianType* Jout) const {
Eigen::VectorXd dist_coeffs = camera_->getDistortion().getParameters();
typename aslam::common::NumDiffFunctor<2, numIntrinsics>::ValueType out_keypoint;
Eigen::Matrix<double, 2, Eigen::Dynamic> JoutDynamic;
aslam::ProjectionResult res;
Eigen::Matrix<double, Eigen::Dynamic, 1> xDynamic = x;
if (!Jout) {
res = camera_->project3Functional(point_3d_, &xDynamic, &dist_coeffs, &out_keypoint);
} else {
res = camera_->project3Functional(point_3d_, &xDynamic, &dist_coeffs, &out_keypoint,
nullptr, &JoutDynamic, nullptr);
(*Jout) = JoutDynamic;
}
fvec = out_keypoint;
return static_cast<bool>(res);
};
aslam::Camera::ConstPtr camera_;
Eigen::Vector3d point_3d_;
};
TYPED_TEST(TestCameras, JacobianWrtIntrinsics) {
// Test on a random point...
Eigen::Vector3d point_3d = this->camera_->createRandomVisiblePoint(3);
// Using the test intrinsic parameters.
Eigen::VectorXd intrinsics = this->camera_->getParameters();
TEST_JACOBIAN_FINITE_DIFFERENCE(IntrinsicJacobianFunctor<TypeParam::CameraType::parameterCount()>,
intrinsics, 1e-8, 1e-6, this->camera_, point_3d);
}
/// Wrapper that brings the distortion function to the form needed by the differentiator.
template<int numParams>
struct DistortionJacobianFunctor : public aslam::common::NumDiffFunctor<2, numParams> {
DistortionJacobianFunctor(aslam::Camera::ConstPtr camera, const Eigen::Vector3d& point_3d)
: camera_(camera),
point_3d_(point_3d) {
CHECK(camera);
};
typedef aslam::common::NumDiffFunctor<2, numParams> Functor;
virtual ~DistortionJacobianFunctor() {};
virtual bool functional(
const typename Functor::InputType& x,
typename Functor::ValueType& fvec,
typename Functor::JacobianType* Jout) const {
Eigen::VectorXd dist_coeffs = camera_->getDistortion().getParameters();
typename Functor::ValueType out_keypoint;
// Convert to dynamic sized matrix types.
Eigen::Matrix<double, 2, Eigen::Dynamic> JoutDynamic;
Eigen::Matrix<double, Eigen::Dynamic, 1> dist_coeff_dynamic = x;
aslam::ProjectionResult res;
if (!Jout) {
res = camera_->project3Functional(point_3d_, nullptr, &dist_coeff_dynamic,
&out_keypoint);
} else {
res = camera_->project3Functional(point_3d_, nullptr, &dist_coeff_dynamic,
&out_keypoint, nullptr, nullptr, &JoutDynamic);
(*Jout) = JoutDynamic;
}
fvec = out_keypoint;
return static_cast<bool>(res);
};
aslam::Camera::ConstPtr camera_;
Eigen::Vector3d point_3d_;
};
TYPED_TEST(TestCameras, JacobianWrtDistortion) {
// Test on a random point...
Eigen::Vector3d point_3d = this->camera_->createRandomVisiblePoint(3);
// Using the test distortion parameters.
Eigen::VectorXd dist_coeffs = this->camera_->getDistortion().getParameters();
TEST_JACOBIAN_FINITE_DIFFERENCE(DistortionJacobianFunctor<TypeParam::DistortionType::kNumOfParams>,
dist_coeffs, 1e-8, 1e-4 , this->camera_, point_3d);
}
TYPED_TEST(TestCameras, EuclideanToOnAxisKeypoint) {
Eigen::Vector3d euclidean(0, 0, 1);
Eigen::Vector2d keypoint;
this->camera_->project3(euclidean, &keypoint);
Eigen::Vector2d image_center(this->camera_->cu(), this->camera_->cv());
EXPECT_TRUE(EIGEN_MATRIX_NEAR(image_center, keypoint, 1e-15));
}
TYPED_TEST(TestCameras, isVisible) {
const double ru = this->camera_->imageWidth();
const double rv = this->camera_->imageHeight();
const double cu = this->camera_->cu();
const double cv = this->camera_->cv();
Eigen::Vector2d keypoint1(0, 0);
EXPECT_TRUE(this->camera_->isKeypointVisible(keypoint1)) << "Keypoint1: " << keypoint1;
Eigen::Vector2d keypoint2(ru - 1, rv - 1);
EXPECT_TRUE(this->camera_->isKeypointVisible(keypoint2)) << "Keypoint2: " << keypoint2;
Eigen::Vector2d keypoint3(cu, cv);
EXPECT_TRUE(this->camera_->isKeypointVisible(keypoint3)) << "Keypoint3: " << keypoint3;
Eigen::Vector2d keypoint4(-1, 0);
EXPECT_FALSE(this->camera_->isKeypointVisible(keypoint4)) << "Keypoint4: " << keypoint4;
Eigen::Vector2d keypoint5(-1, -1);
EXPECT_FALSE(this->camera_->isKeypointVisible(keypoint5)) << "Keypoint5: " << keypoint5;
Eigen::Vector3d keypoint6(ru, rv, 1);
EXPECT_FALSE(this->camera_->isKeypointVisible(keypoint6.head<2>())) << "Keypoint6: " << keypoint6;
}
TYPED_TEST(TestCameras, isVisibleWithMargin) {
const double ru = this->camera_->imageWidth();
const double rv = this->camera_->imageHeight();
const double cu = this->camera_->cu();
const double cv = this->camera_->cv();
const double margin = 5.0;
Eigen::Vector2d keypoint1(margin, margin);
EXPECT_TRUE(this->camera_->isKeypointVisibleWithMargin(keypoint1, margin)) << "Keypoint1: " << keypoint1;
Eigen::Vector2d keypoint2(ru - 1 - margin, rv - 1 - margin);
EXPECT_TRUE(this->camera_->isKeypointVisibleWithMargin(keypoint2, margin)) << "Keypoint2: " << keypoint2;
Eigen::Vector2d keypoint3(cu, cv);
EXPECT_TRUE(this->camera_->isKeypointVisibleWithMargin(keypoint3, margin)) << "Keypoint3: " << keypoint3;
Eigen::Vector2d keypoint4(0, 0);
EXPECT_FALSE(this->camera_->isKeypointVisibleWithMargin(keypoint4, margin)) << "Keypoint4: " << keypoint4;
Eigen::Vector2f keypoint5(ru-1, rv-1);
EXPECT_FALSE(this->camera_->isKeypointVisibleWithMargin(keypoint5, 5.0f)) << "Keypoint5: " << keypoint5;
Eigen::Vector3i keypoint6(ru, rv, 1);
EXPECT_FALSE(this->camera_->isKeypointVisibleWithMargin(keypoint6.head<2>(), 5)) << "Keypoint6: " << keypoint6;
}
TYPED_TEST(TestCameras, isProjectable) {
EXPECT_TRUE(this->camera_->isProjectable3(Eigen::Vector3d(0, 0, 1))); // Center.
EXPECT_TRUE(this->camera_->isProjectable3(Eigen::Vector3d(5, -5, 30))); // In front of cam and visible.
EXPECT_FALSE(this->camera_->isProjectable3(Eigen::Vector3d(5000, -5, 1))); // In front of cam, outside range.
EXPECT_FALSE(this->camera_->isProjectable3(Eigen::Vector3d(-10, -10, -10))); // Behind cam.
EXPECT_FALSE(this->camera_->isProjectable3(Eigen::Vector3d(0, 0, -1))); // Behind, center.
}
TYPED_TEST(TestCameras, CameraTest_isInvertible) {
const int N = 100;
const double depth = 10.0;
Eigen::Matrix3Xd points1(3,N);
Eigen::Matrix2Xd projections1(2,N);
Eigen::Matrix3Xd points2(3,N);
Eigen::Matrix3Xd points3(3,N);
Eigen::Matrix2Xd projections3(2,N);
Eigen::Vector3d point;
Eigen::Vector2d keypoint;
// N times, project and back-project a random point at a known depth.
// Then check that the back projection matches the projection.
for(size_t n = 0; n < N; ++n) {
points1.col(n) = this->camera_->createRandomVisiblePoint(depth);
aslam::ProjectionResult result = this->camera_->project3(points1.col(n), &keypoint);
projections1.col(n) = keypoint;
ASSERT_EQ(aslam::ProjectionResult::Status::KEYPOINT_VISIBLE, result.getDetailedStatus());
bool success = this->camera_->backProject3(keypoint, &point);
ASSERT_TRUE(success);
point.normalize();
points2.col(n) = point * depth;
}
// The distortion models are not invertible so we have to be generous here.
EXPECT_TRUE(EIGEN_MATRIX_NEAR(points1, points2, 1e-2));
// Do the same with the vectorized functions.
std::vector<aslam::ProjectionResult> result;
this->camera_->project3Vectorized(points1, &projections3, &result);
for(size_t n = 0; n < N; ++n) {
ASSERT_EQ(aslam::ProjectionResult::Status::KEYPOINT_VISIBLE, result[n].getDetailedStatus());
}
std::vector<unsigned char> success;
this->camera_->backProject3Vectorized(projections3, &points3, &success);
for(size_t n = 0; n < N; ++n) {
ASSERT_TRUE(success[n]);
points3.col(n).normalize();
points3.col(n) *= depth;
}
// The distortion models are not invertible so we have to be generous here.
EXPECT_TRUE(EIGEN_MATRIX_NEAR(points1, points3, 1e-2));
}
TYPED_TEST(TestCameras, TestClone) {
aslam::Camera::Ptr cam1(this->camera_->clone());
EXPECT_TRUE(this->camera_.get() != nullptr); // Check both are valid objects.
EXPECT_TRUE(cam1.get() != nullptr);
EXPECT_TRUE(this->camera_.get() != cam1.get()); // Check those are two different instances.
EXPECT_TRUE(*(this->camera_) == *cam1); // Check that the copy is the same as the original.
// Check that the distortion object is copied aswell.
EXPECT_TRUE(&this->camera_->getDistortion() != &cam1->getDistortion());
// Check that the copy is the same as the original.
EXPECT_TRUE(this->camera_->getDistortion() == cam1->getDistortion());
}
TYPED_TEST(TestCameras, invalidMaskTest) {
// Die on empty mask.
cv::Mat mask;
EXPECT_DEATH(this->camera_->setMask(mask), "^");
// Die on wrong type.
mask = cv::Mat::zeros(cv::Size2i(this->camera_->imageWidth(), this->camera_->imageHeight()), CV_8UC2);
EXPECT_DEATH(this->camera_->setMask(mask), "^");
// Die on wrong size.
mask = cv::Mat::zeros(cv::Size2i(this->camera_->imageWidth() - 1, this->camera_->imageHeight()), CV_8UC1);
EXPECT_DEATH(this->camera_->setMask(mask), "^");
}
TYPED_TEST(TestCameras, validMaskTest) {
cv::Mat mask = cv::Mat::ones(cv::Size2i(this->camera_->imageWidth(), this->camera_->imageHeight()), CV_8UC1);
mask.at<uint8_t>(20, 10) = 0;
EXPECT_FALSE(this->camera_->hasMask());
this->camera_->setMask(mask);
EXPECT_TRUE(this->camera_->hasMask());
typedef Eigen::Vector2d Vec2;
EXPECT_TRUE(this->camera_->isMasked(Vec2(-1.,-1.)));
EXPECT_FALSE(this->camera_->isMasked(Vec2(0.,0.)));
EXPECT_TRUE(this->camera_->isMasked(Vec2(this->camera_->imageWidth(),
this->camera_->imageHeight())));
EXPECT_FALSE(this->camera_->isMasked(Vec2(this->camera_->imageWidth() - 1.1,
this->camera_->imageHeight() - 1.1)));
EXPECT_FALSE(this->camera_->isMasked(Vec2(0.0,
this->camera_->imageHeight() - 1.1)));
EXPECT_FALSE(this->camera_->isMasked(Vec2(this->camera_->imageWidth() - 1.1,
0.0)));
// Check the valid/invalid.
EXPECT_FALSE(this->camera_->isMasked(Vec2(2.0, 2.0)));
EXPECT_FALSE(this->camera_->isMasked(Vec2(9.0, 19.0)));
EXPECT_FALSE(this->camera_->isMasked(Vec2(10.0, 19.0)));
EXPECT_FALSE(this->camera_->isMasked(Vec2(10.0, 21.0)));
EXPECT_FALSE(this->camera_->isMasked(Vec2(11.0, 21.0)));
EXPECT_FALSE(this->camera_->isMasked(Vec2(9.0, 21.0)));
EXPECT_TRUE(this->camera_->isMasked(Vec2(10.0, 20.0)));
EXPECT_TRUE(this->camera_->isMasked(Vec2(10.5, 20.5)));
}
TYPED_TEST(TestCameras, YamlSerialization){
ASSERT_NE(this->camera_, nullptr);
this->camera_->saveToYaml("test.yaml");
aslam::Camera::Ptr camera = aslam::Camera::loadFromYaml("test.yaml");
ASSERT_NE(camera, nullptr);
EXPECT_TRUE(*camera.get() == *this->camera_.get());
}
///////////////////////////////////////////////
// Model specific test cases
///////////////////////////////////////////////
TEST(TestCameraPinhole, ManualProjectionWithoutDistortion) {
//Create camera without distortion
aslam::PinholeCamera::Ptr camera = aslam::PinholeCamera::createTestCamera();
double kx = 1.0,
ky = 1.2,
kz = 10.0;
Eigen::Vector3d euclidean(kx, ky, kz);
Eigen::Vector2d keypoint;
// Manually project
Eigen::Vector2d keypoint_manual(camera->fu() * (kx / kz) + camera->cu(),
camera->fv() * (ky / kz) + camera->cv());
// Project using the camera methods
aslam::ProjectionResult res;
res = camera->project3(euclidean, &keypoint);
EXPECT_TRUE(res.getDetailedStatus() == aslam::ProjectionResult::KEYPOINT_VISIBLE);
EXPECT_TRUE(EIGEN_MATRIX_NEAR(keypoint_manual, keypoint, 1e-15));
keypoint.setZero();
Eigen::Matrix<double, 2, 3> out_jacobian;
res = camera->project3(euclidean, &keypoint, &out_jacobian);
EXPECT_TRUE(res.getDetailedStatus() == aslam::ProjectionResult::KEYPOINT_VISIBLE);
EXPECT_TRUE(EIGEN_MATRIX_NEAR(keypoint_manual, keypoint, 1e-15));
keypoint.setZero();
res = camera->project3Functional(euclidean, nullptr, nullptr, &keypoint);
EXPECT_TRUE(res.getDetailedStatus() == aslam::ProjectionResult::KEYPOINT_VISIBLE);
EXPECT_TRUE(EIGEN_MATRIX_NEAR(keypoint_manual, keypoint, 1e-15));
keypoint.setZero();
res = camera->project3Functional(euclidean, nullptr, nullptr, &keypoint,
nullptr, nullptr, nullptr);
EXPECT_TRUE(res.getDetailedStatus() == aslam::ProjectionResult::KEYPOINT_VISIBLE);
EXPECT_TRUE(EIGEN_MATRIX_NEAR(keypoint_manual, keypoint, 1e-15));
keypoint.setZero();
}
TEST(TestCameraUnifiedProjection, ManualProjectionWithoutDistortion) {
//Create camera without distortion
aslam::UnifiedProjectionCamera::Ptr camera = aslam::UnifiedProjectionCamera::createTestCamera();
double kx = 1.0,
ky = 1.2,
kz = 10.0;
Eigen::Vector3d euclidean(kx, ky, kz);
Eigen::Vector2d keypoint;
// Manually project
const double rz = 1.0 / (kz + camera->xi() * euclidean.norm());
Eigen::Vector2d keypoint_manual(camera->fu() * (kx * rz) + camera->cu(),
camera->fv() * (ky * rz) + camera->cv());
// Project using the camera methods
aslam::ProjectionResult res;
res = camera->project3(euclidean, &keypoint);
EXPECT_TRUE(res.getDetailedStatus() == aslam::ProjectionResult::KEYPOINT_VISIBLE);
EXPECT_TRUE(EIGEN_MATRIX_NEAR(keypoint_manual, keypoint, 1e-15));
keypoint.setZero();
Eigen::Matrix<double, 2, 3> out_jacobian;
res = camera->project3(euclidean, &keypoint, &out_jacobian);
EXPECT_TRUE(res.getDetailedStatus() == aslam::ProjectionResult::KEYPOINT_VISIBLE);
EXPECT_TRUE(EIGEN_MATRIX_NEAR(keypoint_manual, keypoint, 1e-15));
keypoint.setZero();
res = camera->project3Functional(euclidean, nullptr, nullptr, &keypoint);
EXPECT_TRUE(res.getDetailedStatus() == aslam::ProjectionResult::KEYPOINT_VISIBLE);
EXPECT_TRUE(EIGEN_MATRIX_NEAR(keypoint_manual, keypoint, 1e-15));
keypoint.setZero();
res = camera->project3Functional(euclidean, nullptr,
nullptr, &keypoint, nullptr, nullptr, nullptr);
EXPECT_TRUE(res.getDetailedStatus() == aslam::ProjectionResult::KEYPOINT_VISIBLE);
EXPECT_TRUE(EIGEN_MATRIX_NEAR(keypoint_manual, keypoint, 1e-15));
keypoint.setZero();
}
TEST(TestCameraUnifiedProjection, ProjectionResult) {
// Create camera without distortion.
aslam::UnifiedProjectionCamera::Ptr cam = aslam::UnifiedProjectionCamera::createTestCamera();
Eigen::Vector2d keypoint;
aslam::ProjectionResult ret;
// In front of cam -> visible.
ret = cam->project3(Eigen::Vector3d(1, 1, 10), &keypoint);
EXPECT_EQ(ret.getDetailedStatus(), aslam::ProjectionResult::Status::KEYPOINT_VISIBLE);
EXPECT_TRUE(static_cast<bool>(ret));
// Outside image box.
ret = cam->project3(Eigen::Vector3d(0.0, 10, -10), &keypoint);
EXPECT_EQ(ret.getDetailedStatus(), aslam::ProjectionResult::Status::KEYPOINT_OUTSIDE_IMAGE_BOX);
EXPECT_FALSE(static_cast<bool>(ret));
// Invalid projection (invalid if: z <= -(fov_parameter(xi()) * d) )
ret = cam->project3(Eigen::Vector3d(0, 0, -10), &keypoint);
EXPECT_EQ(ret.getDetailedStatus(), aslam::ProjectionResult::Status::PROJECTION_INVALID);
EXPECT_FALSE(static_cast<bool>(ret));
}
TEST(TestCameraPinhole, ProjectionResult) {
// Create camera without distortion.
aslam::PinholeCamera::Ptr cam = aslam::PinholeCamera::createTestCamera();
Eigen::Vector2d keypoint;
aslam::ProjectionResult ret;
// Check initialization value of aslam::ProjectionResult
EXPECT_EQ(ret.getDetailedStatus(), aslam::ProjectionResult::Status::UNINITIALIZED);
// In front of cam -> visible.
ret = cam->project3(Eigen::Vector3d(1, 1, 10), &keypoint);
EXPECT_EQ(ret.getDetailedStatus(), aslam::ProjectionResult::Status::KEYPOINT_VISIBLE);
EXPECT_TRUE(static_cast<bool>(ret));
// Behind cam -> not visible.
ret = cam->project3(Eigen::Vector3d(1, 1, -10), &keypoint);
EXPECT_EQ(ret.getDetailedStatus(), aslam::ProjectionResult::Status::POINT_BEHIND_CAMERA);
EXPECT_FALSE(static_cast<bool>(ret));
// Outside image box
ret = cam->project3(Eigen::Vector3d(1000, 1000, 10), &keypoint);
EXPECT_EQ(ret.getDetailedStatus(), aslam::ProjectionResult::Status::KEYPOINT_OUTSIDE_IMAGE_BOX);
EXPECT_FALSE(static_cast<bool>(ret));
// Invalid projection
ret = cam->project3(Eigen::Vector3d(1, 1, 0.0), &keypoint);
EXPECT_EQ(ret.getDetailedStatus(), aslam::ProjectionResult::Status::PROJECTION_INVALID);
EXPECT_FALSE(static_cast<bool>(ret));
}
TEST(CameraComparison, TestEquality) {
aslam::Camera::Ptr pinhole_nodist = aslam::PinholeCamera::createTestCamera();
aslam::Camera::Ptr pinhole_radtan = aslam::PinholeCamera::createTestCamera<aslam::RadTanDistortion>();
aslam::Camera::Ptr pinhole_equi = aslam::PinholeCamera::createTestCamera<aslam::EquidistantDistortion>();
EXPECT_TRUE(*pinhole_nodist == *pinhole_nodist); // Same camera, should be equal.
EXPECT_FALSE(*pinhole_radtan == *pinhole_nodist); // Different distortion model.
EXPECT_FALSE(*pinhole_radtan == *pinhole_equi); // Different distortion model.
aslam::Camera::Ptr udc_nodist = aslam::UnifiedProjectionCamera::createTestCamera();
aslam::Camera::Ptr udc_radtan = aslam::UnifiedProjectionCamera::createTestCamera<aslam::RadTanDistortion>();
aslam::Camera::Ptr udc_fisheye = aslam::UnifiedProjectionCamera::createTestCamera<aslam::FisheyeDistortion>();
EXPECT_FALSE(*pinhole_nodist == *udc_nodist); // Different camera model.
EXPECT_FALSE(*pinhole_nodist == *udc_fisheye); // Different camera and distortion model.
aslam::PinholeCamera::Ptr pinhole_A =
aslam::createCamera<aslam::PinholeCamera, aslam::RadTanDistortion>(
Eigen::Vector4d(400, 400, 300, 200), // intrinsics
720, 480, //resolution
Eigen::Vector4d(0.1, 0.2, 0.3, 0.4)); // distortion coeffs
aslam::PinholeCamera::Ptr pinhole_B =
aslam::createCamera<aslam::PinholeCamera, aslam::RadTanDistortion>(
Eigen::Vector4d(500, 400, 300, 200), // intrinsics
720, 480, //resolution
Eigen::Vector4d(0.1, 0.2, 0.3, 0.4)); // distortion coeffs
aslam::PinholeCamera::Ptr pinhole_C =
aslam::createCamera<aslam::PinholeCamera, aslam::RadTanDistortion>(
Eigen::Vector4d(400, 400, 300, 200), // intrinsics
720, 480, //resolution
Eigen::Vector4d(0.3, 0.2, 0.3, 0.4)); // distortion coeffs
aslam::PinholeCamera::Ptr pinhole_D =
aslam::createCamera<aslam::PinholeCamera, aslam::RadTanDistortion>(
Eigen::Vector4d(400, 460, 300, 200), // intrinsics
720, 480, //resolution
Eigen::Vector4d(0.4, 0.2, 0.3, 0.4)); // distortion coeffs
EXPECT_TRUE(*pinhole_C == *pinhole_C); // Same camera, should be equal.
EXPECT_FALSE(*pinhole_A == *pinhole_B); // Different intrinsics.
EXPECT_FALSE(*pinhole_A == *pinhole_C); // Different distortion coeffs.
EXPECT_FALSE(*pinhole_C == *pinhole_D); // Different intrinsics and distortion coeffs.
}
///////////////////////////////////////////////
// Test valid parameters
///////////////////////////////////////////////
TEST(TestParameters, testPinholeParameters) {
// Check num parameters:
Eigen::Vector3d invalid1 = Eigen::Vector3d::Zero();
EXPECT_FALSE(aslam::PinholeCamera::areParametersValid(invalid1));
Eigen::Matrix<double, 5, 1> invalid2 = Eigen::Matrix<double, 5, 1>::Zero();
EXPECT_FALSE(aslam::PinholeCamera::areParametersValid(invalid2));
Eigen::Vector4d invalid3 = Eigen::Vector4d::Zero();
EXPECT_FALSE(aslam::PinholeCamera::areParametersValid(invalid3));
// Check any of the paramters below 0:
Eigen::Vector4d invalid4 = Eigen::Vector4d(0.0, 1.0, 1.0, 1.0);
EXPECT_FALSE(aslam::PinholeCamera::areParametersValid(invalid4));
Eigen::Vector4d invalid5 = Eigen::Vector4d(1.0, 0.0, 1.0, 1.0);
EXPECT_FALSE(aslam::PinholeCamera::areParametersValid(invalid5));
Eigen::Vector4d invalid6 = Eigen::Vector4d(1.0, 1.0, 0.0, 1.0);
EXPECT_FALSE(aslam::PinholeCamera::areParametersValid(invalid6));
Eigen::Vector4d invalid7 = Eigen::Vector4d(1.0, 1.0, 1.0, 0.0);
EXPECT_FALSE(aslam::PinholeCamera::areParametersValid(invalid7));
Eigen::Vector4d valid = Eigen::Vector4d(1.0, 1.0, 1.0, 1.0);
EXPECT_TRUE(aslam::PinholeCamera::areParametersValid(valid));
}
TEST(TestParameters, testUnifiedProjectionParameters) {
// Check num parameters:
Eigen::Vector4d invalid1 = Eigen::Vector4d::Zero();
EXPECT_FALSE(aslam::UnifiedProjectionCamera::areParametersValid(invalid1));
Eigen::Matrix<double, 6, 1> invalid2 = Eigen::Matrix<double, 6, 1>::Zero();
EXPECT_FALSE(aslam::UnifiedProjectionCamera::areParametersValid(invalid2));
typedef Eigen::Matrix<double, 5, 1> Intrinsics;
Intrinsics invalid3 = Intrinsics::Zero();
EXPECT_FALSE(aslam::UnifiedProjectionCamera::areParametersValid(invalid3));
// Check any of the paramters below 0:
Intrinsics invalid4;
invalid4 << -1.0, 1.0, 1.0, 1.0, 1.0;
EXPECT_FALSE(aslam::UnifiedProjectionCamera::areParametersValid(invalid4));
Intrinsics invalid5;
invalid5 << 1.0, 0.0, 1.0, 1.0, 1.0;
EXPECT_FALSE(aslam::UnifiedProjectionCamera::areParametersValid(invalid5));
Intrinsics invalid6;
invalid6 << 1.0, 1.0, 0.0, 1.0, 1.0;
EXPECT_FALSE(aslam::UnifiedProjectionCamera::areParametersValid(invalid6));
Intrinsics invalid7;
invalid7 << 1.0, 1.0, 1.0, 0.0, 1.0;
EXPECT_FALSE(aslam::UnifiedProjectionCamera::areParametersValid(invalid7));
Intrinsics invalid8;
invalid8 << 1.0, 1.0, 1.0, 1.0, 0.0;
EXPECT_FALSE(aslam::UnifiedProjectionCamera::areParametersValid(invalid8));
Intrinsics valid;
valid << 0.0, 1.0, 1.0, 1.0, 1.0;
EXPECT_TRUE(aslam::UnifiedProjectionCamera::areParametersValid(valid));
}
TEST(TestCameraFactory, testEmptyYaml) {
YAML::Node node = YAML::Load("{}");
aslam::Camera::Ptr camera;
camera = node.as<aslam::Camera::Ptr>();
EXPECT_EQ(camera, nullptr);
}
TEST(TestCameraFactory, testNoDistortionYaml) {
YAML::Node node = YAML::Load("{type: pinhole, intrinsics: {rows: 4, cols: 1, data: [100,110,320,240]}, image_height: 480, image_width: 640}");
aslam::Camera::Ptr camera;
camera = node.as<aslam::Camera::Ptr>();
EXPECT_TRUE(camera.get() != nullptr);
EXPECT_EQ(typeid(*camera.get()), typeid(aslam::PinholeCamera));
aslam::PinholeCamera::Ptr pincam = std::dynamic_pointer_cast<aslam::PinholeCamera>(camera);
EXPECT_EQ(100, pincam->fu());
EXPECT_EQ(110, pincam->fv());
EXPECT_EQ(320, pincam->cu());
EXPECT_EQ(240, pincam->cv());
EXPECT_EQ(480u, pincam->imageHeight());
EXPECT_EQ(640u, pincam->imageWidth());
// To keep the yaml simple, if there is no id, a random id is created.
EXPECT_TRUE(pincam->getId().isValid());
EXPECT_EQ(0u, pincam->getLineDelayNanoSeconds());
EXPECT_EQ(aslam::NullDistortion(), pincam->getDistortion());
}
TEST(TestCameraFactory, testBadIntrinsics1) {
// Data size doesn't match the rows/cols
YAML::Node node = YAML::Load("{type: pinhole, intrinsics: {rows: 4, cols: 1, data: [100,110,320]}, image_height: 480, image_width: 640}");
aslam::Camera::Ptr camera;
camera = node.as<aslam::Camera::Ptr>();
EXPECT_EQ(camera, nullptr);
}
TEST(TestCameraFactory, testBadIntrinsics2) {
// Intrinsics size doesn't match the required size.
YAML::Node node = YAML::Load("{type: pinhole, intrinsics: {rows: 3, cols: 1, data: [100,110,320]}, image_height: 480, image_width: 640}");
aslam::Camera::Ptr camera;
camera = node.as<aslam::Camera::Ptr>();
EXPECT_EQ(camera, nullptr);
}
ASLAM_UNITTEST_ENTRYPOINT
| 41.24595 | 144 | 0.69278 | shuhannod |
142ccccb72f03cfdda6d0666fcc986a6fee6aaa2 | 12,266 | cpp | C++ | iree/compiler/Dialect/Shape/Plugins/XLA/XlaHloShapeBuilder.cpp | shanshanpt/iree | 89351bba213e391b22c1fa4a80963827c4d82d86 | [
"Apache-2.0"
] | null | null | null | iree/compiler/Dialect/Shape/Plugins/XLA/XlaHloShapeBuilder.cpp | shanshanpt/iree | 89351bba213e391b22c1fa4a80963827c4d82d86 | [
"Apache-2.0"
] | null | null | null | iree/compiler/Dialect/Shape/Plugins/XLA/XlaHloShapeBuilder.cpp | shanshanpt/iree | 89351bba213e391b22c1fa4a80963827c4d82d86 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "iree/compiler/Dialect/Shape/Plugins/XLA/XlaHloShapeBuilder.h"
#include "iree/compiler/Dialect/Shape/IR/Builders.h"
#include "iree/compiler/Dialect/Shape/IR/ShapeInterface.h"
#include "iree/compiler/Dialect/Shape/IR/ShapeOps.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/Optional.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/IR/Value.h"
#include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h"
using llvm::None;
using llvm::Optional;
using llvm::SmallVector;
using namespace mlir::iree_compiler::Shape;
namespace mlir {
namespace xla_hlo {
namespace {
template <typename HloOp>
Value rewriteXlaBinaryElementwiseOpShape(RankedShapeType resultShape, HloOp op,
OpBuilder &builder) {
if (!op) return nullptr;
if (op.broadcast_dimensions()) {
// Has implicit broadcast - ignore for now.
return nullptr;
}
// No implicit broadcast. Tread as same element type.
SmallVector<Value, 4> inputOperands(op.getOperands());
return buildCastInputsToResultShape(op.getLoc(), resultShape, inputOperands,
builder);
}
Value rewriteXlaDotOpShape(RankedShapeType resultRs, DotOp dotOp,
OpBuilder &builder) {
auto lhsType = dotOp.lhs().getType().dyn_cast<RankedTensorType>();
auto rhsType = dotOp.rhs().getType().dyn_cast<RankedTensorType>();
auto resultType = dotOp.getResult().getType().dyn_cast<RankedTensorType>();
if (!lhsType || !rhsType || !resultType) return nullptr;
// Shape transfer function:
// [n] dot [n] -> scalar
// [m x k] dot [k] -> [m]
// [m x k] dot [k x n] -> [m x n]
auto lhsRank = lhsType.getRank();
auto rhsRank = rhsType.getRank();
auto resultRank = resultType.getRank();
auto loc = dotOp.getLoc();
if (lhsRank == 1 && rhsRank == 1 && resultRank == 0) {
auto scalarShape = RankedShapeType::getChecked({}, loc);
return builder.create<ConstRankedShapeOp>(dotOp.getLoc(), scalarShape);
} else if (lhsRank == 2 && rhsRank == 1 && resultRank == 1) {
SmallVector<Value, 1> dynamicDims;
if (resultRs.isDimDynamic(0)) {
auto lhsGetShape = builder.create<GetRankedShapeOp>(
loc, RankedShapeType::get(lhsType.getShape(), builder.getContext()),
dotOp.lhs());
auto getMDim =
builder.create<RankedDimOp>(loc, builder.getIndexType(), lhsGetShape,
builder.getI64IntegerAttr(0));
dynamicDims.push_back(getMDim);
}
return builder.create<MakeRankedShapeOp>(loc, resultRs, dynamicDims);
} else if (lhsRank == 2 && rhsRank == 2 && resultRank == 2) {
SmallVector<Value, 2> dynamicDims;
if (resultRs.isDimDynamic(0)) {
auto lhsGetShape = builder.create<GetRankedShapeOp>(
loc, RankedShapeType::get(lhsType.getShape(), builder.getContext()),
dotOp.lhs());
auto getMDim =
builder.create<RankedDimOp>(loc, builder.getIndexType(), lhsGetShape,
builder.getI64IntegerAttr(0));
dynamicDims.push_back(getMDim);
}
if (resultRs.isDimDynamic(1)) {
auto rhsGetShape = builder.create<GetRankedShapeOp>(
loc, RankedShapeType::get(rhsType.getShape(), builder.getContext()),
dotOp.rhs());
auto getNDim =
builder.create<RankedDimOp>(loc, builder.getIndexType(), rhsGetShape,
builder.getI64IntegerAttr(1));
dynamicDims.push_back(getNDim);
}
return builder.create<MakeRankedShapeOp>(loc, resultRs, dynamicDims);
} else {
return nullptr;
}
}
Value rewriteReduce(RankedShapeType resultShape, ReduceOp reduceOp,
OpBuilder &builder) {
Location loc = reduceOp.getLoc();
// Get a common operand shape.
Value operandShape;
SmallVector<Value, 4> operandShapes;
RankedShapeType operandRs;
for (auto operand : reduceOp.operands()) {
auto shape = builder.create<GetRankedShapeOp>(loc, operand);
operandRs = shape.getRankedShape();
operandShapes.push_back(shape);
}
assert(!operandShapes.empty());
if (operandShapes.size() == 1) {
// Single operand.
operandShape = operandShapes.front();
} else {
// Multiple operands must be compatible.
operandShape =
builder.create<CastCompatibleShapeOp>(loc, operandRs, operandShapes);
}
// Map reduction dims onto operand dimensions.
SmallVector<bool, 4> isDimReduced;
isDimReduced.resize(operandRs.getRank());
for (const auto &apIntValue : reduceOp.dimensions().getIntValues()) {
auto intValue = apIntValue.getZExtValue();
assert(intValue < isDimReduced.size());
isDimReduced[intValue] = true;
}
// Map operand -> result dynamic dims.
assert(resultShape.getRank() ==
(operandRs.getRank() - reduceOp.dimensions().getNumElements()));
SmallVector<Value, 4> resultDims;
for (unsigned operandDimIndex = 0, e = isDimReduced.size();
operandDimIndex < e; ++operandDimIndex) {
unsigned resultDimIndex = resultDims.size();
// Skip reduced operand indices and non-dynamic result indices.
if (isDimReduced[operandDimIndex] ||
!resultShape.isDimDynamic(resultDimIndex))
continue;
resultDims.push_back(
builder.create<RankedDimOp>(loc, operandShape, operandDimIndex));
}
return builder.create<MakeRankedShapeOp>(loc, resultShape, resultDims);
}
// NOTE: This op is an HLO interloper and is just here until a corresponding
// HLO is created. As such, it is included in this file even though not HLO
// currently.
Value rewriteShapexRankedBroadcastInDim(RankedShapeType resultShape,
RankedBroadcastInDimOp bidOp,
OpBuilder &builder) {
if (!bidOp) return nullptr;
return bidOp.result_shape();
}
Value rewriteTranspose(RankedShapeType resultShape, TransposeOp transposeOp,
OpBuilder &builder) {
if (!transposeOp) return nullptr;
auto loc = transposeOp.getLoc();
auto operandType =
transposeOp.operand().getType().dyn_cast<RankedTensorType>();
if (!operandType) return nullptr;
auto operandShapeValue = builder.create<GetRankedShapeOp>(
loc, RankedShapeType::get(operandType.getShape(), builder.getContext()),
transposeOp.operand());
SmallVector<int64_t, 4> perm;
for (const auto &permValue : transposeOp.permutation().getIntValues()) {
perm.push_back(permValue.getSExtValue());
}
assert(perm.size() == resultShape.getRank());
// Map the dynamic dims.
SmallVector<Value, 4> dynamicDims;
for (int64_t i = 0, e = resultShape.getRank(); i < e; ++i) {
if (!resultShape.isDimDynamic(i)) continue;
int64_t operandDim = perm[i];
auto dimValue = builder.create<RankedDimOp>(
loc, builder.getIndexType(), operandShapeValue,
builder.getI64IntegerAttr(operandDim));
dynamicDims.push_back(dimValue);
}
return builder.create<MakeRankedShapeOp>(loc, resultShape, dynamicDims);
}
// Returns a value of type `!shapex.ranked_shape` for the input value.
static Value getRankedShapeAsValue(Value v, OpBuilder &builder, Location loc) {
assert(v.getType().isa<TensorType>());
auto type = v.getType().dyn_cast<RankedTensorType>();
if (!type) {
return nullptr;
}
return builder.create<GetRankedShapeOp>(
loc, RankedShapeType::get(type.getShape(), builder.getContext()), v);
}
// Returns a value representing the extent of dimension `dim`.
static Value getExtent(Value v, int64_t dim, OpBuilder &builder, Location loc) {
return builder.create<RankedDimOp>(loc, v, dim);
}
Value rewriteDotGeneral(RankedShapeType resultShape, DotGeneralOp op,
OpBuilder &builder) {
Location loc = op.getLoc();
auto lhsShape = getRankedShapeAsValue(op.lhs(), builder, loc);
auto rhsShape = getRankedShapeAsValue(op.rhs(), builder, loc);
if (!lhsShape || !rhsShape) {
return nullptr;
}
auto getFreeDims = [&](ArrayRef<int64_t> batchDims,
ArrayRef<int64_t> contractingDims, int64_t rank) {
llvm::BitVector freeDims(rank, true);
for (int64_t dim : batchDims) {
freeDims.reset(dim);
}
for (int64_t dim : contractingDims) {
freeDims.reset(dim);
}
SmallVector<int64_t, 4> result;
for (auto bitIndex : freeDims.set_bits()) {
result.push_back(bitIndex);
}
return result;
};
auto lhsRankedShape = lhsShape.getType().cast<RankedShapeType>();
auto rhsRankedShape = rhsShape.getType().cast<RankedShapeType>();
auto dotDimensions = op.dot_dimension_numbers();
auto lhsFreeDims = getFreeDims(
llvm::to_vector<4>(
dotDimensions.lhs_batching_dimensions().getValues<int64_t>()),
llvm::to_vector<4>(
dotDimensions.lhs_contracting_dimensions().getValues<int64_t>()),
lhsRankedShape.getRank());
auto rhsFreeDims = getFreeDims(
llvm::to_vector<4>(
dotDimensions.rhs_batching_dimensions().getValues<int64_t>()),
llvm::to_vector<4>(
dotDimensions.rhs_contracting_dimensions().getValues<int64_t>()),
rhsRankedShape.getRank());
SmallVector<Value, 6> outputExtents;
for (int64_t dim :
dotDimensions.lhs_batching_dimensions().getValues<int64_t>()) {
// TODO(silvasean): Add a version of MakeRankedShapeOp that takes
// all dimensions. Having to constantly check if a dim is dynamic
// upon construction is a waste of time, more testing burden, etc.
// We can easily canonicalize to the more constrained one.
if (lhsRankedShape.isDimDynamic(dim)) {
outputExtents.push_back(getExtent(lhsShape, dim, builder, loc));
}
}
for (int64_t dim : lhsFreeDims) {
if (lhsRankedShape.isDimDynamic(dim)) {
outputExtents.push_back(getExtent(lhsShape, dim, builder, loc));
}
}
for (int64_t dim : rhsFreeDims) {
if (rhsRankedShape.isDimDynamic(dim)) {
outputExtents.push_back(getExtent(rhsShape, dim, builder, loc));
}
}
return builder.create<MakeRankedShapeOp>(loc, resultShape, outputExtents);
}
Value rewriteDynamicReshape(RankedShapeType resultShape, DynamicReshapeOp op,
OpBuilder &builder) {
return builder.create<FromExtentTensorOp>(op.getLoc(), resultShape,
op.output_shape());
}
} // namespace
// Creates a custom op shape builder for XLA-HLO ops that are not otherwise
// supported through traits or other declarative means.
void populateXlaHloCustomOpShapeBuilder(CustomOpShapeBuilderList &builders) {
auto &b = builders.make<CallbackCustomOpShapeBuilder>();
// NOTE: Most of these *should not* be "custom ops". They should be coming
// from declarative shape information, but that doesn't exist yet.
#define INSERT_EW_OP(OpTy) \
b.insertOpRankedShapeBuilder<OpTy>(rewriteXlaBinaryElementwiseOpShape<OpTy>);
INSERT_EW_OP(AddOp);
INSERT_EW_OP(Atan2Op);
INSERT_EW_OP(DivOp);
INSERT_EW_OP(MaxOp);
INSERT_EW_OP(MinOp);
INSERT_EW_OP(MulOp);
INSERT_EW_OP(PowOp);
INSERT_EW_OP(RemOp);
INSERT_EW_OP(ShiftLeftOp);
INSERT_EW_OP(ShiftRightArithmeticOp);
INSERT_EW_OP(ShiftRightLogicalOp);
INSERT_EW_OP(SubOp);
b.insertOpRankedShapeBuilder<DotOp>(rewriteXlaDotOpShape);
b.insertOpRankedShapeBuilder<RankedBroadcastInDimOp>(
rewriteShapexRankedBroadcastInDim);
b.insertOpRankedShapeBuilder<ReduceOp>(rewriteReduce);
b.insertOpRankedShapeBuilder<TransposeOp>(rewriteTranspose);
b.insertOpRankedShapeBuilder<xla_hlo::DotGeneralOp>(rewriteDotGeneral);
b.insertOpRankedShapeBuilder<xla_hlo::DynamicReshapeOp>(
rewriteDynamicReshape);
}
} // namespace xla_hlo
} // namespace mlir
| 38.211838 | 80 | 0.69126 | shanshanpt |
142d323a03dc52282b70141eddd1a3c93d6ff2f6 | 971 | hpp | C++ | Code/include/OE/UI_OLD/Layouts/LayoutElement.hpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | 21 | 2018-06-26T16:37:36.000Z | 2022-01-11T01:19:42.000Z | Code/include/OE/UI_OLD/Layouts/LayoutElement.hpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | null | null | null | Code/include/OE/UI_OLD/Layouts/LayoutElement.hpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | 3 | 2019-10-01T14:10:50.000Z | 2021-11-19T20:30:18.000Z | #ifndef UI_LAYOUT_ELEMENT_HPP
#define UI_LAYOUT_ELEMENT_HPP
#include "OE/Math/Vec2.hpp"
namespace OrbitEngine { namespace UI {
enum LayoutProperty {
MINIMUM_SIZE = 0,
PREFERRED_SIZE,
FLEXIBLE_SIZE
};
enum Axis : int {
HORIZONTAL = 0, VERTICAL = 1
};
typedef Axis Orientation;
class LayoutElement {
public:
virtual float getLayoutPropertyAlongAxis(LayoutProperty property, Axis axis) { return m_LayoutProperties[property][axis]; };
void setLayoutPropertyAlongAxis(float value, LayoutProperty property, Axis axis) { m_LayoutProperties[property][axis] = value; };
Math::Vec2f getLayoutProperty(LayoutProperty property) { return Math::Vec2f(getLayoutPropertyAlongAxis(property, (Axis)0), getLayoutPropertyAlongAxis(property, (Axis)1)); };
void setLayoutProperty(Math::Vec2f value, LayoutProperty property) { m_LayoutProperties[property] = value; };
private:
Math::Vec2f m_LayoutProperties[3];
protected:
LayoutElement() {};
};
} }
#endif | 28.558824 | 175 | 0.762101 | mlomb |
142dee91a299e862a961533dec929be5fdc96bf9 | 1,901 | cpp | C++ | libraries/lib-basic-ui/GenericString.cpp | generic-pers0n/saucedacity | c737a38345c35b6b18900ee5ca0fe714b7957af6 | [
"CC-BY-3.0"
] | 11 | 2021-08-08T18:34:30.000Z | 2022-01-14T11:48:17.000Z | libraries/lib-basic-ui/GenericString.cpp | saucedacity/saucedacity | c737a38345c35b6b18900ee5ca0fe714b7957af6 | [
"CC-BY-3.0"
] | 11 | 2021-08-07T18:20:36.000Z | 2022-01-06T18:40:27.000Z | libraries/lib-basic-ui/GenericString.cpp | generic-pers0n/saucedacity | c737a38345c35b6b18900ee5ca0fe714b7957af6 | [
"CC-BY-3.0"
] | 1 | 2021-12-29T02:10:21.000Z | 2021-12-29T02:10:21.000Z | /*!********************************************************************
Saucedacity: A Digital Audio Editor
@file GenericString.cpp
@brief GenericString implementation.
Avery King
**********************************************************************/
#include "GenericString.h"
namespace GenericUI {
GenericString::GenericString()
{
}
GenericString::GenericString(GenericString& source)
{
mString = source.mString;
}
GenericString::GenericString(GenericString&& source)
{
mString = source.mString;
source.mString = wxEmptyString;
}
GenericString::GenericString(wxString& source)
{
mString = source;
}
GenericString::GenericString(const char* source)
{
std::string dummy = source;
mString = wxString(dummy);
}
GenericString::GenericString(std::string& source)
{
mString = wxString(source);
}
GenericString::GenericString(std::wstring& source)
{
mString = wxString(source);
}
//// Member functions /////////////////////////////////////////////////////////
wxString& GenericString::GetInternalString()
{
return mString;
}
char GenericString::GetChar(size_t pos)
{
return mString.GetChar(pos).GetValue();
}
//// Operators Overloads //////////////////////////////////////////////////////
GenericString& GenericString::operator=(GenericString& source)
{
mString = source.mString;
return *this;
}
GenericString& GenericString::operator=(GenericString&& source)
{
mString = source.mString;
source.mString = wxEmptyString;
return *this;
}
GenericString& GenericString::operator=(wxString& source)
{
mString = source;
return *this;
}
GenericString& GenericString::operator=(std::string& source)
{
mString = wxString(source);
return *this;
}
GenericString& GenericString::operator=(std::wstring& source)
{
mString = wxString(source);
return *this;
}
char GenericString::operator[] (size_t pos)
{
return GetChar(pos);
}
} // namespace GenericUI
| 18.637255 | 79 | 0.637033 | generic-pers0n |
28a0627334f6d5bbd9d094d76ec79466c4a66a6c | 5,222 | cpp | C++ | src/model/test/AirLoopHVACOutdoorAirSystem_GTest.cpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 354 | 2015-01-10T17:46:11.000Z | 2022-03-29T10:00:00.000Z | src/model/test/AirLoopHVACOutdoorAirSystem_GTest.cpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 3,243 | 2015-01-02T04:54:45.000Z | 2022-03-31T17:22:22.000Z | src/model/test/AirLoopHVACOutdoorAirSystem_GTest.cpp | jmarrec/OpenStudio | 5276feff0d8dbd6c8ef4e87eed626bc270a19b14 | [
"blessing"
] | 157 | 2015-01-07T15:59:55.000Z | 2022-03-30T07:46:09.000Z | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <gtest/gtest.h>
#include "ModelFixture.hpp"
#include "../AirLoopHVACOutdoorAirSystem.hpp"
#include "../AirLoopHVACOutdoorAirSystem_Impl.hpp"
#include "../ControllerOutdoorAir.hpp"
#include "../ControllerOutdoorAir_Impl.hpp"
#include "../HVACComponent.hpp"
#include "../HVACComponent_Impl.hpp"
#include "../CoilHeatingElectric.hpp"
#include "../Schedule.hpp"
#include "../Node.hpp"
#include "../AirLoopHVAC.hpp"
#include "../../utilities/idd/IddEnums.hpp"
#include <utilities/idd/IddEnums.hxx>
using namespace openstudio::model;
TEST_F(ModelFixture, AirLoopHVACOutdoorAirSystem_AirLoopHVACOutdoorAirSystem) {
Model model = Model();
OptionalModelObject modelObject;
ControllerOutdoorAir controller(model);
AirLoopHVACOutdoorAirSystem oaSystem = AirLoopHVACOutdoorAirSystem(model, controller);
ASSERT_EQ(openstudio::IddObjectType::OS_AirLoopHVAC_OutdoorAirSystem, oaSystem.iddObjectType().value());
}
TEST_F(ModelFixture, AirLoopHVACOutdoorAirSystem_controllerOutdoorAir) {
Model model = Model();
OptionalModelObject modelObject;
ControllerOutdoorAir controller(model);
AirLoopHVACOutdoorAirSystem oaSystem = AirLoopHVACOutdoorAirSystem(model, controller);
ASSERT_EQ(openstudio::IddObjectType::OS_Controller_OutdoorAir, oaSystem.getControllerOutdoorAir().iddObjectType().value());
}
TEST_F(ModelFixture, AirLoopHVACOutdoorAirSystem_clone) {
Model model = Model();
Model model2 = Model();
OptionalModelObject modelObject;
ControllerOutdoorAir controller(model);
AirLoopHVACOutdoorAirSystem oaSystem = AirLoopHVACOutdoorAirSystem(model, controller);
ASSERT_EQ(openstudio::IddObjectType::OS_Controller_OutdoorAir, oaSystem.getControllerOutdoorAir().iddObjectType().value());
AirLoopHVACOutdoorAirSystem oaSystem2 = oaSystem.clone(model2).cast<AirLoopHVACOutdoorAirSystem>();
ASSERT_EQ(openstudio::IddObjectType::OS_Controller_OutdoorAir, oaSystem2.getControllerOutdoorAir().iddObjectType().value());
}
//TEST_F(ModelFixture,AirLoopHVACOutdoorAirSystem_edges)
//{
// Model m;
// Schedule s = m.alwaysOnDiscreteSchedule();
// AirLoopHVAC airLoop(m);
// ControllerOutdoorAir controllerOutdoorAir(m);
// AirLoopHVACOutdoorAirSystem outdoorAirSystem(m,controllerOutdoorAir);
// CoilHeatingElectric coil(m, s);
//
// Node supplyOutletNode = airLoop.supplyOutletNode();
// outdoorAirSystem.addToNode(supplyOutletNode);
// coil.addToNode(supplyOutletNode);
// boost::optional<ModelObject> testObject = airLoop.supplyComponent(outdoorAirSystem.handle());
// ASSERT_TRUE(testObject);
// EXPECT_EQ(outdoorAirSystem, *testObject);
// std::vector<HVACComponent> edges = outdoorAirSystem.getImpl<detail::HVACComponent_Impl>()->edges(false); // should be Node
// ASSERT_EQ(1, edges.size());
// edges = edges[0].getImpl<detail::HVACComponent_Impl>()->edges(false); // should be CoilHeatingElectric
// ASSERT_EQ(1, edges.size());
// EXPECT_EQ(coil, edges[0]);
//}
| 50.699029 | 126 | 0.748372 | muehleisen |
28a146ff9f543d7952310d003b9ce88a6f1c69cc | 2,177 | cpp | C++ | QueuePP/source/store.cpp | AntonPoturaev/QueuePP | 25ea571abdd62ab6409da6dbad5bfcd20898ffb1 | [
"Unlicense"
] | null | null | null | QueuePP/source/store.cpp | AntonPoturaev/QueuePP | 25ea571abdd62ab6409da6dbad5bfcd20898ffb1 | [
"Unlicense"
] | null | null | null | QueuePP/source/store.cpp | AntonPoturaev/QueuePP | 25ea571abdd62ab6409da6dbad5bfcd20898ffb1 | [
"Unlicense"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
///
/// Project Queue++
/// Copyright (c) 2016
///
////////////////////////////////////////////////////////////////////////////////
/// @file types.hpp
/// @authors Poturaev Anton
/// @date 11.02.2016
///
/// @brief Implementation of ...
///
////////////////////////////////////////////////////////////////////////////////
#include "store.hpp"
#include <cassert>
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/functional/hash.hpp>
namespace boost {
std::size_t hash_value(Queues::queue::ptr_t const& q) {
assert(q && "Bad data!");
return hash_value(q->get_name());
}
} /// end namespace boost
namespace Queues { namespace details {
namespace {
typedef std::lock_guard<std::mutex> const _lock_t;
} /// end unnamed namespace
store::~store() {
_lock_t lock(_access);
_store.clear();
}
store& store::instance() {
static store instance;
return instance;
}
queue::ptr_t store::get_by_name(std::string const& name) const {
_lock_t lock(_access);
auto const found = _find_by_name(name);
return _store.end() == found ? nullptr : *found;
}
bool store::add(queue::ptr_t const& q) {
_lock_t lock(_access);
assert(q && "Bad data!");
return _store.insert(q).second;
}
bool store::add(queue::ptr_t&& q) {
_lock_t lock(_access);
assert(q && "Bad data!");
return _store.insert(std::forward<queue::ptr_t>(q)).second;
}
void store::remove(queue::ptr_t const& queue) {
_lock_t lock(_access);
assert(queue && "Bad data!");
remove(queue->get_name());
}
void store::remove(std::string const& name) {
_lock_t lock(_access);
_store.erase(_find_by_name(name));
}
store::_store_t::const_iterator store::_find_by_name(std::string const& name) const {
/// TODO: rewrite this
return std::find_if(_store.begin(), _store.end(), boost::bind(&queue::get_name, _1) == name);
}
}} /// end namespace Queues::details
| 26.876543 | 98 | 0.523656 | AntonPoturaev |
28a3322f01dc5a1a56ac29fb05cf0bd2ae5ff5f9 | 3,591 | cpp | C++ | CMinus/CMinus/attribute/attribute_collection.cpp | benbraide/CMinusMinus | 6e32b825f192634538b3adde6ca579a548ca3f7e | [
"MIT"
] | null | null | null | CMinus/CMinus/attribute/attribute_collection.cpp | benbraide/CMinusMinus | 6e32b825f192634538b3adde6ca579a548ca3f7e | [
"MIT"
] | null | null | null | CMinus/CMinus/attribute/attribute_collection.cpp | benbraide/CMinusMinus | 6e32b825f192634538b3adde6ca579a548ca3f7e | [
"MIT"
] | null | null | null | #include "../type/type_object.h"
#include "attribute_collection.h"
cminus::attribute::collection::collection(std::shared_ptr<type::object> target_type)
: target_type_(target_type){}
cminus::attribute::collection::collection(const list_type &list, std::shared_ptr<type::object> target_type)
: target_type_(target_type){
for (auto entry : list)
add(entry);
}
cminus::attribute::collection::collection(const map_type &list, std::shared_ptr<type::object> target_type)
: list_(list), target_type_(target_type){}
cminus::attribute::collection::collection(map_type &&list, std::shared_ptr<type::object> target_type)
: list_(std::move(list)), target_type_(target_type){}
void cminus::attribute::collection::set_target_type(std::shared_ptr<type::object> value){
target_type_ = value;
}
std::shared_ptr<cminus::type::object> cminus::attribute::collection::get_target_type() const{
return target_type_;
}
void cminus::attribute::collection::add(std::shared_ptr<object> value){
if (value != nullptr && !has(*value))
list_[value.get()] = value;
}
void cminus::attribute::collection::remove(const object &target){
if (list_.empty())
return;
for (auto it = list_.begin(); it != list_.end(); ++it){
if (it->first->is_same(target)){
list_.erase(it);
break;
}
}
}
void cminus::attribute::collection::remove(const std::string &qname){
if (list_.empty())
return;
for (auto it = list_.begin(); it != list_.end(); ++it){
if (it->first->get_qname() == qname){
list_.erase(it);
break;
}
}
}
void cminus::attribute::collection::remove_primitive(const std::string &name){
if (list_.empty())
return;
for (auto it = list_.begin(); it != list_.end(); ++it){
if (it->first->is_primitive() && it->first->get_name() == name){
list_.erase(it);
break;
}
}
}
void cminus::attribute::collection::clear(){
list_.clear();
}
bool cminus::attribute::collection::has(const object &target) const{
if (list_.empty())
return false;
for (auto &entry : list_){
if (entry.first->is_same(target))
return true;
}
return false;
}
bool cminus::attribute::collection::has(const std::string &qname) const{
if (list_.empty())
return false;
for (auto &entry : list_){
if (entry.first->get_qname() == qname)
return true;
}
return false;
}
bool cminus::attribute::collection::has_primitive(const std::string &name) const{
if (list_.empty())
return false;
for (auto &entry : list_){
if (entry.first->is_primitive() && entry.first->get_name() == name)
return true;
}
return false;
}
void cminus::attribute::collection::traverse(const std::function<void(std::shared_ptr<object>)> &callback) const{
if (list_.empty())
return;
auto no_type = (target_type_ == nullptr);
for (auto &entry : list_){
if (no_type || entry.first->applies_to_type(*target_type_))
callback(entry.second);
}
}
void cminus::attribute::collection::traverse_all(const std::function<void(std::shared_ptr<object>)> &callback) const{
if (list_.empty())
return;
for (auto &entry : list_)
callback(entry.second);
}
cminus::attribute::query_result cminus::attribute::collection::query(stage_type stage, std::shared_ptr<memory::reference> target, std::shared_ptr<memory::reference> arg) const{
auto result = query_result::nil;
traverse([&](std::shared_ptr<object> attr){
if (auto current_result = object::handle_query_result(stage, *attr, target, arg); result == query_result::nil)
result = current_result;
});
return result;
}
const cminus::attribute::collection::map_type &cminus::attribute::collection::get_list() const{
return list_;
}
| 25.468085 | 176 | 0.69897 | benbraide |
28a38d15e5526afbc21b50ae04438d05e525e353 | 1,046 | hpp | C++ | player/playerlib/NodeReader.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | player/playerlib/NodeReader.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | player/playerlib/NodeReader.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | /*
* This file is part of FFL project.
*
* The MIT License (MIT)
* Copyright (C) 2017-2018 zhufeifei All rights reserved.
*
* NodeReader.hpp
* Created by zhufeifei(34008081@qq.com) on 2018/03/03
*
* 视频文件读写,解复用的
*
*/
#pragma once
#include "NodeBase.hpp"
#include "IReader.hpp"
namespace player {
class NodeReader : public NodeBase, public IReader {
public:
NodeReader();
~NodeReader();
protected:
//
// 成功创建了node
//
virtual void onCreate();
//
// 成功删除了node
//
virtual void onDestroy();
public:
//
// 打开
//
void play(const char* url);
//
// 暂停读,但是不关闭
//
void pause();
//
// 恢复读
//
void resume();
//
// 设置开始读位置
//
void seek(int64_t pos);
//
// 关闭
//
void close();
public:
//
// 获取播放时长
//
int64_t getDurationUs() ;
//
// 获取当前的播放位置
//
int64_t getCurrentUs() ;
private:
//
// 控制输入,数据输入接口
//
InputInterface mControlInput;
InputInterface mDataInput;
//
// 数据处理完成后的输出接口
//
OutputInterface mDataOutput;
//
//
//
IReader* mImpl;
};
}
| 13.240506 | 57 | 0.58891 | zhenfei2016 |
28aa115bfb89cf963b0ea22406ae6f8dece58a5b | 2,054 | cc | C++ | asylo/platform/posix/io/io_context_eventfd.cc | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | 890 | 2018-05-03T17:27:37.000Z | 2022-03-30T03:54:35.000Z | asylo/platform/posix/io/io_context_eventfd.cc | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | 71 | 2018-05-03T22:36:07.000Z | 2021-10-04T22:58:59.000Z | asylo/platform/posix/io/io_context_eventfd.cc | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | 127 | 2018-05-03T21:03:47.000Z | 2022-03-28T20:21:43.000Z | /*
*
* Copyright 2018 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "asylo/platform/posix/io/io_context_eventfd.h"
constexpr uint64_t kMaxCounter = 0xfffffffffffffffe;
constexpr ssize_t kCounterBufSize = sizeof(uint64_t);
namespace asylo {
namespace io {
ssize_t IOContextEventFd::Read(void *buf, size_t count) {
if (count < kCounterBufSize) {
errno = EINVAL;
return -1;
}
absl::MutexLock counter_mutex_lock(&counter_mutex_);
if (nonblock_ && (counter_ == 0)) {
errno = EAGAIN;
return -1;
} else {
auto ready = [this]() { return counter_ > 0; };
counter_mutex_.Await(absl::Condition(&ready));
}
if (semaphore_) {
*reinterpret_cast<uint64_t *>(buf) = 1;
--counter_;
} else {
*reinterpret_cast<uint64_t *>(buf) = counter_;
counter_ = 0;
}
return kCounterBufSize;
}
ssize_t IOContextEventFd::Write(const void *buf, size_t count) {
if (count < kCounterBufSize) {
errno = EINVAL;
return -1;
}
uint64_t add = *reinterpret_cast<const uint64_t *>(buf);
if (add > kMaxCounter) {
errno = EINVAL;
return -1;
}
absl::MutexLock counter_mutex_lock(&counter_mutex_);
if (nonblock_ && (counter_ + add > kMaxCounter)) {
errno = EAGAIN;
return -1;
} else {
auto ready = [this, add]() { return (counter_ + add) <= kMaxCounter; };
counter_mutex_.Await(absl::Condition(&ready));
}
counter_ += add;
return kCounterBufSize;
}
int IOContextEventFd::Close() {
return 0;
}
} // namespace io
} // namespace asylo
| 26.675325 | 75 | 0.678676 | kevin405 |
28b803182a830c9fc4501fe4754c36c05ffe90d5 | 12,474 | cpp | C++ | SheepShaver/src/MacOSX/sys_darwin.cpp | jvernet/macemu | c616a0dae0f451fc15016765c896175fae3f46cf | [
"Intel",
"X11"
] | 940 | 2015-01-04T12:20:10.000Z | 2022-03-29T12:35:27.000Z | SheepShaver/src/MacOSX/sys_darwin.cpp | Seanpm2001-virtual-machines/macemu | c616a0dae0f451fc15016765c896175fae3f46cf | [
"Intel",
"X11"
] | 163 | 2015-02-10T09:08:10.000Z | 2022-03-13T05:48:10.000Z | SheepShaver/src/MacOSX/sys_darwin.cpp | Seanpm2001-virtual-machines/macemu | c616a0dae0f451fc15016765c896175fae3f46cf | [
"Intel",
"X11"
] | 188 | 2015-01-07T19:46:11.000Z | 2022-03-26T19:06:00.000Z | /*
* $Id$
*
* sys_darwin.cpp - Extra Darwin system dependant routines. Called by:
*
* sys_unix.cpp - System dependent routines, Unix implementation
*
* Based on Apple's CDROMSample.c and Evan Jones' cd-discid.c patches
*
* Basilisk II (C) 1997-2008 Christian Bauer
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#import <errno.h>
#import <sys/param.h>
#import <IOKit/IOKitLib.h>
#import <IOKit/IOBSD.h>
#import <IOKit/serial/IOSerialKeys.h>
#import <IOKit/storage/IOMedia.h>
#import <IOKit/storage/IOMediaBSDClient.h>
#ifdef HAVE_IOKIT_STORAGE_IOBLOCKSTORAGEDEVICE_H
#import <IOKit/storage/IOBlockStorageDevice.h>
#endif
#import <IOKit/storage/IOCDMedia.h>
#import <IOKit/storage/IOCDMediaBSDClient.h>
#import <CoreFoundation/CoreFoundation.h>
#include "sysdeps.h"
#include "sys.h"
#include "prefs.h"
#define DEBUG 0
#import "debug.h"
// Global variables
static volatile CFRunLoopRef media_poll_loop = NULL;
static bool media_thread_active = false;
static pthread_t media_thread;
// Prototypes
static void *media_poll_func(void *);
// From sys_unix.cpp
extern void SysMediaArrived(const char *path, int type);
extern void SysMediaRemoved(const char *path, int type);
/*
* Initialization
*/
void DarwinSysInit(void)
{
if (!PrefsFindBool("nocdrom")) {
media_thread_active = (pthread_create(&media_thread, NULL, media_poll_func, NULL) == 0);
D(bug("Media poll thread installed (%ld)\n", media_thread));
}
}
/*
* Deinitialization
*/
void DarwinSysExit(void)
{
// Stop media poll thread
if (media_thread_active) {
while (media_poll_loop == NULL || !CFRunLoopIsWaiting(media_poll_loop))
usleep(0);
CFRunLoopStop(media_poll_loop);
pthread_join(media_thread, NULL);
media_poll_loop = NULL;
media_thread_active = false;
}
}
/*
* Get the BSD-style path of specified object
*/
static kern_return_t get_device_path(io_object_t obj, char *path, size_t maxPathLength)
{
kern_return_t kernResult = KERN_FAILURE;
CFTypeRef pathAsCFString = IORegistryEntryCreateCFProperty(obj, CFSTR(kIOBSDNameKey),
kCFAllocatorDefault, 0);
if (pathAsCFString) {
strcpy(path, "/dev/");
size_t pathLength = strlen(path);
if (CFStringGetCString((const __CFString *)pathAsCFString,
path + pathLength,
maxPathLength - pathLength,
kCFStringEncodingASCII))
kernResult = KERN_SUCCESS;
CFRelease(pathAsCFString);
}
return kernResult;
}
/*
* kIOMatchedNotification handler
*/
static void media_arrived(int type, io_iterator_t iterator)
{
io_object_t obj;
while ((obj = IOIteratorNext(iterator))) {
char path[MAXPATHLEN];
kern_return_t kernResult = get_device_path(obj, path, sizeof(path));
if (kernResult == KERN_SUCCESS) {
D(bug("Media Arrived: %s\n", path));
SysMediaArrived(path, type);
}
kernResult = IOObjectRelease(obj);
if (kernResult != KERN_SUCCESS) {
fprintf(stderr, "IOObjectRelease() returned %d\n", kernResult);
}
}
}
/*
* kIOTerminatedNotification handler
*/
static void media_removed(int type, io_iterator_t iterator)
{
io_object_t obj;
while ((obj = IOIteratorNext(iterator))) {
char path[MAXPATHLEN];
kern_return_t kernResult = get_device_path(obj, path, sizeof(path));
if (kernResult == KERN_SUCCESS) {
D(bug("Media Removed: %s\n", path));
SysMediaRemoved(path, type);
}
kernResult = IOObjectRelease(obj);
if (kernResult != KERN_SUCCESS) {
fprintf(stderr, "IOObjectRelease() returned %d\n", kernResult);
}
}
}
/*
* Media poll function
*
* NOTE: to facilitate orderly thread termination, media_poll_func MUST end up waiting in CFRunLoopRun.
* Early returns must be avoided, even if there is nothing useful to be done here. See DarwinSysExit.
*/
static void dummy(void *) { }; // stub for dummy runloop source
static void *media_poll_func(void *)
{
media_poll_loop = CFRunLoopGetCurrent();
mach_port_t masterPort;
kern_return_t kernResult;
CFMutableDictionaryRef matchingDictionary;
CFRunLoopSourceRef loopSource = NULL;
CFRunLoopSourceRef dummySource = NULL;
if ((kernResult = IOMasterPort(bootstrap_port, &masterPort)) != KERN_SUCCESS)
fprintf(stderr, "IOMasterPort() returned %d\n", kernResult);
else if ((matchingDictionary = IOServiceMatching(kIOCDMediaClass)) == NULL)
fprintf(stderr, "IOServiceMatching() returned a NULL dictionary\n");
else {
matchingDictionary = (CFMutableDictionaryRef)CFRetain(matchingDictionary);
IONotificationPortRef notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
loopSource = IONotificationPortGetRunLoopSource(notificationPort);
CFRunLoopAddSource(media_poll_loop, loopSource, kCFRunLoopDefaultMode);
io_iterator_t mediaArrivedIterator;
kernResult = IOServiceAddMatchingNotification(notificationPort,
kIOMatchedNotification,
matchingDictionary,
(IOServiceMatchingCallback)media_arrived,
(void *)MEDIA_CD, &mediaArrivedIterator);
if (kernResult != KERN_SUCCESS)
fprintf(stderr, "IOServiceAddMatchingNotification() returned %d\n", kernResult);
media_arrived(MEDIA_CD, mediaArrivedIterator);
io_iterator_t mediaRemovedIterator;
kernResult = IOServiceAddMatchingNotification(notificationPort,
kIOTerminatedNotification,
matchingDictionary,
(IOServiceMatchingCallback)media_removed,
(void *)MEDIA_CD, &mediaRemovedIterator);
if (kernResult != KERN_SUCCESS)
fprintf(stderr, "IOServiceAddMatchingNotification() returned %d\n", kernResult);
media_removed(MEDIA_CD, mediaRemovedIterator);
}
if (loopSource == NULL) {
// add a dummy runloop source to prevent premature return from CFRunLoopRun
CFRunLoopSourceContext context = { 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, dummy };
dummySource = CFRunLoopSourceCreate(NULL, 0, &context);
CFRunLoopAddSource(media_poll_loop, dummySource, kCFRunLoopDefaultMode);
}
CFRunLoopRun();
if (dummySource != NULL)
CFRelease(dummySource);
return NULL;
}
void DarwinAddFloppyPrefs(void)
{
mach_port_t masterPort; // The way to talk to the kernel
io_iterator_t allFloppies; // List of possible floppys
CFMutableDictionaryRef classesToMatch;
io_object_t nextFloppy;
if ( IOMasterPort(MACH_PORT_NULL, &masterPort) != KERN_SUCCESS )
bug("IOMasterPort failed. Won't be able to do anything with floppy drives\n");
// This selects all partitions of all disks
classesToMatch = IOServiceMatching(kIOMediaClass);
if ( classesToMatch )
{
// Skip drivers and partitions
CFDictionarySetValue(classesToMatch,
CFSTR(kIOMediaWholeKey), kCFBooleanTrue);
// Skip fixed drives (hard disks?)
CFDictionarySetValue(classesToMatch,
CFSTR(kIOMediaEjectableKey), kCFBooleanTrue);
}
if ( IOServiceGetMatchingServices(masterPort,
classesToMatch, &allFloppies) != KERN_SUCCESS )
{
D(bug("IOServiceGetMatchingServices failed. No removable drives found?\n"));
return;
}
// Iterate through each floppy
while ((nextFloppy = IOIteratorNext(allFloppies)))
{
char bsdPath[MAXPATHLEN];
long size = 0;
Boolean gotSize = FALSE;
CFTypeRef sizeAsCFNumber =
IORegistryEntryCreateCFProperty(nextFloppy,
CFSTR(kIOMediaSizeKey),
kCFAllocatorDefault, 0);
if (sizeAsCFNumber)
{
gotSize = CFNumberGetValue((CFNumberRef)sizeAsCFNumber, kCFNumberSInt32Type, &size);
CFRelease(sizeAsCFNumber);
}
if (gotSize)
{
D(bug("Got size of %ld\n", size));
if ( size < 800 * 1024 || size > 1440 * 1024 )
{
D(puts("Device does not appear to be 800k or 1440k"));
continue;
}
}
else {
D(puts("Couldn't get kIOMediaSizeKey of device"));
continue; // if kIOMediaSizeKey is unavailable, we shouldn't use it anyway
}
if (get_device_path(nextFloppy, bsdPath, sizeof(bsdPath)) == KERN_SUCCESS) {
PrefsAddString("floppy", bsdPath);
} else {
D(bug("Could not get BSD device path for floppy\n"));
}
}
IOObjectRelease(nextFloppy);
IOObjectRelease(allFloppies);
}
void DarwinAddSerialPrefs(void)
{
mach_port_t masterPort; // The way to talk to the kernel
io_iterator_t allModems; // List of modems on the system
CFMutableDictionaryRef classesToMatch;
io_object_t nextModem;
if ( IOMasterPort(MACH_PORT_NULL, &masterPort) != KERN_SUCCESS )
bug("IOMasterPort failed. Won't be able to do anything with modems\n");
// Serial devices are instances of class IOSerialBSDClient
classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
if ( classesToMatch )
{
// Narrow the search a little further. Each serial device object has
// a property with key kIOSerialBSDTypeKey and a value that is one of
// kIOSerialBSDAllTypes, kIOSerialBSDModemType, or kIOSerialBSDRS232Type.
CFDictionarySetValue(classesToMatch,
CFSTR(kIOSerialBSDTypeKey),
CFSTR(kIOSerialBSDModemType));
// This will find built-in and USB modems, but not serial modems.
}
if ( IOServiceGetMatchingServices(masterPort,
classesToMatch, &allModems) != KERN_SUCCESS )
{
D(bug("IOServiceGetMatchingServices failed. No modems found?\n"));
return;
}
// Iterate through each modem
while ((nextModem = IOIteratorNext(allModems)))
{
char bsdPath[MAXPATHLEN];
CFTypeRef bsdPathAsCFString =
IORegistryEntryCreateCFProperty(nextModem,
CFSTR(kIOCalloutDeviceKey),
// kIODialinDeviceKey?
kCFAllocatorDefault, 0);
*bsdPath = '\0';
if ( bsdPathAsCFString )
{
if ( CFStringGetCString((const __CFString *)bsdPathAsCFString,
bsdPath, MAXPATHLEN,
kCFStringEncodingASCII) )
{
D(bug("Modem BSD path: %s\n", bsdPath));
// Note that if there are multiple modems, we only get the last
PrefsAddString("seriala", bsdPath);
}
else
D(bug("Could not get BSD device path for modem\n"));
CFRelease(bsdPathAsCFString);
}
else
D(puts("Cannot determine bsdPath for modem\n"));
}
IOObjectRelease(nextModem);
IOObjectRelease(allModems);
// Getting a printer device is a bit harder. Creating a fake device
// that emulates a simple printer (e.g. a HP DeskJet) is one possibility,
// but for now I will just create a fake, safe, device entry:
PrefsAddString("serialb", "/dev/null");
}
#ifdef MAC_OS_X_VERSION_10_2
/*
* Read CD-ROM TOC (binary MSF format, 804 bytes max.)
*/
bool DarwinCDReadTOC(char *name, uint8 *toc)
{
char *c, *devname;
int fd;
// The open filehandle is something like /dev/disk5s1
// The DKIOCCDREADTOC ioctl needs the original cd file,
// so we strip the s1 suffix off it, and open the file just for this ioctl
devname = strdup(name);
if ( ! devname )
return false;
for ( c = devname; *c; ++c ) ; // Go to the end of the name,
--c, --c; // point to the 's1' on the end,
*c = '\0'; // and truncate the string
fd = open(devname, O_RDONLY);
if ( ! fd )
{
printf("Failed to open CD device %s for ioctl\n", devname);
free(devname);
return false;
}
D(bug("Opened %s for ioctl()\n", devname));
dk_cd_read_toc_t TOCrequest;
// Setup the ioctl request structure:
memset(&TOCrequest, 0, sizeof(TOCrequest));
TOCrequest.buffer = toc;
TOCrequest.bufferLength = 804;
TOCrequest.formatAsTime = kCDTrackInfoAddressTypeTrackNumber;
if ( ioctl(fd, DKIOCCDREADTOC, &TOCrequest) < 0 )
{
printf("ioctl(DKIOCCDREADTOC) failed: %s\n", strerror(errno));
close(fd);
free(devname);
return false;
}
if ( TOCrequest.bufferLength < sizeof(CDTOC) )
{
printf("ioctl(DKIOCCDREADTOC): only read %d bytes (a CDTOC is at least %d)\n",
TOCrequest.bufferLength, (int)sizeof(CDTOC));
close(fd);
free(devname);
return false;
}
D(bug("ioctl(DKIOCCDREADTOC) read %d bytes\n", TOCrequest.bufferLength));
close(fd);
free(devname);
return true;
}
#endif
| 28.285714 | 104 | 0.719016 | jvernet |
28b92ffb134d8456e86ac6a01fb77949fe96e59b | 10,742 | hpp | C++ | rclcpp/include/rclcpp/subscription_base.hpp | squizz617/rclcpp | 8e5ddb1f81d4ddf8f788b1d67cbb0e7ef477d504 | [
"Apache-2.0"
] | 3 | 2021-07-05T11:20:10.000Z | 2022-02-18T16:13:15.000Z | rclcpp/include/rclcpp/subscription_base.hpp | squizz617/rclcpp | 8e5ddb1f81d4ddf8f788b1d67cbb0e7ef477d504 | [
"Apache-2.0"
] | 16 | 2020-12-16T16:20:21.000Z | 2022-02-28T11:32:48.000Z | rclcpp/include/rclcpp/subscription_base.hpp | irobot-ros/rclcpp | edcae47df2528a9c06cfd98f204ad9b5d2da56b4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Open Source Robotics Foundation, Inc.
//
// 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.
#ifndef RCLCPP__SUBSCRIPTION_BASE_HPP_
#define RCLCPP__SUBSCRIPTION_BASE_HPP_
#include <atomic>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <utility>
#include "rcl/subscription.h"
#include "rmw/rmw.h"
#include "rclcpp/any_subscription_callback.hpp"
#include "rclcpp/experimental/intra_process_manager.hpp"
#include "rclcpp/experimental/subscription_intra_process_base.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/message_info.hpp"
#include "rclcpp/qos.hpp"
#include "rclcpp/qos_event.hpp"
#include "rclcpp/serialized_message.hpp"
#include "rclcpp/type_support_decl.hpp"
#include "rclcpp/visibility_control.hpp"
namespace rclcpp
{
namespace node_interfaces
{
class NodeBaseInterface;
} // namespace node_interfaces
namespace experimental
{
/**
* IntraProcessManager is forward declared here, avoiding a circular inclusion between
* `intra_process_manager.hpp` and `subscription_base.hpp`.
*/
class IntraProcessManager;
} // namespace experimental
/// Virtual base class for subscriptions. This pattern allows us to iterate over different template
/// specializations of Subscription, among other things.
class SubscriptionBase : public std::enable_shared_from_this<SubscriptionBase>
{
public:
RCLCPP_SMART_PTR_DEFINITIONS_NOT_COPYABLE(SubscriptionBase)
/// Default constructor.
/**
* \param[in] node_base NodeBaseInterface pointer used in parts of the setup.
* \param[in] type_support_handle rosidl type support struct, for the Message type of the topic.
* \param[in] topic_name Name of the topic to subscribe to.
* \param[in] subscription_options Options for the subscription.
* \param[in] is_serialized is true if the message will be delivered still serialized
*/
RCLCPP_PUBLIC
SubscriptionBase(
rclcpp::node_interfaces::NodeBaseInterface * node_base,
const rosidl_message_type_support_t & type_support_handle,
const std::string & topic_name,
const rcl_subscription_options_t & subscription_options,
bool is_serialized = false);
/// Default destructor.
RCLCPP_PUBLIC
virtual ~SubscriptionBase();
/// Get the topic that this subscription is subscribed on.
RCLCPP_PUBLIC
const char *
get_topic_name() const;
RCLCPP_PUBLIC
std::shared_ptr<rcl_subscription_t>
get_subscription_handle();
RCLCPP_PUBLIC
std::shared_ptr<const rcl_subscription_t>
get_subscription_handle() const;
/// Get all the QoS event handlers associated with this subscription.
/** \return The vector of QoS event handlers. */
RCLCPP_PUBLIC
const std::vector<std::shared_ptr<rclcpp::QOSEventHandlerBase>> &
get_event_handlers() const;
/// Get the actual QoS settings, after the defaults have been determined.
/**
* The actual configuration applied when using RMW_QOS_POLICY_*_SYSTEM_DEFAULT
* can only be resolved after the creation of the publisher, and it
* depends on the underlying rmw implementation.
* If the underlying setting in use can't be represented in ROS terms,
* it will be set to RMW_QOS_POLICY_*_UNKNOWN.
* May throw runtime_error when an unexpected error occurs.
*
* \return The actual qos settings.
* \throws std::runtime_error if failed to get qos settings
*/
RCLCPP_PUBLIC
rclcpp::QoS
get_actual_qos() const;
/// Take the next inter-process message from the subscription as a type erased pointer.
/**
* \sa Subscription::take() for details on how this function works.
*
* The only difference is that it takes a type erased pointer rather than a
* reference to the exact message type.
*
* This type erased version facilitates using the subscriptions in a type
* agnostic way using SubscriptionBase::create_message() and
* SubscriptionBase::handle_message().
*
* \param[out] message_out The type erased message pointer into which take
* will copy the data.
* \param[out] message_info_out The message info for the taken message.
* \returns true if data was taken and is valid, otherwise false
* \throws any rcl errors from rcl_take, \sa rclcpp::exceptions::throw_from_rcl_error()
*/
RCLCPP_PUBLIC
bool
take_type_erased(void * message_out, rclcpp::MessageInfo & message_info_out);
/// Take the next inter-process message, in its serialized form, from the subscription.
/**
* For now, if data is taken (written) into the message_out and
* message_info_out then true will be returned.
* Unlike Subscription::take(), taking data serialized is not possible via
* intra-process for the time being, so it will not need to de-duplicate
* data in any case.
*
* \param[out] message_out The serialized message data structure used to
* store the taken message.
* \param[out] message_info_out The message info for the taken message.
* \returns true if data was taken and is valid, otherwise false
* \throws any rcl errors from rcl_take, \sa rclcpp::exceptions::throw_from_rcl_error()
*/
RCLCPP_PUBLIC
bool
take_serialized(rclcpp::SerializedMessage & message_out, rclcpp::MessageInfo & message_info_out);
/// Borrow a new message.
/** \return Shared pointer to the fresh message. */
RCLCPP_PUBLIC
virtual
std::shared_ptr<void>
create_message() = 0;
/// Borrow a new serialized message
/** \return Shared pointer to a rcl_message_serialized_t. */
RCLCPP_PUBLIC
virtual
std::shared_ptr<rclcpp::SerializedMessage>
create_serialized_message() = 0;
/// Check if we need to handle the message, and execute the callback if we do.
/**
* \param[in] message Shared pointer to the message to handle.
* \param[in] message_info Metadata associated with this message.
*/
RCLCPP_PUBLIC
virtual
void
handle_message(std::shared_ptr<void> & message, const rclcpp::MessageInfo & message_info) = 0;
RCLCPP_PUBLIC
virtual
void
handle_loaned_message(void * loaned_message, const rclcpp::MessageInfo & message_info) = 0;
/// Return the message borrowed in create_message.
/** \param[in] message Shared pointer to the returned message. */
RCLCPP_PUBLIC
virtual
void
return_message(std::shared_ptr<void> & message) = 0;
/// Return the message borrowed in create_serialized_message.
/** \param[in] message Shared pointer to the returned message. */
RCLCPP_PUBLIC
virtual
void
return_serialized_message(std::shared_ptr<rclcpp::SerializedMessage> & message) = 0;
RCLCPP_PUBLIC
const rosidl_message_type_support_t &
get_message_type_support_handle() const;
/// Return if the subscription is serialized
/**
* \return `true` if the subscription is serialized, `false` otherwise
*/
RCLCPP_PUBLIC
bool
is_serialized() const;
/// Get matching publisher count.
/** \return The number of publishers on this topic. */
RCLCPP_PUBLIC
size_t
get_publisher_count() const;
/// Check if subscription instance can loan messages.
/**
* Depending on the middleware and the message type, this will return true if the middleware
* can allocate a ROS message instance.
*
* \return boolean flag indicating if middleware can loan messages.
*/
RCLCPP_PUBLIC
bool
can_loan_messages() const;
using IntraProcessManagerWeakPtr =
std::weak_ptr<rclcpp::experimental::IntraProcessManager>;
/// Implemenation detail.
RCLCPP_PUBLIC
void
setup_intra_process(
uint64_t intra_process_subscription_id,
IntraProcessManagerWeakPtr weak_ipm);
/// Return the waitable for intra-process
/**
* \return the waitable sharedpointer for intra-process, or nullptr if intra-process is not setup.
* \throws std::runtime_error if the intra process manager is destroyed
*/
RCLCPP_PUBLIC
rclcpp::Waitable::SharedPtr
get_intra_process_waitable() const;
/// Exchange state of whether or not a part of the subscription is used by a wait set.
/**
* Used to ensure parts of the subscription are not used with multiple wait
* sets simultaneously.
*
* \param[in] pointer_to_subscription_part address of a subscription part
* \param[in] in_use_state the new state to exchange, true means "now in use",
* and false means "no longer in use".
* \returns the current "in use" state.
* \throws std::invalid_argument If pointer_to_subscription_part is nullptr.
* \throws std::runtime_error If the pointer given is not a pointer to one of
* the parts of the subscription which can be used with a wait set.
*/
RCLCPP_PUBLIC
bool
exchange_in_use_by_wait_set_state(void * pointer_to_subscription_part, bool in_use_state);
protected:
template<typename EventCallbackT>
void
add_event_handler(
const EventCallbackT & callback,
const rcl_subscription_event_type_t event_type)
{
auto handler = std::make_shared<QOSEventHandler<EventCallbackT,
std::shared_ptr<rcl_subscription_t>>>(
callback,
rcl_subscription_event_init,
get_subscription_handle(),
event_type);
qos_events_in_use_by_wait_set_.insert(std::make_pair(handler.get(), false));
event_handlers_.emplace_back(handler);
}
RCLCPP_PUBLIC
void default_incompatible_qos_callback(QOSRequestedIncompatibleQoSInfo & info) const;
RCLCPP_PUBLIC
bool
matches_any_intra_process_publishers(const rmw_gid_t * sender_gid) const;
rclcpp::node_interfaces::NodeBaseInterface * const node_base_;
std::shared_ptr<rcl_node_t> node_handle_;
std::shared_ptr<rcl_subscription_t> subscription_handle_;
std::shared_ptr<rcl_subscription_t> intra_process_subscription_handle_;
std::vector<std::shared_ptr<rclcpp::QOSEventHandlerBase>> event_handlers_;
bool use_intra_process_;
IntraProcessManagerWeakPtr weak_ipm_;
uint64_t intra_process_subscription_id_;
private:
RCLCPP_DISABLE_COPY(SubscriptionBase)
rosidl_message_type_support_t type_support_;
bool is_serialized_;
std::atomic<bool> subscription_in_use_by_wait_set_{false};
std::atomic<bool> intra_process_subscription_waitable_in_use_by_wait_set_{false};
std::unordered_map<rclcpp::QOSEventHandlerBase *,
std::atomic<bool>> qos_events_in_use_by_wait_set_;
};
} // namespace rclcpp
#endif // RCLCPP__SUBSCRIPTION_BASE_HPP_
| 33.886435 | 100 | 0.754515 | squizz617 |
28ba3290c1bd771e7dee70f8c740f77677e8fa9b | 9,880 | cpp | C++ | CPU_6502/CPU_6502/vm_class.cpp | JimmyHwang/PC6502 | d93067bd46a5df5c30a50ec79f5dff1c419edfc5 | [
"MIT"
] | null | null | null | CPU_6502/CPU_6502/vm_class.cpp | JimmyHwang/PC6502 | d93067bd46a5df5c30a50ec79f5dff1c419edfc5 | [
"MIT"
] | 4 | 2021-02-09T10:33:44.000Z | 2021-02-09T10:35:59.000Z | CPU_6502/CPU_6502/vm_class.cpp | JimmyHwang/PC6502 | d93067bd46a5df5c30a50ec79f5dff1c419edfc5 | [
"MIT"
] | null | null | null | #include "main.h"
//#define DEBUG_ADDRESSS_DECODER
//-----------------------------------------------------------------------------
// Memory Hook for CPU
//-----------------------------------------------------------------------------
UINT8
MemoryRead8(
MEMORY_CONTROL_PROTOCOL *Protocol,
UINTN Ip
) {
UINT8 Data;
int Index;
VM_CLASS *This;
BASE_DEVICE_CLASS *Device;
This = _CR(Protocol, VM_CLASS, MemoryControl);
Index = (Ip >> ADDRESS_MASK_BITS) & ADDRESS_INDEX_MASK;
Device = This->DeviceMappingTable[Index];
Data = Device->Read8(Ip);
//
// Update ShadowMemory for Disassembly
//
if (This->ShadowMemory) {
This->ShadowMemory[Ip] = Data;
}
//
// Record memory action
//
int wp = This->MemoryAccessIndex;
MEMORY_ACCESS *record = &This->MemoryAccessHistory[wp];
record->Mode = MEMORY_ACCESS_READ;
record->Address = (UINT16)Ip;
record->Data = Data;
wp = (wp + 1) & MEMORY_ACCESS_MASK;
This->MemoryAccessIndex = wp;
if (This->MemoryAccessCount < MEMORY_ACCESS_MAX) {
This->MemoryAccessCount++;
}
#ifdef DEBUG_ADDRESSS_DECODER
DebugOut(L"R8,0x%lX=0x%08X", Ip, Data);
#endif
return Data;
}
VOID
MemoryWrite8(
MEMORY_CONTROL_PROTOCOL *Protocol,
UINTN Ip,
UINT8 Data
) {
int Index;
VM_CLASS *This;
BASE_DEVICE_CLASS *Device;
#ifdef DEBUG_ADDRESSS_DECODER
DebugOut(L"W8,0x%lX=0x%08X", Ip, Data);
#endif
This = _CR(Protocol, VM_CLASS, MemoryControl);
Index = (Ip >> ADDRESS_MASK_BITS) & ADDRESS_INDEX_MASK;
Device = This->DeviceMappingTable[Index];
//
// Update ShadowMemory for Disassembly
//
if (Device->ReadOnly == false) {
if (This->ShadowMemory) {
This->ShadowMemory[Ip] = Data;
}
Device->Write8(Ip, Data);
}
//
// Record memory action
//
int wp = This->MemoryAccessIndex;
MEMORY_ACCESS *record = &This->MemoryAccessHistory[wp];
record->Mode = MEMORY_ACCESS_WRITE;
record->Address = (UINT16)Ip;
record->Data = Data;
wp = (wp + 1) & MEMORY_ACCESS_MASK;
This->MemoryAccessIndex = wp;
if (This->MemoryAccessCount < MEMORY_ACCESS_MAX) {
This->MemoryAccessCount++;
}
}
UINT16
MemoryRead16(
MEMORY_CONTROL_PROTOCOL *Protocol,
UINTN Ip
)
{
assert(false);
return 0;
}
VOID
MemoryWrite16(
MEMORY_CONTROL_PROTOCOL *Protocol,
UINTN Ip,
UINT16 Data
)
{
assert(false);
}
UINT32
MemoryRead32(
MEMORY_CONTROL_PROTOCOL *Protocol,
UINTN Ip
)
{
assert(false);
return 0;
}
VOID
MemoryWrite32(
MEMORY_CONTROL_PROTOCOL *Protocol,
UINTN Ip,
UINT32 Data
)
{
assert(false);
}
char *VM_CLASS::Talk(char *message) {
string jstr;
BASE_DEVICE_CLASS *dev;
DNA_STATUS status;
json jst;
string target;
string command;
jst = {};
jstr = message;
auto j = json::parse(jstr);
target = j["Target"];
if (target == "XIO") {
status = this->FindDevice("XIO", &dev);
jst = dev->Talk(j);
} else if (target == "CPU") {
jst = this->CPU->Talk(j);
} else if (target == "VM") {
command = j["Command"];
if (command == "Reload") {
jst = this->Reload();
} else {
jst["Status"] = "Failed";
jst["Message"] = "Command not found";
}
} else {
jst["Status"] = "Failed";
jst["Message"] = "Target not found";
}
return ExportJsonString(jst);
}
//-----------------------------------------------------------------------------
// Private Functions
//-----------------------------------------------------------------------------
void VM_CLASS::AddDevice(BASE_DEVICE_CLASS *Device, UINTN Address, UINTN Size) {
int i;
UINTN addr;
Device->VM = this;
Device->Base = Address;
//
// Add to device list for manager device resources
//
for (i = 0; i < MAX_DEVICE_COUNT; i++) {
if (this->DeviceList[i] == NULL) {
this->DeviceList[i] = Device;
break;
}
}
//
// Add Device to Mapping Table
//
for (i = 0; i < 16; i++) {
addr = i << ADDRESS_MASK_BITS;
if (addr >= Address && addr <= Address + Size) {
this->DeviceMappingTable[i] = Device;
}
}
}
//-----------------------------------------------------------------------------
// Public Functions
//-----------------------------------------------------------------------------
DNA_STATUS VM_CLASS::AddDeviceROM(UINT16 base, UINT16 size, UINT8 *buffer) {
DNA_STATUS Status;
ROM_DEVICE_CLASS *ROM;
ROM = new ROM_DEVICE_CLASS(size);
ROM->LoadImage(buffer, size);
this->AddDevice(ROM, base, size);
if (this->ShadowMemory) {
memcpy(this->ShadowMemory + base, buffer, size);
}
Status = DNA_SUCCESS;
return Status;
}
DNA_STATUS VM_CLASS::AddDeviceROM(UINT16 base, UINT16 size, string filename) {
DNA_STATUS Status;
ROM_DEVICE_CLASS *ROM;
ROM = new ROM_DEVICE_CLASS(size);
ROM->LoadFile(filename);
this->AddDevice(ROM, base, size);
if (this->ShadowMemory) {
memcpy(this->ShadowMemory + base, ROM->Buffer, size);
}
Status = DNA_SUCCESS;
return Status;
}
DNA_STATUS VM_CLASS::AddDeviceRAM(UINT16 base, UINT16 size) {
DNA_STATUS Status;
RAM_DEVICE_CLASS *RAM;
RAM = new RAM_DEVICE_CLASS(size);
this->AddDevice(RAM, base, size);
Status = DNA_SUCCESS;
return Status;
}
DNA_STATUS VM_CLASS::AddDeviceXIO(UINT16 base, UINT16 size) {
DNA_STATUS Status;
XIO_DEVICE_CLASS *XIO;
XIO = new XIO_DEVICE_CLASS(size);
this->AddDevice(XIO, base, size);
Status = DNA_SUCCESS;
return Status;
}
DNA_STATUS VM_CLASS::FindDevice(string Type, BASE_DEVICE_CLASS **Device) {
return FindDevice(Type, Device, 0);
}
DNA_STATUS VM_CLASS::FindDevice(string Type, BASE_DEVICE_CLASS **Device, int Index) {
DNA_STATUS status;
BASE_DEVICE_CLASS *dev;
int i;
status = DNA_NOT_FOUND;
for (i = 0; i < MAX_DEVICE_COUNT; i++) {
if (this->DeviceList[i] != NULL) {
dev = this->DeviceList[i];
if (dev->Type == Type) {
if (Index == 0) {
*Device = dev;
status = DNA_SUCCESS;
break;
} else {
Index--;
}
}
}
}
return status;
}
DNA_STATUS VM_CLASS::Reset() {
DNA_STATUS Status;
//
// Clear Memory History
//
this->MemoryAccessIndex = 0;
this->MemoryAccessCount = 0;
//
// Reset Processor
//
this->CpuControl->Reset(this->CpuControl);
Status = DNA_SUCCESS;
return Status;
}
DNA_STATUS VM_CLASS::Reload() {
DNA_STATUS Status;
DNA_STATUS Result;
int i;
BASE_DEVICE_CLASS *Device;
ROM_DEVICE_CLASS *ROM;
Result = DNA_NOT_FOUND;
for (i = 0; i < 16; i++) {
Status = this->FindDevice("ROM", &Device, i);
if (Status == DNA_SUCCESS) {
Result = DNA_SUCCESS;
ROM = (ROM_DEVICE_CLASS *)Device;
Status = ROM->Reload();
if (Status == DNA_SUCCESS) {
if (this->ShadowMemory) {
memcpy(this->ShadowMemory + ROM->Base, ROM->Buffer, ROM->Size);
}
} else {
Result = Status;
break;
}
}
return Result;
}
//
// Clear Memory History
//
this->MemoryAccessIndex = 0;
this->MemoryAccessCount = 0;
//
// Reset Processor
//
this->CpuControl->Reset(this->CpuControl);
Status = DNA_SUCCESS;
return Status;
}
//
// flag.0 (count.24)
// Run with Step Over
//
DNA_STATUS VM_CLASS::Run(int count) {
DNA_STATUS Status;
int flag;
flag = count & 0xFF000000;
count &= 0xFFFFFF;
Status = DNA_SUCCESS;
if (flag & VM_STEP_OVER_FLAG) {
UINT16 pc;
UINT16 target_pc;
UINT8 opcode;
pc = CPU->pc;
opcode = this->ShadowMemory[pc];
if (opcode == 0x20) { // is JSR instruction
target_pc = pc + 3;
do {
Status = this->CpuControl->Run(this->CpuControl, 1);
if (Status == DNA_BREAK_POINT) {
break;
}
} while (CPU->pc != target_pc);
} else {
Status = this->CpuControl->Run(this->CpuControl, 1);
}
} else if (flag & VM_THREAD_FLAG) {
ThreadRunningFlag = true;
if (flag & VM_THREAD_COUNT_FLAG) {
ThreadContinueFlag = true;
} else if (count == 0) {
ThreadContinueFlag = true;
count = 0x1000;
} else {
ThreadContinueFlag = false;
}
do {
Status = this->CpuControl->Run(this->CpuControl, count);
if (Status == DNA_BREAK_POINT) {
break;
}
} while (ThreadContinueFlag);
ThreadRunningFlag = false;
} else {
Status = this->CpuControl->Run(this->CpuControl, count);
}
return Status;
}
DNA_STATUS VM_CLASS::Halt() {
DNA_STATUS Status;
if (ThreadRunningFlag) {
Status = this->CpuControl->Halt (this->CpuControl);
} else {
Status = DNA_NOT_FOUND;
}
return Status;
}
//-----------------------------------------------------------------------------
// Constructor & Destructor
//-----------------------------------------------------------------------------
VM_CLASS::VM_CLASS() {
int i;
NULL_DEVICE_CLASS *NUL;
this->CPU = new CLASS_MOS6502();
this->CpuControl = &this->CPU->CpuControl;
this->CPU->MemoryControl = &this->MemoryControl;
this->MemoryControl.Read8 = MemoryRead8;
this->MemoryControl.Write8 = MemoryWrite8;
this->MemoryControl.Read16 = MemoryRead16;
this->MemoryControl.Write16 = MemoryWrite16;
this->MemoryControl.Read32 = MemoryRead32;
this->MemoryControl.Write32 = MemoryWrite32;
//
// Initialize Shadow Memory
//
this->ShadowMemory = (UINT8 *)malloc(0x10000);
//
// Initialize Device List
//
for (i = 0; i < MAX_DEVICE_COUNT; i++) {
this->DeviceList[i] = NULL;
}
//
// Initialize Mapping Table
//
NUL = new NULL_DEVICE_CLASS();
this->AddDevice (NUL, 0x0000, 0x10000);
}
VM_CLASS::~VM_CLASS() {
int i;
BASE_DEVICE_CLASS *device;
//
// Free Shadow Memory
//
free (this->ShadowMemory);
//
// Free Device
//
for (i = 0; i < MAX_DEVICE_COUNT; i++) {
device = this->DeviceList[i];
if (device != NULL) {
delete device;
this->DeviceList[i] = NULL;
}
}
}
| 21.858407 | 85 | 0.589676 | JimmyHwang |
28badb48492f82e1e867e8b6c966911cd60e76cc | 10,891 | cpp | C++ | triad-sycl/OptionParser.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 162 | 2015-01-25T23:22:48.000Z | 2022-03-19T12:36:05.000Z | triad-sycl/OptionParser.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 20 | 2016-01-08T21:54:33.000Z | 2021-11-05T13:36:30.000Z | triad-sycl/OptionParser.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 85 | 2015-01-06T15:27:13.000Z | 2022-01-24T16:49:09.000Z | #include <string>
#include <vector>
#include <map>
#include "OptionParser.h"
#include "Utility.h"
#include <sstream>
#include <fstream>
#include <iomanip>
using namespace std;
OptionParser::OptionParser()
: helpRequested( false )
{
addOption("configFile", OPT_STRING, "",
"specify configuration file", 'c');
addOption("help", OPT_BOOL, "", "print this usage", 'h');
}
void OptionParser::addOption(const string &longName,
OptionType type,
const string &defaultValue,
const string &helpText,
char shortLetter)
{
Option opt;
opt.longName = longName;
opt.type = type;
opt.defaultValue = defaultValue;
opt.value = defaultValue;
opt.helpText = helpText;
opt.shortLetter = shortLetter;
if (optionMap.count(longName)>0)
cout << "Internal error: used option long name '"<<longName<<"' twice.\n";
optionMap[longName] = opt;
if (shortLetter != '\0')
{
if (shortLetterMap.count(shortLetter)>0)
cout << "Internal error: used option short letter '"
<< shortLetter<<"' twice (for '"
<< shortLetterMap[opt.shortLetter]
<< "' and '"
<< longName <<"')\n";
shortLetterMap[opt.shortLetter] = opt.longName;
}
}
bool OptionParser::parse(int argc, const char *const argv[])
{
vector<string> args;
for (int i=1; i<argc; i++)
args.push_back(argv[i]);
return parse(args);
}
//
// Modifications:
// Jeremy Meredith, Thu Nov 4 14:42:18 EDT 2010
// Don't print out usage here; count on the caller to do that.
// The main reason is we parse the options in parallel and
// don't want every task to print an error or help text.
//
bool OptionParser::parse(const vector<string> &args) {
for (int i=0; i<args.size(); i++) {
//parse arguments
string temp = args[i];
if (temp[0] != '-')
{
cout << "failure, no leading - in option: " << temp << "\n";
cout << "Ignoring remaining options" << endl;
return false;
}
else if (temp[0] == '-' && temp[1] == '-') //Long Name argument
{
string longName = temp.substr(2);
if (longName=="configFile" && ! (i+1>=args.size())) {
if (!parseFile(args[i+1]))
{
return false;
}
i++;
continue;
}
if (optionMap.find(longName) == optionMap.end()) {
cout << "Option not recognized: " << temp << endl;
cout << "Ignoring remaining options" << endl;
return false;
}
if (optionMap[longName].type == OPT_BOOL) {
//Option is bool and is flagged true
optionMap[longName].value = "true";
} else {
if (i+1 >= args.size()) {
cout << "failure, option: " << temp << " with no value\n";
cout << "Ignoring remaining options" << endl;
return false;
} else {
optionMap[longName].value = args[i+1];
i++;
}
}
}
else //Short name argument
{
int nopts = temp.length()-1;
for (int p=0; p<nopts; p++)
{
char shortLetter = temp[p+1];
if (shortLetterMap.find(shortLetter) == shortLetterMap.end()) {
cout << "Option: " << temp << " not recognized.\n";
cout << "Ignoring remaining options" << endl;
return false;
}
string longName = shortLetterMap[shortLetter];
if (longName=="configFile" && ! (i+1>=args.size())) {
if (!parseFile(args[i+1]))
{
return false;
}
i++;
continue;
}
if (optionMap[longName].type == OPT_BOOL) {
//Option is bool and is flagged true
optionMap[longName].value = "true";
} else {
if (i+1 >= args.size() || p < nopts-1)
{
//usage();
cout << "failure, option: -" << shortLetter << " with no value\n";
cout << "Ignoring remaining options" << endl;
return false;
}
else
{
optionMap[longName].value = args[i+1];
i++;
}
}
}
}
}
if (getOptionBool("help"))
{
helpRequested = true;
return false;
}
return true;
}
void OptionParser::print() const {
vector<string> printed;
OptionMap::const_iterator i = optionMap.begin();
cout << "Printing Options" << endl;
while(i != optionMap.end()) {
Option o = i->second;
bool skip = false;
for (int j=0; j<printed.size(); j++) {
if (printed[j] == o.longName) skip = true;
}
if (!skip) {
printed.push_back(o.longName);
o.print();
i++;
cout << "---------------------" << endl;
} else { i++; }
}
}
long long OptionParser::getOptionInt(const string &name) const {
long long retVal;
OptionMap::const_iterator iter = optionMap.find( name );
if (iter == optionMap.end()) {
cout << "getOptionInt: option name \"" << name << "\" not recognized.\n";
return -9999;
}
stringstream ss(iter->second.value);
ss >> retVal;
return retVal;
}
float OptionParser::getOptionFloat(const string &name) const {
float retVal;
OptionMap::const_iterator iter = optionMap.find( name );
if (iter == optionMap.end()) {
cout << "getOptionFloat: option name \"" << name << "\" not recognized.\n";
return -9999;
}
stringstream ss(iter->second.value);
ss >> retVal;
return retVal;
}
bool OptionParser::getOptionBool(const string &name) const {
int retVal;
OptionMap::const_iterator iter = optionMap.find( name );
if (iter == optionMap.end()) {
cout << "getOptionBool: option name \"" << name << "\" not recognized.\n";
return false;
}
return (iter->second.value == "true");
}
string OptionParser::getOptionString(const string &name) const {
OptionMap::const_iterator iter = optionMap.find( name );
if (iter == optionMap.end()) {
cout << "getOptionString: option name \"" << name << "\" not recognized.\n";
return "ERROR - Option not recognized";
}
return iter->second.value;
}
vector<long long> OptionParser::getOptionVecInt(const string &name) const {
vector<long long> retval = vector<long long>(0);
OptionMap::const_iterator iter = optionMap.find( name );
if (iter == optionMap.end()) {
cout << "getOptionVecInt: option name \"" << name << "\" not recognized.\n";
return retval;
}
vector<string> tokens = SplitValues(iter->second.value, ',');
for (int i=0; i<tokens.size(); i++) {
stringstream ss(tokens[i]);
long long j;
ss >> j;
retval.push_back(j);
}
return retval;
}
vector<float> OptionParser::getOptionVecFloat(const string &name) const {
vector<float> retval = vector<float>(0);
OptionMap::const_iterator iter = optionMap.find( name );
if (iter == optionMap.end()) {
cout << "getOptionVecFloat: option name \"" << name << "\" not recognized.\n";
return retval;
}
vector<string> tokens = SplitValues(iter->second.value, ',');
for (int i=0; i<tokens.size(); i++) {
stringstream ss(tokens[i]);
float f;
ss >> f;
cout << "F: " << f << endl;
retval.push_back(f);
}
return retval;
}
vector<string> OptionParser::getOptionVecString(const string &name) const {
vector<string> retval = vector<string>(0);
OptionMap::const_iterator iter = optionMap.find( name );
if (iter == optionMap.end()) {
cout << "getOptionVecString: option name \"" << name << "\" not recognized.\n";
return retval;
}
vector<string> tokens = SplitValues(iter->second.value, ',');
for (int i=0; i<tokens.size(); i++) {
stringstream ss(tokens[i]);
string s;
ss >> s;
retval.push_back(s);
}
return retval;
}
void OptionParser::printHelp(const string &optionName) const {
OptionMap::const_iterator iter = optionMap.find( optionName );
if (iter == optionMap.end()) {
cout << "printHelp: option name \"" << optionName << "\" not recognized.\n";
} else {
cout << iter->second.helpText;
}
}
bool OptionParser::parseFile(const string &fileName) {
ifstream inf(fileName.c_str());
string line;
vector<string> optionsFromFile;
if (!inf.good()) {
cout << "Bad config file" << endl;
return false;
}
while (!getline(inf, line).eof())
{
if (line[0] == '#')
continue;
else {
vector<string> tokens = SplitValues(line, ' ');
for (int i=0; i<tokens.size(); i++) {
if (i==0) {
optionsFromFile.push_back("--"+tokens[i]);
} else {
optionsFromFile.push_back(tokens[i]);
}
}
}
}
inf.close();
return parse(optionsFromFile);
}
void OptionParser::usage() const {
string type;
cout << "Usage: benchmark ";
OptionMap::const_iterator j = optionMap.begin();
Option jo = j->second;
cout << "[--" << jo.longName << " ";
if (jo.type == OPT_INT || jo.type == OPT_FLOAT)
type = "number";
else if (jo.type == OPT_BOOL)
type = "";
else if (jo.type == OPT_STRING)
type = "value";
else if (jo.type == OPT_VECFLOAT || jo.type == OPT_VECINT)
type = "n1,n2,...";
else if (jo.type == OPT_VECSTRING)
type = "value1,value2,...";
cout << type << "]" << endl;
while (++j !=optionMap.end()) {
jo = j->second;
cout << " [--" << jo.longName << " ";
if (jo.type == OPT_INT || jo.type == OPT_FLOAT)
type = "number";
else if (jo.type == OPT_BOOL)
type = "";
else if (jo.type == OPT_STRING)
type = "value";
else if (jo.type == OPT_VECFLOAT || jo.type == OPT_VECINT)
type = "n1,n2,...";
else if (jo.type == OPT_VECSTRING)
type = "value1,value2,...";
cout << type << "]" << endl;
}
cout << endl;
cout << "Available Options: " << endl;
OptionMap::const_iterator i = optionMap.begin();
while(i != optionMap.end()) {
Option o = i->second;
cout << " ";
if (o.shortLetter)
cout << "-" << o.shortLetter << ", ";
else
cout << " ";
cout << setiosflags(ios::left) << setw(25)
<< "--" + o.longName + " " << o.helpText << endl;
i++;
}
}
| 27.997429 | 88 | 0.524102 | BeauJoh |
28bce1fc6f52371373ec58e7d240f1779bc20602 | 4,328 | cpp | C++ | src/oswindows/TsfClient/TfCandidateList.cpp | millimoji/ribbon | 59e6659848f5edc435d58078f0cdcd805daf9f3f | [
"MIT"
] | null | null | null | src/oswindows/TsfClient/TfCandidateList.cpp | millimoji/ribbon | 59e6659848f5edc435d58078f0cdcd805daf9f3f | [
"MIT"
] | null | null | null | src/oswindows/TsfClient/TfCandidateList.cpp | millimoji/ribbon | 59e6659848f5edc435d58078f0cdcd805daf9f3f | [
"MIT"
] | null | null | null | // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
#include "pch.h"
#include "TipPrivate.h"
#include "TfCandidateList.h"
#include "TfEnumTfCandidates.h"
#include "TfCandidateString.h"
HRESULT CTfCandidateList::CreateInstance(_Outptr_ ITfCandidateList **ppobj, size_t candStrReserveSize)
{
if (ppobj == nullptr)
{
return E_INVALIDARG;
}
*ppobj = nullptr;
*ppobj = new (std::nothrow) CTfCandidateList(candStrReserveSize);
if (*ppobj == nullptr)
{
return E_OUTOFMEMORY;
}
return S_OK;
}
HRESULT CTfCandidateList::CreateInstance(REFIID riid, _Outptr_ void **ppvObj, size_t candStrReserveSize)
{
if (ppvObj == nullptr)
{
return E_INVALIDARG;
}
*ppvObj = nullptr;
*ppvObj = new (std::nothrow) CTfCandidateList(candStrReserveSize);
if (*ppvObj == nullptr)
{
return E_OUTOFMEMORY;
}
return ((CTfCandidateList*)(*ppvObj))->QueryInterface(riid, ppvObj);
}
CTfCandidateList::CTfCandidateList(size_t candStrReserveSize)
{
_refCount = 0;
if (0 < candStrReserveSize)
{
_tfCandStrList.reserve(candStrReserveSize);
}
}
CTfCandidateList::~CTfCandidateList()
{
}
STDMETHODIMP CTfCandidateList::QueryInterface(REFIID riid, _Outptr_ void **ppvObj)
{
if (ppvObj == nullptr)
{
return E_POINTER;
}
*ppvObj = nullptr;
if (IsEqualIID(riid, IID_IUnknown))
{
*ppvObj = (ITfCandidateList*)this;
}
else if (IsEqualIID(riid, IID_ITfCandidateList))
{
*ppvObj = (ITfCandidateList*)this;
}
if (*ppvObj == nullptr)
{
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
STDMETHODIMP_(ULONG) CTfCandidateList::AddRef()
{
return (ULONG)InterlockedIncrement((LONG*)&_refCount);
}
STDMETHODIMP_(ULONG) CTfCandidateList::Release()
{
ULONG cRefT = (ULONG)InterlockedDecrement((LONG*)&_refCount);
if (0 < cRefT)
{
return cRefT;
}
delete this;
return 0;
}
STDMETHODIMP CTfCandidateList::EnumCandidates(_Outptr_ IEnumTfCandidates **ppEnum)
{
return CEnumTfCandidates::CreateInstance(IID_IEnumTfCandidates, (void**)ppEnum, _tfCandStrList);
}
STDMETHODIMP CTfCandidateList::GetCandidate(ULONG nIndex, _Outptr_result_maybenull_ ITfCandidateString **ppCandStr)
{
if (ppCandStr == nullptr)
{
return E_POINTER;
}
*ppCandStr = nullptr;
ULONG sizeCandStr = (ULONG)_tfCandStrList.Count();
if (sizeCandStr <= nIndex)
{
return E_FAIL;
}
for (UINT i = 0; i < _tfCandStrList.Count(); i++)
{
ITfCandidateString** ppCandStrCur = _tfCandStrList.GetAt(i);
ULONG indexCur = 0;
if ((nullptr != ppCandStrCur) && (SUCCEEDED((*ppCandStrCur)->GetIndex(&indexCur))))
{
if (nIndex == indexCur)
{
BSTR bstr;
CTfCandidateString* pTipCandidateStrCur = (CTfCandidateString*)(*ppCandStrCur);
pTipCandidateStrCur->GetString(&bstr);
CTfCandidateString::CreateInstance(IID_ITfCandidateString, (void**)ppCandStr);
if (nullptr != (*ppCandStr))
{
CTfCandidateString* pTipCandidateStr = (CTfCandidateString*)(*ppCandStr);
pTipCandidateStr->SetString((LPCWSTR)bstr, SysStringLen(bstr));
}
SysFreeString(bstr);
break;
}
}
}
return S_OK;
}
STDMETHODIMP CTfCandidateList::GetCandidateNum(_Out_ ULONG *pnCnt)
{
if (pnCnt == nullptr)
{
return E_POINTER;
}
*pnCnt = (ULONG)(_tfCandStrList.Count());
return S_OK;
}
STDMETHODIMP CTfCandidateList::SetResult(ULONG /*nIndex*/, TfCandidateResult /*imcr*/)
{
return E_NOTIMPL;
}
STDMETHODIMP CTfCandidateList::SetCandidate(_In_ ITfCandidateString **ppCandStr)
{
if (ppCandStr == nullptr)
{
return E_POINTER;
}
ITfCandidateString** ppCandLast = _tfCandStrList.Append();
if (ppCandLast)
{
*ppCandLast = *ppCandStr;
}
return S_OK;
}
| 23.394595 | 115 | 0.639325 | millimoji |
28bd3b133d3139d6f17fe1121b9bc6f7ee02b370 | 4,768 | cpp | C++ | daemon/worktipsnetctl.cpp | Ghost-ai-cpu/lokinet | 2f2074d1069b39d0e455bcbf12ea53304a6a76a1 | [
"Zlib"
] | null | null | null | daemon/worktipsnetctl.cpp | Ghost-ai-cpu/lokinet | 2f2074d1069b39d0e455bcbf12ea53304a6a76a1 | [
"Zlib"
] | null | null | null | daemon/worktipsnetctl.cpp | Ghost-ai-cpu/lokinet | 2f2074d1069b39d0e455bcbf12ea53304a6a76a1 | [
"Zlib"
] | null | null | null | #include <config/config.hpp>
#include <router_contact.hpp>
#include <util/logging/logger.hpp>
#include <util/logging/ostream_logger.hpp>
#include <cxxopts.hpp>
#include <string>
#include <vector>
#ifdef WITH_CURL
#include <curl/curl.h>
#endif
namespace
{
bool
dumpRc(const std::vector< std::string >& files)
{
nlohmann::json result;
for(const auto& file : files)
{
llarp::RouterContact rc;
const bool ret = rc.Read(file.c_str());
if(ret)
{
result[file] = rc.ToJson();
}
else
{
std::cerr << "file = " << file << " was not a valid rc file\n";
}
}
std::cout << result << "\n";
return true;
}
#ifdef WITH_CURL
size_t
curlCallback(void* contents, size_t size, size_t nmemb, void* userp) noexcept
{
auto* str = static_cast< std::string* >(userp);
size_t realsize = size * nmemb;
char* asChar = static_cast< char* >(contents);
std::copy(asChar, asChar + realsize, std::back_inserter(*str));
return realsize;
}
bool
executeJsonRpc(const std::string& command, const std::string& configFile)
{
// Do init (on windows this will do socket initialisation)
curl_global_init(CURL_GLOBAL_ALL);
llarp::Config config;
if(!config.Load(configFile.c_str()))
{
llarp::LogError("Failed to load from config file: ", configFile);
return false;
}
if(!config.api.enableRPCServer())
{
llarp::LogError("Config does not have RPC enabled");
return false;
}
std::string address = config.api.rpcBindAddr() + "/jsonrpc";
const nlohmann::json request{{"method", command},
{"params", nlohmann::json::object()},
{"id", "foo"}};
const std::string requestStr = request.dump();
std::unique_ptr< curl_slist, void (*)(curl_slist*) > chunk(
curl_slist_append(nullptr, "content-type: application/json"),
&curl_slist_free_all);
std::unique_ptr< CURL, void (*)(CURL*) > curl(curl_easy_init(),
&curl_easy_cleanup);
curl_easy_setopt(curl.get(), CURLOPT_URL, address.c_str());
curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, requestStr.c_str());
curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDSIZE, requestStr.size());
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, chunk.get());
std::string result;
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, curlCallback);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &result);
auto res = curl_easy_perform(curl.get());
if(res != CURLE_OK)
{
llarp::LogError("Failed to curl endpoint, ", curl_easy_strerror(res));
return false;
}
std::cout << result << "\n";
return true;
}
#endif
} // namespace
int
main(int argc, char* argv[])
{
cxxopts::Options options("worktipsnetctl",
"WorktipsNET is a free, open source, private, "
"decentralized, \"market based sybil resistant\" "
"and IP based onion routing network");
options.add_options()("v,verbose", "Verbose", cxxopts::value< bool >())(
"h,help", "help", cxxopts::value< bool >())(
"c,config", "config file",
cxxopts::value< std::string >()->default_value(
llarp::GetDefaultConfigPath().string()))
#ifdef WITH_CURL
("j,jsonrpc", "hit json rpc endpoint", cxxopts::value< std::string >())
#endif
("dump", "dump rc file",
cxxopts::value< std::vector< std::string > >(), "FILE");
try
{
const auto result = options.parse(argc, argv);
if(result.count("verbose") > 0)
{
SetLogLevel(llarp::eLogDebug);
llarp::LogContext::Instance().logStream =
std::make_unique< llarp::OStreamLogStream >(true, std::cerr);
llarp::LogDebug("debug logging activated");
}
else
{
SetLogLevel(llarp::eLogError);
llarp::LogContext::Instance().logStream =
std::make_unique< llarp::OStreamLogStream >(true, std::cerr);
}
if(result.count("help") > 0)
{
std::cout << options.help() << std::endl;
return 0;
}
if(result.count("dump") > 0)
{
if(!dumpRc(result["dump"].as< std::vector< std::string > >()))
{
return 1;
}
}
#ifdef WITH_CURL
if(result.count("jsonrpc") > 0)
{
if(!executeJsonRpc(result["jsonrpc"].as< std::string >(),
result["config"].as< std::string >()))
{
return 1;
}
}
#endif
}
catch(const cxxopts::OptionParseException& ex)
{
std::cerr << ex.what() << std::endl;
std::cout << options.help() << std::endl;
return 1;
}
return 0;
}
| 26.488889 | 79 | 0.5862 | Ghost-ai-cpu |
28be698df0f1a2f04af20506bc2572ac38c20b1d | 20,356 | cc | C++ | java/src/main/c++/jni_spark_vw.cc | thmavri/vowpal_wabbit | 6a5f1f3b790cd37530fae4ec436f5c76683d5b27 | [
"BSD-3-Clause"
] | null | null | null | java/src/main/c++/jni_spark_vw.cc | thmavri/vowpal_wabbit | 6a5f1f3b790cd37530fae4ec436f5c76683d5b27 | [
"BSD-3-Clause"
] | null | null | null | java/src/main/c++/jni_spark_vw.cc | thmavri/vowpal_wabbit | 6a5f1f3b790cd37530fae4ec436f5c76683d5b27 | [
"BSD-3-Clause"
] | null | null | null | #include "jni_spark_vw.h"
#include "vw_exception.h"
#include "best_constant.h"
#include "util.h"
#include "options_serializer_boost_po.h"
#include "learner.h"
#include "simple_label_parser.h"
#include <algorithm>
#include <exception>
#include "shared_data.h"
jobject getJavaPrediction(JNIEnv* env, vw* all, example* ex);
// Guards
StringGuard::StringGuard(JNIEnv* env, jstring source) : _env(env), _source(source), _cstr(nullptr)
{
_cstr = _env->GetStringUTFChars(source, 0);
}
StringGuard::~StringGuard()
{
if (_cstr)
{
_env->ReleaseStringUTFChars(_source, _cstr);
_env->DeleteLocalRef(_source);
}
}
const char* StringGuard::c_str() { return _cstr; }
CriticalArrayGuard::CriticalArrayGuard(JNIEnv* env, jarray arr) : _env(env), _arr(arr), _arr0(nullptr)
{
_arr0 = env->GetPrimitiveArrayCritical(arr, nullptr);
}
CriticalArrayGuard::~CriticalArrayGuard()
{
if (_arr0)
{
_env->ReleasePrimitiveArrayCritical(_arr, _arr0, JNI_ABORT);
}
}
void* CriticalArrayGuard::data() { return _arr0; }
// VW
JNIEXPORT jlong JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_initialize(JNIEnv* env, jclass, jstring args)
{
StringGuard g_args(env, args);
try
{
return reinterpret_cast<jlong>(VW::initialize(g_args.c_str()));
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
return 0;
}
}
JNIEXPORT jlong JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_initializeFromModel(
JNIEnv* env, jclass, jstring args, jbyteArray model)
{
StringGuard g_args(env, args);
CriticalArrayGuard modelGuard(env, model);
try
{
int size = env->GetArrayLength(model);
auto* model0 = reinterpret_cast<const char*>(modelGuard.data());
io_buf buffer;
buffer.add_file(VW::io::create_buffer_view(model0, size));
return reinterpret_cast<jlong>(VW::initialize(g_args.c_str(), &buffer));
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
return 0;
}
}
void populateMultiEx(JNIEnv* env, jobjectArray examples, vw& all, multi_ex& ex_coll)
{
bool fieldIdInitialized = false;
int length = env->GetArrayLength(examples);
if (length > 0)
{
jobject jex = env->GetObjectArrayElement(examples, 0);
jclass cls = env->GetObjectClass(jex);
jfieldID fieldId = env->GetFieldID(cls, "nativePointer", "J");
for (int i = 0; i < length; i++)
{
jex = env->GetObjectArrayElement(examples, i);
// JavaObject VowpalWabbitExampleWrapper -> example*
auto exWrapper = (VowpalWabbitExampleWrapper*)get_native_pointer(env, jex);
VW::setup_example(all, exWrapper->_example);
ex_coll.push_back(exWrapper->_example);
}
}
}
JNIEXPORT jobject JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_learn(
JNIEnv* env, jobject vwObj, jobjectArray examples)
{
auto* all = reinterpret_cast<vw*>(get_native_pointer(env, vwObj));
multi_ex ex_coll;
try
{
populateMultiEx(env, examples, *all, ex_coll);
all->learn(ex_coll);
// as this is not a ring-based example it is not freed
as_multiline(all->l)->finish_example(*all, ex_coll);
// prediction is in the first example
return getJavaPrediction(env, all, ex_coll[0]);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
return nullptr;
}
}
JNIEXPORT jobject JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_predict(
JNIEnv* env, jobject vwObj, jobjectArray examples)
{
auto* all = reinterpret_cast<vw*>(get_native_pointer(env, vwObj));
multi_ex ex_coll;
try
{
populateMultiEx(env, examples, *all, ex_coll);
all->predict(ex_coll);
// as this is not a ring-based example it is not freed
as_multiline(all->l)->finish_example(*all, ex_coll);
// prediction is in the first example
return getJavaPrediction(env, all, ex_coll[0]);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
return nullptr;
}
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_performRemainingPasses(JNIEnv* env, jobject vwObj)
{
auto* all = reinterpret_cast<vw*>(get_native_pointer(env, vwObj));
try
{
if (all->numpasses > 1)
{
all->do_reset_source = true;
VW::start_parser(*all);
VW::LEARNER::generic_driver(*all);
VW::end_parser(*all);
}
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT jbyteArray JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_getModel(JNIEnv* env, jobject vwObj)
{
auto* all = reinterpret_cast<vw*>(get_native_pointer(env, vwObj));
try
{ // save in stl::vector
auto model_buffer = std::make_shared<std::vector<char>>();
io_buf buffer;
buffer.add_file(VW::io::create_vector_writer(model_buffer));
VW::save_predictor(*all, buffer);
// copy to Java
jbyteArray ret = env->NewByteArray(model_buffer->size());
CHECK_JNI_EXCEPTION(nullptr);
env->SetByteArrayRegion(ret, 0, model_buffer->size(), (const jbyte*)&model_buffer->data()[0]);
CHECK_JNI_EXCEPTION(nullptr);
return ret;
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
return nullptr;
}
}
JNIEXPORT jobject JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_getArguments(JNIEnv* env, jobject vwObj)
{
auto* all = reinterpret_cast<vw*>(get_native_pointer(env, vwObj));
// serialize the command line
VW::config::options_serializer_boost_po serializer;
for (auto const& option : all->options->get_all_options())
{
if (all->options->was_supplied(option->m_name))
{
serializer.add(*option);
}
}
// move it to Java
// Note: don't keep serializer.str().c_str() around in some variable. it get's deleted after str() is de-allocated
jstring args = env->NewStringUTF(serializer.str().c_str());
CHECK_JNI_EXCEPTION(nullptr);
jclass clazz = env->FindClass("org/vowpalwabbit/spark/VowpalWabbitArguments");
CHECK_JNI_EXCEPTION(nullptr);
jmethodID ctor = env->GetMethodID(clazz, "<init>", "(IILjava/lang/String;DD)V");
CHECK_JNI_EXCEPTION(nullptr);
return env->NewObject(clazz, ctor, all->num_bits, all->hash_seed, args, all->eta, all->power_t);
}
JNIEXPORT jobject JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_getPerformanceStatistics(
JNIEnv* env, jobject vwObj)
{
auto* all = reinterpret_cast<vw*>(get_native_pointer(env, vwObj));
long numberOfExamplesPerPass;
double weightedExampleSum;
double weightedLabelSum;
double averageLoss;
float bestConstant;
float bestConstantLoss;
long totalNumberOfFeatures;
if (all->current_pass == 0)
numberOfExamplesPerPass = all->sd->example_number;
else
numberOfExamplesPerPass = all->sd->example_number / all->current_pass;
weightedExampleSum = all->sd->weighted_examples();
weightedLabelSum = all->sd->weighted_labels;
if (all->holdout_set_off)
if (all->sd->weighted_labeled_examples > 0)
averageLoss = all->sd->sum_loss / all->sd->weighted_labeled_examples;
else
averageLoss = 0; // TODO should report NaN, but not clear how to do in platform independent manner
else if ((all->sd->holdout_best_loss == FLT_MAX) || (all->sd->holdout_best_loss == FLT_MAX * 0.5))
averageLoss = 0; // TODO should report NaN, but not clear how to do in platform independent manner
else
averageLoss = all->sd->holdout_best_loss;
get_best_constant(all->loss.get(), all->sd, bestConstant, bestConstantLoss);
totalNumberOfFeatures = all->sd->total_features;
jclass clazz = env->FindClass("org/vowpalwabbit/spark/VowpalWabbitPerformanceStatistics");
CHECK_JNI_EXCEPTION(nullptr);
jmethodID ctor = env->GetMethodID(clazz, "<init>", "(JDDDFFJ)V");
CHECK_JNI_EXCEPTION(nullptr);
return env->NewObject(clazz, ctor, numberOfExamplesPerPass, weightedExampleSum, weightedLabelSum, averageLoss,
bestConstant, bestConstantLoss, totalNumberOfFeatures);
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_endPass(JNIEnv* env, jobject vwObj)
{
auto* all = reinterpret_cast<vw*>(get_native_pointer(env, vwObj));
try
{
// note: this code duplication seems bound for trouble
// from parse_dispatch_loop.h:26
// from learner.cc:41
reset_source(*all, all->num_bits);
all->do_reset_source = false;
all->passes_complete++;
all->current_pass++;
all->l->end_pass();
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_finish(JNIEnv* env, jobject vwObj)
{
auto* all = reinterpret_cast<vw*>(get_native_pointer(env, vwObj));
try
{
VW::sync_stats(*all);
VW::finish(*all);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT jint JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitNative_hash(
JNIEnv* env, jclass, jbyteArray data, jint offset, jint len, jint seed)
{
CriticalArrayGuard dataGuard(env, data);
const char* values0 = (const char*)dataGuard.data();
return (jint)uniform_hash(values0 + offset, len, seed);
}
// VW Example
#define INIT_VARS \
auto exWrapper = reinterpret_cast<VowpalWabbitExampleWrapper*>(get_native_pointer(env, exampleObj)); \
vw* all = exWrapper->_all; \
example* ex = exWrapper->_example;
JNIEXPORT jlong JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_initialize(
JNIEnv* env, jclass, jlong vwPtr, jboolean isEmpty)
{
auto* all = reinterpret_cast<vw*>(vwPtr);
try
{
example* ex = VW::alloc_examples(1);
ex->interactions = &all->interactions;
ex->extent_interactions = &all->extent_interactions;
if (isEmpty)
{
char empty = '\0';
VW::read_line(*all, ex, &empty);
}
else
all->example_parser->lbl_parser.default_label(&ex->l);
return reinterpret_cast<jlong>(new VowpalWabbitExampleWrapper(all, ex));
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
return 0;
}
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_finish(JNIEnv* env, jobject exampleObj)
{
INIT_VARS
try
{
VW::dealloc_examples(ex, 1);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_clear(JNIEnv* env, jobject exampleObj)
{
INIT_VARS
try
{
VW::empty_example(*all, *ex);
all->example_parser->lbl_parser.default_label(&ex->l);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
void addNamespaceIfNotExists(vw* all, example* ex, char ns)
{
if (std::find(ex->indices.begin(), ex->indices.end(), ns) == ex->indices.end())
{
ex->indices.push_back(ns);
}
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_addToNamespaceDense(
JNIEnv* env, jobject exampleObj, jchar ns, jint weight_index_base, jdoubleArray values)
{
INIT_VARS
try
{
addNamespaceIfNotExists(all, ex, ns);
auto features = ex->feature_space.data() + ns;
CriticalArrayGuard valuesGuard(env, values);
double* values0 = (double*)valuesGuard.data();
int size = env->GetArrayLength(values);
int mask = (1 << all->num_bits) - 1;
// pre-allocate
features->values.reserve(features->values.capacity() + size);
features->indicies.reserve(features->indicies.capacity() + size);
double* values_itr = values0;
double* values_end = values0 + size;
for (; values_itr != values_end; ++values_itr, ++weight_index_base)
{
float x = *values_itr;
if (x != 0)
{
features->values.push_back_unchecked(x);
features->indicies.push_back_unchecked(weight_index_base & mask);
}
}
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_addToNamespaceSparse(
JNIEnv* env, jobject exampleObj, jchar ns, jintArray indices, jdoubleArray values)
{
INIT_VARS
try
{
addNamespaceIfNotExists(all, ex, ns);
auto features = ex->feature_space.data() + ns;
CriticalArrayGuard indicesGuard(env, indices);
int* indices0 = (int*)indicesGuard.data();
CriticalArrayGuard valuesGuard(env, values);
double* values0 = (double*)valuesGuard.data();
int size = env->GetArrayLength(indices);
int mask = (1 << all->num_bits) - 1;
// pre-allocate
features->values.reserve(features->values.capacity() + size);
features->indicies.reserve(features->indicies.capacity() + size);
int* indices_itr = indices0;
int* indices_end = indices0 + size;
double* values_itr = values0;
for (; indices_itr != indices_end; ++indices_itr, ++values_itr)
{
float x = *values_itr;
if (x != 0)
{
features->values.push_back_unchecked(x);
features->indicies.push_back_unchecked(*indices_itr & mask);
}
}
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_setLabel(
JNIEnv* env, jobject exampleObj, jfloat weight, jfloat label)
{
INIT_VARS
try
{
label_data* ld = &ex->l.simple;
ld->label = label;
auto& red_fts = ex->_reduction_features.template get<simple_label_reduction_features>();
red_fts.weight = weight;
count_label(all->sd, ld->label);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_setDefaultLabel(JNIEnv* env, jobject exampleObj)
{
INIT_VARS
try
{
all->example_parser->lbl_parser.default_label(&ex->l);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_setContextualBanditLabel(
JNIEnv* env, jobject exampleObj, jint action, jdouble cost, jdouble probability)
{
INIT_VARS
try
{
CB::label* ld = &ex->l.cb;
CB::cb_class f;
f.action = (uint32_t)action;
f.cost = (float)cost;
f.probability = (float)probability;
ld->costs.push_back(f);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_setSharedLabel(JNIEnv* env, jobject exampleObj)
{
INIT_VARS
try
{
// https://github.com/VowpalWabbit/vowpal_wabbit/blob/master/vowpalwabbit/parse_example_json.h#L437
CB::label* ld = &ex->l.cb;
CB::cb_class f;
f.partial_prediction = 0.;
f.action = (uint32_t)uniform_hash("shared", 6 /*length of string*/, 0);
f.cost = FLT_MAX;
f.probability = -1.f;
ld->costs.push_back(f);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT jobject JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_getPrediction(JNIEnv* env, jobject exampleObj)
{
INIT_VARS
return getJavaPrediction(env, all, ex);
}
JNIEXPORT void JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_learn(JNIEnv* env, jobject exampleObj)
{
INIT_VARS
try
{
VW::setup_example(*all, ex);
all->learn(*ex);
// as this is not a ring-based example it is not free'd
VW::LEARNER::as_singleline(all->l)->finish_example(*all, *ex);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
}
}
JNIEXPORT jobject JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_predict(JNIEnv* env, jobject exampleObj)
{
INIT_VARS
try
{
VW::setup_example(*all, ex);
all->predict(*ex);
// as this is not a ring-based example it is not free'd
VW::LEARNER::as_singleline(all->l)->finish_example(*all, *ex);
return getJavaPrediction(env, all, ex);
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
return nullptr;
}
}
JNIEXPORT jstring JNICALL Java_org_vowpalwabbit_spark_VowpalWabbitExample_toString(JNIEnv* env, jobject exampleObj)
{
INIT_VARS
try
{
std::ostringstream ostr;
ostr << "VowpalWabbitExample(label=";
auto lp = all->example_parser->lbl_parser;
if (!memcmp(&lp, &simple_label_parser, sizeof(lp)))
{
label_data* ld = &ex->l.simple;
const auto& red_fts = ex->_reduction_features.template get<simple_label_reduction_features>();
ostr << "simple " << ld->label << ":" << red_fts.weight << ":" << red_fts.initial;
}
else if (!memcmp(&lp, &CB::cb_label, sizeof(lp)))
{
CB::label* ld = &ex->l.cb;
ostr << "CB " << ld->costs.size();
if (ld->costs.size() > 0)
{
ostr << " ";
CB::cb_class& f = ld->costs[0];
// Ignore checking if f.action == uniform_hash("shared")
if (f.partial_prediction == 0 && f.cost == FLT_MAX && f.probability == -1.f)
ostr << "shared";
else
ostr << f.action << ":" << f.cost << ":" << f.probability;
}
}
else
{
ostr << "unsupported label";
}
ostr << ";";
for (auto& ns : ex->indices)
{
if (ns == 0)
ostr << "NULL:0,";
else
{
if ((ns >= 'a' && ns <= 'z') || (ns >= 'A' && ns <= 'Z'))
ostr << "'" << (char)ns << "':";
ostr << (int)ns << ",";
}
for (auto& f : ex->feature_space[ns])
{
auto idx = f.index();
ostr << (idx & all->weights.mask()) << "/" << idx << ":" << f.value() << ", ";
}
}
ostr << ")";
return env->NewStringUTF(ostr.str().c_str());
}
catch (...)
{
rethrow_cpp_exception_as_java_exception(env);
return nullptr;
}
}
// re-use prediction conversation methods
jobject multilabel_predictor(example* vec, JNIEnv* env);
jfloatArray scalars_predictor(example* vec, JNIEnv* env);
jobject action_scores_prediction(example* vec, JNIEnv* env);
jobject action_probs_prediction(example* vec, JNIEnv* env);
jobject getJavaPrediction(JNIEnv* env, vw* all, example* ex)
{
jclass predClass;
jmethodID ctr;
switch (all->l->pred_type)
{
case prediction_type_t::scalar:
predClass = env->FindClass("org/vowpalwabbit/spark/prediction/ScalarPrediction");
CHECK_JNI_EXCEPTION(nullptr);
ctr = env->GetMethodID(predClass, "<init>", "(FF)V");
CHECK_JNI_EXCEPTION(nullptr);
return env->NewObject(predClass, ctr, VW::get_prediction(ex), ex->confidence);
case prediction_type_t::prob:
predClass = env->FindClass("java/lang/Float");
CHECK_JNI_EXCEPTION(nullptr);
ctr = env->GetMethodID(predClass, "<init>", "(F)V");
CHECK_JNI_EXCEPTION(nullptr);
return env->NewObject(predClass, ctr, ex->pred.prob);
case prediction_type_t::multiclass:
predClass = env->FindClass("java/lang/Integer");
CHECK_JNI_EXCEPTION(nullptr);
ctr = env->GetMethodID(predClass, "<init>", "(I)V");
CHECK_JNI_EXCEPTION(nullptr);
return env->NewObject(predClass, ctr, ex->pred.multiclass);
case prediction_type_t::scalars:
return scalars_predictor(ex, env);
case prediction_type_t::action_probs:
return action_probs_prediction(ex, env);
case prediction_type_t::action_scores:
return action_scores_prediction(ex, env);
case prediction_type_t::multilabels:
return multilabel_predictor(ex, env);
default:
{
std::ostringstream ostr;
ostr << "prediction type '" << to_string(all->l->pred_type) << "' is not supported";
env->ThrowNew(env->FindClass("java/lang/UnsupportedOperationException"), ostr.str().c_str());
return nullptr;
}
}
}
| 27.620081 | 121 | 0.656956 | thmavri |
28bf32ff2ec315fe9b4786a33bfc0e9342656ed5 | 41,161 | cpp | C++ | source/idlib/math/Lcp.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | 2 | 2021-05-02T18:37:48.000Z | 2021-07-18T16:18:14.000Z | source/idlib/math/Lcp.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | source/idlib/math/Lcp.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | // Copyright (C) 2007 Id Software, Inc.
//
#include "../precompiled.h"
#pragma hdrstop
// static idCVar lcp_showFailures( "lcp_showFailures", "0", CVAR_SYSTEM | CVAR_BOOL, "show LCP solver failures" );
const float LCP_BOUND_EPSILON = 1e-5f;
const float LCP_ACCEL_EPSILON = 1e-5f;
const float LCP_DELTA_ACCEL_EPSILON = 1e-9f;
const float LCP_DELTA_FORCE_EPSILON = 1e-9f;
#define IGNORE_UNSATISFIABLE_VARIABLES
//===============================================================
// M
// idLCP_Square MrE
// E
//===============================================================
class idLCP_Square : public idLCP {
public:
virtual bool Solve( const idMatX &o_m, idVecX &o_x, const idVecX &o_b, const idVecX &o_lo, const idVecX &o_hi, const int *o_boxIndex );
private:
idMatX m; // original matrix
idVecX b; // right hand side
idVecX lo, hi; // low and high bounds
idVecX f, a; // force and acceleration
idVecX delta_f, delta_a; // delta force and delta acceleration
idMatX clamped; // LU factored sub matrix for clamped variables
idVecX diagonal; // reciprocal of diagonal of U of the LU factored sub matrix for clamped variables
int numUnbounded; // number of unbounded variables
int numClamped; // number of clamped variables
float ** rowPtrs; // pointers to the rows of m
int * boxIndex; // box index
int * side; // tells if a variable is at the low boundary = -1, high boundary = 1 or inbetween = 0
int * permuted; // index to keep track of the permutation
bool padded; // set to true if the rows of the initial matrix are 16 byte padded
private:
bool FactorClamped( void );
void SolveClamped( idVecX &x, const float *b );
void Swap( int i, int j );
void AddClamped( int r );
void RemoveClamped( int r );
void CalcForceDelta( int d, float dir );
void CalcAccelDelta( int d );
void ChangeForce( int d, float step );
void ChangeAccel( int d, float step );
void GetMaxStep( int d, float dir, float &maxStep, int &limit, int &limitSide ) const;
};
/*
============
idLCP_Square::FactorClamped
============
*/
bool idLCP_Square::FactorClamped( void ) {
for ( int i = 0; i < numClamped; i++ ) {
memcpy( clamped[i], rowPtrs[i], numClamped * sizeof( float ) );
}
return SIMDProcessor->MatX_LU_Factor( clamped, diagonal, numClamped );
}
/*
============
idLCP_Square::SolveClamped
============
*/
void idLCP_Square::SolveClamped( idVecX &x, const float *b ) {
int i, j;
float sum;
// solve L
for ( i = 0; i < numClamped; i++ ) {
sum = b[i];
for ( j = 0; j < i; j++ ) {
sum -= clamped[i][j] * x[j];
}
x[i] = sum;
}
// solve U
for ( i = numClamped - 1; i >= 0; i-- ) {
sum = x[i];
for ( j = i + 1; j < numClamped; j++ ) {
sum -= clamped[i][j] * x[j];
}
x[i] = sum * diagonal[i];
}
}
/*
============
idLCP_Square::Swap
============
*/
void idLCP_Square::Swap( int i, int j ) {
if ( i == j ) {
return;
}
idSwap( rowPtrs[i], rowPtrs[j] );
m.SwapColumns( i, j );
b.SwapElements( i, j );
lo.SwapElements( i, j );
hi.SwapElements( i, j );
a.SwapElements( i, j );
f.SwapElements( i, j );
if ( boxIndex ) {
idSwap( boxIndex[i], boxIndex[j] );
}
idSwap( side[i], side[j] );
idSwap( permuted[i], permuted[j] );
}
/*
============
idLCP_Square::AddClamped
============
*/
void idLCP_Square::AddClamped( int r ) {
int i, j;
float sum;
assert( r >= numClamped );
// add a row at the bottom and a column at the right of the factored
// matrix for the clamped variables
Swap( numClamped, r );
// add row to L
for ( i = 0; i < numClamped; i++ ) {
sum = rowPtrs[numClamped][i];
for ( j = 0; j < i; j++ ) {
sum -= clamped[numClamped][j] * clamped[j][i];
}
clamped[numClamped][i] = sum * diagonal[i];
}
// add column to U
for ( i = 0; i <= numClamped; i++ ) {
sum = rowPtrs[i][numClamped];
for ( j = 0; j < i; j++ ) {
sum -= clamped[i][j] * clamped[j][numClamped];
}
clamped[i][numClamped] = sum;
}
diagonal[numClamped] = 1.0f / clamped[numClamped][numClamped];
numClamped++;
}
/*
============
idLCP_Square::RemoveClamped
============
*/
void idLCP_Square::RemoveClamped( int r ) {
int i, j;
float *y0, *y1, *z0, *z1;
double diag, beta0, beta1, p0, p1, q0, q1, d;
assert( r < numClamped );
numClamped--;
// no need to swap and update the factored matrix when the last row and column are removed
if ( r == numClamped ) {
return;
}
y0 = (float *) _alloca16( numClamped * sizeof( float ) );
z0 = (float *) _alloca16( numClamped * sizeof( float ) );
y1 = (float *) _alloca16( numClamped * sizeof( float ) );
z1 = (float *) _alloca16( numClamped * sizeof( float ) );
// the row/column need to be subtracted from the factorization
for ( i = 0; i < numClamped; i++ ) {
y0[i] = -rowPtrs[i][r];
}
memset( y1, 0, numClamped * sizeof( float ) );
y1[r] = 1.0f;
memset( z0, 0, numClamped * sizeof( float ) );
z0[r] = 1.0f;
for ( i = 0; i < numClamped; i++ ) {
z1[i] = -rowPtrs[r][i];
}
// swap the to be removed row/column with the last row/column
Swap( r, numClamped );
// the swapped last row/column need to be added to the factorization
for ( i = 0; i < numClamped; i++ ) {
y0[i] += rowPtrs[i][r];
}
for ( i = 0; i < numClamped; i++ ) {
z1[i] += rowPtrs[r][i];
}
z1[r] = 0.0f;
// update the beginning of the to be updated row and column
for ( i = 0; i < r; i++ ) {
p0 = y0[i];
beta1 = z1[i] * diagonal[i];
clamped[i][r] += p0;
for ( j = i+1; j < numClamped; j++ ) {
z1[j] -= beta1 * clamped[i][j];
}
for ( j = i+1; j < numClamped; j++ ) {
y0[j] -= p0 * clamped[j][i];
}
clamped[r][i] += beta1;
}
// update the lower right corner starting at r,r
for ( i = r; i < numClamped; i++ ) {
diag = clamped[i][i];
p0 = y0[i];
p1 = z0[i];
diag += p0 * p1;
if ( diag == 0.0f ) {
idLib::common->Printf( "idLCP_Square::RemoveClamped: updating factorization failed\n" );
return;
}
beta0 = p1 / diag;
q0 = y1[i];
q1 = z1[i];
diag += q0 * q1;
if ( diag == 0.0f ) {
idLib::common->Printf( "idLCP_Square::RemoveClamped: updating factorization failed\n" );
return;
}
d = 1.0f / diag;
beta1 = q1 * d;
clamped[i][i] = diag;
diagonal[i] = d;
for ( j = i+1; j < numClamped; j++ ) {
d = clamped[i][j];
d += p0 * z0[j];
z0[j] -= beta0 * d;
d += q0 * z1[j];
z1[j] -= beta1 * d;
clamped[i][j] = d;
}
for ( j = i+1; j < numClamped; j++ ) {
d = clamped[j][i];
y0[j] -= p0 * d;
d += beta0 * y0[j];
y1[j] -= q0 * d;
d += beta1 * y1[j];
clamped[j][i] = d;
}
}
return;
}
/*
============
idLCP_Square::CalcForceDelta
modifies this->delta_f
============
*/
ID_INLINE void idLCP_Square::CalcForceDelta( int d, float dir ) {
int i;
float *ptr;
delta_f[d] = dir;
if ( numClamped == 0 ) {
return;
}
// get column d of matrix
ptr = (float *) _alloca16( numClamped * sizeof( float ) );
for ( i = 0; i < numClamped; i++ ) {
ptr[i] = rowPtrs[i][d];
}
// solve force delta
SolveClamped( delta_f, ptr );
// flip force delta based on direction
if ( dir > 0.0f ) {
ptr = delta_f.ToFloatPtr();
for ( i = 0; i < numClamped; i++ ) {
ptr[i] = - ptr[i];
}
}
}
/*
============
idLCP_Square::CalcAccelDelta
modifies this->delta_a and uses this->delta_f
============
*/
ID_INLINE void idLCP_Square::CalcAccelDelta( int d ) {
int j;
float dot;
// only the not clamped variables, including the current variable, can have a change in acceleration
for ( j = numClamped; j <= d; j++ ) {
// only the clamped variables and the current variable have a force delta unequal zero
SIMDProcessor->Dot( dot, rowPtrs[j], delta_f.ToFloatPtr(), numClamped );
delta_a[j] = dot + rowPtrs[j][d] * delta_f[d];
}
}
/*
============
idLCP_Square::ChangeForce
modifies this->f and uses this->delta_f
============
*/
ID_INLINE void idLCP_Square::ChangeForce( int d, float step ) {
// only the clamped variables and current variable have a force delta unequal zero
SIMDProcessor->MulAdd( f.ToFloatPtr(), step, delta_f.ToFloatPtr(), numClamped );
f[d] += step * delta_f[d];
}
/*
============
idLCP_Square::ChangeAccel
modifies this->a and uses this->delta_a
============
*/
ID_INLINE void idLCP_Square::ChangeAccel( int d, float step ) {
// only the not clamped variables, including the current variable, can have an acceleration unequal zero
SIMDProcessor->MulAdd( a.ToFloatPtr() + numClamped, step, delta_a.ToFloatPtr() + numClamped, d - numClamped + 1 );
}
/*
============
idLCP_Square::GetMaxStep
============
*/
void idLCP_Square::GetMaxStep( int d, float dir, float &maxStep, int &limit, int &limitSide ) const {
int i;
float s;
// default to a full step for the current variable
if ( idMath::Fabs( delta_a[d] ) > LCP_DELTA_ACCEL_EPSILON ) {
maxStep = -a[d] / delta_a[d];
} else {
maxStep = 0.0f;
}
limit = d;
limitSide = 0;
// test the current variable
if ( dir < 0.0f ) {
if ( lo[d] != -idMath::INFINITY ) {
s = ( lo[d] - f[d] ) / dir;
if ( s < maxStep ) {
maxStep = s;
limitSide = -1;
}
}
} else {
if ( hi[d] != idMath::INFINITY ) {
s = ( hi[d] - f[d] ) / dir;
if ( s < maxStep ) {
maxStep = s;
limitSide = 1;
}
}
}
// test the clamped bounded variables
for ( i = numUnbounded; i < numClamped; i++ ) {
if ( delta_f[i] < -LCP_DELTA_FORCE_EPSILON ) {
// if there is a low boundary
if ( lo[i] != -idMath::INFINITY ) {
s = ( lo[i] - f[i] ) / delta_f[i];
if ( s < maxStep ) {
maxStep = s;
limit = i;
limitSide = -1;
}
}
} else if ( delta_f[i] > LCP_DELTA_FORCE_EPSILON ) {
// if there is a high boundary
if ( hi[i] != idMath::INFINITY ) {
s = ( hi[i] - f[i] ) / delta_f[i];
if ( s < maxStep ) {
maxStep = s;
limit = i;
limitSide = 1;
}
}
}
}
// test the not clamped bounded variables
for ( i = numClamped; i < d; i++ ) {
if ( side[i] == -1 ) {
if ( delta_a[i] >= -LCP_DELTA_ACCEL_EPSILON ) {
continue;
}
} else if ( side[i] == 1 ) {
if ( delta_a[i] <= LCP_DELTA_ACCEL_EPSILON ) {
continue;
}
} else {
continue;
}
// ignore variables for which the force is not allowed to take any substantial value
if ( lo[i] >= -LCP_BOUND_EPSILON && hi[i] <= LCP_BOUND_EPSILON ) {
continue;
}
s = -a[i] / delta_a[i];
if ( s < maxStep ) {
maxStep = s;
limit = i;
limitSide = 0;
}
}
}
/*
============
idLCP_Square::Solve
============
*/
bool idLCP_Square::Solve( const idMatX &o_m, idVecX &o_x, const idVecX &o_b, const idVecX &o_lo, const idVecX &o_hi, const int *o_boxIndex ) {
int i, j, n, limit, limitSide, boxStartIndex;
float dir, maxStep, dot, s;
char *failed;
// true when the matrix rows are 16 byte padded
padded = ((o_m.GetNumRows()+3)&~3) == o_m.GetNumColumns();
assert( padded || o_m.GetNumRows() == o_m.GetNumColumns() );
assert( o_x.GetSize() == o_m.GetNumRows() );
assert( o_b.GetSize() == o_m.GetNumRows() );
assert( o_lo.GetSize() == o_m.GetNumRows() );
assert( o_hi.GetSize() == o_m.GetNumRows() );
// allocate memory for permuted input
f.SetData( o_m.GetNumRows(), VECX_ALLOCA( o_m.GetNumRows() ) );
a.SetData( o_b.GetSize(), VECX_ALLOCA( o_b.GetSize() ) );
b.SetData( o_b.GetSize(), VECX_ALLOCA( o_b.GetSize() ) );
lo.SetData( o_lo.GetSize(), VECX_ALLOCA( o_lo.GetSize() ) );
hi.SetData( o_hi.GetSize(), VECX_ALLOCA( o_hi.GetSize() ) );
if ( o_boxIndex ) {
boxIndex = (int *)_alloca16( o_x.GetSize() * sizeof( int ) );
memcpy( boxIndex, o_boxIndex, o_x.GetSize() * sizeof( int ) );
} else {
boxIndex = NULL;
}
// we override the const on o_m here but on exit the matrix is unchanged
m.SetData( o_m.GetNumRows(), o_m.GetNumColumns(), const_cast<float *>(o_m[0]) );
f.Zero();
a.Zero();
b = o_b;
lo = o_lo;
hi = o_hi;
// pointers to the rows of m
rowPtrs = (float **) _alloca16( m.GetNumRows() * sizeof( float * ) );
for ( i = 0; i < m.GetNumRows(); i++ ) {
rowPtrs[i] = m[i];
}
// tells if a variable is at the low boundary, high boundary or inbetween
side = (int *) _alloca16( m.GetNumRows() * sizeof( int ) );
// index to keep track of the permutation
permuted = (int *) _alloca16( m.GetNumRows() * sizeof( int ) );
for ( i = 0; i < m.GetNumRows(); i++ ) {
permuted[i] = i;
}
// permute input so all unbounded variables come first
numUnbounded = 0;
for ( i = 0; i < m.GetNumRows(); i++ ) {
if ( lo[i] == -idMath::INFINITY && hi[i] == idMath::INFINITY ) {
if ( numUnbounded != i ) {
Swap( numUnbounded, i );
}
numUnbounded++;
}
}
// permute input so all variables using the boxIndex come last
boxStartIndex = m.GetNumRows();
if ( boxIndex ) {
for ( i = m.GetNumRows() - 1; i >= numUnbounded; i-- ) {
if ( boxIndex[i] >= 0 && ( lo[i] != -idMath::INFINITY || hi[i] != idMath::INFINITY ) ) {
boxStartIndex--;
if ( boxStartIndex != i ) {
Swap( boxStartIndex, i );
}
}
}
}
// sub matrix for factorization
clamped.SetData( m.GetNumRows(), m.GetNumColumns(), MATX_ALLOCA( m.GetNumRows() * m.GetNumColumns() ) );
diagonal.SetData( m.GetNumRows(), VECX_ALLOCA( m.GetNumRows() ) );
// all unbounded variables are clamped
numClamped = numUnbounded;
// if there are unbounded variables
if ( numUnbounded ) {
// factor and solve for unbounded variables
if ( !FactorClamped() ) {
idLib::common->Printf( "idLCP_Square::Solve: unbounded factorization failed\n" );
return false;
}
SolveClamped( f, b.ToFloatPtr() );
// if there are no bounded variables we are done
if ( numUnbounded == m.GetNumRows() ) {
o_x = f; // the vector is not permuted
return true;
}
}
#ifdef IGNORE_UNSATISFIABLE_VARIABLES
int numIgnored = 0;
#endif
// allocate for delta force and delta acceleration
delta_f.SetData( m.GetNumRows(), VECX_ALLOCA( m.GetNumRows() ) );
delta_a.SetData( m.GetNumRows(), VECX_ALLOCA( m.GetNumRows() ) );
// solve for bounded variables
failed = NULL;
for ( i = numUnbounded; i < m.GetNumRows(); i++ ) {
// once we hit the box start index we can initialize the low and high boundaries of the variables using the box index
if ( i == boxStartIndex ) {
for ( j = 0; j < boxStartIndex; j++ ) {
o_x[permuted[j]] = f[j];
}
for ( j = boxStartIndex; j < m.GetNumRows(); j++ ) {
s = o_x[boxIndex[j]];
if ( lo[j] != -idMath::INFINITY ) {
lo[j] = - idMath::Fabs( lo[j] * s );
}
if ( hi[j] != idMath::INFINITY ) {
hi[j] = idMath::Fabs( hi[j] * s );
}
}
}
// calculate acceleration for current variable
SIMDProcessor->Dot( dot, rowPtrs[i], f.ToFloatPtr(), i );
a[i] = dot - b[i];
// if already at the low boundary
if ( lo[i] >= -LCP_BOUND_EPSILON && a[i] >= -LCP_ACCEL_EPSILON ) {
side[i] = -1;
continue;
}
// if already at the high boundary
if ( hi[i] <= LCP_BOUND_EPSILON && a[i] <= LCP_ACCEL_EPSILON ) {
side[i] = 1;
continue;
}
// if inside the clamped region
if ( idMath::Fabs( a[i] ) <= LCP_ACCEL_EPSILON ) {
side[i] = 0;
AddClamped( i );
continue;
}
// drive the current variable into a valid region
for ( n = 0; n < maxIterations; n++ ) {
// direction to move
if ( a[i] <= 0.0f ) {
dir = 1.0f;
} else {
dir = -1.0f;
}
// calculate force delta
CalcForceDelta( i, dir );
// calculate acceleration delta: delta_a = m * delta_f;
CalcAccelDelta( i );
// maximum step we can take
GetMaxStep( i, dir, maxStep, limit, limitSide );
if ( maxStep <= 0.0f ) {
#ifdef IGNORE_UNSATISFIABLE_VARIABLES
// ignore the current variable completely
lo[i] = hi[i] = 0.0f;
f[i] = 0.0f;
side[i] = -1;
numIgnored++;
#else
failed = va( "invalid step size %.4f", maxStep );
#endif
break;
}
// change force
ChangeForce( i, maxStep );
// change acceleration
ChangeAccel( i, maxStep );
// clamp/unclamp the variable that limited this step
side[limit] = limitSide;
switch( limitSide ) {
case 0: {
a[limit] = 0.0f;
AddClamped( limit );
break;
}
case -1: {
f[limit] = lo[limit];
if ( limit != i ) {
RemoveClamped( limit );
}
break;
}
case 1: {
f[limit] = hi[limit];
if ( limit != i ) {
RemoveClamped( limit );
}
break;
}
}
// if the current variable limited the step we can continue with the next variable
if ( limit == i ) {
break;
}
}
if ( n >= maxIterations ) {
failed = va( "max iterations %d", maxIterations );
break;
}
if ( failed ) {
break;
}
}
#ifdef IGNORE_UNSATISFIABLE_VARIABLES
if ( numIgnored ) {
/* if ( lcp_showFailures.GetBool() ) {
idLib::common->Printf( "idLCP_Symmetric::Solve: %d of %d bounded variables ignored\n", numIgnored, m.GetNumRows() - numUnbounded );
}*/
}
#endif
// if failed clear remaining forces
if ( failed ) {
/* if ( lcp_showFailures.GetBool() ) {
idLib::common->Printf( "idLCP_Square::Solve: %s (%d of %d bounded variables ignored)\n", failed, m.GetNumRows() - i, m.GetNumRows() - numUnbounded );
}*/
for ( j = i; j < m.GetNumRows(); j++ ) {
f[j] = 0.0f;
}
}
#if defined(_DEBUG) && 0
if ( !failed ) {
// test whether or not the solution satisfies the complementarity conditions
for ( i = 0; i < m.GetNumRows(); i++ ) {
a[i] = -b[i];
for ( j = 0; j < m.GetNumRows(); j++ ) {
a[i] += rowPtrs[i][j] * f[j];
}
if ( f[i] == lo[i] ) {
if ( lo[i] != hi[i] && a[i] < -LCP_ACCEL_EPSILON ) {
int bah1 = 1;
}
} else if ( f[i] == hi[i] ) {
if ( lo[i] != hi[i] && a[i] > LCP_ACCEL_EPSILON ) {
int bah2 = 1;
}
} else if ( f[i] < lo[i] || f[i] > hi[i] || idMath::Fabs( a[i] ) > 1.0f ) {
int bah3 = 1;
}
}
}
#endif
// unpermute result
for ( i = 0; i < f.GetSize(); i++ ) {
o_x[permuted[i]] = f[i];
}
// unpermute original matrix
for ( i = 0; i < m.GetNumRows(); i++ ) {
for ( j = 0; j < m.GetNumRows(); j++ ) {
if ( permuted[j] == i ) {
break;
}
}
if ( i != j ) {
m.SwapColumns( i, j );
idSwap( permuted[i], permuted[j] );
}
}
return true;
}
//===============================================================
// M
// idLCP_Symmetric MrE
// E
//===============================================================
class idLCP_Symmetric : public idLCP {
public:
virtual bool Solve( const idMatX &o_m, idVecX &o_x, const idVecX &o_b, const idVecX &o_lo, const idVecX &o_hi, const int *o_boxIndex );
private:
idMatX m; // original matrix
idVecX b; // right hand side
idVecX lo, hi; // low and high bounds
idVecX f, a; // force and acceleration
idVecX delta_f, delta_a; // delta force and delta acceleration
idMatX clamped; // LDLt factored sub matrix for clamped variables
idVecX diagonal; // reciprocal of diagonal of LDLt factored sub matrix for clamped variables
idVecX solveCache1; // intermediate result cached in SolveClamped
idVecX solveCache2; // "
int numUnbounded; // number of unbounded variables
int numClamped; // number of clamped variables
int clampedChangeStart; // lowest row/column changed in the clamped matrix during an iteration
float ** rowPtrs; // pointers to the rows of m
int * boxIndex; // box index
int * side; // tells if a variable is at the low boundary = -1, high boundary = 1 or inbetween = 0
int * permuted; // index to keep track of the permutation
bool padded; // set to true if the rows of the initial matrix are 16 byte padded
private:
bool FactorClamped( void );
void SolveClamped( idVecX &x, const float *b );
void Swap( int i, int j );
void AddClamped( int r, bool useSolveCache );
void RemoveClamped( int r );
void CalcForceDelta( int d, float dir );
void CalcAccelDelta( int d );
void ChangeForce( int d, float step );
void ChangeAccel( int d, float step );
void GetMaxStep( int d, float dir, float &maxStep, int &limit, int &limitSide ) const;
};
/*
============
idLCP_Symmetric::FactorClamped
============
*/
bool idLCP_Symmetric::FactorClamped( void ) {
clampedChangeStart = 0;
for ( int i = 0; i < numClamped; i++ ) {
memcpy( clamped[i], rowPtrs[i], numClamped * sizeof( float ) );
}
return SIMDProcessor->MatX_LDLT_Factor( clamped, diagonal, numClamped );
}
/*
============
idLCP_Symmetric::SolveClamped
============
*/
void idLCP_Symmetric::SolveClamped( idVecX &x, const float *b ) {
// solve L
SIMDProcessor->MatX_LowerTriangularSolve( clamped, solveCache1.ToFloatPtr(), b, numClamped, clampedChangeStart );
// solve D
SIMDProcessor->Mul( solveCache2.ToFloatPtr(), solveCache1.ToFloatPtr(), diagonal.ToFloatPtr(), numClamped );
// solve Lt
SIMDProcessor->MatX_LowerTriangularSolveTranspose( clamped, x.ToFloatPtr(), solveCache2.ToFloatPtr(), numClamped );
clampedChangeStart = numClamped;
}
/*
============
idLCP_Symmetric::Swap
============
*/
void idLCP_Symmetric::Swap( int i, int j ) {
if ( i == j ) {
return;
}
idSwap( rowPtrs[i], rowPtrs[j] );
m.SwapColumns( i, j );
b.SwapElements( i, j );
lo.SwapElements( i, j );
hi.SwapElements( i, j );
a.SwapElements( i, j );
f.SwapElements( i, j );
if ( boxIndex ) {
idSwap( boxIndex[i], boxIndex[j] );
}
idSwap( side[i], side[j] );
idSwap( permuted[i], permuted[j] );
}
/*
============
idLCP_Symmetric::AddClamped
============
*/
void idLCP_Symmetric::AddClamped( int r, bool useSolveCache ) {
float d, dot;
assert( r >= numClamped );
if ( numClamped < clampedChangeStart ) {
clampedChangeStart = numClamped;
}
// add a row at the bottom and a column at the right of the factored
// matrix for the clamped variables
Swap( numClamped, r );
// solve for v in L * v = rowPtr[numClamped]
if ( useSolveCache ) {
// the lower triangular solve was cached in SolveClamped called by CalcForceDelta
memcpy( clamped[numClamped], solveCache2.ToFloatPtr(), numClamped * sizeof( float ) );
// calculate row dot product
SIMDProcessor->Dot( dot, solveCache2.ToFloatPtr(), solveCache1.ToFloatPtr(), numClamped );
} else {
float *v = (float *) _alloca16( numClamped * sizeof( float ) );
SIMDProcessor->MatX_LowerTriangularSolve( clamped, v, rowPtrs[numClamped], numClamped );
// add bottom row to L
SIMDProcessor->Mul( clamped[numClamped], v, diagonal.ToFloatPtr(), numClamped );
// calculate row dot product
SIMDProcessor->Dot( dot, clamped[numClamped], v, numClamped );
}
// update diagonal[numClamped]
d = rowPtrs[numClamped][numClamped] - dot;
if ( d == 0.0f ) {
idLib::common->Printf( "idLCP_Symmetric::AddClamped: updating factorization failed\n" );
numClamped++;
return;
}
clamped[numClamped][numClamped] = d;
diagonal[numClamped] = 1.0f / d;
numClamped++;
}
/*
============
idLCP_Symmetric::RemoveClamped
============
*/
void idLCP_Symmetric::RemoveClamped( int r ) {
int i, j, n;
float *addSub, *original, *v, *ptr, *v1, *v2, dot;
double sum, diag, newDiag, invNewDiag, p1, p2, alpha1, alpha2, beta1, beta2;
assert( r < numClamped );
if ( r < clampedChangeStart ) {
clampedChangeStart = r;
}
numClamped--;
// no need to swap and update the factored matrix when the last row and column are removed
if ( r == numClamped ) {
return;
}
// swap the to be removed row/column with the last row/column
Swap( r, numClamped );
// update the factored matrix
addSub = (float *) _alloca16( numClamped * sizeof( float ) );
if ( r == 0 ) {
if ( numClamped == 1 ) {
diag = rowPtrs[0][0];
if ( diag == 0.0f ) {
idLib::common->Printf( "idLCP_Symmetric::RemoveClamped: updating factorization failed\n" );
return;
}
clamped[0][0] = diag;
diagonal[0] = 1.0f / diag;
return;
}
// calculate the row/column to be added to the lower right sub matrix starting at (r, r)
original = rowPtrs[numClamped];
ptr = rowPtrs[r];
addSub[0] = ptr[0] - original[numClamped];
for ( i = 1; i < numClamped; i++ ) {
addSub[i] = ptr[i] - original[i];
}
} else {
v = (float *) _alloca16( numClamped * sizeof( float ) );
// solve for v in L * v = rowPtr[r]
SIMDProcessor->MatX_LowerTriangularSolve( clamped, v, rowPtrs[r], r );
// update removed row
SIMDProcessor->Mul( clamped[r], v, diagonal.ToFloatPtr(), r );
// if the last row/column of the matrix is updated
if ( r == numClamped - 1 ) {
// only calculate new diagonal
SIMDProcessor->Dot( dot, clamped[r], v, r );
diag = rowPtrs[r][r] - dot;
if ( diag == 0.0f ) {
idLib::common->Printf( "idLCP_Symmetric::RemoveClamped: updating factorization failed\n" );
return;
}
clamped[r][r] = diag;
diagonal[r] = 1.0f / diag;
return;
}
// calculate the row/column to be added to the lower right sub matrix starting at (r, r)
for ( i = 0; i < r; i++ ) {
v[i] = clamped[r][i] * clamped[i][i];
}
for ( i = r; i < numClamped; i++ ) {
if ( i == r ) {
sum = clamped[r][r];
} else {
sum = clamped[r][r] * clamped[i][r];
}
ptr = clamped[i];
for ( j = 0; j < r; j++ ) {
sum += ptr[j] * v[j];
}
addSub[i] = rowPtrs[r][i] - sum;
}
}
// add row/column to the lower right sub matrix starting at (r, r)
v1 = (float *) _alloca16( numClamped * sizeof( float ) );
v2 = (float *) _alloca16( numClamped * sizeof( float ) );
diag = idMath::SQRT_1OVER2;
v1[r] = ( 0.5f * addSub[r] + 1.0f ) * diag;
v2[r] = ( 0.5f * addSub[r] - 1.0f ) * diag;
for ( i = r+1; i < numClamped; i++ ) {
v1[i] = v2[i] = addSub[i] * diag;
}
alpha1 = 1.0f;
alpha2 = -1.0f;
// simultaneous update/downdate of the sub matrix starting at (r, r)
n = clamped.GetNumColumns();
for ( i = r; i < numClamped; i++ ) {
diag = clamped[i][i];
p1 = v1[i];
newDiag = diag + alpha1 * p1 * p1;
if ( newDiag == 0.0f ) {
idLib::common->Printf( "idLCP_Symmetric::RemoveClamped: updating factorization failed\n" );
return;
}
alpha1 /= newDiag;
beta1 = p1 * alpha1;
alpha1 *= diag;
diag = newDiag;
p2 = v2[i];
newDiag = diag + alpha2 * p2 * p2;
if ( newDiag == 0.0f ) {
idLib::common->Printf( "idLCP_Symmetric::RemoveClamped: updating factorization failed\n" );
return;
}
clamped[i][i] = newDiag;
diagonal[i] = invNewDiag = 1.0f / newDiag;
alpha2 *= invNewDiag;
beta2 = p2 * alpha2;
alpha2 *= diag;
// update column below diagonal (i,i)
ptr = clamped.ToFloatPtr() + i;
for ( j = i+1; j < numClamped - 1; j += 2 ) {
float sum0 = ptr[(j+0)*n];
float sum1 = ptr[(j+1)*n];
v1[j+0] -= p1 * sum0;
v1[j+1] -= p1 * sum1;
sum0 += beta1 * v1[j+0];
sum1 += beta1 * v1[j+1];
v2[j+0] -= p2 * sum0;
v2[j+1] -= p2 * sum1;
sum0 += beta2 * v2[j+0];
sum1 += beta2 * v2[j+1];
ptr[(j+0)*n] = sum0;
ptr[(j+1)*n] = sum1;
}
for ( ; j < numClamped; j++ ) {
sum = ptr[j*n];
v1[j] -= p1 * sum;
sum += beta1 * v1[j];
v2[j] -= p2 * sum;
sum += beta2 * v2[j];
ptr[j*n] = sum;
}
}
}
/*
============
idLCP_Symmetric::CalcForceDelta
modifies this->delta_f
============
*/
ID_INLINE void idLCP_Symmetric::CalcForceDelta( int d, float dir ) {
int i;
float *ptr;
delta_f[d] = dir;
if ( numClamped == 0 ) {
return;
}
// solve force delta
SolveClamped( delta_f, rowPtrs[d] );
// flip force delta based on direction
if ( dir > 0.0f ) {
ptr = delta_f.ToFloatPtr();
for ( i = 0; i < numClamped; i++ ) {
ptr[i] = - ptr[i];
}
}
}
/*
============
idLCP_Symmetric::CalcAccelDelta
modifies this->delta_a and uses this->delta_f
============
*/
ID_INLINE void idLCP_Symmetric::CalcAccelDelta( int d ) {
int j;
float dot;
// only the not clamped variables, including the current variable, can have a change in acceleration
for ( j = numClamped; j <= d; j++ ) {
// only the clamped variables and the current variable have a force delta unequal zero
SIMDProcessor->Dot( dot, rowPtrs[j], delta_f.ToFloatPtr(), numClamped );
delta_a[j] = dot + rowPtrs[j][d] * delta_f[d];
}
}
/*
============
idLCP_Symmetric::ChangeForce
modifies this->f and uses this->delta_f
============
*/
ID_INLINE void idLCP_Symmetric::ChangeForce( int d, float step ) {
// only the clamped variables and current variable have a force delta unequal zero
SIMDProcessor->MulAdd( f.ToFloatPtr(), step, delta_f.ToFloatPtr(), numClamped );
f[d] += step * delta_f[d];
}
/*
============
idLCP_Symmetric::ChangeAccel
modifies this->a and uses this->delta_a
============
*/
ID_INLINE void idLCP_Symmetric::ChangeAccel( int d, float step ) {
// only the not clamped variables, including the current variable, can have an acceleration unequal zero
SIMDProcessor->MulAdd( a.ToFloatPtr() + numClamped, step, delta_a.ToFloatPtr() + numClamped, d - numClamped + 1 );
}
/*
============
idLCP_Symmetric::GetMaxStep
============
*/
void idLCP_Symmetric::GetMaxStep( int d, float dir, float &maxStep, int &limit, int &limitSide ) const {
int i;
float s;
// default to a full step for the current variable
if ( idMath::Fabs( delta_a[d] ) > LCP_DELTA_ACCEL_EPSILON ) {
maxStep = -a[d] / delta_a[d];
} else {
maxStep = 0.0f;
}
limit = d;
limitSide = 0;
// test the current variable
if ( dir < 0.0f ) {
if ( lo[d] != -idMath::INFINITY ) {
s = ( lo[d] - f[d] ) / dir;
if ( s < maxStep ) {
maxStep = s;
limitSide = -1;
}
}
} else {
if ( hi[d] != idMath::INFINITY ) {
s = ( hi[d] - f[d] ) / dir;
if ( s < maxStep ) {
maxStep = s;
limitSide = 1;
}
}
}
// test the clamped bounded variables
for ( i = numUnbounded; i < numClamped; i++ ) {
if ( delta_f[i] < -LCP_DELTA_FORCE_EPSILON ) {
// if there is a low boundary
if ( lo[i] != -idMath::INFINITY ) {
s = ( lo[i] - f[i] ) / delta_f[i];
if ( s < maxStep ) {
maxStep = s;
limit = i;
limitSide = -1;
}
}
} else if ( delta_f[i] > LCP_DELTA_FORCE_EPSILON ) {
// if there is a high boundary
if ( hi[i] != idMath::INFINITY ) {
s = ( hi[i] - f[i] ) / delta_f[i];
if ( s < maxStep ) {
maxStep = s;
limit = i;
limitSide = 1;
}
}
}
}
// test the not clamped bounded variables
for ( i = numClamped; i < d; i++ ) {
if ( side[i] == -1 ) {
if ( delta_a[i] >= -LCP_DELTA_ACCEL_EPSILON ) {
continue;
}
} else if ( side[i] == 1 ) {
if ( delta_a[i] <= LCP_DELTA_ACCEL_EPSILON ) {
continue;
}
} else {
continue;
}
// ignore variables for which the force is not allowed to take any substantial value
if ( lo[i] >= -LCP_BOUND_EPSILON && hi[i] <= LCP_BOUND_EPSILON ) {
continue;
}
s = -a[i] / delta_a[i];
if ( s < maxStep ) {
maxStep = s;
limit = i;
limitSide = 0;
}
}
}
/*
============
idLCP_Symmetric::Solve
============
*/
bool idLCP_Symmetric::Solve( const idMatX &o_m, idVecX &o_x, const idVecX &o_b, const idVecX &o_lo, const idVecX &o_hi, const int *o_boxIndex ) {
int i, j, n, limit, limitSide, boxStartIndex;
float dir, maxStep, dot, s;
char *failed = NULL;
// true when the matrix rows are 16 byte padded
padded = ((o_m.GetNumRows()+3)&~3) == o_m.GetNumColumns();
assert( padded || o_m.GetNumRows() == o_m.GetNumColumns() );
assert( o_x.GetSize() == o_m.GetNumRows() );
assert( o_b.GetSize() == o_m.GetNumRows() );
assert( o_lo.GetSize() == o_m.GetNumRows() );
assert( o_hi.GetSize() == o_m.GetNumRows() );
// allocate memory for permuted input
f.SetData( o_m.GetNumRows(), VECX_ALLOCA( o_m.GetNumRows() ) );
a.SetData( o_b.GetSize(), VECX_ALLOCA( o_b.GetSize() ) );
b.SetData( o_b.GetSize(), VECX_ALLOCA( o_b.GetSize() ) );
lo.SetData( o_lo.GetSize(), VECX_ALLOCA( o_lo.GetSize() ) );
hi.SetData( o_hi.GetSize(), VECX_ALLOCA( o_hi.GetSize() ) );
if ( o_boxIndex ) {
boxIndex = (int *)_alloca16( o_x.GetSize() * sizeof( int ) );
memcpy( boxIndex, o_boxIndex, o_x.GetSize() * sizeof( int ) );
} else {
boxIndex = NULL;
}
// we override the const on o_m here but on exit the matrix is unchanged
m.SetData( o_m.GetNumRows(), o_m.GetNumColumns(), const_cast<float *>(o_m[0]) );
f.Zero();
a.Zero();
b = o_b;
lo = o_lo;
hi = o_hi;
// pointers to the rows of m
rowPtrs = (float **) _alloca16( m.GetNumRows() * sizeof( float * ) );
for ( i = 0; i < m.GetNumRows(); i++ ) {
rowPtrs[i] = m[i];
}
// tells if a variable is at the low boundary, high boundary or inbetween
side = (int *) _alloca16( m.GetNumRows() * sizeof( int ) );
// index to keep track of the permutation
permuted = (int *) _alloca16( m.GetNumRows() * sizeof( int ) );
for ( i = 0; i < m.GetNumRows(); i++ ) {
permuted[i] = i;
}
// permute input so all unbounded variables come first
numUnbounded = 0;
for ( i = 0; i < m.GetNumRows(); i++ ) {
if ( lo[i] == -idMath::INFINITY && hi[i] == idMath::INFINITY ) {
if ( numUnbounded != i ) {
Swap( numUnbounded, i );
}
numUnbounded++;
}
}
// permute input so all variables using the boxIndex come last
boxStartIndex = m.GetNumRows();
if ( boxIndex ) {
for ( i = m.GetNumRows() - 1; i >= numUnbounded; i-- ) {
if ( boxIndex[i] >= 0 && ( lo[i] != -idMath::INFINITY || hi[i] != idMath::INFINITY ) ) {
boxStartIndex--;
if ( boxStartIndex != i ) {
Swap( boxStartIndex, i );
}
}
}
}
// sub matrix for factorization
clamped.SetData( m.GetNumRows(), m.GetNumColumns(), MATX_ALLOCA( m.GetNumRows() * m.GetNumColumns() ) );
diagonal.SetData( m.GetNumRows(), VECX_ALLOCA( m.GetNumRows() ) );
solveCache1.SetData( m.GetNumRows(), VECX_ALLOCA( m.GetNumRows() ) );
solveCache2.SetData( m.GetNumRows(), VECX_ALLOCA( m.GetNumRows() ) );
// all unbounded variables are clamped
numClamped = numUnbounded;
// if there are unbounded variables
if ( numUnbounded ) {
// factor and solve for unbounded variables
if ( !FactorClamped() ) {
idLib::common->Printf( "idLCP_Symmetric::Solve: unbounded factorization failed\n" );
return false;
}
SolveClamped( f, b.ToFloatPtr() );
// if there are no bounded variables we are done
if ( numUnbounded == m.GetNumRows() ) {
o_x = f; // the vector is not permuted
return true;
}
}
#ifdef IGNORE_UNSATISFIABLE_VARIABLES
int numIgnored = 0;
#endif
// allocate for delta force and delta acceleration
delta_f.SetData( m.GetNumRows(), VECX_ALLOCA( m.GetNumRows() ) );
delta_a.SetData( m.GetNumRows(), VECX_ALLOCA( m.GetNumRows() ) );
// solve for bounded variables
failed = NULL;
for ( i = numUnbounded; i < m.GetNumRows(); i++ ) {
clampedChangeStart = 0;
// once we hit the box start index we can initialize the low and high boundaries of the variables using the box index
if ( i == boxStartIndex ) {
for ( j = 0; j < boxStartIndex; j++ ) {
o_x[permuted[j]] = f[j];
}
for ( j = boxStartIndex; j < m.GetNumRows(); j++ ) {
s = o_x[boxIndex[j]];
if ( lo[j] != -idMath::INFINITY ) {
lo[j] = - idMath::Fabs( lo[j] * s );
}
if ( hi[j] != idMath::INFINITY ) {
hi[j] = idMath::Fabs( hi[j] * s );
}
}
}
// calculate acceleration for current variable
SIMDProcessor->Dot( dot, rowPtrs[i], f.ToFloatPtr(), i );
a[i] = dot - b[i];
// if already at the low boundary
if ( lo[i] >= -LCP_BOUND_EPSILON && a[i] >= -LCP_ACCEL_EPSILON ) {
side[i] = -1;
continue;
}
// if already at the high boundary
if ( hi[i] <= LCP_BOUND_EPSILON && a[i] <= LCP_ACCEL_EPSILON ) {
side[i] = 1;
continue;
}
// if inside the clamped region
if ( idMath::Fabs( a[i] ) <= LCP_ACCEL_EPSILON ) {
side[i] = 0;
AddClamped( i, false );
continue;
}
// drive the current variable into a valid region
for ( n = 0; n < maxIterations; n++ ) {
// direction to move
if ( a[i] <= 0.0f ) {
dir = 1.0f;
} else {
dir = -1.0f;
}
// calculate force delta
CalcForceDelta( i, dir );
// calculate acceleration delta: delta_a = m * delta_f;
CalcAccelDelta( i );
// maximum step we can take
GetMaxStep( i, dir, maxStep, limit, limitSide );
if ( maxStep <= 0.0f ) {
#ifdef IGNORE_UNSATISFIABLE_VARIABLES
// ignore the current variable completely
lo[i] = hi[i] = 0.0f;
f[i] = 0.0f;
side[i] = -1;
numIgnored++;
#else
failed = va( "invalid step size %.4f", maxStep );
#endif
break;
}
// change force
ChangeForce( i, maxStep );
// change acceleration
ChangeAccel( i, maxStep );
// clamp/unclamp the variable that limited this step
side[limit] = limitSide;
switch( limitSide ) {
case 0: {
a[limit] = 0.0f;
AddClamped( limit, ( limit == i ) );
break;
}
case -1: {
f[limit] = lo[limit];
if ( limit != i ) {
RemoveClamped( limit );
}
break;
}
case 1: {
f[limit] = hi[limit];
if ( limit != i ) {
RemoveClamped( limit );
}
break;
}
}
// if the current variable limited the step we can continue with the next variable
if ( limit == i ) {
break;
}
}
if ( n >= maxIterations ) {
failed = va( "max iterations %d", maxIterations );
break;
}
if ( failed ) {
break;
}
}
#ifdef IGNORE_UNSATISFIABLE_VARIABLES
if ( numIgnored ) {
/* if ( lcp_showFailures.GetBool() ) {
idLib::common->Printf( "idLCP_Symmetric::Solve: %d of %d bounded variables ignored\n", numIgnored, m.GetNumRows() - numUnbounded );
}*/
}
#endif
// if failed clear remaining forces
if ( failed ) {
/* if ( lcp_showFailures.GetBool() ) {
idLib::common->Printf( "idLCP_Symmetric::Solve: %s (%d of %d bounded variables ignored)\n", failed, m.GetNumRows() - i, m.GetNumRows() - numUnbounded );
}*/
for ( j = i; j < m.GetNumRows(); j++ ) {
f[j] = 0.0f;
}
}
#if defined(_DEBUG) && 0
if ( !failed ) {
// test whether or not the solution satisfies the complementarity conditions
for ( i = 0; i < m.GetNumRows(); i++ ) {
a[i] = -b[i];
for ( j = 0; j < m.GetNumRows(); j++ ) {
a[i] += rowPtrs[i][j] * f[j];
}
if ( f[i] == lo[i] ) {
if ( lo[i] != hi[i] && a[i] < -LCP_ACCEL_EPSILON ) {
int bah1 = 1;
}
} else if ( f[i] == hi[i] ) {
if ( lo[i] != hi[i] && a[i] > LCP_ACCEL_EPSILON ) {
int bah2 = 1;
}
} else if ( f[i] < lo[i] || f[i] > hi[i] || idMath::Fabs( a[i] ) > 1.0f ) {
int bah3 = 1;
}
}
}
#endif
// unpermute result
for ( i = 0; i < f.GetSize(); i++ ) {
o_x[permuted[i]] = f[i];
}
// unpermute original matrix
for ( i = 0; i < m.GetNumRows(); i++ ) {
for ( j = 0; j < m.GetNumRows(); j++ ) {
if ( permuted[j] == i ) {
break;
}
}
if ( i != j ) {
m.SwapColumns( i, j );
idSwap( permuted[i], permuted[j] );
}
}
return failed ? false : true;
}
//===============================================================
//
// idLCP
//
//===============================================================
/*
============
idLCP::AllocSquare
============
*/
idLCP *idLCP::AllocSquare( void ) {
idLCP *lcp = new idLCP_Square;
lcp->SetMaxIterations( 32 );
return lcp;
}
/*
============
idLCP::AllocSymmetric
============
*/
idLCP *idLCP::AllocSymmetric( void ) {
idLCP *lcp = new idLCP_Symmetric;
lcp->SetMaxIterations( 32 );
return lcp;
}
/*
============
idLCP::~idLCP
============
*/
idLCP::~idLCP( void ) {
}
/*
============
idLCP::SetMaxIterations
============
*/
void idLCP::SetMaxIterations( int max ) {
maxIterations = max;
}
/*
============
idLCP::GetMaxIterations
============
*/
int idLCP::GetMaxIterations( void ) {
return maxIterations;
}
| 25.7901 | 156 | 0.562669 | JasonHutton |
28c0961fda250a1b1e9db6394c475466af3f5533 | 19,072 | cpp | C++ | code/SDK/sources/MagicSoftware/FreeMagic/Source/Containment3D/MgcCont3DMinSphere.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 7 | 2018-03-27T12:36:07.000Z | 2020-06-26T11:31:52.000Z | code/SDK/sources/MagicSoftware/FreeMagic/Source/Containment3D/MgcCont3DMinSphere.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 2 | 2018-05-26T23:17:14.000Z | 2019-04-14T18:33:27.000Z | code/SDK/sources/MagicSoftware/FreeMagic/Source/Containment3D/MgcCont3DMinSphere.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 5 | 2020-10-18T11:55:26.000Z | 2022-03-28T07:21:35.000Z | // Magic Software, Inc.
// http://www.magic-software.com
// Copyright (c) 2000-2002. All Rights Reserved
//
// Source code from Magic Software is supplied under the terms of a license
// agreement and may not be copied or disclosed except in accordance with the
// terms of that agreement. The various license agreements may be found at
// the Magic Software web site. This file is subject to the license
//
// FREE SOURCE CODE
// http://www.magic-software.com/License/free.pdf
#include "stdafx.h"
#pragma hdrstop
#include "MgcCont3DMinSphere.h"
using namespace Mgc;
// error checking
static const Real gs_fEpsilon = 1e-03f;
static const Real gs_fOnePlusEpsilon = 1.0f + gs_fEpsilon;
// indices of points that support current minimum volume sphere
class Support
{
public:
int m_iQuantity;
int m_aiIndex[4];
bool Contains (int iIndex, Vector3** apkPoint)
{
for (int i = 0; i < m_iQuantity; i++)
{
Vector3 kDiff = *apkPoint[iIndex] - *apkPoint[m_aiIndex[i]];
if ( kDiff.SquaredLength() < gs_fEpsilon )
return true;
}
return false;
}
};
// All internal minimal sphere calculations store the squared radius in the
// radius member of Sphere. Only at the end is a sqrt computed.
//----------------------------------------------------------------------------
static bool PointInsideSphere (const Vector3& rkP, const Sphere& rkS)
{
Vector3 kDiff = rkP - rkS.Center();
Real fTest = kDiff.SquaredLength();
return fTest <= gs_fOnePlusEpsilon*rkS.Radius(); // theory: test <= R^2
}
//----------------------------------------------------------------------------
static Sphere ExactSphere1 (const Vector3& rkP)
{
Sphere kMinimal;
kMinimal.Center() = rkP;
kMinimal.Radius() = 0.0f;
return kMinimal;
}
//----------------------------------------------------------------------------
static Sphere ExactSphere2 (const Vector3& rkP0, const Vector3& rkP1)
{
Sphere kMinimal;
kMinimal.Center() = 0.5f*(rkP0+rkP1);
Vector3 kDiff = rkP1 - rkP0;
kMinimal.Radius() = 0.25f*kDiff.SquaredLength();
return kMinimal;
}
//----------------------------------------------------------------------------
static Sphere ExactSphere3 (const Vector3& rkP0, const Vector3& rkP1,
const Vector3& rkP2)
{
// Compute the circle (in 3D) containing p0, p1, and p2. The Center() in
// barycentric coordinates is K = u0*p0+u1*p1+u2*p2 where u0+u1+u2=1.
// The Center() is equidistant from the three points, so |K-p0| = |K-p1| =
// |K-p2| = R where R is the radius of the circle.
//
// From these conditions,
// K-p0 = u0*A + u1*B - A
// K-p1 = u0*A + u1*B - B
// K-p2 = u0*A + u1*B
// where A = p0-p2 and B = p1-p2, which leads to
// r^2 = |u0*A+u1*B|^2 - 2*Dot(A,u0*A+u1*B) + |A|^2
// r^2 = |u0*A+u1*B|^2 - 2*Dot(B,u0*A+u1*B) + |B|^2
// r^2 = |u0*A+u1*B|^2
// Subtracting the last equation from the first two and writing
// the equations as a linear system,
//
// +- -++ -+ +- -+
// | Dot(A,A) Dot(A,B) || u0 | = 0.5 | Dot(A,A) |
// | Dot(B,A) Dot(B,B) || u1 | | Dot(B,B) |
// +- -++ -+ +- -+
//
// The following code solves this system for u0 and u1, then
// evaluates the third equation in r^2 to obtain r.
Vector3 kA = rkP0 - rkP2;
Vector3 kB = rkP1 - rkP2;
Real fAdA = kA.Dot(kA);
Real fAdB = kA.Dot(kB);
Real fBdB = kB.Dot(kB);
Real fDet = fAdA*fBdB-fAdB*fAdB;
Sphere kMinimal;
if ( Math::FAbs(fDet) > gs_fEpsilon )
{
Real fHalfInvDet = 0.5f/fDet;
Real fU0 = fHalfInvDet*fBdB*(fAdA-fAdB);
Real fU1 = fHalfInvDet*fAdA*(fBdB-fAdB);
Real fU2 = 1.0f-fU0-fU1;
kMinimal.Center() = fU0*rkP0 + fU1*rkP1 + fU2*rkP2;
Vector3 kTmp = fU0*kA + fU1*kB;
kMinimal.Radius() = kTmp.SquaredLength();
}
else
{
kMinimal.Center() = Vector3::ZERO;
kMinimal.Radius() = Math::MAX_REAL;
}
return kMinimal;
}
//----------------------------------------------------------------------------
static Sphere ExactSphere4 (const Vector3& rkP0, const Vector3& rkP1,
const Vector3& rkP2, const Vector3& rkP3)
{
// Compute the sphere containing p0, p1, p2, and p3. The Center() in
// barycentric coordinates is K = u0*p0+u1*p1+u2*p2+u3*p3 where
// u0+u1+u2+u3=1. The Center() is equidistant from the three points, so
// |K-p0| = |K-p1| = |K-p2| = |K-p3| = R where R is the radius of the
// sphere.
//
// From these conditions,
// K-p0 = u0*A + u1*B + u2*C - A
// K-p1 = u0*A + u1*B + u2*C - B
// K-p2 = u0*A + u1*B + u2*C - C
// K-p3 = u0*A + u1*B + u2*C
// where A = p0-p3, B = p1-p3, and C = p2-p3 which leads to
// r^2 = |u0*A+u1*B+u2*C|^2 - 2*Dot(A,u0*A+u1*B+u2*C) + |A|^2
// r^2 = |u0*A+u1*B+u2*C|^2 - 2*Dot(B,u0*A+u1*B+u2*C) + |B|^2
// r^2 = |u0*A+u1*B+u2*C|^2 - 2*Dot(C,u0*A+u1*B+u2*C) + |C|^2
// r^2 = |u0*A+u1*B+u2*C|^2
// Subtracting the last equation from the first three and writing
// the equations as a linear system,
//
// +- -++ -+ +- -+
// | Dot(A,A) Dot(A,B) Dot(A,C) || u0 | = 0.5 | Dot(A,A) |
// | Dot(B,A) Dot(B,B) Dot(B,C) || u1 | | Dot(B,B) |
// | Dot(C,A) Dot(C,B) Dot(C,C) || u2 | | Dot(C,C) |
// +- -++ -+ +- -+
//
// The following code solves this system for u0, u1, and u2, then
// evaluates the fourth equation in r^2 to obtain r.
Vector3 kE10 = rkP0 - rkP3;
Vector3 kE20 = rkP1 - rkP3;
Vector3 kE30 = rkP2 - rkP3;
Real aafA[3][3];
aafA[0][0] = kE10.Dot(kE10);
aafA[0][1] = kE10.Dot(kE20);
aafA[0][2] = kE10.Dot(kE30);
aafA[1][0] = aafA[0][1];
aafA[1][1] = kE20.Dot(kE20);
aafA[1][2] = kE20.Dot(kE30);
aafA[2][0] = aafA[0][2];
aafA[2][1] = aafA[1][2];
aafA[2][2] = kE30.Dot(kE30);
Real afB[3];
afB[0] = 0.5f*aafA[0][0];
afB[1] = 0.5f*aafA[1][1];
afB[2] = 0.5f*aafA[2][2];
Real aafAInv[3][3];
aafAInv[0][0] = aafA[1][1]*aafA[2][2]-aafA[1][2]*aafA[2][1];
aafAInv[0][1] = aafA[0][2]*aafA[2][1]-aafA[0][1]*aafA[2][2];
aafAInv[0][2] = aafA[0][1]*aafA[1][2]-aafA[0][2]*aafA[1][1];
aafAInv[1][0] = aafA[1][2]*aafA[2][0]-aafA[1][0]*aafA[2][2];
aafAInv[1][1] = aafA[0][0]*aafA[2][2]-aafA[0][2]*aafA[2][0];
aafAInv[1][2] = aafA[0][2]*aafA[1][0]-aafA[0][0]*aafA[1][2];
aafAInv[2][0] = aafA[1][0]*aafA[2][1]-aafA[1][1]*aafA[2][0];
aafAInv[2][1] = aafA[0][1]*aafA[2][0]-aafA[0][0]*aafA[2][1];
aafAInv[2][2] = aafA[0][0]*aafA[1][1]-aafA[0][1]*aafA[1][0];
Real fDet = aafA[0][0]*aafAInv[0][0] + aafA[0][1]*aafAInv[1][0] +
aafA[0][2]*aafAInv[2][0];
Sphere kMinimal;
if ( Math::FAbs(fDet) > gs_fEpsilon )
{
Real fInvDet = 1.0f/fDet;
int iRow, iCol;
for (iRow = 0; iRow < 3; iRow++)
{
for (iCol = 0; iCol < 3; iCol++)
aafAInv[iRow][iCol] *= fInvDet;
}
Real afU[4];
for (iRow = 0; iRow < 3; iRow++)
{
afU[iRow] = 0.0f;
for (iCol = 0; iCol < 3; iCol++)
afU[iRow] += aafAInv[iRow][iCol]*afB[iCol];
}
afU[3] = 1.0f - afU[0] - afU[1] - afU[2];
kMinimal.Center() = afU[0]*rkP0 + afU[1]*rkP1 + afU[2]*rkP2 +
afU[3]*rkP3;
Vector3 kTmp = afU[0]*kE10 + afU[1]*kE20 + afU[2]*kE30;
kMinimal.Radius() = kTmp.SquaredLength();
}
else
{
kMinimal.Center() = Vector3::ZERO;
kMinimal.Radius() = Math::MAX_REAL;
}
return kMinimal;
}
//----------------------------------------------------------------------------
static Sphere UpdateSupport1 (int i, Vector3** apkPerm, Support& rkSupp)
{
const Vector3& rkP0 = *apkPerm[rkSupp.m_aiIndex[0]];
const Vector3& rkP1 = *apkPerm[i];
Sphere kMinimal = ExactSphere2(rkP0,rkP1);
rkSupp.m_iQuantity = 2;
rkSupp.m_aiIndex[1] = i;
return kMinimal;
}
//----------------------------------------------------------------------------
static Sphere UpdateSupport2 (int i, Vector3** apkPerm, Support& rkSupp)
{
const Vector3& rkP0 = *apkPerm[rkSupp.m_aiIndex[0]];
const Vector3& rkP1 = *apkPerm[rkSupp.m_aiIndex[1]];
const Vector3& rkP2 = *apkPerm[i];
Sphere akS[3];
Real fMinRSqr = Math::MAX_REAL;
int iIndex = -1;
akS[0] = ExactSphere2(rkP0,rkP2);
if ( PointInsideSphere(rkP1,akS[0]) )
{
fMinRSqr = akS[0].Radius();
iIndex = 0;
}
akS[1] = ExactSphere2(rkP1,rkP2);
if ( akS[1].Radius() < fMinRSqr )
{
if ( PointInsideSphere(rkP0,akS[1]) )
{
fMinRSqr = akS[1].Radius();
iIndex = 1;
}
}
Sphere kMinimal;
if ( iIndex != -1 )
{
kMinimal = akS[iIndex];
rkSupp.m_aiIndex[1-iIndex] = i;
}
else
{
kMinimal = ExactSphere3(rkP0,rkP1,rkP2);
assert( kMinimal.Radius() <= fMinRSqr );
rkSupp.m_iQuantity = 3;
rkSupp.m_aiIndex[2] = i;
}
return kMinimal;
}
//----------------------------------------------------------------------------
static Sphere UpdateSupport3 (int i, Vector3** apkPerm, Support& rkSupp)
{
const Vector3& rkP0 = *apkPerm[rkSupp.m_aiIndex[0]];
const Vector3& rkP1 = *apkPerm[rkSupp.m_aiIndex[1]];
const Vector3& rkP2 = *apkPerm[rkSupp.m_aiIndex[2]];
const Vector3& rkP3 = *apkPerm[i];
Sphere akS[6];
Real fMinRSqr = Math::MAX_REAL;
int iIndex = -1;
akS[0] = ExactSphere2(rkP0,rkP3);
if ( PointInsideSphere(rkP1,akS[0]) && PointInsideSphere(rkP2,akS[0]) )
{
fMinRSqr = akS[0].Radius();
iIndex = 0;
}
akS[1] = ExactSphere2(rkP1,rkP3);
if ( akS[1].Radius() < fMinRSqr
&& PointInsideSphere(rkP0,akS[1]) && PointInsideSphere(rkP2,akS[1]) )
{
fMinRSqr = akS[1].Radius();
iIndex = 1;
}
akS[2] = ExactSphere2(rkP2,rkP3);
if ( akS[2].Radius() < fMinRSqr
&& PointInsideSphere(rkP0,akS[2]) && PointInsideSphere(rkP1,akS[2]) )
{
fMinRSqr = akS[2].Radius();
iIndex = 2;
}
akS[3] = ExactSphere3(rkP0,rkP1,rkP3);
if ( akS[3].Radius() < fMinRSqr && PointInsideSphere(rkP2,akS[3]) )
{
fMinRSqr = akS[3].Radius();
iIndex = 3;
}
akS[4] = ExactSphere3(rkP0,rkP2,rkP3);
if ( akS[4].Radius() < fMinRSqr && PointInsideSphere(rkP1,akS[4]) )
{
fMinRSqr = akS[4].Radius();
iIndex = 4;
}
akS[5] = ExactSphere3(rkP1,rkP2,rkP3);
if ( akS[5].Radius() < fMinRSqr && PointInsideSphere(rkP0,akS[5]) )
{
fMinRSqr = akS[5].Radius();
iIndex = 5;
}
Sphere kMinimal;
switch ( iIndex )
{
case 0:
kMinimal = akS[0];
rkSupp.m_iQuantity = 2;
rkSupp.m_aiIndex[1] = i;
break;
case 1:
kMinimal = akS[1];
rkSupp.m_iQuantity = 2;
rkSupp.m_aiIndex[0] = i;
break;
case 2:
kMinimal = akS[2];
rkSupp.m_iQuantity = 2;
rkSupp.m_aiIndex[0] = rkSupp.m_aiIndex[2];
rkSupp.m_aiIndex[1] = i;
break;
case 3:
kMinimal = akS[3];
rkSupp.m_aiIndex[2] = i;
break;
case 4:
kMinimal = akS[4];
rkSupp.m_aiIndex[1] = i;
break;
case 5:
kMinimal = akS[5];
rkSupp.m_aiIndex[0] = i;
break;
default:
kMinimal = ExactSphere4(rkP0,rkP1,rkP2,rkP3);
assert( kMinimal.Radius() <= fMinRSqr );
rkSupp.m_iQuantity = 4;
rkSupp.m_aiIndex[3] = i;
break;
}
return kMinimal;
}
//----------------------------------------------------------------------------
static Sphere UpdateSupport4 (int i, Vector3** apkPerm, Support& rkSupp)
{
const Vector3& rkP0 = *apkPerm[rkSupp.m_aiIndex[0]];
const Vector3& rkP1 = *apkPerm[rkSupp.m_aiIndex[1]];
const Vector3& rkP2 = *apkPerm[rkSupp.m_aiIndex[2]];
const Vector3& rkP3 = *apkPerm[rkSupp.m_aiIndex[3]];
const Vector3& rkP4 = *apkPerm[i];
Sphere akS[14];
Real fMinRSqr = Math::MAX_REAL;
int iIndex = -1;
akS[0] = ExactSphere2(rkP0,rkP4);
if ( PointInsideSphere(rkP1,akS[0])
&& PointInsideSphere(rkP2,akS[0])
&& PointInsideSphere(rkP3,akS[0]) )
{
fMinRSqr = akS[0].Radius();
iIndex = 0;
}
akS[1] = ExactSphere2(rkP1,rkP4);
if ( akS[1].Radius() < fMinRSqr && PointInsideSphere(rkP0,akS[1])
&& PointInsideSphere(rkP2,akS[1]) && PointInsideSphere(rkP3,akS[1]) )
{
fMinRSqr = akS[1].Radius();
iIndex = 1;
}
akS[2] = ExactSphere2(rkP2,rkP4);
if ( akS[2].Radius() < fMinRSqr && PointInsideSphere(rkP0,akS[2])
&& PointInsideSphere(rkP1,akS[2]) && PointInsideSphere(rkP3,akS[2]) )
{
fMinRSqr = akS[2].Radius();
iIndex = 2;
}
akS[3] = ExactSphere2(rkP3,rkP4);
if ( akS[3].Radius() < fMinRSqr && PointInsideSphere(rkP0,akS[3])
&& PointInsideSphere(rkP1,akS[3]) && PointInsideSphere(rkP2,akS[3]) )
{
fMinRSqr = akS[3].Radius();
iIndex = 3;
}
akS[4] = ExactSphere3(rkP0,rkP1,rkP4);
if ( akS[4].Radius() < fMinRSqr && PointInsideSphere(rkP2,akS[4])
&& PointInsideSphere(rkP3,akS[4]) )
{
fMinRSqr = akS[4].Radius();
iIndex = 4;
}
akS[5] = ExactSphere3(rkP0,rkP2,rkP4);
if ( akS[5].Radius() < fMinRSqr && PointInsideSphere(rkP1,akS[5])
&& PointInsideSphere(rkP3,akS[5]) )
{
fMinRSqr = akS[5].Radius();
iIndex = 5;
}
akS[6] = ExactSphere3(rkP0,rkP3,rkP4);
if ( akS[6].Radius() < fMinRSqr && PointInsideSphere(rkP1,akS[6])
&& PointInsideSphere(rkP2,akS[6]) )
{
fMinRSqr = akS[6].Radius();
iIndex = 6;
}
akS[7] = ExactSphere3(rkP1,rkP2,rkP4);
if ( akS[7].Radius() < fMinRSqr && PointInsideSphere(rkP0,akS[7])
&& PointInsideSphere(rkP3,akS[7]) )
{
fMinRSqr = akS[7].Radius();
iIndex = 7;
}
akS[8] = ExactSphere3(rkP1,rkP3,rkP4);
if ( akS[8].Radius() < fMinRSqr && PointInsideSphere(rkP0,akS[8])
&& PointInsideSphere(rkP2,akS[8]) )
{
fMinRSqr = akS[8].Radius();
iIndex = 8;
}
akS[9] = ExactSphere3(rkP2,rkP3,rkP4);
if ( akS[9].Radius() < fMinRSqr && PointInsideSphere(rkP0,akS[9])
&& PointInsideSphere(rkP1,akS[9]) )
{
fMinRSqr = akS[9].Radius();
iIndex = 9;
}
akS[10] = ExactSphere4(rkP0,rkP1,rkP2,rkP4);
if ( akS[10].Radius() < fMinRSqr && PointInsideSphere(rkP3,akS[10]) )
{
fMinRSqr = akS[10].Radius();
iIndex = 10;
}
akS[11] = ExactSphere4(rkP0,rkP1,rkP3,rkP4);
if ( akS[11].Radius() < fMinRSqr && PointInsideSphere(rkP2,akS[11]) )
{
fMinRSqr = akS[11].Radius();
iIndex = 11;
}
akS[12] = ExactSphere4(rkP0,rkP2,rkP3,rkP4);
if ( akS[12].Radius() < fMinRSqr && PointInsideSphere(rkP1,akS[12]) )
{
fMinRSqr = akS[12].Radius();
iIndex = 12;
}
akS[13] = ExactSphere4(rkP1,rkP2,rkP3,rkP4);
if ( akS[13].Radius() < fMinRSqr && PointInsideSphere(rkP0,akS[13]) )
{
fMinRSqr = akS[13].Radius();
iIndex = 13;
}
assert( iIndex != -1 );
Sphere kMinimal = akS[iIndex];
switch ( iIndex )
{
case 0:
rkSupp.m_iQuantity = 2;
rkSupp.m_aiIndex[1] = i;
break;
case 1:
rkSupp.m_iQuantity = 2;
rkSupp.m_aiIndex[0] = i;
break;
case 2:
rkSupp.m_iQuantity = 2;
rkSupp.m_aiIndex[0] = rkSupp.m_aiIndex[2];
rkSupp.m_aiIndex[1] = i;
break;
case 3:
rkSupp.m_iQuantity = 2;
rkSupp.m_aiIndex[0] = rkSupp.m_aiIndex[3];
rkSupp.m_aiIndex[1] = i;
break;
case 4:
rkSupp.m_iQuantity = 3;
rkSupp.m_aiIndex[2] = i;
break;
case 5:
rkSupp.m_iQuantity = 3;
rkSupp.m_aiIndex[1] = i;
break;
case 6:
rkSupp.m_iQuantity = 3;
rkSupp.m_aiIndex[1] = rkSupp.m_aiIndex[3];
rkSupp.m_aiIndex[2] = i;
break;
case 7:
rkSupp.m_iQuantity = 3;
rkSupp.m_aiIndex[0] = i;
break;
case 8:
rkSupp.m_iQuantity = 3;
rkSupp.m_aiIndex[0] = rkSupp.m_aiIndex[3];
rkSupp.m_aiIndex[2] = i;
break;
case 9:
rkSupp.m_iQuantity = 3;
rkSupp.m_aiIndex[0] = rkSupp.m_aiIndex[3];
rkSupp.m_aiIndex[1] = i;
break;
case 10:
rkSupp.m_aiIndex[3] = i;
break;
case 11:
rkSupp.m_aiIndex[2] = i;
break;
case 12:
rkSupp.m_aiIndex[1] = i;
break;
case 13:
rkSupp.m_aiIndex[0] = i;
break;
}
return kMinimal;
}
//----------------------------------------------------------------------------
typedef Sphere (*UpdateFunction)(int,Vector3**,Support&);
static UpdateFunction gs_aoUpdate[5] =
{
NULL,
UpdateSupport1,
UpdateSupport2,
UpdateSupport3,
UpdateSupport4
};
//----------------------------------------------------------------------------
Sphere Mgc::MinSphere (int iQuantity, const Vector3* akPoint)
{
// initialize random number generator
static bool s_bFirstTime = true;
if ( s_bFirstTime )
{
srand(367);
s_bFirstTime = false;
}
Sphere kMinimal;
Support kSupp;
if ( iQuantity >= 1 )
{
// create identity permutation (0,1,...,iQuantity-1)
Vector3** apkPerm = new Vector3*[iQuantity];
int i;
for (i = 0; i < iQuantity; i++)
apkPerm[i] = (Vector3*)&akPoint[i];
// generate random permutation
for (i = iQuantity-1; i > 0; i--)
{
int j = rand() % (i+1);
if ( j != i )
{
Vector3* pSave = apkPerm[i];
apkPerm[i] = apkPerm[j];
apkPerm[j] = pSave;
}
}
kMinimal = ExactSphere1(*apkPerm[0]);
kSupp.m_iQuantity = 1;
kSupp.m_aiIndex[0] = 0;
i = 1;
while ( i < iQuantity )
{
if ( !kSupp.Contains(i,apkPerm) )
{
if ( !PointInsideSphere(*apkPerm[i],kMinimal) )
{
Sphere kSph = gs_aoUpdate[kSupp.m_iQuantity](i,apkPerm,
kSupp);
if ( kSph.Radius() > kMinimal.Radius() )
{
kMinimal = kSph;
i = 0;
continue;
}
}
}
i++;
}
delete[] apkPerm;
}
else
{
assert( false );
}
kMinimal.Radius() = Math::Sqrt(kMinimal.Radius());
return kMinimal;
}
//----------------------------------------------------------------------------
| 29.52322 | 78 | 0.511063 | Rikoshet-234 |
28c9fb94fdc9b5c76adb70ee665b1238d787ff12 | 1,094 | cc | C++ | effects/src/passthrough.cc | mnyrenius/awesome-fxd | b643cea47a92aa465d24194e23a10e4ff34e0de1 | [
"MIT"
] | null | null | null | effects/src/passthrough.cc | mnyrenius/awesome-fxd | b643cea47a92aa465d24194e23a10e4ff34e0de1 | [
"MIT"
] | null | null | null | effects/src/passthrough.cc | mnyrenius/awesome-fxd | b643cea47a92aa465d24194e23a10e4ff34e0de1 | [
"MIT"
] | null | null | null | #include <audio_processor.h>
#include <fx_plugin.h>
#include <cstring>
#include <memory>
namespace awesomefx
{
class Passthrough : public AudioProcessor
{
public:
Passthrough(const AudioProcessingContext& context)
{
printf("Current sample rate: %u\n", context.getSampleRate());
}
void process(Sample* in_l, Sample* in_r, Sample* out_l, Sample* out_r, std::size_t numSamples) override
{
std::memcpy(out_l, in_l, sizeof(Sample) * numSamples);
std::memcpy(out_r, in_r, sizeof(Sample) * numSamples);
}
void setParameter(const AudioProcessor::Parameter& param) override
{
}
};
class PassthroughPlugin : public FxPlugin
{
public:
FxPluginInfo getPluginInfo() const override
{
return {"Passthrough", {"Param1", "Param2"}};
}
AudioProcessor::Ptr createAudioProcessor(const AudioProcessingContext& context) const override
{
return std::make_unique<Passthrough>(context);
}
};
}
using namespace awesomefx;
extern "C" FxPlugin::Ptr createFxPlugin()
{
return std::make_unique<PassthroughPlugin>();
}
| 21.45098 | 107 | 0.691956 | mnyrenius |
28cbf30a8076c33e2a78dc2ec1ccb8d287177627 | 6,821 | hpp | C++ | files/connector.hpp | DmitryKorotin/mama | 8ec15c4a1cb70332d6caf8abd30a9229c1875628 | [
"Apache-2.0"
] | null | null | null | files/connector.hpp | DmitryKorotin/mama | 8ec15c4a1cb70332d6caf8abd30a9229c1875628 | [
"Apache-2.0"
] | null | null | null | files/connector.hpp | DmitryKorotin/mama | 8ec15c4a1cb70332d6caf8abd30a9229c1875628 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) DataStax, Inc.
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 "auth.hpp"
#include "callback.hpp"
#include "connection.hpp"
#include "socket_connector.hpp"
#ifndef DATASTAX_INTERNAL_CONNECTION_CONNECTOR_HPP
#define DATASTAX_INTERNAL_CONNECTION_CONNECTOR_HPP
namespace datastax { namespace internal { namespace core {
class AuthResponseRequest;
class Config;
class ResponseMessage;
class RequestCallback;
/**
* Connection settings.
*/
struct ConnectionSettings {
/**
* Constructor. Initialize with default settings.
*/
ConnectionSettings();
/**
* Constructor. Initialize connection settings from a config object.
*
* @param config The config object.
*/
ConnectionSettings(const Config& config);
SocketSettings socket_settings;
uint64_t connect_timeout_ms;
AuthProvider::Ptr auth_provider;
unsigned int idle_timeout_secs;
unsigned int heartbeat_interval_secs;
bool no_compact;
String application_name;
String application_version;
String client_id;
};
/**
* A connector. This contains all the initialization code to connect a
* connection.
*/
class Connector
: public RefCounted<Connector>
, public ConnectionListener {
friend class StartupCallback;
public:
typedef SharedRefPtr<Connector> Ptr;
typedef Vector<Ptr> Vec;
typedef internal::Callback<void, Connector*> Callback;
enum ConnectionError {
CONNECTION_OK,
CONNECTION_CANCELED,
CONNECTION_ERROR_AUTH,
CONNECTION_ERROR_CONNECT,
CONNECTION_ERROR_CLOSE,
CONNECTION_ERROR_INTERNAL,
CONNECTION_ERROR_INVALID_OPCODE,
CONNECTION_ERROR_INVALID_PROTOCOL,
CONNECTION_ERROR_KEYSPACE,
CONNECTION_ERROR_RESPONSE,
CONNECTION_ERROR_SSL_HANDSHAKE,
CONNECTION_ERROR_SSL_VERIFY,
CONNECTION_ERROR_SOCKET,
CONNECTION_ERROR_TIMEOUT
};
public:
/**
* Constructor
*
* @param host The host to connect to.
* @param protocol_version The protocol version to use for the connection.
* @param callback A callback that is called when the connection is connected or
* if an error occurred.
*/
Connector(const Host::Ptr& host, ProtocolVersion protocol_version, const Callback& callback);
/**
* Set the keyspace to connect with. Calls "USE <keyspace>" after
* the connection is connected and protocol handshake is completed.
*
* @param keyspace A keyspace to register after connection.
* @return The connector to chain calls.
*/
Connector* with_keyspace(const String& keyspace);
/**
* Set the event types to register for during the protocol handshake.
*
* @param event_types A bit set of event types to register.
* @return The connector to chain calls.
*/
Connector* with_event_types(int event_types);
/**
* Set the connection listener to use after the connection is connected.
*
* @param listener A listener that handles connection events.
* @return The connector to chain calls.
*/
Connector* with_listener(ConnectionListener* listener);
/**
* Set the metrics object to use to record metrics.
*
* @param metrics A metrics object.
* @return The connector to chain calls.
*/
Connector* with_metrics(Metrics* metrics);
/**
* Set the connection and socket settings.
*
* @param The settings to use for connecting the connection.
* @return The connector to chain calls.
*/
Connector* with_settings(const ConnectionSettings& settings);
/**
* Connect the connection.
*
* @param loop An event loop to use for connecting the connection.
*/
void connect(uv_loop_t* loop);
/**
* Cancel the connection process.
*/
void cancel();
/**
* Release the connection from the connector. If not released in the callback
* the connection automatically be closed.
*
* @return The connection object for this connector. This returns a null object
* if the connection is not connected or an error occurred.
*/
Connection::Ptr release_connection();
public:
uv_loop_t* loop() { return loop_; }
const Address& address() const { return socket_connector_->address(); }
const ProtocolVersion protocol_version() const { return protocol_version_; }
bool is_ok() const { return error_code_ == CONNECTION_OK; }
bool is_canceled() const { return error_code_ == CONNECTION_CANCELED; }
bool is_invalid_protocol() const { return error_code_ == CONNECTION_ERROR_INVALID_PROTOCOL; }
bool is_auth_error() const { return error_code_ == CONNECTION_ERROR_AUTH; }
bool is_ssl_error() const {
return error_code_ == CONNECTION_ERROR_SSL_HANDSHAKE ||
error_code_ == CONNECTION_ERROR_SSL_VERIFY;
}
bool is_timeout_error() const { return error_code_ == CONNECTION_ERROR_TIMEOUT; }
bool is_keyspace_error() const { return error_code_ == CONNECTION_ERROR_KEYSPACE; }
bool is_critical_error() const {
return is_auth_error() || is_ssl_error() || is_invalid_protocol() || is_keyspace_error();
}
ConnectionError error_code() { return error_code_; }
const String& error_message() { return error_message_; }
SocketConnector::SocketError socket_error_code() { return socket_connector_->error_code(); }
const String& socket_error_message() { return socket_connector_->error_message(); }
CassError ssl_error_code() { return socket_connector_->ssl_error_code(); }
private:
void finish();
void on_error(ConnectionError code, const String& message);
void on_ready_or_set_keyspace();
void on_ready_or_register_for_events();
void on_supported(ResponseMessage* response);
void on_authenticate(const String& class_name);
void on_auth_challenge(const AuthResponseRequest* request, const String& token);
void on_auth_success(const AuthResponseRequest* request, const String& token);
virtual void on_close(Connection* connection);
void on_connect(SocketConnector* socket_connector);
void on_timeout(Timer* timer);
private:
Callback callback_;
uv_loop_t* loop_;
Host::Ptr host_;
Connection::Ptr connection_;
SocketConnector::Ptr socket_connector_;
Timer timer_;
ConnectionError error_code_;
String error_message_;
ProtocolVersion protocol_version_;
String keyspace_;
int event_types_;
ConnectionListener* listener_;
Metrics* metrics_;
ConnectionSettings settings_;
};
}}} // namespace datastax::internal::core
#endif
| 29.528139 | 95 | 0.743733 | DmitryKorotin |
28cda7cc336ef0443938bde337e3a37d5726a80a | 1,125 | cpp | C++ | vendor/github.com/antlr/antlr4/runtime/Cpp/runtime/src/atn/LexerSkipAction.cpp | mikijov/rune | 66f58cc337e3fb919034128bec690fb86e708234 | [
"Apache-2.0"
] | null | null | null | vendor/github.com/antlr/antlr4/runtime/Cpp/runtime/src/atn/LexerSkipAction.cpp | mikijov/rune | 66f58cc337e3fb919034128bec690fb86e708234 | [
"Apache-2.0"
] | null | null | null | vendor/github.com/antlr/antlr4/runtime/Cpp/runtime/src/atn/LexerSkipAction.cpp | mikijov/rune | 66f58cc337e3fb919034128bec690fb86e708234 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
#include "misc/MurmurHash.h"
#include "Lexer.h"
#include "atn/LexerSkipAction.h"
using namespace antlr4;
using namespace antlr4::atn;
using namespace antlr4::misc;
const Ref<LexerSkipAction> LexerSkipAction::getInstance() {
static Ref<LexerSkipAction> instance(new LexerSkipAction());
return instance;
}
LexerSkipAction::LexerSkipAction() {
}
LexerActionType LexerSkipAction::getActionType() const {
return LexerActionType::SKIP;
}
bool LexerSkipAction::isPositionDependent() const {
return false;
}
void LexerSkipAction::execute(Lexer *lexer) {
lexer->skip();
}
size_t LexerSkipAction::hashCode() const {
size_t hash = MurmurHash::initialize();
hash = MurmurHash::update(hash, (size_t)getActionType());
return MurmurHash::finish(hash, 1);
}
bool LexerSkipAction::operator == (const LexerAction &obj) const {
return &obj == this;
}
std::string LexerSkipAction::toString() const {
return "skip";
}
| 23.4375 | 66 | 0.739556 | mikijov |
28d615000acb979439498f09150476da3e942d53 | 2,837 | cpp | C++ | WeaponOffset.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | WeaponOffset.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | WeaponOffset.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
#include "StdAfx.h"
#include "WeaponOffset.h"
#include "Utility/Hermite.h"
#include <Mannequin/Serialization.h>
void SWeaponOffset::Serialize(Serialization::IArchive& ar)
{
ar(m_position, "Position", "Position");
ar(m_rotation, "Rotation", "Rotation");
}
CWeaponOffsetState::CWeaponOffsetState()
: m_current(ZERO)
, m_last(ZERO)
, m_transitiontime(0.0f)
, m_time(0.0f)
{
}
void CWeaponOffsetState::SetState(const SWeaponOffset& offset, float transitionTime)
{
m_last = ComputeCurrentOffset();
m_current = offset;
m_time = 0.0f;
m_transitiontime = transitionTime;
}
SWeaponOffset CWeaponOffsetState::Blend(float deltaTime)
{
SWeaponOffset result = ComputeCurrentOffset();
m_time += deltaTime;
return result;
}
SWeaponOffset CWeaponOffsetState::ComputeCurrentOffset()
{
SWeaponOffset result;
if (m_transitiontime > 0.0f)
{
float t = Hermite2(SATURATE(m_time / m_transitiontime));
result.m_position = LERP(m_last.m_position, m_current.m_position, t);
result.m_rotation = Lerp(m_last.m_rotation, m_current.m_rotation, t);
}
else
{
result = m_current;
}
return result;
}
CWeaponOffsetStack::CWeaponOffsetStack()
: m_nextId(0)
{
m_weaponOffsetLayers.reserve(4);
}
SWeaponOffset CWeaponOffsetStack::Blend(float deltaTime)
{
return m_state.Blend(deltaTime);
}
void CWeaponOffsetStack::SetOffset(const SWeaponOffset& offset, float blendTime)
{
m_state.SetState(offset, blendTime);
}
CWeaponOffsetStack::TOffsetId CWeaponOffsetStack::PushOffset(const SWeaponOffset& offset, uint32 layer, float blendTime)
{
TOffsetId lastActiveId = m_weaponOffsetLayers.empty() ? -1 : m_weaponOffsetLayers.begin()->m_id;
TWeaponOffsetLayers::iterator it = m_weaponOffsetLayers.begin();
for (; it != m_weaponOffsetLayers.end(); ++it)
{
if (it->m_layer <= layer)
break;
}
SWeaponOffsetLayer layerOffset;
layerOffset.m_offset = offset;
layerOffset.m_layer = layer;
layerOffset.m_id = m_nextId++;
m_weaponOffsetLayers.insert(it, layerOffset);
if (m_weaponOffsetLayers.begin()->m_id != lastActiveId)
m_state.SetState(m_weaponOffsetLayers[0].m_offset, blendTime);
return layerOffset.m_id;
}
void CWeaponOffsetStack::PopOffset(TOffsetId offsetId, float blendTime)
{
TOffsetId lastActiveId = m_weaponOffsetLayers.empty() ? -1 : m_weaponOffsetLayers.begin()->m_id;
TWeaponOffsetLayers::iterator it = m_weaponOffsetLayers.begin();
for (; it != m_weaponOffsetLayers.end(); ++it)
{
if (it->m_id == offsetId)
break;
}
if (it != m_weaponOffsetLayers.end())
m_weaponOffsetLayers.erase(it);
if (m_weaponOffsetLayers.empty())
m_state.SetState(SWeaponOffset(ZERO), blendTime);
else if(m_weaponOffsetLayers.begin()->m_id != lastActiveId)
m_state.SetState(m_weaponOffsetLayers[0].m_offset, blendTime);
}
| 21.823077 | 120 | 0.752556 | IvarJonsson |
28da71dd189f5e17b3dd89db50bea1d2ed9b7969 | 1,717 | cpp | C++ | src/camera.cpp | Arjentix/Pi-RTSP-Server | 7346030b22d7e7c64f9a8fd0a3f8611a255da9d8 | [
"MIT"
] | null | null | null | src/camera.cpp | Arjentix/Pi-RTSP-Server | 7346030b22d7e7c64f9a8fd0a3f8611a255da9d8 | [
"MIT"
] | null | null | null | src/camera.cpp | Arjentix/Pi-RTSP-Server | 7346030b22d7e7c64f9a8fd0a3f8611a255da9d8 | [
"MIT"
] | 1 | 2021-09-08T09:32:15.000Z | 2021-09-08T09:32:15.000Z | /*
MIT License
Copyright (c) 2021 Polyakov Daniil Alexandrovich
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 "camera.h"
#include <unistd.h>
namespace {
/**
* @brief Initialize and open camera
*
* @return Opened camera object
*/
raspicam::RaspiCam OpenCamera() {
raspicam::RaspiCam camera;
camera.setFormat(raspicam::RASPICAM_FORMAT_RGB);
camera.setFrameRate(10);
if (!camera.open()) {
throw CameraOpeningError("Can't open camera");
}
sleep(3);
return camera;
}
} // namespace
CameraOpeningError::CameraOpeningError(std::string_view message) :
std::runtime_error(message.data()) {}
raspicam::RaspiCam &Camera::GetInstance() {
static raspicam::RaspiCam camera = OpenCamera();
return camera;
}
| 30.122807 | 78 | 0.7682 | Arjentix |
28df063924662d13f1fcd904ac19c519e1287cf7 | 2,075 | cpp | C++ | LRUCache/HashLRUCache.cpp | zhanMingming/DataStruct | 7e0c665f02d49919e3df2f08f7a5945300ebd8f1 | [
"MIT"
] | 1 | 2019-11-23T15:41:58.000Z | 2019-11-23T15:41:58.000Z | LRUCache/HashLRUCache.cpp | zhanMingming/DataStruct | 7e0c665f02d49919e3df2f08f7a5945300ebd8f1 | [
"MIT"
] | null | null | null | LRUCache/HashLRUCache.cpp | zhanMingming/DataStruct | 7e0c665f02d49919e3df2f08f7a5945300ebd8f1 | [
"MIT"
] | null | null | null | #include"HashLRUCache.h"
#include"Hash.h"
namespace zhanmm {
HashLRUCache::HashLRUCache(const std::string& name_, CacheOption option)
:name(name_)
{
db_num = option.db_num;
assert(db_num > 0);
//name = name_;
if (option.maxmemory != -1) {
const size_t per_capacity = (option.maxmemory + db_num - 1) / db_num;
option.maxmemory = per_capacity;
}
shard = new LRUCache*[db_num];
for (int index = 0; index < db_num; ++index) {
shard[index] = new LRUCache(option);
}
}
HashLRUCache::~HashLRUCache() {
for(int index = 0; index < db_num; ++index) {
delete shard[index];
}
delete[] shard;
shard = nullptr;
}
bool HashLRUCache::Set(const std::string& key, const std::string& value, int expire_time) {
std::cout << "shardKey:" << Shard(key) << std::endl;
return shard[Shard(key)]->Set(key, value, expire_time);
}
std::string HashLRUCache::Get(const std::string& key) {
return shard[Shard(key)]->Get(key);
}
uint32_t HashLRUCache::Shard(const std::string& key) {
return (Hash(key.data(), key.size(), 0) & (db_num -1));
}
bool HashLRUCache::ExpireKey(const std::string& key, int expire_time) {
return shard[Shard(key)]->ExpireKey(key, expire_time);
}
void HashLRUCache::DeleteKeyIfExpireCycle() {
//uint64_t start = ustime();
int total_expire_num = TotalExpireNum();
int del_expire_num = 0;
for(int pos = 0; pos < db_num; ++pos) {
LRUCache* cur = shard[pos];
//int del_expire_num =0;
int num = cur->ExpireKeyNum();
if (num == 0) {
//cur->AvgTtl(0);
continue;
}
// 获取键值对数量
int slots = cur->Slots();
// 如果 expireKey/ slots < 1%, 则先别扫描此db
if (num && slots > 100 && (num * 100/ slots < 1)) {
break;
}
del_expire_num += cur->RandomRemoveExpireKey();
if (del_expire_num > total_expire_num/4) {
break;
}
}
}
} //namespace zhanmm
| 22.311828 | 91 | 0.568193 | zhanMingming |
28e05e61747a6b44d930b74bdd5b0ca8acbb095c | 483 | cpp | C++ | Source/Tests/LinuxSyscalls/x64/Ioctl.cpp | MerryMage/FEX | 55d981fcb01dffd172f48ca83304b2062ccd95b3 | [
"MIT"
] | null | null | null | Source/Tests/LinuxSyscalls/x64/Ioctl.cpp | MerryMage/FEX | 55d981fcb01dffd172f48ca83304b2062ccd95b3 | [
"MIT"
] | null | null | null | Source/Tests/LinuxSyscalls/x64/Ioctl.cpp | MerryMage/FEX | 55d981fcb01dffd172f48ca83304b2062ccd95b3 | [
"MIT"
] | null | null | null | /*
$info$
tags: LinuxSyscalls|syscalls-x86-64
$end_info$
*/
#include "Tests/LinuxSyscalls/Syscalls.h"
#include "Tests/LinuxSyscalls/x64/Syscalls.h"
#include <stddef.h>
#include <stdint.h>
#include <sys/ioctl.h>
namespace FEX::HLE::x64 {
void RegisterIoctl() {
REGISTER_SYSCALL_IMPL_X64(ioctl, [](FEXCore::Core::CpuStateFrame *Frame, int fd, uint64_t request, void *args) -> uint64_t {
uint64_t Result = ::ioctl(fd, request, args);
SYSCALL_ERRNO();
});
}
}
| 21.954545 | 128 | 0.687371 | MerryMage |
28e1d1a45f3f34a4c72949f010606c41049e3612 | 213 | cpp | C++ | tst/extraordinary_graphs.cpp | kele/mixed_connectivity | fb038d9ef70a9df3b109fe364df41e98f1775f0e | [
"MIT"
] | null | null | null | tst/extraordinary_graphs.cpp | kele/mixed_connectivity | fb038d9ef70a9df3b109fe364df41e98f1775f0e | [
"MIT"
] | 1 | 2016-01-22T00:25:09.000Z | 2016-01-22T00:25:09.000Z | tst/extraordinary_graphs.cpp | kele/mixed_connectivity | fb038d9ef70a9df3b109fe364df41e98f1775f0e | [
"MIT"
] | null | null | null | #include "extraordinary_graphs.hpp"
std::vector<edge_base_t> petersen_graph_e =
{
{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}, {1, 8}, {2, 6}, {3, 9}, {7, 4}, {0, 5},
{5, 6}, {6, 7}, {7, 8}, {8, 9}, {9, 5}
};
| 26.625 | 83 | 0.450704 | kele |
28e1e600bd4ad9a43ceec5c822d9303ed1ae8683 | 1,111 | hpp | C++ | src/include/duckdb/parser/parsed_data/create_table_info.hpp | RelationalAI-oss/duckdb | a4908ae17de3ac62d42633ada03077b8c3ead7a5 | [
"MIT"
] | 2 | 2020-01-07T17:19:02.000Z | 2020-01-09T22:04:04.000Z | src/include/duckdb/parser/parsed_data/create_table_info.hpp | RelationalAI-oss/duckdb | a4908ae17de3ac62d42633ada03077b8c3ead7a5 | [
"MIT"
] | null | null | null | src/include/duckdb/parser/parsed_data/create_table_info.hpp | RelationalAI-oss/duckdb | a4908ae17de3ac62d42633ada03077b8c3ead7a5 | [
"MIT"
] | null | null | null | //===----------------------------------------------------------------------===//
// DuckDB
//
// parser/parsed_data/create_table_info.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/common/common.hpp"
#include "duckdb/common/unordered_set.hpp"
#include "duckdb/parser/column_definition.hpp"
#include "duckdb/parser/constraint.hpp"
namespace duckdb {
struct CreateTableInfo {
//! Schema name to insert to
string schema;
//! Table name to insert to
string table;
//! List of columns of the table
vector<ColumnDefinition> columns;
//! List of constraints on the table
vector<unique_ptr<Constraint>> constraints;
//! Ignore if the entry already exists, instead of failing
bool if_not_exists = false;
//! Whether or not it is a temporary table
bool temporary = false;
CreateTableInfo() : schema(INVALID_SCHEMA), if_not_exists(false), temporary(false) {
}
CreateTableInfo(string schema, string name) : schema(schema), table(name), if_not_exists(false), temporary(false) {
}
};
} // namespace duckdb
| 29.236842 | 116 | 0.620162 | RelationalAI-oss |
28e56082e85e8c246aeed62c99b3b7589712c39e | 2,418 | hpp | C++ | fon9/auth/AuthBase.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | 21 | 2019-01-29T14:41:46.000Z | 2022-03-11T00:22:56.000Z | fon9/auth/AuthBase.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | null | null | null | fon9/auth/AuthBase.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | 9 | 2019-01-27T14:19:33.000Z | 2022-03-11T06:18:24.000Z | /// \file fon9/auth/AuthBase.hpp
/// \author fonwinz@gmail.com
#ifndef __fon9_auth_AuthBase_hpp__
#define __fon9_auth_AuthBase_hpp__
#include "fon9/auth/AuthBase.h"
#include "fon9/intrusive_ptr.hpp"
#include "fon9/SortedVector.hpp"
#include "fon9/CharVector.hpp"
namespace fon9 { namespace auth {
class fon9_API AuthMgr;
using AuthMgrSP = intrusive_ptr<AuthMgr>;
class fon9_API AuthSession;
using AuthSessionSP = intrusive_ptr<AuthSession>;
class fon9_API RoleMgr;
using RoleMgrSP = intrusive_ptr<RoleMgr>;
using PolicyId = CharVector;
using PolicyName = CharVector;
using RoleId = PolicyId;
using UserId = PolicyId;
fon9_WARN_DISABLE_PADDING;
/// \ingroup auth
/// 認證要求的結果代碼及額外資訊(字串).
struct AuthR {
fon9_Auth_R RCode_;
/// - RCode_ == fon9_Auth_Success, 則此處為成功的額外訊息, 例如: "3天後密碼過期,請盡速更換密碼".
/// - RCode_ == fon9_Auth_NeedsMore, 則此處為 SASL 的 challenge 訊息.
/// - fon9_IsAuthError(RCode_), 則此處為失敗原因.
std::string Info_;
AuthR(fon9_Auth_R rcode = fon9_Auth_EOther) : RCode_{rcode} {
}
AuthR(fon9_Auth_R rcode, std::string info) : RCode_{rcode}, Info_{std::move(info)} {
}
bool IsError() const {
return fon9_IsAuthError(this->RCode_);
}
bool IsSuccess() const {
return !this->IsError();
}
explicit operator bool() const {
return !this->IsError();
}
bool operator!() const {
return this->IsError();
}
};
fon9_MSC_WARN_POP;
/// \ingroup auth
/// 登入成功後根據 RoleId 取得的使用者政策列表.
/// 為了讓 TreeOp::GetIteratorForPod(), TreeOp::GetIteratorForGv() 能夠運行. 所以需提供:
/// - ContainerLowerBound(PolicyKeys& policies, StrView strKeyText);
/// - ContainerFind(PolicyKeys& policies, StrView strKeyText);
/// - 且 PolicyKeys 不可使用 using PolicyKeys = std::map<>; 因為 TreeOp 找不到 namespace fon9::auth;
struct PolicyKeys : public SortedVector<PolicyName, PolicyId> {};
//struct PolicyKeys : public std::map<PolicyName, PolicyId> {};
// std::map<> 與 SortedVector<> 在這兒可以完全交換使用.
inline PolicyKeys::iterator ContainerLowerBound(PolicyKeys& policies, StrView strKeyText) {
return policies.lower_bound(PolicyKeys::key_type::MakeRef(strKeyText));
}
inline PolicyKeys::iterator ContainerFind(PolicyKeys& policies, StrView strKeyText) {
return policies.find(PolicyKeys::key_type::MakeRef(strKeyText));
}
/// \ingroup auth
/// 使用者的角色設定.
struct RoleConfig {
RoleId RoleId_;
PolicyKeys PolicyKeys_;
};
} } // namespaces
#endif//__fon9_auth_AuthBase_hpp__
| 29.487805 | 91 | 0.726634 | fonwin |
28e6ff03e2665d11d7f069f9092db30d81485ba6 | 498 | hpp | C++ | libs/gui/include/sge/gui/renderer/base_ref.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/gui/include/sge/gui/renderer/base_ref.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/gui/include/sge/gui/renderer/base_ref.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_GUI_RENDERER_BASE_REF_HPP_INCLUDED
#define SGE_GUI_RENDERER_BASE_REF_HPP_INCLUDED
#include <sge/gui/renderer/base_fwd.hpp>
#include <fcppt/reference_impl.hpp>
namespace sge::gui::renderer
{
using base_ref = fcppt::reference<sge::gui::renderer::base>;
}
#endif
| 24.9 | 61 | 0.74498 | cpreh |
28e97639efa2d85fd3cd8e4128ea7ca434431415 | 587 | hpp | C++ | lab/lab12/cstereoshape.hpp | YZL24/SUSTech-CS205 | c15e4055b3e260e84e94c8db46b4180448c3619f | [
"MIT"
] | null | null | null | lab/lab12/cstereoshape.hpp | YZL24/SUSTech-CS205 | c15e4055b3e260e84e94c8db46b4180448c3619f | [
"MIT"
] | null | null | null | lab/lab12/cstereoshape.hpp | YZL24/SUSTech-CS205 | c15e4055b3e260e84e94c8db46b4180448c3619f | [
"MIT"
] | null | null | null | #pragma once
#include <iomanip>
#include <iostream>
using namespace std;
class CStereoShape {
static int numberOfObject;
public:
virtual double getArea() const {
cout << "CStereoShape::getArea()" << endl;
return 0.0f;
}
virtual double getVolume() const {
cout << "CStereoShape::getVolume()" << endl;
return 0.0f;
}
virtual void show() const { cout << "CStereoShape::show()" << endl; }
static int getNumOfObject() { return numberOfObject; }
CStereoShape() { numberOfObject++; }
};
int CStereoShape::numberOfObject = 0;
| 22.576923 | 73 | 0.632027 | YZL24 |
28ebaf76052c51cf0c158de0fdade462e2ad0745 | 12,536 | cpp | C++ | FGSMTest.cpp | formal-verification-research/ARFramework | 9be2b7170618da8c46cb10ed9c67adf68fcaac2a | [
"MIT"
] | null | null | null | FGSMTest.cpp | formal-verification-research/ARFramework | 9be2b7170618da8c46cb10ed9c67adf68fcaac2a | [
"MIT"
] | null | null | null | FGSMTest.cpp | formal-verification-research/ARFramework | 9be2b7170618da8c46cb10ed9c67adf68fcaac2a | [
"MIT"
] | null | null | null | #include <iostream>
#include <set>
#include "tensorflow_graph_tools.hpp"
#include "GraphManager.hpp"
#include "grid_tools.hpp"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/core/framework/tensor_util.h"
int main(int argc, char* argv[])
{
std::string graph = "graph.pb";
std::string input_layer = "input_layer";
std::string output_layer = "output_layer";
std::string gradient_layer = "gradient_layer_tmp_placeholder";
std::string granularity_str = "granularity";
std::string verification_radius = "verification radius";
std::string initial_activation = "initial_activation.pb";
std::string root_dir = ".";
std::string class_averages = "class_averages";
std::string label_proto = "label_proto";
std::string label_layer = "label_layer_placeholder";
std::string fgsm_balance_factor_opt = "1.0";
std::string enforce_domain_str = "true";
std::string domain_range_min_str = "0.0";
std::string domain_range_max_str = "1.0";
std::string modified_fgsm_dim_selection = "largest_first";
std::string num_abstractions_str = "1000";
std::string abstraction_strategy_str = "modifiedFGSM";
std::vector<tensorflow::Flag> flag_list = {
tensorflow::Flag("graph", &graph, "path to protobuf graph to be executed"),
tensorflow::Flag("input_layer", &input_layer, "name of input layer"),
tensorflow::Flag("output_layer", &output_layer, "name of output layer"),
tensorflow::Flag("gradient_layer", &gradient_layer, "name of the gradient layer (optional - used for FGSM)"),
tensorflow::Flag("granularity", &granularity_str, "use this option is all dimensions share a discrete range"),
tensorflow::Flag("verification_radius", &verification_radius, "'radius' of hyperrectangle within which safety is to be verified"),
tensorflow::Flag("initial_activation", &initial_activation, "initial tested activation"),
tensorflow::Flag("root_dir", &root_dir, "root_dir"),
tensorflow::Flag("class_averages", &class_averages, "the class averages of the training data (optional - used for FGSM)"),
tensorflow::Flag("label_proto", &label_proto, "protocol buffer of label image corresponding with initial activation"),
tensorflow::Flag("label_layer", &label_layer, "name of label layer"),
tensorflow::Flag("enforce_domain", &enforce_domain_str, "enforce the domain range (true, false)"),
tensorflow::Flag("abstraction_strategy", &abstraction_strategy_str, "abstraction strategy (modifiedFGSM, R+FGSM"),
tensorflow::Flag("domain_range_min", &domain_range_min_str, "lower bound on domain range (default = 0.0)"),
tensorflow::Flag("domain_range_max", &domain_range_max_str, "upper bound on domain range (default = 1.0)"),
tensorflow::Flag("modified_fgsm_dim_selection", &modified_fgsm_dim_selection, "dimension selection strategy to use (gradient_based, intellifeature, largest_first - default)"),
tensorflow::Flag("num_abstractions", &num_abstractions_str, "number of abstractions to generate (adversarial examples)"),
tensorflow::Flag("fgsm_balance_factor", &fgsm_balance_factor_opt, "Balance factor for modified FGSM algorithm (ratio dimensions fgsm/random)")
};
std::string usage = tensorflow::Flags::Usage(argv[0], flag_list);
const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
if (!parse_result)
{
LOG(ERROR) << usage;
return -1;
}
tensorflow::port::InitMain(argv[0], &argc, &argv);
if (argc > 1) {
LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
return -1;
}
const auto enforce_domain = enforce_domain_str == "true";
if(gradient_layer == "gradient_layer_tmp_placeholder")
{
LOG(ERROR) << "must provide gradient layer\n";
return -1;
}
if(granularity_str == "granularity")
{
LOG(ERROR) << "must provided granularity\n";
return -1;
}
if(verification_radius == "verification radius")
{
LOG(ERROR) << "must provide verification radius";
return -1;
}
auto granularity_val = std::atof(granularity_str.c_str());
auto radius = std::atof(verification_radius.c_str());
auto fgsm_balance_factor = std::atof(fgsm_balance_factor_opt.c_str());
auto domain_range_min = std::atof(domain_range_min_str.c_str());
auto domain_range_max = std::atof(domain_range_max_str.c_str());
auto num_abstractions = std::atoi(num_abstractions_str.c_str());
auto graph_path = tensorflow::io::JoinPath(root_dir, graph);
GraphManager gm(graph_path);
if(!gm.ok())
{
LOG(ERROR) << "Could not initialize graph manager at: "
<< graph_path;
return -1;
}
auto initial_activation_path =
tensorflow::io::JoinPath(root_dir, initial_activation);
auto init_act_tensor_status_pair =
GraphManager::ReadBinaryTensorProto(initial_activation_path);
if(!init_act_tensor_status_pair.first)
{
LOG(ERROR)
<< "Could not read initial activation protobuf: "
<< initial_activation_path;
return -1;
}
auto init_act_tensor = init_act_tensor_status_pair.second;
auto init_act_point = graph_tool::tensorToPoint(
init_act_tensor);
std::vector<tensorflow::int64> batch_input_shape(init_act_tensor.dims());
for(auto i = 0u; i < batch_input_shape.size(); ++i)
batch_input_shape[i] = init_act_tensor.dim_size(i);
auto logits_init_activation =
gm.feedThroughModel(
std::bind(graph_tool::makeFeedDict,
input_layer,
init_act_point,
batch_input_shape),
&graph_tool::parseGraphOutToVector,
{output_layer});
if(!gm.ok())
{
LOG(ERROR) << "Error while feeding through model";
exit(1);
}
unsigned orig_class =
graph_tool::getClassOfClassificationVector(logits_init_activation);
std::cout << "Original class: " << orig_class << "\n";
std::vector<long double> granularity(init_act_point.size(),
granularity_val);
std::cout << "Granularity: " << granularity_val << "\n";
std::cout << "Input shape: (";
for(auto&& elem : batch_input_shape)
std::cout << elem << " ";
std::cout << ")\n";
std::cout << "Verification radius: " << radius << "\n";
std::cout << "Root Directory: " << root_dir << "\n";
grid::dimension_selection_strategy_t dimension_selection_strategy =
grid::largestDimFirst;
if(modified_fgsm_dim_selection == "largest_first")
std::cout << "Using largest first dimension selection strategy\n";
auto hasAveragesProto = class_averages != "class_averages";
auto hasLabelProto = label_proto != "label_proto";
auto hasLabelLayer = label_layer != "label_layer_placeholder";
if(!hasLabelProto || !hasLabelLayer)
{
LOG(ERROR) << "Need gradient layer, label proto, and label layer";
return -1;
}
if(modified_fgsm_dim_selection == "random")
{
std::cout << "Using random dimension selection heuristic\n";
dimension_selection_strategy =
grid::randomDimSelection;
}
if(hasAveragesProto && modified_fgsm_dim_selection == "intellifeature")
{
std::cout << "Using Intellifeature\n";
std::string class_averages_path =
tensorflow::io::JoinPath(root_dir, class_averages);
auto class_averages_proto_pair =
GraphManager::ReadBinaryTensorProto(class_averages_path);
if(!class_averages_proto_pair.first)
{
LOG(ERROR) << "Unable to read class averages proto";
return -1;
}
auto averages = graph_tool::tensorToPoints(
class_averages_proto_pair.second);
dimension_selection_strategy =
grid::IntellifeatureDimSelection(
averages,
&grid::l2norm,
orig_class);
}
auto label_tensor_path =
tensorflow::io::JoinPath(root_dir, label_proto);
auto label_tensor_pair =
GraphManager::ReadBinaryTensorProto(label_tensor_path);
if(!label_tensor_pair.first)
{
LOG(ERROR) << "Unable to read label proto";
exit(1);
}
auto label_tensor = label_tensor_pair.second;
std::cout << "FGSM Balance Factor: " << fgsm_balance_factor
<< "\n";
auto grad_func =
[&,label_tensor_copy = label_tensor]
(grid::point const& p) -> grid::point
{
auto createGradientFeedDict =
[&]() -> graph_tool::feed_dict_type_t
{
auto p_tensor =
graph_tool::pointToTensor(p, batch_input_shape);
return {{input_layer, p_tensor},
{label_layer, label_tensor_copy}};
};
auto retVal = gm.feedThroughModel(
createGradientFeedDict,
&graph_tool::parseGraphOutToVector,
{gradient_layer});
if(!gm.ok())
LOG(ERROR) << "Error with model";
return retVal;
};
if(modified_fgsm_dim_selection == "gradient_based")
{
std::cout << "Using gradient_based dimension selection\n";
dimension_selection_strategy =
grid::GradientBasedDimensionSelection(grad_func);
}
grid::region_abstraction_strategy_t abstraction_strategy =
grid::ModifiedFGSMWithFallbackRegionAbstraction(
num_abstractions,
grad_func,
dimension_selection_strategy,
grid::RandomPointRegionAbstraction(1u),
granularity,
fgsm_balance_factor);
if(abstraction_strategy_str == "R+FGSM")
{
abstraction_strategy = grid::RPlusFGSMAbstraction(
num_abstractions,
grad_func,
granularity,
0.1);
}
grid::region orig_region(init_act_point.size());
for(auto i = 0u; i < orig_region.size(); ++i)
{
orig_region[i].first =
init_act_point[i] - radius;
orig_region[i].second =
init_act_point[i] + radius;
}
grid::region domain_range(orig_region.size());
for(auto i = 0u; i < domain_range.size(); ++i)
{
domain_range[i].first = domain_range_min;
domain_range[i].second = domain_range_max;
}
orig_region = grid::snapToDomainRange(orig_region, domain_range);
auto abstractions = abstraction_strategy(orig_region);
std::set<grid::point> unique_abstractions;
for(auto&& pt : abstractions)
{
auto pt_to_add = grid::enforceSnapDiscreteGrid(
pt, init_act_point, granularity);
if(enforce_domain)
{
pt_to_add = grid::snapToDomainRange(
pt_to_add, domain_range);
}
unique_abstractions.insert(pt_to_add);
}
std::cout << "Unique Abstractions: "
<< unique_abstractions.size() << "\n";
auto pointIsSafe = [&](grid::point const& p)
{
auto logits_out = gm.feedThroughModel(
std::bind(graph_tool::makeFeedDict,
input_layer, p, batch_input_shape),
&graph_tool::parseGraphOutToVector,
{output_layer});
if(!gm.ok())
LOG(ERROR) << "GM Error in pointIsSafe";
auto class_out =
graph_tool::getClassOfClassificationVector(
logits_out);
return class_out == orig_class;
};
auto numAdvExamples = 0u;
for(auto&& pt : unique_abstractions)
{
if(pointIsSafe(pt))
continue;
++numAdvExamples;
}
std::cout << "Number Adversarial Examples: "
<< numAdvExamples << "\n";
auto success_rate = (double)numAdvExamples / (double)unique_abstractions.size() * 100.0;
std::cout << "Success Rate: " << success_rate << "\n";
return 0;
}
| 39.05296 | 183 | 0.625718 | formal-verification-research |
28ec806e43af25655d0e07f9fa130d76938f5256 | 17,083 | cpp | C++ | src/main/cpp/smtpappender.cpp | pseiderer/logging-log4cxx | 5fa793b8ae382ec7a3374a190aee2cf81479e6a6 | [
"Apache-2.0"
] | 174 | 2017-04-10T21:29:14.000Z | 2022-03-09T11:38:53.000Z | src/main/cpp/smtpappender.cpp | pseiderer/logging-log4cxx | 5fa793b8ae382ec7a3374a190aee2cf81479e6a6 | [
"Apache-2.0"
] | 58 | 2018-01-11T16:21:24.000Z | 2022-03-21T22:26:09.000Z | src/main/cpp/smtpappender.cpp | pseiderer/logging-log4cxx | 5fa793b8ae382ec7a3374a190aee2cf81479e6a6 | [
"Apache-2.0"
] | 110 | 2017-04-10T21:22:40.000Z | 2022-03-15T13:34:00.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/net/smtpappender.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/stringtokenizer.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/loader.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
#include <apr_strings.h>
#include <vector>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
using namespace log4cxx::spi;
#if LOG4CXX_HAVE_LIBESMTP
#include <auth-client.h>
#include <libesmtp.h>
#endif
namespace log4cxx
{
namespace net
{
//
// The following two classes implement an C++ SMTP wrapper over libesmtp.
// The same signatures could be implemented over different SMTP implementations
// or libesmtp could be combined with libgmime to enable support for non-ASCII
// content.
#if LOG4CXX_HAVE_LIBESMTP
/**
* SMTP Session.
*/
class SMTPSession
{
public:
/**
* Create new instance.
*/
SMTPSession(const LogString& smtpHost,
int smtpPort,
const LogString& smtpUsername,
const LogString& smtpPassword,
Pool& p) : session(0), authctx(0),
user(toAscii(smtpUsername, p)),
pwd(toAscii(smtpPassword, p))
{
auth_client_init();
session = smtp_create_session();
if (session == 0)
{
throw Exception("Could not initialize session.");
}
std::string host(toAscii(smtpHost, p));
host.append(1, ':');
host.append(p.itoa(smtpPort));
smtp_set_server(session, host.c_str());
authctx = auth_create_context();
auth_set_mechanism_flags(authctx, AUTH_PLUGIN_PLAIN, 0);
auth_set_interact_cb(authctx, authinteract, (void*) this);
if (*user || *pwd)
{
smtp_auth_set_context(session, authctx);
}
}
~SMTPSession()
{
smtp_destroy_session(session);
auth_destroy_context(authctx);
}
void send(Pool& p)
{
int status = smtp_start_session(session);
if (!status)
{
size_t bufSize = 128;
char* buf = p.pstralloc(bufSize);
smtp_strerror(smtp_errno(), buf, bufSize);
throw Exception(buf);
}
}
operator smtp_session_t()
{
return session;
}
static char* toAscii(const LogString& str, Pool& p)
{
char* buf = p.pstralloc(str.length() + 1);
char* current = buf;
for (LogString::const_iterator iter = str.begin();
iter != str.end();
iter++)
{
unsigned int c = *iter;
if (c > 0x7F)
{
c = '?';
}
*current++ = c;
}
*current = 0;
return buf;
}
private:
SMTPSession(SMTPSession&);
SMTPSession& operator=(SMTPSession&);
smtp_session_t session;
auth_context_t authctx;
char* user;
char* pwd;
/**
* This method is called if the SMTP server requests authentication.
*/
static int authinteract(auth_client_request_t request, char** result, int fields,
void* arg)
{
SMTPSession* pThis = (SMTPSession*) arg;
for (int i = 0; i < fields; i++)
{
int flag = request[i].flags & 0x07;
if (flag == AUTH_USER)
{
result[i] = pThis->user;
}
else if (flag == AUTH_PASS)
{
result[i] = pThis->pwd;
}
}
return 1;
}
};
/**
* A message in an SMTP session.
*/
class SMTPMessage
{
public:
SMTPMessage(SMTPSession& session,
const LogString& from,
const LogString& to,
const LogString& cc,
const LogString& bcc,
const LogString& subject,
const LogString msg, Pool& p)
{
message = smtp_add_message(session);
body = current = toMessage(msg, p);
messagecbState = 0;
smtp_set_reverse_path(message, toAscii(from, p));
addRecipients(to, "To", p);
addRecipients(cc, "Cc", p);
addRecipients(bcc, "Bcc", p);
if (!subject.empty())
{
smtp_set_header(message, "Subject", toAscii(subject, p));
}
smtp_set_messagecb(message, messagecb, this);
}
~SMTPMessage()
{
}
private:
SMTPMessage(const SMTPMessage&);
SMTPMessage& operator=(const SMTPMessage&);
smtp_message_t message;
const char* body;
const char* current;
int messagecbState;
void addRecipients(const LogString& addresses, const char* field, Pool& p)
{
if (!addresses.empty())
{
char* str = p.pstrdup(toAscii(addresses, p));;
smtp_set_header(message, field, NULL, str);
char* last;
for (char* next = apr_strtok(str, ",", &last);
next;
next = apr_strtok(NULL, ",", &last))
{
smtp_add_recipient(message, next);
}
}
}
static const char* toAscii(const LogString& str, Pool& p)
{
return SMTPSession::toAscii(str, p);
}
/**
* Message bodies can only contain US-ASCII characters and
* CR and LFs can only occur together.
*/
static const char* toMessage(const LogString& str, Pool& p)
{
//
// count the number of carriage returns and line feeds
//
int feedCount = 0;
for (size_t pos = str.find_first_of(LOG4CXX_STR("\n\r"));
pos != LogString::npos;
pos = str.find_first_of(LOG4CXX_STR("\n\r"), ++pos))
{
feedCount++;
}
//
// allocate sufficient space for the modified message
char* retval = p.pstralloc(str.length() + feedCount + 1);
char* current = retval;
char* startOfLine = current;
//
// iterator through message
//
for (LogString::const_iterator iter = str.begin();
iter != str.end();
iter++)
{
unsigned int c = *iter;
//
// replace non-ASCII characters with '?'
//
if (c > 0x7F)
{
*current++ = 0x3F; // '?'
}
else if (c == 0x0A || c == 0x0D)
{
//
// replace any stray CR or LF with CRLF
// reset start of line
*current++ = 0x0D;
*current++ = 0x0A;
startOfLine = current;
LogString::const_iterator next = iter + 1;
if (next != str.end() && (*next == 0x0A || *next == 0x0D))
{
iter++;
}
}
else
{
//
// truncate any lines to 1000 characters (including CRLF)
// as required by RFC.
if (current < startOfLine + 998)
{
*current++ = (char) c;
}
}
}
*current = 0;
return retval;
}
/**
* Callback for message.
*/
static const char* messagecb(void** ctx, int* len, void* arg)
{
*ctx = 0;
const char* retval = 0;
SMTPMessage* pThis = (SMTPMessage*) arg;
// rewind message
if (len == NULL)
{
pThis->current = pThis->body;
}
else
{
// we are asked for headers, but we don't have any
if ((pThis->messagecbState)++ == 0)
{
return NULL;
}
if (pThis->current)
{
*len = strlen(pThis->current);
}
retval = pThis->current;
pThis->current = 0;
}
return retval;
}
};
#endif
class LOG4CXX_EXPORT DefaultEvaluator :
public virtual spi::TriggeringEventEvaluator,
public virtual helpers::Object
{
public:
DECLARE_LOG4CXX_OBJECT(DefaultEvaluator)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(DefaultEvaluator)
LOG4CXX_CAST_ENTRY(spi::TriggeringEventEvaluator)
END_LOG4CXX_CAST_MAP()
DefaultEvaluator();
/**
Is this <code>event</code> the e-mail triggering event?
<p>This method returns <code>true</code>, if the event level
has ERROR level or higher. Otherwise it returns
<code>false</code>.
*/
virtual bool isTriggeringEvent(const spi::LoggingEventPtr& event);
private:
DefaultEvaluator(const DefaultEvaluator&);
DefaultEvaluator& operator=(const DefaultEvaluator&);
}; // class DefaultEvaluator
}
}
IMPLEMENT_LOG4CXX_OBJECT(DefaultEvaluator)
IMPLEMENT_LOG4CXX_OBJECT(SMTPAppender)
DefaultEvaluator::DefaultEvaluator()
{
}
bool DefaultEvaluator::isTriggeringEvent(const spi::LoggingEventPtr& event)
{
return event->getLevel()->isGreaterOrEqual(Level::getError());
}
SMTPAppender::SMTPAppender()
: smtpPort(25), bufferSize(512), locationInfo(false), cb(bufferSize),
evaluator(new DefaultEvaluator())
{
}
/**
Use <code>evaluator</code> passed as parameter as the
TriggeringEventEvaluator for this SMTPAppender. */
SMTPAppender::SMTPAppender(spi::TriggeringEventEvaluatorPtr evaluator)
: smtpPort(25), bufferSize(512), locationInfo(false), cb(bufferSize),
evaluator(evaluator)
{
}
SMTPAppender::~SMTPAppender()
{
finalize();
}
bool SMTPAppender::requiresLayout() const
{
return true;
}
LogString SMTPAppender::getFrom() const
{
return from;
}
void SMTPAppender::setFrom(const LogString& newVal)
{
from = newVal;
}
LogString SMTPAppender::getSubject() const
{
return subject;
}
void SMTPAppender::setSubject(const LogString& newVal)
{
subject = newVal;
}
LogString SMTPAppender::getSMTPHost() const
{
return smtpHost;
}
void SMTPAppender::setSMTPHost(const LogString& newVal)
{
smtpHost = newVal;
}
int SMTPAppender::getSMTPPort() const
{
return smtpPort;
}
void SMTPAppender::setSMTPPort(int newVal)
{
smtpPort = newVal;
}
bool SMTPAppender::getLocationInfo() const
{
return locationInfo;
}
void SMTPAppender::setLocationInfo(bool newVal)
{
locationInfo = newVal;
}
LogString SMTPAppender::getSMTPUsername() const
{
return smtpUsername;
}
void SMTPAppender::setSMTPUsername(const LogString& newVal)
{
smtpUsername = newVal;
}
LogString SMTPAppender::getSMTPPassword() const
{
return smtpPassword;
}
void SMTPAppender::setSMTPPassword(const LogString& newVal)
{
smtpPassword = newVal;
}
void SMTPAppender::setOption(const LogString& option,
const LogString& value)
{
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize")))
{
setBufferSize(OptionConverter::toInt(value, 512));
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("EVALUATORCLASS"), LOG4CXX_STR("evaluatorclass")))
{
setEvaluatorClass(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FROM"), LOG4CXX_STR("from")))
{
setFrom(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPHOST"), LOG4CXX_STR("smtphost")))
{
setSMTPHost(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPUSERNAME"), LOG4CXX_STR("smtpusername")))
{
setSMTPUsername(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPPASSWORD"), LOG4CXX_STR("smtppassword")))
{
setSMTPPassword(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SUBJECT"), LOG4CXX_STR("subject")))
{
setSubject(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("TO"), LOG4CXX_STR("to")))
{
setTo(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("CC"), LOG4CXX_STR("cc")))
{
setCc(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BCC"), LOG4CXX_STR("bcc")))
{
setBcc(value);
}
else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPPORT"), LOG4CXX_STR("smtpport")))
{
setSMTPPort(OptionConverter::toInt(value, 25));
}
else
{
AppenderSkeleton::setOption(option, value);
}
}
bool SMTPAppender::asciiCheck(const LogString& value, const LogString& field)
{
for (LogString::const_iterator iter = value.begin();
iter != value.end();
iter++)
{
if (0x7F < (unsigned int) *iter)
{
LogLog::warn(field + LOG4CXX_STR(" contains non-ASCII character"));
return false;
}
}
return true;
}
/**
Activate the specified options, such as the smtp host, the
recipient, from, etc. */
void SMTPAppender::activateOptions(Pool& p)
{
bool activate = true;
if (layout == 0)
{
errorHandler->error(LOG4CXX_STR("No layout set for appender named [") + name + LOG4CXX_STR("]."));
activate = false;
}
if (evaluator == 0)
{
errorHandler->error(LOG4CXX_STR("No TriggeringEventEvaluator is set for appender [") +
name + LOG4CXX_STR("]."));
activate = false;
}
if (smtpHost.empty())
{
errorHandler->error(LOG4CXX_STR("No smtpHost is set for appender [") +
name + LOG4CXX_STR("]."));
activate = false;
}
if (to.empty() && cc.empty() && bcc.empty())
{
errorHandler->error(LOG4CXX_STR("No recipient address is set for appender [") +
name + LOG4CXX_STR("]."));
activate = false;
}
activate &= asciiCheck(to, LOG4CXX_STR("to"));
activate &= asciiCheck(cc, LOG4CXX_STR("cc"));
activate &= asciiCheck(bcc, LOG4CXX_STR("bcc"));
activate &= asciiCheck(from, LOG4CXX_STR("from"));
#if !LOG4CXX_HAVE_LIBESMTP
errorHandler->error(LOG4CXX_STR("log4cxx built without SMTP support."));
activate = false;
#endif
if (activate)
{
AppenderSkeleton::activateOptions(p);
}
}
/**
Perform SMTPAppender specific appending actions, mainly adding
the event to a cyclic buffer and checking if the event triggers
an e-mail to be sent. */
void SMTPAppender::append(const spi::LoggingEventPtr& event, Pool& p)
{
if (!checkEntryConditions())
{
return;
}
LogString ndc;
event->getNDC(ndc);
event->getThreadName();
// Get a copy of this thread's MDC.
event->getMDCCopy();
cb.add(event);
if (evaluator->isTriggeringEvent(event))
{
sendBuffer(p);
}
}
/**
This method determines if there is a sense in attempting to append.
<p>It checks whether there is a set output target and also if
there is a set layout. If these checks fail, then the boolean
value <code>false</code> is returned. */
bool SMTPAppender::checkEntryConditions()
{
#if LOG4CXX_HAVE_LIBESMTP
if ((to.empty() && cc.empty() && bcc.empty()) || from.empty() || smtpHost.empty())
{
errorHandler->error(LOG4CXX_STR("Message not configured."));
return false;
}
if (evaluator == 0)
{
errorHandler->error(LOG4CXX_STR("No TriggeringEventEvaluator is set for appender [") +
name + LOG4CXX_STR("]."));
return false;
}
if (layout == 0)
{
errorHandler->error(LOG4CXX_STR("No layout set for appender named [") + name + LOG4CXX_STR("]."));
return false;
}
return true;
#else
return false;
#endif
}
void SMTPAppender::close()
{
this->closed = true;
}
LogString SMTPAppender::getTo() const
{
return to;
}
void SMTPAppender::setTo(const LogString& addressStr)
{
to = addressStr;
}
LogString SMTPAppender::getCc() const
{
return cc;
}
void SMTPAppender::setCc(const LogString& addressStr)
{
cc = addressStr;
}
LogString SMTPAppender::getBcc() const
{
return bcc;
}
void SMTPAppender::setBcc(const LogString& addressStr)
{
bcc = addressStr;
}
/**
Send the contents of the cyclic buffer as an e-mail message.
*/
void SMTPAppender::sendBuffer(Pool& p)
{
#if LOG4CXX_HAVE_LIBESMTP
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize on 'cb'.
try
{
LogString sbuf;
layout->appendHeader(sbuf, p);
int len = cb.length();
for (int i = 0; i < len; i++)
{
LoggingEventPtr event = cb.get();
layout->format(sbuf, event, p);
}
layout->appendFooter(sbuf, p);
SMTPSession session(smtpHost, smtpPort, smtpUsername, smtpPassword, p);
SMTPMessage message(session, from, to, cc,
bcc, subject, sbuf, p);
session.send(p);
}
catch (std::exception& e)
{
LogLog::error(LOG4CXX_STR("Error occured while sending e-mail notification."), e);
}
#endif
}
/**
Returns value of the <b>EvaluatorClass</b> option.
*/
LogString SMTPAppender::getEvaluatorClass()
{
return evaluator == 0 ? LogString() : evaluator->getClass().getName();
}
log4cxx::spi::TriggeringEventEvaluatorPtr SMTPAppender::getEvaluator() const
{
return evaluator;
}
void SMTPAppender::setEvaluator(log4cxx::spi::TriggeringEventEvaluatorPtr& trigger)
{
evaluator = trigger;
}
/**
The <b>BufferSize</b> option takes a positive integer
representing the maximum number of logging events to collect in a
cyclic buffer. When the <code>BufferSize</code> is reached,
oldest events are deleted as new events are added to the
buffer. By default the size of the cyclic buffer is 512 events.
*/
void SMTPAppender::setBufferSize(int sz)
{
this->bufferSize = sz;
cb.resize(sz);
}
/**
The <b>EvaluatorClass</b> option takes a string value
representing the name of the class implementing the {@link
TriggeringEventEvaluator} interface. A corresponding object will
be instantiated and assigned as the triggering event evaluator
for the SMTPAppender.
*/
void SMTPAppender::setEvaluatorClass(const LogString& value)
{
ObjectPtr obj = ObjectPtr(Loader::loadClass(value).newInstance());
evaluator = log4cxx::cast<TriggeringEventEvaluator>(obj);
}
| 21.596713 | 111 | 0.684891 | pseiderer |
28ed5bb5fe4494fe35cc39a2cfad45a8903c559f | 9,256 | cpp | C++ | src/easylib.cpp | orgtechservice/libmaycloud | b6e58e637160d32ecf022ba2e2ae1b243597bc28 | [
"MIT"
] | 4 | 2020-06-27T18:30:17.000Z | 2020-07-23T17:39:15.000Z | src/easylib.cpp | orgtechservice/libmaycloud | b6e58e637160d32ecf022ba2e2ae1b243597bc28 | [
"MIT"
] | null | null | null | src/easylib.cpp | orgtechservice/libmaycloud | b6e58e637160d32ecf022ba2e2ae1b243597bc28 | [
"MIT"
] | null | null | null | #include "maycloud/easylib.h"
#include <unistd.h>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
EasyVector explode(const std::string &delimiter, const std::string &str) {
EasyVector result;
int length = str.length();
int delimiter_length = delimiter.length();
if(delimiter_length==0) return result;
int i = 0;
int k = 0;
while(i < length) {
int j = 0;
while((i + j < length) && (j < delimiter_length) && (str[i + j] == delimiter[j])) j++;
if(j == delimiter_length) {
result.push_back(str.substr(k, i - k));
i += delimiter_length;
k = i;
} else {
i ++;
}
}
result.push_back(str.substr(k, i - k));
return result;
}
std::string implode(const std::string &sep, const std::list<std::string> &list)
{
std::string result;
std::list<std::string>::const_iterator it = list.begin();
if ( it == list.end() ) return result;
result = *it;
++it;
while ( it != list.end() )
{
result += sep + *it;
++it;
}
return result;
}
/**
* Вернуть переменные окружения в виде ассоциативного массива
*/
EasyRow easyEnviron(char **envp)
{
EasyRow env;
for(; *envp; envp++)
{
char *line = *envp;
char *x = strchr(line, '=');
if ( x )
{
env[ std::string(line, x) ] = x + 1;
}
else
{
env[line] = "";
}
}
return env;
}
/**
* Вернуть переменные окружения в виде ассоциативного массива
*/
EasyRow easyEnviron()
{
return easyEnviron(environ);
}
/**
* Распарсить команду, представленную в виде строки, в
* набор аргументов EasyVector.
*
* TODO штука недотестирована, но для работы виртуалок должно хватить.
*
* @param args выходной набор аргументов
*/
void parseCmdString(const std::string &cmd, EasyVector& args)
{
std::size_t pos = 0;
bool open = false;
char opening = 0;
std::string arg;
while(cmd[pos] != 0)
{
if(cmd[pos] == '\'' or cmd[pos] == '\"')
{
if(pos == 0 or cmd[pos - 1] != '\\')
{
if(!open)
{
opening = cmd[pos];
open = true;
pos++;
continue;
}
else
{
if(cmd[pos] == opening)
{
opening = 0;
open = false;
pos++;
continue;
}
}
}
}
if(cmd[pos] == ' ')
{
if(!open)
{
args.append(arg);
arg = "";
}
else arg += cmd[pos];
}
else arg += cmd[pos];
pos++;
}
args.append(arg);
}
int easyExec(const std::string &filename, EasyVector args, char **envp)
{
typedef char * const *argv_t;
const char **argv;
int argc = args.size();
argv = new const char*[argc+1];
for(int i = 0; i < argc; i++)
{
argv[i] = args[i].c_str();
}
argv[argc] = 0;
return execve(filename.c_str(), (argv_t)argv, (argv_t)envp);
}
/**
* Вызов exec()
*
* переменные окружения наследуются из текущегое процесса, из переменной environ
*/
int easyExec(const std::string &filename, EasyVector args)
{
return easyExec(filename, args, environ);
}
/**
* Вызов exec()
*
* Переменные окружения задаются в виде списка строк вида "KEY=value"
*/
int easyExec(const std::string &filename, EasyVector args, EasyVector env)
{
char **envp;
int envc = env.size();
envp = new char*[envc+1];
for(int i = 0; i < envc; i++)
{
envp[i] = const_cast<char*>(env[i].c_str());
}
envp[envc] = 0;
return easyExec(filename, args, envp);
}
/**
* Вызов exec()
*
* Переменные окружения задаются в виде ассоциативного массива
*/
int easyExec(const std::string &filename, EasyVector args, EasyRow env)
{
EasyVector e;
for(EasyRow::const_iterator it = env.begin(); it != env.end(); ++it)
{
e.append(it->first + "=" + it->second);
}
return easyExec(filename, args, e);
}
/**
* Получить вывод команды командной строки
*/
std::string getCmdOutput(const std::string& cmd) {
char buffer[512];
std::string result;
FILE *pipe = popen(cmd.c_str(), "r");
if (!pipe) {
std::cerr << "getCmdOutput(" + cmd + "): popen() failed\n";
return "";
}
while (fgets(buffer, sizeof buffer, pipe) != NULL) {
result += buffer;
}
pclose(pipe);
return result;
}
bool sendCmd(const std::string &cmd) {
return !system(cmd.c_str());
}
bool sendCmd(const std::string &cmd, const std::string &error_message) {
if (!system(cmd.c_str())) {
return true;
} else {
std::cerr << error_message << '\n';
return false;
}
}
bool sendCmdLog(const std::string &cmd) {
if (!system(cmd.c_str())) {
logger.information(cmd.c_str());
return true;
} else {
return false;
}
}
bool sendCmdLog(const std::string &cmd, const std::string &success_log_message) {
if (!system(cmd.c_str())) {
logger.information(success_log_message.c_str());
return true;
} else {
return false;
}
}
bool sendCmdLog(const std::string &cmd, const std::string &error_message, const std::string &success_log_message) {
if (!system(cmd.c_str())) {
logger.information(success_log_message.c_str());
return true;
} else {
std::cerr << error_message << '\n';
return false;
}
}
static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* Раскодировать из base64
* © https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
*/
std::string base64_decode(const std::string &encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while(in_len -- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i ++] = encoded_string[in_]; in_ ++;
if(i == 4) {
for(i = 0; i < 4; i ++) char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for(i = 0; (i < 3); i ++) ret += char_array_3[i];
i = 0;
}
}
if(i) {
for(j = i; j < 4; j ++) char_array_4[j] = 0;
for(j = 0; j < 4; j ++) char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
/**
* Locale-independent conversion of ASCII characters to lowercase.
*/
int av_tolower(int c) {
if (c >= 'A' && c <= 'Z') c ^= 0x20;
return c;
}
/**
* Decodes an URL from its percent-encoded form back into normal
* representation. This function returns the decoded URL in a string.
* The URL to be decoded does not necessarily have to be encoded but
* in that case the original string is duplicated.
*
* @param url a string to be decoded.
* @return new string with the URL decoded or NULL if decoding failed.
* Note that the returned string should be explicitly freed when not
* used anymore.
*/
char *urldecode(const char *url)
{
int s = 0, d = 0, url_len = 0;
char c;
char *dest = NULL;
if(!url) return NULL;
url_len = strlen(url) + 1;
dest = (char *) malloc(url_len);
if(!dest) return NULL;
while(s < url_len) {
c = url[s++];
if(c == '%' && s + 2 < url_len) {
char c2 = url[s ++];
char c3 = url[s ++];
if(isxdigit(c2) && isxdigit(c3)) {
c2 = tolower(c2);
c3 = tolower(c3);
if(c2 <= '9')
c2 = c2 - '0';
else
c2 = c2 - 'a' + 10;
if(c3 <= '9')
c3 = c3 - '0';
else
c3 = c3 - 'a' + 10;
dest[d ++] = 16 * c2 + c3;
} else { /* %zz or something other invalid */
dest[d ++] = c;
dest[d ++] = c2;
dest[d ++] = c3;
}
} else if(c == '+') {
dest[d ++] = ' ';
} else {
dest[d ++] = c;
}
}
return dest;
}
std::string urldecode(const std::string &url) {
char *buf = urldecode(url.c_str());
std::string result(buf);
free(buf);
return result;
}
std::string trim(const std::string &s) {
auto wsfront=std::find_if_not(s.begin(),s.end(),[](int c){return std::isspace(c);});
auto wsback=std::find_if_not(s.rbegin(),s.rend(),[](int c){return std::isspace(c);}).base();
return (wsback<=wsfront ? std::string() : std::string(wsfront,wsback));
}
std::string regexEscape(const std::string &s) {
std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s])" };
return std::regex_replace(s, specialChars, R"(\$&)");
}
bool setPidFile(const char* fn) {
FILE* f = fopen(fn, "w+");
if(!f) {
perror("Can't create PID-file");
return false;
}
fprintf(f, "%u", getpid());
fclose(f);
return true;
}
bool fileExists(const std::string& path) {
return std::ifstream(path).good();
}
bool directoryExists(const std::string &path) {
DIR *dir;
if ((dir = opendir(path.c_str())) != NULL) {
closedir(dir);
return true;
} else {
return false;
}
}
/**
* Вернуть время в микросекундах
*/
double microtime() {
struct timeval time;
gettimeofday(&time, NULL);
return (((unsigned long long) time.tv_sec * 1000000) + time.tv_usec) / 1000000.0;
}
void strReplace(std::string &subject, const std::string &search, const std::string &replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
| 21.084282 | 115 | 0.60901 | orgtechservice |
28ee566db50cf6329ae9e711cd9a8c026c41acb5 | 2,722 | cpp | C++ | 001BlankGUI/Middlewares/ST/touchgfx/framework/source/touchgfx/widgets/canvas/AbstractPainterABGR2222.cpp | fjpolo/STM23F746Disco-Playground | 446e8cd45b6ab3d771a782977e7630cf92a01a88 | [
"MIT"
] | null | null | null | 001BlankGUI/Middlewares/ST/touchgfx/framework/source/touchgfx/widgets/canvas/AbstractPainterABGR2222.cpp | fjpolo/STM23F746Disco-Playground | 446e8cd45b6ab3d771a782977e7630cf92a01a88 | [
"MIT"
] | null | null | null | 001BlankGUI/Middlewares/ST/touchgfx/framework/source/touchgfx/widgets/canvas/AbstractPainterABGR2222.cpp | fjpolo/STM23F746Disco-Playground | 446e8cd45b6ab3d771a782977e7630cf92a01a88 | [
"MIT"
] | null | null | null | /******************************************************************************
* Copyright (c) 2018(-2021) STMicroelectronics.
* All rights reserved.
*
* This file is part of the TouchGFX 4.17.0 distribution.
*
* This software is licensed under terms that can be found in the LICENSE file in
* the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
*******************************************************************************/
#include <touchgfx/hal/Types.hpp>
#include <touchgfx/lcd/LCD.hpp>
#include <touchgfx/widgets/canvas/AbstractPainterABGR2222.hpp>
#include <platform/driver/lcd/LCD8bpp_ABGR2222.hpp>
namespace touchgfx
{
void AbstractPainterABGR2222::render(uint8_t* ptr,
int x,
int xAdjust,
int y,
unsigned count,
const uint8_t* covers)
{
uint8_t* p = ptr + (x + xAdjust);
const uint8_t* const p_lineend = p + count;
currentX = x + areaOffsetX;
currentY = y + areaOffsetY;
if (renderInit())
{
do
{
uint8_t red, green, blue, alpha;
if (renderNext(red, green, blue, alpha))
{
const uint8_t combinedAlpha = LCD::div255((*covers) * LCD::div255(alpha * widgetAlpha));
if (combinedAlpha == 0xFF) // max alpha=255 on "*covers" and max alpha=255 on "widgetAlpha"
{
// Render a solid pixel
renderPixel(p, red, green, blue);
}
else
{
const uint8_t ialpha = 0xFF - combinedAlpha;
const uint8_t p_red = LCD8bpp_ABGR2222::getRedFromNativeColor(*p);
const uint8_t p_green = LCD8bpp_ABGR2222::getGreenFromNativeColor(*p);
const uint8_t p_blue = LCD8bpp_ABGR2222::getBlueFromNativeColor(*p);
renderPixel(p,
LCD::div255(red * combinedAlpha + p_red * ialpha),
LCD::div255(green * combinedAlpha + p_green * ialpha),
LCD::div255(blue * combinedAlpha + p_blue * ialpha));
}
}
covers++;
p++;
currentX++;
} while (p < p_lineend);
}
}
void AbstractPainterABGR2222::renderPixel(uint8_t* p, uint8_t red, uint8_t green, uint8_t blue)
{
*p = LCD8bpp_ABGR2222::getNativeColorFromRGB(red, green, blue);
}
} // namespace touchgfx
| 38.885714 | 108 | 0.495224 | fjpolo |
28ef3385331649833bfc4544d0747c9869557dea | 1,628 | cpp | C++ | cpp/oneapi/dal/algo/subgraph_isomorphism/graph_matching_types.cpp | PivovarA/oneDAL | 79bbe88fb3904c4afc60c5ae900f6199e5b44425 | [
"Apache-2.0"
] | null | null | null | cpp/oneapi/dal/algo/subgraph_isomorphism/graph_matching_types.cpp | PivovarA/oneDAL | 79bbe88fb3904c4afc60c5ae900f6199e5b44425 | [
"Apache-2.0"
] | 12 | 2019-04-30T11:57:33.000Z | 2021-01-15T14:06:49.000Z | cpp/oneapi/dal/algo/subgraph_isomorphism/graph_matching_types.cpp | PivovarA/oneDAL | 79bbe88fb3904c4afc60c5ae900f6199e5b44425 | [
"Apache-2.0"
] | 2 | 2019-04-30T09:06:05.000Z | 2019-08-15T06:39:47.000Z | /*******************************************************************************
* Copyright 2021 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "oneapi/dal/algo/subgraph_isomorphism/graph_matching_types.hpp"
namespace oneapi::dal::preview {
namespace subgraph_isomorphism {
class detail::graph_matching_result_impl : public base {
public:
table vertex_match;
std::int64_t match_count;
};
using detail::graph_matching_result_impl;
graph_matching_result::graph_matching_result() : impl_(new graph_matching_result_impl()) {}
graph_matching_result::graph_matching_result(const table& vertex_match, std::int64_t match_count)
: impl_(new graph_matching_result_impl()) {
impl_->vertex_match = vertex_match;
impl_->match_count = match_count;
}
table graph_matching_result::get_vertex_match() const {
return impl_->vertex_match;
}
int64_t graph_matching_result::get_match_count() const {
return impl_->match_count;
}
} // namespace subgraph_isomorphism
} // namespace oneapi::dal::preview
| 34.638298 | 97 | 0.697174 | PivovarA |
28f1af2a8ecdc8fde3b212c997be7750c3d2a561 | 4,474 | cpp | C++ | src/App.cpp | JadedCtrl/Calendar | 12e1362b7b1261e3d233c11c1096462e4cb8b15a | [
"MIT"
] | 20 | 2017-08-29T09:01:26.000Z | 2021-12-14T13:43:18.000Z | src/App.cpp | JadedCtrl/Calendar | 12e1362b7b1261e3d233c11c1096462e4cb8b15a | [
"MIT"
] | 78 | 2017-08-29T18:08:24.000Z | 2022-01-17T17:45:23.000Z | src/App.cpp | JadedCtrl/Calendar | 12e1362b7b1261e3d233c11c1096462e4cb8b15a | [
"MIT"
] | 25 | 2017-09-03T07:03:18.000Z | 2022-03-11T06:29:32.000Z | /*
* Copyight 2017 Akshay Agarwal, agarwal.akshay.akshay8@gmail.com
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "App.h"
#include <AboutWindow.h>
#include <Catalog.h>
#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <FindDirectory.h>
#include <LocaleRoster.h>
#include <NodeInfo.h>
#include <locale.h>
#include "EventWindow.h"
#include "EventSyncWindow.h"
#include "CategoryWindow.h"
#include "MainWindow.h"
#include "Preferences.h"
#include "PreferenceWindow.h"
const char* kAppName = B_TRANSLATE_SYSTEM_NAME("Calendar");
const char* kSignature = "application/x-vnd.calendar";
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "App"
App::App()
:
BApplication(kSignature),
fPreferenceWindow(NULL),
fCategoryWindow(NULL),
fPreferences(NULL),
fEventSyncWindow(NULL)
{
BPath settingsPath;
find_directory(B_USER_SETTINGS_DIRECTORY, &settingsPath);
settingsPath.Append(kAppName);
BDirectory preferencesDir(settingsPath.Path());
if(preferencesDir.InitCheck() == B_ENTRY_NOT_FOUND) {
preferencesDir.CreateDirectory(settingsPath.Path(), &preferencesDir);
}
fPreferencesFile.SetTo(&preferencesDir, "settings");
fPreferences = new Preferences();
fPreferences->Load(fPreferencesFile.Path());
fPreferences->fSettingsPath = settingsPath;
fMainWindow = new MainWindow();
fMainWindow->Show();
}
App::~App()
{
fPreferences->Save(fPreferencesFile.Path());
delete fPreferences;
}
void
App::AboutRequested()
{
const char* authors[] = {
"Akshay Agarwal",
"Humdinger",
"Jaidyn Levesque",
"malbx",
"Fredrik Modéen",
"Bach Nguyen",
NULL
};
BAboutWindow* aboutW = new BAboutWindow(kAppName, kSignature);
aboutW->AddDescription(B_TRANSLATE(
"A calendar application to manage your appointments."));
aboutW->AddCopyright(2017, "Akshay Agarwal");
aboutW->AddAuthors(authors);
aboutW->Show();
}
bool
App::QuitRequested()
{
fPreferences->fMainWindowRect = fMainWindow->Frame();
if (fMainWindow->Lock())
fMainWindow->Quit();
return true;
}
Preferences*
App::GetPreferences()
{
return fPreferences;
}
MainWindow*
App::mainWindow()
{
return fMainWindow;
}
CategoryWindow*
App::categoryWindow()
{
return fCategoryWindow;
}
void
App::MessageReceived(BMessage* message)
{
switch(message->what) {
case kMenuAppPref:
{
if (fPreferenceWindow == NULL) {
fPreferenceWindow = new PreferenceWindow(fMainWindow->Frame(),
fPreferences);
fPreferenceWindow->Show();
}
fPreferenceWindow->Activate();
break;
}
case kMenuCategoryEdit:
{
if (fCategoryWindow == NULL) {
fCategoryWindow = new CategoryWindow();
fCategoryWindow->Show();
}
fCategoryWindow->Activate();
break;
}
case kCategoryWindowQuitting:
fCategoryWindow = NULL;
break;
case kMenuSyncGCAL:
{
if (fEventSyncWindow == NULL) {
fEventSyncWindow = new EventSyncWindow();
fEventSyncWindow->Show();
}
fEventSyncWindow->Activate();
break;
}
case kEventSyncWindowQuitting:
fEventSyncWindow = NULL;
break;
case kPreferenceWindowQuitting:
fPreferenceWindow = NULL;
break;
case kAppPreferencesChanged:
fMainWindow->PostMessage(message);
break;
case B_REFS_RECEIVED:
RefsReceived(message);
break;
case B_LOCALE_CHANGED:
fMainWindow->PostMessage(message);
break;
default: {
BApplication::MessageReceived(message);
break;
}
}
}
void
App::RefsReceived(BMessage* message)
{
int i = 0;
entry_ref ref;
BFile file;
BNodeInfo info;
char type[B_FILE_NAME_LENGTH];
while (message->HasRef("refs", i)) {
BMessage msg = BMessage(B_REFS_RECEIVED);
message->FindRef("refs", i++, &ref);
msg.AddRef("refs", &ref);
file.SetTo(&ref, B_READ_ONLY);
info.SetTo(&file);
info.GetType(type);
if (BString(type) == BString("application/x-calendar-event") ||
BString(type) == BString("text/calendar"))
fMainWindow->PostMessage(&msg);
else if (BString(type) == BString("application/x-calendar-category")) {
MessageReceived(new BMessage(kMenuCategoryEdit));
fCategoryWindow->PostMessage(&msg);
}
}
}
void
App::ArgvReceived(int32 argc, char** argv)
{
BMessage message(B_REFS_RECEIVED);
for (int32 i = 1; i < argc; i++) {
BEntry entry(argv[i]);
entry_ref ref;
if (entry.Exists() && entry.GetRef(&ref) == B_OK)
message.AddRef("refs", &ref);
}
RefsReceived(&message);
}
int
main()
{
setlocale(LC_ALL, "");
App app;
app.Run();
return 0;
}
| 18.411523 | 73 | 0.706974 | JadedCtrl |
28f4fb502eb130a0f4ce1b0757d889711376a595 | 178 | cc | C++ | src/mob/hostile/Chaos.cc | kallentu/pathos | 1914edbccc98baef79d98fb065119230072ac40d | [
"MIT"
] | 7 | 2019-05-09T15:38:55.000Z | 2021-12-07T03:13:29.000Z | src/mob/hostile/Chaos.cc | kallentu/pathos | 1914edbccc98baef79d98fb065119230072ac40d | [
"MIT"
] | 1 | 2019-06-20T03:01:18.000Z | 2019-06-20T03:01:18.000Z | src/mob/hostile/Chaos.cc | kallentu/pathos | 1914edbccc98baef79d98fb065119230072ac40d | [
"MIT"
] | null | null | null | #include "mob/hostile/Chaos.h"
#include "mob/player/Player.h"
using namespace Pathos;
void Chaos::beKilledBy(Player &p) {
p.addExperience(5000000);
p.addDrachma(250000);
}
| 17.8 | 35 | 0.730337 | kallentu |
28f6f491695166664efa66bcb10d2dc9fc6cb828 | 39,107 | hh | C++ | include/qpdf/QPDFObjectHandle.hh | ams-tschoening/qpdf | 8f06da75343a5e970ff7a6f275c319172e6292d0 | [
"Apache-2.0"
] | null | null | null | include/qpdf/QPDFObjectHandle.hh | ams-tschoening/qpdf | 8f06da75343a5e970ff7a6f275c319172e6292d0 | [
"Apache-2.0"
] | null | null | null | include/qpdf/QPDFObjectHandle.hh | ams-tschoening/qpdf | 8f06da75343a5e970ff7a6f275c319172e6292d0 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2005-2019 Jay Berkenbilt
//
// This file is part of qpdf.
//
// 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.
//
// Versions of qpdf prior to version 7 were released under the terms
// of version 2.0 of the Artistic License. At your option, you may
// continue to consider qpdf to be licensed under those terms. Please
// see the manual for additional information.
#ifndef QPDFOBJECTHANDLE_HH
#define QPDFOBJECTHANDLE_HH
#include <qpdf/DLL.h>
#include <qpdf/Types.h>
#include <qpdf/Constants.h>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <qpdf/QPDFObjGen.hh>
#include <qpdf/PointerHolder.hh>
#include <qpdf/Buffer.hh>
#include <qpdf/InputSource.hh>
#include <qpdf/QPDFTokenizer.hh>
#include <qpdf/QPDFObject.hh>
class Pipeline;
class QPDF;
class QPDF_Dictionary;
class QPDF_Array;
class QPDFTokenizer;
class QPDFExc;
class Pl_QPDFTokenizer;
class QPDFObjectHandle
{
public:
// This class is used by replaceStreamData. It provides an
// alternative way of associating stream data with a stream. See
// comments on replaceStreamData and newStream for additional
// details.
class QPDF_DLL_CLASS StreamDataProvider
{
public:
QPDF_DLL
virtual ~StreamDataProvider()
{
}
// The implementation of this function must write stream data
// to the given pipeline. The stream data must conform to
// whatever filters are explicitly associated with the stream.
// QPDFWriter may, in some cases, add compression, but if it
// does, it will update the filters as needed. Every call to
// provideStreamData for a given stream must write the same
// data. The object ID and generation passed to this method
// are those that belong to the stream on behalf of which the
// provider is called. They may be ignored or used by the
// implementation for indexing or other purposes. This
// information is made available just to make it more
// convenient to use a single StreamDataProvider object to
// provide data for multiple streams.
virtual void provideStreamData(int objid, int generation,
Pipeline* pipeline) = 0;
};
// The TokenFilter class provides a way to filter content streams
// in a lexically aware fashion. TokenFilters can be attached to
// streams using the addTokenFilter or addContentTokenFilter
// methods or can be applied on the spot by filterPageContents.
// You may also use Pl_QPDFTokenizer directly if you need full
// control.
//
// The handleToken method is called for each token, including the
// eof token, and then handleEOF is called at the very end.
// Handlers may call write (or writeToken) to pass data
// downstream. Please see examples/pdf-filter-tokens.cc and
// examples/pdf-count-strings.cc for examples of using
// TokenFilters.
//
// Please note that when you call token.getValue() on a token of
// type tt_string, you get the string value without any
// delimiters. token.getRawValue() will return something suitable
// for being written to output, or calling writeToken with a
// string token will also work. The correct way to construct a
// string token that would write the literal value (str) is
// QPDFTokenizer::Token(QPDFTokenizer::tt_string, "str").
class QPDF_DLL_CLASS TokenFilter
{
public:
QPDF_DLL
TokenFilter()
{
}
QPDF_DLL
virtual ~TokenFilter()
{
}
virtual void handleToken(QPDFTokenizer::Token const&) = 0;
QPDF_DLL
virtual void handleEOF();
class PipelineAccessor
{
friend class Pl_QPDFTokenizer;
private:
static void setPipeline(TokenFilter* f, Pipeline* p)
{
f->setPipeline(p);
}
};
protected:
QPDF_DLL
void write(char const* data, size_t len);
QPDF_DLL
void write(std::string const& str);
QPDF_DLL
void writeToken(QPDFTokenizer::Token const&);
private:
void setPipeline(Pipeline*);
Pipeline* pipeline;
};
// This class is used by parse to decrypt strings when reading an
// object that contains encrypted strings.
class StringDecrypter
{
public:
QPDF_DLL
virtual ~StringDecrypter()
{
}
virtual void decryptString(std::string& val) = 0;
};
// This class is used by parsePageContents. Callers must
// instantiate a subclass of this with handlers defined to accept
// QPDFObjectHandles that are parsed from the stream.
class ParserCallbacks
{
public:
QPDF_DLL
virtual ~ParserCallbacks()
{
}
virtual void handleObject(QPDFObjectHandle) = 0;
virtual void handleEOF() = 0;
protected:
// Implementors may call this method during parsing to
// terminate parsing early. This method throws an exception
// that is caught by parsePageContents, so its effect is
// immediate.
QPDF_DLL
void terminateParsing();
};
// Convenience object for rectangles
class Rectangle
{
public:
Rectangle() :
llx(0.0),
lly(0.0),
urx(0.0),
ury(0.0)
{
}
Rectangle(double llx, double lly,
double urx, double ury) :
llx(llx),
lly(lly),
urx(urx),
ury(ury)
{
}
double llx;
double lly;
double urx;
double ury;
};
// Convenience object for transformation matrices
class Matrix
{
public:
Matrix() :
a(0.0),
b(0.0),
c(0.0),
d(0.0),
e(0.0),
f(0.0)
{
}
Matrix(double a, double b, double c,
double d, double e, double f) :
a(a),
b(b),
c(c),
d(d),
e(e),
f(f)
{
}
double a;
double b;
double c;
double d;
double e;
double f;
};
QPDF_DLL
QPDFObjectHandle();
QPDF_DLL
QPDFObjectHandle(QPDFObjectHandle const&);
QPDF_DLL
QPDFObjectHandle&
operator=(QPDFObjectHandle const&);
QPDF_DLL
bool isInitialized() const;
// Return type code and type name of underlying object. These are
// useful for doing rapid type tests (like switch statements) or
// for testing and debugging.
QPDF_DLL
QPDFObject::object_type_e getTypeCode();
QPDF_DLL
char const* getTypeName();
// Exactly one of these will return true for any object. Operator
// and InlineImage are only allowed in content streams.
QPDF_DLL
bool isBool();
QPDF_DLL
bool isNull();
QPDF_DLL
bool isInteger();
QPDF_DLL
bool isReal();
QPDF_DLL
bool isName();
QPDF_DLL
bool isString();
QPDF_DLL
bool isOperator();
QPDF_DLL
bool isInlineImage();
QPDF_DLL
bool isArray();
QPDF_DLL
bool isDictionary();
QPDF_DLL
bool isStream();
QPDF_DLL
bool isReserved();
// This returns true in addition to the query for the specific
// type for indirect objects.
QPDF_DLL
bool isIndirect();
// True for everything except array, dictionary, stream, word, and
// inline image.
QPDF_DLL
bool isScalar();
// Public factory methods
// Wrap an object in an array if it is not already an array. This
// is a helper for cases in which something in a PDF may either be
// a single item or an array of items, which is a common idiom.
QPDF_DLL
QPDFObjectHandle wrapInArray();
// Construct an object of any type from a string representation of
// the object. Throws QPDFExc with an empty filename and an
// offset into the string if there is an error. Any indirect
// object syntax (obj gen R) will cause a logic_error exception to
// be thrown. If object_description is provided, it will appear
// in the message of any QPDFExc exception thrown for invalid
// syntax.
QPDF_DLL
static QPDFObjectHandle parse(std::string const& object_str,
std::string const& object_description = "");
// Construct an object as above by reading from the given
// InputSource at its current position and using the tokenizer you
// supply. Indirect objects and encrypted strings are permitted.
// This method is intended to be called by QPDF for parsing
// objects that are ready from the object's input stream.
QPDF_DLL
static QPDFObjectHandle parse(PointerHolder<InputSource> input,
std::string const& object_description,
QPDFTokenizer&, bool& empty,
StringDecrypter* decrypter,
QPDF* context);
// Older method: stream_or_array should be the value of /Contents
// from a page object. It's more convenient to just call
// QPDFPageObjectHelper::parsePageContents on the page object, and
// error messages will also be more useful because the page object
// information will be known.
QPDF_DLL
static void parseContentStream(QPDFObjectHandle stream_or_array,
ParserCallbacks* callbacks);
// When called on a stream or stream array that is some page's
// content streams, do the same as pipePageContents. This method
// is a lower level way to do what
// QPDFPageObjectHelper::pipePageContents does, but it allows you
// to perform this operation on a contents object that is
// disconnected from a page object. The description argument
// should describe the containing page and is used in error
// messages. The all_description argument is initialized to
// something that could be used to describe the result of the
// pipeline. It is the description amended with the identifiers of
// the underlying objects.
QPDF_DLL
void pipeContentStreams(Pipeline* p, std::string const& description,
std::string& all_description);
// As of qpdf 8, it is possible to add custom token filters to a
// stream. The tokenized stream data is passed through the token
// filter after all original filters but before content stream
// normalization if requested. This is a low-level interface to
// add it to a stream. You will usually want to call
// QPDFPageObjectHelper::addContentTokenFilter instead, which can
// be applied to a page object, and which will automatically
// handle the case of pages whose contents are split across
// multiple streams.
void addTokenFilter(PointerHolder<TokenFilter> token_filter);
// Legacy helpers for parsing content streams. These methods are
// not going away, but newer code should call the correspond
// methods in QPDFPageObjectHelper instead. The specification and
// behavior of these methods are the same as the identically named
// methods in that class, but newer functionality will be added
// there.
QPDF_DLL
void parsePageContents(ParserCallbacks* callbacks);
QPDF_DLL
void filterPageContents(TokenFilter* filter, Pipeline* next = 0);
QPDF_DLL
void pipePageContents(Pipeline* p);
QPDF_DLL
void addContentTokenFilter(PointerHolder<TokenFilter> token_filter);
// End legacy content stream helpers
// Type-specific factories
QPDF_DLL
static QPDFObjectHandle newNull();
QPDF_DLL
static QPDFObjectHandle newBool(bool value);
QPDF_DLL
static QPDFObjectHandle newInteger(long long value);
QPDF_DLL
static QPDFObjectHandle newReal(std::string const& value);
QPDF_DLL
static QPDFObjectHandle newReal(double value, int decimal_places = 0);
QPDF_DLL
static QPDFObjectHandle newName(std::string const& name);
QPDF_DLL
static QPDFObjectHandle newString(std::string const& str);
// Create a string encoded in UTF-16 from the given utf8-encoded
// string. Such strings are appropriately encoded to appear in PDF
// files outside of content streams, such as in document metadata
// form field values, page labels, outlines, and similar locations.
QPDF_DLL
static QPDFObjectHandle newUnicodeString(std::string const& utf8_str);
QPDF_DLL
static QPDFObjectHandle newOperator(std::string const&);
QPDF_DLL
static QPDFObjectHandle newInlineImage(std::string const&);
QPDF_DLL
static QPDFObjectHandle newArray();
QPDF_DLL
static QPDFObjectHandle newArray(
std::vector<QPDFObjectHandle> const& items);
QPDF_DLL
static QPDFObjectHandle newArray(Rectangle const&);
QPDF_DLL
static QPDFObjectHandle newArray(Matrix const&);
QPDF_DLL
static QPDFObjectHandle newDictionary();
QPDF_DLL
static QPDFObjectHandle newDictionary(
std::map<std::string, QPDFObjectHandle> const& items);
// Create an array from a rectangle. Equivalent to the rectangle
// form of newArray.
QPDF_DLL
static QPDFObjectHandle newFromRectangle(Rectangle const&);
// Create an array from a matrix. Equivalent to the matrix
// form of newArray.
QPDF_DLL
static QPDFObjectHandle newFromMatrix(Matrix const&);
// Create a new stream and associate it with the given qpdf
// object. A subsequent call must be made to replaceStreamData()
// to provide data for the stream. The stream's dictionary may be
// retrieved by calling getDict(), and the resulting dictionary
// may be modified. Alternatively, you can create a new
// dictionary and call replaceDict to install it.
QPDF_DLL
static QPDFObjectHandle newStream(QPDF* qpdf);
// Create a new stream and associate it with the given qpdf
// object. Use the given buffer as the stream data. The stream
// dictionary's /Length key will automatically be set to the size
// of the data buffer. If additional keys are required, the
// stream's dictionary may be retrieved by calling getDict(), and
// the resulting dictionary may be modified. This method is just
// a convenient wrapper around the newStream() and
// replaceStreamData(). It is a convenience methods for streams
// that require no parameters beyond the stream length. Note that
// you don't have to deal with compression yourself if you use
// QPDFWriter. By default, QPDFWriter will automatically compress
// uncompressed stream data. Example programs are provided that
// illustrate this.
QPDF_DLL
static QPDFObjectHandle newStream(QPDF* qpdf, PointerHolder<Buffer> data);
// Create new stream with data from string. This method will
// create a copy of the data rather than using the user-provided
// buffer as in the PointerHolder<Buffer> version of newStream.
QPDF_DLL
static QPDFObjectHandle newStream(QPDF* qpdf, std::string const& data);
// A reserved object is a special sentinel used for qpdf to
// reserve a spot for an object that is going to be added to the
// QPDF object. Normally you don't have to use this type since
// you can just call QPDF::makeIndirectObject. However, in some
// cases, if you have to create objects with circular references,
// you may need to create a reserved object so that you can have a
// reference to it and then replace the object later. Reserved
// objects have the special property that they can't be resolved
// to direct objects. This makes it possible to replace a
// reserved object with a new object while preserving existing
// references to them. When you are ready to replace a reserved
// object with its replacement, use QPDF::replaceReserved for this
// purpose rather than the more general QPDF::replaceObject. It
// is an error to try to write a QPDF with QPDFWriter if it has
// any reserved objects in it.
QPDF_DLL
static QPDFObjectHandle newReserved(QPDF* qpdf);
// Provide an owning qpdf and object description. The library does
// this automatically with objects that are read from from the
// input PDF and with objects that are created programmatically
// and inserted into the QPDF by adding them to an array or a
// dictionary or creating a new indirect object. Most end user
// code will not need to call this. If an object has an owning
// qpdf and object description, it enables qpdf to give warnings
// with proper context in some cases where it would otherwise
// raise exceptions.
QPDF_DLL
void setObjectDescription(QPDF* owning_qpdf,
std::string const& object_description);
QPDF_DLL
bool hasObjectDescription();
// Accessor methods. If an accessor method that is valid for only
// a particular object type is called on an object of the wrong
// type, an exception is thrown.
// Methods for bool objects
QPDF_DLL
bool getBoolValue();
// Methods for integer objects
QPDF_DLL
long long getIntValue();
QPDF_DLL
int getIntValueAsInt();
QPDF_DLL
unsigned long long getUIntValue();
QPDF_DLL
unsigned int getUIntValueAsUInt();
// Methods for real objects
QPDF_DLL
std::string getRealValue();
// Methods that work for both integer and real objects
QPDF_DLL
bool isNumber();
QPDF_DLL
double getNumericValue();
// Methods for name objects; see also name and array objects
QPDF_DLL
std::string getName();
// Methods for string objects
QPDF_DLL
std::string getStringValue();
// If a string starts with the UTF-16 marker, it is converted from
// UTF-16 to UTF-8. Otherwise, it is treated as a string encoded
// with PDF Doc Encoding. PDF Doc Encoding is identical to
// ISO-8859-1 except in the range from 0200 through 0240, where
// there is a mapping of characters to Unicode. QPDF versions
// prior to version erroneously left characters in that range
// unmapped.
QPDF_DLL
std::string getUTF8Value();
// Methods for content stream objects
QPDF_DLL
std::string getOperatorValue();
QPDF_DLL
std::string getInlineImageValue();
// Methods for array objects; see also name and array objects
QPDF_DLL
int getArrayNItems();
QPDF_DLL
QPDFObjectHandle getArrayItem(int n);
QPDF_DLL
std::vector<QPDFObjectHandle> getArrayAsVector();
QPDF_DLL
bool isRectangle();
// If the array an array of four numeric values, return as a
// rectangle. Otherwise, return the rectangle [0, 0, 0, 0]
QPDF_DLL
Rectangle getArrayAsRectangle();
QPDF_DLL
bool isMatrix();
// If the array an array of six numeric values, return as a
// matrix. Otherwise, return the matrix [1, 0, 0, 1, 0, 0]
QPDF_DLL
Matrix getArrayAsMatrix();
// Methods for dictionary objects
QPDF_DLL
bool hasKey(std::string const&);
QPDF_DLL
QPDFObjectHandle getKey(std::string const&);
QPDF_DLL
std::set<std::string> getKeys();
QPDF_DLL
std::map<std::string, QPDFObjectHandle> getDictAsMap();
// Methods for name and array objects
QPDF_DLL
bool isOrHasName(std::string const&);
// Merge resource dictionaries. Assumes resource dictionaries have
// the property that the collection of keys of all first-level
// dictionary members contains no duplicates. This method does
// nothing if both this object and the other object are not
// dictionaries. Otherwise, it has following behavior, where
// "object" refers to the object whose method is invoked, and
// "other" refers to the argument:
//
// * For each key in "other" whose value is an array:
// * If "object" does not have that entry, shallow copy it.
// * Otherwise, if "object" has an array in the same place,
// append to that array any objects in "other"'s array that
// are not already present.
// * For each key in "other" whose value is a dictionary:
// * If "object" does not have that entry, shallow copy it.
// * Otherwise, for each key in the subdictionary:
// * If key is not present in "object"'s entry, shallow copy it.
// * Otherwise, ignore. Conflicts are not detected.
//
// The primary purpose of this method is to facilitate merging of
// resource dictionaries that are supposed to have the same scope
// as each other. For example, this can be used to merge a form
// XObject's /Resources dictionary with a form field's /DR.
// Conflicts are not detected. If, in the future, there should be
// a need to detect conflicts, this method could detect them and
// return a mapping from old to new names. This mapping could be
// used for filtering the stream. This would be necessary, for
// example, to merge a form XObject's resources with a page's
// resources with the intention of concatenating the content
// streams.
QPDF_DLL
void mergeResources(QPDFObjectHandle other);
// Get all resource names from a resource dictionary. If this
// object is a dictionary, this method returns a set of all the
// keys in all top-level subdictionaries. For resources
// dictionaries, this is the collection of names that may be
// referenced in the content stream.
QPDF_DLL
std::set<std::string> getResourceNames();
// Find a unique name within a resource dictionary starting with a
// given prefix. This method works by appending a number to the
// given prefix. It searches starting with min_suffix and sets
// min_suffix to selected value upon return. This can be used to
// increase efficiency if adding multiple items with the same
// prefix. (Why doesn't it set min_suffix to the next number?
// Well, maybe you aren't going to actually use the name it
// returns.)
QPDF_DLL
std::string getUniqueResourceName(std::string const& prefix,
int& min_suffix);
// Return the QPDF object that owns an indirect object. Returns
// null for a direct object.
QPDF_DLL
QPDF* getOwningQPDF();
// Create a shallow of an object as a direct object, but do not
// traverse across indirect object boundaries. That means that,
// for dictionaries and arrays, any keys or items that were
// indirect objects will still be indirect objects that point to
// the same place.
QPDF_DLL
QPDFObjectHandle shallowCopy();
// Mutator methods. Use with caution.
// Recursively copy this object, making it direct. Throws an
// exception if a loop is detected or any sub-object is a stream.
QPDF_DLL
void makeDirect();
// Mutator methods for array objects
QPDF_DLL
void setArrayItem(int, QPDFObjectHandle const&);
QPDF_DLL
void setArrayFromVector(std::vector<QPDFObjectHandle> const& items);
// Insert an item before the item at the given position ("at") so
// that it has that position after insertion. If "at" is equal to
// the size of the array, insert the item at the end.
QPDF_DLL
void insertItem(int at, QPDFObjectHandle const& item);
QPDF_DLL
void appendItem(QPDFObjectHandle const& item);
// Remove the item at that position, reducing the size of the
// array by one.
QPDF_DLL
void eraseItem(int at);
// Mutator methods for dictionary objects
// Replace value of key, adding it if it does not exist
QPDF_DLL
void replaceKey(std::string const& key, QPDFObjectHandle);
// Remove key, doing nothing if key does not exist
QPDF_DLL
void removeKey(std::string const& key);
// If the object is null, remove the key. Otherwise, replace it.
QPDF_DLL
void replaceOrRemoveKey(std::string const& key, QPDFObjectHandle);
// Methods for stream objects
QPDF_DLL
QPDFObjectHandle getDict();
// If addTokenFilter has been called for this stream, then the
// original data should be considered to be modified. This means we
// should avoid optimizations such as not filtering a stream that
// is already compressed.
QPDF_DLL
bool isDataModified();
// Returns filtered (uncompressed) stream data. Throws an
// exception if the stream is filtered and we can't decode it.
QPDF_DLL
PointerHolder<Buffer> getStreamData(
qpdf_stream_decode_level_e level = qpdf_dl_generalized);
// Returns unfiltered (raw) stream data.
QPDF_DLL
PointerHolder<Buffer> getRawStreamData();
// Write stream data through the given pipeline. A null pipeline
// value may be used if all you want to do is determine whether a
// stream is filterable and would be filtered based on the
// provided flags. If flags is 0, write raw stream data and return
// false. Otherwise, the flags alter the behavior in the following
// way:
//
// encode_flags:
//
// qpdf_sf_compress -- compress data with /FlateDecode if no other
// compression filters are applied.
//
// qpdf_sf_normalize -- tokenize as content stream and normalize tokens
//
// decode_level:
//
// qpdf_dl_none -- do not decode any streams.
//
// qpdf_dl_generalized -- decode supported general-purpose
// filters. This includes /ASCIIHexDecode, /ASCII85Decode,
// /LZWDecode, and /FlateDecode.
//
// qpdf_dl_specialized -- in addition to generalized filters, also
// decode supported non-lossy specialized filters. This includes
// /RunLengthDecode.
//
// qpdf_dl_all -- in addition to generalized and non-lossy
// specialized filters, decode supported lossy filters. This
// includes /DCTDecode.
//
// If, based on the flags and the filters and decode parameters,
// we determine that we know how to apply all requested filters,
// do so and return true if we are successful.
//
// In all cases, a return value of true means that filtered data
// has been written successfully. If filtering is requested but
// this method returns false, it means there was some error in the
// filtering, in which case the resulting data is likely partially
// filtered and/or incomplete and may not be consistent with the
// configured filters. QPDFWriter handles this by attempting to
// get the stream data without filtering, but callers should
// consider a false return value when decode_level is not
// qpdf_dl_none to be a potential loss of data. If you intend to
// retry in that case, pass true as the value of will_retry. This
// changes the warning issued by the library to indicate that the
// operation will be retried without filtering to avoid data loss.
QPDF_DLL
bool pipeStreamData(Pipeline*,
int encode_flags,
qpdf_stream_decode_level_e decode_level,
bool suppress_warnings = false,
bool will_retry = false);
// Legacy pipeStreamData. This maps to the the flags-based
// pipeStreamData as follows:
// filter = false -> encode_flags = 0
// filter = true -> decode_level = qpdf_dl_generalized
// normalize = true -> encode_flags |= qpdf_sf_normalize
// compress = true -> encode_flags |= qpdf_sf_compress
QPDF_DLL
bool pipeStreamData(Pipeline*, bool filter,
bool normalize, bool compress);
// Replace a stream's dictionary. The new dictionary must be
// consistent with the stream's data. This is most appropriately
// used when creating streams from scratch that will use a stream
// data provider and therefore start with an empty dictionary. It
// may be more convenient in this case than calling getDict and
// modifying it for each key. The pdf-create example does this.
QPDF_DLL
void replaceDict(QPDFObjectHandle);
// Replace this stream's stream data with the given data buffer,
// and replace the /Filter and /DecodeParms keys in the stream
// dictionary with the given values. (If either value is empty,
// the corresponding key is removed.) The stream's /Length key is
// replaced with the length of the data buffer. The stream is
// interpreted as if the data read from the file, after any
// decryption filters have been applied, is as presented.
QPDF_DLL
void replaceStreamData(PointerHolder<Buffer> data,
QPDFObjectHandle const& filter,
QPDFObjectHandle const& decode_parms);
// Replace the stream's stream data with the given string.
// This method will create a copy of the data rather than using
// the user-provided buffer as in the PointerHolder<Buffer> version
// of replaceStreamData.
QPDF_DLL
void replaceStreamData(std::string const& data,
QPDFObjectHandle const& filter,
QPDFObjectHandle const& decode_parms);
// As above, replace this stream's stream data. Instead of
// directly providing a buffer with the stream data, call the
// given provider's provideStreamData method. See comments on the
// StreamDataProvider class (defined above) for details on the
// method. The data must be consistent with filter and
// decode_parms as provided. Although it is more complex to use
// this form of replaceStreamData than the one that takes a
// buffer, it makes it possible to avoid allocating memory for the
// stream data. Example programs are provided that use both forms
// of replaceStreamData.
// Note about stream length: for any given stream, the provider
// must provide the same amount of data each time it is called.
// This is critical for making linearization work properly.
// Versions of qpdf before 3.0.0 required a length to be specified
// here. Starting with version 3.0.0, this is no longer necessary
// (or permitted). The first time the stream data provider is
// invoked for a given stream, the actual length is stored.
// Subsequent times, it is enforced that the length be the same as
// the first time.
// If you have gotten a compile error here while building code
// that worked with older versions of qpdf, just omit the length
// parameter. You can also simplify your code by not having to
// compute the length in advance.
QPDF_DLL
void replaceStreamData(PointerHolder<StreamDataProvider> provider,
QPDFObjectHandle const& filter,
QPDFObjectHandle const& decode_parms);
// Access object ID and generation. For direct objects, return
// object ID 0.
// NOTE: Be careful about calling getObjectID() and
// getGeneration() directly as this can lead to the pattern of
// depending on object ID or generation without the other. In
// general, when keeping track of object IDs, it's better to use
// QPDFObjGen instead.
QPDF_DLL
QPDFObjGen getObjGen() const;
QPDF_DLL
int getObjectID() const;
QPDF_DLL
int getGeneration() const;
QPDF_DLL
std::string unparse();
QPDF_DLL
std::string unparseResolved();
// For strings only, force binary representation. Otherwise, same
// as unparse.
QPDF_DLL
std::string unparseBinary();
// Return encoded as JSON. For most object types, there is an
// obvious mapping. The JSON is generated as follows:
// * Names are encoded as strings representing the normalized value of
// getName()
// * Indirect references are encoded as strings containing "obj gen R"
// * Strings are encoded as UTF-8 strings with unrepresentable binary
// characters encoded as \uHHHH
// * Encoding streams just encodes the stream's dictionary; the stream
// data is not represented
// * Object types that are only valid in content streams (inline
// image, operator) as well as "reserved" objects are not
// representable and will be serialized as "null".
// If dereference_indirect is true and this is an indirect object,
// show the actual contents of the object. The effect of
// dereference_indirect applies only to this object. It is not
// recursive.
QPDF_DLL
JSON getJSON(bool dereference_indirect = false);
// Legacy helper methods for commonly performed operations on
// pages. Newer code should use QPDFPageObjectHelper instead. The
// specification and behavior of these methods are the same as the
// identically named methods in that class, but newer
// functionality will be added there.
QPDF_DLL
std::map<std::string, QPDFObjectHandle> getPageImages();
QPDF_DLL
std::vector<QPDFObjectHandle> getPageContents();
QPDF_DLL
void addPageContents(QPDFObjectHandle contents, bool first);
QPDF_DLL
void rotatePage(int angle, bool relative);
QPDF_DLL
void coalesceContentStreams();
// End legacy page helpers
// Issue a warning about this object if possible. If the object
// has a description, a warning will be issued. Otherwise, if
// throw_if_no_description is true, throw an exception. Otherwise
// do nothing. Objects read normally from the file have
// descriptions. See comments on setObjectDescription for
// additional details.
QPDF_DLL
void warnIfPossible(std::string const& warning,
bool throw_if_no_description = false);
// Initializers for objects. This Factory class gives the QPDF
// class specific permission to call factory methods without
// making it a friend of the whole QPDFObjectHandle class.
class Factory
{
friend class QPDF;
private:
static QPDFObjectHandle newIndirect(QPDF* qpdf,
int objid, int generation)
{
return QPDFObjectHandle::newIndirect(qpdf, objid, generation);
}
// object must be dictionary object
static QPDFObjectHandle newStream(
QPDF* qpdf, int objid, int generation,
QPDFObjectHandle stream_dict, qpdf_offset_t offset, size_t length)
{
return QPDFObjectHandle::newStream(
qpdf, objid, generation, stream_dict, offset, length);
}
};
friend class Factory;
// Accessor for raw underlying object -- only QPDF is allowed to
// call this.
class ObjAccessor
{
friend class QPDF;
private:
static PointerHolder<QPDFObject> getObject(QPDFObjectHandle& o)
{
o.dereference();
return o.m->obj;
}
};
friend class ObjAccessor;
// Provide access to specific classes for recursive
// releaseResolved().
class ReleaseResolver
{
friend class QPDF_Dictionary;
friend class QPDF_Array;
friend class QPDF_Stream;
private:
static void releaseResolved(QPDFObjectHandle& o)
{
o.releaseResolved();
}
};
friend class ReleaseResolver;
// Convenience routine: Throws if the assumption is violated. Your
// code will be better if you call one of the isType methods and
// handle the case of the type being wrong, but these can be
// convenient if you have already verified the type.
QPDF_DLL
void assertInitialized() const;
QPDF_DLL
void assertNull();
QPDF_DLL
void assertBool();
QPDF_DLL
void assertInteger();
QPDF_DLL
void assertReal();
QPDF_DLL
void assertName();
QPDF_DLL
void assertString();
QPDF_DLL
void assertOperator();
QPDF_DLL
void assertInlineImage();
QPDF_DLL
void assertArray();
QPDF_DLL
void assertDictionary();
QPDF_DLL
void assertStream();
QPDF_DLL
void assertReserved();
QPDF_DLL
void assertIndirect();
QPDF_DLL
void assertScalar();
QPDF_DLL
void assertNumber();
// The isPageObject method checks the /Type key of the object.
// This is not completely reliable as there are some otherwise
// valid files whose /Type is wrong for page objects. qpdf is
// slightly more accepting but may still return false here when
// treating the object as a page would work. Use this sparingly.
QPDF_DLL
bool isPageObject();
QPDF_DLL
bool isPagesObject();
QPDF_DLL
void assertPageObject();
private:
QPDFObjectHandle(QPDF*, int objid, int generation);
QPDFObjectHandle(QPDFObject*);
enum parser_state_e
{
st_top,
st_start,
st_stop,
st_eof,
st_dictionary,
st_array
};
// Private object factory methods
static QPDFObjectHandle newIndirect(QPDF*, int objid, int generation);
static QPDFObjectHandle newStream(
QPDF* qpdf, int objid, int generation,
QPDFObjectHandle stream_dict, qpdf_offset_t offset, size_t length);
void typeWarning(char const* expected_type,
std::string const& warning);
void objectWarning(std::string const& warning);
void assertType(char const* type_name, bool istype);
void dereference();
void copyObject(std::set<QPDFObjGen>& visited, bool cross_indirect);
void releaseResolved();
static void setObjectDescriptionFromInput(
QPDFObjectHandle, QPDF*, std::string const&,
PointerHolder<InputSource>, qpdf_offset_t);
static QPDFObjectHandle parseInternal(
PointerHolder<InputSource> input,
std::string const& object_description,
QPDFTokenizer& tokenizer, bool& empty,
StringDecrypter* decrypter, QPDF* context,
bool content_stream);
void parseContentStream_internal(
std::string const& description,
ParserCallbacks* callbacks);
static void parseContentStream_data(
PointerHolder<Buffer>,
std::string const& description,
ParserCallbacks* callbacks);
std::vector<QPDFObjectHandle> arrayOrStreamToStreamArray(
std::string const& description, std::string& all_description);
static void warn(QPDF*, QPDFExc const&);
class Members
{
friend class ObjAccessor;
friend class QPDFObjectHandle;
public:
QPDF_DLL
~Members();
private:
Members();
Members(QPDF* qpdf, int objid, int generation);
Members(QPDFObject* data);
bool initialized;
QPDF* qpdf;
int objid; // 0 for direct object
int generation;
PointerHolder<QPDFObject> obj;
bool reserved;
};
PointerHolder<Members> m;
};
#endif // QPDFOBJECTHANDLE_HH
| 36.858624 | 78 | 0.681285 | ams-tschoening |
28f81470874a91a6c5d61980bc5e0757988b216d | 8,782 | cpp | C++ | examples/jointHistIOExample.cpp | GRAVITYLab/edda | 2acd00373db1003922db9f5959644e7506de5726 | [
"MIT"
] | 3 | 2016-01-15T20:17:21.000Z | 2021-01-21T02:32:15.000Z | examples/jointHistIOExample.cpp | GRAVITYLab/edda | 2acd00373db1003922db9f5959644e7506de5726 | [
"MIT"
] | 11 | 2016-07-26T01:37:46.000Z | 2018-06-19T16:50:25.000Z | examples/jointHistIOExample.cpp | GRAVITYLab/edda | 2acd00373db1003922db9f5959644e7506de5726 | [
"MIT"
] | 12 | 2016-02-09T04:31:41.000Z | 2021-12-03T01:04:04.000Z | #include <string>
#include <vector>
#include "dataset/distr_array.h"
#include "distributions/distribution_modeler.h"
#include "distributions/joint_GMM.h"
#include "distributions/joint_gaussian.h"
#include "io/edda_reader.h"
#include "io/edda_writer.h"
#include "distributions/joint_histogram.h"
using namespace edda;
using namespace std;
using namespace edda::dist;
int main(int argc, char* argv[])
{
if (argc < 10)
{
cout << "USAGE: check the parameter list!!\n";
exit(11);
}
string filename1 = argv[1];
string filename2 = argv[2];
string filename3 = argv[3];
int xdim = atoi(argv[4]);
int ydim = atoi(argv[5]);
int zdim = atoi(argv[6]);
int blockXdim = atoi(argv[7]);
int blockYdim = atoi(argv[8]);
int blockZdim = atoi(argv[9]);
//////for quicker testing
//cout << "USAGE: default settings\n";
//string filename1 = "E:/Data/edda/PRECIPf25.binLE.raw_corrected_2_subsampled";
//string filename2 = "E:/Data/edda/QGRAUPf25.binLE.raw_corrected_2_subsampled";
//string filename3 = "E:/Data/edda/QRAINf25.binLE.raw_corrected_2_subsampled";
//int xdim =30;
//int ydim = 30;
//int zdim = 30;
//int blockXdim = 10;
//int blockYdim = 10;
//int blockZdim = 10;
int nVar = 3;
int nComp = 2;
//from here to the creation of "Dataset<Real> *ds" is the same with the example in MVDistrModelerExample_Hist.cpp
float *inData1;
inData1 = new float[xdim*ydim*zdim];
FILE *fIn1 = fopen(filename1.c_str(), "rb");
if (!fIn1)
{
fprintf(stderr, "Error opening file\n");
exit(13);
}
size_t readStatus1 = fread(inData1, sizeof(float), xdim*ydim*zdim, fIn1);
fclose(fIn1);
float *inData2;
inData2 = new float[xdim*ydim*zdim];
FILE *fIn2 = fopen(filename2.c_str(), "rb");
if (!fIn2)
{
fprintf(stderr, "Error opening file\n");
exit(13);
}
size_t readStatus2 = fread(inData2, sizeof(float), xdim*ydim*zdim, fIn2);
fclose(fIn2);
float *inData3;
inData3 = new float[xdim*ydim*zdim];
FILE *fIn3 = fopen(filename3.c_str(), "rb");
if (!fIn3)
{
fprintf(stderr, "Error opening file\n");
exit(13);
}
size_t readStatus3 = fread(inData3, sizeof(float), xdim*ydim*zdim, fIn3);
fclose(fIn3);
int newW(0), newH(0), newD(0);
if (xdim % blockXdim == 0)
newW = xdim / blockXdim;
else
{
fprintf(stderr, "Wrong dimension combination\n");
exit(14);
}
if (ydim % blockYdim == 0)
newH = ydim / blockYdim;
else
{
fprintf(stderr, "Wrong dimension combination\n");
exit(14);
}
if (zdim % blockZdim == 0)
newD = zdim / blockZdim;
else
{
fprintf(stderr, "Wrong dimension combination\n");
exit(14);
}
DistributionModeler mv_dm(newW*newH*newD);
cout << "starting partitioning\n";
int counter = 0;
for (size_t z = 0; z<zdim; z += blockZdim)
{
for (size_t y = 0; y<ydim; y += blockYdim)
{
for (size_t x = 0; x<xdim; x += blockXdim)
{
Real* data1 = (Real*)malloc(sizeof(Real)*blockXdim*blockYdim*blockZdim);
Real* data2 = (Real*)malloc(sizeof(Real)*blockXdim*blockYdim*blockZdim);
Real* data3 = (Real*)malloc(sizeof(Real)*blockXdim*blockYdim*blockZdim);
std::vector<Real> min_val(3, FLT_MAX);
std::vector<Real> max_val(3, -FLT_MAX);
std::vector<int> bins(3, 30);
int i = 0;
for (size_t zz = z; zz<z + blockZdim; zz++)
{
for (size_t yy = y; yy<y + blockYdim; yy++)
{
for (size_t xx = x; xx<x + blockXdim; xx++)
{
data1[i] = (Real)(inData1[zz*xdim*ydim + yy*xdim + xx]);
data2[i] = (Real)(inData2[zz*xdim*ydim + yy*xdim + xx]);
data3[i] = (Real)(inData3[zz*xdim*ydim + yy*xdim + xx]);
if (data1[i]<min_val[0]) min_val[0] = data1[i];
if (data1[i]>max_val[0]) max_val[0] = data1[i];
if (data2[i]<min_val[1]) min_val[1] = data2[i];
if (data2[i]>max_val[1]) max_val[1] = data2[i];
if (data3[i]<min_val[2]) min_val[2] = data3[i];
if (data3[i]>max_val[2]) max_val[2] = data3[i];
i++;
}
}
}
std::vector<Real*> trainSamples;
trainSamples.push_back(data1);
trainSamples.push_back(data2);
trainSamples.push_back(data3);
std::cout << "dimensions: [" << z << "][" << y << "][" << x << "]\n";
mv_dm.computeJointHistogram(trainSamples, blockXdim*blockYdim*blockZdim, min_val, max_val, bins, counter);
counter++;
}
}
}
std::vector<DistrArray *> dVec;
dVec.push_back(mv_dm.getDistrArray());
Dataset<Real> *ds = new Dataset<Real>(new RegularCartesianGrid(newW, newH, newD), dVec);
shared_ptr<Dataset<Real>> shr_ds(ds);
//write the dataset using the writer
EddaWriter eddaWriter;
eddaWriter.writeEddaDataset(shr_ds, "testDataJointHist.edda");
//read the dataset using the reader
EddaReader eddaReader;
shared_ptr<Dataset<Real>> shr_ds2 = eddaReader.loadEddaDataset("testDataJointHist.edda");
//basic compare
int numDistrArray1 = shr_ds->getNumDistrArray();
int numDistrArray2 = shr_ds2->getNumDistrArray();
if (numDistrArray1 != numDistrArray2){
cout << "Joint Histogram IO failed! number of arrays changed! " << endl;
return 0;
}
DistrArray *array1 = shr_ds->getArray(0); //we know there is only 1 array
DistrArray *array2 = shr_ds2->getArray(0); //we know there is only 1 array
int n1 = array1->getLength();
int n2 = array2->getLength();
if (n1 != n2){
cout << "Joint Histogram IO failed! length of arrays changed! " << endl;
return 0;
}
//print and compare one arbitrary candidate
cout << endl << "Compare one single Histogram from original dataset, and the dataset after IO: " << endl << endl;
dist::Variant curDist1 = array1->getDistr(n1 / 2);
dist::JointHistogram curJHist1 = boost::get<dist::JointHistogram>(curDist1);
cout << "joint Histogram No. " << n1 / 2 << " from the original dataset:" << endl;
cout << curJHist1 << endl << endl;
dist::Variant curDist2 = array2->getDistr(n1 / 2);
dist::JointHistogram curJHist2 = boost::get<dist::JointHistogram>(curDist2);
cout << "joint Histogram No. " << n1 / 2 << " from the dataset after IO:" << endl;
cout << curJHist2 << endl;
//compare every parameter one by one
double dif = 0.0;
for (int j = 0; j < n1; j++){
dist::Variant curDist1 = array1->getDistr(j);
dist::Variant curDist2 = array2->getDistr(j);
string s = getName(curDist2);
if (s.compare(0, 15, "JointHistogram") != 0) {
cout << "Joint Histogram IO failed! arrays element not joint Histogram! " << endl;
return 0;
}
dist::JointHistogram curJHist1 = boost::get<dist::JointHistogram>(curDist1);
dist::JointHistogram curJHist2 = boost::get<dist::JointHistogram>(curDist2);
int num_vars1 = curJHist1.getNumVars();
int num_vars2 = curJHist2.getNumVars();
if (num_vars1 != num_vars2){
cout << "Joint Histogram IO failed! num_vars of at least one joint Histogram changed! " << endl;
return 0;
}
std::vector<Real> min_vals1 = curJHist1.getMinVals();
std::vector<Real> min_vals2 = curJHist2.getMinVals();
std::vector<Real> max_vals1 = curJHist1.getMaxVals();
std::vector<Real> max_vals2 = curJHist2.getMaxVals();
std::vector<Real> bin_widths1 = curJHist1.getBinWidths();
std::vector<Real> bin_widths2 = curJHist2.getBinWidths();
std::vector<int> num_bins1 = curJHist1.getNumBins();
std::vector<int> num_bins2 = curJHist2.getNumBins();
for (int v = 0; v < num_vars1; v++) {
dif += abs(min_vals1[v] - min_vals2[v]);
dif += abs(max_vals1[v] - max_vals2[v]);
dif += abs(bin_widths1[v] - bin_widths2[v]);
dif += abs(num_bins1[v] - num_bins2[v]);
}
//compare pdf
boost::unordered_map<std::vector<int>, Real> pdf1 = curJHist1.getDistr();
boost::unordered_map<std::vector<int>, Real> pdf2 = curJHist2.getDistr();
int n_pdf1 = pdf1.size();
int n_pdf2 = pdf2.size();
if (n_pdf1 != n_pdf2) {
cout << "Joint Histogram IO failed! pdf size of at least one joint Histogram changed! " << endl;
return 0;
}
for (auto it1 = pdf1.begin(); it1 != pdf1.end(); ++it1) {
std::vector<int> vint1 = it1->first;
if (pdf2.find(vint1) == pdf2.end()) {
cout << "Joint Histogram IO failed! at least one key of at least one pdf of at least one joint Histogram changed! " << endl;
return 0;
}
Real r1 = it1->second;
Real r2 = pdf2[vint1];
int n_vint1 = vint1.size();
dif += abs(r1 - r2);
}
//compare mean and cov
std::vector<Real> curMean1 = getJointMean(curJHist1);
ublas_matrix curCov1 = curJHist1.getCovariance();
std::vector<Real> curMean2 = getJointMean(curJHist2);
ublas_matrix curCov2 = curJHist2.getCovariance();
for (int i = 0; i < num_vars1; i++) {
dif += abs(curMean1[i] - curMean2[i]);
}
for (int j = 0; j < num_vars1; j++) {
for (int i = j; i < num_vars1; i++) {
dif += abs(curCov1(j, i) - curCov2(j, i));
}
}
}
cout << "the total difference between parameters of the modeler result and the IO result is: " << dif << endl;
return 1;
} | 29.972696 | 128 | 0.656001 | GRAVITYLab |
28fab419c1d125cdef791ecf805e7cd13bb470cf | 8,643 | cc | C++ | mace/ops/arm/base/activation.cc | zhangzhimin/mace | c28f093d719fd650a4308895cd045c26d0f198f6 | [
"Apache-2.0"
] | 1 | 2021-08-02T12:17:58.000Z | 2021-08-02T12:17:58.000Z | mace/ops/arm/base/activation.cc | zhangzhimin/mace | c28f093d719fd650a4308895cd045c26d0f198f6 | [
"Apache-2.0"
] | null | null | null | mace/ops/arm/base/activation.cc | zhangzhimin/mace | c28f093d719fd650a4308895cd045c26d0f198f6 | [
"Apache-2.0"
] | 1 | 2021-08-02T12:18:00.000Z | 2021-08-02T12:18:00.000Z | // Copyright 2020 The MACE 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 "mace/ops/arm/base/activation.h"
#include <algorithm>
#include "mace/ops/arm/base/common_neon.h"
namespace mace {
namespace ops {
namespace arm {
extern template void Activation<uint8_t>::ActivateRelu(
utils::ThreadPool *, const Tensor *, Tensor *);
extern template void Activation<uint8_t>::ActivateRelux(
utils::ThreadPool *, const Tensor *, Tensor *);
extern template void Activation<uint8_t>::ActivateLeakyRelu(
utils::ThreadPool *, const Tensor *, Tensor *);
extern template void Activation<uint8_t>::ActivateTanh(
utils::ThreadPool *, const Tensor *, Tensor *);
extern template void Activation<uint8_t>::ActivateSigmoid(
utils::ThreadPool *, const Tensor *, Tensor *);
template<typename T>
MaceStatus Activation<T>::Compute(const OpContext *context,
const Tensor *input, Tensor *output) {
Tensor::MappingGuard input_guard(input);
if (input != output) {
MACE_RETURN_IF_ERROR(output->ResizeLike(input));
Tensor::MappingGuard output_guard(output);
DoActivation(context, input, output);
} else {
DoActivation(context, input, output);
}
return MaceStatus::MACE_SUCCESS;
}
template<typename T>
void Activation<T>::DoActivation(const OpContext *context,
const Tensor *input,
Tensor *output) {
utils::ThreadPool &thread_pool =
context->device()->cpu_runtime()->thread_pool();
switch (type_) {
case RELU: {
ActivateRelu(&thread_pool, input, output);
break;
}
case RELUX: {
ActivateRelux(&thread_pool, input, output);
break;
}
case LEAKYRELU: {
ActivateLeakyRelu(&thread_pool, input, output);
break;
}
case TANH: {
ActivateTanh(&thread_pool, input, output);
break;
}
case SIGMOID: {
ActivateSigmoid(&thread_pool, input, output);
break;
}
case ELU: {
ActivateElu(&thread_pool, input, output);
break;
}
case NOOP: {
break;
}
default: {
MACE_NOT_IMPLEMENTED;
}
}
}
template<typename T>
void Activation<T>::ActivateRelu(utils::ThreadPool *thread_pool,
const Tensor *input,
Tensor *output) {
const auto input_data = input->data<T>();
auto output_data = output->mutable_data<T>();
const index_t input_size = input->size();
const float32x4_t vzero = vdupq_n_f32(0.f);
const index_t block_count = input_size / 4;
thread_pool->Compute1D(
[=](index_t start, index_t end, index_t step) {
const T *input_ptr = input_data + start * 4;
T *output_ptr = output_data + start * 4;
for (index_t i = start; i < end; i += step) {
float32x4_t v = vld1q(input_ptr);
v = vmaxq_f32(v, vzero);
vst1q(output_ptr, v);
input_ptr += 4;
output_ptr += 4;
}
},
0, block_count, 1);
// remain
for (index_t i = block_count * 4; i < input_size; ++i) {
output_data[i] = std::max(0.f, input_data[i]);
}
}
template<typename T>
void Activation<T>::ActivateRelux(utils::ThreadPool *thread_pool,
const Tensor *input,
Tensor *output) {
const auto input_data = input->data<T>();
auto output_data = output->mutable_data<T>();
const index_t input_size = input->size();
const float32x4_t vzero = vdupq_n_f32(0.f);
const float32x4_t vlimit = vdupq_n_f32(limit_);
const index_t block_count = input_size / 4;
thread_pool->Compute1D(
[=](index_t start, index_t end, index_t step) {
auto input_ptr = input_data + start * 4;
auto output_ptr = output_data + start * 4;
for (index_t i = start; i < end; i += step) {
float32x4_t v = vld1q(input_ptr);
v = vmaxq_f32(v, vzero);
v = vminq_f32(v, vlimit);
vst1q(output_ptr, v);
input_ptr += 4;
output_ptr += 4;
}
},
0, block_count, 1);
// remain
for (index_t i = block_count * 4; i < input_size; ++i) {
output_data[i] = std::max(0.f, std::min(limit_, input_data[i]));
}
}
template<typename T>
void Activation<T>::ActivateLeakyRelu(utils::ThreadPool *thread_pool,
const Tensor *input,
Tensor *output) {
const auto input_data = input->data<T>();
auto output_data = output->mutable_data<T>();
const index_t input_size = input->size();
const float32x4_t vzero = vdupq_n_f32(0.f);
const float32x4_t valpha = vdupq_n_f32(activation_coefficient_);
const index_t block_count = input_size / 4;
thread_pool->Compute1D(
[=](index_t start, index_t end, index_t step) {
auto input_ptr = input_data + start * 4;
auto output_ptr = output_data + start * 4;
for (index_t i = start; i < end; i += step) {
float32x4_t v = vld1q(input_ptr);
float32x4_t u = vminq_f32(v, vzero);
v = vmaxq_f32(v, vzero);
v = vmlaq_f32(v, valpha, u);
vst1q(output_ptr, v);
input_ptr += 4;
output_ptr += 4;
}
},
0, block_count, 1);
// remain
for (index_t i = block_count * 4; i < input_size; ++i) {
output_data[i] = std::max(input_data[i], 0.f) +
std::min(input_data[i], 0.f) * activation_coefficient_;
}
}
template<typename T>
void Activation<T>::ActivateTanh(utils::ThreadPool *thread_pool,
const Tensor *input,
Tensor *output) {
const auto input_data = input->data<T>();
auto output_data = output->mutable_data<T>();
const index_t input_size = input->size();
thread_pool->Compute1D(
[=](index_t start, index_t end, index_t step) {
for (index_t i = start; i < end; i += step) {
output_data[i] = std::tanh(input_data[i]);
}
},
0, input_size, 1);
}
template<typename T>
void Activation<T>::ActivateSigmoid(utils::ThreadPool *thread_pool,
const Tensor *input,
Tensor *output) {
const auto input_data = input->data<T>();
auto output_data = output->mutable_data<T>();
const index_t input_size = input->size();
thread_pool->Compute1D(
[=](index_t start, index_t end, index_t step) {
for (index_t i = start; i < end; i += step) {
output_data[i] = 1 / (1 + std::exp(-(input_data[i])));
}
},
0, input_size, 1);
}
template<typename T>
void Activation<T>::ActivateElu(utils::ThreadPool *thread_pool,
const Tensor *input,
Tensor *output) {
const auto *input_data = input->data<T>();
auto *output_data = output->mutable_data<T>();
const index_t input_size = input->size();
thread_pool->Compute1D(
[=](index_t start, index_t end, index_t step) {
for (index_t i = start; i < end; i += step) {
const auto in_val = input_data[i];
if (in_val < 0) {
output_data[i] = (std::exp(in_val) - 1) * activation_coefficient_;
} else {
output_data[i] = in_val;
}
}
},
0, input_size, 1);
}
void RegisterActivationDelegator(OpDelegatorRegistry *registry) {
MACE_REGISTER_DELEGATOR(
registry, Activation<float>, delegator::ActivationParam,
MACE_DELEGATOR_KEY(Activation, DeviceType::CPU, float, ImplType::NEON));
#ifdef MACE_ENABLE_QUANTIZE
MACE_REGISTER_DELEGATOR(
registry, Activation<uint8_t>, delegator::ActivationParam,
MACE_DELEGATOR_KEY(Activation, DeviceType::CPU, uint8_t, ImplType::NEON));
#endif // MACE_ENABLE_QUANTIZE
MACE_REGISTER_BF16_DELEGATOR(
registry, Activation<BFloat16>, delegator::ActivationParam,
MACE_DELEGATOR_KEY(Activation, DeviceType::CPU, BFloat16,
ImplType::NEON));
}
} // namespace arm
} // namespace ops
} // namespace mace
| 31.315217 | 80 | 0.608006 | zhangzhimin |
28fc5e0ee00f8cafe17e4f2ae0ec58241a43fc4f | 311 | hpp | C++ | libraries/fc/include/fc/io/fstream.hpp | Laighno/evt | 90b94e831aebb62c6ad19ce59c9089e9f51cfd77 | [
"MIT"
] | 1,411 | 2018-04-23T03:57:30.000Z | 2022-02-13T10:34:22.000Z | libraries/fc/include/fc/io/fstream.hpp | Zhang-Zexi/evt | e90fe4dbab4b9512d120c79f33ecc62791e088bd | [
"Apache-2.0"
] | 27 | 2018-06-11T10:34:42.000Z | 2019-07-27T08:50:02.000Z | libraries/fc/include/fc/io/fstream.hpp | Zhang-Zexi/evt | e90fe4dbab4b9512d120c79f33ecc62791e088bd | [
"Apache-2.0"
] | 364 | 2018-06-09T12:11:53.000Z | 2020-12-15T03:26:48.000Z | #include <fc/filesystem.hpp>
#include <string>
namespace fc {
/**
* Grab the full contents of a file into a string object.
* NB reading a full file into memory is a poor choice
* if the file may be very large.
*/
void read_file_contents(const fc::path& filename, std::string& result);
} // namespace fc
| 22.214286 | 71 | 0.707395 | Laighno |
28ffda0111a2631aba49658194e5f1f182e25259 | 15,123 | cpp | C++ | src/byte_compare.cpp | baydroid/Dictionary_Trie | bc58403992ee978b0ed76645f66582222b36a2bd | [
"Apache-2.0"
] | null | null | null | src/byte_compare.cpp | baydroid/Dictionary_Trie | bc58403992ee978b0ed76645f66582222b36a2bd | [
"Apache-2.0"
] | null | null | null | src/byte_compare.cpp | baydroid/Dictionary_Trie | bc58403992ee978b0ed76645f66582222b36a2bd | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017 transmission.aquitaine@yahoo.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "addr_width.h"
#include "basic_types.h"
#include "zprintf_etc.h"
#ifdef IS64BIT
#ifdef IS_INTEL_ENDIAN
inline uinta byteOf1stBitNZ(uinta x) // assumes x != 0
{
if (x & 0x00000000FFFFFFFF)
{
if (x & 0x000000000000FFFF)
return x & 0x00000000000000FF ? 0 : 1;
else
return x & 0x0000000000FF0000 ? 2 : 3;
}
else
{
if (x & 0x0000FFFF00000000)
return x & 0x000000FF00000000 ? 4 : 5;
else
return x & 0x00FF000000000000 ? 6 : 7;
}
}
static uinta startMasks[9] =
{
0xFFFFFFFFFFFFFFFF,
0xFFFFFFFFFFFFFF00,
0xFFFFFFFFFFFF0000,
0xFFFFFFFFFF000000,
0xFFFFFFFF00000000,
0xFFFFFF0000000000,
0xFFFF000000000000,
0xFF00000000000000,
0x0000000000000000
};
static uinta endMasks[9] =
{
0x0000000000000000,
0x00000000000000FF,
0x000000000000FFFF,
0x0000000000FFFFFF,
0x00000000FFFFFFFF,
0x000000FFFFFFFFFF,
0x0000FFFFFFFFFFFF,
0x00FFFFFFFFFFFFFF,
0xFFFFFFFFFFFFFFFF
};
#else
inline uinta byteOf1stBitNZ(uinta x) // assumes x != 0
{
if (x & 0xFFFFFFFF00000000)
{
if (x & 0xFFFF000000000000)
return x & 0xFF00000000000000 ? 0 : 1;
else
return x & 0x0000FF0000000000 ? 2 : 3;
}
else
{
if (x & 0x00000000FFFF0000)
return x & 0x00000000FF000000 ? 4 : 5;
else
return x & 0x000000000000FF00 ? 6 : 7;
}
}
static uinta startMasks[9] =
{
0xFFFFFFFFFFFFFFFF,
0x00FFFFFFFFFFFFFF,
0x0000FFFFFFFFFFFF,
0x000000FFFFFFFFFF,
0x00000000FFFFFFFF,
0x0000000000FFFFFF,
0x000000000000FFFF,
0x00000000000000FF,
0x0000000000000000
};
static uinta endMasks[9] =
{
0x0000000000000000,
0xFF00000000000000,
0xFFFF000000000000,
0xFFFFFF0000000000,
0xFFFFFFFF00000000,
0xFFFFFFFFFF000000,
0xFFFFFFFFFFFF0000,
0xFFFFFFFFFFFFFF00,
0xFFFFFFFFFFFFFFFF
};
#endif
#else
#ifdef IS_INTEL_ENDIAN
inline uinta byteOf1stBitNZ(uinta x) // assumes x != 0
{
if (x & 0x0000FFFF)
return x & 0x000000FF ? 0 : 1;
else
return x & 0x00FF0000 ? 2 : 3;
}
static uinta startMasks[5] =
{
0xFFFFFFFF,
0xFFFFFF00,
0xFFFF0000,
0xFF000000,
0x00000000
};
static uinta endMasks[5] =
{
0x00000000,
0x000000FF,
0x0000FFFF,
0x00FFFFFF,
0xFFFFFFFF,
};
#else
inline uinta byteOf1stBitNZ(uinta x) // assumes x != 0
{
if (x & 0xFFFF0000)
return x & 0xFF000000 ? 0 : 1;
else
return x & 0x0000FF00 ? 2 : 3;
}
static uinta startMasks[5] =
{
0xFFFFFFFF,
0x00FFFFFF,
0x0000FFFF,
0x000000FF,
0x00000000,
};
static uinta endMasks[5] =
{
0x00000000,
0xFF000000,
0xFFFF0000,
0xFFFFFF00,
0xFFFFFFFF,
};
#endif
#endif
#define WORDSIZE ((uinta)(sizeof(void*)))
#define OFFSETMASK ((uinta)(WORDSIZE - 1))
#define WORDMASK ((uinta)(~OFFSETMASK))
inline uinta compareBytesAligned(const uint8 *floor1, const uint8 *floor2, uinta offset, uinta len)
{
const uinta *p1, *p2;
if (offset)
{
p1 = (uinta*)((uinta)floor1 & WORDMASK);
p2 = (uinta*)((uinta)floor2 & WORDMASK);
uinta x = startMasks[offset] & (*p1++ ^ *p2++);
if (x) return byteOf1stBitNZ(x) - offset;
}
else
{
p1 = (uinta*)floor1;
p2 = (uinta*)floor2;
}
const uint8 *roof1 = floor1 + len;
const uinta *p1Roof = (uinta*)((uinta)roof1 & WORDMASK);
if (p1 < p1Roof)
{
uinta x;
do x = *p1++ ^ *p2++; while (!x && p1 != p1Roof);
if (x) return byteOf1stBitNZ(x) + (uint8*)(p1 - 1) - floor1;
}
offset = roof1 - (uint8*)p1Roof;
if (offset)
{
uinta x = endMasks[offset] & (*p1 ^ *p2);
if (x) return byteOf1stBitNZ(x) + len - offset;
}
return len;
}
inline uinta compareBytes2Ahead(const uint8 *floor1, uinta offset1, const uint8 *floor2, uinta offset2, uinta len) // aasumes offset1 < offset2
{
const uinta *p1, *p2;
uinta p2Value = 0;
uinta p2Pending = 0;
offset2 -= offset1;
uinta rShift = 8*offset2;
uinta lShift = 8*(WORDSIZE - offset2);
if (offset1)
{
p1 = (uinta*)((uinta)floor1 & WORDMASK);
p2 = (uinta*)((uinta)floor2 & WORDMASK);
p2Value = *p2++;
p2Pending = *p2++;
#ifdef IS_INTEL_ENDIAN
p2Value = (p2Value >> rShift) | (p2Pending << lShift);
#else
p2Value = (p2Value << rShift) | (p2Pending >> lShift);
#endif
uinta x = startMasks[offset1] & (*p1++ ^ p2Value);
if (x) return byteOf1stBitNZ(x) - offset1;
}
else
{
p1 = (uinta*)floor1;
p2 = (uinta*)((uinta)floor2 & WORDMASK);
p2Pending = *p2++;
}
const uint8 *roof1 = floor1 + len;
const uinta *p1Roof = (uinta*)((uinta)roof1 & WORDMASK);
if (p1 < p1Roof)
{
uinta x;
do
{
p2Value = p2Pending;
p2Pending = *p2++;
#ifdef IS_INTEL_ENDIAN
p2Value = (p2Value >> rShift) | (p2Pending << lShift);
#else
p2Value = (p2Value << rShift) | (p2Pending >> lShift);
#endif
x = *p1++ ^ p2Value;
}
while (!x && p1 != p1Roof);
if (x) return byteOf1stBitNZ(x) + (uint8*)(p1 - 1) - floor1;
}
offset1 = roof1 - (uint8*)p1Roof;
if (offset1)
{
if (offset1 + offset2 > WORDSIZE)
{
p2Value = p2Pending;
p2Pending = *p2;
#ifdef IS_INTEL_ENDIAN
p2Value = (p2Value >> rShift) | (p2Pending << lShift);
#else
p2Value = (p2Value << rShift) | (p2Pending >> lShift);
#endif
}
else
#ifdef IS_INTEL_ENDIAN
p2Value = p2Pending >> rShift;
#else
p2Value = p2Pending << rShift;
#endif
uinta x = endMasks[offset1] & (*p1 ^ p2Value);
if (x) return byteOf1stBitNZ(x) + len - offset1;
}
return len;
}
inline uinta compareBytes(const uint8 *floor1, const uint8 *roof1, const uint8 *floor2, const uint8 *roof2)
{
uinta offset1 = roof1 - floor1;
uinta offset2 = roof2 - floor2;
uinta len = offset1 < offset2 ? offset1 : offset2;
switch (len)
{
case 1:
return *floor1 != *floor2 ? 0 : 1;
case 2:
if (*floor1 != *floor2) return 0;
return *++floor1 != *++floor2 ? 1 : 2;
case 3:
if (*floor1 != *floor2) return 0;
if (*++floor1 != *++floor2) return 1;
return *++floor1 != *++floor2 ? 2 : 3;
default:
offset1 = (uinta)floor1 & OFFSETMASK;
offset2 = (uinta)floor2 & OFFSETMASK;
if (offset2 < offset1)
{
uinta temp = (uinta)floor1;
floor1 = floor2;
floor2 = (uint8*)temp;
temp = offset1;
offset1 = offset2;
offset2 = temp;
}
uinta x = offset1 + len;
if (x & WORDMASK && x != WORDSIZE)
{
if (offset1 == offset2)
return compareBytesAligned(floor1, floor2, offset1, len);
else
return compareBytes2Ahead(floor1, offset1, floor2, offset2, len);
}
else
{
if (offset1 == offset2)
{
x = (*((uinta*)((uinta)floor1 & WORDMASK)) ^ *((uinta*)((uinta)floor2 & WORDMASK))) & startMasks[offset1] & endMasks[x];
return x ? byteOf1stBitNZ(x) - offset1 : len;
}
else if ((offset2 + len - 1) & WORDMASK)
{
uinta *p2 = (uinta*)((uinta)floor2 & WORDMASK);
offset2 -= offset1;
#ifdef IS_INTEL_ENDIAN
x = (*((uinta*)((uinta)floor1 & WORDMASK)) ^ (*p2 >> 8*offset2 | p2[1] << 8*(WORDSIZE - offset2))) & startMasks[offset1] & endMasks[x];
#else
x = (*((uinta*)((uinta)floor1 & WORDMASK)) ^ (*p2 << 8*offset2 | p2[1] >> 8*(WORDSIZE - offset2))) & startMasks[offset1] & endMasks[x];
#endif
return x ? byteOf1stBitNZ(x) - offset1 : len;
}
else
{
#ifdef IS_INTEL_ENDIAN
x = (*((uinta*)((uinta)floor1 & WORDMASK)) ^ (*((uinta*)((uinta)floor2 & WORDMASK)) >> 8*(offset2 - offset1))) & startMasks[offset1] & endMasks[x];
#else
x = (*((uinta*)((uinta)floor1 & WORDMASK)) ^ (*((uinta*)((uinta)floor2 & WORDMASK)) << 8*(offset2 - offset1))) & startMasks[offset1] & endMasks[x];
#endif
return x ? byteOf1stBitNZ(x) - offset1 : len;
}
}
}
}
static uint32 randomSeed = 1;
static const uint8 *randomSeedBytes = (uint8*)&randomSeed;
static void randomFill(uint8 *floor, uint8 *roof)
{
while (floor < roof)
{
randomSeed = 1103515245*randomSeed + 12345;
*floor++ = randomSeedBytes[0];
if (floor >= roof) break;
*floor++ = randomSeedBytes[1];
}
}
static void dumpMemory(FILE *fout, const void *floor, const void *roof)
{
static const TCHAR *rightMarginFormat = sizeof(void*) == 4 ? _T("%08X: ") : _T("%016llX: ");
TCHAR str[17];
str[16] = 0;
uinta padLen = (uinta)floor & 0xF;
uinta pos = 0;
uint8 *pmem = (uint8*)floor;
while (padLen--)
{
if (pos == 0) zfprintf(fout, rightMarginFormat, (uinta)((uint8*)floor - (padLen + 1)));
zfprintf(fout, (pos % 4 == 3 ? _T(" ") : _T(" ")));
str[pos++] = _T(' ');
}
while (pmem < (uint8*)roof)
{
if (pos == 0) zfprintf(fout, rightMarginFormat, (uinta)pmem);
uint8 ch = *pmem++;
zfprintf(fout, _T("%02X "), (uint32)ch);
if (pos % 4 == 3) zfprintf(fout, _T(" "));
str[pos++] = (_T(' ') <= ch && ch <= _T('~')) ? ch : _T('.');
if (pos == 16)
{
zfprintf(fout, _T("%s\n"), str);
pos = 0;
}
}
if (pos && pos != 16)
{
while (pos < 16)
{
zfprintf(fout, (pos % 4 == 3 ? _T(" ") : _T(" ")));
str[pos++] = _T(' ');
}
zfprintf(fout, _T("%s\n"), str);
}
}
#define BUFLEN (0x10000)
static uint8 buf1[BUFLEN];
static uint8 buf2[BUFLEN];
static void compareBytesCheckResult(const TCHAR *message, const uinta expectedResult, const uint8 *floor1, const uint8 *roof1, const uint8 *floor2, const uint8 *roof2)
{
uinta result = compareBytes(floor1, roof1, floor2, roof2);
if (result != expectedResult)
{
uinta len1 = roof1 - floor1;
uinta len2 = roof2 - floor2;
uinta startOffset1 = (uinta)floor1 & OFFSETMASK;
uinta endOffset1 = (uinta)roof1 & OFFSETMASK;
uinta startOffset2 = (uinta)floor2 & OFFSETMASK;
uinta endOffset2 = (uinta)roof2 & OFFSETMASK;
zprintf("\nHOUSTON We'Ve got a problem! %s\n", message);
zprintf(" Got 0x%K (%yu), But Wanted 0x%K (%yu)\n", result, result, expectedResult, expectedResult);
zprintf(" Start Offsets (%yu, %yu) End Offsets (%yu, %yu)\n", startOffset1, startOffset2, endOffset1, endOffset2);
zprintf(" Lengths 0x%K (%yu), 0x%K (%yu)\n", len1, len1, len2, len2);
zprintf("\nDUMPING BUFFER 1\n");
dumpMemory(stdout, (const uint8*)buf1, roof1);
zprintf("\nDUMPING BUFFER 2\n");
dumpMemory(stdout, (const uint8*)buf2, roof2);
zprintf("\n");
exit(0);
}
}
static void testAllPositions(uinta offset1, uinta offset2, uinta len)
{
randomFill(buf1, buf1 + offset1 + offset2 + len);
memcpy(buf2 + offset2, buf1 + offset1, len);
for (uinta i = 0; i < offset1; i++) buf1[i] = 0;
for (uinta i = 0; i < offset2; i++) buf2[i] = 0xFF;
for (uinta i = offset1 + len; i < offset1 + len + WORDSIZE; i++) buf1[i] = 0;
for (uinta i = offset2 + len; i < offset2 + len + WORDSIZE; i++) buf2[i] = 0xFF;
compareBytesCheckResult("(different ends)", len, buf1 + offset1, buf1 + offset1 + len, buf2 + offset2, buf2 + offset2 + len);
for (uinta i = 0; i < len; i++)
{
buf1[offset1 + i] = ~buf1[offset1 + i];
compareBytesCheckResult("(different ends)", i, buf1 + offset1, buf1 + offset1 + len, buf2 + offset2, buf2 + offset2 + len);
buf2[offset2 + i] = ~buf2[offset2 + i];
}
for (uinta i = 0; i < offset2; i++) buf2[i] = 0;
for (uinta i = offset2 + len; i < offset2 + len + WORDSIZE; i++) buf2[i] = 0;
compareBytesCheckResult("(same ends)", len, buf1 + offset1, buf1 + offset1 + len, buf2 + offset2, buf2 + offset2 + len);
for (uinta i = 0; i < len; i++)
{
buf1[offset1 + i] = ~buf1[offset1 + i];
compareBytesCheckResult("(same ends)", i, buf1 + offset1, buf1 + offset1 + len, buf2 + offset2, buf2 + offset2 + len);
buf2[offset2 + i] = ~buf2[offset2 + i];
}
}
static void testShortRuns()
{
for (uinta len = 1; len < 41; len++)
for (uinta offset1 = 0; offset1 < WORDSIZE; offset1++)
for (uinta offset2 = 0; offset2 < WORDSIZE; offset2++)
testAllPositions(offset1, offset2, len);
}
static void testLongRuns()
{
for (uinta len = 7; len < 8*7*7; len += 1)
for (uinta offset1 = 0; offset1 < WORDSIZE; offset1++)
for (uinta offset2 = 0; offset2 < WORDSIZE; offset2++)
testAllPositions(offset1, offset2, len);
}
static void test()
{
testShortRuns();
testLongRuns();
// randomFill(buf1, buf1 + BUFLEN);
// memcpy(buf2, buf1, BUFLEN);
// uinta result = compareBytes(buf1, buf1 + BUFLEN, buf2, buf2 + BUFLEN);
// printf("BUFLEN = %llu, result = %llu\n", (uint64)BUFLEN, (uint64)result);
// buf2[BUFLEN - 2] = 0;
// result = compareBytes(buf1, buf1 + BUFLEN, buf2, buf2 + BUFLEN);
// printf("BUFLEN = %llu, result = %llu\n", (uint64)BUFLEN, (uint64)result);
}
int main(int argc, char *argv[])
{
test();
return 0;
}
| 27.697802 | 167 | 0.544336 | baydroid |
e906176dfa07a8df170a4da4dc34fa7f176baf17 | 4,538 | cpp | C++ | src/maxmatching_test.cpp | chikiulo/yisi | fd07bfc58ab5ce8d5ee41d5e563d3c8d42e992db | [
"MIT"
] | 18 | 2019-01-23T16:06:29.000Z | 2022-02-16T19:26:27.000Z | src/maxmatching_test.cpp | nrc-cnrc/YiSi | fd07bfc58ab5ce8d5ee41d5e563d3c8d42e992db | [
"MIT"
] | 5 | 2019-02-13T13:46:10.000Z | 2022-01-03T14:58:40.000Z | src/maxmatching_test.cpp | nrc-cnrc/YiSi | fd07bfc58ab5ce8d5ee41d5e563d3c8d42e992db | [
"MIT"
] | 1 | 2021-08-13T19:01:18.000Z | 2021-08-13T19:01:18.000Z | /**
* @file maxmatching_test.cpp
* @brief Unit test for maxmatching.
*
* @author Jackie Lo
*
* Multilingual Text Processing / Traitement multilingue de textes
* Digital Technologies Research Centre / Centre de recherche en technologies numériques
* National Research Council Canada / Conseil national de recherches Canada
* Copyright 2018, Her Majesty in Right of Canada /
* Copyright 2018, Sa Majeste la Reine du Chef du Canada
*/
#include <iostream>
#include "maxmatching.h"
using namespace std;
using namespace yisi;
int main(int argc, char* argv[])
{
vector<pair<pair<maxmatching_t::id_type, maxmatching_t::id_type>,
maxmatching_t::weight_type> > r;
//test case 1
//square matrix
// | a| b| c
//1|1.0|0.0|0.0
//2|0.0|1.0|0.0
//3|0.0|0.0|1.0
maxmatching_t t1;
t1.add_weight(0, 3, 1.0);
t1.add_weight(0, 4, 0.0);
t1.add_weight(0, 5, 0.0);
t1.add_weight(1, 3, 0.0);
t1.add_weight(1, 4, 1.0);
t1.add_weight(1, 5, 0.0);
t1.add_weight(2, 3, 0.0);
t1.add_weight(2, 4, 0.0);
t1.add_weight(2, 5, 1.0);
r = t1.run();
cout << "Test case 1: " << endl;
cout << " | 3| 4| 5" << endl;
cout << "0|1.0|0.0|0.0" << endl;
cout << "1|0.0|1.0|0.0" << endl;
cout << "2|0.0|0.0|1.0" << endl;
for (size_t i = 0; i < r.size(); i++) {
cout << "(" << r[i].first.first << "," << r[i].first.second << ","
<< r[i].second << ")" << endl;
}
r.clear();
//test case 2
//square matrix
// | a| b| c
//1|0.7|0.3|0.0
//2|0.0|0.7|0.3
//3|0.3|0.0|0.7
maxmatching_t t2;
t2.add_weight(0, 3, 0.7);
t2.add_weight(0, 4, 0.3);
t2.add_weight(0, 5, 0.0);
t2.add_weight(1, 3, 0.0);
t2.add_weight(1, 4, 0.7);
t2.add_weight(1, 5, 0.3);
t2.add_weight(2, 3, 0.3);
t2.add_weight(2, 4, 0.0);
t2.add_weight(2, 5, 0.7);
r = t2.run();
cout << "Test case 2: " << endl;
cout << " | 3| 4| 5" << endl;
cout << "0|0.7|0.3|0.0" << endl;
cout << "1|0.0|0.7|0.3" << endl;
cout << "2|0.3|0.0|0.7" << endl;
for (size_t i = 0; i < r.size(); i++) {
cout << "(" << r[i].first.first << "," << r[i].first.second << ","
<< r[i].second << ")" << endl;
}
r.clear();
//test case 3
//square matrix
// | a| b| c
//1|1.0|1.0|0.8
//2|0.9|0.8|0.1
//3|0.9|0.7|0.4
maxmatching_t t3;
t3.add_weight(0, 3, 1.0);
t3.add_weight(0, 4, 1.0);
t3.add_weight(0, 5, 0.8);
t3.add_weight(1, 3, 0.9);
t3.add_weight(1, 4, 0.8);
t3.add_weight(1, 5, 0.1);
t3.add_weight(2, 3, 0.9);
t3.add_weight(2, 4, 0.7);
t3.add_weight(2, 5, 0.4);
r = t3.run();
cout << "Test case 3: " << endl;
cout << " | 3| 4| 5" << endl;
cout << "0|1.0|1.0|0.8" << endl;
cout << "1|0.9|0.8|0.1" << endl;
cout << "2|0.9|0.7|0.4" << endl;
for (size_t i = 0; i < r.size(); i++) {
cout << "(" << r[i].first.first << "," << r[i].first.second << ","
<< r[i].second << ")" << endl;
}
r.clear();
//test case 4
//rectangular matrix
// | a| b
//1|0.9|0.9
//2|0.9|0.8
//3|0.8|0.1
//4|1.0|0.1
maxmatching_t t4;
t4.add_weight(0, 4, 0.9);
t4.add_weight(0, 5, 0.9);
t4.add_weight(1, 4, 0.9);
t4.add_weight(1, 5, 0.8);
t4.add_weight(2, 4, 0.8);
t4.add_weight(2, 5, 0.1);
t4.add_weight(3, 4, 1.0);
t4.add_weight(3, 5, 0.1);
r = t4.run();
cout << "Test case 4: " << endl;
cout << " | 4| 5" << endl;
cout << "0|0.9|0.9" << endl;
cout << "1|0.9|0.8" << endl;
cout << "2|0.8|0.1" << endl;
cout << "3|1.0|0.1" << endl;
for (size_t i = 0; i < r.size(); i++) {
cout << "(" << r[i].first.first << "," << r[i].first.second << ","
<< r[i].second << ")" << endl;
}
r.clear();
//test case 5
//rectangular matrix
// | a| b
//1|0.9|0.7
//2|0.8|0.6
//3|0.7|0.1
//4|0.9|0.1
maxmatching_t t5;
t5.add_weight(0, 4, 0.9);
t5.add_weight(0, 5, 0.7);
t5.add_weight(1, 4, 0.8);
t5.add_weight(1, 5, 0.6);
t5.add_weight(2, 4, 0.7);
t5.add_weight(2, 5, 0.1);
t5.add_weight(3, 4, 0.9);
t5.add_weight(3, 5, 0.1);
r = t5.run();
cout << "Test case 5: " << endl;
cout << " | 4| 5" << endl;
cout << "0|0.9|0.7" << endl;
cout << "1|0.8|0.6" << endl;
cout << "2|0.7|0.1" << endl;
cout << "3|0.9|0.1" << endl;
for (size_t i = 0; i < r.size(); i++) {
cout << "(" << r[i].first.first << "," << r[i].first.second << ","
<< r[i].second << ")" << endl;
}
r.clear();
return 0;
} // main
| 25.784091 | 88 | 0.494271 | chikiulo |
e90e9b77a42ee42082241bec9e9d6806ab76d43f | 2,458 | cpp | C++ | Modules/DiffusionCore/DicomImport/mitkDiffusionHeaderGEDICOMFileReader.cpp | HRS-Navigation/MITK-Diffusion | b1bf62d1c76f0d0cc26dd252561cb5d8769b4f87 | [
"BSD-3-Clause"
] | 37 | 2019-07-05T10:55:06.000Z | 2022-03-21T12:09:35.000Z | Modules/DiffusionImaging/DiffusionCore/src/DicomImport/mitkDiffusionHeaderGEDICOMFileReader.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 6 | 2019-11-04T16:05:47.000Z | 2022-03-22T15:53:31.000Z | Modules/DiffusionImaging/DiffusionCore/src/DicomImport/mitkDiffusionHeaderGEDICOMFileReader.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 10 | 2019-10-15T14:37:26.000Z | 2022-02-18T03:22:01.000Z | #include "mitkDiffusionHeaderGEDICOMFileReader.h"
#include <vnl/vnl_math.h>
mitk::DiffusionHeaderGEDICOMFileReader
::DiffusionHeaderGEDICOMFileReader()
{
}
mitk::DiffusionHeaderGEDICOMFileReader
::~DiffusionHeaderGEDICOMFileReader()
{
}
bool mitk::DiffusionHeaderGEDICOMFileReader
::ReadDiffusionHeader(std::string filename)
{
gdcm::Reader gdcmReader;
gdcmReader.SetFileName( filename.c_str() );
gdcmReader.Read();
gdcm::Tag ge_bvalue_tag( 0x0043, 0x1039 );
gdcm::Tag ge_gradient_x( 0x0019, 0x10bb );
gdcm::Tag ge_gradient_y( 0x0019, 0x10bc );
gdcm::Tag ge_gradient_z( 0x0019, 0x10bd );
bool success = true;
DiffusionImageDICOMHeaderInformation header_info;
std::string ge_tagvalue_string;
char* pEnd;
// start with b-value
success = RevealBinaryTag( ge_bvalue_tag, gdcmReader.GetFile().GetDataSet(), ge_tagvalue_string );
// b value stored in the first bytes
// typical example: "1000\8\0\0" for bvalue=1000
// "40\8\0\0" for bvalue=40
// so we need to cut off the last 6 elements
const char* bval_string = ge_tagvalue_string.substr(0,ge_tagvalue_string.length()-6).c_str();
header_info.b_value = static_cast<unsigned int>(strtod( bval_string, &pEnd ));
// now retrieve the gradient direction
if(success &&
RevealBinaryTag( ge_gradient_x, gdcmReader.GetFile().GetDataSet(), ge_tagvalue_string ) )
{
header_info.g_vector[0] = strtod( ge_tagvalue_string.c_str(), &pEnd );
}
else
{
success = false;
}
if( success &&
RevealBinaryTag( ge_gradient_y, gdcmReader.GetFile().GetDataSet(), ge_tagvalue_string ) )
{
header_info.g_vector[1] = strtod( ge_tagvalue_string.c_str(), &pEnd );
}
else
{
success = false;
}
if( success &&
RevealBinaryTag( ge_gradient_z, gdcmReader.GetFile().GetDataSet(), ge_tagvalue_string ) )
{
header_info.g_vector[2] = strtod( ge_tagvalue_string.c_str(), &pEnd );
}
else
{
success = false;
}
if( success )
{
// Fix for (0,0,0) direction in IVIM datasets
if( header_info.b_value > 0 &&
header_info.g_vector.two_norm() < vnl_math::eps )
{
header_info.g_vector.fill(1);
header_info.g_vector.normalize();
header_info.isotropic = true;
}
// mark baseline
if( header_info.b_value == 0 )
header_info.baseline = true;
this->m_HeaderInformationList.push_back( header_info );
header_info.Print();
}
return success;
}
| 23.864078 | 100 | 0.691619 | HRS-Navigation |
e91175226283e9704ced1f0a0c1d2e5f384cc5f9 | 3,547 | hh | C++ | elements/ids/ahocorasickplus.hh | regufo/fastclick | d56d31c722266ea5d0cfd31435e81ca10dda5e69 | [
"BSD-3-Clause-Clear"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | elements/ids/ahocorasickplus.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | elements/ids/ahocorasickplus.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | /*
*
* This file is part of multifast. Modified to work with click by Pavel Lazar
*
Copyright 2010-2015 Kamiar Kanani <kamiar.kanani@gmail.com>
multifast is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
multifast 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 multifast. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CLICK_AHOCORASICKPLUS_H_
#define CLICK_AHOCORASICKPLUS_H_
#include "ahocorasick.h"
#include <click/string.hh>
#include <click/packet.hh>
CLICK_DECLS
// Forward declarations
struct ac_trie;
struct ac_text;
class AhoCorasick
{
public:
enum EnumReturnStatus
{
RETURNSTATUS_SUCCESS = 0, // No error occurred
RETURNSTATUS_DUPLICATE_PATTERN, // Duplicate patterns
RETURNSTATUS_LONG_PATTERN, // Long pattern
RETURNSTATUS_ZERO_PATTERN, // Empty pattern (zero length)
RETURNSTATUS_AUTOMATA_CLOSED, // Automata is closed
RETURNSTATUS_FAILED, // General unknown failure
};
typedef unsigned int PatternId;
struct Match
{
unsigned int position;
PatternId id;
};
public:
AhoCorasick();
~AhoCorasick();
EnumReturnStatus add_pattern (const String &pattern, PatternId id);
EnumReturnStatus add_pattern (const char pattern[], PatternId id);
void finalize();
void reset();
bool match_any (const String& text, bool keep);
bool match_any (const Packet *p, bool keep);
bool match_any (const char* text, int size, bool keep);
int match_first(const char* text, int size, bool keep);
int match_first(const Packet *p, bool keep);
int match_first(const String& text, bool keep);
bool is_open();
private:
struct ac_trie *_automata;
AC_TEXT_t *_text;
};
inline bool
AhoCorasick::match_any (const String& text, bool keep) {
return match_any(text.c_str(), text.length(), keep);
}
inline bool
AhoCorasick::match_any(const Packet* p, bool keep) {
return match_any((char *)p->data(), p->length(), keep);
}
inline int
AhoCorasick::match_first(const Packet* p, bool keep) {
return match_first((char *)p->data(), p->length(), keep);
}
inline int
AhoCorasick::match_first(const String& text, bool keep) {
return match_first(text.c_str(), text.length(), keep);
}
inline void
AhoCorasick::finalize ()
{
ac_trie_finalize (_automata);
}
inline bool
AhoCorasick::match_any(const char* text_to_match, int length, bool keep) {
_text->astring = text_to_match;
_text->length = length;
ac_trie_settext(_automata, _text, (int)keep);
AC_MATCH_t match = ac_trie_findnext(_automata);
return match.size > 0;
}
inline int
AhoCorasick::match_first(const char* text_to_match, int length, bool keep) {
_text->astring = text_to_match;
_text->length = length;
ac_trie_settext(_automata, _text, (int)keep);
AC_MATCH_t match = ac_trie_findnext(_automata);
if (match.size > 0) {
return (int) match.patterns->id.u.number;
}
return -1;
}
inline void
AhoCorasick::reset() {
ac_trie_release (_automata);
_automata = ac_trie_create ();
}
inline bool
AhoCorasick::is_open() {
return _automata->trie_open != 0;
}
CLICK_ENDDECLS
#endif /* CLICK_AHOCORASICKPLUS_H_ */
| 26.080882 | 77 | 0.733014 | regufo |
e9130d11252c70bebaad27ae1d481ffad762fd0e | 18,473 | cpp | C++ | Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_USB_HID.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 216 | 2019-03-09T06:41:28.000Z | 2022-02-25T16:27:19.000Z | Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_USB_HID.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 9 | 2020-09-27T08:00:52.000Z | 2021-07-02T14:27:31.000Z | Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_USB_HID.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 29 | 2019-03-09T10:12:24.000Z | 2021-03-03T22:25:29.000Z | //
// FILE NAME: CIDMacroEng_USBHIDClass.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 02/11/2005
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements a set of derivatives of the class info and class
// value classes, which implement the fundamental MEng.USBHID macro class.
//
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Facility specific includes
// ---------------------------------------------------------------------------
#include "CIDMacroEng_.hpp"
// ---------------------------------------------------------------------------
// Magic RTTI macros
// ---------------------------------------------------------------------------
RTTIDecls(TMEngUSBHIDVal,TMEngClassVal)
RTTIDecls(TMEngUSBHIDInfo,TMEngClassInfo)
// ---------------------------------------------------------------------------
// Local data
// ---------------------------------------------------------------------------
namespace
{
namespace CIDMacroEng_USBHIDClasses
{
// -----------------------------------------------------------------------
// The names for the types that we support here. Each derivative has to
// be able to return strings that contain its name and full name.
// -----------------------------------------------------------------------
const TString strUSBHID(L"USBHID");
const TString strUSBHIDClassPath(L"MEng.System.Runtime.USBHID");
}
}
// ---------------------------------------------------------------------------
// CLASS: TMEngUSBHIDVal
// PREFIX: mecv
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngUSBHIDVal: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngUSBHIDVal::TMEngUSBHIDVal( const TString& strName
, const tCIDLib::TCard2 c2Id
, const tCIDMacroEng::EConstTypes eConst) :
TMEngClassVal(strName, c2Id, eConst)
, m_c2ProductId(0)
, m_c2VendorId(0)
{
}
TMEngUSBHIDVal::~TMEngUSBHIDVal()
{
// If they didn't close it, then we need to
try
{
if (m_flDevice.bIsOpen())
m_flDevice.Close();
}
catch(TError& errToCatch)
{
// If in verbose mode we'll log the C++ error
if (!errToCatch.bLogged() && facCIDMacroEng().bLogWarnings())
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
}
}
// ---------------------------------------------------------------------------
// TMEngUSBHIDVal: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngUSBHIDVal::bDbgFormat( TTextOutStream& strmTarget
, const TMEngClassInfo&
, const tCIDMacroEng::EDbgFmts eFormat
, const tCIDLib::ERadices
, const TCIDMacroEngine& ) const
{
if (eFormat == tCIDMacroEng::EDbgFmts::Short)
{
if (m_flDevice.bIsOpen())
strmTarget << L"[Device is open]";
else
strmTarget << L"[Device is closed]";
return kCIDLib::True;
}
else if (eFormat == tCIDMacroEng::EDbgFmts::Long)
{
if (m_flDevice.bIsOpen())
{
strmTarget << L"Vendor Id = 0x"
<< TTextOutStream::strmfHex4() << m_c2VendorId
<< TTextOutStream::strmfDefault()
<< L"\nProduct Id = 0x"
<< TTextOutStream::strmfHex4() << m_c2ProductId
<< TTextOutStream::strmfDefault();
}
}
return kCIDLib::False;
}
// ---------------------------------------------------------------------------
// TMEngUSBHIDVal: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngUSBHIDVal::bFindDevPath(const tCIDLib::TCard2 c2VendorId
, const tCIDLib::TCard2 c2ProductId
, TString& strToFill)
{
// Try to find a device with the indicated ids
if (TUSBDev::bFindHIDDev(c2VendorId, c2ProductId, strToFill))
return kCIDLib::True;
return kCIDLib::False;
}
tCIDLib::TBoolean
TMEngUSBHIDVal::bReadBytes( TMemBuf& mbufToFill
, const tCIDLib::TCard4 c4ToRead
, const tCIDLib::TCard4 c4WaitFor
, const tCIDLib::TBoolean bThrowIfNot)
{
return m_flDevice.c4ReadBufferTO
(
mbufToFill.pc1Data()
, c4ToRead
, c4WaitFor
, m_evIO
, bThrowIfNot
) == 9;
}
tCIDLib::TVoid
TMEngUSBHIDVal::Open(const TString& strDevPath
, const tCIDLib::TCard2 c2VendorId
, const tCIDLib::TCard2 c2ProductId)
{
m_flDevice.strName(strDevPath);
m_flDevice.Open
(
tCIDLib::EAccessModes::ReadWrite
, tCIDLib::ECreateActs::OpenIfExists
, tCIDLib::EFilePerms::Default
, tCIDLib::EFileFlags::USBDevice
);
// It worked, so set the ids
m_c2VendorId = c2VendorId;
m_c2ProductId = c2ProductId;
}
tCIDLib::TVoid TMEngUSBHIDVal::Close()
{
// If the device is open, then close it
if (m_flDevice.bIsOpen())
m_flDevice.Close();
}
tCIDLib::TVoid TMEngUSBHIDVal::Reset()
{
// Shouldn't be possible, but close it just in case
if (m_flDevice.bIsOpen())
m_flDevice.Close();
}
tCIDLib::TVoid
TMEngUSBHIDVal::WriteBytes( const TMemBuf& mbufToSend
, const tCIDLib::TCard4 c4ToSend
, const tCIDLib::TCard4 c4WaitFor)
{
m_flDevice.c4WriteBufferTO
(
mbufToSend.pc1Data()
, c4ToSend
, c4WaitFor
, m_evIO
);
}
// ---------------------------------------------------------------------------
// CLASS: TMEngUSBHIDInfo
// PREFIX: meci
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngUSBHIDInfo: Public, static methods
// ---------------------------------------------------------------------------
const TString& TMEngUSBHIDInfo::strPath()
{
return CIDMacroEng_USBHIDClasses::strUSBHIDClassPath;
}
// ---------------------------------------------------------------------------
// TMEngUSBHIDInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngUSBHIDInfo::TMEngUSBHIDInfo(TCIDMacroEngine& meOwner) :
TMEngClassInfo
(
CIDMacroEng_USBHIDClasses::strUSBHID
, TFacCIDMacroEng::strRuntimeClassPath
, meOwner
, kCIDLib::False
, tCIDMacroEng::EClassExt::Final
, L"MEng.Object"
)
, m_c2EnumId_Errors(kCIDMacroEng::c2BadId)
, m_c2MethId_DefCtor(kCIDMacroEng::c2BadId)
, m_c2MethId_Close(kCIDMacroEng::c2BadId)
, m_c2MethId_FindDevice(kCIDMacroEng::c2BadId)
, m_c2MethId_Open(kCIDMacroEng::c2BadId)
, m_c2MethId_Read(kCIDMacroEng::c2BadId)
, m_c2MethId_Write(kCIDMacroEng::c2BadId)
, m_c4ErrCloseFailed(kCIDLib::c4MaxCard)
, m_c4ErrDevNotFound(kCIDLib::c4MaxCard)
, m_c4ErrOpenFailed(kCIDLib::c4MaxCard)
, m_c4ErrReadFailed(kCIDLib::c4MaxCard)
, m_c4ErrWriteFailed(kCIDLib::c4MaxCard)
, m_pmeciErrors(nullptr)
{
}
TMEngUSBHIDInfo::~TMEngUSBHIDInfo()
{
}
// ---------------------------------------------------------------------------
// TMEngUSBHIDInfo: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TMEngUSBHIDInfo::Init(TCIDMacroEngine& meOwner)
{
//
// We need to add some nested enum types. First we do one for the days
// of the week, months, and then for errors.
//
{
m_pmeciErrors = new TMEngEnumInfo
(
meOwner
, L"USBHIDErrors"
, strClassPath()
, L"MEng.Enum"
, 5
);
m_c4ErrCloseFailed = m_pmeciErrors->c4AddEnumItem(L"CloseFailed", TString::strEmpty());
m_c4ErrDevNotFound = m_pmeciErrors->c4AddEnumItem(L"DevNotFound", L"No device with ids %(1)/%(2) was found");
m_c4ErrOpenFailed = m_pmeciErrors->c4AddEnumItem(L"OpenFailed", TString::strEmpty());
m_c4ErrReadFailed = m_pmeciErrors->c4AddEnumItem(L"ReadFailed", TString::strEmpty());
m_c4ErrWriteFailed = m_pmeciErrors->c4AddEnumItem(L"WriteFailed", TString::strEmpty());
m_pmeciErrors->BaseClassInit(meOwner);
m_c2EnumId_Errors = meOwner.c2AddClass(m_pmeciErrors);
bAddNestedType(m_pmeciErrors->strClassPath());
}
// Add the default constructor
{
TMEngMethodInfo methiNew
(
L"ctor1_MEng.USBHID"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.bIsCtor(kCIDLib::True);
m_c2MethId_DefCtor = c2AddMethodInfo(methiNew);
}
// Close the device if open
{
TMEngMethodInfo methiNew
(
L"Close"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
m_c2MethId_Close = c2AddMethodInfo(methiNew);
}
// Close the device if a device is present
{
TMEngMethodInfo methiNew
(
L"FindDevice"
, tCIDMacroEng::EIntrinsics::Boolean
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"VendorId", tCIDMacroEng::EIntrinsics::Card2);
methiNew.c2AddInParm(L"ProductId", tCIDMacroEng::EIntrinsics::Card2);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_FindDevice = c2AddMethodInfo(methiNew);
}
// Open the device based on vendor/product id
{
TMEngMethodInfo methiNew
(
L"Open"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"VendorId", tCIDMacroEng::EIntrinsics::Card2);
methiNew.c2AddInParm(L"ProductId", tCIDMacroEng::EIntrinsics::Card2);
m_c2MethId_Open = c2AddMethodInfo(methiNew);
}
// Read bytes from the device
{
TMEngMethodInfo methiNew
(
L"Read"
, tCIDMacroEng::EIntrinsics::Boolean
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInParm(L"Count", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"ThrowIfNot", tCIDMacroEng::EIntrinsics::Boolean);
m_c2MethId_Read = c2AddMethodInfo(methiNew);
}
// Write bytes to the device
{
TMEngMethodInfo methiNew
(
L"Write"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"ToWrite", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInParm(L"Count", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_Write = c2AddMethodInfo(methiNew);
}
}
TMEngClassVal*
TMEngUSBHIDInfo::pmecvMakeStorage(const TString& strName
, TCIDMacroEngine& meOwner
, const tCIDMacroEng::EConstTypes eConst) const
{
return new TMEngUSBHIDVal(strName, c2Id(), eConst);
}
// ---------------------------------------------------------------------------
// TMEngUSBHIDInfo: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngUSBHIDInfo::bInvokeMethod( TCIDMacroEngine& meOwner
, const TMEngMethodInfo& methiTarget
, TMEngClassVal& mecvInstance)
{
TMEngUSBHIDVal& mecvActual = static_cast<TMEngUSBHIDVal&>(mecvInstance);
const tCIDLib::TCard4 c4FirstInd = meOwner.c4FirstParmInd(methiTarget);
const tCIDLib::TCard2 c2MethId = methiTarget.c2Id();
if (c2MethId == m_c2MethId_DefCtor)
{
try
{
mecvActual.Reset();
}
catch(TError& errToCatch)
{
// If in verbose mode we'll log the C++ error
if (!errToCatch.bLogged() && facCIDMacroEng().bLogWarnings())
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
ThrowAnErr(meOwner, m_c4ErrCloseFailed, errToCatch.strErrText());
}
}
else if (c2MethId == m_c2MethId_Close)
{
try
{
mecvActual.Close();
}
catch(TError& errToCatch)
{
// If in verbose mode we'll log the C++ error
if (!errToCatch.bLogged() && facCIDMacroEng().bLogWarnings())
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
ThrowAnErr(meOwner, m_c4ErrCloseFailed, errToCatch.strErrText());
}
}
else if (c2MethId == m_c2MethId_FindDevice)
{
const tCIDLib::TCard2 c2VendorId = meOwner.c2StackValAt(c4FirstInd);
const tCIDLib::TCard2 c2ProductId = meOwner.c2StackValAt(c4FirstInd + 1);
TMEngStringVal& mecvPath = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 2);
TMEngBooleanVal& mecvRet = meOwner.mecvStackAtAs<TMEngBooleanVal>(c4FirstInd - 1);
mecvRet.bValue
(
mecvActual.bFindDevPath(c2VendorId, c2ProductId, mecvPath.strValue())
);
}
else if (c2MethId == m_c2MethId_Open)
{
// First see if there is such a device
TString strPath;
const tCIDLib::TCard2 c2VendorId = meOwner.c2StackValAt(c4FirstInd);
const tCIDLib::TCard2 c2ProductId = meOwner.c2StackValAt(c4FirstInd + 1);
if (!mecvActual.bFindDevPath(c2VendorId, c2ProductId, strPath))
{
ThrowAnErr
(
meOwner
, m_c4ErrDevNotFound
, TCardinal(c2VendorId)
, TCardinal(c2ProductId)
);
}
try
{
mecvActual.Open(strPath, c2VendorId, c2ProductId);
}
catch(const TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrOpenFailed, errToCatch.strErrText());
}
}
else if (c2MethId == m_c2MethId_Read)
{
tCIDLib::TBoolean bRet = kCIDLib::False;
try
{
bRet = mecvActual.bReadBytes
(
meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd).mbufValue()
, meOwner.c4StackValAt(c4FirstInd + 1)
, meOwner.c4StackValAt(c4FirstInd + 2)
, meOwner.bStackValAt(c4FirstInd + 3)
);
}
catch(const TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrReadFailed, errToCatch.strErrText());
}
TMEngBooleanVal& mecvRet = meOwner.mecvStackAtAs<TMEngBooleanVal>(c4FirstInd - 1);
mecvRet.bValue(bRet);
}
else if (c2MethId == m_c2MethId_Write)
{
try
{
mecvActual.WriteBytes
(
meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd).mbufValue()
, meOwner.c4StackValAt(c4FirstInd + 1)
, meOwner.c4StackValAt(c4FirstInd + 2)
);
}
catch(const TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrWriteFailed, errToCatch.strErrText());
}
}
else
{
return kCIDLib::False;
}
return kCIDLib::True;
}
// ---------------------------------------------------------------------------
// TMEngUSBHIDInfo: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid
TMEngUSBHIDInfo::ThrowAnErr( TCIDMacroEngine& meOwner
, const tCIDLib::TCard4 c4ToThrow
, const TString& strText)
{
// Set the exception info on the engine
meOwner.SetException
(
m_c2EnumId_Errors
, strClassPath()
, c4ToThrow
, m_pmeciErrors->strPartialName(c4ToThrow)
, strText
, meOwner.c4CurLine()
);
// And throw the excpetion that represents a macro level exception
throw TExceptException();
}
tCIDLib::TVoid
TMEngUSBHIDInfo::ThrowAnErr( TCIDMacroEngine& meOwner
, const tCIDLib::TCard4 c4ToThrow
, const MFormattable& fmtblToken1
, const MFormattable& fmtblToken2)
{
TString strText(m_pmeciErrors->strTextValue(c4ToThrow));
strText.eReplaceToken(fmtblToken1, kCIDLib::chDigit1);
strText.eReplaceToken(fmtblToken2, kCIDLib::chDigit2);
// Set the exception info on the engine
meOwner.SetException
(
m_c2EnumId_Errors
, strClassPath()
, c4ToThrow
, m_pmeciErrors->strPartialName(c4ToThrow)
, strText
, meOwner.c4CurLine()
);
// And throw the excpetion that represents a macro level exception
throw TExceptException();
}
| 32.015598 | 117 | 0.525794 | MarkStega |
e91352a4d7747e3a94d178e11517004402fb12ef | 16,265 | cpp | C++ | core/mapi/cache/namedPropCache.cpp | bradhugh/mfcmapi | d5bf8e44132a7b1c2fca6c725c915c4eb83e9557 | [
"MIT"
] | null | null | null | core/mapi/cache/namedPropCache.cpp | bradhugh/mfcmapi | d5bf8e44132a7b1c2fca6c725c915c4eb83e9557 | [
"MIT"
] | null | null | null | core/mapi/cache/namedPropCache.cpp | bradhugh/mfcmapi | d5bf8e44132a7b1c2fca6c725c915c4eb83e9557 | [
"MIT"
] | null | null | null | #include <core/stdafx.h>
#include <core/mapi/cache/namedPropCache.h>
#include <core/mapi/cache/namedProps.h>
#include <core/interpret/guid.h>
#include <core/mapi/mapiMemory.h>
#include <core/mapi/mapiFunctions.h>
#include <core/utility/registry.h>
#include <core/utility/strings.h>
#include <core/utility/output.h>
#include <core/addin/mfcmapi.h>
#include <core/addin/addin.h>
#include <core/utility/error.h>
namespace cache
{
namespace directMapi
{
_Check_return_ HRESULT GetRange(
_In_ LPMAPIPROP lpMAPIProp,
ULONG start,
ULONG end,
std::vector<std::shared_ptr<namedPropCacheEntry>>& names)
{
if (start > end) return {};
// Allocate our tag array
const auto count = end - start + 1;
auto lpTag = mapi::allocate<LPSPropTagArray>(CbNewSPropTagArray(count));
if (lpTag)
{
// Populate the array
lpTag->cValues = count;
for (ULONG tag = start, i = 0; tag <= end; tag++, i++)
{
mapi::setTag(lpTag, i) = PROP_TAG(PT_NULL, tag);
}
const HRESULT hRes = WC_H(GetNamesFromIDs(lpMAPIProp, lpTag, NULL, names));
MAPIFreeBuffer(lpTag);
return hRes;
}
return E_OUTOFMEMORY;
}
_Check_return_ std::vector<std::shared_ptr<namedPropCacheEntry>>
GetAllNamesFromIDs(_In_ LPMAPIFOLDER lpMAPIFolder)
{
auto names = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
// We didn't get any names - try manual
constexpr auto ulLowerBound = __LOWERBOUND;
const auto ulUpperBound = FindHighestNamedProp(lpMAPIFolder);
ULONG batchSize = registry::namedPropBatchSize;
output::DebugPrint(
output::dbgLevel::NamedProp,
L"GetAllNamesFromIDs: Walking through all IDs from 0x%X to 0x%X, looking for mappings to names\n",
ulLowerBound,
ulUpperBound);
auto iTag = ulLowerBound;
while (iTag <= ulUpperBound && iTag < __UPPERBOUND)
{
auto end = min(iTag + batchSize - 1, ulUpperBound);
std::vector<std::shared_ptr<namedPropCacheEntry>> range;
range.reserve(batchSize);
// Trying to get a range of these props can fail with MAPI_E_CALL_FAILED if it's too big for the buffer
// In this scenario, reopen the object, lower the batch size, and try again
HRESULT hRes = WC_H(GetRange(lpMAPIFolder, iTag, end, range));
if (hRes == MAPI_E_CALL_FAILED)
{
LPMAPIFOLDER newFolder = nullptr;
hRes = WC_H(GetRootFolder(lpMAPIFolder, &newFolder));
// If we can't re-open the root folder, something is bad - just break out
if (FAILED(hRes))
{
break;
}
// Swap the folder, lower the batch size, and try again
lpMAPIFolder->Release();
lpMAPIFolder = newFolder;
batchSize /= 2;
// If batch size drops to 0, it's not going to work
if (batchSize == 0)
{
break;
}
continue;
}
else if (FAILED(hRes))
{
// Other errors are unexpected
break;
}
for (const auto& name : range)
{
if (name->getMapiNameId()->lpguid != nullptr)
{
names.push_back(name);
}
}
// Go to the next batch
iTag += batchSize;
}
lpMAPIFolder->Release();
return names;
}
_Check_return_ std::vector<std::shared_ptr<namedPropCacheEntry>>
GetAllNamesFromIDsFromContainer(LPMAPICONTAINER lpMAPIContainer)
{
LPMAPIFOLDER lpRootFolder = nullptr;
if (FAILED(GetRootFolder(lpMAPIContainer, &lpRootFolder)))
{
return {};
}
return GetAllNamesFromIDs(lpRootFolder);
}
_Check_return_ std::vector<std::shared_ptr<namedPropCacheEntry>> GetAllNamesFromIDsFromMdb(LPMDB lpMdb)
{
LPMAPIFOLDER lpRootFolder = nullptr;
if (FAILED(GetRootFolder(lpMdb, &lpRootFolder)))
{
return {};
}
return GetAllNamesFromIDs(lpRootFolder);
}
// Returns a vector of NamedPropCacheEntry for the input tags
// Sourced directly from MAPI
_Check_return_ HRESULT GetNamesFromIDs(
_In_ LPMAPIPROP lpMAPIProp,
_In_opt_ LPSPropTagArray lpPropTags,
ULONG ulFlags,
std::vector<std::shared_ptr<namedPropCacheEntry>>& names)
{
if (!lpMAPIProp)
{
return E_INVALIDARG;
}
LPMAPINAMEID* lppPropNames = nullptr;
LPSPropTagArray lpPropTagsLocal = lpPropTags;
auto ulPropNames = ULONG{};
// Try a direct call first
const auto hRes = WC_H_GETPROPS(
lpMAPIProp->GetNamesFromIDs(&lpPropTagsLocal, nullptr, ulFlags, &ulPropNames, &lppPropNames));
// If we failed and we were doing an all props lookup, try it manually instead
if (hRes == MAPI_E_CALL_FAILED && !lpPropTags)
{
auto lpContainer = mapi::safe_cast<LPMAPICONTAINER>(lpMAPIProp);
if (lpContainer)
{
names = GetAllNamesFromIDsFromContainer(lpContainer);
lpContainer->Release();
return S_OK;
}
auto lpMdb = mapi::safe_cast<LPMDB>(lpMAPIProp);
if (lpMdb)
{
names = GetAllNamesFromIDsFromMdb(lpMdb);
lpMdb->Release();
return S_OK;
}
// Can't do the get all props special route because object wasn't IID_IMAPIContainer
return hRes;
}
if (ulPropNames && lppPropNames)
{
for (ULONG i = 0; i < ulPropNames; i++)
{
auto ulPropID = ULONG{};
if (lpPropTagsLocal) ulPropID = PROP_ID(mapi::getTag(lpPropTagsLocal, i));
names.emplace_back(namedPropCacheEntry::make(lppPropNames[i], ulPropID));
}
}
// Only free if it was allocated by GetNamesFromIDs
if (lpPropTagsLocal != lpPropTags)
{
MAPIFreeBuffer(lpPropTagsLocal);
}
return hRes;
}
// Returns a vector of NamedPropCacheEntry for the input tags
// Sourced directly from MAPI
_Check_return_ HRESULT GetNamesFromIDs(
_In_ LPMAPIPROP lpMAPIProp,
_In_ const std::vector<ULONG> tags,
ULONG ulFlags,
std::vector<std::shared_ptr<namedPropCacheEntry>>& names)
{
if (!lpMAPIProp)
{
return E_INVALIDARG;
}
const auto countTags = ULONG(tags.size());
auto ulPropTags = mapi::allocate<LPSPropTagArray>(CbNewSPropTagArray(countTags));
if (ulPropTags)
{
ulPropTags->cValues = countTags;
ULONG i = 0;
for (const auto& tag : tags)
{
mapi::setTag(ulPropTags, i++) = tag;
}
return WC_H(GetNamesFromIDs(lpMAPIProp, ulPropTags, ulFlags, names));
}
MAPIFreeBuffer(ulPropTags);
return E_OUTOFMEMORY;
}
// Returns a vector of tags for the input names
// Sourced directly from MAPI
_Check_return_ LPSPropTagArray
GetIDsFromNames(_In_ LPMAPIPROP lpMAPIProp, std::vector<MAPINAMEID> nameIDs, ULONG ulFlags)
{
if (!lpMAPIProp) return {};
LPSPropTagArray lpTags = nullptr;
if (nameIDs.empty())
{
WC_H_GETPROPS_S(lpMAPIProp->GetIDsFromNames(0, nullptr, ulFlags, &lpTags));
}
else
{
std::vector<const MAPINAMEID*> lpNameIDs = {};
for (const auto& nameID : nameIDs)
{
lpNameIDs.emplace_back(&nameID);
}
auto names = const_cast<MAPINAMEID**>(lpNameIDs.data());
WC_H_GETPROPS_S(lpMAPIProp->GetIDsFromNames(ULONG(lpNameIDs.size()), names, ulFlags, &lpTags));
}
return lpTags;
}
} // namespace directMapi
std::list<std::shared_ptr<namedPropCacheEntry>>& namedPropCache::getCache() noexcept
{
// We keep a list of named prop cache entries
static std::list<std::shared_ptr<namedPropCacheEntry>> cache;
return cache;
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(const std::function<bool(const std::shared_ptr<namedPropCacheEntry>&)>& compare)
{
const auto& cache = getCache();
const auto entry =
find_if(cache.begin(), cache.end(), [compare](const auto& _entry) { return compare(_entry); });
if (entry != cache.end())
{
output::DebugPrint(output::dbgLevel::NamedPropCache, L"find: found match\n");
return *entry;
}
else
{
output::DebugPrint(output::dbgLevel::NamedPropCache, L"find: no match\n");
return namedPropCacheEntry::empty();
}
}
_Check_return_ std::shared_ptr<namedPropCacheEntry> namedPropCache::find(
const std::shared_ptr<cache::namedPropCacheEntry>& entry,
bool bMatchSig,
bool bMatchID,
bool bMatchName)
{
if (fIsSet(output::dbgLevel::NamedPropCache))
{
output::DebugPrint(
output::dbgLevel::NamedPropCache,
L"find: bMatchSig=%d, bMatchID=%d, bMatchName=%d\n",
bMatchSig,
bMatchID,
bMatchName);
entry->output();
}
return find([&](const auto& _entry) { return _entry->match(entry, bMatchSig, bMatchID, bMatchName); });
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(_In_ const std::vector<BYTE>& _sig, _In_ const MAPINAMEID& _mapiNameId)
{
if (fIsSet(output::dbgLevel::NamedPropCache))
{
const auto nameidString = strings::MAPINAMEIDToString(_mapiNameId);
if (_sig.empty())
{
output::DebugPrint(output::dbgLevel::NamedPropCache, L"find: _mapiNameId: %ws\n", nameidString.c_str());
}
else
{
const auto sigStr = strings::BinToHexString(_sig, true);
output::DebugPrint(
output::dbgLevel::NamedPropCache,
L"find: _sig=%ws, _mapiNameId: %ws\n",
sigStr.c_str(),
nameidString.c_str());
}
}
return find([&](const auto& _entry) { return _entry->match(_sig, _mapiNameId); });
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(_In_ const std::vector<BYTE>& _sig, ULONG _ulPropID)
{
if (fIsSet(output::dbgLevel::NamedPropCache))
{
if (_sig.empty())
{
output::DebugPrint(output::dbgLevel::NamedPropCache, L"find: _ulPropID=%04X\n", _ulPropID);
}
else
{
const auto sigStr = strings::BinToHexString(_sig, true);
output::DebugPrint(
output::dbgLevel::NamedPropCache, L"find: _sig=%ws, _ulPropID=%04X\n", sigStr.c_str(), _ulPropID);
}
}
return find([&](const auto& _entry) { return _entry->match(_sig, _ulPropID); });
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(ULONG _ulPropID, _In_ const MAPINAMEID& _mapiNameId)
{
if (fIsSet(output::dbgLevel::NamedPropCache))
{
const auto nameidString = strings::MAPINAMEIDToString(_mapiNameId);
output::DebugPrint(
output::dbgLevel::NamedPropCache,
L"find: _ulPropID=%04X, _mapiNameId: %ws\n",
_ulPropID,
nameidString.c_str());
}
return find([&](const auto& _entry) { return _entry->match(_ulPropID, _mapiNameId); });
}
// Add a mapping to the cache if it doesn't already exist
// If given a signature, we include it in our search.
// If not, we search without it
void
namedPropCache::add(const std::vector<std::shared_ptr<namedPropCacheEntry>>& entries, const std::vector<BYTE>& sig)
{
auto& cache = getCache();
for (auto& entry : entries)
{
output::DebugPrint(output::dbgLevel::NamedPropCache, L"add:\n");
entry->output();
if (entry->getPropID() == PT_ERROR)
{
output::DebugPrint(output::dbgLevel::NamedPropCache, L"add: Skipping error property\n");
continue;
}
auto match = std::shared_ptr<namedPropCacheEntry>{};
if (sig.empty())
{
match = find(entry, false, true, true);
}
else
{
entry->setSig(sig);
match = find(entry, true, true, true);
}
if (!namedPropCacheEntry::valid(match))
{
if (fIsSet(output::dbgLevel::NamedPropCache))
{
const auto names = NameIDToPropNames(entry->getMapiNameId());
if (names.empty())
{
output::DebugPrint(output::dbgLevel::NamedPropCache, L"add: Caching unknown property\n");
entry->output();
}
else
{
output::DebugPrint(
output::dbgLevel::NamedPropCache, L"add: Caching property %ws\n", names[0].c_str());
entry->output();
}
}
cache.emplace_back(entry);
}
}
}
// If signature is empty then do not use a signature
_Check_return_ std::vector<std::shared_ptr<namedPropCacheEntry>> namedPropCache::GetNamesFromIDs(
_In_ LPMAPIPROP lpMAPIProp,
_In_ const std::vector<BYTE>& sig,
_In_opt_ const LPSPropTagArray lpPropTags)
{
if (!lpMAPIProp) return {};
// If this is a get all names call, we have to go direct to MAPI since we cannot trust the cache is full.
if (!lpPropTags)
{
output::DebugPrint(output::dbgLevel::NamedPropCache, L"GetNamesFromIDs: making direct all for all props\n");
std::vector<std::shared_ptr<namedPropCacheEntry>> names;
WC_H_S(directMapi::GetNamesFromIDs(lpMAPIProp, nullptr, NULL, names));
// Cache the results
add(names, sig);
return names;
}
// We're going to walk the cache, looking for the values we need. As soon as we have all the values we need, we're done
// If we reach the end of the cache and don't have everything, we set up to make a GetNamesFromIDs call.
auto results = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
auto misses = std::vector<ULONG>{};
// First pass, find any misses we might have
output::DebugPrint(output::dbgLevel::NamedPropCache, L"GetNamesFromIDs: Looking for misses\n");
for (ULONG ulTarget = 0; ulTarget < lpPropTags->cValues; ulTarget++)
{
const auto ulPropTag = mapi::getTag(lpPropTags, ulTarget);
const auto ulPropId = PROP_ID(ulPropTag);
// ...check the cache
const auto lpEntry = find(sig, ulPropId);
if (!namedPropCacheEntry::valid(lpEntry))
{
misses.emplace_back(ulPropTag);
}
}
// Go to MAPI with whatever's left. We set up for a single call to GetNamesFromIDs.
if (!misses.empty())
{
output::DebugPrint(
output::dbgLevel::NamedPropCache, L"GetNamesFromIDs: Add %d misses to cache\n", misses.size());
std::vector<std::shared_ptr<namedPropCacheEntry>> missed;
missed.reserve(misses.size());
WC_H_S(directMapi::GetNamesFromIDs(lpMAPIProp, misses, NULL, missed));
// Cache the results
add(missed, sig);
}
// Second pass, do our lookup with a populated cache
output::DebugPrint(output::dbgLevel::NamedPropCache, L"GetNamesFromIDs: Lookup again from cache\n");
for (ULONG ulTarget = 0; ulTarget < lpPropTags->cValues; ulTarget++)
{
const auto ulPropId = PROP_ID(mapi::getTag(lpPropTags, ulTarget));
// ...check the cache
const auto lpEntry = find(sig, ulPropId);
if (namedPropCacheEntry::valid(lpEntry))
{
results.emplace_back(lpEntry);
}
else
{
results.emplace_back(namedPropCacheEntry::make(nullptr, ulPropId, sig));
}
}
return results;
}
// If signature is empty then do not use a signature
_Check_return_ LPSPropTagArray namedPropCache::GetIDsFromNames(
_In_ LPMAPIPROP lpMAPIProp,
_In_ const std::vector<BYTE>& sig,
_In_ std::vector<MAPINAMEID> nameIDs,
ULONG ulFlags)
{
if (!lpMAPIProp || !nameIDs.size()) return {};
// We're going to walk the cache, looking for the values we need. As soon as we have all the values we need, we're done
// If we reach the end of the cache and don't have everything, we set up to make a GetIDsFromNames call.
auto misses = std::vector<MAPINAMEID>{};
// First pass, find the tags we don't have cached
output::DebugPrint(output::dbgLevel::NamedPropCache, L"GetIDsFromNames: Looking for misses\n");
for (const auto& nameID : nameIDs)
{
const auto lpEntry = find(sig, nameID);
if (!namedPropCacheEntry::valid(lpEntry))
{
misses.emplace_back(nameID);
}
}
// Go to MAPI with whatever's left.
if (!misses.empty())
{
auto missed = directMapi::GetIDsFromNames(lpMAPIProp, misses, ulFlags);
if (missed && missed->cValues == misses.size())
{
// Cache the results
auto toCache = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
for (ULONG i = 0; i < misses.size(); i++)
{
toCache.emplace_back(namedPropCacheEntry::make(&misses[i], mapi::getTag(missed, i), sig));
}
output::DebugPrint(
output::dbgLevel::NamedPropCache, L"GetIDsFromNames: Add %d misses to cache\n", misses.size());
add(toCache, sig);
}
MAPIFreeBuffer(missed);
}
// Second pass, do our lookup with a populated cache
auto countIDs = ULONG(nameIDs.size());
output::DebugPrint(output::dbgLevel::NamedPropCache, L"GetIDsFromNames: Lookup again from cache\n");
auto results = mapi::allocate<LPSPropTagArray>(CbNewSPropTagArray(countIDs));
if (results)
{
results->cValues = countIDs;
ULONG i = 0;
for (const auto& nameID : nameIDs)
{
const auto lpEntry = find(sig, nameID);
mapi::setTag(results, i++) = namedPropCacheEntry::valid(lpEntry) ? lpEntry->getPropID() : 0;
}
}
return results;
}
} // namespace cache | 28.787611 | 121 | 0.683123 | bradhugh |
e9146d2463b01d73381ff0751600ab1c49a7a756 | 1,285 | cpp | C++ | flite/src/audio/streaming.cpp | Barath-Kannan/flite | 236f91a9a1e60fd25f1deed6d48022567cd7100f | [
"Apache-2.0"
] | 7 | 2017-12-10T23:02:22.000Z | 2021-08-05T21:12:11.000Z | flite/src/audio/streaming.cpp | Barath-Kannan/flite | 236f91a9a1e60fd25f1deed6d48022567cd7100f | [
"Apache-2.0"
] | null | null | null | flite/src/audio/streaming.cpp | Barath-Kannan/flite | 236f91a9a1e60fd25f1deed6d48022567cd7100f | [
"Apache-2.0"
] | 3 | 2018-10-28T03:47:09.000Z | 2020-06-04T08:54:23.000Z | #include "flite/audio/audio.hpp"
#include "flite/synthcommon/wave.hpp"
#include "flite/utils/string.hpp"
CST_VAL_REGISTER_TYPE(audio_streaming_info, cst_audio_streaming_info)
cst_audio_streaming_info* new_audio_streaming_info(void)
{
cst_audio_streaming_info* asi =
cst_alloc(struct cst_audio_streaming_info_struct, 1);
asi->min_buffsize = 256;
asi->asc = NULL;
asi->userdata = NULL;
return asi;
}
void delete_audio_streaming_info(cst_audio_streaming_info* asi)
{
if (asi)
cst_free(asi);
return;
}
int audio_stream_chunk(const cst_wave* w, int start, int size, int last, cst_audio_streaming_info* asi)
{
/* Called with new samples from start for size samples */
/* last is true if this is the last segment. */
/* This is really just and example that you can copy for you streaming */
/* function */
/* This particular example is *not* thread safe */
static cst_audiodev* ad = 0;
if (start == 0)
ad = audio_open(w->sample_rate, w->num_channels, CST_AUDIO_LINEAR16);
audio_write(ad, &w->samples[start], size * sizeof(short));
if (last == 1) {
audio_close(ad);
ad = NULL;
}
/* if you want to stop return CST_AUDIO_STREAM_STOP */
return CST_AUDIO_STREAM_CONT;
}
| 26.22449 | 103 | 0.686381 | Barath-Kannan |
e914d16bbbff3e159e1574a99d339fbb11930c2e | 389 | cc | C++ | test/refract/dsd/test-Null.cc | darkcl/drafter | 62dcc54341d76b1dae7bca1777f5eea8815b0c3b | [
"MIT"
] | null | null | null | test/refract/dsd/test-Null.cc | darkcl/drafter | 62dcc54341d76b1dae7bca1777f5eea8815b0c3b | [
"MIT"
] | null | null | null | test/refract/dsd/test-Null.cc | darkcl/drafter | 62dcc54341d76b1dae7bca1777f5eea8815b0c3b | [
"MIT"
] | null | null | null | //
// test/refract/dsd/test-Null.cc
// test-librefract
//
// Created by Thomas Jandecka on 27/08/2017
// Copyright (c) 2017 Apiary Inc. All rights reserved.
//
#include "catch.hpp"
#include "refract/dsd/Null.h"
using namespace refract;
using namespace dsd;
TEST_CASE("`Null`'s default element name is `null`", "[Element][Null]")
{
REQUIRE(std::string(Null::name) == "null");
}
| 19.45 | 71 | 0.676093 | darkcl |
e91823da496b427dff99305a66d73682176d2a78 | 19,556 | cpp | C++ | examples/dnn_introduction2_ex.cpp | ckproc/dlib-19.7 | 0ca40f5e85de2436e557bee9a805d3987d2d9507 | [
"BSL-1.0"
] | null | null | null | examples/dnn_introduction2_ex.cpp | ckproc/dlib-19.7 | 0ca40f5e85de2436e557bee9a805d3987d2d9507 | [
"BSL-1.0"
] | 4 | 2018-02-27T15:44:25.000Z | 2018-02-28T01:26:03.000Z | examples/dnn_introduction2_ex.cpp | ckproc/dlib-19.7 | 0ca40f5e85de2436e557bee9a805d3987d2d9507 | [
"BSL-1.0"
] | null | null | null | // The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*
This is an example illustrating the use of the deep learning tools from the
dlib C++ Library. I'm assuming you have already read the dnn_introduction_ex.cpp
example. So in this example program I'm going to go over a number of more
advanced parts of the API, including:
- Using multiple GPUs
- Training on large datasets that don't fit in memory
- Defining large networks
- Accessing and configuring layers in a network
*/
#include <dlib/dnn.h>
#include <iostream>
#include <dlib/data_io.h>
using namespace std;
using namespace dlib;
// ----------------------------------------------------------------------------------------
// Let's start by showing how you can conveniently define large and complex
// networks. The most important tool for doing this are C++'s alias templates.
// These let us define new layer types that are combinations of a bunch of other
// layers. These will form the building blocks for more complex networks.
// So let's begin by defining the building block of a residual network (see
// Figure 2 in Deep Residual Learning for Image Recognition by He, Zhang, Ren,
// and Sun). We are going to decompose the residual block into a few alias
// statements. First, we define the core block.
// Here we have parameterized the "block" layer on a BN layer (nominally some
// kind of batch normalization), the number of filter outputs N, and the stride
// the block operates at.
template <
int N,
template <typename> class BN,
int stride,
typename SUBNET
>
using block = BN<con<N,3,3,1,1,relu<BN<con<N,3,3,stride,stride,SUBNET>>>>>;
// Next, we need to define the skip layer mechanism used in the residual network
// paper. They create their blocks by adding the input tensor to the output of
// each block. So we define an alias statement that takes a block and wraps it
// with this skip/add structure.
// Note the tag layer. This layer doesn't do any computation. It exists solely
// so other layers can refer to it. In this case, the add_prev1 layer looks for
// the tag1 layer and will take the tag1 output and add it to the input of the
// add_prev1 layer. This combination allows us to implement skip and residual
// style networks. We have also set the block stride to 1 in this statement.
// The significance of that is explained next.
template <
template <int,template<typename>class,int,typename> class block,
int N,
template<typename>class BN,
typename SUBNET
>
using residual = add_prev1<block<N,BN,1,tag1<SUBNET>>>;
// Some residual blocks do downsampling. They do this by using a stride of 2
// instead of 1. However, when downsampling we need to also take care to
// downsample the part of the network that adds the original input to the output
// or the sizes won't make sense (the network will still run, but the results
// aren't as good). So here we define a downsampling version of residual. In
// it, we make use of the skip1 layer. This layer simply outputs whatever is
// output by the tag1 layer. Therefore, the skip1 layer (there are also skip2,
// skip3, etc. in dlib) allows you to create branching network structures.
// residual_down creates a network structure like this:
/*
input from SUBNET
/ \
/ \
block downsample(using avg_pool)
\ /
\ /
add tensors (using add_prev2 which adds the output of tag2 with avg_pool's output)
|
output
*/
template <
template <int,template<typename>class,int,typename> class block,
int N,
template<typename>class BN,
typename SUBNET
>
using residual_down = add_prev2<avg_pool<2,2,2,2,skip1<tag2<block<N,BN,2,tag1<SUBNET>>>>>>;
// Now we can define 4 different residual blocks we will use in this example.
// The first two are non-downsampling residual blocks while the last two
// downsample. Also, res and res_down use batch normalization while ares and
// ares_down have had the batch normalization replaced with simple affine
// layers. We will use the affine version of the layers when testing our
// networks.
template <typename SUBNET> using res = relu<residual<block,8,bn_con,SUBNET>>;
template <typename SUBNET> using ares = relu<residual<block,8,affine,SUBNET>>;
template <typename SUBNET> using res_down = relu<residual_down<block,8,bn_con,SUBNET>>;
template <typename SUBNET> using ares_down = relu<residual_down<block,8,affine,SUBNET>>;
// Now that we have these convenient aliases, we can define a residual network
// without a lot of typing. Note the use of a repeat layer. This special layer
// type allows us to type repeat<9,res,SUBNET> instead of
// res<res<res<res<res<res<res<res<res<SUBNET>>>>>>>>>. It will also prevent
// the compiler from complaining about super deep template nesting when creating
// large networks.
const unsigned long number_of_classes = 10;
using net_type = loss_multiclass_log<fc<number_of_classes,
avg_pool_everything<
res<res<res<res_down<
repeat<9,res, // repeat this layer 9 times
res_down<
res<
input<matrix<unsigned char>>
>>>>>>>>>>;
// And finally, let's define a residual network building block that uses
// parametric ReLU units instead of regular ReLU.
template <typename SUBNET>
using pres = prelu<add_prev1<bn_con<con<8,3,3,1,1,prelu<bn_con<con<8,3,3,1,1,tag1<SUBNET>>>>>>>>;
// ----------------------------------------------------------------------------------------
int main(int argc, char** argv) try
{
if (argc != 2)
{
cout << "This example needs the MNIST dataset to run!" << endl;
cout << "You can get MNIST from http://yann.lecun.com/exdb/mnist/" << endl;
cout << "Download the 4 files that comprise the dataset, decompress them, and" << endl;
cout << "put them in a folder. Then give that folder as input to this program." << endl;
return 1;
}
std::vector<matrix<unsigned char>> training_images;
std::vector<unsigned long> training_labels;
std::vector<matrix<unsigned char>> testing_images;
std::vector<unsigned long> testing_labels;
load_mnist_dataset(argv[1], training_images, training_labels, testing_images, testing_labels);
// dlib uses cuDNN under the covers. One of the features of cuDNN is the
// option to use slower methods that use less RAM or faster methods that use
// a lot of RAM. If you find that you run out of RAM on your graphics card
// then you can call this function and we will request the slower but more
// RAM frugal cuDNN algorithms.
set_dnn_prefer_smallest_algorithms();
// Create a network as defined above. This network will produce 10 outputs
// because that's how we defined net_type. However, fc layers can have the
// number of outputs they produce changed at runtime.
net_type net;
// So if you wanted to use the same network but override the number of
// outputs at runtime you can do so like this:
net_type net2(num_fc_outputs(15));
// Now, let's imagine we wanted to replace some of the relu layers with
// prelu layers. We might do it like this:
using net_type2 = loss_multiclass_log<fc<number_of_classes,
avg_pool_everything<
pres<res<res<res_down< // 2 prelu layers here
tag4<repeat<9,pres, // 9 groups, each containing 2 prelu layers
res_down<
res<
input<matrix<unsigned char>>
>>>>>>>>>>>;
// prelu layers have a floating point parameter. If you want to set it to
// something other than its default value you can do so like this:
net_type2 pnet(prelu_(0.2),
prelu_(0.25),
repeat_group(prelu_(0.3),prelu_(0.4)) // Initialize all the prelu instances in the repeat
// layer. repeat_group() is needed to group the
// things that are part of repeat's block.
);
// As you can see, a network will greedily assign things given to its
// constructor to the layers inside itself. The assignment is done in the
// order the layers are defined, but it will skip layers where the
// assignment doesn't make sense.
// Now let's print the details of the pnet to the screen and inspect it.
cout << "The pnet has " << pnet.num_layers << " layers in it." << endl;
cout << pnet << endl;
// These print statements will output this (I've truncated it since it's
// long, but you get the idea):
/*
The pnet has 131 layers in it.
layer<0> loss_multiclass_log
layer<1> fc (num_outputs=10) learning_rate_mult=1 weight_decay_mult=1 bias_learning_rate_mult=1 bias_weight_decay_mult=0
layer<2> avg_pool (nr=0, nc=0, stride_y=1, stride_x=1, padding_y=0, padding_x=0)
layer<3> prelu (initial_param_value=0.2)
layer<4> add_prev1
layer<5> bn_con eps=1e-05 learning_rate_mult=1 weight_decay_mult=0 bias_learning_rate_mult=1 bias_weight_decay_mult=1
layer<6> con (num_filters=8, nr=3, nc=3, stride_y=1, stride_x=1, padding_y=1, padding_x=1) learning_rate_mult=1 weight_decay_mult=1 bias_learning_rate_mult=1 bias_weight_decay_mult=0
layer<7> prelu (initial_param_value=0.25)
layer<8> bn_con eps=1e-05 learning_rate_mult=1 weight_decay_mult=0 bias_learning_rate_mult=1 bias_weight_decay_mult=1
layer<9> con (num_filters=8, nr=3, nc=3, stride_y=1, stride_x=1, padding_y=1, padding_x=1) learning_rate_mult=1 weight_decay_mult=1 bias_learning_rate_mult=1 bias_weight_decay_mult=0
layer<10> tag1
...
layer<34> relu
layer<35> bn_con eps=1e-05 learning_rate_mult=1 weight_decay_mult=0 bias_learning_rate_mult=1 bias_weight_decay_mult=1
layer<36> con (num_filters=8, nr=3, nc=3, stride_y=2, stride_x=2, padding_y=0, padding_x=0) learning_rate_mult=1 weight_decay_mult=1 bias_learning_rate_mult=1 bias_weight_decay_mult=0
layer<37> tag1
layer<38> tag4
layer<39> prelu (initial_param_value=0.3)
layer<40> add_prev1
layer<41> bn_con eps=1e-05 learning_rate_mult=1 weight_decay_mult=0 bias_learning_rate_mult=1 bias_weight_decay_mult=1
...
layer<118> relu
layer<119> bn_con eps=1e-05 learning_rate_mult=1 weight_decay_mult=0 bias_learning_rate_mult=1 bias_weight_decay_mult=1
layer<120> con (num_filters=8, nr=3, nc=3, stride_y=2, stride_x=2, padding_y=0, padding_x=0) learning_rate_mult=1 weight_decay_mult=1 bias_learning_rate_mult=1 bias_weight_decay_mult=0
layer<121> tag1
layer<122> relu
layer<123> add_prev1
layer<124> bn_con eps=1e-05 learning_rate_mult=1 weight_decay_mult=0 bias_learning_rate_mult=1 bias_weight_decay_mult=1
layer<125> con (num_filters=8, nr=3, nc=3, stride_y=1, stride_x=1, padding_y=1, padding_x=1) learning_rate_mult=1 weight_decay_mult=1 bias_learning_rate_mult=1 bias_weight_decay_mult=0
layer<126> relu
layer<127> bn_con eps=1e-05 learning_rate_mult=1 weight_decay_mult=0 bias_learning_rate_mult=1 bias_weight_decay_mult=1
layer<128> con (num_filters=8, nr=3, nc=3, stride_y=1, stride_x=1, padding_y=1, padding_x=1) learning_rate_mult=1 weight_decay_mult=1 bias_learning_rate_mult=1 bias_weight_decay_mult=0
layer<129> tag1
layer<130> input<matrix>
*/
// Now that we know the index numbers for each layer, we can access them
// individually using layer<index>(pnet). For example, to access the output
// tensor for the first prelu layer we can say:
layer<3>(pnet).get_output();
// Or to print the prelu parameter for layer 7 we can say:
cout << "prelu param: "<< layer<7>(pnet).layer_details().get_initial_param_value() << endl;
// We can also access layers by their type. This next statement finds the
// first tag1 layer in pnet, and is therefore equivalent to calling
// layer<10>(pnet):
layer<tag1>(pnet);
// The tag layers don't do anything at all and exist simply so you can tag
// parts of your network and access them by layer<tag>(). You can also
// index relative to a tag. So for example, to access the layer immediately
// after tag4 you can say:
layer<tag4,1>(pnet); // Equivalent to layer<38+1>(pnet).
// Or to access the layer 2 layers after tag4:
layer<tag4,2>(pnet);
// Tagging is a very useful tool for making complex network structures. For
// example, the add_prev1 layer is implemented internally by using a call to
// layer<tag1>().
// Ok, that's enough talk about defining and inspecting networks. Let's
// talk about training networks!
// The dnn_trainer will use SGD by default, but you can tell it to use
// different solvers like adam with a weight decay of 0.0005 and the given
// momentum parameters.
dnn_trainer<net_type,adam> trainer(net,adam(0.0005, 0.9, 0.999));
// Also, if you have multiple graphics cards you can tell the trainer to use
// them together to make the training faster. For example, replacing the
// above constructor call with this one would cause it to use GPU cards 0
// and 1.
//dnn_trainer<net_type,adam> trainer(net,adam(0.0005, 0.9, 0.999), {0,1});
trainer.be_verbose();
// While the trainer is running it keeps an eye on the training error. If
// it looks like the error hasn't decreased for the last 2000 iterations it
// will automatically reduce the learning rate by 0.1. You can change these
// default parameters to some other values by calling these functions. Or
// disable the automatic shrinking entirely by setting the shrink factor to 1.
trainer.set_iterations_without_progress_threshold(2000);
trainer.set_learning_rate_shrink_factor(0.1);
// The learning rate will start at 1e-3.
trainer.set_learning_rate(1e-3);
trainer.set_synchronization_file("mnist_resnet_sync", std::chrono::seconds(100));
// Now, what if your training dataset is so big it doesn't fit in RAM? You
// make mini-batches yourself, any way you like, and you send them to the
// trainer by repeatedly calling trainer.train_one_step().
//
// For example, the loop below stream MNIST data to out trainer.
std::vector<matrix<unsigned char>> mini_batch_samples;
std::vector<unsigned long> mini_batch_labels;
dlib::rand rnd(time(0));
// Loop until the trainer's automatic shrinking has shrunk the learning rate to 1e-6.
// Given our settings, this means it will stop training after it has shrunk the
// learning rate 3 times.
while(trainer.get_learning_rate() >= 1e-6)
{
mini_batch_samples.clear();
mini_batch_labels.clear();
// make a 128 image mini-batch
while(mini_batch_samples.size() < 128)
{
auto idx = rnd.get_random_32bit_number()%training_images.size();
mini_batch_samples.push_back(training_images[idx]);
mini_batch_labels.push_back(training_labels[idx]);
}
// Tell the trainer to update the network given this mini-batch
trainer.train_one_step(mini_batch_samples, mini_batch_labels);
// You can also feed validation data into the trainer by periodically
// calling trainer.test_one_step(samples,labels). Unlike train_one_step(),
// test_one_step() doesn't modify the network, it only computes the testing
// error which it records internally. This testing error will then be print
// in the verbose logging and will also determine when the trainer's
// automatic learning rate shrinking happens. Therefore, test_one_step()
// can be used to perform automatic early stopping based on held out data.
}
// When you call train_one_step(), the trainer will do its processing in a
// separate thread. This allows the main thread to work on loading data
// while the trainer is busy executing the mini-batches in parallel.
// However, this also means we need to wait for any mini-batches that are
// still executing to stop before we mess with the net object. Calling
// get_net() performs the necessary synchronization.
trainer.get_net();
net.clean();
serialize("mnist_res_network.dat") << net;
// Now we have a trained network. However, it has batch normalization
// layers in it. As is customary, we should replace these with simple
// affine layers before we use the network. This can be accomplished by
// making a network type which is identical to net_type but with the batch
// normalization layers replaced with affine. For example:
using test_net_type = loss_multiclass_log<fc<number_of_classes,
avg_pool_everything<
ares<ares<ares<ares_down<
repeat<9,ares,
ares_down<
ares<
input<matrix<unsigned char>>
>>>>>>>>>>;
// Then we can simply assign our trained net to our testing net.
test_net_type tnet = net;
// Or if you only had a file with your trained network you could deserialize
// it directly into your testing network.
deserialize("mnist_res_network.dat") >> tnet;
// And finally, we can run the testing network over our data.
std::vector<unsigned long> predicted_labels = tnet(training_images);
int num_right = 0;
int num_wrong = 0;
for (size_t i = 0; i < training_images.size(); ++i)
{
if (predicted_labels[i] == training_labels[i])
++num_right;
else
++num_wrong;
}
cout << "training num_right: " << num_right << endl;
cout << "training num_wrong: " << num_wrong << endl;
cout << "training accuracy: " << num_right/(double)(num_right+num_wrong) << endl;
predicted_labels = tnet(testing_images);
num_right = 0;
num_wrong = 0;
for (size_t i = 0; i < testing_images.size(); ++i)
{
if (predicted_labels[i] == testing_labels[i])
++num_right;
else
++num_wrong;
}
cout << "testing num_right: " << num_right << endl;
cout << "testing num_wrong: " << num_wrong << endl;
cout << "testing accuracy: " << num_right/(double)(num_right+num_wrong) << endl;
}
catch(std::exception& e)
{
cout << e.what() << endl;
}
| 50.272494 | 199 | 0.647525 | ckproc |
e91855f7666372a037ceea23552201a7ada33d0c | 749 | cpp | C++ | test/pre_reserch/plag_original_codes/04_039.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | 13 | 2021-01-20T19:53:16.000Z | 2021-11-14T16:30:32.000Z | test/training_data/plag_original_codes/04_039.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | null | null | null | test/training_data/plag_original_codes/04_039.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | null | null | null | // 引用元 : https://atcoder.jp/contests/abc137/submissions/6820151
// 得点 : 300
// コード長 : 642
// 実行時間 : 127
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<string> s(n);
for (int i = 0; i < n; ++i) {
cin >> s[i];
sort(s[i].begin(), s[i].end());
}
sort(s.begin(), s.end());
unsigned long long count = 0;
unsigned long long buf = 0;
int c = 0;
for (int i = 1; i < n; ++i) {
if (s[i] == s[i-1]) {
++c;
buf = buf + c;
}
else {
if (buf != 0) {
count += buf;
buf = 0;
c = 0;
}
}
}
count += buf;
cout << count << endl;
return 0;
}
| 17.022727 | 63 | 0.456609 | xryuseix |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.