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
108
| 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
67k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dd552ff3fb052cc6a64cc3f993fc688091cbefe2
| 862
|
cpp
|
C++
|
Notebook/src-bkp/Highly Decomposite Number.cpp
|
aajjbb/contest-files
|
b8842681b96017063a7baeac52ae1318bf59d74d
|
[
"Apache-2.0"
] | 1
|
2018-08-28T19:58:40.000Z
|
2018-08-28T19:58:40.000Z
|
Notebook/src-bkp/Highly Decomposite Number.cpp
|
aajjbb/contest-files
|
b8842681b96017063a7baeac52ae1318bf59d74d
|
[
"Apache-2.0"
] | 2
|
2017-04-16T00:48:05.000Z
|
2017-08-03T20:12:26.000Z
|
Notebook/src-bkp/Highly Decomposite Number.cpp
|
aajjbb/contest-files
|
b8842681b96017063a7baeac52ae1318bf59d74d
|
[
"Apache-2.0"
] | 4
|
2016-03-04T19:42:00.000Z
|
2018-01-08T11:42:00.000Z
|
bool p[MAXN];
vector<int> primes;
void build(void) {
memset(p, true, sizeof(p));
for (int i = 2; i <= MAXN; i++) {
if (p[i]) {
primes.push_back(i);
for (int j = i * i; j <= MAXN; j += i) {
p[j] = false;
}
}
}
}
int func(Int x) {
int ans = 1;
for (int i = 0; i < (int) primes.size() && x > 1; i++) {
if (x % primes[i] == 0) {
int curr = 0;
while (x % primes[i] == 0) {
x /= primes[i];
curr += 1;
}
ans *= (curr + 1);
}
}
return ans;
}
set<Int> st;
void go(int id, Int v, int last) {
Int base = primes[id];
if (v > MAXV) return;
st.insert(v);
for (int i = 0; i <= last; i++) {
v *= (Int) base;
if (v > MAXV) break;
go(id + 1, v, i);
}
}
vector<Int> ans;
for (set<Int>::iterator it = st.begin(); it != st.end(); it++) {
int s = func(*it);
if (s > curr) {
ans.push_back(*it);
curr = s;
}
}
| 15.392857
| 64
| 0.474478
|
aajjbb
|
dd55c9a76e5fab0d929abdd83067aeef115e8bf4
| 64
|
cc
|
C++
|
MCDataProducts/src/CrvDigiMC.cc
|
bonventre/Offline
|
77db9d6368f27ab9401c690c2c2a4257ade6c231
|
[
"Apache-2.0"
] | 1
|
2021-06-25T00:00:12.000Z
|
2021-06-25T00:00:12.000Z
|
MCDataProducts/src/CrvDigiMC.cc
|
bonventre/Offline
|
77db9d6368f27ab9401c690c2c2a4257ade6c231
|
[
"Apache-2.0"
] | 125
|
2020-04-03T13:44:30.000Z
|
2021-10-15T21:29:57.000Z
|
MCDataProducts/src/CrvDigiMC.cc
|
bonventre/Offline
|
77db9d6368f27ab9401c690c2c2a4257ade6c231
|
[
"Apache-2.0"
] | 2
|
2019-10-14T17:46:58.000Z
|
2020-03-30T21:05:15.000Z
|
#include "MCDataProducts/inc/CrvDigiMC.hh"
namespace mu2e
{
}
| 10.666667
| 42
| 0.75
|
bonventre
|
dd5bd5d2272934b306850d72505e29339fcaf099
| 2,006
|
cc
|
C++
|
cpp/functions/run/run_benchmark_santos.cc
|
michieluithetbroek/A-MDVRP
|
fe7739f3961ddb25db8f64ec20472915d3c95168
|
[
"MIT"
] | 23
|
2020-04-09T16:33:23.000Z
|
2022-03-21T16:41:11.000Z
|
cpp/functions/run/run_benchmark_santos.cc
|
michieluithetbroek/A-MDVRP
|
fe7739f3961ddb25db8f64ec20472915d3c95168
|
[
"MIT"
] | 2
|
2020-04-10T11:55:28.000Z
|
2020-04-10T12:11:51.000Z
|
cpp/functions/run/run_benchmark_santos.cc
|
michieluithetbroek/A-MDVRP
|
fe7739f3961ddb25db8f64ec20472915d3c95168
|
[
"MIT"
] | 10
|
2020-05-28T18:59:52.000Z
|
2022-03-10T13:32:44.000Z
|
#include "./../../main.ih"
/*
* This functions runs all the instances from Santos
*
* TODO remove bool deterministic
*/
void run_benchmark_santos(int idx_instance, bool deterministic, int rep)
{
bool const withoutGurobi = false;
if (not deterministic)
throw string("Opportunistic run is not allowed! (run_benchmark_santos)");
g_cutPasses = 500;
g_userSettingA = 200; //200;
g_userSettingB = 200;
g_cplexFocusLB = true; // CPLEX focussed on LB
g_onlyRoot = false; // Solve the whole branch-and-bound
g_cplexCuts = true; // 0 = with cplex cuts, -1 = without
g_useGurobi = true;
if (withoutGurobi)
{
g_cplexFocusLB = false; // CPLEX focussed on LB
g_onlyRoot = false; // Solve the whole branch-and-bound
g_cplexCuts = true; // 0 = with cplex cuts, -1 = without
g_useGurobi = false;
}
int const cutProfile = 1;
/*
* The following sets the global enums INSTANCE and DATA_ASYMMETRY
* This is used in the Data struct to set the costs and to activate
* the proper constraints in the ModelA class.
*
*/
hash_and_set_globals(12, 0);
Data data (idx_instance);
if (deterministic and not withoutGurobi)
{
string folder("results/santos/"
+ to_string(idx_instance)
+ "_nThreads-"
+ to_string(g_nThreads)
+ "_rep-"
+ to_string(rep));
run_single_instance(data, folder, cutProfile);
}
else if (deterministic and withoutGurobi)
{
cout << "without Gurobi!" << endl;
string folder("results/santos/"
+ to_string(idx_instance)
+ "_nThreads-"
+ to_string(g_nThreads)
+ "_withoutGurobi"
+ "_rep-"
+ to_string(rep));
run_single_instance(data, folder, cutProfile);
}
else
{
string folder("results/santos/"
+ to_string(idx_instance)
+ "_par_" + to_string(rep));
run_single_instance(data, folder, cutProfile);
}
}
| 24.168675
| 77
| 0.621137
|
michieluithetbroek
|
dd5f44f135378685091c3e4105c9a09dec58f000
| 2,639
|
cpp
|
C++
|
src/main.cpp
|
finnff/IPASS-19
|
b65ad79282a63c1f0db3addfaf865e99677ecd2c
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
finnff/IPASS-19
|
b65ad79282a63c1f0db3addfaf865e99677ecd2c
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
finnff/IPASS-19
|
b65ad79282a63c1f0db3addfaf865e99677ecd2c
|
[
"MIT"
] | null | null | null |
#include "mpu6050.hpp"
#include "pongresources.hpp"
int main(int argc, char **argv) {
namespace target = hwlib::target;
// Intialize OLED display
auto scl = target::pin_oc(target::pins::d10);
auto sda = target::pin_oc(target::pins::d11);
auto i2c_bus = hwlib::i2c_bus_bit_banged_scl_sda(scl, sda);
auto w = hwlib::glcd_oled(i2c_bus, 0x3c);
// Intialize i2c bus for use with 2x gy-521 Breakout boards
auto scl1 = target::pin_oc(target::pins::d21);
auto sda1 = target::pin_oc(target::pins::d20);
auto iic = hwlib::i2c_bus_bit_banged_scl_sda(scl1, sda1);
auto chipL = mpu6050(iic, 0x68); // AD0 LOW
auto chipR = mpu6050(iic, 0x69); // AD0 HI
chipL.init();
chipR.init();
int rwidth =
128; // Set screen width resolution , OLED is 128*64, used for scaling
int rheight = 64;
int Lscore = 0; // init score
int Rscore = 0;
RandomBall b(w, 128, 64); // Construct random ball object
bat r(w, hwlib::xy((rwidth - (rwidth / 10)) - 2, rheight / 2),
hwlib::xy((rwidth - (rwidth / 10)), ((rheight / 2) + (rheight / 5))));
bat l(w, hwlib::xy(rwidth / 10, rheight / 2),
hwlib::xy((rwidth / 10 + 2), ((rheight / 2) + (rheight / 5))));
for (;;) {
int lroll = chipL.readRollAngle(); // read roll angle of MPU6050, this is
// the input of the game.
int rroll = chipR.readRollAngle();
w.clear();
if (lroll < -30 && l.start.y > 0) {
l.moveup();
}
if (lroll > 30 && l.end.y < rheight) {
l.movedown();
}
if (rroll < -30 && r.start.y > 0) {
r.moveup();
}
if (rroll > 30 && r.end.y < rheight) {
r.movedown();
}
r.draw();
l.draw();
b.move();
if (b.end.x == (rwidth - (rwidth / 10) - 2) ||
b.end.x == (rwidth - (rwidth / 10) - 3)) { // Right Collision
if (b.start.y <= r.end.y && b.start.y >= r.start.y) {
b.change_speed_factor(-1, 1);
} else {
Lscore++; // Lose condition
hwlib::cout << Lscore << " - " << Rscore << hwlib::endl;
hwlib::wait_ms(500);
b.reset();
}
}
if (b.start.x == (rwidth / 10) + 1 ||
b.start.x == (rwidth / 10)) { // Left Collision
if (b.start.y <= l.end.y && b.start.y >= l.start.y) {
b.change_speed_factor(-1, 1);
} else {
Rscore++; // Lose condition
hwlib::cout << Lscore << " - " << Rscore << hwlib::endl;
hwlib::wait_ms(500);
b.reset();
}
}
if (b.start.y >= rheight - 1 ||
b.start.y <= 0) { // Bounce top/bottom of screen
b.change_speed_factor(1, -1);
}
w.flush();
}
}
| 29.322222
| 78
| 0.535809
|
finnff
|
e578239b4948fa914b39f0e674029a09d13b6d54
| 7,285
|
cpp
|
C++
|
src/engine/drawSys.cpp
|
karwler/BKGraph
|
1b65f82d4c44e3982cf6cef775e88a16c857d6e3
|
[
"WTFPL"
] | null | null | null |
src/engine/drawSys.cpp
|
karwler/BKGraph
|
1b65f82d4c44e3982cf6cef775e88a16c857d6e3
|
[
"WTFPL"
] | null | null | null |
src/engine/drawSys.cpp
|
karwler/BKGraph
|
1b65f82d4c44e3982cf6cef775e88a16c857d6e3
|
[
"WTFPL"
] | 2
|
2017-11-09T16:14:39.000Z
|
2018-02-08T19:09:40.000Z
|
#include "world.h"
// FONT SET
FontSet::FontSet(const string& path) :
file(path)
{
// check if font can be loaded
TTF_Font* tmp = TTF_OpenFont(file.c_str(), Default::fontTestHeight);
if (!tmp)
throw "Couldn't open font " + file + '\n' + TTF_GetError();
// get approximate height scale factor
int size;
TTF_SizeUTF8(tmp, Default::fontTestString, nullptr, &size);
heightScale = float(Default::fontTestHeight) / float(size);
TTF_CloseFont(tmp);
}
FontSet::~FontSet() {
for (const pair<const int, TTF_Font*>& it : fonts)
TTF_CloseFont(it.second);
}
void FontSet::clear() {
for (const pair<const int, TTF_Font*>& it : fonts)
TTF_CloseFont(it.second);
fonts.clear();
}
TTF_Font* FontSet::addSize(int size) {
TTF_Font* font = TTF_OpenFont(file.c_str(), size);
if (font)
fonts.insert(make_pair(size, font));
return font;
}
TTF_Font* FontSet::getFont(int height) {
height = int(float(height) * heightScale);
return fonts.count(height) ? fonts.at(height) : addSize(height); // load font if it hasn't been loaded yet
}
int FontSet::length(const string& text, int height) {
int len = 0;
TTF_Font* font = getFont(height);
if (font)
TTF_SizeUTF8(font, text.c_str(), &len, nullptr);
return len;
}
// DRAW SYS
DrawSys::DrawSys(SDL_Window* window, int driverIndex) :
fontSet(Filer::findFont(World::winSys()->getSettings().font))
{
renderer = SDL_CreateRenderer(window, driverIndex, Default::rendererFlags);
if (!renderer)
throw "Couldn't create renderer:\n" + string(SDL_GetError());
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
}
DrawSys::~DrawSys() {
SDL_DestroyRenderer(renderer);
}
SDL_Rect DrawSys::viewport() const {
SDL_Rect view;
SDL_RenderGetViewport(renderer, &view);
return view;
}
SDL_Texture* DrawSys::renderText(const string& text, int height, vec2i& size) {
if (text.empty()) { // not possible to draw empty text
size = 0;
return nullptr;
}
SDL_Surface* surf = TTF_RenderUTF8_Blended(fontSet.getFont(height), text.c_str(), Default::colorText);
SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf);
size = vec2i(surf->w, surf->h);
SDL_FreeSurface(surf);
return tex;
}
void DrawSys::drawWidgets() {
SDL_SetRenderDrawColor(renderer, Default::colorBackground.r, Default::colorBackground.g, Default::colorBackground.b, Default::colorBackground.a);
SDL_RenderClear(renderer);
World::scene()->getLayout()->drawSelf(); // draw main widgets
if (World::scene()->getPopup()) { // draw popup if exists and dim main widgets
SDL_Rect view = viewport();
SDL_SetRenderDrawColor(renderer, Default::colorPopupDim.r, Default::colorPopupDim.g, Default::colorPopupDim.b, Default::colorPopupDim.a);
SDL_RenderFillRect(renderer, &view);
World::scene()->getPopup()->drawSelf();
}
if (World::scene()->getContext()) // draw context if exists
drawContext(World::scene()->getContext());
if (LineEdit* let = dynamic_cast<LineEdit*>(World::scene()->capture)) // draw caret if capturing LineEdit
drawRect(let->caretRect(), Default::colorLight);
SDL_RenderPresent(renderer);
}
void DrawSys::drawButton(Button* wgt) {
drawRect(overlapRect(wgt->rect(), wgt->parentFrame()), Default::colorNormal);
}
void DrawSys::drawCheckBox(CheckBox* wgt) {
SDL_Rect frame = wgt->parentFrame();
drawRect(overlapRect(wgt->rect(), frame), Default::colorNormal); // draw background
drawRect(overlapRect(wgt->boxRect(), frame), wgt->on ? Default::colorLight : Default::colorDark); // draw checkbox
}
void DrawSys::drawColorBox(ColorBox* wgt) {
SDL_Rect frame = wgt->parentFrame();
drawRect(overlapRect(wgt->rect(), frame), Default::colorNormal); // draw background
drawRect(overlapRect(wgt->boxRect(), frame), wgt->color); // draw colorbox
}
void DrawSys::drawSlider(Slider* wgt) {
SDL_Rect frame = wgt->parentFrame();
drawRect(overlapRect(wgt->rect(), frame), Default::colorNormal); // draw background
drawRect(overlapRect(wgt->barRect(), frame), Default::colorDark); // draw bar
drawRect(overlapRect(wgt->sliderRect(), frame), Default::colorLight); // draw slider
}
void DrawSys::drawLabel(Label* wgt) {
SDL_Rect rect = overlapRect(wgt->rect(), wgt->parentFrame());
drawRect(rect, Default::colorNormal); // draw background
if (wgt->tex) { // modify frame and draw text if exists
rect.x += Default::textOffset;
rect.w -= Default::textOffset * 2;
drawText(wgt->tex, wgt->textRect(), rect);
}
}
void DrawSys::drawGraphView(GraphView* wgt) {
vec2i pos = wgt->position();
vec2i siz = wgt->size();
int endy = pos.y + siz.y;
// draw lines
vec2i lstt = vec2i(dotToPix(vec2f(World::winSys()->getSettings().viewPos.x, 0.f), World::winSys()->getSettings().viewPos, World::winSys()->getSettings().viewSize, vec2f(siz))) + pos;
drawLine(lstt, vec2i(lstt.x + siz.x - 1, lstt.y), Default::colorGraph, {pos.x, pos.y, siz.x, siz.y});
lstt = vec2i(dotToPix(vec2f(0.f, World::winSys()->getSettings().viewPos.y), World::winSys()->getSettings().viewPos, World::winSys()->getSettings().viewSize, vec2f(siz))) + pos;
drawLine(lstt, vec2i(lstt.x, lstt.y + siz.y - 1), Default::colorGraph, {pos.x, pos.y, siz.x, siz.y});
// draw graphs
for (const Graph& it : wgt->getGraphs()) {
SDL_Color color = World::program()->getFunction(it.fid).color;
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
sizt start = 0;
bool lastIn = false;
for (sizt x=0; x<it.pixs.size(); x++) {
bool curIn = inRange(it.pixs[x].y, pos.y, endy);
if (curIn) {
if (!lastIn)
start = x;
} else if (lastIn)
SDL_RenderDrawLines(renderer, &it.pixs[start], int(x-start));
lastIn = curIn;
}
if (lastIn)
SDL_RenderDrawLines(renderer, &it.pixs[start], int(it.pixs.size()-start));
}
}
void DrawSys::drawScrollArea(ScrollArea* box) {
vec2t vis = box->visibleWidgets(); // get index interval of items on screen and draw children
for (sizt i=vis.l; i<vis.u; i++)
box->getWidget(i)->drawSelf();
drawRect(box->barRect(), Default::colorDark); // draw scroll bar
drawRect(box->sliderRect(), Default::colorLight); // draw scroll slider
}
void DrawSys::drawPopup(Popup* pop) {
drawRect(pop->rect(), Default::colorNormal); // draw background
for (Widget* it : pop->getWidgets()) // draw children
it->drawSelf();
}
void DrawSys::drawContext(Context* con) {
SDL_Rect rect = con->rect();
drawRect(rect, Default::colorLight); // draw background
const vector<ContextItem>& items = con->getItems();
for (sizt i=0; i<items.size(); i++) // draw items aka. text
drawText(items[i].tex, con->itemRect(i), rect);
}
void DrawSys::drawRect(const SDL_Rect& rect, SDL_Color color) {
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
SDL_RenderFillRect(renderer, &rect);
}
void DrawSys::drawLine(vec2i pos, vec2i end, SDL_Color color, const SDL_Rect& frame) {
if (cropLine(pos, end, frame)) {
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
SDL_RenderDrawLine(renderer, pos.x, pos.y, end.x, end.y);
}
}
void DrawSys::drawText(SDL_Texture* tex, const SDL_Rect& rect, const SDL_Rect& frame) {
// crop destination rect and original texture rect
if (SDL_Rect dst; SDL_IntersectRect(&rect, &frame, &dst)) {
SDL_Rect src = {dst.x - rect.x, dst.y - rect.y, dst.w, dst.h};
SDL_RenderCopy(renderer, tex, &src, &dst);
}
}
| 33.883721
| 183
| 0.700069
|
karwler
|
e57c906c68ba77d31d2b02e65cc1fbd6aa245ee8
| 4,123
|
cpp
|
C++
|
solution/solutionthread.cpp
|
vitkorob/studentprojects
|
3b071eabec33f9e27eec81eaf5df339276c039be
|
[
"MIT"
] | null | null | null |
solution/solutionthread.cpp
|
vitkorob/studentprojects
|
3b071eabec33f9e27eec81eaf5df339276c039be
|
[
"MIT"
] | null | null | null |
solution/solutionthread.cpp
|
vitkorob/studentprojects
|
3b071eabec33f9e27eec81eaf5df339276c039be
|
[
"MIT"
] | null | null | null |
#include "solutionthread.h"
solutionThread::solutionThread()
{
metRKu = 1;
gam = 0.2;
g = 9.81;
L = 2;
del = 0.9;
p2 = 4;
eps = 0.0005;
x0 = 2;
v0 = 3;
t = 30;
step = 0.01;
}
double solutionThread::p(double y2)
{
return y2;
}
double solutionThread::q(double x2, double y2, double t2)
{
return ((-1) * gam * y2) - g * x2 / (L * (1 + del * cos(p2 * t2)));
}
void solutionThread::nextValueEuler(double *x, double *y, double t, double h)
{
*x += h * p(*y);
*y += h * q(*x, *y, t);
}
void solutionThread::nextValueRKutt(double *x, double *y, double t, double h)
{
double x1 = h * p(*y);
double y1 = h * q(*x, *y, t);
double x2 = h * p(*y + y1 * 0.5);
double y2 = h * q(*x + x1 * 0.5, *y + y1 * 0.5, t + h * 0.5);
double x3 = h * p(*y + y2 * 0.5);
double y3 = h * q(*x + x2 * 0.5, *y + y2 * 0.5, t + h * 0.5);
double x4 = h * p(*y + y3);
double y4 = h * q(*x + x3, *y + y3, t + h);
*x += (x1 + 2 * x2 + 2 * x3 + x4) / 6;
*y += (y1 + 2 * y2 + 2 * y3 + y4) / 6;
}
void solutionThread::run()
{
pnt_t.clear();
pnt_x.clear();
pnt_y.clear();
pnt_t.append(0);
pnt_x.append(x0);
pnt_y.append(v0);
double next_t0 = 0;
FILE *data = fopen("ivan-data.txt", "w");
fprintf(data, "%f\t%f\t%f\n", 0.0, x0, v0);
FILE *fileMetod = fopen("ivan-step.txt", "a");
double next_x0;
double next_y0;
double next_x1;
double next_y1;
double next_x2;
double next_y2;
double next_x3;
double next_y3;
double next_x_tmp = x0;
double next_y_tmp = v0;
if(metRKu)
{
while(next_t0 < t)
{
next_x0 = next_x1 = next_x2 = next_x_tmp;
next_y0 = next_y1 = next_y2 = next_y_tmp;
nextValueRKutt(&next_x0, &next_y0, next_t0, step);
nextValueRKutt(&next_x1, &next_y1, next_t0, 2 * step);
next_x3 = next_x0;
next_y3 = next_y0;
nextValueRKutt(&next_x3, &next_y3, next_t0 + step, step);
nextValueRKutt(&next_x2, &next_y2, next_t0, 0.5 * step);
nextValueRKutt(&next_x2, &next_y2, next_t0 + 0.5 * step, 0.5 * step);
if((fabs(next_x0 - next_x2) / 15 <= eps && fabs(next_x3 - next_x1) / 15 > eps) || next_y_tmp == 0)
{
pnt_t.append(next_t0 += step);
pnt_x.append(next_x_tmp = next_x0);
pnt_y.append(next_y_tmp = next_y0);
fprintf(data, "%f\t%f\t%f\n", next_t0, next_x0, next_y0);
}
else if(fabs(next_x3 - next_x1) / 15 < eps)
{
step *= 2;
}
else
{
step *= 0.5;
}
}
fprintf(fileMetod, "rkutt\t%.18lf\t%.18lf\n", eps, t / pnt_t.size());
fclose(fileMetod);
}
else
{
while(next_t0 < t)
{
next_x0 = next_x1 = next_x2 = next_x_tmp;
next_y0 = next_y1 = next_y2 = next_y_tmp;
nextValueEuler(&next_x0, &next_y0, next_t0, step);
nextValueEuler(&next_x1, &next_y1, next_t0, 2 * step);
next_x3 = next_x0;
next_y3 = next_y0;
nextValueEuler(&next_x3, &next_y3, next_t0 + step, step);
nextValueEuler(&next_x2, &next_y2, next_t0, 0.5 * step);
nextValueEuler(&next_x2, &next_y2, next_t0 + 0.5 * step, 0.5 * step);
if((fabs(next_x0 - next_x2) <= eps && fabs(next_x3 - next_x1) > eps) || next_y_tmp == 0)
{
pnt_t.append(next_t0 += step);
pnt_x.append(next_x_tmp = next_x0);
pnt_y.append(next_y_tmp = next_y0);
fprintf(data, "%f\t%f\t%f\n", next_t0, next_x0, next_y0);
}
else if(fabs(next_x3 - next_x1) < eps)
{
step *= 2;
}
else
{
step *= 0.5;
}
}
fprintf(fileMetod, "euler\t%.18lf\t%.18lf\n", eps, t / pnt_t.size());
fclose(fileMetod);
}
fclose(data);
}
| 25.140244
| 110
| 0.489207
|
vitkorob
|
e57c9863ca18340b608f0fa9bc4715893eb932b2
| 1,303
|
cxx
|
C++
|
Qt/Components/pqColorOverlay.cxx
|
xj361685640/ParaView
|
0a27eef5abc5a0c0472ab0bc806c4db881156e64
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 815
|
2015-01-03T02:14:04.000Z
|
2022-03-26T07:48:07.000Z
|
Qt/Components/pqColorOverlay.cxx
|
xj361685640/ParaView
|
0a27eef5abc5a0c0472ab0bc806c4db881156e64
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 9
|
2015-04-28T20:10:37.000Z
|
2021-08-20T18:19:01.000Z
|
Qt/Components/pqColorOverlay.cxx
|
xj361685640/ParaView
|
0a27eef5abc5a0c0472ab0bc806c4db881156e64
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 328
|
2015-01-22T23:11:46.000Z
|
2022-03-14T06:07:52.000Z
|
#include "pqColorOverlay.h"
#include <QPainter>
//-----------------------------------------------------------------------------
pqColorOverlay::pqColorOverlay(QWidget* parent)
: QWidget(parent)
{
setAttribute(Qt::WA_NoSystemBackground);
setAttribute(Qt::WA_TransparentForMouseEvents);
}
//-----------------------------------------------------------------------------
QColor pqColorOverlay::rgb() const
{
return Rgba;
}
//-----------------------------------------------------------------------------
void pqColorOverlay::setRgb(int r, int g, int b)
{
Rgba.setRgb(r, g, b);
this->repaint();
}
//-----------------------------------------------------------------------------
void pqColorOverlay::setRgb(QColor rgb)
{
Rgba.setRgb(rgb.red(), rgb.green(), rgb.blue());
this->repaint();
}
//-----------------------------------------------------------------------------
int pqColorOverlay::opacity() const
{
return Rgba.alpha();
}
//-----------------------------------------------------------------------------
void pqColorOverlay::setOpacity(int opacity)
{
Rgba.setAlpha(opacity);
this->repaint();
}
//-----------------------------------------------------------------------------
void pqColorOverlay::paintEvent(QPaintEvent*)
{
QPainter(this).fillRect(rect(), QBrush{ Rgba });
}
| 25.54902
| 79
| 0.403684
|
xj361685640
|
e57eee5672315a1c7762eba6e21dd57c0a8e7435
| 128
|
hpp
|
C++
|
Vendor/GLM/glm/ext/vector_uint1.hpp
|
wdrDarx/DEngine3
|
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
|
[
"MIT"
] | 2
|
2022-01-11T21:15:31.000Z
|
2022-02-22T21:14:33.000Z
|
Vendor/GLM/glm/ext/vector_uint1.hpp
|
wdrDarx/DEngine3
|
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
|
[
"MIT"
] | null | null | null |
Vendor/GLM/glm/ext/vector_uint1.hpp
|
wdrDarx/DEngine3
|
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
|
[
"MIT"
] | null | null | null |
version https://git-lfs.github.com/spec/v1
oid sha256:936046e1e48adf16a2daa297a69e3318537c55f39572a05efbae9aca1479cf89
size 711
| 32
| 75
| 0.882813
|
wdrDarx
|
e57fbaf38376bfb6b8788e60265427cd6c14091e
| 3,882
|
hpp
|
C++
|
include/cynodelic/mulinum/detail/split_helpers.hpp
|
cynodelic/mulinum
|
fc7b9e750aadaede2cee8d840e65fa3832787764
|
[
"BSL-1.0"
] | null | null | null |
include/cynodelic/mulinum/detail/split_helpers.hpp
|
cynodelic/mulinum
|
fc7b9e750aadaede2cee8d840e65fa3832787764
|
[
"BSL-1.0"
] | null | null | null |
include/cynodelic/mulinum/detail/split_helpers.hpp
|
cynodelic/mulinum
|
fc7b9e750aadaede2cee8d840e65fa3832787764
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2021 Álvaro Ceballos
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
/**
* @file split_helpers.hpp
*
* @brief Helpers for the `split` metafunction.
*/
#ifndef CYNODELIC_MULINUM_DETAIL_SPLIT_HELPERS_HPP
#define CYNODELIC_MULINUM_DETAIL_SPLIT_HELPERS_HPP
#include <cstddef>
#include <cynodelic/mulinum/config.hpp>
#include <cynodelic/mulinum/if.hpp>
#include <cynodelic/mulinum/string.hpp>
#include <cynodelic/mulinum/concat.hpp>
#include <cynodelic/mulinum/make_from_tag.hpp>
namespace cynodelic { namespace mulinum {
namespace detail
{
/**
* @brief Helper for @ref split.
*/
template <char, typename>
struct split_remove_front_delims;
/**
* @brief Helper for @ref split.
*/
template <char Delim, char First_, char... Others_>
struct split_remove_front_delims<Delim, string<First_, Others_...>>
{
using type = if_<
(Delim == First_),
typename split_remove_front_delims<Delim, string<Others_...>>::type,
string<First_, Others_...>
>;
};
/**
* @brief Helper for @ref split.
*/
template <char Delim, char Last_>
struct split_remove_front_delims<Delim, string<Last_>>
{
using type = if_<
(Delim == Last_),
string<>,
string<Last_>
>;
};
/**
* @brief Helper for @ref split.
*/
template <char, std::size_t, typename, bool>
struct split_make_delims_unique;
/**
* @brief Helper for @ref split.
*/
template <char Delim, std::size_t N, char First_, char Second_>
struct split_make_delims_unique<Delim, N, string<First_, Second_>, true>
{
using type = if_<
(First_ == Delim) && (Second_ == Delim),
string<>,
string<First_>
>;
};
/**
* @brief Helper for @ref split.
*/
template <char Delim, std::size_t N, char First_, char Second_, char... Others_>
struct split_make_delims_unique<Delim, N, string<First_, Second_, Others_...>, false>
{
using type = concat<
if_<
(First_ == Delim) && (Second_ == Delim),
string<>,
string<First_>
>,
typename split_make_delims_unique<Delim, N - 1, string<Second_, Others_...>, (N - 1) == 0>::type
>;
};
/**
* @brief Helper for @ref split.
*/
template <char, typename>
struct split_take_first_item;
/**
* @brief Helper for @ref split.
*/
template <char Delim, char First_, char... Others_>
struct split_take_first_item<Delim, string<First_, Others_...>>
{
using type = if_<
(First_ == Delim),
string<>,
concat<
string<First_>,
typename split_take_first_item<Delim, string<Others_...>>::type
>
>;
};
/**
* @brief Helper for @ref split.
*/
template <char Delim, char Last_>
struct split_take_first_item<Delim, string<Last_>>
{
using type = if_<
Last_ == Delim,
string<>,
string<Last_>
>;
};
/**
* @brief Helper for @ref split.
*/
template <char Delim, typename StringT_, std::size_t From>
using split_take_item = typename detail::split_take_first_item<Delim, take_c<StringT_, From, StringT_::size - From>>::type;
/**
* @brief Helper for @ref split.
*/
template <typename TypeContainerTag, char Delim, typename StringT_, std::size_t Count, bool = (Count == StringT_::size)>
struct splitter
{
using type = concat<
make_from_tag<TypeContainerTag, split_take_item<Delim, StringT_, Count>>,
typename splitter<
TypeContainerTag,
Delim,
StringT_,
(Count + split_take_item<Delim, StringT_, Count>::size + 1)
>::type
>;
};
/**
* @brief Helper for @ref split.
*/
template <typename TypeContainerTag, char Delim, typename StringT_, std::size_t Count>
struct splitter<TypeContainerTag, Delim, StringT_, Count, true>
{
using type = make_from_tag<TypeContainerTag>;
};
} // end of "detail" namespace
}} // end of "cynodelic::mulinum" namespace
#endif // CYNODELIC_MULINUM_DETAIL_SPLIT_HELPERS_HPP
| 21.687151
| 124
| 0.676455
|
cynodelic
|
e582a8d0fc49f20af9374fe9a7e4fda2278e60e7
| 129
|
cc
|
C++
|
tensorflow-yolo-ios/dependencies/google/protobuf/stubs/atomicops_internals_x86_msvc.cc
|
initialz/tensorflow-yolo-face-ios
|
ba74cf39168d0128e91318e65a1b88ce4d65a167
|
[
"MIT"
] | 27
|
2017-06-07T19:07:32.000Z
|
2020-10-15T10:09:12.000Z
|
tensorflow-yolo-ios/dependencies/google/protobuf/stubs/atomicops_internals_x86_msvc.cc
|
initialz/tensorflow-yolo-face-ios
|
ba74cf39168d0128e91318e65a1b88ce4d65a167
|
[
"MIT"
] | 3
|
2017-08-25T17:39:46.000Z
|
2017-11-18T03:40:55.000Z
|
tensorflow-yolo-ios/dependencies/google/protobuf/stubs/atomicops_internals_x86_msvc.cc
|
initialz/tensorflow-yolo-face-ios
|
ba74cf39168d0128e91318e65a1b88ce4d65a167
|
[
"MIT"
] | 10
|
2017-06-16T18:04:45.000Z
|
2018-07-05T17:33:01.000Z
|
version https://git-lfs.github.com/spec/v1
oid sha256:516879d2c1b04ff8b7ba32487c8446e3241805e4352f374533aa6756863b4cad
size 4366
| 32.25
| 75
| 0.883721
|
initialz
|
e5847e79f40e20540105d7d68c2b19de80dc5ceb
| 4,115
|
cpp
|
C++
|
ufora/FORA/TypedFora/ABI/MutableVectorHandleCodegen.cpp
|
ufora/ufora
|
04db96ab049b8499d6d6526445f4f9857f1b6c7e
|
[
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 571
|
2015-11-05T20:07:07.000Z
|
2022-01-24T22:31:09.000Z
|
ufora/FORA/TypedFora/ABI/MutableVectorHandleCodegen.cpp
|
timgates42/ufora
|
04db96ab049b8499d6d6526445f4f9857f1b6c7e
|
[
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 218
|
2015-11-05T20:37:55.000Z
|
2021-05-30T03:53:50.000Z
|
ufora/FORA/TypedFora/ABI/MutableVectorHandleCodegen.cpp
|
timgates42/ufora
|
04db96ab049b8499d6d6526445f4f9857f1b6c7e
|
[
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 40
|
2015-11-07T21:42:19.000Z
|
2021-05-23T03:48:19.000Z
|
/***************************************************************************
Copyright 2015 Ufora 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 "MutableVectorHandleCodegen.hpp"
#include "NativeLayoutType.hppml"
#include "../../Judgment/JudgmentOnValue.hppml"
#include "../../../core/SymbolExport.hpp"
#include "../../../core/Logging.hpp"
#include "../../Native/NativeCode.hppml"
#include "../../Native/NativeTypeFor.hpp"
#include "../../Native/NativeExpressionBuilder.hppml"
#include "../../Native/TypedNativeLibraryFunction.hpp"
#include "DestructorsAndConstructors.hppml"
using TypedFora::Abi::MutableVectorHandle;
NativeType NativeTypeForImpl<MutableVectorHandle>::get()
{
return
NativeType::Composite("mRefcount", NativeType::uword()) +
NativeType::Composite("mSize", NativeType::uword()) +
NativeType::Composite("mRawDataPtr", NativeType::uint8().ptr()) +
NativeType::Composite("mOwningMemoryPool", NativeType::Nothing().ptr()) +
NativeType::Composite("mElementJOV", NativeTypeFor<JudgmentOnValue>::get()) +
NativeType::Composite("mVectorHash", NativeTypeFor<hash_type>::get())
;
}
extern "C" {
BSA_DLLEXPORT
void FORA_clib_incrementMutableVectorHandleRefcount(MutableVectorHandle* handle)
{
handle->incrementRefcount();
}
BSA_DLLEXPORT
uint8_t FORA_clib_decrementMutableVectorHandleRefcount(MutableVectorHandle* handle)
{
return handle->decrementRefcount();
}
}
namespace TypedFora {
namespace Abi {
namespace MutableVectorHandleCodegen {
NativeExpression sizeExpression(
const NativeExpression& arrayPtrE
)
{
lassert(*arrayPtrE.type() == NativeTypeFor<MutableVectorHandle>::get().ptr());
return arrayPtrE["mSize"].load();
}
NativeExpression incrementRefcountExpr(
const NativeExpression& arrayPtrE
)
{
lassert(*arrayPtrE.type() == NativeTypeFor<MutableVectorHandle>::get().ptr());
return makeTypedNativeLibraryFunction(
&FORA_clib_incrementMutableVectorHandleRefcount
)(arrayPtrE).getExpression()
;
}
NativeExpression decrementRefcountExpr(
const NativeExpression& arrayPtrE
)
{
lassert(*arrayPtrE.type() == NativeTypeFor<MutableVectorHandle>::get().ptr());
return makeTypedNativeLibraryFunction(
&FORA_clib_decrementMutableVectorHandleRefcount
)(arrayPtrE).getExpression()
;
}
NativeExpression basePointerExpressionAsRawPtr(
const NativeExpression& arrayPtrE
)
{
return
arrayPtrE["mRawDataPtr"]
.load()
;
}
NativeExpression getItemExpr(
const NativeExpression& arrayPtrE,
const NativeExpression& indexE,
const JudgmentOnValue& elementJov
)
{
if (elementJov.constant())
return NativeExpression();
return TypedFora::Abi::duplicate(
elementJov,
arrayPtrE["mRawDataPtr"]
.load()
.cast(nativeLayoutType(elementJov).ptr(), true)
[indexE].load()
);
}
NativeExpression setItemExpr(
const NativeExpression& arrayPtrE,
const NativeExpression& indexE,
const NativeExpression& dataE,
const JudgmentOnValue& elementJov
)
{
NativeExpressionBuilder builder;
if (elementJov.constant())
return NativeExpression();
NativeExpression eltPtr = builder.add(
arrayPtrE["mRawDataPtr"].load()
.cast(nativeLayoutType(elementJov).ptr(), false)
[indexE]
);
NativeExpression duplicatedVal =
builder.add(
TypedFora::Abi::duplicate(elementJov, dataE)
);
builder.add(
TypedFora::Abi::destroy(elementJov, eltPtr.load())
);
builder.add(
eltPtr.store(duplicatedVal)
);
return builder(NativeExpression());
}
}
}
}
| 25.401235
| 83
| 0.710814
|
ufora
|
e586cb9547fbb7a410e2af42433496cd9ae6ab0c
| 3,417
|
cxx
|
C++
|
private/inet/mshtml/src/site/ole/frame.cxx
|
King0987654/windows2000
|
01f9c2e62c4289194e33244aade34b7d19e7c9b8
|
[
"MIT"
] | 11
|
2017-09-02T11:27:08.000Z
|
2022-01-02T15:25:24.000Z
|
private/inet/mshtml/src/site/ole/frame.cxx
|
King0987654/windows2000
|
01f9c2e62c4289194e33244aade34b7d19e7c9b8
|
[
"MIT"
] | null | null | null |
private/inet/mshtml/src/site/ole/frame.cxx
|
King0987654/windows2000
|
01f9c2e62c4289194e33244aade34b7d19e7c9b8
|
[
"MIT"
] | 14
|
2019-01-16T01:01:23.000Z
|
2022-02-20T15:54:27.000Z
|
//+---------------------------------------------------------------------
//
// File: frame.cxx
//
// Contents: frame tag implementation
//
// Classes: CFrameSite, etc..
//
//------------------------------------------------------------------------
#include "headers.hxx"
#ifndef X_FORMKRNL_HXX_
#define X_FORMKRNL_HXX_
#include "formkrnl.hxx"
#endif
#ifndef X_FRAME_HXX_
#define X_FRAME_HXX_
#include "frame.hxx"
#endif
#ifndef X_FRAMESET_HXX_
#define X_FRAMESET_HXX_
#include "frameset.hxx"
#endif
#ifndef X_PROPS_HXX_
#define X_PROPS_HXX_
#include "props.hxx"
#endif
#define _cxx_
#include "frame.hdl"
MtDefine(CFrameElement, Elements, "CFrameElement")
MtDefine(CIFrameElement, Elements, "CIFrameElement")
const CElement::CLASSDESC CFrameElement::s_classdesc =
{
{
&CLSID_HTMLFrameElement, // _pclsid
0, // _idrBase
#ifndef NO_PROPERTY_PAGE
s_apclsidPages, // _apClsidPages
#endif // NO_PROPERTY_PAGE
s_acpi, // _pcpi
ELEMENTDESC_NEVERSCROLL |
ELEMENTDESC_OLESITE, // _dwFlags
&IID_IHTMLFrameElement, // _piidDispinterface
&s_apHdlDescs, // _apHdlDesc
},
(void *)s_apfnpdIHTMLFrameElement, // _pfnTearOff
NULL, // _pAccelsDesign
NULL // _pAccelsRun
};
//+---------------------------------------------------------------------------
//
// element creator used by parser
//
//----------------------------------------------------------------------------
HRESULT
CFrameElement::CreateElement(CHtmTag *pht,
CDoc *pDoc, CElement **ppElementResult)
{
Assert(ppElementResult);
*ppElementResult = new CFrameElement(pDoc);
RRETURN ( (*ppElementResult) ? S_OK : E_OUTOFMEMORY);
}
//+---------------------------------------------------------------------------
//
// Member: CFrameElement constructor
//
//----------------------------------------------------------------------------
CFrameElement::CFrameElement(CDoc *pDoc)
: CFrameSite(ETAG_FRAME, pDoc)
{
}
//+----------------------------------------------------------------------------
//
// Member: CFrameElement:get_height
//
//-----------------------------------------------------------------------------
STDMETHODIMP CFrameElement::get_height(VARIANT * p)
{
HRESULT hr = S_OK;
if (p)
{
V_VT(p) = VT_I4;
CLayout * pLayout = GetCurLayout();
V_I4(p) = pLayout->GetHeight();
}
RRETURN(SetErrorInfo(hr));
}
STDMETHODIMP CFrameElement::put_height(VARIANT p)
{
RRETURN(SetErrorInfo(CTL_E_METHODNOTAPPLICABLE));
}
//+----------------------------------------------------------------------------
//
// Member: CFrameElement:get_width
//
//-----------------------------------------------------------------------------
STDMETHODIMP CFrameElement::get_width(VARIANT * p)
{
HRESULT hr = S_OK;
if (p)
{
V_VT(p) = VT_I4;
CLayout * pLayout = GetCurLayout();
V_I4(p) = pLayout->GetWidth();
}
RRETURN(SetErrorInfo(hr));
}
STDMETHODIMP CFrameElement::put_width(VARIANT p)
{
RRETURN(SetErrorInfo(CTL_E_METHODNOTAPPLICABLE));
}
| 26.083969
| 80
| 0.458589
|
King0987654
|
e5887ce1debe7449e1edd420a14fcb83002b21a4
| 12,076
|
cpp
|
C++
|
angsd/abcGL.cpp
|
peterdfields/angsd-wrapper
|
199abf0b513a763114511f08dfce742305f41a91
|
[
"MIT"
] | 6
|
2015-07-25T02:05:07.000Z
|
2021-05-27T08:37:01.000Z
|
angsd/abcGL.cpp
|
peterdfields/angsd-wrapper
|
199abf0b513a763114511f08dfce742305f41a91
|
[
"MIT"
] | 60
|
2015-01-10T20:46:25.000Z
|
2018-09-19T22:32:02.000Z
|
angsd/abcGL.cpp
|
peterdfields/angsd-wrapper
|
199abf0b513a763114511f08dfce742305f41a91
|
[
"MIT"
] | 8
|
2015-04-12T09:37:58.000Z
|
2017-04-25T19:30:39.000Z
|
/*
thorfinn thorfinn@binf.ku.dk dec17 2012
part of angsd
This class will calculate the GL in 4 differnt ways
1) SAMtools 0.1.16+ version
2) Simple GATK model
3) SOAPsnp
4) SYK
4 different output formats are supplied
1) binary 10xdouble persample
2) beagle output (requires estimation of major/minor)\
3) binary beagle
4) text output of the 10 llhs persample
*/
#include <cmath>
#include <zlib.h>
#include <assert.h>
#include "kstring.h"//<-used for buffered output when dumping beagle 0.204
#include "bfgs.h"
#include "analysisFunction.h"
#include "abc.h"
#include "abcGL.h"
#include "abcError.h"
extern int refToInt[256];
static float *logfactorial=NULL;
void readError(double **errors,const char *fname){
fprintf(stderr,"will try to read errorestimates from file:%s\n",fname);
FILE *fp=NULL;
if(NULL==(fp=fopen(fname,"r"))){
fprintf(stderr,"Error opening file: %s\n",fname);
exit(0);
}
char buf[LENS];
double res[16];
for(int i=0;i<16;i++) res[i] = 0;
int nLines =0;
while(fgets(buf,LENS,fp)){
res[0] += atof(strtok(buf," \t\n"));
for(int i=1;i<16;i++)
res[i] += atof(strtok(NULL," \t\n"));
nLines ++;
}
for(int j=0;j<16;j++)
fprintf(stderr,"%f\t",res[j]);
fprintf(stderr,"\nEstimating errors using nChunks:%d\n",nLines);
int pos =0;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
errors[i][j] = res[pos++]/(1.0*nLines);
if(fp) fclose(fp);
}
void abcGL::printArg(FILE *argFile){
fprintf(argFile,"---------------------\n%s:\n",__FILE__);
fprintf(argFile,"\t-GL=%d: \n",GL);
fprintf(argFile,"\t1: SAMtools\n");
fprintf(argFile,"\t2: GATK\n");
fprintf(argFile,"\t3: SOAPsnp\n");
fprintf(argFile,"\t4: SYK\n");
fprintf(argFile,"\t-trim\t\t%d\t\t(zero means no trimming)\n",trim);
fprintf(argFile,"\t-tmpdir\t\t%s/\t(used by SOAPsnp)\n",angsd_tmpdir);
fprintf(argFile,"\t-errors\t\t%s\t\t(used by SYK)\n",errorFname);
fprintf(argFile,"\t-minInd\t\t%d\t\t(0 indicates no filtering)\n",minInd);
fprintf(argFile,"\n");
fprintf(argFile,"Filedumping:\n");
fprintf(argFile,"\t-doGlf\t%d\n",doGlf);
fprintf(argFile,"\t1: binary glf (10 log likes)\t%s\n",postfix);
fprintf(argFile,"\t2: beagle likelihood file\t%s\n",beaglepostfix);
fprintf(argFile,"\t3: binary 3 times likelihood\t%s\n",postfix);
fprintf(argFile,"\t4: text version (10 log likes)\t%s\n",postfix);
fprintf(argFile,"\n");
}
void abcGL::getOptions(argStruct *arguments){
//parse all parameters that this class could use
GL=angsd::getArg("-GL",GL,arguments);
trim = angsd::getArg("-trim",trim,arguments);
angsd_tmpdir = angsd::getArg("-tmpdir",angsd_tmpdir,arguments);
doGlf=angsd::getArg("-doGlf",doGlf,arguments);
errorFname = angsd::getArg("-errors",errorFname,arguments);
minInd = angsd::getArg("-minInd",minInd,arguments);
int doCounts=0;
int doMajorMinor =0;
doCounts=angsd::getArg("-doCounts",doCounts,arguments);
doMajorMinor=angsd::getArg("-doMajorMinor",doMajorMinor,arguments);
if(arguments->inputtype==INPUT_GLF&&GL!=0){
fprintf(stderr,"Can't calculate genotype likelihoods from glf files\n");
exit(0);
}
if(arguments->inputtype==INPUT_GLF)
return;
if(doGlf&&GL==0){
fprintf(stderr,"\t-> You need to choose a genotype likelihood model -GL for dumping genotype likelihoods\n");
exit(0);
}
if(GL==0&&doGlf==0){
shouldRun[index] =0;
return;
}
if(GL==0)
return;
if(GL<0||GL>4){
fprintf(stderr,"\t-> You've choosen a GL model=%d, only 1,2,3,4 are implemented\n",GL);
exit(0);
}
if(GL==4&&(doCounts==0)){
fprintf(stderr,"\t-> Must supply -doCounts for SYK model\n");
exit(0);
}
if((doGlf==2||doGlf==3) && doMajorMinor==0){
fprintf(stderr,"\t-> For dumping beaglestyle output you need to estimate major/minor: -doMajorMinor\n");
exit(0);
}
if(arguments->inputtype==INPUT_BEAGLE&&doGlf){
fprintf(stderr,"\t-> cannot output likelihoods (doGlf) when input is beagle\n");
exit(0);
}
if(arguments->inputtype!=INPUT_BAM&&arguments->inputtype!=INPUT_PILEUP){
fprintf(stderr,"Error: Likelihoods can only be estimated based on SOAP input and uppile input\n");
exit(0);
}
printArg(arguments->argumentFile);
}
abcGL::abcGL(const char *outfiles,argStruct *arguments,int inputtype){
errors = NULL;
postfix = ".glf.gz";
beaglepostfix = ".beagle.gz";
trim =0;
GL=0;
doGlf=0;
errorFname = NULL;
errorProbs = NULL;
GL=0;
minInd=0;
angsd_tmpdir = strdup("angsd_tmpdir");
if(arguments->argc==2){
if(!strcasecmp(arguments->argv[1],"-GL")){
printArg(stdout);
exit(0);
}else
return;
}
getOptions(arguments);
printArg(arguments->argumentFile);
// if(GL==0)
// return;
if(GL==1)
bam_likes_init();
else if(GL==2)
gatk_init();
else if(GL==3){
soap.init(arguments->nInd,angsd_tmpdir);
if(soap.doRecal)
fprintf(stderr,"[%s] Will calculate recalibration matrices, please don't do any other analysis\n",__FILE__);
else
fprintf(stderr,"[%s] Will use precalculated calibration matrices\n",__FILE__);
}else if(GL==4) {
//default errormatrix
double errorsDefault[4][4]={{0 ,0.00031 , 0.00373 , 0.000664},
{0.000737, 0 , 0.000576, 0.001702},
{0.001825,0.000386, 0 , 0.000653},
{0.00066 ,0.003648, 0.000321, 0 },
};
//allocate and plug in default values
errors = new double *[4];
for(int i=0;i<4;i++){
errors[i] = new double[4];
for(int j=0;j<4;j++)
errors[i][j] = errorsDefault[i][j];
}
if(errorFname!=NULL)
readError(errors,errorFname);
errorProbs = abcError::generateErrorPointers(errors,3,4);
}
gzoutfile = Z_NULL;
bufstr.s=NULL; bufstr.l=bufstr.m=0;// <- used for buffered output
bufstr.l=0;
if(doGlf){
if(doGlf!=2)
gzoutfile = aio::openFileGz(outfiles,postfix,GZOPT);
else{
gzoutfile = aio::openFileGz(outfiles,beaglepostfix,GZOPT);
kputs("marker\tallele1\tallele2",&bufstr);
for(int i=0;i<arguments->nInd;i++){
kputs("\tInd",&bufstr);
kputw(i,&bufstr);
kputs("\tInd",&bufstr);
kputw(i,&bufstr);
kputs("\tInd",&bufstr);
kputw(i,&bufstr);
}
kputc('\n',&bufstr);
gzwrite(gzoutfile,bufstr.s,bufstr.l);
}
}
}
abcGL::~abcGL(){
free(angsd_tmpdir);
if(GL==0&&doGlf==0)
return;
else if(GL==1)
bam_likes_destroy();
else if(GL==2)
gatk_destroy();
else if(GL==4)
abcError::killGlobalErrorProbs(errorProbs);
if(doGlf) gzclose(gzoutfile);
if(bufstr.s!=NULL)
free(bufstr.s);
if(errors){
for(int i=0;i<4;i++)
delete [] errors[i];
delete [] errors;
}
delete [] logfactorial;
}
void abcGL::clean(funkyPars *pars){
if(pars->likes!=NULL){
for(int i=0;i<pars->numSites;i++)
delete [] pars->likes[i];
delete [] pars->likes;
}
}
void abcGL::print(funkyPars *pars){
if(doGlf)
printLike(pars);
}
void abcGL::run(funkyPars *pars){
assert(pars!=NULL);
if(GL==0)
return;
//assert(pars->chk!=NULL);
double **likes = NULL;
if(soap.doRecal!=1)
likes = new double*[pars->chk->nSites];
if(GL==1)
call_bam(pars->chk,likes,trim);
else if(GL==2)
call_gatk(pars->chk,likes,trim);
else if(GL==3){
soap.run(pars->chk,likes,pars->ref,trim);
//we dont estimate GL but make a calibration matrix
if(soap.doRecal==1)
return;
}else if(GL==4)
getLikesFullError10Genotypes(pars->numSites,pars->nInd,pars->counts,errorProbs,pars->keepSites,likes);
pars->likes = likes;
/*
if trimming has been requested, then some site might not contain data,
we therefore set keepsites to zero for these sites
while we are at it, lets also count the effective sample size persite
*/
if(1){
for(int s=0;s<pars->numSites;s++){
// fprintf(stderr,"keepSites[%d]=%d\n",s,pars->keepSites[s]);
if(pars->keepSites[s]==0)
continue;
int efSize=0;
for(int i=0;i<pars->nInd;i++){
for(int ii=1;ii<10;ii++){
if(pars->likes[s][i*10+ii]!=pars->likes[s][i*10+0]){
efSize++;
// break;
}
}
}
pars->keepSites[s] = efSize;
if(minInd!=0&&minInd>efSize)
pars->keepSites[s] = 0;
}
}
//rescale the genotype likelihoods to loglike ratios.
if(1){
for(int s=0;s<pars->numSites;s++){
if(pars->keepSites[s]==0)
continue;
for(int i=0;i<pars->nInd;i++)
angsd::logrescale(pars->likes[s] +i*10,10);
}
}
}
void abcGL::getLikesFullError10Genotypes(int numSites,int nInd,suint **counts,double ****errorProbs,int *keepSites,double **loglikes) {
//only calculate this once
if(logfactorial==NULL)//dont bother populating if exists.
logfactorial=abcError::logfact(LOGMAX); //calculate log factorials
double *logError;
for(int s=0;s<numSites;s++){
loglikes[s] = new double [10*nInd];
if(keepSites[s]==0)
continue;
for(int allele1=0;allele1<4;allele1++) {
for(int allele2=allele1;allele2<4;allele2++){
int Gindex=angsd::majorminor[allele1][allele2];
int geno=0;
int m2=allele2;
if(allele1!=allele2)
geno++;
else{//total grimt must redo
m2++;
if(m2>3)
m2=0;
}
logError=errorProbs[geno][allele1][m2];
for(int i=0;i<nInd;i++){
loglikes[s][i*10+Gindex]=logfactorial[counts[s][i*4+0]+counts[s][i*4+1]+counts[s][i*4+2]+counts[s][i*4+3]]; //should be computed before these loops for faster implimentation
for(int j=0;j<4;j++)
loglikes[s][i*10+Gindex]+=-logfactorial[counts[s][i*4+j]]+counts[s][i*4+j]*logError[j];
}
}
}
}
}
void abcGL::printLike(funkyPars *pars) {
assert(pars->likes!=NULL);
if(doGlf==1){
//glffinn format
for(int i=0;i<pars->numSites;i++){
if(pars->keepSites[i]==0)
continue;
gzwrite(gzoutfile,pars->likes[i],sizeof(double)*10*pars->nInd);
}
}
else if(doGlf==2){
//beagle format
bufstr.l = 0; //set tmpbuf beginning to zero
for(int s=0;s<pars->numSites;s++) {
if(pars->keepSites[s]==0)
continue;
kputs(header->name[pars->refId],&bufstr);
kputc('_',&bufstr);
kputw(pars->posi[s]+1,&bufstr);
kputc('\t',&bufstr);
kputw(pars->major[s],&bufstr);
kputc('\t',&bufstr);
kputw(pars->minor[s],&bufstr);
int major = pars->major[s];
int minor = pars->minor[s];
assert(major!=4&&minor!=4);
for(int i=0;i<pars->nInd;i++) {
double norm=exp(pars->likes[s][i*10+angsd::majorminor[major][major]])+exp(pars->likes[s][i*10+angsd::majorminor[major][minor]])+exp(pars->likes[s][i*10+angsd::majorminor[minor][minor]]);
double val1 = exp(pars->likes[s][i*10+angsd::majorminor[major][major]])/norm;
double val2 = exp(pars->likes[s][i*10+angsd::majorminor[major][minor]])/norm;
double val3 = exp(pars->likes[s][i*10+angsd::majorminor[minor][minor]])/norm;
ksprintf(&bufstr, "\t%f",val1);
ksprintf(&bufstr, "\t%f",val2);
ksprintf(&bufstr, "\t%f",val3);
}
kputc('\n',&bufstr);
}
gzwrite(gzoutfile,bufstr.s,bufstr.l);
}
else if(doGlf==3) { //FGV v0.208 Aug,28
for(int s=0;s<pars->numSites;s++) {
if(pars->keepSites[s]==0) //TSK 0.441 sep 25
continue;
int major = pars->major[s];
int minor = pars->minor[s] ;
assert(major!=4&&minor!=4);
for(int i=0;i<pars->nInd;i++) {
double dump[3];
dump[0] = pars->likes[s][i*10+angsd::majorminor[major][major]] ;
dump[1] = pars->likes[s][i*10+angsd::majorminor[major][minor]] ;
dump[2] = pars->likes[s][i*10+angsd::majorminor[minor][minor]] ;
gzwrite(gzoutfile,dump,3*sizeof(double));
}
}
} else if(doGlf==4){
bufstr.l=0;
//otherwise print textoutput
for(int s=0;s<pars->numSites;s++){
if(pars->keepSites[s]==0)
continue;
kputs(header->name[pars->refId],&bufstr);
kputc('\t',&bufstr);
kputw(pars->posi[s]+1,&bufstr);
for(int i=0;i<10*pars->nInd;i++)
ksprintf(&bufstr, "\t%f",pars->likes[s][i]);
kputc('\n',&bufstr);
}
gzwrite(gzoutfile,bufstr.s,bufstr.l);
}
}
| 25.748401
| 187
| 0.622226
|
peterdfields
|
e588ba30a9a4c0dc44a82cb38413c711dd3b5fc2
| 14,602
|
cpp
|
C++
|
src/qt-console/tray-monitor/runjob.cpp
|
tech-niche-biz/bacula-9.4.4
|
5e74458b612354f6838652dac9ddff94be1bbce6
|
[
"BSD-2-Clause"
] | null | null | null |
src/qt-console/tray-monitor/runjob.cpp
|
tech-niche-biz/bacula-9.4.4
|
5e74458b612354f6838652dac9ddff94be1bbce6
|
[
"BSD-2-Clause"
] | null | null | null |
src/qt-console/tray-monitor/runjob.cpp
|
tech-niche-biz/bacula-9.4.4
|
5e74458b612354f6838652dac9ddff94be1bbce6
|
[
"BSD-2-Clause"
] | null | null | null |
/*
Bacula(R) - The Network Backup Solution
Copyright (C) 2000-2018 Kern Sibbald
The original author of Bacula is Kern Sibbald, with contributions
from many others, a complete list can be found in the file AUTHORS.
You may use this file and others of this release according to the
license defined in the LICENSE file, which includes the Affero General
Public License, v3.0 ("AGPLv3") and some additional permissions and
terms pursuant to its AGPLv3 Section 7.
This notice must be preserved when any source code is
conveyed and/or propagated.
Bacula(R) is a registered trademark of Kern Sibbald.
*/
#include "runjob.h"
#include <QMessageBox>
static void fillcombo(QComboBox *cb, alist *lst, bool addempty=true)
{
if (lst && lst->size() > 0) {
QStringList list;
char *str;
if (addempty) {
list << QString("");
}
foreach_alist(str, lst) {
list << QString(str);
}
cb->addItems(list);
} else {
cb->setEnabled(false);
}
}
RunJob::RunJob(RESMON *r): QDialog(), res(r), tabAdvanced(NULL)
{
int nbjob;
if (res->jobs->size() == 0) {
QMessageBox msgBox;
msgBox.setText(_("This restricted console does not have access to Backup jobs"));
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
deleteLater();
return;
}
ui.setupUi(this);
setModal(true);
connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(close_cb()));
connect(ui.okButton, SIGNAL(clicked()), this, SLOT(runjob()));
connect(ui.jobCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(jobChanged(int)));
connect(ui.levelCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(levelChanged(int)));
ui.dateTimeEdit->setMinimumDate(QDate::currentDate());
ui.dateTimeEdit->setMaximumDate(QDate::currentDate().addDays(7));
ui.dateTimeEdit->setDate(QDate::currentDate());
ui.dateTimeEdit->setTime(QTime::currentTime());
ui.boxEstimate->setVisible(false);
res->mutex->lock();
nbjob = res->jobs->size();
fillcombo(ui.jobCombo, res->jobs, (nbjob > 1));
fillcombo(ui.clientCombo, res->clients);
fillcombo(ui.filesetCombo,res->filesets);
fillcombo(ui.poolCombo, res->pools);
fillcombo(ui.storageCombo,res->storages);
fillcombo(ui.catalogCombo,res->catalogs);
res->mutex->unlock();
connect(ui.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChange(int)));
QStringList levels;
levels << "" << "Incremental" << "Differential" << "Full";
ui.levelCombo->addItems(levels);
MONITOR *m = (MONITOR*) GetNextRes(R_MONITOR, NULL);
if (!m->display_advanced_options) {
tabAdvanced = ui.tabWidget->widget(1);
ui.tabWidget->removeTab(1);
}
show();
}
void RunJob::tabChange(int idx)
{
QString q = ui.tabWidget->tabText(idx);
if (q.contains("Advanced")) {
if (ui.jobCombo->currentText().compare("") == 0) {
pm_strcpy(curjob, "");
ui.tab2->setEnabled(false);
} else if (ui.jobCombo->currentText().compare(curjob.c_str()) != 0) {
task *t = new task();
char *job = bstrdup(ui.jobCombo->currentText().toUtf8().data());
pm_strcpy(curjob, job); // Keep the job name to not refresh the Advanced tab the next time
Dmsg1(10, "get defaults for %s\n", job);
res->mutex->lock();
bfree_and_null(res->defaults.job);
res->defaults.job = job;
res->mutex->unlock();
ui.tab2->setEnabled(false);
connect(t, SIGNAL(done(task *)), this, SLOT(fill_defaults(task *)), Qt::QueuedConnection);
t->init(res, TASK_DEFAULTS);
res->wrk->queue(t);
}
}
}
void RunJob::runjob()
{
POOL_MEM tmp;
char *p;
p = ui.jobCombo->currentText().toUtf8().data();
if (!p || !*p) {
QMessageBox msgBox;
msgBox.setText(_("Nothing selected"));
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
return;
}
Mmsg(command, "run job=\"%s\" yes", p);
if (strcmp(p, NPRTB(res->defaults.job)) == 0 || strcmp("", NPRTB(res->defaults.job)) == 0) {
p = ui.storageCombo->currentText().toUtf8().data();
if (p && *p && strcmp(p, NPRTB(res->defaults.storage)) != 0) {
Mmsg(tmp, " storage=\"%s\"", p);
pm_strcat(command, tmp.c_str());
}
p = ui.clientCombo->currentText().toUtf8().data();
if (p && *p && strcmp(p, NPRTB(res->defaults.client)) != 0) {
Mmsg(tmp, " client=\"%s\"", p);
pm_strcat(command, tmp.c_str());
}
p = ui.levelCombo->currentText().toUtf8().data();
if (p && *p && strcmp(p, NPRTB(res->defaults.level)) != 0) {
Mmsg(tmp, " level=\"%s\"", p);
pm_strcat(command, tmp.c_str());
}
p = ui.poolCombo->currentText().toUtf8().data();
if (p && *p && strcmp(p, NPRTB(res->defaults.pool)) != 0) {
Mmsg(tmp, " pool=\"%s\"", p);
pm_strcat(command, tmp.c_str());
}
p = ui.filesetCombo->currentText().toUtf8().data();
if (p && *p && strcmp(p, NPRTB(res->defaults.fileset)) != 0) {
Mmsg(tmp, " fileset=\"%s\"", p);
pm_strcat(command, tmp.c_str());
}
if (res->defaults.priority && res->defaults.priority != ui.prioritySpin->value()) {
Mmsg(tmp, " priority=\"%d\"", res->defaults.priority);
pm_strcat(command, tmp.c_str());
}
}
QDate dnow = QDate::currentDate();
QTime tnow = QTime::currentTime();
QDate dval = ui.dateTimeEdit->date();
QTime tval = ui.dateTimeEdit->time();
if (dval > dnow || (dval == dnow && tval > tnow)) {
Mmsg(tmp, " when=\"%s %s\"", dval.toString("yyyy-MM-dd").toUtf8().data(), tval.toString("hh:mm:00").toUtf8().data());
pm_strcat(command, tmp.c_str());
}
if (res->type == R_CLIENT) {
pm_strcat(command, " fdcalled=1");
}
// Build the command and run it!
task *t = new task();
t->init(res, TASK_RUN);
connect(t, SIGNAL(done(task *)), this, SLOT(jobStarted(task *)), Qt::QueuedConnection);
t->arg = command.c_str();
res->wrk->queue(t);
}
void RunJob::jobStarted(task *t)
{
Dmsg1(10, "%s\n", command.c_str());
Dmsg1(10, "-> jobid=%d\n", t->result.i);
deleteLater();
delete t;
}
void RunJob::close_cb(task *t)
{
deleteLater();
delete t;
}
void RunJob::close_cb()
{
task *t = new task();
connect(t, SIGNAL(done(task *)), this, SLOT(close_cb(task *)), Qt::QueuedConnection);
t->init(res, TASK_DISCONNECT);
res->wrk->queue(t);
}
void RunJob::jobChanged(int)
{
char *p;
ui.levelCombo->setCurrentIndex(0);
ui.storageCombo->setCurrentIndex(0);
ui.filesetCombo->setCurrentIndex(0);
ui.clientCombo->setCurrentIndex(0);
ui.storageCombo->setCurrentIndex(0);
ui.poolCombo->setCurrentIndex(0);
ui.catalogCombo->setCurrentIndex(0);
p = ui.jobCombo->currentText().toUtf8().data();
if (p && *p) {
task *t = new task();
t->init(res, TASK_INFO);
pm_strcpy(info, p);
connect(t, SIGNAL(done(task *)), this, SLOT(jobInfo(task *)), Qt::QueuedConnection);
t->arg = info.c_str(); // Jobname
t->arg2 = NULL; // Level
res->wrk->queue(t);
}
}
void RunJob::levelChanged(int)
{
char *p;
p = ui.jobCombo->currentText().toUtf8().data();
if (p && *p) {
pm_strcpy(info, p);
p = ui.levelCombo->currentText().toUtf8().data();
if (p && *p) {
task *t = new task();
pm_strcpy(level, p);
connect(t, SIGNAL(done(task *)), this, SLOT(jobInfo(task *)), Qt::QueuedConnection);
t->init(res, TASK_INFO);
t->arg = info.c_str(); // Jobname
t->arg2 = level.c_str(); // Level
res->wrk->queue(t);
}
}
}
void RunJob::jobInfo(task *t)
{
char ed1[50];
res->mutex->lock();
if (res->infos.CorrNbJob == 0) {
ui.boxEstimate->setVisible(false);
} else {
QString t;
edit_uint64_with_suffix(res->infos.JobBytes, ed1);
strncat(ed1, "B", sizeof(ed1));
ui.labelJobBytes->setText(QString(ed1));
ui.labelJobFiles->setText(QString(edit_uint64_with_commas(res->infos.JobFiles, ed1)));
ui.labelJobLevel->setText(QString(job_level_to_str(res->infos.JobLevel)));
t = tr("Computed over %1 job%2, the correlation is %3/100.").arg(res->infos.CorrNbJob).arg(res->infos.CorrNbJob>1?"s":"").arg(res->infos.CorrJobBytes);
ui.labelJobBytes_2->setToolTip(t);
t = tr("Computed over %1 job%2, The correlation is %3/100.").arg(res->infos.CorrNbJob).arg(res->infos.CorrNbJob>1?"s":"").arg(res->infos.CorrJobFiles);
ui.labelJobFiles_2->setToolTip(t);
ui.boxEstimate->setVisible(true);
}
res->mutex->unlock();
t->deleteLater();
}
static void set_combo(QComboBox *dest, char *str)
{
if (str) {
int idx = dest->findText(QString(str), Qt::MatchExactly);
if (idx >= 0) {
dest->setCurrentIndex(idx);
}
}
}
void RunJob::fill_defaults(task *t)
{
if (t->status == true) {
res->mutex->lock();
set_combo(ui.levelCombo, res->defaults.level);
set_combo(ui.filesetCombo, res->defaults.fileset);
set_combo(ui.clientCombo, res->defaults.client);
set_combo(ui.storageCombo, res->defaults.storage);
set_combo(ui.poolCombo, res->defaults.pool);
set_combo(ui.catalogCombo, res->defaults.catalog);
res->mutex->unlock();
}
ui.tab2->setEnabled(true);
t->deleteLater();
}
RunJob::~RunJob()
{
Dmsg0(10, "~RunJob()\n");
if (tabAdvanced) {
delete tabAdvanced;
}
}
void TSched::init(const char *cmd_dir)
{
bool started = (timer >= 0);
if (started) {
stop();
}
bfree_and_null(command_dir);
command_dir = bstrdup(cmd_dir);
if (started) {
start();
}
}
TSched::TSched() {
timer = -1;
command_dir = NULL;
}
TSched::~TSched() {
if (timer >= 0) {
stop();
}
bfree_and_null(command_dir);
}
#include <dirent.h>
int breaddir(DIR *dirp, POOLMEM *&dname);
bool TSched::read_command_file(const char *file, alist *lst, btime_t mtime)
{
POOLMEM *line;
bool ret=false;
char *p;
TSchedJob *s;
Dmsg1(50, "open command file %s\n", file);
FILE *fp = fopen(file, "r");
if (!fp) {
return false;
}
line = get_pool_memory(PM_FNAME);
/* Get the first line, client/component:command */
while (bfgets(line, fp) != NULL) {
strip_trailing_junk(line);
Dmsg1(50, "%s\n", line);
if (line[0] == '#') {
continue;
}
if ((p = strchr(line, ':')) != NULL) {
*p=0;
s = new TSchedJob(line, p+1, mtime);
lst->append(s);
ret = true;
}
}
free_pool_memory(line);
fclose(fp);
return ret;
}
#include "lib/plugins.h"
#include "lib/cmd_parser.h"
void TSched::timerEvent(QTimerEvent *event)
{
Q_UNUSED(event)
POOL_MEM tmp, command;
TSchedJob *j;
alist lst(10, not_owned_by_alist);
arg_parser parser;
int i;
task *t;
RESMON *res;
scan_for_commands(&lst);
foreach_alist(j, (&lst)) {
if (parser.parse_cmd(j->command) == bRC_OK) {
if ((i = parser.find_arg_with_value("job")) > 0) {
QMessageBox msgbox;
foreach_res(res, R_CLIENT) {
if (strcmp(res->hdr.name, j->component) == 0) {
break;
}
}
if (!res) {
foreach_res(res, R_DIRECTOR) {
if (strcmp(res->hdr.name, j->component) == 0) {
break;
}
}
}
if (!res) {
msgbox.setIcon(QMessageBox::Information);
msgbox.setText(QString("Unable to find the component \"%1\" to run the job \"%2\".").arg(j->component, j->command));
msgbox.setStandardButtons(QMessageBox::Ignore);
} else {
msgbox.setIcon(QMessageBox::Information);
msgbox.setText(QString("The job \"%1\" will start automatically in few seconds...").arg(parser.argv[i]));
msgbox.setStandardButtons(QMessageBox::Ok | QMessageBox::Ignore);
msgbox.setDefaultButton(QMessageBox::Ok);
msgbox.button(QMessageBox::Ok)->animateClick(6000);
}
switch(msgbox.exec()) {
case QMessageBox::Ok:
Mmsg(command, "%s yes", j->command);
if (res->type == R_CLIENT) {
pm_strcat(command, " fdcalled=1");
}
// Build the command and run it!
t = new task();
t->init(res, TASK_RUN);
connect(t, SIGNAL(done(task *)), this, SLOT(jobStarted(task *)), Qt::QueuedConnection);
t->arg = command.c_str();
res->wrk->queue(t);
break;
case QMessageBox::Cancel:
case QMessageBox::Ignore:
break;
}
}
}
delete j;
}
}
void TSched::jobStarted(task *t)
{
Dmsg1(10, "-> jobid=%d\n", t->result.i);
t->deleteLater();
}
bool TSched::scan_for_commands(alist *commands)
{
int name_max, len;
DIR* dp = NULL;
POOL_MEM fname(PM_FNAME), fname2(PM_FNAME);
POOL_MEM dir_entry;
bool ret=false, found=false;
struct stat statp;
name_max = pathconf(".", _PC_NAME_MAX);
if (name_max < 1024) {
name_max = 1024;
}
if (!(dp = opendir(command_dir))) {
berrno be;
Dmsg2(0, "Failed to open directory %s: ERR=%s\n",
command_dir, be.bstrerror());
goto bail_out;
}
for ( ;; ) {
if (breaddir(dp, dir_entry.addr()) != 0) {
if (!found) {
goto bail_out;
}
break;
}
if (strcmp(dir_entry.c_str(), ".") == 0 ||
strcmp(dir_entry.c_str(), "..") == 0) {
continue;
}
len = strlen(dir_entry.c_str());
if (len <= 5) {
continue;
}
if (strcmp(dir_entry.c_str() + len - 5, ".bcmd") != 0) {
continue;
}
Mmsg(fname, "%s/%s", command_dir, dir_entry.c_str());
if (lstat(fname.c_str(), &statp) != 0 || !S_ISREG(statp.st_mode)) {
continue; /* ignore directories & special files */
}
if (read_command_file(fname.c_str(), commands, statp.st_mtime)) {
Mmsg(fname2, "%s.ok", fname.c_str());
unlink(fname2.c_str());
rename(fname.c_str(), fname2.c_str()); // TODO: We should probably unlink the file
}
}
bail_out:
if (dp) {
closedir(dp);
}
return ret;
}
| 28.631373
| 157
| 0.571566
|
tech-niche-biz
|
e58c9e92abb9149e44fdef1940720e0adde09a69
| 4,425
|
hpp
|
C++
|
ramus/patch/ips.hpp
|
qwertymodo/Mercurial-Magic
|
e5ce65510d12ac04e7ebea4ce11d200276baa141
|
[
"ISC"
] | 2
|
2019-01-20T13:05:10.000Z
|
2021-03-31T14:09:03.000Z
|
ramus/patch/ips.hpp
|
qwertymodo/Mercurial-Magic
|
e5ce65510d12ac04e7ebea4ce11d200276baa141
|
[
"ISC"
] | null | null | null |
ramus/patch/ips.hpp
|
qwertymodo/Mercurial-Magic
|
e5ce65510d12ac04e7ebea4ce11d200276baa141
|
[
"ISC"
] | 1
|
2018-10-12T02:47:57.000Z
|
2018-10-12T02:47:57.000Z
|
#pragma once
#include <nall/file.hpp>
#include <nall/filemap.hpp>
#include <nall/stdint.hpp>
#include <nall/string.hpp>
namespace ramus {
struct ipspatch {
inline auto modify(const uint8_t* data, uint size) -> bool;
inline auto source(const uint8_t* data, uint size) -> void;
inline auto target(uint8_t* data, uint size) -> void;
inline auto modify(const string& filename) -> bool;
inline auto source(const string& filename) -> bool;
inline auto target(const string& filename) -> bool;
inline auto size() const -> uint;
enum result : uint {
unknown,
success,
patch_too_small,
patch_invalid_header,
target_too_small,
};
inline auto apply() -> result;
protected:
filemap modifyFile;
const uint8_t* modifyData;
uint modifySize;
filemap sourceFile;
const uint8_t* sourceData;
uint sourceSize;
filemap targetFile;
uint8_t* targetData;
uint targetSize;
uint modifyTargetSize;
bool truncate;
};
auto ipspatch::modify(const uint8_t* data, uint size) -> bool {
if(size < 8) return false;
modifyData = data;
modifySize = size;
uint offset = 5;
auto read8 = [&]() -> uint8_t {
uint8_t data = modifyData[offset++];
return data;
};
auto read16 = [&]() -> uint16_t {
return read8() << 8 | read8();
};
auto read24 = [&]() -> uint32_t {
return read8() << 16 | read16();
};
uint blockAddr, blockSize, rleSize;
uint maxBlockAddr = 0;
modifyTargetSize = 0;
while(offset < modifySize) {
blockAddr = read24();
if(blockAddr == 0x454f46) break; //"EOF"
maxBlockAddr = max(maxBlockAddr, blockAddr);
blockSize = read16();
if(blockSize == 0) { //RLE
rleSize = read16();
modifyTargetSize = max(modifyTargetSize, blockAddr + rleSize);
offset++;
} else {
modifyTargetSize = max(modifyTargetSize, blockAddr + blockSize);
offset += blockSize;
}
}
if(size - offset != 0 && size - offset != 3) return false;
truncate = size - offset == 3;
if(truncate) modifyTargetSize = read24();
return true;
}
auto ipspatch::source(const uint8_t* data, uint size) -> void {
sourceData = data;
sourceSize = size;
if(!truncate) modifyTargetSize = max(modifyTargetSize, sourceSize);
}
auto ipspatch::target(uint8_t* data, uint size) -> void {
targetData = data;
targetSize = size;
}
auto ipspatch::modify(const string& filename) -> bool {
if(modifyFile.open(filename, filemap::mode::read) == false) return false;
return modify(modifyFile.data(), modifyFile.size());
}
auto ipspatch::source(const string& filename) -> bool {
if(sourceFile.open(filename, filemap::mode::read) == false) return false;
source(sourceFile.data(), sourceFile.size());
return true;
}
auto ipspatch::target(const string& filename) -> bool {
file fp;
if(fp.open(filename, file::mode::write) == false) return false;
fp.truncate(modifyTargetSize);
fp.close();
if(targetFile.open(filename, filemap::mode::readwrite) == false) return false;
target(targetFile.data(), targetFile.size());
return true;
}
auto ipspatch::size() const -> uint {
return modifyTargetSize;
}
auto ipspatch::apply() -> result {
if(modifySize < 8) return result::patch_too_small;
uint modifyOffset = 0, sourceRelativeOffset = 0, targetRelativeOffset = 0;
auto read8 = [&]() -> uint8_t {
uint8_t data = modifyData[modifyOffset++];
return data;
};
auto read16 = [&]() -> uint16_t {
return read8() << 8 | read8();
};
auto read24 = [&]() -> uint32_t {
return read8() << 16 | read16();
};
if(read8() != 'P') return result::patch_invalid_header;
if(read8() != 'A') return result::patch_invalid_header;
if(read8() != 'T') return result::patch_invalid_header;
if(read8() != 'C') return result::patch_invalid_header;
if(read8() != 'H') return result::patch_invalid_header;
if(modifyTargetSize > targetSize) return result::target_too_small;
memory::copy(targetData, sourceData, sourceSize);
uint blockAddr, blockSize, rleSize;
while(modifyOffset < modifySize) {
blockAddr = read24();
if(blockAddr == 0x454f46) break; //"EOF"
blockSize = read16();
if(blockSize == 0) { //RLE
rleSize = read16();
memory::fill(targetData + blockAddr, rleSize, read8());
} else {
memory::copy(targetData + blockAddr, modifyData + modifyOffset, blockSize);
modifyOffset += blockSize;
}
}
return result::success;
}
}
| 25.726744
| 81
| 0.660339
|
qwertymodo
|
e5916831f922f5efaa3a87ce01db382c07a90c38
| 2,472
|
hpp
|
C++
|
Assignments/P01/Menu.hpp
|
Landon-Brown1/2143-OOP-Brown
|
fded2b021b588bced3ba2a5c67e8e29694d42b2e
|
[
"MIT"
] | null | null | null |
Assignments/P01/Menu.hpp
|
Landon-Brown1/2143-OOP-Brown
|
fded2b021b588bced3ba2a5c67e8e29694d42b2e
|
[
"MIT"
] | null | null | null |
Assignments/P01/Menu.hpp
|
Landon-Brown1/2143-OOP-Brown
|
fded2b021b588bced3ba2a5c67e8e29694d42b2e
|
[
"MIT"
] | null | null | null |
/*
* AUTHOR: Landon Brown
* FILE TITLE: Menu.hpp
* FILE DESCRIPTION: Menu for the beginning of the game
* DUE DATE: TBD
* DATE CREATED: 03/26/2020
*/
#include <iostream>
#include <string>
using namespace std;
struct Menu{
Menu(){
}
void printIntro(){
cout << endl << " @@----------------------------------------------------@@ " << endl
<< " @@ Welcome to Pokemon: Brown Version! @@ " << endl
<< " @@ If you would like to play, please press 'y'. @@ " << endl
<< "(( ))" << endl
<< " @@ @@ " << endl
<< " @@ @@ " << endl
<< " @@----------------------------------------------------@@ " << endl;
}
void firstSelect(){
cout << endl << " @@----------------------------------------------------@@ " << endl
<< " @@ Player One, please select your Pokemon by typing @@ " << endl
<< " @@ The respective Pokedex number of each Pokemon @@ " << endl
<< "(( you would like in your party (up to 6). The first ))" << endl
<< " @@ Pokemon you choose will be the first in your @@ " << endl
<< " @@ lineup to be sent to battle! @@ " << endl
<< " @@----------------------------------------------------@@ " << endl;
}
void secondSelect(){
cout << endl << " @@----------------------------------------------------@@ " << endl
<< " @@ @@ " << endl
<< " @@ @@ " << endl
<< "(( ))" << endl
<< " @@ @@ " << endl
<< " @@ @@ " << endl
<< " @@----------------------------------------------------@@ " << endl;
}
};
| 51.5
| 101
| 0.222492
|
Landon-Brown1
|
e59532543eb5ced40994ebd6ca67ef20a52ec6f1
| 4,093
|
hpp
|
C++
|
include/mtao/geometry/prune_vertices.hpp
|
mtao/core
|
91f9bc6e852417989ed62675e2bb372e6afc7325
|
[
"MIT"
] | null | null | null |
include/mtao/geometry/prune_vertices.hpp
|
mtao/core
|
91f9bc6e852417989ed62675e2bb372e6afc7325
|
[
"MIT"
] | 4
|
2020-04-18T16:16:05.000Z
|
2020-04-18T16:17:36.000Z
|
include/mtao/geometry/prune_vertices.hpp
|
mtao/core
|
91f9bc6e852417989ed62675e2bb372e6afc7325
|
[
"MIT"
] | null | null | null |
#pragma once
#include "mtao/geometry/kdtree.hpp"
#include <map>
#include "mtao/iterator/enumerate.hpp"
#include "mtao/eigen/stl2eigen.hpp"
namespace mtao { namespace geometry {
//expects a mtao::vector<mtao::Vector<T,D>>
template <typename Container
, typename T
>
auto prune(const Container& V, T eps = T(1e-8)) -> std::tuple<Container, std::map<int,int>> {
using Vec = typename Container::value_type;
constexpr static int D = Vec::RowsAtCompileTime;
using Scalar = typename Vec::Scalar;
std::map<int,int> remap;
Container ret_vec;
if(eps == 0 && V.size() > 0) {
constexpr static bool static_size = D != Eigen::Dynamic;
using StlVec= std::conditional_t<static_size,std::array<Scalar,D>,std::vector<Scalar>>;
ret_vec.reserve(V.size());
int rows = V[0].rows();
std::map<StlVec,int> vmap;
StlVec tmp;
if constexpr(!static_size) {
tmp.resize(rows);
}
for(size_t i=0; i<V.size(); ++i) {
mtao::eigen::stl2eigen(tmp) = V[i];
if(auto it = vmap.find(tmp); it == vmap.end()) {
remap[i] = vmap.size();
vmap[tmp] = vmap.size();
} else {
remap[i] = it->second;
}
}
ret_vec.resize(vmap.size());
for(auto&& [v,i]: vmap) {
ret_vec[i] = mtao::eigen::stl2eigen(v);
}
} else {
KDTree<Scalar,D> tree;
tree.reserve(V.size());
std::map<size_t,size_t> remap;
for(size_t i=0; i<V.size(); ++i) {
remap[i] = tree.pruning_insertion(V[i],eps);
}
ret_vec = tree.points();
}
return std::make_tuple(ret_vec,remap);
}
template <typename DerivedV, typename DerivedF, typename T
>
auto prune_with_map(const Eigen::MatrixBase<DerivedV>& V, const Eigen::MatrixBase<DerivedF>& F, T eps = T(1e-8)) {
constexpr static int D = DerivedV::RowsAtCompileTime;
using Scalar = typename DerivedV::Scalar;
mtao::vector<typename mtao::Vector<Scalar,D>> stlV(V.cols());
for(int i = 0; i < V.cols(); ++i) {
stlV[i] = V.col(i);
}
auto pr = prune(stlV,eps);
//auto [P,m] = prune(stlV,eps);
const mtao::vector<typename mtao::Vector<Scalar,D>>& P = std::get<0>(pr);
const std::map<int,int>& m = std::get<1>(pr);
mtao::ColVectors<Scalar,D> RV(V.rows(),P.size());
for(int i = 0; i < RV.cols(); ++i) {
RV.col(i) = P[i];
}
using IndexType = typename DerivedF::Scalar;
auto RFp = F.unaryExpr([&](const IndexType& idx) -> IndexType {
return m.at(idx);
}).eval();
std::set<int> good_idx;
for(int i = 0; i < RFp.cols(); ++i) {
auto v = RFp.col(i);
std::set<IndexType> indx;
for(int j = 0; j < RFp.rows(); ++j) {
indx.insert(v(j));
}
if(indx.size() == RFp.rows()) {
good_idx.insert(i);
}
}
decltype(RFp) RF(RFp.rows(),good_idx.size());
for(auto&& [i,j]: iterator::enumerate(good_idx) ){
RF.col(i) = RFp.col(j);
}
return std::make_tuple(RV,RF,m);
}
template <typename DerivedV, typename DerivedF
,typename T = typename DerivedV::Scalar>
auto prune(const Eigen::MatrixBase<DerivedV>& V, const Eigen::MatrixBase<DerivedF>& F, T eps = T(1e-8)) {
auto [RV,RF,m] = prune_with_map(V,F,eps);
return std::make_tuple(RV,RF);
}
}}
| 38.252336
| 122
| 0.469094
|
mtao
|
e59611b4bc72740b511887ce25eecfd36758d720
| 439
|
hpp
|
C++
|
security/include/InvalidKeyException.hpp
|
wangsun1983/Obotcha
|
2464e53599305703f5150df72bf73579a39d8ef4
|
[
"MIT"
] | 27
|
2019-04-27T00:51:22.000Z
|
2022-03-30T04:05:44.000Z
|
security/include/InvalidKeyException.hpp
|
wangsun1983/Obotcha
|
2464e53599305703f5150df72bf73579a39d8ef4
|
[
"MIT"
] | 9
|
2020-05-03T12:17:50.000Z
|
2021-10-15T02:18:47.000Z
|
security/include/InvalidKeyException.hpp
|
wangsun1983/Obotcha
|
2464e53599305703f5150df72bf73579a39d8ef4
|
[
"MIT"
] | 1
|
2019-04-16T01:45:36.000Z
|
2019-04-16T01:45:36.000Z
|
#ifndef __OBOTCHA_INVALID_KEY_EXCEPTION_HPP__
#define __OBOTCHA_INVALID_KEY_EXCEPTION_HPP__
#include <fstream>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "Object.hpp"
#include "Exception.hpp"
#include "String.hpp"
namespace obotcha {
DECLARE_EXCEPTION(InvalidKeyException){
public:
InvalidKeyException(const char *str):Exception(str){}
InvalidKeyException(String str):Exception(str){}
};
}
#endif
| 17.56
| 55
| 0.779043
|
wangsun1983
|
e59d226aad84cfaaabe3b77e6cc3312910d3b4bd
| 45,566
|
cpp
|
C++
|
libBKPLPlot/plbuf.cpp
|
rsuchecki/biokanga
|
ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e
|
[
"MIT"
] | null | null | null |
libBKPLPlot/plbuf.cpp
|
rsuchecki/biokanga
|
ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e
|
[
"MIT"
] | null | null | null |
libBKPLPlot/plbuf.cpp
|
rsuchecki/biokanga
|
ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e
|
[
"MIT"
] | null | null | null |
// $Id: plbuf.c 12636 2013-10-26 20:47:49Z airwin $
//
// Handle plot buffer.
//
// Copyright (C) 1992 Maurice LeBrun
// Copyright (C) 2004 Alan W. Irwin
// Copyright (C) 2005 Thomas J. Duck
// Copyright (C) 2006 Jim Dishaw
//
// This file is part of PLplot.
//
// PLplot is free software; you can redistribute it and/or modify
// it under the terms of the GNU Library General Public License as published
// by the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// PLplot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public License
// along with PLplot; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#include "stdafx.h"
#define NEED_PLDEBUG
#include "plplotP.h"
#include "drivers.h"
#include "metadefs.h"
#include <string.h>
typedef unsigned char U_CHAR;
// Function prototypes
void * plbuf_save( PLStream *pls, void *state );
static int rd_command( PLStream *pls, U_CHAR *p_c );
static void rd_data( PLStream *pls, void *buf, size_t buf_size );
static void wr_command( PLStream *pls, U_CHAR c );
static void wr_data( PLStream *pls, void *buf, size_t buf_size );
static void plbuf_control( PLStream *pls, U_CHAR c );
static void rdbuf_init( PLStream *pls );
static void rdbuf_line( PLStream *pls );
static void rdbuf_polyline( PLStream *pls );
static void rdbuf_eop( PLStream *pls );
static void rdbuf_bop( PLStream *pls );
static void rdbuf_state( PLStream *pls );
static void rdbuf_esc( PLStream *pls );
static void plbuf_fill( PLStream *pls );
static void rdbuf_fill( PLStream *pls );
static void plbuf_swin( PLStream *pls, PLWindow *plwin );
static void rdbuf_swin( PLStream *pls );
//--------------------------------------------------------------------------
// plbuf_init()
//
// Initialize device.
// Actually just disables writes if plot buffer is already open (occurs
// when one stream is cloned, as in printing).
//--------------------------------------------------------------------------
void
plbuf_init( PLStream *pls )
{
dbug_enter( "plbuf_init" );
pls->plbuf_read = FALSE;
#ifdef BUFFERED_FILE
if ( pls->plbufFile != NULL )
pls->plbuf_write = FALSE;
#else
if ( pls->plbuf_buffer != NULL )
pls->plbuf_write = FALSE;
#endif
}
//--------------------------------------------------------------------------
// plbuf_line()
//
// Draw a line in the current color from (x1,y1) to (x2,y2).
//--------------------------------------------------------------------------
void
plbuf_line( PLStream *pls, short x1a, short y1a, short x2a, short y2a )
{
short xpl[2], ypl[2];
dbug_enter( "plbuf_line" );
wr_command( pls, (U_CHAR) LINE );
xpl[0] = x1a;
xpl[1] = x2a;
ypl[0] = y1a;
ypl[1] = y2a;
wr_data( pls, xpl, sizeof ( short ) * 2 );
wr_data( pls, ypl, sizeof ( short ) * 2 );
}
//--------------------------------------------------------------------------
// plbuf_polyline()
//
// Draw a polyline in the current color.
//--------------------------------------------------------------------------
void
plbuf_polyline( PLStream *pls, short *xa, short *ya, PLINT npts )
{
dbug_enter( "plbuf_polyline" );
wr_command( pls, (U_CHAR) POLYLINE );
wr_data( pls, &npts, sizeof ( PLINT ) );
wr_data( pls, xa, sizeof ( short ) * (size_t) npts );
wr_data( pls, ya, sizeof ( short ) * (size_t) npts );
}
//--------------------------------------------------------------------------
// plbuf_eop()
//
// End of page.
//--------------------------------------------------------------------------
void
plbuf_eop( PLStream * PL_UNUSED( pls ) )
{
dbug_enter( "plbuf_eop" );
}
//--------------------------------------------------------------------------
// plbuf_bop()
//
// Set up for the next page.
// To avoid problems redisplaying partially filled pages, on each BOP the
// old file is thrown away and a new one is obtained. This way we can just
// read up to EOF to get everything on the current page.
//
// Also write state information to ensure the next page is correct.
//--------------------------------------------------------------------------
void
plbuf_bop( PLStream *pls )
{
dbug_enter( "plbuf_bop" );
plbuf_tidy( pls );
#ifdef BUFFERED_FILE
pls->plbufFile = pl_create_tempfile( NULL );
if ( pls->plbufFile == NULL )
plexit( "plbuf_bop: Error opening plot data storage file." );
#else
// Need a better place to initialize this value
pls->plbuf_buffer_grow = 128 * 1024;
if ( pls->plbuf_buffer == NULL )
{
// We have not allocated a buffer, so do it now
if ( ( pls->plbuf_buffer = malloc( pls->plbuf_buffer_grow ) ) == NULL )
plexit( "plbuf_bop: Error allocating plot buffer." );
pls->plbuf_buffer_size = pls->plbuf_buffer_grow;
pls->plbuf_top = 0;
pls->plbuf_readpos = 0;
}
else
{
// Buffer is allocated, move the top to the beginning
pls->plbuf_top = 0;
}
#endif
wr_command( pls, (U_CHAR) BOP );
plbuf_state( pls, PLSTATE_COLOR0 );
plbuf_state( pls, PLSTATE_WIDTH );
}
//--------------------------------------------------------------------------
// plbuf_tidy()
//
// Close graphics file
//--------------------------------------------------------------------------
void
plbuf_tidy( PLStream * PL_UNUSED( pls ) )
{
dbug_enter( "plbuf_tidy" );
#ifdef BUFFERED_FILE
if ( pls->plbufFile == NULL )
return;
fclose( pls->plbufFile )
pls->plbufFile = NULL;
#endif
}
//--------------------------------------------------------------------------
// plbuf_state()
//
// Handle change in PLStream state (color, pen width, fill attribute, etc).
//--------------------------------------------------------------------------
void
plbuf_state( PLStream *pls, PLINT op )
{
dbug_enter( "plbuf_state" );
wr_command( pls, (U_CHAR) CHANGE_STATE );
wr_command( pls, (U_CHAR) op );
switch ( op )
{
case PLSTATE_WIDTH:
wr_data( pls, &( pls->width ), sizeof ( pls->width ) );
break;
case PLSTATE_COLOR0:
wr_data( pls, &( pls->icol0 ), sizeof ( pls->icol0 ) );
if ( pls->icol0 == PL_RGB_COLOR )
{
wr_data( pls, &( pls->curcolor.r ), sizeof ( pls->curcolor.r ) );
wr_data( pls, &( pls->curcolor.g ), sizeof ( pls->curcolor.g ) );
wr_data( pls, &( pls->curcolor.b ), sizeof ( pls->curcolor.b ) );
}
break;
case PLSTATE_COLOR1:
wr_data( pls, &( pls->icol1 ), sizeof ( pls->icol1 ) );
break;
case PLSTATE_FILL:
wr_data( pls, &( pls->patt ), sizeof ( pls->patt ) );
break;
}
}
//--------------------------------------------------------------------------
// plbuf_image()
//
// write image described in points pls->dev_x[], pls->dev_y[], pls->dev_z[].
// pls->nptsX, pls->nptsY.
//--------------------------------------------------------------------------
static void
plbuf_image( PLStream *pls, IMG_DT *img_dt )
{
PLINT npts = pls->dev_nptsX * pls->dev_nptsY;
dbug_enter( "plbuf_image" );
wr_data( pls, &pls->dev_nptsX, sizeof ( PLINT ) );
wr_data( pls, &pls->dev_nptsY, sizeof ( PLINT ) );
wr_data( pls, &img_dt->xmin, sizeof ( PLFLT ) );
wr_data( pls, &img_dt->ymin, sizeof ( PLFLT ) );
wr_data( pls, &img_dt->dx, sizeof ( PLFLT ) );
wr_data( pls, &img_dt->dy, sizeof ( PLFLT ) );
wr_data( pls, &pls->dev_zmin, sizeof ( short ) );
wr_data( pls, &pls->dev_zmax, sizeof ( short ) );
wr_data( pls, pls->dev_ix, sizeof ( short ) * (size_t) npts );
wr_data( pls, pls->dev_iy, sizeof ( short ) * (size_t) npts );
wr_data( pls, pls->dev_z, sizeof ( unsigned short ) * (size_t) ( ( pls->dev_nptsX - 1 ) * ( pls->dev_nptsY - 1 ) ) );
}
//--------------------------------------------------------------------------
// plbuf_text()
//
// Handle text call.
//--------------------------------------------------------------------------
static void
plbuf_text( PLStream *pls, EscText *text )
{
PLUNICODE fci;
dbug_enter( "plbuf_text" );
// Retrieve the font characterization integer
plgfci( &fci );
// Write the text information
wr_data( pls, &fci, sizeof ( PLUNICODE ) );
wr_data( pls, &pls->chrht, sizeof ( PLFLT ) );
wr_data( pls, &pls->diorot, sizeof ( PLFLT ) );
wr_data( pls, &pls->clpxmi, sizeof ( PLFLT ) );
wr_data( pls, &pls->clpxma, sizeof ( PLFLT ) );
wr_data( pls, &pls->clpymi, sizeof ( PLFLT ) );
wr_data( pls, &pls->clpyma, sizeof ( PLFLT ) );
wr_data( pls, &text->base, sizeof ( PLINT ) );
wr_data( pls, &text->just, sizeof ( PLFLT ) );
wr_data( pls, text->xform, sizeof ( PLFLT ) * 4 );
wr_data( pls, &text->x, sizeof ( PLINT ) );
wr_data( pls, &text->y, sizeof ( PLINT ) );
wr_data( pls, &text->refx, sizeof ( PLINT ) );
wr_data( pls, &text->refy, sizeof ( PLINT ) );
wr_data( pls, &text->unicode_array_len, sizeof ( PLINT ) );
if ( text->unicode_array_len )
wr_data( pls, text->unicode_array, sizeof ( PLUNICODE ) * text->unicode_array_len );
}
//--------------------------------------------------------------------------
// plbuf_text_unicode()
//
// Handle text buffering for the new unicode pathway.
//--------------------------------------------------------------------------
static void
plbuf_text_unicode( PLStream *pls, EscText *text )
{
PLUNICODE fci;
dbug_enter( "plbuf_text" );
// Retrieve the font characterization integer
plgfci( &fci );
// Write the text information
wr_data( pls, &fci, sizeof ( PLUNICODE ) );
wr_data( pls, &pls->chrht, sizeof ( PLFLT ) );
wr_data( pls, &pls->diorot, sizeof ( PLFLT ) );
wr_data( pls, &pls->clpxmi, sizeof ( PLFLT ) );
wr_data( pls, &pls->clpxma, sizeof ( PLFLT ) );
wr_data( pls, &pls->clpymi, sizeof ( PLFLT ) );
wr_data( pls, &pls->clpyma, sizeof ( PLFLT ) );
wr_data( pls, &text->base, sizeof ( PLINT ) );
wr_data( pls, &text->just, sizeof ( PLFLT ) );
wr_data( pls, text->xform, sizeof ( PLFLT ) * 4 );
wr_data( pls, &text->x, sizeof ( PLINT ) );
wr_data( pls, &text->y, sizeof ( PLINT ) );
wr_data( pls, &text->refx, sizeof ( PLINT ) );
wr_data( pls, &text->refy, sizeof ( PLINT ) );
wr_data( pls, &text->n_fci, sizeof ( PLUNICODE ) );
wr_data( pls, &text->n_char, sizeof ( PLUNICODE ) );
wr_data( pls, &text->n_ctrl_char, sizeof ( PLINT ) );
wr_data( pls, &text->unicode_array_len, sizeof ( PLINT ) );
}
//--------------------------------------------------------------------------
// plbuf_esc()
//
// Escape function. Note that any data written must be in device
// independent form to maintain the transportability of the metafile.
//
// Functions:
//
// PLESC_FILL Fill polygon
// PLESC_SWIN Set plot window parameters
// PLESC_IMAGE Draw image
// PLESC_HAS_TEXT Draw PostScript text
// PLESC_CLEAR Clear Background
// PLESC_START_RASTERIZE
// PLESC_END_RASTERIZE Start and stop rasterization
//--------------------------------------------------------------------------
void
plbuf_esc( PLStream *pls, PLINT op, void *ptr )
{
dbug_enter( "plbuf_esc" );
wr_command( pls, (U_CHAR) ESCAPE );
wr_command( pls, (U_CHAR) op );
switch ( op )
{
case PLESC_FILL:
plbuf_fill( pls );
break;
case PLESC_SWIN:
plbuf_swin( pls, (PLWindow *) ptr );
break;
case PLESC_IMAGE:
plbuf_image( pls, (IMG_DT *) ptr );
break;
case PLESC_HAS_TEXT:
if ( ptr != NULL ) // Check required by GCW driver, please don't remove
plbuf_text( pls, (EscText *) ptr );
break;
case PLESC_BEGIN_TEXT:
case PLESC_TEXT_CHAR:
case PLESC_CONTROL_CHAR:
case PLESC_END_TEXT:
plbuf_text_unicode( pls, (EscText *) ptr );
break;
#if 0
// These are a no-op. They just need an entry in the buffer.
case PLESC_CLEAR:
case PLESC_START_RASTERIZE:
case PLESC_END_RASTERIZE:
break;
#endif
}
}
//--------------------------------------------------------------------------
// plbuf_fill()
//
// Fill polygon described in points pls->dev_x[] and pls->dev_y[].
//--------------------------------------------------------------------------
static void
plbuf_fill( PLStream *pls )
{
dbug_enter( "plbuf_fill" );
wr_data( pls, &pls->dev_npts, sizeof ( PLINT ) );
wr_data( pls, pls->dev_x, sizeof ( short ) * (size_t) pls->dev_npts );
wr_data( pls, pls->dev_y, sizeof ( short ) * (size_t) pls->dev_npts );
}
//--------------------------------------------------------------------------
// plbuf_swin()
//
// Set up plot window parameters.
//--------------------------------------------------------------------------
static void
plbuf_swin( PLStream *pls, PLWindow *plwin )
{
wr_data( pls, &plwin->dxmi, sizeof ( PLFLT ) );
wr_data( pls, &plwin->dxma, sizeof ( PLFLT ) );
wr_data( pls, &plwin->dymi, sizeof ( PLFLT ) );
wr_data( pls, &plwin->dyma, sizeof ( PLFLT ) );
wr_data( pls, &plwin->wxmi, sizeof ( PLFLT ) );
wr_data( pls, &plwin->wxma, sizeof ( PLFLT ) );
wr_data( pls, &plwin->wymi, sizeof ( PLFLT ) );
wr_data( pls, &plwin->wyma, sizeof ( PLFLT ) );
}
//--------------------------------------------------------------------------
// Routines to read from & process the plot buffer.
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// rdbuf_init()
//
// Initialize device.
//--------------------------------------------------------------------------
static void
rdbuf_init( PLStream * PL_UNUSED( pls ) )
{
dbug_enter( "rdbuf_init" );
}
//--------------------------------------------------------------------------
// rdbuf_line()
//
// Draw a line in the current color from (x1,y1) to (x2,y2).
//--------------------------------------------------------------------------
static void
rdbuf_line( PLStream *pls )
{
short xpl[2], ypl[2];
PLINT npts = 2;
dbug_enter( "rdbuf_line" );
rd_data( pls, xpl, sizeof ( short ) * (size_t) npts );
rd_data( pls, ypl, sizeof ( short ) * (size_t) npts );
plP_line( xpl, ypl );
}
//--------------------------------------------------------------------------
// rdbuf_polyline()
//
// Draw a polyline in the current color.
//--------------------------------------------------------------------------
static void
rdbuf_polyline( PLStream *pls )
{
short _xpl[PL_MAXPOLY], _ypl[PL_MAXPOLY];
short *xpl, *ypl;
PLINT npts;
dbug_enter( "rdbuf_polyline" );
rd_data( pls, &npts, sizeof ( PLINT ) );
if ( npts > PL_MAXPOLY )
{
xpl = (short *) malloc( (size_t) ( npts + 1 ) * sizeof ( short ) );
ypl = (short *) malloc( (size_t) ( npts + 1 ) * sizeof ( short ) );
if ( ( xpl == NULL ) || ( ypl == NULL ) )
{
plexit( "rdbuf_polyline: Insufficient memory for large polyline" );
}
}
else
{
xpl = _xpl;
ypl = _ypl;
}
rd_data( pls, xpl, sizeof ( short ) * (size_t) npts );
rd_data( pls, ypl, sizeof ( short ) * (size_t) npts );
plP_polyline( xpl, ypl, npts );
if ( npts > PL_MAXPOLY )
{
free( xpl );
free( ypl );
}
}
//--------------------------------------------------------------------------
// rdbuf_eop()
//
// End of page.
//--------------------------------------------------------------------------
static void
rdbuf_eop( PLStream * PL_UNUSED( pls ) )
{
dbug_enter( "rdbuf_eop" );
}
//--------------------------------------------------------------------------
// rdbuf_bop()
//
// Set up for the next page.
//--------------------------------------------------------------------------
static void
rdbuf_bop( PLStream *pls )
{
dbug_enter( "rdbuf_bop" );
pls->nplwin = 0;
}
//--------------------------------------------------------------------------
// rdbuf_state()
//
// Handle change in PLStream state (color, pen width, fill attribute, etc).
//--------------------------------------------------------------------------
static void
rdbuf_state( PLStream *pls )
{
U_CHAR op;
dbug_enter( "rdbuf_state" );
rd_data( pls, &op, sizeof ( U_CHAR ) );
switch ( op )
{
case PLSTATE_WIDTH: {
U_CHAR width;
rd_data( pls, &width, sizeof ( U_CHAR ) );
pls->width = width;
plP_state( PLSTATE_WIDTH );
break;
}
case PLSTATE_COLOR0: {
short icol0;
U_CHAR r, g, b;
PLFLT a;
rd_data( pls, &icol0, sizeof ( short ) );
if ( icol0 == PL_RGB_COLOR )
{
rd_data( pls, &r, sizeof ( U_CHAR ) );
rd_data( pls, &g, sizeof ( U_CHAR ) );
rd_data( pls, &b, sizeof ( U_CHAR ) );
a = 1.0;
}
else
{
if ( (int) icol0 >= pls->ncol0 )
{
char buffer[256];
snprintf( buffer, 256, "rdbuf_state: Invalid color map entry: %d", (int) icol0 );
plabort( buffer );
return;
}
r = pls->cmap0[icol0].r;
g = pls->cmap0[icol0].g;
b = pls->cmap0[icol0].b;
a = pls->cmap0[icol0].a;
}
pls->icol0 = icol0;
pls->curcolor.r = r;
pls->curcolor.g = g;
pls->curcolor.b = b;
pls->curcolor.a = a;
plP_state( PLSTATE_COLOR0 );
break;
}
case PLSTATE_COLOR1: {
short icol1;
rd_data( pls, &icol1, sizeof ( short ) );
pls->icol1 = icol1;
pls->curcolor.r = pls->cmap1[icol1].r;
pls->curcolor.g = pls->cmap1[icol1].g;
pls->curcolor.b = pls->cmap1[icol1].b;
pls->curcolor.a = pls->cmap1[icol1].a;
plP_state( PLSTATE_COLOR1 );
break;
}
case PLSTATE_FILL: {
signed char patt;
rd_data( pls, &patt, sizeof ( signed char ) );
pls->patt = patt;
plP_state( PLSTATE_FILL );
break;
}
}
}
//--------------------------------------------------------------------------
// rdbuf_esc()
//
// Escape function.
// Must fill data structure with whatever data that was written,
// then call escape function.
//
// Note: it is best to only call the escape function for op-codes that
// are known to be supported.
//
// Functions:
//
// PLESC_FILL Fill polygon
// PLESC_SWIN Set plot window parameters
// PLESC_IMAGE Draw image
// PLESC_HAS_TEXT Draw PostScript text
// PLESC_BEGIN_TEXT Commands for the alternative unicode text handling path
// PLESC_TEXT_CHAR
// PLESC_CONTROL_CHAR
// PLESC_END_TEXT
// PLESC_CLEAR Clear Background
//--------------------------------------------------------------------------
static void
rdbuf_image( PLStream *pls );
static void
rdbuf_text( PLStream *pls );
static void
rdbuf_text_unicode( PLINT op, PLStream *pls );
static void
rdbuf_esc( PLStream *pls )
{
U_CHAR op;
dbug_enter( "rdbuf_esc" );
rd_data( pls, &op, sizeof ( U_CHAR ) );
switch ( op )
{
case PLESC_FILL:
rdbuf_fill( pls );
break;
case PLESC_SWIN:
rdbuf_swin( pls );
break;
case PLESC_IMAGE:
rdbuf_image( pls );
break;
case PLESC_HAS_TEXT:
rdbuf_text( pls );
break;
case PLESC_BEGIN_TEXT:
case PLESC_TEXT_CHAR:
case PLESC_CONTROL_CHAR:
case PLESC_END_TEXT:
rdbuf_text_unicode( op, pls );
break;
case PLESC_CLEAR:
plP_esc( PLESC_CLEAR, NULL );
break;
case PLESC_START_RASTERIZE:
plP_esc( PLESC_START_RASTERIZE, NULL );
break;
case PLESC_END_RASTERIZE:
plP_esc( PLESC_END_RASTERIZE, NULL );
break;
}
}
//--------------------------------------------------------------------------
// rdbuf_fill()
//
// Fill polygon described by input points.
//--------------------------------------------------------------------------
static void
rdbuf_fill( PLStream *pls )
{
short _xpl[PL_MAXPOLY], _ypl[PL_MAXPOLY];
short *xpl, *ypl;
PLINT npts;
dbug_enter( "rdbuf_fill" );
rd_data( pls, &npts, sizeof ( PLINT ) );
if ( npts > PL_MAXPOLY )
{
xpl = (short *) malloc( (size_t) ( npts + 1 ) * sizeof ( short ) );
ypl = (short *) malloc( (size_t) ( npts + 1 ) * sizeof ( short ) );
if ( ( xpl == NULL ) || ( ypl == NULL ) )
{
plexit( "rdbuf_polyline: Insufficient memory for large polyline" );
}
}
else
{
xpl = _xpl;
ypl = _ypl;
}
rd_data( pls, xpl, sizeof ( short ) * (size_t) npts );
rd_data( pls, ypl, sizeof ( short ) * (size_t) npts );
plP_fill( xpl, ypl, npts );
if ( npts > PL_MAXPOLY )
{
free( xpl );
free( ypl );
}
}
//--------------------------------------------------------------------------
// rdbuf_image()
//
// .
//--------------------------------------------------------------------------
static void
rdbuf_image( PLStream *pls )
{
// Unnecessarily initialize dev_iy and dev_z to quiet -O1
// -Wuninitialized warnings which are false alarms. (If something
// goes wrong with the dev_ix malloc below any further use of
// dev_iy and dev_z does not occur. Similarly, if something goes
// wrong with the dev_iy malloc below any further use of dev_z
// does not occur.)
short *dev_ix, *dev_iy = NULL;
unsigned short *dev_z = NULL, dev_zmin, dev_zmax;
PLINT nptsX, nptsY, npts;
PLFLT xmin, ymin, dx, dy;
dbug_enter( "rdbuf_image" );
rd_data( pls, &nptsX, sizeof ( PLINT ) );
rd_data( pls, &nptsY, sizeof ( PLINT ) );
npts = nptsX * nptsY;
rd_data( pls, &xmin, sizeof ( PLFLT ) );
rd_data( pls, &ymin, sizeof ( PLFLT ) );
rd_data( pls, &dx, sizeof ( PLFLT ) );
rd_data( pls, &dy, sizeof ( PLFLT ) );
rd_data( pls, &dev_zmin, sizeof ( short ) );
rd_data( pls, &dev_zmax, sizeof ( short ) );
// NOTE: Even though for memory buffered version all the data is in memory,
// we still allocate and copy the data because I think that method works
// better in a multithreaded environment. I could be wrong.
//
if ( ( ( dev_ix = (short *) malloc( (size_t) npts * sizeof ( short ) ) ) == NULL ) ||
( ( dev_iy = (short *) malloc( (size_t) npts * sizeof ( short ) ) ) == NULL ) ||
( ( dev_z = (unsigned short *) malloc( (size_t) ( ( nptsX - 1 ) * ( nptsY - 1 ) ) * sizeof ( unsigned short ) ) ) == NULL ) )
plexit( "rdbuf_image: Insufficient memory" );
rd_data( pls, dev_ix, sizeof ( short ) * (size_t) npts );
rd_data( pls, dev_iy, sizeof ( short ) * (size_t) npts );
rd_data( pls, dev_z, sizeof ( unsigned short ) * (size_t) ( ( nptsX - 1 ) * ( nptsY - 1 ) ) );
//
// COMMENTED OUT by Hezekiah Carty
// Commented (hopefullly temporarily) until the dev_fastimg rendering
// path can be updated to support the new plimage internals. In the
// meantime this function is not actually used so the issue of how to
// update the code to support the new interface can be ignored.
//
//plP_image(dev_ix, dev_iy, dev_z, nptsX, nptsY, xmin, ymin, dx, dy, dev_zmin, dev_zmax);
free( dev_ix );
free( dev_iy );
free( dev_z );
}
//--------------------------------------------------------------------------
// rdbuf_swin()
//
// Set up plot window parameters.
//--------------------------------------------------------------------------
static void
rdbuf_swin( PLStream *pls )
{
PLWindow plwin;
rd_data( pls, &plwin.dxmi, sizeof ( PLFLT ) );
rd_data( pls, &plwin.dxma, sizeof ( PLFLT ) );
rd_data( pls, &plwin.dymi, sizeof ( PLFLT ) );
rd_data( pls, &plwin.dyma, sizeof ( PLFLT ) );
rd_data( pls, &plwin.wxmi, sizeof ( PLFLT ) );
rd_data( pls, &plwin.wxma, sizeof ( PLFLT ) );
rd_data( pls, &plwin.wymi, sizeof ( PLFLT ) );
rd_data( pls, &plwin.wyma, sizeof ( PLFLT ) );
plP_swin( &plwin );
}
//--------------------------------------------------------------------------
// rdbuf_text()
//
// Draw PostScript text.
//--------------------------------------------------------------------------
static void
rdbuf_text( PLStream *pls )
{
PLUNICODE( fci );
EscText text;
PLFLT xform[4];
PLUNICODE* unicode;
text.xform = xform;
// Read in the data
rd_data( pls, &fci, sizeof ( PLUNICODE ) );
rd_data( pls, &pls->chrht, sizeof ( PLFLT ) );
rd_data( pls, &pls->diorot, sizeof ( PLFLT ) );
rd_data( pls, &pls->clpxmi, sizeof ( PLFLT ) );
rd_data( pls, &pls->clpxma, sizeof ( PLFLT ) );
rd_data( pls, &pls->clpymi, sizeof ( PLFLT ) );
rd_data( pls, &pls->clpyma, sizeof ( PLFLT ) );
rd_data( pls, &text.base, sizeof ( PLINT ) );
rd_data( pls, &text.just, sizeof ( PLFLT ) );
rd_data( pls, text.xform, sizeof ( PLFLT ) * 4 );
rd_data( pls, &text.x, sizeof ( PLINT ) );
rd_data( pls, &text.y, sizeof ( PLINT ) );
rd_data( pls, &text.refx, sizeof ( PLINT ) );
rd_data( pls, &text.refy, sizeof ( PLINT ) );
rd_data( pls, &text.unicode_array_len, sizeof ( PLINT ) );
if ( text.unicode_array_len )
{
if ( ( unicode = (PLUNICODE *) malloc( text.unicode_array_len * sizeof ( PLUNICODE ) ) )
== NULL )
plexit( "rdbuf_text: Insufficient memory" );
rd_data( pls, unicode, sizeof ( PLUNICODE ) * text.unicode_array_len );
text.unicode_array = unicode;
}
else
text.unicode_array = NULL;
// Make the call for unicode devices
if ( pls->dev_unicode )
{
plsfci( fci );
plP_esc( PLESC_HAS_TEXT, &text );
}
}
//--------------------------------------------------------------------------
// rdbuf_text_unicode()
//
// Draw text for the new unicode handling pathway.
//--------------------------------------------------------------------------
static void
rdbuf_text_unicode( PLINT op, PLStream *pls )
{
PLUNICODE( fci );
EscText text;
PLFLT xform[4];
text.xform = xform;
// Read in the data
rd_data( pls, &fci, sizeof ( PLUNICODE ) );
rd_data( pls, &pls->chrht, sizeof ( PLFLT ) );
rd_data( pls, &pls->diorot, sizeof ( PLFLT ) );
rd_data( pls, &pls->clpxmi, sizeof ( PLFLT ) );
rd_data( pls, &pls->clpxma, sizeof ( PLFLT ) );
rd_data( pls, &pls->clpymi, sizeof ( PLFLT ) );
rd_data( pls, &pls->clpyma, sizeof ( PLFLT ) );
rd_data( pls, &text.base, sizeof ( PLINT ) );
rd_data( pls, &text.just, sizeof ( PLFLT ) );
rd_data( pls, text.xform, sizeof ( PLFLT ) * 4 );
rd_data( pls, &text.x, sizeof ( PLINT ) );
rd_data( pls, &text.y, sizeof ( PLINT ) );
rd_data( pls, &text.refx, sizeof ( PLINT ) );
rd_data( pls, &text.refy, sizeof ( PLINT ) );
rd_data( pls, &text.n_fci, sizeof ( PLUNICODE ) );
rd_data( pls, &text.n_char, sizeof ( PLUNICODE ) );
rd_data( pls, &text.n_ctrl_char, sizeof ( PLINT ) );
rd_data( pls, &text.unicode_array_len, sizeof ( PLINT ) );
if ( pls->dev_unicode )
{
plsfci( fci );
plP_esc( op, &text );
}
}
//--------------------------------------------------------------------------
// plRemakePlot()
//
// Rebuilds plot from plot buffer, usually in response to a window
// resize or exposure event.
//--------------------------------------------------------------------------
void
plRemakePlot( PLStream *pls )
{
U_CHAR c;
int plbuf_status;
PLStream *save_pls;
dbug_enter( "plRemakePlot" );
// Change the status of the flags before checking for a buffer.
// Actually, more thought is needed if we want to support multithreaded
// code correctly, specifically the case where two threads are using
// the same plot stream (e.g. one thread is drawing the plot and another
// thread is processing window manager messages).
//
plbuf_status = pls->plbuf_write;
pls->plbuf_write = FALSE;
pls->plbuf_read = TRUE;
#ifdef BUFFERED_FILE
if ( pls->plbufFile )
{
rewind( pls->plbufFile );
#else
if ( pls->plbuf_buffer )
{
pls->plbuf_readpos = 0;
#endif
// Need to change where m_plsc points to before processing the commands.
// If we have multiple plot streams, this will prevent the commands from
// going to the wrong plot stream.
//
save_pls = m_plsc;
m_plsc = pls;
while ( rd_command( pls, &c ) )
{
plbuf_control( pls, c );
}
m_plsc = save_pls;
}
pls->plbuf_read = FALSE;
pls->plbuf_write = plbuf_status;
}
//--------------------------------------------------------------------------
// plbuf_control()
//
// Processes commands read from the plot buffer.
//--------------------------------------------------------------------------
static void
plbuf_control( PLStream *pls, U_CHAR c )
{
static U_CHAR c_old = 0;
dbug_enter( "plbuf_control" );
switch ( (int) c )
{
case INITIALIZE:
rdbuf_init( pls );
break;
case EOP:
rdbuf_eop( pls );
break;
case BOP:
rdbuf_bop( pls );
break;
case CHANGE_STATE:
rdbuf_state( pls );
break;
case LINE:
rdbuf_line( pls );
break;
case POLYLINE:
rdbuf_polyline( pls );
break;
case ESCAPE:
rdbuf_esc( pls );
break;
default:
pldebug( "plbuf_control", "Unrecognized command %d, previous %d\n", c, c_old );
}
c_old = c;
}
//--------------------------------------------------------------------------
// rd_command()
//
// Read & return the next command
//--------------------------------------------------------------------------
static int
rd_command( PLStream *pls, U_CHAR *p_c )
{
int count;
#ifdef BUFFERED_FILE
count = fread( p_c, sizeof ( U_CHAR ), 1, pls->plbufFile );
#else
if ( pls->plbuf_readpos < pls->plbuf_top )
{
*p_c = *(U_CHAR *) ( (U_CHAR *) pls->plbuf_buffer + pls->plbuf_readpos );
pls->plbuf_readpos += sizeof ( U_CHAR );
count = sizeof ( U_CHAR );
}
else
{
count = 0;
}
#endif
return ( count );
}
//--------------------------------------------------------------------------
// rd_data()
//
// Read the data associated with the command
//--------------------------------------------------------------------------
static void
rd_data( PLStream *pls, void *buf, size_t buf_size )
{
#ifdef BUFFERED_FILE
plio_fread( buf, buf_size, 1, pls->plbufFile );
#else
// If U_CHAR is not the same size as what memcpy() expects (typically 1 byte)
// then this code will have problems. A better approach might be to use
// uint8_t from <stdint.h> but I do not know how portable that approach is
//
memcpy( buf, (U_CHAR *) pls->plbuf_buffer + pls->plbuf_readpos, buf_size );
pls->plbuf_readpos += buf_size;
#endif
}
//--------------------------------------------------------------------------
// wr_command()
//
// Write the next command
//--------------------------------------------------------------------------
static void
wr_command( PLStream *pls, U_CHAR c )
{
#ifdef BUFFERED_FILE
plio_fwrite( &c1, sizeof ( U_CHAR ), 1, pls->plbufFile );
#else
if ( ( pls->plbuf_top + sizeof ( U_CHAR ) ) >= pls->plbuf_buffer_size )
{
// Not enough space, need to grow the buffer
pls->plbuf_buffer_size += pls->plbuf_buffer_grow;
if ( pls->verbose )
printf( "Growing buffer to %d KB\n", (int) ( pls->plbuf_buffer_size / 1024 ) );
if ( ( pls->plbuf_buffer = realloc( pls->plbuf_buffer, pls->plbuf_buffer_size ) ) == NULL )
plexit( "plbuf wr_data: Plot buffer grow failed" );
}
*(U_CHAR *) ( (U_CHAR *) pls->plbuf_buffer + pls->plbuf_top ) = c;
pls->plbuf_top += sizeof ( U_CHAR );
#endif
}
//--------------------------------------------------------------------------
// wr_data()
//
// Write the data associated with a command
//--------------------------------------------------------------------------
static void
wr_data( PLStream *pls, void *buf, size_t buf_size )
{
#ifdef BUFFERED_FILE
plio_fwrite( buf, buf_size, 1, pls->plbufFile );
#else
if ( ( pls->plbuf_top + buf_size ) >= pls->plbuf_buffer_size )
{
// Not enough space, need to grow the buffer
// Must make sure the increase is enough for this data
pls->plbuf_buffer_size += pls->plbuf_buffer_grow *
( ( pls->plbuf_top + buf_size - pls->plbuf_buffer_size ) /
pls->plbuf_buffer_grow + 1 );
while ( pls->plbuf_top + buf_size >= pls->plbuf_buffer_size )
;
if ( ( pls->plbuf_buffer = realloc( pls->plbuf_buffer, pls->plbuf_buffer_size ) ) == NULL )
plexit( "plbuf wr_data: Plot buffer grow failed" );
}
// If U_CHAR is not the same size as what memcpy() expects (typically 1 byte)
// then this code will have problems. A better approach might be to use
// uint8_t from <stdint.h> but I do not know how portable that approach is
//
memcpy( (U_CHAR *) pls->plbuf_buffer + pls->plbuf_top, buf, buf_size );
pls->plbuf_top += buf_size;
#endif
}
// plbuf_save(state)
//
// Saves the current state of the plot into a save buffer.
// This code was originally in gcw.c and gcw-lib.c. The original
// code used a temporary file for the plot buffer and memory
// to perserve colormaps. That method does not offer a clean
// break between using memory buffers and file buffers. This
// function preserves the same functionality by returning a data
// structure that saves the plot buffer and colormaps seperately.
//
// The caller passes an existing save buffer for reuse or NULL
// to force the allocation of a new buffer. Since one malloc()
// is used for everything, the entire save buffer can be freed
// with one free() call.
//
//
struct _color_map
{
PLColor *cmap;
PLINT icol;
PLINT ncol;
};
struct _state
{
size_t size; // Size of the save buffer
int valid; // Flag to indicate a valid save state
#ifdef BUFFERED_FILE
FILE *plbufFile;
#else
void *plbuf_buffer;
size_t plbuf_buffer_size;
size_t plbuf_top;
size_t plbuf_readpos;
#endif
struct _color_map *color_map;
};
void * plbuf_save( PLStream *pls, void *state )
{
size_t save_size;
struct _state *plot_state = (struct _state *) state;
PLINT i;
U_CHAR *buf; // Assume that this is byte-sized
if ( pls->plbuf_write )
{
pls->plbuf_write = FALSE;
pls->plbuf_read = TRUE;
// Determine the size of the buffer required to save everything. We
// assume that there are only two colormaps, but have written the code
// that more than two can be handled with minimal changes.
//
save_size = sizeof ( struct _state )
+ 2 * sizeof ( struct _color_map )
+ (size_t) ( pls->ncol0 ) * sizeof ( PLColor )
+ (size_t) ( pls->ncol1 ) * sizeof ( PLColor );
#ifndef BUFFERED_FILE
// Only copy as much of the plot buffer that is being used
save_size += pls->plbuf_top;
#endif
// If a buffer exists, determine if we need to resize it
if ( state != NULL )
{
// We have a save buffer, is it smaller than the current size requirement?
if ( plot_state->size < save_size )
{
// Yes, reallocate a larger one
if ( ( plot_state = (struct _state *) realloc( state, save_size ) ) == NULL )
{
// NOTE: If realloc fails, then plot_state ill be NULL.
// This will leave the original buffer untouched, thus we
// mark it as invalid and return it back to the caller.
//
plwarn( "plbuf: Unable to reallocate sufficient memory to save state" );
plot_state->valid = 0;
return state;
}
plot_state->size = save_size;
}
}
else
{
// A buffer does not exist, so we need to allocate one
if ( ( plot_state = (struct _state *) malloc( save_size ) ) == NULL )
{
plwarn( "plbuf: Unable to allocate sufficient memory to save state" );
return NULL;
}
plot_state->size = save_size;
#ifdef BUFFERED_FILE
// Make sure the FILE pointer is NULL in order to preven bad things from happening...
plot_state->plbufFile = NULL;
#endif
}
// At this point we have an appropriately sized save buffer.
// We need to invalidate the state of the save buffer, since it
// will not be valid until after everything is copied. We use
// this approach vice freeing the memory and returning a NULL pointer
// in order to prevent allocating and freeing memory needlessly.
//
plot_state->valid = 0;
// Point buf to the space after the struct _state
buf = (U_CHAR *) ( plot_state + 1 );
#ifdef BUFFERED_FILE
// Remove the old tempfile, if it exists
if ( plot_state->plbufFile != NULL )
{
fclose( plot_state->plbufFile );
}
// Copy the plot buffer to a tempfile
if ( ( plot_state->plbufFile = pl_create_tempfile( NULL ) ) == NULL )
{
// Throw a warning since this might be a permissions problem
// and we may not want to force an exit
//
plwarn( "plbuf: Unable to open temporary file to save state" );
return (void *) plot_state;
}
else
{
U_CHAR tmp;
rewind( pls->plbufFile );
while ( count = fread( &tmp, sizeof ( U_CHAR ), 1, pls->plbufFile ) )
{
if ( fwrite( &tmp, sizeof ( U_CHAR ), 1, plot_state->plbufFile ) != count )
{
// Throw a warning since this might be a permissions problem
// and we may not want to force an exit
//
plwarn( "plbuf: Unable to write to temporary file" );
fclose( plot_state->plbufFile );
plot_state->plbufFile = NULL;
return (void *) plot_state;
}
}
}
#else
// Again, note, that we only copy the portion of the plot buffer that is being used
plot_state->plbuf_buffer_size = pls->plbuf_top;
plot_state->plbuf_top = pls->plbuf_top;
plot_state->plbuf_readpos = 0;
// Create a pointer that points in the space we allocated after struct _state
plot_state->plbuf_buffer = (void *) buf;
buf += pls->plbuf_top;
// Copy the plot buffer to our new buffer. Again, I must stress, that we only
// are copying the portion of the plot buffer that is being used
//
if ( memcpy( plot_state->plbuf_buffer, pls->plbuf_buffer, pls->plbuf_top ) == NULL )
{
// This should never be NULL
plwarn( "plbuf: Got a NULL in memcpy!" );
return (void *) plot_state;
}
#endif
pls->plbuf_write = TRUE;
pls->plbuf_read = FALSE;
// Save the colormaps. First create a pointer that points in the space we allocated
// after the plot buffer
plot_state->color_map = (struct _color_map *) buf;
buf += sizeof ( struct _color_map ) * 2;
// Then we need to make space for the colormaps themselves
plot_state->color_map[0].cmap = (PLColor *) buf;
buf += sizeof ( PLColor ) * (size_t) ( pls->ncol0 );
plot_state->color_map[1].cmap = (PLColor *) buf;
buf += sizeof ( PLColor ) * (size_t) ( pls->ncol1 );
// Save cmap 0
plot_state->color_map[0].icol = pls->icol0;
plot_state->color_map[0].ncol = pls->ncol0;
for ( i = 0; i < pls->ncol0; i++ )
{
pl_cpcolor( &( plot_state->color_map[0].cmap[i] ), &pls->cmap0[i] );
}
// Save cmap 1
plot_state->color_map[1].icol = pls->icol1;
plot_state->color_map[1].ncol = pls->ncol1;
for ( i = 0; i < pls->ncol1; i++ )
{
pl_cpcolor( &( plot_state->color_map[1].cmap[i] ), &pls->cmap1[i] );
}
plot_state->valid = 1;
return (void *) plot_state;
}
return NULL;
}
// plbuf_restore(PLStream *, state)
//
// Restores the passed state
//
void plbuf_restore( PLStream *pls, void *state )
{
struct _state *new_state = (struct _state *) state;
#ifdef BUFFERED_FILE
pls->plbufFile = new_state->save_file;
#else
pls->plbuf_buffer = new_state->plbuf_buffer;
pls->plbuf_buffer_size = new_state->plbuf_buffer_size;
pls->plbuf_top = new_state->plbuf_top;
pls->plbuf_readpos = new_state->plbuf_readpos;
#endif
// cmap 0
pls->cmap0 = new_state->color_map[0].cmap;
pls->icol0 = new_state->color_map[0].icol;
pls->ncol0 = new_state->color_map[0].ncol;
// cmap 1
pls->cmap1 = new_state->color_map[1].cmap;
pls->icol1 = new_state->color_map[1].icol;
pls->ncol1 = new_state->color_map[1].ncol;
}
// plbuf_switch(PLStream *, state)
//
// Makes the passed state the current one. Preserves the previous state
// by returning a save buffer.
//
// NOTE: The current implementation can cause a memory leak under the
// following scenario:
// 1) plbuf_save() is called
// 2) plbuf_switch() is called
// 3) Commands are called which cause the plot buffer to grow
// 4) plbuf_swtich() is called
//
void * plbuf_switch( PLStream *pls, void *state )
{
struct _state *new_state = (struct _state *) state;
struct _state *prev_state;
size_t save_size;
// No saved state was passed, return a NULL--we hope the caller
// is smart enough to notice
//
if ( state == NULL )
return NULL;
if ( !new_state->valid )
{
plwarn( "plbuf: Attempting to switch to an invalid saved state" );
return NULL;
}
save_size = sizeof ( struct _state )
+ 2 * sizeof ( struct _color_map );
if ( ( prev_state = (struct _state *) malloc( save_size ) ) == NULL )
{
plwarn( "plbuf: Unable to allocate memory to save state" );
return NULL;
}
// Set some housekeeping variables
prev_state->size = save_size;
prev_state->valid = 1;
// Preserve the existing state
#ifdef BUFFERED_FILE
prev_state->plbufFile = pls->plbufFile;
#else
prev_state->plbuf_buffer = pls->plbuf_buffer;
prev_state->plbuf_buffer_size = pls->plbuf_buffer_size;
prev_state->plbuf_top = pls->plbuf_top;
prev_state->plbuf_readpos = pls->plbuf_readpos;
#endif
// cmap 0
prev_state->color_map[0].cmap = pls->cmap0;
prev_state->color_map[0].icol = pls->icol0;
prev_state->color_map[0].ncol = pls->ncol0;
// cmap 1
prev_state->color_map[1].cmap = pls->cmap1;
prev_state->color_map[1].icol = pls->icol1;
prev_state->color_map[1].ncol = pls->ncol1;
plbuf_restore( pls, new_state );
return (void *) prev_state;
}
| 30.976207
| 135
| 0.510073
|
rsuchecki
|
e59fdf2108f8a9cc91b033460bb0e43df2c9850d
| 1,251
|
cpp
|
C++
|
misc/longincsubseq.cpp
|
plilja/algolib
|
84b1e3115f18bac02632b6bef4ca11c3392e76a4
|
[
"Apache-2.0"
] | null | null | null |
misc/longincsubseq.cpp
|
plilja/algolib
|
84b1e3115f18bac02632b6bef4ca11c3392e76a4
|
[
"Apache-2.0"
] | null | null | null |
misc/longincsubseq.cpp
|
plilja/algolib
|
84b1e3115f18bac02632b6bef4ca11c3392e76a4
|
[
"Apache-2.0"
] | null | null | null |
#include "longincsubseq.h"
#include <cmath>
using std::vector;
/*
* Do a binary search for the integer j. Such that lowerBound<=j<=upperBound
* and that maximizes seq[M[j]] while keeping seq[M[j]]<x.
*/
int binSearch(vector<int> &M, const vector<int> &seq, int x, int lowerBound, int upperBound)
{
int lo = lowerBound;
int hi = upperBound;
while (lo <= hi) {
int middle = ceil((lo + hi) / 2.0);
if (seq[M[middle]] < x) {
lo = middle + 1;
} else {
hi = middle - 1;
}
}
return lo;
}
vector<int> recreateSolution(vector<int> &P, int ans_length, int final_idx)
{
vector<int> result(ans_length);
int tmp = final_idx;
for (int i = ans_length - 1; i >= 0; --i) {
result[i] = tmp;
tmp = P[tmp];
}
return result;
}
vector<int> longincsubseq(const vector<int> &seq)
{
int len = seq.size();
vector<int> M(len + 1);
vector<int> P(len);
int ans_length = 0;
M[0] = 0;
for (int i = 0; i < len; ++i) {
int lo = binSearch(M, seq, seq[i], 1, ans_length);
P[i] = M[lo - 1];
M[lo] = i;
ans_length = std::max(ans_length, lo);
}
return recreateSolution(P, ans_length, M[ans_length]);
}
| 22.745455
| 92
| 0.54996
|
plilja
|
e59fe0557fffaea876c7d5aecde27a3afe0f5c40
| 1,034
|
cpp
|
C++
|
codeforces/N - Egg Drop/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/N - Egg Drop/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/N - Egg Drop/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: JU_AAA: prdx9_abir, aniks2645, kzvd4729 created: Sep/15/2017 22:21
* solution_verdict: Accepted language: GNU C++14
* run_time: 15 ms memory_used: 0 KB
* problem: https://codeforces.com/gym/100819/problem/N
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
long n,k,x;
string s;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>k;
long sf=1,br=k;
for(long i=1; i<=n; i++)
{
cin>>x>>s;
if(s=="SAFE")
{
sf=max(sf,x);
}
if(s=="BROKEN")
{
br=min(br,x);
}
}
cout<<sf+1<<" ";
cout<<br-1<<endl;
return 0;
}
| 30.411765
| 111
| 0.352998
|
kzvd4729
|
e5a236aecc80419a14be0d7747cb1aec36bfe2c4
| 2,314
|
hpp
|
C++
|
include/ESPSerial.hpp
|
willson556/avr-2807
|
6bbb73072d94ab0cae2808d67aed5651c91a74b6
|
[
"MIT"
] | null | null | null |
include/ESPSerial.hpp
|
willson556/avr-2807
|
6bbb73072d94ab0cae2808d67aed5651c91a74b6
|
[
"MIT"
] | null | null | null |
include/ESPSerial.hpp
|
willson556/avr-2807
|
6bbb73072d94ab0cae2808d67aed5651c91a74b6
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Transport.hpp"
#include <driver/uart.h>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
namespace AVR
{
class ESPSerial : public Transport
{
public:
ESPSerial(uart_port_t port, uart_config_t config, size_t buffer_size, int timeout, int tx_pin, int rx_pin, int rts_pin, int cts_pin)
: port{port},
config{config},
buffer_size{buffer_size},
timeout{timeout},
tx_pin{tx_pin},
rx_pin{rx_pin},
rts_pin{rts_pin},
cts_pin{cts_pin}
{
}
void connect() const override
{
ESP_ERROR_CHECK(uart_param_config(port, &config));
ESP_ERROR_CHECK(uart_set_pin(port, tx_pin, rx_pin, rts_pin, cts_pin));
ESP_ERROR_CHECK(uart_driver_install(port, buffer_size, buffer_size, 10, (void**)&queue, 0));
}
void write(const std::vector<uint8_t> &data) const override
{
ESP_ERROR_CHECK(uart_write_bytes(port, reinterpret_cast<const char *>(data.data()), data.size()));
}
std::vector<uint8_t> read(size_t max_length, bool wait_for_all) const override
{
unsigned long start_time = esp_timer_get_time();
size_t data_available;
bool ready_to_read = false;
do {
ESP_ERROR_CHECK(uart_get_buffered_data_len(port, &data_available));
if (data_available >= max_length) {
ready_to_read = true;
} else if (!wait_for_all && data_available > 0) {
ready_to_read = true;
}
} while ( esp_timer_get_time() - start_time < timeout * 1000
&& !ready_to_read );
if (!ready_to_read) {
return std::vector<uint8_t>{};
}
std::vector<uint8_t> data(data_available);
auto read_length = uart_read_bytes(port, data.data(), data.size(), timeout * portTICK_PERIOD_MS);
data.resize(read_length < 0 ? 0 : read_length);
return data;
}
void flush() const override
{
uart_flush(port);
}
private:
const uart_port_t port;
const uart_config_t config;
const size_t buffer_size;
const int timeout; // ms
const int tx_pin;
const int rx_pin;
const int rts_pin;
const int cts_pin;
QueueHandle_t queue;
};
} // namespace AVR
| 26.295455
| 136
| 0.627053
|
willson556
|
e5a54cd2ebd54f02c76a28d3131a827eeba66201
| 31,884
|
cpp
|
C++
|
enduser/windows.com/wuau/wuauclt/customlb.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
enduser/windows.com/wuau/wuauclt/customlb.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
enduser/windows.com/wuau/wuauclt/customlb.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
#include "pch.h"
#pragma hdrstop
void SetMYLBAcc(HWND hListWin);
void DrawMYLBFocus(HWND hListWin, LPDRAWITEMSTRUCT lpdis, MYLBFOCUS enCurFocus, INT nCurFocusId);
void DrawItem(LPDRAWITEMSTRUCT lpdis, BOOL fSelectionDisabled);
void DrawTitle(HDC hDC, LBITEM * plbi, RECT rc);
void DrawRTF(HDC hDC, LBITEM * plbi, const RECT & rc /*, BOOL bHit*/);
void DrawDescription(HDC hDC, LBITEM * plbi, RECT & rc);
void DrawBitmap(HDC hDC, LBITEM * plbi, const RECT & rc, BOOL fSel, BOOL fSelectionDisabled);
void CalcTitleFocusRect(const RECT &rcIn, RECT & rcOut);
void CalcRTFFocusRect(const RECT &rcIn, RECT & rcOut);
int CalcDescHeight(HDC hDC, LPTSTR ptszDescription, int cx);
int CalcRTFHeight(HDC hDC, LPTSTR ptszRTF);
int CalcRTFWidth(HDC hDC, LPTSTR ptszRTF);
int CalcTitleHeight(HDC hDC, LPTSTR ptszTitle, int cx);
int CalcItemHeight(HDC hDC, LPTSTR ptszTitle, LPTSTR ptszDescription, LPTSTR ptszRTF, int cx);
void CalcItemLocation(HDC hDC, LBITEM * plbi, const RECT & rc);
void ToggleSelection(HWND hDlg, HWND hListWin, LBITEM *pItem);
void AddItem(LPTSTR tszTitle, LPTSTR tszDesc, LPTSTR tszRTF, int index, BOOL fSelected, BOOL fRTF);
BOOL CurItemHasRTF(HWND hListWin);
void RedrawMYLB(HWND hwndLB);
void LaunchRTF(HWND hListWin);
HBITMAP ghBmpGrayOut; //=NULL;
HBITMAP ghBmpCheck; // = NULL;
HBITMAP ghBmpClear; // = NULL;
HFONT ghFontUnderline; // = NULL;
HFONT ghFontBold; // = NULL;
HFONT ghFontNormal; // = NULL;
HWND ghWndList; //=NULL;
MYLBFOCUS gFocus;
INT gFocusItemId;
TCHAR gtszRTFShortcut[MAX_RTFSHORTCUTDESC_LENGTH];
void LaunchRTF(HWND hListWin)
{
HWND hDlg = GetParent(hListWin);
int i = (LONG)SendMessage(ghWndList, LB_GETCURSEL, 0, 0);
if(i != LB_ERR)
{
LBITEM* pItem = (LBITEM*)SendMessage(hListWin, LB_GETITEMDATA, i, 0);
if (pItem && pItem->bRTF)
{
DEBUGMSG("MYLB show RTF for item %S", pItem->szTitle);
PostMessage(GetParent(hDlg), AUMSG_SHOW_RTF, LOWORD(pItem->m_index), 0);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Overwrite hListWin's accessibility behavior using dynamic annotation server
////////////////////////////////////////////////////////////////////////////////
void SetMYLBAcc(HWND hListWin)
{
IAccPropServices * pAccPropSvc = NULL;
HRESULT hr = CoCreateInstance(CLSID_AccPropServices,
NULL,
CLSCTX_INPROC_SERVER,
IID_IAccPropServices,
(void **) &pAccPropSvc);
if( hr == S_OK && pAccPropSvc )
{
MYLBAccPropServer* pMYLBPropSrv = new MYLBAccPropServer( pAccPropSvc );
if( pMYLBPropSrv )
{
MSAAPROPID propids[4];
propids[0] = PROPID_ACC_NAME;
propids[1] = PROPID_ACC_STATE;
propids[2] = PROPID_ACC_ROLE;
propids[3] = PROPID_ACC_DESCRIPTION;
pAccPropSvc->SetHwndPropServer( hListWin, OBJID_CLIENT, 0, propids, 4, pMYLBPropSrv, ANNO_CONTAINER);
pMYLBPropSrv->Release();
}
pAccPropSvc->Release();
}
else
{
DEBUGMSG("WANRING: WUAUCLT Fail to create object AccPropServices with error %#lx", hr);
}
// Mark the listbox so that the server can tell if it alive
SetProp(hListWin, MYLBALIVEPROP, (HANDLE)TRUE);
}
/*void DumpRect(LPCTSTR tszName, RECT rc)
{
DEBUGMSG("DumpRect %S at (%d, %d, %d, %d)", tszName, rc.left, rc.top, rc.right, rc.bottom);
}
*/
void DrawItem(LPDRAWITEMSTRUCT lpdis, BOOL fSelectionDisabled)
{
LRESULT lResult = SendMessage(lpdis->hwndItem, LB_GETITEMDATA, lpdis->itemID, 0);
if (LB_ERR == lResult)
{
return;
}
LBITEM * plbi = (LBITEM*) lResult;
CalcItemLocation(lpdis->hDC, plbi, lpdis->rcItem);
// Draw the title of the item
DrawTitle(lpdis->hDC, plbi, plbi->rcTitle);
// Draw the text of the item
DrawDescription(lpdis->hDC, plbi, plbi->rcText);
// Draw the bitmap
DrawBitmap(lpdis->hDC, plbi, plbi->rcBitmap, plbi->bSelect, fSelectionDisabled);
// draw the Read this First
DrawRTF(lpdis->hDC, plbi, plbi->rcRTF);
}
BOOL CurItemHasRTF(HWND hListWin)
{
int i = (LONG)SendMessage(hListWin, LB_GETCURSEL, 0, 0);
if (LB_ERR == i)
{
return FALSE;
}
LBITEM *pItem = (LBITEM*)SendMessage(hListWin, LB_GETITEMDATA, (WPARAM)i, 0);
return pItem->bRTF;
}
BOOL fDisableSelection(void)
{
AUOPTION auopt;
if (SUCCEEDED(gInternals->m_getServiceOption(&auopt))
&& auopt.fDomainPolicy && AUOPTION_SCHEDULED == auopt.dwOption)
{
return TRUE;
}
return FALSE;
}
void ToggleSelection(HWND hDlg, HWND hListWin, LBITEM *pItem)
{
//DEBUGMSG("ToggleSelection()");
if (NULL == hDlg || NULL == hListWin || NULL == pItem || pItem->m_index >= gInternals->m_ItemList.Count())
{
AUASSERT(FALSE); //should never reach here.
return;
}
HDC hDC = GetDC(hListWin);
if (NULL == hDC)
{
return;
}
pItem->bSelect = !pItem->bSelect;
DrawBitmap(hDC, pItem, pItem->rcBitmap, pItem->bSelect, FALSE); //obviously selection is allowed
#ifndef TESTUI
gInternals->m_ItemList[pItem->m_index].SetStatus(pItem->bSelect ? AUCATITEM_SELECTED : AUCATITEM_UNSELECTED);
#endif
PostMessage(GetParent(hDlg), AUMSG_SELECTION_CHANGED, 0, 0);
ReleaseDC(hListWin, hDC);
}
void RedrawMYLB(HWND hwndLB)
{
//DEBUGMSG("REDRAW MYLB ");
InvalidateRect(ghWndList, NULL, TRUE);
UpdateWindow(ghWndList);
}
void CalcTitleFocusRect(const RECT &rcIn, RECT & rcOut)
{
rcOut = rcIn;
rcOut.right -= TITLE_MARGIN * 2/3;
rcOut.top += SECTION_SPACING * 2/3;
rcOut.bottom -= SECTION_SPACING*2/3 ;
}
void CalcRTFFocusRect(const RECT &rcIn, RECT & rcOut)
{
rcOut = rcIn;
rcOut.left -=3;
rcOut.right +=3;
rcOut.top -= 2;
rcOut.bottom += 2;
}
void DrawMYLBFocus(HWND hListWin, LPDRAWITEMSTRUCT lpdis, MYLBFOCUS enCurFocus, INT nCurFocusId)
{
LBITEM * pItem;
LRESULT lResult;
//DEBUGMSG("DrawMYLBFocus for current focus %d with Item %d", enCurFocus, nCurFocusId);
RECT rcNew;
if (nCurFocusId != lpdis->itemID)
{
return;
}
if (GetFocus() != ghWndList )
{
// DEBUGMSG("CustomLB doesn't have focus");
return;
}
lResult = SendMessage(hListWin, LB_GETITEMDATA, lpdis->itemID, 0);
if (LB_ERR == lResult)
{
DEBUGMSG("DrawMYLBFocus() fail to get item data");
goto done;
}
pItem = (LBITEM*) lResult;
if (!EqualRect(&lpdis->rcItem, &pItem->rcItem))
{
CalcItemLocation(lpdis->hDC, pItem, lpdis->rcItem);
}
if (enCurFocus == MYLB_FOCUS_RTF)
{
CalcRTFFocusRect(pItem->rcRTF, rcNew);
}
if (enCurFocus == MYLB_FOCUS_TITLE)
{
CalcTitleFocusRect(pItem->rcTitle, rcNew);
}
DrawFocusRect(lpdis->hDC, &rcNew); //set new focus rect
done:
return;
}
LRESULT CallDefLBWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static WNDPROC s_defLBWndProc = NULL;
if (NULL == s_defLBWndProc)
{
s_defLBWndProc = (WNDPROC) GetWindowLongPtr(hWnd, GWLP_USERDATA);
}
return CallWindowProc(s_defLBWndProc, hWnd, message, wParam, lParam);
}
LRESULT CALLBACK newLBWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_GETDLGCODE:
return DLGC_WANTALLKEYS;
case WM_KEYDOWN:
switch(wParam)
{
case VK_RIGHT:
case VK_LEFT:
if (MYLB_FOCUS_RTF == gFocus)
{
DEBUGMSG("LB change focus to Title");
gFocus = MYLB_FOCUS_TITLE;
RedrawMYLB(ghWndList);
}
else if (MYLB_FOCUS_TITLE == gFocus && CurItemHasRTF(hWnd))
{
DEBUGMSG("LB change focus to RTF");
gFocus = MYLB_FOCUS_RTF;
RedrawMYLB(ghWndList);
}
break;
case VK_F1:
if (GetKeyState(VK_SHIFT)<0)
{//SHIFT down
LaunchRTF(hWnd);
return 0;
}
break;
case VK_RETURN:
if (MYLB_FOCUS_RTF == gFocus)
{
DEBUGMSG("MYLB show RTF ");
LaunchRTF(hWnd);
}
break;
case VK_TAB:
PostMessage(GetParent(hWnd), WM_NEXTDLGCTL, 0, 0L);
break;
default:
return CallDefLBWndProc(hWnd, message, wParam, lParam);
}
return 0;
case WM_KEYUP:
switch(wParam)
{
case VK_RIGHT:
case VK_LEFT:
break;
case VK_RETURN:
break;
default:
return CallDefLBWndProc(hWnd, message, wParam, lParam);
}
return 0;
default:
break;
}
return CallDefLBWndProc(hWnd, message, wParam, lParam);
}
// Message handler for Custom List box.
LRESULT CALLBACK CustomLBWndProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
static int lenx;
int clb;
LBITEM *item;
static BOOL s_fSelectionDisabled;
switch (message)
{
case WM_CREATE:
{
RECT rcLst, rcDlg;
LOGFONT lf;
HFONT parentFont;
TCHAR tszRTF[MAX_RTF_LENGTH] = _T("");
GetClientRect(hDlg, &rcDlg);
rcDlg.top += 2;
rcDlg.bottom -= 3;
rcDlg.left += 2;
rcDlg.right -= 2;
s_fSelectionDisabled = fDisableSelection();
ghWndList = CreateWindow(_T("listbox"), NULL,
WS_CHILD | WS_VISIBLE | LBS_NOTIFY | LBS_OWNERDRAWVARIABLE |
LBS_NOINTEGRALHEIGHT | LBS_HASSTRINGS | LBS_WANTKEYBOARDINPUT |
WS_VSCROLL | WS_HSCROLL | WS_TABSTOP,
rcDlg.left, rcDlg.top, rcDlg.right - rcDlg.left, rcDlg.bottom - rcDlg.top,
hDlg, NULL, ghInstance, NULL);
if (NULL == ghWndList)
{
return -1;
}
WNDPROC defLBWndProc = (WNDPROC) GetWindowLongPtr(ghWndList, GWLP_WNDPROC);
SetWindowLongPtr(ghWndList, GWLP_USERDATA, (LONG_PTR) defLBWndProc);
SetWindowLongPtr(ghWndList, GWLP_WNDPROC, (LONG_PTR) newLBWndProc);
HDC hDC = GetDC(ghWndList);
GetWindowRect(hDlg, &rcDlg);
GetClientRect(ghWndList, &rcLst);
lenx = rcLst.right - rcLst.left;
// Load read this first text from resource file
LoadString(ghInstance, IDS_READTHISFIRST, tszRTF, MAX_RTF_LENGTH);
// load keyboard shortcut description for Read this First
LoadString(ghInstance, IDS_RTFSHORTCUT, gtszRTFShortcut, MAX_RTFSHORTCUTDESC_LENGTH);
// Load the bitmaps
ghBmpClear = (HBITMAP)LoadImage(ghInstance, MAKEINTRESOURCE(IDB_CLEAR), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS | LR_CREATEDIBSECTION);
ghBmpCheck = (HBITMAP)LoadImage(ghInstance, MAKEINTRESOURCE(IDB_CHECK), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS | LR_CREATEDIBSECTION);
ghBmpGrayOut = (HBITMAP)LoadImage(ghInstance, MAKEINTRESOURCE(IDB_GRAYOUT), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS | LR_CREATEDIBSECTION);
// Create BOLD and Italic fonts
ZeroMemory(&lf, sizeof(lf));
//fixcode: check return value of GetCurrentObject()
GetObject(GetCurrentObject(hDC, OBJ_FONT), sizeof(lf), &lf);
//fixcode: check return value of GetParent()
parentFont = (HFONT)SendMessage(GetParent(hDlg), WM_GETFONT, 0, 0);
SendMessage(hDlg, WM_SETFONT, (WPARAM)parentFont, FALSE);
SelectObject(hDC, parentFont);
//fixcode: check return value of GetCurrentObject()
GetObject(GetCurrentObject(hDC, OBJ_FONT), sizeof(lf), &lf);
lf.lfUnderline = TRUE;
lf.lfWeight = FW_NORMAL;
//fixcode: check return value of CreateFontIndirect()
ghFontUnderline = CreateFontIndirect(&lf);
lf.lfUnderline = FALSE;
lf.lfWeight = FW_NORMAL;
//fixcode: check return value of CreateFontIndirect()
ghFontNormal = CreateFontIndirect(&lf);
lf.lfUnderline = FALSE;
lf.lfWeight = FW_HEAVY;
//fixcode: check return value of CreateFontIndirect()
ghFontBold = CreateFontIndirect(&lf);
ReleaseDC(ghWndList, hDC);
#ifdef TESTUI
{
AddItem(_T("Test 1 Very long title Test 1 Very long title Test 1 Very long title Test 1 Very long title "),
_T("Description"), tszRTF, 0, TRUE, TRUE);
AddItem(_T("Test 2"), _T("Another description. No RTF"), tszRTF,0, TRUE, FALSE);
}
#else
#if 0
DEBUGMSG("WM_CREATE: before add item rcLst=(%d, %d)-(%d, %d)", rcLst.left, rcLst.top, rcLst.right, rcLst.bottom);
#endif
{
for (UINT i = 0; i < gInternals->m_ItemList.Count(); i++)
{
DEBUGMSG("selected[%d] = %lu", i, gInternals->m_ItemList[i].dwStatus());
if ( !gInternals->m_ItemList[i].fHidden() )
{
AddItem(gInternals->m_ItemList[i].bstrTitle(),
gInternals->m_ItemList[i].bstrDescription(),
tszRTF,
i,
gInternals->m_ItemList[i].fSelected(),
IsRTFDownloaded(gInternals->m_ItemList[i].bstrRTFPath(), GetSystemDefaultLangID()));
}
}
}
GetClientRect(ghWndList, &rcLst);
#if 0
DEBUGMSG("WM_CREATE: after add item rcLst=(%d, %d)-(%d, %d)", rcLst.left, rcLst.top, rcLst.right, rcLst.bottom);
#endif
if (rcLst.right - rcLst.left != lenx)
{
lenx = rcLst.right - rcLst.left;
hDC = GetDC(ghWndList);
int nListIndex = 0;
for (UINT i = 0; i < gInternals->m_ItemList.Count(); i++)
{
DEBUGMSG("selected[%d] = %lu", i, gInternals->m_ItemList[i].dwStatus());
if ( !gInternals->m_ItemList[i].fHidden() )
{
if (LB_ERR == SendMessage(
ghWndList,
LB_SETITEMHEIGHT,
nListIndex,
CalcItemHeight(
hDC,
gInternals->m_ItemList[i].bstrTitle(),
gInternals->m_ItemList[i].bstrDescription(),
tszRTF,
lenx)))
{
DEBUGMSG("failed to recalc height of item %u", i);
break;
}
nListIndex++;
}
}
ReleaseDC(ghWndList, hDC);
}
#endif
SendMessage(ghWndList, LB_SETCURSEL, 0, 0);
gFocus = MYLB_FOCUS_TITLE;
gFocusItemId = 0;
SetMYLBAcc(ghWndList);
return 0;
}
case WM_MOVE:
{
RECT rcList;
GetWindowRect(ghWndList, &rcList); // need this to force LB to realize it got moved
return(TRUE);
}
case WM_SETCURSOR:
{
if (ghWndList == (HWND)wParam && LOWORD(lParam) == HTCLIENT && HIWORD(lParam) == WM_MOUSEMOVE)
{
POINT pt;
RECT rc;
GetCursorPos(&pt);
if (0 == MapWindowPoints(NULL, ghWndList, &pt, 1))
{
DEBUGMSG("MYLBWndProc MapWindowPoints failed");
return FALSE;
}
DWORD dwPos;
dwPos = MAKELONG( pt.x, pt.y);
DWORD dwItem = (LONG)SendMessage(ghWndList, LB_ITEMFROMPOINT, 0, dwPos);
if (LOWORD(dwItem) == -1)
return(FALSE);
item = (LBITEM*)SendMessage(ghWndList, LB_GETITEMDATA, LOWORD(dwItem), 0);
SendMessage(ghWndList, LB_GETITEMRECT, LOWORD(dwItem), (LPARAM)&rc);
if (!EqualRect(&rc, &item->rcItem))
{
HDC hDC = GetDC(ghWndList);
CalcItemLocation(hDC, item, rc);
ReleaseDC(ghWndList, hDC);
}
if (item->bRTF && PtInRect(&item->rcRTF, pt))
{
// DEBUGMSG("Change Cursor to hand in MOUSEMOVE");
SetCursor(ghCursorHand);
return TRUE;
}
return FALSE;
}
else
if (ghWndList == (HWND)wParam && LOWORD(lParam) == HTCLIENT && HIWORD(lParam) == WM_LBUTTONDOWN)
{
POINT pt;
RECT rc;
GetCursorPos(&pt);
if (0 == MapWindowPoints(NULL, ghWndList, &pt, 1))
{
DEBUGMSG("MYLBWndProc MapWindowPoints failed");
return FALSE;
}
DWORD dwPos;
dwPos = MAKELONG( pt.x, pt.y);
DWORD dwItem = (LONG)SendMessage(ghWndList, LB_ITEMFROMPOINT, 0, dwPos);
if (LOWORD(dwItem) == -1)
return(FALSE);
item = (LBITEM*)SendMessage(ghWndList, LB_GETITEMDATA, LOWORD(dwItem), 0);
SendMessage(ghWndList, LB_GETITEMRECT, LOWORD(dwItem), (LPARAM)&rc);
if (!EqualRect(&rc, &item->rcItem))
{
HDC hDC = GetDC(ghWndList);
CalcItemLocation(hDC, item, rc);
ReleaseDC(ghWndList, hDC);
}
// Are we clicking on the Title?
if (PtInRect(&item->rcBitmap, pt))
{
if (!s_fSelectionDisabled)
{
ToggleSelection(hDlg, ghWndList, item);
}
// DEBUGMSG("WM_SETCURSOR change gFocus to TITLE");
gFocus = MYLB_FOCUS_TITLE;
gFocusItemId = dwItem;
RedrawMYLB(ghWndList);
return TRUE;
}
// or are we clicking on the RTF?
if (item->bRTF && PtInRect(&item->rcRTF, pt))
{
PostMessage(GetParent(hDlg), AUMSG_SHOW_RTF, LOWORD(item->m_index), 0);
SetCursor(ghCursorHand);
//DEBUGMSG("WM_SETCURSOR change gFocus to RTF");
gFocus = MYLB_FOCUS_RTF;
gFocusItemId = dwItem;
RedrawMYLB(ghWndList);
return TRUE;
}
return FALSE;
}
return FALSE;
}
case WM_MEASUREITEM:
{
LPMEASUREITEMSTRUCT lpmis = (LPMEASUREITEMSTRUCT) lParam ;
#if 0
DEBUGMSG("WM_MEASUREITEM: ctlId=%u, itemId=%u, itemWidth=%u, itemHeight=%u", lpmis->CtlID, lpmis->itemID, lpmis->itemWidth, lpmis->itemHeight);
#endif
HDC hdc = GetDC(ghWndList);
LBITEM * plbi = (LBITEM*)lpmis->itemData;
lpmis->itemHeight = CalcItemHeight(hdc, plbi->szTitle, plbi->pszDescription, plbi->szRTF, lenx);
ReleaseDC(ghWndList, hdc);
return TRUE;
}
case WM_PAINT:
PAINTSTRUCT ps;
RECT borderRect;
BeginPaint(hDlg, &ps);
GetClientRect(hDlg, &borderRect);
DrawEdge(ps.hdc, &borderRect, EDGE_ETCHED, BF_RECT);
EndPaint(hDlg, &ps);
break;
case WM_NEXTDLGCTL:
PostMessage(GetParent(hDlg), WM_NEXTDLGCTL, 0, 0L);
return 0;
case WM_KEYUP:
//DEBUGMSG("MYLB got KEYUP key %d", wParam);
switch(wParam)
{
case VK_TAB:
case VK_DOWN:
case VK_UP:
SetFocus(ghWndList);
return 0;
default:
break;
}
break;
case WM_VKEYTOITEM:
{
//DEBUGMSG("WM_VKEYTOITEM got char %d", LOWORD(wParam));
if (LOWORD(wParam) != VK_SPACE)
{
return -1;
}
if (MYLB_FOCUS_TITLE == gFocus)
{
int i = (LONG)SendMessage(ghWndList, LB_GETCURSEL, 0, 0);
if (LB_ERR == i)
{
return -2;
}
item = (LBITEM*)SendMessage(ghWndList, LB_GETITEMDATA, i, 0);
if (!s_fSelectionDisabled)
{
ToggleSelection(hDlg, ghWndList, item);
}
return -2;
}
if (MYLB_FOCUS_RTF == gFocus)
{
LaunchRTF(ghWndList);
}
return -2;
}
case WM_DRAWITEM:
{
LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT) lParam;
#if 0
DEBUGMSG("WM_DRAWITEM: ctlId=%u, itemId=%u, rcItem=(%d, %d)-(%d, %d)", lpdis->CtlID, lpdis->itemID, lpdis->rcItem.left, lpdis->rcItem.top, lpdis->rcItem.right, lpdis->rcItem.bottom);
#endif
// If there are no list box items, skip this message.
if (lpdis->itemID == -1)
{
break;
}
// Draw the bitmap and text for the list box item. Draw a
// rectangle around the bitmap if it is selected.
switch (lpdis->itemAction)
{
case ODA_SELECT:
case ODA_DRAWENTIRE:
//DEBUGMSG("MYLB WM_DRAWITEM ODA_DRAWENTIRE for %d", lpdis->itemID);
DrawItem(lpdis, s_fSelectionDisabled);
DrawMYLBFocus(ghWndList, lpdis, gFocus, gFocusItemId);
break;
case ODA_FOCUS:
if (lpdis->itemID != gFocusItemId)
{
gFocusItemId = lpdis->itemID;
gFocus = MYLB_FOCUS_TITLE;
}
//DEBUGMSG("MYLB ODA_FOCUS change focus to %d", gFocusItemId);
DrawItem(lpdis, s_fSelectionDisabled);
DrawMYLBFocus(ghWndList, lpdis, gFocus, gFocusItemId);
break;
}
return TRUE;
}
case WM_DESTROY:
// need to cleanup the fonts
if (ghFontBold)
DeleteObject(ghFontBold);
if (ghFontUnderline)
DeleteObject(ghFontUnderline);
if (ghFontNormal)
DeleteObject(ghFontNormal);
if (ghBmpCheck)
DeleteObject(ghBmpCheck);
if (ghBmpGrayOut)
DeleteObject(ghBmpGrayOut);
if (ghBmpClear)
DeleteObject(ghBmpClear);
ghFontNormal = NULL;
ghFontBold = NULL;
ghFontUnderline = NULL;
ghBmpCheck = NULL;
ghBmpGrayOut = NULL;
ghBmpClear = NULL;
EnterCriticalSection(&gcsClient);
RemoveProp( ghWndList, MYLBALIVEPROP );
clb = (LONG)SendMessage(ghWndList, LB_GETCOUNT, 0, 0);
for(int i = 0; i < clb; i++)
{
item = (LBITEM*)SendMessage(ghWndList, LB_GETITEMDATA, i, 0);
delete(item);
}
LeaveCriticalSection(&gcsClient);
return 0;
}
return DefWindowProc(hDlg, message, wParam, lParam);
}
void DrawTitle(HDC hDC, LBITEM * plbi, RECT rc)
{
// we want the bitmap to be on the same background as the title, let's do this here since we
// already have all the measures.
RECT rcTop = rc;
rcTop.left = 0;
// draw menu background rectangle for the title and bitmap
HBRUSH hBrush;
if (! (hBrush = CreateSolidBrush(GetSysColor(COLOR_MENU))))
{
DEBUGMSG("WUAUCLT CreateSolidBrush failure in DrawTitle, GetLastError=%lu", GetLastError());
return;
}
FillRect(hDC, (LPRECT)&rcTop, hBrush);
if (NULL != hBrush)
{
DeleteObject(hBrush);
}
// draw 3d look
DrawEdge(hDC, &rcTop, EDGE_ETCHED, BF_RECT);
// change text and back ground color of list box's selection
DWORD dwOldTextColor = SetTextColor(hDC, GetSysColor(COLOR_MENUTEXT)); // black text color
DWORD dwOldBkColor = SetBkColor(hDC, GetSysColor(COLOR_MENU)); // text cell light gray background
HFONT hFontPrev = (HFONT)SelectObject(hDC, ghFontBold);
rc.left += TITLE_MARGIN;
rc.top += SECTION_SPACING;
rc.right -= TITLE_MARGIN;
rc.bottom -= SECTION_SPACING;
DrawText(hDC, (LPTSTR)plbi->szTitle, -1,
&rc, DT_WORDBREAK | DT_NOPREFIX);
// restore text and back ground color of list box's selection
SetTextColor(hDC, dwOldTextColor);
SetBkColor(hDC, dwOldBkColor);
SelectObject(hDC, hFontPrev);
return;
}
void DrawRTF(HDC hDC, LBITEM * plbi, const RECT & rc /*,BOOL fHit*/)
{
if (!plbi->bRTF)
return;
//draw RTF background
RECT rcBackGround;
CalcRTFFocusRect(rc, rcBackGround);
HBRUSH hBrush;
if (!(hBrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW))))
{
DEBUGMSG("WUAUCLT CreateSolidBrush failure in DrawRTF, GetLastError=%lu", GetLastError());
return;
}
if (!FillRect(hDC, (LPRECT)&rcBackGround, hBrush))
{
DEBUGMSG("Fail to erase RTF background");
}
if (NULL != hBrush)
{
DeleteObject(hBrush);
}
HFONT hFontPrev = (HFONT) SelectObject(hDC, ghFontUnderline);
DWORD dwOldTextColor = SetTextColor(hDC, GetSysColor(ATTENTION_COLOR));
SetBkMode(hDC, TRANSPARENT);
// add the read this first
TextOut(hDC, (int)(rc.left), (int)(rc.top),
(LPTSTR)plbi->szRTF, lstrlen(plbi->szRTF));
// restore text and back ground color of list box's selection
SetTextColor(hDC, dwOldTextColor);
SelectObject(hDC, hFontPrev);
return;
}
void DrawDescription(HDC hDC, LBITEM * plbi, RECT & rc)
{
#if 0
DEBUGMSG("draw \"%S\" (%d, %d) - (%d, %d)", (LPTSTR)plbi->pszDescription, rc.left, rc.top, rc.right, rc.bottom);
#endif
HFONT hFontPrev = (HFONT)SelectObject(hDC, ghFontNormal);
DrawText(hDC, (LPTSTR)plbi->pszDescription, -1,
&rc, DT_BOTTOM | DT_EXPANDTABS | DT_WORDBREAK | DT_EDITCONTROL | DT_NOPREFIX);
SelectObject(hDC, hFontPrev);
return;
}
void DrawBitmap(HDC hDC, LBITEM * plbi, const RECT & rc, BOOL fSel, BOOL fSelectionDisabled)
{
HDC hdcMem;
plbi->bSelect = fSel;
if (hdcMem = CreateCompatibleDC(hDC))
{
HGDIOBJ hBmp;
if (fSelectionDisabled)
{
hBmp = ghBmpGrayOut;
// DEBUGMSG("Set bitmap to grayout");
}
else
{
// DEBUGMSG("Set bitmap to selectable");
hBmp = (plbi->bSelect ? ghBmpCheck : ghBmpClear);
}
HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcMem, hBmp);
BitBlt(hDC,
rc.left + 3, rc.top + SECTION_SPACING,
rc.right - rc.left,
rc.bottom - rc.top,
hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, hbmpOld);
DeleteDC(hdcMem);
}
}
BOOL GetBmpSize(HANDLE hBmp, SIZE *psz)
{
if (NULL == hBmp || NULL == psz)
{
DEBUGMSG("Error: GetBmpSize() invalid parameter");
return FALSE;
}
BITMAP bm;
ZeroMemory(&bm, sizeof(bm));
if (0 == GetObject(hBmp, sizeof(bm), &bm))
{
return FALSE;
}
psz->cx = bm.bmWidth;
psz->cy = bm.bmHeight;
return TRUE;
}
//fixcode: should return error code
void AddItem(LPTSTR tszTitle, LPTSTR tszDesc, LPTSTR tszRTF, int index, BOOL fSelected, BOOL fRTF)
{
LBITEM *newItem = new(LBITEM);
if (! newItem)
{
DEBUGMSG("WUAUCLT new() failed in AddItem, GetLastError=%lu", GetLastError());
goto Failed;
}
DWORD dwDescLen = max(lstrlen(tszDesc), MAX_DESC_LENGTH);
newItem->pszDescription = (LPTSTR) malloc((dwDescLen+1) * sizeof(TCHAR));
if (NULL == newItem->pszDescription)
{
DEBUGMSG("AddItem() fail to alloc memory for description");
goto Failed;
}
(void)StringCchCopyEx(newItem->szTitle, ARRAYSIZE(newItem->szTitle), tszTitle, NULL, NULL, MISTSAFE_STRING_FLAGS);
(void)StringCchCopyEx(newItem->pszDescription, dwDescLen+1, tszDesc, NULL, NULL, MISTSAFE_STRING_FLAGS);
(void)StringCchCopyEx(newItem->szRTF, ARRAYSIZE(newItem->szRTF), tszRTF, NULL, NULL, MISTSAFE_STRING_FLAGS);
newItem->m_index = index;
newItem->bSelect = fSelected;
newItem->bRTF = fRTF;
LRESULT i = SendMessage(ghWndList, LB_GETCOUNT, 0, 0);
if (LB_ERR == i ||
LB_ERR == (i = SendMessage(ghWndList, LB_INSERTSTRING, (WPARAM) i, (LPARAM) newItem->szTitle)) ||
LB_ERRSPACE == i ||
LB_ERR == SendMessage(ghWndList, LB_SETITEMDATA, (WPARAM) i, (LPARAM) newItem))
{
DEBUGMSG("WUAUCLT AddItem() fail to add item to listbox");
goto Failed;
}
return;
Failed:
SafeDelete(newItem);
QuitNRemind(TIMEOUT_INX_TOMORROW);
}
////////////////////////////////////////////////////
// utility function
// calculate the height of a paragraph in current
// device context
////////////////////////////////////////////////////
UINT GetParagraphHeight(HDC hDC, LPTSTR tszPara, int nLineWidth, UINT uExtraFormat = 0)
{
UINT y = 0;
if (0 == nLineWidth)
{
return 0;
}
RECT rc;
ZeroMemory(&rc, sizeof(rc));
rc.right = nLineWidth;
if (0 == DrawText(hDC, tszPara, -1, &rc, DT_WORDBREAK | DT_NOPREFIX | DT_NOCLIP | DT_CALCRECT | uExtraFormat))
{
DEBUGMSG("failed to calc paragraph height w/ error %ld", GetLastError());
return 0;
}
#if 0
else
{
DEBUGMSG("para \"%S\" line-width=%lu (%d, %d) - (%d, %d)", tszPara, nLineWidth, rc.left, rc.top, rc.right, rc.bottom);
}
#endif
return rc.bottom - rc.top + 1;
}
int CalcDescHeight(HDC hDC, LPTSTR ptszDescription, int cx)
{
int y = 0;
HFONT hPrevFont = NULL;
hPrevFont = (HFONT) SelectObject(hDC, ghFontNormal);
y = GetParagraphHeight(hDC, ptszDescription, cx, DT_BOTTOM | DT_EXPANDTABS | DT_EDITCONTROL);
SelectObject(hDC, hPrevFont);
return y;
}
int CalcRTFHeight(HDC hDC, LPTSTR ptszRTF)
{
SIZE sz ;
ZeroMemory(&sz, sizeof(sz));
HFONT hPrevFont = (HFONT) SelectObject(hDC, ghFontUnderline);
//fixcode: check return value of GetTextExtentPoint32()
GetTextExtentPoint32(hDC, ptszRTF, lstrlen(ptszRTF), &sz);
SelectObject(hDC, hPrevFont);
return sz.cy;
}
int CalcRTFWidth(HDC hDC, LPTSTR ptszRTF)
{
SIZE sz;
HFONT hPrevFont = (HFONT) SelectObject(hDC, ghFontUnderline);
//fixcode: check return value of GetTextExtentPoint32()
GetTextExtentPoint32(hDC, ptszRTF, lstrlen(ptszRTF), &sz);
SelectObject(hDC, hPrevFont);
return sz.cx;
}
int CalcTitleHeight(HDC hDC, LPTSTR ptszTitle, int cx)
{
INT y = 0;
INT iBmpHeight = 0;
HFONT hPrevFont = (HFONT) SelectObject(hDC, ghFontBold);
y = GetParagraphHeight(hDC, ptszTitle, cx);
SelectObject(hDC, hPrevFont);
// get checkbox size
if (NULL != ghBmpCheck && NULL != ghBmpClear && NULL != ghBmpGrayOut)
{
SIZE sz1 ;
SIZE sz2 ;
SIZE sz3 ;
sz1.cy = sz2.cy = sz3.cy = DEF_CHECK_HEIGHT;
GetBmpSize(ghBmpCheck, &sz1);
GetBmpSize(ghBmpClear, &sz2);
GetBmpSize(ghBmpGrayOut, &sz3);
iBmpHeight = max(sz1.cy, sz2.cy);
iBmpHeight = max(iBmpHeight, sz3.cy);
}
return max(y, iBmpHeight); //make title height a little bigger for clearer focus rect
}
int CalcItemHeight(HDC hdc, LPTSTR ptszTitle, LPTSTR ptszDescription, LPTSTR ptszRTF, int cx)
{
return CalcTitleHeight(hdc, ptszTitle, cx - XBITMAP - 2* TITLE_MARGIN)
+ CalcDescHeight(hdc, ptszDescription, cx - XBITMAP )
+ CalcRTFHeight(hdc, ptszRTF) + 4 * SECTION_SPACING;
}
////////////////////////////////////////////////////////////
/// Layout of listbox item:
/// spacing
/// bitmap margin TITLE margin
/// spacing
/// DESCRIPTION
/// spacing
/// RTF rtf_margin
/// spacing
///////////////////////////////////////////////////////////
void CalcItemLocation(HDC hDC, LBITEM * plbi, const RECT & rc)
{
// Calculate the positon of each element
plbi->rcItem = rc;
plbi->rcTitle = rc;
plbi->rcTitle.left += XBITMAP ;
plbi->rcTitle.bottom = plbi->rcTitle.top + CalcTitleHeight(hDC, plbi->szTitle, plbi->rcTitle.right - plbi->rcTitle.left - 2* TITLE_MARGIN)
+ 2 * SECTION_SPACING;
plbi->rcText = rc;
plbi->rcText.left = plbi->rcTitle.left;
plbi->rcText.right = plbi->rcTitle.right;
plbi->rcText.top = plbi->rcTitle.bottom;
int nRtfHeight = CalcRTFHeight(hDC, plbi->szRTF);
plbi->rcText.bottom -= nRtfHeight + SECTION_SPACING; //
plbi->rcRTF = plbi->rcText;
plbi->rcRTF.top = plbi->rcText.bottom;
plbi->rcRTF.bottom = plbi->rcRTF.top + nRtfHeight;
plbi->rcRTF.right = plbi->rcText.right - RTF_MARGIN;
plbi->rcRTF.left = plbi->rcRTF.right - CalcRTFWidth(hDC, plbi->szRTF);
plbi->rcBitmap = rc;
plbi->rcBitmap.bottom = plbi->rcTitle.bottom;
return;
}
| 30.164617
| 188
| 0.59475
|
npocmaka
|
e5a9272774f3c2af98b49b6bc3803df1d49c988e
| 3,815
|
cpp
|
C++
|
src/renderEffects/auraCompositing.cpp
|
mfirmin/xray-vision
|
c40fc300d95d55c15f0dffa484b7123eb69238b5
|
[
"MIT"
] | 1
|
2021-09-13T20:22:29.000Z
|
2021-09-13T20:22:29.000Z
|
src/renderEffects/auraCompositing.cpp
|
mfirmin/xray-vision
|
c40fc300d95d55c15f0dffa484b7123eb69238b5
|
[
"MIT"
] | null | null | null |
src/renderEffects/auraCompositing.cpp
|
mfirmin/xray-vision
|
c40fc300d95d55c15f0dffa484b7123eb69238b5
|
[
"MIT"
] | 1
|
2021-09-13T20:22:31.000Z
|
2021-09-13T20:22:31.000Z
|
#include "auraCompositing.hpp"
#include "gl/shaderUtils.hpp"
#include "light/light.hpp"
#include <array>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <string>
#include <sstream>
AuraCompositingEffect::AuraCompositingEffect(int w, int h) :
width(w), height(h)
{
}
void AuraCompositingEffect::initialize() {
createDebugProgram();
createProgram();
createArrayObjects();
}
AuraCompositingEffect::~AuraCompositingEffect() {
// TODO: Free buffers
}
void AuraCompositingEffect::createArrayObjects() {
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vertexBuffer);
glGenBuffers(1, &uvBuffer);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
// NDC Coords
std::vector<float> vertices = {
-1.0f, -1.0f,
1.0f, -1.0f,
-1.0f, 1.0f,
1.0f, 1.0f
};
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GL_FLOAT), vertices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, uvBuffer);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
std::vector<float> uvs = {
0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f
};
glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(GL_FLOAT), uvs.data(), GL_STATIC_DRAW);
}
void AuraCompositingEffect::createDebugProgram() {
std::string vertexShaderSource = R"(
#version 330
layout(location = 0) in vec2 position;
layout(location = 1) in vec2 uv;
out vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position, 0.0, 1.0);
}
)";
std::string fragmentShaderSource = R"(
#version 330
uniform sampler2D input;
in vec2 vUv;
out vec4 fragColor;
void main() {
vec3 color = texture(input, vUv).rgb;
color = color + vec3(1.0) * 0.5;
fragColor = vec4(color, 1.0);
}
)";
debugProgram = ShaderUtils::compile(vertexShaderSource, fragmentShaderSource);
}
void AuraCompositingEffect::createProgram() {
std::string vertexShaderSource = R"(
#version 330
layout(location = 0) in vec2 position;
layout(location = 1) in vec2 uv;
out vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position, 0.0, 1.0);
}
)";
std::string fragmentShaderSource = R"(
#version 330
uniform mat4 viewMatrix;
uniform sampler2D scene;
uniform sampler2D aura;
in vec2 vUv;
out vec4 fragColor;
void main() {
vec4 sceneColor = texture(scene, vUv);
vec4 auraColor = texture(aura, vUv);
fragColor = vec4(mix(sceneColor.rgb, auraColor.rgb, auraColor.a), 1.0);
}
)";
program = ShaderUtils::compile(vertexShaderSource, fragmentShaderSource);
}
void AuraCompositingEffect::render(GLuint sceneTexture, GLuint auraTexture) {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClearColor(0.0, 0.0, 0.0, 1.0);
// Clear it
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// render the screen object to it
glBindVertexArray(vao);
auto prog = program;
// use the debug program from the deferred target (just render 1 property)
glUseProgram(prog);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, sceneTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, auraTexture);
glUniform1i(glGetUniformLocation(prog, "scene"), 0);
glUniform1i(glGetUniformLocation(prog, "aura"), 1);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glUseProgram(0);
}
| 23.404908
| 103
| 0.627785
|
mfirmin
|
e5b01e0b2838076f577fed8c236caabd12886b77
| 1,409
|
cpp
|
C++
|
src/drone_marker_pub.cpp
|
i3drobotics/kimera_rviz_markers
|
e1de992b98dc28f508376dc5736e48efa894c90d
|
[
"MIT"
] | 2
|
2019-09-22T09:20:56.000Z
|
2019-12-12T11:40:03.000Z
|
src/drone_marker_pub.cpp
|
i3drobotics/kimera_rviz_markers
|
e1de992b98dc28f508376dc5736e48efa894c90d
|
[
"MIT"
] | 2
|
2020-01-16T12:56:04.000Z
|
2020-05-21T17:19:44.000Z
|
src/drone_marker_pub.cpp
|
i3drobotics/kimera_rviz_markers
|
e1de992b98dc28f508376dc5736e48efa894c90d
|
[
"MIT"
] | 5
|
2019-09-23T18:16:40.000Z
|
2021-07-03T14:21:29.000Z
|
#include "kimera_rviz_markers/kimera_rviz_markers.h"
int main(int argc, char** argv) {
// Initialize ROS node
ros::init(argc, argv, "drone_marker_pub");
ros::NodeHandle nh_;
ros::NodeHandle nh_private_ ("~");
krm::DroneParams quad_params;
nh_private_.getParam("frame_id", quad_params.frame_id);
nh_private_.getParam("scale", quad_params.scale);
nh_private_.getParam("num_rotors", quad_params.num_rotors);
nh_private_.getParam("arm_len", quad_params.arm_len);
nh_private_.getParam("body_width", quad_params.body_width);
nh_private_.getParam("body_height", quad_params.body_height);
nh_private_.getParam("r_color", quad_params.r_color);
nh_private_.getParam("g_color", quad_params.g_color);
nh_private_.getParam("b_color", quad_params.b_color);
tf::Vector3 position (0, 0, 0);
ros::Time timestamp = ros::Time();
std::vector<visualization_msgs::Marker> drone_markers =
krm::makeDroneMarkers(timestamp, quad_params);
ros::Rate rate (20);
ros::Publisher drone_marker_pub =
nh_.advertise<visualization_msgs::MarkerArray>("drone_markers", 10, true);
while(ros::ok()) {
if (drone_marker_pub.getNumSubscribers() > 0) {
visualization_msgs::MarkerArray msg;
msg.markers = drone_markers;
drone_marker_pub.publish(msg);
}
ros::spinOnce();
rate.sleep();
}
ROS_INFO("Exiting drone marker publisher.");
return EXIT_SUCCESS;
}
| 32.767442
| 80
| 0.726757
|
i3drobotics
|
e5b2c5518f46c1344445a67cd64dc67eb029a489
| 5,117
|
cpp
|
C++
|
test/block.cpp
|
MaskRay/asteria
|
56a9251f5bb80b92e5aff25eac145f8cd2495096
|
[
"BSD-3-Clause"
] | null | null | null |
test/block.cpp
|
MaskRay/asteria
|
56a9251f5bb80b92e5aff25eac145f8cd2495096
|
[
"BSD-3-Clause"
] | null | null | null |
test/block.cpp
|
MaskRay/asteria
|
56a9251f5bb80b92e5aff25eac145f8cd2495096
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is part of Asteria.
// Copyleft 2018, LH_Mouse. All wrongs reserved.
#include "_test_init.hpp"
#include "../asteria/src/block.hpp"
#include "../asteria/src/xpnode.hpp"
#include "../asteria/src/statement.hpp"
#include "../asteria/src/global_context.hpp"
#include "../asteria/src/executive_context.hpp"
using namespace Asteria;
int main()
{
Vector<Statement> text;
// var res = 0;
Vector<Xpnode> expr;
expr.emplace_back(Xpnode::S_literal { D_integer(0) });
text.emplace_back(Statement::S_var_def { String::shallow("res"), false, std::move(expr) });
// const data = [ 1, 2, 3, 2 * 5 ];
expr.clear();
expr.emplace_back(Xpnode::S_literal { D_integer(1) });
expr.emplace_back(Xpnode::S_literal { D_integer(2) });
expr.emplace_back(Xpnode::S_literal { D_integer(3) });
expr.emplace_back(Xpnode::S_literal { D_integer(2) });
expr.emplace_back(Xpnode::S_literal { D_integer(5) });
expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_mul, false });
expr.emplace_back(Xpnode::S_unnamed_array { 4 });
text.emplace_back(Statement::S_var_def { String::shallow("data"), true, std::move(expr) });
// for(each k, v in data) {
// res += k * v;
// }
Vector<Xpnode> range;
range.emplace_back(Xpnode::S_named_reference { String::shallow("data") });
expr.clear();
expr.emplace_back(Xpnode::S_named_reference { String::shallow("res") });
expr.emplace_back(Xpnode::S_named_reference { String::shallow("k") });
expr.emplace_back(Xpnode::S_named_reference { String::shallow("v") });
expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_mul, false });
expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_add, true });
Vector<Statement> body;
body.emplace_back(Statement::S_expr { std::move(expr) });
text.emplace_back(Statement::S_for_each { String::shallow("k"), String::shallow("v"), std::move(range), std::move(body) });
// for(var j = 0; j <= 3; ++j) {
// res += data[j];
// if(data[j] == 2) {
// break;
// }
// }
body.clear();
expr.clear();
expr.emplace_back(Xpnode::S_named_reference { String::shallow("res") });
expr.emplace_back(Xpnode::S_named_reference { String::shallow("data") });
expr.emplace_back(Xpnode::S_named_reference { String::shallow("j") });
expr.emplace_back(Xpnode::S_subscript { String::shallow("") });
expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_add, true });
body.emplace_back(Statement::S_expr { std::move(expr) });
expr.clear();
expr.emplace_back(Xpnode::S_named_reference { String::shallow("data") });
expr.emplace_back(Xpnode::S_named_reference { String::shallow("j") });
expr.emplace_back(Xpnode::S_subscript { String::shallow("") });
expr.emplace_back(Xpnode::S_literal { D_integer(2) });
expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_cmp_eq, false });
Vector<Statement> branch_true;
branch_true.emplace_back(Statement::S_break { Statement::target_unspec });
body.emplace_back(Statement::S_if { std::move(expr), std::move(branch_true), Block() });
expr.clear();
expr.emplace_back(Xpnode::S_literal { D_integer(0) });
Vector<Statement> init;
init.emplace_back(Statement::S_var_def { String::shallow("j"), false, std::move(expr) });
Vector<Xpnode> cond;
cond.emplace_back(Xpnode::S_named_reference { String::shallow("j") });
cond.emplace_back(Xpnode::S_literal { D_integer(3) });
cond.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_cmp_lte, false });
Vector<Xpnode> step;
step.emplace_back(Xpnode::S_named_reference { String::shallow("j") });
step.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_prefix_inc, false });
text.emplace_back(Statement::S_for { std::move(init), std::move(cond), std::move(step), std::move(body) });
auto block = Block(std::move(text));
Global_context global;
Executive_context ctx;
Reference ref;
auto status = block.execute_in_place(ref, ctx, global);
ASTERIA_TEST_CHECK(status == Block::status_next);
auto qref = ctx.get_named_reference_opt(String::shallow("res"));
ASTERIA_TEST_CHECK(qref != nullptr);
ASTERIA_TEST_CHECK(qref->read().check<D_integer>() == 41);
qref = ctx.get_named_reference_opt(String::shallow("data"));
ASTERIA_TEST_CHECK(qref != nullptr);
ASTERIA_TEST_CHECK(qref->read().check<D_array>().size() == 4);
ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(0).check<D_integer>() == 1);
ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(1).check<D_integer>() == 2);
ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(2).check<D_integer>() == 3);
ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(3).check<D_integer>() == 10);
qref = ctx.get_named_reference_opt(String::shallow("k"));
ASTERIA_TEST_CHECK(qref == nullptr);
qref = ctx.get_named_reference_opt(String::shallow("v"));
ASTERIA_TEST_CHECK(qref == nullptr);
qref = ctx.get_named_reference_opt(String::shallow("j"));
ASTERIA_TEST_CHECK(qref == nullptr);
}
| 49.679612
| 127
| 0.676959
|
MaskRay
|
e5b47aedd92161daa823caa61d248330e8358f2f
| 17,987
|
cpp
|
C++
|
src/app/screens/application/main_menu_screen.cpp
|
lili2012/BarbersAndRebarbs
|
8a3c10cebded55dabaf6f8673735c6f3606cb4af
|
[
"MIT"
] | 4
|
2016-04-26T20:25:07.000Z
|
2021-12-15T06:58:57.000Z
|
src/app/screens/application/main_menu_screen.cpp
|
lili2012/BarbersAndRebarbs
|
8a3c10cebded55dabaf6f8673735c6f3606cb4af
|
[
"MIT"
] | 2
|
2016-07-29T22:52:12.000Z
|
2016-09-22T08:30:29.000Z
|
src/app/screens/application/main_menu_screen.cpp
|
lili2012/BarbersAndRebarbs
|
8a3c10cebded55dabaf6f8673735c6f3606cb4af
|
[
"MIT"
] | 1
|
2020-10-31T10:20:32.000Z
|
2020-10-31T10:20:32.000Z
|
// The MIT License (MIT)
// Copyright (c) 2015 nabijaczleweli
// 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 "main_menu_screen.hpp"
#include "../../../game/firearm/firearm.hpp"
#include "../../../reference/container.hpp"
#include "../../../reference/joystick_info.hpp"
#include "../../../util/file.hpp"
#include "../../../util/sound.hpp"
#include "../../../util/url.hpp"
#include "../../../util/zstd.hpp"
#include "../../application.hpp"
#include "../game/main_game_screen.hpp"
#include <cmath>
#include <fmt/format.h>
#include <iostream>
#include <jsonpp/parser.hpp>
#include <semver/semver200.h>
using namespace std::literals;
void main_menu_screen::move_selection(main_menu_screen::direction dir, bool end = false) {
const auto max_idx = main_buttons.size() - 1;
auto desired_selection = selected;
switch(dir) {
case direction::up:
if(end)
desired_selection = max_idx;
else
desired_selection = selected + 1;
break;
case direction::down:
if(selected && !end)
desired_selection = selected - 1;
else
desired_selection = 0;
break;
}
desired_selection = std::min(max_idx, desired_selection);
if(app_configuration.play_sounds) {
if(desired_selection != selected)
selected_option_switch_sound->play();
else
selected_option_unchanged_sound->play();
}
selected = desired_selection;
}
void main_menu_screen::press_button() {
if(app_configuration.play_sounds)
selected_option_select_sound->play();
auto itr = main_buttons.begin();
advance(itr, selected);
(itr->second)(itr->first);
}
void main_menu_screen::try_drawings() {
if(!(control_frames_counter++ % 10)) {
control_frames_counter = 0;
if(joystick_drawing.first != sf::Joystick::isConnected(0)) {
joystick_drawing.first ^= 1;
joystick_drawing.second.move(0, joystick_drawing.second.size().y * .55f * (joystick_drawing.first ? 1 : -1));
keys_drawing.move(0, joystick_drawing.second.size().y * .55f * (joystick_drawing.first ? -1 : 1));
}
}
}
void main_menu_screen::load_game(sf::Text & txt, const std::string & save_path) {
const auto data = decompress_file_to_string(save_path);
if(!std::get<1>(data))
txt.setString(global_iser.translate_key("gui.main_menu.text.load_file_inaccessible"));
else if(const auto err_s = std::get<2>(data))
txt.setString(fmt::format(global_iser.translate_key("gui.main_menu.text.load_decompression_error"), err_s));
else {
json::value save;
json::parse(std::get<0>(data), save);
app.schedule_screen<main_game_screen>(save.as<json::object>());
}
}
void main_menu_screen::set_default_menu_items() {
main_buttons.clear();
main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.start"), font_swirly),
[&](sf::Text &) { app.schedule_screen<main_game_screen>(); });
main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.load"), font_swirly), [&](sf::Text & txt) {
main_buttons.clear();
main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.back"), font_swirly), [&](sf::Text &) { set_default_menu_items(); });
for(auto && fname : [] {
auto saves = list_files(saves_root);
std::sort(saves.begin(), saves.end());
return saves;
}())
main_buttons.emplace_front(sf::Text(fname.substr(0, fname.rfind('.')), font_swirly),
[&, fname = fname ](sf::Text &) { load_game(txt, saves_root + '/' + fname); });
selected = main_buttons.size() - 1;
});
main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text."s + (app_configuration.play_sounds ? "" : "un") + "mute"), font_swirly),
[&](sf::Text & txt) {
app_configuration.play_sounds = !app_configuration.play_sounds;
txt.setString(global_iser.translate_key("gui.main_menu.text."s + (app_configuration.play_sounds ? "" : "un") + "mute"));
app.retry_music();
});
main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.configure"), font_swirly), [&](sf::Text &) { set_config_menu_items(); });
main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.quit"), font_swirly), [&](sf::Text &) { app.window.close(); });
selected = main_buttons.size() - 1;
}
void main_menu_screen::set_config_menu_items() {
main_buttons.clear();
bool music_volume_changed = false;
const auto langs = config::available_languages();
const std::size_t cur_lang_idx = std::distance(langs.begin(), std::find(langs.begin(), langs.end(), app_configuration.language));
const auto volume_func = [&](const char * key, float & volume, auto additional) {
return [&, key, additional](sf::Text & text) {
volume += .05f;
if(volume > 1.f)
volume = 0.f;
additional(volume);
text.setString(fmt::format(global_iser.translate_key(key), volume * 100.f));
};
};
main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.back"), font_swirly), [&](sf::Text &) {
local_iser = cpp_localiser::localiser(localization_root, app_configuration.language);
global_iser = cpp_localiser::localiser(local_iser, fallback_iser);
if(music_volume_changed)
app.retry_music();
set_default_menu_items();
});
main_buttons.emplace_front(sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_lang"), app_configuration.language), font_pixelish, 20),
[&, langs = std::move(langs), idx = cur_lang_idx ](sf::Text & text) mutable {
++idx;
if(idx == langs.size())
idx = 0;
app_configuration.language = langs[idx];
text.setString(fmt::format(global_iser.translate_key("gui.main_menu.text.config_lang"), app_configuration.language));
});
main_buttons.emplace_front(
sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_controller_deadzone"), app_configuration.controller_deadzone), font_pixelish,
20),
[&](sf::Text & text) {
app_configuration.controller_deadzone += 5;
if(app_configuration.controller_deadzone > 100)
app_configuration.controller_deadzone = 0;
text.setString(fmt::format(global_iser.translate_key("gui.main_menu.text.config_controller_deadzone"), app_configuration.controller_deadzone));
});
main_buttons.emplace_front(
sf::Text(global_iser.translate_key("gui.main_menu.text.config_vsync_"s + (app_configuration.vsync ? "on" : "off")), font_pixelish, 20),
[&](sf::Text & text) {
app_configuration.vsync ^= 1;
text.setString(global_iser.translate_key("gui.main_menu.text.config_vsync_"s + (app_configuration.vsync ? "on" : "off")));
});
main_buttons.emplace_front(sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_fps"), app_configuration.FPS), font_pixelish, 20),
[&](sf::Text & text) {
app_configuration.FPS += 30;
if(app_configuration.FPS > 120)
app_configuration.FPS = 0;
text.setString(fmt::format(global_iser.translate_key("gui.main_menu.text.config_fps"), app_configuration.FPS));
});
main_buttons.emplace_front(
sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_music_volume"), app_configuration.music_volume * 100.f), font_pixelish, 20),
volume_func("gui.main_menu.text.config_music_volume", app_configuration.music_volume, [&](auto) { music_volume_changed = true; }));
main_buttons.emplace_front(
sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_sound_effect_volume"), app_configuration.sound_effect_volume * 100.f),
font_pixelish, 20),
volume_func("gui.main_menu.text.config_sound_effect_volume", app_configuration.sound_effect_volume, [&](auto vol) {
selected_option_switch_sound->setVolume(output_volume(vol * .8));
selected_option_select_sound->setVolume(output_volume(vol * .8));
update_ready_sound->setVolume(output_volume(vol * .8));
}));
main_buttons.emplace_front(sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_default_firearm"),
firearm::properties().at(app_configuration.player_default_firearm).name),
font_pixelish, 20),
[&, itr = firearm::properties().find(app_configuration.player_default_firearm) ](sf::Text & text) mutable {
++itr;
if(itr == firearm::properties().end())
itr = firearm::properties().begin();
app_configuration.player_default_firearm = itr->first;
text.setString(fmt::format(global_iser.translate_key("gui.main_menu.text.config_default_firearm"), itr->second.name));
});
selected = main_buttons.size() - 1;
}
void main_menu_screen::setup() {
screen::setup();
}
int main_menu_screen::loop() {
const auto & winsize = app.window.getSize();
unsigned int buttid = 0;
for(auto & button : main_buttons) {
const auto & btnbds = button.first.getGlobalBounds();
button.first.setPosition((winsize.x * (59.f / 60.f)) - btnbds.width,
(winsize.y * (7.f / 8.f)) - (buttid + 1) * btnbds.height - (winsize.y * ((buttid * 1.f) / 90.f)));
button.first.setFillColor((buttid == selected) ? sf::Color::Red : sf::Color::White);
++buttid;
}
if(std::get<3>(update) && std::get<0>(update).valid()) {
std::get<3>(update) = false;
std::get<1>(update) = std::thread([&] {
auto result = std::get<0>(update).get();
std::cout << result.header["X-RateLimit-Remaining"] << " GitHub API accesses left\n";
if(!(result.status_code >= 200 && result.status_code < 300))
std::get<2>(update).setString(fmt::format(global_iser.translate_key("gui.main_menu.text.update_connection_fail"), result.status_code));
else {
json::value newest_update;
json::parse(result.text, newest_update);
auto new_version_s = newest_update["tag_name"].as<std::string>();
new_version_s = new_version_s.substr(new_version_s.find_first_of("0123456789"));
if(version::Semver200_version(new_version_s) <= version::Semver200_version(BARBERSANDREBARBS_VERSION))
std::get<2>(update).setString(global_iser.translate_key("gui.main_menu.text.update_none_found"));
else {
if(app_configuration.play_sounds)
update_ready_sound->play();
std::get<2>(update).setString(fmt::format(global_iser.translate_key("gui.main_menu.text.update_found"), new_version_s));
main_buttons.emplace_back(
sf::Text(global_iser.translate_key("gui.main_menu.text.update"), font_swirly),
[&, url = newest_update["html_url"].as<std::string>() ](sf::Text &) {
if(!launch_browser(url)) {
main_buttons.clear();
main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.back"), font_swirly),
[&](sf::Text &) { set_default_menu_items(); });
main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.update_browser_fail_0"), font_pixelish, 20),
[&](sf::Text &) {});
main_buttons.emplace_front(sf::Text(url, font_pixelish, 20), [&](sf::Text & txt) { copy_to_clipboard(txt.getString()); });
main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.update_browser_fail_1"), font_pixelish, 20),
[&](sf::Text &) {});
selected = main_buttons.size() - 1;
}
});
}
}
});
}
return 0;
}
int main_menu_screen::draw() {
for(const auto & button : main_buttons)
app.window.draw(button.first);
try_drawings();
if(joystick_drawing.first)
app.window.draw(joystick_drawing.second);
app.window.draw(keys_drawing);
app.window.draw(std::get<2>(update));
return 0;
}
int main_menu_screen::handle_event(const sf::Event & event) {
if(int i = screen::handle_event(event))
return i;
switch(static_cast<int>(event.type)) {
case sf::Event::MouseMoved: {
unsigned int buttid = 0;
for(const auto & button : main_buttons) {
if(button.first.getGlobalBounds().contains(event.mouseMove.x, event.mouseMove.y)) {
if(app_configuration.play_sounds && selected != buttid)
selected_option_switch_sound->play();
selected = buttid;
break;
}
++buttid;
}
} break;
case sf::Event::MouseButtonPressed:
if(event.mouseButton.button == sf::Mouse::Left)
for(const auto & button : main_buttons)
if(button.first.getGlobalBounds().contains(event.mouseButton.x, event.mouseButton.y)) {
press_button();
break;
}
break;
case sf::Event::MouseWheelMoved:
move_selection((event.mouseWheel.delta > 0) ? direction::up : direction::down);
break;
case sf::Event::KeyPressed:
switch(static_cast<int>(event.key.code)) {
case sf::Keyboard::Key::Home:
move_selection(direction::up, true);
break;
case sf::Keyboard::Key::End:
move_selection(direction::down, true);
break;
case sf::Keyboard::Key::Up:
move_selection(direction::up);
break;
case sf::Keyboard::Key::Down:
move_selection(direction::down);
break;
case sf::Keyboard::Key::Return:
case sf::Keyboard::Key::Space:
press_button();
break;
}
break;
case sf::Event::JoystickMoved:
if(event.joystickMove.axis == X360_axis_mappings::LeftStickVertical || event.joystickMove.axis == X360_axis_mappings::DPadVertical) {
if(event.joystickMove.position && (event.joystickMove.position >= 25 || event.joystickMove.position <= -25)) {
if(joystick_up)
break;
joystick_up = true;
const int sign = event.joystickMove.position / std::abs(event.joystickMove.position);
move_selection((sign == ((event.joystickMove.axis == X360_axis_mappings::LeftStickVertical) ? X360_axis_up_right_mappings::LeftStickVertical
: X360_axis_up_right_mappings::DPadVertical))
? direction::up
: direction::down);
} else
joystick_up = false;
}
break;
case sf::Event::JoystickButtonPressed:
if(event.joystickButton.button == X360_button_mappings::A)
press_button();
break;
}
return 0;
}
main_menu_screen::main_menu_screen(application & theapp)
: screen(theapp), control_frames_counter(0), joystick_up(false), joystick_drawing(false, drawing("xbox", app.window.getSize())),
keys_drawing("keyboard", app.window.getSize()),
update(std::future<cpr::Response>(), std::thread(), sf::Text("", font_monospace, 10), app_configuration.use_network),
selected_option_switch_sound(
audiere::OpenSoundEffect(audio_device, (sound_root + "/main_menu/mouse_over.wav").c_str(), audiere::SoundEffectType::MULTIPLE)),
selected_option_unchanged_sound(
audiere::OpenSoundEffect(audio_device, (sound_root + "/main_menu/Alt_Fire_Switch.mp3").c_str(), audiere::SoundEffectType::MULTIPLE)),
selected_option_select_sound(
audiere::OpenSoundEffect(audio_device, (sound_root + "/main_menu/mouse_click.wav").c_str(), audiere::SoundEffectType::MULTIPLE)),
update_ready_sound(audiere::OpenSoundEffect(audio_device, (sound_root + "/main_menu/update.wav").c_str(), audiere::SoundEffectType::SINGLE)) {
selected_option_switch_sound->setVolume(output_volume(app_configuration.sound_effect_volume * .8));
selected_option_unchanged_sound->setVolume(output_volume(app_configuration.sound_effect_volume * .8));
selected_option_select_sound->setVolume(output_volume(app_configuration.sound_effect_volume * .8));
update_ready_sound->setVolume(output_volume(app_configuration.sound_effect_volume * .8));
if(app_configuration.use_network)
std::get<0>(update) =
cpr::GetAsync(cpr::Url("https://api.github.com/repos/nabijaczleweli/BarbersAndRebarbs/releases/latest"), cpr::Parameters{{"anon", "true"}});
keys_drawing.move(app.window.getSize().x / 4 - keys_drawing.size().x / 2, app.window.getSize().y / 2 - keys_drawing.size().y / 2);
joystick_drawing.second.move(app.window.getSize().x / 4 - joystick_drawing.second.size().x / 2,
app.window.getSize().y / 2 - joystick_drawing.second.size().y / 2);
set_default_menu_items();
}
main_menu_screen::~main_menu_screen() {
if(std::get<1>(update).joinable())
std::get<1>(update).join();
}
| 44.743781
| 158
| 0.666148
|
lili2012
|
e5b4ebd57e1b88ac6da16124de2c7ea201245b2a
| 59,846
|
cpp
|
C++
|
src/bitmask.cpp
|
leannejdong/MGOSDT
|
29559e5feb19490e77b11d0382558cd8529feba4
|
[
"BSD-3-Clause"
] | 1
|
2022-03-09T03:17:35.000Z
|
2022-03-09T03:17:35.000Z
|
src/bitmask.cpp
|
leannejdong/MGOSDT
|
29559e5feb19490e77b11d0382558cd8529feba4
|
[
"BSD-3-Clause"
] | null | null | null |
src/bitmask.cpp
|
leannejdong/MGOSDT
|
29559e5feb19490e77b11d0382558cd8529feba4
|
[
"BSD-3-Clause"
] | null | null | null |
#include "bitmask.hpp"
// ********************************
// ** Function Module Definition **
// ********************************
std::vector< std::vector<codeblock> > Bitmask::ranges = std::vector< std::vector<codeblock> >();
std::vector<size_t> Bitmask::hashes = std::vector<size_t>();
std::vector<char> Bitmask::counts = std::vector<char>();
// Pre-computed number of set bits for 4-bit sequences
// unsigned int Bitmask::bit_count[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
const bitblock Bitmask::bits_per_block = 8 * sizeof(bitblock);
const bitblock Bitmask::ranges_per_code = 8 * sizeof(codeblock) / log2((double)(8 * sizeof(rangeblock)));
const bitblock Bitmask::bits_per_range = log2((double)(8 * sizeof(rangeblock)));
tbb::scalable_allocator< bitblock > Bitmask::allocator = tbb::scalable_allocator< bitblock >();
bool Bitmask::integrity_check = true;
bool Bitmask::precomputed = false;
// @param blocks: the blocks containing bits
// @param size: the number of bits which are represented in blocks
// @modifies blocks will be set to have all bits be 1
void Bitmask::ones(bitblock * const blocks, unsigned int size) {
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
for (unsigned int i = 0; i < number_of_blocks; ++i) { blocks[i] = ~((bitblock)(0)); }
Bitmask::clean(blocks, number_of_blocks, block_offset);
}
// @param blocks: the blocks containing bits
// @param size: the number of bits which are represented in blocks
// @modifies blocks will be set to have all bits be 0
void Bitmask::zeros(bitblock * const blocks, unsigned int size) {
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
for (unsigned int i = 0; i < number_of_blocks; ++i) { blocks[i] = (bitblock)(0); }
Bitmask::clean(blocks, number_of_blocks, block_offset);
}
void Bitmask::copy(bitblock * const blocks, bitblock * const other_blocks, unsigned int size) {
if (blocks == other_blocks) { return; }
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(blocks, number_of_blocks, block_offset);
Bitmask::clean(other_blocks, number_of_blocks, block_offset);
for (unsigned int i = 0; i < number_of_blocks; ++i) { other_blocks[i] = blocks[i]; }
}
void Bitmask::block_layout(unsigned int size, unsigned int * number_of_blocks, unsigned int * block_offset) {
if (size == 0) {
* number_of_blocks = 1;
} else {
* number_of_blocks = size / (Bitmask::bits_per_block) + (int)(size % Bitmask::bits_per_block != 0);
}
*block_offset = size % (Bitmask::bits_per_block);
}
void Bitmask::clean(bitblock * const blocks, unsigned int number_of_blocks, unsigned int offset) {
if (offset == 0) { return; }
bitblock mask = ~((bitblock)(0)) >> (Bitmask::bits_per_block - offset);
blocks[number_of_blocks - 1] = blocks[number_of_blocks - 1] & mask;
}
unsigned int Bitmask::count(bitblock * const blocks, unsigned int size) {
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(blocks, number_of_blocks, block_offset);
return mpn_popcount(blocks, number_of_blocks);
}
// @note this returns the number of contiguous sequences of 1's
unsigned int Bitmask::words(bitblock * const blocks, unsigned int size) {
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(blocks, number_of_blocks, block_offset);
bool sign = Bitmask::get(blocks, size, 0);
unsigned int i = 0;
unsigned int j = Bitmask::scan(blocks, size, i, !sign);
unsigned int words = 0;
while (j <= size) {
if (sign) { ++words; }
if (j == size) { break; }
i = j;
sign = !sign;
j = Bitmask::scan(blocks, size, i, !sign);
}
return words;
}
void Bitmask::bit_and(bitblock * const blocks, bitblock * other_blocks, unsigned int size, bool flip) {
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(blocks, number_of_blocks, block_offset);
if (!flip) {
// Special Offload to GMP Implementation
mpn_and_n(other_blocks, other_blocks, blocks, number_of_blocks);
} else {
// Special Offload to GMP Implementation
mpn_nior_n(other_blocks, other_blocks, other_blocks, number_of_blocks);
mpn_nior_n(other_blocks, other_blocks, blocks, number_of_blocks);
}
}
void Bitmask::bit_or(bitblock * blocks, bitblock * other_blocks, unsigned int size, bool flip) {
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(blocks, number_of_blocks, block_offset);
if (!flip) {
// Special Offload to GMP Implementation
mpn_ior_n(other_blocks, other_blocks, blocks, number_of_blocks);
} else {
// Special Offload to GMP Implementation
mpn_nand_n(other_blocks, other_blocks, other_blocks, number_of_blocks);
mpn_nand_n(other_blocks, other_blocks, blocks, number_of_blocks);
}
}
void Bitmask::bit_xor(bitblock * const blocks, bitblock * other_blocks, unsigned int size, bool flip) {
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(blocks, number_of_blocks, block_offset);
if (!flip) {
// Special Offload to GMP Implementation
mpn_xor_n(other_blocks, other_blocks, blocks, number_of_blocks);
} else {
// Special Offload to GMP Implementation
mpn_xnor_n(other_blocks, other_blocks, blocks, number_of_blocks);
}
}
bool Bitmask::equals(bitblock * const blocks, bitblock * const other_blocks, unsigned int size, bool flip) {
if (blocks == other_blocks) { return true; }
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(blocks, number_of_blocks, block_offset);
Bitmask::clean(other_blocks, number_of_blocks, block_offset);
if (!flip) {
return mpn_cmp(blocks, other_blocks, number_of_blocks) == 0;
} else {
mpn_nand_n(blocks, blocks, blocks, number_of_blocks);
Bitmask::clean(blocks, number_of_blocks, block_offset);
bool equals = mpn_cmp(blocks, other_blocks, number_of_blocks) == 0;
mpn_nand_n(blocks, blocks, blocks, number_of_blocks);
Bitmask::clean(blocks, number_of_blocks, block_offset);
return equals;
}
}
int Bitmask::compare(bitblock * const left, bitblock * const right, unsigned int size) {
if (left == right) { return false; }
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(left, number_of_blocks, block_offset);
Bitmask::clean(right, number_of_blocks, block_offset);
return mpn_cmp(left, right, number_of_blocks);
}
bool Bitmask::less_than(bitblock * const left, bitblock * const right, unsigned int size) {
return Bitmask::compare(left, right, size) < 0;
}
bool Bitmask::greater_than(bitblock * const left, bitblock * const right, unsigned int size) {
return Bitmask::compare(left, right, size) > 0;
}
size_t Bitmask::hash(bitblock * const blocks, unsigned int size) {
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(blocks, number_of_blocks, block_offset);
bool sign = Bitmask::get(blocks, size, 0);
unsigned int i = 0;
unsigned int j = Bitmask::scan(blocks, size, i, !sign);
size_t seed = 1 * sign;
while (j <= size) {
seed ^= j - i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
if (j == size) { break; }
i = j;
sign = !sign;
j = Bitmask::scan(blocks, size, i, !sign);
}
return seed;
}
unsigned int Bitmask::get(bitblock * const blocks, unsigned int size, unsigned int index) {
if (Bitmask::integrity_check && (index < 0 || index >= size)) {
std::stringstream reason;
reason << "Index " << index << " is outside the valid range [" << 0 << "," << size - 1 << "].";
throw IntegrityViolation("Bitmask::get", reason.str());
}
unsigned int block_index = index / Bitmask::bits_per_block;
unsigned int bit_index = index % Bitmask::bits_per_block;
bitblock block = blocks[block_index];
return (block >> bit_index) & 1;
}
void Bitmask::set(bitblock * const blocks, unsigned int size, unsigned int index, bool value) {
if (Bitmask::integrity_check && (index < 0 || index >= size)) {
std::stringstream reason;
reason << "Index " << index << " is outside the valid range [" << 0 << "," << size - 1 << "].";
throw IntegrityViolation("Bitmask::get", reason.str());
}
unsigned int block_index = index / Bitmask::bits_per_block;
unsigned int bit_index = index % Bitmask::bits_per_block;
bitblock mask = (bitblock)(1) << bit_index;
if (value) {
blocks[block_index] = blocks[block_index] | mask;
} else {
blocks[block_index] = blocks[block_index] & ~mask;
}
}
int Bitmask::scan(bitblock * const blocks, int size, int start, bool value) {
if (start >= size) { return size; }
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(blocks, number_of_blocks, block_offset);
unsigned int block_index = start / Bitmask::bits_per_block;
if (block_index >= number_of_blocks) { return size; }
if (value) {
bitblock skip_block = (bitblock)(0);
bitblock mask_block = ~((bitblock)(0)) << (start % Bitmask::bits_per_block);
bitblock block = blocks[block_index] & mask_block; // clear lower bits to ignore them
while (block == skip_block) {
++block_index;
if (block_index >= number_of_blocks) { return size; }
block = blocks[block_index];
}
int bit_index = mpn_scan1(& block, 0);
return block_index * Bitmask::bits_per_block + bit_index;
} else {
bitblock skip_block = ~((bitblock)(0));
bitblock mask_block = ((bitblock)(1) << (start % Bitmask::bits_per_block)) - (bitblock)(1);
bitblock block = blocks[block_index] | mask_block; // Set lower bits to ignore them
while (block == skip_block) {
++block_index;
if (block_index >= number_of_blocks) { return size; }
block = blocks[block_index];
}
int bit_index = mpn_scan0(& block, 0);
return block_index * Bitmask::bits_per_block + bit_index;
}
}
int Bitmask::rscan(bitblock * const blocks, int size, int start, bool value) {
if (start < 0) { return -1; }
unsigned int number_of_blocks, block_offset;
Bitmask::block_layout(size, & number_of_blocks, & block_offset);
Bitmask::clean(blocks, number_of_blocks, block_offset);
int block_index = start / Bitmask::bits_per_block;
if (block_index < 0) { return -1; }
if (value) {
bitblock skip_block = (bitblock)(0);
bitblock mask_block = ~((bitblock)(0)) >> (Bitmask::bits_per_block - 1 - (start % Bitmask::bits_per_block));
bitblock block = blocks[block_index] & mask_block; // clear lower bits to ignore them
while (block == skip_block) {
--block_index;
if (block_index < 0) { return -1; }
block = blocks[block_index];
}
unsigned int count = sizeof(block) * 8 - 1;
bitblock reverse_block = block;
block >>= 1;
while (block) {
reverse_block <<= 1;
reverse_block |= block & 1;
block >>= 1;
count--;
}
reverse_block <<= count;
int bit_index = mpn_scan1(& reverse_block, 0);
return (block_index + 1) * Bitmask::bits_per_block - 1 - bit_index;
} else {
bitblock skip_block = ~((bitblock)(0));
bitblock mask_block = ~((bitblock)(0)) >> (Bitmask::bits_per_block - 1 - (start % Bitmask::bits_per_block));
mask_block = ~mask_block;
bitblock block = blocks[block_index] | mask_block; // Set lower bits to ignore them
while (block == skip_block) {
--block_index;
if (block_index < 0) { return -1; }
block = blocks[block_index];
}
unsigned int count = sizeof(block) * 8 - 1;
bitblock reverse_block = block;
block >>= 1;
while (block) {
reverse_block <<= 1;
reverse_block |= block & 1;
block >>= 1;
count--;
}
reverse_block <<= count;
int bit_index = mpn_scan0(& reverse_block, 0);
return (block_index + 1) * Bitmask::bits_per_block - 1 - bit_index;
}
}
bool Bitmask::scan_range(bool value, int & begin, int & end) const {
if (begin >= this -> _size) { return false; }
begin = this -> scan(begin, value);
if (begin >= this -> _size) { return false; }
end = this -> scan(begin, !value);
return true;
}
bool Bitmask::rscan_range(bool value, int & begin, int & end) const {
if (begin < 0) { return false; }
begin = this -> rscan(begin, value);
if (begin < 0) { return false; }
end = this -> rscan(begin, !value);
return true;
}
std::string Bitmask::to_string(bitblock * const blocks, unsigned int size, bool reverse) {
std::string bitstring;
bitstring.resize(size);
char zero = '0';
char one = '1';
if (reverse) { // Copy the bits
for (unsigned int i = 0; i < size; ++i) { bitstring[i] = Bitmask::get(blocks, size, size - 1 - i) ? one : zero; }
} else {
for (unsigned int i = 0; i < size; ++i) { bitstring[i] = Bitmask::get(blocks, size, i) ? one : zero; }
}
return bitstring;
};
void Bitmask::precompute() {
if (Bitmask::precomputed) { return; }
Bitmask::precomputed = true;
std::map< rangeblock, std::vector<char> > collection;
char block_size = 8 * sizeof(rangeblock);
rangeblock max = ~((rangeblock)0);
for (rangeblock key = 0; key <= max; ++key) {
std::vector<char> code;
if (key == (rangeblock)0) {
code.emplace_back((char)(-block_size));
} else if (key == (rangeblock)1) {
code.emplace_back((char)1);
code.emplace_back((char)(-block_size+1));
} else {
unsigned int prefix_length = std::floor(log2((double)key));
unsigned int suffix_length = block_size - prefix_length;
unsigned int prefix_mask = ~(~0 << prefix_length);
rangeblock prefix_key = key & prefix_mask;
unsigned int prior = (key >> (prefix_length-1)) & 1;
unsigned int bit = (key >> prefix_length) & 1;
std::vector<char> const & prefix = collection.at(prefix_key);
code = prefix;
if (bit == 1) {
if (prior == 0) {
char suffix = code.at(code.size()-1);
code[code.size() - 1] = suffix + suffix_length;
code.emplace_back(1);
if (1 - suffix_length != 0) {
code.emplace_back(1 - suffix_length);
}
} else if (prior == 1) {
code[code.size() - 2] += 1;
code[code.size() - 1] += 1;
if (code[code.size() - 1] == 0) {
code.pop_back();
}
}
}
}
collection.emplace(key, code);
if (key == max) { break; }
}
for (auto iterator = collection.begin(); iterator != collection.end(); iterator++) {
std::vector<char> const & encoding = iterator -> second;
std::vector<codeblock> packed_encoding;
unsigned int counter = 0;
codeblock packed_code = 0;
unsigned int offset = 0;
for (auto subiterator = encoding.begin(); subiterator != encoding.end(); ++subiterator) {
short code = * subiterator; // some char representing anywhere from 1 to 16 bits
if (code > 0) { counter += code; }
if (offset == Bitmask::ranges_per_code) {
packed_encoding.emplace_back(packed_code);
packed_code = 0;
offset = 0;
}
unsigned int shift = offset * Bitmask::bits_per_range;
packed_code = packed_code | ((codeblock)(std::abs(code) - 1) << shift);
++offset;
}
if (offset > 0) {
packed_encoding.emplace_back(packed_code);
}
Bitmask::ranges.emplace_back(packed_encoding);
Bitmask::counts.emplace_back(counter);
bool leading_sign = ((iterator -> first) & 1) == 1;
size_t seed = leading_sign;
std::vector<codeblock> const & codes = packed_encoding;
for (auto code_iterator = codes.begin(); code_iterator != codes.end(); ++code_iterator) {
seed ^= * code_iterator + 0x9e3779b9 + (seed << 6) + (seed >> 2);
if ((int)(* code_iterator) > 0) { counter += * code_iterator; }
}
Bitmask::hashes.emplace_back(seed);
}
}
// **********************
// ** Class Definition **
// **********************
Bitmask::Bitmask() {}
Bitmask::Bitmask(unsigned int size, bool filler, bitblock * local_buffer) {
initialize(size, local_buffer);
if (filler) { fill(); } else { clear(); }
Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset);
}
Bitmask::Bitmask(bitblock * source_blocks, unsigned int size, bitblock * local_buffer) {
if (Bitmask::integrity_check && source_blocks == NULL) {
std::stringstream reason;
reason << "Attempt to construct Bitmask from null source";
throw IntegrityViolation("Bitmask::Bitmask", reason.str());
}
initialize(size, local_buffer);
memcpy(this -> content, source_blocks, this -> _used_blocks * sizeof(bitblock));
Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset);
}
Bitmask::Bitmask(dynamic_bitset const & source, bitblock * local_buffer) {
initialize(source.size(), local_buffer);
// Initialize content using the blocks of this bitset
std::vector< bitblock > source_blocks;
source_blocks.resize(source.num_blocks());
boost::to_block_range(source, source_blocks.begin());
memcpy(this -> content, source_blocks.data(), this -> _used_blocks * sizeof(bitblock));
Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset);
}
Bitmask::Bitmask(Bitmask const & source, bitblock * local_buffer) {
if (source._size == 0) { return; }
if (Bitmask::integrity_check && !source.valid()) {
std::stringstream reason;
reason << "Attempt to construct Bitmask from null source";
throw IntegrityViolation("Bitmask::Bitmask", reason.str());
}
initialize(source.size(), local_buffer);
memcpy(this -> content, source.data(), this -> _used_blocks * sizeof(bitblock));
Bitmask::clean(this->content, this->_used_blocks, this->_offset);
}
Bitmask::~Bitmask() {
if (this -> shallow == false && valid()) {
Bitmask::allocator.deallocate(this -> content, this -> _max_blocks);
}
}
void Bitmask::initialize(unsigned int size, bitblock * local_buffer) {
this -> _size = size;
unsigned int num_blocks;
Bitmask::block_layout(this -> _size, & num_blocks, & (this -> _offset));
this -> _used_blocks = this -> _max_blocks = num_blocks;
if (local_buffer == NULL) {
this -> content = (bitblock *) Bitmask::allocator.allocate(this -> _max_blocks);
} else {
this -> content = local_buffer;
this -> shallow = true;
}
Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset);
}
void Bitmask::resize(unsigned int new_size) {
if (this -> _size == new_size) { return; }
if (this -> content == NULL) {
initialize(new_size);
} else if (Bitmask::integrity_check && new_size > (this -> capacity())) {
std::cout << "Resize: " << new_size << ", Capacity: " << this -> capacity() << "\n";
std::stringstream reason;
reason << "Attempt to resize beyond allocated capacity";
throw IntegrityViolation("Bitmask::resize", reason.str());
}
this -> _size = new_size;
Bitmask::block_layout(new_size, & (this -> _used_blocks), & (this -> _offset));
Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset);
}
void Bitmask::copy_to(bitblock * dest_blocks) const {
if (this -> _size == 0) { return; }
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Attempt to copy from null source";
throw IntegrityViolation("Bitmask::copy_to", reason.str());
}
if (Bitmask::integrity_check && dest_blocks == NULL) {
std::stringstream reason;
reason << "Attempt to copy to null destination";
throw IntegrityViolation("Bitmask::copy_to", reason.str());
}
Bitmask::copy(this -> content, dest_blocks, this -> _size);
}
void Bitmask::copy_from(bitblock * src_blocks) {
if (Bitmask::integrity_check && src_blocks == NULL) {
std::stringstream reason;
reason << "Attempt to copy from null source";
throw IntegrityViolation("Bitmask::copy_from", reason.str());
}
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Attempt to copy to null destination";
throw IntegrityViolation("Bitmask::copy_from", reason.str());
}
Bitmask::copy(src_blocks, this -> content, this -> _size);
}
Bitmask & Bitmask::operator=(Bitmask const & other) {
if (other.size() == 0) { return * this; }
if (this -> content == NULL) { initialize(other.size()); } // resize this instance to match
if (this -> _size != other.size()) { resize(other.size()); } // resize this instance to match
bitblock * blocks = this -> content;
bitblock * other_blocks = other.content;
memcpy(blocks, other_blocks, this -> _used_blocks * sizeof(bitblock));
return * this;
}
bitblock * Bitmask::data() const {
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Accessing invalid data";
throw IntegrityViolation("Bitmask::data", reason.str());
}
return this -> content;
}
unsigned int Bitmask::operator[](unsigned int index) const {
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Accessing invalid data";
throw IntegrityViolation("Bitmask::operator[]", reason.str());
}
return get(index);
}
unsigned int Bitmask::get(unsigned int index) const {
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Accessing invalid data";
throw IntegrityViolation("Bitmask::get", reason.str());
}
bitblock * blocks = this -> content;
unsigned int block_index = index / Bitmask::bits_per_block;
unsigned int bit_index = index % Bitmask::bits_per_block;
bitblock block = blocks[block_index];
return (int)((block >> bit_index) % 2);
}
void Bitmask::set(unsigned int index, bool value) {
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Accessing invalid data";
throw IntegrityViolation("Bitmask::set", reason.str());
}
bitblock * blocks = this -> content;
unsigned int block_index = index / Bitmask::bits_per_block;
unsigned int bit_index = index % Bitmask::bits_per_block;
bitblock mask = (bitblock)(1) << bit_index;
if (value) {
blocks[block_index] = blocks[block_index] | mask;
} else {
blocks[block_index] = blocks[block_index] & ~mask;
}
}
unsigned int Bitmask::size() const { return this -> _size; }
unsigned int Bitmask::capacity() const { return this -> _max_blocks * Bitmask::bits_per_block; }
unsigned int Bitmask::count() const {
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Accessing invalid data";
throw IntegrityViolation("Bitmask::count", reason.str());
}
return mpn_popcount(this -> content, this -> _used_blocks);
}
bool Bitmask::empty() const {
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Accessing invalid data";
throw IntegrityViolation("Bitmask::empty", reason.str());
}
return mpn_zero_p(this -> content, this -> _used_blocks);
}
bool Bitmask::full() const {
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Accessing invalid data";
throw IntegrityViolation("Bitmask::full", reason.str());
}
return this -> count() == this -> size();
}
int Bitmask::scan(int start, bool value) const {
if (start >= size()) { return size(); }
bitblock * blocks = this -> content;
unsigned int block_index = start / Bitmask::bits_per_block;
if (block_index >= this -> _used_blocks) { return size(); }
if (value) {
bitblock skip_block = (bitblock)(0);
bitblock mask_block = ~((bitblock)(0)) << (start % Bitmask::bits_per_block);
bitblock block = blocks[block_index] & mask_block; // clear lower bits to ignore them
while (block == skip_block) {
++block_index;
if (block_index >= this -> _used_blocks) { return size(); }
block = blocks[block_index];
}
int bit_index = mpn_scan1(& block, 0);
return block_index * Bitmask::bits_per_block + bit_index;
} else {
bitblock skip_block = ~((bitblock)(0));
bitblock mask_block = ((bitblock)(1) << (start % Bitmask::bits_per_block)) - (bitblock)(1);
bitblock block = blocks[block_index] | mask_block; // Set lower bits to ignore them
while (block == skip_block) {
++block_index;
if (block_index >= this -> _used_blocks) { return size(); }
block = blocks[block_index];
}
int bit_index = mpn_scan0(& block, 0);
return block_index * Bitmask::bits_per_block + bit_index;
}
}
int Bitmask::rscan(int start, bool value) const {
if (start < 0) { return -1; }
bitblock * blocks = this -> content;
int block_index = start / Bitmask::bits_per_block;
if (block_index < 0) { return -1; }
if (value) {
bitblock skip_block = (bitblock)(0);
bitblock mask_block = ~((bitblock)(0)) >> (Bitmask::bits_per_block - 1 - (start % Bitmask::bits_per_block));
bitblock block = blocks[block_index] & mask_block; // clear lower bits to ignore them
while (block == skip_block) {
--block_index;
if (block_index < 0) { return -1; }
block = blocks[block_index];
}
unsigned int count = sizeof(block) * 8 - 1;
bitblock reverse_block = block;
block >>= 1;
while (block) {
reverse_block <<= 1;
reverse_block |= block & 1;
block >>= 1;
count--;
}
reverse_block <<= count;
int bit_index = mpn_scan1(& reverse_block, 0);
return (block_index + 1) * Bitmask::bits_per_block - 1 - bit_index;
} else {
bitblock skip_block = ~((bitblock)(0));
bitblock mask_block = ~((bitblock)(0)) >> (Bitmask::bits_per_block - 1 - (start % Bitmask::bits_per_block));
mask_block = ~mask_block;
bitblock block = blocks[block_index] | mask_block; // Set lower bits to ignore them
while (block == skip_block) {
--block_index;
if (block_index < 0) { return -1; }
block = blocks[block_index];
}
unsigned int count = sizeof(block) * 8 - 1;
bitblock reverse_block = block;
block >>= 1;
while (block) {
reverse_block <<= 1;
reverse_block |= block & 1;
block >>= 1;
count--;
}
reverse_block <<= count;
int bit_index = mpn_scan0(& reverse_block, 0);
return (block_index + 1) * Bitmask::bits_per_block - 1 - bit_index;
}
}
unsigned int Bitmask::words() const {
if (this -> _size == 0) { return 0; }
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Accessing invalid data";
throw IntegrityViolation("Bitmask::words", reason.str());
}
unsigned int max = size();
bool sign = get(0);
unsigned int i = 0;
unsigned int j = scan(i, !sign);
unsigned int words = 0;
while (j <= max) {
if (sign) { ++words; }
if (j == max) { break; }
i = j;
sign = !sign;
j = scan(i, !sign);
}
return words;
}
void Bitmask::bit_and(bitblock * other_blocks, bool flip) const {
if (Bitmask::integrity_check && (!valid() || other_blocks == NULL)) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::bit_and", reason.str());
}
Bitmask::bit_and(content, other_blocks, _size, flip);
}
void Bitmask::bit_and(Bitmask const & other, bool flip) const {
if (this -> _size == 0 && other._size == 0) { return; }
if (Bitmask::integrity_check && (!valid() || !other.valid())) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::bit_and", reason.str());
}
bitblock * blocks = this -> content;
bitblock * other_blocks = other.content;
unsigned int block_count = std::min(this -> _used_blocks, other._used_blocks);
if (!flip) {
// Special Offload to GMP Implementation
mpn_and_n(other_blocks, blocks, other_blocks, block_count);
} else {
// Special Offload to GMP Implementation
mpn_nior_n(other_blocks, other_blocks, other_blocks, block_count);
mpn_nior_n(other_blocks, blocks, other_blocks, block_count);
}
};
void Bitmask::bit_or(bitblock * other_blocks, bool flip) const {
if (Bitmask::integrity_check && (!valid() || other_blocks == NULL)) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::bit_or", reason.str());
}
Bitmask::bit_or(content, other_blocks, _size, flip);
}
void Bitmask::bit_or(Bitmask const & other, bool flip) const {
if (this -> _size == 0 && other._size == 0) { return; }
if (Bitmask::integrity_check && (!valid() || !other.valid())) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::bit_or", reason.str());
}
bitblock * blocks = this -> content;
bitblock * other_blocks = other.content;
unsigned int block_count = std::min(this -> _used_blocks, other._used_blocks);
if (!flip) {
// Special Offload to GMP Implementation
mpn_ior_n(other_blocks, blocks, other_blocks, block_count);
} else {
// Special Offload to GMP Implementation
mpn_nand_n(other_blocks, other_blocks, other_blocks, block_count);
mpn_nand_n(other_blocks, blocks, other_blocks, block_count);
}
};
void Bitmask::bit_xor(bitblock * other_blocks, bool flip) const {
if (Bitmask::integrity_check && (!valid() || other_blocks == NULL)) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::bit_xor", reason.str());
}
Bitmask::bit_xor(content, other_blocks, _size, flip);
}
void Bitmask::bit_xor(Bitmask const & other, bool flip) const {
if (this -> _size == 0 && other._size == 0) { return; }
if (Bitmask::integrity_check && (!valid() || !other.valid())) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::bit_xor", reason.str());
}
bitblock * blocks = this -> content;
bitblock * other_blocks = other.content;
unsigned int block_count = std::min(this -> _used_blocks, other._used_blocks);
if (!flip) {
// Special Offload to GMP Implementation
mpn_xor_n(other_blocks, blocks, other_blocks, block_count);
} else {
// Special Offload to GMP Implementation
mpn_xnor_n(other_blocks, blocks, other_blocks, block_count);
}
};
void Bitmask::clear() {
if (this -> _size == 0) { return; }
bitblock * blocks = this -> content;
for (unsigned int i = 0; i < this -> _used_blocks; ++i) {
blocks[i] = (bitblock)(0);
}
}
void Bitmask::fill() {
if (this -> _size == 0) { return; }
bitblock * blocks = this -> content;
for (unsigned int i = 0; i < this -> _used_blocks; ++i) {
blocks[i] = ~((bitblock)(0));
}
Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset);
}
bool Bitmask::operator==(bitblock * other) const {
if (Bitmask::integrity_check && (!valid() || other == NULL)) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::operator==", reason.str());
}
return Bitmask::equals(this -> content, other, this -> _size);
}
bool Bitmask::operator==(Bitmask const & other) const {
if (this -> _size == 0 && other._size == 0) { return true; }
if (Bitmask::integrity_check && (!valid() || !other.valid())) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::operator==", reason.str());
}
if (size() != other.size()) { return false; }
return mpn_cmp(this -> content, other.data(), this -> _used_blocks) == 0;
}
bool Bitmask::operator<(Bitmask const & other) const {
if (Bitmask::integrity_check && (!valid() || !other.valid())) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::operator<", reason.str());
}
return Bitmask::less_than(this -> content, other.data(), this -> _size);
}
bool Bitmask::operator>(Bitmask const & other) const {
if (Bitmask::integrity_check && (!valid() || !other.valid())) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::operator>", reason.str());
}
return Bitmask::greater_than(this -> content, other.data(), this -> _size);
}
bool Bitmask::operator!=(Bitmask const & other) const {
if (this -> _size == 0 && other._size == 0) { return false; }
if (Bitmask::integrity_check && (!valid() || !other.valid())) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::operator==", reason.str());
}
return !(* this == other);
}
bool Bitmask::operator<=(Bitmask const & other) const { return !(* this > other); }
bool Bitmask::operator>=(Bitmask const & other) const { return !(* this < other); }
size_t Bitmask::hash(bool bitwise) const {
size_t seed = this -> _size;
if (this -> _size == 0) { return seed; }
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Operating with invalid data";
throw IntegrityViolation("Bitmask::hash", reason.str());
}
// unsigned int max = size();
// bool sign = get(0);
// unsigned int i = 0;
// unsigned int j = scan(i, !sign);
// size_t seed = 1 * sign;
// while (j <= max) {
// seed ^= j - i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
// if (j == max) { break; }
// i = j;
// sign = !sign;
// j = scan(i, !sign);
// }
bitblock * blocks = this -> content;
for (unsigned int i = 0; i < this -> _used_blocks; ++i) {
seed ^= blocks[i] + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
std::string Bitmask::to_string(bool reverse) const {
if (this -> _size == 0) { return ""; }
if (Bitmask::integrity_check && !valid()) {
std::stringstream reason;
reason << "Rendering with invalid data";
throw IntegrityViolation("Bitmask::to_string", reason.str());
}
return Bitmask::to_string(this -> content, this -> _size);
}
bool Bitmask::valid() const {
return this -> content != NULL;
}
void Bitmask::benchmark(unsigned int size) {
unsigned int trials = 100;
unsigned int samples = 1000;
unsigned int length = size;
unsigned int blocks, offset;
Bitmask::block_layout(length, & blocks, & offset);
unsigned int bytes = blocks * Bitmask::bits_per_block / 8;
// unsigned int nails = Bitmask::bits_per_block - offset - 1;
unsigned int nails = 0;
float custom_copy = 0.0;
float custom_compare = 0.0;
float custom_count = 0.0;
float custom_and = 0.0;
float custom_or = 0.0;
float custom_xor = 0.0;
float custom_hash = 0.0;
float custom_iterate = 0.0;
float std_copy = 0.0;
float std_compare = 0.0;
float gmp_copy = 0.0;
float gmp_compare = 0.0;
float gmp_count = 0.0;
float gmp_and = 0.0;
float gmp_or = 0.0;
float gmp_xor = 0.0;
float gmp_hash = 0.0;
float gmp_iterate = 0.0;
std::cout << "Benchmarking Memory Copy..." << "\n";
for (unsigned int i = 10; i < trials; ++i) {
Bitmask expectation(length);
for (unsigned int j = 0; j < length; ++j) { expectation.set(j, j % 100 < i); }
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, (j+i) % 100 < i);
}
// Memory Copy: Custom
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
beta = alpha;
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
custom_copy += duration;
if (beta != expectation) {
std::cout << "Custom copy is incorrect." << "\n";
std::cout << "Expected: " << expectation.to_string() << "\n";
std::cout << "Got: " << beta.to_string() << "\n";
exit(1);
}
}
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, (j+i) % 100 < i);
}
// Memory Copy: STD
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
memcpy(beta.data(), alpha.data(), bytes);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
std_copy += duration;
if (beta != expectation) {
std::cout << "STD copy is incorrect." << "\n";
std::cout << "Expected: " << expectation.to_string() << "\n";
std::cout << "Got: " << beta.to_string() << "\n";
exit(1);
}
}
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, (j+i) % 100 < i);
}
// Translation to mpz objects
mpz_t mpz_alpha;
mpz_t mpz_beta;
mpz_init2(mpz_alpha, length);
mpz_init2(mpz_beta, length);
mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data());
mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, beta.data());
// Memory Copy: GMP
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, alpha.data());
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
gmp_copy += duration;
// Clear necessary since mpz_export does not copy zero words (it assumes the destination memory has be cleared)
alpha.clear();
beta.clear();
// Translation from mpz objects
mpz_export(alpha.data(), NULL, -1, sizeof(bitblock), -1, nails, mpz_alpha);
mpz_export(beta.data(), NULL, -1, sizeof(bitblock), -1, nails, mpz_beta);
if (beta != expectation) {
std::cout << "GMP copy is incorrect." << "\n";
std::cout << "Expected: " << expectation.to_string() << "\n";
std::cout << "Got: " << beta.to_string() << "\n";
exit(1);
}
}
}
std::cout << "Results:" << "\n";
std::cout << " Custom Copy Average Runtime: " << (float)custom_copy / (float)(trials * samples) << " ns" << "\n";
std::cout << " STD Copy Average Runtime: " << (float)std_copy / (float)(trials * samples) << " ns" << "\n";
std::cout << " GMP Copy Average Runtime: " << (float)gmp_copy / (float)(trials * samples) << " ns" << "\n";
std::cout << "Benchmarking Memory Compare..." << "\n";
for (unsigned int i = 10; i < trials; ++i) {
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, j % 100 < i);
}
// Memory Compare: Custom
auto start = std::chrono::high_resolution_clock::now();
bool eq;
for (unsigned int k = 0; k < samples; ++k) {
eq = alpha == beta;
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
custom_compare += duration;
if (!eq) {
std::cout << "Custom compare is incorrect." << std::endl;
exit(1);
}
}
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, j % 100 < i);
}
// Memory Compare: STD
auto start = std::chrono::high_resolution_clock::now();
int eq;
for (unsigned int k = 0; k < samples; ++k) {
eq = memcmp(alpha.data(), beta.data(), bytes);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
std_compare += duration;
if (eq != 0) {
std::cout << "STD compare is incorrect." << std::endl;
exit(1);
}
}
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, j % 100 < i);
}
// Translation to mpz objects
mpz_t mpz_alpha;
mpz_t mpz_beta;
mpz_init2(mpz_alpha, length);
mpz_init2(mpz_beta, length);
mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data());
mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, beta.data());
// Memory Compare: GMP
auto start = std::chrono::high_resolution_clock::now();
int eq;
for (unsigned int k = 0; k < samples; ++k) {
eq = mpz_cmp(mpz_alpha, mpz_beta);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
gmp_compare += duration;
// Clear necessary since mpz_export does not copy zero words (it assumes the destination memory has be cleared)
alpha.clear();
beta.clear();
// Translation from mpz objects
mpz_export(alpha.data(), NULL, -1, sizeof(bitblock), -1, nails, mpz_alpha);
mpz_export(beta.data(), NULL, -1, sizeof(bitblock), -1, nails, mpz_beta);
if (eq != 0) {
std::cout << "GMP compare is incorrect." << std::endl;
std::cout << "Alpha: " << alpha.to_string() << std::endl;
std::cout << "Beta: " << beta.to_string() << std::endl;
exit(1);
}
}
}
std::cout << "Results:" << std::endl;
std::cout << " Custom Compare Average Runtime: " << (float)custom_compare / (float)(trials * samples) << " ns" << std::endl;
std::cout << " STD Compare Average Runtime: " << (float)std_compare / (float)(trials * samples) << " ns" << std::endl;
std::cout << " GMP Compare Average Runtime: " << (float)gmp_compare / (float)(trials * samples) << " ns" << std::endl;
std::cout << "Benchmarking Bit Counting..." << std::endl;
for (unsigned int i = 10; i < trials; ++i) {
unsigned int expectation = 0;
for (unsigned int j = 0; j < length; ++j) { if (j % 100 < i) { ++expectation; } }
{
// Set-up
Bitmask alpha(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
}
// Bit Count: Custom
auto start = std::chrono::high_resolution_clock::now();
unsigned int cnt;
for (unsigned int k = 0; k < samples; ++k) {
cnt = alpha.count();
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
custom_count += duration;
if (cnt != expectation) {
std::cout << "Custom count is incorrect." << std::endl;
exit(1);
}
}
{
// Set-up
Bitmask alpha(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
}
// Translation to mpz objects
mpz_t mpz_alpha;
mpz_init2(mpz_alpha, length);
mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data());
// Bit Count: GMP
auto start = std::chrono::high_resolution_clock::now();
unsigned int cnt;
for (unsigned int k = 0; k < samples; ++k) {
cnt = mpz_popcount(mpz_alpha);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
gmp_count += duration;
// Clear necessary since mpz_export does not copy zero words (it assumes the destination memory has be cleared)
alpha.clear();
// Translation from mpz objects
mpz_export(alpha.data(), NULL, -1, sizeof(bitblock), -1, nails, mpz_alpha);
if (cnt != expectation) {
std::cout << "GMP compare is incorrect." << std::endl;
std::cout << "Alpha: " << alpha.to_string() << std::endl;
exit(1);
}
}
}
std::cout << "Results:" << std::endl;
std::cout << " Custom Count Average Runtime: " << (float)custom_count / (float)(trials * samples) << " ns" << std::endl;
std::cout << " GMP Count Average Runtime: " << (float)gmp_count / (float)(trials * samples) << " ns" << std::endl;
std::cout << "Benchmarking Logical AND..." << std::endl;
for (unsigned int i = 10; i < trials; ++i) {
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, (j+i) % 100 < i);
}
// Logical AND: Custom
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
alpha.bit_and(beta);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
custom_and += duration;
}
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, (j+i) % 100 < i);
}
// Translation to mpz objects
mpz_t mpz_alpha;
mpz_t mpz_beta;
mpz_t mpz_gamma;
mpz_init2(mpz_alpha, length);
mpz_init2(mpz_beta, length);
mpz_init2(mpz_gamma, length);
mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data());
mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, beta.data());
// Logical AND: GMP
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
mpz_and(mpz_gamma, mpz_alpha, mpz_beta);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
gmp_and += duration;
}
}
std::cout << "Results:" << std::endl;
std::cout << " Custom Logical AND Average Runtime: " << (float)custom_and / (float)(trials * samples) << " ns" << std::endl;
std::cout << " GMP Logical AND Average Runtime: " << (float)gmp_and / (float)(trials * samples) << " ns" << std::endl;
std::cout << "Benchmarking Logical OR..." << std::endl;
for (unsigned int i = 10; i < trials; ++i) {
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, (j+i) % 100 < i);
}
// Logical OR: Custom
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
alpha.bit_or(beta);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
custom_or += duration;
}
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, (j+i) % 100 < i);
}
// Translation to mpz objects
mpz_t mpz_alpha;
mpz_t mpz_beta;
mpz_t mpz_gamma;
mpz_init2(mpz_alpha, length);
mpz_init2(mpz_beta, length);
mpz_init2(mpz_gamma, length);
mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data());
mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, beta.data());
// Logical OR: GMP
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
mpz_ior(mpz_gamma, mpz_alpha, mpz_beta);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
gmp_or += duration;
}
}
std::cout << "Results:" << std::endl;
std::cout << " Custom Logical OR Average Runtime: " << (float)custom_or / (float)(trials * samples) << " ns" << std::endl;
std::cout << " GMP Logical OR Average Runtime: " << (float)gmp_or / (float)(trials * samples) << " ns" << std::endl;
std::cout << "Benchmarking Logical XOR..." << std::endl;
for (unsigned int i = 10; i < trials; ++i) {
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, (j+i) % 100 < i);
}
// Logical XOR: Custom
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
alpha.bit_xor(beta);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
custom_xor += duration;
}
{
// Set-up
Bitmask alpha(length);
Bitmask beta(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
beta.set(j, (j+i) % 100 < i);
}
// Translation to mpz objects
mpz_t mpz_alpha;
mpz_t mpz_beta;
mpz_t mpz_gamma;
mpz_init2(mpz_alpha, length);
mpz_init2(mpz_beta, length);
mpz_init2(mpz_gamma, length);
mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data());
mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, beta.data());
// Logical XOR: GMP
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
mpz_xor(mpz_gamma, mpz_alpha, mpz_beta);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
gmp_xor += duration;
}
}
std::cout << "Results:" << std::endl;
std::cout << " Custom Logical XOR Average Runtime: " << (float)custom_xor / (float)(trials * samples) << " ns" << std::endl;
std::cout << " GMP Logical XOR Average Runtime: " << (float)gmp_xor / (float)(trials * samples) << " ns" << std::endl;
std::cout << "Benchmarking Hash Function..." << std::endl;
for (unsigned int i = 10; i < trials; ++i) {
{
// Set-up
Bitmask alpha(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
}
// Hash Function: Custom
auto start = std::chrono::high_resolution_clock::now();
size_t code;
for (unsigned int k = 0; k < samples; ++k) {
code = alpha.hash(false);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
custom_hash += duration;
}
{
// Set-up
Bitmask alpha(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
}
// Hash Function: GMP
auto start = std::chrono::high_resolution_clock::now();
size_t code;
for (unsigned int k = 0; k < samples; ++k) {
code = alpha.hash(true);
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
gmp_hash += duration;
}
}
std::cout << "Results:" << std::endl;
std::cout << " Full Scan Hash Function Average Runtime: " << (float)custom_hash / (float)(trials * samples) << " ns" << std::endl;
std::cout << " Bit Scan Hash Function Average Runtime: " << (float)gmp_hash / (float)(trials * samples) << " ns" << std::endl;
std::cout << "Benchmarking Iteration..." << std::endl;
for (unsigned int i = 10; i < trials; ++i) {
{
// Set-up
Bitmask alpha(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
}
// Iteration: Custom
unsigned int cnt = 0;
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
cnt = 0;
for (unsigned q = 0; q < length; ++q) {
if (alpha.get(q)) { ++cnt; }
}
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
custom_iterate += duration;
if (cnt != alpha.count()) {
std::cout << "Custom iteration is incorrect." << std::endl;
std::cout << "Alpha: " << alpha.to_string() << std::endl;
exit(1);
}
}
{
// Set-up
Bitmask alpha(length);
for (unsigned int j = 0; j < length; ++j) {
alpha.set(j, j % 100 < i);
}
// Iteration: GMP
unsigned int cnt;
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int k = 0; k < samples; ++k) {
cnt = 0;
bool sign = alpha.get(0);
unsigned int p = 0;
unsigned int q = alpha.scan(p, !sign);
unsigned int max = length;
while (q <= max) {
if (sign) { cnt += q - p; }
if (q == max) { break; }
p = q;
sign = !sign;
q = alpha.scan(p, !sign);
}
}
auto finish = std::chrono::high_resolution_clock::now();
float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
gmp_iterate += duration;
if (cnt != alpha.count()) {
std::cout << "GMP iteration is incorrect." << std::endl;
std::cout << "Expected: " << alpha.count() << ", Got: " << cnt << std::endl;
std::cout << "Alpha: " << alpha.to_string() << std::endl;
exit(1);
}
}
}
std::cout << "Results:" << std::endl;
std::cout << " Full Scan Iteration Average Runtime: " << (float)custom_hash / (float)(trials * samples) << " ns" << std::endl;
std::cout << " Bit Scan Iteration Average Runtime: " << (float)gmp_hash / (float)(trials * samples) << " ns" << std::endl;
}
| 40.246133
| 135
| 0.56764
|
leannejdong
|
e5b512b0fc43c8350dd4d4f782937f3cc617d7dd
| 29,034
|
cpp
|
C++
|
B2G/gecko/gfx/thebes/gfxPlatformFontList.cpp
|
wilebeast/FireFox-OS
|
43067f28711d78c429a1d6d58c77130f6899135f
|
[
"Apache-2.0"
] | 3
|
2015-08-31T15:24:31.000Z
|
2020-04-24T20:31:29.000Z
|
B2G/gecko/gfx/thebes/gfxPlatformFontList.cpp
|
wilebeast/FireFox-OS
|
43067f28711d78c429a1d6d58c77130f6899135f
|
[
"Apache-2.0"
] | null | null | null |
B2G/gecko/gfx/thebes/gfxPlatformFontList.cpp
|
wilebeast/FireFox-OS
|
43067f28711d78c429a1d6d58c77130f6899135f
|
[
"Apache-2.0"
] | 3
|
2015-07-29T07:17:15.000Z
|
2020-11-04T06:55:37.000Z
|
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifdef MOZ_LOGGING
#define FORCE_PR_LOG /* Allow logging in the release build */
#endif
#include "prlog.h"
#include "gfxPlatformFontList.h"
#include "nsUnicharUtils.h"
#include "nsUnicodeRange.h"
#include "nsUnicodeProperties.h"
#include "mozilla/Preferences.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/Attributes.h"
using namespace mozilla;
// font info loader constants
static const uint32_t kDelayBeforeLoadingCmaps = 8 * 1000; // 8secs
static const uint32_t kIntervalBetweenLoadingCmaps = 150; // 150ms
static const uint32_t kNumFontsPerSlice = 10; // read in info 10 fonts at a time
#ifdef PR_LOGGING
#define LOG_FONTLIST(args) PR_LOG(gfxPlatform::GetLog(eGfxLog_fontlist), \
PR_LOG_DEBUG, args)
#define LOG_FONTLIST_ENABLED() PR_LOG_TEST( \
gfxPlatform::GetLog(eGfxLog_fontlist), \
PR_LOG_DEBUG)
#endif // PR_LOGGING
gfxPlatformFontList *gfxPlatformFontList::sPlatformFontList = nullptr;
static const char* kObservedPrefs[] = {
"font.",
"font.name-list.",
"intl.accept_languages", // hmmmm...
nullptr
};
class gfxFontListPrefObserver MOZ_FINAL : public nsIObserver {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
};
static gfxFontListPrefObserver* gFontListPrefObserver = nullptr;
NS_IMPL_ISUPPORTS1(gfxFontListPrefObserver, nsIObserver)
NS_IMETHODIMP
gfxFontListPrefObserver::Observe(nsISupports *aSubject,
const char *aTopic,
const PRUnichar *aData)
{
NS_ASSERTION(!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID), "invalid topic");
// XXX this could be made to only clear out the cache for the prefs that were changed
// but it probably isn't that big a deal.
gfxPlatformFontList::PlatformFontList()->ClearPrefFonts();
gfxFontCache::GetCache()->AgeAllGenerations();
return NS_OK;
}
NS_IMPL_ISUPPORTS1(gfxPlatformFontList::MemoryReporter, nsIMemoryMultiReporter)
NS_MEMORY_REPORTER_MALLOC_SIZEOF_FUN(FontListMallocSizeOf, "font-list")
NS_IMETHODIMP
gfxPlatformFontList::MemoryReporter::GetName(nsACString &aName)
{
aName.AssignLiteral("font-list");
return NS_OK;
}
NS_IMETHODIMP
gfxPlatformFontList::MemoryReporter::CollectReports
(nsIMemoryMultiReporterCallback* aCb,
nsISupports* aClosure)
{
FontListSizes sizes;
sizes.mFontListSize = 0;
sizes.mFontTableCacheSize = 0;
sizes.mCharMapsSize = 0;
gfxPlatformFontList::PlatformFontList()->SizeOfIncludingThis(&FontListMallocSizeOf,
&sizes);
aCb->Callback(EmptyCString(),
NS_LITERAL_CSTRING("explicit/gfx/font-list"),
nsIMemoryReporter::KIND_HEAP, nsIMemoryReporter::UNITS_BYTES,
sizes.mFontListSize,
NS_LITERAL_CSTRING("Memory used to manage the list of font families and faces."),
aClosure);
aCb->Callback(EmptyCString(),
NS_LITERAL_CSTRING("explicit/gfx/font-charmaps"),
nsIMemoryReporter::KIND_HEAP, nsIMemoryReporter::UNITS_BYTES,
sizes.mCharMapsSize,
NS_LITERAL_CSTRING("Memory used to record the character coverage of individual fonts."),
aClosure);
if (sizes.mFontTableCacheSize) {
aCb->Callback(EmptyCString(),
NS_LITERAL_CSTRING("explicit/gfx/font-tables"),
nsIMemoryReporter::KIND_HEAP, nsIMemoryReporter::UNITS_BYTES,
sizes.mFontTableCacheSize,
NS_LITERAL_CSTRING("Memory used for cached font metrics and layout tables."),
aClosure);
}
return NS_OK;
}
NS_IMETHODIMP
gfxPlatformFontList::MemoryReporter::GetExplicitNonHeap(int64_t* aAmount)
{
// This reporter only measures heap memory.
*aAmount = 0;
return NS_OK;
}
gfxPlatformFontList::gfxPlatformFontList(bool aNeedFullnamePostscriptNames)
: mNeedFullnamePostscriptNames(aNeedFullnamePostscriptNames),
mStartIndex(0), mIncrement(kNumFontsPerSlice), mNumFamilies(0)
{
mFontFamilies.Init(100);
mOtherFamilyNames.Init(30);
mOtherFamilyNamesInitialized = false;
if (mNeedFullnamePostscriptNames) {
mFullnames.Init(100);
mPostscriptNames.Init(100);
}
mFaceNamesInitialized = false;
mPrefFonts.Init(10);
mBadUnderlineFamilyNames.Init(10);
LoadBadUnderlineList();
// pref changes notification setup
NS_ASSERTION(!gFontListPrefObserver,
"There has been font list pref observer already");
gFontListPrefObserver = new gfxFontListPrefObserver();
NS_ADDREF(gFontListPrefObserver);
Preferences::AddStrongObservers(gFontListPrefObserver, kObservedPrefs);
mSharedCmaps.Init(16);
}
gfxPlatformFontList::~gfxPlatformFontList()
{
mSharedCmaps.Clear();
NS_ASSERTION(gFontListPrefObserver, "There is no font list pref observer");
Preferences::RemoveObservers(gFontListPrefObserver, kObservedPrefs);
NS_RELEASE(gFontListPrefObserver);
}
nsresult
gfxPlatformFontList::InitFontList()
{
mFontFamilies.Clear();
mOtherFamilyNames.Clear();
mOtherFamilyNamesInitialized = false;
if (mNeedFullnamePostscriptNames) {
mFullnames.Clear();
mPostscriptNames.Clear();
}
mFaceNamesInitialized = false;
mPrefFonts.Clear();
CancelLoader();
// initialize ranges of characters for which system-wide font search should be skipped
mCodepointsWithNoFonts.reset();
mCodepointsWithNoFonts.SetRange(0,0x1f); // C0 controls
mCodepointsWithNoFonts.SetRange(0x7f,0x9f); // C1 controls
NS_RegisterMemoryMultiReporter(new MemoryReporter);
sPlatformFontList = this;
return NS_OK;
}
void
gfxPlatformFontList::GenerateFontListKey(const nsAString& aKeyName, nsAString& aResult)
{
aResult = aKeyName;
ToLowerCase(aResult);
}
void
gfxPlatformFontList::InitOtherFamilyNames()
{
mOtherFamilyNamesInitialized = true;
Telemetry::AutoTimer<Telemetry::FONTLIST_INITOTHERFAMILYNAMES> timer;
// iterate over all font families and read in other family names
mFontFamilies.Enumerate(gfxPlatformFontList::InitOtherFamilyNamesProc, this);
}
PLDHashOperator
gfxPlatformFontList::InitOtherFamilyNamesProc(nsStringHashKey::KeyType aKey,
nsRefPtr<gfxFontFamily>& aFamilyEntry,
void* userArg)
{
gfxPlatformFontList *fc = static_cast<gfxPlatformFontList*>(userArg);
aFamilyEntry->ReadOtherFamilyNames(fc);
return PL_DHASH_NEXT;
}
void
gfxPlatformFontList::InitFaceNameLists()
{
mFaceNamesInitialized = true;
// iterate over all font families and read in other family names
Telemetry::AutoTimer<Telemetry::FONTLIST_INITFACENAMELISTS> timer;
mFontFamilies.Enumerate(gfxPlatformFontList::InitFaceNameListsProc, this);
}
PLDHashOperator
gfxPlatformFontList::InitFaceNameListsProc(nsStringHashKey::KeyType aKey,
nsRefPtr<gfxFontFamily>& aFamilyEntry,
void* userArg)
{
gfxPlatformFontList *fc = static_cast<gfxPlatformFontList*>(userArg);
aFamilyEntry->ReadFaceNames(fc, fc->NeedFullnamePostscriptNames());
return PL_DHASH_NEXT;
}
void
gfxPlatformFontList::PreloadNamesList()
{
nsAutoTArray<nsString, 10> preloadFonts;
gfxFontUtils::GetPrefsFontList("font.preload-names-list", preloadFonts);
uint32_t numFonts = preloadFonts.Length();
for (uint32_t i = 0; i < numFonts; i++) {
nsAutoString key;
GenerateFontListKey(preloadFonts[i], key);
// only search canonical names!
gfxFontFamily *familyEntry = mFontFamilies.GetWeak(key);
if (familyEntry) {
familyEntry->ReadOtherFamilyNames(this);
}
}
}
void
gfxPlatformFontList::SetFixedPitch(const nsAString& aFamilyName)
{
gfxFontFamily *family = FindFamily(aFamilyName);
if (!family) return;
family->FindStyleVariations();
nsTArray<nsRefPtr<gfxFontEntry> >& fontlist = family->GetFontList();
uint32_t i, numFonts = fontlist.Length();
for (i = 0; i < numFonts; i++) {
fontlist[i]->mFixedPitch = 1;
}
}
void
gfxPlatformFontList::LoadBadUnderlineList()
{
nsAutoTArray<nsString, 10> blacklist;
gfxFontUtils::GetPrefsFontList("font.blacklist.underline_offset", blacklist);
uint32_t numFonts = blacklist.Length();
for (uint32_t i = 0; i < numFonts; i++) {
nsAutoString key;
GenerateFontListKey(blacklist[i], key);
mBadUnderlineFamilyNames.PutEntry(key);
}
}
bool
gfxPlatformFontList::ResolveFontName(const nsAString& aFontName, nsAString& aResolvedFontName)
{
gfxFontFamily *family = FindFamily(aFontName);
if (family) {
aResolvedFontName = family->Name();
return true;
}
return false;
}
struct FontListData {
FontListData(nsIAtom *aLangGroup,
const nsACString& aGenericFamily,
nsTArray<nsString>& aListOfFonts) :
mLangGroup(aLangGroup), mGenericFamily(aGenericFamily),
mListOfFonts(aListOfFonts) {}
nsIAtom *mLangGroup;
const nsACString& mGenericFamily;
nsTArray<nsString>& mListOfFonts;
};
PLDHashOperator
gfxPlatformFontList::HashEnumFuncForFamilies(nsStringHashKey::KeyType aKey,
nsRefPtr<gfxFontFamily>& aFamilyEntry,
void *aUserArg)
{
FontListData *data = static_cast<FontListData*>(aUserArg);
// use the first variation for now. This data should be the same
// for all the variations and should probably be moved up to
// the Family
gfxFontStyle style;
style.language = data->mLangGroup;
bool needsBold;
nsRefPtr<gfxFontEntry> aFontEntry = aFamilyEntry->FindFontForStyle(style, needsBold);
NS_ASSERTION(aFontEntry, "couldn't find any font entry in family");
if (!aFontEntry)
return PL_DHASH_NEXT;
/* skip symbol fonts */
if (aFontEntry->IsSymbolFont())
return PL_DHASH_NEXT;
if (aFontEntry->SupportsLangGroup(data->mLangGroup) &&
aFontEntry->MatchesGenericFamily(data->mGenericFamily)) {
nsAutoString localizedFamilyName;
aFamilyEntry->LocalizedName(localizedFamilyName);
data->mListOfFonts.AppendElement(localizedFamilyName);
}
return PL_DHASH_NEXT;
}
void
gfxPlatformFontList::GetFontList(nsIAtom *aLangGroup,
const nsACString& aGenericFamily,
nsTArray<nsString>& aListOfFonts)
{
FontListData data(aLangGroup, aGenericFamily, aListOfFonts);
mFontFamilies.Enumerate(gfxPlatformFontList::HashEnumFuncForFamilies, &data);
aListOfFonts.Sort();
aListOfFonts.Compact();
}
struct FontFamilyListData {
FontFamilyListData(nsTArray<nsRefPtr<gfxFontFamily> >& aFamilyArray)
: mFamilyArray(aFamilyArray)
{}
static PLDHashOperator AppendFamily(nsStringHashKey::KeyType aKey,
nsRefPtr<gfxFontFamily>& aFamilyEntry,
void *aUserArg)
{
FontFamilyListData *data = static_cast<FontFamilyListData*>(aUserArg);
data->mFamilyArray.AppendElement(aFamilyEntry);
return PL_DHASH_NEXT;
}
nsTArray<nsRefPtr<gfxFontFamily> >& mFamilyArray;
};
void
gfxPlatformFontList::GetFontFamilyList(nsTArray<nsRefPtr<gfxFontFamily> >& aFamilyArray)
{
FontFamilyListData data(aFamilyArray);
mFontFamilies.Enumerate(FontFamilyListData::AppendFamily, &data);
}
gfxFontEntry*
gfxPlatformFontList::SystemFindFontForChar(const uint32_t aCh,
int32_t aRunScript,
const gfxFontStyle* aStyle)
{
gfxFontEntry* fontEntry = nullptr;
// is codepoint with no matching font? return null immediately
if (mCodepointsWithNoFonts.test(aCh)) {
return nullptr;
}
// try to short-circuit font fallback for U+FFFD, used to represent
// encoding errors: just use a platform-specific fallback system
// font that is guaranteed (or at least highly likely) to be around,
// or a cached family from last time U+FFFD was seen. this helps
// speed up pages with lots of encoding errors, binary-as-text, etc.
if (aCh == 0xFFFD && mReplacementCharFallbackFamily.Length() > 0) {
bool needsBold; // ignored in the system fallback case
fontEntry = FindFontForFamily(mReplacementCharFallbackFamily,
aStyle, needsBold);
if (fontEntry && fontEntry->TestCharacterMap(aCh))
return fontEntry;
}
TimeStamp start = TimeStamp::Now();
// search commonly available fonts
bool common = true;
fontEntry = CommonFontFallback(aCh, aRunScript, aStyle);
// if didn't find a font, do system-wide fallback (except for specials)
uint32_t cmapCount = 0;
if (!fontEntry) {
common = false;
fontEntry = GlobalFontFallback(aCh, aRunScript, aStyle, cmapCount);
}
TimeDuration elapsed = TimeStamp::Now() - start;
#ifdef PR_LOGGING
PRLogModuleInfo *log = gfxPlatform::GetLog(eGfxLog_textrun);
if (NS_UNLIKELY(log)) {
uint32_t charRange = gfxFontUtils::CharRangeBit(aCh);
uint32_t unicodeRange = FindCharUnicodeRange(aCh);
int32_t script = mozilla::unicode::GetScriptCode(aCh);
PR_LOG(log, PR_LOG_WARNING,\
("(textrun-systemfallback-%s) char: u+%6.6x "
"char-range: %d unicode-range: %d script: %d match: [%s]"
" time: %dus cmaps: %d\n",
(common ? "common" : "global"), aCh,
charRange, unicodeRange, script,
(fontEntry ? NS_ConvertUTF16toUTF8(fontEntry->Name()).get() :
"<none>"),
int32_t(elapsed.ToMicroseconds()),
cmapCount));
}
#endif
// no match? add to set of non-matching codepoints
if (!fontEntry) {
mCodepointsWithNoFonts.set(aCh);
} else if (aCh == 0xFFFD && fontEntry) {
mReplacementCharFallbackFamily = fontEntry->FamilyName();
}
// track system fallback time
static bool first = true;
int32_t intElapsed = int32_t(first ? elapsed.ToMilliseconds() :
elapsed.ToMicroseconds());
Telemetry::Accumulate((first ? Telemetry::SYSTEM_FONT_FALLBACK_FIRST :
Telemetry::SYSTEM_FONT_FALLBACK),
intElapsed);
first = false;
// track the script for which fallback occurred (incremented one make it
// 1-based)
Telemetry::Accumulate(Telemetry::SYSTEM_FONT_FALLBACK_SCRIPT, aRunScript + 1);
return fontEntry;
}
PLDHashOperator
gfxPlatformFontList::FindFontForCharProc(nsStringHashKey::KeyType aKey, nsRefPtr<gfxFontFamily>& aFamilyEntry,
void *userArg)
{
GlobalFontMatch *data = static_cast<GlobalFontMatch*>(userArg);
// evaluate all fonts in this family for a match
aFamilyEntry->FindFontForChar(data);
return PL_DHASH_NEXT;
}
#define NUM_FALLBACK_FONTS 8
gfxFontEntry*
gfxPlatformFontList::CommonFontFallback(const uint32_t aCh,
int32_t aRunScript,
const gfxFontStyle* aMatchStyle)
{
nsAutoTArray<const char*,NUM_FALLBACK_FONTS> defaultFallbacks;
uint32_t i, numFallbacks;
gfxPlatform::GetPlatform()->GetCommonFallbackFonts(aCh, aRunScript,
defaultFallbacks);
numFallbacks = defaultFallbacks.Length();
for (i = 0; i < numFallbacks; i++) {
nsAutoString familyName;
const char *fallbackFamily = defaultFallbacks[i];
familyName.AppendASCII(fallbackFamily);
gfxFontFamily *fallback =
gfxPlatformFontList::PlatformFontList()->FindFamily(familyName);
if (!fallback)
continue;
gfxFontEntry *fontEntry;
bool needsBold; // ignored in the system fallback case
// use first font in list that supports a given character
fontEntry = fallback->FindFontForStyle(*aMatchStyle, needsBold);
if (fontEntry && fontEntry->TestCharacterMap(aCh)) {
return fontEntry;
}
}
return nullptr;
}
gfxFontEntry*
gfxPlatformFontList::GlobalFontFallback(const uint32_t aCh,
int32_t aRunScript,
const gfxFontStyle* aMatchStyle,
uint32_t& aCmapCount)
{
// otherwise, try to find it among local fonts
GlobalFontMatch data(aCh, aRunScript, aMatchStyle);
// iterate over all font families to find a font that support the character
mFontFamilies.Enumerate(gfxPlatformFontList::FindFontForCharProc, &data);
aCmapCount = data.mCmapsTested;
return data.mBestMatch;
}
#ifdef XP_WIN
#include <windows.h>
// crude hack for using when monitoring process
static void LogRegistryEvent(const wchar_t *msg)
{
HKEY dummyKey;
HRESULT hr;
wchar_t buf[512];
wsprintfW(buf, L" log %s", msg);
hr = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buf, 0, KEY_READ, &dummyKey);
if (SUCCEEDED(hr)) {
RegCloseKey(dummyKey);
}
}
#endif
gfxFontFamily*
gfxPlatformFontList::FindFamily(const nsAString& aFamily)
{
nsAutoString key;
gfxFontFamily *familyEntry;
GenerateFontListKey(aFamily, key);
NS_ASSERTION(mFontFamilies.Count() != 0, "system font list was not initialized correctly");
// lookup in canonical (i.e. English) family name list
if ((familyEntry = mFontFamilies.GetWeak(key))) {
return familyEntry;
}
// lookup in other family names list (mostly localized names)
if ((familyEntry = mOtherFamilyNames.GetWeak(key)) != nullptr) {
return familyEntry;
}
// name not found and other family names not yet fully initialized so
// initialize the rest of the list and try again. this is done lazily
// since reading name table entries is expensive.
// although ASCII localized family names are possible they don't occur
// in practice so avoid pulling in names at startup
if (!mOtherFamilyNamesInitialized && !IsASCII(aFamily)) {
InitOtherFamilyNames();
if ((familyEntry = mOtherFamilyNames.GetWeak(key)) != nullptr) {
return familyEntry;
}
}
return nullptr;
}
gfxFontEntry*
gfxPlatformFontList::FindFontForFamily(const nsAString& aFamily, const gfxFontStyle* aStyle, bool& aNeedsBold)
{
gfxFontFamily *familyEntry = FindFamily(aFamily);
aNeedsBold = false;
if (familyEntry)
return familyEntry->FindFontForStyle(*aStyle, aNeedsBold);
return nullptr;
}
bool
gfxPlatformFontList::GetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<nsRefPtr<gfxFontFamily> > *array)
{
return mPrefFonts.Get(uint32_t(aLangGroup), array);
}
void
gfxPlatformFontList::SetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<nsRefPtr<gfxFontFamily> >& array)
{
mPrefFonts.Put(uint32_t(aLangGroup), array);
}
void
gfxPlatformFontList::AddOtherFamilyName(gfxFontFamily *aFamilyEntry, nsAString& aOtherFamilyName)
{
nsAutoString key;
GenerateFontListKey(aOtherFamilyName, key);
if (!mOtherFamilyNames.GetWeak(key)) {
mOtherFamilyNames.Put(key, aFamilyEntry);
#ifdef PR_LOGGING
LOG_FONTLIST(("(fontlist-otherfamily) canonical family: %s, "
"other family: %s\n",
NS_ConvertUTF16toUTF8(aFamilyEntry->Name()).get(),
NS_ConvertUTF16toUTF8(aOtherFamilyName).get()));
#endif
if (mBadUnderlineFamilyNames.Contains(key))
aFamilyEntry->SetBadUnderlineFamily();
}
}
void
gfxPlatformFontList::AddFullname(gfxFontEntry *aFontEntry, nsAString& aFullname)
{
if (!mFullnames.GetWeak(aFullname)) {
mFullnames.Put(aFullname, aFontEntry);
#ifdef PR_LOGGING
LOG_FONTLIST(("(fontlist-fullname) name: %s, fullname: %s\n",
NS_ConvertUTF16toUTF8(aFontEntry->Name()).get(),
NS_ConvertUTF16toUTF8(aFullname).get()));
#endif
}
}
void
gfxPlatformFontList::AddPostscriptName(gfxFontEntry *aFontEntry, nsAString& aPostscriptName)
{
if (!mPostscriptNames.GetWeak(aPostscriptName)) {
mPostscriptNames.Put(aPostscriptName, aFontEntry);
#ifdef PR_LOGGING
LOG_FONTLIST(("(fontlist-postscript) name: %s, psname: %s\n",
NS_ConvertUTF16toUTF8(aFontEntry->Name()).get(),
NS_ConvertUTF16toUTF8(aPostscriptName).get()));
#endif
}
}
bool
gfxPlatformFontList::GetStandardFamilyName(const nsAString& aFontName, nsAString& aFamilyName)
{
aFamilyName.Truncate();
ResolveFontName(aFontName, aFamilyName);
return !aFamilyName.IsEmpty();
}
gfxCharacterMap*
gfxPlatformFontList::FindCharMap(gfxCharacterMap *aCmap)
{
aCmap->CalcHash();
gfxCharacterMap *cmap = AddCmap(aCmap);
cmap->mShared = true;
return cmap;
}
// add a cmap to the shared cmap set
gfxCharacterMap*
gfxPlatformFontList::AddCmap(const gfxCharacterMap* aCharMap)
{
CharMapHashKey *found =
mSharedCmaps.PutEntry(const_cast<gfxCharacterMap*>(aCharMap));
return found->GetKey();
}
// remove the cmap from the shared cmap set
void
gfxPlatformFontList::RemoveCmap(const gfxCharacterMap* aCharMap)
{
// skip lookups during teardown
if (mSharedCmaps.Count() == 0) {
return;
}
// cmap needs to match the entry *and* be the same ptr before removing
CharMapHashKey *found =
mSharedCmaps.GetEntry(const_cast<gfxCharacterMap*>(aCharMap));
if (found && found->GetKey() == aCharMap) {
mSharedCmaps.RemoveEntry(const_cast<gfxCharacterMap*>(aCharMap));
}
}
void
gfxPlatformFontList::InitLoader()
{
GetFontFamilyList(mFontFamiliesToLoad);
mStartIndex = 0;
mNumFamilies = mFontFamiliesToLoad.Length();
}
bool
gfxPlatformFontList::RunLoader()
{
uint32_t i, endIndex = (mStartIndex + mIncrement < mNumFamilies ? mStartIndex + mIncrement : mNumFamilies);
bool loadCmaps = !UsesSystemFallback() ||
gfxPlatform::GetPlatform()->UseCmapsDuringSystemFallback();
// for each font family, load in various font info
for (i = mStartIndex; i < endIndex; i++) {
gfxFontFamily* familyEntry = mFontFamiliesToLoad[i];
// find all faces that are members of this family
familyEntry->FindStyleVariations();
if (familyEntry->GetFontList().Length() == 0) {
// failed to load any faces for this family, so discard it
nsAutoString key;
GenerateFontListKey(familyEntry->Name(), key);
mFontFamilies.Remove(key);
continue;
}
// load the cmaps if needed
if (loadCmaps) {
familyEntry->ReadAllCMAPs();
}
// read in face names
familyEntry->ReadFaceNames(this, mNeedFullnamePostscriptNames);
// check whether the family can be considered "simple" for style matching
familyEntry->CheckForSimpleFamily();
}
mStartIndex = endIndex;
return (mStartIndex >= mNumFamilies);
}
void
gfxPlatformFontList::FinishLoader()
{
mFontFamiliesToLoad.Clear();
mNumFamilies = 0;
}
// Support for memory reporting
static size_t
SizeOfFamilyEntryExcludingThis(const nsAString& aKey,
const nsRefPtr<gfxFontFamily>& aFamily,
nsMallocSizeOfFun aMallocSizeOf,
void* aUserArg)
{
FontListSizes *sizes = static_cast<FontListSizes*>(aUserArg);
aFamily->SizeOfExcludingThis(aMallocSizeOf, sizes);
sizes->mFontListSize += aKey.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
// we return zero here because the measurements have been added directly
// to the relevant fields of the FontListSizes record
return 0;
}
// this is also used by subclasses that hold additional hashes of family names
/*static*/ size_t
gfxPlatformFontList::SizeOfFamilyNameEntryExcludingThis
(const nsAString& aKey,
const nsRefPtr<gfxFontFamily>& aFamily,
nsMallocSizeOfFun aMallocSizeOf,
void* aUserArg)
{
// we don't count the size of the family here, because this is an *extra*
// reference to a family that will have already been counted in the main list
return aKey.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
}
static size_t
SizeOfFontNameEntryExcludingThis(const nsAString& aKey,
const nsRefPtr<gfxFontEntry>& aFont,
nsMallocSizeOfFun aMallocSizeOf,
void* aUserArg)
{
// the font itself is counted by its owning family; here we only care about
// the name stored in the hashtable key
return aKey.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
}
static size_t
SizeOfPrefFontEntryExcludingThis
(const uint32_t& aKey,
const nsTArray<nsRefPtr<gfxFontFamily> >& aList,
nsMallocSizeOfFun aMallocSizeOf,
void* aUserArg)
{
// again, we only care about the size of the array itself; we don't follow
// the refPtrs stored in it, because they point to entries already owned
// and accounted-for by the main font list
return aList.SizeOfExcludingThis(aMallocSizeOf);
}
static size_t
SizeOfStringEntryExcludingThis(nsStringHashKey* aHashEntry,
nsMallocSizeOfFun aMallocSizeOf,
void* aUserArg)
{
return aHashEntry->GetKey().SizeOfExcludingThisIfUnshared(aMallocSizeOf);
}
static size_t
SizeOfSharedCmapExcludingThis(CharMapHashKey* aHashEntry,
nsMallocSizeOfFun aMallocSizeOf,
void* aUserArg)
{
FontListSizes *sizes = static_cast<FontListSizes*>(aUserArg);
uint32_t size = aHashEntry->GetKey()->SizeOfIncludingThis(aMallocSizeOf);
sizes->mCharMapsSize += size;
// we return zero here because the measurements have been added directly
// to the relevant fields of the FontListSizes record
return 0;
}
void
gfxPlatformFontList::SizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf,
FontListSizes* aSizes) const
{
aSizes->mFontListSize +=
mFontFamilies.SizeOfExcludingThis(SizeOfFamilyEntryExcludingThis,
aMallocSizeOf, aSizes);
aSizes->mFontListSize +=
mOtherFamilyNames.SizeOfExcludingThis(SizeOfFamilyNameEntryExcludingThis,
aMallocSizeOf);
if (mNeedFullnamePostscriptNames) {
aSizes->mFontListSize +=
mFullnames.SizeOfExcludingThis(SizeOfFontNameEntryExcludingThis,
aMallocSizeOf);
aSizes->mFontListSize +=
mPostscriptNames.SizeOfExcludingThis(SizeOfFontNameEntryExcludingThis,
aMallocSizeOf);
}
aSizes->mFontListSize +=
mCodepointsWithNoFonts.SizeOfExcludingThis(aMallocSizeOf);
aSizes->mFontListSize +=
mReplacementCharFallbackFamily.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
aSizes->mFontListSize +=
mFontFamiliesToLoad.SizeOfExcludingThis(aMallocSizeOf);
aSizes->mFontListSize +=
mPrefFonts.SizeOfExcludingThis(SizeOfPrefFontEntryExcludingThis,
aMallocSizeOf);
aSizes->mFontListSize +=
mBadUnderlineFamilyNames.SizeOfExcludingThis(SizeOfStringEntryExcludingThis,
aMallocSizeOf);
aSizes->mFontListSize +=
mSharedCmaps.SizeOfExcludingThis(SizeOfSharedCmapExcludingThis,
aMallocSizeOf, aSizes);
}
void
gfxPlatformFontList::SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf,
FontListSizes* aSizes) const
{
aSizes->mFontListSize += aMallocSizeOf(this);
SizeOfExcludingThis(aMallocSizeOf, aSizes);
}
| 33.257732
| 114
| 0.661604
|
wilebeast
|
e5b5c80434acda90be4e02bfcc27736f0c17d656
| 2,910
|
cpp
|
C++
|
11. DP 2/Maximum_sum_rect.cpp
|
bhavinvirani/Competitive-Programming-coding-ninjas
|
5e50ae7ad3fc969a4970f91f8d895c986353bb71
|
[
"MIT"
] | null | null | null |
11. DP 2/Maximum_sum_rect.cpp
|
bhavinvirani/Competitive-Programming-coding-ninjas
|
5e50ae7ad3fc969a4970f91f8d895c986353bb71
|
[
"MIT"
] | null | null | null |
11. DP 2/Maximum_sum_rect.cpp
|
bhavinvirani/Competitive-Programming-coding-ninjas
|
5e50ae7ad3fc969a4970f91f8d895c986353bb71
|
[
"MIT"
] | null | null | null |
/* Maximum Sum Rectangle
Send Feedback
Given a 2D array, find the maximum sum rectangle in it. In other words find maximum sum over all rectangles in the matrix.
Input Format:
First line of input will contain T(number of test case), each test case follows as.
First line contains 2 numbers n and m denoting number of rows and number of columns. Next n lines contain m space separated integers denoting elements of matrix nxm.
Output Format:
Output a single integer, maximum sum rectangle for each test case in a newline.
Constraints
1 <= T <= 50
1<=n,m<=100
-10^5 <= mat[i][j] <= 10^5
Sample Input
1
4 5
1 2 -1 -4 -20
-8 -3 4 2 1
3 8 10 1 3
-4 -1 1 7 -6
Sample Output
29 */
#include <bits/stdc++.h>
using namespace std;
int kadane(vector<int> vec)
{
int maxSum = INT_MIN, curSum = 0;
for (int i = 0; i < vec.size(); i++)
{
curSum += vec[i];
maxSum = max(maxSum, curSum);
curSum = (curSum < 0) ? 0 : curSum;
}
return maxSum;
}
int findMaxSum(vector<vector<int>> arr, int row, int col)
{
// int ans = 0;
// int startx = 0, starty = 0, endx = 0, endy = 0;
// for (int i = 0; i < row; i++)
// {
// startx = i;
// for (int j = 0; j < col; j++)
// {
// starty = j;
// for (int m = 0; m < row; m++)
// {
// endx = m;
// for (int n = 0; n < col; n++)
// {
// endy = n;
// int sum = 0;
// for (int a = startx; a <= endx; a++)
// {
// for (int b = starty; b <= endy; b++)
// {
// sum += arr[a][b];
// }
// }
// if (sum > ans)
// ans = sum;
// }
// }
// }
// }
//? 2nd approch
int max_sum_soFar = INT_MIN;
for(int i = 0; i < row; i++){
vector<int> temp(row);
for (int j = i; j < col; j++)
{
for (int k = 0; k < row; k++){
temp[k] += arr[k][j];
}
max_sum_soFar = max(max_sum_soFar, kadane(temp));
}
}
return max_sum_soFar;
}
int main()
{
freopen("/home/spy/Desktop/input.txt", "r", stdin);
freopen("/home/spy/Desktop/output.txt", "w", stdout);
int t;
cin >> t;
while (t--)
{
int n, m;
cin >> n >> m;
vector<vector<int>> arr;
for (int i = 0; i < n; i++)
{
vector<int> tmp;
for (int j = 0; j < m; j++)
{
int x;
cin >> x;
tmp.push_back(x);
}
arr.push_back(tmp);
}
int ans;
ans = findMaxSum(arr, n, m);
cout << ans << endl;
}
return 0;
}
| 24.453782
| 165
| 0.434021
|
bhavinvirani
|
e5c0f68c90c0999dfe19a01d29d9c0ff54282c05
| 3,491
|
cpp
|
C++
|
src/OptPlan/Opt_SnowflakeInterestingOrders.cpp
|
fsaintjacques/cstore
|
3300a81c359c4a48e13ad397e3eb09384f57ccd7
|
[
"BSD-2-Clause"
] | 14
|
2016-07-11T04:08:09.000Z
|
2022-03-11T05:56:59.000Z
|
src/OptPlan/Opt_SnowflakeInterestingOrders.cpp
|
ibrarahmad/cstore
|
3300a81c359c4a48e13ad397e3eb09384f57ccd7
|
[
"BSD-2-Clause"
] | null | null | null |
src/OptPlan/Opt_SnowflakeInterestingOrders.cpp
|
ibrarahmad/cstore
|
3300a81c359c4a48e13ad397e3eb09384f57ccd7
|
[
"BSD-2-Clause"
] | 13
|
2016-06-01T10:41:15.000Z
|
2022-01-06T09:01:15.000Z
|
/*
* Opt_SnowflakeInterestingOrders.h
* OptDev
*
* Created by Nga Tran on 11/10/05.
* Questions, ask Nga Tran at nga@brandeis.edu or Tien Hoang at hoangt@brandeis.edu
*
* This class keeps interesting orders of a snowflake query
*/
#include "Opt_SnowflakeInterestingOrders.h"
// Default constructor
Opt_SnowflakeInterestingOrders::Opt_SnowflakeInterestingOrders()
{
m_sQueryName = "";
}
// Provide query name
Opt_SnowflakeInterestingOrders::Opt_SnowflakeInterestingOrders(string sQueryName)
{
m_sQueryName = sQueryName;
}
// Provide query names and 1 object
Opt_SnowflakeInterestingOrders::Opt_SnowflakeInterestingOrders(string sQueryName, list<Opt_Column*> order)
{
m_sQueryName = sQueryName;
mOrderList.push_back(order);
}
// Destructor
Opt_SnowflakeInterestingOrders::~Opt_SnowflakeInterestingOrders()
{
}
// String presentation of this class
string Opt_SnowflakeInterestingOrders::toStringNoTableDot(string sIndent)
{
string sReturn = sIndent;
sReturn.append(m_sQueryName);
sReturn.append(": \n");
sIndent += "\t";
list<InterestingOrder>::iterator orderIt;
for (orderIt = mOrderList.begin(); orderIt != mOrderList.end(); orderIt++)
{
sReturn.append(sIndent);
InterestingOrder order = *orderIt;
list<Opt_Column*>::iterator colIt;
for (colIt = order.begin(); colIt != order.end(); colIt++)
{
sReturn.append((*colIt)->toStringNoTableDot());
sReturn.append(" ");
}
sReturn.append("\n");
}
return sReturn;
}
// String presentation of this class
string Opt_SnowflakeInterestingOrders::toString(string sIndent)
{
string sReturn = sIndent;
sReturn.append(m_sQueryName);
sReturn.append(": \n");
sIndent += "\t";
list<InterestingOrder>::iterator orderIt;
for (orderIt = mOrderList.begin(); orderIt != mOrderList.end(); orderIt++)
{
sReturn.append(sIndent);
InterestingOrder order = *orderIt;
list<Opt_Column*>::iterator colIt;
for (colIt = order.begin(); colIt != order.end(); colIt++)
{
sReturn.append((*colIt)->toString());
sReturn.append(" ");
}
sReturn.append("\n");
}
return sReturn;
}
void Opt_SnowflakeInterestingOrders::setQueryName(string sQueryName)
{
m_sQueryName = sQueryName;
}
string Opt_SnowflakeInterestingOrders::getQueryName()
{
return m_sQueryName;
}
list<InterestingOrder> Opt_SnowflakeInterestingOrders::getOrderList()
{
return mOrderList;
}
// Add an order
// return true (1) if the order added
bool Opt_SnowflakeInterestingOrders::addOrder(string sQueryName, list<Opt_Column*> order)
{
if (m_sQueryName.compare(sQueryName) == 0)
{
// Check if the order already existed
list<InterestingOrder>::iterator it;
for (it = mOrderList.begin(); it != mOrderList.end(); it++)
{
list<Opt_Column*> intertestingOrder = *it;
// Check if number of columns in the orders are the same
if (intertestingOrder.size() != order.size())
{
continue;
}
// Compare if orders are exactly the same
bool isTheSame = 1;
list<Opt_Column*>::iterator existColIt = intertestingOrder.begin();
list<Opt_Column*>::iterator colIt = order.begin();
while( (existColIt != intertestingOrder.end()) && (colIt != order.end()) )
{
if (((*existColIt)->getColumnName()).compare((*colIt)->getColumnName()) != 0)
{
isTheSame = 0;
}
existColIt++;
colIt++;
}
if (isTheSame)
{
// the order already existed
return 1;
}
}
mOrderList.push_back(order);
return 1;
}
return 0;
}
| 22.967105
| 106
| 0.696649
|
fsaintjacques
|
e5c3467258e82f5fb0ba2c296149d9a250bf4d61
| 1,964
|
cpp
|
C++
|
tools/faodel-stress/serdes/SerdesStringObject.cpp
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 2
|
2019-01-25T21:21:07.000Z
|
2021-04-29T17:24:00.000Z
|
tools/faodel-stress/serdes/SerdesStringObject.cpp
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 8
|
2018-10-09T14:35:30.000Z
|
2020-09-30T20:09:42.000Z
|
tools/faodel-stress/serdes/SerdesStringObject.cpp
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 2
|
2019-04-23T19:01:36.000Z
|
2021-05-11T07:44:55.000Z
|
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#include <iostream>
#include "lunasa/common/GenericSequentialDataBundle.hh"
#include "SerdesStringObject.hh"
using namespace std;
SerdesStringObject::SerdesStringObject(JobSerdes::params_t params,
std::function<int ()> f_prng) {
//Populate our string list
for(int i=0; i<params.num_items; i++) {
strings.emplace_back(faodel::RandomString( f_prng() ));
}
}
typedef lunasa::GenericSequentialBundle<uint64_t> bundle_t;
lunasa::DataObject SerdesStringObject::pup() const {
// Since this is a series of random length strings, the easiest thing to
// do is just pack them into an LDO using the GenericSequentialBundler
// class. You allocate space for all the strings, and then use a
// bundle_offsets_t to keep track of where you are in the LDO.
//Figure out how much space our strings need. Note: each item as a 32b length
uint32_t payload_size=0;
for(auto &s: strings) {
payload_size += s.size() + sizeof(uint32_t);
}
//Allocate an LDO, overlay our bundle structure on it, and wipe the header
lunasa::DataObject ldo(sizeof(bundle_t), payload_size,lunasa::DataObject::AllocatorType::eager);
auto *msg = ldo.GetMetaPtr<bundle_t *>();
msg->Init();
//Use the offsets to track where we are so we don't overflow
lunasa::bundle_offsets_t counters(&ldo);
for(auto &s : strings) {
bool ok=msg->AppendBack(counters, s);
if(!ok) std::cerr<<"Serialization problems in SerdesStringObject\n";
}
return ldo;
}
void SerdesStringObject::pup(const lunasa::DataObject &ldo) {
auto *msg = ldo.GetMetaPtr<bundle_t *>();
lunasa::bundle_offsets_t counters(&ldo);
strings.resize(0);
string s;
while(msg->GetNext(counters, &s)) {
strings.emplace_back(s);
}
}
| 31.174603
| 98
| 0.709776
|
faodel
|
e5c3df8ba4595b3c658c146a3ff58059345fd197
| 679
|
cpp
|
C++
|
src/classes/Ciudad.cpp
|
mattaereal/AntColonyOptimization
|
b45df28cb181395d290d6c6accbc9297fa863aff
|
[
"MIT"
] | null | null | null |
src/classes/Ciudad.cpp
|
mattaereal/AntColonyOptimization
|
b45df28cb181395d290d6c6accbc9297fa863aff
|
[
"MIT"
] | null | null | null |
src/classes/Ciudad.cpp
|
mattaereal/AntColonyOptimization
|
b45df28cb181395d290d6c6accbc9297fa863aff
|
[
"MIT"
] | null | null | null |
/*
* Ciudad.cpp
*
* Created on: May 3, 2014
* Author: matt
*/
#include "Ciudad.h"
Ciudad::Ciudad(double c, string n, double p) {
this->pheromone = p;
this->cost = c;
this->name = n;
}
Ciudad::Ciudad() {
this->cost = 0;
this->pheromone = 0;
this->name = "Undefined, please define city";
}
Ciudad::~Ciudad() {
}
double Ciudad::getCost() const {
return cost;
}
void Ciudad::setCost(double c) {
this->cost = c;
}
const string & Ciudad::getName() const {
return name;
}
void Ciudad::setName(const string& n) {
this->name = n;
}
double Ciudad::getPheromone() const {
return pheromone;
}
void Ciudad::setPheromone(double ph) {
this->pheromone = ph;
}
| 13.58
| 46
| 0.630339
|
mattaereal
|
e5c71a4a32057faabff0ea40bcba8665a95d7538
| 2,072
|
cpp
|
C++
|
android-31/android/net/vcn/VcnGatewayConnectionConfig_Builder.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/android/net/vcn/VcnGatewayConnectionConfig_Builder.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-31/android/net/vcn/VcnGatewayConnectionConfig_Builder.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../../JLongArray.hpp"
#include "../ipsec/ike/IkeTunnelConnectionParams.hpp"
#include "./VcnGatewayConnectionConfig.hpp"
#include "../../../JString.hpp"
#include "./VcnGatewayConnectionConfig_Builder.hpp"
namespace android::net::vcn
{
// Fields
// QJniObject forward
VcnGatewayConnectionConfig_Builder::VcnGatewayConnectionConfig_Builder(QJniObject obj) : JObject(obj) {}
// Constructors
VcnGatewayConnectionConfig_Builder::VcnGatewayConnectionConfig_Builder(JString arg0, android::net::ipsec::ike::IkeTunnelConnectionParams arg1)
: JObject(
"android.net.vcn.VcnGatewayConnectionConfig$Builder",
"(Ljava/lang/String;Landroid/net/ipsec/ike/IkeTunnelConnectionParams;)V",
arg0.object<jstring>(),
arg1.object()
) {}
// Methods
android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::addExposedCapability(jint arg0) const
{
return callObjectMethod(
"addExposedCapability",
"(I)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;",
arg0
);
}
android::net::vcn::VcnGatewayConnectionConfig VcnGatewayConnectionConfig_Builder::build() const
{
return callObjectMethod(
"build",
"()Landroid/net/vcn/VcnGatewayConnectionConfig;"
);
}
android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::removeExposedCapability(jint arg0) const
{
return callObjectMethod(
"removeExposedCapability",
"(I)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;",
arg0
);
}
android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::setMaxMtu(jint arg0) const
{
return callObjectMethod(
"setMaxMtu",
"(I)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;",
arg0
);
}
android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::setRetryIntervalsMillis(JLongArray arg0) const
{
return callObjectMethod(
"setRetryIntervalsMillis",
"([J)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;",
arg0.object<jlongArray>()
);
}
} // namespace android::net::vcn
| 31.876923
| 143
| 0.770753
|
YJBeetle
|
e5caa02a9570fe3d651f75716711e14ad46223c2
| 1,559
|
cpp
|
C++
|
src/materials/HomogeneousMedia.cpp
|
ibfernandes/NarvalEngine
|
fb9ad53ebc7b244f4eed76f43e7aac2faa94772a
|
[
"MIT"
] | 6
|
2020-02-06T03:30:25.000Z
|
2021-10-12T11:38:24.000Z
|
src/materials/HomogeneousMedia.cpp
|
ibfernandes/NarvalEngine
|
fb9ad53ebc7b244f4eed76f43e7aac2faa94772a
|
[
"MIT"
] | 1
|
2021-07-29T17:38:23.000Z
|
2021-07-29T17:38:23.000Z
|
src/materials/HomogeneousMedia.cpp
|
ibfernandes/NarvalEngine
|
fb9ad53ebc7b244f4eed76f43e7aac2faa94772a
|
[
"MIT"
] | 1
|
2020-02-14T06:42:03.000Z
|
2020-02-14T06:42:03.000Z
|
#include "materials/HomogeneousMedia.h"
namespace narvalengine {
HomogeneousMedia::HomogeneousMedia(glm::vec3 scattering, glm::vec3 absorption, float density) {
this->scattering = scattering;
this->absorption = absorption;
this->extinction = absorption + scattering;
this->density = density;
}
HomogeneousMedia::~HomogeneousMedia() {
}
glm::vec3 HomogeneousMedia::Tr(float distance) {
glm::vec3 v = extinction * distance * density;
return exp(-v);
}
glm::vec3 HomogeneousMedia::Tr(Ray incoming, RayIntersection ri) {
return Tr(ri.tFar - ri.tNear);
}
/*
intersection must be inside or at the boundary of the volume
*/
glm::vec3 HomogeneousMedia::sample(Ray incoming, Ray &scattered, RayIntersection intersection) {
float t = -std::log(1 - random()) / avg(extinction);
float distInsideVolume = intersection.tFar - intersection.tNear;
t = t / distInsideVolume;
bool sampledMedia = t < distInsideVolume;
//point is inside volume
if (sampledMedia) {
//move ray to near intersection at voxel
scattered.o = incoming.getPointAt(t);
scattered.d = intersection.primitive->material->bsdf->sample(incoming.d, intersection.normal);
} else {
scattered.o = incoming.getPointAt(distInsideVolume + 0.001f);
scattered.d = incoming.d;
//return glm::vec3(0, 1, 0);
}
glm::vec3 Tr = this->Tr(t);
glm::vec3 density = sampledMedia ? (extinction * Tr) : Tr;
float pdf = avg(density);
if (pdf == 0) pdf = 1;
glm::vec3 result = sampledMedia ? (Tr * scattering / pdf) : Tr / pdf;
return result;
}
}
| 27.350877
| 97
| 0.695318
|
ibfernandes
|
e5cdc4d1f569a0ed885f165863170e5e1a0ebb24
| 764
|
cpp
|
C++
|
InsertionSortList.cpp
|
yplusplus/LeetCode
|
122bd31b291af1e97ee4e9349a8e65bba6e04c96
|
[
"MIT"
] | 3
|
2017-11-27T03:01:50.000Z
|
2021-03-13T08:14:00.000Z
|
InsertionSortList.cpp
|
yplusplus/LeetCode
|
122bd31b291af1e97ee4e9349a8e65bba6e04c96
|
[
"MIT"
] | null | null | null |
InsertionSortList.cpp
|
yplusplus/LeetCode
|
122bd31b291af1e97ee4e9349a8e65bba6e04c96
|
[
"MIT"
] | null | null | null |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode *new_head = NULL;
while (head) {
ListNode *next = head->next;
if (new_head == NULL || new_head->val > head->val) {
head->next = new_head;
new_head = head;
} else {
ListNode *p = new_head;
while (p->next != NULL && p->next->val < head->val) p = p->next;
head->next = p->next;
p->next = head;
}
head = next;
}
return new_head;
}
};
| 27.285714
| 80
| 0.458115
|
yplusplus
|
e5d5698fd37e77a6821d26a04bb9c8aa4ce06e25
| 48
|
hpp
|
C++
|
include/EnglishLogicConfig.hpp
|
mikhov-ivan/english-logic
|
1554cb42d816bc8446ec3be3ba35509fb3dfe0d0
|
[
"MIT"
] | null | null | null |
include/EnglishLogicConfig.hpp
|
mikhov-ivan/english-logic
|
1554cb42d816bc8446ec3be3ba35509fb3dfe0d0
|
[
"MIT"
] | null | null | null |
include/EnglishLogicConfig.hpp
|
mikhov-ivan/english-logic
|
1554cb42d816bc8446ec3be3ba35509fb3dfe0d0
|
[
"MIT"
] | null | null | null |
#define VERSION_MAJOR 1
#define VERSION_MINOR 0
| 16
| 23
| 0.833333
|
mikhov-ivan
|
e5d5f4730db4ae23fed4f1331cfe1f7b949c1554
| 4,806
|
hh
|
C++
|
3DVision_SourceCode_Group12/IsoExMod/IsoEx/Extractors/ExtendedMarchingCubesT.hh
|
kunal71091/Depth_Normal_Fusion
|
407e204abfbd6c8efe2f98a07415bd623ad84422
|
[
"MIT"
] | 1
|
2019-10-23T06:32:40.000Z
|
2019-10-23T06:32:40.000Z
|
3DVision_SourceCode_Group12/IsoExMod/IsoEx/Extractors/ExtendedMarchingCubesT.hh
|
kunal71091/Depth_Normal_Fusion
|
407e204abfbd6c8efe2f98a07415bd623ad84422
|
[
"MIT"
] | null | null | null |
3DVision_SourceCode_Group12/IsoExMod/IsoEx/Extractors/ExtendedMarchingCubesT.hh
|
kunal71091/Depth_Normal_Fusion
|
407e204abfbd6c8efe2f98a07415bd623ad84422
|
[
"MIT"
] | 1
|
2021-09-23T03:35:30.000Z
|
2021-09-23T03:35:30.000Z
|
/*===========================================================================*\
* *
* IsoEx *
* Copyright (C) 2002 by Computer Graphics Group, RWTH Aachen *
* www.rwth-graphics.de *
* *
*---------------------------------------------------------------------------*
* *
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*===========================================================================*/
//=============================================================================
//
// CLASS ExtendedMarchingCubesT
//
//=============================================================================
#ifndef ISOEX_EXTMARCHINGCUBEST_HH
#define ISOEX_EXTMARCHINGCUBEST_HH
//== INCLUDES =================================================================
#include <IsoEx/Extractors/Edge2VertexMapT.hh>
#include <IsoEx/Grids/Grid.hh>
#include <vector>
//== NAMESPACES ===============================================================
namespace IsoEx {
//== CLASS DEFINITION =========================================================
/** \class ExtendedMarchingCubesT ExtendedMarchingCubesT.hh <IsoEx/Extractors/ExtendedMarchingCubesT.hh>
This class implements the Extended Marching Cubes of Kobbelt et al,
Siggraph 2001.
The 0-level iso-surface is extracted in the constructor. Use it through
the convenience function
<b>IsoEx::extended_marching_cubes()</b>.
\ingroup extractors
*/
template <class Mesh, class Grid>
class ExtendedMarchingCubesT
{
public:
ExtendedMarchingCubesT(const Grid& _grid,
Mesh& _mesh,
double _feature_angle);
private:
typedef typename Grid::PointIdx PointIdx;
typedef typename Grid::CubeIdx CubeIdx;
typedef typename Grid::CubeIterator CubeIterator;
typedef typename Mesh::VertexHandle VertexHandle;
typedef std::vector<VertexHandle> VertexHandleVector;
void process_cube(CubeIdx _idx);
VertexHandle add_vertex(PointIdx _p0, PointIdx _p1);
VertexHandle find_feature(const VertexHandleVector& _vhandles);
void flip_edges();
const Grid& grid_;
Mesh& mesh_;
float feature_angle_;
unsigned int n_edges_, n_corners_;
// maps an edge to the sample vertex generated on it
Edge2VertexMapT<PointIdx, VertexHandle> edge2vertex_;
};
//-----------------------------------------------------------------------------
/** Convenience wrapper for the Extended Marching Cubes algorithm.
\see IsoEx::ExtendedMarchingCubesT
\ingroup extractors
*/
template <class Mesh, class Grid>
void extended_marching_cubes(const Grid& _grid,
Mesh& _mesh,
double _feature_angle)
{
ExtendedMarchingCubesT<Mesh,Grid> emc(_grid, _mesh, _feature_angle);
}
//=============================================================================
} // namespace IsoEx
//=============================================================================
#if defined(INCLUDE_TEMPLATES) && !defined(ISOEX_EXTMARCHINGCUBEST_C)
#define ISOEX_EXTMARCHINGCUBEST_TEMPLATES
#include "ExtendedMarchingCubesT.cc"
#endif
//=============================================================================
#endif // ISOEX_EXTMARCHINGCUBEST_HH defined
//=============================================================================
| 38.142857
| 104
| 0.445901
|
kunal71091
|
e5d8081d82ed686cf3cc2ee5be3492a853de7911
| 3,909
|
hpp
|
C++
|
include/mbgl/style/filter.hpp
|
TanJay/mapbox-gl-native
|
6348fe9f4acccce65d1396aa9eab79e6c44bcfc2
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
include/mbgl/style/filter.hpp
|
TanJay/mapbox-gl-native
|
6348fe9f4acccce65d1396aa9eab79e6c44bcfc2
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
include/mbgl/style/filter.hpp
|
TanJay/mapbox-gl-native
|
6348fe9f4acccce65d1396aa9eab79e6c44bcfc2
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
#pragma once
#include <mbgl/util/variant.hpp>
#include <mbgl/util/feature.hpp>
#include <mbgl/util/geometry.hpp>
#include <string>
#include <vector>
#include <tuple>
namespace mbgl {
namespace style {
class Filter;
class NullFilter {
public:
friend bool operator==(const NullFilter&, const NullFilter&) {
return true;
}
};
class EqualsFilter {
public:
std::string key;
Value value;
friend bool operator==(const EqualsFilter& lhs, const EqualsFilter& rhs) {
return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value);
}
};
class NotEqualsFilter {
public:
std::string key;
Value value;
friend bool operator==(const NotEqualsFilter& lhs, const NotEqualsFilter& rhs) {
return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value);
}
};
class LessThanFilter {
public:
std::string key;
Value value;
friend bool operator==(const LessThanFilter& lhs, const LessThanFilter& rhs) {
return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value);
}
};
class LessThanEqualsFilter {
public:
std::string key;
Value value;
friend bool operator==(const LessThanEqualsFilter& lhs, const LessThanEqualsFilter& rhs) {
return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value);
}
};
class GreaterThanFilter {
public:
std::string key;
Value value;
friend bool operator==(const GreaterThanFilter& lhs, const GreaterThanFilter& rhs) {
return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value);
}
};
class GreaterThanEqualsFilter {
public:
std::string key;
Value value;
friend bool operator==(const GreaterThanEqualsFilter& lhs, const GreaterThanEqualsFilter& rhs) {
return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value);
}
};
class InFilter {
public:
std::string key;
std::vector<Value> values;
friend bool operator==(const InFilter& lhs, const InFilter& rhs) {
return std::tie(lhs.key, lhs.values) == std::tie(rhs.key, rhs.values);
}
};
class NotInFilter {
public:
std::string key;
std::vector<Value> values;
friend bool operator==(const NotInFilter& lhs, const NotInFilter& rhs) {
return std::tie(lhs.key, lhs.values) == std::tie(rhs.key, rhs.values);
}
};
class AnyFilter {
public:
std::vector<Filter> filters;
friend bool operator==(const AnyFilter& lhs, const AnyFilter& rhs) {
return lhs.filters == rhs.filters;
}
};
class AllFilter {
public:
std::vector<Filter> filters;
friend bool operator==(const AllFilter& lhs, const AllFilter& rhs) {
return lhs.filters == rhs.filters;
}
};
class NoneFilter {
public:
std::vector<Filter> filters;
friend bool operator==(const NoneFilter& lhs, const NoneFilter& rhs) {
return lhs.filters == rhs.filters;
}
};
class HasFilter {
public:
std::string key;
friend bool operator==(const HasFilter& lhs, const HasFilter& rhs) {
return lhs.key == rhs.key;
}
};
class NotHasFilter {
public:
std::string key;
friend bool operator==(const NotHasFilter& lhs, const NotHasFilter& rhs) {
return lhs.key == rhs.key;
}
};
using FilterBase = variant<
class NullFilter,
class EqualsFilter,
class NotEqualsFilter,
class LessThanFilter,
class LessThanEqualsFilter,
class GreaterThanFilter,
class GreaterThanEqualsFilter,
class InFilter,
class NotInFilter,
class AnyFilter,
class AllFilter,
class NoneFilter,
class HasFilter,
class NotHasFilter>;
class Filter : public FilterBase {
public:
using FilterBase::FilterBase;
bool operator()(const Feature&) const;
template <class PropertyAccessor>
bool operator()(FeatureType type, optional<FeatureIdentifier> id, PropertyAccessor accessor) const;
};
} // namespace style
} // namespace mbgl
| 22.210227
| 103
| 0.665643
|
TanJay
|
e5d9066ad1106be9e446fbc5f940183ea2859206
| 3,455
|
cpp
|
C++
|
src/OpcUaStackServer/AddressSpaceModel/BaseNodeClass.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 108
|
2018-10-08T17:03:32.000Z
|
2022-03-21T00:52:26.000Z
|
src/OpcUaStackServer/AddressSpaceModel/BaseNodeClass.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 287
|
2018-09-18T14:59:12.000Z
|
2022-01-13T12:28:23.000Z
|
src/OpcUaStackServer/AddressSpaceModel/BaseNodeClass.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 32
|
2018-10-19T14:35:03.000Z
|
2021-11-12T09:36:46.000Z
|
/*
Copyright 2015-2017 Kai Huebl (kai@huebl-sgh.de)
Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser
Datei nur in Übereinstimmung mit der Lizenz erlaubt.
Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0.
Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart,
erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE
GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend.
Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen
im Rahmen der Lizenz finden Sie in der Lizenz.
Autor: Kai Huebl (kai@huebl-sgh.de)
*/
#include "OpcUaStackServer/AddressSpaceModel/BaseNodeClass.h"
namespace OpcUaStackServer
{
BaseNodeClass::BaseNodeClass(void)
: nodeId_()
, nodeClass_()
, browseName_()
, displayName_()
, description_()
, writeMask_()
, userWriteMask_()
, forwardNodeSync_()
{
}
BaseNodeClass::BaseNodeClass(NodeClassType nodeClass)
: nodeId_()
, nodeClass_(nodeClass)
, browseName_()
, displayName_()
, description_()
, writeMask_()
, userWriteMask_()
, forwardNodeSync_()
{
}
BaseNodeClass::~BaseNodeClass(void)
{
}
NodeIdAttribute&
BaseNodeClass::nodeId(void)
{
return nodeId_;
}
NodeClassAttribute&
BaseNodeClass::nodeClass(void)
{
return nodeClass_;
}
BrowseNameAttribute&
BaseNodeClass::browseName(void)
{
return browseName_;
}
DisplayNameAttribute&
BaseNodeClass::displayName(void)
{
return displayName_;
}
DescriptionAttribute&
BaseNodeClass::description(void)
{
return description_;
}
WriteMaskAttribute&
BaseNodeClass::writeMask(void)
{
return writeMask_;
}
UserWriteMaskAttribute&
BaseNodeClass::userWriteMask(void)
{
return userWriteMask_;
}
Attribute*
BaseNodeClass::nodeIdAttribute(void)
{
return &nodeId_;
}
Attribute*
BaseNodeClass::nodeClassAttribute(void)
{
return &nodeClass_;
}
Attribute*
BaseNodeClass::browseNameAttribute(void)
{
return &browseName_;
}
Attribute*
BaseNodeClass::displayNameAttribute(void)
{
return &displayName_;
}
Attribute*
BaseNodeClass::descriptionAttribute(void)
{
return &description_;
}
Attribute*
BaseNodeClass::writeMaskAttribute(void)
{
return &writeMask_;
}
Attribute*
BaseNodeClass::userWriteMaskAttribute(void)
{
return &userWriteMask_;
}
ReferenceItemMap&
BaseNodeClass::referenceItemMap(void)
{
return referenceItemMap_;
}
void
BaseNodeClass::copyTo(BaseNodeClass::SPtr baseNodeClass)
{
copyTo(*baseNodeClass);
}
void
BaseNodeClass::copyTo(BaseNodeClass& baseNodeClass)
{
nodeIdAttribute()->copyTo(baseNodeClass.nodeIdAttribute());
nodeClassAttribute()->copyTo(baseNodeClass.nodeClassAttribute());
browseNameAttribute()->copyTo(baseNodeClass.browseNameAttribute());
displayNameAttribute()->copyTo(baseNodeClass.displayNameAttribute());
descriptionAttribute()->copyTo(baseNodeClass.descriptionAttribute());
writeMaskAttribute()->copyTo(baseNodeClass.writeMaskAttribute());
userWriteMaskAttribute()->copyTo(baseNodeClass.userWriteMaskAttribute());
referenceItemMap_.copyTo(baseNodeClass.referenceItemMap());
}
void
BaseNodeClass::forwardNodeSync(ForwardNodeSync::SPtr forwardNodeSync)
{
forwardNodeSync_ = forwardNodeSync;
}
ForwardNodeSync::SPtr
BaseNodeClass::forwardNodeSync(void)
{
return forwardNodeSync_;
}
}
| 19.971098
| 86
| 0.754269
|
gianricardo
|
e5db1ceefa47fb1c63edd6f59d89695fab5ebf8a
| 1,860
|
hpp
|
C++
|
code/include/boids2D/Boid.hpp
|
Shutter-Island-Team/Shutter-island
|
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
|
[
"MIT"
] | 4
|
2016-06-24T09:22:18.000Z
|
2019-06-13T13:50:53.000Z
|
code/include/boids2D/Boid.hpp
|
Shutter-Island-Team/Shutter-island
|
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
|
[
"MIT"
] | null | null | null |
code/include/boids2D/Boid.hpp
|
Shutter-Island-Team/Shutter-island
|
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
|
[
"MIT"
] | 2
|
2016-06-10T12:46:17.000Z
|
2018-10-14T06:37:21.000Z
|
#ifndef BOID_HPP
#define BOID_HPP
#include <glm/glm.hpp>
#include <memory>
#include <vector>
#include "BoidType.hpp"
/**
* @class Boid
* @brief Parent class for a Boid (can be rooted or movable)
*/
class Boid
{
public:
/**
* @brief Constructor for a Boid
* @param[in] location The initial position
* @param[in] t Type of the boid
*/
Boid(glm::vec3 location, BoidType t);
/**
* @brief Getter for the location
*/
const glm::vec3 & getLocation() const;
/**
* @brief Setter for the location
* @param[in] location The new location
*/
void setLocation(const glm::vec3 & location);
/**
* @brief Getter of the angle
*/
const float & getAngle() const;
/**
* @brief Setter of the angle
* @param[in] angle The new angle
*/
void setAngle(const float & angle);
/**
* @brief Getter of the type of the boid
* @return Type of the boid
*/
const BoidType & getBoidType() const;
/**
* @brief Getter of the size of the boid
*/
const float & getScale() const;
/**
* @brief Setter of the size of the boid
*/
void setScale(const float & scale);
void disapear();
const bool & toDisplay() const;
bool isFoodRemaining() const;
void decreaseFoodRemaining();
bool isDecomposed() const;
void bodyDecomposition();
protected:
/**
* @brief Constructor for a Boid
* @param[in] location The initial position
* @param[in] t Type of the boid
*/
Boid(glm::vec3 location, BoidType t, int amountFood);
glm::vec3 m_location; ///< Position of the boid
private:
BoidType m_boidType; ///< Type of the boid @see BoidType.hpp
float m_angle; ///< Angle of position of the boid
float m_scale; ///< Size of the boid
bool m_display;
int m_amountFood;
float m_decomposition;
};
typedef std::shared_ptr<Boid> BoidPtr;
#endif
| 19.375
| 62
| 0.639247
|
Shutter-Island-Team
|
e5db32d10e0d6bb07f5501200886eda9f3445bcb
| 1,433
|
cxx
|
C++
|
direct/src/plugin/run_p3dpython.cxx
|
kestred/panda3d
|
16bfd3750f726a8831771b81649d18d087917fd5
|
[
"PHP-3.01",
"PHP-3.0"
] | 3
|
2018-03-09T12:07:29.000Z
|
2021-02-25T06:50:25.000Z
|
direct/src/plugin/run_p3dpython.cxx
|
Sinkay/panda3d
|
16bfd3750f726a8831771b81649d18d087917fd5
|
[
"PHP-3.01",
"PHP-3.0"
] | null | null | null |
direct/src/plugin/run_p3dpython.cxx
|
Sinkay/panda3d
|
16bfd3750f726a8831771b81649d18d087917fd5
|
[
"PHP-3.01",
"PHP-3.0"
] | null | null | null |
// Filename: run_p3dpython.cxx
// Created by: drose (29Aug09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "p3dPythonRun.h"
#include "run_p3dpython.h"
////////////////////////////////////////////////////////////////////
// Function: run_p3dpython
// Description: This externally-visible function is the main entry
// point to this DLL, and it starts the whole thing
// running. Returns true on success, false on failure.
////////////////////////////////////////////////////////////////////
bool
run_p3dpython(const char *program_name, const char *archive_file,
FHandle input_handle, FHandle output_handle,
const char *log_pathname, bool interactive_console) {
P3DPythonRun::_global_ptr =
new P3DPythonRun(program_name, archive_file, input_handle, output_handle,
log_pathname, interactive_console);
bool result = P3DPythonRun::_global_ptr->run_python();
delete P3DPythonRun::_global_ptr;
P3DPythonRun::_global_ptr = NULL;
return result;
}
| 39.805556
| 78
| 0.571528
|
kestred
|
e5dbc06954d6a35ea13235b91c158246ea1a534a
| 287
|
cpp
|
C++
|
DarkestTowerServer/DarkestTowerServer/Fighter.cpp
|
OztGod/DarkestTowerServer
|
65043e1e7b158727f7f6ad7c008f1f2847174542
|
[
"MIT"
] | null | null | null |
DarkestTowerServer/DarkestTowerServer/Fighter.cpp
|
OztGod/DarkestTowerServer
|
65043e1e7b158727f7f6ad7c008f1f2847174542
|
[
"MIT"
] | 2
|
2015-09-23T17:17:52.000Z
|
2015-09-23T18:16:46.000Z
|
DarkestTowerServer/DarkestTowerServer/Fighter.cpp
|
OztGod/DarkestTowerServer
|
65043e1e7b158727f7f6ad7c008f1f2847174542
|
[
"MIT"
] | null | null | null |
#include "Fighter.h"
#include "FighterAttack.h"
#include "Charge.h"
Fighter::Fighter(int idx)
:Hero(HeroClass::FIGHTER, 17 + rand() % 4, 5 + rand() % 2, idx)
{
skills.push_back(SkillInfo(std::make_unique<FighterAttack>()));
skills.push_back(SkillInfo(std::make_unique<Charge>()));
}
| 26.090909
| 64
| 0.700348
|
OztGod
|
e5de1c12a0f2f37847a3bf7b8f1b83a25aa37ca3
| 202
|
hpp
|
C++
|
addons/CBRN_sounds/sounds/assaultboy/cfgVehicles.hpp
|
ASO-TheM/ChemicalWarfare
|
51322934ef1da7ba0f3bb04c1d537767d8e48cc4
|
[
"MIT"
] | 4
|
2018-04-28T16:09:21.000Z
|
2021-08-24T12:51:55.000Z
|
addons/CBRN_sounds/sounds/assaultboy/cfgVehicles.hpp
|
ASO-TheM/ChemicalWarfare
|
51322934ef1da7ba0f3bb04c1d537767d8e48cc4
|
[
"MIT"
] | 29
|
2018-04-01T23:31:33.000Z
|
2020-01-02T17:02:11.000Z
|
addons/CBRN_sounds/sounds/assaultboy/cfgVehicles.hpp
|
ASO-TheM/ChemicalWarfare
|
51322934ef1da7ba0f3bb04c1d537767d8e48cc4
|
[
"MIT"
] | 10
|
2018-07-13T15:02:06.000Z
|
2021-04-06T17:12:11.000Z
|
class Sound_CBRN_cough_assaultboy:Sound_CBRN_coughBase {sound = "CBRN_cough_assaultboy";};
class Sound_CBRN_coughMuffled_assaultboy:Sound_CBRN_coughMuffledBase {sound = "CBRN_coughMuffled_assaultboy";};
| 101
| 111
| 0.876238
|
ASO-TheM
|
e5de8c7bde5e7838158f776a68a38781533229f6
| 8,252
|
cpp
|
C++
|
catkin_ws/src/control_stack/src/sim/simulator_node.cpp
|
VishnuPrem/multi_robot_restaurant
|
6aea83a3c7acd9b7d25e1a2c6e05ef3a5c28a876
|
[
"MIT"
] | 7
|
2020-06-23T23:34:33.000Z
|
2020-12-11T20:08:11.000Z
|
catkin_ws/src/control_stack/src/sim/simulator_node.cpp
|
VishnuPrem/multi_robot_restaurant
|
6aea83a3c7acd9b7d25e1a2c6e05ef3a5c28a876
|
[
"MIT"
] | null | null | null |
catkin_ws/src/control_stack/src/sim/simulator_node.cpp
|
VishnuPrem/multi_robot_restaurant
|
6aea83a3c7acd9b7d25e1a2c6e05ef3a5c28a876
|
[
"MIT"
] | 4
|
2020-09-02T20:17:22.000Z
|
2020-10-19T01:51:29.000Z
|
// Copyright 2019 kvedder@seas.upenn.edu
// School of Engineering and Applied Sciences,
// University of Pennsylvania
//
//
// 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 <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <visualization_msgs/MarkerArray.h>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
#include <algorithm>
#include <cmath>
#include <random>
#include <string>
#include <vector>
#include "cs/util/constants.h"
#include "cs/util/map.h"
#include "cs/util/pose.h"
#include "cs/util/util.h"
#include "cs/util/visualization.h"
#include "shared/math/geometry.h"
#include "shared/math/math_util.h"
#include "config_reader/config_reader.h"
namespace sim {
CONFIG_FLOAT(kLaserStdDev, "sim.kLaserStdDev");
CONFIG_FLOAT(kArcExecStdDev, "sim.kArcExecStdDev");
CONFIG_FLOAT(kArcReadStdDev, "sim.kArcReadStdDev");
CONFIG_FLOAT(kRotateExecStdDev, "sim.kRotateExecStdDev");
CONFIG_FLOAT(kRotateReadStdDev, "sim.kRotateReadStdDev");
CONFIG_FLOAT(kStartPositionX, "sim.kStartPositionX");
CONFIG_FLOAT(kStartPositionY, "sim.kStartPositionY");
CONFIG_FLOAT(kStartPositionTheta, "sim.kStartPositionTheta");
CONFIG_STRING(kMap, "sim.kMap");
CONFIG_FLOAT(laser_min_angle, "sim.laser.min_angle");
CONFIG_FLOAT(laser_max_angle, "sim.laser.max_angle");
CONFIG_INT(laser_num_readings, "sim.laser.num_readings");
CONFIG_FLOAT(laser_angle_delta, "sim.laser.angle_delta");
CONFIG_FLOAT(laser_min_reading, "sim.laser.min_reading");
CONFIG_FLOAT(laser_max_reading, "sim.laser.max_reading");
} // namespace sim
// std::random_device rd;
std::mt19937 gen(0);
std_msgs::Header MakeHeader(const std::string& frame_id) {
static uint32_t seq = 0;
std_msgs::Header header;
header.seq = (++seq);
header.frame_id = frame_id;
header.stamp = ros::Time::now();
return header;
}
sensor_msgs::LaserScan MakeScan(const util::Pose& robot_pose,
const util::Map& map,
const float noise_stddev) {
std::normal_distribution<> noise_dist(0.0f, noise_stddev);
sensor_msgs::LaserScan scan;
scan.header = MakeHeader("laser");
scan.angle_min = sim::CONFIG_laser_min_angle;
scan.angle_max = sim::CONFIG_laser_max_angle;
scan.angle_increment = sim::CONFIG_laser_angle_delta;
scan.range_min = sim::CONFIG_laser_min_reading;
scan.range_max = sim::CONFIG_laser_max_reading;
scan.scan_time = 0;
scan.time_increment = 0;
for (int ray_idx = 0; ray_idx < sim::CONFIG_laser_num_readings; ++ray_idx) {
const float angle = math_util::AngleMod(sim::CONFIG_laser_min_angle +
sim::CONFIG_laser_angle_delta *
static_cast<float>(ray_idx) +
robot_pose.rot);
const util::Pose ray(robot_pose.tra, angle);
const float dist =
map.MinDistanceAlongRay(ray,
sim::CONFIG_laser_min_reading,
sim::CONFIG_laser_max_reading - kEpsilon);
scan.ranges.push_back(dist + noise_dist(gen));
}
return scan;
}
util::Twist AddExecutionOdomNoise(util::Twist move) {
std::normal_distribution<> along_arc_dist(
0.0f, sim::CONFIG_kArcExecStdDev * move.tra.norm());
std::normal_distribution<> rotation_dist(
0.0f, sim::CONFIG_kRotateExecStdDev * move.rot + 0.005);
move.tra.x() += along_arc_dist(gen);
move.rot += rotation_dist(gen);
return move;
}
util::Twist AddReadingOdomNoise(util::Twist move) {
std::normal_distribution<> along_arc_dist(
0.0f, sim::CONFIG_kArcReadStdDev * move.tra.norm());
std::normal_distribution<> rotation_dist(
0.0f, sim::CONFIG_kRotateReadStdDev * move.rot);
move.tra.x() += along_arc_dist(gen);
move.rot += rotation_dist(gen);
return move;
}
template <typename T>
util::Pose FollowTrajectory(const util::Pose& pose_global_frame,
const T& distance_along_arc,
const T& rotation) {
const Eigen::Rotation2Df robot_to_global_frame(pose_global_frame.rot);
const Eigen::Matrix<T, 2, 1> robot_forward_global_frame =
robot_to_global_frame * Eigen::Matrix<T, 2, 1>(1, 0);
if (rotation == 0) {
util::Pose updated_pose = pose_global_frame;
updated_pose.tra += robot_forward_global_frame * distance_along_arc;
return updated_pose;
}
const T circle_radius = distance_along_arc / rotation;
const T move_x_dst = std::sin(rotation) * circle_radius;
const T move_y_dst = std::cos(fabs(rotation)) * circle_radius - circle_radius;
const Eigen::Matrix<T, 2, 1> movement_arc_robot_frame(move_x_dst, move_y_dst);
const Eigen::Matrix<T, 2, 1> movement_arc_global_frame =
robot_to_global_frame * movement_arc_robot_frame;
return {movement_arc_global_frame + pose_global_frame.tra,
math_util::AngleMod(rotation + pose_global_frame.rot)};
}
util::Twist commanded_velocity;
void CommandedVelocityCallback(const geometry_msgs::Twist& nv) {
commanded_velocity = util::Twist(nv);
}
int main(int argc, char** argv) {
util::PrintCurrentWorkingDirectory();
config_reader::ConfigReader reader(
{"src/ServiceRobotControlStack/control_stack/config/nav_config.lua",
"src/ServiceRobotControlStack/control_stack/config/sim_config.lua"});
ros::init(argc, argv, "simulator");
ros::NodeHandle n;
ros::Publisher initial_pose_pub =
n.advertise<geometry_msgs::Twist>("true_pose", 1);
ros::Publisher scan_pub =
n.advertise<sensor_msgs::LaserScan>(constants::kLaserTopic, 10);
ros::Publisher odom_pub =
n.advertise<nav_msgs::Odometry>(constants::kOdomTopic, 10);
ros::Publisher map_pub = n.advertise<visualization_msgs::Marker>("map", 10);
ros::Publisher initial_pose_vis_pub =
n.advertise<visualization_msgs::MarkerArray>("true_pose_vis", 1);
ros::Subscriber command_sub = n.subscribe(
constants::kCommandVelocityTopic, 10, &CommandedVelocityCallback);
static constexpr float kLoopRate = 10;
ros::Rate loop_rate(kLoopRate);
const util::Map map(sim::CONFIG_kMap);
util::Pose current_pose(sim::CONFIG_kStartPositionX,
sim::CONFIG_kStartPositionY,
sim::CONFIG_kStartPositionTheta);
while (ros::ok()) {
const util::Twist executed_move =
AddExecutionOdomNoise(commanded_velocity / kLoopRate);
const util::Twist reported_move = AddReadingOdomNoise(executed_move);
current_pose = FollowTrajectory(
current_pose, executed_move.tra.x(), executed_move.rot);
scan_pub.publish(MakeScan(current_pose, map, sim::CONFIG_kLaserStdDev));
nav_msgs::Odometry odom_msg;
odom_msg.header = MakeHeader("base_link");
odom_msg.twist.twist = (reported_move * kLoopRate).ToTwist();
odom_pub.publish(odom_msg);
initial_pose_pub.publish(current_pose.ToTwist());
visualization_msgs::MarkerArray arr;
visualization::DrawPose(
current_pose, "map", "true_pose_vis", 1, 1, 1, 1, &arr);
initial_pose_vis_pub.publish(arr);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
| 37.853211
| 80
| 0.708434
|
VishnuPrem
|
e5e7a30ebbffc75b417222539fae251a92732333
| 2,747
|
cpp
|
C++
|
Editor/gui/InspectorWidget/widget/impl/CameraComponentWidget.cpp
|
obivan43/pawnengine
|
ec092fa855d41705f3fb55fcf1aa5e515d093405
|
[
"MIT"
] | null | null | null |
Editor/gui/InspectorWidget/widget/impl/CameraComponentWidget.cpp
|
obivan43/pawnengine
|
ec092fa855d41705f3fb55fcf1aa5e515d093405
|
[
"MIT"
] | null | null | null |
Editor/gui/InspectorWidget/widget/impl/CameraComponentWidget.cpp
|
obivan43/pawnengine
|
ec092fa855d41705f3fb55fcf1aa5e515d093405
|
[
"MIT"
] | null | null | null |
#include "CameraComponentWidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
namespace editor::impl {
CameraComponentWidget::CameraComponentWidget(QWidget* parent)
: QWidget(parent)
, m_Camera(nullptr)
, m_Projection(nullptr)
, m_ProjectionLabel(nullptr)
, m_IsActiveCamera(nullptr)
, m_IsActiveCameraLabel(nullptr) {
QVBoxLayout* layout = new QVBoxLayout(this);
QHBoxLayout* projectionLayout = new QHBoxLayout();
m_Projection = new QComboBox(this);
m_Projection->addItem("Perspective", pawn::math::CameraType::Perspective);
m_Projection->addItem("Orthographic", pawn::math::CameraType::Orthographic);
m_ProjectionLabel = new QLabel("Projection", this);
m_ProjectionLabel->setMinimumWidth(80);
projectionLayout->addWidget(m_ProjectionLabel);
projectionLayout->addWidget(m_Projection);
QHBoxLayout* activeCameraLayout = new QHBoxLayout();
m_IsActiveCamera = new QCheckBox(this);
m_IsActiveCameraLabel = new QLabel("Active camera", this);
m_IsActiveCameraLabel->setMinimumWidth(80);
activeCameraLayout->addWidget(m_IsActiveCameraLabel);
activeCameraLayout->addWidget(m_IsActiveCamera);
layout->addLayout(projectionLayout);
layout->addLayout(activeCameraLayout);
setLayout(layout);
InitConnections();
}
void CameraComponentWidget::OnProjectionChanged(int index) {
if (m_Camera) {
pawn::math::Camera& camera = static_cast<pawn::math::Camera&>(*m_Camera);
pawn::math::CameraType type = qvariant_cast<pawn::math::CameraType>(m_Projection->itemData(index));
switch (type) {
case pawn::math::CameraType::Perspective:
{
camera.SetPerspective();
break;
}
case pawn::math::CameraType::Orthographic:
{
camera.SetOrthographic();
break;
}
default:
break;
}
}
}
void CameraComponentWidget::OnActiveCameraStateChanged(bool state) {
if (m_Camera) {
m_Camera->IsActiveCamera = state;
}
}
void CameraComponentWidget::SetCamera(pawn::engine::CameraComponent* camera) {
m_Camera = camera;
if (m_Camera) {
pawn::math::Camera& camera = static_cast<pawn::math::Camera&>(*m_Camera);
pawn::math::CameraType type = camera.GetType();
int index = m_Projection->findData(type);
if (index != -1) {
m_Projection->setCurrentIndex(index);
}
m_IsActiveCamera->setChecked(m_Camera->IsActiveCamera);
}
}
void CameraComponentWidget::InitConnections() {
connect(
m_Projection,
SIGNAL(currentIndexChanged(int)),
this,
SLOT(OnProjectionChanged(int))
);
connect(
m_IsActiveCamera,
SIGNAL(clicked(bool)),
this,
SLOT(OnActiveCameraStateChanged(bool))
);
}
}
| 25.201835
| 103
| 0.69312
|
obivan43
|
e5e9918171f8610da10971bf5ef47eacc1d9275c
| 5,711
|
cpp
|
C++
|
CookieEngine/src/Render/Drawers/MiniMapDrawer.cpp
|
qbleuse/Cookie-Engine
|
705d19d9e4c79e935e32244759ab63523dfbe6c4
|
[
"CC-BY-4.0"
] | null | null | null |
CookieEngine/src/Render/Drawers/MiniMapDrawer.cpp
|
qbleuse/Cookie-Engine
|
705d19d9e4c79e935e32244759ab63523dfbe6c4
|
[
"CC-BY-4.0"
] | null | null | null |
CookieEngine/src/Render/Drawers/MiniMapDrawer.cpp
|
qbleuse/Cookie-Engine
|
705d19d9e4c79e935e32244759ab63523dfbe6c4
|
[
"CC-BY-4.0"
] | null | null | null |
#include "Core/Math/Mat4.hpp"
#include "Render/D3D11Helper.hpp"
#include "Resources/Mesh.hpp"
#include "Resources/Texture.hpp"
#include "Core/Primitives.hpp"
#include "Resources/Map.hpp"
#include "Render/DrawDataHandler.hpp"
#include "Render/Drawers/MiniMapDrawer.hpp"
#include "Render/Camera.hpp"
using namespace Cookie::Core::Math;
using namespace Cookie::Render;
struct VS_CONSTANT_BUFFER
{
Mat4 model;
Vec4 tileNb;
};
/*======================= CONSTRUCTORS/DESTRUCTORS =======================*/
MiniMapDrawer::MiniMapDrawer():
mapMesh{Core::Primitives::CreateCube()},
quadColor{ std::make_unique<Resources::Texture>("White", Vec4(MINI_MAP_QUAD_COLOR)) }
{
InitShader();
/* creating a quad that works with line strips */
std::vector<float> vertices = { -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f };
std::vector<unsigned int> indices = { 0 , 1, 2, 3 , 0 };
quad = std::make_unique<Resources::Mesh>("lineQuad", vertices, indices, 5);
}
MiniMapDrawer::~MiniMapDrawer()
{
if (VShader)
{
VShader->Release();
}
if (PShader)
{
PShader->Release();
}
if (VCBuffer)
{
VCBuffer->Release();
}
if (ILayout)
{
ILayout->Release();
}
}
/*======================= INIT METHODS =======================*/
void MiniMapDrawer::InitShader()
{
ID3DBlob* blob = nullptr;
std::string source = (const char*)R"(#line 27
struct VOut
{
float4 position : SV_POSITION;
float2 uv : UV;
};
cbuffer MODEL_CONSTANT : register(b0)
{
float4x4 model;
float2 tileNb;
};
cbuffer CAM_CONSTANT : register(b1)
{
float4x4 proj;
float4x4 view;
};
VOut main(float3 position : POSITION, float2 uv : UV, float3 normal : NORMAL)
{
VOut output;
output.position = mul(mul(mul(float4(position,1.0),model),view), proj);
output.uv = uv * tileNb;
return output;
}
)";
Render::CompileVertex(source, &blob, &VShader);
source = (const char*)R"(#line 83
Texture2D albedoTex : register(t0);
SamplerState WrapSampler : register(s0);
float4 main(float4 position : SV_POSITION, float2 uv : UV) : SV_TARGET
{
return float4(albedoTex.Sample(WrapSampler,uv).rgb,1.0);
})";
struct Vertex
{
Core::Math::Vec3 position;
Core::Math::Vec2 uv;
Core::Math::Vec3 normal;
};
// create the input layout object
D3D11_INPUT_ELEMENT_DESC ied[] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex,position), D3D11_INPUT_PER_VERTEX_DATA, 0},
{"UV", 0, DXGI_FORMAT_R32G32_FLOAT, 0, offsetof(Vertex, uv), D3D11_INPUT_PER_VERTEX_DATA, 0},
{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, normal), D3D11_INPUT_PER_VERTEX_DATA, 0},
};
Render::CreateLayout(&blob, ied, 3, &ILayout);
Render::CompilePixel(source, &PShader);
VS_CONSTANT_BUFFER vbuffer = {};
Render::CreateBuffer(&vbuffer, sizeof(VS_CONSTANT_BUFFER), &VCBuffer);
blob->Release();
}
/*======================= REALTIME METHODS =======================*/
void MiniMapDrawer::Set(const Camera& cam, const Resources::Map& map)
{
mapAlbedo = map.model.albedo;
mapTrs = map.trs.TRS;
tileNb = map.tilesNb;
Vec3 middle = cam.ScreenPointToWorldDir({ { 0.0f,0.0f } });
//Vec3 UpperRight = cam.ScreenPointToWorldDir({ { 1.0f,1.0f } });
//Vec3 DownLeft = cam.ScreenPointToWorldDir({ { -1.0f,-1.0f } });
//
float t = (-cam.pos.y) / middle.y;
middle = cam.pos + middle * t;
//t = (-cam.pos.y) / UpperRight.y;
//UpperRight = cam.pos + UpperRight * t;
//t = (-cam.pos.y) / DownLeft.y;
//DownLeft = cam.pos + DownLeft * t;
quadTrs = Mat4::Scale({ 10.0f,1.0f,10.0f }) * Mat4::Translate(middle);
}
void MiniMapDrawer::Draw()
{
/* set shader */
RendererRemote::context->VSSetShader(VShader, nullptr, 0);
RendererRemote::context->PSSetShader(PShader, nullptr, 0);
RendererRemote::context->IASetInputLayout(ILayout);
/* filling constant buffer with map info */
VS_CONSTANT_BUFFER vbuffer = {};
vbuffer.model = mapTrs;
vbuffer.tileNb = { tileNb.x,tileNb.y,0.0f,0.0f };
RendererRemote::context->VSSetConstantBuffers(0, 1, &VCBuffer);
WriteBuffer(&vbuffer, sizeof(vbuffer), 0, &VCBuffer);;
/* map texture */
if (mapAlbedo)
mapAlbedo->Set(0);
/* then draw the map */
mapMesh->Set();
mapMesh->Draw();
/* drawing the quad of view of the cam */
RendererRemote::context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);
/* removing depth buffer */
ID3D11RenderTargetView* rtv = nullptr;
Render::RendererRemote::context->OMGetRenderTargets(1, &rtv, nullptr);
Render::RendererRemote::context->OMSetRenderTargets(1, &rtv, nullptr);
/* we can use the same shader as it is pretty close put matrix in vbuffer */
vbuffer.model = quadTrs;
WriteBuffer(&vbuffer, sizeof(vbuffer), 0, &VCBuffer);
/* set a white texture and draw */
quadColor->Set();
quad->Set();
quad->Draw();
/* when you use Getter in dx11 it adds a ref in the object,
* so we release it*/
rtv->Release();
RendererRemote::context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
| 28.133005
| 120
| 0.596568
|
qbleuse
|
e5ec6bfd9225a596f2111ae906a938b3348f3bd1
| 2,495
|
hpp
|
C++
|
inc/dirac_op.hpp
|
lkeegan/canonical
|
9380e8026f637e50b6354eaf9aeb6728b28bac3c
|
[
"MIT"
] | null | null | null |
inc/dirac_op.hpp
|
lkeegan/canonical
|
9380e8026f637e50b6354eaf9aeb6728b28bac3c
|
[
"MIT"
] | null | null | null |
inc/dirac_op.hpp
|
lkeegan/canonical
|
9380e8026f637e50b6354eaf9aeb6728b28bac3c
|
[
"MIT"
] | null | null | null |
#ifndef LKEEGAN_CANONICAL_DIRAC_OP_H
#define LKEEGAN_CANONICAL_DIRAC_OP_H
#include <random>
#include "4d.hpp"
#include "Eigen3/Eigen/Eigenvalues"
#include "omp.h"
#include "su3.hpp"
// staggered space-dependent gamma matrices
// for now stored as 5x doubles per site but they are just +/- signs, and g[0]
// is just + everywhere g[4] is gamma_5
class gamma_matrices {
private:
double g_[5];
public:
double& operator[](int i) { return g_[i]; }
double operator[](int i) const { return g_[i]; }
};
// Staggered dirac operator
class dirac_op {
private:
// Construct staggered eta (gamma) matrices
void construct_eta(field<gamma_matrices>& eta, const lattice& grid);
public:
std::ranlux48 rng;
double mass;
double mu_I;
field<gamma_matrices> eta;
bool ANTI_PERIODIC_BCS = true;
bool GAUGE_LINKS_INCLUDE_ETA_BCS = false;
dirac_op(const lattice& grid, double mass, double mu_I = 0.0);
explicit dirac_op(const lattice& grid) : dirac_op::dirac_op(grid, 0.0, 0.0) {}
void apbcs_in_time(field<gauge>& U) const;
// Applies eta matrices and apbcs in time to the gauge links U
// Required before and after using EO versions of dirac op
// Toggles flag GAUGE_LINKS_INCLUDE_ETA_BCS
void apply_eta_bcs_to_U(field<gauge>& U);
void remove_eta_bcs_from_U(field<gauge>& U);
// Axial gauge: all timelike links 1 except at T-1 boundary
void gauge_fix_axial(field<gauge>& U) const;
void gaussian_P(field<gauge>& P);
void random_U(field<gauge>& U, double eps);
// Returns eigenvalues of Dirac op
// Explicitly constructs dense (3*VOL)x(3*VOL) matrix Dirac op and finds all
// eigenvalues
Eigen::MatrixXcd D_eigenvalues(field<gauge>& U);
// Same for DDdagger, but much faster since we can use a hermitian solver.
Eigen::MatrixXcd DDdagger_eigenvalues(field<gauge>& U);
// explicitly construct dirac op as dense (3*VOL)x(3*VOL) matrix
Eigen::MatrixXcd D_dense_matrix(field<gauge>& U);
// explicitly construct dense (2x3xVOL3)x(2x3xVOL3) matrix P
// diagonalise and return all eigenvalues
// NOTE: also gauge fixes U to axial gauge
// NOTE2: also multiplies single gauge link U[T-1,ix3=0] by exp(i theta)
Eigen::MatrixXcd P_eigenvalues(field<gauge>& U, double theta = 0.0);
// explicitly construct dense (2x3xVOL3)x(2x3xVOL3) matrix
// B at timeslice it, using normalisation D = 2m + U..
// MUST be lexi grid layout for U!
Eigen::MatrixXcd B_dense_matrix(field<gauge>& U, int it);
};
#endif // LKEEGAN_CANONICAL_DIRAC_OP_H
| 32.828947
| 80
| 0.726653
|
lkeegan
|
e5ec74faa22ac5c889e31f6c93ef137cdb41447a
| 5,108
|
cc
|
C++
|
src/tim/vx/ops/rnn_cell.cc
|
gdh1995/TIM-VX
|
242a6bd05ae9153a6b563c39e6f6de16568812df
|
[
"MIT"
] | null | null | null |
src/tim/vx/ops/rnn_cell.cc
|
gdh1995/TIM-VX
|
242a6bd05ae9153a6b563c39e6f6de16568812df
|
[
"MIT"
] | null | null | null |
src/tim/vx/ops/rnn_cell.cc
|
gdh1995/TIM-VX
|
242a6bd05ae9153a6b563c39e6f6de16568812df
|
[
"MIT"
] | null | null | null |
/****************************************************************************
*
* Copyright (c) 2021 Vivante Corporation
*
* 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 "tim/vx/ops.h"
#include "vsi_nn_pub.h"
#include "op_impl.h"
#include <array>
namespace tim {
namespace vx {
namespace ops {
class RNNCellImpl : public OpImpl {
public:
enum {
// signature
FULLY_CONNECTED_0_IN = 0,
FULLY_CONNECTED_0_WEIGHT = 1,
FULLY_CONNECTED_0_BIAS = 2,
FULLY_CONNECTED_1_WEIGHT = 3,
FULLY_CONNECTED_1_STATE_IN = 4,
INPUT_CNT,
OUT = 0,
STATE_OUT,
OUT_CNT,
// signature end
};
RNNCellImpl(Graph* graph, int input_cnt, int output_cnt,
DataLayout layout = DataLayout::ANY)
: OpImpl(graph, -1, input_cnt, output_cnt, layout) {
fc0_ = graph->CreateOperation<tim::vx::ops::FullyConnected>(0, 4);
fc1_ = graph->CreateOperation<tim::vx::ops::FullyConnected>(0, 4);
add_ = graph->CreateOperation<tim::vx::ops::Add>();
tanh_ = graph->CreateOperation<tim::vx::ops::Tanh>();
data_convert_ = graph->CreateOperation<tim::vx::ops::DataConvert>();
}
~RNNCellImpl() {}
RNNCellImpl& BindInput(const std::shared_ptr<Tensor>& tensor) override {
in_tensors_[input_tensor_index] = tensor;
if (this->input_tensor_index == INPUT_CNT - 1) {
// Get all input tensor
tim::vx::ShapeType shape = {0, 0};
tim::vx::TensorSpec FC0_spec(tim::vx::DataType::FLOAT32, shape,
tim::vx::TensorAttribute::TRANSIENT);
tim::vx::TensorSpec FC1_spec(tim::vx::DataType::FLOAT32, shape,
tim::vx::TensorAttribute::TRANSIENT);
tim::vx::TensorSpec add_spec(tim::vx::DataType::FLOAT32, shape,
tim::vx::TensorAttribute::TRANSIENT);
auto FC0_tensor = graph_->CreateTensor(FC0_spec);
auto FC1_tensor = graph_->CreateTensor(FC1_spec);
auto add_tensor = graph_->CreateTensor(add_spec);
fc0_->BindInput(in_tensors_[FULLY_CONNECTED_0_IN]);
fc0_->BindInput(in_tensors_[FULLY_CONNECTED_0_WEIGHT]);
fc0_->BindInput(in_tensors_[FULLY_CONNECTED_0_BIAS]);
fc0_->BindOutput(FC0_tensor);
fc1_->BindInput(in_tensors_[FULLY_CONNECTED_1_WEIGHT]);
fc1_->BindInput(in_tensors_[FULLY_CONNECTED_1_STATE_IN]);
fc1_->BindOutput(FC1_tensor);
add_->BindInput(FC0_tensor);
add_->BindInput(FC1_tensor);
add_->BindOutput(add_tensor);
tanh_->BindInput(add_tensor);
}
this->input_tensor_index++;
return *this;
}
RNNCellImpl& BindOutput(const std::shared_ptr<Tensor>& tensor) override {
out_tensors_[output_tensor_index] = tensor;
tanh_->BindOutput(out_tensors_[OUT]);
data_convert_->BindInput(out_tensors_[OUT]);
if (this->output_tensor_index == OUT_CNT - 1) {
data_convert_->BindOutput(out_tensors_[STATE_OUT]);
}
this->output_tensor_index++;
return *this;
}
vsi_nn_node_t* node() override { return nullptr; }
std::vector<std::shared_ptr<Tensor>> InputsTensor() override {
return inputs_tensor_;
}
std::vector<std::shared_ptr<Tensor>> OutputsTensor() override {
return outputs_tensor_;
}
private:
std::shared_ptr<tim::vx::Operation> fc0_;
std::shared_ptr<tim::vx::Operation> fc1_;
std::shared_ptr<tim::vx::Operation> add_;
std::shared_ptr<tim::vx::Operation> tanh_;
std::shared_ptr<tim::vx::Operation> data_convert_;
std::array<std::shared_ptr<tim::vx::Tensor>, INPUT_CNT> in_tensors_;
std::array<std::shared_ptr<tim::vx::Tensor>, OUT_CNT> out_tensors_;
};
RNNCell::RNNCell(Graph* graph, ActivationType activation)
: activation_(activation) {
impl_ = std::make_unique<RNNCellImpl>(graph, 0, 0, DataLayout::ANY);
}
std::shared_ptr<Operation> RNNCell::Clone(std::shared_ptr<Graph>& graph) const {
return graph->CreateOperation<RNNCell>(this->activation_);
}
} // namespace ops
} // namespace vx
} // namespace tim
| 35.72028
| 80
| 0.669538
|
gdh1995
|
e5f27ff62e3c8fe8f15130737b095fadf08dec16
| 3,670
|
cpp
|
C++
|
src/coinbase_pro/parser.cpp
|
olned/ssc2ce-cpp
|
306188fa66322773721f71a8b52ea107ff2288cd
|
[
"BSL-1.0"
] | null | null | null |
src/coinbase_pro/parser.cpp
|
olned/ssc2ce-cpp
|
306188fa66322773721f71a8b52ea107ff2288cd
|
[
"BSL-1.0"
] | null | null | null |
src/coinbase_pro/parser.cpp
|
olned/ssc2ce-cpp
|
306188fa66322773721f71a8b52ea107ff2288cd
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Oleg Nedbaylo 2020.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE
// or copy at http://www.boost.org/LICENSE_1_0.txt
#include "parser.hpp"
#include <cstdlib>
#include <fmt/format.h>
#include <iostream>
#include <rapidjson/document.h>
namespace ssc2ce {
CoinbaseParser::CoinbaseParser()
{
}
bool CoinbaseParser::parse(const char *message)
{
if (message[0] == char(0)) {
last_error_msg_ = "Empty string.";
return false;
}
last_error_msg_.clear();
using namespace rapidjson;
rapidjson::Document doc;
doc.Parse(message);
if (doc.IsNull()) {
last_error_msg_ = "Unable to parse the message, probably the wrong JSON format.";
return false;
}
bool processed = false;
if (doc.HasMember("type")) {
const char *message_type = doc["type"].GetString();
switch (message_type[0]) {
case 'a':
// activate
break;
case 'c':
// change
break;
case 'd':
// done
break;
case 'h':
// heartbeat
break;
case 'l':
// l2update
processed = handle_l2update(doc);
case 'm':
// match
break;
case 'o':
// open
break;
case 'r':
// received
break;
case 's':
switch (message_type[1]) {
case 'n':
processed = handle_snapshot(doc);
case 't':
// status
break;
default:
// subscribe
break;
}
break;
case 't':
// ticker
break;
default:
break;
}
if (!processed) {
last_error_msg_ = fmt::format("CoinbaseParser Unsupported: {} in message: {}", message_type, message);
}
} // namespace ssc2ce
else {
last_error_msg_ = fmt::format("CoinbaseParser Unknown message format: {}", message);
}
return processed;
} // namespace ssc2ce
bool CoinbaseParser::handle_snapshot(const rapidjson::Value &data)
{
auto &book = find_or_create_book(data["product_id"].GetString());
book.clear();
for (const auto &item : data["bids"].GetArray()) {
auto price = std::atof(item[0].GetString());
auto size = std::atof(item[1].GetString());
book.add_bid(price, size);
}
for (const auto &item : data["asks"].GetArray()) {
auto price = std::atof(item[0].GetString());
auto size = std::atof(item[1].GetString());
book.add_ask(price, size);
}
if (on_book_setup_)
on_book_setup_(&book);
return true;
}
bool CoinbaseParser::handle_l2update(const rapidjson::Value &data)
{
auto &book = find_or_create_book(data["product_id"].GetString());
book.set_time(data["time"].GetString());
for (const auto &item : data["changes"].GetArray()) {
if (item[0].GetString()[0] == 's') // sell
{
const auto price = std::atof(item[1].GetString());
const auto size = std::atof(item[2].GetString());
book.update_ask(price, size);
} else {
const auto price = std::atof(item[1].GetString());
const auto size = std::atof(item[2].GetString());
book.update_bid(price, size);
}
}
if (on_book_update_)
on_book_update_(&book);
return true;
}
CoinbaseBookL2 &CoinbaseParser::find_or_create_book(const std::string_view &instrumnet)
{
const auto key = std::hash<std::string_view>{}(instrumnet);
if (auto p = books_.find(key); p != books_.end()) {
return p->second;
} else {
auto [x, ok] = books_.emplace(key, CoinbaseBookL2(std::string(instrumnet)));
return x->second;
}
};
BookL2 const *CoinbaseParser::get_book(const std::string_view &instrument)
{
BookL2 const *book = &find_or_create_book(instrument);
return book;
}
} // namespace ssc2ce
| 22.9375
| 108
| 0.617984
|
olned
|
e5fa02c892e73170ede5a8caa420d2099b86323e
| 1,006
|
cpp
|
C++
|
Projects/Demo/source/Common/ControledLightComponent.cpp
|
NeroBurner/ETEngine
|
3fe039ff65cd1355957bcfce3f851fa411a86d94
|
[
"MIT"
] | null | null | null |
Projects/Demo/source/Common/ControledLightComponent.cpp
|
NeroBurner/ETEngine
|
3fe039ff65cd1355957bcfce3f851fa411a86d94
|
[
"MIT"
] | null | null | null |
Projects/Demo/source/Common/ControledLightComponent.cpp
|
NeroBurner/ETEngine
|
3fe039ff65cd1355957bcfce3f851fa411a86d94
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "ControledLightComponent.h"
#include <EtCore/Reflection/Registration.h>
namespace et {
namespace demo {
// reflection
//------------
RTTR_REGISTRATION
{
rttr::registration::class_<ControledLightComponent>("controled light component");
BEGIN_REGISTER_POLYMORPHIC_CLASS(ControledLightComponentDesc, "controled light comp desc")
END_REGISTER_POLYMORPHIC_CLASS(ControledLightComponentDesc, fw::I_ComponentDescriptor);
}
DEFINE_FORCED_LINKING(ControledLightComponentDesc) // force the linker to include this unit
ECS_REGISTER_COMPONENT(ControledLightComponent);
//======================================
// Controled Light Component Descriptor
//======================================
//---------------------------------------
// ControledLightComponentDesc::MakeData
//
// Create a spawn component from a descriptor
//
ControledLightComponent* ControledLightComponentDesc::MakeData()
{
return new ControledLightComponent();
}
} // namespace demo
} // namespace et
| 22.863636
| 91
| 0.698807
|
NeroBurner
|
e5fa89f24b53ada66750cbf7e14b96d67cba0025
| 2,386
|
hpp
|
C++
|
docker/private/priority_queue.hpp
|
Better-Idea/Mix-C
|
71f34a5fc8c17a516cf99bc397289d046364a82e
|
[
"Apache-2.0"
] | 41
|
2019-09-24T02:17:34.000Z
|
2022-01-18T03:14:46.000Z
|
docker/private/priority_queue.hpp
|
Better-Idea/Mix-C
|
71f34a5fc8c17a516cf99bc397289d046364a82e
|
[
"Apache-2.0"
] | 2
|
2019-11-04T09:01:40.000Z
|
2020-06-23T03:03:38.000Z
|
docker/private/priority_queue.hpp
|
Better-Idea/Mix-C
|
71f34a5fc8c17a516cf99bc397289d046364a82e
|
[
"Apache-2.0"
] | 8
|
2019-09-24T02:17:35.000Z
|
2021-09-11T00:21:03.000Z
|
#ifndef xpack_docker_priority_queue
#define xpack_docker_priority_queue
#pragma push_macro("xuser")
#undef xuser
#define xuser mixc::docker_priority_queue::inc
#include"algo/heap_root.hpp"
#include"define/base_type.hpp"
#include"docker/shared_array.hpp"
#include"docker/transmitter.hpp"
#include"dumb/mirror.hpp"
#include"macro/xexport.hpp"
#include"macro/xis_nullptr.hpp"
#include"macro/xref.hpp"
#include"macro/xstruct.hpp"
#include"memop/cast.hpp"
#pragma pop_macro("xuser")
namespace mixc::docker_priority_queue {
template<class final_t, class item_t>
xstruct(
xtmpl(priority_queue, final_t, item_t),
xprif(m_items, inc::shared_array<item_t>)
)
using mirror = inc::shared_array<inc::mirror<item_t>>;
priority_queue(){}
template<class finalx_t >
priority_queue(priority_queue<finalx_t, item_t> const & object) :
m_items((inc::shared_array<item_t> &)object.m_items){}
priority_queue(::length initial_capacity) :
m_items(initial_capacity){}
void clear() {
the_t{}.m_items.swap(xref(m_items));
}
void push(item_t const & value) {
// 本次 push 无需拷贝构造
inc::cast<mirror>(m_items).push(inc::mirror<item_t>{});
// 本次 push 默认内部拷贝构造
inc::heap_root::push(m_items, m_items.length() - 1, value);
}
inc::transmitter<item_t> pop() {
auto length = m_items.length();
inc::transmitter<item_t> r = m_items[0];
inc::heap_root::pop(m_items, length, m_items[length - 1]);
inc::cast<mirror>(m_items).pop();
return r;
}
void swap(the_t * object){
m_items.swap(object);
}
final_t & operator= (decltype(nullptr)){
m_items = nullptr;
return thex;
}
final_t & operator= (the_t const & object){
m_items = object.m_items;
return thex;
}
xpubgetx(root, inc::transmitter<item_t>){
return m_items[0];
}
xpubgetx(length, uxx){
return m_items.length();
}
xpubgetx(is_empty, bool){
return m_items.length() == 0;
}
xis_nullptr(
m_items == nullptr
)
};
}
#endif
#define xusing_docker_name ::mixc::docker_priority_queue
| 26.808989
| 74
| 0.594719
|
Better-Idea
|
e5fce778a67f3c86688c7648a8bc5fde7458882f
| 2,127
|
cpp
|
C++
|
UCF HSPT Documents/2011/Solutions/genetics.cpp
|
p473lr/i-urge-mafia-gear
|
ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e
|
[
"Apache-2.0"
] | null | null | null |
UCF HSPT Documents/2011/Solutions/genetics.cpp
|
p473lr/i-urge-mafia-gear
|
ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e
|
[
"Apache-2.0"
] | null | null | null |
UCF HSPT Documents/2011/Solutions/genetics.cpp
|
p473lr/i-urge-mafia-gear
|
ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
#include<fstream>
#include<cctype>
#include<cstdlib>
using namespace std;
char input[16]; //variable to store each line of input
/*
Array to manipulate the integer to genetic character conversion.
For any character its array index is the corresponding value. For example 'G' has value of 2
For for any integer the corresponding character at that integer is the genetic character.
*/
char base4chars[5] = "ACGT";
/*
A linear search to find the corresponding integer value. just search through the array base4chars for the index.
*/
int getbase4charvalue(char ch){
for(int i=0;i<4;++i){
if(base4chars[i]==ch){
return i;
}
}
return -1; //this line will never be executed
}
/*
recursively printing the base 4 representation of the integer.
*/
void base10to4(int n){
if(n==0) return;
base10to4(n/4); //before printing the last digit we need to print the bese-4 representation of n/4
cout<<base4chars[n%4];
}
/*
base 4 to base 10 conversion.
*/
int base4to10(char input[]){
int ret = 0;
for(int i=0;input[i];++i){
ret*=4;
ret+=getbase4charvalue(input[i]);
}
return ret;
}
int main(){
//Added to make the program read from file
ifstream inputFile("E:\genetics.in");
int test_cases;
//cin>>test_cases;
inputFile>>test_cases;
for(int sequence = 1 ; sequence <= test_cases ; ++sequence){
//cin>>input;
inputFile>>input;
cout<<"Sequence #"<<sequence<<": ";
/*
If the first symbol is a digit then the input is given as a base 10 integer.
*/
if(isdigit(input[0])){
int value = atoi(input); //converting the input string to an integer
base10to4(value); //outputting the base-10 input to base-4 recursively
cout<<endl;
}
/*
If the first symbol is not a digit then the input is given in base 4.
*/
else{
cout<<base4to10(input)<<endl;
}
}
return 0;
}
| 25.321429
| 113
| 0.597555
|
p473lr
|
f90046ff57205cdeb4834d4efff9cbd713a8c33e
| 2,328
|
cc
|
C++
|
cms/src/model/DeleteNotifyPolicyRequest.cc
|
sdk-team/aliyun-openapi-cpp-sdk
|
d0e92f6f33126dcdc7e40f60582304faf2c229b7
|
[
"Apache-2.0"
] | 3
|
2020-01-06T08:23:14.000Z
|
2022-01-22T04:41:35.000Z
|
cms/src/model/DeleteNotifyPolicyRequest.cc
|
sdk-team/aliyun-openapi-cpp-sdk
|
d0e92f6f33126dcdc7e40f60582304faf2c229b7
|
[
"Apache-2.0"
] | null | null | null |
cms/src/model/DeleteNotifyPolicyRequest.cc
|
sdk-team/aliyun-openapi-cpp-sdk
|
d0e92f6f33126dcdc7e40f60582304faf2c229b7
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/cms/model/DeleteNotifyPolicyRequest.h>
using AlibabaCloud::Cms::Model::DeleteNotifyPolicyRequest;
DeleteNotifyPolicyRequest::DeleteNotifyPolicyRequest() :
RpcServiceRequest("cms", "2018-03-08", "DeleteNotifyPolicy")
{}
DeleteNotifyPolicyRequest::~DeleteNotifyPolicyRequest()
{}
std::string DeleteNotifyPolicyRequest::getPolicyType()const
{
return policyType_;
}
void DeleteNotifyPolicyRequest::setPolicyType(const std::string& policyType)
{
policyType_ = policyType;
setParameter("PolicyType", policyType);
}
std::string DeleteNotifyPolicyRequest::getAlertName()const
{
return alertName_;
}
void DeleteNotifyPolicyRequest::setAlertName(const std::string& alertName)
{
alertName_ = alertName;
setParameter("AlertName", alertName);
}
std::string DeleteNotifyPolicyRequest::getGroupId()const
{
return groupId_;
}
void DeleteNotifyPolicyRequest::setGroupId(const std::string& groupId)
{
groupId_ = groupId;
setParameter("GroupId", groupId);
}
std::string DeleteNotifyPolicyRequest::getId()const
{
return id_;
}
void DeleteNotifyPolicyRequest::setId(const std::string& id)
{
id_ = id;
setParameter("Id", id);
}
std::string DeleteNotifyPolicyRequest::getDimensions()const
{
return dimensions_;
}
void DeleteNotifyPolicyRequest::setDimensions(const std::string& dimensions)
{
dimensions_ = dimensions;
setParameter("Dimensions", dimensions);
}
std::string DeleteNotifyPolicyRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void DeleteNotifyPolicyRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setParameter("AccessKeyId", accessKeyId);
}
| 24.765957
| 79
| 0.752148
|
sdk-team
|
f9024c35e6b29e9f8d8c30463ab7097cd9a2108d
| 624
|
cpp
|
C++
|
src/Math.cpp
|
mmha/efiraytracer
|
bd14e70db1e5390080e47c2e619a8a20d2e75ca6
|
[
"BSL-1.0"
] | 8
|
2018-03-02T17:42:15.000Z
|
2021-09-14T21:59:19.000Z
|
src/Math.cpp
|
mmha/efiraytracer
|
bd14e70db1e5390080e47c2e619a8a20d2e75ca6
|
[
"BSL-1.0"
] | null | null | null |
src/Math.cpp
|
mmha/efiraytracer
|
bd14e70db1e5390080e47c2e619a8a20d2e75ca6
|
[
"BSL-1.0"
] | null | null | null |
#include <cstdint>
// TODO Use SSE
// http://www.myreckonings.com/Dead_Reckoning/Online/Materials/Fast_Approximation_of_Elementary_Functions.pdf
extern "C" float tanf(float x) {
float tan;
__asm__("FPTAN;" : "=t"(tan) : "0"(x));
return tan;
}
extern "C" double sqrt(double x) {
__asm__("sqrtsd %1, %0" : "+x"(x) : "x"(x), "x"(x));
return x;
}
// http://martin.ankerl.com/2012/01/25/optimized-approximative-pow-in-c-and-cpp/
extern "C" double pow(double a, double b) {
union {
double d;
int32_t x[2];
} u = {a};
u.x[1] = static_cast<int32_t>(b * (u.x[1] - 1072632447) + 1072632447);
u.x[0] = 0;
return u.d;
}
| 24.96
| 109
| 0.641026
|
mmha
|
f9055ee5a4b61ca351341a9eff91ee855516a200
| 1,930
|
cpp
|
C++
|
Practicum_Homeworks_2021/04_Practice/main.cpp
|
NaskoVasilev/OOP-FMI
|
00443be9ef1931beae1e06f40fbb76ea09a46d1a
|
[
"MIT"
] | 4
|
2020-11-14T11:22:39.000Z
|
2021-11-02T08:35:24.000Z
|
Practicum_Homeworks_2021/04_Practice/main.cpp
|
NaskoVasilev/OOP-FMI
|
00443be9ef1931beae1e06f40fbb76ea09a46d1a
|
[
"MIT"
] | null | null | null |
Practicum_Homeworks_2021/04_Practice/main.cpp
|
NaskoVasilev/OOP-FMI
|
00443be9ef1931beae1e06f40fbb76ea09a46d1a
|
[
"MIT"
] | 6
|
2020-11-08T12:55:25.000Z
|
2022-01-23T17:33:47.000Z
|
#include "card.hpp"
#include "duelist.hpp"
#include <iostream>
using namespace std;
int main() {
MonsterCard *dragon = new MonsterCard("Blue-Eyes White Dragon",
"This legendary dragon is a powerful engine of destruction.", 3000, 2500, 10);
MonsterCard *magician = new MonsterCard("Dark Magician", "The ultimate wizard.", 2500, 2100, 15);
MagicCard *swords = new MagicCard("Swords of Revealing Light", "Your opponent's monsters cannot declare an attack.",
CardType::spell, 20);
MagicCard *cylinder = new MagicCard("Magic Cylinder", "Inflict damage to your opponent equal to its ATK.",
CardType::trap, 7);
PendulumCard *timegazer = new PendulumCard("Timegazer Magician", "Your opponent cannot activate Trap Magic Cards",
1200, 600, CardType::spell, 8, 5);
Duelist firstDuelist("Ivan Ivanov");
firstDuelist.getDeck().setName("Magician Deck");
firstDuelist.getDeck().addCard(dragon);
firstDuelist.getDeck().addCard(swords);
firstDuelist.getDeck().addCard(magician);
firstDuelist.getDeck().addCard(cylinder);
firstDuelist.getDeck().addCard(timegazer);
cout << "Initial deck" << endl;
firstDuelist.display();
cout << endl;
firstDuelist.loadDeck("magician_deck.txt");
cout << "The deck after loading five new cards" << endl;
firstDuelist.display();
cout << endl;
firstDuelist.saveDeck("double_deck.txt");
Duelist duelist("Atanas");
duelist.loadDeck("double_deck.txt");
MagicCard *box = new MagicCard("Mystic Box", "Destroy one monster.", CardType::spell, 5);
duelist.getDeck().setCard(5, box);
cout << "Result after changing Swords of Revealing Light with Mystic Box" << endl;
duelist.display();
cout << endl;
cout << firstDuelist.duel(duelist);
}
| 39.387755
| 120
| 0.638342
|
NaskoVasilev
|
f905d68556ea6891fbacf9aa7d32580665bbd957
| 2,194
|
cc
|
C++
|
src/hlib/libcpp/os.cc
|
hascal/llvm
|
f9893068ec2cff12889d2a8c3f935bccda8769e3
|
[
"MIT"
] | null | null | null |
src/hlib/libcpp/os.cc
|
hascal/llvm
|
f9893068ec2cff12889d2a8c3f935bccda8769e3
|
[
"MIT"
] | null | null | null |
src/hlib/libcpp/os.cc
|
hascal/llvm
|
f9893068ec2cff12889d2a8c3f935bccda8769e3
|
[
"MIT"
] | null | null | null |
string os_name()
{
#ifdef _WIN32
return "win32";
#elif _WIN64
return "win64";
#elif __APPLE__ || __MACH__ || macintosh || Macintosh
return "macos";
#elif __linux__
return "linux";
#elif __FreeBSD__
return "freebsd";
#elif __unix || __unix__
return "unix";
#elif __ANDROID__
return "android";
#elif AMIGA
return "amiga";
#elif __FreeBSD__ || __OpenBSD__ || __NetBSD__ || __DragonFly__
return "bsd";
#elif __CYGWIN__
return "cygwin";
#elif __minix
return "minix";
#elif __MSDOS__
return "msdos";
#elif __sun
return "solaris";
#elif __SYMBIAN32__
return "symbian";
#elif __MVS__
return "zvm";
#else
return "unknown";
#endif
}
int system(string cmd)
{
return system(cmd.c_str());
}
bool is_x86(){
if(sizeof(void*) == 4)
return true;
else
return false;
}
bool is_64(){
return !is_x86();
}
string compiler_name(){
#ifdef __clang__
return "clang";
#elif __GNUC__
return "gcc";
#elif _MSC_VER
return "msvc";
#elif __BORLANDC__
return "bcc";
#elif __DMC__
return "dmc";
#elif __INTEL_COMPILER
return "icc";
#else
return "unknown";
#endif
}
// refernce: https://sourceforge.net/p/predef/wiki/Architectures/
string arch()
{
string comname = compiler_name();
if(comname == "msvc"){
#ifdef _M_AMD64
return "AMD64";
#elif _M_IX86
return "intel32";
#elif _M_IA64
return "ia64"; // also supports by intel c++ : __itanium__
#elif _M_PPC
return "powerpc";
#else
return "unknown";
#endif
}else if(comname == "gcc"){
#ifdef __amd64__ || __amd64
return "AMD64";
#elif __arm__
return "arm";
#elif __i386__ || __i486__ || __i586__ || __i686__
return "intel32";
#elif __ia64__
return "ia64";
#elif __mips__
return "mips";
#elif __powerpc__ || __powerpc64__
return "powerpc";
#else
return "unknown";
#endif
}
// todo : support intel c++
return "unknown";
}
| 20.12844
| 67
| 0.568368
|
hascal
|
f90bd9d71cd5d5659b11dbb985099333744bbc32
| 3,714
|
hpp
|
C++
|
rmvmathtest/profile/Profiler.hpp
|
vitali-kurlovich/RMMath
|
a982b89e5db08e9cd16cb08e92839a315b6198dc
|
[
"MIT"
] | null | null | null |
rmvmathtest/profile/Profiler.hpp
|
vitali-kurlovich/RMMath
|
a982b89e5db08e9cd16cb08e92839a315b6198dc
|
[
"MIT"
] | null | null | null |
rmvmathtest/profile/Profiler.hpp
|
vitali-kurlovich/RMMath
|
a982b89e5db08e9cd16cb08e92839a315b6198dc
|
[
"MIT"
] | null | null | null |
//
// Created by Vitali Kurlovich on 3/22/16.
//
#ifndef RMVECTORMATH_PROFILER_HPP
#define RMVECTORMATH_PROFILER_HPP
#include <vector>
#include <stack>
#include <chrono>
#include "ProfileCase.hpp"
#include <profiler/MathStatistic.hpp>
namespace profiler {
class Profiler {
protected:
std::vector<const ProfileCase*> profileCases;
std::stack<std::chrono::steady_clock::time_point> timestack;
bool _blockCout{false};
public:
void addProfileCases(const ProfileCase* profileCase ) {
profileCases.push_back(profileCase);
}
void run() {
std::cout << "Start profiling..." << std::endl;
std::vector<const ProfileCase*>::iterator i;
_blockCout = true;
for (u_int32_t iter = 0; iter < 10; iter++) {
for (i = profileCases.begin(); i != profileCases.end(); ++i) {
rmmath::MathStatistic::instance().resetAll();
(*i)->run();
}
}
_blockCout = false;
for (i = profileCases.begin(); i!= profileCases.end(); ++i) {
printProfileCaseHeader(*i);
rmmath::MathStatistic::instance().resetAll();
(*i)->run();
}
}
public:
void beginProfileCase(const char* casename) {
if (_blockCout)
return;
printBeginProfileCase(casename);
rmmath::MathStatistic::instance().resetAll();
auto now = std::chrono::steady_clock::now();
timestack.push(now);
}
void endProfileCase(const char* casename) {
if (_blockCout)
return;
auto now = std::chrono::steady_clock::now();
auto begintime = timestack.top();
timestack.pop();
std::cout << "Duration: " << std::chrono::duration_cast<std::chrono::milliseconds>(now - begintime).count() << "ms" << std::endl;
printMathStatistic();
}
protected:
void printProfileCaseHeader(const ProfileCase* profileCase) {
std::cout << "[--- " << profileCase->getName() << " ---]" << std::endl;
}
void printMathStatistic() {
bool show = false;
auto mul = rmmath::MathStatistic::instance().mul();
show |= (mul > 0);
auto div = rmmath::MathStatistic::instance().div();
show |= (div > 0);
auto sum = rmmath::MathStatistic::instance().sum();
show |= (sum > 0);
auto sub = rmmath::MathStatistic::instance().sub();
show |= (sub > 0);
auto sqrt = rmmath::MathStatistic::instance().sqrt();
show |= (sqrt > 0);
if (!show)
return;
std::cout << "[ Math Statistic ]" << std::endl;
if (sum > 0) {
std::cout << " Sum: " << sum <<std::endl;
}
if (sub > 0) {
std::cout << " Sub: " << sub <<std::endl;
}
if (mul > 0) {
std::cout << " Mul: " << mul <<std::endl;
}
if (div > 0) {
std::cout << " Div: " << div <<std::endl;
}
if (sqrt > 0) {
std::cout << " Sqrt: " << sqrt <<std::endl;
}
std::cout << "[ -------------- ]" << std::endl;
}
void printBeginProfileCase(const char* casename) {
std::cout << "+++ " << casename << " +++" << std::endl;
}
};
}
#endif //RMVECTORMATH_PROFILER_HPP
| 27.511111
| 142
| 0.469575
|
vitali-kurlovich
|
f90e466b4b041fdce6f38dfc35d3732befd0a0d3
| 1,476
|
cpp
|
C++
|
Source/source/mob_types/ship_type.cpp
|
Neocraftz1553/Pikifen
|
e10e1f9f28d4e5229db64c291a8b2ccbb013b7e2
|
[
"MIT"
] | null | null | null |
Source/source/mob_types/ship_type.cpp
|
Neocraftz1553/Pikifen
|
e10e1f9f28d4e5229db64c291a8b2ccbb013b7e2
|
[
"MIT"
] | null | null | null |
Source/source/mob_types/ship_type.cpp
|
Neocraftz1553/Pikifen
|
e10e1f9f28d4e5229db64c291a8b2ccbb013b7e2
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) Andre 'Espyo' Silva 2013.
* The following source file belongs to the open-source project Pikifen.
* Please read the included README and LICENSE files for more information.
* Pikmin is copyright (c) Nintendo.
*
* === FILE DESCRIPTION ===
* Ship type class and ship type-related functions.
*/
#include "ship_type.h"
#include "../functions.h"
#include "../mob_fsms/ship_fsm.h"
#include "../mobs/ship.h"
#include "../utils/string_utils.h"
/* ----------------------------------------------------------------------------
* Creates a type of ship.
*/
ship_type::ship_type() :
mob_type(MOB_CATEGORY_SHIPS),
can_heal(false),
beam_radius(0.0f) {
target_type = MOB_TARGET_TYPE_NONE;
ship_fsm::create_fsm(this);
}
/* ----------------------------------------------------------------------------
* Returns the vector of animation conversions.
*/
anim_conversion_vector ship_type::get_anim_conversions() const {
anim_conversion_vector v;
v.push_back(std::make_pair(SHIP_ANIM_IDLING, "idling"));
return v;
}
/* ----------------------------------------------------------------------------
* Loads properties from a data file.
* file:
* File to read from.
*/
void ship_type::load_properties(data_node* file) {
reader_setter rs(file);
rs.set("beam_offset_x", beam_offset.x);
rs.set("beam_offset_y", beam_offset.y);
rs.set("beam_radius", beam_radius);
rs.set("can_heal", can_heal);
}
| 26.357143
| 79
| 0.576558
|
Neocraftz1553
|
f90ecaadb121feefac9c6a25b033eb5aded3fce0
| 3,012
|
cpp
|
C++
|
recommendation/pytorch/negative_sampling_cpp/negative_sampling.cpp
|
mengkai94/training
|
2a0aa29e700a33e9d3bf2645d13d89fb525e29fc
|
[
"Apache-2.0"
] | 567
|
2018-09-13T05:07:49.000Z
|
2020-11-23T11:52:11.000Z
|
recommendation/pytorch/negative_sampling_cpp/negative_sampling.cpp
|
mengkai94/training
|
2a0aa29e700a33e9d3bf2645d13d89fb525e29fc
|
[
"Apache-2.0"
] | 222
|
2018-09-14T10:15:39.000Z
|
2020-11-20T22:21:09.000Z
|
recommendation/pytorch/negative_sampling_cpp/negative_sampling.cpp
|
mengkai94/training
|
2a0aa29e700a33e9d3bf2645d13d89fb525e29fc
|
[
"Apache-2.0"
] | 279
|
2018-09-16T12:40:29.000Z
|
2020-11-17T14:22:52.000Z
|
#include <torch/torch.h>
#include <vector>
#include <iostream>
#include <algorithm>
#include <random>
#include <cstdint>
struct NegativeSampler {
NegativeSampler(at::Tensor positives, int n_user, int n_item) :
positives_lists(n_user)
{
std::cout << "C++ PyTorch extension for negative sampling created." << std::endl;
n_user_ = n_user;
n_item_ = n_item;
n_positives_ = positives.size(0);
preprocessPositives(positives);
}
void preprocessPositives(at::Tensor positives) {
auto positives_accessor = positives.accessor<int64_t, 2>();
for (int i = 0; i != positives.size(0); ++i) {
int user = positives_accessor[i][0];
int item = positives_accessor[i][1];
positives_lists[user].push_back(item);
}
}
at::Tensor generate_test_part(int num_negatives, int chunk_size, int user_offset) {
at::Tensor negatives = torch::empty({num_negatives * chunk_size, 2},
torch::CPU(torch::kInt64));
int i = 0;
for (int u = 0; u != chunk_size; ++u) {
int user = user_offset + u;
for (int ni = 0; ni != num_negatives; ++ni) {
bool is_positive = true;
// repeat until a negative is found
int item = -1;
while (is_positive) {
item = static_cast<int>(at::randint(0, n_item_ - 1, {1}, torch::kInt64).data<int64_t>()[0]);
// check if the sampled number is a positive
is_positive = std::binary_search(positives_lists[user].begin(), positives_lists[user].end(), item);
}
negatives[i][0] = user;
negatives[i][1] = item;
++i;
}
}
return negatives;
}
at::Tensor generate_train(int num_negatives) {
at::Tensor negatives = torch::empty({num_negatives * n_positives_, 2}, torch::CPU(torch::kInt64));
int i = 0;
for (int u = 0; u != n_user_; ++u) {
// sample num_negatives for each positives for each user
for (int ni = 0; ni != num_negatives; ++ni) {
for (int pi = 0; pi != positives_lists[u].size(); ++pi) {
bool is_positive = true;
// repeat until a negative is found
int item = -1;
while (is_positive) {
item = static_cast<int>(at::randint(0, n_item_ - 1, {1}, torch::kInt64).data<int64_t>()[0]);
// check if the sampled number is a positive
is_positive = std::binary_search(positives_lists[u].begin(),
positives_lists[u].end(), item);
}
negatives[i][0] = u;
negatives[i][1] = item;
++i;
}
}
}
return negatives;
}
private:
std::vector<std::vector<int>> positives_lists;
int n_user_;
int n_item_;
int n_positives_;
};
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
py::class_<NegativeSampler>(m, "NegativeSampler")
.def(py::init<at::Tensor, int, int>())
.def("generate_train", &NegativeSampler::generate_train)
.def("generate_test_part", &NegativeSampler::generate_test_part);
}
| 31.051546
| 109
| 0.598274
|
mengkai94
|
f910671bb18dacb21a3fee701ad67ffed76d4d38
| 5,037
|
cpp
|
C++
|
Source/SIMPLib/Common/INamedObject.cpp
|
mhitzem/SIMPL
|
cd8a58f8d955d232ea039121cc5286cc9545c7a6
|
[
"NRL"
] | 3
|
2018-01-18T18:27:02.000Z
|
2021-06-13T06:10:52.000Z
|
Source/SIMPLib/Common/INamedObject.cpp
|
mhitzem/SIMPL
|
cd8a58f8d955d232ea039121cc5286cc9545c7a6
|
[
"NRL"
] | 211
|
2016-07-27T12:18:16.000Z
|
2021-11-02T13:42:11.000Z
|
Source/SIMPLib/Common/INamedObject.cpp
|
mhitzem/SIMPL
|
cd8a58f8d955d232ea039121cc5286cc9545c7a6
|
[
"NRL"
] | 23
|
2016-02-15T21:23:47.000Z
|
2021-08-11T15:35:24.000Z
|
/* ============================================================================
* Copyright (c) 2019 BlueQuartz Software, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the names of any of the BlueQuartz Software contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include "INamedObject.h"
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
INamedObject::HashType INamedObject::CreateHash(const QString& string)
{
return std::hash<std::string>()(string.toStdString());
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
INamedObject::INamedObject(const QString& name)
: m_Name(name)
, m_NameHash(CreateHash(name))
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
INamedObject::~INamedObject()
{
ParentCollectionType collections = getParentCollections();
for(const auto& collection : collections)
{
collection->erase(getName());
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString INamedObject::getName() const
{
return m_Name;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
bool INamedObject::setName(const QString& name)
{
for(const auto& collection : m_ParentCollctions)
{
// If collection does not exist, something has else gone wrong and requires attention.
if(collection->contains(name))
{
return false;
}
}
m_NameHash = CreateHash(name);
m_Name = name;
return true;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
INamedObject::HashType INamedObject::getNameHash() const
{
return m_NameHash;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
INamedObject::ParentCollectionType INamedObject::getParentCollections() const
{
return m_ParentCollctions;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void INamedObject::addToCollection(INamedCollection* collection)
{
m_ParentCollctions.insert(collection);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void INamedObject::removeFromCollection(INamedCollection* collection)
{
m_ParentCollctions.erase(collection);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
bool INamedObject::operator<(const INamedObject& other) const
{
return getNameHash() < other.getNameHash();
}
bool INamedObject::operator==(const INamedObject& other) const
{
return getNameHash() == other.getNameHash();
}
// -----------------------------------------------------------------------------
INamedObject::Pointer INamedObject::NullPointer()
{
return Pointer(static_cast<Self*>(nullptr));
}
| 35.723404
| 90
| 0.475084
|
mhitzem
|
f911468765228b7d1ecd797f927a2b1e5ad48ac8
| 3,102
|
hpp
|
C++
|
drivers/inc/reg.hpp
|
scatty101/imxrt1062
|
4fb991c138d16e02ed8ea58b096be2034c9e5063
|
[
"MIT"
] | 2
|
2021-02-01T21:21:52.000Z
|
2021-02-07T07:19:18.000Z
|
drivers/inc/reg.hpp
|
scatty101/imxrt1062
|
4fb991c138d16e02ed8ea58b096be2034c9e5063
|
[
"MIT"
] | null | null | null |
drivers/inc/reg.hpp
|
scatty101/imxrt1062
|
4fb991c138d16e02ed8ea58b096be2034c9e5063
|
[
"MIT"
] | 1
|
2021-02-01T21:25:19.000Z
|
2021-02-01T21:25:19.000Z
|
#ifndef IMXRT_DRIVERS_REG_HPP_
#define IMXRT_DRIVERS_REG_HPP_
#include <imxrt1062/hardware.hpp>
namespace imxdrivers
{
/**
* @brief DSB
*
*/
static inline void data_sync()
{
__DSB();
}
/**
* @brief Sometimes IRQ are executed so fast, that irq flag isn't cleared until leave of irq. This function solves this problem.
*
*/
static inline void irq_save_exit()
{
data_sync();
}
/**
* @brief Performs OR operation.
*
* @tparam reg_t
* @tparam value_t
* @param reg
* @param value
*/
template <typename reg_t, typename value_t>
static inline constexpr void reg_set(reg_t ®, const value_t &value = static_cast<value_t>(0))
{
reg |= static_cast<reg_t>(value);
}
/**
* @brief Performs write operation.
*
* @tparam reg_t
* @tparam value_t
* @param reg
* @param value
*/
template <typename reg_t, typename value_t>
static inline constexpr void reg_write(reg_t ®, const value_t &value = static_cast<value_t>(0))
{
reg = static_cast<reg_t>(value);
}
/**
* @brief Peforms AND NOT operation
*
* @tparam reg_t
* @tparam value_t
* @param reg
* @param value
*/
template <typename reg_t, typename value_t>
static inline constexpr void reg_clear(reg_t ®, const value_t &value = static_cast<value_t>(0))
{
reg &= static_cast<reg_t>(~value);
}
/**
* @brief Performs read operation
*
* @tparam reg_t
* @param reg
* @return constexpr reg_t
*/
template <typename reg_t>
static inline constexpr reg_t reg_get(const reg_t ®)
{
return reg;
}
template <typename reg_t, typename mask_t, typename shift_t, typename value_t>
static inline constexpr void reg_manipulate(reg_t ®, const mask_t &mask, const shift_t &shift, const value_t &value)
{
auto reg_temp = reg_get(reg);
reg_clear(reg_temp, mask);
reg_set(reg_temp, (value << shift) & mask);
reg_write(reg, reg_temp);
}
template <typename reg_t, typename bit_pos_t>
static inline bool reg_get_bit(const reg_t ®, const bit_pos_t &bit_pos)
{
return (reg_get(reg) >> bit_pos) & 0x1;
}
template <typename reg_t, typename bit_pos_t>
static inline constexpr void reg_clear_bit(reg_t ®, const bit_pos_t &bit_pos)
{
reg_clear(reg, 1 << bit_pos);
}
template <typename reg_t, typename bit_pos_t>
static inline constexpr void reg_set_bit(reg_t ®, const bit_pos_t &bit_pos)
{
reg_set(reg, 1 << bit_pos);
}
template <typename reg_t, typename bit_pos_t>
static inline constexpr void reg_manipulate_bit(reg_t ®, const bit_pos_t &bit_pos, const bool &value)
{
if (value)
{
reg_set_bit(reg, bit_pos);
}
else
{
reg_clear_bit(reg, bit_pos);
}
}
} // namespace imxdrivers
#endif // IMXRT_DRIVERS_REG_HPP_
| 25.636364
| 132
| 0.60735
|
scatty101
|
f9161a0c7752ad4996b90dd7c9ff0793a01177b3
| 319,755
|
hpp
|
C++
|
include/alibabacloud/pai_plugin_20220112.hpp
|
alibabacloud-sdk-cpp/paiplugin-20220112
|
350e03cc56139f270d6ef0eb75b474a79d9ded8d
|
[
"Apache-2.0"
] | null | null | null |
include/alibabacloud/pai_plugin_20220112.hpp
|
alibabacloud-sdk-cpp/paiplugin-20220112
|
350e03cc56139f270d6ef0eb75b474a79d9ded8d
|
[
"Apache-2.0"
] | null | null | null |
include/alibabacloud/pai_plugin_20220112.hpp
|
alibabacloud-sdk-cpp/paiplugin-20220112
|
350e03cc56139f270d6ef0eb75b474a79d9ded8d
|
[
"Apache-2.0"
] | null | null | null |
// This file is auto-generated, don't edit it. Thanks.
#ifndef ALIBABACLOUD_PAIPLUGIN20220112_H_
#define ALIBABACLOUD_PAIPLUGIN20220112_H_
#include <alibabacloud/open_api.hpp>
#include <boost/throw_exception.hpp>
#include <darabonba/core.hpp>
#include <darabonba/util.hpp>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
namespace Alibabacloud_PaiPlugin20220112 {
class CreateCampaignRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<string> remark{};
CreateCampaignRequest() {}
explicit CreateCampaignRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
}
virtual ~CreateCampaignRequest() = default;
};
class CreateCampaignResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> updatedTime{};
CreateCampaignResponseBodyData() {}
explicit CreateCampaignResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~CreateCampaignResponseBodyData() = default;
};
class CreateCampaignResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateCampaignResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateCampaignResponseBody() {}
explicit CreateCampaignResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateCampaignResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateCampaignResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateCampaignResponseBody() = default;
};
class CreateCampaignResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateCampaignResponseBody> body{};
CreateCampaignResponse() {}
explicit CreateCampaignResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateCampaignResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateCampaignResponseBody>(model1);
}
}
}
virtual ~CreateCampaignResponse() = default;
};
class CreateGroupRequest : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> column{};
shared_ptr<string> filter{};
shared_ptr<string> inferenceJobId{};
shared_ptr<string> name{};
shared_ptr<bool> phoneNumber{};
shared_ptr<string> project{};
shared_ptr<string> remark{};
shared_ptr<long> source{};
shared_ptr<string> table{};
shared_ptr<string> text{};
shared_ptr<string> uri{};
CreateGroupRequest() {}
explicit CreateGroupRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (column) {
res["Column"] = boost::any(*column);
}
if (filter) {
res["Filter"] = boost::any(*filter);
}
if (inferenceJobId) {
res["InferenceJobId"] = boost::any(*inferenceJobId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (project) {
res["Project"] = boost::any(*project);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (source) {
res["Source"] = boost::any(*source);
}
if (table) {
res["Table"] = boost::any(*table);
}
if (text) {
res["Text"] = boost::any(*text);
}
if (uri) {
res["Uri"] = boost::any(*uri);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("Column") != m.end() && !m["Column"].empty()) {
column = make_shared<string>(boost::any_cast<string>(m["Column"]));
}
if (m.find("Filter") != m.end() && !m["Filter"].empty()) {
filter = make_shared<string>(boost::any_cast<string>(m["Filter"]));
}
if (m.find("InferenceJobId") != m.end() && !m["InferenceJobId"].empty()) {
inferenceJobId = make_shared<string>(boost::any_cast<string>(m["InferenceJobId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<bool>(boost::any_cast<bool>(m["PhoneNumber"]));
}
if (m.find("Project") != m.end() && !m["Project"].empty()) {
project = make_shared<string>(boost::any_cast<string>(m["Project"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Source") != m.end() && !m["Source"].empty()) {
source = make_shared<long>(boost::any_cast<long>(m["Source"]));
}
if (m.find("Table") != m.end() && !m["Table"].empty()) {
table = make_shared<string>(boost::any_cast<string>(m["Table"]));
}
if (m.find("Text") != m.end() && !m["Text"].empty()) {
text = make_shared<string>(boost::any_cast<string>(m["Text"]));
}
if (m.find("Uri") != m.end() && !m["Uri"].empty()) {
uri = make_shared<string>(boost::any_cast<string>(m["Uri"]));
}
}
virtual ~CreateGroupRequest() = default;
};
class CreateGroupResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<long> amount{};
shared_ptr<string> column{};
shared_ptr<string> createdTime{};
shared_ptr<string> filter{};
shared_ptr<string> id{};
shared_ptr<string> inferenceJobId{};
shared_ptr<string> name{};
shared_ptr<bool> phoneNumber{};
shared_ptr<string> project{};
shared_ptr<string> remark{};
shared_ptr<long> source{};
shared_ptr<long> status{};
shared_ptr<string> table{};
shared_ptr<string> text{};
shared_ptr<string> updatedTime{};
shared_ptr<string> uri{};
CreateGroupResponseBodyData() {}
explicit CreateGroupResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (amount) {
res["Amount"] = boost::any(*amount);
}
if (column) {
res["Column"] = boost::any(*column);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (filter) {
res["Filter"] = boost::any(*filter);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (inferenceJobId) {
res["InferenceJobId"] = boost::any(*inferenceJobId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (project) {
res["Project"] = boost::any(*project);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (source) {
res["Source"] = boost::any(*source);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (table) {
res["Table"] = boost::any(*table);
}
if (text) {
res["Text"] = boost::any(*text);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (uri) {
res["Uri"] = boost::any(*uri);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("Amount") != m.end() && !m["Amount"].empty()) {
amount = make_shared<long>(boost::any_cast<long>(m["Amount"]));
}
if (m.find("Column") != m.end() && !m["Column"].empty()) {
column = make_shared<string>(boost::any_cast<string>(m["Column"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Filter") != m.end() && !m["Filter"].empty()) {
filter = make_shared<string>(boost::any_cast<string>(m["Filter"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("InferenceJobId") != m.end() && !m["InferenceJobId"].empty()) {
inferenceJobId = make_shared<string>(boost::any_cast<string>(m["InferenceJobId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<bool>(boost::any_cast<bool>(m["PhoneNumber"]));
}
if (m.find("Project") != m.end() && !m["Project"].empty()) {
project = make_shared<string>(boost::any_cast<string>(m["Project"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Source") != m.end() && !m["Source"].empty()) {
source = make_shared<long>(boost::any_cast<long>(m["Source"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("Table") != m.end() && !m["Table"].empty()) {
table = make_shared<string>(boost::any_cast<string>(m["Table"]));
}
if (m.find("Text") != m.end() && !m["Text"].empty()) {
text = make_shared<string>(boost::any_cast<string>(m["Text"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("Uri") != m.end() && !m["Uri"].empty()) {
uri = make_shared<string>(boost::any_cast<string>(m["Uri"]));
}
}
virtual ~CreateGroupResponseBodyData() = default;
};
class CreateGroupResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateGroupResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateGroupResponseBody() {}
explicit CreateGroupResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateGroupResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateGroupResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateGroupResponseBody() = default;
};
class CreateGroupResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateGroupResponseBody> body{};
CreateGroupResponse() {}
explicit CreateGroupResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateGroupResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateGroupResponseBody>(model1);
}
}
}
virtual ~CreateGroupResponse() = default;
};
class CreateInferenceJobRequest : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> dataPath{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> targetPath{};
shared_ptr<string> trainingJobId{};
shared_ptr<string> userConfig{};
CreateInferenceJobRequest() {}
explicit CreateInferenceJobRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (targetPath) {
res["TargetPath"] = boost::any(*targetPath);
}
if (trainingJobId) {
res["TrainingJobId"] = boost::any(*trainingJobId);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("TargetPath") != m.end() && !m["TargetPath"].empty()) {
targetPath = make_shared<string>(boost::any_cast<string>(m["TargetPath"]));
}
if (m.find("TrainingJobId") != m.end() && !m["TrainingJobId"].empty()) {
trainingJobId = make_shared<string>(boost::any_cast<string>(m["TrainingJobId"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~CreateInferenceJobRequest() = default;
};
class CreateInferenceJobResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> groupId{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> targetPath{};
shared_ptr<string> trainingJobId{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
CreateInferenceJobResponseBodyData() {}
explicit CreateInferenceJobResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (targetPath) {
res["TargetPath"] = boost::any(*targetPath);
}
if (trainingJobId) {
res["TrainingJobId"] = boost::any(*trainingJobId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TargetPath") != m.end() && !m["TargetPath"].empty()) {
targetPath = make_shared<string>(boost::any_cast<string>(m["TargetPath"]));
}
if (m.find("TrainingJobId") != m.end() && !m["TrainingJobId"].empty()) {
trainingJobId = make_shared<string>(boost::any_cast<string>(m["TrainingJobId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~CreateInferenceJobResponseBodyData() = default;
};
class CreateInferenceJobResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateInferenceJobResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateInferenceJobResponseBody() {}
explicit CreateInferenceJobResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateInferenceJobResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateInferenceJobResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateInferenceJobResponseBody() = default;
};
class CreateInferenceJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateInferenceJobResponseBody> body{};
CreateInferenceJobResponse() {}
explicit CreateInferenceJobResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateInferenceJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateInferenceJobResponseBody>(model1);
}
}
}
virtual ~CreateInferenceJobResponse() = default;
};
class CreateScheduleRequest : public Darabonba::Model {
public:
shared_ptr<long> endTime{};
shared_ptr<string> executeTime{};
shared_ptr<string> groupId{};
shared_ptr<string> name{};
shared_ptr<long> repeatCycle{};
shared_ptr<long> repeatCycleUnit{};
shared_ptr<long> repeatTimes{};
shared_ptr<string> signName{};
shared_ptr<string> signatureId{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
CreateScheduleRequest() {}
explicit CreateScheduleRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (endTime) {
res["EndTime"] = boost::any(*endTime);
}
if (executeTime) {
res["ExecuteTime"] = boost::any(*executeTime);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (repeatCycle) {
res["RepeatCycle"] = boost::any(*repeatCycle);
}
if (repeatCycleUnit) {
res["RepeatCycleUnit"] = boost::any(*repeatCycleUnit);
}
if (repeatTimes) {
res["RepeatTimes"] = boost::any(*repeatTimes);
}
if (signName) {
res["SignName"] = boost::any(*signName);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) {
endTime = make_shared<long>(boost::any_cast<long>(m["EndTime"]));
}
if (m.find("ExecuteTime") != m.end() && !m["ExecuteTime"].empty()) {
executeTime = make_shared<string>(boost::any_cast<string>(m["ExecuteTime"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("RepeatCycle") != m.end() && !m["RepeatCycle"].empty()) {
repeatCycle = make_shared<long>(boost::any_cast<long>(m["RepeatCycle"]));
}
if (m.find("RepeatCycleUnit") != m.end() && !m["RepeatCycleUnit"].empty()) {
repeatCycleUnit = make_shared<long>(boost::any_cast<long>(m["RepeatCycleUnit"]));
}
if (m.find("RepeatTimes") != m.end() && !m["RepeatTimes"].empty()) {
repeatTimes = make_shared<long>(boost::any_cast<long>(m["RepeatTimes"]));
}
if (m.find("SignName") != m.end() && !m["SignName"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["SignName"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
}
virtual ~CreateScheduleRequest() = default;
};
class CreateScheduleResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<long> endTime{};
shared_ptr<string> executeTime{};
shared_ptr<string> groupId{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> repeatCycle{};
shared_ptr<long> repeatCycleUnit{};
shared_ptr<long> repeatTimes{};
shared_ptr<string> signName{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<string> updatedTime{};
CreateScheduleResponseBodyData() {}
explicit CreateScheduleResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (endTime) {
res["EndTime"] = boost::any(*endTime);
}
if (executeTime) {
res["ExecuteTime"] = boost::any(*executeTime);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (repeatCycle) {
res["RepeatCycle"] = boost::any(*repeatCycle);
}
if (repeatCycleUnit) {
res["RepeatCycleUnit"] = boost::any(*repeatCycleUnit);
}
if (repeatTimes) {
res["RepeatTimes"] = boost::any(*repeatTimes);
}
if (signName) {
res["SignName"] = boost::any(*signName);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) {
endTime = make_shared<long>(boost::any_cast<long>(m["EndTime"]));
}
if (m.find("ExecuteTime") != m.end() && !m["ExecuteTime"].empty()) {
executeTime = make_shared<string>(boost::any_cast<string>(m["ExecuteTime"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("RepeatCycle") != m.end() && !m["RepeatCycle"].empty()) {
repeatCycle = make_shared<long>(boost::any_cast<long>(m["RepeatCycle"]));
}
if (m.find("RepeatCycleUnit") != m.end() && !m["RepeatCycleUnit"].empty()) {
repeatCycleUnit = make_shared<long>(boost::any_cast<long>(m["RepeatCycleUnit"]));
}
if (m.find("RepeatTimes") != m.end() && !m["RepeatTimes"].empty()) {
repeatTimes = make_shared<long>(boost::any_cast<long>(m["RepeatTimes"]));
}
if (m.find("SignName") != m.end() && !m["SignName"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["SignName"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~CreateScheduleResponseBodyData() = default;
};
class CreateScheduleResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateScheduleResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateScheduleResponseBody() {}
explicit CreateScheduleResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateScheduleResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateScheduleResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateScheduleResponseBody() = default;
};
class CreateScheduleResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateScheduleResponseBody> body{};
CreateScheduleResponse() {}
explicit CreateScheduleResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateScheduleResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateScheduleResponseBody>(model1);
}
}
}
virtual ~CreateScheduleResponse() = default;
};
class CreateSignatureRequest : public Darabonba::Model {
public:
shared_ptr<string> description{};
shared_ptr<string> name{};
CreateSignatureRequest() {}
explicit CreateSignatureRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (description) {
res["Description"] = boost::any(*description);
}
if (name) {
res["Name"] = boost::any(*name);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
}
virtual ~CreateSignatureRequest() = default;
};
class CreateSignatureResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
CreateSignatureResponseBodyData() {}
explicit CreateSignatureResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~CreateSignatureResponseBodyData() = default;
};
class CreateSignatureResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateSignatureResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateSignatureResponseBody() {}
explicit CreateSignatureResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateSignatureResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateSignatureResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateSignatureResponseBody() = default;
};
class CreateSignatureResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateSignatureResponseBody> body{};
CreateSignatureResponse() {}
explicit CreateSignatureResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateSignatureResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateSignatureResponseBody>(model1);
}
}
}
virtual ~CreateSignatureResponse() = default;
};
class CreateTemplateRequest : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> description{};
shared_ptr<string> name{};
shared_ptr<string> signature{};
shared_ptr<string> signatureId{};
shared_ptr<long> type{};
CreateTemplateRequest() {}
explicit CreateTemplateRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (content) {
res["Content"] = boost::any(*content);
}
if (description) {
res["Description"] = boost::any(*description);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (signature) {
res["Signature"] = boost::any(*signature);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (type) {
res["Type"] = boost::any(*type);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Content") != m.end() && !m["Content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["Content"]));
}
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Signature") != m.end() && !m["Signature"].empty()) {
signature = make_shared<string>(boost::any_cast<string>(m["Signature"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Type") != m.end() && !m["Type"].empty()) {
type = make_shared<long>(boost::any_cast<long>(m["Type"]));
}
}
virtual ~CreateTemplateRequest() = default;
};
class CreateTemplateResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> createdTime{};
shared_ptr<string> description{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> reason{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<long> type{};
shared_ptr<string> updatedTime{};
CreateTemplateResponseBodyData() {}
explicit CreateTemplateResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (content) {
res["Content"] = boost::any(*content);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (description) {
res["Description"] = boost::any(*description);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (reason) {
res["Reason"] = boost::any(*reason);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (type) {
res["Type"] = boost::any(*type);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Content") != m.end() && !m["Content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["Content"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Reason") != m.end() && !m["Reason"].empty()) {
reason = make_shared<string>(boost::any_cast<string>(m["Reason"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("Type") != m.end() && !m["Type"].empty()) {
type = make_shared<long>(boost::any_cast<long>(m["Type"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~CreateTemplateResponseBodyData() = default;
};
class CreateTemplateResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateTemplateResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateTemplateResponseBody() {}
explicit CreateTemplateResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateTemplateResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateTemplateResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateTemplateResponseBody() = default;
};
class CreateTemplateResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateTemplateResponseBody> body{};
CreateTemplateResponse() {}
explicit CreateTemplateResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateTemplateResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateTemplateResponseBody>(model1);
}
}
}
virtual ~CreateTemplateResponse() = default;
};
class CreateTrainingJobRequest : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> dataPath{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> userConfig{};
CreateTrainingJobRequest() {}
explicit CreateTrainingJobRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~CreateTrainingJobRequest() = default;
};
class CreateTrainingJobResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
CreateTrainingJobResponseBodyData() {}
explicit CreateTrainingJobResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~CreateTrainingJobResponseBodyData() = default;
};
class CreateTrainingJobResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateTrainingJobResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateTrainingJobResponseBody() {}
explicit CreateTrainingJobResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateTrainingJobResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateTrainingJobResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateTrainingJobResponseBody() = default;
};
class CreateTrainingJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateTrainingJobResponseBody> body{};
CreateTrainingJobResponse() {}
explicit CreateTrainingJobResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateTrainingJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateTrainingJobResponseBody>(model1);
}
}
}
virtual ~CreateTrainingJobResponse() = default;
};
class DeleteCampaignResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteCampaignResponseBody() {}
explicit DeleteCampaignResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteCampaignResponseBody() = default;
};
class DeleteCampaignResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteCampaignResponseBody> body{};
DeleteCampaignResponse() {}
explicit DeleteCampaignResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteCampaignResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteCampaignResponseBody>(model1);
}
}
}
virtual ~DeleteCampaignResponse() = default;
};
class DeleteGroupResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteGroupResponseBody() {}
explicit DeleteGroupResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteGroupResponseBody() = default;
};
class DeleteGroupResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteGroupResponseBody> body{};
DeleteGroupResponse() {}
explicit DeleteGroupResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteGroupResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteGroupResponseBody>(model1);
}
}
}
virtual ~DeleteGroupResponse() = default;
};
class DeleteInferenceJobResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteInferenceJobResponseBody() {}
explicit DeleteInferenceJobResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteInferenceJobResponseBody() = default;
};
class DeleteInferenceJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteInferenceJobResponseBody> body{};
DeleteInferenceJobResponse() {}
explicit DeleteInferenceJobResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteInferenceJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteInferenceJobResponseBody>(model1);
}
}
}
virtual ~DeleteInferenceJobResponse() = default;
};
class DeleteScheduleResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteScheduleResponseBody() {}
explicit DeleteScheduleResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteScheduleResponseBody() = default;
};
class DeleteScheduleResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteScheduleResponseBody> body{};
DeleteScheduleResponse() {}
explicit DeleteScheduleResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteScheduleResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteScheduleResponseBody>(model1);
}
}
}
virtual ~DeleteScheduleResponse() = default;
};
class DeleteSignatureResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteSignatureResponseBody() {}
explicit DeleteSignatureResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteSignatureResponseBody() = default;
};
class DeleteSignatureResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteSignatureResponseBody> body{};
DeleteSignatureResponse() {}
explicit DeleteSignatureResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteSignatureResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteSignatureResponseBody>(model1);
}
}
}
virtual ~DeleteSignatureResponse() = default;
};
class DeleteTemplateResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteTemplateResponseBody() {}
explicit DeleteTemplateResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteTemplateResponseBody() = default;
};
class DeleteTemplateResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteTemplateResponseBody> body{};
DeleteTemplateResponse() {}
explicit DeleteTemplateResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteTemplateResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteTemplateResponseBody>(model1);
}
}
}
virtual ~DeleteTemplateResponse() = default;
};
class DeleteTrainingJobResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteTrainingJobResponseBody() {}
explicit DeleteTrainingJobResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteTrainingJobResponseBody() = default;
};
class DeleteTrainingJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteTrainingJobResponseBody> body{};
DeleteTrainingJobResponse() {}
explicit DeleteTrainingJobResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteTrainingJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteTrainingJobResponseBody>(model1);
}
}
}
virtual ~DeleteTrainingJobResponse() = default;
};
class GetAlgorithmResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> description{};
shared_ptr<string> id{};
shared_ptr<string> inferUserConfigMap{};
shared_ptr<string> name{};
shared_ptr<string> trainUserConfigMap{};
GetAlgorithmResponseBodyData() {}
explicit GetAlgorithmResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (description) {
res["Description"] = boost::any(*description);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (inferUserConfigMap) {
res["InferUserConfigMap"] = boost::any(*inferUserConfigMap);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (trainUserConfigMap) {
res["TrainUserConfigMap"] = boost::any(*trainUserConfigMap);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("InferUserConfigMap") != m.end() && !m["InferUserConfigMap"].empty()) {
inferUserConfigMap = make_shared<string>(boost::any_cast<string>(m["InferUserConfigMap"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("TrainUserConfigMap") != m.end() && !m["TrainUserConfigMap"].empty()) {
trainUserConfigMap = make_shared<string>(boost::any_cast<string>(m["TrainUserConfigMap"]));
}
}
virtual ~GetAlgorithmResponseBodyData() = default;
};
class GetAlgorithmResponseBody : public Darabonba::Model {
public:
shared_ptr<GetAlgorithmResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetAlgorithmResponseBody() {}
explicit GetAlgorithmResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetAlgorithmResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetAlgorithmResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetAlgorithmResponseBody() = default;
};
class GetAlgorithmResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetAlgorithmResponseBody> body{};
GetAlgorithmResponse() {}
explicit GetAlgorithmResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetAlgorithmResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetAlgorithmResponseBody>(model1);
}
}
}
virtual ~GetAlgorithmResponse() = default;
};
class GetCampaignResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> updatedTime{};
GetCampaignResponseBodyData() {}
explicit GetCampaignResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~GetCampaignResponseBodyData() = default;
};
class GetCampaignResponseBody : public Darabonba::Model {
public:
shared_ptr<GetCampaignResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetCampaignResponseBody() {}
explicit GetCampaignResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetCampaignResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetCampaignResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetCampaignResponseBody() = default;
};
class GetCampaignResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetCampaignResponseBody> body{};
GetCampaignResponse() {}
explicit GetCampaignResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetCampaignResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetCampaignResponseBody>(model1);
}
}
}
virtual ~GetCampaignResponse() = default;
};
class GetGroupResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<long> amount{};
shared_ptr<string> column{};
shared_ptr<string> createdTime{};
shared_ptr<string> filter{};
shared_ptr<string> id{};
shared_ptr<string> inferenceJobId{};
shared_ptr<string> name{};
shared_ptr<bool> phoneNumber{};
shared_ptr<string> project{};
shared_ptr<string> remark{};
shared_ptr<long> source{};
shared_ptr<long> status{};
shared_ptr<string> table{};
shared_ptr<string> text{};
shared_ptr<string> updatedTime{};
shared_ptr<string> uri{};
GetGroupResponseBodyData() {}
explicit GetGroupResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (amount) {
res["Amount"] = boost::any(*amount);
}
if (column) {
res["Column"] = boost::any(*column);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (filter) {
res["Filter"] = boost::any(*filter);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (inferenceJobId) {
res["InferenceJobId"] = boost::any(*inferenceJobId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (project) {
res["Project"] = boost::any(*project);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (source) {
res["Source"] = boost::any(*source);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (table) {
res["Table"] = boost::any(*table);
}
if (text) {
res["Text"] = boost::any(*text);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (uri) {
res["Uri"] = boost::any(*uri);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("Amount") != m.end() && !m["Amount"].empty()) {
amount = make_shared<long>(boost::any_cast<long>(m["Amount"]));
}
if (m.find("Column") != m.end() && !m["Column"].empty()) {
column = make_shared<string>(boost::any_cast<string>(m["Column"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Filter") != m.end() && !m["Filter"].empty()) {
filter = make_shared<string>(boost::any_cast<string>(m["Filter"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("InferenceJobId") != m.end() && !m["InferenceJobId"].empty()) {
inferenceJobId = make_shared<string>(boost::any_cast<string>(m["InferenceJobId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<bool>(boost::any_cast<bool>(m["PhoneNumber"]));
}
if (m.find("Project") != m.end() && !m["Project"].empty()) {
project = make_shared<string>(boost::any_cast<string>(m["Project"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Source") != m.end() && !m["Source"].empty()) {
source = make_shared<long>(boost::any_cast<long>(m["Source"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("Table") != m.end() && !m["Table"].empty()) {
table = make_shared<string>(boost::any_cast<string>(m["Table"]));
}
if (m.find("Text") != m.end() && !m["Text"].empty()) {
text = make_shared<string>(boost::any_cast<string>(m["Text"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("Uri") != m.end() && !m["Uri"].empty()) {
uri = make_shared<string>(boost::any_cast<string>(m["Uri"]));
}
}
virtual ~GetGroupResponseBodyData() = default;
};
class GetGroupResponseBody : public Darabonba::Model {
public:
shared_ptr<GetGroupResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetGroupResponseBody() {}
explicit GetGroupResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetGroupResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetGroupResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetGroupResponseBody() = default;
};
class GetGroupResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetGroupResponseBody> body{};
GetGroupResponse() {}
explicit GetGroupResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetGroupResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetGroupResponseBody>(model1);
}
}
}
virtual ~GetGroupResponse() = default;
};
class GetInferenceJobResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> groupId{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> targetPath{};
shared_ptr<string> trainingJobId{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
GetInferenceJobResponseBodyData() {}
explicit GetInferenceJobResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (targetPath) {
res["TargetPath"] = boost::any(*targetPath);
}
if (trainingJobId) {
res["TrainingJobId"] = boost::any(*trainingJobId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TargetPath") != m.end() && !m["TargetPath"].empty()) {
targetPath = make_shared<string>(boost::any_cast<string>(m["TargetPath"]));
}
if (m.find("TrainingJobId") != m.end() && !m["TrainingJobId"].empty()) {
trainingJobId = make_shared<string>(boost::any_cast<string>(m["TrainingJobId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~GetInferenceJobResponseBodyData() = default;
};
class GetInferenceJobResponseBody : public Darabonba::Model {
public:
shared_ptr<GetInferenceJobResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetInferenceJobResponseBody() {}
explicit GetInferenceJobResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetInferenceJobResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetInferenceJobResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetInferenceJobResponseBody() = default;
};
class GetInferenceJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetInferenceJobResponseBody> body{};
GetInferenceJobResponse() {}
explicit GetInferenceJobResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetInferenceJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetInferenceJobResponseBody>(model1);
}
}
}
virtual ~GetInferenceJobResponse() = default;
};
class GetMessageConfigResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> smsReportUrl{};
shared_ptr<string> smsUpUrl{};
GetMessageConfigResponseBodyData() {}
explicit GetMessageConfigResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (smsReportUrl) {
res["SmsReportUrl"] = boost::any(*smsReportUrl);
}
if (smsUpUrl) {
res["SmsUpUrl"] = boost::any(*smsUpUrl);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("SmsReportUrl") != m.end() && !m["SmsReportUrl"].empty()) {
smsReportUrl = make_shared<string>(boost::any_cast<string>(m["SmsReportUrl"]));
}
if (m.find("SmsUpUrl") != m.end() && !m["SmsUpUrl"].empty()) {
smsUpUrl = make_shared<string>(boost::any_cast<string>(m["SmsUpUrl"]));
}
}
virtual ~GetMessageConfigResponseBodyData() = default;
};
class GetMessageConfigResponseBody : public Darabonba::Model {
public:
shared_ptr<GetMessageConfigResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetMessageConfigResponseBody() {}
explicit GetMessageConfigResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetMessageConfigResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetMessageConfigResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetMessageConfigResponseBody() = default;
};
class GetMessageConfigResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetMessageConfigResponseBody> body{};
GetMessageConfigResponse() {}
explicit GetMessageConfigResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetMessageConfigResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetMessageConfigResponseBody>(model1);
}
}
}
virtual ~GetMessageConfigResponse() = default;
};
class GetScheduleResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<long> endTime{};
shared_ptr<string> executeTime{};
shared_ptr<string> groupId{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> repeatCycle{};
shared_ptr<long> repeatCycleUnit{};
shared_ptr<long> repeatTimes{};
shared_ptr<string> signName{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<string> updatedTime{};
GetScheduleResponseBodyData() {}
explicit GetScheduleResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (endTime) {
res["EndTime"] = boost::any(*endTime);
}
if (executeTime) {
res["ExecuteTime"] = boost::any(*executeTime);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (repeatCycle) {
res["RepeatCycle"] = boost::any(*repeatCycle);
}
if (repeatCycleUnit) {
res["RepeatCycleUnit"] = boost::any(*repeatCycleUnit);
}
if (repeatTimes) {
res["RepeatTimes"] = boost::any(*repeatTimes);
}
if (signName) {
res["SignName"] = boost::any(*signName);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) {
endTime = make_shared<long>(boost::any_cast<long>(m["EndTime"]));
}
if (m.find("ExecuteTime") != m.end() && !m["ExecuteTime"].empty()) {
executeTime = make_shared<string>(boost::any_cast<string>(m["ExecuteTime"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("RepeatCycle") != m.end() && !m["RepeatCycle"].empty()) {
repeatCycle = make_shared<long>(boost::any_cast<long>(m["RepeatCycle"]));
}
if (m.find("RepeatCycleUnit") != m.end() && !m["RepeatCycleUnit"].empty()) {
repeatCycleUnit = make_shared<long>(boost::any_cast<long>(m["RepeatCycleUnit"]));
}
if (m.find("RepeatTimes") != m.end() && !m["RepeatTimes"].empty()) {
repeatTimes = make_shared<long>(boost::any_cast<long>(m["RepeatTimes"]));
}
if (m.find("SignName") != m.end() && !m["SignName"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["SignName"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~GetScheduleResponseBodyData() = default;
};
class GetScheduleResponseBody : public Darabonba::Model {
public:
shared_ptr<GetScheduleResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetScheduleResponseBody() {}
explicit GetScheduleResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetScheduleResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetScheduleResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetScheduleResponseBody() = default;
};
class GetScheduleResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetScheduleResponseBody> body{};
GetScheduleResponse() {}
explicit GetScheduleResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetScheduleResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetScheduleResponseBody>(model1);
}
}
}
virtual ~GetScheduleResponse() = default;
};
class GetSignatureResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> description{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> reason{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
GetSignatureResponseBodyData() {}
explicit GetSignatureResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (description) {
res["Description"] = boost::any(*description);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (reason) {
res["Reason"] = boost::any(*reason);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Reason") != m.end() && !m["Reason"].empty()) {
reason = make_shared<string>(boost::any_cast<string>(m["Reason"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~GetSignatureResponseBodyData() = default;
};
class GetSignatureResponseBody : public Darabonba::Model {
public:
shared_ptr<GetSignatureResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetSignatureResponseBody() {}
explicit GetSignatureResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetSignatureResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetSignatureResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetSignatureResponseBody() = default;
};
class GetSignatureResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetSignatureResponseBody> body{};
GetSignatureResponse() {}
explicit GetSignatureResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetSignatureResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetSignatureResponseBody>(model1);
}
}
}
virtual ~GetSignatureResponse() = default;
};
class GetTemplateResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> createdTime{};
shared_ptr<string> description{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> reason{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<long> type{};
shared_ptr<string> updatedTime{};
GetTemplateResponseBodyData() {}
explicit GetTemplateResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (content) {
res["Content"] = boost::any(*content);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (description) {
res["Description"] = boost::any(*description);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (reason) {
res["Reason"] = boost::any(*reason);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (type) {
res["Type"] = boost::any(*type);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Content") != m.end() && !m["Content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["Content"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Reason") != m.end() && !m["Reason"].empty()) {
reason = make_shared<string>(boost::any_cast<string>(m["Reason"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("Type") != m.end() && !m["Type"].empty()) {
type = make_shared<long>(boost::any_cast<long>(m["Type"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~GetTemplateResponseBodyData() = default;
};
class GetTemplateResponseBody : public Darabonba::Model {
public:
shared_ptr<GetTemplateResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetTemplateResponseBody() {}
explicit GetTemplateResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetTemplateResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetTemplateResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetTemplateResponseBody() = default;
};
class GetTemplateResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetTemplateResponseBody> body{};
GetTemplateResponse() {}
explicit GetTemplateResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetTemplateResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetTemplateResponseBody>(model1);
}
}
}
virtual ~GetTemplateResponse() = default;
};
class GetTrainingJobResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
GetTrainingJobResponseBodyData() {}
explicit GetTrainingJobResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~GetTrainingJobResponseBodyData() = default;
};
class GetTrainingJobResponseBody : public Darabonba::Model {
public:
shared_ptr<GetTrainingJobResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetTrainingJobResponseBody() {}
explicit GetTrainingJobResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetTrainingJobResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetTrainingJobResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetTrainingJobResponseBody() = default;
};
class GetTrainingJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetTrainingJobResponseBody> body{};
GetTrainingJobResponse() {}
explicit GetTrainingJobResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetTrainingJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetTrainingJobResponseBody>(model1);
}
}
}
virtual ~GetTrainingJobResponse() = default;
};
class GetUserResponseBodyData : public Darabonba::Model {
public:
shared_ptr<long> accountStatus{};
GetUserResponseBodyData() {}
explicit GetUserResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (accountStatus) {
res["AccountStatus"] = boost::any(*accountStatus);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("AccountStatus") != m.end() && !m["AccountStatus"].empty()) {
accountStatus = make_shared<long>(boost::any_cast<long>(m["AccountStatus"]));
}
}
virtual ~GetUserResponseBodyData() = default;
};
class GetUserResponseBody : public Darabonba::Model {
public:
shared_ptr<GetUserResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetUserResponseBody() {}
explicit GetUserResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetUserResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetUserResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetUserResponseBody() = default;
};
class GetUserResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetUserResponseBody> body{};
GetUserResponse() {}
explicit GetUserResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetUserResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetUserResponseBody>(model1);
}
}
}
virtual ~GetUserResponse() = default;
};
class ListAlgorithmsRequest : public Darabonba::Model {
public:
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
ListAlgorithmsRequest() {}
explicit ListAlgorithmsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
}
virtual ~ListAlgorithmsRequest() = default;
};
class ListAlgorithmsResponseBodyDataAlgorithms : public Darabonba::Model {
public:
shared_ptr<string> id{};
shared_ptr<string> name{};
ListAlgorithmsResponseBodyDataAlgorithms() {}
explicit ListAlgorithmsResponseBodyDataAlgorithms(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
}
virtual ~ListAlgorithmsResponseBodyDataAlgorithms() = default;
};
class ListAlgorithmsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListAlgorithmsResponseBodyDataAlgorithms>> algorithms{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListAlgorithmsResponseBodyData() {}
explicit ListAlgorithmsResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithms) {
vector<boost::any> temp1;
for(auto item1:*algorithms){
temp1.push_back(boost::any(item1.toMap()));
}
res["Algorithms"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithms") != m.end() && !m["Algorithms"].empty()) {
if (typeid(vector<boost::any>) == m["Algorithms"].type()) {
vector<ListAlgorithmsResponseBodyDataAlgorithms> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Algorithms"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListAlgorithmsResponseBodyDataAlgorithms model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
algorithms = make_shared<vector<ListAlgorithmsResponseBodyDataAlgorithms>>(expect1);
}
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListAlgorithmsResponseBodyData() = default;
};
class ListAlgorithmsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListAlgorithmsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListAlgorithmsResponseBody() {}
explicit ListAlgorithmsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListAlgorithmsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListAlgorithmsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListAlgorithmsResponseBody() = default;
};
class ListAlgorithmsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListAlgorithmsResponseBody> body{};
ListAlgorithmsResponse() {}
explicit ListAlgorithmsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListAlgorithmsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListAlgorithmsResponseBody>(model1);
}
}
}
virtual ~ListAlgorithmsResponse() = default;
};
class ListCampaignsRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<string> remark{};
ListCampaignsRequest() {}
explicit ListCampaignsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
}
virtual ~ListCampaignsRequest() = default;
};
class ListCampaignsResponseBodyDataCampaigns : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> updatedTime{};
ListCampaignsResponseBodyDataCampaigns() {}
explicit ListCampaignsResponseBodyDataCampaigns(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~ListCampaignsResponseBodyDataCampaigns() = default;
};
class ListCampaignsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListCampaignsResponseBodyDataCampaigns>> campaigns{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListCampaignsResponseBodyData() {}
explicit ListCampaignsResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (campaigns) {
vector<boost::any> temp1;
for(auto item1:*campaigns){
temp1.push_back(boost::any(item1.toMap()));
}
res["Campaigns"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Campaigns") != m.end() && !m["Campaigns"].empty()) {
if (typeid(vector<boost::any>) == m["Campaigns"].type()) {
vector<ListCampaignsResponseBodyDataCampaigns> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Campaigns"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListCampaignsResponseBodyDataCampaigns model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
campaigns = make_shared<vector<ListCampaignsResponseBodyDataCampaigns>>(expect1);
}
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListCampaignsResponseBodyData() = default;
};
class ListCampaignsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListCampaignsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListCampaignsResponseBody() {}
explicit ListCampaignsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListCampaignsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListCampaignsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListCampaignsResponseBody() = default;
};
class ListCampaignsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListCampaignsResponseBody> body{};
ListCampaignsResponse() {}
explicit ListCampaignsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListCampaignsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListCampaignsResponseBody>(model1);
}
}
}
virtual ~ListCampaignsResponse() = default;
};
class ListGroupsRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<bool> phoneNumber{};
shared_ptr<string> remark{};
shared_ptr<long> source{};
shared_ptr<long> status{};
ListGroupsRequest() {}
explicit ListGroupsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (source) {
res["Source"] = boost::any(*source);
}
if (status) {
res["Status"] = boost::any(*status);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<bool>(boost::any_cast<bool>(m["PhoneNumber"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Source") != m.end() && !m["Source"].empty()) {
source = make_shared<long>(boost::any_cast<long>(m["Source"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
}
virtual ~ListGroupsRequest() = default;
};
class ListGroupsResponseBodyDataGroups : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<long> amount{};
shared_ptr<string> column{};
shared_ptr<string> createdTime{};
shared_ptr<string> filter{};
shared_ptr<string> id{};
shared_ptr<string> inferenceJobId{};
shared_ptr<string> name{};
shared_ptr<bool> phoneNumber{};
shared_ptr<string> project{};
shared_ptr<string> remark{};
shared_ptr<long> source{};
shared_ptr<long> status{};
shared_ptr<string> table{};
shared_ptr<string> text{};
shared_ptr<string> updatedTime{};
shared_ptr<string> uri{};
ListGroupsResponseBodyDataGroups() {}
explicit ListGroupsResponseBodyDataGroups(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (amount) {
res["Amount"] = boost::any(*amount);
}
if (column) {
res["Column"] = boost::any(*column);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (filter) {
res["Filter"] = boost::any(*filter);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (inferenceJobId) {
res["InferenceJobId"] = boost::any(*inferenceJobId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (project) {
res["Project"] = boost::any(*project);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (source) {
res["Source"] = boost::any(*source);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (table) {
res["Table"] = boost::any(*table);
}
if (text) {
res["Text"] = boost::any(*text);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (uri) {
res["Uri"] = boost::any(*uri);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("Amount") != m.end() && !m["Amount"].empty()) {
amount = make_shared<long>(boost::any_cast<long>(m["Amount"]));
}
if (m.find("Column") != m.end() && !m["Column"].empty()) {
column = make_shared<string>(boost::any_cast<string>(m["Column"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Filter") != m.end() && !m["Filter"].empty()) {
filter = make_shared<string>(boost::any_cast<string>(m["Filter"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("InferenceJobId") != m.end() && !m["InferenceJobId"].empty()) {
inferenceJobId = make_shared<string>(boost::any_cast<string>(m["InferenceJobId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<bool>(boost::any_cast<bool>(m["PhoneNumber"]));
}
if (m.find("Project") != m.end() && !m["Project"].empty()) {
project = make_shared<string>(boost::any_cast<string>(m["Project"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Source") != m.end() && !m["Source"].empty()) {
source = make_shared<long>(boost::any_cast<long>(m["Source"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("Table") != m.end() && !m["Table"].empty()) {
table = make_shared<string>(boost::any_cast<string>(m["Table"]));
}
if (m.find("Text") != m.end() && !m["Text"].empty()) {
text = make_shared<string>(boost::any_cast<string>(m["Text"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("Uri") != m.end() && !m["Uri"].empty()) {
uri = make_shared<string>(boost::any_cast<string>(m["Uri"]));
}
}
virtual ~ListGroupsResponseBodyDataGroups() = default;
};
class ListGroupsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListGroupsResponseBodyDataGroups>> groups{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListGroupsResponseBodyData() {}
explicit ListGroupsResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (groups) {
vector<boost::any> temp1;
for(auto item1:*groups){
temp1.push_back(boost::any(item1.toMap()));
}
res["Groups"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Groups") != m.end() && !m["Groups"].empty()) {
if (typeid(vector<boost::any>) == m["Groups"].type()) {
vector<ListGroupsResponseBodyDataGroups> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Groups"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListGroupsResponseBodyDataGroups model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
groups = make_shared<vector<ListGroupsResponseBodyDataGroups>>(expect1);
}
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListGroupsResponseBodyData() = default;
};
class ListGroupsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListGroupsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListGroupsResponseBody() {}
explicit ListGroupsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListGroupsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListGroupsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListGroupsResponseBody() = default;
};
class ListGroupsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListGroupsResponseBody> body{};
ListGroupsResponse() {}
explicit ListGroupsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListGroupsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListGroupsResponseBody>(model1);
}
}
}
virtual ~ListGroupsResponse() = default;
};
class ListInferenceJobsRequest : public Darabonba::Model {
public:
shared_ptr<string> campaignId{};
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
ListInferenceJobsRequest() {}
explicit ListInferenceJobsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
}
virtual ~ListInferenceJobsRequest() = default;
};
class ListInferenceJobsResponseBodyDataInferenceJobs : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> groupId{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> targetPath{};
shared_ptr<string> trainingJobId{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
ListInferenceJobsResponseBodyDataInferenceJobs() {}
explicit ListInferenceJobsResponseBodyDataInferenceJobs(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (targetPath) {
res["TargetPath"] = boost::any(*targetPath);
}
if (trainingJobId) {
res["TrainingJobId"] = boost::any(*trainingJobId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TargetPath") != m.end() && !m["TargetPath"].empty()) {
targetPath = make_shared<string>(boost::any_cast<string>(m["TargetPath"]));
}
if (m.find("TrainingJobId") != m.end() && !m["TrainingJobId"].empty()) {
trainingJobId = make_shared<string>(boost::any_cast<string>(m["TrainingJobId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~ListInferenceJobsResponseBodyDataInferenceJobs() = default;
};
class ListInferenceJobsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListInferenceJobsResponseBodyDataInferenceJobs>> inferenceJobs{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListInferenceJobsResponseBodyData() {}
explicit ListInferenceJobsResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (inferenceJobs) {
vector<boost::any> temp1;
for(auto item1:*inferenceJobs){
temp1.push_back(boost::any(item1.toMap()));
}
res["InferenceJobs"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("InferenceJobs") != m.end() && !m["InferenceJobs"].empty()) {
if (typeid(vector<boost::any>) == m["InferenceJobs"].type()) {
vector<ListInferenceJobsResponseBodyDataInferenceJobs> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["InferenceJobs"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListInferenceJobsResponseBodyDataInferenceJobs model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
inferenceJobs = make_shared<vector<ListInferenceJobsResponseBodyDataInferenceJobs>>(expect1);
}
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListInferenceJobsResponseBodyData() = default;
};
class ListInferenceJobsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListInferenceJobsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListInferenceJobsResponseBody() {}
explicit ListInferenceJobsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListInferenceJobsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListInferenceJobsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListInferenceJobsResponseBody() = default;
};
class ListInferenceJobsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListInferenceJobsResponseBody> body{};
ListInferenceJobsResponse() {}
explicit ListInferenceJobsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListInferenceJobsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListInferenceJobsResponseBody>(model1);
}
}
}
virtual ~ListInferenceJobsResponse() = default;
};
class ListMessageMetricsRequest : public Darabonba::Model {
public:
shared_ptr<string> endDate{};
shared_ptr<string> groupId{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<string> scheduleId{};
shared_ptr<string> signature{};
shared_ptr<string> signatureId{};
shared_ptr<string> startDate{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<long> templateType{};
ListMessageMetricsRequest() {}
explicit ListMessageMetricsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (endDate) {
res["EndDate"] = boost::any(*endDate);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (scheduleId) {
res["ScheduleId"] = boost::any(*scheduleId);
}
if (signature) {
res["Signature"] = boost::any(*signature);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (startDate) {
res["StartDate"] = boost::any(*startDate);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (templateType) {
res["TemplateType"] = boost::any(*templateType);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("EndDate") != m.end() && !m["EndDate"].empty()) {
endDate = make_shared<string>(boost::any_cast<string>(m["EndDate"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("ScheduleId") != m.end() && !m["ScheduleId"].empty()) {
scheduleId = make_shared<string>(boost::any_cast<string>(m["ScheduleId"]));
}
if (m.find("Signature") != m.end() && !m["Signature"].empty()) {
signature = make_shared<string>(boost::any_cast<string>(m["Signature"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("StartDate") != m.end() && !m["StartDate"].empty()) {
startDate = make_shared<string>(boost::any_cast<string>(m["StartDate"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("TemplateType") != m.end() && !m["TemplateType"].empty()) {
templateType = make_shared<long>(boost::any_cast<long>(m["TemplateType"]));
}
}
virtual ~ListMessageMetricsRequest() = default;
};
class ListMessageMetricsResponseBodyDataMetrics : public Darabonba::Model {
public:
shared_ptr<string> date{};
shared_ptr<long> fail{};
shared_ptr<long> pending{};
shared_ptr<double> rate{};
shared_ptr<long> success{};
shared_ptr<long> total{};
ListMessageMetricsResponseBodyDataMetrics() {}
explicit ListMessageMetricsResponseBodyDataMetrics(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (date) {
res["Date"] = boost::any(*date);
}
if (fail) {
res["Fail"] = boost::any(*fail);
}
if (pending) {
res["Pending"] = boost::any(*pending);
}
if (rate) {
res["Rate"] = boost::any(*rate);
}
if (success) {
res["Success"] = boost::any(*success);
}
if (total) {
res["Total"] = boost::any(*total);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Date") != m.end() && !m["Date"].empty()) {
date = make_shared<string>(boost::any_cast<string>(m["Date"]));
}
if (m.find("Fail") != m.end() && !m["Fail"].empty()) {
fail = make_shared<long>(boost::any_cast<long>(m["Fail"]));
}
if (m.find("Pending") != m.end() && !m["Pending"].empty()) {
pending = make_shared<long>(boost::any_cast<long>(m["Pending"]));
}
if (m.find("Rate") != m.end() && !m["Rate"].empty()) {
rate = make_shared<double>(boost::any_cast<double>(m["Rate"]));
}
if (m.find("Success") != m.end() && !m["Success"].empty()) {
success = make_shared<long>(boost::any_cast<long>(m["Success"]));
}
if (m.find("Total") != m.end() && !m["Total"].empty()) {
total = make_shared<long>(boost::any_cast<long>(m["Total"]));
}
}
virtual ~ListMessageMetricsResponseBodyDataMetrics() = default;
};
class ListMessageMetricsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListMessageMetricsResponseBodyDataMetrics>> metrics{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListMessageMetricsResponseBodyData() {}
explicit ListMessageMetricsResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (metrics) {
vector<boost::any> temp1;
for(auto item1:*metrics){
temp1.push_back(boost::any(item1.toMap()));
}
res["Metrics"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Metrics") != m.end() && !m["Metrics"].empty()) {
if (typeid(vector<boost::any>) == m["Metrics"].type()) {
vector<ListMessageMetricsResponseBodyDataMetrics> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Metrics"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListMessageMetricsResponseBodyDataMetrics model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
metrics = make_shared<vector<ListMessageMetricsResponseBodyDataMetrics>>(expect1);
}
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListMessageMetricsResponseBodyData() = default;
};
class ListMessageMetricsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListMessageMetricsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListMessageMetricsResponseBody() {}
explicit ListMessageMetricsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListMessageMetricsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListMessageMetricsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListMessageMetricsResponseBody() = default;
};
class ListMessageMetricsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListMessageMetricsResponseBody> body{};
ListMessageMetricsResponse() {}
explicit ListMessageMetricsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListMessageMetricsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListMessageMetricsResponseBody>(model1);
}
}
}
virtual ~ListMessageMetricsResponse() = default;
};
class ListMessagesRequest : public Darabonba::Model {
public:
shared_ptr<string> datetime{};
shared_ptr<string> errorCode{};
shared_ptr<string> groupId{};
shared_ptr<string> messageId{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<string> phoneNumber{};
shared_ptr<string> requestId{};
shared_ptr<string> scheduleId{};
shared_ptr<string> signature{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<long> templateType{};
ListMessagesRequest() {}
explicit ListMessagesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (datetime) {
res["Datetime"] = boost::any(*datetime);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (messageId) {
res["MessageId"] = boost::any(*messageId);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
if (scheduleId) {
res["ScheduleId"] = boost::any(*scheduleId);
}
if (signature) {
res["Signature"] = boost::any(*signature);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (templateType) {
res["TemplateType"] = boost::any(*templateType);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Datetime") != m.end() && !m["Datetime"].empty()) {
datetime = make_shared<string>(boost::any_cast<string>(m["Datetime"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<string>(boost::any_cast<string>(m["ErrorCode"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("MessageId") != m.end() && !m["MessageId"].empty()) {
messageId = make_shared<string>(boost::any_cast<string>(m["MessageId"]));
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<string>(boost::any_cast<string>(m["PhoneNumber"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
if (m.find("ScheduleId") != m.end() && !m["ScheduleId"].empty()) {
scheduleId = make_shared<string>(boost::any_cast<string>(m["ScheduleId"]));
}
if (m.find("Signature") != m.end() && !m["Signature"].empty()) {
signature = make_shared<string>(boost::any_cast<string>(m["Signature"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("TemplateType") != m.end() && !m["TemplateType"].empty()) {
templateType = make_shared<long>(boost::any_cast<long>(m["TemplateType"]));
}
}
virtual ~ListMessagesRequest() = default;
};
class ListMessagesResponseBodyDataMessages : public Darabonba::Model {
public:
shared_ptr<string> errorCode{};
shared_ptr<string> groupId{};
shared_ptr<string> id{};
shared_ptr<string> outId{};
shared_ptr<string> phoneNumber{};
shared_ptr<string> scheduleId{};
shared_ptr<string> signature{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateParams{};
shared_ptr<long> templateType{};
ListMessagesResponseBodyDataMessages() {}
explicit ListMessagesResponseBodyDataMessages(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (outId) {
res["OutId"] = boost::any(*outId);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (scheduleId) {
res["ScheduleId"] = boost::any(*scheduleId);
}
if (signature) {
res["Signature"] = boost::any(*signature);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateParams) {
res["TemplateParams"] = boost::any(*templateParams);
}
if (templateType) {
res["TemplateType"] = boost::any(*templateType);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<string>(boost::any_cast<string>(m["ErrorCode"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("OutId") != m.end() && !m["OutId"].empty()) {
outId = make_shared<string>(boost::any_cast<string>(m["OutId"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<string>(boost::any_cast<string>(m["PhoneNumber"]));
}
if (m.find("ScheduleId") != m.end() && !m["ScheduleId"].empty()) {
scheduleId = make_shared<string>(boost::any_cast<string>(m["ScheduleId"]));
}
if (m.find("Signature") != m.end() && !m["Signature"].empty()) {
signature = make_shared<string>(boost::any_cast<string>(m["Signature"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateParams") != m.end() && !m["TemplateParams"].empty()) {
templateParams = make_shared<string>(boost::any_cast<string>(m["TemplateParams"]));
}
if (m.find("TemplateType") != m.end() && !m["TemplateType"].empty()) {
templateType = make_shared<long>(boost::any_cast<long>(m["TemplateType"]));
}
}
virtual ~ListMessagesResponseBodyDataMessages() = default;
};
class ListMessagesResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListMessagesResponseBodyDataMessages>> messages{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListMessagesResponseBodyData() {}
explicit ListMessagesResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (messages) {
vector<boost::any> temp1;
for(auto item1:*messages){
temp1.push_back(boost::any(item1.toMap()));
}
res["Messages"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Messages") != m.end() && !m["Messages"].empty()) {
if (typeid(vector<boost::any>) == m["Messages"].type()) {
vector<ListMessagesResponseBodyDataMessages> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Messages"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListMessagesResponseBodyDataMessages model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
messages = make_shared<vector<ListMessagesResponseBodyDataMessages>>(expect1);
}
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListMessagesResponseBodyData() = default;
};
class ListMessagesResponseBody : public Darabonba::Model {
public:
shared_ptr<ListMessagesResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListMessagesResponseBody() {}
explicit ListMessagesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListMessagesResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListMessagesResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListMessagesResponseBody() = default;
};
class ListMessagesResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListMessagesResponseBody> body{};
ListMessagesResponse() {}
explicit ListMessagesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListMessagesResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListMessagesResponseBody>(model1);
}
}
}
virtual ~ListMessagesResponse() = default;
};
class ListSchedulesRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> status{};
ListSchedulesRequest() {}
explicit ListSchedulesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (status) {
res["Status"] = boost::any(*status);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
}
virtual ~ListSchedulesRequest() = default;
};
class ListSchedulesResponseBodyDataSchedules : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<long> endTime{};
shared_ptr<string> executeTime{};
shared_ptr<string> groupId{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> repeatCycle{};
shared_ptr<long> repeatCycleUnit{};
shared_ptr<long> repeatTimes{};
shared_ptr<string> signName{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<string> updatedTime{};
ListSchedulesResponseBodyDataSchedules() {}
explicit ListSchedulesResponseBodyDataSchedules(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (endTime) {
res["EndTime"] = boost::any(*endTime);
}
if (executeTime) {
res["ExecuteTime"] = boost::any(*executeTime);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (repeatCycle) {
res["RepeatCycle"] = boost::any(*repeatCycle);
}
if (repeatCycleUnit) {
res["RepeatCycleUnit"] = boost::any(*repeatCycleUnit);
}
if (repeatTimes) {
res["RepeatTimes"] = boost::any(*repeatTimes);
}
if (signName) {
res["SignName"] = boost::any(*signName);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) {
endTime = make_shared<long>(boost::any_cast<long>(m["EndTime"]));
}
if (m.find("ExecuteTime") != m.end() && !m["ExecuteTime"].empty()) {
executeTime = make_shared<string>(boost::any_cast<string>(m["ExecuteTime"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("RepeatCycle") != m.end() && !m["RepeatCycle"].empty()) {
repeatCycle = make_shared<long>(boost::any_cast<long>(m["RepeatCycle"]));
}
if (m.find("RepeatCycleUnit") != m.end() && !m["RepeatCycleUnit"].empty()) {
repeatCycleUnit = make_shared<long>(boost::any_cast<long>(m["RepeatCycleUnit"]));
}
if (m.find("RepeatTimes") != m.end() && !m["RepeatTimes"].empty()) {
repeatTimes = make_shared<long>(boost::any_cast<long>(m["RepeatTimes"]));
}
if (m.find("SignName") != m.end() && !m["SignName"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["SignName"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~ListSchedulesResponseBodyDataSchedules() = default;
};
class ListSchedulesResponseBodyData : public Darabonba::Model {
public:
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<vector<ListSchedulesResponseBodyDataSchedules>> schedules{};
shared_ptr<long> totalCount{};
ListSchedulesResponseBodyData() {}
explicit ListSchedulesResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (schedules) {
vector<boost::any> temp1;
for(auto item1:*schedules){
temp1.push_back(boost::any(item1.toMap()));
}
res["Schedules"] = boost::any(temp1);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("Schedules") != m.end() && !m["Schedules"].empty()) {
if (typeid(vector<boost::any>) == m["Schedules"].type()) {
vector<ListSchedulesResponseBodyDataSchedules> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Schedules"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListSchedulesResponseBodyDataSchedules model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
schedules = make_shared<vector<ListSchedulesResponseBodyDataSchedules>>(expect1);
}
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListSchedulesResponseBodyData() = default;
};
class ListSchedulesResponseBody : public Darabonba::Model {
public:
shared_ptr<ListSchedulesResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListSchedulesResponseBody() {}
explicit ListSchedulesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListSchedulesResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListSchedulesResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListSchedulesResponseBody() = default;
};
class ListSchedulesResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListSchedulesResponseBody> body{};
ListSchedulesResponse() {}
explicit ListSchedulesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListSchedulesResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListSchedulesResponseBody>(model1);
}
}
}
virtual ~ListSchedulesResponse() = default;
};
class ListSignaturesRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> status{};
ListSignaturesRequest() {}
explicit ListSignaturesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (status) {
res["Status"] = boost::any(*status);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
}
virtual ~ListSignaturesRequest() = default;
};
class ListSignaturesResponseBodyDataSignatures : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
ListSignaturesResponseBodyDataSignatures() {}
explicit ListSignaturesResponseBodyDataSignatures(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~ListSignaturesResponseBodyDataSignatures() = default;
};
class ListSignaturesResponseBodyData : public Darabonba::Model {
public:
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<vector<ListSignaturesResponseBodyDataSignatures>> signatures{};
shared_ptr<long> totalCount{};
ListSignaturesResponseBodyData() {}
explicit ListSignaturesResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (signatures) {
vector<boost::any> temp1;
for(auto item1:*signatures){
temp1.push_back(boost::any(item1.toMap()));
}
res["Signatures"] = boost::any(temp1);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("Signatures") != m.end() && !m["Signatures"].empty()) {
if (typeid(vector<boost::any>) == m["Signatures"].type()) {
vector<ListSignaturesResponseBodyDataSignatures> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Signatures"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListSignaturesResponseBodyDataSignatures model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
signatures = make_shared<vector<ListSignaturesResponseBodyDataSignatures>>(expect1);
}
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListSignaturesResponseBodyData() = default;
};
class ListSignaturesResponseBody : public Darabonba::Model {
public:
shared_ptr<ListSignaturesResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListSignaturesResponseBody() {}
explicit ListSignaturesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListSignaturesResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListSignaturesResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListSignaturesResponseBody() = default;
};
class ListSignaturesResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListSignaturesResponseBody> body{};
ListSignaturesResponse() {}
explicit ListSignaturesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListSignaturesResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListSignaturesResponseBody>(model1);
}
}
}
virtual ~ListSignaturesResponse() = default;
};
class ListTemplatesRequest : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> status{};
shared_ptr<long> type{};
ListTemplatesRequest() {}
explicit ListTemplatesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (content) {
res["Content"] = boost::any(*content);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (type) {
res["Type"] = boost::any(*type);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Content") != m.end() && !m["Content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["Content"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("Type") != m.end() && !m["Type"].empty()) {
type = make_shared<long>(boost::any_cast<long>(m["Type"]));
}
}
virtual ~ListTemplatesRequest() = default;
};
class ListTemplatesResponseBodyDataTemplates : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> createdTime{};
shared_ptr<string> description{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> reason{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<long> type{};
shared_ptr<string> updatedTime{};
ListTemplatesResponseBodyDataTemplates() {}
explicit ListTemplatesResponseBodyDataTemplates(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (content) {
res["Content"] = boost::any(*content);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (description) {
res["Description"] = boost::any(*description);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (reason) {
res["Reason"] = boost::any(*reason);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (type) {
res["Type"] = boost::any(*type);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Content") != m.end() && !m["Content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["Content"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Reason") != m.end() && !m["Reason"].empty()) {
reason = make_shared<string>(boost::any_cast<string>(m["Reason"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("Type") != m.end() && !m["Type"].empty()) {
type = make_shared<long>(boost::any_cast<long>(m["Type"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~ListTemplatesResponseBodyDataTemplates() = default;
};
class ListTemplatesResponseBodyData : public Darabonba::Model {
public:
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<vector<ListTemplatesResponseBodyDataTemplates>> templates{};
shared_ptr<long> totalCount{};
ListTemplatesResponseBodyData() {}
explicit ListTemplatesResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (templates) {
vector<boost::any> temp1;
for(auto item1:*templates){
temp1.push_back(boost::any(item1.toMap()));
}
res["Templates"] = boost::any(temp1);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("Templates") != m.end() && !m["Templates"].empty()) {
if (typeid(vector<boost::any>) == m["Templates"].type()) {
vector<ListTemplatesResponseBodyDataTemplates> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Templates"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListTemplatesResponseBodyDataTemplates model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
templates = make_shared<vector<ListTemplatesResponseBodyDataTemplates>>(expect1);
}
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListTemplatesResponseBodyData() = default;
};
class ListTemplatesResponseBody : public Darabonba::Model {
public:
shared_ptr<ListTemplatesResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListTemplatesResponseBody() {}
explicit ListTemplatesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListTemplatesResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListTemplatesResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListTemplatesResponseBody() = default;
};
class ListTemplatesResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListTemplatesResponseBody> body{};
ListTemplatesResponse() {}
explicit ListTemplatesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListTemplatesResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListTemplatesResponseBody>(model1);
}
}
}
virtual ~ListTemplatesResponse() = default;
};
class ListTrainingJobsRequest : public Darabonba::Model {
public:
shared_ptr<string> campaignId{};
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
ListTrainingJobsRequest() {}
explicit ListTrainingJobsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
}
virtual ~ListTrainingJobsRequest() = default;
};
class ListTrainingJobsResponseBodyDataTrainingJobs : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
ListTrainingJobsResponseBodyDataTrainingJobs() {}
explicit ListTrainingJobsResponseBodyDataTrainingJobs(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~ListTrainingJobsResponseBodyDataTrainingJobs() = default;
};
class ListTrainingJobsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
shared_ptr<vector<ListTrainingJobsResponseBodyDataTrainingJobs>> trainingJobs{};
ListTrainingJobsResponseBodyData() {}
explicit ListTrainingJobsResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
if (trainingJobs) {
vector<boost::any> temp1;
for(auto item1:*trainingJobs){
temp1.push_back(boost::any(item1.toMap()));
}
res["TrainingJobs"] = boost::any(temp1);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) {
pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"]));
}
if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) {
pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"]));
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
if (m.find("TrainingJobs") != m.end() && !m["TrainingJobs"].empty()) {
if (typeid(vector<boost::any>) == m["TrainingJobs"].type()) {
vector<ListTrainingJobsResponseBodyDataTrainingJobs> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["TrainingJobs"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListTrainingJobsResponseBodyDataTrainingJobs model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
trainingJobs = make_shared<vector<ListTrainingJobsResponseBodyDataTrainingJobs>>(expect1);
}
}
}
virtual ~ListTrainingJobsResponseBodyData() = default;
};
class ListTrainingJobsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListTrainingJobsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListTrainingJobsResponseBody() {}
explicit ListTrainingJobsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListTrainingJobsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListTrainingJobsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListTrainingJobsResponseBody() = default;
};
class ListTrainingJobsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListTrainingJobsResponseBody> body{};
ListTrainingJobsResponse() {}
explicit ListTrainingJobsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListTrainingJobsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListTrainingJobsResponseBody>(model1);
}
}
}
virtual ~ListTrainingJobsResponse() = default;
};
class SendMessageRequest : public Darabonba::Model {
public:
shared_ptr<string> groupId{};
shared_ptr<vector<string>> outIds{};
shared_ptr<vector<string>> phoneNumbers{};
shared_ptr<string> scheduleId{};
shared_ptr<string> signName{};
shared_ptr<string> signatureId{};
shared_ptr<vector<string>> smsUpExtendCodes{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<vector<string>> templateParams{};
SendMessageRequest() {}
explicit SendMessageRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (outIds) {
res["OutIds"] = boost::any(*outIds);
}
if (phoneNumbers) {
res["PhoneNumbers"] = boost::any(*phoneNumbers);
}
if (scheduleId) {
res["ScheduleId"] = boost::any(*scheduleId);
}
if (signName) {
res["SignName"] = boost::any(*signName);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (smsUpExtendCodes) {
res["SmsUpExtendCodes"] = boost::any(*smsUpExtendCodes);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (templateParams) {
res["TemplateParams"] = boost::any(*templateParams);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("OutIds") != m.end() && !m["OutIds"].empty()) {
vector<string> toVec1;
if (typeid(vector<boost::any>) == m["OutIds"].type()) {
vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["OutIds"]);
for (auto item:vec1) {
toVec1.push_back(boost::any_cast<string>(item));
}
}
outIds = make_shared<vector<string>>(toVec1);
}
if (m.find("PhoneNumbers") != m.end() && !m["PhoneNumbers"].empty()) {
vector<string> toVec1;
if (typeid(vector<boost::any>) == m["PhoneNumbers"].type()) {
vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["PhoneNumbers"]);
for (auto item:vec1) {
toVec1.push_back(boost::any_cast<string>(item));
}
}
phoneNumbers = make_shared<vector<string>>(toVec1);
}
if (m.find("ScheduleId") != m.end() && !m["ScheduleId"].empty()) {
scheduleId = make_shared<string>(boost::any_cast<string>(m["ScheduleId"]));
}
if (m.find("SignName") != m.end() && !m["SignName"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["SignName"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("SmsUpExtendCodes") != m.end() && !m["SmsUpExtendCodes"].empty()) {
vector<string> toVec1;
if (typeid(vector<boost::any>) == m["SmsUpExtendCodes"].type()) {
vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["SmsUpExtendCodes"]);
for (auto item:vec1) {
toVec1.push_back(boost::any_cast<string>(item));
}
}
smsUpExtendCodes = make_shared<vector<string>>(toVec1);
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("TemplateParams") != m.end() && !m["TemplateParams"].empty()) {
vector<string> toVec1;
if (typeid(vector<boost::any>) == m["TemplateParams"].type()) {
vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["TemplateParams"]);
for (auto item:vec1) {
toVec1.push_back(boost::any_cast<string>(item));
}
}
templateParams = make_shared<vector<string>>(toVec1);
}
}
virtual ~SendMessageRequest() = default;
};
class SendMessageResponseBodyDataMessages : public Darabonba::Model {
public:
shared_ptr<string> id{};
shared_ptr<string> phoneNumber{};
SendMessageResponseBodyDataMessages() {}
explicit SendMessageResponseBodyDataMessages(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (id) {
res["Id"] = boost::any(*id);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<string>(boost::any_cast<string>(m["PhoneNumber"]));
}
}
virtual ~SendMessageResponseBodyDataMessages() = default;
};
class SendMessageResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<SendMessageResponseBodyDataMessages>> messages{};
shared_ptr<string> requestId{};
SendMessageResponseBodyData() {}
explicit SendMessageResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (messages) {
vector<boost::any> temp1;
for(auto item1:*messages){
temp1.push_back(boost::any(item1.toMap()));
}
res["Messages"] = boost::any(temp1);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Messages") != m.end() && !m["Messages"].empty()) {
if (typeid(vector<boost::any>) == m["Messages"].type()) {
vector<SendMessageResponseBodyDataMessages> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Messages"])){
if (typeid(map<string, boost::any>) == item1.type()) {
SendMessageResponseBodyDataMessages model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
messages = make_shared<vector<SendMessageResponseBodyDataMessages>>(expect1);
}
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~SendMessageResponseBodyData() = default;
};
class SendMessageResponseBody : public Darabonba::Model {
public:
shared_ptr<SendMessageResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
SendMessageResponseBody() {}
explicit SendMessageResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
SendMessageResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<SendMessageResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~SendMessageResponseBody() = default;
};
class SendMessageResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<SendMessageResponseBody> body{};
SendMessageResponse() {}
explicit SendMessageResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
SendMessageResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<SendMessageResponseBody>(model1);
}
}
}
virtual ~SendMessageResponse() = default;
};
class SmsReportRequestBody : public Darabonba::Model {
public:
shared_ptr<string> bizId{};
shared_ptr<string> errCode{};
shared_ptr<string> errMsg{};
shared_ptr<string> messageId{};
shared_ptr<string> outId{};
shared_ptr<string> phoneNumber{};
shared_ptr<string> reportTime{};
shared_ptr<string> requestId{};
shared_ptr<string> sendTime{};
shared_ptr<string> signName{};
shared_ptr<string> smsSize{};
shared_ptr<bool> success{};
shared_ptr<string> templateCode{};
SmsReportRequestBody() {}
explicit SmsReportRequestBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (bizId) {
res["biz_id"] = boost::any(*bizId);
}
if (errCode) {
res["err_code"] = boost::any(*errCode);
}
if (errMsg) {
res["err_msg"] = boost::any(*errMsg);
}
if (messageId) {
res["message_id"] = boost::any(*messageId);
}
if (outId) {
res["out_id"] = boost::any(*outId);
}
if (phoneNumber) {
res["phone_number"] = boost::any(*phoneNumber);
}
if (reportTime) {
res["report_time"] = boost::any(*reportTime);
}
if (requestId) {
res["request_id"] = boost::any(*requestId);
}
if (sendTime) {
res["send_time"] = boost::any(*sendTime);
}
if (signName) {
res["sign_name"] = boost::any(*signName);
}
if (smsSize) {
res["sms_size"] = boost::any(*smsSize);
}
if (success) {
res["success"] = boost::any(*success);
}
if (templateCode) {
res["template_code"] = boost::any(*templateCode);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("biz_id") != m.end() && !m["biz_id"].empty()) {
bizId = make_shared<string>(boost::any_cast<string>(m["biz_id"]));
}
if (m.find("err_code") != m.end() && !m["err_code"].empty()) {
errCode = make_shared<string>(boost::any_cast<string>(m["err_code"]));
}
if (m.find("err_msg") != m.end() && !m["err_msg"].empty()) {
errMsg = make_shared<string>(boost::any_cast<string>(m["err_msg"]));
}
if (m.find("message_id") != m.end() && !m["message_id"].empty()) {
messageId = make_shared<string>(boost::any_cast<string>(m["message_id"]));
}
if (m.find("out_id") != m.end() && !m["out_id"].empty()) {
outId = make_shared<string>(boost::any_cast<string>(m["out_id"]));
}
if (m.find("phone_number") != m.end() && !m["phone_number"].empty()) {
phoneNumber = make_shared<string>(boost::any_cast<string>(m["phone_number"]));
}
if (m.find("report_time") != m.end() && !m["report_time"].empty()) {
reportTime = make_shared<string>(boost::any_cast<string>(m["report_time"]));
}
if (m.find("request_id") != m.end() && !m["request_id"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["request_id"]));
}
if (m.find("send_time") != m.end() && !m["send_time"].empty()) {
sendTime = make_shared<string>(boost::any_cast<string>(m["send_time"]));
}
if (m.find("sign_name") != m.end() && !m["sign_name"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["sign_name"]));
}
if (m.find("sms_size") != m.end() && !m["sms_size"].empty()) {
smsSize = make_shared<string>(boost::any_cast<string>(m["sms_size"]));
}
if (m.find("success") != m.end() && !m["success"].empty()) {
success = make_shared<bool>(boost::any_cast<bool>(m["success"]));
}
if (m.find("template_code") != m.end() && !m["template_code"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["template_code"]));
}
}
virtual ~SmsReportRequestBody() = default;
};
class SmsReportRequest : public Darabonba::Model {
public:
shared_ptr<vector<SmsReportRequestBody>> body{};
SmsReportRequest() {}
explicit SmsReportRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (body) {
vector<boost::any> temp1;
for(auto item1:*body){
temp1.push_back(boost::any(item1.toMap()));
}
res["body"] = boost::any(temp1);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(vector<boost::any>) == m["body"].type()) {
vector<SmsReportRequestBody> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["body"])){
if (typeid(map<string, boost::any>) == item1.type()) {
SmsReportRequestBody model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
body = make_shared<vector<SmsReportRequestBody>>(expect1);
}
}
}
virtual ~SmsReportRequest() = default;
};
class SmsReportResponseBody : public Darabonba::Model {
public:
shared_ptr<long> code{};
shared_ptr<string> msg{};
SmsReportResponseBody() {}
explicit SmsReportResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (code) {
res["code"] = boost::any(*code);
}
if (msg) {
res["msg"] = boost::any(*msg);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("code") != m.end() && !m["code"].empty()) {
code = make_shared<long>(boost::any_cast<long>(m["code"]));
}
if (m.find("msg") != m.end() && !m["msg"].empty()) {
msg = make_shared<string>(boost::any_cast<string>(m["msg"]));
}
}
virtual ~SmsReportResponseBody() = default;
};
class SmsReportResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<SmsReportResponseBody> body{};
SmsReportResponse() {}
explicit SmsReportResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
SmsReportResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<SmsReportResponseBody>(model1);
}
}
}
virtual ~SmsReportResponse() = default;
};
class SmsUpRequestBody : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> destCode{};
shared_ptr<string> phoneNumber{};
shared_ptr<string> sendTime{};
shared_ptr<long> sequenceId{};
shared_ptr<string> signName{};
SmsUpRequestBody() {}
explicit SmsUpRequestBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (content) {
res["content"] = boost::any(*content);
}
if (destCode) {
res["dest_code"] = boost::any(*destCode);
}
if (phoneNumber) {
res["phone_number"] = boost::any(*phoneNumber);
}
if (sendTime) {
res["send_time"] = boost::any(*sendTime);
}
if (sequenceId) {
res["sequence_id"] = boost::any(*sequenceId);
}
if (signName) {
res["sign_name"] = boost::any(*signName);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("content") != m.end() && !m["content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["content"]));
}
if (m.find("dest_code") != m.end() && !m["dest_code"].empty()) {
destCode = make_shared<string>(boost::any_cast<string>(m["dest_code"]));
}
if (m.find("phone_number") != m.end() && !m["phone_number"].empty()) {
phoneNumber = make_shared<string>(boost::any_cast<string>(m["phone_number"]));
}
if (m.find("send_time") != m.end() && !m["send_time"].empty()) {
sendTime = make_shared<string>(boost::any_cast<string>(m["send_time"]));
}
if (m.find("sequence_id") != m.end() && !m["sequence_id"].empty()) {
sequenceId = make_shared<long>(boost::any_cast<long>(m["sequence_id"]));
}
if (m.find("sign_name") != m.end() && !m["sign_name"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["sign_name"]));
}
}
virtual ~SmsUpRequestBody() = default;
};
class SmsUpRequest : public Darabonba::Model {
public:
shared_ptr<vector<SmsUpRequestBody>> body{};
SmsUpRequest() {}
explicit SmsUpRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (body) {
vector<boost::any> temp1;
for(auto item1:*body){
temp1.push_back(boost::any(item1.toMap()));
}
res["body"] = boost::any(temp1);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(vector<boost::any>) == m["body"].type()) {
vector<SmsUpRequestBody> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["body"])){
if (typeid(map<string, boost::any>) == item1.type()) {
SmsUpRequestBody model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
body = make_shared<vector<SmsUpRequestBody>>(expect1);
}
}
}
virtual ~SmsUpRequest() = default;
};
class SmsUpResponseBody : public Darabonba::Model {
public:
shared_ptr<long> code{};
shared_ptr<string> msg{};
SmsUpResponseBody() {}
explicit SmsUpResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (code) {
res["code"] = boost::any(*code);
}
if (msg) {
res["msg"] = boost::any(*msg);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("code") != m.end() && !m["code"].empty()) {
code = make_shared<long>(boost::any_cast<long>(m["code"]));
}
if (m.find("msg") != m.end() && !m["msg"].empty()) {
msg = make_shared<string>(boost::any_cast<string>(m["msg"]));
}
}
virtual ~SmsUpResponseBody() = default;
};
class SmsUpResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<SmsUpResponseBody> body{};
SmsUpResponse() {}
explicit SmsUpResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
SmsUpResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<SmsUpResponseBody>(model1);
}
}
}
virtual ~SmsUpResponse() = default;
};
class UpdateCampaignRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<string> remark{};
UpdateCampaignRequest() {}
explicit UpdateCampaignRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
}
virtual ~UpdateCampaignRequest() = default;
};
class UpdateCampaignResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> updatedTime{};
UpdateCampaignResponseBodyData() {}
explicit UpdateCampaignResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~UpdateCampaignResponseBodyData() = default;
};
class UpdateCampaignResponseBody : public Darabonba::Model {
public:
shared_ptr<UpdateCampaignResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
UpdateCampaignResponseBody() {}
explicit UpdateCampaignResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
UpdateCampaignResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<UpdateCampaignResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~UpdateCampaignResponseBody() = default;
};
class UpdateCampaignResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<UpdateCampaignResponseBody> body{};
UpdateCampaignResponse() {}
explicit UpdateCampaignResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
UpdateCampaignResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<UpdateCampaignResponseBody>(model1);
}
}
}
virtual ~UpdateCampaignResponse() = default;
};
class UpdateReportUrlRequest : public Darabonba::Model {
public:
shared_ptr<string> url{};
UpdateReportUrlRequest() {}
explicit UpdateReportUrlRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (url) {
res["Url"] = boost::any(*url);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Url") != m.end() && !m["Url"].empty()) {
url = make_shared<string>(boost::any_cast<string>(m["Url"]));
}
}
virtual ~UpdateReportUrlRequest() = default;
};
class UpdateReportUrlResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
UpdateReportUrlResponseBody() {}
explicit UpdateReportUrlResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~UpdateReportUrlResponseBody() = default;
};
class UpdateReportUrlResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<UpdateReportUrlResponseBody> body{};
UpdateReportUrlResponse() {}
explicit UpdateReportUrlResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
UpdateReportUrlResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<UpdateReportUrlResponseBody>(model1);
}
}
}
virtual ~UpdateReportUrlResponse() = default;
};
class UpdateUploadUrlRequest : public Darabonba::Model {
public:
shared_ptr<string> url{};
UpdateUploadUrlRequest() {}
explicit UpdateUploadUrlRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (url) {
res["Url"] = boost::any(*url);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Url") != m.end() && !m["Url"].empty()) {
url = make_shared<string>(boost::any_cast<string>(m["Url"]));
}
}
virtual ~UpdateUploadUrlRequest() = default;
};
class UpdateUploadUrlResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
UpdateUploadUrlResponseBody() {}
explicit UpdateUploadUrlResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~UpdateUploadUrlResponseBody() = default;
};
class UpdateUploadUrlResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<UpdateUploadUrlResponseBody> body{};
UpdateUploadUrlResponse() {}
explicit UpdateUploadUrlResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
UpdateUploadUrlResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<UpdateUploadUrlResponseBody>(model1);
}
}
}
virtual ~UpdateUploadUrlResponse() = default;
};
class Client : Alibabacloud_OpenApi::Client {
public:
explicit Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config);
string getEndpoint(shared_ptr<string> productId,
shared_ptr<string> regionId,
shared_ptr<string> endpointRule,
shared_ptr<string> network,
shared_ptr<string> suffix,
shared_ptr<map<string, string>> endpointMap,
shared_ptr<string> endpoint);
CreateCampaignResponse createCampaign(shared_ptr<CreateCampaignRequest> request);
CreateCampaignResponse createCampaignWithOptions(shared_ptr<CreateCampaignRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateGroupResponse createGroup(shared_ptr<CreateGroupRequest> request);
CreateGroupResponse createGroupWithOptions(shared_ptr<CreateGroupRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateInferenceJobResponse createInferenceJob(shared_ptr<CreateInferenceJobRequest> request);
CreateInferenceJobResponse createInferenceJobWithOptions(shared_ptr<CreateInferenceJobRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateScheduleResponse createSchedule(shared_ptr<CreateScheduleRequest> request);
CreateScheduleResponse createScheduleWithOptions(shared_ptr<CreateScheduleRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateSignatureResponse createSignature(shared_ptr<CreateSignatureRequest> request);
CreateSignatureResponse createSignatureWithOptions(shared_ptr<CreateSignatureRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateTemplateResponse createTemplate(shared_ptr<CreateTemplateRequest> request);
CreateTemplateResponse createTemplateWithOptions(shared_ptr<CreateTemplateRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateTrainingJobResponse createTrainingJob(shared_ptr<CreateTrainingJobRequest> request);
CreateTrainingJobResponse createTrainingJobWithOptions(shared_ptr<CreateTrainingJobRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteCampaignResponse deleteCampaign(shared_ptr<string> Id);
DeleteCampaignResponse deleteCampaignWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteGroupResponse deleteGroup(shared_ptr<string> Id);
DeleteGroupResponse deleteGroupWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteInferenceJobResponse deleteInferenceJob(shared_ptr<string> Id);
DeleteInferenceJobResponse deleteInferenceJobWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteScheduleResponse deleteSchedule(shared_ptr<string> Id);
DeleteScheduleResponse deleteScheduleWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteSignatureResponse deleteSignature(shared_ptr<string> Id);
DeleteSignatureResponse deleteSignatureWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteTemplateResponse deleteTemplate(shared_ptr<string> Id);
DeleteTemplateResponse deleteTemplateWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteTrainingJobResponse deleteTrainingJob(shared_ptr<string> Id);
DeleteTrainingJobResponse deleteTrainingJobWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetAlgorithmResponse getAlgorithm(shared_ptr<string> Id);
GetAlgorithmResponse getAlgorithmWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetCampaignResponse getCampaign(shared_ptr<string> Id);
GetCampaignResponse getCampaignWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetGroupResponse getGroup(shared_ptr<string> Id);
GetGroupResponse getGroupWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetInferenceJobResponse getInferenceJob(shared_ptr<string> Id);
GetInferenceJobResponse getInferenceJobWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetMessageConfigResponse getMessageConfig();
GetMessageConfigResponse getMessageConfigWithOptions(shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetScheduleResponse getSchedule(shared_ptr<string> Id);
GetScheduleResponse getScheduleWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetSignatureResponse getSignature(shared_ptr<string> Id);
GetSignatureResponse getSignatureWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetTemplateResponse getTemplate(shared_ptr<string> Id);
GetTemplateResponse getTemplateWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetTrainingJobResponse getTrainingJob(shared_ptr<string> Id);
GetTrainingJobResponse getTrainingJobWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetUserResponse getUser();
GetUserResponse getUserWithOptions(shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListAlgorithmsResponse listAlgorithms(shared_ptr<ListAlgorithmsRequest> request);
ListAlgorithmsResponse listAlgorithmsWithOptions(shared_ptr<ListAlgorithmsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListCampaignsResponse listCampaigns(shared_ptr<ListCampaignsRequest> request);
ListCampaignsResponse listCampaignsWithOptions(shared_ptr<ListCampaignsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListGroupsResponse listGroups(shared_ptr<ListGroupsRequest> request);
ListGroupsResponse listGroupsWithOptions(shared_ptr<ListGroupsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListInferenceJobsResponse listInferenceJobs(shared_ptr<ListInferenceJobsRequest> request);
ListInferenceJobsResponse listInferenceJobsWithOptions(shared_ptr<ListInferenceJobsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListMessageMetricsResponse listMessageMetrics(shared_ptr<ListMessageMetricsRequest> request);
ListMessageMetricsResponse listMessageMetricsWithOptions(shared_ptr<ListMessageMetricsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListMessagesResponse listMessages(shared_ptr<ListMessagesRequest> request);
ListMessagesResponse listMessagesWithOptions(shared_ptr<ListMessagesRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListSchedulesResponse listSchedules(shared_ptr<ListSchedulesRequest> request);
ListSchedulesResponse listSchedulesWithOptions(shared_ptr<ListSchedulesRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListSignaturesResponse listSignatures(shared_ptr<ListSignaturesRequest> request);
ListSignaturesResponse listSignaturesWithOptions(shared_ptr<ListSignaturesRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListTemplatesResponse listTemplates(shared_ptr<ListTemplatesRequest> request);
ListTemplatesResponse listTemplatesWithOptions(shared_ptr<ListTemplatesRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListTrainingJobsResponse listTrainingJobs(shared_ptr<ListTrainingJobsRequest> request);
ListTrainingJobsResponse listTrainingJobsWithOptions(shared_ptr<ListTrainingJobsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
SendMessageResponse sendMessage(shared_ptr<SendMessageRequest> request);
SendMessageResponse sendMessageWithOptions(shared_ptr<SendMessageRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
SmsReportResponse smsReport(shared_ptr<SmsReportRequest> request);
SmsReportResponse smsReportWithOptions(shared_ptr<SmsReportRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
SmsUpResponse smsUp(shared_ptr<SmsUpRequest> request);
SmsUpResponse smsUpWithOptions(shared_ptr<SmsUpRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
UpdateCampaignResponse updateCampaign(shared_ptr<string> Id, shared_ptr<UpdateCampaignRequest> request);
UpdateCampaignResponse updateCampaignWithOptions(shared_ptr<string> Id,
shared_ptr<UpdateCampaignRequest> request,
shared_ptr<map<string, string>> headers,
shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
UpdateReportUrlResponse updateReportUrl(shared_ptr<UpdateReportUrlRequest> request);
UpdateReportUrlResponse updateReportUrlWithOptions(shared_ptr<UpdateReportUrlRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
UpdateUploadUrlResponse updateUploadUrl(shared_ptr<UpdateUploadUrlRequest> request);
UpdateUploadUrlResponse updateUploadUrlWithOptions(shared_ptr<UpdateUploadUrlRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
virtual ~Client() = default;
};
} // namespace Alibabacloud_PaiPlugin20220112
#endif
| 33.454175
| 199
| 0.615746
|
alibabacloud-sdk-cpp
|
f916613855148acf4ddb6053fd02d8472bba92ea
| 1,924
|
cpp
|
C++
|
kdl/schema/resource_type/resource_field.cpp
|
EvocationGames/libKDL
|
90eb2ce71a1545f6e33164230f0e5d6ece0acaa7
|
[
"MIT"
] | null | null | null |
kdl/schema/resource_type/resource_field.cpp
|
EvocationGames/libKDL
|
90eb2ce71a1545f6e33164230f0e5d6ece0acaa7
|
[
"MIT"
] | null | null | null |
kdl/schema/resource_type/resource_field.cpp
|
EvocationGames/libKDL
|
90eb2ce71a1545f6e33164230f0e5d6ece0acaa7
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2021 Tom Hancocks
//
// 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 <kdl/schema/resource_type/resource_field.hpp>
#include <kdl/schema/resource_type/resource_field_value.hpp>
// MARK: - Constructor
kdl::lib::resource_field::resource_field(const std::string& name)
: m_name(name)
{
}
kdl::lib::resource_field::resource_field(const std::shared_ptr<struct resource_field_value>& field)
: m_name(field->name()), m_values({ field })
{
}
// MARK: - Accessor
auto kdl::lib::resource_field::name() const -> std::string
{
return m_name;
}
// MARK: - Field Value Management
auto kdl::lib::resource_field::add_value(const std::shared_ptr<struct resource_field_value> &value) -> void
{
m_values.emplace_back(value);
}
auto kdl::lib::resource_field::values() const -> const std::vector<std::shared_ptr<struct resource_field_value>> &
{
return m_values;
}
| 34.357143
| 114
| 0.748441
|
EvocationGames
|
f922029c60842453b1aff0f88adab5004227c320
| 2,135
|
cpp
|
C++
|
plugins/notifications/notifier.cpp
|
boomt1337/nitroshare-desktop
|
3ab9eb4075f78cbf2ee0fb82cea66814406a2248
|
[
"MIT"
] | 1,460
|
2015-01-31T14:09:18.000Z
|
2022-03-24T09:43:19.000Z
|
plugins/notifications/notifier.cpp
|
boomt1337/nitroshare-desktop
|
3ab9eb4075f78cbf2ee0fb82cea66814406a2248
|
[
"MIT"
] | 254
|
2015-01-29T19:58:28.000Z
|
2022-03-30T01:00:38.000Z
|
plugins/notifications/notifier.cpp
|
boomt1337/nitroshare-desktop
|
3ab9eb4075f78cbf2ee0fb82cea66814406a2248
|
[
"MIT"
] | 245
|
2015-02-18T16:40:52.000Z
|
2022-03-29T18:38:45.000Z
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Nathan Osman
*
* 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 <nitroshare/action.h>
#include <nitroshare/actionregistry.h>
#include <nitroshare/application.h>
#include <nitroshare/logger.h>
#include <nitroshare/message.h>
#include "notifier.h"
const QString MessageTag = "mdns";
const QString ShowTrayNotificationAction = "showtraynotification";
Notifier::Notifier(Application *application)
: mApplication(application)
{
}
void Notifier::showNotification(const QString &actionName, const QString &title, const QString &message)
{
// Find the action for showing the tray notification
Action *action = mApplication->actionRegistry()->find(actionName);
if (!action) {
mApplication->logger()->log(new Message(
Message::Warning,
MessageTag,
QString("\"%1\" action was not found").arg(actionName)
));
return;
}
// Invoke the action to show the notification
action->invoke(QVariantMap{
{ "title", title },
{ "message", message }
});
}
| 35
| 104
| 0.717564
|
boomt1337
|
f9240d7d91ab4d35253d601837acf6a1707a1799
| 500
|
cpp
|
C++
|
lib/stringManipulation/src/string_manipulation.cpp
|
Xav83/AdventOfCode
|
7e305b89abe0a497efdab0f1a3bfe2bfc24b36d5
|
[
"MIT"
] | 2
|
2019-11-14T18:11:02.000Z
|
2020-01-20T22:40:31.000Z
|
lib/stringManipulation/src/string_manipulation.cpp
|
Xav83/AdventOfCode
|
7e305b89abe0a497efdab0f1a3bfe2bfc24b36d5
|
[
"MIT"
] | null | null | null |
lib/stringManipulation/src/string_manipulation.cpp
|
Xav83/AdventOfCode
|
7e305b89abe0a497efdab0f1a3bfe2bfc24b36d5
|
[
"MIT"
] | null | null | null |
#include <functional>
#include <sstream>
void foreachElementsInStringDelimitedBy(
const std::string &input, const char delimiter,
std::function<void(const std::string &)> callback) {
std::stringstream ss(input);
std::string token;
while (std::getline(ss, token, delimiter)) {
callback(token);
}
}
void foreachLineIn(const std::string &input,
std::function<void(const std::string &)> callback) {
foreachElementsInStringDelimitedBy(input, '\n', callback);
}
| 26.315789
| 71
| 0.688
|
Xav83
|
f924414c965b39dcf3af5eabf4ac9a247dbad819
| 31,268
|
cpp
|
C++
|
unittests/test.cpp
|
attcs/TreeNode
|
1728cc3a1c605e17c328a27c12de5aa685f80fc1
|
[
"MIT"
] | null | null | null |
unittests/test.cpp
|
attcs/TreeNode
|
1728cc3a1c605e17c328a27c12de5aa685f80fc1
|
[
"MIT"
] | null | null | null |
unittests/test.cpp
|
attcs/TreeNode
|
1728cc3a1c605e17c328a27c12de5aa685f80fc1
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include <memory>
#include "../treenode.h"
#include <vector>
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
#include <execution>
#endif
struct DbEntity
{
int val = 0;
};
bool operator==(DbEntity const& l, DbEntity const& r)
{
return l.val == r.val;
}
namespace TreeNodeTests
{
using namespace std;
TEST(TreeNode, add_child_parent_eq)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(&root, node->parent());
}
TEST(TreeNode, get_1)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(1, node->get().val);
}
TEST(TreeNode, add_child_1child_PrevIsNull)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(nullptr, node->prev());
}
TEST(TreeNode, add_child_1child_NextIsNull)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(nullptr, node->next());
}
TEST(TreeNode, add_child_1child_next_bfsIsNullAndNode)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(nullptr, node->next_bfs());
EXPECT_EQ(node, root.next_bfs());
}
TEST(TreeNode, add_child_2child_PrevNextParent)
{
TreeNode<DbEntity> root;
auto const node1 = root.add_child(DbEntity{ 1 });
auto const node2 = root.add_child(DbEntity{ 2 });
EXPECT_EQ(1, node1->get().val);
EXPECT_EQ(2, node2->get().val);
EXPECT_EQ(&root, node1->parent());
EXPECT_EQ(&root, node2->parent());
EXPECT_EQ(nullptr, node1->prev());
EXPECT_EQ(node2, node1->next());
EXPECT_EQ(nullptr, node2->next());
}
TEST(TreeNode, add_child_2child_parentIsRoot)
{
TreeNode<DbEntity> root;
auto const node1 = root.add_child(DbEntity{ 1 });
auto const node2 = root.add_child(DbEntity{ 2 });
EXPECT_EQ(&root, node1->parent());
EXPECT_EQ(&root, node2->parent());
}
TEST(TreeNode, add_child_2child_valsAreOk)
{
TreeNode<DbEntity> root;
auto const node1 = root.add_child(DbEntity{ 1 });
auto const node2 = root.add_child(DbEntity{ 2 });
EXPECT_EQ(1, node1->get().val);
EXPECT_EQ(2, node2->get().val);
}
TEST(TreeNode, add_child_2child_prevAndnextAreOk)
{
TreeNode<DbEntity> root;
auto const node1 = root.add_child(DbEntity{ 1 });
auto const node2 = root.add_child(DbEntity{ 2 });
EXPECT_EQ(nullptr, node1->prev());
EXPECT_EQ(node2, node1->next());
EXPECT_EQ(nullptr, node2->next());
}
TEST(TreeNode, add_child_2child_next_bfsIsOk)
{
TreeNode<DbEntity> root;
auto const node1 = root.add_child(DbEntity{ 1 });
auto const node2 = root.add_child(DbEntity{ 2 });
EXPECT_EQ(node1, root.next_bfs());
EXPECT_EQ(node2, node1->next_bfs());
EXPECT_EQ(nullptr, node2->next_bfs());
}
TEST(TreeNode, add_child_2child1grandchild1_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(grandchild11, child2->next_bfs());
EXPECT_EQ(nullptr, grandchild11->next_bfs());
}
TEST(TreeNode, add_child_2child1grandchild2_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild21 = child2->add_child(DbEntity{ 21 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(grandchild21, child2->next_bfs());
EXPECT_EQ(nullptr, grandchild21->next_bfs());
}
TEST(TreeNode, add_child_2child2grandchildInOrder_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
auto grandchild21 = child2->add_child(DbEntity{ 21 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(grandchild11, child2->next_bfs());
EXPECT_EQ(grandchild21, grandchild11->next_bfs());
EXPECT_EQ(nullptr, grandchild21->next_bfs());
}
TEST(TreeNode, add_child_2child2grandchildInReverseOrder_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild21 = child2->add_child(DbEntity{ 21 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(grandchild11, child2->next_bfs());
EXPECT_EQ(grandchild21, grandchild11->next_bfs());
EXPECT_EQ(nullptr, grandchild21->next_bfs());
}
TEST(TreeNode, add_child_3child2grandchildInOrder_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto child3 = root.add_child(DbEntity{ 3 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
auto grandchild31 = child3->add_child(DbEntity{ 31 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(child3, child2->next_bfs());
EXPECT_EQ(grandchild11, child3->next_bfs());
EXPECT_EQ(grandchild31, grandchild11->next_bfs());
EXPECT_EQ(nullptr, grandchild31->next_bfs());
EXPECT_EQ(6, root.size());
EXPECT_EQ(2, child3->size());
}
TEST(TreeNode, add_child_3child2grandchild3Atlast_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
auto child3 = root.add_child(DbEntity{ 3 });
auto grandchild31 = child3->add_child(DbEntity{ 31 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(child3, child2->next_bfs());
EXPECT_EQ(grandchild11, child3->next_bfs());
EXPECT_EQ(grandchild31, grandchild11->next_bfs());
EXPECT_EQ(nullptr, grandchild31->next_bfs());
}
TEST(TreeNode, add_child_3child3grandchild_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto child3 = root.add_child(DbEntity{ 3 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
auto grandchild12 = child1->add_child(DbEntity{ 12 });
auto grandchild31 = child3->add_child(DbEntity{ 31 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(child3, child2->next_bfs());
EXPECT_EQ(grandchild11, child3->next_bfs());
EXPECT_EQ(grandchild12, grandchild11->next_bfs());
EXPECT_EQ(grandchild31, grandchild12->next_bfs());
EXPECT_EQ(nullptr, grandchild31->next_bfs());
EXPECT_EQ(7, root.size());
EXPECT_EQ(3, child1->size());
}
TEST(TreeNode, add_child_3child3grandchild3Atlast_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
auto grandchild12 = child1->add_child(DbEntity{ 12 });
auto child3 = root.add_child(DbEntity{ 3 });
auto grandchild31 = child3->add_child(DbEntity{ 31 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(child3, child2->next_bfs());
EXPECT_EQ(grandchild11, child3->next_bfs());
EXPECT_EQ(grandchild12, grandchild11->next_bfs());
EXPECT_EQ(grandchild31, grandchild12->next_bfs());
EXPECT_EQ(nullptr, grandchild31->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_111_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c31 = c3->add_child(DbEntity{ 31 });
auto c111 = c11->add_child(DbEntity{ 111 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c31, c12->next_bfs());
EXPECT_EQ(c111, c31->next_bfs());
EXPECT_EQ(nullptr, c111->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_111_r_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c111 = c11->add_child(DbEntity{ 111 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c31 = c3->add_child(DbEntity{ 31 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c31, c12->next_bfs());
EXPECT_EQ(c111, c31->next_bfs());
EXPECT_EQ(nullptr, c111->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_121_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c31 = c3->add_child(DbEntity{ 31 });
auto c121 = c12->add_child(DbEntity{ 121 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c31, c12->next_bfs());
EXPECT_EQ(c121, c31->next_bfs());
EXPECT_EQ(nullptr, c121->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_121_r_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c121 = c12->add_child(DbEntity{ 121 });
auto c31 = c3->add_child(DbEntity{ 31 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c31, c12->next_bfs());
EXPECT_EQ(c121, c31->next_bfs());
EXPECT_EQ(nullptr, c121->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_131_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c31 = c3->add_child(DbEntity{ 31 });
auto c131 = c31->add_child(DbEntity{ 131 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c31, c12->next_bfs());
EXPECT_EQ(c131, c31->next_bfs());
EXPECT_EQ(nullptr, c131->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_211_131_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c21 = c2->add_child(DbEntity{ 21 });
auto c211 = c21->add_child(DbEntity{ 211 });
auto c212 = c21->add_child(DbEntity{ 212 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c31 = c3->add_child(DbEntity{ 31 });
auto c131 = c31->add_child(DbEntity{ 131 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c21, c12->next_bfs());
EXPECT_EQ(c31, c21->next_bfs());
EXPECT_EQ(c211, c31->next_bfs());
EXPECT_EQ(c212, c211->next_bfs());
EXPECT_EQ(c131, c212->next_bfs());
EXPECT_EQ(nullptr, c131->next_bfs());
EXPECT_EQ(11, root.size());
EXPECT_EQ(3, c3->size());
EXPECT_EQ(1, c3->size_segment());
}
TEST(TreeNode, child_begin_in_depth__empty__0__root)
{
TreeNode<int> root(0);
auto node = root.child_begin_in_depth(0);
EXPECT_EQ(&root, node);
}
TEST(TreeNode, child_begin_in_depth__2level__0__root)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_begin_in_depth(0);
EXPECT_EQ(&root, node);
}
TEST(TreeNode, child_begin_in_depth__2level__1__c1)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_begin_in_depth(1);
EXPECT_EQ(c1, node);
}
TEST(TreeNode, child_begin_in_depth__2level__2__c11)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_begin_in_depth(2);
EXPECT_EQ(c11, node);
}
TEST(TreeNode, child_begin_in_depth__2level__2__c21)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto node = root.child_begin_in_depth(2);
EXPECT_EQ(c21, node);
}
TEST(TreeNode, child_begin_in_depth__3level__3__c211)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto c211 = c21->add_child(211);
auto node = root.child_begin_in_depth(3);
EXPECT_EQ(c211, node);
}
TEST(TreeNode, child_begin_in_depth__3level__4__null)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto c211 = c21->add_child(211);
auto node = root.child_begin_in_depth(4);
EXPECT_EQ(nullptr, node);
}
TEST(TreeNode, child_end_in_depth__empty__0__null)
{
TreeNode<int> root(0);
auto node = root.child_end_in_depth(0);
EXPECT_EQ(nullptr, node);
}
TEST(TreeNode, child_end_in_depth__2level__0__c1)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_end_in_depth(0);
EXPECT_EQ(c1, node);
}
TEST(TreeNode, child_end_in_depth__2level__1__c11)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_end_in_depth(1);
EXPECT_EQ(c11, node);
}
TEST(TreeNode, child_end_in_depth__2level11__2__null)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_end_in_depth(2);
EXPECT_EQ(nullptr, node);
}
TEST(TreeNode, child_end_in_depth__2level21__2__null)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto node = root.child_end_in_depth(2);
EXPECT_EQ(nullptr, node);
}
TEST(TreeNode, child_end_in_depth__3level__2__c211)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto c211 = c21->add_child(211);
auto node = root.child_end_in_depth(2);
EXPECT_EQ(c211, node);
}
TEST(TreeNode, child_end_in_depth__3level__4__null)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto c211 = c21->add_child(211);
auto node = root.child_end_in_depth(4);
EXPECT_EQ(nullptr, node);
}
TEST(TreeNode, clear_root_DoesNothing)
{
TreeNode<int> root(0);
root.clear();
EXPECT_EQ(0, root.get());
EXPECT_EQ(nullptr, root.child_first());
EXPECT_EQ(nullptr, root.next());
}
TEST(TreeNode, clear_root_ChildsAreNull)
{
TreeNode<int> root(0);
root.add_child(1)->add_child(11);
root.add_child(2);
root.add_child(3);
root.clear();
EXPECT_EQ(nullptr, root.child_first());
EXPECT_EQ(nullptr, root.child_last());
EXPECT_EQ(1, root.size());
}
TEST(TreeNode, clear_c21_complex)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
c1->add_child(11)
->add_child(111)
->parent()
->add_child(112)
->parent()
->add_child(113)
->add_child(1131)
->add_child(11311);
auto c21 = root.add_child(2)
->add_child(21);
c21->add_child(211)
->add_child(2111);
c21->add_child(212)
->add_child(2121);
c21->add_child(213)
->add_child(2131);
root.add_child(3);
vector<int> vals_before;
copy(root.begin(), root.end(), back_inserter(vals_before));
vector<int> const expected_before = { 0, 1, 2, 3, 11, 21, 111, 112, 113, 211, 212, 213, 1131, 2111, 2121, 2131, 11311 };
EXPECT_EQ(expected_before, vals_before);
c21->clear();
vector<int> vals_after;
copy(root.begin(), root.end(), back_inserter(vals_after));
vector<int> const expected_after = { 0, 1, 2, 3, 11, 21, 111, 112, 113, 1131, 11311 };
EXPECT_EQ(expected_after, vals_after);
EXPECT_EQ(11, root.size());
EXPECT_EQ(7, c1->size());
}
TEST(TreeNode, remove_c21_1level)
{
TreeNode<int> root(0);
root.add_child(1);
auto c2 = root.add_child(2);
root.add_child(3);
c2->remove();
vector<int> vals;
copy(root.begin(), root.end(), back_inserter(vals));
vector<int> expected = { 0, 1, 3 };
EXPECT_EQ(expected, vals);
EXPECT_EQ(3, root.size());
}
TEST(TreeNode, remove_c21_complex)
{
TreeNode<int> root(0);
root.add_child(1)
->add_child(11)
->add_child(111)
->parent()
->add_child(112)
->parent()
->add_child(113)
->add_child(1131)
->add_child(11311);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
c21->add_child(211)
->add_child(2111);
c21->add_child(212)
->add_child(2121);
c21->add_child(213)
->add_child(2131);
root.add_child(3);
vector<int> vals_before;
copy(root.begin(), root.end(), back_inserter(vals_before));
vector<int> const expected_before = { 0, 1, 2, 3, 11, 21, 111, 112, 113, 211, 212, 213, 1131, 2111, 2121, 2131, 11311 };
EXPECT_EQ(expected_before, vals_before);
c21->remove();
vector<int> vals_after;
copy(root.begin(), root.end(), back_inserter(vals_after));
vector<int> const expected_after = { 0, 1, 2, 3, 11, 111, 112, 113, 1131, 11311 };
EXPECT_EQ(expected_after, vals_after);
EXPECT_EQ(10, root.size());
EXPECT_EQ(1, c2->size());
}
TEST(TreeNode, begin_segment_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_segment();
}
TEST(TreeNode, end_segment_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_segment();
}
TEST(TreeNode, begin_segment_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_segment<TreeNode<int> const*>();
}
TEST(TreeNode, end_segment_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_segment<TreeNode<int> const*>();
}
TEST(TreeNode, begin_dfs_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_dfs();
}
TEST(TreeNode, end_dfs_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_dfs();
}
TEST(TreeNode, begin_dfs_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_dfs<TreeNode<int> const*>();
}
TEST(TreeNode, end_dfs_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_dfs<TreeNode<int> const*>();
}
TEST(TreeNode, begin_bfs_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_bfs();
}
TEST(TreeNode, end_bfs_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_bfs();
}
TEST(TreeNode, begin_bfs_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_bfs<TreeNode<int> const*>();
}
TEST(TreeNode, end_bfs_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_bfs<TreeNode<int> const*>();
}
TEST(TreeNode, begin_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin();
}
TEST(TreeNode, end_const_ShouldCompile)
{
TreeNode<int> const root;
root.end();
}
TEST(TreeNode, copyctor)
{
TreeNode<int> root(0);
auto c11o = root.add_child(1)->add_child(11);
root.add_child(2);
root.add_child(3);
auto root_copied(root);
EXPECT_EQ(0, root_copied.get());
auto c1 = root_copied.next_bfs();
EXPECT_EQ(1, c1->get());
auto c2 = c1->next_bfs();
EXPECT_EQ(2, c2->get());
auto c3 = c2->next_bfs();
EXPECT_EQ(3, c3->get());
auto c11 = c3->next_bfs();
EXPECT_EQ(11, c11->get());
EXPECT_EQ(c11, c1->child_first());
EXPECT_NE(c11, c11o);
}
TEST(TreeNode, initializerlist)
{
TreeNode<int> root = { 0, 1, 2, 3};
EXPECT_EQ(0, root.get());
auto c1 = root.next_bfs();
EXPECT_EQ(1, c1->get());
auto c2 = c1->next_bfs();
EXPECT_EQ(2, c2->get());
auto c3 = c2->next_bfs();
EXPECT_EQ(3, c3->get());
}
TEST(TreeNode, foreach)
{
TreeNode<int> root = { 0, 1, 2, 3 };
auto c11 = root.child_first()->add_child(4);
c11->add_child(5);
int i = 0;
for (auto v : root)
EXPECT_EQ(i++, v);
}
}
namespace IteratorSegmentTests
{
using namespace std;
TEST(IteratorSegment, begin_segment_RootEmptySg_Null)
{
TreeNode<DbEntity> root;
EXPECT_EQ(IteratorSegment<DbEntity>(nullptr), root.begin_segment());
}
TEST(IteratorSegment, end_segment_RootEmptySg_Null)
{
TreeNode<DbEntity> root;
EXPECT_EQ(IteratorSegment<DbEntity>(nullptr), root.end_segment());
}
TEST(IteratorSegment, begin_segment_1Child_Is1)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(node->get().val, (*root.begin_segment()).val);
}
TEST(IteratorSegment, end_segment_1Child_IsNull)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(IteratorSegment<DbEntity>(nullptr), root.end_segment());
}
TEST(IteratorSegment, pointer_operator_T)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(node->get().val, root.begin_segment()->val);
}
TEST(IteratorSegment, usability_copy_value123)
{
TreeNode<DbEntity> root;
root.add_child(DbEntity{ 1 });
root.add_child(DbEntity{ 2 });
root.add_child(DbEntity{ 3 });
vector<DbEntity> vals;
copy(root.begin_segment(), root.end_segment(), back_inserter(vals));
auto const expected = vector<DbEntity>{ DbEntity{1}, DbEntity{2}, DbEntity{3} };
EXPECT_EQ(expected, vals);
}
TEST(IteratorSegment, usability_copy_node123)
{
TreeNode<DbEntity> root;
auto node1 = root.add_child(DbEntity{ 1 });
auto node2 = root.add_child(DbEntity{ 2 });
auto node3 = root.add_child(DbEntity{ 3 });
vector<TreeNode<DbEntity>*> vals;
copy(root.begin_segment<TreeNode<DbEntity>*>(), root.end_segment<TreeNode<DbEntity>*>(), back_inserter(vals));
auto const expected = vector<TreeNode<DbEntity>*>{ node1, node2, node3 };
EXPECT_EQ(expected, vals);
}
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
TEST(IteratorSegment, usability_copy_par_val10)
{
constexpr int n = 10;
TreeNode<DbEntity> root;
vector<DbEntity> expected;
for (int i = 0; i < n; ++i)
root.add_child(expected.emplace_back(DbEntity{ i + 1 }));
vector<DbEntity> vals(n);
copy(execution::par_unseq, root.begin_segment(), root.end_segment(), vals.begin());
EXPECT_EQ(expected, vals);
}
#endif
}
namespace IteratorDepthFirstSearchTests
{
using namespace std;
TEST(IteratorDfs, order_copy_value0)
{
TreeNode<int> root(0);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value0123)
{
TreeNode<int> root;
root.add_child(1);
root.add_child(2);
root.add_child(3);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 3};
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value011123)
{
TreeNode<int> root;
auto n1 = root.add_child(1);
auto n2 = root.add_child(2);
auto n3 = root.add_child(3);
n1->add_child(11);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 11, 2, 3 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value012213)
{
TreeNode<int> root;
root.add_child(1);
root.add_child(2)
->add_child(21);
root.add_child(3);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 21, 3 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value012331)
{
TreeNode<int> root;
root.add_child(1);
root.add_child(2);
root.add_child(3)
->add_child(31);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 3, 31 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value01112331)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11);
root.add_child(2);
root.add_child(3)
->add_child(31);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 11, 2, 3, 31 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value011111123)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11)
->add_child(111);
root.add_child(2);
root.add_child(3);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 11, 111, 2, 3 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value01111112212113)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11)
->add_child(111);
auto n2 = root.add_child(2)
->add_child(21)
->add_child(211);
auto n3 = root.add_child(3);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 11, 111, 2, 21, 211, 3 };
EXPECT_EQ(expected, vals);
}
TEST(StepManagerDfs, next_1_null)
{
TreeNode<int> root;
TreeNode<int>* node = &root;
StepManagerDfs::next<TreeNode<int>>(node);
EXPECT_EQ(nullptr, node);
}
TEST(StepManagerDfs, prev_1_null)
{
TreeNode<int> root;
TreeNode<int>* node = &root;
StepManagerDfs::prev<TreeNode<int>>(node);
EXPECT_EQ(nullptr, node);
}
TEST(StepManagerDfs, next_parent_child)
{
TreeNode<int> root(0);
auto node = &root;
auto ch = root.add_child(1);
StepManagerDfs::next<TreeNode<int>>(node);
EXPECT_EQ(ch, node);
}
TEST(StepManagerDfs, prev_parent_child)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto node = c1;
StepManagerDfs::prev<TreeNode<int>>(node);
EXPECT_EQ(&root, node);
}
TEST(StepManagerDfs, next_neighbour)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto node = c1;
StepManagerDfs::next<TreeNode<int>>(node);
EXPECT_EQ(c2, node);
}
TEST(StepManagerDfs, prev_neighbour)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto node = c2;
StepManagerDfs::prev<TreeNode<int>>(node);
EXPECT_EQ(c1, node);
}
TEST(StepManagerDfs, next_c1111_to_c2)
{
TreeNode<int> root(0);
auto c1111 = root.add_child(1)
->add_child(11)
->add_child(111)
->add_child(1111);
auto c2 = root.add_child(2);
auto node = c1111;
StepManagerDfs::next<TreeNode<int>>(node);
EXPECT_EQ(c2, node);
}
TEST(StepManagerDfs, prev_c2_to_c1111)
{
TreeNode<int> root(0);
auto c1111 = root.add_child(1)
->add_child(11)
->add_child(111)
->add_child(1111);
auto c2 = root.add_child(2);
auto node = c2;
StepManagerDfs::prev<TreeNode<int>>(node);
EXPECT_EQ(c1111, node);
}
TEST(StepManagerDfs, next_c1111_null)
{
TreeNode<int> root(0);
auto c1111 = root.add_child(1)
->add_child(11)
->add_child(111)
->add_child(1111);
auto node = c1111;
StepManagerDfs::next<TreeNode<int>>(node);
EXPECT_EQ(nullptr, node);
}
TEST(StepManagerDfs, prev_c1111_c111)
{
TreeNode<int> root(0);
auto c111 = root.add_child(1)
->add_child(11)
->add_child(111);
auto c1111 = c111->add_child(1111);
auto node = c1111;
StepManagerDfs::prev<TreeNode<int>>(node);
EXPECT_EQ(c111, node);
}
}
namespace IteratorBreadthFirstSearchTests
{
using namespace std;
TEST(IteratorBfs, order_copy_value0)
{
TreeNode<int> root(0);
vector<int> vals;
copy(root.begin_bfs(), root.end_bfs(), back_inserter(vals));
auto const expected = vector<int>{ 0 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorBfs, order_copy_value0123)
{
TreeNode<int> root;
root.add_child(1);
root.add_child(2);
root.add_child(3);
vector<int> vals;
copy(root.begin_bfs(), root.end_bfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 3 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorBfs, order_copy_value012311212231111311)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11)
->add_child(111);
auto node2 = root.add_child(2);
node2->add_child(21);
root.add_child(3)
->add_child(31)
->add_child(311);
node2->add_child(22);
vector<int> vals;
copy(root.begin_bfs(), root.end_bfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 3, 11, 21, 22, 31, 111, 311 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorBfs, order_inrange_level23_copy_value11212231111311)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11)
->add_child(111);
auto node2 = root.add_child(2);
node2->add_child(21);
root.add_child(3)
->add_child(31)
->add_child(311)
->add_child(3111);
node2->add_child(22);
vector<int> vals;
copy(root.begin_bfs(2), root.end_bfs(3), back_inserter(vals));
auto const expected = vector<int>{ 11, 21, 22, 31, 111, 311 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorBfs, begin_end_const_ShouldCompile)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11)
->add_child(111);
auto node2 = root.add_child(2);
node2->add_child(21);
root.add_child(3)
->add_child(31)
->add_child(311);
node2->add_child(22);
auto const& root_const = root;
vector<int> vals;
copy(root_const.begin(), root_const.end(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 3, 11, 21, 22, 31, 111, 311 };
EXPECT_EQ(expected, vals);
}
}
| 24.428125
| 124
| 0.646444
|
attcs
|
f9244945ecec1e566af7c4149db1742b7f2ee1f7
| 469
|
cpp
|
C++
|
lcm.cpp
|
shu736/First
|
034d0326def08fb6b104411dd3b37eb6c1e03eda
|
[
"MIT"
] | null | null | null |
lcm.cpp
|
shu736/First
|
034d0326def08fb6b104411dd3b37eb6c1e03eda
|
[
"MIT"
] | null | null | null |
lcm.cpp
|
shu736/First
|
034d0326def08fb6b104411dd3b37eb6c1e03eda
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
int lcm(int, int);
int main()
{
int a, b, result;
int prime[100];
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
result = lcm(a, b);
printf("The LCM of %d and %d is %d\n", a, b, result);
return 0;
}
int lcm(int a, int b)
{
static int common = 1;
if (common % a == 0 && common % b == 0)
{
return common;
}
common++;
lcm(a, b);
return common;
}
| 16.75
| 58
| 0.460554
|
shu736
|
234d42fdfc563de21241340a582b66d85721babd
| 28,425
|
cpp
|
C++
|
src/j_plot.cpp
|
tsyw/JoSIM
|
c1dc2a127787a5f5f6750ef84768f30abee8dcae
|
[
"MIT"
] | 1
|
2020-07-25T12:15:30.000Z
|
2020-07-25T12:15:30.000Z
|
src/j_plot.cpp
|
tsyw/JoSIM
|
c1dc2a127787a5f5f6750ef84768f30abee8dcae
|
[
"MIT"
] | null | null | null |
src/j_plot.cpp
|
tsyw/JoSIM
|
c1dc2a127787a5f5f6750ef84768f30abee8dcae
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2018 Johannes Delport
// This code is licensed under MIT license (see LICENSE for details)
#include "j_plot.hpp"
#ifdef USING_MATPLOTLIB
namespace plt = matplotlibcpp;
#endif
/*
Determine traces to plot from the control part of the main circuit
*/
void traces_to_plot(InputFile& iFile, std::vector<std::string> controlPart, std::vector<std::string>& traceLabel, std::vector<std::vector<double>>& traceData) {
std::vector<std::string> tokens, labeltokens, nodesTokens;
std::vector<double> trace;
std::map<std::string, std::vector<double>> traces;
std::string columnLabel1, columnLabel2, label, nodesToPlot;
int index1 = -1;
int index2 = -1;
for (const auto &string : controlPart) {
/****************************************************/
/* PRINT */
/****************************************************/
if (string.find("PRINT") != std::string::npos) {
tokens = tokenize_space(string);
/* Print the identified node voltage */
/*****************************************************************************************************/
if (tokens[1] == "NODEV") {
/* If more than one node is specified */
if (tokens.size() == 4) {
/* If second node is ground */
if(tokens[3] == "0" || tokens[3] == "GND") {
label = "NODE VOLTAGE " + tokens[2];
if (tokens[2][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[2], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[2] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[2] = tokens[2] + "_" + labeltokens[n];
}
}
columnLabel1 = "C_NV" + tokens[2];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_NODE_FOUND, tokens[2]);
}
}
/* If first node is ground */
else if (tokens[2] == "0" || tokens[3] == "GND") {
label = "NODE VOLTAGE " + tokens[3];
if (tokens[3][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[3], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[3] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[3] = tokens[3] + "_" + labeltokens[n];
}
}
columnLabel1 = "C_NV" + tokens[3];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
trace.clear();
trace = xVect[index1];
std::fill(trace.begin(), trace.end(), 0.0);
std::transform(trace.begin(), trace.end(), xVect[index1].begin(), trace.begin(), std::minus<double>());
traceLabel.push_back(label);
traceData.push_back(trace);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_NODE_FOUND, tokens[3]);
}
}
/* If neither are ground*/
else {
label = "NODE VOLTAGE " + tokens[2] + " to " + tokens[3];
columnLabel1 = "C_NV" + tokens[2];
columnLabel2 = "C_NV" + tokens[3];
if (tokens[2][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[2], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[2] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[2] = tokens[2] + "_" + labeltokens[n];
}
}
if (tokens[3][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[3], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[3] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[3] = tokens[3] + "_" + labeltokens[n];
}
}
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
trace.clear();
trace = xVect[index1];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel2) != iFile.matA.columnNames.end()) {
index2 = index_of(iFile.matA.columnNames, columnLabel2);
std::transform(xVect[index1].begin(), xVect[index1].end(), xVect[index2].begin(), trace.begin(), std::minus<double>());
traceLabel.push_back(label);
traceData.push_back(trace);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_NODE_FOUND, tokens[3]);
}
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_NODE_FOUND, tokens[2]);
}
}
}
/* If only one node is specified */
else {
label = "NODE VOLTAGE " + tokens[2];
columnLabel1 = "C_NV" + tokens[2];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
else {
/* Error this node was not found and can therefore not be printed */
}
}
}
/* Print the identified junction phase */
/*****************************************************************************************************/
else if (tokens[1] == "PHASE") {
label = "PHASE " + tokens[2];
if (tokens[2][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[2], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[2] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[2] = tokens[2] + "_" + labeltokens[n];
}
}
columnLabel1 = "C_P" + tokens[2];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_DEVICE_FOUND, tokens[2]);
}
}
/* Print the identified device voltage */
/*****************************************************************************************************/
else if (tokens[1] == "DEVV") {
label = "NOTHING";
if (tokens[2][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[2], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[2] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[2] = tokens[2] + "_" + labeltokens[n];
}
}
for (auto i : iFile.matA.elements) {
if (i.label == tokens[2]) {
trace.clear();
if (i.VPindex == -1) trace = xVect[i.VNindex];
else if (i.VNindex == -1) trace = xVect[i.VPindex];
else {
trace = xVect[i.VPindex];
std::transform(xVect[i.VPindex].begin(), xVect[i.VPindex].end(), xVect[i.VNindex].begin(), trace.begin(), std::minus<double>());
}
label = "DEVICE VOLTAGE " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
}
if (label == "NOTHING") {
if (VERBOSE) plotting_errors(NO_SUCH_DEVICE_FOUND, tokens[2]);
}
}
/* Print the identified device current */
/*****************************************************************************************************/
else if (tokens[1] == "DEVI") {
label = "NOTHING";
if (tokens[2][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[2], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[2] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[2] = tokens[2] + "_" + labeltokens[n];
}
}
std::vector<double> trace;
for (auto i : iFile.matA.elements) {
if (i.label == tokens[2]) {
if (tokens[2][0] == 'R') {
if (i.VPindex == -1) trace = xVect[i.VNindex];
else if (i.VNindex == -1) trace = xVect[i.VPindex];
else std::transform(xVect[i.VPindex].begin(), xVect[i.VPindex].end(), xVect[i.VNindex].begin(), trace.begin(), std::minus<double>());
std::transform(trace.begin(), trace.end(), trace.begin(), std::bind(std::multiplies<double>(), std::placeholders::_1, (1/i.value)));
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else if (tokens[2][0] == 'C') {
}
else if (tokens[2][0] == 'L') {
if (i.CURindex == -1) simulation_errors(INDUCTOR_CURRENT_NOT_FOUND, i.label);
else trace = xVect[i.CURindex];
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else if (tokens[2][0] == 'I') {
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(iFile.matA.sources[i.label]);
}
else if (tokens[2][0] == 'V') {
if (VERBOSE) simulation_errors(CURRENT_THROUGH_VOLTAGE_SOURCE, i.label);
}
else if (tokens[2][0] == 'B') {
trace = junctionCurrents["R_" + i.label];
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else plotting_errors(NO_SUCH_DEVICE_FOUND, tokens[2]);
}
}
if (label == "NOTHING") {
plotting_errors(NO_SUCH_DEVICE_FOUND, tokens[2]);
}
}
/* No such print command error thrown */
else {
if (VERBOSE) plotting_errors(NO_SUCH_PLOT_TYPE, tokens[1]);
}
}
/****************************************************/
/* PLOT */
/****************************************************/
else if (string.find("PLOT") != std::string::npos) {
tokens = tokenize_space(string);
for (int k = 1; k < tokens.size(); k++) {
/* If plotting voltage */
if(tokens[k][0] == 'V') {
/* Identify part between brackets */
nodesToPlot = tokens[k].substr(2);
nodesToPlot = nodesToPlot.substr(0, nodesToPlot.size() - 1);
/* If multiple arguments are specified for V */
if (nodesToPlot.find(',') != std::string::npos) {
nodesTokens = tokenize_delimeter(nodesToPlot, ",");
if(nodesTokens.size() > 2) {
plotting_errors(TOO_MANY_NODES, string);
}
/* Ensure node 1 is not ground */
if(nodesTokens[0] == "0" || nodesTokens[0] == "GND") {
if(nodesTokens[1] == "0" || nodesTokens[1] == "GND") {
plotting_errors(BOTH_ZERO, string);
}
else {
if (nodesTokens[1][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[1], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesTokens[1] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesTokens[1] = nodesTokens[1] + "_" + labeltokens[n];
}
}
columnLabel1 = "C_NV" + nodesTokens[1];
/* If this is a node voltage */
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
trace.clear();
trace = xVect[index1];
std::fill(trace.begin(), trace.end(), 0.0);
std::transform(trace.begin(), trace.end(), xVect[index1].begin(), trace.begin(), std::minus<double>());
traceLabel.push_back(label);
traceData.push_back(trace);
}
/* Else node not found */
else {
plotting_errors(NO_SUCH_NODE_FOUND, string);
}
}
}
/* Check if node 2 is ground */
else {
if(tokens[1] == "0" || tokens[1] == "GND") {
if (tokens[0][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[0], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[0] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[0] = tokens[0] + "_" + labeltokens[n];
}
}
columnLabel1 = "C_NV" + tokens[0];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
else {
plotting_errors(NO_SUCH_NODE_FOUND, string);
}
}
/* Neither nodes are ground */
else {
label = "NODE VOLTAGE " + nodesTokens[0] + " to " + nodesTokens[1];
columnLabel1 = "C_NV" + nodesTokens[0];
columnLabel2 = "C_NV" + nodesTokens[1];
if (nodesTokens[0][0] == 'X') {
labeltokens = tokenize_delimeter(nodesTokens[0], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesTokens[0] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesTokens[0] = nodesTokens[0] + "_" + labeltokens[n];
}
}
if (nodesTokens[1][0] == 'X') {
labeltokens = tokenize_delimeter(nodesTokens[1], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesTokens[1] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesTokens[1] = nodesTokens[1] + "_" + labeltokens[n];
}
}
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
trace.clear();
trace = xVect[index1];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel2) != iFile.matA.columnNames.end()) {
index2 = index_of(iFile.matA.columnNames, columnLabel2);
std::transform(xVect[index1].begin(), xVect[index1].end(), xVect[index2].begin(), trace.begin(), std::minus<double>());
traceLabel.push_back(label);
traceData.push_back(trace);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_NODE_FOUND, string);
}
}
}
}
}
/* If only one argument is specified for V */
else {
/* Ensure node is not ground */
if(nodesToPlot != "0" || nodesToPlot != "GND") {
if (nodesToPlot[0] == 'X') {
labeltokens = tokenize_delimeter(nodesToPlot, "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesToPlot = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesToPlot = nodesToPlot + "_" + labeltokens[n];
}
}
label = "C_NV" + nodesToPlot;
/* If this is a node voltage */
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), label) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, label);
label = "NODE VOLTAGE " + nodesToPlot;
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
/* Else it might be device voltage */
else {
label = "NOTHING";
for (auto i : iFile.matA.elements) {
if (i.label == nodesToPlot) {
trace.clear();
if (i.VPindex == -1) trace = xVect[i.VNindex];
else if (i.VNindex == -1) trace = xVect[i.VPindex];
else {
trace = xVect[i.VPindex];
std::transform(xVect[i.VPindex].begin(), xVect[i.VPindex].end(), xVect[i.VNindex].begin(), trace.begin(), std::minus<double>());
}
label = "DEVICE VOLTAGE " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
}
if (label == "NOTHING") {
if (VERBOSE) plotting_errors(NO_SUCH_DEVICE_FOUND, nodesToPlot);
}
}
}
}
}
else if (tokens[k][0] == 'I') {
/* Identify part between brackets */
nodesToPlot = tokens[k].substr(2);
nodesToPlot = nodesToPlot.substr(0, nodesToPlot.size() - 1);
label = "NOTHING";
if (nodesToPlot[0] == 'X') {
labeltokens = tokenize_delimeter(nodesToPlot, "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesToPlot = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesToPlot = nodesToPlot + "_" + labeltokens[n];
}
}
std::vector<double> trace;
for (auto i : iFile.matA.elements) {
if (i.label == nodesToPlot) {
if (nodesToPlot[0] == 'R') {
if (i.VPindex == -1) trace = xVect[i.VNindex];
else if (i.VNindex == -1) trace = xVect[i.VPindex];
else std::transform(xVect[i.VPindex].begin(), xVect[i.VPindex].end(), xVect[i.VNindex].begin(), trace.begin(), std::minus<double>());
std::transform(trace.begin(), trace.end(), trace.begin(), std::bind(std::multiplies<double>(), std::placeholders::_1, (1/i.value)));
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else if (nodesToPlot[0] == 'C') {
}
else if (nodesToPlot[0] == 'L') {
if (i.CURindex == -1) simulation_errors(INDUCTOR_CURRENT_NOT_FOUND, i.label);
else trace = xVect[i.CURindex];
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else if (nodesToPlot[0] == 'I') {
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(iFile.matA.sources[i.label]);
}
else if (nodesToPlot[0] == 'V') {
if (VERBOSE) simulation_errors(CURRENT_THROUGH_VOLTAGE_SOURCE, i.label);
}
else if (nodesToPlot[0] == 'B') {
trace = junctionCurrents["R_" + i.label];
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else plotting_errors(NO_SUCH_DEVICE_FOUND, string);
}
}
if (label == "NOTHING") {
plotting_errors(NO_SUCH_DEVICE_FOUND, string);
}
}
else if (tokens[k][0] == 'P') {
/* Identify part between brackets */
nodesToPlot = tokens[k].substr(2);
nodesToPlot = nodesToPlot.substr(0, nodesToPlot.size() - 1);
label = "PHASE " + nodesToPlot;
if (nodesToPlot[0] == 'X') {
labeltokens = tokenize_delimeter(nodesToPlot, "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesToPlot = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesToPlot = nodesToPlot + "_" + labeltokens[n];
}
}
columnLabel1 = "C_P" + nodesToPlot;
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_DEVICE_FOUND, nodesToPlot);
}
}
}
}
/****************************************************/
/* SAVE */
/****************************************************/
else if (string.find("SAVE") != std::string::npos) {
tokens = tokenize_space(string);
for (int k = 1; k < tokens.size(); k++) {
index1 = tokens[k].find("@");
if(index1 != std::string::npos) tokens[k] = tokens[k].substr(0, index1) + tokens[k].substr(index1+1);
index1 = tokens[k].find("[");
if(index1 != std::string::npos) tokens[k] = tokens[k].substr(0, index1);
index1 = tokens[k].find(".");
if(index1 != std::string::npos) {
tokens[k] = tokens[k].substr(0, index1) + "_" + tokens[k].substr(index1+1);
}
/* If this is a current source */
if (iFile.matA.sources.find(tokens[k]) != iFile.matA.sources.end()) {
label = "CURRENT " + tokens[k];
traceLabel.push_back(label);
traceData.push_back(iFile.matA.sources[tokens[k]]);
}
}
}
}
}
/*
Function that creates a plotting window with all available traces to plot
*/
int plot_all_traces(InputFile& iFile) {
#ifdef USING_FLTK
Fl_Window * win = new Fl_Window(1240, 768);
Fl_Scroll * scroll = new Fl_Scroll(0, 0, win->w(), win->h());
std::vector<Fl_Chart *> Charts;
std::string label;
int counter = 0;
for (auto i : iFile.matA.columnNames) {
label = substring_after(i, "C_");
Charts.push_back(new Fl_Chart(20, 20 + (counter * (scroll->h() / 3)), scroll->w() - 40, (scroll->h()/3 - 20)));
Charts[counter]->type(FL_LINE_CHART);
for (int j = 0; j < xVect[counter].size(); j++) {
Charts[counter]->add(xVect[counter][j]);
}
Charts[counter]->color(FL_WHITE);
Charts[counter]->align(FL_ALIGN_INSIDE|FL_ALIGN_CENTER|FL_ALIGN_TOP);
Charts[counter]->copy_label(label.c_str());
counter++;
}
win->resizable(scroll);
win->label(INPUT_FILE.c_str());
win->show();
return(Fl::run());
#elif USING_MATPLOTLIB
int counter = 0;
if (iFile.matA.columnNames.size() <= 3) {
plt::figure();
//plt::figure_size(800, 600);
for (auto i : iFile.matA.columnNames) {
plt::subplot(iFile.matA.columnNames.size(), 1, counter + 1);
plt::grid(true);
plt::plot(timeAxis, xVect[counter]);
plt::title(substring_after(i, "C_"));
if(substring_after(i, "C_")[0] == 'N') plt::ylabel("Voltage (V)");
else if (substring_after(i, "C_")[0] == 'I') plt::ylabel("Current (A)");
else if (substring_after(i, "C_")[0] == 'P') plt::ylabel("Phase (rads)");
counter++;
}
plt::xlabel("Time (s)");
plt::tight_layout();
plt::show();
}
else {
for (int j = 0; j < iFile.matA.columnNames.size(); j = j + 3) {
counter = j;
//plt::figure_size(800, 600);
plt::figure();
while((counter < iFile.matA.columnNames.size()) && (counter < j + 3)) {
plt::subplot(3, 1, (counter - j) + 1);
plt::grid(true);
plt::plot(timeAxis, xVect[counter]);
plt::title(substring_after(iFile.matA.columnNames[counter], "C_"));
if(substring_after(iFile.matA.columnNames[counter], "C_")[0] == 'N') plt::ylabel("Voltage (V)");
else if (substring_after(iFile.matA.columnNames[counter], "C_")[0] == 'I') plt::ylabel("Current (A)");
else if (substring_after(iFile.matA.columnNames[counter], "C_")[0] == 'P') plt::ylabel("Phase (rads)");
counter++;
}
plt::xlabel("Time (s)");
plt::tight_layout();
plt::show(false);
}
plt::show();
}
return 0;
#endif
return 0;
}
/*
Function that creates a plotting window only for the specified plots in the simulation
*/
int plot_traces(InputFile& iFile) {
#ifdef USING_FLTK
std::vector<std::string> traceLabel;
std::vector<std::vector<double>> traceData;
traces_to_plot(iFile.controlPart, traceLabel, traceData);
Fl_Window * win = new Fl_Window(1240, 768);
Fl_Scroll * scroll = new Fl_Scroll(0, 0, win->w(), win->h());
std::vector<Fl_Chart *> Charts;
if(traceLabel.size() > 0) {
for (int i = 0; i < traceLabel.size(); i++) {
Charts.push_back(new Fl_Chart(20, 20 + (i * (scroll->h() / 3)), scroll->w() - 40, (scroll->h() / 3 - 20)));
Charts[i]->type(FL_LINE_CHART);
for (int j = 0; j < traceData[i].size(); j++) {
Charts[i]->add(traceData[i][j]);
}
Charts[i]->color(FL_WHITE);
Charts[i]->align(FL_ALIGN_INSIDE | FL_ALIGN_CENTER | FL_ALIGN_TOP);
Charts[i]->copy_label(traceLabel[i].c_str());
}
}
else if (traceLabel.size() == 0) {
std::cout << "W: Plotting requested but no plot/print/save commands found." << std::endl;
std::cout << "W: Plotting all the node voltages by default." << std::endl;
int j = 0;
std::string label;
for (int i = 0; i < iFile.matA.columnNames.size(); i++) {
label = substring_after(iFile.matA.columnNames[i], "C_");
if(label[0] == 'N') {
Charts.push_back(new Fl_Chart(20, 20 + (j * (scroll->h() / 3)), scroll->w() - 40, (scroll->h() / 3 - 20)));
Charts[j]->type(FL_LINE_CHART);
for (int k = 0; k < xVect[i].size(); k++) {
Charts[j]->add(xVect[i][k]);
}
Charts[j]->color(FL_WHITE);
Charts[j]->align(FL_ALIGN_INSIDE | FL_ALIGN_CENTER | FL_ALIGN_TOP);
Charts[j]->copy_label(label.c_str());
j++;
}
}
}
win->resizable(win);
win->label(INPUT_FILE.c_str());
win->show();
return(Fl::run());
#elif USING_MATPLOTLIB
std::vector<std::string> traceLabel;
std::vector<std::vector<double>> traceData;
traces_to_plot(iFile, iFile.controlPart, traceLabel, traceData);
if(traceLabel.size() > 0) {
if (traceLabel.size() <= 3) {
//plt::figure_size(800, 600);
plt::figure();
for (int i = 0; i < traceLabel.size(); i++) {
plt::subplot(traceLabel.size(), 1, i + 1);
plt::grid(true);
plt::plot(timeAxis, traceData[i]);
plt::title(traceLabel[i].c_str());
if(traceLabel[i].find("VOLTAGE") != std::string::npos) plt::ylabel("Voltage (V)");
else if (traceLabel[i].find("CURRENT") != std::string::npos) plt::ylabel("Current (A)");
else if (traceLabel[i].find("PHASE") != std::string::npos) plt::ylabel("Phase (rads)");
}
plt::xlabel("Time (s)");
plt::tight_layout();
plt::show();
}
else {
for (int j = 0; j < traceLabel.size(); j = j + 3) {
int i = j;
//plt::figure_size(800, 600);
plt::figure();
while((i < traceLabel.size()) && (i < j + 3)) {
plt::subplot(3, 1, (i - j) + 1);
plt::grid(true);
plt::plot(timeAxis, traceData[i]);
plt::title(traceLabel[i].c_str());
if(traceLabel[i].find("VOLTAGE") != std::string::npos) { plt::ylabel("Voltage (V)"); }
else if (traceLabel[i].find("CURRENT") != std::string::npos) { plt::ylabel("Current (A)"); }
else if (traceLabel[i].find("PHASE") != std::string::npos) { plt::ylabel("Phase (rads)"); }
i++;
}
plt::xlabel("Time (s)");
plt::tight_layout();
plt::show(false);
}
plt::show();
}
}
else if(traceLabel.size() == 0) {
std::cout << "W: Plotting requested but no plot/print/save commands found." << std::endl;
std::cout << "W: Plotting all the node voltages by default." << std::endl;
// Find all the NV column indices
std::vector<int> nvIndices;
for(int i = 0; i < iFile.matA.columnNames.size(); i++) if(iFile.matA.columnNames[i][2] == 'N') nvIndices.push_back(i);
for (int j = 0; j < nvIndices.size(); j = j + 3) {
int i = j;
plt::figure_size(800, 600);
while((i < nvIndices.size()) && (i < j + 3)) {
plt::subplot(3, 1, (i - j) + 1);
plt::grid(true);
plt::plot(timeAxis, xVect[nvIndices[i]]);
plt::title(substring_after(iFile.matA.columnNames[nvIndices[i]], "C_").c_str());
plt::ylabel("Voltage (V)");
i++;
}
plt::xlabel("Time (s)");
plt::tight_layout();
plt::show(false);
}
plt::show();
}
return 0;
#endif
return 0;
}
| 41.07659
| 161
| 0.552366
|
tsyw
|
234fdceea4773f1e33084b230737b0ffba9d8adf
| 4,431
|
cpp
|
C++
|
src/cui-1.0.4/MBA/MBA.cpp
|
MaiReo/crass
|
11579527090faecab27f98b1e221172822928f57
|
[
"BSD-3-Clause"
] | 1
|
2021-07-21T00:58:45.000Z
|
2021-07-21T00:58:45.000Z
|
src/cui-1.0.4/MBA/MBA.cpp
|
MaiReo/crass
|
11579527090faecab27f98b1e221172822928f57
|
[
"BSD-3-Clause"
] | null | null | null |
src/cui-1.0.4/MBA/MBA.cpp
|
MaiReo/crass
|
11579527090faecab27f98b1e221172822928f57
|
[
"BSD-3-Clause"
] | null | null | null |
#include <windows.h>
#include <tchar.h>
#include <crass_types.h>
#include <acui.h>
#include <cui.h>
#include <package.h>
#include <resource.h>
#include <cui_error.h>
#include <stdio.h>
/* 接口数据结构: 表示cui插件的一般信息 */
struct acui_information MBA_cui_information = {
_T("飛翔システム"), /* copyright */
_T(""), /* system */
_T(".gdp"), /* package */
_T("1.0.1"), /* revision */
_T("痴漢公賊"), /* author */
_T("2009-3-18 20:35"), /* date */
NULL, /* notion */
ACUI_ATTRIBUTE_LEVEL_STABLE
};
/* 所有的封包特定的数据结构都要放在这个#pragma段里 */
#pragma pack (1)
typedef struct {
u32 index_entries;
} gdp_header_t;
typedef struct {
s8 name[260];
u32 length;
u32 offset;
} gdp_entry_t;
#pragma pack ()
/********************* gdp *********************/
static int MBA_gdp_extract_directory(struct package *pkg,
struct package_directory *pkg_dir);
/* 封包匹配回调函数 */
static int MBA_gdp_match(struct package *pkg)
{
if (pkg->pio->open(pkg, IO_READONLY))
return -CUI_EOPEN;
struct package_directory pkg_dir;
int ret = MBA_gdp_extract_directory(pkg, &pkg_dir);
if (!ret)
delete [] pkg_dir.directory;
return ret;
}
/* 封包索引目录提取函数 */
static int MBA_gdp_extract_directory(struct package *pkg,
struct package_directory *pkg_dir)
{
if (pkg->pio->readvec(pkg, &pkg_dir->index_entries, 4, 0, IO_SEEK_SET))
return -CUI_EREADVEC;
DWORD index_buffer_length = pkg_dir->index_entries * sizeof(gdp_entry_t);
gdp_entry_t *index_buffer = new gdp_entry_t[pkg_dir->index_entries];
if (!index_buffer)
return -CUI_EMEM;
if (pkg->pio->read(pkg, index_buffer, index_buffer_length)) {
delete [] index_buffer;
return -CUI_EREAD;
}
pkg_dir->directory = index_buffer;
pkg_dir->directory_length = index_buffer_length;
pkg_dir->index_entry_length = sizeof(gdp_entry_t);
return 0;
}
/* 封包索引项解析函数 */
static int MBA_gdp_parse_resource_info(struct package *pkg,
struct package_resource *pkg_res)
{
gdp_entry_t *gdp_entry;
gdp_entry = (gdp_entry_t *)pkg_res->actual_index_entry;
strcpy(pkg_res->name, gdp_entry->name);
pkg_res->name_length = -1; /* -1表示名称以NULL结尾 */
pkg_res->raw_data_length = gdp_entry->length;
pkg_res->actual_data_length = 0; /* 数据都是明文 */
pkg_res->offset = gdp_entry->offset;
return 0;
}
/* 封包资源提取函数 */
static int MBA_gdp_extract_resource(struct package *pkg,
struct package_resource *pkg_res)
{
BYTE *raw = new BYTE[pkg_res->raw_data_length];
if (!raw)
return -CUI_EMEM;
if (pkg->pio->readvec(pkg, raw, pkg_res->raw_data_length,
pkg_res->offset, IO_SEEK_SET)) {
delete [] raw;
return -CUI_EREADVEC;
}
pkg_res->raw_data = raw;
return 0;
}
/* 资源保存函数 */
static int MBA_gdp_save_resource(struct resource *res,
struct package_resource *pkg_res)
{
if (res->rio->create(res))
return -CUI_ECREATE;
if (pkg_res->actual_data && pkg_res->actual_data_length) {
if (res->rio->write(res, pkg_res->actual_data, pkg_res->actual_data_length)) {
res->rio->close(res);
return -CUI_EWRITE;
}
} else if (pkg_res->raw_data && pkg_res->raw_data_length) {
if (res->rio->write(res, pkg_res->raw_data, pkg_res->raw_data_length)) {
res->rio->close(res);
return -CUI_EWRITE;
}
}
res->rio->close(res);
return 0;
}
/* 封包资源释放函数 */
static void MBA_gdp_release_resource(struct package *pkg,
struct package_resource *pkg_res)
{
if (pkg_res->actual_data) {
delete [] pkg_res->actual_data;
pkg_res->actual_data = NULL;
}
if (pkg_res->raw_data) {
delete [] pkg_res->raw_data;
pkg_res->raw_data = NULL;
}
}
/* 封包卸载函数 */
static void MBA_gdp_release(struct package *pkg,
struct package_directory *pkg_dir)
{
if (pkg_dir->directory) {
delete [] pkg_dir->directory;
pkg_dir->directory = NULL;
}
pkg->pio->close(pkg);
}
/* 封包处理回调函数集合 */
static cui_ext_operation MBA_gdp_operation = {
MBA_gdp_match, /* match */
MBA_gdp_extract_directory, /* extract_directory */
MBA_gdp_parse_resource_info, /* parse_resource_info */
MBA_gdp_extract_resource, /* extract_resource */
MBA_gdp_save_resource, /* save_resource */
MBA_gdp_release_resource, /* release_resource */
MBA_gdp_release /* release */
};
/* 接口函数: 向cui_core注册支持的封包类型 */
int CALLBACK MBA_register_cui(struct cui_register_callback *callback)
{
if (callback->add_extension(callback->cui, _T(".gdp"), NULL,
NULL, &MBA_gdp_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR
| CUI_EXT_FLAG_WEAK_MAGIC))
return -1;
return 0;
}
}
| 23.822581
| 80
| 0.693297
|
MaiReo
|
23517d313abc400a073f8b524b70ab131eb930f0
| 2,585
|
cpp
|
C++
|
PLUTO/Src/Chombo/AMRLevelPlutoFactory.cpp
|
Mixpap/JetCloudSim
|
bc44ca3eb3956b87a4390428d897099a92a8b9b2
|
[
"MIT"
] | 1
|
2018-11-21T20:32:36.000Z
|
2018-11-21T20:32:36.000Z
|
PLUTO/Src/Chombo/AMRLevelPlutoFactory.cpp
|
Mixpap/JetCloudSim
|
bc44ca3eb3956b87a4390428d897099a92a8b9b2
|
[
"MIT"
] | 3
|
2018-10-08T22:20:49.000Z
|
2018-10-19T14:00:44.000Z
|
PLUTO/Src/Chombo/AMRLevelPlutoFactory.cpp
|
Mixpap/JetCloudSim
|
bc44ca3eb3956b87a4390428d897099a92a8b9b2
|
[
"MIT"
] | 1
|
2019-06-26T05:37:43.000Z
|
2019-06-26T05:37:43.000Z
|
#ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include "AMRLevelPlutoFactory.H"
#include "NamespaceHeader.H"
AMRLevelPlutoFactory::AMRLevelPlutoFactory()
{
m_patchPluto = NULL;
m_isDefined = false;
}
AMRLevelPlutoFactory::~AMRLevelPlutoFactory()
{
if (m_patchPluto != NULL)
{
delete m_patchPluto;
m_patchPluto = NULL;
}
m_isDefined = false;
}
void AMRLevelPlutoFactory::define(const Real& a_cfl,
const Real& a_domainLength,
const int& a_verbosity,
const Real& a_refineThresh,
const int& a_tagBufferSize,
const Real& a_initialDtMultiplier,
const PatchPluto* const a_patchPluto)
{
// Store the CFL number
m_cfl = a_cfl;
// Store the physical dimension of the longest side of the domain
m_domainLength = a_domainLength;
// Store the verbosity of the object
m_verbosity = a_verbosity;
// Store the refinement threshold for gradient
m_refineThresh = a_refineThresh;
// Store the tag buffer size
m_tagBufferSize = a_tagBufferSize;
// Store the initial dt multiplier
m_initialDtMultiplier = a_initialDtMultiplier;
// Delete any existing physics object
if (m_patchPluto != NULL)
{
delete m_patchPluto;
m_patchPluto = NULL;
}
// Store the object that supplies the physics needed by the integrator
// (used as a factory)
m_patchPluto = a_patchPluto->new_patchPluto();
// The object is defined
m_isDefined = true;
}
AMRLevel* AMRLevelPlutoFactory::new_amrlevel() const
{
// Make sure everything is defined
CH_assert(isDefined());
// Create a new AMRLevelPluto
AMRLevelPluto* amrGodPtr = new AMRLevelPluto();
// Set up new object
amrGodPtr->defineParams(m_cfl,
m_domainLength,
m_verbosity,
m_refineThresh,
m_tagBufferSize,
m_initialDtMultiplier,
m_patchPluto);
// Return it
return (static_cast <AMRLevel*> (amrGodPtr));
}
// Check that everything is defined
bool AMRLevelPlutoFactory::isDefined() const
{
return m_isDefined;
}
#include "NamespaceFooter.H"
| 25.594059
| 81
| 0.591876
|
Mixpap
|
2351dd801afdf4dd24e9dec216d419dd3d8c8b83
| 11,486
|
cpp
|
C++
|
src/stacker_system.cpp
|
scullion/stacker
|
ba9241c85962f210ea37784ebee3072dac63df46
|
[
"MIT"
] | null | null | null |
src/stacker_system.cpp
|
scullion/stacker
|
ba9241c85962f210ea37784ebee3072dac63df46
|
[
"MIT"
] | null | null | null |
src/stacker_system.cpp
|
scullion/stacker
|
ba9241c85962f210ea37784ebee3072dac63df46
|
[
"MIT"
] | null | null | null |
#include "stacker_system.h"
#include "stacker_shared.h"
#include "stacker_attribute_buffer.h"
#include "stacker_util.h"
#include "stacker_platform.h"
#include "stacker_document.h"
#include "stacker_layer.h"
namespace stkr {
static void make_font_descriptor(LogicalFont *descriptor, const char *face,
unsigned size, unsigned flags)
{
if (face != NULL) {
strncpy(descriptor->face, face, sizeof(descriptor->face));
descriptor->face[sizeof(descriptor->face) - 1] = '\0';
} else {
descriptor->face[0] = '\0';
}
descriptor->font_size = size;
descriptor->flags = (uint16_t)flags;
}
static void initialize_font_cache(System *system)
{
system->default_font_id = INVALID_FONT_ID;
system->font_cache_entries = 0;
make_font_descriptor(&system->default_font_descriptor,
DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE, DEFAULT_FONT_FLAGS);
system->default_font_id = get_font_id(system,
&system->default_font_descriptor);
ensure(system->default_font_id != INVALID_FONT_ID);
system->debug_label_font_id = INVALID_FONT_ID;
}
/* Returns a key uniquely identifying a font specification. */
static uint32_t make_font_key(const LogicalFont *logfont)
{
uint32_t seed = logfont->font_size | (logfont->flags << 16);
return murmur3_32(logfont->face, strlen(logfont->face), seed);
}
/* Precalculates numbers needed for typesetting from the system font metrics. */
static void calculate_derived_font_metrics(FontMetrics *metrics)
{
/* w = (1/3)em, y = (1/6)em, z = (1/9)em */
static const int ONE_THIRD = (1 << TEXT_METRIC_PRECISION) / 3;
static const int ONE_SIXTH = (1 << TEXT_METRIC_PRECISION) / 6;
static const int ONE_NINTH = (1 << TEXT_METRIC_PRECISION) / 9;
metrics->space_width = fixed_multiply(metrics->em_width, ONE_THIRD, TEXT_METRIC_PRECISION);
metrics->space_stretch = fixed_multiply(metrics->em_width, ONE_SIXTH, TEXT_METRIC_PRECISION);
metrics->space_shrink = fixed_multiply(metrics->em_width, ONE_NINTH, TEXT_METRIC_PRECISION);
metrics->paragraph_indent_width = metrics->em_width;
}
/* Returns the ID of a font from the font cache, creating it if necessary. */
int16_t get_font_id(System *system, const LogicalFont *logfont)
{
uint32_t key = make_font_key(logfont);
for (unsigned i = 0; i < system->font_cache_entries; ++i)
if (system->font_cache[i].key == key)
return (int16_t)i;
if (system->font_cache_entries == MAX_CACHED_FONTS)
return 0;
void *handle = platform_match_font(system->back_end, logfont);
if (handle == NULL)
return system->default_font_id;
CachedFont *cf = system->font_cache + system->font_cache_entries;
cf->key = key;
cf->handle = handle;
cf->descriptor = *logfont;
platform_font_metrics(system->back_end, handle, &cf->metrics);
calculate_derived_font_metrics(&cf->metrics);
return int16_t(system->font_cache_entries++);
}
/* Returns the system handle for a cached font. */
void *get_font_handle(System *system, int16_t font_id)
{
assertb(unsigned(font_id) < system->font_cache_entries);
return system->font_cache[font_id].handle;
}
/* Returns the logical font used to create a font ID. */
const LogicalFont *get_font_descriptor(System *system, int16_t font_id)
{
if (font_id != INVALID_FONT_ID) {
assertb(unsigned(font_id) < system->font_cache_entries);
return &system->font_cache[font_id].descriptor;
}
return &system->default_font_descriptor;
}
const FontMetrics *get_font_metrics(System *system, int16_t font_id)
{
assertb(unsigned(font_id) < system->font_cache_entries);
return &system->font_cache[font_id].metrics;
}
unsigned measure_text(System *system, int16_t font_id, const void *text,
unsigned length, unsigned *advances)
{
void *font_handle = get_font_handle(system, font_id);
return platform_measure_text(system->back_end, font_handle,
text, length, advances);
}
/* A convenience function to determine the size of a string's bounding
* rectangle. Optionally returns the temporary heap-allocated advances array
* used, for which the caller takes responsibility. */
unsigned measure_text_rectangle(System *system, int16_t font_id,
const void *text, unsigned length, unsigned *out_width,
unsigned *out_height, unsigned **out_advances)
{
unsigned *advances = new unsigned[length];
unsigned num_characters = measure_text(system, font_id, text,
length, advances);
if (out_width != NULL) {
*out_width = 0;
for (unsigned i = 0; i < num_characters; ++i)
*out_width += advances[i];
*out_width = round_fixed_to_int(*out_width, TEXT_METRIC_PRECISION);
}
if (out_height != NULL) {
const FontMetrics *metrics = get_font_metrics(system, font_id);
*out_height = round_fixed_to_int(metrics->height, TEXT_METRIC_PRECISION);
}
if (out_advances != NULL) {
*out_advances = advances;
} else {
delete [] out_advances;
}
return num_characters;
}
/* Precomputes hashed rule names for tag tokens and pseudo classes. */
static void make_built_in_rule_names(System *system)
{
system->rule_name_all = murmur3_64_cstr("*");
system->rule_name_active = murmur3_64_cstr(":active");
system->rule_name_highlighted = murmur3_64_cstr(":highlighted");
for (unsigned i = 0; i < NUM_KEYWORDS; ++i) {
system->token_rule_names[i] = murmur3_64_cstr(
TOKEN_STRINGS[TOKEN_KEYWORD_FIRST + i]);
}
}
static unsigned add_font_assignments(AttributeAssignment *attributes,
unsigned count, const char *face, unsigned size, unsigned flags)
{
attributes[count++] = make_assignment(TOKEN_FONT, face);
attributes[count++] = make_assignment(TOKEN_FONT_SIZE, size);
attributes[count++] = make_assignment(TOKEN_BOLD, (flags & STYLE_BOLD) != 0, VSEM_BOOLEAN);
attributes[count++] = make_assignment(TOKEN_ITALIC, (flags & TOKEN_ITALIC) != 0, VSEM_BOOLEAN);
attributes[count++] = make_assignment(TOKEN_UNDERLINE, (flags & STYLE_UNDERLINE) != 0, VSEM_BOOLEAN);
return count;
}
static void add_default_rules(System *system)
{
static const unsigned MAX_ROOT_ATTRIBUTES = 32;
AttributeAssignment attributes[MAX_ROOT_ATTRIBUTES];
unsigned count = 0;
attributes[count++] = make_assignment(TOKEN_COLOR, DEFAULT_TEXT_COLOR, VSEM_COLOR);
attributes[count++] = make_assignment(TOKEN_JUSTIFY, TOKEN_LEFT, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_WRAP, TOKEN_WORD_WRAP, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_LEADING, TOKEN_AUTO, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_WHITE_SPACE, TOKEN_NORMAL, VSEM_TOKEN);
count = add_font_assignments(attributes, count, DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE, DEFAULT_FONT_FLAGS);
add_rule(NULL, system, NULL, "document", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_WIDTH, TOKEN_GROW, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_JUSTIFY, TOKEN_FLUSH, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_INDENT, TOKEN_AUTO, VSEM_TOKEN);
add_rule(NULL, system, NULL, "p", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_CURSOR, TOKEN_CURSOR_HAND, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_UNDERLINE, true, VSEM_BOOLEAN);
attributes[count++] = make_assignment(TOKEN_COLOR, DEFAULT_LINK_COLOR, VSEM_COLOR);
add_rule(NULL, system, NULL, "a", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_COLOR, DEFAULT_HIGHLIGHTED_LINK_COLOR, VSEM_COLOR);
add_rule(NULL, system, NULL, "a:highlighted", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_COLOR, DEFAULT_ACTIVE_LINK_COLOR, VSEM_COLOR);
add_rule(NULL, system, NULL, "a:active", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_WIDTH, TOKEN_GROW, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_FONT_SIZE, 2.5f, VSEM_NONE, AOP_MULTIPLY);
attributes[count++] = make_assignment(TOKEN_BOLD, true, VSEM_BOOLEAN);
add_rule(NULL, system, NULL, "h1", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_WIDTH, TOKEN_GROW, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_FONT_SIZE, 2.0f, VSEM_NONE, AOP_MULTIPLY);
attributes[count++] = make_assignment(TOKEN_BOLD, true, VSEM_BOOLEAN);
add_rule(NULL, system, NULL, "h2", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_WIDTH, TOKEN_GROW, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_FONT_SIZE, 1.5f, VSEM_NONE, AOP_MULTIPLY);
attributes[count++] = make_assignment(TOKEN_BOLD, true, VSEM_BOOLEAN);
add_rule(NULL, system, NULL, "h3", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_WHITE_SPACE, TOKEN_PRESERVE, VSEM_TOKEN);
count = add_font_assignments(attributes, count, DEFAULT_FIXED_FONT_FACE, DEFAULT_FIXED_FONT_SIZE, DEFAULT_FIXED_FONT_FLAGS);
add_rule(NULL, system, NULL, "code", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
}
static void initialize_url_notifications(System *system, UrlCache *url_cache)
{
if (url_cache != NULL) {
system->image_layer_notify_id = url_cache->add_notify_sink(
(urlcache::NotifyCallback)&image_layer_notify_callback, system);
system->document_notify_id = url_cache->add_notify_sink(
(urlcache::NotifyCallback)&document_fetch_notify_callback, system);
} else {
system->image_layer_notify_id = urlcache::INVALID_NOTIFY_SINK_ID;
}
}
static void deinitialize_url_notifications(System *system, UrlCache *url_cache)
{
if (url_cache != NULL) {
url_cache->remove_notify_sink(system->image_layer_notify_id);
url_cache->remove_notify_sink(system->document_notify_id);
}
}
int16_t get_debug_label_font_id(System *system)
{
if (system->debug_label_font_id == INVALID_FONT_ID) {
LogicalFont descriptor;
make_font_descriptor(&descriptor, DEBUG_LABEL_FONT_FACE,
DEBUG_LABEL_FONT_SIZE, DEBUG_LABEL_FONT_FLAGS);
system->debug_label_font_id = get_font_id(system, &descriptor);
}
return system->debug_label_font_id;
}
System *create_system(unsigned flags, BackEnd *back_end, UrlCache *url_cache,
TextEncoding encoding, TextEncoding message_encoding)
{
System *system = new System();
system->flags = flags;
system->encoding = encoding;
system->message_encoding = message_encoding;
system->back_end = back_end;
system->url_cache = url_cache;
system->rule_table_revision = 0;
system->rule_revision_counter = 0;
system->total_boxes = 0;
system->total_nodes = 0;
initialize_font_cache(system);
make_built_in_rule_names(system);
initialize_url_notifications(system, url_cache);
add_default_rules(system);
return system;
}
void destroy_system(System *system)
{
assertb(system->total_nodes == 0);
assertb(system->total_boxes == 0);
clear_rule_table(&system->global_rules);
for (unsigned i = 0; i < system->font_cache_entries; ++i)
platform_release_font(system->back_end, system->font_cache[i].handle);
deinitialize_url_notifications(system, system->url_cache);
delete system;
}
BackEnd *get_back_end(System *system)
{
return system->back_end;
}
unsigned get_total_nodes(const System *system)
{
return system->total_nodes;
}
unsigned get_total_boxes(const System *system)
{
return system->total_boxes;
}
} // namespace stkr
| 38.673401
| 125
| 0.765715
|
scullion
|
2355492847a974f82b3e39e3ad68c1326d4c7bdf
| 407
|
cpp
|
C++
|
src/format.cpp
|
nalinraut/System-Monitor
|
cd51a040455bad43d835606fb3013b35a40f4fc4
|
[
"MIT"
] | null | null | null |
src/format.cpp
|
nalinraut/System-Monitor
|
cd51a040455bad43d835606fb3013b35a40f4fc4
|
[
"MIT"
] | null | null | null |
src/format.cpp
|
nalinraut/System-Monitor
|
cd51a040455bad43d835606fb3013b35a40f4fc4
|
[
"MIT"
] | null | null | null |
#include <string>
#include "format.h"
using std::string;
string Format::ElapsedTime(long int seconds) {
long int HH{seconds/3600};
long int H_re{seconds%3600};
long int MM{H_re/60};
long int SS{H_re%60};
string HH_str{std::to_string(HH)};
string MM_str{std::to_string(MM)};
string SS_str{std::to_string(SS)};
string time{HH_str+':'+MM_str+':'+SS_str};
return time;
}
| 23.941176
| 47
| 0.653563
|
nalinraut
|
235572b54424b5bf201c86257542fb05e43cff74
| 4,134
|
cpp
|
C++
|
19f/qual/prime/prime.cpp
|
willzhang05/icpc-practice
|
42f1fde0e7e26ba44d433688393db71e02b043b7
|
[
"MIT"
] | null | null | null |
19f/qual/prime/prime.cpp
|
willzhang05/icpc-practice
|
42f1fde0e7e26ba44d433688393db71e02b043b7
|
[
"MIT"
] | null | null | null |
19f/qual/prime/prime.cpp
|
willzhang05/icpc-practice
|
42f1fde0e7e26ba44d433688393db71e02b043b7
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
std::unordered_set<int> PRIMES = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131,
137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223,
227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311,
313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613,
617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719,
727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827,
829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049,
1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163,
1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283,
1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423};
int PRIMES_LIST[224] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131,
137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223,
227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311,
313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613,
617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719,
727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827,
829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049,
1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163,
1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283,
1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423};
std::unordered_map<int, std::unordered_set<int>> NONPRIME;
int find_nonprime(int val, std::unordered_set<int> *temp_seen) {
// if (result.count(val) != 0 || temp_seen->count(val) != 0){
// return 0;
//}
if (temp_seen->count(val) != 0) {
return 0;
}
if (NONPRIME.count(val) != 0) {
std::set_union(temp_seen->begin(), temp_seen->end(), NONPRIME[val].begin(),
NONPRIME[val].end(), std::inserter(*temp_seen, temp_seen->begin()));
return 0;
}
temp_seen->insert(val);
int count = 0;
for (int p = 0; p < 224; p++) {
// std::cout << val << ":" << PRIMES_LIST[p] << "\n";
if (val % PRIMES_LIST[p] == 0) {
count += find_nonprime(val / PRIMES_LIST[p], temp_seen);
}
}
return 0;
}
int main() {
int q;
std::cin >> q;
for (int j = 0; j < q; j++) {
int i;
std::cin >> i;
std::unordered_set<int> temp_seen;
int count = find_nonprime(i, &temp_seen);
std::cout << temp_seen.size() << "\n";
NONPRIME.insert(std::make_pair(i, temp_seen));
temp_seen.clear();
}
return 0;
}
| 52.329114
| 100
| 0.516933
|
willzhang05
|
2355c6b669e088ed141f637d36ec5804b5e750df
| 1,510
|
hh
|
C++
|
Archive/Stroika_FINAL_for_STERL_1992/Library/User/Headers/EnableView.hh
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 28
|
2015-09-22T21:43:32.000Z
|
2022-02-28T01:35:01.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Library/User/Headers/EnableView.hh
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 98
|
2015-01-22T03:21:27.000Z
|
2022-03-02T01:47:00.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Library/User/Headers/EnableView.hh
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 4
|
2019-02-21T16:45:25.000Z
|
2022-02-18T13:40:04.000Z
|
/* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
#ifndef __EnableView__
#define __EnableView__
/*
* $Header: /fuji/lewis/RCS/EnableView.hh,v 1.1 1992/06/20 17:33:49 lewis Exp $
*
* Description:
*
*
* TODO:
*
*
* Notes:
*
* Changes:
* $Log: EnableView.hh,v $
* Revision 1.1 1992/06/20 17:33:49 lewis
* Initial revision
*
* Revision 1.2 1992/03/26 09:24:26 lewis
* Got rid of oldLive first argument to EffectiveLiveChanged () method.
*
* Revision 1.1 1992/03/13 16:00:55 lewis
* Initial revision
*
*
*
*/
#include "EnableItem.hh"
#include "View.hh"
#if qCanFreelyUseVirtualBaseClasses
class EnableView : public virtual EnableItem, public virtual View {
#else
class EnableView : public EnableItem, public View {
#endif
protected:
EnableView (Boolean enabled = kEnabled);
public:
override Boolean GetLive () const;
protected:
override void EffectiveLiveChanged (Boolean newLive, UpdateMode updateMode);
override Boolean GetEnabled_ () const;
override void SetEnabled_ (Boolean enabled, UpdateMode updateMode);
private:
Boolean fEnabled;
};
/*
********************************************************************************
************************************ InLines ***********************************
********************************************************************************
*/
// For gnuemacs:
// Local Variables: ***
// mode:C++ ***
// tab-width:4 ***
// End: ***
#endif /*__EnableView__*/
| 19.358974
| 81
| 0.570861
|
SophistSolutions
|
2355c6bae8ee711ddb14deac4d4970de16e1fc9e
| 2,686
|
cpp
|
C++
|
problemes/probleme2xx/probleme280.cpp
|
ZongoForSpeed/ProjectEuler
|
2e2d45f984d48a1da8275886c976f909a0de94ce
|
[
"MIT"
] | 6
|
2015-10-13T17:07:21.000Z
|
2018-05-08T11:50:22.000Z
|
problemes/probleme2xx/probleme280.cpp
|
ZongoForSpeed/ProjectEuler
|
2e2d45f984d48a1da8275886c976f909a0de94ce
|
[
"MIT"
] | null | null | null |
problemes/probleme2xx/probleme280.cpp
|
ZongoForSpeed/ProjectEuler
|
2e2d45f984d48a1da8275886c976f909a0de94ce
|
[
"MIT"
] | null | null | null |
#include "problemes.h"
#include "arithmetique.h"
#include "matrice.h"
#include <bitset>
typedef unsigned long long nombre;
typedef std::vector<nombre> vecteur;
namespace {
long double algorithme(size_t sx, size_t sy, const std::bitset<5> &haut, const std::bitset<5> &bas) {
static std::map<std::tuple<size_t, size_t, size_t, size_t>, long double> cache;
auto clef = std::make_tuple(sx, sy, haut.to_ulong(), bas.to_ulong());
if (auto it = cache.find(clef);it != cache.end())
return it->second;
matrice::matrice<long double> A(25, 25, 0);
matrice::vecteur<long double> b(25, 0);
for (size_t x = 0; x < 5; ++x)
for (size_t y = 0; y < 5; ++y) {
size_t p = x + 5 * y;
A(p, p) = 1;
if (y == 0 && bas.test(x)) {
if (haut.none())
continue;
auto _bas = bas;
_bas.reset(x);
b(p) = algorithme(x, 4 - y, _bas, haut);
continue;
}
size_t t = 0;
if (x < 4) ++t;
if (x > 0) ++t;
if (y < 4) ++t;
if (y > 0) ++t;
long double f = 1.0L / t;
b(p) = 1;
if (x < 4) A(p, x + 1 + y * 5) = -f;
if (x > 0) A(p, x - 1 + y * 5) = -f;
if (y < 4) A(p, x + y * 5 + 5) = -f;
if (y > 0) A(p, x + y * 5 - 5) = -f;
}
matrice::vecteur<long double> c(25, 0);
// Résolution système A.c = b
matrice::resolutionLU(A, b, c);
long double resultat = c(sx + sy * 5);
cache[clef] = resultat;
return resultat;
}
}
ENREGISTRER_PROBLEME(280, "Ant and seeds") {
// A laborious ant walks randomly on a 5x5 grid. The walk starts from the central square. At each step, the ant
// moves to an adjacent square at random, without leaving the grid; thus there are 2, 3 or 4 possible moves at each
// step depending on the ant's position.
//
// At the start of the walk, a seed is placed on each square of the bas row.
// When the ant isn't carrying a seed and reaches a square of the bas row containing a seed, it will start to carry
// the seed. The ant will drop the seed on the first empty square of the haut row it eventually reaches.
//
// What's the expected number of steps until all seeds have been dropped in the top row?
//
// Give your answer rounded to 6 decimal places.
long double resultat = algorithme(2, 2, 31, 31);
return std::to_fixed(resultat, 6);
}
| 34.435897
| 119
| 0.513403
|
ZongoForSpeed
|
235d7868e431534664a820838212d93d28440767
| 7,370
|
cpp
|
C++
|
PhysicsEngine/ModulePhysics.cpp
|
bielrabasa/PhysicsEngine
|
ef3bc64c419a6da4ae234873e3d9da8c196197ec
|
[
"MIT"
] | 1
|
2021-12-27T15:12:27.000Z
|
2021-12-27T15:12:27.000Z
|
PhysicsEngine/ModulePhysics.cpp
|
bielrabasa/PhysicsEngine
|
ef3bc64c419a6da4ae234873e3d9da8c196197ec
|
[
"MIT"
] | null | null | null |
PhysicsEngine/ModulePhysics.cpp
|
bielrabasa/PhysicsEngine
|
ef3bc64c419a6da4ae234873e3d9da8c196197ec
|
[
"MIT"
] | null | null | null |
#include "Globals.h"
#include "Application.h"
#include "ModulePhysics.h"
#include "math.h"
ModulePhysics::ModulePhysics(Application* app, bool start_enabled) : Module(app, start_enabled)
{
debug = true;
}
ModulePhysics::~ModulePhysics()
{
}
bool ModulePhysics::Start()
{
LOG("Creating Physics 2D environment");
cannon_ball_texture = App->textures->Load("Assets/cannon_ball.png");
return true;
}
update_status ModulePhysics::PreUpdate()
{
return UPDATE_CONTINUE;
}
update_status ModulePhysics::Update()
{
return UPDATE_CONTINUE;
}
update_status ModulePhysics::PostUpdate()
{
p2List_item<Ball*>* current_ball = balls.getFirst();
while (current_ball != NULL) {
if (current_ball->data->physics_enabled) {
ResetForces(current_ball->data);
ComputeForces(current_ball->data);
NewtonsLaw(current_ball->data);
Integrator(current_ball->data);
CollisionSolver(current_ball->data);
}
current_ball = current_ball->next;
}
//DeleteBalls();
DrawBalls();
DrawColliders();
//Debug
if(App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)
debug = !debug;
if(!debug)
return UPDATE_CONTINUE;
//Debug options (mode debug activated)
return UPDATE_CONTINUE;
}
bool ModulePhysics::CleanUp()
{
LOG("Destroying physics world");
return true;
}
void ModulePhysics::ResetForces(Ball* ball) {
ball->fx = ball->fy = 0.0;
ball->ax = ball->ay = 0.0;
}
void ModulePhysics::ComputeForces(Ball* ball) {
//Apply Gravity
ball->fgx = ball->mass * GRAVITY_X;
ball->fgy = ball->mass * GRAVITY_Y;
ball->fx += ball->fgx;
ball->fy += ball->fgy;
//Apply Aerodinamic lift / drag
}
void ModulePhysics::NewtonsLaw(Ball* ball) {
//ForceSum = m * a
ball->ax = ball->fx / ball->mass;
ball->ay = ball->fy / ball->mass;
}
void ModulePhysics::Integrator(Ball* ball) {
if (integrator_type == integrators::VERLET) {
ball->x += ball->vx * dt + 0.5 * ball->ax * dt * dt;
ball->y += ball->vy * dt + 0.5 * ball->ay * dt * dt;
ball->vx += ball->ax * dt;
ball->vy += ball->ay * dt;
}
if (integrator_type == integrators::EULER_BACK) {
}
if (integrator_type == integrators::EULER_FORW) {
}
}
void ModulePhysics::CollisionSolver(Ball* ball) {
p2List_item<Collider*>* current_collider = colliders.getFirst();
while (current_collider != NULL) {
if (current_collider->data->rectangle) {
if ((ball->x + ball->radius > current_collider->data->rect.x) &&
(ball->x - ball->radius < current_collider->data->rect.x + current_collider->data->rect.w) &&
(ball->y + ball->radius > current_collider->data->rect.y) &&
(ball->y - ball->radius < current_collider->data->rect.y + current_collider->data->rect.h)) {
if ((ball->x + ball->radius > current_collider->data->rect.x) &&
(ball->x - ball->radius < current_collider->data->rect.x + current_collider->data->rect.w) &&
(ball->y + ball->radius - ball->vy > current_collider->data->rect.y) &&
(ball->y - ball->radius - ball->vy < current_collider->data->rect.y + current_collider->data->rect.h)) { //Horizontal Colision
if (ball->vx > 0) { //Right colision
ball->x -= 2 * (ball->x - (current_collider->data->rect.x - ball->radius));
}
else { //Left colision
ball->x += 2 * (-ball->x + (current_collider->data->rect.x + current_collider->data->rect.w + ball->radius));
}
ball->vy = ball->vy * ball->cr;
ball->vx = -ball->vx * ball->cr;
}
else if ((ball->x + ball->radius - ball->vx > current_collider->data->rect.x) &&
(ball->x - ball->radius - ball->vx < current_collider->data->rect.x + current_collider->data->rect.w) &&
(ball->y + ball->radius > current_collider->data->rect.y) &&
(ball->y - ball->radius < current_collider->data->rect.y + current_collider->data->rect.h)) { //Vertical Colision
if (ball->vy > 0) { //Floor colision
ball->y -= 2*(ball->y - (current_collider->data->rect.y - ball->radius));
}
else { //Ceiling colision
ball->y = current_collider->data->rect.y + (-ball->y + (current_collider->data->rect.y + current_collider->data->rect.h));
}
ball->vy = -ball->vy * ball->cr;
ball->vx = ball->vx * ball->cr;
}
else {//diagonal colision FUYM
if (ball->vy > 0) { //floor colision
ball->y = current_collider->data->rect.y - ball->radius;
}
else { //ceiling colision
ball->y = current_collider->data->rect.y + current_collider->data->rect.h + ball->radius;
}
ball->vy = -ball->vy * ball->cr;
ball->vx = -ball->vx * ball->cr;
}
}
}
else { //CIRCLE
double vecX = ball->x - current_collider->data->rect.x;
double vecY = ball->y - current_collider->data->rect.y;
double distance = sqrt(vecX * vecX + vecY * vecY);
if (current_collider->data->r + ball->radius > distance) { //Ball colliding ARREGLAR
//unitary vector
vecX = vecX / distance;
vecY = vecY / distance;
//tp out
ball->x = current_collider->data->rect.x + vecX * (current_collider->data->r + ball->radius);
ball->y = current_collider->data->rect.y + vecY * (current_collider->data->r + ball->radius);
//solver
double vector[2] = { ball->x - current_collider->data->rect.x,
ball->y - current_collider->data->rect.y };
double dotProduct = (ball->vx * vector[0]) + (ball->vy * vector[1]);
double vectorModule = sqrt((vector[0] * vector[0]) + (vector[1] * vector[1]));
ball->vx += -2 * (dotProduct / (vectorModule * vectorModule)) * vector[0] * ball->cr;
ball->vy += -2 * (dotProduct / (vectorModule * vectorModule)) * vector[1] * ball->cr;
}
}
current_collider = current_collider->next;
}
}
void ModulePhysics::DeleteBalls() {
p2List_item<Ball*>* current_ball = balls.getFirst();
while (current_ball != NULL) {
if (current_ball->data->y > 700) {
Ball* b = current_ball->data;
current_ball = current_ball->next;
balls.del(balls.findNode(b));
delete b;
}
else {
current_ball = current_ball->next;
}
}
}
void ModulePhysics::DeleteAllBalls() {
p2List_item<Ball*>* current_ball = balls.getFirst();
while (current_ball != NULL) {
Ball* b = current_ball->data;
current_ball = current_ball->next;
balls.del(balls.findNode(b));
delete b;
}
}
void ModulePhysics::DisableEnablePhysics() {
p2List_item<Ball*>* current_ball = balls.getFirst();
while (current_ball != NULL) {
current_ball->data->physics_enabled = !current_ball->data->physics_enabled;
current_ball = current_ball->next;
}
}
void ModulePhysics::DrawBalls() {
p2List_item<Ball*>* current_ball = balls.getFirst();
while (current_ball != NULL) {
//App->renderer->Blit(cannon_ball_texture, current_ball->data->x - 16, current_ball->data->y - 16, NULL, 2);
App->renderer->DrawCircle(current_ball->data->x, current_ball->data->y, current_ball->data->radius, 250, 250, 250);
current_ball = current_ball->next;
}
}
void ModulePhysics::DrawColliders() {
p2List_item<Collider*>* current_collider = colliders.getFirst();
while (current_collider != NULL) {
if (current_collider->data->rectangle) { //RECTANGLE
App->renderer->DrawQuad(current_collider->data->rect, 100, 100, 100, 255, false);
}
else { //CIRCLE
App->renderer->DrawCircle(current_collider->data->rect.x,
current_collider->data->rect.y, current_collider->data->r, 100, 100, 100);
}
current_collider = current_collider->next;
}
}
| 30.580913
| 131
| 0.650204
|
bielrabasa
|
235e62563051f8d69068c588855edf82d894b371
| 1,186
|
cpp
|
C++
|
graph-theory/diameter_tree.cpp
|
Swaraj-Deep/data-structures-algorithms
|
0ffef6806a3e0348b56e685c73857c99341a39d8
|
[
"MIT"
] | 2
|
2020-03-27T13:39:52.000Z
|
2020-03-29T00:14:27.000Z
|
graph-theory/diameter_tree.cpp
|
Swaraj-Deep/data-structures
|
0ffef6806a3e0348b56e685c73857c99341a39d8
|
[
"MIT"
] | null | null | null |
graph-theory/diameter_tree.cpp
|
Swaraj-Deep/data-structures
|
0ffef6806a3e0348b56e685c73857c99341a39d8
|
[
"MIT"
] | null | null | null |
/*
***************************
* *
* Author: Swaraj Deep *
* *
***************************
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void dfs_search(vector<vector<int>> &tree, vector<bool> &visited, int vertex, int dist, int &max_dist, int &max_node)
{
visited[vertex] = true;
if (dist > max_dist)
{
max_dist = dist;
max_node = vertex;
}
for (int child : tree[vertex])
{
if (!visited[child])
{
dfs_search(tree, visited, child, dist + 1, max_dist, max_node);
}
}
}
// To get maximum distance we have to make two dfs calls
// 1 -> call to get the node with maxm distance from the passed root and in the
// 2 -> call we get the required diameter
int max_distance(vector<vector<int>> &tree, vector<bool> &visited, int vertex, int dist)
{
int max_dist = -1;
int max_node = -1;
dfs_search(tree, visited, vertex, dist, max_dist, max_node);
replace(visited.begin(), visited.end(), true, false);
max_dist = -1;
dfs_search(tree, visited, max_node, 0, max_dist, max_node);
return max_dist;
}
| 26.355556
| 117
| 0.572513
|
Swaraj-Deep
|
2360490613d578811f9ae04a22cea2c5c4490d44
| 5,267
|
cxx
|
C++
|
src/core/SessionWatchdogContext.cxx
|
Dynatrace/openkit-native
|
e072599196ea9086a2f9cfe67bae701d7d470fc0
|
[
"Apache-2.0"
] | 8
|
2018-09-18T15:33:51.000Z
|
2022-02-20T12:19:03.000Z
|
src/core/SessionWatchdogContext.cxx
|
Dynatrace/openkit-native
|
e072599196ea9086a2f9cfe67bae701d7d470fc0
|
[
"Apache-2.0"
] | 2
|
2018-09-19T07:15:36.000Z
|
2019-03-14T17:16:19.000Z
|
src/core/SessionWatchdogContext.cxx
|
Dynatrace/openkit-native
|
e072599196ea9086a2f9cfe67bae701d7d470fc0
|
[
"Apache-2.0"
] | 15
|
2018-09-17T07:37:06.000Z
|
2020-10-02T11:47:47.000Z
|
/**
* Copyright 2018-2021 Dynatrace 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
*
* 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 "SessionWatchdogContext.h"
#include <algorithm>
#include <list>
using namespace core;
static const std::chrono::milliseconds DEFAULT_SLEEP_TIME_MILLISECONDS = std::chrono::seconds(5);
SessionWatchdogContext::SessionWatchdogContext(std::shared_ptr<providers::ITimingProvider> timingProvider,
std::shared_ptr<core::util::IInterruptibleThreadSuspender> threadSuspender)
: mIsShutdown(false)
, mTimingProvider(timingProvider)
, mThreadSuspender(threadSuspender)
, mSessionsToClose()
, mSessionsToSplitByTimeout()
{
}
const std::chrono::milliseconds& SessionWatchdogContext::getDefaultSleepTime()
{
return DEFAULT_SLEEP_TIME_MILLISECONDS;
}
void SessionWatchdogContext::execute()
{
auto durationToNextCloseInMillis = closeExpiredSessions();
auto durationToNextSplitInMillis = splitTimedOutSessions();
mThreadSuspender->sleep(std::min(durationToNextCloseInMillis, durationToNextSplitInMillis));
}
void SessionWatchdogContext::requestShutdown()
{
mIsShutdown = true;
mThreadSuspender->wakeup();
}
bool SessionWatchdogContext::isShutdownRequested()
{
return mIsShutdown;
}
void SessionWatchdogContext::closeOrEnqueueForClosing(std::shared_ptr<core::objects::SessionInternals> session, int64_t closeGracePeriodInMillis)
{
if (session->tryEnd())
{
return;
}
auto closeTime = mTimingProvider->provideTimestampInMilliseconds() + closeGracePeriodInMillis;
session->setSplitByEventsGracePeriodEndTimeInMillis(closeTime);
mSessionsToClose.put(session);
}
void SessionWatchdogContext::dequeueFromClosing(std::shared_ptr<core::objects::SessionInternals> session)
{
mSessionsToClose.remove(session);
}
void SessionWatchdogContext::addToSplitByTimeout(std::shared_ptr<core::objects::ISessionProxy> sessionProxy)
{
if (sessionProxy->isFinished())
{
return;
}
mSessionsToSplitByTimeout.put(sessionProxy);
}
void SessionWatchdogContext::removeFromSplitByTimeout(std::shared_ptr<core::objects::ISessionProxy> sessionProxy)
{
mSessionsToSplitByTimeout.remove(sessionProxy);
}
std::vector<std::shared_ptr<core::objects::SessionInternals>> SessionWatchdogContext::getSessionsToClose()
{
return mSessionsToClose.toStdVector();
}
std::vector<std::shared_ptr<core::objects::ISessionProxy>> SessionWatchdogContext::getSessionsToSplitByTimeout()
{
return mSessionsToSplitByTimeout.toStdVector();
}
int64_t SessionWatchdogContext::closeExpiredSessions()
{
auto sleepTimeInMillis = DEFAULT_SLEEP_TIME_MILLISECONDS.count();
auto allSessions = mSessionsToClose.toStdVector();
std::list<std::shared_ptr<core::objects::SessionInternals>> closableSessions;
// first iteration - get all closeable sessions
for (auto& session : allSessions)
{
auto nowInMillis = mTimingProvider->provideTimestampInMilliseconds();
auto gracePeriodEndTimeInMillis = session->getSplitByEventsGracePeriodEndTimeInMillis();
auto isGracePeriodExpired = gracePeriodEndTimeInMillis <= nowInMillis;
if (isGracePeriodExpired)
{
closableSessions.push_back(session);
continue;
}
auto sleepTimeToGracePeriodEndInMillis = gracePeriodEndTimeInMillis - nowInMillis;
sleepTimeInMillis = std::min(sleepTimeInMillis, sleepTimeToGracePeriodEndInMillis);
}
// remove the sessions
for (auto& session : closableSessions)
{
mSessionsToClose.remove(session);
session->end(false);
}
return sleepTimeInMillis;
}
int64_t SessionWatchdogContext::splitTimedOutSessions()
{
auto sleepTimeInMillis = DEFAULT_SLEEP_TIME_MILLISECONDS.count();
auto sessionProxiesToRemove = std::list<std::shared_ptr<core::objects::ISessionProxy>>();
auto allSessionProxies = mSessionsToSplitByTimeout.toStdVector();
// first iteration - get all session proxies that can be removed
for(auto& sessionProxy : allSessionProxies)
{
auto nextSessionSplitInMillis = sessionProxy->splitSessionByTime();
if (nextSessionSplitInMillis < 0)
{
sessionProxiesToRemove.push_back(sessionProxy);
continue;
}
auto nowInMillis = mTimingProvider->provideTimestampInMilliseconds();
auto durationToNextSplit = nextSessionSplitInMillis - nowInMillis;
if (durationToNextSplit < 0)
{
continue;
}
sleepTimeInMillis = std::min(sleepTimeInMillis, durationToNextSplit);
}
// remove previously identified session proxies
for(auto& sessionProxy : sessionProxiesToRemove)
{
mSessionsToSplitByTimeout.remove(sessionProxy);
}
return sleepTimeInMillis;
}
| 31.538922
| 145
| 0.748813
|
Dynatrace
|
236052da1cee9c60bc77d7d85ec7c9de2059bfe4
| 880
|
hpp
|
C++
|
src/Structures/SymbolBBox.hpp
|
Werni2A/O2CP
|
a20c0102e1c5aca35874cc6bc89f083c66dfeb0e
|
[
"MIT"
] | 5
|
2021-10-01T06:48:21.000Z
|
2021-12-23T11:14:41.000Z
|
src/Structures/SymbolBBox.hpp
|
Werni2A/O2CP
|
a20c0102e1c5aca35874cc6bc89f083c66dfeb0e
|
[
"MIT"
] | 7
|
2021-09-26T19:53:53.000Z
|
2022-01-06T13:04:03.000Z
|
src/Structures/SymbolBBox.hpp
|
Werni2A/O2CP
|
a20c0102e1c5aca35874cc6bc89f083c66dfeb0e
|
[
"MIT"
] | 1
|
2022-01-05T19:24:58.000Z
|
2022-01-05T19:24:58.000Z
|
#ifndef SYMBOLBBOX_H
#define SYMBOLBBOX_H
#include <cstdint>
#include <iostream>
#include <ostream>
#include <string>
#include "../General.hpp"
struct SymbolBBox
{
int32_t x1;
int32_t y1;
int32_t x2;
int32_t y2;
};
[[maybe_unused]]
static std::string to_string(const SymbolBBox& aObj)
{
std::string str;
str += std::string(nameof::nameof_type<decltype(aObj)>()) + ":" + newLine();
str += indent(1) + "x1 = " + std::to_string(aObj.x1) + newLine();
str += indent(1) + "y1 = " + std::to_string(aObj.y1) + newLine();
str += indent(1) + "x2 = " + std::to_string(aObj.x2) + newLine();
str += indent(1) + "y2 = " + std::to_string(aObj.y2) + newLine();
return str;
}
[[maybe_unused]]
static std::ostream& operator<<(std::ostream& aOs, const SymbolBBox& aVal)
{
aOs << to_string(aVal);
return aOs;
}
#endif // SYMBOLBBOX_H
| 18.723404
| 80
| 0.617045
|
Werni2A
|
23609737f9842ba0dbf84900221ba099a8bcf25a
| 7,913
|
cpp
|
C++
|
src/kvstore/StatisticStore.cpp
|
MMyheart/nebula1.0
|
e39fa11b88d5495e4d13cae3c14f39456b7b0629
|
[
"Apache-2.0"
] | null | null | null |
src/kvstore/StatisticStore.cpp
|
MMyheart/nebula1.0
|
e39fa11b88d5495e4d13cae3c14f39456b7b0629
|
[
"Apache-2.0"
] | null | null | null |
src/kvstore/StatisticStore.cpp
|
MMyheart/nebula1.0
|
e39fa11b88d5495e4d13cae3c14f39456b7b0629
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright (c) 2021 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "kvstore/StatisticStore.h"
#include <rocksdb/convenience.h>
#include "base/Base.h"
#include "fs/FileUtils.h"
#include "kvstore/RocksEngine.h"
#include "kvstore/RocksEngineConfig.h"
namespace nebula {
namespace kvstore {
StatisticStore::~StatisticStore() {
dbs_.clear();
LOG(INFO) << "~StatisticStore()";
}
bool StatisticStore::init() {
auto rootPath = folly::stringPrintf("%s/nebula", dataPath_.c_str());
auto dirs = fs::FileUtils::listAllDirsInDir(rootPath.c_str());
for (auto& dir : dirs) {
GraphSpaceID spaceId;
try {
spaceId = folly::to<GraphSpaceID>(dir);
} catch (const std::exception& ex) {
LOG(ERROR) << "Data path invalid: " << ex.what();
return false;
}
std::string statisticPath =
folly::stringPrintf("%s/nebula/%d/statistic/data", dataPath_.c_str(), spaceId);
if (fs::FileUtils::fileType(statisticPath.c_str()) == fs::FileType::NOTEXIST) {
LOG(INFO) << "spaceID " << spaceId << " need not to statistic";
continue;
}
if (fs::FileUtils::fileType(statisticPath.c_str()) != fs::FileType::DIRECTORY) {
LOG(FATAL) << statisticPath << " is not directory";
}
dbs_[spaceId].reset(newDB(statisticPath));
}
return true;
}
void StatisticStore::stop() {
for (const auto& db : dbs_) {
rocksdb::CancelAllBackgroundWork(db.second.get(), true);
}
}
rocksdb::DB* StatisticStore::newDB(const std::string& path) {
rocksdb::Options options;
rocksdb::DB* db = nullptr;
rocksdb::Status status = initRocksdbOptions(options);
CHECK(status.ok());
status = rocksdb::DB::Open(options, path, &db);
if (status.IsNoSpace()) {
LOG(WARNING) << status.ToString();
} else {
CHECK(status.ok()) << status.ToString();
}
return db;
}
void StatisticStore::addStatistic(GraphSpaceID spaceId) {
folly::RWSpinLock::WriteHolder wh(&lock_);
if (this->dbs_.find(spaceId) != this->dbs_.end()) {
LOG(INFO) << "Space " << spaceId << " has statistic!";
return;
}
std::string statisticPath =
folly::stringPrintf("%s/nebula/%d/statistic/data", dataPath_.c_str(), spaceId);
if (!fs::FileUtils::makeDir(statisticPath)) {
LOG(FATAL) << "makeDir " << statisticPath << " failed";
}
LOG(INFO) << "Create statistic for space " << spaceId << ", dataPath=" << statisticPath;
dbs_[spaceId].reset(newDB(statisticPath));
}
ResultCode StatisticStore::setOption(GraphSpaceID spaceId,
const std::string& configKey,
const std::string& configValue) {
std::unordered_map<std::string, std::string> configOptions = {{configKey, configValue}};
rocksdb::Status status = dbs_[spaceId]->SetOptions(configOptions);
if (status.ok()) {
LOG(INFO) << "SetOption Succeeded: " << configKey << ":" << configValue;
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "SetOption Failed: " << configKey << ":" << configValue;
return ResultCode::ERR_INVALID_ARGUMENT;
}
}
ResultCode StatisticStore::setDBOption(GraphSpaceID spaceId,
const std::string& configKey,
const std::string& configValue) {
std::unordered_map<std::string, std::string> configOptions = {{configKey, configValue}};
rocksdb::Status status = dbs_[spaceId]->SetDBOptions(configOptions);
if (status.ok()) {
LOG(INFO) << "SetDBOption Succeeded: " << configKey << ":" << configValue;
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "SetDBOption Failed: " << configKey << ":" << configValue;
return ResultCode::ERR_INVALID_ARGUMENT;
}
}
ResultCode StatisticStore::compact(GraphSpaceID spaceId) {
rocksdb::CompactRangeOptions options;
rocksdb::Status status = dbs_[spaceId]->CompactRange(options, nullptr, nullptr);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "CompactAll Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::flush(GraphSpaceID spaceId) {
rocksdb::FlushOptions options;
rocksdb::Status status = dbs_[spaceId]->Flush(options);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "Flush Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::multiRemove(GraphSpaceID spaceId, std::vector<std::string> keys) {
rocksdb::WriteBatch deletes(100000);
for (size_t i = 0; i < keys.size(); i++) {
deletes.Delete(keys[i]);
}
rocksdb::WriteOptions options;
rocksdb::Status status = dbs_[spaceId]->Write(options, &deletes);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "MultiRemove Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::multiPut(GraphSpaceID spaceId, std::vector<KV> kvs) {
rocksdb::WriteBatch updates(100000);
for (size_t i = 0; i < kvs.size(); i++) {
updates.Put(kvs[i].first, kvs[i].second);
}
rocksdb::WriteOptions options;
rocksdb::Status status = dbs_[spaceId]->Write(options, &updates);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "MultiPut Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::put(GraphSpaceID spaceId, KV kv) {
rocksdb::WriteOptions options;
rocksdb::Status status = dbs_[spaceId]->Put(options, kv.first, kv.second);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "Put Failed: " << kv.first << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::get(GraphSpaceID spaceId, std::string key, std::string* value) {
rocksdb::ReadOptions options;
rocksdb::Status status = dbs_[spaceId]->Get(options, rocksdb::Slice(key), value);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else if (status.IsNotFound()) {
VLOG(3) << "Get: " << key << " Not Found";
return ResultCode::ERR_KEY_NOT_FOUND;
} else {
VLOG(3) << "Get Failed: " << key << " " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::multiGet(GraphSpaceID spaceId,
const std::vector<std::string>& keys,
std::vector<std::string>* values) {
rocksdb::ReadOptions options;
std::vector<rocksdb::Slice> slices;
for (size_t index = 0; index < keys.size(); index++) {
slices.emplace_back(keys[index]);
}
auto status = dbs_[spaceId]->MultiGet(options, slices, values);
auto allExist = std::all_of(status.begin(), status.end(), [](const auto& s) { return s.ok(); });
if (allExist) {
return ResultCode::SUCCEEDED;
} else {
return ResultCode::ERR_PARTIAL_RESULT;
}
}
ResultCode StatisticStore::prefix(GraphSpaceID spaceId,
const std::string& prefix,
std::unique_ptr<KVIterator>* storageIter) {
rocksdb::ReadOptions options;
options.prefix_same_as_start = true;
rocksdb::Iterator* iter = dbs_[spaceId]->NewIterator(options);
if (iter) {
iter->Seek(rocksdb::Slice(prefix));
}
*storageIter = std::make_unique<RocksPrefixIter>(iter, prefix);
return ResultCode::SUCCEEDED;
}
} // namespace kvstore
} // namespace nebula
| 35.80543
| 100
| 0.614558
|
MMyheart
|
23625249e60afe425625fa27e472e0f1fd16cf6e
| 6,196
|
cpp
|
C++
|
ui-qt/Pretreatment/GrayHistogram/Roi/LabelGrayHistogram.cpp
|
qianyongjun123/FPGA-Industrial-Smart-Camera
|
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
|
[
"MIT"
] | 1
|
2017-12-28T08:08:02.000Z
|
2017-12-28T08:08:02.000Z
|
ui-qt/Pretreatment/GrayHistogram/Roi/LabelGrayHistogram.cpp
|
qianyongjun123/FPGA-Industrial-Smart-Camera
|
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
|
[
"MIT"
] | null | null | null |
ui-qt/Pretreatment/GrayHistogram/Roi/LabelGrayHistogram.cpp
|
qianyongjun123/FPGA-Industrial-Smart-Camera
|
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
|
[
"MIT"
] | 3
|
2017-12-28T08:08:05.000Z
|
2021-11-12T07:59:13.000Z
|
#include "LabelGrayHistogram.h"
#include <qdebug.h>
#include <QPen>
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
#define LINEWIDTH 30
LabelGrayHistogram::LabelGrayHistogram(QWidget *parent) : QLabel(parent)
{
m_max =100;
m_mode = -1;
for(int i=0; i<2560;i++)
{
m_grade[i] = 0;
}
}
void LabelGrayHistogram::mousePressEvent(QMouseEvent *e)
{
QLabel::mousePressEvent(e);
}
void LabelGrayHistogram::mouseMoveEvent(QMouseEvent *e)
{
QLabel::mouseMoveEvent(e);
}
void LabelGrayHistogram::mouseReleaseEvent(QMouseEvent *e)
{
QLabel::mouseReleaseEvent(e);
}
void LabelGrayHistogram::PaintGray(QPainter *painter)
{
painter->drawLine(100,400,610,400);//x轴
painter->drawLine(600,390,610,400);
painter->drawLine(600,410,610,400);
painter->drawLine(100,400,100,100);//y轴
painter->drawLine(90,110,100,100);
painter->drawLine(110,110,100,100);
painter->drawText(90,420,"0");
painter->drawText(610,420,"255");
int i = 0;
for(i= 1; i< 15;i++)
{
painter->drawLine(100+i*34,400,100+i*34,395);
painter->drawText(100+i*34-5,420,QString::number(15+16*(i-1)));
}
int iGrade = this->m_max/10;
//painter->drawText(60,100+5,QString::number(m_max));
//painter->drawText(100,100,QString::number(m_max));
for(i = 1;i<10;i++)
{
painter->drawLine(100,100+i*30,105,100+i*30);
//painter->drawText(60,100+i*30+5,QString::number(m_max-iGrade*i));
/*QString strTemp = QString::number(10-i);
strTemp +="/10";
painter->drawText(60,100+i*30+5,strTemp);*/
}
float fScale = 0.0;
fScale = 300.0/m_max*1.0;
int iMax = m_grade[0];
int iIndex = 0;
for(i = 0; i<255;i++)
{
if(m_grade[i] > iMax)
{
iMax = m_grade[i];
iIndex = i;
}
painter->drawLine(100+i*2,400-m_grade[i]*fScale,100+i*2+1,400-m_grade[i+1]*fScale);
}
painter->drawText(100+iIndex*2,400-m_grade[iIndex]*fScale,QString::number(m_max));
}
void LabelGrayHistogram::PaintByColoum(QPainter *painter)
{
painter->drawLine(0,400,640,400);//x轴
painter->drawLine(630,390,640,400);
painter->drawLine(630,410,640,400);
painter->drawLine(0,400,0,100);//y轴
painter->drawLine(-10,110,0,100);
painter->drawLine(10,110,0,100);
painter->drawText(3,420,"0");
painter->drawText(610,420,"640");
int i = 0;
for(i= 1; i< 15;i++)
{
painter->drawLine(i*42,400,i*42,395);
painter->drawText(i*42-8,420,QString::number(42+42*(i-1)));
}
int iGrade = this->m_max/10;
//painter->drawText(0,100+5,QString::number(m_max));
//painter->drawText(0,100,QString::number(m_max));
for(i = 1;i<10;i++)
{
painter->drawLine(0,100+i*30,5,100+i*30);
//painter->drawText(5,100+i*30+10,QString::number(m_max-iGrade*i));
/*QString strTemp = QString::number(10-i);
strTemp +="/10";
painter->drawText(5,100+i*30+5,strTemp);*/
}
float fScale = 0.0;
fScale = 300.0/m_max*1.0;
int iMax = m_grade[0];
int iIndex = 0;
for(i = 0; i<639;i++)
{
if(m_times == 4)
painter->drawLine(i,400-m_grade[i*4]*fScale,i+1,400-m_grade[i*4+4]*fScale);
else if(m_times == 2)
painter->drawLine(i,400-m_grade[i*2]*fScale,i+1,400-m_grade[i*2+2]*fScale);
else if(m_times == 1)
painter->drawLine(i,400-m_grade[i]*fScale,i+1,400-m_grade[i+1]*fScale);
if(m_grade[i*m_times] > iMax)
{
iMax = m_grade[i*m_times];
iIndex = i;
}
}
painter->drawText(iIndex,400-m_grade[iIndex*m_times]*fScale,QString::number(m_max));
}
void LabelGrayHistogram::PaintByRow(QPainter *painter)
{
painter->drawLine(100,400,580,400);//x轴
painter->drawLine(570,390,580,400);
painter->drawLine(570,410,580,400);
painter->drawLine(100,400,100,100);//y轴
painter->drawLine(90,110,100,100);
painter->drawLine(110,110,100,100);
painter->drawText(90,420,"0");
painter->drawText(580,420,"480");
int i = 0;
for(i= 1; i< 15;i++)
{
painter->drawLine(100+i*32,400,100+i*32,395);
painter->drawText(100+i*32-5,420,QString::number(32+32*(i-1)));
}
int iGrade = this->m_max/10;
//painter->drawText(60,100+5,QString::number(m_max));
//painter->drawText(100,100,QString::number(m_max));
for(i = 1;i<10;i++)
{
painter->drawLine(100,100+i*30,105,100+i*30);
//painter->drawText(60,100+i*30+5,QString::number(m_max-iGrade*i));
/*QString strTemp = QString::number(10-i);
strTemp += "/10";
painter->drawText(60,100+i*30+5,strTemp);*/
}
float fScale = 0.0;
fScale = 300.0/m_max*1.0;
int iMax = m_grade[0];
int iIndex = 0;
for(i = 0; i<479;i++)
{
if(m_times == 1)
painter->drawLine(100+i,400-m_grade[i]*fScale,100+i+1,400-m_grade[i+1]*fScale);
else if(m_times == 2)
painter->drawLine(100+i,400-m_grade[i*2]*fScale,100+i+1,400-m_grade[i*2+2]*fScale);
else if(m_times == 4)
painter->drawLine(100+i,400-m_grade[i*4]*fScale,100+i+1,400-m_grade[i*4+4]*fScale);
if(m_grade[i*m_times] > iMax)
{
iMax = m_grade[i*m_times];
iIndex = i;
}
}
painter->drawText(100+iIndex,400-m_grade[iIndex*m_times]*fScale,QString::number(m_max));
}
void LabelGrayHistogram::paintEvent(QPaintEvent *e)
{
QLabel::paintEvent(e);
QPainter painter(this);
QPen pen;
pen.setColor(Qt::red);
pen.setWidth(1);
painter.setPen(pen);
if(m_mode == 0)
{
PaintGray(&painter);
}else if(m_mode == 1) //列
{
PaintByColoum(&painter);
}else if(m_mode == 2) //行
{
PaintByRow(&painter);
}
}
void LabelGrayHistogram::SetGrade(unsigned int *gradeArr, int size, int mode,int times)
{
this->m_size = size;
this->m_mode = mode;
m_times = times;
m_max = gradeArr[0];
for(int i = 0;i<size;i++)
{
this->m_grade[i] = gradeArr[i];
if(gradeArr[i] > m_max)
{
m_max = gradeArr[i];
}
}
update();
}
| 27.784753
| 95
| 0.589413
|
qianyongjun123
|
2367f31d4ca3bf43363e4d2c5415ded954b3c0b7
| 21,908
|
cxx
|
C++
|
StRoot/Stl3Util/gl3/gl3Conductor.cxx
|
xiaohaijin/RHIC-STAR
|
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
|
[
"MIT"
] | 2
|
2018-12-24T19:37:00.000Z
|
2022-02-28T06:57:20.000Z
|
StRoot/Stl3Util/gl3/gl3Conductor.cxx
|
xiaohaijin/RHIC-STAR
|
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
|
[
"MIT"
] | null | null | null |
StRoot/Stl3Util/gl3/gl3Conductor.cxx
|
xiaohaijin/RHIC-STAR
|
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
|
[
"MIT"
] | null | null | null |
//:>------------------------------------------------------------------
//: FILE: gl3Conductor.cc
//: HISTORY:
//: 1 feb 2000 version 1.00
//: 6 jul 2000 add St_l3_Coordinate_Transformer
//: 27 jul 2000 add print timing
//:<------------------------------------------------------------------
#include "Stl3Util/gl3/gl3Conductor.h"
#include "Stl3Util/base/L3swap.h"
#include "Stl3Util/base/realcc.h"
#include "Stl3Util/base/FtfLog.h"
#include <time.h>
#include <errno.h>
#include <netinet/in.h>
#include <unistd.h>
#ifdef GL3ONLINE
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#endif
//VP extern int errno;
//####################################################################
//
//####################################################################
gl3Conductor::gl3Conductor (void){
unsigned int start = realcc();
sleep(1);
unsigned int stop = realcc();
ccPerMs = (double)(stop-start)/1000.;
//ftfLog("gl3Conductor: estimated CPU freq: %7.3f MHz\n", ccPerMs/1000.);
nAlgorithms = 0;
}
//####################################################################
//
//####################################################################
gl3Conductor::~gl3Conductor ( ) {
if ( event != NULL ) delete[] event ;
clearAlgorithms();
if ( algorithm != NULL ) delete algorithm;
if ( summary != NULL ) delete[] summary ;
if ( summaryData != NULL ) free (summaryData) ;
delete []tokenIndex ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::configure (L3_CFG *cfg)
{
clearAlgorithms();
if(cfg == NULL || cfg == (L3_CFG *)-1) {
ftfLog("gl3Conductor::configure: No configuration information found.\n");
return 1;
}
L3_ALGORITHMS *algos = cfg->l3_setup.gl3_algorithms;
for (int i=0; i<GL3_ALG_MAX_NUM; i++) {
if(ntohl(algos[i].alg_id) != 0) {
gl3Algorithm *algo =
gl3InstantiateAlgorithm(ntohl(algos[i].alg_id));
if (algo == NULL) {
ftfLog("gl3Conductor::configure: Instantiation of algorithm #%d failed.\n", i);
return 1;
}
algo->setScaling(ntohl(algos[i].preScale),
ntohl(algos[i].postScale));
if (algo->setParameters(ntohl(algos[i].GI1),
ntohl(algos[i].GI2),
ntohl(algos[i].GI3),
ntohl(algos[i].GI4),
ntohl(algos[i].GI5),
fswap(algos[i].GF1),
fswap(algos[i].GF2),
fswap(algos[i].GF3),
fswap(algos[i].GF4),
fswap(algos[i].GF5))) {
ftfLog("gl3Conductor::configure: Invalid parameters for algorithm %s (ID %d)", algo->getAlgorithmName(), algo->getAlgorithmID());
return 1;
}
if(add(algo) != 0) {
ftfLog("gl3Conductor::configure: Appending algorithm %s (ID %i) to list failed.\n",
algo->getAlgorithmName(), algo->getAlgorithmID());
return 1;
}
algo->showConfiguration();
}
}
//ftfLog("gl3Conductor::configure: Done.\n");
return 0;
}
//####################################################################
//
//####################################################################
int gl3Conductor::add( gl3Algorithm* module ) {
if ( nAlgorithms >= maxAlgorithms ) {
ftfLog ( "gl3Conductor::add: Max. number of algorithms reached\n" ) ;
return 1;
}
algorithm[nAlgorithms] = module ;
nAlgorithms++ ;
return 0 ;
}
//####################################################################
//
//####################################################################
void gl3Conductor::clearAlgorithms()
{
for (int i =0; i<nAlgorithms; i++) {
if(algorithm[i]) {
delete algorithm[i];
algorithm[i] = NULL;
}
}
nAlgorithms = 0;
}
//####################################################################
//
//####################################################################
int gl3Conductor::checkHistoRequest ( ) {
#ifdef GL3ONLINE
struct sockaddr_in remoteAddress; /* connector's address information */
socklen_t sin_size = sizeof(struct sockaddr_in);
if ((remoteSocket = accept(socketFd, (struct sockaddr *)&remoteAddress,
&sin_size)) == -1) {
return 0;
}
const int maxBytes = 100000 ;
char* buffer = new char[maxBytes];
int nBytes = writeHistos ( maxBytes, buffer ) ;
if ( nBytes < 0 ) {
ftfLog ( "gl3Conductor::checkHistoRequest: buffer too small \n " ) ;
return 1 ;
}
int nSend = send(remoteSocket, buffer, nBytes, 0 ) ;
ftfLog ( "gl3Conductor: %d out of %d bytes sent\n ", nSend, nBytes ) ;
if ( nSend == -1) {
perror("send");
return 1 ;
}
delete []buffer ;
#endif
return 0 ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::end ( ){
#ifdef GL3ONLINE
close ( socketFd ) ;
#endif
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
algorithm[i]->end( );
}
return 0 ;
}
//####################################################################
//
//####################################################################
gl3Event* gl3Conductor::getEvent ( int token ) {
int index = getTokenIndex(token) ;
if (index < 0)
return NULL;
else
return &(event[index]) ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::init ( ){
ftfLog("gl3Conductor::init: %d algos\n", nAlgorithms);
#ifdef GL3ONLINE
l3Rates = new gl3Histo("l3rates",
"L3 trigger rates",
nAlgorithms+2, -2.5, (double)nAlgorithms-0.5);
histoList.push_back(l3Rates);
allocateTimingHistos();
#endif
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
algorithm[i]->init();
}
nReco = 0;
return 0 ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::processEvent(EventDescriptor *desc,
L3_P* l3data,
TrgSumData* trgSum,
RawTrgDet* trgRaw)
{
resetTimer();
// If we get a EventDescriptor, it should be for the right token
if ( desc && desc->token != l3data->bh.token ) {
ftfLog ("gl3Conductor::readEvent: token mismatch (%d and %d)\n",
desc->token, l3data->bh.token);
return -1;
}
int token = l3data->bh.token;
if ( token < 0 || token > maxTokens ){
ftfLog ("gl3Conductor::readEvent: %d token out of bounds\n", token );
return -1;
}
// Look for a free event container
int index = getFreeEventIndex();
if ( index < 0 ) {
ftfLog ( "gl3Conductor::readEvent: No free event container \n" ) ;
return -1;
}
tokenIndex[token] = index;
// Read Event and check if errors occured
if (event[index].readEventDescriptor(desc) != 0) {
ftfLog ( "gl3Conductor::processEvent: error reading EventDescriptor\n" ) ;
return -1;
}
if ( event[index].getTrgCmd() == 0 ||
event[index].getTrgCmd() == 1 ||
event[index].getTrgCmd() == 2 ||
event[index].getTrgCmd() == 3 ) {
ftfLog ("gl3Conductor::processEvent: Trigger Command 0,1,2 or 3 received\n");
return 2; // hard trigger
}
if ( event[index].getTrgCmd() == 5 ||
event[index].getTrgCmd() == 6 ||
event[index].getTrgCmd() == 7 ) {
ftfLog ("gl3Conductor::processEvent: Trigger Command 5,6 or 7 received - unknown physics run type\n");
// continue reading data and running algorithms
}
// Read L3 data
if ( event[index].readL3Data(l3data) != 0 ) {
ftfLog ( "gl3Conductor::processEvent: error reading L3 data\n" ) ;
return -1;
}
// Do not ontinue (run algorithms) if we have a laser or pulser event.
// Return decision = 1 to ensure the event is built.
if ( event[index].getTrgCmd() >= 8 ) {
// Laser trigger
return 2; // hard trigger
}
timingMark(); // step 1
if ( event[index].readTrgData(trgSum, trgRaw) != 0 ) {
ftfLog ( "gl3Conductor::processEvent: error reading TRG data\n" ) ;
return -1;
}
timingMark(); // step 2
// The preparation is done, now let's run the algorithms.
int decision = 0;
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
int alg_decision = algorithm[i]->process( &(event[index]));
if (alg_decision > decision) {
decision = alg_decision;
}
timingMark(); // step 3...2+nAlgorithms
}
// Now increment the counters for the algorithms. Can't be done
// earlier, because if an event crashes, we do not want to have
// any counters incremented
nReco++;
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
algorithm[i]->incrementCounters();
}
collectSummary(token);
timingMark(); // step 4+nAlgorithms
fillTimingHistos();
#ifdef GL3ONLINE
l3Rates->Fill(-2); // event was processed
if (decision) {
l3Rates->Fill(-1); // event was triggered for any reason
for (int i=0; i<nAlgorithms;i++) {
if (summaryData[index].alg[i].accept)
l3Rates->Fill(i); // accepted because of algorithm #i
// cout << "alg #" << i << ": "
// << summaryData[index].alg[i].accept
// << " histo: " << l3Rates->GetY(i+2)
// << endl;
}
}
if ( communicationsFlag ) {
checkHistoRequest();
}
#endif
if (nAlgorithms == 0) decision=1; // no algs -> trigger everything
return decision ;
}
//####################################################################
// Copy the previously filled summary data to the requested locations
//####################################################################
int gl3Conductor::fillSummary(int token,
struct L3_summary* summaryDest,
struct L3_SUMD *summaryDataDest)
{
int index = getTokenIndex(token);
if (index < 0) return 1;
memcpy(summaryDest, &summary[index], sizeof(L3_summary));
memcpy(summaryDataDest, &summaryData[index],
summaryData[index].bh.length*4);
return 0;
}
//####################################################################
// Fill summary information for a given token
//####################################################################
int gl3Conductor::collectSummary(int token)
{
int index = tokenIndex[token];
if (index < 0) return 1;
sprintf(summaryData->bh.bank_type, CHAR_L3_SUMD);
summaryData[index].bh.length =
(sizeof(L3_SUMD) + (nAlgorithms-1)*sizeof(algorithm_data))/4;
summaryData[index].bh.bank_id = 0;
summaryData[index].bh.format_ver = 0;
summaryData[index].bh.byte_order = DAQ_RAW_FORMAT_ORDER;
summaryData[index].bh.format_number = 0;
summaryData[index].bh.token = token;
summaryData[index].bh.w9 = DAQ_RAW_FORMAT_WORD9;
summaryData[index].bh.crc = 0;
summaryData[index].nProcessed = 0;
summaryData[index].nReconstructed = nReco;
summaryData[index].nAlg = nAlgorithms;
summary[index].accept = 0;
summary[index].build = 0;
summary[index].on = 0;
for (int i = 0; i < nAlgorithms; i++) {
algorithm[i]->fillSummary(&summaryData[index].alg[i]);
if(summaryData[index].alg[i].on)
summary[index].on |= 1<<i;
if(summaryData[index].alg[i].accept)
summary[index].accept |= 1<<i;
if(summaryData[index].alg[i].build)
summary[index].build |= 1<<i;
}
summary[index].nTracks = event[index].getNTracks();
return 0;
}
//####################################################################
//
//####################################################################
int gl3Conductor::releaseToken ( int token ) {
int index = getTokenIndex(token);
if (index < 0) return 1;
event[index].resetEvent();
return 0;
}
//####################################################################
//
//####################################################################
int gl3Conductor::resetHistos ( ) {
list<gl3Histo*>::iterator histo;
for(histo=histoList.begin(); histo!=histoList.end(); histo++) {
(*histo)->Reset();
}
return 0 ;
}//####################################################################
//
//####################################################################
int gl3Conductor::runStart ( int _runNumber ) {
runNumber = _runNumber ;
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
algorithm[i]->init();
}
nReco = 0;
return resetHistos ( ) ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::runEnd ( ) {
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
algorithm[i]->end( );
}
return 0 ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::setCommunications ( ){
//
#ifdef GL3ONLINE
struct sockaddr_in gl3Address; /* my address information */
gl3Port = 3333 ;
int backLog = 5 ; // how many pending connections will hold
if ((socketFd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
ftfLog("setCommunications socket: %s",strerror(errno) );
return -1;
}
fcntl(socketFd, F_SETFL, O_NONBLOCK);
gl3Address.sin_family = AF_INET; /* host byte order */
gl3Address.sin_port = htons(gl3Port); /* short, network byte order */
gl3Address.sin_addr.s_addr = INADDR_ANY;/* automatically fill with my IP */
bzero(&(gl3Address.sin_zero), 8); /* zero the rest of the struct */
if (bind(socketFd, (struct sockaddr *)&gl3Address,
sizeof(struct sockaddr)) == -1) {
ftfLog("setCommunications bind: %s",strerror(errno) );
return -1;
}
if (listen(socketFd, backLog) == -1) {
ftfLog("setCommunications listen: %s",strerror(errno) );
return -1;
}
#endif
return 0 ;
}
//####################################################################
//
//####################################################################
void gl3Conductor::setBField ( float bField ){
for ( int i = 0 ; i < maxEvents ; i++ ) {
event[i].setBField ( bField ) ;
}
}
//####################################################################
//
//####################################################################
void gl3Conductor::setHitProcessing ( int hitPro ){
hitProcessing = hitPro ;
for ( int i = 0 ; i < maxEvents ; i++ ) {
event[i].setHitProcessing ( hitPro ) ;
}
}
//####################################################################
//
//####################################################################
void gl3Conductor::setMaxSectorNForTrackMerging ( int _maxSectorNForTrackMerging ){
maxSectorNForTrackMerging = _maxSectorNForTrackMerging ;
for ( int i = 0 ; i < maxEvents ; i++ ) {
event[i].setMaxSectorNForTrackMerging ( _maxSectorNForTrackMerging ) ;
}
}
//####################################################################
//
//####################################################################
int gl3Conductor::setup ( St_l3_Coordinate_Transformer* _trans,
int maxEventsIn, int maxAlgorithmsIn ) {
//
communicationsFlag = 1 ;
event = 0 ;
algorithm = 0 ;
runNumber = 0 ;
maxTokens = 4096 ;
tokenIndex = new int[maxTokens+1];
maxEvents = maxEventsIn ;
maxAlgorithms = maxAlgorithmsIn ;
event = new gl3Event[maxEvents] ;
summary = new L3_summary[maxEvents];
summaryData = (L3_SUMD*) malloc( maxEvents * (sizeof(L3_SUMD) +
(maxAlgorithms-1)*sizeof(algorithm_data)));
algorithm = new pGl3Algorithm[maxAlgorithms] ;
for (int i=0; i<maxAlgorithms;i++) algorithm[i]=NULL;
nEvents = 0 ;
nAlgorithms = 0 ;
//
for ( int i = 0 ; i < maxTokens ; i++ ) tokenIndex[i] = 0 ;
//
// Setup communications
//
#ifdef GL3ONLINE
if ( communicationsFlag ){
if(setCommunications() )
return -1;
}
#endif
hitProcessing = 0 ;
for ( int i = 0 ; i < maxEvents ; i++ ) {
event[i].setHitProcessing ( hitProcessing ) ;
event[i].setCoordinateTransformer ( _trans ) ;
}
ftfLog("analysis framework set up\n");
return 0 ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::writeHistos ( int maxBytes, char *buffer )
{
gl3HistoContainer* container = (gl3HistoContainer *)buffer ;
ftfLog ( "nHistos %d \n", histoList.size() ) ;
container->runNumber = runNumber ;
container->nHistos = histoList.size();
char* pointer = (char *)&(container->buffer) ;
char* endBuffer = buffer + maxBytes ;
int nBytes ;
int nTotalBytes = 6; // offset coming from gl3HistoContainer
//gl3Histo hTest ;
list<gl3Histo*>::iterator histo;
for(histo=histoList.begin(); histo!=histoList.end(); histo++) {
nBytes = (*histo)->Write ( endBuffer-pointer, pointer ) ;
if ( nBytes <= 0 ) {
ftfLog ( "gl3Container::writeHistos %d byte long buffer is too short \n", maxBytes ) ;
return 0 ;
}
// ftfLog ( "nBytes written %d pointer %x \n", nBytes, pointer ) ;
nTotalBytes += nBytes ;
if ( nTotalBytes > maxBytes ) {
ftfLog ( "gl3Conductor::writeHistos: nTotalBytes %d max %d\n", nTotalBytes, maxBytes ) ;
return -1 ;
}
pointer += nBytes * sizeof(char) ;
}
container->nBytes = nTotalBytes ;
ftfLog ( "gl3Conductor::writeHistos: histos %d Bytes %d \n",
histoList.size(), nTotalBytes ) ;
return nTotalBytes ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::getFreeEventIndex()
{
int freeEventIndex = -1 ;
for ( int i = 0 ; i < maxEvents ; i++ ) {
if ( !(event[i].getBusy() ) ) {
freeEventIndex = i ;
nEvents++ ;
break ;
}
}
return freeEventIndex;
}
//####################################################################
//
//####################################################################
int gl3Conductor::getTokenIndex(int token)
{
if (token < 0 || token > 4096) {
ftfLog("gl3Conductor: token [%d] out of bounds \n", token );
return -1;
}
int index = tokenIndex[token];
if (index < 0 || index >= maxTokens) {
ftfLog("gl3Conductor: event index %d out of bounds \n", token );
return -2;
}
return index;
};
//####################################################################
//
//####################################################################
void gl3Conductor::resetTimer()
{
lastTimeEntry=0;
cpuTimes.clear();
realTimes.clear();
cpuTimes.reserve(5+nAlgorithms);
realTimes.reserve(5+nAlgorithms);
timingMark();
}
void gl3Conductor::timingMark()
{
cpuTimes[lastTimeEntry] = clock();
realTimes[lastTimeEntry] = realcc();
lastTimeEntry++;
}
void gl3Conductor::allocateTimingHistos()
{
#ifdef GL3ONLINE
timingHistos.resize(3+nAlgorithms);
timingHistos[0] = new gl3Histo("time_read_l3",
"Timing: read L3 data",
50,0,300);
timingHistos[1] = new gl3Histo("time_read_trg",
"Timing: read TRG data",
50,0,100);
char hid[30], htitle[100];
for(int i=0; i<nAlgorithms;i++) {
sprintf(hid, "time_alg_%d", i);
sprintf(htitle, "Timing: algorithms %d", i);
timingHistos[2+i] = new gl3Histo(hid, htitle,
60,0,30);
}
timingHistos[2+nAlgorithms] = new gl3Histo("time_total",
"Timing: total",
50,0,300);
for(int i=0;i<timingHistos.size();i++) {
histoList.push_back(timingHistos[i]);
}
#endif
}
void gl3Conductor::fillTimingHistos()
{
#ifdef GL3ONLINE
timingHistos[0]->Fill(double(realTimes[1] - realTimes[0])/ccPerMs);
timingHistos[1]->Fill(double(realTimes[2] - realTimes[1])/ccPerMs);
for(int i=0; i<nAlgorithms;i++) {
timingHistos[2+i]->Fill(double(realTimes[3+i] - realTimes[2+i])/ccPerMs);
}
timingHistos[2+nAlgorithms]->
Fill(double(realTimes[lastTimeEntry-1] - realTimes[0])/ccPerMs);
ftfLog("total time: %f\n",
double(realTimes[lastTimeEntry-1] - realTimes[0])/ccPerMs);
#endif
}
void gl3Conductor::printTiming()
{
for (int i=1; i<lastTimeEntry;i++) {
ftfLog("gl3Conductor: timing step %2d: CPU: %8f real: %8f\n",
i, (double)cpuTimes[i]-cpuTimes[i-1]/CLOCKS_PER_SEC,
(double)(realTimes[i]-realTimes[i-1])/ccPerMs);
}
}
//####################################################################
//
//####################################################################
// void gl3Conductor::printTiming ( ){
// ftfLog ( "********************************\n" ) ;
// ftfLog ( "* gl3 timing *\n" ) ;
// ftfLog ( "* Total: Real %5.0f (ms) \n", 1000.*totalRealTime ) ;
// ftfLog ( "* CPu %5.0f (ms) \n", 1000.*totalCpuTime ) ;
// ftfLog ( "* Algorithm Real Cpu *\n" ) ;
// ftfLog ( "* ( ) ( ) *\n" ) ;
// for ( int i = 0 ; i < nAlgorithms ; i++ ) {
// ftfLog ( "* %d %7.1f %7.1f *\n",
// i, 100.*algorithmRealTime[i]/totalRealTime,
// 100.*algorithmCpuTime[i]/totalCpuTime ) ;
// }
// ftfLog ( "********************************\n" ) ;
// }
| 28.195624
| 131
| 0.486169
|
xiaohaijin
|
236ad59187e5f3802e205398aece605a869c9eb4
| 530
|
cpp
|
C++
|
cpp/src/library.cpp
|
vibhatha/mycythonlib
|
38db78636646b5a14c605556ae561261dc425c8e
|
[
"Apache-2.0"
] | null | null | null |
cpp/src/library.cpp
|
vibhatha/mycythonlib
|
38db78636646b5a14c605556ae561261dc425c8e
|
[
"Apache-2.0"
] | null | null | null |
cpp/src/library.cpp
|
vibhatha/mycythonlib
|
38db78636646b5a14c605556ae561261dc425c8e
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by vibhatha on 3/19/20.
//
#include "../include/library.h"
#include "iostream"
using namespace std;
Library::Library() {
}
void Library::c_multiply(double *array, double multiplier, int m) {
int i, j ;
int index = 0 ;
for (i = 0; i < m; i++) {
array[index] = array[index] * multiplier ;
index ++;
}
return ;
}
void Library::printArray(double *array, int length) {
for (int i = 0; i < length; ++i) {
cout << array[i] << " ";
}
cout << endl;
}
| 16.060606
| 67
| 0.532075
|
vibhatha
|
236ae6d7f99c44649c72258be304280ce3c1dadb
| 2,025
|
cpp
|
C++
|
SAEEngineCore/submodules/object/tests/build_test/test.cpp
|
SAEEngine/SAEEngineCore
|
bede6c973caf7c4526ac5539ec2c9917139f2067
|
[
"MIT"
] | 2
|
2020-10-31T09:59:36.000Z
|
2020-11-01T04:22:56.000Z
|
SAEEngineCore/submodules/object/tests/build_test/test.cpp
|
SAEEngine/SAEEngineCore
|
bede6c973caf7c4526ac5539ec2c9917139f2067
|
[
"MIT"
] | null | null | null |
SAEEngineCore/submodules/object/tests/build_test/test.cpp
|
SAEEngine/SAEEngineCore
|
bede6c973caf7c4526ac5539ec2c9917139f2067
|
[
"MIT"
] | null | null | null |
/*
Return GOOD_TEST (0) if the test was passed.
Return anything other than GOOD_TEST (0) if the test was failed.
*/
// Common standard library headers
#include <cassert>
/**
* @brief Return this from main if the test was passsed.
*/
constexpr static inline int GOOD_TEST = 0;
// Include the headers you need for testing here
#include <SAEEngineCore_Object.h>
#include <SAEEngineCore_Environment.h>
#include <SAEEngineCore_glObject.h>
#include <chrono>
#include <thread>
#include <fstream>
#include <sstream>
#include <string>
#include <array>
#include <iostream>
#include <cmath>
using namespace sae::engine::core;
class ElementList : public GFXView
{
public:
void refresh() override
{
if (this->child_count() == 0)
return;
auto _x = this->bounds().left();
auto _w = this->bounds().width();
auto _eachWidth = (_w - ((this->child_count() - 1) * this->margin_)) / (this->child_count());
for (auto& o : this->children())
{
auto& _b = o->bounds();
_b.left() = _x;
_b.right() = _b.left() + _eachWidth;
_b.top() = this->bounds().top();
_b.bottom() = this->bounds().bottom();
_x += _eachWidth + this->margin_;
};
};
ElementList(GFXContext* _context, Rect _r, pixels_t _margin = 5_px) :
GFXView{ _context, _r }, margin_{ _margin }
{};
private:
pixels_t margin_ = 0;
};
int main(int argc, char* argv[], char* envp[])
{
GFXContext _context{ nullptr, Rect{{ 0_px, 0_px}, { 1600_px, 900_px } } };
auto _listB = _context.bounds();
auto _listPtr = new ElementList{ &_context, _listB, 0_px };
_listPtr->emplace(new GFXObject{ {} });
_listPtr->emplace(new GFXObject{ {} });
_listPtr->emplace(new GFXObject{ {} });
_listPtr->emplace(new GFXObject{ {} });
_context.emplace(_listPtr);
_context.refresh();
_listB.right() = _listB.left() + 600_px;
auto _list2Ptr = new ElementList{ &_context, _listB, 0_px };
_list2Ptr->emplace(new GFXObject{ {} });
_list2Ptr->emplace(new GFXObject{ {} });
_context.emplace(_list2Ptr);
_context.refresh();
return GOOD_TEST;
};
| 22.252747
| 95
| 0.669136
|
SAEEngine
|
2370c744e4e0262381f18133e5f777dfa220f054
| 12,069
|
cpp
|
C++
|
classes/CSocket.cpp
|
clockworkengineer/Antikythera_mechanism
|
572dc5c83303548134adf8325f77c795c02481f2
|
[
"MIT"
] | 1
|
2021-03-04T07:04:50.000Z
|
2021-03-04T07:04:50.000Z
|
classes/CSocket.cpp
|
clockworkengineer/Antikythera_mechanism
|
572dc5c83303548134adf8325f77c795c02481f2
|
[
"MIT"
] | null | null | null |
classes/CSocket.cpp
|
clockworkengineer/Antikythera_mechanism
|
572dc5c83303548134adf8325f77c795c02481f2
|
[
"MIT"
] | 1
|
2021-11-29T08:24:52.000Z
|
2021-11-29T08:24:52.000Z
|
//
// Class: CSocket
//
// Description: Class for connecting to / listening for connections from remote peers
// and the reading/writing of data using sockets. It supports both plain and TLS/SSL
// connections and is implemented using BOOST:ASIO synchronous API calls. At present it
// only has basic TLS/SSL support and is geared more towards client support but this may
// change in future.
//
// Dependencies: C20++ - Language standard features used.
// BOOST ASIO - Used to talk to FTP server.
//
// =================
// CLASS DEFINITIONS
// =================
#include "CSocket.hpp"
// ====================
// CLASS IMPLEMENTATION
// ====================
//
// C++ STL
//
#include <iostream>
#include <fstream>
// =======
// IMPORTS
// =======
// =========
// NAMESPACE
// =========
namespace Antik::Network
{
// ===========================
// PRIVATE TYPES AND CONSTANTS
// ===========================
// ==========================
// PUBLIC TYPES AND CONSTANTS
// ==========================
// ========================
// PRIVATE STATIC VARIABLES
// ========================
// =======================
// PUBLIC STATIC VARIABLES
// =======================
// ===============
// PRIVATE METHODS
// ===============
//
// Socket listener thread method for incoming connections. At present it listens
// on a random port but sets m_hostPort to its value. The connected socket is created
// local and moved to m_socket on success.
//
void CSocket::connectionListener()
{
try
{
boost::asio::ip::tcp::acceptor acceptor(m_ioService, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 0));
m_hostPort = std::to_string(acceptor.local_endpoint().port());
m_isListenThreadRunning = true;
std::unique_ptr<SSLSocket> socket = std::make_unique<SSLSocket>(m_ioService, *m_sslContext);
if (!socket)
{
throw std::runtime_error("Could not create socket.");
}
acceptor.accept(socket->next_layer(), m_socketError);
if (m_socketError)
{
throw std::runtime_error(m_socketError.message());
}
m_socket = std::move(socket);
}
catch (const std::exception &e)
{
m_thrownException = std::current_exception();
}
m_isListenThreadRunning = false;
}
// ==============
// PUBLIC METHODS
// ==============
//
// Cleanup after socket connection. This includes stopping any unused listener
// thread and closing the socket if still open. Note: if the thread is still waiting
// for a connect it is woken up with a fake connect.
//
void CSocket::cleanup()
{
try
{
if (m_isListenThreadRunning && m_socketListenThread)
{
m_isListenThreadRunning = false;
try
{
boost::asio::ip::tcp::socket socket{m_ioService};
boost::asio::ip::tcp::resolver::query query(m_hostAddress, m_hostPort);
boost::asio::connect(socket, m_ioQueryResolver.resolve(query));
socket.close();
}
catch (std::exception &e)
{
throw std::runtime_error("Could not wake listener thread with fake connect.");
}
m_socketListenThread->join();
}
close();
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Listen for connections
//
void CSocket::listenForConnection()
{
try
{
// Start connection listener thread and wait until its listening
m_socketListenThread = std::make_unique<std::thread>(&CSocket::connectionListener, this);
while (!m_isListenThreadRunning)
{
continue;
}
if (m_thrownException)
{
std::rethrow_exception(m_thrownException);
}
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Wait until a socket is connected.
//
void CSocket::waitUntilConnected()
{
try
{
// Listener thread is running (wait for it to finish)
if (m_socketListenThread)
{
m_socketListenThread->join();
}
// TLS handshake if SSL enabled
tlsHandshake();
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Connect to a given host and port.The connecting socket is created
// local and moved to m_socket on success.
//
void CSocket::connect()
{
try
{
std::unique_ptr<SSLSocket> socket = std::make_unique<SSLSocket>(m_ioService, *m_sslContext);
if (!socket)
{
throw std::runtime_error("Could not create socket.");
}
boost::asio::ip::tcp::resolver::query query{m_hostAddress, m_hostPort};
socket->next_layer().connect(*m_ioQueryResolver.resolve(query), m_socketError);
if (m_socketError)
{
throw std::runtime_error(m_socketError.message());
}
m_socket = std::move(socket);
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Read data from socket into buffer
//
size_t CSocket::read(char *readBuffer, size_t bufferLength)
{
try
{
size_t bytesRead{0};
// No socket present
if (!m_socket)
{
throw std::logic_error("No socket present.");
}
// Read data
if (m_sslActive)
{
bytesRead = m_socket->read_some(boost::asio::buffer(readBuffer, bufferLength), m_socketError);
}
else
{
bytesRead = m_socket->next_layer().read_some(boost::asio::buffer(readBuffer, bufferLength), m_socketError);
}
// Signal any non end of file error
if (m_socketError && m_socketError != boost::asio::error::eof)
{
throw std::runtime_error(m_socketError.message());
}
return (bytesRead);
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Write data to socket
//
size_t CSocket::write(const char *writeBuffer, size_t writeLength)
{
try
{
size_t bytesWritten{0};
// No socket present
if (!m_socket)
{
throw std::logic_error("No socket present.");
}
// Write data
if (m_sslActive)
{
bytesWritten = m_socket->write_some(boost::asio::buffer(writeBuffer, writeLength), m_socketError);
}
else
{
bytesWritten = m_socket->next_layer().write_some(boost::asio::buffer(writeBuffer, writeLength), m_socketError);
}
// Signal any non end of file error
if (m_socketError && m_socketError != boost::asio::error::eof)
{
throw std::runtime_error(m_socketError.message());
}
return (bytesWritten);
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Perform TLS handshake if SSL enabled
//
void CSocket::tlsHandshake()
{
try
{
// If SSL not enabled return
if (!m_sslEnabled)
{
return;
}
// No socket present
if (!m_socket)
{
throw std::logic_error("No socket present.");
}
m_socket->handshake(SSLSocket::client, m_socketError);
if (m_socketError)
{
throw std::runtime_error(m_socketError.message());
}
m_sslActive = true;
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Closedown any running SSL and close socket. Move m_socket to local
// socket and close it down.
//
void CSocket::close()
{
try
{
std::unique_ptr<SSLSocket> socket{std::move(m_socket)};
// Socket exists and is open
if (socket && socket->next_layer().is_open())
{
// Shutdown TLS
if (m_sslActive)
{
m_sslActive = false;
socket->shutdown(m_socketError);
}
// Close socket
socket->next_layer().close(m_socketError);
if (m_socketError)
{
throw std::runtime_error(m_socketError.message());
}
}
// Remove any listen thread
if (m_socketListenThread)
{
m_socketListenThread.reset();
}
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Set SSL context for the TLS version se
//
void CSocket::setTLSVersion(TLSVerion version)
{
m_tlsVersion = version;
switch (m_tlsVersion)
{
case TLSVerion::v1_0:
m_sslContext = std::make_unique<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv1);
break;
case TLSVerion::v1_1:
m_sslContext = std::make_unique<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv11);
break;
case TLSVerion::v1_2:
m_sslContext = std::make_unique<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv12);
break;
}
}
//
// Work out ip address for local machine. This is quite difficult to achieve but
// this is the best code i have seen for doing it. It just tries to connect to
// google.com with a udp connect to get the local socket endpoint.
// Note: Fall back of localhost on failure.
//
std::string CSocket::localIPAddress()
{
static std::string localIPAddress;
if (localIPAddress.empty())
{
try
{
boost::asio::io_service ioService;
boost::asio::ip::udp::resolver resolver(ioService);
boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), "google.com", "");
boost::asio::ip::udp::socket socket(ioService);
socket.connect(*resolver.resolve(query));
localIPAddress = socket.local_endpoint().address().to_string();
socket.close();
}
catch (std::exception &e)
{
return ("127.0.0.1");
}
}
return (localIPAddress);
}
// ============================
// CLASS PRIVATE DATA ACCESSORS
// ============================
void CSocket::setSslEnabled(bool sslEnabled)
{
m_sslEnabled = sslEnabled;
}
bool CSocket::isSslEnabled() const
{
return m_sslEnabled;
}
void CSocket::setHostAddress(std::string hostAddress)
{
m_hostAddress = hostAddress;
}
std::string CSocket::getHostAddress() const
{
return m_hostAddress;
}
void CSocket::setHostPort(std::string hostPort)
{
m_hostPort = hostPort;
}
std::string CSocket::getHostPort() const
{
return m_hostPort;
}
} // namespace Antik::Network
| 30.946154
| 128
| 0.50029
|
clockworkengineer
|
2372772d8a2edf2c0a7646a0368031bad79ae542
| 3,752
|
cpp
|
C++
|
SCLT/Objects/Material/MaterialBRDF.cpp
|
chicio/Multispectral-Ray-tracing
|
ea5b399770eddd1927aae8a8ae4640dead42c48c
|
[
"MIT"
] | 95
|
2016-05-05T10:46:49.000Z
|
2021-12-20T12:51:41.000Z
|
SCLT/Objects/Material/MaterialBRDF.cpp
|
chicio/Multispectral-Ray-tracing
|
ea5b399770eddd1927aae8a8ae4640dead42c48c
|
[
"MIT"
] | 1
|
2021-12-06T03:21:32.000Z
|
2021-12-06T03:21:32.000Z
|
SCLT/Objects/Material/MaterialBRDF.cpp
|
chicio/Multispectral-Ray-tracing
|
ea5b399770eddd1927aae8a8ae4640dead42c48c
|
[
"MIT"
] | 8
|
2017-03-12T03:04:08.000Z
|
2022-03-17T01:27:41.000Z
|
//
// MaterialBRDF.cpp
// Spectral Clara Lux tracer
//
// Created by Fabrizio Duroni on 23/11/15.
// Copyright © 2015 Fabrizio Duroni. All rights reserved.
//
#include "pch.h"
#include "MaterialBRDF.hpp"
#include "Illuminant.hpp"
Spectrum<constant::spectrumSamples> MaterialBRDF::f(const Vector3D& wi,
const Vector3D& wo,
const Intersection& intersection) const {
Spectrum<constant::spectrumSamples> f(0.0f);
for(std::vector<BRDF *>::size_type i = 0; i != brdfs.size(); i++) {
f = f + brdfs[i]->f(wi, wo, intersection);
}
return f;
}
Spectrum<constant::spectrumSamples> MaterialBRDF::samplef(Vector3D* wi,
const Vector3D& wo,
const Intersection& intersection,
const BRDFType type) const {
Spectrum<constant::spectrumSamples> f(0.0f);
for(std::vector<BRDF *>::size_type i = 0; i != brdfs.size(); i++) {
if(brdfs[i]->brdfType == type) {
f = f + brdfs[i]->samplef(wi, wo, intersection);
}
}
return f;
}
float MaterialBRDF::pdf(const Vector3D& wi,
const Vector3D& wo,
const Intersection& intersection,
const BRDFType type) const {
for(std::vector<BRDF *>::size_type i = 0; i != brdfs.size(); i++) {
if(brdfs[i]->brdfType == type) {
return brdfs[i]->pdf(wi, wo, intersection);
}
}
return 0.0F;
}
Material* MaterialBRDF::emissiveMaterial(Spectrum<constant::spectrumSamples> illuminant) {
MaterialBRDF* emissiveMaterial = new MaterialBRDF();
emissiveMaterial->le = illuminant;
emissiveMaterial->brdfs.push_back(new Lambertian(Spectrum<constant::spectrumSamples>(0.0f)));
return emissiveMaterial;
}
Material* MaterialBRDF::matteMaterial(Spectrum<constant::spectrumSamples> spectrum) {
//Matte material.
MaterialBRDF* matteMaterial = new MaterialBRDF();
matteMaterial->brdfs.push_back(new Lambertian(spectrum));
return matteMaterial;
}
Material* MaterialBRDF::matteMaterial(Spectrum<constant::spectrumSamples> spectrum, float degree) {
//Matte material.
MaterialBRDF* matteMaterial = new MaterialBRDF();
matteMaterial->brdfs.push_back(new OrenNayar (spectrum, degree));
return matteMaterial;
}
Material* MaterialBRDF::plasticMaterial(Spectrum<constant::spectrumSamples> spectrumDiffuse,
Spectrum<constant::spectrumSamples> spectrumSpecular,
float roughness) {
//Plastic material.
MaterialBRDF* plasticMaterial = new MaterialBRDF();
plasticMaterial->brdfs.push_back(new Lambertian (spectrumDiffuse));
plasticMaterial->brdfs.push_back(new TorranceSparrow(spectrumSpecular, 1.5, roughness));
return plasticMaterial;
}
Material* MaterialBRDF::glassMaterial() {
MaterialBRDF* mirrorMaterial = new MaterialBRDF();
mirrorMaterial->brdfs.push_back(new SpecularReflection(Spectrum<constant::spectrumSamples>(1.0f), 1.5));
mirrorMaterial->brdfs.push_back(new SpecularTransmission(Spectrum<constant::spectrumSamples>(1.0f), 1.5));
return mirrorMaterial;
}
Material* MaterialBRDF::measuredMaterial(const char *filename, bool interpolated) {
MaterialBRDF* measuredMaterial = new MaterialBRDF();
measuredMaterial->brdfs.push_back(new Measured(filename, interpolated));
return measuredMaterial;
}
| 32.344828
| 110
| 0.611141
|
chicio
|
2373bfefa0e0944e7f73099ae42a8648da18b3b6
| 2,085
|
cpp
|
C++
|
src/Log.cpp
|
wibbe/zum-cpp
|
0fc753cac5f577eb56eaa9e8330f466b2cdaa38c
|
[
"MIT"
] | null | null | null |
src/Log.cpp
|
wibbe/zum-cpp
|
0fc753cac5f577eb56eaa9e8330f466b2cdaa38c
|
[
"MIT"
] | null | null | null |
src/Log.cpp
|
wibbe/zum-cpp
|
0fc753cac5f577eb56eaa9e8330f466b2cdaa38c
|
[
"MIT"
] | null | null | null |
#include "Log.h"
#include "bx/platform.h"
#include <cstdlib>
#include <cstdio>
static std::string logFile()
{
#if BX_PLATFORM_LINUX || BX_PLATFORM_OSX
static const std::string LOG_FILE = "/.zumlog";
const char * home = getenv("HOME");
if (home)
return std::string(home) + LOG_FILE;
else
return "~" + LOG_FILE;
#else
return "log.txt";
#endif
}
void clearLog()
{
FILE * file = fopen(logFile().c_str(), "w");
fclose(file);
}
void _logValue(FILE * file, char value)
{
fprintf(file, "%c", value);
fprintf(stderr, "%c", value);
}
void _logValue(FILE * file, int value)
{
fprintf(file, "%d", value);
fprintf(stderr, "%d", value);
}
void _logValue(FILE * file, uint32_t value)
{
fprintf(file, "%d", value);
fprintf(stderr, "%d", value);
}
void _logValue(FILE * file, long value)
{
fprintf(file, "%ld", value);
fprintf(stderr, "%ld", value);
}
void _logValue(FILE * file, long long int value)
{
fprintf(file, "%lld", value);
fprintf(stderr, "%lld", value);
}
void _logValue(FILE * file, float value)
{
fprintf(file, "%f", value);
fprintf(stderr, "%f", value);
}
void _logValue(FILE * file, double value)
{
fprintf(file, "%f", value);
fprintf(stderr, "%f", value);
}
void _logValue(FILE * file, const char * value)
{
fprintf(file, "%s", value);
fprintf(stderr, "%s", value);
}
void _logValue(FILE * file, Str const& value)
{
fprintf(file, "%s", value.utf8().c_str());
fprintf(stderr, "%s", value.utf8().c_str());
}
void _logValue(FILE * file, std::string const& value)
{
fprintf(file, "%s", value.c_str());
fprintf(stderr, "%s", value.c_str());
}
FILE * _logBegin()
{
return fopen(logFile().c_str(), "at");
}
void _logEnd(FILE * file)
{
_logValue(file, "\n");
fclose(file);
fflush(stderr);
}
void logInfo(Str const& message)
{
FILE * file = fopen(logFile().c_str(), "at");
fprintf(file, "INFO: %s\n", message.utf8().c_str());
fclose(file);
}
void logError(Str const& message)
{
FILE * file = fopen(logFile().c_str(), "at");
fprintf(file, "ERROR: %s\n", message.utf8().c_str());
fclose(file);
}
| 18.289474
| 55
| 0.62446
|
wibbe
|
2374eece4b5cb807686524d494c2f570d888704c
| 7,577
|
hpp
|
C++
|
include/yamail/resource_pool/async/detail/queue.hpp
|
JonasProgrammer/resource_pool
|
5b8e0d542e40805b187af7b94770e95f292379c9
|
[
"MIT"
] | 17
|
2018-12-02T10:16:37.000Z
|
2022-02-25T22:58:35.000Z
|
include/yamail/resource_pool/async/detail/queue.hpp
|
JonasProgrammer/resource_pool
|
5b8e0d542e40805b187af7b94770e95f292379c9
|
[
"MIT"
] | 27
|
2017-12-25T14:54:38.000Z
|
2021-01-28T12:30:10.000Z
|
include/yamail/resource_pool/async/detail/queue.hpp
|
JonasProgrammer/resource_pool
|
5b8e0d542e40805b187af7b94770e95f292379c9
|
[
"MIT"
] | 5
|
2017-12-25T14:41:52.000Z
|
2022-03-26T06:22:22.000Z
|
#ifndef YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP
#define YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP
#include <yamail/resource_pool/error.hpp>
#include <yamail/resource_pool/time_traits.hpp>
#include <boost/asio/executor.hpp>
#include <boost/asio/post.hpp>
#include <algorithm>
#include <list>
#include <map>
#include <mutex>
#include <unordered_map>
namespace yamail {
namespace resource_pool {
namespace async {
namespace asio = boost::asio;
namespace detail {
using clock = std::chrono::steady_clock;
template <class Handler>
class expired_handler {
Handler handler;
public:
using executor_type = std::decay_t<decltype(asio::get_associated_executor(handler))>;
expired_handler() = default;
template <class HandlerT>
explicit expired_handler(HandlerT&& handler,
std::enable_if_t<!std::is_same_v<std::decay_t<HandlerT>, expired_handler>, void*> = nullptr)
: handler(std::forward<HandlerT>(handler)) {
static_assert(std::is_same_v<std::decay_t<HandlerT>, Handler>, "HandlerT is not Handler");
}
void operator ()() {
handler(make_error_code(error::get_resource_timeout));
}
void operator ()() const {
handler(make_error_code(error::get_resource_timeout));
}
auto get_executor() const noexcept {
return asio::get_associated_executor(handler);
}
};
template <class Handler>
expired_handler(Handler&&) -> expired_handler<std::decay_t<Handler>>;
template <class Value, class IoContext>
struct queued_value {
Value request;
IoContext& io_context;
};
template <class Value, class Mutex, class IoContext, class Timer>
class queue : public std::enable_shared_from_this<queue<Value, Mutex, IoContext, Timer>> {
public:
using value_type = Value;
using io_context_t = IoContext;
using timer_t = Timer;
using queued_value_t = queued_value<value_type, io_context_t>;
queue(std::size_t capacity) : _capacity(capacity) {}
queue(const queue&) = delete;
queue(queue&&) = delete;
std::size_t capacity() const noexcept { return _capacity; }
std::size_t size() const noexcept;
bool empty() const noexcept;
const timer_t& timer(io_context_t& io_context);
bool push(io_context_t& io_context, time_traits::duration wait_duration, value_type&& request);
boost::optional<queued_value_t> pop();
private:
using mutex_t = Mutex;
using lock_guard = std::lock_guard<mutex_t>;
struct expiring_request {
using list = std::list<expiring_request>;
using list_it = typename list::iterator;
using multimap = std::multimap<time_traits::time_point, expiring_request*>;
using multimap_it = typename multimap::iterator;
io_context_t* io_context;
queue::value_type request;
list_it order_it;
multimap_it expires_at_it;
expiring_request() = default;
};
using request_multimap_value = typename expiring_request::multimap::value_type;
using timers_map = typename std::unordered_map<const io_context_t*, timer_t>;
const std::size_t _capacity;
mutable mutex_t _mutex;
typename expiring_request::list _ordered_requests_pool;
typename expiring_request::list _ordered_requests;
typename expiring_request::multimap _expires_at_requests;
timers_map _timers;
bool fit_capacity() const { return _expires_at_requests.size() < _capacity; }
void cancel(boost::system::error_code ec, time_traits::time_point expires_at);
void update_timer();
timer_t& get_timer(io_context_t& io_context);
};
template <class V, class M, class I, class T>
std::size_t queue<V, M, I, T>::size() const noexcept {
const lock_guard lock(_mutex);
return _expires_at_requests.size();
}
template <class V, class M, class I, class T>
bool queue<V, M, I, T>::empty() const noexcept {
const lock_guard lock(_mutex);
return _ordered_requests.empty();
}
template <class V, class M, class I, class T>
const typename queue<V, M, I, T>::timer_t& queue<V, M, I, T>::timer(io_context_t& io_context) {
const lock_guard lock(_mutex);
return get_timer(io_context);
}
template <class V, class M, class I, class T>
bool queue<V, M, I, T>::push(io_context_t& io_context, time_traits::duration wait_duration, value_type&& request) {
const lock_guard lock(_mutex);
if (!fit_capacity()) {
return false;
}
if (_ordered_requests_pool.empty()) {
_ordered_requests_pool.emplace_back();
}
const auto order_it = _ordered_requests_pool.begin();
_ordered_requests.splice(_ordered_requests.end(), _ordered_requests_pool, order_it);
expiring_request& req = *order_it;
req.io_context = std::addressof(io_context);
req.request = std::move(request);
req.order_it = order_it;
const auto expires_at = time_traits::add(time_traits::now(), wait_duration);
req.expires_at_it = _expires_at_requests.insert(std::make_pair(expires_at, &req));
update_timer();
return true;
}
template <class V, class M, class I, class T>
boost::optional<typename queue<V, M, I, T>::queued_value_t> queue<V, M, I, T>::pop() {
const lock_guard lock(_mutex);
if (_ordered_requests.empty()) {
return {};
}
const auto ordered_it = _ordered_requests.begin();
expiring_request& req = *ordered_it;
queued_value_t result {std::move(req.request), *req.io_context};
_expires_at_requests.erase(req.expires_at_it);
_ordered_requests_pool.splice(_ordered_requests_pool.begin(), _ordered_requests, ordered_it);
update_timer();
return { std::move(result) };
}
template <class V, class M, class I, class T>
void queue<V, M, I, T>::cancel(boost::system::error_code ec, time_traits::time_point expires_at) {
if (ec) {
return;
}
const lock_guard lock(_mutex);
const auto begin = _expires_at_requests.begin();
const auto end = _expires_at_requests.upper_bound(expires_at);
std::for_each(begin, end, [&] (request_multimap_value& v) {
const auto req = v.second;
asio::post(*req->io_context, expired_handler(std::move(req->request)));
_ordered_requests_pool.splice(_ordered_requests_pool.begin(), _ordered_requests, req->order_it);
});
_expires_at_requests.erase(_expires_at_requests.begin(), end);
update_timer();
}
template <class V, class M, class I, class T>
void queue<V, M, I, T>::update_timer() {
using timers_map_value = typename timers_map::value_type;
if (_expires_at_requests.empty()) {
std::for_each(_timers.begin(), _timers.end(), [] (timers_map_value& v) { v.second.cancel(); });
_timers.clear();
return;
}
const auto earliest_expire = _expires_at_requests.begin();
const auto expires_at = earliest_expire->first;
auto& timer = get_timer(*earliest_expire->second->io_context);
timer.expires_at(expires_at);
std::weak_ptr<queue> weak(this->shared_from_this());
timer.async_wait([weak, expires_at] (boost::system::error_code ec) {
if (const auto locked = weak.lock()) {
locked->cancel(ec, expires_at);
}
});
}
template <class V, class M, class I, class T>
typename queue<V, M, I, T>::timer_t& queue<V, M, I, T>::get_timer(io_context_t& io_context) {
auto it = _timers.find(&io_context);
if (it != _timers.end()) {
return it->second;
}
return _timers.emplace(&io_context, timer_t(io_context)).first->second;
}
} // namespace detail
} // namespace async
} // namespace resource_pool
} // namespace yamail
#endif // YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP
| 33.526549
| 115
| 0.700937
|
JonasProgrammer
|
2378fd7fec6d7510bbff013b9a0ea4b2b7f215bd
| 268
|
cpp
|
C++
|
src/portaudiohandler.cpp
|
aparks5/synthcastle
|
ebb542d014c87a11a83b9e212668eca75a333fbf
|
[
"MIT"
] | 2
|
2021-12-20T03:20:05.000Z
|
2021-12-28T16:15:20.000Z
|
src/portaudiohandler.cpp
|
aparks5/synthcastle
|
ebb542d014c87a11a83b9e212668eca75a333fbf
|
[
"MIT"
] | 69
|
2021-08-30T13:09:01.000Z
|
2022-01-15T17:41:40.000Z
|
src/portaudiohandler.cpp
|
aparks5/synthcastle
|
ebb542d014c87a11a83b9e212668eca75a333fbf
|
[
"MIT"
] | null | null | null |
/// Copyright(c) 2021. Anthony Parks. All rights reserved.
#include "portaudiohandler.h"
PortAudioHandler::PortAudioHandler()
: m_result(Pa_Initialize())
{
}
PortAudioHandler::~PortAudioHandler()
{
if (m_result == paNoError)
{
Pa_Terminate();
}
}
| 17.866667
| 59
| 0.682836
|
aparks5
|
2379857d0af4607a620b76853af3c51e2d41dcac
| 1,173
|
cpp
|
C++
|
Source/Trickery/Test.cpp
|
D4rk1n/ModernProblemsModernSolutions
|
bb8f96f9701fe3eee3b5a513b42575a3d0075bb4
|
[
"Apache-2.0"
] | null | null | null |
Source/Trickery/Test.cpp
|
D4rk1n/ModernProblemsModernSolutions
|
bb8f96f9701fe3eee3b5a513b42575a3d0075bb4
|
[
"Apache-2.0"
] | null | null | null |
Source/Trickery/Test.cpp
|
D4rk1n/ModernProblemsModernSolutions
|
bb8f96f9701fe3eee3b5a513b42575a3d0075bb4
|
[
"Apache-2.0"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "Test.h"
// Sets default values for this component's properties
UTest::UTest()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UTest::BeginPlay()
{
Super::BeginPlay();
Owner = GetOwner();
POpen = GetWorld()->GetFirstPlayerController()->GetPawn();
// ...
}
// Called every frame
void UTest::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
if (AOpen&&PPlate)
{
//UE_LOG(LogTemp, Warning, TEXT("lol "));
if (PPlate->IsOverlappingActor(AOpen)) {
UE_LOG(LogTemp, Warning, TEXT("Actor that opens "))
FRotator r(0, -50, 0);
Owner->SetActorRotation(r);
}
if (PPlate->IsOverlappingActor(POpen)) {
UE_LOG(LogTemp, Warning, TEXT("Pawn that opens "))
FRotator r(0, -50, 0);
Owner->SetActorRotation(r);
}
}
// ...
}
| 24.4375
| 121
| 0.700767
|
D4rk1n
|
237cc3acae3061fd145e90a3004595c0a35619b0
| 354
|
hpp
|
C++
|
include/toy/gadget/IntToHexChar.hpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | 4
|
2017-07-06T22:18:41.000Z
|
2021-05-24T21:28:37.000Z
|
include/toy/gadget/IntToHexChar.hpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | null | null | null |
include/toy/gadget/IntToHexChar.hpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | 1
|
2020-08-02T13:00:38.000Z
|
2020-08-02T13:00:38.000Z
|
#pragma once
#include "toy/Standard.hpp"
#include "toy/gadget/Export.hpp"
namespace toy{
namespace gadget{
// 1 -> '1'
// 2 -> '2'
// 11 -> 'b'
// 15 -> 'f'
// 16 -> [error]
TOY_API_GADGET extern char IntToHexChar(int);
// 1 -> '1'
// 2 -> '2'
// 11 -> 'B'
// 15 -> 'F'
// 16 -> [error]
TOY_API_GADGET extern char IntToHexChar_Capital(int);
}}
| 14.16
| 53
| 0.573446
|
ToyAuthor
|
237fc3ac31b5b7e05509b8d16e2810e96459d81d
| 278
|
hpp
|
C++
|
package/config/config/config_config.hpp
|
mambaru/wfc_core
|
0c3e7fba82a9bb1580582968efae02ef7fabc87a
|
[
"MIT"
] | null | null | null |
package/config/config/config_config.hpp
|
mambaru/wfc_core
|
0c3e7fba82a9bb1580582968efae02ef7fabc87a
|
[
"MIT"
] | 5
|
2019-12-06T01:01:01.000Z
|
2021-04-20T21:16:34.000Z
|
package/config/config/config_config.hpp
|
mambaru/wfc_core
|
0c3e7fba82a9bb1580582968efae02ef7fabc87a
|
[
"MIT"
] | null | null | null |
//
// Author: Vladimir Migashko <migashko@gmail.com>, (C) 2013-2018
//
// Copyright: See COPYING file that comes with this distribution
//
#pragma once
namespace wfc{ namespace core{
struct config_config
{
bool reload_sighup = false;
time_t reload_changed_ms = 0;
};
}}
| 15.444444
| 64
| 0.715827
|
mambaru
|
23814363269462e69bd0dc675502639a6f45b87f
| 6,427
|
cc
|
C++
|
chrome/browser/sync/engine/build_commit_command.cc
|
rwatson/chromium-capsicum
|
b03da8e897f897c6ad2cda03ceda217b760fd528
|
[
"BSD-3-Clause"
] | 11
|
2015-03-20T04:08:08.000Z
|
2021-11-15T15:51:36.000Z
|
chrome/browser/sync/engine/build_commit_command.cc
|
rwatson/chromium-capsicum
|
b03da8e897f897c6ad2cda03ceda217b760fd528
|
[
"BSD-3-Clause"
] | null | null | null |
chrome/browser/sync/engine/build_commit_command.cc
|
rwatson/chromium-capsicum
|
b03da8e897f897c6ad2cda03ceda217b760fd528
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/engine/build_commit_command.h"
#include <set>
#include <string>
#include <vector>
#include "chrome/browser/sync/engine/syncer_proto_util.h"
#include "chrome/browser/sync/engine/syncer_util.h"
#include "chrome/browser/sync/sessions/sync_session.h"
#include "chrome/browser/sync/syncable/syncable.h"
#include "chrome/browser/sync/syncable/syncable_changes_version.h"
#include "chrome/browser/sync/util/sync_types.h"
using std::set;
using std::string;
using std::vector;
using syncable::ExtendedAttribute;
using syncable::Id;
using syncable::MutableEntry;
namespace browser_sync {
using sessions::SyncSession;
BuildCommitCommand::BuildCommitCommand() {}
BuildCommitCommand::~BuildCommitCommand() {}
void BuildCommitCommand::AddExtensionsActivityToMessage(
SyncSession* session, CommitMessage* message) {
const ExtensionsActivityMonitor::Records& records =
session->extensions_activity();
for (ExtensionsActivityMonitor::Records::const_iterator it = records.begin();
it != records.end(); ++it) {
sync_pb::CommitMessage_ChromiumExtensionsActivity* activity_message =
message->add_extensions_activity();
activity_message->set_extension_id(it->second.extension_id);
activity_message->set_bookmark_writes_since_last_commit(
it->second.bookmark_write_count);
}
}
void BuildCommitCommand::ExecuteImpl(SyncSession* session) {
ClientToServerMessage message;
message.set_share(session->context()->account_name());
message.set_message_contents(ClientToServerMessage::COMMIT);
CommitMessage* commit_message = message.mutable_commit();
commit_message->set_cache_guid(
session->write_transaction()->directory()->cache_guid());
AddExtensionsActivityToMessage(session, commit_message);
const vector<Id>& commit_ids = session->status_controller()->commit_ids();
for (size_t i = 0; i < commit_ids.size(); i++) {
Id id = commit_ids[i];
SyncEntity* sync_entry =
static_cast<SyncEntity*>(commit_message->add_entries());
sync_entry->set_id(id);
MutableEntry meta_entry(session->write_transaction(),
syncable::GET_BY_ID,
id);
CHECK(meta_entry.good());
// This is the only change we make to the entry in this function.
meta_entry.Put(syncable::SYNCING, true);
string name = meta_entry.Get(syncable::NON_UNIQUE_NAME);
CHECK(!name.empty()); // Make sure this isn't an update.
sync_entry->set_name(name);
// Set the non_unique_name. If we do, the server ignores
// the |name| value (using |non_unique_name| instead), and will return
// in the CommitResponse a unique name if one is generated.
// We send both because it may aid in logging.
sync_entry->set_non_unique_name(name);
// Deleted items with negative parent ids can be a problem so we set the
// parent to 0. (TODO(sync): Still true in protocol?).
Id new_parent_id;
if (meta_entry.Get(syncable::IS_DEL) &&
!meta_entry.Get(syncable::PARENT_ID).ServerKnows()) {
new_parent_id = session->write_transaction()->root_id();
} else {
new_parent_id = meta_entry.Get(syncable::PARENT_ID);
}
sync_entry->set_parent_id(new_parent_id);
// TODO(sync): Investigate all places that think transactional commits
// actually exist.
//
// This is the only logic we'll need when transactional commits are moved
// to the server. If our parent has changes, send up the old one so the
// server can correctly deal with multiple parents.
if (new_parent_id != meta_entry.Get(syncable::SERVER_PARENT_ID) &&
0 != meta_entry.Get(syncable::BASE_VERSION) &&
syncable::CHANGES_VERSION != meta_entry.Get(syncable::BASE_VERSION)) {
sync_entry->set_old_parent_id(meta_entry.Get(syncable::SERVER_PARENT_ID));
}
int64 version = meta_entry.Get(syncable::BASE_VERSION);
if (syncable::CHANGES_VERSION == version || 0 == version) {
// If this CHECK triggers during unit testing, check that we haven't
// altered an item that's an unapplied update.
CHECK(!id.ServerKnows()) << meta_entry;
sync_entry->set_version(0);
} else {
CHECK(id.ServerKnows()) << meta_entry;
sync_entry->set_version(meta_entry.Get(syncable::BASE_VERSION));
}
sync_entry->set_ctime(ClientTimeToServerTime(
meta_entry.Get(syncable::CTIME)));
sync_entry->set_mtime(ClientTimeToServerTime(
meta_entry.Get(syncable::MTIME)));
set<ExtendedAttribute> extended_attributes;
meta_entry.GetAllExtendedAttributes(
session->write_transaction(), &extended_attributes);
set<ExtendedAttribute>::iterator iter;
sync_pb::ExtendedAttributes* mutable_extended_attributes =
sync_entry->mutable_extended_attributes();
for (iter = extended_attributes.begin(); iter != extended_attributes.end();
++iter) {
sync_pb::ExtendedAttributes_ExtendedAttribute *extended_attribute =
mutable_extended_attributes->add_extendedattribute();
extended_attribute->set_key(iter->key());
SyncerProtoUtil::CopyBlobIntoProtoBytes(iter->value(),
extended_attribute->mutable_value());
}
// Deletion is final on the server, let's move things and then delete them.
if (meta_entry.Get(syncable::IS_DEL)) {
sync_entry->set_deleted(true);
} else if (meta_entry.Get(syncable::IS_BOOKMARK_OBJECT)) {
sync_pb::SyncEntity_BookmarkData* bookmark =
sync_entry->mutable_bookmarkdata();
bookmark->set_bookmark_folder(meta_entry.Get(syncable::IS_DIR));
const Id& prev_id = meta_entry.Get(syncable::PREV_ID);
string prev_string = prev_id.IsRoot() ? string() : prev_id.GetServerId();
sync_entry->set_insert_after_item_id(prev_string);
if (!meta_entry.Get(syncable::IS_DIR)) {
string bookmark_url = meta_entry.Get(syncable::BOOKMARK_URL);
bookmark->set_bookmark_url(bookmark_url);
SyncerProtoUtil::CopyBlobIntoProtoBytes(
meta_entry.Get(syncable::BOOKMARK_FAVICON),
bookmark->mutable_bookmark_favicon());
}
}
}
session->status_controller()->mutable_commit_message()->CopyFrom(message);
}
} // namespace browser_sync
| 41.464516
| 80
| 0.715419
|
rwatson
|
238147189c29475ac43a113d5e97782feee7d072
| 345
|
cpp
|
C++
|
OOP Lab/Lab9/LE/LE9_9.cpp
|
HANS-2002/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo
|
8a9d67153797e9a6d438151c70f6726a50079df4
|
[
"MIT"
] | 2
|
2021-09-18T10:50:20.000Z
|
2021-11-12T13:19:45.000Z
|
OOP Lab/Lab9/LE/LE9_9.cpp
|
HANS-2002/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo
|
8a9d67153797e9a6d438151c70f6726a50079df4
|
[
"MIT"
] | null | null | null |
OOP Lab/Lab9/LE/LE9_9.cpp
|
HANS-2002/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo
|
8a9d67153797e9a6d438151c70f6726a50079df4
|
[
"MIT"
] | 3
|
2021-09-10T14:08:12.000Z
|
2021-09-18T10:52:09.000Z
|
// (Class Template) Write a program to explain class template by creating a template T for a class
// named pair having two data members of type T which are inputted by a constructor and a
// member function get-max() return the greatest of two numbers to main. Note: the value of T
// depends upon the data type specified during object creation
| 86.25
| 98
| 0.776812
|
HANS-2002
|
2384b259525d7b7da51ab90093316c169352b226
| 15,767
|
cpp
|
C++
|
newbase/NFmiRect.cpp
|
fmidev/smartmet-library-newbase
|
12d93660c06e3c66a039ea75530bd9ca5daf7ab8
|
[
"MIT"
] | null | null | null |
newbase/NFmiRect.cpp
|
fmidev/smartmet-library-newbase
|
12d93660c06e3c66a039ea75530bd9ca5daf7ab8
|
[
"MIT"
] | 7
|
2017-01-17T10:46:33.000Z
|
2019-11-21T07:50:17.000Z
|
newbase/NFmiRect.cpp
|
fmidev/smartmet-library-newbase
|
12d93660c06e3c66a039ea75530bd9ca5daf7ab8
|
[
"MIT"
] | 2
|
2017-01-17T07:33:28.000Z
|
2018-04-26T07:10:23.000Z
|
// ======================================================================
/*!
* \file NFmiRect.cpp
* \brief Implementation of class NFmiRect
*/
// ======================================================================
/*!
* \class NFmiRect
*
* Undocumented
*
*/
// ======================================================================
#include "NFmiRect.h"
#include <boost/functional/hash.hpp>
#include <macgyver/Exception.h>
#include <algorithm>
#include <fstream>
// ----------------------------------------------------------------------
/*!
* Constructor
*
* \param firstCorner Undocumented
* \param oppositeCorner Undocumented
*/
// ----------------------------------------------------------------------
NFmiRect::NFmiRect(const NFmiPoint &firstCorner, const NFmiPoint &oppositeCorner)
: itsPlace(std::min(firstCorner.X(), oppositeCorner.X()),
std::min(firstCorner.Y(), oppositeCorner.Y())),
itsSize(NFmiPoint(std::max(firstCorner.X(), oppositeCorner.X()),
std::max(firstCorner.Y(), oppositeCorner.Y())) -
itsPlace)
{
}
// ----------------------------------------------------------------------
/*!
* Constructor
*
* \param left Undocumented
* \param top Undocumented
* \param right Undocumented
* \param bottom Undocumented
*/
// ----------------------------------------------------------------------
NFmiRect::NFmiRect(double left, double top, double right, double bottom)
: itsPlace(std::min(left, right), std::min(top, bottom)),
itsSize(NFmiPoint(std::max(left, right), std::max(top, bottom)) - itsPlace)
{
}
// ----------------------------------------------------------------------
/*!
* \param theValue Undocumented
*/
// ----------------------------------------------------------------------
void NFmiRect::Inflate(double theValue)
{
try
{
itsSize += NFmiPoint(2 * theValue, 2 * theValue);
itsPlace -= NFmiPoint(theValue, theValue);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theXValue Undocumented
* \param theYValue Undocumented
*/
// ----------------------------------------------------------------------
void NFmiRect::Inflate(double theXValue, double theYValue)
{
try
{
itsSize += NFmiPoint(2 * theXValue, 2 * theYValue);
itsPlace -= NFmiPoint(theXValue, theYValue);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theValue Undocumented
*/
// ----------------------------------------------------------------------
void NFmiRect::Inflate(const NFmiPoint &theValue)
{
try
{
NFmiPoint theSizingValue(theValue);
theSizingValue += theValue;
itsSize += theSizingValue;
itsPlace -= theValue;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param thePoint Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiRect::NearestCorner(const NFmiPoint &thePoint) const
{
try
{
double dLeftTop = TopLeft().Distance(thePoint);
double dRightTop = TopRight().Distance(thePoint);
double dLeftBottom = BottomLeft().Distance(thePoint);
double dRightBottom = BottomRight().Distance(thePoint);
if (dLeftTop <= dRightTop)
{
if (dLeftTop <= dLeftBottom)
return TopLeft();
else
return BottomLeft();
}
else
{
if (dRightTop <= dRightBottom)
return TopRight();
else
return BottomRight();
}
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theRatioXperY Undocumented
* \param fKeepX Undocumented
* \param theDirection Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
// Säätää rectin aspect ration halutuksi. fKeepX ollessa tosi ei muuteta
// x:n arvoja. Korjaukset tehdään halutun nurkan ('theDirection') suhteen
// eli valittu nurkka "pysyy paikallaan". Jos muutos on mahdoton (esim.
// aspectratio=0), palauttaa funktio false:n muuten true:n.
bool NFmiRect::AdjustAspectRatio(double theRatioXperY, bool fKeepX, FmiDirection theDirection)
{
try
{
if (theRatioXperY == 0.)
return false;
NFmiRect originalRect(itsPlace, itsPlace + itsSize); // 9.9.99/EL
if (fKeepX)
Size(NFmiPoint(Width(), Width() / theRatioXperY));
else
Size(NFmiPoint(theRatioXperY * Height(), Height()));
double newWidth = Width();
double newHeight = Height();
// Origona on nurkka 'kTopLeft' missä (X,Y) = TopLeft()
// X kasvaa "vasemmalta oikealle"
// Y kasvaa "ylhäältä alas"
switch (theDirection)
{
case kTopLeft:
return true; // Nurkka on origossa - Place() pysyy paikallaan
case kTopRight:
Place(NFmiPoint(originalRect.TopRight().X() - newWidth, TopRight().Y()));
return true;
case kBottomLeft:
Place(NFmiPoint(originalRect.BottomLeft().X(), originalRect.BottomLeft().Y() - newHeight));
return true;
case kBottomRight:
Place(NFmiPoint(originalRect.BottomRight().X() - newWidth,
originalRect.BottomRight().Y() - newHeight));
return true;
case kCenter:
Center(originalRect.Center());
return true;
default:
return false;
}
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Projisoi annetun maailma koordinaatin siten että jos piste on rectin
* sisällä, palautettu rect saa arvon 0,0 - 1,1 sen mukaan miten se rectin
* sisään osui. Origo on top-left ja 1,1 on bottom-right kulma. Jos se on
* ruudun ulkona, tulee mukaan mahdolliset negatiiviset ja 1:stä suuremmat arvot.
*
* \param thePoint The relative world point that is projected to rect dimensions.
* \return The given point in rect's world coordinates.
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiRect::Project(const NFmiPoint &thePlace) const
{
try
{
NFmiPoint newPoint = thePlace - TopLeft();
return NFmiPoint(newPoint.X() / Width(), newPoint.Y() / Height());
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Assignment operator
*
* \param thePoint The other object being assigned
* \return The assigned object
*/
// ----------------------------------------------------------------------
NFmiRect &NFmiRect::operator+=(const NFmiPoint &thePoint)
{
try
{
itsPlace += thePoint;
return *this;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Substraction operator
*
* \param thePoint The coordinates being substracted
* \return The resulting rectangle
*/
// ----------------------------------------------------------------------
NFmiRect &NFmiRect::operator-=(const NFmiPoint &thePoint)
{
try
{
itsPlace -= thePoint;
return *this;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Addition operator
*
* \param theRect The rectangle being added
* \return The resulting rectangle
*/
// ----------------------------------------------------------------------
NFmiRect &NFmiRect::operator+=(const NFmiRect &theRect)
{
try
{
itsPlace = NFmiPoint(Left() < theRect.Left() ? Left() : theRect.Left(),
Top() < theRect.Top() ? Top() : theRect.Top());
itsSize = NFmiPoint(Right() > theRect.Right() ? Right() : theRect.Right(),
Bottom() > theRect.Bottom() ? Bottom() : theRect.Bottom()) -
itsPlace;
return *this;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Substraction operator
*
* \param theRect The rectangle being substracted
* \result The resulting rectangle
*/
// ----------------------------------------------------------------------
NFmiRect &NFmiRect::operator-=(const NFmiRect &theRect)
{
try
{
itsPlace = NFmiPoint(Left() > theRect.Left() ? Left() : theRect.Left(),
Top() > theRect.Top() ? Top() : theRect.Top());
itsSize = NFmiPoint(Right() < theRect.Right() ? Right() : theRect.Right(),
Bottom() < theRect.Bottom() ? Bottom() : theRect.Bottom()) -
itsPlace;
return *this;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param newCenter Undocumented
*/
// ----------------------------------------------------------------------
void NFmiRect::Center(const NFmiPoint &newCenter)
{
try
{
Place(NFmiPoint(newCenter.X() - (Width() / 2.), newCenter.Y() - (Height() / 2.)));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Palauttaa kahta rectiä ympäröivän rectin.
* \param theRect Undocumented
* \result Undocumented
*/
// ----------------------------------------------------------------------
const NFmiRect NFmiRect::SmallestEnclosing(const NFmiRect &theRect) const
{
try
{
double left = Left() < theRect.Left() ? Left() : theRect.Left();
double top = Top() < theRect.Top() ? Top() : theRect.Top();
double right = Right() > theRect.Right() ? Right() : theRect.Right();
double bottom = Bottom() > theRect.Bottom() ? Bottom() : theRect.Bottom();
return NFmiRect(left, top, right, bottom);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Palauttaa pienimmän rect:in, mikä pitää sisällään this-rect:in ja
* parametrina annetun rect:in eli leikkaus.
* \param theRect Undocumented
* \result Undocumented
*/
// ----------------------------------------------------------------------
const NFmiRect NFmiRect::Intersection(const NFmiRect &theRect) const
{
try
{
double left = Left() > theRect.Left() ? Left() : theRect.Left();
double top = Top() > theRect.Top() ? Top() : theRect.Top();
double right = Right() < theRect.Right() ? Right() : theRect.Right();
double bottom = Bottom() < theRect.Bottom() ? Bottom() : theRect.Bottom();
return NFmiRect(left, top, right, bottom);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Write the rectangle to the given output stream
*
* \param file The output stream to write to
* \result The output stream written to
*/
// ----------------------------------------------------------------------
std::ostream &NFmiRect::Write(std::ostream &file) const
{
try
{
file << itsPlace;
file << itsSize;
return file;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Read new rectangle definition from the given input stream
*
* \param file The input stream to read from
* \return The input stream read from
*/
// ----------------------------------------------------------------------
std::istream &NFmiRect::Read(std::istream &file)
{
try
{
file >> itsPlace;
file >> itsSize;
return file;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Addition of a point and a rectangle
*
* \param leftPoint Undocumented
* \param rightRect Undocumented
* \return Undocumemted
*/
// ----------------------------------------------------------------------
NFmiRect operator+(const NFmiPoint &leftPoint, const NFmiRect &rightRect)
{
try
{
return NFmiRect(
NFmiPoint(leftPoint.X() + rightRect.Left(), leftPoint.Y() + rightRect.Top()),
NFmiPoint(leftPoint.X() + rightRect.Right(), leftPoint.Y() + rightRect.Bottom()));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Substraction of a point and a rectangle
*
* \param leftPoint Undocumented
* \param rightRect Undocumented
* \return Undocumemted
*/
// ----------------------------------------------------------------------
NFmiRect operator-(const NFmiPoint &leftPoint, const NFmiRect &rightRect)
{
try
{
return NFmiRect(
NFmiPoint(leftPoint.X() - rightRect.Left(), leftPoint.Y() - rightRect.Top()),
NFmiPoint(leftPoint.X() - rightRect.Right(), leftPoint.Y() - rightRect.Bottom()));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Addition of a point and a rectangle
*
* \param leftRect Undocumented
* \param rightPoint Undocumented
* \result Undocumented
*/
// ----------------------------------------------------------------------
NFmiRect operator+(const NFmiRect &leftRect, const NFmiPoint &rightPoint)
{
try
{
return NFmiRect(
NFmiPoint(rightPoint.X() + leftRect.Left(), rightPoint.Y() + leftRect.Top()),
NFmiPoint(rightPoint.X() + leftRect.Right(), rightPoint.Y() + leftRect.Bottom()));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Substraction of a rectangle and a point
*
* \param leftRect Undocumented
* \param rightPoint Undocumented
* \result Undocumented
*/
// ----------------------------------------------------------------------
NFmiRect operator-(const NFmiRect &leftRect, const NFmiPoint &rightPoint)
{
try
{
return NFmiRect(
NFmiPoint(rightPoint.X() - leftRect.Left(), rightPoint.Y() - leftRect.Top()),
NFmiPoint(rightPoint.X() - leftRect.Right(), rightPoint.Y() - leftRect.Bottom()));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
bool NFmiRect::Intersect(const NFmiRect &theRect) const
{
try
{
if (this->Left() < theRect.Right() && this->Right() > theRect.Left() &&
this->Top() < theRect.Bottom() && this->Bottom() > theRect.Top())
return true;
else
return false;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return hash value for the rectangle
*/
// ----------------------------------------------------------------------
std::size_t NFmiRect::HashValue() const
{
try
{
std::size_t hash = itsPlace.HashValue();
boost::hash_combine(hash, itsSize.HashValue());
return hash;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ======================================================================
| 26.814626
| 99
| 0.490328
|
fmidev
|
2385728ed6e584fa445b30a6a16b3161dcf5820b
| 3,542
|
cpp
|
C++
|
scaffold/Setting.cpp
|
taozhijiang/roo
|
bea672b9274f91f4002a9742e096152b0d62f122
|
[
"BSD-3-Clause"
] | null | null | null |
scaffold/Setting.cpp
|
taozhijiang/roo
|
bea672b9274f91f4002a9742e096152b0d62f122
|
[
"BSD-3-Clause"
] | null | null | null |
scaffold/Setting.cpp
|
taozhijiang/roo
|
bea672b9274f91f4002a9742e096152b0d62f122
|
[
"BSD-3-Clause"
] | 2
|
2019-08-23T02:31:42.000Z
|
2020-05-02T00:12:36.000Z
|
/*-
* Copyright (c) 2019 TAO Zhijiang<taozhijiang@gmail.com>
*
* Licensed under the BSD-3-Clause license, see LICENSE for full information.
*
*/
#include <sstream>
#include <iostream>
#include <scaffold/Setting.h>
#include <scaffold/Status.h>
namespace roo {
bool Setting::init(std::string file) {
cfg_file_ = file;
setting_ptr_.reset( new libconfig::Config() );
if (!setting_ptr_) {
log_err("create libconfig failed.");
return false;
}
// try load and explain the cfg_file first.
try {
setting_ptr_->readFile(file.c_str());
} catch(libconfig::FileIOException &fioex) {
fprintf(stderr, "I/O error while reading file: %s.", file.c_str());
log_err( "I/O error while reading file: %s.", file.c_str());
setting_ptr_.reset();
} catch(libconfig::ParseException &pex) {
fprintf(stderr, "Parse error at %d - %s", pex.getLine(), pex.getError());
log_err( "Parse error at %d - %s", pex.getLine(), pex.getError());
setting_ptr_.reset();
}
// when init, parse conf failed was critical.
if (!setting_ptr_) {
return false;
}
return true;
}
int Setting::update_runtime_setting() {
if (cfg_file_.empty()) {
log_err("param cfg_file is not set, may not initialized ???");
return -1;
}
std::lock_guard<std::mutex> lock(lock_);
if (in_process_) {
log_err("!!! already in process, please try again later!");
return 0;
}
auto setting = load_cfg_file();
if (!setting) {
in_process_ = false;
log_err("load config file %s failed.", cfg_file_.c_str());
return false;
}
// 重新读取配置并且解析成功之后,才更新这个指针
std::swap(setting, setting_ptr_);
last_update_time_ = ::time(NULL);
int ret = 0;
for (auto it = calls_.begin(); it != calls_.end(); ++it) {
ret += (it->second)(*setting_ptr_); // call it!
}
log_warning("Setting::update_runtime_conf total callback return: %d", ret);
in_process_ = false;
return ret;
}
int Setting::attach_runtime_callback(const std::string& name, SettingUpdateCallable func) {
if (name.empty() || !func){
log_err("invalid name or func param.");
return -1;
}
std::lock_guard<std::mutex> lock(lock_);
calls_.push_back({name, func});
log_info("register runtime for %s success.", name.c_str());
return 0;
}
int Setting::module_status(std::string& module, std::string& name, std::string& val) {
module = "roo";
name = "Setting";
std::stringstream ss;
ss << "attached runtime update: " << std::endl;
std::lock_guard<std::mutex> lock(lock_);
int i = 1;
for (auto it = calls_.begin(); it != calls_.end(); ++it) {
ss << "\t" << i++ << ". "<< it->first << std::endl;
}
val = ss.str();
return 0;
}
std::shared_ptr<libconfig::Config> Setting::load_cfg_file() {
std::shared_ptr<libconfig::Config> setting = std::make_shared<libconfig::Config>();
if (!setting) {
log_err("create libconfig::Config instance failed!");
return setting; // nullptr
}
try {
setting->readFile(cfg_file_.c_str());
} catch (libconfig::FileIOException& fioex) {
log_err("I/O error while reading file: %s.", cfg_file_.c_str());
setting.reset();
} catch (libconfig::ParseException& pex) {
log_err("Parse error at %d - %s", pex.getLine(), pex.getError());
setting.reset();
}
return setting;
}
} // end namespace roo
| 25.120567
| 91
| 0.601073
|
taozhijiang
|
23875d96f499e5a6f87d8a846965a7aab0aeabaa
| 1,736
|
cxx
|
C++
|
HTRunInfo/HTDAQStackInfo.cxx
|
dellaquilamaster/RIBbit2
|
5e792724676a7b84e19e9512b2d6295287f81a4e
|
[
"Unlicense"
] | null | null | null |
HTRunInfo/HTDAQStackInfo.cxx
|
dellaquilamaster/RIBbit2
|
5e792724676a7b84e19e9512b2d6295287f81a4e
|
[
"Unlicense"
] | null | null | null |
HTRunInfo/HTDAQStackInfo.cxx
|
dellaquilamaster/RIBbit2
|
5e792724676a7b84e19e9512b2d6295287f81a4e
|
[
"Unlicense"
] | 1
|
2019-05-03T17:50:21.000Z
|
2019-05-03T17:50:21.000Z
|
#include <HTDAQStackInfo.h>
//________________________________________________
HTDAQStackInfo::HTDAQStackInfo(const char * name, int stackID) :
fNModules(0),
fStackName(name),
fStackID(stackID)
{}
//________________________________________________
HTDAQStackInfo::~HTDAQStackInfo()
{
Clear();
}
//________________________________________________
void HTDAQStackInfo::Clear()
{
for(int i=0; i<fNModules; i++) {
if(fModuleInStack[i]) {
delete fModuleInStack[i];
}
}
fModuleInStack.clear();
fNModules=0;
}
//________________________________________________
int HTDAQStackInfo::GetNModules() const
{
return fNModules;
}
//________________________________________________
RBElectronics * HTDAQStackInfo::GetModule(int n_module) const
{
return fModuleInStack[n_module]->GetModule();
}
//________________________________________________
const char * HTDAQStackInfo::GetModuleType(int n_module) const
{
return fModuleInStack[n_module]->GetModuleType();
}
//________________________________________________
int HTDAQStackInfo::GetModuleVSN(int n_module) const
{
return fModuleInStack[n_module]->GetVSN();
}
//________________________________________________
int HTDAQStackInfo::GetStackID() const
{
return fStackID;
}
//________________________________________________
const char * HTDAQStackInfo::GetStackName() const
{
return fStackName.c_str();
}
//________________________________________________
HTModuleInfo * HTDAQStackInfo::GetModuleInfo(int n_module) const
{
return fModuleInStack[n_module];
}
//________________________________________________
void HTDAQStackInfo::AddModuleInfo(HTModuleInfo * new_module_info)
{
fNModules++;
fModuleInStack.push_back(new_module_info);
return;
}
| 22.545455
| 66
| 0.801843
|
dellaquilamaster
|
238de8358cb0938b34eacfe1305a0bb6b5442982
| 3,202
|
cpp
|
C++
|
unit_tests/core/math/euler_angles/src/unit_euler_angles.cpp
|
ricortiz/OpenTissue
|
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
|
[
"Zlib"
] | 76
|
2018-02-20T11:30:52.000Z
|
2022-03-31T12:45:06.000Z
|
unit_tests/core/math/euler_angles/src/unit_euler_angles.cpp
|
ricortiz/OpenTissue
|
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
|
[
"Zlib"
] | 27
|
2018-11-20T14:32:49.000Z
|
2021-11-24T15:26:45.000Z
|
unit_tests/core/math/euler_angles/src/unit_euler_angles.cpp
|
ricortiz/OpenTissue
|
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
|
[
"Zlib"
] | 24
|
2018-02-21T01:45:26.000Z
|
2022-03-07T07:06:49.000Z
|
//
// OpenTissue, A toolbox for physical based simulation and animation.
// Copyright (C) 2007 Department of Computer Science, University of Copenhagen
//
#include <OpenTissue/configuration.h>
#include <OpenTissue/core/math/math_euler_angles.h>
#define BOOST_AUTO_TEST_MAIN
#include <OpenTissue/utility/utility_push_boost_filter.h>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>
#include <OpenTissue/utility/utility_pop_boost_filter.h>
using namespace OpenTissue;
void do_test( double const & phi_in, double const & psi_in, double const & theta_in)
{
OpenTissue::math::Quaternion<double> Q_in;
OpenTissue::math::Quaternion<double> Q_out;
OpenTissue::math::Quaternion<double> identity;
OpenTissue::math::Quaternion<double> Qz1;
OpenTissue::math::Quaternion<double> Qy;
OpenTissue::math::Quaternion<double> Qz2;
double const too_small = 10e-7;
double phi_out = 0.0;
double psi_out = 0.0;
double theta_out = 0.0;
Qz1.Rz(theta_in);
Qy.Ry(psi_in);
Qz2.Rz(phi_in);
Q_in = OpenTissue::math::prod( Qz2 , OpenTissue::math::prod( Qy , Qz1) );
OpenTissue::math::ZYZ_euler_angles(Q_in,phi_out,psi_out,theta_out);
if(psi_in > 0.0)
{
// we only want to do this if we are not in a gimbal lock
Qz1.Rz(theta_out);
Qy.Ry(psi_out);
Qz2.Rz(phi_out);
Q_out = OpenTissue::math::prod( Qz2 , OpenTissue::math::prod( Qy , Qz1) );
identity = OpenTissue::math::prod( OpenTissue::math::conj(Q_out), Q_in );
double const s = fabs( fabs(identity.s()) - 1.0 );
double const v0 = fabs(identity.v()(0));
double const v1 = fabs(identity.v()(1));
double const v2 = fabs(identity.v()(2));
BOOST_CHECK( s < too_small);
BOOST_CHECK( v0 < too_small);
BOOST_CHECK( v1 < too_small);
BOOST_CHECK( v2 < too_small);
double const dphi = fabs(phi_in - phi_out);
double const dpsi = fabs(psi_in - psi_out);
double const dtheta = fabs(theta_in - theta_out);
BOOST_CHECK( dphi < too_small);
BOOST_CHECK( dpsi < too_small);
BOOST_CHECK( dtheta < too_small);
}
else
{
// In gimbal lock phi and theta behaves strangely
BOOST_CHECK_CLOSE( 0.0, theta_out, 0.01);
double const dpsi = fabs(psi_out);
BOOST_CHECK( dpsi < too_small);
double new_phi = phi_in + theta_in;
double const pi = 3.1415926535897932384626433832795;
double const two_pi = 2.0*pi;
while(new_phi>pi) new_phi -= two_pi;
while(new_phi<-pi) new_phi += two_pi;
double const dphi = fabs(new_phi - phi_out);
BOOST_CHECK( dphi < too_small);
}
}
BOOST_AUTO_TEST_SUITE(opentissue_math_euler_angles);
BOOST_AUTO_TEST_CASE(ZYZ)
{
size_t N = 15;
double const pi = 3.1415926535897932384626433832795;
double const two_pi = 2.0*pi;
double const delta = (two_pi)/(N-1);
double phi = -pi+delta;
for(;phi<pi;)
{
double psi = 0.0;
for(;psi<pi;)
{
double theta = -pi+delta;
for(;theta<pi;)
{
do_test( phi, psi, theta );
theta += delta;
}
psi += delta;
}
phi += delta;
}
}
BOOST_AUTO_TEST_SUITE_END();
| 27.367521
| 84
| 0.67614
|
ricortiz
|
2390b9de6c1a931be7e506b913688dfde1b290ed
| 902
|
cpp
|
C++
|
Recover Binary Search Tree.cpp
|
Subhash3/Algorithms-For-Software-Developers
|
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
|
[
"BSD-2-Clause"
] | 2
|
2021-10-01T04:20:04.000Z
|
2021-10-01T04:20:06.000Z
|
Recover Binary Search Tree.cpp
|
Subhash3/Algorithms-For-Software-Developers
|
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
|
[
"BSD-2-Clause"
] | 1
|
2021-10-01T18:00:09.000Z
|
2021-10-01T18:00:09.000Z
|
Recover Binary Search Tree.cpp
|
Subhash3/Algorithms-For-Software-Developers
|
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
|
[
"BSD-2-Clause"
] | 8
|
2021-10-01T04:20:38.000Z
|
2022-03-19T17:05:05.000Z
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* first=0;
TreeNode* sec=0;
TreeNode* prev=new TreeNode(INT_MIN);
void inorder(TreeNode* root){
if(!root)
return;
inorder(root->left);
if(!first&&root->val<prev->val)
first=prev;
if(first&&root->val<prev->val)
sec=root;
prev=root;
inorder(root->right);
}
void recoverTree(TreeNode* root) {
inorder(root);
int temp=first->val;
first->val=sec->val;
sec->val=temp;
}
};
| 25.771429
| 93
| 0.543237
|
Subhash3
|