hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0bb13cfb0c00d0ec1cf38368fe8d74434b262f52 | 16,275 | cpp | C++ | src/lava_lib/reader_bgeo/test/test_pack_fragments6_anim.cpp | cinepost/Falcor | f70bd1d97c064d6f91a017d4409aa2037fd6903a | [
"BSD-3-Clause"
] | 7 | 2018-09-25T23:45:52.000Z | 2021-07-07T04:08:01.000Z | src/lava_lib/reader_bgeo/test/test_pack_fragments6_anim.cpp | cinepost/Falcor | f70bd1d97c064d6f91a017d4409aa2037fd6903a | [
"BSD-3-Clause"
] | 2 | 2021-03-02T10:16:06.000Z | 2021-08-13T10:10:21.000Z | src/lava_lib/reader_bgeo/test/test_pack_fragments6_anim.cpp | cinepost/Lava | f70bd1d97c064d6f91a017d4409aa2037fd6903a | [
"BSD-3-Clause"
] | 3 | 2020-06-07T05:47:48.000Z | 2020-10-03T12:34:54.000Z | /*
* Copyright 2018 Laika, LLC. Authored by Peter Stuart
*
* Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
* http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
* http://opensource.org/licenses/MIT>, at your option. This file may not be
* copied, modified, or distributed except according to those terms.
*/
#include <hboost/test/unit_test.hpp>
#include "bgeo/parser/StorageTraits.h"
#include "bgeo/Bgeo.h"
#include "bgeo/PackedFragment.h"
#include "bgeo/Poly.h"
namespace ika
{
namespace bgeo
{
namespace test_pack_fragments6_anim
{
class PackFragments6AnimFixture
{
public:
PackFragments6AnimFixture()
: bgeo("geo/pack_fragments6_anim_16.0020.bgeo")
{
}
protected:
Bgeo bgeo;
};
namespace
{
std::vector<float> expected_P = {
1.05895591, 0.285170734, 0.807400465,
0.380258828, 0.249864608, 0.380244672,
0.017419463, 0.208380997, -0.334947854,
0.0339404829, 0.24616015, -1.13657546,
-0.535132408, 0.34420222, 0.583373249,
-1.40871906, 0.333948344, 1.63560438
};
} // namespace anonymous
HBOOST_FIXTURE_TEST_SUITE(test_pack_fragments6_anim, PackFragments6AnimFixture)
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_counts)
{
HBOOST_CHECK_EQUAL(6, bgeo.getPointCount());
HBOOST_CHECK_EQUAL(6, bgeo.getTotalVertexCount());
HBOOST_CHECK_EQUAL(6, bgeo.getPrimitiveCount());
HBOOST_CHECK_EQUAL(28, bgeo.getPointAttributeCount());
HBOOST_CHECK_EQUAL(2, bgeo.getPrimitiveAttributeCount());
HBOOST_CHECK_EQUAL(3, bgeo.getDetailAttributeCount());
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_P)
{
std::vector<float> P;
bgeo.getP(P);
HBOOST_CHECK_EQUAL_COLLECTIONS(expected_P.begin(), expected_P.end(),
P.begin(), P.end());
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_name)
{
auto attribute = bgeo.getPointAttributeByName("name");
HBOOST_REQUIRE(attribute);
std::vector<std::string> strings;
attribute->getStrings(strings);
std::vector<std::string> expected_names = {
"piece0",
"piece1",
"piece2",
"piece3",
"piece4",
"piece5"
};
HBOOST_CHECK_EQUAL_COLLECTIONS(expected_names.begin(), expected_names.end(),
strings.begin(), strings.end());
HBOOST_CHECK_EQUAL(bgeo::parser::storage::Int32,
attribute->getFundamentalType());
std::vector<int32> indices;
attribute->getData(indices);
std::vector<int32> expected_indices = {
0, 1, 2, 3, 4, 5
};
HBOOST_CHECK_EQUAL_COLLECTIONS(expected_indices.begin(),
expected_indices.end(),
indices.begin(), indices.end());
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_path)
{
auto attribute = bgeo.getPrimitiveAttributeByName("path");
HBOOST_REQUIRE(attribute);
std::vector<std::string> strings;
attribute->getStrings(strings);
std::vector<std::string> expected_paths = {
"op:/obj/fracture/assemble1/pack/piece0",
"op:/obj/fracture/assemble1/pack/piece1",
"op:/obj/fracture/assemble1/pack/piece2",
"op:/obj/fracture/assemble1/pack/piece3",
"op:/obj/fracture/assemble1/pack/piece4",
"op:/obj/fracture/assemble1/pack/piece5"
};
HBOOST_CHECK_EQUAL_COLLECTIONS(expected_paths.begin(), expected_paths.end(),
strings.begin(), strings.end());
HBOOST_CHECK_EQUAL(bgeo::parser::storage::Int32,
attribute->getFundamentalType());
std::vector<int32> indices;
attribute->getData(indices);
std::vector<int32> expected_indices = {
0, 1, 2, 3, 4, 5
};
HBOOST_CHECK_EQUAL_COLLECTIONS(expected_indices.begin(),
expected_indices.end(),
indices.begin(), indices.end());
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_primitives_are_fragments)
{
for (int i = 0; i < 6; ++i)
{
auto primitive = bgeo.getPrimitive(i);
HBOOST_REQUIRE(primitive);
HBOOST_CHECK(primitive->isType<PackedFragment>());
}
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_packed_parameters_common)
{
for (int i = 0; i < 6; ++i)
{
auto primitive = bgeo.getPrimitive(i);
HBOOST_REQUIRE(primitive);
auto fragment = primitive->cast<PackedFragment>();
HBOOST_REQUIRE(fragment);
// name attribute
HBOOST_CHECK_EQUAL("name", fragment->getNameAttribute());
}
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_fragment_parameters_0)
{
auto primitive = bgeo.getPrimitive(0);
HBOOST_REQUIRE(primitive);
auto fragment = primitive->cast<PackedFragment>();
HBOOST_REQUIRE(fragment);
// bounding box
HBOOST_CHECK(fragment->hasBoundingBox());
double bounds[6] = { -1 };
fragment->getBoundingBox(bounds);
double expected_bounds[] = {
-0.242365837097167969, 0.5,
0.670282125473022461, 1.25357699394226074,
-0.330976128578186035, 0.5
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_bounds[0], &expected_bounds[6],
&bounds[0], &bounds[6]);
// translate
double translate[3] = { -1 };
fragment->getTranslate(translate);
HBOOST_CHECK_CLOSE(expected_P[0], translate[0], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[1], translate[1], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[2], translate[2], 0.0001);
// pivot
double pivot[3] = { -1 };
fragment->getPivot(pivot);
HBOOST_CHECK_CLOSE(0.235550165, pivot[0], 0.0001);
HBOOST_CHECK_CLOSE(0.99797374, pivot[1], 0.0001);
HBOOST_CHECK_CLOSE(0.150272042, pivot[2], 0.0001);
// extra transform
double xform[16] = { -1 };
fragment->getExtraTransform(xform);
double expected_xform[16] = {
-0.0518918045862753474, -0.998043174790356979, -0.0348870767074283689, 0,
0.797668590893775731, -0.0624418255500654301, 0.599854907535661508, 0,
-0.600859459364777249, 0.00329917713326104665, 0.799347861274998572, 0,
0, 0, 0, 1
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_xform[0], &expected_xform[16],
&xform[0], &xform[16]);
// name
HBOOST_CHECK_EQUAL("piece0", fragment->getName());
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_fragment_parameters_1)
{
auto primitive = bgeo.getPrimitive(1);
HBOOST_REQUIRE(primitive);
auto fragment = primitive->cast<PackedFragment>();
HBOOST_REQUIRE(fragment);
// bounding box
HBOOST_CHECK(fragment->hasBoundingBox());
double bounds[6] = { -1 };
fragment->getBoundingBox(bounds);
double expected_bounds[] = {
-0.268821775913238525, 0.5,
0.253576993942260742, 0.813160300254821777,
-0.204243898391723633, 0.5
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_bounds[0], &expected_bounds[6],
&bounds[0], &bounds[6]);
// translate
double translate[3] = { -1 };
fragment->getTranslate(translate);
HBOOST_CHECK_CLOSE(expected_P[3], translate[0], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[4], translate[1], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[5], translate[2], 0.0001);
// pivot
double pivot[3] = { -1 };
fragment->getPivot(pivot);
HBOOST_CHECK_CLOSE(0.212833121, pivot[0], 0.0001);
HBOOST_CHECK_CLOSE(0.503501475, pivot[1], 0.0001);
HBOOST_CHECK_CLOSE(0.246036574, pivot[2], 0.0001);
// extra transform
double xform[16] = { -1 };
fragment->getExtraTransform(xform);
double expected_xform[16] = {
0.999428612448282516, -6.9286906325881756e-06, 0.0337990917395382603, 0,
8.35459815014941818e-06, 1.00000000091885499, -4.20465176045956289e-05, 0,
-0.0337990923843057844, 4.23048727781376782e-05, 0.999428613354261475, 0,
0, 0, 0, 1
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_xform[0], &expected_xform[16],
&xform[0], &xform[16]);
// name
HBOOST_CHECK_EQUAL("piece1", fragment->getName());
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_fragment_parameters_2)
{
auto primitive = bgeo.getPrimitive(2);
HBOOST_REQUIRE(primitive);
auto fragment = primitive->cast<PackedFragment>();
HBOOST_REQUIRE(fragment);
// bounding box
HBOOST_CHECK(fragment->hasBoundingBox());
double bounds[6] = { -1 };
fragment->getBoundingBox(bounds);
double expected_bounds[] = {
-0.5, 0.5,
0.253576993942260742, 0.745403587818145752,
-0.5, 0.141023203730583191
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_bounds[0], &expected_bounds[6],
&bounds[0], &bounds[6]);
// translate
double translate[3] = { -1 };
fragment->getTranslate(translate);
HBOOST_CHECK_CLOSE(expected_P[6], translate[0], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[7], translate[1], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[8], translate[2], 0.0001);
// pivot
double pivot[3] = { -1 };
fragment->getPivot(pivot);
HBOOST_CHECK_CLOSE(0.0103541994, pivot[0], 0.0001);
HBOOST_CHECK_CLOSE(0.461953759, pivot[1], 0.0001);
HBOOST_CHECK_CLOSE(-0.263642013, pivot[2], 0.0001);
// extra transform
double xform[16] = { -1 };
fragment->getExtraTransform(xform);
double expected_xform[16] = {
0.9803066436124932, 1.68166665777458304e-06, 0.197481550542809192, 0,
-1.15584012746216497e-05, 1.00000000126048794, 4.88608178032138438e-05, 0,
-0.197481551204991224,-5.01811565537572078e-05, 0.980306644182303288, 0,
0, 0, 0, 1
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_xform[0], &expected_xform[16],
&xform[0], &xform[16]);
// name
HBOOST_CHECK_EQUAL("piece2", fragment->getName());
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_fragment_parameters_3)
{
auto primitive = bgeo.getPrimitive(3);
HBOOST_REQUIRE(primitive);
auto fragment = primitive->cast<PackedFragment>();
HBOOST_REQUIRE(fragment);
// bounding box
HBOOST_CHECK(fragment->hasBoundingBox());
double bounds[6] = { -1 };
fragment->getBoundingBox(bounds);
double expected_bounds[] = {
-0.5, 0.5,
0.588265895843505859, 1.25357699394226074,
-0.5, 0.0676364079117774963
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_bounds[0], &expected_bounds[6],
&bounds[0], &bounds[6]);
// translate
double translate[3] = { -1 };
fragment->getTranslate(translate);
HBOOST_CHECK_CLOSE(expected_P[9], translate[0], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[10], translate[1], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[11], translate[2], 0.0001);
// pivot
double pivot[3] = { -1 };
fragment->getPivot(pivot);
HBOOST_CHECK_CLOSE(-0.039192643, pivot[0], 0.0001);
HBOOST_CHECK_CLOSE(0.959815145, pivot[1], 0.0001);
HBOOST_CHECK_CLOSE(-0.280727088, pivot[2], 0.0001);
// extra transform
double xform[16] = { -1 };
fragment->getExtraTransform(xform);
double expected_xform[16] = {
0.999904219062128896, -0.00235137996785824473, -0.0136395968421466861, 0,
-0.0138033897079322763, -0.0970109708050519437, -0.99518750038440984, 0,
0.00101687425842656213,0.995280499977191035, -0.0970340961279856778, 0,
0, 0, 0, 1
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_xform[0], &expected_xform[16],
&xform[0], &xform[16]);
// name
HBOOST_CHECK_EQUAL("piece3", fragment->getName());
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_fragment_parameters_4)
{
auto primitive = bgeo.getPrimitive(4);
HBOOST_REQUIRE(primitive);
auto fragment = primitive->cast<PackedFragment>();
HBOOST_REQUIRE(fragment);
// bounding box
HBOOST_CHECK(fragment->hasBoundingBox());
double bounds[6] = { -1 };
fragment->getBoundingBox(bounds);
double expected_bounds[] = {
-0.5, 0.0485223196446895599,
0.253576993942260742, 1.05693364143371582,
-0.367936700582504272, 0.5
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_bounds[0], &expected_bounds[6],
&bounds[0], &bounds[6]);
// translate
double translate[3] = { -1 };
fragment->getTranslate(translate);
HBOOST_CHECK_CLOSE(expected_P[12], translate[0], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[13], translate[1], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[14], translate[2], 0.0001);
// pivot
double pivot[3] = { -1 };
fragment->getPivot(pivot);
HBOOST_CHECK_CLOSE(-0.313334644, pivot[0], 0.0001);
HBOOST_CHECK_CLOSE(0.583304524, pivot[1], 0.0001);
HBOOST_CHECK_CLOSE(0.15184693, pivot[2], 0.0001);
// extra transform
double xform[16] = { -1 };
fragment->getExtraTransform(xform);
double expected_xform[16] = {
0.17022728703553916, -0.0646950902099336644, 0.983278818787320708, 0,
0.0678319475133114247, 0.996244820432252376, 0.0538049852109514989, 0,
-0.983067458448507403, 0.057538634901671791, 0.173976479649089022, 0,
0, 0, 0, 1
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_xform[0], &expected_xform[16],
&xform[0], &xform[16]);
// name
HBOOST_CHECK_EQUAL("piece4", fragment->getName());
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_fragment_parameters_5)
{
auto primitive = bgeo.getPrimitive(5);
HBOOST_REQUIRE(primitive);
auto fragment = primitive->cast<PackedFragment>();
HBOOST_REQUIRE(fragment);
// bounding box
HBOOST_CHECK(fragment->hasBoundingBox());
double bounds[6] = { -1 };
fragment->getBoundingBox(bounds);
double expected_bounds[] = {
-0.5, 0.169905036687850952,
0.688788354396820068, 1.25357699394226074,
-0.00462805712595582008, 0.5
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_bounds[0], &expected_bounds[6],
&bounds[0], &bounds[6]);
// translate
double translate[3] = { -1 };
fragment->getTranslate(translate);
HBOOST_CHECK_CLOSE(expected_P[15], translate[0], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[16], translate[1], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[17], translate[2], 0.0001);
// pivot
double pivot[3] = { -1 };
fragment->getPivot(pivot);
HBOOST_CHECK_CLOSE(-0.227203056, pivot[0], 0.0001);
HBOOST_CHECK_CLOSE(1.02395141, pivot[1], 0.0001);
HBOOST_CHECK_CLOSE(0.310710579, pivot[2], 0.0001);
// extra transform
double xform[16] = { -1 };
fragment->getExtraTransform(xform);
double expected_xform[16] = {
0.392875552927262728, 0.892322469276475183, 0.222281886919948407, 0,
-0.883014969801582894, 0.433556421756600086, -0.179758958278906339, 0,
-0.256774713616727657, -0.125655352540829379, 0.958267906504157829, 0,
0, 0, 0, 1
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_xform[0], &expected_xform[16],
&xform[0], &xform[16]);
// name
HBOOST_CHECK_EQUAL("piece5", fragment->getName());
}
HBOOST_AUTO_TEST_CASE(test_pack_fragments6_anim_embedded_geo)
{
auto primitive = bgeo.getPrimitive(0);
HBOOST_REQUIRE(primitive);
auto fragment = primitive->cast<PackedFragment>();
HBOOST_REQUIRE(fragment);
auto embeddedGeo = fragment->getEmbeddedGeo();
HBOOST_CHECK(embeddedGeo);
HBOOST_CHECK_EQUAL(116, embeddedGeo->getPointCount());
HBOOST_CHECK_EQUAL(216, embeddedGeo->getTotalVertexCount());
HBOOST_CHECK_EQUAL(1, embeddedGeo->getPrimitiveCount());
HBOOST_CHECK_EQUAL(2, embeddedGeo->getPointAttributeCount());
HBOOST_CHECK_EQUAL(1, embeddedGeo->getVertexAttributeCount());
HBOOST_CHECK_EQUAL(2, embeddedGeo->getPrimitiveAttributeCount());
HBOOST_CHECK_EQUAL(1, embeddedGeo->getDetailAttributeCount());
auto embeddedPrim = embeddedGeo->getPrimitive(0);
HBOOST_CHECK(embeddedPrim->isType<Poly>());
}
HBOOST_AUTO_TEST_SUITE_END()
} // namespace test_pack_fragments6_anim
} // namespace bgeo
} // namespace ika
| 32.100592 | 82 | 0.661075 | [
"vector",
"transform"
] |
0bb4c4420e440c9c5ab65f515b447fd026ceedcc | 6,099 | cpp | C++ | source/Ch07/drill/calculator08.cpp | Atroox/UDProg-Introduction | ac0ddca66825480c0e3c8fe2d93ba2a57da4068f | [
"CC0-1.0"
] | null | null | null | source/Ch07/drill/calculator08.cpp | Atroox/UDProg-Introduction | ac0ddca66825480c0e3c8fe2d93ba2a57da4068f | [
"CC0-1.0"
] | null | null | null | source/Ch07/drill/calculator08.cpp | Atroox/UDProg-Introduction | ac0ddca66825480c0e3c8fe2d93ba2a57da4068f | [
"CC0-1.0"
] | null | null | null | /*
calculator08buggy.cpp
Helpful comments removed.
We have inserted 3 bugs that the compiler will catch and 3 that it won't.
*/
/* GRAMMAR
=======
Calculation:
Statement
Print
Quit
Calculation Statement
Statement:
Declaration
Expression
Declaration:
"let" Name "=" Expression
Expression:
Term
Expression + Term
Expression - Term
Term:
Primary
Term * Primary
Term / Primary
Term % Primary
Primary:
Number
( Expression )
- Primary
? Primary
Primary ^ Primary
Number:
floating-point-literal
*/
#include "std_lib_facilities.h"
struct Token {
char kind; //what kind of token
double value; //for numbers:a value
string name;
Token(char ch) :kind(ch), value(0) { } //make a token from a char
Token(char ch, double val) :kind(ch), value(val) { } //make a token from a char and a double
Token(char ch, string n) :kind(ch), name(n) { } //make a token from a char and a string
};
class Token_stream {
bool full; // is there a Token in the buffer?
Token buffer; // here is where we keep a Token put back using putback()
public:
Token_stream() :full(0), buffer(0) { }
Token get(); //get a token
void unget(Token t) { buffer = t; full = true; }
void ignore(char c); // discard characters up to and including a c
};
const char let = 'L';
const char quit = 'Q'; //Q for quitting the program
const char print = '='; //= for printing the result
const char number = '8'; //8 to represent the numbers
const char name = 'a';
const char square_root = '?';
Token Token_stream::get() // read characters from cin and compose a Token
{
if (full) { full = false; return buffer; } // check if we already have a Token ready
char ch;
cin >> ch; // note that >> skips whitespace (space, newline, tab, etc.)
switch (ch) {
case '(':
case ')':
case '+':
case '-':
case '*':
case '/':
case '%':
case print:
case quit:
case square_root:
return Token(ch); // let each character represent itself
case '.': // a floating-point-literal can start with a dot
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{ cin.putback(ch); // put digit back into the input stream
double val;
cin >> val; // read a floating-point number
return Token(number, val);
}
default:
if (isalpha(ch))
{
string s;
s += ch;
while (cin.get(ch) && isalpha(ch) || isdigit(ch)) s += ch;
cin.unget();
if (s == "L") return Token(let);
if (s == "Q") return Token(name);
return Token(name, s);
}
error("Bad token");
}
}
void Token_stream::ignore(char c)
{
if (full && c == buffer.kind) { //look in buffer
full = false;
return;
}
full = false;
char ch = 0; //look for input
while (cin >> ch)
if (ch == c) return;
}
struct Variable { //introducing variables
string name;
double value;
Variable(string n, double v) :name(n), value(v) { }
};
vector<Variable> names;
double get_value(string s) //return the value of string s
{
for (int i = 0; i < names.size(); ++i)
if (names[i].name == s) return names[i].value;
error("get: undefined name ", s);
}
void set_value(string s, double d) //set variable named s to d
{
for (int i = 0; i < names.size(); ++i)
if (names[i].name == s) {
names[i].value = d;
return;
}
error("set: undefined name ", s);
}
bool is_declared(string s)
{
for (int i = 0; i < names.size(); ++i)
if (names[i].name == s) return true;
return false;
}
Token_stream ts;
double expression();
double primary()
{
Token t = ts.get();
switch (t.kind) {
case '(':
{ double d = expression();
t = ts.get();
if (t.kind != ')') error("')' expected");
return d;
}
case '-':
return primary();
case number:
return t.value;
case name:
return get_value(t.name);
case square_root:
{
double d = primary();
if(d < 0) error("Can't sqrt() negative numbers");
return sqrt(d);
}
default:
error("primary expected");
}
}
double term()
{
double left = primary();
while (true) {
Token t = ts.get();
switch (t.kind) {
case '*':
left *= primary();
break;
case '/':
{ double d = primary();
if (d == 0) error("divide by zero");
left /= d;
break;
}
default:
ts.unget(t);
return left;
}
}
}
double expression()
{
double left = term();
while (true) {
Token t = ts.get();
switch (t.kind) {
case '+':
left += term();
break;
case '-':
left -= term();
break;
default:
ts.unget(t);
return left;
}
}
}
double define_name(string n, double v)
{
if (is_declared(n)) error(n, " declared twice"); //see if name is already declared
names.push_back(Variable(n, v));
return v;
}
double declaration()
{
Token t = ts.get();
if (t.kind != name) error("name expected in declaration");
string name = t.name;
if (is_declared(name)) error(name, " declared twice");
Token t2 = ts.get();
if (t2.kind != '=') error("= missing in declaration of ", name);
double d = expression();
names.push_back(Variable(name, d));
return d;
}
double statement()
{
Token t = ts.get();
switch (t.kind) {
case let:
return declaration();
default:
ts.unget(t);
return expression();
}
}
void clean_up_mess() //resets program after an error
{
ts.ignore(print);
}
const string prompt = "> ";
const string result = "= ";
void calculate()
{
while (true) try {
cout << prompt;
Token t = ts.get();
while (t.kind == print) t = ts.get(); //discard all "prints"
if (t.kind == quit) return;
ts.unget(t);
cout << result << statement() << endl;
}
catch (runtime_error& e) {
cerr << e.what() << endl; //Write error message
clean_up_mess();
}
}
int main()
try {
define_name("pi",3.1415926535); //defining variables
define_name("e",2.7182818284);
define_name("k", 1000);
calculate();
return 0;
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
char c;
while (cin >> c && c != '=');
return 1;
}
catch (...) {
cerr << "exception\n";
char c;
while (cin >> c && c != '=');
return 2;
} | 19.119122 | 94 | 0.597967 | [
"vector"
] |
0bb68a6af1b655357e107af1412d7a0c170404c1 | 15,368 | cc | C++ | rocket/rocket_generator.cc | ebruneton/black_hole_shader | e72b3f293409893a6fa25528b29572c96fc57f57 | [
"BSD-3-Clause"
] | 68 | 2020-04-12T20:40:22.000Z | 2022-03-19T08:20:22.000Z | rocket/rocket_generator.cc | ebruneton/black_hole_shader | e72b3f293409893a6fa25528b29572c96fc57f57 | [
"BSD-3-Clause"
] | null | null | null | rocket/rocket_generator.cc | ebruneton/black_hole_shader | e72b3f293409893a6fa25528b29572c96fc57f57 | [
"BSD-3-Clause"
] | 9 | 2020-07-06T08:46:29.000Z | 2022-03-02T00:20:08.000Z | /**
* Copyright (c) 2020 Eric Bruneton
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
#include <memory>
#include <vector>
#include "math/vector.h"
#include "png++/png.hpp"
namespace rocket {
namespace {
using dimensional::vec3;
constexpr double kEpsilon = 1e-6;
constexpr int NUM_CIRCUMFERENCE_SAMPLES = 32;
constexpr int NUM_VERTEX_COMPONENTS = 13;
constexpr int TEXTURE_SIZE = 512;
vec3 cross(const vec3& p, const vec3& q) {
const double x = p.y() * q.z() - p.z() * q.y();
const double y = p.z() * q.x() - p.x() * q.z();
const double z = p.x() * q.y() - p.y() * q.x();
return vec3(x, y, z);
}
class Triangle {
public:
Triangle(const vec3& a, const vec3& b, const vec3& c) {
a_ = a;
ab_ = b - a;
ac_ = c - a;
}
bool RayHit(const vec3& origin, const vec3& dir) const {
const vec3 p = cross(dir, ac_);
const double det = dot(ab_, p)();
if (std::abs(det) < kEpsilon) {
return false;
}
const vec3 t = origin - a_;
double u = dot(t, p)() / det;
if (u < 0.0 || u > 1.0) {
return false;
}
const vec3 q = cross(t, ab_);
const double v = dot(dir, q)() / det;
if (v < 0.0 || u + v > 1.0) {
return false;
}
return dot(ac_, q) / det > 0.0;
}
private:
vec3 a_;
vec3 ab_;
vec3 ac_;
};
class Mesh {
public:
Mesh() {}
void AddTriangle(const vec3& a, const vec3& b, const vec3& c) {
triangles_.emplace_back(a, b, c);
}
bool RayHit(const vec3& origin, const vec3& dir) const {
for (const Triangle& triangle : triangles_) {
if (triangle.RayHit(origin, dir)) {
return true;
}
}
return false;
}
private:
std::vector<Triangle> triangles_;
};
double Theta(const int u_index) {
return (2.0 * M_PI * u_index) / NUM_CIRCUMFERENCE_SAMPLES;
}
class ProfilePoint {
public:
ProfilePoint(const double z, const double r)
: z_(z), r_(r), v_(0.0), ao_(1.0) {}
double z() const { return z_; }
double r() const { return r_; }
double v() const { return v_; }
double ao() const { return ao_; }
void SetZ(const double z) { z_ = z; }
void SetR(const double r) { r_ = r; }
void SetV(const double v) { v_ = v; }
void SetAo(const double ao) { ao_ = ao; }
private:
double z_;
double r_;
double v_;
double ao_;
};
class Profile {
public:
Profile(const std::vector<ProfilePoint>& points) : points_(points) {}
int size() const { return points_.size(); }
const ProfilePoint& point(const int index) const { return points_[index]; }
ProfilePoint& point(const int index) { return points_[index]; }
double GetLength() const {
double length = 0.0;
for (int i = 0; i < size() - 1; ++i) {
const ProfilePoint& p = point(i);
const ProfilePoint& q = point(i + 1);
const double dz = p.z() - q.z();
const double dr = p.r() - q.r();
length += sqrt(dz * dz + dr * dr);
}
return length;
}
vec3 GetPoint(const int u_index, const int v_index) const {
const double theta = Theta(u_index);
const ProfilePoint& p = point(v_index);
return vec3(p.r() * cos(theta), p.r() * sin(theta), p.z());
}
vec3 GetNormal(const int u_index, const int v_index) const {
const double theta = Theta(u_index);
const vec3 n = GetNormal(v_index);
return vec3(n.x() * cos(theta), n.x() * sin(theta), n.z());
}
vec3 GetTangent(const int u_index, const int v_index) const {
vec3 n = GetNormal(u_index, v_index);
if (std::abs(n.z()) == 1.0) {
return vec3(1.0, 0.0, 0.0);
}
const double theta = Theta(u_index);
return vec3(-sin(theta), cos(theta), 0.0);
}
void Resize(const float dz, const float scale) {
for (int i = 0; i < size(); ++i) {
ProfilePoint& p = point(i);
p.SetZ((p.z() + dz) * scale);
p.SetR(p.r() * scale);
}
}
void ComputeTexCoords(const double v0, const double length_scale) {
double v = v0;
point(0).SetV(v);
for (int v_index = 1; v_index < size(); ++v_index) {
const ProfilePoint& p = point(v_index - 1);
ProfilePoint& q = point(v_index);
const double dz = p.z() - q.z();
const double dr = p.r() - q.r();
v += sqrt(dz * dz + dr * dr) * length_scale;
q.SetV(v);
}
}
void ComputeAmbientOcclusion(const Mesh& mesh) {
for (int v_index = 0; v_index < size(); ++v_index) {
const vec3 p = GetPoint(0, v_index);
const vec3 n = GetNormal(0, v_index);
const vec3 t1 = GetTangent(0, v_index);
const vec3 t2 = cross(n, t1);
const int NPHI = 16;
const int NZ = 16;
int num_visible_dirs = 0;
for (int i = 0; i < NPHI; ++i) {
const double phi = (i + 0.5) * M_PI / NPHI;
for (int j = 0; j < NZ; ++j) {
const double z = (j + 0.5) / NZ;
const double r = sqrt(1.0 - z * z);
const vec3 dir = (t1 * cos(phi) + t2 * sin(phi)) * r + n * z;
if (!mesh.RayHit(p + n * kEpsilon, dir)) {
++num_visible_dirs;
}
}
}
point(v_index).SetAo(static_cast<double>(num_visible_dirs) / (NZ * NPHI));
}
}
static void Save(const std::vector<Profile>& profiles,
const std::string& filename) {
std::vector<int32_t> header;
std::vector<float> vertex_buffer;
std::vector<int32_t> index_buffer;
for (const Profile& profile : profiles) {
profile.AppendToBuffers(&index_buffer, &vertex_buffer);
}
header.push_back(vertex_buffer.size());
header.push_back(index_buffer.size());
std::ofstream output_stream(filename,
std::ofstream::out | std::ofstream::binary);
output_stream.write((const char*)header.data(),
header.size() * sizeof(int32_t));
output_stream.write((const char*)vertex_buffer.data(),
vertex_buffer.size() * sizeof(float));
output_stream.write((const char*)index_buffer.data(),
index_buffer.size() * sizeof(int32_t));
output_stream.close();
}
private:
vec3 GetNormal(const int v_index) const {
vec3 n(0.0, 0.0, 0.0);
vec3 p(point(v_index).r(), 0.0, point(v_index).z());
if (v_index + 1 < size()) {
vec3 q(point(v_index + 1).r(), 0.0, point(v_index + 1).z());
vec3 n_pq(q.z() - p.z(), 0.0, p.x() - q.x());
n += n_pq;
}
if (v_index > 0) {
vec3 q(point(v_index - 1).r(), 0.0, point(v_index - 1).z());
vec3 n_qp(p.z() - q.z(), 0.0, q.x() - p.x());
n += n_qp;
}
return normalize(n);
}
void AppendToBuffers(std::vector<int32_t>* index_buffer,
std::vector<float>* vertex_buffer) const {
const int start_index = vertex_buffer->size() / NUM_VERTEX_COMPONENTS;
for (int v = 0; v < size() - 1; ++v) {
for (int u = 0; u < NUM_CIRCUMFERENCE_SAMPLES; ++u) {
const int index0 =
start_index + u + v * (NUM_CIRCUMFERENCE_SAMPLES + 1);
const int index1 = index0 + 1;
const int index2 = index0 + 1 + (NUM_CIRCUMFERENCE_SAMPLES + 1);
const int index3 = index0 + (NUM_CIRCUMFERENCE_SAMPLES + 1);
index_buffer->push_back(index0);
index_buffer->push_back(index1);
index_buffer->push_back(index2);
index_buffer->push_back(index2);
index_buffer->push_back(index3);
index_buffer->push_back(index0);
}
}
for (int v = 0; v < size(); ++v) {
for (int u = 0; u <= NUM_CIRCUMFERENCE_SAMPLES; ++u) {
const vec3 p = GetPoint(u, v);
const vec3 n = GetNormal(u, v);
const vec3 t = GetTangent(u, v);
const float tex_u = static_cast<float>(u) / NUM_CIRCUMFERENCE_SAMPLES;
const float tex_v = point(v).v();
vertex_buffer->push_back(p.x());
vertex_buffer->push_back(p.y());
vertex_buffer->push_back(p.z());
vertex_buffer->push_back(n.x());
vertex_buffer->push_back(n.y());
vertex_buffer->push_back(n.z());
vertex_buffer->push_back(t.x());
vertex_buffer->push_back(t.y());
vertex_buffer->push_back(t.z());
vertex_buffer->push_back(1.0);
vertex_buffer->push_back(tex_u);
vertex_buffer->push_back(1.0 - tex_v);
vertex_buffer->push_back(point(v).ao());
}
}
}
std::vector<ProfilePoint> points_;
};
Mesh BuildMesh(const std::vector<Profile>& profiles) {
Mesh m;
for (const Profile& profile : profiles) {
for (int v = 0; v < profile.size() - 1; ++v) {
for (int u = 0; u < NUM_CIRCUMFERENCE_SAMPLES; ++u) {
vec3 p0 = profile.GetPoint(u, v);
vec3 p1 = profile.GetPoint(u + 1, v);
vec3 p2 = profile.GetPoint(u + 1, v + 1);
vec3 p3 = profile.GetPoint(u, v + 1);
m.AddTriangle(p0, p1, p2);
m.AddTriangle(p2, p3, p0);
}
}
}
return m;
}
void ComputeRocketModel(const std::string& output_dir) {
std::vector<Profile> profiles;
profiles.push_back(Profile({{180, 0}, {180, 23}}));
profiles.push_back(Profile({{180, 23},
{160, 32},
{128, 47},
{96, 60},
{64, 71},
{32, 79},
{0, 84}}));
profiles.push_back(Profile({{0, 84},
{32, 79},
{64, 71},
{96, 60},
{128, 47},
{160, 32},
{180, 23}}));
profiles.push_back(Profile({{180, 23}, {185, 29}}));
profiles.push_back(
Profile({{185, 29}, {185, 72}, {188, 84}, {197, 93}, {209, 96}}));
profiles.push_back(Profile({{209, 96}, {209, 138}}));
profiles.push_back(Profile({{209, 138}, {532, 138}}));
profiles.push_back(Profile({{532, 138}, {610, 90}, {688, 42}}));
profiles.push_back(Profile({{688, 42}, {688, 0}}));
for (Profile& profile : profiles) {
profile.Resize(-344, 1.0 / 138);
}
std::vector<double> lengths;
double total_length = 0.0;
for (Profile& profile : profiles) {
const double length = profile.GetLength();
lengths.push_back(length);
total_length += length;
}
std::vector<int> texture_sizes;
int total_texture_size = 0;
for (unsigned int i = 0; i < lengths.size(); ++i) {
const int texture_size = std::max(
static_cast<int>(round(lengths[i] / total_length * TEXTURE_SIZE)), 2);
texture_sizes.push_back(texture_size);
total_texture_size += texture_size;
}
int i = 0;
while (total_texture_size != TEXTURE_SIZE) {
if (texture_sizes[i] <= TEXTURE_SIZE / 20) {
i = (i + 1) % texture_sizes.size();
continue;
}
const int increment = total_texture_size > TEXTURE_SIZE ? -1 : 1;
texture_sizes[i] += increment;
total_texture_size += increment;
}
int texture_offset = 0;
for (unsigned int i = 0; i < lengths.size(); ++i) {
const double v0 = (texture_offset + 0.5) / TEXTURE_SIZE;
const double v1 = (texture_offset + texture_sizes[i] - 0.5) / TEXTURE_SIZE;
profiles[i].ComputeTexCoords(v0, (v1 - v0) / lengths[i]);
texture_offset += texture_sizes[i];
}
Mesh mesh = BuildMesh(profiles);
for (Profile& profile : profiles) {
profile.ComputeAmbientOcclusion(mesh);
}
Profile::Save(profiles, output_dir + "rocket.dat");
}
void ComputeRocketTextures(const std::string& input_dir,
const std::string& output_dir) {
png::image<png::rgba_pixel> color(input_dir + "color.png");
png::image<png::rgba_pixel> height(input_dir + "height.png");
png::image<png::rgba_pixel> occlusion(input_dir + "occlusion.png");
png::image<png::rgba_pixel> roughness(input_dir + "roughness.png");
png::image<png::rgba_pixel> metallic(input_dir + "metallic.png");
const int w = height.get_width();
const int h = height.get_height();
png::image<png::rgba_pixel> base_color_map(w, h);
png::image<png::rgba_pixel> occlusion_roughness_metallic_map(w, h);
png::image<png::rgba_pixel> normal_map(w, h);
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
const double slope_x =
(height[y][(x + 1) % w].red - height[y][(x + w - 1) % w].red) / 64.0;
const double slope_y = (height[std::max(y - 1, 0)][x].red -
height[std::min(y + 1, h - 1)][x].red) /
64.0;
const vec3 normal = normalize(vec3(-slope_x, -slope_y, 1.0));
base_color_map[y][x].red = color[y][x].red;
base_color_map[y][x].green = color[y][x].green;
base_color_map[y][x].blue = color[y][x].blue;
base_color_map[y][x].alpha = 255;
occlusion_roughness_metallic_map[y][x].red = occlusion[y][x].red;
occlusion_roughness_metallic_map[y][x].green = roughness[y][x].red;
occlusion_roughness_metallic_map[y][x].blue = metallic[y][x].red;
occlusion_roughness_metallic_map[y][x].alpha = 255;
normal_map[y][x].red =
static_cast<int>(round((normal.x() * 0.5 + 0.5) * 255.0));
normal_map[y][x].green =
static_cast<int>(round((normal.y() * 0.5 + 0.5) * 255.0));
normal_map[y][x].blue =
static_cast<int>(round((normal.z() * 0.5 + 0.5) * 255.0));
normal_map[y][x].alpha = 255;
}
}
base_color_map.write(output_dir + "rocket_base_color.png");
occlusion_roughness_metallic_map.write(
output_dir + "rocket_occlusion_roughness_metallic.png");
normal_map.write(output_dir + "rocket_normal.png");
}
} // namespace
} // namespace rocket
int main(int argc, char** argv) {
if (argc < 3) {
std::cerr << "Usage: rocket_generator <input directory> <output directory>"
<< std::endl;
return -1;
}
rocket::ComputeRocketModel(argv[2]);
rocket::ComputeRocketTextures(argv[1], argv[2]);
}
| 33.701754 | 80 | 0.594092 | [
"mesh",
"vector"
] |
0bb69c1fd900dbe0049ad50e356be81b9523283f | 6,681 | cc | C++ | nox/src/lib/poll-loop.cc | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 28 | 2015-02-04T13:59:25.000Z | 2021-12-29T03:44:47.000Z | nox/src/lib/poll-loop.cc | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 552 | 2015-01-05T18:25:54.000Z | 2022-03-16T18:51:13.000Z | nox/src/lib/poll-loop.cc | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 25 | 2015-02-04T18:48:20.000Z | 2020-06-18T15:51:05.000Z | /* Copyright 2008 (C) Nicira, Inc.
*
* This file is part of NOX.
*
* NOX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NOX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NOX. If not, see <http://www.gnu.org/licenses/>.
*/
#include "poll-loop.hh"
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <queue>
#include <vector>
#include "fault.hh"
#include "threads/cooperative.hh"
namespace vigil {
namespace {
struct Poll_thread
{
Co_sema wakeup;
co_thread* thread;
};
} // null namespace
class Poll_loop_impl
{
public:
Poll_loop_impl(unsigned int n_threads);
~Poll_loop_impl() { }
void add_pollable(Pollable*);
void remove_pollable(Pollable*);
void run();
private:
boost::ptr_vector<Poll_thread> threads;
Poll_thread* polling_thread;
std::deque<Poll_thread*> dormant_threads;
Co_cond new_pollable;
Co_sema started;
typedef std::list<Pollable_ref> Pollable_list;
Pollable_list pollables;
void poll_thread_main(Poll_thread*);
bool service_pollables(Poll_thread*);
void appoint_polling_thread(Pollable_list::iterator i);
};
Poll_loop_impl::Poll_loop_impl(unsigned int n_threads)
{
assert(n_threads > 0);
polling_thread = NULL;
threads.reserve(n_threads);
for (int i = 0; i < n_threads - 1; i++) {
Poll_thread* pt = new Poll_thread;
threads.push_back(pt);
pt->thread = co_thread_create(
&co_group_coop,
boost::bind(&Poll_loop_impl::poll_thread_main, this, pt));
started.down();
}
}
void
Poll_loop_impl::add_pollable(Pollable* p)
{
Pollable_ref ref = {p, 0};
p->pollables_pos = pollables.insert(pollables.end(), ref);
new_pollable.broadcast();
}
void
Poll_loop_impl::remove_pollable(Pollable* p)
{
Pollable_ref& ref = *p->pollables_pos;
assert(ref.pollable);
ref.pollable = NULL;
if (ref.ref_cnt == 0) {
pollables.erase(p->pollables_pos);
}
}
void
Poll_loop_impl::run()
{
Poll_thread* pt = new Poll_thread;
threads.push_back(pt);
pt->thread = co_self();
polling_thread = pt;
poll_thread_main(pt);
threads.pop_back();
}
#define NEXT_WITH_REFERENCE(CODE) \
do { \
Pollable_ref& ref = *i; \
++ref.ref_cnt; \
if (ref.pollable) { \
CODE; \
} \
if (!--ref.ref_cnt && !ref.pollable) { \
i = pollables.erase(i); \
} else { \
++i; \
} \
} while (0)
void
Poll_loop_impl::poll_thread_main(Poll_thread* pt)
{
started.up();
for (;;) {
/* Wait until we become the polling thread. */
if (pt != polling_thread) {
dormant_threads.push_front(pt);
pt->wakeup.down();
assert(pt == polling_thread);
}
/* Service pollables. */
while (service_pollables(pt)) {
co_poll();
co_yield();
}
if (pt == polling_thread) {
/* We are still the polling thread, but nobody has any work. */
co_might_yield();
Pollable_list::iterator end = pollables.end();
for (Pollable_list::iterator i = pollables.begin(); i != end; ) {
NEXT_WITH_REFERENCE(ref.pollable->wait());
}
new_pollable.wait();
co_block();
} else {
/* Some other thread is now the polling thread. */
}
}
}
bool
Poll_loop_impl::service_pollables(Poll_thread* pt)
{
assert(pt == polling_thread);
bool progress = false;
Pollable_list::iterator end = pollables.end();
for (Pollable_list::iterator i = pollables.begin(); i != end; ) {
NEXT_WITH_REFERENCE(
co_set_preblock_hook(
boost::bind(&Poll_loop_impl::appoint_polling_thread, this, i));
if (ref.pollable->poll()) {
progress = true;
}
co_unset_preblock_hook();
);
if (polling_thread != pt) {
/* p.poll() blocked somewhere, so we got removed as the polling
* thread. */
if (polling_thread) {
/* Someone else is the polling thread now. */
return false;
} else {
/* Everyone was busy, so we might as well reclaim the position.
* But there's no sense in retaining our current notion of
* progress, so we might as well return and let the caller
* start another loop. This has the cost of a call to
* co_poll(), but we need to make sure that that gets called
* sometime anyhow; it should have a relatively small cost
* relative to the cost of blocking and switching threads. */
polling_thread = pt;
return true;
}
}
}
return progress;
}
void
Poll_loop_impl::appoint_polling_thread(Pollable_list::iterator i)
{
/* Rotate the pollables list in-place, so that the next dispatcher we wake
* up will resume from where we left off. Otherwise pollables toward the
* end of the list will get starved if earlier ones tend to block. */
pollables.splice(pollables.begin(), pollables, ++i, pollables.end());
if (!dormant_threads.empty()) {
polling_thread = dormant_threads.front();
dormant_threads.pop_front();
polling_thread->wakeup.up();
} else {
polling_thread = NULL;
}
}
/* Implement Poll_loop_impl in terms of Poll_loop. */
Poll_loop::Poll_loop(unsigned int n_threads)
: pimpl(new Poll_loop_impl(n_threads))
{
}
Poll_loop::~Poll_loop()
{
delete pimpl;
}
void
Poll_loop::add_pollable(Pollable* p)
{
pimpl->add_pollable(p);
}
void
Poll_loop::remove_pollable(Pollable* p)
{
pimpl->remove_pollable(p);
}
void
Poll_loop::run()
{
pimpl->run();
}
} // namespace vigil
| 27.607438 | 79 | 0.587487 | [
"vector"
] |
0bbb26ee6aaef5bca242737fcef658be03571563 | 8,839 | cpp | C++ | CmnCtrl1/toolbar2.cpp | zemtsov-artem/PywinautoTestapps | 09153eb9ed3a951f1a7014d7e70e31ae02696b58 | [
"MIT"
] | 2 | 2020-06-17T15:22:30.000Z | 2022-02-08T00:02:03.000Z | CmnCtrl1/toolbar2.cpp | zemtsov-artem/PywinautoTestapps | 09153eb9ed3a951f1a7014d7e70e31ae02696b58 | [
"MIT"
] | 2 | 2016-02-29T20:21:22.000Z | 2020-05-28T00:51:33.000Z | CmnCtrl1/toolbar2.cpp | zemtsov-artem/PywinautoTestapps | 09153eb9ed3a951f1a7014d7e70e31ae02696b58 | [
"MIT"
] | 10 | 2015-12-14T18:55:28.000Z | 2021-06-30T11:39:08.000Z | // ToolBar2.cpp : implementation file
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "afxpriv.h"
#include "CmnCtrl1.h"
#include "Toolbar2.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CPaletteBar
CPaletteBar::CPaletteBar() : m_pTBButtons(NULL)
{
}
CPaletteBar::~CPaletteBar()
{
delete []m_pTBButtons;
}
BEGIN_MESSAGE_MAP(CPaletteBar, CToolBarCtrl)
//{{AFX_MSG_MAP(CPaletteBar)
ON_NOTIFY_RANGE( TTN_NEEDTEXTA, 0, 0xFFFF, OnNeedTextA)
ON_NOTIFY_RANGE( TTN_NEEDTEXTW, 0, 0xFFFF, OnNeedTextW)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL CPaletteBar::Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID )
{
BOOL bRet = CToolBarCtrl::Create(dwStyle, rect, pParentWnd, nID);
m_nButtonCount = ID_ELLIPSE - ID_ERASE + 1;
VERIFY(AddBitmap(m_nButtonCount,IDR_PALETTEBAR) != -1);
m_pTBButtons = new TBBUTTON[m_nButtonCount];
int nIndex;
for (nIndex = 0; nIndex < m_nButtonCount; nIndex++)
{
CString string;
string.LoadString(nIndex + ID_ERASE);
// Add second '\0'
int nStringLength = string.GetLength() + 1;
TCHAR* pString = string.GetBufferSetLength(nStringLength);
pString[nStringLength] = 0;
VERIFY((m_pTBButtons[nIndex].iString = AddStrings(pString)) != -1);
string.ReleaseBuffer();
m_pTBButtons[nIndex].fsState = TBSTATE_ENABLED;
m_pTBButtons[nIndex].fsStyle = TBSTYLE_CHECKGROUP;
m_pTBButtons[nIndex].dwData = 0;
m_pTBButtons[nIndex].iBitmap = nIndex;
m_pTBButtons[nIndex].idCommand = nIndex + ID_ERASE;
}
for (nIndex = 0; nIndex < m_nButtonCount; nIndex++)
{
VERIFY(AddButtons(1,&m_pTBButtons[nIndex]));
}
return bRet;
}
/////////////////////////////////////////////////////////////////////////////
// CPaletteBar message handlers
// MFC routes the notifications sent to the parent of the control to
// the control before the parent can process the notification.
// The control object can handle the notification or ignore it.
// If the notification is handled then return TRUE. Otherwise MFC
// will route it to the parent of the control.
BOOL CPaletteBar::OnChildNotify(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pLResult)
{
if (message == WM_NOTIFY)
{
NMHDR *pNMHDR = (NMHDR *) lParam;
switch (pNMHDR->code)
{
case TBN_BEGINADJUST :
return BeginAdjust(wParam, lParam, pLResult);
case TBN_BEGINDRAG:
return BeginDrag(wParam, lParam, pLResult);
case TBN_CUSTHELP:
return CustomizeHelp(wParam, lParam, pLResult);
case TBN_ENDADJUST:
return EndAdjust(wParam, lParam, pLResult);
case TBN_ENDDRAG:
return EndDrag(wParam, lParam, pLResult);
case TBN_GETBUTTONINFO:
return GetButtonInfo(wParam, lParam, pLResult);
case TBN_QUERYDELETE:
return QueryDelete(wParam, lParam, pLResult);
case TBN_QUERYINSERT:
return QueryInsert(wParam, lParam, pLResult);
case TBN_RESET:
return Reset(wParam, lParam, pLResult);
case TBN_TOOLBARCHANGE:
return ToolBarChange(wParam, lParam, pLResult);
}
}
return CToolBarCtrl::OnChildNotify(message, wParam, lParam, pLResult);
}
BOOL CPaletteBar::BeginAdjust(WPARAM /*wParam*/, LPARAM /*lParam*/, LRESULT* /*pLResult*/)
{
TRACE(_T("TBN_BEGINADJUST\n"));
// the customize dialog box is about to be displayed
// save toolbar state before customization using the dialog
// Use this information to restore the state if reset button is pressed
SaveState(HKEY_CURRENT_USER,_T("Software\\Microsoft\\VC70\\Samples\\CtrlDemo"),_T("Palette Tool Bar"));
return TRUE;
}
BOOL CPaletteBar::BeginDrag(WPARAM /*wParam*/, LPARAM /*lParam*/, LRESULT* pLResult)
{
TRACE(_T("TBN_BEGINDRAG\n"));
// we are not implementing custon drag and drop
* pLResult = FALSE;
return FALSE;
}
BOOL CPaletteBar::CustomizeHelp(WPARAM /*wParam*/, LPARAM /*lParam*/, LRESULT* /*pLResult*/)
{
TRACE(_T("TBN_CUSTHELP\n"));
// Sample displays a message box but a valid help topic
// can be displayed for the customize dialog for this toolbar
AfxMessageBox(_T("Help not implemented!"));
return TRUE;
}
BOOL CPaletteBar::EndAdjust(WPARAM /*wParam*/, LPARAM /*lParam*/, LRESULT* /*pLResult*/)
{
TRACE(_T("TBN_ENDADJUST\n"));
// the customize dialog box has been closed
return TRUE;
}
BOOL CPaletteBar::EndDrag(WPARAM /*wParam*/, LPARAM /*lParam*/, LRESULT* pLResult)
{
TRACE(_T("TBN_ENDDRAG\n"));
// Code to handle custom drag and drop. This message indicates that
// the item is being dropped
* pLResult = FALSE;
return TRUE;
}
BOOL CPaletteBar::GetButtonInfo(WPARAM /*wParam*/, LPARAM lParam, LRESULT* pLResult)
{
// This notification message has to be handled correctly if
// all operations in the custom dialogbox has to function correctly
// We have to supply information for the button specified by pTBN->tbButton
//
// This notification is sent in the following cases
//
// After TBN_BEGINADJUST the control sends these notifications until
// * pLResult is TRUE. We have to supply valid values when this value is
// set to TRUE. Here the control is collecting information for all
// the buttons that have to be displayed in the dialog box
//
// The control sends this notification to get information about
// a button if the user is trying to add it to the toolbar or
// rearranging the buttons on the toolbar from within the dialog
TRACE(_T("TBN_GETBUTTONINFO\n"));
TBNOTIFY *pTBN = (TBNOTIFY *) lParam;
if (pTBN->iItem >= m_nButtonCount || pTBN->iItem < 0)
{
* pLResult = FALSE;
}
else
{
CString buffer;
buffer.LoadString(pTBN->iItem + ID_ERASE);
// set the string for the button
// truncate the string if its length is greater than the buffer
// supplied by the toolbar
_tcsncpy_s(pTBN->pszText, pTBN->cchText, buffer, _TRUNCATE);
pTBN->pszText[pTBN->cchText - 1] = '\0';
// set the button info
pTBN->tbButton = m_pTBButtons[pTBN->iItem];
// valid values are structure
*pLResult = TRUE;
}
return TRUE;
}
BOOL CPaletteBar::QueryDelete(WPARAM /*wParam*/, LPARAM /*lParam*/, LRESULT* pLResult)
{
TRACE(_T("TBN_QUERYDELETE\n"));
// in this sample any button can be deleted
// if a particular button cannot be deleted set *pResult to FALSE for that item
*pLResult = TRUE;
return TRUE;
}
BOOL CPaletteBar::QueryInsert(WPARAM /*wParam*/, LPARAM /*lParam*/, LRESULT* pLResult)
{
TRACE(_T("TBN_QUERYINSERT\n"));
// in this sample buttons can be inserted at any location on the
// toolbar
*pLResult = TRUE;
return TRUE;
}
BOOL CPaletteBar::Reset(WPARAM /*wParam*/, LPARAM /*lParam*/, LRESULT* pLResult)
{
TRACE(_T("TBN_RESET\n"));
// User has pressed the reset button
// restore the state of the toolbar to the state it was before customization
RestoreState(HKEY_CURRENT_USER,_T("Software\\Microsoft\\VC70\\Samples\\CtrlDemo"),_T("Palette Tool Bar"));
*pLResult = TRUE;
return TRUE;
}
BOOL CPaletteBar::ToolBarChange(WPARAM /*wParam*/, LPARAM /*lParam*/, LRESULT* /*pLResult*/)
{
TRACE(_T("TBN_TOOLBARCHANGE\n"));
// the toolbar has changed
return TRUE;
}
// Helper function for tooltips
CString CPaletteBar::NeedText(UINT nID, NMHDR* pNotifyStruct, LRESULT* /*lResult*/ )
{
LPTOOLTIPTEXT lpTTT = (LPTOOLTIPTEXT)pNotifyStruct ;
ASSERT(nID == lpTTT->hdr.idFrom);
CString toolTipText;
toolTipText.LoadString(nID);
// szText length is 80
int nLength = (toolTipText.GetLength() > 79) ? 79 : toolTipText.GetLength();
toolTipText = toolTipText.Left(nLength);
return toolTipText;
}
void CPaletteBar::OnNeedTextW(UINT /*nID*/, NMHDR* pNotifyStruct, LRESULT * lResult )
{
//size_t numchars;
if (pNotifyStruct->idFrom >= ID_ERASE && pNotifyStruct->idFrom <= ID_ELLIPSE)
{
CString toolTipText = NeedText((UINT)pNotifyStruct->idFrom, pNotifyStruct, lResult);
LPTOOLTIPTEXTW lpTTT = (LPTOOLTIPTEXTW)pNotifyStruct;
#ifdef _UNICODE
_tcsncpy_s(lpTTT->szText, TTT_BUF_SIZE, (LPCTSTR)toolTipText, toolTipText.GetLength());
#else
mbstowcs_s(&numchars, lpTTT->szText, TTT_BUF_SIZE, (LPCTSTR)toolTipText, toolTipText.GetLength());
#endif
}
}
void CPaletteBar::OnNeedTextA(UINT /*nID*/, NMHDR* pNotifyStruct, LRESULT * lResult )
{
if (pNotifyStruct->idFrom >= ID_ERASE && pNotifyStruct->idFrom <= ID_ELLIPSE)
{
CString toolTipText = NeedText((UINT)pNotifyStruct->idFrom, pNotifyStruct, lResult);
LPTOOLTIPTEXT lpTTT = (LPTOOLTIPTEXT)pNotifyStruct;
_tcscpy_s(lpTTT->szText, TTT_BUF_SIZE, (LPCTSTR)toolTipText);
}
}
| 27.113497 | 107 | 0.716484 | [
"object"
] |
0bbf05fae7dc6b429782faf94e79d8c50d54fe41 | 11,230 | hpp | C++ | include/chronicle/data_log.hpp | ortfero/chronicle | 01142507775676d7e671f5a16353123184cf3e9a | [
"MIT"
] | null | null | null | include/chronicle/data_log.hpp | ortfero/chronicle | 01142507775676d7e671f5a16353123184cf3e9a | [
"MIT"
] | null | null | null | include/chronicle/data_log.hpp | ortfero/chronicle | 01142507775676d7e671f5a16353123184cf3e9a | [
"MIT"
] | null | null | null | /* This file is part of chronicle library
* Copyright 2020-2021 Andrei Ilin <ortfero@gmail.com>
*
* 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.
*/
#pragma once
#include <thread>
#include <atomic>
#include <vector>
#include <memory>
#if defined(_WIN32)
#if !defined(_X86_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_)
#if defined(_M_IX86)
#define _X86_
#elif defined(_M_AMD64)
#define _AMD64_
#elif defined(_M_ARM)
#define _ARM_
#elif defined(_M_ARM64)
#define _ARM64_
#endif
#endif
#include <processthreadsapi.h>
#endif
#ifdef CHRONICLE_USE_SYSTEM_HYDRA
#include <hydra/activity.hpp>
#include <hydra/queue_batch.hpp>
#include <hydra/mpsc_queue.hpp>
#include <hydra/spsc_queue.hpp>
#else
#include "bundled/hydra/activity.hpp"
#include "bundled/hydra/queue_batch.hpp"
#include "bundled/hydra/mpsc_queue.hpp"
#include "bundled/hydra/spsc_queue.hpp"
#endif // CHRONICLE_USE_SYSTEM_HYDRA
#ifdef CHRONICLE_USE_SYSTEM_UFORMAT
#include <uformat/texter.hpp>
#else
#include "bundled/uformat/texter.hpp"
#endif // CHRONICLE_USE_SYSTEM_UFORMAT
#include "traits.hpp"
#include "severity.hpp"
#include "message.hpp"
#include "sink.hpp"
namespace chronicle {
template<typename Tr>
struct data_log {
using data_type = typename Tr::data_type;
using format_type = typename Tr::format_type;
using queue_type = typename Tr::queue_type;
using clock_type = typename Tr::clock_type;
using duration = typename clock_type::duration;
using time_point = typename clock_type::time_point;
using message_type = message<data_type, time_point>;
using activity_type = hydra::activity<message_type, queue_type>;
using batch_type = typename activity_type::batch;
using size_type = typename activity_type::size_type;
using sinks_type = std::vector<std::unique_ptr<sink>>;
static constexpr size_type default_queue_size = 8192;
data_log(size_type message_size) noexcept:
message_size_{message_size}
{ }
data_log(data_log const&) = delete;
data_log& operator = (data_log const&) = delete;
~data_log() { close(); }
bool opened() const noexcept { return activity_.active(); }
size_type blocks_count() const noexcept { return activity_.blocks_count(); }
void severity(severity s) noexcept { severity_ = s; }
enum severity severity() const noexcept { return severity_; }
sinks_type const& sinks() const noexcept { return sinks_; }
void prologue(std::string text) noexcept { prologue_ = std::move(text); }
void epilogue(std::string text) noexcept { epilogue_ = std::move(text); }
bool add_sink(std::unique_ptr<sink>&& sink_ptr) {
if(!sink_ptr || !sink_ptr->ready())
return false;
sinks_.emplace_back(std::move(sink_ptr));
return true;
}
template<typename Rep, typename Period>
void flush_timeout(std::chrono::duration<Rep, Period> const& timeout) noexcept {
flush_timeout_ = timeout;
}
duration flush_timeout() const noexcept {
return flush_timeout_;
}
bool open(std::unique_ptr<sink>&& sink_ptr, size_type queue_size = default_queue_size) {
if(!add_sink(std::move(sink_ptr)))
return false;
return open(queue_size);
}
bool open(size_type queue_size = default_queue_size) {
if(sinks_.empty())
return false;
for(auto const& each_sink: sinks_)
if(!each_sink->ready())
return false;
if(!prologue_.empty())
for(auto& each_sink: sinks_)
each_sink->prologue(prologue_.data(), prologue_.size());
activity_.reserve(queue_size);
return activity_.run([this](auto& batch) {
buffer_.clear();
buffer_.reserve(message_size_ * batch.size());
auto const now = clock_type::now();
while(auto sequence = batch.try_fetch()) {
message_type& message = batch[sequence];
message.time = now;
format_.print(message, buffer_);
batch.fetched();
}
bool have_to_flush;
if(now - last_flush_time_ > flush_timeout_) {
last_flush_time_ = now;
have_to_flush = true;
} else {
have_to_flush = false;
}
for(auto& each_sink: sinks_) {
each_sink->write(now, buffer_.data(), buffer_.size());
if(have_to_flush)
each_sink->flush();
}
});
}
void close() {
if (!activity_.active())
return;
activity_.stop();
if(!epilogue_.empty())
for(auto& each_sink: sinks_)
each_sink->epilogue(epilogue_.data(), epilogue_.size());
for(auto& each_sink: sinks_)
each_sink->close();
}
template<size_t N1, size_t N2> void failure(char const (&tag)[N1], char const (&text)[N2]) {
this->template print<severity::failure>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1});
}
template<size_t N1, size_t N2> void failure(char const (&tag)[N1], char const (&text)[N2], data_type const& data) {
this->template print<severity::failure>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1}, data);
}
template<size_t N1, size_t N2> void error(char const (&tag)[N1], char const (&text)[N2]) {
this->template print<severity::error>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1});
}
template<size_t N1, size_t N2> void error(char const (&tag)[N1], char const (&text)[N2], data_type const& data) {
this->template print<severity::error>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1}, data);
}
template<typename R, size_t N1, size_t N2> R error_with(R&& r, char const (&tag)[N1], char const (&text)[N2]) {
this->template print<severity::error>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1});
return std::forward<R>(r);
}
template<typename R, size_t N1, size_t N2> R error_with(R&& r, char const (&tag)[N1], char const (&text)[N2], data_type const& data) {
this->template print<severity::error>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1}, data);
return std::forward<R>(r);
}
template<size_t N1, size_t N2> void warning(char const (&tag)[N1], char const (&text)[N2]) {
this->template print<severity::warning>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1});
}
template<size_t N1, size_t N2> void warning(char const (&tag)[N1], char const (&text)[N2], data_type const& data) {
this->template print<severity::warning>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1}, data);
}
template<size_t N1, size_t N2> void info(char const (&tag)[N1], char const (&text)[N2]) {
this->template print<severity::info>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1});
}
template<size_t N1, size_t N2> void info(char const (&tag)[N1], char const (&text)[N2], data_type const& data) {
this->template print<severity::info>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1}, data);
}
template<size_t N1, size_t N2> void extra(char const (&tag)[N1], char const (&text)[N2]) {
this->template print<severity::extra>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1});
}
template<size_t N1, size_t N2> void extra(char const (&tag)[N1], char const (&text)[N2], data_type const& data) {
this->template print<severity::extra>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1}, data);
}
template<size_t N1, size_t N2> void trace(char const (&tag)[N1], char const (&text)[N2]) {
this->template print<severity::trace>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1});
}
template<size_t N1, size_t N2> void trace(char const (&tag)[N1], char const (&text)[N2], data_type const& data) {
this->template print<severity::trace>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1}, data);
}
#ifdef NDEBUG
template<size_t N1, size_t N2> void debug(char const (&)[N1], char const (&)[N2]) {
}
template<size_t N1, size_t N2> void debug(char const (&)[N1], char const (&)[N2], data_type const&) {
}
#else
template<size_t N1, size_t N2> void debug(char const (&tag)[N1], char const (&text)[N2]) {
this->template print<severity::debug>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1});
}
template<size_t N1, size_t N2> void debug(char const (&tag)[N1], char const (&text)[N2], data_type const& data) {
this->template print<severity::debug>(std::string_view{tag, N1 - 1}, std::string_view{text, N2 - 1}, data);
}
#endif
protected:
template<chronicle::severity S> void print(std::string_view const& tag,
std::string_view const& text) {
if(severity_ < S)
return;
message_type* m = claim<S>(tag, text);
if(!m)
return;
publish(*m);
}
template<chronicle::severity S> void print(std::string_view const& tag,
std::string_view const& text,
data_type const& data) {
if(severity_ < S)
return;
message_type* m = claim<S>(tag, text);
if(!m)
return;
m->data = data;
m->has_data = true;
publish(*m);
}
void publish(message_type const& m) {
activity_.publish(m.sequence);
}
template<chronicle::severity S> message_type* claim(std::string_view const& source,
std::string_view const& text) {
auto const sequence = activity_.claim();
if(!sequence)
return nullptr;
message_type& m = activity_[sequence];
m.sequence = sequence;
m.severity = S;
#if defined(_WIN32)
m.thread_id = unsigned(GetCurrentThreadId());
#else
#error Unsupported system
#endif
m.source = source;
m.text = text;
m.has_data = false;
return &m;
}
private:
sinks_type sinks_;
enum severity severity_{chronicle::severity::info};
activity_type activity_;
size_type message_size_;
uformat::dynamic_texter buffer_;
duration flush_timeout_;
time_point last_flush_time_;
format_type format_;
std::string prologue_{"\n LOG OPENED\n\n"};
std::string epilogue_{"\n LOG CLOSED\n\n"};
}; // data_log
template<typename D>
using unique_data_log = data_log<traits_unique_default<D>>;
template<typename D>
using shared_data_log = data_log<traits_shared_default<D>>;
} // chronicle
| 29.397906 | 136 | 0.673197 | [
"vector"
] |
0bc23fa876809877ecb415a6db222df12275dad2 | 16,157 | cpp | C++ | app/PrefsDialog.cpp | Toysoft/ciderpress | 640959dad551ba75a48bd3c49629579730ead351 | [
"BSD-3-Clause"
] | null | null | null | app/PrefsDialog.cpp | Toysoft/ciderpress | 640959dad551ba75a48bd3c49629579730ead351 | [
"BSD-3-Clause"
] | null | null | null | app/PrefsDialog.cpp | Toysoft/ciderpress | 640959dad551ba75a48bd3c49629579730ead351 | [
"BSD-3-Clause"
] | null | null | null | /*
* CiderPress
* Copyright (C) 2007 by faddenSoft, LLC. All Rights Reserved.
* See the file LICENSE for distribution terms.
*/
#include "stdafx.h"
#include "PrefsDialog.h"
#include "ChooseDirDialog.h"
#ifdef CAN_UPDATE_FILE_ASSOC
#include "EditAssocDialog.h"
#endif
#include "Main.h"
#include "NufxArchive.h"
#include "resource.h"
#include <afxpriv.h> // need WM_COMMANDHELP
/*
* ===========================================================================
* PrefsGeneralPage
* ===========================================================================
*/
BEGIN_MESSAGE_MAP(PrefsGeneralPage, CPropertyPage)
ON_CONTROL_RANGE(BN_CLICKED, IDC_COL_PATHNAME, IDC_COL_ACCESS, OnChangeRange)
ON_BN_CLICKED(IDC_PREF_SHRINKIT_COMPAT, OnChange)
ON_BN_CLICKED(IDC_PREF_REDUCE_SHK_ERROR_CHECKS, OnChange)
ON_BN_CLICKED(IDC_PREF_SHK_BAD_MAC, OnChange)
ON_BN_CLICKED(IDC_PREF_COERCE_DOS, OnChange)
ON_BN_CLICKED(IDC_PREF_SPACES_TO_UNDER, OnChange)
ON_BN_CLICKED(IDC_PREF_PASTE_JUNKPATHS, OnChange)
ON_BN_CLICKED(IDC_PREF_SUCCESS_BEEP, OnChange)
ON_BN_CLICKED(IDC_COL_DEFAULTS, OnDefaults)
#ifdef CAN_UPDATE_FILE_ASSOC
ON_BN_CLICKED(IDC_PREF_ASSOCIATIONS, OnAssociations)
#endif
ON_MESSAGE(WM_HELP, OnHelpInfo)
ON_MESSAGE(WM_COMMANDHELP, OnCommandHelp)
END_MESSAGE_MAP()
void PrefsGeneralPage::OnChange(void)
{
/*
* They clicked on a checkbox, just mark the page as dirty so the "apply"
* button will be enabled.
*/
SetModified(TRUE);
}
void PrefsGeneralPage::OnChangeRange(UINT nID)
{
SetModified(TRUE);
}
void PrefsGeneralPage::OnDefaults(void)
{
/*
* Since we don't actually set column widths here, we need to tell the main
* window that the defaults button was pushed. It needs to reset all column
* widths to defaults, and then take into account any checking and un-checking
* that was done after "defaults" was pushed.
*/
LOGD("OnDefaults");
CButton* pButton;
fDefaultsPushed = true;
ASSERT(IDC_COL_ACCESS == IDC_COL_PATHNAME + (kNumVisibleColumns-1));
/* assumes that the controls are numbered sequentially */
for (int i = 0; i < kNumVisibleColumns; i++) {
pButton = (CButton*) GetDlgItem(IDC_COL_PATHNAME+i);
ASSERT(pButton != NULL);
pButton->SetCheck(1); // 0=unchecked, 1=checked, 2=indeterminate
}
SetModified(TRUE);
}
#ifdef CAN_UPDATE_FILE_ASSOC
void PrefsGeneralPage::OnAssociations(void)
{
EditAssocDialog assocDlg;
assocDlg.fOurAssociations = fOurAssociations;
fOurAssociations = NULL;
if (assocDlg.DoModal() == IDOK) {
/*
* Make a copy of the changes and mark us as modified so
* the Apply/Cancel buttons behave as expected. (We don't make
* a copy so much as steal the data from the dialog object.)
*/
delete[] fOurAssociations;
fOurAssociations = assocDlg.fOurAssociations;
assocDlg.fOurAssociations = NULL;
SetModified(TRUE);
}
}
#endif
void PrefsGeneralPage::DoDataExchange(CDataExchange* pDX)
{
/*
* The various column checkboxes are independent. We still do the xfer
* for "pathname" even though it's disabled.
*/
fReady = true;
ASSERT(NELEM(fColumn) == 9);
DDX_Check(pDX, IDC_COL_PATHNAME, fColumn[0]);
DDX_Check(pDX, IDC_COL_TYPE, fColumn[1]);
DDX_Check(pDX, IDC_COL_AUXTYPE, fColumn[2]);
DDX_Check(pDX, IDC_COL_MODDATE, fColumn[3]);
DDX_Check(pDX, IDC_COL_FORMAT, fColumn[4]);
DDX_Check(pDX, IDC_COL_SIZE, fColumn[5]);
DDX_Check(pDX, IDC_COL_RATIO, fColumn[6]);
DDX_Check(pDX, IDC_COL_PACKED, fColumn[7]);
DDX_Check(pDX, IDC_COL_ACCESS, fColumn[8]);
DDX_Check(pDX, IDC_PREF_SHRINKIT_COMPAT, fMimicShrinkIt);
DDX_Check(pDX, IDC_PREF_SHK_BAD_MAC, fBadMacSHK);
DDX_Check(pDX, IDC_PREF_REDUCE_SHK_ERROR_CHECKS, fReduceSHKErrorChecks);
DDX_Check(pDX, IDC_PREF_COERCE_DOS, fCoerceDOSFilenames);
DDX_Check(pDX, IDC_PREF_SPACES_TO_UNDER, fSpacesToUnder);
DDX_Check(pDX, IDC_PREF_PASTE_JUNKPATHS, fPasteJunkPaths);
DDX_Check(pDX, IDC_PREF_SUCCESS_BEEP, fBeepOnSuccess);
}
/*
* ===========================================================================
* PrefsDiskImagePage
* ===========================================================================
*/
BEGIN_MESSAGE_MAP(PrefsDiskImagePage, CPropertyPage)
ON_BN_CLICKED(IDC_PDISK_CONFIRM_FORMAT, OnChange)
ON_BN_CLICKED(IDC_PDISK_OPENVOL_RO, OnChange)
ON_BN_CLICKED(IDC_PDISK_OPENVOL_PHYS0, OnChange)
ON_BN_CLICKED(IDC_PDISK_PRODOS_ALLOWLOWER, OnChange)
ON_BN_CLICKED(IDC_PDISK_PRODOS_USESPARSE, OnChange)
ON_MESSAGE(WM_HELP, OnHelpInfo)
ON_MESSAGE(WM_COMMANDHELP, OnCommandHelp)
END_MESSAGE_MAP()
BOOL PrefsDiskImagePage::OnInitDialog(void)
{
//LOGI("OnInit!");
return CPropertyPage::OnInitDialog();
}
void PrefsDiskImagePage::OnChange(void)
{
LOGD("OnChange");
SetModified(TRUE); // enable the "apply" button
}
//void PrefsDiskImagePage::OnChangeRange(UINT nID)
//{
// LOGD("OnChangeRange id=%d", nID);
// SetModified(TRUE);
//}
void PrefsDiskImagePage::DoDataExchange(CDataExchange* pDX)
{
fReady = true;
DDX_Check(pDX, IDC_PDISK_CONFIRM_FORMAT, fQueryImageFormat);
DDX_Check(pDX, IDC_PDISK_OPENVOL_RO, fOpenVolumeRO);
DDX_Check(pDX, IDC_PDISK_OPENVOL_PHYS0, fOpenVolumePhys0);
DDX_Check(pDX, IDC_PDISK_PRODOS_ALLOWLOWER, fProDOSAllowLower);
DDX_Check(pDX, IDC_PDISK_PRODOS_USESPARSE, fProDOSUseSparse);
}
/*
* ===========================================================================
* PrefsCompressionPage
* ===========================================================================
*/
BEGIN_MESSAGE_MAP(PrefsCompressionPage, CPropertyPage)
ON_CONTROL_RANGE(BN_CLICKED, IDC_DEFC_UNCOMPRESSED, IDC_DEFC_BZIP2, OnChangeRange)
ON_MESSAGE(WM_HELP, OnHelpInfo)
ON_MESSAGE(WM_COMMANDHELP, OnCommandHelp)
END_MESSAGE_MAP()
BOOL PrefsCompressionPage::OnInitDialog(void)
{
if (!NufxArchive::IsCompressionSupported(kNuThreadFormatHuffmanSQ)) {
DisableWnd(IDC_DEFC_SQUEEZE);
if (fCompressType == kNuThreadFormatHuffmanSQ)
fCompressType = kNuThreadFormatUncompressed;
}
if (!NufxArchive::IsCompressionSupported(kNuThreadFormatLZW1)) {
DisableWnd(IDC_DEFC_LZW1);
if (fCompressType == kNuThreadFormatLZW1)
fCompressType = kNuThreadFormatUncompressed;
}
if (!NufxArchive::IsCompressionSupported(kNuThreadFormatLZW2)) {
DisableWnd(IDC_DEFC_LZW2);
if (fCompressType == kNuThreadFormatLZW2) {
fCompressType = kNuThreadFormatUncompressed;
}
}
if (!NufxArchive::IsCompressionSupported(kNuThreadFormatLZC12)) {
DisableWnd(IDC_DEFC_LZC12);
if (fCompressType == kNuThreadFormatLZC12)
fCompressType = kNuThreadFormatUncompressed;
}
if (!NufxArchive::IsCompressionSupported(kNuThreadFormatLZC16)) {
DisableWnd(IDC_DEFC_LZC16);
if (fCompressType == kNuThreadFormatLZC16)
fCompressType = kNuThreadFormatUncompressed;
}
if (!NufxArchive::IsCompressionSupported(kNuThreadFormatDeflate)) {
DisableWnd(IDC_DEFC_DEFLATE);
if (fCompressType == kNuThreadFormatDeflate)
fCompressType = kNuThreadFormatUncompressed;
}
if (!NufxArchive::IsCompressionSupported(kNuThreadFormatBzip2)) {
DisableWnd(IDC_DEFC_BZIP2);
if (fCompressType == kNuThreadFormatBzip2)
fCompressType = kNuThreadFormatUncompressed;
}
/* now invoke DoDataExchange with our modified fCompressType */
return CPropertyPage::OnInitDialog();
}
void PrefsCompressionPage::DisableWnd(int id)
{
CWnd* pWnd;
pWnd = GetDlgItem(id);
if (pWnd == NULL) {
ASSERT(false);
return;
}
pWnd->EnableWindow(FALSE);
}
void PrefsCompressionPage::OnChangeRange(UINT nID)
{
SetModified(TRUE); // enable the "apply" button
}
void PrefsCompressionPage::DoDataExchange(CDataExchange* pDX)
{
/*
* Compression types match the NuThreadFormat enum in NufxLib.h, starting
* with IDC_DEFC_UNCOMPRESSED.
*/
LOGV("OnInit comp!");
fReady = true;
DDX_Radio(pDX, IDC_DEFC_UNCOMPRESSED, fCompressType);
}
/*
* ===========================================================================
* PrefsFviewPage
* ===========================================================================
*/
BEGIN_MESSAGE_MAP(PrefsFviewPage, CPropertyPage)
ON_CONTROL_RANGE(BN_CLICKED, IDC_PVIEW_NOWRAP_TEXT, IDC_PVIEW_HIRES_BW, OnChangeRange)
ON_CONTROL_RANGE(BN_CLICKED, IDC_PVIEW_HITEXT, IDC_PVIEW_TEXT8, OnChangeRange)
ON_EN_CHANGE(IDC_PVIEW_SIZE_EDIT, OnChange)
ON_CBN_SELCHANGE(IDC_PVIEW_DHR_CONV_COMBO, OnChange)
ON_MESSAGE(WM_HELP, OnHelpInfo)
ON_MESSAGE(WM_COMMANDHELP, OnCommandHelp)
END_MESSAGE_MAP()
BOOL PrefsFviewPage::OnInitDialog(void)
{
CSpinButtonCtrl* pSpin;
LOGV("Configuring spin");
pSpin = (CSpinButtonCtrl*) GetDlgItem(IDC_PVIEW_SIZE_SPIN);
ASSERT(pSpin != NULL);
UDACCEL uda;
uda.nSec = 0;
uda.nInc = 64;
pSpin->SetRange(1, 32767);
pSpin->SetAccel(1, &uda);
LOGD("OnInit done!");
return CPropertyPage::OnInitDialog();
}
void PrefsFviewPage::OnChange(void)
{
LOGD("OnChange");
SetModified(TRUE); // enable the "apply" button
}
void PrefsFviewPage::OnChangeRange(UINT nID)
{
LOGD("OnChangeRange id=%d", nID);
SetModified(TRUE);
}
void PrefsFviewPage::DoDataExchange(CDataExchange* pDX)
{
fReady = true;
//DDX_Check(pDX, IDC_PVIEW_EOL_RAW, fEOLConvRaw);
DDX_Check(pDX, IDC_PVIEW_NOWRAP_TEXT, fNoWrapText);
DDX_Check(pDX, IDC_PVIEW_BOLD_HEXDUMP, fHighlightHexDump);
DDX_Check(pDX, IDC_PVIEW_BOLD_BASIC, fHighlightBASIC);
DDX_Check(pDX, IDC_PVIEW_DISASM_ONEBYTEBRKCOP, fConvDisasmOneByteBrkCop);
DDX_Check(pDX, IDC_PVIEW_HIRES_BW, fConvHiResBlackWhite);
DDX_CBIndex(pDX, IDC_PVIEW_DHR_CONV_COMBO, fConvDHRAlgorithm);
DDX_Check(pDX, IDC_PVIEW_HITEXT, fConvTextEOL_HA);
DDX_Check(pDX, IDC_PVIEW_CPMTEXT, fConvCPMText);
DDX_Check(pDX, IDC_PVIEW_PASCALTEXT, fConvPascalText);
DDX_Check(pDX, IDC_PVIEW_PASCALCODE, fConvPascalCode);
DDX_Check(pDX, IDC_PVIEW_APPLESOFT, fConvApplesoft);
DDX_Check(pDX, IDC_PVIEW_INTEGER, fConvInteger);
DDX_Check(pDX, IDC_PVIEW_GWP, fConvGWP);
DDX_Check(pDX, IDC_PVIEW_TEXT8, fConvText8);
DDX_Check(pDX, IDC_PVIEW_AWP, fConvAWP);
DDX_Check(pDX, IDC_PVIEW_ADB, fConvADB);
DDX_Check(pDX, IDC_PVIEW_ASP, fConvASP);
DDX_Check(pDX, IDC_PVIEW_SCASSEM, fConvSCAssem);
DDX_Check(pDX, IDC_PVIEW_DISASM, fConvDisasm);
DDX_Check(pDX, IDC_PVIEW_HIRES, fConvHiRes);
DDX_Check(pDX, IDC_PVIEW_DHR, fConvDHR);
DDX_Check(pDX, IDC_PVIEW_SHR, fConvSHR);
DDX_Check(pDX, IDC_PVIEW_PRINTSHOP, fConvPrintShop);
DDX_Check(pDX, IDC_PVIEW_MACPAINT, fConvMacPaint);
DDX_Check(pDX, IDC_PVIEW_PRODOSFOLDER, fConvProDOSFolder);
DDX_Check(pDX, IDC_PVIEW_RESOURCES, fConvResources);
DDX_Check(pDX, IDC_PVIEW_RELAX_GFX, fRelaxGfxTypeCheck);
DDX_Text(pDX, IDC_PVIEW_SIZE_EDIT, fMaxViewFileSizeKB);
DDV_MinMaxUInt(pDX, fMaxViewFileSizeKB, 1, 32767);
}
/*
* ===========================================================================
* PrefsFilesPage
* ===========================================================================
*/
BEGIN_MESSAGE_MAP(PrefsFilesPage, CPropertyPage)
ON_EN_CHANGE(IDC_PREF_TEMP_FOLDER, OnChange)
ON_EN_CHANGE(IDC_PREF_EXTVIEWER_EXTS, OnChange)
ON_BN_CLICKED(IDC_PREF_CHOOSE_TEMP_FOLDER, OnChooseFolder)
ON_MESSAGE(WM_HELP, OnHelpInfo)
ON_MESSAGE(WM_COMMANDHELP, OnCommandHelp)
END_MESSAGE_MAP()
BOOL PrefsFilesPage::OnInitDialog(void)
{
fChooseFolderButton.ReplaceDlgCtrl(this, IDC_PREF_CHOOSE_TEMP_FOLDER);
fChooseFolderButton.SetBitmapID(IDB_CHOOSE_FOLDER);
return CPropertyPage::OnInitDialog();
}
void PrefsFilesPage::OnChange(void)
{
SetModified(TRUE); // enable the "apply" button
}
void PrefsFilesPage::DoDataExchange(CDataExchange* pDX)
{
fReady = true;
DDX_Text(pDX, IDC_PREF_TEMP_FOLDER, fTempPath);
DDX_Text(pDX, IDC_PREF_EXTVIEWER_EXTS, fExtViewerExts);
/* validate the path field */
if (pDX->m_bSaveAndValidate) {
if (fTempPath.IsEmpty()) {
CString appName;
CheckedLoadString(&appName, IDS_MB_APP_NAME);
MessageBox(L"You must specify a path for temp files",
appName, MB_OK);
pDX->Fail();
}
// we *could* try to validate the path here...
}
}
void PrefsFilesPage::OnChooseFolder(void)
{
/*
* They want to choose the folder from a menu hierarchy. Show them a list.
*/
ChooseDirDialog chooseDir(this);
CWnd* pEditWnd;
CString editPath;
/* get the currently-showing text from the edit field */
pEditWnd = GetDlgItem(IDC_PREF_TEMP_FOLDER);
ASSERT(pEditWnd != NULL);
pEditWnd->GetWindowText(editPath);
chooseDir.SetPathName(editPath);
if (chooseDir.DoModal() == IDOK) {
const WCHAR* ccp = chooseDir.GetPathName();
LOGD("New temp path chosen = '%ls'", ccp);
pEditWnd->SetWindowText(ccp);
// activate the "apply" button
OnChange();
}
}
/*
* ===========================================================================
* PrefsSheet
* ===========================================================================
*/
BEGIN_MESSAGE_MAP(PrefsSheet, CPropertySheet)
ON_WM_NCCREATE()
ON_BN_CLICKED(ID_APPLY_NOW, OnApplyNow)
ON_COMMAND(ID_HELP, OnIDHelp)
ON_MESSAGE(WM_HELP, OnHelpInfo)
END_MESSAGE_MAP()
PrefsSheet::PrefsSheet(CWnd* pParentWnd) :
CPropertySheet(L"Preferences", pParentWnd)
{
AddPage(&fGeneralPage);
AddPage(&fDiskImagePage);
AddPage(&fFviewPage);
AddPage(&fCompressionPage);
AddPage(&fFilesPage);
/* this happens automatically with appropriate ID_HELP handlers */
//m_psh.dwFlags |= PSH_HASHELP;
}
BOOL PrefsSheet::OnNcCreate(LPCREATESTRUCT cs)
{
LOGV("PrefsSheet OnNcCreate");
BOOL val = CPropertySheet::OnNcCreate(cs);
ModifyStyleEx(0, WS_EX_CONTEXTHELP);
return val;
}
void PrefsSheet::OnApplyNow(void)
{
BOOL result;
if (fGeneralPage.fReady) {
//LOGI("Apply to general?");
result = fGeneralPage.UpdateData(TRUE);
if (!result)
return;
}
if (fDiskImagePage.fReady) {
//LOGI("Apply to disk images?");
result = fDiskImagePage.UpdateData(TRUE);
if (!result)
return;
}
if (fCompressionPage.fReady) {
//LOGI("Apply to compression?");
result = fCompressionPage.UpdateData(TRUE);
if (!result)
return;
}
if (fFviewPage.fReady) {
//LOGI("Apply to fview?");
result = fFviewPage.UpdateData(TRUE);
if (!result)
return;
}
if (fFilesPage.fReady) {
//LOGI("Apply to fview?");
result = fFilesPage.UpdateData(TRUE);
if (!result)
return;
}
/* reset all to "unmodified" state */
LOGD("All 'applies' were successful");
((MainWindow*) AfxGetMainWnd())->ApplyNow(this);
fGeneralPage.SetModified(FALSE);
fGeneralPage.fDefaultsPushed = false;
fDiskImagePage.SetModified(FALSE);
fCompressionPage.SetModified(FALSE);
fFviewPage.SetModified(FALSE);
fFilesPage.SetModified(FALSE);
}
void PrefsSheet::OnIDHelp(void)
{
LOGD("PrefsSheet OnIDHelp");
SendMessage(WM_COMMANDHELP);
}
| 31.556641 | 91 | 0.644303 | [
"object"
] |
0bc44b688408a15050784e8b0ba6b7f0b32410e5 | 29,074 | cpp | C++ | src/old/generate_constraints.cpp | souradeep-111/sherlock | bf34fb4713e5140b893c98382055fb963230d69d | [
"MIT"
] | 34 | 2018-02-17T14:18:57.000Z | 2022-03-08T19:21:00.000Z | src/old/generate_constraints.cpp | souradeep-111/sherlock_2 | 763e5817cca2b69f0e96560835a442434980b3a8 | [
"MIT"
] | 4 | 2018-02-09T07:58:44.000Z | 2021-01-15T14:32:02.000Z | src/old/generate_constraints.cpp | souradeep-111/sherlock_2 | 763e5817cca2b69f0e96560835a442434980b3a8 | [
"MIT"
] | 12 | 2018-02-05T15:13:05.000Z | 2021-10-05T04:16:44.000Z | #include "generate_constraints.h"
mutex mtx_gen_cons;
bool debug_gen_constr = true;
constraints_stack :: constraints_stack()
{
env_ptr = new GRBEnv();
erase_line();
env_ptr->set(GRB_IntParam_OutputFlag, 0);
model_ptr = new GRBModel(*env_ptr);
model_ptr->set(GRB_DoubleParam_IntFeasTol, sherlock_parameters.int_tolerance);
neurons.clear();
binaries.clear();
neuron_bounds.clear();
}
void constraints_stack :: create_the_input_overapproximation_for_each_neuron(
computation_graph & CG,
region_constraints & input
)
{
// Need to write this :
// Takes in as input some description of the input region and does an
// analysis to give over and under approximtion of the input ranges to each neuron
input_region = input;
map< uint32_t, node >& all_nodes = CG.return_ref_to_all_nodes();
vector< uint32_t > input_indices, output_indices;
CG.return_id_of_input_output_nodes(input_indices, output_indices);
for(auto each_node : all_nodes)
{
auto flag = find(input_indices.begin(), input_indices.end(), each_node.first);
if(flag == input_indices.end())
{
neuron_bounds[each_node.first] = make_pair(-sherlock_parameters.MILP_M, sherlock_parameters.MILP_M);
}
}
}
void constraints_stack :: generate_graph_constraints(region_constraints & region,
computation_graph & CG,
uint32_t output_node_id)
{
// Basically encode the whole network here
// Getting a reference to all the nodes in the computation graph
map< uint32_t, node >& all_nodes = CG.return_ref_to_all_nodes();
// Declaring the neurons for the input nodes of the computation graph
vector< uint32_t > input_node_indices, output_node_indices;
CG.return_id_of_input_output_nodes(input_node_indices, output_node_indices);
for(auto & input_node_index : input_node_indices)
{
GRBVar var = model_ptr->addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_CONTINUOUS, all_nodes[input_node_index].get_node_name() );
neurons.insert( make_pair( input_node_index , var ) );
}
/* NOTE : Don't change 'neurons' here, it is supposed to be a list of input neurons to the computation graph here */
// impose constraints on the input nodes of the computation graph
region.add_this_region_to_MILP_model(neurons, model_ptr);
// A table which keeps track of the nodes who's constraints have already been added ,
// we initialize it with the inputs of the computation graph to begin with
vector < uint32_t > explored_nodes;
for(auto each_input_index : input_node_indices)
{
explored_nodes.push_back(each_input_index);
}
// Call generate_node_constraints on the output of the graph
generate_node_constraints(CG, explored_nodes ,output_node_id);
}
void constraints_stack :: generate_node_constraints( computation_graph & CG,
vector< uint32_t > explored_nodes,
uint32_t output_node_id)
{
// NOTE: ALGORITHM--
// Create a queue for unexplored nodes in the graph
// Until the queue is empty
// pop a node
// Call the function : add constraint for node
// if threads are available and there is still stuff in the queue
// pop a node , ..... (basically everything that you did in the main loop )
// wait for all the threads you started to end
map< uint32_t, node >& all_nodes = CG.return_ref_to_all_nodes();
set < uint32_t > unexplored_nodes;
GRBVar output_var = model_ptr->addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_CONTINUOUS, all_nodes[output_node_id].get_node_name());
neurons.insert(make_pair(output_node_id, output_var));
vector< thread > threads_currently_running;
set< uint32_t > nodes_to_explore;
unexplored_nodes.insert(output_node_id);
uint32_t current_node_id;
while(!unexplored_nodes.empty())
{
current_node_id = *(unexplored_nodes.begin());
unexplored_nodes.erase(unexplored_nodes.begin());
// cout << "Adding constraints for " << current_node_id << endl;
add_constraints_for_node(*this, current_node_id, CG, model_ptr, nodes_to_explore);
explored_nodes.push_back(current_node_id);
// Adding all the new nodes to explore to the list
for(set<uint32_t> ::iterator it = nodes_to_explore.begin(); it != nodes_to_explore.end(); it ++)
{
unexplored_nodes.insert(*it);
}
// cout << "Unexplored nodes : [ " ;
// for(set<uint32_t> ::iterator it = unexplored_nodes.begin(); it != unexplored_nodes.end(); it ++)
// {
// cout << *it << " , ";
// }
// cout << " ] " << endl;
}
}
void add_constraints_for_node(constraints_stack & CS, uint32_t current_node_id,
computation_graph & CG, GRBModel * model_ptr,
set < uint32_t >& nodes_to_explore )
{
map< uint32_t, GRBVar > input_nodes_to_the_current_node;
map< uint32_t, pair< node * , double > > list_of_backward_nodes;
nodes_to_explore.erase(current_node_id);
map< uint32_t, node >& all_nodes = CG.return_ref_to_all_nodes();
all_nodes[current_node_id].get_backward_connections(list_of_backward_nodes);
GRBVar ip_sum = model_ptr->addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_CONTINUOUS,
all_nodes[current_node_id].get_node_name() + "_ip_sum" );
input_nodes_to_the_current_node.clear();
for(auto backward_node : list_of_backward_nodes)
{
string check_string("input_node");
auto is_an_input_node = ( CG.return_node_position(backward_node.first)).compare(check_string);
if(( is_an_input_node != 0) && (CS.neurons.find(backward_node.first) == CS.neurons.end()))
{
// Create a gurobi variable which will be used for adding constraints using that backward
// nodes' output.
GRBVar gurobi_var = model_ptr->addVar(-GRB_INFINITY, GRB_INFINITY, 0.0, GRB_CONTINUOUS,
all_nodes[backward_node.first].get_node_name());
CS.neurons.insert(make_pair(backward_node.first, gurobi_var));
nodes_to_explore.insert(backward_node.first);
input_nodes_to_the_current_node.insert(make_pair(backward_node.first, gurobi_var));
}
else
{
input_nodes_to_the_current_node.insert(make_pair(backward_node.first, CS.neurons[backward_node.first]));
}
}
CS.create_sum_of_inputs_and_return_var(input_nodes_to_the_current_node, all_nodes[current_node_id], ip_sum, model_ptr);
CS.relate_input_output(all_nodes[current_node_id], ip_sum, CS.neurons[current_node_id], model_ptr);
}
// Remember this function might be implemented inside several threads, need to keep in mind
// how the different threads behave
void constraints_stack :: create_sum_of_inputs_and_return_var(map< uint32_t, GRBVar > & inputs_to_node,
node current_node,
GRBVar & sum_variable,
GRBModel * model_ptr)
{
// Given a Gurobi Var vector , sum them up and return a reference to the return val
GRBVar gurobi_one = model_ptr->addVar(1.0, 1.0, 0.0, GRB_CONTINUOUS, "const_name");
map< uint32_t, pair< node* , double > > backward_nodes;
current_node.get_backward_connections(backward_nodes);
double data, weight_val, bias_val;
uint32_t node_index;
GRBLinExpr expression_1, expression_2;
GRBLinExpr expression_zero(0.0);
expression_1 = expression_zero;
current_node.get_bias(bias_val);
for(auto some_backward_node : backward_nodes)
{
node_index = some_backward_node.first;
weight_val = some_backward_node.second.second;
data = weight_val;
expression_1.addTerms(& data, & inputs_to_node[node_index], 1);
}
data = bias_val;
expression_1.addTerms(& data, & gurobi_one, 1);
model_ptr->addConstr(expression_1, GRB_EQUAL, sum_variable, current_node.get_node_name() + "_sum_constr_");
}
double constraints_stack :: get_M_val_for_node(uint32_t node_index)
{
assert(neuron_bounds[node_index].first < neuron_bounds[node_index].second);
double max;
if(abs(neuron_bounds[node_index].first) > abs(neuron_bounds[node_index].second))
{
max = abs(neuron_bounds[node_index].first);
}
else
{
max = abs(neuron_bounds[node_index].second);
}
return max;
}
// Remember this function might be implemented inside several threads, need to keep in mind
// how the different threads behave
void constraints_stack :: relate_input_output(node current_node,
GRBVar input_var, GRBVar output_var,
GRBModel * model_ptr)
{
// Basically input some switch-case type implementation
// if node_type is a _none_, then just say input = output
// if node type is _relu_, then add one binary variable, and use the big M from the input ranges
// computed and add the constraint
// if node type is sigmoid/tanh/etc , get the upper bound and lower bound constraints
// add them, and assert that the output is indeed included there
type node_type = current_node.get_node_type();
if(node_type == _none_)
{
model_ptr->addConstr(input_var, GRB_EQUAL, output_var, current_node.get_node_name() + "_ip_op_constr_" );
}
else if(node_type == _relu_)
{
if(!sherlock_parameters.encode_relu_new)
{
GRBVar current_node_binary_var = model_ptr->addVar( 0.0, 1.0, 0.0, GRB_BINARY, current_node.get_node_name() + "_delta_" );
GRBVar gurobi_one = model_ptr->addVar(1.0, 1.0, 0.0, GRB_CONTINUOUS, "const_name");
binaries[current_node.get_node_number()] = current_node_binary_var;
GRBLinExpr expression(0.0);
double data = 1.0;
expression.addTerms(& data, & input_var, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & current_node_binary_var, 1);
data = (sherlock_parameters.int_tolerance * get_M_val_for_node(current_node.get_node_number()));
expression.addTerms(& data, & gurobi_one, 1);
model_ptr->addConstr(output_var, GRB_LESS_EQUAL, expression, current_node.get_node_name() + "_ip_op_constr_a_");
model_ptr->addConstr(output_var, GRB_GREATER_EQUAL, input_var, current_node.get_node_name() + "_ip_op_constr_b_");
model_ptr->addConstr(output_var, GRB_GREATER_EQUAL, 0.0, current_node.get_node_name() + "_ip_op_constr_c_");
GRBLinExpr expression_0(0.0);
data = get_M_val_for_node(current_node.get_node_number());
expression_0.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression_0.addTerms( & data, & current_node_binary_var, 1);
data = get_M_val_for_node(current_node.get_node_number()) * (-sherlock_parameters.int_tolerance);
expression_0.addTerms(& data, & gurobi_one, 1);
model_ptr->addConstr(output_var, GRB_LESS_EQUAL, expression_0, current_node.get_node_name() + "_ip_op_constr_d_");
GRBLinExpr trick_expression(0.0);
data = sherlock_parameters.epsilon;
trick_expression.addTerms(& data, & gurobi_one, 1);
data = (-get_M_val_for_node(current_node.get_node_number()));
trick_expression.addTerms(& data, & current_node_binary_var, 1);
model_ptr->addConstr(input_var, GRB_GREATER_EQUAL, trick_expression, current_node.get_node_name() + "_trick_lower");
GRBLinExpr trick_expression_(0.0);
data = (-sherlock_parameters.epsilon);
trick_expression_.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
trick_expression_.addTerms(&data, & gurobi_one, 1);
data = (-get_M_val_for_node(current_node.get_node_number()));
trick_expression_.addTerms(& data, & current_node_binary_var, 1);
model_ptr->addConstr(input_var, GRB_LESS_EQUAL, trick_expression_, current_node.get_node_name() + "_trick_upper");
}
else
{
GRBVar current_node_binary_var = model_ptr->addVar( 0.0, 1.0, 0.0, GRB_BINARY, current_node.get_node_name() + "_delta_" );
GRBVar gurobi_one = model_ptr->addVar(1.0, 1.0, 0.0, GRB_CONTINUOUS, "const_name");
binaries[current_node.get_node_number()] = current_node_binary_var;
GRBLinExpr expression(0.0);
double data = 1.0;
expression.addTerms(& data, & input_var, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & current_node_binary_var, 1);
model_ptr->addConstr(output_var, GRB_LESS_EQUAL, expression, current_node.get_node_name() + "_ip_op_constr_a_");
model_ptr->addConstr(output_var, GRB_GREATER_EQUAL, input_var, current_node.get_node_name() + "_ip_op_constr_b_");
model_ptr->addConstr(output_var, GRB_GREATER_EQUAL, 0.0, current_node.get_node_name() + "_ip_op_constr_c_");
GRBLinExpr expression_0(0.0);
data = get_M_val_for_node(current_node.get_node_number());
expression_0.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression_0.addTerms(& data, & current_node_binary_var, 1);
model_ptr->addConstr(output_var, GRB_LESS_EQUAL, expression_0, current_node.get_node_name() + "_ip_op_constr_d_");
GRBLinExpr trick_expression(0.0);
data = sherlock_parameters.epsilon;
trick_expression.addTerms(& data, & gurobi_one, 1);
data = (-get_M_val_for_node(current_node.get_node_number()));
trick_expression.addTerms(& data, & current_node_binary_var, 1);
model_ptr->addConstr(input_var, GRB_GREATER_EQUAL, trick_expression, current_node.get_node_name() + "_trick_lower");
GRBLinExpr trick_expression_(0.0);
data = (-sherlock_parameters.epsilon);
trick_expression_.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
trick_expression_.addTerms(&data, & gurobi_one, 1);
data = (-get_M_val_for_node(current_node.get_node_number()));
trick_expression_.addTerms(& data, & current_node_binary_var, 1);
model_ptr->addConstr(input_var, GRB_LESS_EQUAL, trick_expression_, current_node.get_node_name() + "_trick_upper");
}
}
else if(node_type == _sigmoid_)
{
GRBVar binary_1 = model_ptr->addVar(0.0, 1.0, 0.0, GRB_BINARY, current_node.get_node_name() + "_delta_1_");
GRBVar binary_2 = model_ptr->addVar(0.0, 1.0, 0.0, GRB_BINARY, current_node.get_node_name() + "_delta_2_");
GRBVar binary_3 = model_ptr->addVar(0.0, 1.0, 0.0, GRB_BINARY, current_node.get_node_name() + "_delta_3_");
GRBVar gurobi_one = model_ptr->addVar(1.0, 1.0, 0.0, GRB_CONTINUOUS, "const_name");
GRBLinExpr expression(0.0);
double data = 1.0;
expression.addTerms(& data, & binary_1, 1);
data = 1.0;
expression.addTerms(& data, & binary_2, 1);
data = 1.0;
expression.addTerms(& data, & binary_3, 1);
model_ptr->addConstr(expression, GRB_EQUAL, 1.0, current_node.get_node_name() + "_binary_sum_constraint_");
model_ptr->addConstr(output_var, GRB_LESS_EQUAL, 1.0, current_node.get_node_name() + "_output_upper_" );
model_ptr->addConstr(output_var, GRB_GREATER_EQUAL, 0.0, current_node.get_node_name() + "_output_lower_" );
// Linear Piece #1
expression = 0.0;
data = -2.3-sherlock_parameters.epsilon;
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_1, 1);
model_ptr->addConstr(input_var, GRB_LESS_EQUAL, expression, current_node.get_node_name() + "_left_input_" );
expression = 0.0;
data = 0.1;
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_1, 1);
model_ptr->addConstr(output_var, GRB_LESS_EQUAL, expression, current_node.get_node_name() + "_left_output_");
// Linear Piece #2
expression = 0.0;
data = 2.3 - sherlock_parameters.epsilon;
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_2, 1);
model_ptr->addConstr(input_var, GRB_LESS_EQUAL, expression, current_node.get_node_name() + "_middle_input_a_" );
expression = 0.0;
data = -2.3 + sherlock_parameters.epsilon;
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_2, 1);
model_ptr->addConstr(input_var, GRB_GREATER_EQUAL, expression, current_node.get_node_name() + "_middle_input_b_" );
expression = 0.0;
data = 0.2;
expression.addTerms(& data, & input_var , 1);
data = 0.55;
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_2, 1);
model_ptr->addConstr(output_var, GRB_LESS_EQUAL, expression, current_node.get_node_name() + "_middle_output_a_");
expression = 0.0;
data = 0.2;
expression.addTerms(& data, & input_var , 1);
data = 0.45;
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_2, 1);
model_ptr->addConstr(output_var, GRB_GREATER_EQUAL, expression, current_node.get_node_name() + "_middle_output_b_");
// Linear Piece #3
expression = 0.0;
data = 2.3 + sherlock_parameters.epsilon;
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_3, 1);
model_ptr->addConstr(input_var, GRB_GREATER_EQUAL, expression, current_node.get_node_name() + "_right_input_" );
expression = 0.0;
data = 0.9;
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_3, 1);
model_ptr->addConstr(output_var, GRB_GREATER_EQUAL, expression, current_node.get_node_name() + "_right_output_");
}
else if(node_type == _tanh_)
{
GRBVar binary_1 = model_ptr->addVar(0.0, 1.0, 0.0, GRB_BINARY, current_node.get_node_name() + "_delta_1_");
GRBVar binary_2 = model_ptr->addVar(0.0, 1.0, 0.0, GRB_BINARY, current_node.get_node_name() + "_delta_2_");
GRBVar binary_3 = model_ptr->addVar(0.0, 1.0, 0.0, GRB_BINARY, current_node.get_node_name() + "_delta_3_");
GRBVar gurobi_one = model_ptr->addVar(1.0, 1.0, 0.0, GRB_CONTINUOUS, "const_name");
GRBLinExpr expression(0.0);
double data = 1.0;
expression.addTerms(& data, & binary_1, 1);
data = 1.0;
expression.addTerms(& data, & binary_2, 1);
data = 1.0;
expression.addTerms(& data, & binary_3, 1);
model_ptr->addConstr(expression, GRB_EQUAL, 1.0, current_node.get_node_name() + "_binary_sum_constraint_");
model_ptr->addConstr(output_var, GRB_LESS_EQUAL, 1.0, current_node.get_node_name() + "_output_upper_" );
model_ptr->addConstr(output_var, GRB_GREATER_EQUAL, -1.0, current_node.get_node_name() + "_output_lower_" );
// Linear Piece #1
expression = 0.0;
data = -1.5-sherlock_parameters.epsilon;
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_1, 1);
model_ptr->addConstr(input_var, GRB_LESS_EQUAL, expression, current_node.get_node_name() + "_left_input_" );
expression = 0.0;
data = -0.9;
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_1, 1);
model_ptr->addConstr(output_var, GRB_LESS_EQUAL, expression, current_node.get_node_name() + "_left_output_");
// Linear Piece #2
expression = 0.0;
data = 1.5 - sherlock_parameters.epsilon;
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_2, 1);
model_ptr->addConstr(input_var, GRB_LESS_EQUAL, expression, current_node.get_node_name() + "_middle_input_a_" );
expression = 0.0;
data = -1.5 + sherlock_parameters.epsilon;
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_2, 1);
model_ptr->addConstr(input_var, GRB_GREATER_EQUAL, expression, current_node.get_node_name() + "_middle_input_b_" );
expression = 0.0;
data = 0.7;
expression.addTerms(& data, & input_var , 1);
data = 0.15;
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_2, 1);
model_ptr->addConstr(output_var, GRB_LESS_EQUAL, expression, current_node.get_node_name() + "_middle_output_a_");
expression = 0.0;
data = 0.7;
expression.addTerms(& data, & input_var , 1);
data = -0.14;
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_2, 1);
model_ptr->addConstr(output_var, GRB_GREATER_EQUAL, expression, current_node.get_node_name() + "_middle_output_b_");
// Linear Piece #3
expression = 0.0;
data = 1.5 + sherlock_parameters.epsilon;
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_3, 1);
model_ptr->addConstr(input_var, GRB_GREATER_EQUAL, expression, current_node.get_node_name() + "_right_input_" );
expression = 0.0;
data = 0.9;
expression.addTerms(& data, & gurobi_one, 1);
data = -get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & gurobi_one, 1);
data = get_M_val_for_node(current_node.get_node_number());
expression.addTerms(& data, & binary_3, 1);
model_ptr->addConstr(output_var, GRB_GREATER_EQUAL, expression, current_node.get_node_name() + "_right_output_");
}
else
{
cout << "Node type relation missing from the code " << endl;
assert(false);
}
}
void constraints_stack :: delete_and_reinitialize()
{
if(model_ptr)
delete model_ptr;
if(env_ptr)
delete env_ptr;
env_ptr = new GRBEnv();
erase_line();
env_ptr->set(GRB_IntParam_OutputFlag, 0);
model_ptr = new GRBModel(*env_ptr);
neurons.clear();
binaries.clear();
neuron_bounds.clear();
}
void constraints_stack :: add_invariants()
{
// Make a call to the right function in generate invariants and do the implementation
}
bool constraints_stack :: optimize(uint32_t node_index, bool direction,
map< uint32_t, double >& neuron_value,
double & result)
{
neuron_value.clear();
GRBLinExpr objective_expr;
objective_expr = 0;
double data = 1.0;
objective_expr.addTerms(& data, & neurons[node_index] , 1);
if(direction)
{
model_ptr->setObjective(objective_expr, GRB_MAXIMIZE);
}
else
{
model_ptr->setObjective(objective_expr, GRB_MINIMIZE);
}
model_ptr->optimize();
model_ptr->update();
string s = "./Gurobi_file_created/Linear_program.lp";
model_ptr->write(s);
//
// cout << "Status = " << model_ptr->get(GRB_IntAttr_Status) << endl;
// cout << "Objective = " << model_ptr->get(GRB_DoubleAttr_ObjVal) << endl;
// cout << "Objective in the neurons list = " << neurons[node_index].get(GRB_DoubleAttr_X) << endl;
//
// GRBVar *vars = 0;
// int numvars = model_ptr->get(GRB_IntAttr_NumVars);
// vars = model_ptr->getVars();
//
// cout << "Number of variables = " << numvars << endl;
// for (int j = 0; j < numvars; j++)
// {
// GRBVar v = vars[j];
// cout << "For var name = " << v.get(GRB_StringAttr_VarName) ;
// cout << " ------- Value = " << v.get(GRB_DoubleAttr_X) << endl;
// }
// cout << endl;
//
if(model_ptr->get(GRB_IntAttr_Status) == GRB_OPTIMAL)
{
neuron_value.clear();
for(auto & some_neuron : neurons)
{
neuron_value[some_neuron.first] = some_neuron.second.get(GRB_DoubleAttr_X);
}
result = neuron_value[node_index];
nodes_explored_last_optimization = model_ptr->get(GRB_DoubleAttr_NodeCount);
return true;
}
else if(model_ptr->get(GRB_IntAttr_Status) == GRB_INFEASIBLE)
{
neuron_value.clear();
nodes_explored_last_optimization = model_ptr->get(GRB_DoubleAttr_NodeCount);
return false;
}
else
{
cout << "Some unkown Gurobi flag !" << endl;
cout << "Flag returned - " << model_ptr->get(GRB_IntAttr_Status) << endl;
assert(false);
return false;
}
return false;
}
bool constraints_stack :: optimize_enough(uint32_t node_index,
double& current_optima, bool direction,
map< uint32_t, double >& neuron_value)
{
GRBLinExpr objective_expr;
objective_expr = 0;
double data = 1.0;
objective_expr.addTerms(& data, & neurons[node_index] , 1);
if(direction)
{
data = current_optima + sherlock_parameters.MILP_tolerance;
model_ptr->getEnv().set(GRB_IntParam_SolutionLimit, 1);
model_ptr->getEnv().set(GRB_DoubleParam_Cutoff, data);
model_ptr->setObjective(objective_expr, GRB_MAXIMIZE);
}
else
{
data = current_optima - sherlock_parameters.MILP_tolerance;
model_ptr->getEnv().set(GRB_IntParam_SolutionLimit, 1);
model_ptr->getEnv().set(GRB_DoubleParam_Cutoff, data);
model_ptr->setObjective(objective_expr, GRB_MINIMIZE);
}
// Initializing the input vars
// First, open all plants
// for (p = 0; p < nPlants; ++p)
// {
// open[p].set(GRB_DoubleAttr_Start, 1.0);
// }
vector< int > input_indices = input_region.get_input_indices();
for(auto index : input_indices)
{
neurons[index].set(GRB_DoubleAttr_Start, neuron_value[index]);
}
model_ptr->update();
model_ptr->optimize();
string s = "./Gurobi_file_created/Linear_program.lp";
model_ptr->write(s);
if((model_ptr->get(GRB_IntAttr_Status) == GRB_OPTIMAL) || (model_ptr->get(GRB_IntAttr_Status) == GRB_SOLUTION_LIMIT) )
{
neuron_value.clear();
for(auto & some_neuron : neurons)
{
neuron_value[some_neuron.first] = some_neuron.second.get(GRB_DoubleAttr_X);
}
current_optima = neuron_value[node_index];
nodes_explored_last_optimization = model_ptr->get(GRB_DoubleAttr_NodeCount);
return true;
}
else if((model_ptr->get(GRB_IntAttr_Status) == GRB_INFEASIBLE) || (model_ptr->get(GRB_IntAttr_Status) == GRB_CUTOFF) )
{
neuron_value.clear();
nodes_explored_last_optimization = model_ptr->get(GRB_DoubleAttr_NodeCount);
return false;
}
else
{
cout << "Some unkown Gurobi flag !" << endl;
cout << "Flag returned - " << model_ptr->get(GRB_IntAttr_Status) << endl;
assert(false);
return false;
}
return false;
}
| 38.559682 | 134 | 0.687865 | [
"vector"
] |
0bcf61b5b9442b1241ff60a3d4b3a72d3a8869ca | 1,354 | hpp | C++ | ppsh/proc.hpp | easyeagel/core | 3c1c4e5e6337cc319e70ff38af3fa820de0c83dc | [
"MIT"
] | null | null | null | ppsh/proc.hpp | easyeagel/core | 3c1c4e5e6337cc319e70ff38af3fa820de0c83dc | [
"MIT"
] | null | null | null | ppsh/proc.hpp | easyeagel/core | 3c1c4e5e6337cc319e70ff38af3fa820de0c83dc | [
"MIT"
] | null | null | null | // Copyright [2014] <lgb (LiuGuangBao)>
//=====================================================================================
//
// Filename: proc.hpp
//
// Description: Linux proc 文件系统
//
// Version: 1.0
// Created: 2013年12月26日 14时49分23秒
// Revision: none
// Compiler: gcc
//
// Author: lgb (LiuGuangBao), easyeagel@gmx.com
// Organization: ezbty.org
//
//=====================================================================================
#ifndef PPSH_PROC_HPP
#define PPSH_PROC_HPP
#include<ctime>
#include<string>
#include<vector>
namespace ppsh
{
typedef ::pid_t PID_t;
class ProcessInfo
{
public:
ProcessInfo()=default;
ProcessInfo(PID_t pid)
:pid_(pid)
{}
PID_t pidGet() const
{
return pid_;
}
const std::string& cmdGet() const
{
return cmd_;
}
std::time_t startTimeGet() const
{
return startTime_;
}
bool refresh();
static ProcessInfo cmdInfoRead(const std::string& cmd);
bool empty() const
{
return pid_==0;
}
private:
PID_t pid_=0;
std::string cmd_;
std::time_t startTime_;
};
class SysProc
{
public:
void refresh();
const ProcessInfo* find(const std::string& name) const;
private:
std::vector<ProcessInfo> proc_;
};
}
#endif //PPSH_PROC_HPP
| 16.119048 | 87 | 0.522157 | [
"vector"
] |
0bd517310d2536600b9dd5d982c87d66245f207c | 4,423 | cc | C++ | TopDownTW.cc | JoeyEremondi/treewidth-memoization | 5cd6be9e05bba189d14409f28c37805948ef11b3 | [
"BSD-3-Clause"
] | 1 | 2015-07-25T15:09:11.000Z | 2015-07-25T15:09:11.000Z | TopDownTW.cc | JoeyEremondi/treewidth-memoization | 5cd6be9e05bba189d14409f28c37805948ef11b3 | [
"BSD-3-Clause"
] | 1 | 2015-09-19T00:44:24.000Z | 2015-09-21T16:47:12.000Z | TopDownTW.cc | JoeyEremondi/treewidth-memoization | 5cd6be9e05bba189d14409f28c37805948ef11b3 | [
"BSD-3-Clause"
] | null | null | null | #include "TopDownTW.hh"
#include "UpperBound.hh"
#include "BottomUpTW.hh"
#include "Simplicial.hh"
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream> // for ostringstream
#include <cassert>
const int maxDictSize = 1000000000;
const int maxBottumUpSize = 1000000000;
const int topLevelNoStore = 10;
const int bottomLevelNoStore = 5;
TopDownTW::TopDownTW(const Graph& gIn)
: G(gIn)
, allVertices(boost::vertices(G).first, boost::vertices(G).second)
, bottomUpInfo(G, maxBottumUpSize)
{
nGraph = boost::num_vertices(G);
std::sort(allVertices.begin(), allVertices.end(),
[gIn](auto v1, auto v2) -> bool
{
return boost::degree(v1, gIn) > boost::degree(v2, gIn);
});
}
int TopDownTW::topDownTW(const Graph& G)
{
//First, check if we found a bottom-up solution without running out of space
if (bottomUpInfo.foundSolution())
{
std::cout << "Bottom up found solution\n";
return bottomUpInfo.solution();
}
std::cout << "Bottom up finished after " << bottomUpInfo.levelReached() << " levels\n";
VSet S(G);
//Remove elements in the max-clique of G
VSet maxClique = exactMaxClique(G);
std::vector<Vertex> cliqueVec(maxClique.size());
maxClique.members(cliqueVec);
std::cout << "Max clique " << showSet(maxClique) << "\n";
for (auto iter = cliqueVec.begin(); iter != cliqueVec.end(); ++iter)
{
S.erase(*iter);
}
sharedUpperBound = bottomUpInfo.bestUpperBound();
lowerBound = d2degen(S, G);
std::cout << "d2 lower " << lowerBound << "\n";
lowerBound = std::max(lowerBound, MMD(S, G));
std::cout << "MMD lower " << MMD(S, G) << "\n";
std::cout << "Found lower bound " << lowerBound << "\n";
return topDownTWFromSet(G, S, S.size());
}
int TopDownTW::topDownTWFromSet(const Graph& G, const VSet& S, int nSet)
{
static std::vector<std::map<VSet, int>> TW(nGraph);
const int threshold = -1;
if (S.empty())
{
return NO_WIDTH;
}
else if (nSet <= bottomUpInfo.levelReached())
{
auto searchInfo = bottomUpInfo.topLevelDict()->find(S);
if (searchInfo == bottomUpInfo.topLevelDict()->end())
{
return sharedUpperBound;
}
else
{
return searchInfo->second;
}
}
auto setSearch = TW[nSet].find(S);
auto setEnd = TW[nSet].end();
if (setSearch != setEnd) //TODO replace with memo lookup
{
return setSearch->second;
}
/*
else if (nSet < threshold)
{
return bottomUpTWFromSet(G, S, sharedUpperBound);
}*/
else
{
std::vector<int> qValues(nGraph);
findQvalues(nGraph, S, G, qValues);
int minTW = sharedUpperBound;
//Do a simplicial vertex first if it exists
for (Vertex v : allVertices)
{
if (false)//(S.contains(v) && isSimplicial(G, v, SStart))
{
VSet SminusV(S);
SminusV.erase(v);
int finalTW = minTW = std::min(minTW, std::max(qValues[v], topDownTWFromSet(G, SminusV, nSet - 1)));
TW[nSet][S] = minTW;
return finalTW;
}
}
for (Vertex v : allVertices)
{
if (S.contains(v))
{
VSet SminusV(S);
SminusV.erase(v);
int q = qValues[v];
//assert(setUpperBound >= sharedUpperBound);
//Don't recursively calculate TW if we know Q is bigger
/*
if (q >= setUpperBound)
{
minTW = std::min(minTW, q);
}*/
if (q < minTW || q < sharedUpperBound )
{
int setUpperBound = sharedUpperBound;
std::vector<Vertex> sortedMembers;
SminusV.members(sortedMembers);
setUpperBound = permutTW(nGraph, S, sortedMembers, G);
if (q >= setUpperBound || setUpperBound < lowerBound)
{
minTW = std::min(minTW, q);
}
else
{
minTW = std::min(minTW, std::max(q, topDownTWFromSet(G, SminusV, nSet - 1)));
sharedUpperBound = std::min(sharedUpperBound, std::max(minTW, nGraph - nSet - 1));
}
}
}
}
try
{
//Don't cache the top few layers, to save space
//Same for the bottom few layers
if (nGraph - nSet > topLevelNoStore && nSet > bottomLevelNoStore)
{
TW[nSet][S] = minTW;
numInDict++;
if (numInDict % 500000 == 0)
{
std::cerr << numInDict << " elements currently stored\n";
}
}
}
catch (const std::bad_alloc& e) {
std::cerr << numInDict << " elements stored in Dict\n";
std::cerr << "Emptying layer" << nSet << ", deleting" << TW[nSet].size() << " elements\n";
numInDict -= TW[nSet].size();
TW[nSet].clear(); //TODO smarter than emptying entire layer?
}
return minTW;
}
}
| 20.668224 | 104 | 0.631246 | [
"vector"
] |
0be2f69df31a8b252ed6d23f862b667f921bf704 | 6,346 | cpp | C++ | src/blocks/loop_roll.cpp | AjayBrahmakshatriya/mirror-cpp | f19fdfbfdc3f333a5e20f88374b87a3509dd1af7 | [
"MIT"
] | 46 | 2021-01-06T22:32:35.000Z | 2022-03-20T23:22:36.000Z | src/blocks/loop_roll.cpp | AjayBrahmakshatriya/mirror-cpp | f19fdfbfdc3f333a5e20f88374b87a3509dd1af7 | [
"MIT"
] | 2 | 2021-01-07T15:24:05.000Z | 2022-03-31T18:32:19.000Z | src/blocks/loop_roll.cpp | AjayBrahmakshatriya/mirror-cpp | f19fdfbfdc3f333a5e20f88374b87a3509dd1af7 | [
"MIT"
] | 4 | 2021-03-02T19:25:53.000Z | 2021-12-26T14:12:47.000Z | #include "blocks/loop_roll.h"
#include "builder/builder.h"
#include "builder/dyn_var.h"
namespace block {
static bool is_roll(std::string s) {
if (s != "" && s.length() > 5 && s[0] == 'r' && s[1] == 'o' &&
s[2] == 'l' && s[3] == 'l' && s[4] == '.')
return true;
return false;
}
static int unique_counter = 0;
static void process_match(stmt_block::Ptr b, int match_start, int match_end) {
stmt::Ptr first = b->stmts[match_start];
constant_expr_finder finder;
first->accept(&finder);
unsigned int num_constants = finder.constants.size();
// Assume int constants for now
std::vector<std::vector<int>> vals;
vals.resize(num_constants);
for (unsigned int i = 0; i < num_constants; i++) {
vals[i].push_back(to<int_const>(finder.constants[i])->value);
}
for (int i = match_start + 1; i < match_end; i++) {
constant_expr_finder finder;
b->stmts[i]->accept(&finder);
assert(finder.constants.size() == num_constants);
for (unsigned int j = 0; j < num_constants; j++)
vals[j].push_back(
to<int_const>(finder.constants[j])->value);
}
std::vector<stmt::Ptr> new_stmts;
for (int i = 0; i < match_start; i++) {
new_stmts.push_back(b->stmts[i]);
}
std::vector<var::Ptr> new_vars;
for (unsigned int i = 0; i < num_constants; i++) {
var::Ptr new_var = std::make_shared<var>();
new_var->var_name =
"roll_var_" + std::to_string(unique_counter);
unique_counter++;
new_var->var_type =
builder::dyn_var<int[]>::create_block_type();
to<array_type>(new_var->var_type)->size =
match_end - match_start;
decl_stmt::Ptr new_decl = std::make_shared<decl_stmt>();
new_decl->decl_var = new_var;
new_vars.push_back(new_var);
initializer_list_expr::Ptr new_init =
std::make_shared<initializer_list_expr>();
for (unsigned int j = 0; j < vals[i].size(); j++) {
int_const::Ptr new_const =
std::make_shared<int_const>();
new_const->value = vals[i][j];
new_init->elems.push_back(new_const);
}
new_decl->init_expr = new_init;
new_stmts.push_back(new_decl);
}
for_stmt::Ptr new_for = std::make_shared<for_stmt>();
var::Ptr i_var = std::make_shared<var>();
i_var->var_name = "index_var_" + std::to_string(unique_counter);
unique_counter++;
i_var->var_type = builder::dyn_var<int>::create_block_type();
decl_stmt::Ptr new_decl = std::make_shared<decl_stmt>();
new_decl->decl_var = i_var;
int_const::Ptr init_const = std::make_shared<int_const>();
init_const->value = 0;
new_decl->init_expr = init_const;
new_for->decl_stmt = new_decl;
lt_expr::Ptr new_lt = std::make_shared<lt_expr>();
var_expr::Ptr new_var_expr = std::make_shared<var_expr>();
new_var_expr->var1 = i_var;
int_const::Ptr new_const_expr = std::make_shared<int_const>();
new_const_expr->value = match_end - match_start;
new_lt->expr1 = new_var_expr;
new_lt->expr2 = new_const_expr;
new_for->cond = new_lt;
assign_expr::Ptr new_assign = std::make_shared<assign_expr>();
new_var_expr = std::make_shared<var_expr>();
new_var_expr->var1 = i_var;
var_expr::Ptr new_var_expr2 = std::make_shared<var_expr>();
new_var_expr2->var1 = i_var;
new_const_expr = std::make_shared<int_const>();
new_const_expr->value = 1;
plus_expr::Ptr new_plus = std::make_shared<plus_expr>();
new_plus->expr1 = new_var_expr2;
new_plus->expr2 = new_const_expr;
new_assign->var1 = new_var_expr;
new_assign->expr1 = new_plus;
new_for->update = new_assign;
new_for->body = std::make_shared<stmt_block>();
// Replace constants
std::vector<expr::Ptr> replace;
for (unsigned int i = 0; i < num_constants; i++) {
sq_bkt_expr::Ptr new_sq_bkt = std::make_shared<sq_bkt_expr>();
var_expr::Ptr new_var1 = std::make_shared<var_expr>();
new_var1->var1 = new_vars[i];
var_expr::Ptr new_var2 = std::make_shared<var_expr>();
new_var2->var1 = i_var;
new_sq_bkt->var_expr = new_var1;
new_sq_bkt->index = new_var2;
replace.push_back(new_sq_bkt);
}
constant_replacer replacer;
replacer.replace = replace;
first->accept(&replacer);
to<stmt_block>(new_for->body)->stmts.push_back(first);
first->annotation = "from." + first->annotation;
new_stmts.push_back(new_for);
for (unsigned int i = match_end; i < b->stmts.size(); i++)
new_stmts.push_back(b->stmts[i]);
b->stmts = new_stmts;
}
void loop_roll_finder::visit(stmt_block::Ptr b) {
// First visit all the children
for (auto stmt : b->stmts) {
stmt->accept(this);
}
// Now find opportunities for rolling
while (1) {
int match_start = -1;
int match_end = -1;
for (unsigned int i = 0; i < b->stmts.size(); i++) {
auto stmt = b->stmts[i];
if (is_roll(stmt->annotation)) {
std::string match = stmt->annotation;
match_start = i;
match_end = b->stmts.size();
for (; i < b->stmts.size(); i++) {
if (b->stmts[i]->annotation != match) {
match_end = i;
break;
}
}
}
}
if (match_start != -1) {
process_match(b, match_start, match_end);
} else
break;
}
}
void constant_expr_finder::visit(int_const::Ptr a) { constants.push_back(a); }
void constant_replacer::visit(plus_expr::Ptr a) {
if (isa<const_expr>(a->expr1)) {
a->expr1 = replace[curr_index++];
} else
a->expr1->accept(this);
if (isa<const_expr>(a->expr2)) {
a->expr2 = replace[curr_index++];
} else
a->expr2->accept(this);
}
void constant_replacer::visit(mul_expr::Ptr a) {
if (isa<const_expr>(a->expr1)) {
a->expr1 = replace[curr_index++];
} else
a->expr1->accept(this);
if (isa<const_expr>(a->expr2)) {
a->expr2 = replace[curr_index++];
} else
a->expr2->accept(this);
}
void constant_replacer::visit(minus_expr::Ptr a) {
if (isa<const_expr>(a->expr1)) {
a->expr1 = replace[curr_index++];
} else
a->expr1->accept(this);
if (isa<const_expr>(a->expr2)) {
a->expr2 = replace[curr_index++];
} else
a->expr2->accept(this);
}
void constant_replacer::visit(div_expr::Ptr a) {
if (isa<const_expr>(a->expr1)) {
a->expr1 = replace[curr_index++];
} else
a->expr1->accept(this);
if (isa<const_expr>(a->expr2)) {
a->expr2 = replace[curr_index++];
} else
a->expr2->accept(this);
}
void constant_replacer::visit(sq_bkt_expr::Ptr a) {
if (isa<const_expr>(a->var_expr)) {
a->var_expr = replace[curr_index++];
} else
a->var_expr->accept(this);
if (isa<const_expr>(a->index)) {
a->index = replace[curr_index++];
} else
a->index->accept(this);
}
} // namespace block
| 29.654206 | 78 | 0.670816 | [
"vector"
] |
0be66ce08e600d71cdd1dae2fea54795b66b50e8 | 28,021 | cc | C++ | dcmtk-master2/dcmsr/libcmr/cid7469.cc | happymanx/Weather_FFI | a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f | [
"MIT"
] | null | null | null | dcmtk-master2/dcmsr/libcmr/cid7469.cc | happymanx/Weather_FFI | a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f | [
"MIT"
] | null | null | null | dcmtk-master2/dcmsr/libcmr/cid7469.cc | happymanx/Weather_FFI | a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f | [
"MIT"
] | null | null | null | /*
*
* Copyright (C) 2015-2021, J. Riesmeier, Oldenburg, Germany
* All rights reserved. See COPYRIGHT file for details.
*
* Source file for class CID7469_GenericIntensityAndSizeMeasurements
*
* Generated automatically from DICOM PS 3.16-2021d
* File created on 2021-09-13 09:26:40 by J. Riesmeier
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmsr/cmr/cid7469.h"
// general information on CID 7469 (Generic Intensity and Size Measurements)
#define CONTEXT_GROUP_NUMBER "7469"
#define CONTEXT_GROUP_VERSION "20141110"
#define CONTEXT_GROUP_UID "1.2.840.10008.6.1.1003"
#define CONTEXT_GROUP_TYPE OFTrue /* extensible */
// initialize global/static variable
CID7469_GenericIntensityAndSizeMeasurements::CodeList *CID7469_GenericIntensityAndSizeMeasurements::Codes = NULL;
CID7469_GenericIntensityAndSizeMeasurements::CID7469_GenericIntensityAndSizeMeasurements(const DSRCodedEntryValue &selectedValue)
: DSRContextGroup(CONTEXT_GROUP_NUMBER, "DCMR", CONTEXT_GROUP_VERSION, CONTEXT_GROUP_UID, selectedValue)
{
setExtensible(CONTEXT_GROUP_TYPE);
}
CID7469_GenericIntensityAndSizeMeasurements::CID7469_GenericIntensityAndSizeMeasurements(const EnumType selectedValue,
const OFBool enhancedEncodingMode)
: DSRContextGroup(CONTEXT_GROUP_NUMBER, "DCMR", CONTEXT_GROUP_VERSION, CONTEXT_GROUP_UID, getCodedEntry(selectedValue, enhancedEncodingMode))
{
setExtensible(CONTEXT_GROUP_TYPE);
}
OFCondition CID7469_GenericIntensityAndSizeMeasurements::selectValue(const EnumType selectedValue,
const OFBool enhancedEncodingMode)
{
/* never check the coded entry */
return DSRContextGroup::selectValue(getCodedEntry(selectedValue, enhancedEncodingMode), OFFalse /*check*/, OFFalse /*definedContextGroup*/);
}
OFCondition CID7469_GenericIntensityAndSizeMeasurements::findCodedEntry(const DSRCodedEntryValue &searchForCodedEntry,
DSRCodedEntryValue *foundCodedEntry,
const OFBool enhancedEncodingMode) const
{
OFCondition result = SR_EC_CodedEntryNotInContextGroup;
/* first, search for standard codes */
CodeList::const_iterator iter = getCodes().begin();
CodeList::const_iterator last = getCodes().end();
/* iterate over coded entry list */
while (iter != last)
{
/* if found, exit loop */
if (searchForCodedEntry == iter->second)
{
/* return coded entry (if requested) */
if (foundCodedEntry != NULL)
{
*foundCodedEntry = iter->second;
/* also set enhanced encoding mode (if enabled) */
if (!foundCodedEntry->isEmpty() && enhancedEncodingMode)
setEnhancedEncodingMode(*foundCodedEntry);
}
result = SR_EC_CodedEntryInStandardContextGroup;
break;
}
++iter;
}
/* if not, continue with extended codes */
if (result.bad())
{
result = DSRContextGroup::findCodedEntry(searchForCodedEntry, foundCodedEntry);
/* tbd: set "enhanced encoding mode" to mark a local/extended version? */
}
return result;
}
void CID7469_GenericIntensityAndSizeMeasurements::printCodes(STD_NAMESPACE ostream &stream) const
{
/* print standard codes */
stream << "Standard codes:" << OFendl;
CodeList::const_iterator iter = getCodes().begin();
CodeList::const_iterator last = getCodes().end();
/* iterate over coded entry list */
while (iter != last)
{
stream << " ";
/* print coded entry */
DSRCodedEntryValue(iter->second).print(stream);
stream << OFendl;
++iter;
}
/* print extended codes */
DSRContextGroup::printCodes(stream);
}
// static functions
void CID7469_GenericIntensityAndSizeMeasurements::initialize()
{
/* create and initialize code list */
getCodes();
}
void CID7469_GenericIntensityAndSizeMeasurements::cleanup()
{
/* delete code list, it will be recreated automatically when needed */
delete Codes;
Codes = NULL;
}
DSRCodedEntryValue CID7469_GenericIntensityAndSizeMeasurements::getCodedEntry(const EnumType value,
const OFBool enhancedEncodingMode)
{
DSRCodedEntryValue codedEntry;
/* search for given enumerated value */
CodeList::iterator iter = getCodes().find(value);
/* if found, set the coded entry */
if (iter != getCodes().end())
{
codedEntry = iter->second;
/* also set enhanced encoding mode (if enabled) */
if (!codedEntry.isEmpty() && enhancedEncodingMode)
setEnhancedEncodingMode(codedEntry);
}
return codedEntry;
}
CID7469_GenericIntensityAndSizeMeasurements::CodeList &CID7469_GenericIntensityAndSizeMeasurements::getCodes()
{
/* check whether code list has already been created and initialized */
if (Codes == NULL)
{
/* create a new code list (should never fail) */
Codes = new CodeList();
/* and initialize it by adding the coded entries */
Codes->insert(OFMake_pair(NAcetylaspartate, DSRBasicCodedEntry("115391007", "SCT", "N-acetylaspartate")));
Codes->insert(OFMake_pair(Citrate, DSRBasicCodedEntry("59351004", "SCT", "Citrate")));
Codes->insert(OFMake_pair(Choline, DSRBasicCodedEntry("65123005", "SCT", "Choline")));
Codes->insert(OFMake_pair(Creatine, DSRBasicCodedEntry("14804005", "SCT", "Creatine")));
Codes->insert(OFMake_pair(CreatineAndCholine, DSRBasicCodedEntry("113094", "DCM", "Creatine and Choline")));
Codes->insert(OFMake_pair(Lactate, DSRBasicCodedEntry("83036002", "SCT", "Lactate")));
Codes->insert(OFMake_pair(Lipid, DSRBasicCodedEntry("70106000", "SCT", "Lipid")));
Codes->insert(OFMake_pair(LipidAndLactate, DSRBasicCodedEntry("113095", "DCM", "Lipid and Lactate")));
Codes->insert(OFMake_pair(GlutamateAndGlutamine, DSRBasicCodedEntry("113080", "DCM", "Glutamate and glutamine")));
Codes->insert(OFMake_pair(Glutamine, DSRBasicCodedEntry("25761002", "SCT", "Glutamine")));
Codes->insert(OFMake_pair(Tuarine, DSRBasicCodedEntry("10944007", "SCT", "Tuarine")));
Codes->insert(OFMake_pair(Inositol, DSRBasicCodedEntry("72164009", "SCT", "Inositol")));
Codes->insert(OFMake_pair(CholinePerCreatineRatio, DSRBasicCodedEntry("113081", "DCM", "Choline/Creatine Ratio")));
Codes->insert(OFMake_pair(NAcetylaspartatePerCreatineRatio, DSRBasicCodedEntry("113082", "DCM", "N-acetylaspartate/Creatine Ratio")));
Codes->insert(OFMake_pair(NAcetylaspartatePerCholineRatio, DSRBasicCodedEntry("113083", "DCM", "N-acetylaspartate/Choline Ratio")));
Codes->insert(OFMake_pair(CreatinePlusCholinePerCitrateRatio, DSRBasicCodedEntry("113096", "DCM", "Creatine+Choline/Citrate Ratio")));
Codes->insert(OFMake_pair(T1, DSRBasicCodedEntry("113063", "DCM", "T1")));
Codes->insert(OFMake_pair(T2, DSRBasicCodedEntry("113065", "DCM", "T2")));
Codes->insert(OFMake_pair(T2Star, DSRBasicCodedEntry("113064", "DCM", "T2*")));
Codes->insert(OFMake_pair(ProtonDensity, DSRBasicCodedEntry("113058", "DCM", "Proton Density")));
Codes->insert(OFMake_pair(SpinTaggingPerfusionMRSignalIntensity, DSRBasicCodedEntry("110800", "DCM", "Spin Tagging Perfusion MR Signal Intensity")));
Codes->insert(OFMake_pair(VelocityEncoded, DSRBasicCodedEntry("113070", "DCM", "Velocity encoded")));
Codes->insert(OFMake_pair(TemperatureEncoded, DSRBasicCodedEntry("113067", "DCM", "Temperature encoded")));
Codes->insert(OFMake_pair(ContrastAgentAngioMRSignalIntensity, DSRBasicCodedEntry("110801", "DCM", "Contrast Agent Angio MR Signal Intensity")));
Codes->insert(OFMake_pair(TimeOfFlightAngioMRSignalIntensity, DSRBasicCodedEntry("110802", "DCM", "Time Of Flight Angio MR Signal Intensity")));
Codes->insert(OFMake_pair(ProtonDensityWeightedMRSignalIntensity, DSRBasicCodedEntry("110803", "DCM", "Proton Density Weighted MR Signal Intensity")));
Codes->insert(OFMake_pair(T1WeightedMRSignalIntensity, DSRBasicCodedEntry("110804", "DCM", "T1 Weighted MR Signal Intensity")));
Codes->insert(OFMake_pair(T2WeightedMRSignalIntensity, DSRBasicCodedEntry("110805", "DCM", "T2 Weighted MR Signal Intensity")));
Codes->insert(OFMake_pair(T2StarWeightedMRSignalIntensity, DSRBasicCodedEntry("110806", "DCM", "T2* Weighted MR Signal Intensity")));
Codes->insert(OFMake_pair(DiffusionWeighted, DSRBasicCodedEntry("113043", "DCM", "Diffusion weighted")));
Codes->insert(OFMake_pair(VolumetricDiffusionDxxComponent, DSRBasicCodedEntry("110810", "DCM", "Volumetric Diffusion Dxx Component")));
Codes->insert(OFMake_pair(VolumetricDiffusionDxyComponent, DSRBasicCodedEntry("110811", "DCM", "Volumetric Diffusion Dxy Component")));
Codes->insert(OFMake_pair(VolumetricDiffusionDxzComponent, DSRBasicCodedEntry("110812", "DCM", "Volumetric Diffusion Dxz Component")));
Codes->insert(OFMake_pair(VolumetricDiffusionDyyComponent, DSRBasicCodedEntry("110813", "DCM", "Volumetric Diffusion Dyy Component")));
Codes->insert(OFMake_pair(VolumetricDiffusionDyzComponent, DSRBasicCodedEntry("110814", "DCM", "Volumetric Diffusion Dyz Component")));
Codes->insert(OFMake_pair(VolumetricDiffusionDzzComponent, DSRBasicCodedEntry("110815", "DCM", "Volumetric Diffusion Dzz Component")));
Codes->insert(OFMake_pair(FractionalAnisotropy, DSRBasicCodedEntry("110808", "DCM", "Fractional Anisotropy")));
Codes->insert(OFMake_pair(RelativeAnisotropy, DSRBasicCodedEntry("110809", "DCM", "Relative Anisotropy")));
Codes->insert(OFMake_pair(VolumeRatio, DSRBasicCodedEntry("113288", "DCM", "Volume Ratio")));
Codes->insert(OFMake_pair(ApparentDiffusionCoefficient, DSRBasicCodedEntry("113041", "DCM", "Apparent Diffusion Coefficient")));
Codes->insert(OFMake_pair(DiffusionCoefficient, DSRBasicCodedEntry("113289", "DCM", "Diffusion Coefficient")));
Codes->insert(OFMake_pair(MonoExponentialApparentDiffusionCoefficient, DSRBasicCodedEntry("113290", "DCM", "Mono-exponential Apparent Diffusion Coefficient")));
Codes->insert(OFMake_pair(SlowDiffusionCoefficient, DSRBasicCodedEntry("113291", "DCM", "Slow Diffusion Coefficient")));
Codes->insert(OFMake_pair(FastDiffusionCoefficient, DSRBasicCodedEntry("113292", "DCM", "Fast Diffusion Coefficient")));
Codes->insert(OFMake_pair(FastDiffusionCoefficientFraction, DSRBasicCodedEntry("113293", "DCM", "Fast Diffusion Coefficient Fraction")));
Codes->insert(OFMake_pair(KurtosisDiffusionCoefficient, DSRBasicCodedEntry("113294", "DCM", "Kurtosis Diffusion Coefficient")));
Codes->insert(OFMake_pair(GammaDistributionScaleParameter, DSRBasicCodedEntry("113295", "DCM", "Gamma Distribution Scale Parameter")));
Codes->insert(OFMake_pair(GammaDistributionShapeParameter, DSRBasicCodedEntry("113296", "DCM", "Gamma Distribution Shape Parameter")));
Codes->insert(OFMake_pair(GammaDistributionMode, DSRBasicCodedEntry("113297", "DCM", "Gamma Distribution Mode")));
Codes->insert(OFMake_pair(DistributedDiffusionCoefficient, DSRBasicCodedEntry("113298", "DCM", "Distributed Diffusion Coefficient")));
Codes->insert(OFMake_pair(AnomalousExponentParameter, DSRBasicCodedEntry("113299", "DCM", "Anomalous Exponent Parameter")));
Codes->insert(OFMake_pair(FieldMapMRSignalIntensity, DSRBasicCodedEntry("110807", "DCM", "Field Map MR Signal Intensity")));
Codes->insert(OFMake_pair(T1WeightedDynamicContrastEnhancedMRSignalIntensity, DSRBasicCodedEntry("110816", "DCM", "T1 Weighted Dynamic Contrast Enhanced MR Signal Intensity")));
Codes->insert(OFMake_pair(T2WeightedDynamicContrastEnhancedMRSignalIntensity, DSRBasicCodedEntry("110817", "DCM", "T2 Weighted Dynamic Contrast Enhanced MR Signal Intensity")));
Codes->insert(OFMake_pair(T2StarWeightedDynamicContrastEnhancedMRSignalIntensity, DSRBasicCodedEntry("110818", "DCM", "T2* Weighted Dynamic Contrast Enhanced MR Signal Intensity")));
Codes->insert(OFMake_pair(BloodOxygenationLevel, DSRBasicCodedEntry("110819", "DCM", "Blood Oxygenation Level")));
Codes->insert(OFMake_pair(NuclearMedicineProjectionActivity, DSRBasicCodedEntry("110820", "DCM", "Nuclear Medicine Projection Activity")));
Codes->insert(OFMake_pair(NuclearMedicineTomographicActivity, DSRBasicCodedEntry("110821", "DCM", "Nuclear Medicine Tomographic Activity")));
Codes->insert(OFMake_pair(SpatialDisplacementXComponent, DSRBasicCodedEntry("110822", "DCM", "Spatial Displacement X Component")));
Codes->insert(OFMake_pair(SpatialDisplacementYComponent, DSRBasicCodedEntry("110823", "DCM", "Spatial Displacement Y Component")));
Codes->insert(OFMake_pair(SpatialDisplacementZComponent, DSRBasicCodedEntry("110824", "DCM", "Spatial Displacement Z Component")));
Codes->insert(OFMake_pair(HemodynamicResistance, DSRBasicCodedEntry("110825", "DCM", "Hemodynamic Resistance")));
Codes->insert(OFMake_pair(IndexedHemodynamicResistance, DSRBasicCodedEntry("110826", "DCM", "Indexed Hemodynamic Resistance")));
Codes->insert(OFMake_pair(AttenuationCoefficient, DSRBasicCodedEntry("112031", "DCM", "Attenuation Coefficient")));
Codes->insert(OFMake_pair(TissueVelocity, DSRBasicCodedEntry("110827", "DCM", "Tissue Velocity")));
Codes->insert(OFMake_pair(FlowVelocity, DSRBasicCodedEntry("110828", "DCM", "Flow Velocity")));
Codes->insert(OFMake_pair(PowerDoppler, DSRBasicCodedEntry("425704008", "SCT", "Power Doppler")));
Codes->insert(OFMake_pair(FlowVariance, DSRBasicCodedEntry("110829", "DCM", "Flow Variance")));
Codes->insert(OFMake_pair(Elasticity, DSRBasicCodedEntry("110830", "DCM", "Elasticity")));
Codes->insert(OFMake_pair(Perfusion, DSRBasicCodedEntry("110831", "DCM", "Perfusion")));
Codes->insert(OFMake_pair(SpeedOfSound, DSRBasicCodedEntry("110832", "DCM", "Speed of sound")));
Codes->insert(OFMake_pair(UltrasoundAttenuation, DSRBasicCodedEntry("110833", "DCM", "Ultrasound Attenuation")));
Codes->insert(OFMake_pair(StudentsTTest, DSRBasicCodedEntry("113068", "DCM", "Student's T-test")));
Codes->insert(OFMake_pair(ZScore, DSRBasicCodedEntry("113071", "DCM", "Z-score")));
Codes->insert(OFMake_pair(RCoefficient, DSRBasicCodedEntry("113057", "DCM", "R-Coefficient")));
Codes->insert(OFMake_pair(R2Coefficient, DSRBasicCodedEntry("126220", "DCM", "R2-Coefficient")));
Codes->insert(OFMake_pair(ChiSquare, DSRBasicCodedEntry("126221", "DCM", "Chi-square")));
Codes->insert(OFMake_pair(DW, DSRBasicCodedEntry("126222", "DCM", "D-W")));
Codes->insert(OFMake_pair(AIC, DSRBasicCodedEntry("126223", "DCM", "AIC")));
Codes->insert(OFMake_pair(BIC, DSRBasicCodedEntry("126224", "DCM", "BIC")));
Codes->insert(OFMake_pair(RGBRComponent, DSRBasicCodedEntry("110834", "DCM", "RGB R Component")));
Codes->insert(OFMake_pair(RGBGComponent, DSRBasicCodedEntry("110835", "DCM", "RGB G Component")));
Codes->insert(OFMake_pair(RGBBComponent, DSRBasicCodedEntry("110836", "DCM", "RGB B Component")));
Codes->insert(OFMake_pair(YBR_FULLYComponent, DSRBasicCodedEntry("110837", "DCM", "YBR FULL Y Component")));
Codes->insert(OFMake_pair(YBR_FULL_CBComponent, DSRBasicCodedEntry("110838", "DCM", "YBR FULL CB Component")));
Codes->insert(OFMake_pair(YBR_FULL_CRComponent, DSRBasicCodedEntry("110839", "DCM", "YBR FULL CR Component")));
Codes->insert(OFMake_pair(YBR_PARTIALYComponent, DSRBasicCodedEntry("110840", "DCM", "YBR PARTIAL Y Component")));
Codes->insert(OFMake_pair(YBR_PARTIAL_CBComponent, DSRBasicCodedEntry("110841", "DCM", "YBR PARTIAL CB Component")));
Codes->insert(OFMake_pair(YBR_PARTIAL_CRComponent, DSRBasicCodedEntry("110842", "DCM", "YBR PARTIAL CR Component")));
Codes->insert(OFMake_pair(YBR_ICTYComponent, DSRBasicCodedEntry("110843", "DCM", "YBR ICT Y Component")));
Codes->insert(OFMake_pair(YBR_ICT_CBComponent, DSRBasicCodedEntry("110844", "DCM", "YBR ICT CB Component")));
Codes->insert(OFMake_pair(YBR_ICT_CRComponent, DSRBasicCodedEntry("110845", "DCM", "YBR ICT CR Component")));
Codes->insert(OFMake_pair(YBR_RCTYComponent, DSRBasicCodedEntry("110846", "DCM", "YBR RCT Y Component")));
Codes->insert(OFMake_pair(YBR_RCT_CBComponent, DSRBasicCodedEntry("110847", "DCM", "YBR RCT CB Component")));
Codes->insert(OFMake_pair(YBR_RCT_CRComponent, DSRBasicCodedEntry("110848", "DCM", "YBR RCT CR Component")));
Codes->insert(OFMake_pair(Echogenicity, DSRBasicCodedEntry("110849", "DCM", "Echogenicity")));
Codes->insert(OFMake_pair(XRayAttenuation, DSRBasicCodedEntry("110850", "DCM", "X-Ray Attenuation")));
Codes->insert(OFMake_pair(MRSignalIntensity, DSRBasicCodedEntry("110852", "DCM", "MR signal intensity")));
Codes->insert(OFMake_pair(BinarySegmentation, DSRBasicCodedEntry("110853", "DCM", "Binary Segmentation")));
Codes->insert(OFMake_pair(FractionalProbabilisticSegmentation, DSRBasicCodedEntry("110854", "DCM", "Fractional Probabilistic Segmentation")));
Codes->insert(OFMake_pair(FractionalOccupancySegmentation, DSRBasicCodedEntry("110855", "DCM", "Fractional Occupancy Segmentation")));
Codes->insert(OFMake_pair(R1, DSRBasicCodedEntry("126393", "DCM", "R1")));
Codes->insert(OFMake_pair(R2, DSRBasicCodedEntry("126394", "DCM", "R2")));
Codes->insert(OFMake_pair(R2Star, DSRBasicCodedEntry("126395", "DCM", "R2*")));
Codes->insert(OFMake_pair(MagnetizationTransferRatio, DSRBasicCodedEntry("113098", "DCM", "Magnetization Transfer Ratio")));
Codes->insert(OFMake_pair(MagneticSusceptibility, DSRBasicCodedEntry("126396", "DCM", "Magnetic Susceptibility")));
Codes->insert(OFMake_pair(Ktrans, DSRBasicCodedEntry("126312", "DCM", "Ktrans")));
Codes->insert(OFMake_pair(Kep, DSRBasicCodedEntry("126313", "DCM", "kep")));
Codes->insert(OFMake_pair(Ve, DSRBasicCodedEntry("126314", "DCM", "ve")));
Codes->insert(OFMake_pair(Tau_m, DSRBasicCodedEntry("126330", "DCM", "tau_m")));
Codes->insert(OFMake_pair(Vp, DSRBasicCodedEntry("126331", "DCM", "vp")));
Codes->insert(OFMake_pair(AbsoluteRegionalBloodFlow, DSRBasicCodedEntry("126390", "DCM", "Absolute Regional Blood Flow")));
Codes->insert(OFMake_pair(AbsoluteRegionalBloodVolume, DSRBasicCodedEntry("126391", "DCM", "Absolute Regional Blood Volume")));
Codes->insert(OFMake_pair(RelativeRegionalBloodFlow, DSRBasicCodedEntry("126397", "DCM", "Relative Regional Blood Flow")));
Codes->insert(OFMake_pair(RelativeRegionalBloodVolume, DSRBasicCodedEntry("126398", "DCM", "Relative Regional Blood Volume")));
Codes->insert(OFMake_pair(MeanTransitTime, DSRBasicCodedEntry("113052", "DCM", "Mean Transit Time")));
Codes->insert(OFMake_pair(TimeToPeak, DSRBasicCodedEntry("113069", "DCM", "Time To Peak")));
Codes->insert(OFMake_pair(OxygenExtractionFraction, DSRBasicCodedEntry("126392", "DCM", "Oxygen Extraction Fraction")));
Codes->insert(OFMake_pair(Tmax, DSRBasicCodedEntry("113084", "DCM", "Tmax")));
Codes->insert(OFMake_pair(IAUC, DSRBasicCodedEntry("126320", "DCM", "IAUC")));
Codes->insert(OFMake_pair(IAUC60, DSRBasicCodedEntry("126321", "DCM", "IAUC60")));
Codes->insert(OFMake_pair(IAUC90, DSRBasicCodedEntry("126322", "DCM", "IAUC90")));
Codes->insert(OFMake_pair(IAUC180, DSRBasicCodedEntry("126323", "DCM", "IAUC180")));
Codes->insert(OFMake_pair(IAUCBN, DSRBasicCodedEntry("126324", "DCM", "IAUCBN")));
Codes->insert(OFMake_pair(IAUC60BN, DSRBasicCodedEntry("126325", "DCM", "IAUC60BN")));
Codes->insert(OFMake_pair(IAUC90BN, DSRBasicCodedEntry("126326", "DCM", "IAUC90BN")));
Codes->insert(OFMake_pair(IAUC180BN, DSRBasicCodedEntry("126327", "DCM", "IAUC180BN")));
Codes->insert(OFMake_pair(TimeOfPeakConcentration, DSRBasicCodedEntry("126370", "DCM", "Time of Peak Concentration")));
Codes->insert(OFMake_pair(TimeOfLeadingHalfPeakConcentration, DSRBasicCodedEntry("126372", "DCM", "Time of Leading Half-Peak Concentration")));
Codes->insert(OFMake_pair(BolusArrivalTime, DSRBasicCodedEntry("126371", "DCM", "Bolus Arrival Time")));
Codes->insert(OFMake_pair(TemporalDerivativeThreshold, DSRBasicCodedEntry("126374", "DCM", "Temporal Derivative Threshold")));
Codes->insert(OFMake_pair(MaximumSlope, DSRBasicCodedEntry("126375", "DCM", "Maximum Slope")));
Codes->insert(OFMake_pair(MaximumDifference, DSRBasicCodedEntry("126376", "DCM", "Maximum Difference")));
Codes->insert(OFMake_pair(TracerConcentration, DSRBasicCodedEntry("126377", "DCM", "Tracer Concentration")));
Codes->insert(OFMake_pair(StandardizedUptakeValue, DSRBasicCodedEntry("126400", "DCM", "Standardized Uptake Value")));
Codes->insert(OFMake_pair(SUVbw, DSRBasicCodedEntry("126401", "DCM", "SUVbw")));
Codes->insert(OFMake_pair(SUVlbm, DSRBasicCodedEntry("126402", "DCM", "SUVlbm")));
Codes->insert(OFMake_pair(SUVlbmJames128, DSRBasicCodedEntry("126406", "DCM", "SUVlbm(James128)")));
Codes->insert(OFMake_pair(SUVlbmJanma, DSRBasicCodedEntry("126405", "DCM", "SUVlbm(Janma)")));
Codes->insert(OFMake_pair(SUVbsa, DSRBasicCodedEntry("126403", "DCM", "SUVbsa")));
Codes->insert(OFMake_pair(SUVibw, DSRBasicCodedEntry("126404", "DCM", "SUVibw")));
Codes->insert(OFMake_pair(AbsorbedDose, DSRBasicCodedEntry("128513", "DCM", "Absorbed Dose")));
Codes->insert(OFMake_pair(EquivalentDose, DSRBasicCodedEntry("128512", "DCM", "Equivalent Dose")));
Codes->insert(OFMake_pair(Fat, DSRBasicCodedEntry("256674009", "SCT", "Fat")));
Codes->insert(OFMake_pair(FatFraction, DSRBasicCodedEntry("129100", "DCM", "Fat fraction")));
Codes->insert(OFMake_pair(WaterPerFatInPhase, DSRBasicCodedEntry("129101", "DCM", "Water/fat in phase")));
Codes->insert(OFMake_pair(WaterPerFatOutOfPhase, DSRBasicCodedEntry("129102", "DCM", "Water/fat out of phase")));
Codes->insert(OFMake_pair(NegativeEnhancementIntegral, DSRBasicCodedEntry("113054", "DCM", "Negative enhancement integral")));
Codes->insert(OFMake_pair(SignalChange, DSRBasicCodedEntry("113059", "DCM", "Signal change")));
Codes->insert(OFMake_pair(SignalToNoise, DSRBasicCodedEntry("113060", "DCM", "Signal to noise")));
Codes->insert(OFMake_pair(TimeCourseOfSignal, DSRBasicCodedEntry("113066", "DCM", "Time course of signal")));
Codes->insert(OFMake_pair(Water, DSRBasicCodedEntry("11713004", "SCT", "Water")));
Codes->insert(OFMake_pair(WaterFraction, DSRBasicCodedEntry("129103", "DCM", "Water fraction")));
Codes->insert(OFMake_pair(RelativeLinearStoppingPower, DSRBasicCodedEntry("130086", "DCM", "Relative Linear Stopping Power")));
Codes->insert(OFMake_pair(ClassActivation, DSRBasicCodedEntry("130402", "DCM", "Class activation")));
Codes->insert(OFMake_pair(GradientWeightedClassActivation, DSRBasicCodedEntry("130403", "DCM", "Gradient-weighted class activation")));
Codes->insert(OFMake_pair(Saliency, DSRBasicCodedEntry("130404", "DCM", "Saliency")));
Codes->insert(OFMake_pair(Length, DSRBasicCodedEntry("410668003", "SCT", "Length")));
Codes->insert(OFMake_pair(PathLength, DSRBasicCodedEntry("121211", "DCM", "Path length")));
Codes->insert(OFMake_pair(Distance, DSRBasicCodedEntry("121206", "DCM", "Distance")));
Codes->insert(OFMake_pair(Width, DSRBasicCodedEntry("103355008", "SCT", "Width")));
Codes->insert(OFMake_pair(Depth, DSRBasicCodedEntry("131197000", "SCT", "Depth")));
Codes->insert(OFMake_pair(Diameter, DSRBasicCodedEntry("81827009", "SCT", "Diameter")));
Codes->insert(OFMake_pair(LongAxis, DSRBasicCodedEntry("103339001", "SCT", "Long Axis")));
Codes->insert(OFMake_pair(ShortAxis, DSRBasicCodedEntry("103340004", "SCT", "Short Axis")));
Codes->insert(OFMake_pair(MajorAxis, DSRBasicCodedEntry("131187009", "SCT", "Major Axis")));
Codes->insert(OFMake_pair(MinorAxis, DSRBasicCodedEntry("131188004", "SCT", "Minor Axis")));
Codes->insert(OFMake_pair(PerpendicularAxis, DSRBasicCodedEntry("131189007", "SCT", "Perpendicular Axis")));
Codes->insert(OFMake_pair(Radius, DSRBasicCodedEntry("131190003", "SCT", "Radius")));
Codes->insert(OFMake_pair(Perimeter, DSRBasicCodedEntry("131191004", "SCT", "Perimeter")));
Codes->insert(OFMake_pair(Circumference, DSRBasicCodedEntry("74551000", "SCT", "Circumference")));
Codes->insert(OFMake_pair(DiameterOfCircumscribedCircle, DSRBasicCodedEntry("131192006", "SCT", "Diameter of circumscribed circle")));
Codes->insert(OFMake_pair(Height, DSRBasicCodedEntry("121207", "DCM", "Height")));
Codes->insert(OFMake_pair(LineSegmentLength, DSRBasicCodedEntry("121227", "DCM", "Line segment length")));
Codes->insert(OFMake_pair(Maximum3DDiameterOfAMesh, DSRBasicCodedEntry("L0JK", "IBSI", "Maximum 3D Diameter of a Mesh")));
Codes->insert(OFMake_pair(MajorAxisIn3DLength, DSRBasicCodedEntry("TDIC", "IBSI", "Major Axis in 3D Length")));
Codes->insert(OFMake_pair(MinorAxisIn3DLength, DSRBasicCodedEntry("P9VJ", "IBSI", "Minor Axis in 3D Length")));
Codes->insert(OFMake_pair(LeastAxisIn3DLength, DSRBasicCodedEntry("7J51", "IBSI", "Least Axis in 3D Length")));
Codes->insert(OFMake_pair(Area, DSRBasicCodedEntry("42798000", "SCT", "Area")));
Codes->insert(OFMake_pair(AreaOfDefinedRegion, DSRBasicCodedEntry("131184002", "SCT", "Area of defined region")));
Codes->insert(OFMake_pair(SurfaceAreaOfMesh, DSRBasicCodedEntry("C0JK", "IBSI", "Surface Area of Mesh")));
Codes->insert(OFMake_pair(Volume, DSRBasicCodedEntry("118565006", "SCT", "Volume")));
Codes->insert(OFMake_pair(VolumeEstimatedFromSingle2DRegion, DSRBasicCodedEntry("121216", "DCM", "Volume estimated from single 2D region")));
Codes->insert(OFMake_pair(VolumeEstimatedFromTwoNonCoplanar2DRegions, DSRBasicCodedEntry("121218", "DCM", "Volume estimated from two non-coplanar 2D regions")));
Codes->insert(OFMake_pair(VolumeEstimatedFromThreeOrMoreNonCoplanar2DRegions, DSRBasicCodedEntry("121217", "DCM", "Volume estimated from three or more non-coplanar 2D regions")));
Codes->insert(OFMake_pair(VolumeOfSphere, DSRBasicCodedEntry("121222", "DCM", "Volume of sphere")));
Codes->insert(OFMake_pair(VolumeOfEllipsoid, DSRBasicCodedEntry("121221", "DCM", "Volume of ellipsoid")));
Codes->insert(OFMake_pair(VolumeOfCircumscribedSphere, DSRBasicCodedEntry("121220", "DCM", "Volume of circumscribed sphere")));
Codes->insert(OFMake_pair(VolumeOfBoundingThreeDimensionalRegion, DSRBasicCodedEntry("121219", "DCM", "Volume of bounding three dimensional region")));
Codes->insert(OFMake_pair(VolumeOfMesh, DSRBasicCodedEntry("RNU0", "IBSI", "Volume of Mesh")));
Codes->insert(OFMake_pair(VolumeFromVoxelSummation, DSRBasicCodedEntry("YEKZ", "IBSI", "Volume from Voxel Summation")));
}
/* should never be NULL */
return *Codes;
}
OFCondition CID7469_GenericIntensityAndSizeMeasurements::setEnhancedEncodingMode(DSRCodedEntryValue &codedEntryValue)
{
return codedEntryValue.setEnhancedEncodingMode(CONTEXT_GROUP_NUMBER, "DCMR", CONTEXT_GROUP_VERSION, CONTEXT_GROUP_UID);
}
| 79.379603 | 190 | 0.714714 | [
"mesh",
"shape",
"3d"
] |
0be7f0348d7b46250940dc32817d066b5e12dc01 | 1,893 | cpp | C++ | heap/basic implementation.cpp | BhavinRaichura/algo | 126f4063383a0942f6829a54090d72893ce188a4 | [
"MIT"
] | null | null | null | heap/basic implementation.cpp | BhavinRaichura/algo | 126f4063383a0942f6829a54090d72893ce188a4 | [
"MIT"
] | null | null | null | heap/basic implementation.cpp | BhavinRaichura/algo | 126f4063383a0942f6829a54090d72893ce188a4 | [
"MIT"
] | null | null | null |
void insertIntoHeap(vector<int>&arr,int n){
// n = last element of array which gonna need to add in heap
while(n>0 and arr[n/2]<arr[n]){
int k = arr[n];
arr[n]=arr[n/2];
arr[n/2]=k;
n=n/2;
}
cout<<"max heap: "<<arr[0]<<endl;
}
void insertHeapRecursively(vector<int>&arr,int n){
if(n>0 and arr[n/2]<arr[n]){
int k = arr[n];
arr[n]=arr[n/2];
arr[n/2]=k;
n=n/2;
insertHeapRecursively(arr,n);
}
else
return;
}
int topHeap(vector<int>&arr){
return arr[0];
}
void deleteHeap(vector<int>&arr,int n){
// n = index of last element of array which we are adding to heap
int x= arr[0];
arr[0]=arr[n];
int i =0;
int j=2*i+1;
while(j<n){
if(arr[j]<arr[j+1]){
j = j+1;
}
if(arr[i]<arr[j]){
swap(arr[i],arr[j]);
i = j;
j = 2*i+1;
}
else
break;
}
cout<<" deleted element: "<<x<<" new top is: "<<arr[0]<<endl;
arr[n]=x;
}
int main(){
vector<int>arr;
arr.push_back(1);
cout<<"max heap: "<<arr[0]<<endl;
int x=0;
for(int i=0;i<5;i++){
cin>>x;
arr.push_back(x);
insertHeapRecursively(arr,i+1);
cout<<" max heap: "<<arr[0]<<endl;
}
cout<<"\n-------------------------------------------\n";
for(int i=0;i<arr.size();i++){
deleteHeap(arr,arr.size()-1-i);
}
cout<<"\n-------------------------------------------\n";
for(int i=0;i<arr.size();i++){
cout<<arr[i]<<" ";
}
return 0;
}
| 22.535714 | 73 | 0.37401 | [
"vector"
] |
0beb6196f64cc537a9df32951429b4118c09374c | 5,401 | cpp | C++ | UVA Solved Problem/10047 - The Monocycle/10047 - The Monocycle.cpp | ahmed-dinar/UVA | 5cb43864744475ed7ac94e6cb6cae50ad80603c7 | [
"MIT"
] | null | null | null | UVA Solved Problem/10047 - The Monocycle/10047 - The Monocycle.cpp | ahmed-dinar/UVA | 5cb43864744475ed7ac94e6cb6cae50ad80603c7 | [
"MIT"
] | null | null | null | UVA Solved Problem/10047 - The Monocycle/10047 - The Monocycle.cpp | ahmed-dinar/UVA | 5cb43864744475ed7ac94e6cb6cae50ad80603c7 | [
"MIT"
] | null | null | null | #include<cstdio>
#include<sstream>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<algorithm>
#include<set>
#include<queue>
#include<deque>
#include<stack>
#include<list>
#include<iostream>
#include<fstream>
#include<numeric>
#include<string>
#include<vector>
#include<cstring>
#include<map>
#include<iterator>
using namespace std;
#define filein freopen("in.txt","r",stdin)
#define fileout freopen("out.txt","w",stdout)
#define cs(x) printf("Case %d: ",x)
#define csh(x) printf("Case #%d: ",x)
#define csn(x) printf("Case %d:\n",x)
#define loc(p) puts(p)
#define nFind(v,n) find(all(v),n)==v.end()
#define Find(v,n) find(all(v),n)!=v.end()
#define all(x) x.begin(),x.end()
#define toDigit(x) (x-'0')
#define MS(x,v) memset(&x,v,sizeof(x))
#define CL(x) memset(&x,0,sizeof(x))
#define mp make_pair
#define pb push_back
#define sz size()
#define cl clear()
#define pp pop()
#define em empty()
#define ss second
#define fi first
#define sc1(n) scanf("%d",&n)
#define sc2(n,m) scanf("%d %d",&n,&m)
#define sc3(n,m,v) scanf("%d %d %d",&n,&m,&v)
#define vanish scanf("\n")
#define nl puts("")
#define Iterate(s) for(typeof(s.begin()) it = s.begin(); it != s.end (); it++)
#define FOR(i,k,n) for(__typeof(n) i = (k); i <= (n); ++i)
#define For(i,k,n) for(__typeof(n) i = (k); i < (n); ++i)
#define ROF(i,n) for(__typeof(n) i = n; i >= 0; i--)
#define REP(i,n) for(__typeof(n) i = 0; i < (n); ++i)
#define check(n,pos) (bool)(n & (1<<(pos)))
#define EPS 1e-7
#define PI acos(-1.0)
#define MAX 30
#define oo 200000000
#define MOD 1000000007
typedef long long i64;
typedef unsigned long long ui64;
typedef pair<int,int> pri;
typedef pair<i64,i64> pri64;
typedef vector<int> vci;
typedef vector<string> vcs;
typedef vector<i64> vci64;
typedef vector<pri> vcp;
typedef set<int> IS;
typedef set<string> SS;
typedef queue<int> IQ;
typedef queue<pri> PQ;
int on(int N,int pos){ int m=(N | (1<<pos)); return m; }
int off(int N,int pos){ int m=(N & ~(1<<pos)); return m; }
template<class T>bool iseq(T a,T b){return abs(a-b)<EPS;}
template<class T>T sq(T a){ return (a*a); }
template<class T>T gcd(T a,T b){ return (b==0) ? a : gcd(b,a%b); }
template<class T>T lcm(T a,T b){ return (a/gcd(a,b))*b; }
template<class T>T Pow(T n,T p){ if(p==0) return 1; if(p&1) return n*Pow(n,p-1); else return sq(Pow(n,p/2));}
template<class T>bool isPrime(T n){ for(T i=2; i*i<=n; i++){ if(n%i==0) return false; } return true; }
template<class T>T bMod(T A,T P,T M){ if(P==0) return (T)1; if(!(P&1)){T temp=bMod(A,P/2); return ((temp%M)*(temp%M))%M; } return ((A%M)*(bMod(A,P-1)%M))%M; }
template<class T>T InMod(T A,T M){return bMod(A,M-2,M);}
template<class T>T todeg(T x) { return (180.0*x)/((T)PI);}
template<class T>T torad(T x) { return (x*(T)PI)/(180.0);}
template<class T>T _distance(T x1,T y1,T x2, T y2){return sqrt(sq(x1-x2)+sq(y1-y2));}
struct cyclist
{
int r,c,color,dir,w;
cyclist(int r,int c,int color,int dir,int w) : r(r),c(c),color(color),dir(dir),w(w) {}
};
//N E S W
int dx[]={-1,+0,+1,+0};
int dy[]={+0,-1,+0,+1};
int r,c,ti,tj,vis[MAX][MAX][4][5];
char grids[MAX][MAX];
bool valid(int rr,int cc){
return (rr>=0 && rr<r && cc>=0 && cc<c);
}
int turn(int curd,char turd){
if(turd=='L'){
if(curd==0) return 3;
if(curd==1) return 0;
if(curd==2) return 1;
if(curd==3) return 2;
}
if(turd=='R'){
if(curd==0) return 1;
if(curd==1) return 2;
if(curd==2) return 3;
if(curd==3) return 0;
}
}
int bfs(int rr,int cc){
queue<cyclist>q;
q.push( cyclist(rr,cc,0,0,0) );
vis[rr][cc][0][0]=1;
while(!q.em){
cyclist cy=q.front();
q.pop();
int px=cy.r;
int py=cy.c;
int color=cy.color;
int dir=cy.dir;
int w=cy.w;
if( px==ti && py==tj && color==0 ) return w;
int nx=px+dx[dir];
int ny=py+dy[dir];
int ncolor=(color+1)%5;
if( valid(nx,ny) && grids[nx][ny]!='#' ){
if( !vis[nx][ny][dir][ncolor] ){
vis[nx][ny][dir][ncolor]=1;
q.push( cyclist(nx,ny,ncolor,dir,w+1) );
}
}
int ndir=turn(dir,'L');
nx=px;
ny=py;
ncolor=color;
if( !vis[nx][ny][ndir][ncolor] ){
vis[nx][ny][ndir][ncolor]=1;
q.push( cyclist(nx,ny,ncolor,ndir,w+1) );
}
ndir=turn(dir,'R');
if( !vis[nx][ny][ndir][ncolor] ){
vis[nx][ny][ndir][ncolor]=1;
q.push( cyclist(nx,ny,ncolor,ndir,w+1) );
}
}
return -1;
}
int main(){
// filein;
int T=0,si,sj;
while( scanf("%d %d",&r,&c)==2 ){
if(r+c==0) break;
REP(i,r){
REP(j,c){
cin>>grids[i][j];
if(grids[i][j]=='S')
si=i,sj=j;
else if(grids[i][j]=='T')
ti=i,tj=j;
}
}
memset(&vis,0,sizeof(vis));
int res=bfs(si,sj);
if(T) nl;
printf("Case #%d\n",++T);
if(res==-1)
puts("destination not reachable");
else
printf("minimum time = %d sec\n",res);
}
return 0;
}
| 27.416244 | 159 | 0.524162 | [
"vector"
] |
0bf0876599dd12629c3a0bdb48c145ce3d9681ea | 10,772 | hpp | C++ | src/graph/impl/KokkosGraph_Distance2Color_MatrixSquared_impl.hpp | hmaarrfk/kokkos-kernels | d86db111124cea12e23dd3447b6c307f96ef7439 | [
"BSD-3-Clause"
] | null | null | null | src/graph/impl/KokkosGraph_Distance2Color_MatrixSquared_impl.hpp | hmaarrfk/kokkos-kernels | d86db111124cea12e23dd3447b6c307f96ef7439 | [
"BSD-3-Clause"
] | 4 | 2020-01-06T23:37:05.000Z | 2021-06-07T20:03:05.000Z | src/graph/impl/KokkosGraph_Distance2Color_MatrixSquared_impl.hpp | hmaarrfk/kokkos-kernels | d86db111124cea12e23dd3447b6c307f96ef7439 | [
"BSD-3-Clause"
] | null | null | null | /*
//@HEADER
// ************************************************************************
//
// KokkosKernels 0.9: Linear Algebra and Graph Kernels
// Copyright 2017 Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact William McLendon (wcmclen@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <iomanip>
#include <vector>
#include <KokkosSparse_spgemm.hpp>
#include <Kokkos_Atomic.hpp>
#include <Kokkos_Core.hpp>
#include <Kokkos_MemoryTraits.hpp>
#include <impl/Kokkos_Timer.hpp>
#include "KokkosGraph_Distance1ColorHandle.hpp"
#include "KokkosGraph_Distance1Color.hpp"
#include "KokkosKernels_Handle.hpp"
#ifndef _KOKKOSCOLORINGD2MATRIXSQUAREDIMP_HPP
#define _KOKKOSCOLORINGD2MATRIXSQUAREDIMP_HPP
namespace KokkosGraph {
namespace Impl {
/*! \brief Base class for graph coloring purposes.
* Each color represents the set of the vertices that are independent,
* e.g. no vertex having same color shares an edge.
* General aim is to find the minimum number of colors, minimum number of independent sets.
*/
template<typename HandleType,
typename lno_row_view_t_,
typename lno_nnz_view_t_,
typename clno_row_view_t_,
typename clno_nnz_view_t_>
class GraphColorDistance2MatrixSquared
{
public:
using in_lno_row_view_type = lno_row_view_t_;
using in_lno_nnz_view_type = lno_nnz_view_t_;
using color_type = typename HandleType::GraphColorDistance2HandleType::color_type;
using color_view_type = typename HandleType::GraphColorDistance2HandleType::color_view_type;
using size_type = typename HandleType::size_type;
using const_size_type = typename HandleType::const_size_type;
using nnz_lno_type = typename HandleType::nnz_lno_t;
using MyExecSpace = typename HandleType::HandleExecSpace;
using MyTempMemorySpace = typename HandleType::HandleTempMemorySpace;
using row_lno_view_device_type = typename lno_row_view_t_::device_type;
using const_lno_row_view_type = typename lno_row_view_t_::const_type;
using const_lno_nnz_view_type = typename lno_nnz_view_t_::const_type;
using non_const_lno_nnz_view_type = typename lno_nnz_view_t_::non_const_type;
using const_clno_row_view_type = typename clno_row_view_t_::const_type;
using const_clno_nnz_view_type = typename clno_nnz_view_t_::const_type;
using non_const_clno_nnz_view_type = typename clno_nnz_view_t_::non_const_type;
using size_type_temp_work_view_type = typename HandleType::size_type_temp_work_view_t;
using scalar_temp_work_view_type = typename HandleType::scalar_temp_work_view_t;
using nnz_lno_persistent_work_view_type = typename HandleType::nnz_lno_persistent_work_view_t;
using nnz_lno_temp_work_view_type = typename HandleType::nnz_lno_temp_work_view_t;
using single_dim_index_view_type = typename Kokkos::View<nnz_lno_type, row_lno_view_device_type>;
using my_exec_space = Kokkos::RangePolicy<MyExecSpace>;
protected:
nnz_lno_type nr; // num_rows (# verts)
nnz_lno_type nc; // num cols
size_type ne; // # edges
const_lno_row_view_type xadj; // rowmap, transpose of rowmap
const_lno_nnz_view_type adj; // entries, transpose of entries (size = # edges)
const_clno_row_view_type t_xadj; // rowmap, transpose of rowmap
const_clno_nnz_view_type t_adj; // entries, transpose of entries
nnz_lno_type nv; // num vertices
HandleType* handle; // the handle.
bool verbose;
public:
/**
* \brief GraphColor constructor.
*
* \param nv_: number of vertices in the graph
* \param ne_: number of edges in the graph
* \param row_map: the xadj array of the graph. Its size is nv_ +1
* \param entries: adjacency array of the graph. Its size is ne_
* \param handle: GraphColoringHandle object that holds the specification about the graph coloring,
* including parameters.
*/
GraphColorDistance2MatrixSquared(nnz_lno_type nr_,
nnz_lno_type nc_,
size_type ne_,
const_lno_row_view_type row_map,
const_lno_nnz_view_type entries,
const_clno_row_view_type t_row_map,
const_clno_nnz_view_type t_entries,
HandleType* handle_)
: nr(nr_)
, nc(nc_)
, ne(ne_)
, xadj(row_map)
, adj(entries)
, t_xadj(t_row_map)
, t_adj(t_entries)
, nv(nr_)
, handle(handle_)
, verbose(handle_->get_verbose())
{
}
/** \brief GraphColor destructor.
*/
virtual ~GraphColorDistance2MatrixSquared() {}
/**
* \brief Function to color the vertices of the graphs. This is the base class,
* therefore, it only performs sequential coloring on the host device, ignoring the execution space.
*
* \param colors is the output array corresponding the color of each vertex.Size is this->nv.
* Attn: Color array must be nonnegative numbers. If there is no initial colors,
* it should be all initialized with zeros. Any positive value in the given array, will make the
* algorithm to assume that the color is fixed for the corresponding vertex.
* \param num_phases: The number of iterations (phases) that algorithm takes to converge.
*/
virtual void compute_distance2_color()
{
double time = 0;
Kokkos::Impl::Timer timer;
timer.reset();
std::string algName = "SPGEMM_KK_MEMSPEED";
handle->create_spgemm_handle(KokkosSparse::StringToSPGEMMAlgorithm(algName));
size_type_temp_work_view_type cRowptrs("cRowptrs", nr + 1);
// Call symbolic multiplication of graph with itself (no transposes, and A and B are the same)
KokkosSparse::Experimental::spgemm_symbolic(handle, nr, nc, nr, xadj, adj, false, t_xadj, t_adj, false, cRowptrs);
// Get num nz in C
auto Cnnz = handle->get_spgemm_handle()->get_c_nnz();
// Must create placeholder value views for A and C (values are meaningless)
// Said above that the scalar view type is the same as the colinds view type
scalar_temp_work_view_type aFakeValues("A/B placeholder values (meaningless)", adj.size());
// Allocate C entries array, and placeholder values
nnz_lno_persistent_work_view_type cColinds("C colinds", Cnnz);
scalar_temp_work_view_type cFakeValues("C placeholder values (meaningless)", Cnnz);
// Run the numeric kernel
KokkosSparse::Experimental::spgemm_numeric(
handle, nr, nc, nr, xadj, adj, aFakeValues, false, t_xadj, t_adj, aFakeValues, false, cRowptrs, cColinds, cFakeValues);
if(this->verbose)
{
time = timer.seconds();
std::cout << "\tTime Phase Square Matrix : " << time << std::endl << std::endl;
this->handle->get_distance2_graph_coloring_handle()->add_to_overall_coloring_time_phase4(time);
timer.reset();
}
// done with spgemm
handle->destroy_spgemm_handle();
// Now run distance-1 graph coloring on C, use LocalOrdinal for storing colors
handle->create_graph_coloring_handle();
KokkosGraph::Experimental::graph_color(
handle, nr, nr, /*(const_rowptrs_view)*/ cRowptrs, /*(const_colinds_view)*/ cColinds);
if(this->verbose)
{
time = timer.seconds();
std::cout << "\tTime Phase Graph Coloring : " << time << std::endl << std::endl;
this->handle->get_distance2_graph_coloring_handle()->add_to_overall_coloring_time_phase5(time);
timer.reset();
}
// extract the colors
// auto coloringHandle = handle->get_graph_coloring_handle();
// color_view_type colorsDevice = coloringHandle->get_vertex_colors();
// std::cout << "Num phases: " << handle->get_graph_coloring_handle()->get_num_phases() << std::endl;
this->handle->get_distance2_graph_coloring_handle()->set_num_phases(
this->handle->get_graph_coloring_handle()->get_num_phases());
this->handle->get_distance2_graph_coloring_handle()->set_vertex_colors(
this->handle->get_graph_coloring_handle()->get_vertex_colors());
// clean up coloring handle
handle->destroy_graph_coloring_handle();
}
}; // GraphColorDistance2MatrixSquared (end)
} // namespace Impl
} // namespace KokkosGraph
#endif // _KOKKOSCOLORINGD2MATRIXSQUAREDIMP_HPP
| 45.07113 | 129 | 0.660787 | [
"object",
"vector"
] |
0bf6380135bf1f0f6f4fa437d7eff3e5c725b2d6 | 3,988 | cpp | C++ | src/assetManager.cpp | Yattabyte/MiniAssets | 7e28d0cf03a0833924b8d1cd4edddf4f9e29c97e | [
"BSD-3-Clause"
] | 1 | 2020-06-13T18:52:50.000Z | 2020-06-13T18:52:50.000Z | src/assetManager.cpp | Yattabyte/MiniAssets | 7e28d0cf03a0833924b8d1cd4edddf4f9e29c97e | [
"BSD-3-Clause"
] | null | null | null | src/assetManager.cpp | Yattabyte/MiniAssets | 7e28d0cf03a0833924b8d1cd4edddf4f9e29c97e | [
"BSD-3-Clause"
] | null | null | null | #include "assetManager.hpp"
#include <algorithm>
#include <chrono>
#include <thread>
///////////////////////////////////////////////////////////////////////////
/// Use our shared namespace mini
using namespace mini;
///////////////////////////////////////////////////////////////////////////
/// shareAsset
///////////////////////////////////////////////////////////////////////////
Shared_Asset AssetManager::shareAsset(
const std::string& assetType, const std::string& filename, const std::function<Shared_Asset(void)>& constructor,
const bool threaded) {
// Find out if the asset already exists
std::shared_lock<std::shared_mutex> asset_read_guard(m_mutexAssetMap);
for (const auto& asset : m_assetMap[assetType])
if (asset->getFileName() == filename) {
asset_read_guard.unlock();
asset_read_guard.release();
// Check if we need to wait for initialization
if (!threaded)
// Stay here until asset finalizes
while (!asset->ready())
std::this_thread::sleep_for(std::chrono::milliseconds(1));
return asset;
}
asset_read_guard.unlock();
asset_read_guard.release();
// Create the asset
std::unique_lock<std::shared_mutex> asset_write_guard(m_mutexAssetMap);
const auto& asset = constructor();
m_assetMap[assetType].push_back(asset);
asset_write_guard.unlock();
asset_write_guard.release();
// Initialize now or later, depending if we are threading this order or not
if (threaded) {
std::unique_lock<std::shared_mutex> worker_write_guard(m_mutexWorkorders);
m_workOrders.emplace_back(std::bind(&Asset::initialize, asset));
} else
asset->initialize();
return asset;
}
///////////////////////////////////////////////////////////////////////////
/// beginWorkOrder
///////////////////////////////////////////////////////////////////////////
void AssetManager::beginWorkOrder() {
// Start reading work orders
std::unique_lock<std::shared_mutex> writeGuard(m_mutexWorkorders);
if (!m_workOrders.empty()) {
// Remove front of queue
const Asset_Work_Order workOrder = m_workOrders.front();
m_workOrders.pop_front();
writeGuard.unlock();
writeGuard.release();
// Initialize asset
workOrder();
}
}
///////////////////////////////////////////////////////////////////////////
/// submitNotifyee
///////////////////////////////////////////////////////////////////////////
void AssetManager::submitNotifyee(const std::pair<std::shared_ptr<bool>, std::function<void()>>& callBack) {
std::unique_lock<std::shared_mutex> writeGuard(m_mutexNofications);
m_notifyees.push_back(callBack);
}
///////////////////////////////////////////////////////////////////////////
/// notifyObservers
///////////////////////////////////////////////////////////////////////////
void AssetManager::notifyObservers() {
std::vector<std::pair<std::shared_ptr<bool>, std::function<void()>>> copyNotifyees;
{
std::unique_lock<std::shared_mutex> writeGuard(m_mutexNofications);
copyNotifyees = m_notifyees;
m_notifyees.clear();
}
for (const auto& pair : copyNotifyees)
if (pair.first)
pair.second();
}
///////////////////////////////////////////////////////////////////////////
/// readyToUse
///////////////////////////////////////////////////////////////////////////
bool AssetManager::readyToUse() {
std::shared_lock<std::shared_mutex> readGuard(m_mutexWorkorders);
if (!m_workOrders.empty())
return false;
readGuard = std::shared_lock<std::shared_mutex>(m_mutexAssetMap);
return std::all_of(m_assetMap.begin(), m_assetMap.end(), [](const auto& assetCategory) {
return std::all_of(assetCategory.second.cbegin(), assetCategory.second.cend(), [](const auto& asset) {
return asset->ready();
});
});
} | 36.587156 | 116 | 0.52332 | [
"vector"
] |
0bfa1b57206f389c6c62ed3778ea913de16a2ccc | 6,477 | cpp | C++ | VCL/Frames/archive/TClientSocketFrameUsingVCLSocket.cpp | TotteKarlsson/dsl | 3807cbe5f90a3cd495979eafa8cf5485367b634c | [
"BSD-2-Clause"
] | null | null | null | VCL/Frames/archive/TClientSocketFrameUsingVCLSocket.cpp | TotteKarlsson/dsl | 3807cbe5f90a3cd495979eafa8cf5485367b634c | [
"BSD-2-Clause"
] | null | null | null | VCL/Frames/archive/TClientSocketFrameUsingVCLSocket.cpp | TotteKarlsson/dsl | 3807cbe5f90a3cd495979eafa8cf5485367b634c | [
"BSD-2-Clause"
] | null | null | null | #ifdef MTK_PCH
#include "dsl_pch.h"
#endif
#pragma hdrstop
#include <string>
#include <vector>
#include "TClientSocketFrameUsingVCLSocket.h"
#include "dslUtils.h"
#include "dslVCLUtils.h"
using namespace std;
using namespace dsl;
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "dslIntEdit"
#pragma link "TIntegerLabeledEdit"
#pragma resource "*.dfm"
TClientSocketFrame *ClientSocketFrame;
//---------------------------------------------------------------------------
__fastcall TClientSocketFrame::TClientSocketFrame(TComponent* Owner)
: TFrame(Owner), SB(nullptr)
{
nrOfMessages = 0;
BitBtn1->Caption = "Connect";
StatusBar1->Visible = false;
if(SB)
SB->Panels->Items[0]->Text = "Disconnected...";
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::SetStatusBar(TStatusBar* sb)
{
StatusBar1->Visible = false;
SB = sb;
}
//ClientSocket stuff
void __fastcall TClientSocketFrame::ClientSocketConnect(TObject *Sender,
TCustomWinSocket *Socket)
{
ConsoleMemo->Clear();
RecMsgMemo->Clear();
BitBtn1->Caption = "Disconnect";
StatusBar1->Panels->Items[0]->Text = "Connected to: " + Socket->RemoteHost;
nrOfMessages = 0;
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ClientSocketDisconnect(TObject *Sender,
TCustomWinSocket *Socket)
{
BitBtn1->Caption = "Connect";
if(SB)
SB->Panels->Items[0]->Text = "Disconnected...";
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ClientSocketError(TObject *Sender,
TCustomWinSocket *Socket, TErrorEvent ErrorEvent, int &ErrorCode)
{
RecMsgMemo->Lines->Add("Error connecting to:" + Server + " on port number " + Sysutils::IntToStr(PortNrE->getValue()) );
RecMsgMemo->Lines->Add("The error code was: " + Sysutils::IntToStr(ErrorCode) );
//switch(ErrorCode)
// {
// case eeGeneral: break;
// case eeSend: break;
// case eeReceive: break;
// case eeConnect: break;
// case eeDisconnect: break;
// case eeAccept: break;
//
// default: break;
// }
ClientSocket->Close();
ErrorCode = 0; //Don't raise an exception
BitBtn1->Caption = "Connect";
if(SB)
SB->Panels->Items[0]->Text = "Disconnected...";
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ClientSocketRead(TObject *Sender, TCustomWinSocket *Socket)
{
lastMessage = Socket->ReceiveText().c_str();
vector<string> strs;
strs = splitString(lastMessage, "\n");
for(unsigned int i=0; i < strs.size(); i++)
{
if(strs[i].size())
RecMsgMemo->Lines->Add(strs[i].c_str());
}
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ToggleConnectionExecute(TObject *Sender)
{
ClientSocket->Active ? DisconnectExecute(Sender) : ConnectExecute(Sender);
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::DisconnectExecute(TObject *Sender)
{
ClientSocket->Active = false;
BitBtn1->Caption = "Connect";
if(SB)
SB->Panels->Items[0]->Text = "Disconnected...";
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ConnectExecute(TObject *Sender)
{
if (ClientSocket->Active)
{
return;
}
Server = ServerCB->Text;
PortNr = PortNrE->getValue();
if (Server.Length() < 1)
{
MessageDlg("Assign a valid server!", mtWarning, TMsgDlgButtons() << mbOK, 0);
return;
}
ClientSocket->Port = PortNrE->getValue();
ClientSocket->Host = Server;
ClientSocket->Active = true;
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ConsoleMemoKeyDown(TObject *Sender, WORD &Key, TShiftState Shift)
{
if (Key == VK_RETURN && !Shift.Contains(ssShift))
{
string msg;
for(int i = 0; i < ConsoleMemo->Lines->Count; i++)
{
msg += stdstr(ConsoleMemo->Lines->Strings[i]);
}
//Add newline
msg += '\n';
Send(msg.c_str());
ClearConsoleMemoAExecute(Sender);
}
}
int __fastcall TClientSocketFrame::Send(const string& msg)
{
int bytesSent = ClientSocket->Socket->SendText(msg.c_str());
// RecMsgMemo->Lines->Add(Sysutils::IntToStr(bytesSent) + " bytes sent");
return bytesSent;
}
void __fastcall TClientSocketFrame::ClientSocketConnecting(TObject *Sender, TCustomWinSocket *Socket)
{
BitBtn1->Caption = "Connecting..";
if(SB)
SB->Panels->Items[0]->Text = "Connecting...";
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ClientSocketLookup(TObject *Sender, TCustomWinSocket *Socket)
{
BitBtn1->Caption = "Connecting..";
if(SB)
SB->Panels->Items[0]->Text = "Connecting...";
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ReconnectTimerTimer(TObject *Sender)
{
//Try to reconnect to server
ConnectExecute(Sender);
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ToggleConnectionUpdate(TObject *Sender)
{
//Code when the connection status changes
if(ClientSocket->Active)
{
ReconnectTimer->Enabled = false; //turn off the reconnect timer
}
else
{
AutoReconnectCB->Enabled = true;
ReconnectTimer->Enabled = AutoReconnectCB->Checked;
}
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ClearReceivedMemoAExecute(TObject *Sender)
{
RecMsgMemo->Clear();
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::ClearConsoleMemoAExecute(TObject *Sender)
{
ConsoleMemo->Clear();
}
//---------------------------------------------------------------------------
void __fastcall TClientSocketFrame::FrameExit(TObject *Sender)
{
SetStatusBar(nullptr);
}
| 30.408451 | 122 | 0.537131 | [
"vector"
] |
0bfde2b5636813fd7794910202fd24aacfc67f0d | 1,344 | cpp | C++ | src/bits_of_matcha/engine/ops/Multiply.cpp | matcha-ai/matcha | c1375fc2bfc9fadcbd643fc1540e3ac470dd9408 | [
"MIT"
] | null | null | null | src/bits_of_matcha/engine/ops/Multiply.cpp | matcha-ai/matcha | c1375fc2bfc9fadcbd643fc1540e3ac470dd9408 | [
"MIT"
] | null | null | null | src/bits_of_matcha/engine/ops/Multiply.cpp | matcha-ai/matcha | c1375fc2bfc9fadcbd643fc1540e3ac470dd9408 | [
"MIT"
] | null | null | null | #include "bits_of_matcha/engine/ops/Multiply.h"
#include "bits_of_matcha/engine/cpu/kernels/fill.h"
#include "bits_of_matcha/engine/cpu/kernels/elementwiseBinaryBack.h"
namespace matcha::engine::ops {
Multiply::Multiply(Tensor* a, Tensor* b)
: ElementwiseBinaryOp(a, b)
{}
OpMeta<Multiply> Multiply::meta {
.name = "Multiply",
.back = [](auto ctx) { return new MultiplyBack(ctx); }
};
void Multiply::run() {
outputs[0]->malloc();
runCPU(std::multiplies<float>());
}
MultiplyBack::MultiplyBack(const BackCtx& ctx)
: OpBack(ctx)
, iter_(forward->inputs[0]->shape(), forward->inputs[1]->shape())
{
}
OpMeta<MultiplyBack> MultiplyBack::meta {
.name = "MultiplyBack",
};
void MultiplyBack::run() {
if (outputs[0]) {
cpu::fill(outputs[0]->malloc(), outputs[0]->size(), 0);
cpu::elementwiseBinaryBack(
[](float& a, float& b, float& c) {
// print(a, b, c);
a += b * c;
},
outputs[0]->buffer(),
forward->inputs[1]->buffer(),
inputs[0]->buffer(),
iter_
);
}
if (outputs[1]) {
cpu::fill(outputs[1]->malloc(), outputs[1]->size(), 0);
cpu::elementwiseBinaryBack(
[](float& a, float& b, float& c) {
b += a * c;
},
forward->inputs[0]->buffer(),
outputs[1]->buffer(),
inputs[0]->buffer(),
iter_
);
}
}
}
| 20.676923 | 68 | 0.588542 | [
"shape"
] |
0bfe843b1c9573548d7ee51a703a8b130c425e62 | 2,491 | cpp | C++ | tests/cpp/countingBits/CountingBits.cpp | zlc18/LocalJudge | e8b141d2e80087d447a45cce36bac27b4ddb9cd1 | [
"MIT"
] | null | null | null | tests/cpp/countingBits/CountingBits.cpp | zlc18/LocalJudge | e8b141d2e80087d447a45cce36bac27b4ddb9cd1 | [
"MIT"
] | null | null | null | tests/cpp/countingBits/CountingBits.cpp | zlc18/LocalJudge | e8b141d2e80087d447a45cce36bac27b4ddb9cd1 | [
"MIT"
] | null | null | null | // Source : https://leetcode.com/problems/counting-bits/
// Author : Hao Chen
// Date : 2016-05-30
/***************************************************************************************
*
* Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤
* num calculate the number of 1's in their binary representation and return them as an
* array.
*
* Example:
* For num = 5 you should return [0,1,1,2,1,2].
*
* Follow up:
*
* It is very easy to come up with a solution with run time O(n*sizeof(integer)). But
* can you do it in linear time O(n) /possibly in a single pass?
* Space complexity should be O(n).
* Can you do it like a boss? Do it without using any builtin function like
* __builtin_popcount in c++ or in any other language.
*
* You should make use of what you have produced already.
* Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to
* generate new range from previous.
* Or does the odd/even status of the number help you in calculating the number of 1s?
*
* Credits:Special thanks to @ syedee for adding this problem and creating all test
* cases.
***************************************************************************************/
class Solution {
public:
/*
* Initialization
*
* bits_cnt[0] => 0000 => 0
* bits_cnt[1] => 0001 => 1
*
* if the number has 2 bits (2, 3), then we can split the binary to two parts,
* 2 = 10 + 0 and 3= 10 + 1, then we can reuse the bits_cnt[0] and bits_cnt[1]
*
* bits_cnt[2] => 0010 => 0010 + 0 => 1 + bits_cnt[0];
* bits_cnt[3] => 0011 => 0010 + 1 => 1 + bits_cnt[1];
*
* if the number has 3 bits (4,5,6,7), then we can split the binary to two parts,
* 4 = 100 + 0, 5 = 100 + 01, 6= 100 + 10, 7 = 100 +11
* then we can reuse the bits_cnt[0] and bits_cnt[1]
*
* bits_cnt[4] => 0110 => 0100 + 00 => 1 + bits_cnt[0];
* bits_cnt[5] => 0101 => 0100 + 01 => 1 + bits_cnt[1];
* bits_cnt[6] => 0110 => 0100 + 10 => 1 + bits_cnt[2];
* bits_cnt[7] => 0111 => 0100 + 11 => 1 + bits_cnt[3];
*
* so, we can have the solution:
*
* bits_cnt[x] = bits_cnt[x & (x-1) ] + 1;
*
*/
vector<int> countBits(int num) {
vector<int> bits_cnt(num+1, 0);
for (int i=1; i<=num; i++) {
bits_cnt[i] = bits_cnt[i & (i-1)] + 1;
}
return bits_cnt;
}
};
| 36.632353 | 89 | 0.531513 | [
"vector"
] |
0bff3f800256e9d6828ed1e49224307d3d3e0b0f | 94 | cpp | C++ | limbo/thirdparty/dlx/test/polyomino/deps.cpp | RedFantom/limbo | 8d3e0d484a809fb4b3ff8aa72fd972d16cdab405 | [
"MIT"
] | 74 | 2017-10-19T03:10:52.000Z | 2022-03-28T17:51:54.000Z | limbo/thirdparty/dlx/test/polyomino/deps.cpp | RedFantom/limbo | 8d3e0d484a809fb4b3ff8aa72fd972d16cdab405 | [
"MIT"
] | 3 | 2017-12-06T01:49:21.000Z | 2020-06-22T00:08:12.000Z | limbo/thirdparty/dlx/test/polyomino/deps.cpp | RedFantom/limbo | 8d3e0d484a809fb4b3ff8aa72fd972d16cdab405 | [
"MIT"
] | 26 | 2017-11-07T10:32:54.000Z | 2021-10-02T02:22:37.000Z | #include "../../example/polyomino/Polyomino.cpp"
#include "../../example/polyomino/Shape.cpp"
| 31.333333 | 48 | 0.702128 | [
"shape"
] |
0bffa18de394931b0340b130392b5e8c4922f6c2 | 4,674 | hpp | C++ | shadow/operators/kernels/scale.hpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 20 | 2017-07-04T11:22:47.000Z | 2022-01-16T03:58:32.000Z | shadow/operators/kernels/scale.hpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 2 | 2017-12-03T13:07:39.000Z | 2021-01-13T11:11:52.000Z | shadow/operators/kernels/scale.hpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 10 | 2017-09-30T05:06:30.000Z | 2020-11-13T05:43:44.000Z | #ifndef SHADOW_OPERATORS_KERNELS_SCALE_HPP_
#define SHADOW_OPERATORS_KERNELS_SCALE_HPP_
#include "core/kernel.hpp"
namespace Shadow {
namespace Vision {
template <DeviceType D, typename T>
void ScaleBias(const T* in_data, int count, const T* scale_data,
const T* bias_data, int scale_num, int inner_num, T* out_data,
Context* context);
template <DeviceType D, typename T>
void Scale(const T* in_data, int count, const T* scale_data, int scale_num,
int inner_num, T* out_data, Context* context);
template <DeviceType D, typename T>
void Bias(const T* in_data, int count, const T* bias_data, int scale_num,
int inner_num, T* out_data, Context* context);
} // namespace Vision
} // namespace Shadow
namespace Shadow {
class ScaleKernel : public Kernel {
public:
virtual void Run(const std::shared_ptr<Blob>& input,
const std::shared_ptr<Blob>& scale,
const std::shared_ptr<Blob>& bias,
std::shared_ptr<Blob>& output, Workspace* ws, int axis) = 0;
virtual void Run(const std::shared_ptr<Blob>& input,
std::shared_ptr<Blob>& output, Workspace* ws, int axis,
const VecFloat& scale_value, const VecFloat& bias_value) = 0;
};
template <DeviceType D>
class ScaleKernelDefault : public ScaleKernel {
public:
void Run(const std::shared_ptr<Blob>& input,
const std::shared_ptr<Blob>& scale,
const std::shared_ptr<Blob>& bias, std::shared_ptr<Blob>& output,
Workspace* ws, int axis) override {
const auto* in_data = input->data<float>();
auto* out_data = output->mutable_data<float>();
int count = input->count();
CHECK(scale != nullptr || bias != nullptr);
if (scale != nullptr && bias != nullptr) {
CHECK(scale->shape() == bias->shape());
int inner_dim = input->count(axis + scale->num_axes());
Vision::ScaleBias<D, float>(in_data, count, scale->data<float>(),
bias->data<float>(), scale->count(),
inner_dim, out_data, ws->Ctx().get());
} else if (scale != nullptr) {
int inner_dim = input->count(axis + scale->num_axes());
Vision::Scale<D, float>(in_data, count, scale->data<float>(),
scale->count(), inner_dim, out_data,
ws->Ctx().get());
} else {
int inner_dim = input->count(axis + bias->num_axes());
Vision::Bias<D, float>(in_data, count, bias->data<float>(), bias->count(),
inner_dim, out_data, ws->Ctx().get());
}
}
void Run(const std::shared_ptr<Blob>& input, std::shared_ptr<Blob>& output,
Workspace* ws, int axis, const VecFloat& scale_value,
const VecFloat& bias_value) override {
const auto* in_data = input->data<float>();
auto* out_data = output->mutable_data<float>();
int dim = input->shape(axis), inner_dim = input->count(axis + 1),
count = input->count();
CHECK(!scale_value.empty() || !bias_value.empty());
if (!scale_value.empty() && !bias_value.empty()) {
CHECK_EQ(scale_value.size(), dim);
CHECK_EQ(bias_value.size(), dim);
ws->GrowTempBuffer(2 * dim * sizeof(float));
auto scale = ws->CreateTempBlob({dim}, DataType::kF32);
auto bias = ws->CreateTempBlob({dim}, DataType::kF32);
scale->set_data<float>(scale_value.data(), dim);
bias->set_data<float>(bias_value.data(), dim);
Vision::ScaleBias<D, float>(in_data, count, scale->data<float>(),
bias->data<float>(), dim, inner_dim, out_data,
ws->Ctx().get());
} else if (!scale_value.empty()) {
CHECK_EQ(scale_value.size(), dim);
ws->GrowTempBuffer(dim * sizeof(float));
auto scale = ws->CreateTempBlob({dim}, DataType::kF32);
scale->set_data<float>(scale_value.data(), dim);
Vision::Scale<D, float>(in_data, count, scale->data<float>(), dim,
inner_dim, out_data, ws->Ctx().get());
} else {
CHECK_EQ(bias_value.size(), dim);
ws->GrowTempBuffer(dim * sizeof(float));
auto bias = ws->CreateTempBlob({dim}, DataType::kF32);
bias->set_data<float>(bias_value.data(), dim);
Vision::Bias<D, float>(in_data, count, bias->data<float>(), dim,
inner_dim, out_data, ws->Ctx().get());
}
}
DeviceType device_type() const override { return D; }
std::string kernel_type() const override { return "Default"; }
};
} // namespace Shadow
#endif // SHADOW_OPERATORS_KERNELS_SCALE_HPP_
| 38.95 | 80 | 0.602054 | [
"shape"
] |
0406e6f89459dcbcf12c9c7ca38cb3f999c1ecb5 | 20,906 | cxx | C++ | main/bridges/source/cpp_uno/msvc_win32_intel/except.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/bridges/source/cpp_uno/msvc_win32_intel/except.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/bridges/source/cpp_uno/msvc_win32_intel/except.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_bridges.hxx"
#pragma warning( disable : 4237 )
#include <hash_map>
#include <sal/config.h>
#include <malloc.h>
#include <typeinfo.h>
#include <signal.h>
#include "rtl/alloc.h"
#include "rtl/strbuf.hxx"
#include "rtl/ustrbuf.hxx"
#include "com/sun/star/uno/Any.hxx"
#include "msci.hxx"
#pragma pack(push, 8)
using namespace ::com::sun::star::uno;
using namespace ::std;
using namespace ::osl;
using namespace ::rtl;
namespace CPPU_CURRENT_NAMESPACE
{
//==================================================================================================
static inline OUString toUNOname( OUString const & rRTTIname ) throw ()
{
OUStringBuffer aRet( 64 );
OUString aStr( rRTTIname.copy( 4, rRTTIname.getLength()-4-2 ) ); // filter .?AUzzz@yyy@xxx@@
sal_Int32 nPos = aStr.getLength();
while (nPos > 0)
{
sal_Int32 n = aStr.lastIndexOf( '@', nPos );
aRet.append( aStr.copy( n +1, nPos -n -1 ) );
if (n >= 0)
{
aRet.append( (sal_Unicode)'.' );
}
nPos = n;
}
return aRet.makeStringAndClear();
}
//==================================================================================================
static inline OUString toRTTIname( OUString const & rUNOname ) throw ()
{
OUStringBuffer aRet( 64 );
aRet.appendAscii( RTL_CONSTASCII_STRINGPARAM(".?AV") ); // class ".?AV"; struct ".?AU"
sal_Int32 nPos = rUNOname.getLength();
while (nPos > 0)
{
sal_Int32 n = rUNOname.lastIndexOf( '.', nPos );
aRet.append( rUNOname.copy( n +1, nPos -n -1 ) );
aRet.append( (sal_Unicode)'@' );
nPos = n;
}
aRet.append( (sal_Unicode)'@' );
return aRet.makeStringAndClear();
}
//##################################################################################################
//#### RTTI simulation #############################################################################
//##################################################################################################
typedef hash_map< OUString, void *, OUStringHash, equal_to< OUString > > t_string2PtrMap;
//==================================================================================================
class RTTInfos
{
Mutex _aMutex;
t_string2PtrMap _allRTTI;
static OUString toRawName( OUString const & rUNOname ) throw ();
public:
type_info * getRTTI( OUString const & rUNOname ) throw ();
RTTInfos();
~RTTInfos();
};
//==================================================================================================
class __type_info
{
friend type_info * RTTInfos::getRTTI( OUString const & ) throw ();
friend int msci_filterCppException(
LPEXCEPTION_POINTERS, uno_Any *, uno_Mapping * );
public:
virtual ~__type_info() throw ();
inline __type_info( void * m_data, const char * m_d_name ) throw ()
: _m_data( m_data )
{ ::strcpy( _m_d_name, m_d_name ); } // #100211# - checked
private:
void * _m_data;
char _m_d_name[1];
};
//__________________________________________________________________________________________________
__type_info::~__type_info() throw ()
{
}
//__________________________________________________________________________________________________
type_info * RTTInfos::getRTTI( OUString const & rUNOname ) throw ()
{
// a must be
OSL_ENSURE( sizeof(__type_info) == sizeof(type_info), "### type info structure size differ!" );
MutexGuard aGuard( _aMutex );
t_string2PtrMap::const_iterator const iFind( _allRTTI.find( rUNOname ) );
// check if type is already available
if (iFind == _allRTTI.end())
{
// insert new type_info
OString aRawName( OUStringToOString( toRTTIname( rUNOname ), RTL_TEXTENCODING_ASCII_US ) );
__type_info * pRTTI = new( ::rtl_allocateMemory( sizeof(__type_info) + aRawName.getLength() ) )
__type_info( NULL, aRawName.getStr() );
// put into map
pair< t_string2PtrMap::iterator, bool > insertion(
_allRTTI.insert( t_string2PtrMap::value_type( rUNOname, pRTTI ) ) );
OSL_ENSURE( insertion.second, "### rtti insertion failed?!" );
return (type_info *)pRTTI;
}
else
{
return (type_info *)iFind->second;
}
}
//__________________________________________________________________________________________________
RTTInfos::RTTInfos() throw ()
{
}
//__________________________________________________________________________________________________
RTTInfos::~RTTInfos() throw ()
{
#if OSL_DEBUG_LEVEL > 1
OSL_TRACE( "> freeing generated RTTI infos... <\n" );
#endif
MutexGuard aGuard( _aMutex );
for ( t_string2PtrMap::const_iterator iPos( _allRTTI.begin() );
iPos != _allRTTI.end(); ++iPos )
{
__type_info * pType = (__type_info *)iPos->second;
pType->~__type_info(); // obsolete, but good style...
::rtl_freeMemory( pType );
}
}
//##################################################################################################
//#### Exception raising ###########################################################################
//##################################################################################################
//==================================================================================================
struct ObjectFunction
{
char somecode[12];
typelib_TypeDescription * _pTypeDescr; // type of object
inline static void * operator new ( size_t nSize );
inline static void operator delete ( void * pMem );
ObjectFunction( typelib_TypeDescription * pTypeDescr, void * fpFunc ) throw ();
~ObjectFunction() throw ();
};
inline void * ObjectFunction::operator new ( size_t nSize )
{
void * pMem = rtl_allocateMemory( nSize );
if (pMem != 0)
{
DWORD old_protect;
#if OSL_DEBUG_LEVEL > 0
BOOL success =
#endif
VirtualProtect( pMem, nSize, PAGE_EXECUTE_READWRITE, &old_protect );
OSL_ENSURE( success, "VirtualProtect() failed!" );
}
return pMem;
}
inline void ObjectFunction::operator delete ( void * pMem )
{
rtl_freeMemory( pMem );
}
//__________________________________________________________________________________________________
ObjectFunction::ObjectFunction( typelib_TypeDescription * pTypeDescr, void * fpFunc ) throw ()
: _pTypeDescr( pTypeDescr )
{
::typelib_typedescription_acquire( _pTypeDescr );
unsigned char * pCode = (unsigned char *)somecode;
// a must be!
OSL_ENSURE( (void *)this == (void *)pCode, "### unexpected!" );
// push ObjectFunction this
*pCode++ = 0x68;
*(void **)pCode = this;
pCode += sizeof(void *);
// jmp rel32 fpFunc
*pCode++ = 0xe9;
*(sal_Int32 *)pCode = ((unsigned char *)fpFunc) - pCode - sizeof(sal_Int32);
}
//__________________________________________________________________________________________________
ObjectFunction::~ObjectFunction() throw ()
{
::typelib_typedescription_release( _pTypeDescr );
}
//==================================================================================================
static void * __cdecl __copyConstruct( void * pExcThis, void * pSource, ObjectFunction * pThis )
throw ()
{
::uno_copyData( pExcThis, pSource, pThis->_pTypeDescr, cpp_acquire );
return pExcThis;
}
//==================================================================================================
static void * __cdecl __destruct( void * pExcThis, ObjectFunction * pThis )
throw ()
{
::uno_destructData( pExcThis, pThis->_pTypeDescr, cpp_release );
return pExcThis;
}
// these are non virtual object methods; there is no this ptr on stack => ecx supplies _this_ ptr
//==================================================================================================
static __declspec(naked) void copyConstruct() throw ()
{
__asm
{
// ObjectFunction this already on stack
push [esp+8] // source exc object this
push ecx // exc object
call __copyConstruct
add esp, 12 // + ObjectFunction this
ret 4
}
}
//==================================================================================================
static __declspec(naked) void destruct() throw ()
{
__asm
{
// ObjectFunction this already on stack
push ecx // exc object
call __destruct
add esp, 8 // + ObjectFunction this
ret
}
}
//==================================================================================================
struct ExceptionType
{
sal_Int32 _n0;
type_info * _pTypeInfo;
sal_Int32 _n1, _n2, _n3, _n4;
ObjectFunction * _pCopyCtor;
sal_Int32 _n5;
inline ExceptionType( typelib_TypeDescription * pTypeDescr ) throw ()
: _n0( 0 )
, _n1( 0 )
, _n2( -1 )
, _n3( 0 )
, _n4( pTypeDescr->nSize )
, _pCopyCtor( new ObjectFunction( pTypeDescr, copyConstruct ) )
, _n5( 0 )
{ _pTypeInfo = msci_getRTTI( pTypeDescr->pTypeName ); }
inline ~ExceptionType() throw ()
{ delete _pCopyCtor; }
};
//==================================================================================================
struct RaiseInfo
{
sal_Int32 _n0;
ObjectFunction * _pDtor;
sal_Int32 _n2;
void * _types;
sal_Int32 _n3, _n4;
RaiseInfo( typelib_TypeDescription * pTypeDescr ) throw ();
~RaiseInfo() throw ();
};
//__________________________________________________________________________________________________
RaiseInfo::RaiseInfo( typelib_TypeDescription * pTypeDescr ) throw ()
: _n0( 0 )
, _pDtor( new ObjectFunction( pTypeDescr, destruct ) )
, _n2( 0 )
, _n3( 0 )
, _n4( 0 )
{
// a must be
OSL_ENSURE( sizeof(sal_Int32) == sizeof(ExceptionType *), "### pointer size differs from sal_Int32!" );
typelib_CompoundTypeDescription * pCompTypeDescr;
// info count
sal_Int32 nLen = 0;
for ( pCompTypeDescr = (typelib_CompoundTypeDescription*)pTypeDescr;
pCompTypeDescr; pCompTypeDescr = pCompTypeDescr->pBaseTypeDescription )
{
++nLen;
}
// info count accompanied by type info ptrs: type, base type, base base type, ...
_types = ::rtl_allocateMemory( sizeof(sal_Int32) + (sizeof(ExceptionType *) * nLen) );
*(sal_Int32 *)_types = nLen;
ExceptionType ** ppTypes = (ExceptionType **)((sal_Int32 *)_types + 1);
sal_Int32 nPos = 0;
for ( pCompTypeDescr = (typelib_CompoundTypeDescription*)pTypeDescr;
pCompTypeDescr; pCompTypeDescr = pCompTypeDescr->pBaseTypeDescription )
{
ppTypes[nPos++] = new ExceptionType( (typelib_TypeDescription *)pCompTypeDescr );
}
}
//__________________________________________________________________________________________________
RaiseInfo::~RaiseInfo() throw ()
{
ExceptionType ** ppTypes = (ExceptionType **)((sal_Int32 *)_types + 1);
for ( sal_Int32 nTypes = *(sal_Int32 *)_types; nTypes--; )
{
delete ppTypes[nTypes];
}
::rtl_freeMemory( _types );
delete _pDtor;
}
//==================================================================================================
class ExceptionInfos
{
Mutex _aMutex;
t_string2PtrMap _allRaiseInfos;
public:
static void * getRaiseInfo( typelib_TypeDescription * pTypeDescr ) throw ();
ExceptionInfos() throw ();
~ExceptionInfos() throw ();
};
//__________________________________________________________________________________________________
ExceptionInfos::ExceptionInfos() throw ()
{
}
//__________________________________________________________________________________________________
ExceptionInfos::~ExceptionInfos() throw ()
{
#if OSL_DEBUG_LEVEL > 1
OSL_TRACE( "> freeing exception infos... <\n" );
#endif
MutexGuard aGuard( _aMutex );
for ( t_string2PtrMap::const_iterator iPos( _allRaiseInfos.begin() );
iPos != _allRaiseInfos.end(); ++iPos )
{
delete (RaiseInfo *)iPos->second;
}
}
//__________________________________________________________________________________________________
void * ExceptionInfos::getRaiseInfo( typelib_TypeDescription * pTypeDescr ) throw ()
{
static ExceptionInfos * s_pInfos = 0;
if (! s_pInfos)
{
MutexGuard aGuard( Mutex::getGlobalMutex() );
if (! s_pInfos)
{
#ifdef LEAK_STATIC_DATA
s_pInfos = new ExceptionInfos();
#else
static ExceptionInfos s_allExceptionInfos;
s_pInfos = &s_allExceptionInfos;
#endif
}
}
OSL_ASSERT( pTypeDescr &&
(pTypeDescr->eTypeClass == typelib_TypeClass_STRUCT ||
pTypeDescr->eTypeClass == typelib_TypeClass_EXCEPTION) );
void * pRaiseInfo;
OUString const & rTypeName = *reinterpret_cast< OUString * >( &pTypeDescr->pTypeName );
MutexGuard aGuard( s_pInfos->_aMutex );
t_string2PtrMap::const_iterator const iFind(
s_pInfos->_allRaiseInfos.find( rTypeName ) );
if (iFind == s_pInfos->_allRaiseInfos.end())
{
pRaiseInfo = new RaiseInfo( pTypeDescr );
// put into map
pair< t_string2PtrMap::iterator, bool > insertion(
s_pInfos->_allRaiseInfos.insert( t_string2PtrMap::value_type( rTypeName, pRaiseInfo ) ) );
OSL_ENSURE( insertion.second, "### raise info insertion failed?!" );
}
else
{
// reuse existing info
pRaiseInfo = iFind->second;
}
return pRaiseInfo;
}
//##################################################################################################
//#### exported ####################################################################################
//##################################################################################################
//##################################################################################################
type_info * msci_getRTTI( OUString const & rUNOname )
{
static RTTInfos * s_pRTTIs = 0;
if (! s_pRTTIs)
{
MutexGuard aGuard( Mutex::getGlobalMutex() );
if (! s_pRTTIs)
{
#ifdef LEAK_STATIC_DATA
s_pRTTIs = new RTTInfos();
#else
static RTTInfos s_aRTTIs;
s_pRTTIs = &s_aRTTIs;
#endif
}
}
return s_pRTTIs->getRTTI( rUNOname );
}
//##################################################################################################
void msci_raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp )
{
// no ctor/dtor in here: this leads to dtors called twice upon RaiseException()!
// thus this obj file will be compiled without opt, so no inling of
// ExceptionInfos::getRaiseInfo()
// construct cpp exception object
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );
void * pCppExc = alloca( pTypeDescr->nSize );
::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp );
// a must be
OSL_ENSURE(
sizeof(sal_Int32) == sizeof(void *),
"### pointer size differs from sal_Int32!" );
DWORD arFilterArgs[3];
arFilterArgs[0] = MSVC_magic_number;
arFilterArgs[1] = (DWORD)pCppExc;
arFilterArgs[2] = (DWORD)ExceptionInfos::getRaiseInfo( pTypeDescr );
// destruct uno exception
::uno_any_destruct( pUnoExc, 0 );
TYPELIB_DANGER_RELEASE( pTypeDescr );
// last point to release anything not affected by stack unwinding
RaiseException( MSVC_ExceptionCode, EXCEPTION_NONCONTINUABLE, 3, arFilterArgs );
}
//##############################################################################
int msci_filterCppException(
EXCEPTION_POINTERS * pPointers, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno )
{
if (pPointers == 0)
return EXCEPTION_CONTINUE_SEARCH;
EXCEPTION_RECORD * pRecord = pPointers->ExceptionRecord;
// handle only C++ exceptions:
if (pRecord == 0 || pRecord->ExceptionCode != MSVC_ExceptionCode)
return EXCEPTION_CONTINUE_SEARCH;
#if _MSC_VER < 1300 // MSVC -6
bool rethrow = (pRecord->NumberParameters < 3 ||
pRecord->ExceptionInformation[ 2 ] == 0);
#else
bool rethrow = __CxxDetectRethrow( &pRecord );
OSL_ASSERT( pRecord == pPointers->ExceptionRecord );
#endif
if (rethrow && pRecord == pPointers->ExceptionRecord)
{
// hack to get msvcrt internal _curexception field:
pRecord = *reinterpret_cast< EXCEPTION_RECORD ** >(
reinterpret_cast< char * >( __pxcptinfoptrs() ) +
// as long as we don't demand msvcr source as build prerequisite
// (->platform sdk), we have to code those offsets here.
//
// crt\src\mtdll.h:
// offsetof (_tiddata, _curexception) -
// offsetof (_tiddata, _tpxcptinfoptrs):
#if _MSC_VER < 1300
0x18 // msvcrt,dll
#elif _MSC_VER < 1310
0x20 // msvcr70.dll
#elif _MSC_VER < 1400
0x24 // msvcr71.dll
#else
0x28 // msvcr80.dll
#endif
);
}
// rethrow: handle only C++ exceptions:
if (pRecord == 0 || pRecord->ExceptionCode != MSVC_ExceptionCode)
return EXCEPTION_CONTINUE_SEARCH;
if (pRecord->NumberParameters == 3 &&
// pRecord->ExceptionInformation[ 0 ] == MSVC_magic_number &&
pRecord->ExceptionInformation[ 1 ] != 0 &&
pRecord->ExceptionInformation[ 2 ] != 0)
{
void * types = reinterpret_cast< RaiseInfo * >(
pRecord->ExceptionInformation[ 2 ] )->_types;
if (types != 0 && *reinterpret_cast< DWORD * >( types ) > 0) // count
{
ExceptionType * pType = *reinterpret_cast< ExceptionType ** >(
reinterpret_cast< DWORD * >( types ) + 1 );
if (pType != 0 && pType->_pTypeInfo != 0)
{
OUString aRTTIname(
OStringToOUString(
reinterpret_cast< __type_info * >(
pType->_pTypeInfo )->_m_d_name,
RTL_TEXTENCODING_ASCII_US ) );
OUString aUNOname( toUNOname( aRTTIname ) );
typelib_TypeDescription * pExcTypeDescr = 0;
typelib_typedescription_getByName(
&pExcTypeDescr, aUNOname.pData );
if (pExcTypeDescr == 0)
{
OUStringBuffer buf;
buf.appendAscii(
RTL_CONSTASCII_STRINGPARAM(
"[msci_uno bridge error] UNO type of "
"C++ exception unknown: \"") );
buf.append( aUNOname );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(
"\", RTTI-name=\"") );
buf.append( aRTTIname );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\"!") );
RuntimeException exc(
buf.makeStringAndClear(), Reference< XInterface >() );
uno_type_any_constructAndConvert(
pUnoExc, &exc,
::getCppuType( &exc ).getTypeLibType(), pCpp2Uno );
#if _MSC_VER < 1400 // msvcr80.dll cleans up, different from former msvcrs
// if (! rethrow):
// though this unknown exception leaks now, no user-defined
// exception is ever thrown through the binary C-UNO dispatcher
// call stack.
#endif
}
else
{
// construct uno exception any
uno_any_constructAndConvert(
pUnoExc, (void *) pRecord->ExceptionInformation[1],
pExcTypeDescr, pCpp2Uno );
#if _MSC_VER < 1400 // msvcr80.dll cleans up, different from former msvcrs
if (! rethrow)
{
uno_destructData(
(void *) pRecord->ExceptionInformation[1],
pExcTypeDescr, cpp_release );
}
#endif
typelib_typedescription_release( pExcTypeDescr );
}
return EXCEPTION_EXECUTE_HANDLER;
}
}
}
// though this unknown exception leaks now, no user-defined exception
// is ever thrown through the binary C-UNO dispatcher call stack.
RuntimeException exc(
OUString( RTL_CONSTASCII_USTRINGPARAM(
"[msci_uno bridge error] unexpected "
"C++ exception occurred!") ),
Reference< XInterface >() );
uno_type_any_constructAndConvert(
pUnoExc, &exc, ::getCppuType( &exc ).getTypeLibType(), pCpp2Uno );
return EXCEPTION_EXECUTE_HANDLER;
}
}
#pragma pack(pop)
| 33.289809 | 104 | 0.589448 | [
"object"
] |
0407d432300959d88db1baeb067ade3f86a3e3fd | 4,578 | cpp | C++ | src/particles.cpp | Tearnote/Minote | 35f63fecc01cf9199db1098256277465e1d41d1e | [
"MIT"
] | 8 | 2021-01-18T12:06:21.000Z | 2022-02-13T17:12:56.000Z | src/particles.cpp | Tearnote/Minote | 35f63fecc01cf9199db1098256277465e1d41d1e | [
"MIT"
] | null | null | null | src/particles.cpp | Tearnote/Minote | 35f63fecc01cf9199db1098256277465e1d41d1e | [
"MIT"
] | null | null | null | /**
* Implementation of effects.h
* @file
*/
#include "particles.hpp"
#include <time.h>
#include "cephes/protos.h"
#include "base/array.hpp"
#include "sys/glfw.hpp"
#include "engine/model.hpp"
#include "base/util.hpp"
#include "base/rng.hpp"
using namespace minote;
/// Progress level after which a particle begins to fade out
#define ShimmerFade 0.9f
/**
* Logical description of a particle. Does not change throughout the particle's
* lifetime, and current position can be calculated for any point in time.
*/
typedef struct Particle {
vec3 origin; ///< Starting point
color4 color; ///< Individual tint
int vert; ///< -1 for down, 1 for up
int horz; ///< -1 for left, 1 for right
nsec start; ///< Timestamp of spawning
nsec duration; ///< Total lifetime
float distance; ///< Total distance travelled from origin
float spin; ///< Rate at which the particle turns
EasingFunction<float> ease; ///< Easing profile of the particle progress
} Particle;
constexpr size_t MaxParticles{4096};
static svector<Particle, MaxParticles> particles{};
static Rng rng{};
static svector<ModelFlat::Instance, MaxParticles> particleInstances{};
static bool initialized = false;
void particlesInit(void)
{
if (initialized) return;
rng.seed((uint64_t)time(nullptr));
initialized = true;
}
void particlesUpdate(void)
{
ASSERT(initialized);
size_t numParticles = particles.size();
nsec currentTime = Glfw::getTime();
for (size_t i = numParticles - 1; i < numParticles; i -= 1) {
Particle* currentParticle = &particles[i];
if (currentParticle->start + currentParticle->duration < currentTime) {
particles[i] = particles.back();
particles.pop_back();
}
}
}
void particlesDraw(Engine& engine)
{
ASSERT(initialized);
double fresnelConst = sqrt(4.0 / Tau);
size_t const numParticles = particles.size();
if (!numParticles) return;
for (size_t i = 0; i < numParticles; i += 1) {
Particle* current = &particles[i];
ASSERT(current->spin > 0.0f);
Tween progressTween = {
.from = 0.0f,
.to = 1.0f,
.start = current->start,
.duration = current->duration,
.type = current->ease
};
float progress = progressTween.apply();
ASSERT(progress >= 0.0f && progress <= 1.0f);
double x;
double y;
ASSERT(current->spin > 0.0f);
float distance = progress * current->distance * current->spin;
fresnl(distance * fresnelConst, &y, &x);
x = x / fresnelConst / current->spin;
y = y / fresnelConst / current->spin;
if (current->horz == -1)
x *= -1.0;
else
x += 1.0;
if (current->vert == -1)
y *= -1.0;
x += current->origin.x;
y += current->origin.y;
float angle = distance * distance;
if (current->horz == -1)
angle = radians(180.0f) - angle;
if (current->vert == -1)
angle *= -1.0f;
auto& instance = particleInstances.emplace_back();
instance.tint = current->color;
// Shimmer mitigation
if (progress > ShimmerFade) {
float fadeout = progress - ShimmerFade;
fadeout *= 1.0f / (1.0f - ShimmerFade);
fadeout = 1.0f - fadeout;
fadeout = cubicEaseIn(fadeout);
instance.tint.a *= fadeout;
}
const mat4 translated = make_translate({(float)x, (float)y, current->origin.z});
const mat4 rotated = rotate(translated, angle, {0.0f, 0.0f, 1.0f});
instance.transform = scale(rotated, {1.0f - progress, 1.0f, 1.0f});
}
engine.models.particle.draw(*engine.frame.fb, engine.scene, {
.blending = true
}, particleInstances);
particleInstances.clear();
}
void particlesGenerate(vec3 position, size_t count, ParticleParams* params)
{
ASSERT(initialized);
ASSERT(count);
ASSERT(params);
for (size_t i = 0; i < count; i += 1) {
auto& newParticle = particles.emplace_back();
newParticle.origin = position;
newParticle.color = params->color;
newParticle.start = Glfw::getTime();
newParticle.duration = round(params->durationMin +
(params->durationMax - params->durationMin) * rng.randFloat());
newParticle.ease = params->ease;
if (params->directionHorz != 0)
newParticle.horz = params->directionHorz;
else
newParticle.horz = (int)rng.randInt(2) * 2 - 1;
if (params->directionVert != 0)
newParticle.vert = params->directionVert;
else
newParticle.vert = (int)rng.randInt(2) * 2 - 1;
newParticle.distance = rng.randFloat();
newParticle.distance *= params->distanceMax - params->distanceMin;
newParticle.distance += params->distanceMin;
newParticle.spin = rng.randFloat();
newParticle.spin = quarticEaseIn(newParticle.spin);
newParticle.spin *= params->spinMax - params->spinMin;
newParticle.spin += params->spinMin;
}
}
| 26.16 | 82 | 0.683049 | [
"model",
"transform"
] |
040a78ef4f78cfd3a038dcf06a06e5eaae547cc4 | 5,731 | cc | C++ | src/geometry.cc | bengoana/CPURaytracer | ded16cad975d7e9b5ce6cb715c91403718786316 | [
"MIT"
] | null | null | null | src/geometry.cc | bengoana/CPURaytracer | ded16cad975d7e9b5ce6cb715c91403718786316 | [
"MIT"
] | null | null | null | src/geometry.cc | bengoana/CPURaytracer | ded16cad975d7e9b5ce6cb715c91403718786316 | [
"MIT"
] | null | null | null | /*---------------------------------------------------------------------
Copyright (c) 2020 Pablo Bengoa (bengoana)
https://github.com/bengoana
This software is released under the MIT license.
This program is a college project uploaded for showcase purposes.
---------------------------------------------------------------------*/
#include "geometry.h"
#include "renderer.h"
#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
bool Geometry::AABBIntersection(Ray ray) {
float t1 = (vboxMin[0] - ray.origin[0]) / ray.dir[0];
float t2 = (vboxMax[0] - ray.origin[0]) / ray.dir[0];
float tmin = std::min(t1, t2);
float tmax = std::max(t1, t2);
for (int i = 1; i < 3; ++i) {
t1 = (vboxMin[i] - ray.origin[i]) / ray.dir[i];
t2 = (vboxMax[i] - ray.origin[i]) / ray.dir[i];
tmin = std::max(tmin, std::min(t1, t2));
tmax = std::min(tmax, std::max(t1, t2));
}
return tmax > std::max(tmin, 0.0f);
}
Sphere::Sphere() {
radius_ = 1.0f;
pos_ = glm::vec3(0.0f, 0.0f, 0.0f);
color_ = glm::vec3(1.0f,0.0f,0.0f);
}
Sphere::~Sphere(){
}
float Sphere::ComputeRay(Ray& r){
//if (!AABBIntersection(r)) return -1;
glm::vec3 oc = r.origin - pos_;
float a = glm::dot(r.dir, r.dir);
float b = 2.0 * glm::dot(oc, r.dir);
float c = glm::dot(oc, oc) - radius_ * radius_;
float discriminant = b * b - 4.0f * a * c;
if (discriminant < 0) {
return -1.0;
}
else {
return (-b - sqrt(discriminant)) / (2.0f * a);
}
}
glm::vec3 Sphere::GetNormal(glm::vec3& collision_spot){
return glm::normalize(collision_spot - pos_);
}
void Sphere::InitAABB(){
vboxMax.x = pos_.x + radius_;
vboxMax.y = pos_.y + radius_;
vboxMax.z = pos_.z + radius_;
vboxMin.x = pos_.x - radius_;
vboxMin.y = pos_.y - radius_;
vboxMin.z = pos_.z - radius_;
}
Plane::Plane(){
normal_ = { 0.0f,1.0f,0.0f };
}
Plane::~Plane(){
}
float Plane::ComputeRay(Ray& ray){
glm::vec3 p = { normal_.x,normal_.y ,normal_.z };
float w = glm::length(pos_);
return -(glm::dot(ray.origin, p) + w) / glm::dot(ray.dir, p);
}
glm::vec3 Plane::GetNormal(glm::vec3& collision_spot){
return normal_;
}
CustomGeometry::CustomGeometry(){
use_fast_normal_ = false;
}
CustomGeometry::~CustomGeometry(){
}
void CustomGeometry::LoadObj(const char* filePath){
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string error;
bool result = tinyobj::LoadObj(shapes, materials, error, filePath);
if (shapes.size() < 1) {
printf("Error loading obj\n");
return;
}
if (!error.empty()) {
printf("[OBJLoader]: %s", error.c_str() + 6);;
}
//Only single shape obj supported
vertices_.resize((int)(shapes[0].mesh.positions.size() / 3));
glm::vec3 vmin = pos_;
glm::vec3 vmax = pos_;
for (int i = 0; i < vertices_.size(); i++) {
vertices_[i].position[0] = shapes[0].mesh.positions[i * 3];
vertices_[i].position[1] = shapes[0].mesh.positions[i * 3 + 1];
vertices_[i].position[2] = shapes[0].mesh.positions[i * 3 + 2];
vmin = glm::min(vmin, vertices_[i].position + pos_);
vmax = glm::max(vmax, vertices_[i].position + pos_);
if (shapes[0].mesh.normals.size() > 0) {
vertices_[i].normal[0] = shapes[0].mesh.normals[i * 3];
vertices_[i].normal[1] = shapes[0].mesh.normals[i * 3 + 1];
vertices_[i].normal[2] = shapes[0].mesh.normals[i * 3 + 2];
}
}
vboxMin = vmin;
vboxMax = vmax;
indices_.resize(shapes[0].mesh.indices.size());
for (int i = 0; i < indices_.size(); ++i) {
indices_[i] = shapes[0].mesh.indices[i];
}
shapes.clear();
materials.clear();
}
float CustomGeometry::ComputeRay(Ray& ray){
if (!AABBIntersection(ray)) return -1;
float result = 999999.0f;
for (int i = 0; i < indices_.size(); i += 3) {
float distance = TriCollision(
ray.origin,ray.dir,
vertices_[indices_[i]].position + pos_,
vertices_[indices_[i+1]].position + pos_,
vertices_[indices_[i+2]].position + pos_);
if (distance > -1 && distance < result) {
result = distance;
last_normal_ = glm::cross((vertices_[indices_[i]].position + pos_) - (vertices_[indices_[i + 1]].position + pos_),
(vertices_[indices_[i]].position + pos_) - (vertices_[indices_[i + 2]].position + pos_));
last_normal_ = glm::normalize(last_normal_);
last_normal_ = { 1.0f,0.0f,0.0f };
}
}
if (result >= 999997.0f) result = -1;
return result;
}
glm::vec3 CustomGeometry::GetNormal(glm::vec3& collision_spot){
if(use_fast_normal_)
return last_normal_;
float dist_ = 99999.0f;
int vertex_index_ = 0;
float main_dot = -2.0;
for (int i = 0; i < vertices_.size();++i) {
float dot = glm::dot(collision_spot-(vertices_[i].position + pos_), vertices_[i].normal);
if (dot > main_dot) {
float temp = glm::distance(collision_spot, vertices_[i].position + pos_);
if (dist_ > temp) {
temp = dist_;
main_dot = dot;
vertex_index_ = i;
}
}
}
return vertices_[vertex_index_].normal;
}
inline float CustomGeometry::TriCollision(glm::vec3& ro, glm::vec3& rd, glm::vec3& v0, glm::vec3& v1, glm::vec3& v2){
glm::vec3 v1v0 = v1 - v0;
glm::vec3 v2v0 = v2 - v0;
glm::vec3 rov0 = ro - v0;
glm::vec3 n = cross(v1v0, v2v0);
glm::vec3 q = cross(rov0, rd);
float d = 1.0f / dot(rd, n);
float u = d * dot(-q, v2v0);
float v = d * dot(q, v1v0);
float t = d * dot(-n, rov0);
if (u < 0.0f || u>1.0f || v < 0.0f || (u + v)>1.0f) t = -1.0f;
return t;
} | 27.161137 | 121 | 0.573547 | [
"mesh",
"geometry",
"shape",
"vector"
] |
0416b0b54fdf84b456596d13227627c513399da0 | 49,852 | cpp | C++ | sta-src/Entry/reentry.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 6 | 2018-09-05T12:41:59.000Z | 2021-07-01T05:34:23.000Z | sta-src/Entry/reentry.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-02-07T19:09:21.000Z | 2015-08-14T03:15:42.000Z | sta-src/Entry/reentry.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-03-25T15:50:31.000Z | 2017-12-06T12:16:47.000Z | /*
This program is free software; you can redistribute it and/or modify it under
the terms of the European Union Public Licence - EUPL v.1.1 as published by
the European Commission.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1
for more details.
You should have received a copy of the European Union Public Licence - EUPL v.1.1
along with this program.
Further information about the European Union Public Licence - EUPL v.1.1 can
also be found on the world wide web at http://ec.europa.eu/idabc/eupl
*/
/*
------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----
*/
/*
------------------ Author: Annalisa Riccardi -------------------------------------------------
------------------ E-mail: (nina1983@gmail.com) ----------------------------
Modified by Tiziana Sabatini May 2009
Modified by Valentino Zuccarelli on June 11th 2009 lines 533-534
Modified by Tiziana Sabatini on July 2009 to add the perturbation layer
Modifief extensive by Guillermo to correct errors and provide aspect button November 2010
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <QFile>
#include "reentry.h"
#include "Main/scenariotree.h"
#include "Scenario/scenario.h"
#include "Astro-Core/stacoordsys.h"
#include "Astro-Core/date.h"
#include "Astro-Core/stabody.h"
#include "Astro-Core/perturbations.h"
#include "reentrystructures.h"
#include "EntryTrajectory.h"
#include "Scenario/missionAspectDialog.h"
#include <QtDebug>
using namespace Eigen;
// The commented parts are concerning the Window Analysis Mode/ Dispersion Analysis/ Target Analysis;
// this modes are not functioning in the first version of the software, but their code has been kept for
// further developments
double ReEntryDialog::getLocalRadius(ScenarioEnvironmentType* environment, double latitude)
{
QSharedPointer<ScenarioCentralBodyType> centralBody = environment->CentralBody();
QString centralBodyName = centralBody->Name().trimmed();
const StaBody* body = STA_SOLAR_SYSTEM->lookup(centralBodyName);
if (!body)
{
//qDebug() << "Bad central body '" << centralBodyName << "' in entry trajectory.";
return 0;
}
double f, rs;
f = (body->radii().x() - body->radii().z()) / body->radii().x();
rs = body->radii().x() * sqrt( pow((1-f),2) / (1- f*(2-f) * pow(cos(latitude),2)) );
return rs;
}
ReEntryDialog::ReEntryDialog(ScenarioTree* parent) :
QDialog(parent)
{
setupUi(this);
// XVariabComboBox->addItem(tr("CAPSULE BALLISTIC COEFFICIENT [Kg/m2]"), (int) CAPSULE_BALLISTIC_COEFFICIENT);
// XVariabComboBox->addItem(tr("CAPSULE NOSE RADIUS [m]"), (int) CAPSULE_NOSE_RADIUS);
// XVariabComboBox->addItem(tr("INERTIAL ENTRY VELOCITY [Km/s]"), (int) INERTIAL_ENTRY_VELOCITY);
// XVariabComboBox->addItem(tr("INERTIAL FLIGHT PATH ANGLE [deg]"), (int) INERTIAL_FLIGHT_PATH_ANGLE);
// XVariabComboBox->addItem(tr("INERTIAL HEADING [deg]"), (int) INERTIAL_HEADING);
//
// YVariabComboBox->addItem(tr("CAPSULE BALLISTIC COEFFICIENT [Kg/m2]"), (int) CAPSULE_BALLISTIC_COEFFICIENT);
// YVariabComboBox->addItem(tr("CAPSULE NOSE RADIUS [m]"), (int) CAPSULE_NOSE_RADIUS);
// YVariabComboBox->addItem(tr("INERTIAL ENTRY VELOCITY [Km/s]"), (int) INERTIAL_ENTRY_VELOCITY);
// YVariabComboBox->addItem(tr("INERTIAL FLIGHT PATH ANGLE [deg]"), (int) INERTIAL_FLIGHT_PATH_ANGLE);
// YVariabComboBox->addItem(tr("INERTIAL HEADING [deg]"), (int) INERTIAL_HEADING);
//
// ReentryModeComboBox->addItem(tr("Simulation Mode"), "SIMULATION MODE");
// ReentryModeComboBox->addItem(tr("Window Analysis Mode"), "WINDOW ANALYSIS MODE");
CentralBodyComboBox->setMinimumContentsLength(11);
CentralBodyComboBox->addItem(QIcon(":/icons/ComboEarth.png"), tr("Earth"), (int)STA_EARTH);
CentralBodyComboBox->addItem(QIcon(":/icons/ComboMars.png"), tr("Mars"),(int)STA_MARS);
//CentralBodyComboBox->addItem(QIcon(":/icons/ComboVenus.png"), tr("Venus"),(int)STA_VENUS);
//CentralBodyComboBox->addItem(QIcon(":/icons/ComboJupiter.png"), tr("Jupiter"),(int)STA_JUPITER);
//CentralBodyComboBox->addItem(QIcon(":/icons/ComboSaturn.png"), tr("Saturn"),(int)STA_SATURN);
//CentralBodyComboBox->addItem(QIcon(":/icons/ComboUranus.png"), tr("Uranus"),(int)STA_URANUS);
//CentralBodyComboBox->addItem(QIcon(":/icons/ComboNeptune.png"), tr("Neptune"),(int)STA_NEPTUNE);
//CentralBodyComboBox->addItem(QIcon(":/icons/ComboEarth.png"), tr("Titan"),(int)STA_TITAN);
PropagatorComboBox->addItem(tr("Cowell"), "COWELL");
//PropagatorComboBox->addItem(tr("Gauss"), "GAUSS");
IntegratorComboBox->addItem(tr("Runge-Kutta 4"), "RK4");
//IntegratorComboBox->addItem(tr("Runge-Kutta Fehlberg"), "RKF");
InitialStateComboBox->addItem(tr("Spherical Coordinates"), "SPHERICAL COORDINATES");
InitialStateComboBox->addItem(tr("Keplerian Elements"), "KEPLERIAN ELEMENTS");
InitialStateComboBox->addItem(tr("Cartesian Coordinates"), "CARTESIAN COORDINATES");
//Added combo box to select atmosphere and gravity models
// Patched by Guillermo to make in consistant with Loitering GUI
AtmosphereComboBox->addItem(tr("Earth GRAM-99"), "gram99");
AtmosphereComboBox->addItem(tr("Earth Exponential"), "exponential");
AtmosphereComboBox->addItem(tr("Earth US76"), "ussa1976");
AtmosphereComboBox->addItem(tr("Mars EMCD"), "mars_emcd");
// Patched by Guillermo to make in consistant with Loitering GUI
//GravityComboBox->addItem(QIcon(":/icons/ComboEarth.png"), tr("EGM2008"), "EGM2008");
//GravityComboBox->addItem(QIcon(":/icons/ComboMars.png"), tr("GTM090"), "GTM090");
GravityComboBox->addItem(tr("Earth GM2"), "EGM2008");
GravityComboBox->addItem(tr("Mars GTM"), "GTM090");
GravityComboBox->setEnabled(false);
ZonalsSpinBox->setMaximum(20);
//Add the tesserals SpinBox
TesseralSpinBox = new TesseralBox(this);
TesseralSpinBox->setObjectName(QString::fromUtf8("TesseralSpinBox"));
TesseralSpinBox->setEnabled(false);
TesseralSpinBox->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
TesseralSpinBox->setMaximum(ZonalsSpinBox->value());
TesseralSpinBox->setValue(m_tesserals);
gridLayout_8->addWidget(TesseralSpinBox, 2, 1, 1, 1);
// Set up the input validators
QDoubleValidator* doubleValidator = new QDoubleValidator(this);
QIntValidator* intValidator = new QIntValidator(this);
QDoubleValidator* angleValidator = new QDoubleValidator(this);
angleValidator->setBottom(0.0);
angleValidator->setTop(360.0);
QDoubleValidator* angleLatitudeValidator = new QDoubleValidator(this);
angleLatitudeValidator->setBottom(-90);
angleLatitudeValidator->setTop(90);
QDoubleValidator* angleCommandValidator = new QDoubleValidator(this);
angleCommandValidator->setBottom(-180);
angleCommandValidator->setTop(180);
QDoubleValidator* positiveDoubleValidator = new QDoubleValidator(this);
positiveDoubleValidator->setBottom(0.0);
QDoubleValidator* zeroToOneValidator = new QDoubleValidator(this);
zeroToOneValidator->setBottom(0.0);
zeroToOneValidator->setTop(0.9999);
QDoubleValidator* zeroToHundredValidator = new QDoubleValidator(this);
zeroToHundredValidator->setBottom(0.0);
zeroToHundredValidator->setTop(100);
IntegStepLineEdit->setValidator(positiveDoubleValidator);
EntryAltLineEdit->setValidator(positiveDoubleValidator);
EntryLonLineEdit->setValidator(angleValidator);
EntryLatLineEdit->setValidator(angleLatitudeValidator);
InertialVLineEdit->setValidator(doubleValidator);
InertiaFPALineEdit->setValidator(angleCommandValidator);
InertialHeadLineEdit->setValidator(angleCommandValidator);
positionXEdit->setValidator(doubleValidator);
positionYEdit->setValidator(doubleValidator);
positionZEdit->setValidator(doubleValidator);
velocityXEdit->setValidator(doubleValidator);
velocityYEdit->setValidator(doubleValidator);
velocityZEdit->setValidator(doubleValidator);
semimajorAxisEdit->setValidator(positiveDoubleValidator);
eccentricityEdit->setValidator(zeroToOneValidator);
inclinationEdit->setValidator(angleValidator);
raanEdit->setValidator(angleValidator);
argOfPeriapsisEdit->setValidator(angleValidator);
trueAnomalyEdit->setValidator(angleValidator);
// TargetLonEdit->setValidator(angleValidator);
// TargetLatEdit->setValidator(angleLatitudeValidator);
// NumSimEdit->setValidator(intValidator);
//
// DeltaCBRLineEdit->setValidator(doubleValidator);
// DeltaCMLineEdit->setValidator(doubleValidator);
// DeltaCCDLineEdit->setValidator(zeroToHundredValidator);
// DeltaPCDLineEdit->setValidator(zeroToHundredValidator);
// DeltaAthmDLineEdit->setValidator(doubleValidator);
// EntryLonLineEdit_2->setValidator(angleValidator);
// EntryLatLineEdit_2->setValidator(angleLatitudeValidator);
// VelocityLineEdit->setValidator(doubleValidator);
// FPALineEdit->setValidator(angleCommandValidator);
// IHLineEdit->setValidator(angleCommandValidator);
//
// TimeStepLineEdit_2->setValidator(positiveDoubleValidator);
// TargetLonLineEdit_2->setValidator(angleValidator);
// TargetLatLineEdit_2->setValidator(angleLatitudeValidator);
// NumSimLineEdit_2->setValidator(intValidator);
// BCLineEdit->setValidator(positiveDoubleValidator);
// EntryAltLineEdit_2->setValidator(positiveDoubleValidator);
// InertialVLineEdit_2->setValidator(doubleValidator);
// InertialFPALineEdit->setValidator(angleCommandValidator);
// InertialHLineEdit->setValidator(angleCommandValidator);
//
// MinXLineEdit->setValidator(doubleValidator);
// MaxXLineEdit->setValidator(doubleValidator);
// MinYLineEdit->setValidator(doubleValidator);
// MaxYLineEdit->setValidator(doubleValidator);
connect(GravityFieldRadioButton, SIGNAL(toggled(bool)), GravityComboBox, SLOT(setEnabled(bool)));
connect(GravityFieldRadioButton, SIGNAL(toggled(bool)), ZonalsSpinBox, SLOT(setEnabled(bool)));
connect(GravityFieldRadioButton, SIGNAL(toggled(bool)), TesseralSpinBox, SLOT(setEnabled(bool)));
connect(ZonalsSpinBox, SIGNAL(valueChanged(int)), TesseralSpinBox, SLOT(setVariableMaximum(int)));
}
ReEntryDialog::~ReEntryDialog()
{
delete TesseralSpinBox;
}
bool ReEntryDialog::loadValues(ScenarioEntryArcType* reentry)
{
ScenarioElementIdentifierType* arcIdentifier = reentry->ElementIdentifier().data();
ScenarioEnvironmentType* environment = reentry->Environment().data();
ScenarioTimeLine* parameters = reentry->TimeLine().data();
ScenarioPropagationPositionType* propagation = reentry->PropagationPosition().data();
ScenarioInitialPositionType* initPosition = reentry->InitialPosition().data();
ScenarioREVConstraintsType* constraints=reentry->Constraints().data();
if (loadValues(arcIdentifier) && loadValues(environment) && loadValues(parameters) && loadValues(propagation) && loadValues(constraints) && loadValues(initPosition,environment))
{
return true;
}
else
{
return false;
}
}
bool ReEntryDialog::loadValues(ScenarioElementIdentifierType* arcIdentifier)
{
QString theArcName = arcIdentifier->Name();
entryAspect.loadValueArcName(theArcName);
QString theArcColor = arcIdentifier->colorName();
entryAspect.loadValueArcColor(theArcColor);
QString theArcModel = arcIdentifier->modelName();
entryAspect.loadValueArcModel(theArcModel);
return true;
}
bool ReEntryDialog::saveValues(ScenarioElementIdentifierType* arcIdentifier)
{
// The arc name
QString theArcName = entryAspect.saveValueArcName();
arcIdentifier->setName(theArcName);
// The color
QString theColorName = entryAspect.saveValueArcColor();
arcIdentifier->setColorName(theColorName);
// The model
QString theModelName = entryAspect.saveValueArcModel();
arcIdentifier->setModelName(theModelName);
return true;
}
bool ReEntryDialog::saveValues(ScenarioEntryArcType* reentry)
{
ScenarioElementIdentifierType* identifier = reentry->ElementIdentifier().data();
ScenarioEnvironmentType* environment = reentry->Environment().data();
ScenarioTimeLine* parameters = reentry->TimeLine().data();
ScenarioPropagationPositionType* propagation = reentry->PropagationPosition().data();
ScenarioInitialPositionType* initPosition = reentry->InitialPosition().data();
ScenarioREVConstraintsType* constraints=reentry->Constraints().data();
if (saveValues(identifier) && saveValues(environment) && saveValues(parameters) && saveValues(propagation) && saveValues(constraints) && saveValues(initPosition,environment))
{
return true;
}
else
{
return false;
}
return true;
}
bool ReEntryDialog::loadValues(ScenarioREVConstraintsType* constraints)
{
gLimitLineEdit->setText(QString::number(constraints->maxNormalLoad()));
SPHeatRateLineEdit->setText(QString::number(constraints->maxHeatFlux()));
AltitudeLimitLineEdit->setText(QString::number(constraints->maxAltitude()/1000));
return true;
}
bool ReEntryDialog::saveValues(ScenarioREVConstraintsType* constraints)
{
constraints->setMaxNormalLoad(gLimitLineEdit->text().toDouble());
constraints->setMaxHeatFlux(SPHeatRateLineEdit->text().toDouble());
constraints->setMaxAltitude(AltitudeLimitLineEdit->text().toDouble()*1000);
return true;
}
bool ReEntryDialog::loadValues(ScenarioTimeLine* timeLine)
{
dateTimeEdit->setDateTime(timeLine->StartTime());
return true;
}
bool ReEntryDialog::saveValues(ScenarioTimeLine* timeline)
{
timeline->setStartTime(dateTimeEdit->dateTime());
return true;
}
bool ReEntryDialog::loadValues(ScenarioInitialPositionType* initPosition, ScenarioEnvironmentType* environment)//ALso needs environment as argument for radius calculation
{
ScenarioAbstract6DOFPositionType* position = initPosition->Abstract6DOFPosition().data();
ScenarioKeplerianElementsType* elements = dynamic_cast<ScenarioKeplerianElementsType*>(position);
ScenarioStateVectorType* stateVector = dynamic_cast<ScenarioStateVectorType*>(position);
ScenarioSphericalCoordinatesType* sphericalCoord = dynamic_cast<ScenarioSphericalCoordinatesType*>(position);
Q_ASSERT(elements || stateVector || sphericalCoord);
if (elements)
{
InitialStateComboBox->setCurrentIndex(1);
InitialStateStackedWidget->setCurrentWidget(keplerianPage);
semimajorAxisEdit->setText(QString::number(elements->semiMajorAxis()));
eccentricityEdit->setText(QString::number(elements->eccentricity()));
inclinationEdit->setText(QString::number(elements->inclination()*180/Pi()));
raanEdit->setText(QString::number(elements->RAAN()));
argOfPeriapsisEdit->setText(QString::number(elements->argumentOfPeriapsis()*180/Pi()));
trueAnomalyEdit->setText(QString::number(elements->trueAnomaly()*180/Pi()));
}
else if (stateVector != NULL)
{
InitialStateComboBox->setCurrentIndex(2);
InitialStateStackedWidget->setCurrentWidget(stateVectorPage);
//TODO: check if it works
/*
positionXEdit->setText(QString::number(stateVector->x()));
positionYEdit->setText(QString::number(stateVector->y()));
positionZEdit->setText(QString::number(stateVector->z()));
velocityXEdit->setText(QString::number(stateVector->vx()));
velocityYEdit->setText(QString::number(stateVector->vy()));
velocityZEdit->setText(QString::number(stateVector->vz()));
*/
}
else if(sphericalCoord != NULL)
{
InitialStateComboBox->setCurrentIndex(0);
InitialStateStackedWidget->setCurrentWidget(sphericalPage);
//Need to get central body info to go from r to h
double rs=getLocalRadius(environment, sphericalCoord->latitude());
EntryAltLineEdit->setText(QString::number(sphericalCoord->radialDistance()-rs));
EntryLonLineEdit->setText(QString::number(sphericalCoord->longitude()*180/Pi()));
EntryLatLineEdit->setText(QString::number(sphericalCoord->latitude()*180/Pi()));
InertialVLineEdit->setText(QString::number(sphericalCoord->flightPathVelocity()));
InertiaFPALineEdit->setText(QString::number(sphericalCoord->flightPathAngle()*180/Pi()));
InertialHeadLineEdit->setText(QString::number(sphericalCoord->headingAngle()*180/Pi()));
}
/*
else
{
// Unknown initial state type
return false;
}
*/
return true;
}
bool ReEntryDialog::saveValues(ScenarioInitialPositionType* initPos, ScenarioEnvironmentType* environment)
{
//sta::CoordinateSystemType coordSysType = sta::CoordinateSystemType(CoordSystemComboBox->itemData(CoordSystemComboBox->currentIndex()).toInt());
//initPos->setCoordinateSystem(sta::CoordinateSystem(coordSysType).name());
switch (InitialStateComboBox->currentIndex())
{
case 1:
{
ScenarioKeplerianElementsType* elements = new ScenarioKeplerianElementsType;
elements->setSemiMajorAxis(semimajorAxisEdit->text().toDouble());
elements->setEccentricity(eccentricityEdit->text().toDouble());
elements->setInclination(inclinationEdit->text().toDouble());
elements->setRAAN(raanEdit->text().toDouble());
elements->setArgumentOfPeriapsis(argOfPeriapsisEdit->text().toDouble());
elements->setTrueAnomaly(trueAnomalyEdit->text().toDouble());
initPos->setAbstract6DOFPosition(QSharedPointer<ScenarioAbstract6DOFPositionType>(elements));
}
return true;
case 0:
{
ScenarioSphericalCoordinatesType* spherCoord = new ScenarioSphericalCoordinatesType();
spherCoord->setLatitude(EntryLatLineEdit->text().toDouble()*Pi()/180);
double rs=getLocalRadius(environment, spherCoord->latitude());
spherCoord->setRadialDistance(EntryAltLineEdit->text().toDouble()+rs);
spherCoord->setLongitude(EntryLonLineEdit->text().toDouble()*Pi()/180);
spherCoord->setFlightPathVelocity(InertialVLineEdit->text().toDouble());
spherCoord->setFlightPathAngle(InertiaFPALineEdit->text().toDouble()*Pi()/180);
spherCoord->setHeadingAngle(InertialHeadLineEdit->text().toDouble()*Pi()/180);
initPos->setAbstract6DOFPosition(QSharedPointer<ScenarioAbstract6DOFPositionType>(spherCoord));
}
return true;
default:
return false;
}
}
bool ReEntryDialog::loadValues(ScenarioPropagationPositionType* propagation)
{
QString currentPropagator = propagation->propagator();
for (int i = 0; i < PropagatorComboBox->count(); i++)
{
if (PropagatorComboBox->itemData(i) == currentPropagator)
{
PropagatorComboBox->setCurrentIndex(i);
break;
}
}
QString currentIntegrator = propagation->integrator();
for (int i = 0; i < IntegratorComboBox->count(); i++)
{
if (IntegratorComboBox->itemData(i) == currentIntegrator)
{
IntegratorComboBox->setCurrentIndex(i);
break;
}
}
// Lines atched by Guillermo to cope with the problem of the propagation step on the entry module
// Step <= 5 seconds otherwise it does not integrate properly
IntegStepLineEdit->setText(QString::number(propagation->timeStep()));
//IntegStepLineEdit->setText("5");
return true;
}
bool ReEntryDialog::saveValues(ScenarioPropagationPositionType* propagation)
{
propagation->setIntegrator(IntegratorComboBox->itemData(IntegratorComboBox->currentIndex()).toString());
propagation->setPropagator(PropagatorComboBox->itemData(PropagatorComboBox->currentIndex()).toString());
propagation->setTimeStep(IntegStepLineEdit->text().toDouble());
return true;
}
bool ReEntryDialog::loadValues(ScenarioEnvironmentType* environment)
{
QSharedPointer<ScenarioCentralBodyType> centralBody = environment->CentralBody();
if(!centralBody.isNull())
{
QString centralBodyName = centralBody->Name().trimmed();
const StaBody* body = STA_SOLAR_SYSTEM->lookup(centralBodyName);
if (!body)
{
//qDebug() << "Bad central body '" << centralBodyName << "' in loitering trajectory.";
return false;
}
// Set the central body combo box
for (int i = 0; i < CentralBodyComboBox->count(); i++)
{
if (CentralBodyComboBox->itemData(i) == body->id())
{
CentralBodyComboBox->setCurrentIndex(i);
break;
}
}
/*
QString atmospheremodel = centralBody->atmosphere().trimmed();
atmospheremodel.remove(".stad");
//Set something to check if model is valid
for (int i = 0; i < AtmosphereComboBox->count(); i++)
{
if (AtmosphereComboBox->itemData(i) == atmospheremodel)
{
AtmosphereComboBox->setCurrentIndex(i);
break;
}
}
*/
}
else
{
return false;
}
return true;
}
bool ReEntryDialog::saveValues(ScenarioEnvironmentType* environment)
{
StaBody* centralBody = STA_SOLAR_SYSTEM->lookup(CentralBodyComboBox->currentText());
if (centralBody)
{
environment->CentralBody()->setName(centralBody->name());
}
else
{
qWarning("Unknown central body %s", CentralBodyComboBox->currentText().toAscii().data());
return false;
}
/*
QString atmospheremodel = AtmosphereComboBox->itemData(AtmosphereComboBox->currentIndex()).toString();
environment->CentralBody()->setAtmosphere(atmospheremodel);
*/
return true;
}
/*
bool ReEntryDialog::loadValues(ScenarioEnvironment* environment)
{
#if OLDSCENARIO
ScenarioBody* centralBody = environment->centralBody();
if (centralBody)
{
// Set the central body combo box
for (int i = 0; i < CentralBodyComboBox->count(); i++)
{
if (CentralBodyComboBox->itemData(i) == centralBody->body()->id())
{
CentralBodyComboBox->setCurrentIndex(i);
break;
}
}
}
else return false;
//Add the perturbations; only gravity field and atmospheric drag have been considered;
//(the second one is added by default because obviously is always present in the re-entry)
QList<ScenarioPerturbations*> perturbationsList = environment->perturbationsList();
GravityFieldRadioButton->setChecked(false);
if (!perturbationsList.isEmpty())
{
foreach (ScenarioPerturbations* perturbation, perturbationsList)
{
if (dynamic_cast<ScenarioGravityPerturbations*>(perturbation))
{
ScenarioGravityPerturbations* gravity = dynamic_cast<ScenarioGravityPerturbations*>(perturbation);
GravityFieldRadioButton->setChecked(true);
if(!gravity->modelName().isEmpty())
{
QString gravitymodel = gravity->modelName();
gravitymodel.remove(".stad");
for (int i = 0; i < GravityComboBox->count(); i++)
{
if (GravityComboBox->itemData(i) == gravitymodel)
{
GravityComboBox->setCurrentIndex(i);
break;
}
}
}
else return false;
ZonalsSpinBox->setValue(gravity->zonalCount());
m_tesserals = gravity->tesseralCount();
TesseralSpinBox->setValue(m_tesserals);
}
else if (dynamic_cast<ScenarioAtmosphericDragPerturbations*>(perturbation))
{
ScenarioAtmosphericDragPerturbations* drag = dynamic_cast<ScenarioAtmosphericDragPerturbations*>(perturbation);
if(!drag->atmosphericModel().isEmpty())
{
QString atmospheremodel = drag->atmosphericModel();
atmospheremodel.remove(".stad");
for (int i = 0; i < AtmosphereComboBox->count(); i++)
{
if (AtmosphereComboBox->itemData(i) == atmospheremodel)
{
AtmosphereComboBox->setCurrentIndex(i);
break;
}
}
}
else return false;
}
}
}
#endif
return true;
}
*/
/*
bool ReEntryDialog::loadValues(ScenarioSimulationMode* simulationmode)
{
#if OLDSCENARIO
ScenarioTargettingSimulationParameters* parameters = simulationmode->simulationParameters();
//ScenarioDispersionAnalysis* dispersion = simulationmode->dispersionAnalysis();
if(parameters)
{
ScenarioTimeline* timeline = parameters->timeline();
ScenarioInitialStatePosition* initialStatePos = parameters->initialStatePosition();
ScenarioFinalState* finalstate = parameters->finalState();
QDateTime dateTime = sta::JdToCalendar(sta::MjdToJd(timeline->startTime()));
if(timeline)
{
dateTimeEdit->setDateTime(dateTime);
//TimeStepLineEdit->setText(QString::number(timeline->timeStep()));
}
else return false;
if(initialStatePos)
{
// Set the coordinate system combo box value
// for (int i = 0; i < CoordSystemComboBox->count(); i++)
// {
// if (CoordSystemComboBox->itemData(i) == initialStatePos->coordinateSystem().type())
// {
// CoordSystemComboBox->setCurrentIndex(i);
// break;
// }
// }
ScenarioAbstractInitialState* initialState = initialStatePos->initialState();
ScenarioKeplerianElements* elements = dynamic_cast<ScenarioKeplerianElements*>(initialState);
ScenarioStateVector* stateVector = dynamic_cast<ScenarioStateVector*>(initialState);
ScenarioSphericalCoordinates* sphericalCoord = dynamic_cast<ScenarioSphericalCoordinates*>(initialState);
Q_ASSERT(elements || stateVector || sphericalCoord);
if (elements != NULL)
{
InitialStateComboBox->setCurrentIndex(1);
InitialStateStackedWidget->setCurrentWidget(keplerianPage);
semimajorAxisEdit->setText(QString::number(elements->m_semimajorAxis));
eccentricityEdit->setText(QString::number(elements->m_eccentricity));
inclinationEdit->setText(QString::number(elements->m_inclination));
raanEdit->setText(QString::number(elements->m_raan));
argOfPeriapsisEdit->setText(QString::number(elements->m_argumentOfPeriapsis));
trueAnomalyEdit->setText(QString::number(elements->m_trueAnomaly));
}
else if (stateVector != NULL)
{
InitialStateComboBox->setCurrentIndex(2);
InitialStateStackedWidget->setCurrentWidget(stateVectorPage);
//TODO: check if it works
positionXEdit->setText(QString::number(stateVector->position().x()));
positionYEdit->setText(QString::number(stateVector->position().y()));
positionZEdit->setText(QString::number(stateVector->position().z()));
velocityXEdit->setText(QString::number(stateVector->velocity().x()));
velocityYEdit->setText(QString::number(stateVector->velocity().y()));
velocityZEdit->setText(QString::number(stateVector->velocity().z()));
}
else if(sphericalCoord != NULL)
{
InitialStateComboBox->setCurrentIndex(0);
InitialStateStackedWidget->setCurrentWidget(sphericalPage);
EntryAltLineEdit->setText(QString::number(sphericalCoord->altitude()));
EntryLonLineEdit->setText(QString::number(sphericalCoord->longitude()));
EntryLatLineEdit->setText(QString::number(sphericalCoord->latitude()));
InertialVLineEdit->setText(QString::number(sphericalCoord->inertialVelocity()));
InertiaFPALineEdit->setText(QString::number(sphericalCoord->inertialFlightPathAngle()));
InertialHeadLineEdit->setText(QString::number(sphericalCoord->inertialHeading()));
}
else
{
// Unknown initial state type
return false;
}
}
else return false;
// if(finalstate->isActive()){
// TargetRadioButton->setChecked(true);
// targetLon->setEnabled(true);
// TargetLonEdit->setEnabled(true);
// TragetLat->setEnabled(true);
// TargetLatEdit->setEnabled(true);
// TargetLatEdit->setText(QString::number(finalstate->targetLat()));
// TargetLonEdit->setText(QString::number(finalstate->targetLon()));
// }
// else TargetRadioButton->setChecked(false);
}
else return false;
// if(dispersion->isActive()){
// DispersionAnalysisRadioButton->setChecked(true);
// NumSimulLabel->setEnabled(true);
// NumSimEdit->setEnabled(true);
// DeviationGroupBox->setEnabled(true);
// NumSimEdit->setText(QString::number(dispersion->numSimulations()));
// ScenarioDeviations* deviations = dispersion->deviations();
// DeltaCBRLineEdit->setText(QString::number(deviations->capsuleBaseRadius()));
// DeltaCMLineEdit->setText(QString::number(deviations->capsuleMass()));
// DeltaCCDLineEdit->setText(QString::number(deviations->capsuleCD()));
// DeltaPCDLineEdit->setText(QString::number(deviations->parachuteCD()));
// DeltaAthmDLineEdit->setText(QString::number(deviations->atmosphereDensity()));
// EntryLonLineEdit_2->setText(QString::number(deviations->entryLong()));
// EntryLatLineEdit_2->setText(QString::number(deviations->entryLat()));
// VelocityLineEdit->setText(QString::number(deviations->velocity()));
// FPALineEdit->setText(QString::number(deviations->flightPathAngle()));
// IHLineEdit->setText(QString::number(deviations->inertialHeading()));
// }
// else DispersionAnalysisRadioButton->setChecked(false);
#endif
return true;
}
*/
//bool ReEntryDialog::loadValues(ScenarioWindowMode* windowmode){
// ScenarioTargettingSimulationParameters* parameters = windowmode->simulationParameters();
// ScenarioFixedVariables* fixedvar = windowmode->fixedVariables();
// ScenarioWindow* window = windowmode->window();
//
// NumSimLineEdit_2->setText(QString::number(windowmode->numSimulations()));
//
// if(parameters)
// {
// ScenarioTimeline* timeline = parameters->timeline();
// ScenarioFinalState* finalstate = parameters->finalState();
//
// QDateTime dateTime = sta::JdToCalendar(sta::MjdToJd(timeline->startTime()));
// if(timeline){
// dateTimeEdit_2->setDateTime(dateTime);
// TimeStepLineEdit_2->setText(QString::number(timeline->timeStep()));
// }
// else return false;
// if(finalstate->isActive()){
// TargetLatLineEdit_2->setText(QString::number(finalstate->targetLat()));
// TargetLonLineEdit_2->setText(QString::number(finalstate->targetLon()));
// }
//
// }
// else return false;
//
// if(fixedvar){
// EntryAltLineEdit_2->setText(QString::number(fixedvar->entryAltitude()));
// BCLineEdit->setText(QString::number(fixedvar->ballisticCoeff()));
//
// InertialVLineEdit_2->setText(QString::number(fixedvar->inertialVelocity()));
// InertialFPALineEdit->setText(QString::number(fixedvar->inertialFlightPathAngle()));
// InertialHLineEdit->setText(QString::number(fixedvar->inertialHeading()));
// }
// else return false;
//
// if(window){
// ScenarioAbstractReentryTrajectoryParam* xparam = window->xAxisVariable();
// ScenarioAbstractReentryTrajectoryParam* yparam = window->yAxisVariable();
// if(xparam){
// for(int i=0; i<XVariabComboBox->count(); i++){
// if (XVariabComboBox->itemData(i) == xparam->type())
// {
// XVariabComboBox->setCurrentIndex(i);
// break;
// }
// }
// MinXLineEdit->setText(QString::number(xparam->minRange()));
// MaxXLineEdit->setText(QString::number(xparam->maxRange()));
// }
// else return false;
// if(yparam){
// for(int i=0; i<YVariabComboBox->count(); i++){
// if (YVariabComboBox->itemData(i) == yparam->type())
// {
// YVariabComboBox->setCurrentIndex(i);
// break;
// }
// }
// MinYLineEdit->setText(QString::number(yparam->minRange()));
// MaxYLineEdit->setText(QString::number(yparam->maxRange()));
// }
// else return false;
// }
// else return false;
//
// return true;
//}
/*
bool ReEntryDialog::saveValues(ScenarioEntryArcType* reentry)
{
#if OLDSCENARIO
ScenarioEnvironment* environment = reentry->environment();
//ScenarioProperties* vehicleproperties = reentry->vehicleProperties();
ScenarioSimulationMode* simulationmode = reentry->simulationMode();
//ScenarioWindowMode* windowmode = reentry->windowMode();
ScenarioTrajectoryPropagation* propagation = reentry->trajectoryPropagation();
if(saveValues(environment) && saveValues(propagation) && saveValues(simulationmode))
{
//if(ReentryModeComboBox->currentIndex()==0)
{
//windowmode->setIsActiveFalse();
return true;
}
// else if(ReentryModeComboBox->currentIndex()==1)
// {
// saveValues(windowmode);
// simulationmode->setIsActiveFalse();
// return true;
// }
}
#endif
return true;
}
*/
/*
bool ReEntryDialog::saveValues(ScenarioEnvironment* environment)
{
#if OLDSCENARIO
StaBody* body = STA_SOLAR_SYSTEM->lookup(CentralBodyComboBox->currentText());
ScenarioBody* centralbody = new ScenarioBody(body);
if (body)
{
centralbody->setBody(body);
environment->setCentralBody(centralbody);
}
else return false;
if(!environment->perturbationsList().isEmpty())
{
foreach (ScenarioPerturbations* perturbation, environment->perturbationsList())
environment->removePerturbation(perturbation);
}
if(GravityFieldRadioButton->isChecked())
{
ScenarioGravityPerturbations* gravityPerturbation = new ScenarioGravityPerturbations();
QString gravitymodel = GravityComboBox->itemData(GravityComboBox->currentIndex()).toString();
gravitymodel.append(".stad");
gravityPerturbation->setCentralBody(environment->centralBody()->body());
gravityPerturbation->setModelName(gravitymodel);
gravityPerturbation->setZonalCount(ZonalsSpinBox->value());
m_tesserals = TesseralSpinBox->value();
gravityPerturbation->setTesseralCount(m_tesserals);
environment->addPerturbation(gravityPerturbation);
}
//Atmospheric drag perturbation is added by default
ScenarioAtmosphericDragPerturbations* dragPerturbation = new ScenarioAtmosphericDragPerturbations();
QString atmospheremodel = AtmosphereComboBox->itemData(AtmosphereComboBox->currentIndex()).toString();
atmospheremodel.append(".stad");
dragPerturbation->setAtmosphericModel(atmospheremodel);
dragPerturbation->setCentralBody(environment->centralBody()->body());
environment->addPerturbation(dragPerturbation);
#endif
return true;
}
*/
bool ReEntryDialog::saveValues(ScenarioSimulationMode* simulationmode)
{
#if OLDSCENARIO
ScenarioTargettingSimulationParameters* parameters = new ScenarioTargettingSimulationParameters();
ScenarioTimeline* timeline = new ScenarioTimeline();
ScenarioInitialStatePosition* initialStatePos = new ScenarioInitialStatePosition();
ScenarioBody* centralbody=new ScenarioBody(STA_SOLAR_SYSTEM->lookup(CentralBodyComboBox->currentText()));
initialStatePos->setCentralsystemBody(centralbody);
timeline->setStartTime(sta::JdToMjd(sta::CalendarToJd(dateTimeEdit->dateTime())));
//timeline->setTimeStep(TimeStepLineEdit->text().toDouble());
parameters->setTimeline(timeline);
// int coordSysIndex = CoordSystemComboBox->currentIndex();
// initialStatePos->setCoordinateSystem((sta::CoordinateSystemType) CoordSystemComboBox->itemData(coordSysIndex).toInt());
if (InitialStateComboBox->currentIndex() == 0)
{
ScenarioSphericalCoordinates* spherical = new ScenarioSphericalCoordinates();
spherical->m_altitude = EntryAltLineEdit->text().toDouble();
spherical->m_latitude = EntryLatLineEdit->text().toDouble();
spherical->m_longitude = EntryLonLineEdit->text().toDouble();
spherical->m_inertialV = InertialVLineEdit->text().toDouble();
spherical->m_inertialFPA = InertiaFPALineEdit->text().toDouble();
spherical->m_inertialH = InertialHeadLineEdit->text().toDouble();
initialStatePos->setInitialState(spherical);
}
else if (InitialStateComboBox->currentIndex() == 1)
{
ScenarioKeplerianElements* elements = new ScenarioKeplerianElements();
elements->m_semimajorAxis = semimajorAxisEdit->text().toDouble();
elements->m_eccentricity = eccentricityEdit->text().toDouble();
elements->m_inclination = inclinationEdit->text().toDouble();
elements->m_raan = raanEdit->text().toDouble();
elements->m_argumentOfPeriapsis = argOfPeriapsisEdit->text().toDouble();
elements->m_trueAnomaly = trueAnomalyEdit->text().toDouble();
initialStatePos->setInitialState(elements);
}
else
{
ScenarioStateVector* stateVector = new ScenarioStateVector();
Eigen::Vector3d position(positionXEdit->text().toDouble(),
positionYEdit->text().toDouble(),
positionZEdit->text().toDouble());
Eigen::Vector3d velocity(velocityXEdit->text().toDouble(),
velocityYEdit->text().toDouble(),
velocityZEdit->text().toDouble());
stateVector->setPosition(position);
stateVector->setVelocity(velocity);
initialStatePos->setInitialState(stateVector);
}
parameters->setInitialStatePosition(initialStatePos);
// if(TargetRadioButton->isChecked()){
// ScenarioFinalState* finalstate = new ScenarioFinalState();
// finalstate->setIsActiveTrue();
// finalstate->setTargetLat(TargetLatEdit->text().toDouble());
// finalstate->setTargetLon(TargetLonEdit->text().toDouble());
// parameters->setFinalState(finalstate);
// }
// else
// {
// ScenarioFinalState* finalstate = new ScenarioFinalState();
// finalstate->setIsActiveFalse();
// parameters->setFinalState(finalstate);
// }
// if(DispersionAnalysisRadioButton->isChecked())
// {
// ScenarioDispersionAnalysis* dispersion = new ScenarioDispersionAnalysis();
// ScenarioDeviations* deviations = new ScenarioDeviations();
//
// dispersion->setIsActiveTrue();
// dispersion->setnumSimulations(NumSimEdit->text().toInt());
//
// deviations->setAtmosphereDensity(DeltaAthmDLineEdit->text().toDouble());
// deviations->setCapsuleBaseRadius(DeltaCBRLineEdit->text().toDouble());
// deviations->setCapsuleCD(DeltaCCDLineEdit->text().toDouble());
// deviations->setCapsuleMass(DeltaCMLineEdit->text().toDouble());
// deviations->setEntryLat(EntryLatLineEdit_2->text().toDouble());
// deviations->setEntryLong(EntryLonLineEdit_2->text().toDouble());
// deviations->setFlightPathAngle(FPALineEdit->text().toDouble());
// deviations->setInertialHeading(IHLineEdit->text().toDouble());
// deviations->setParachuteCD(DeltaPCDLineEdit->text().toDouble());
// deviations->setVelocity(VelocityLineEdit->text().toDouble());
//
// dispersion->setDeviations(deviations);
// simulationmode->setDispersionAnalysis(dispersion);
// }
// else
// {
// ScenarioDispersionAnalysis* dispersion = new ScenarioDispersionAnalysis();
// dispersion->setIsActiveFalse();
// simulationmode->setDispersionAnalysis(dispersion);
// }
simulationmode->setSimulationParameters(parameters);
simulationmode->setIsActiveTrue();
#endif
return true;
}
//bool ReEntryDialog::saveValues(ScenarioWindowMode* windowmode){
// ScenarioTargettingSimulationParameters* parameters = new ScenarioTargettingSimulationParameters();
// ScenarioFixedVariables* fixedvar = new ScenarioFixedVariables();
// ScenarioWindow* window = new ScenarioWindow();
//
// ScenarioTimeline* timeline = new ScenarioTimeline();
// timeline->setStartTime(sta::JdToMjd(sta::CalendarToJd(dateTimeEdit_2->dateTime())));
// timeline->setTimeStep(TimeStepLineEdit_2->text().toDouble());
//
// parameters->setTimeline(timeline);
//
// ScenarioFinalState* finalstate = new ScenarioFinalState();
// finalstate->setTargetLat(TargetLatLineEdit_2->text().toDouble());
// finalstate->setTargetLon(TargetLonLineEdit_2->text().toDouble());
// finalstate->setIsActiveTrue();
// parameters->setFinalState(finalstate);
//
// fixedvar->setBallisticCoeff(BCLineEdit->text().toDouble());
// fixedvar->setEntryAltitude(EntryAltLineEdit_2->text().toDouble());
// fixedvar->setInertialHeading(InertialHLineEdit->text().toDouble());
// fixedvar->setInertialFlightPathAngle(InertialFPALineEdit->text().toDouble());
// fixedvar->setInertialVelocity(InertialVLineEdit_2->text().toDouble());
//
//
// ScenarioAbstractReentryTrajectoryParam* xvar = new ScenarioAbstractReentryTrajectoryParam((ReentryTrajectoryParamType)(XVariabComboBox->currentIndex()));
// ScenarioAbstractReentryTrajectoryParam* yvar = new ScenarioAbstractReentryTrajectoryParam((ReentryTrajectoryParamType)(YVariabComboBox->currentIndex()));
// xvar->setMax(MaxXLineEdit->text().toDouble());
// xvar->setMin(MinXLineEdit->text().toDouble());
// yvar->setMax(MaxYLineEdit->text().toDouble());
// yvar->setMin(MinYLineEdit->text().toDouble());
//
//
// window->setXAxisVariable(xvar);
// window->setYAxisVariable(yvar);
//
// windowmode->setnumSimulations(NumSimLineEdit_2->text().toInt());
// windowmode->setSimulationParameters(parameters);
// windowmode->setFixedVariables(fixedvar);
// windowmode->setWindow(window);
//
// windowmode->setIsActiveTrue();
//
// return true;
//}
bool PropagateEntryTrajectory(ScenarioREV* vehicle, ScenarioEntryArcType* entry, QList<double>& sampleTimes,
QList<sta::StateVector>& samples,
PropagationFeedback& propFeedback)
{
QString centralBodyName = entry->Environment()->CentralBody()->Name();
StaBody* centralBody = STA_SOLAR_SYSTEM->lookup(centralBodyName);
if (!centralBody)
{
propFeedback.raiseError(QObject::tr("Unrecognized central body '%1'").arg(centralBodyName));
return false;
}
QString coordSysName = entry->InitialPosition()->CoordinateSystem();
sta::CoordinateSystem coordSys(coordSysName);
if (coordSys.type() == sta::COORDSYS_INVALID)
{
propFeedback.raiseError(QObject::tr("Unrecognized coordinate system '%1'").arg(coordSysName));
return false;
}
//get initial position
const ScenarioTimeLine* timeline = entry->TimeLine().data();
double dt = entry->PropagationPosition()->timeStep();
EntrySettings inputSettings = createEntrySettings(entry, vehicle);
EntryTrajectory trajectory(inputSettings);
EntryParameters parameters = createEntryParametersSimulation(entry, vehicle);
QList<Perturbations*> perturbationsList;
sta::StateVector InitialState;
if(parameters.coordselector==1)
InitialState=sphericalTOcartesian(parameters.inputstate);
double startTime = sta::JdToMjd(sta::CalendarToJd(timeline->StartTime()));
double time_jd = sta::MjdToJd(startTime);
double time_s = sta::daysToSecs(startTime);
sta::StateVector stateVector;
stateVector = trajectory.initialise(parameters, InitialState, startTime);
_status status = OK;
unsigned int steps = 0;
if (dt == 0.0)
{
propFeedback.raiseError(QObject::tr("Time step is zero!"));
return false;
}
if (parameters.m == 0.0)
{
propFeedback.raiseError(QObject::tr("Vehicle mass is zero!"));
return false;
}
if (parameters.Sref == 0.0)
{
propFeedback.raiseError(QObject::tr("Vehicle reference Area is zero!"));
return false;
}
if (inputSettings.maxheatrate == 0)
{
propFeedback.raiseError(QObject::tr("The maximum heat rate is zero!"));
return false;
}
if (inputSettings.maxloadfactor == 0)
{
propFeedback.raiseError(QObject::tr("The maximum load factor is zero!"));
return false;
}
QString file="data/aerodynamics/"+inputSettings.CdCprofilename;
qDebug()<<file;
QFile cdFile(file);
if (cdFile.exists()==0)
{
propFeedback.raiseError(QObject::tr("No Cd file set!"));
return false;
}
cdFile.close();
double posx, posy, posz, velx, vely, velz;
int celestialbody;
if (inputSettings.bodyname == "Earth")
celestialbody = 0;
else if (inputSettings.bodyname == "Mars")
celestialbody = 3;
int i=0;
while (status == OK)
{
stateVector = trajectory.integrate(stateVector, perturbationsList);
status = trajectory.status;
time_jd += sta::secsToDays(dt);
double theta = getGreenwichHourAngle(time_jd);
time_s += dt;
JulianDate jd = sta::secsToDays(time_s);
fixedTOinertial(celestialbody, theta , stateVector.position.x(), stateVector.position.y(), stateVector.position.z(), stateVector.velocity.x(), stateVector.velocity.y(), stateVector.velocity.z(),
posx, posy, posz, velx, vely, velz);
Eigen::Vector3d pos = Vector3d(posx/1000, posy/1000, posz/1000);
Eigen::Vector3d vel = Vector3d(velx/1000, vely/1000, velz/1000);
sta::StateVector statevector = sta::StateVector(pos, vel);
samples << statevector;
sampleTimes << jd;
i++;
}
return true;
//QString propagator = entry->PropagationPosition()->propagator();
//QString integrator = entry->PropagationPosition()->integrator();
}
void ReEntryDialog::on_pushButtonAspect_clicked()
{
entryAspect.exec();
}
| 42.499574 | 203 | 0.644347 | [
"model"
] |
0417a03fe5099e5e86ac65c7cb27ee5e2fb48541 | 7,076 | cpp | C++ | controller/net/PacketReassembler.cpp | danog/libtgvoip | e6211103f04f728200504c0756eff3561746e218 | [
"Unlicense"
] | 1 | 2018-10-20T18:40:21.000Z | 2018-10-20T18:40:21.000Z | controller/net/PacketReassembler.cpp | danog/libtgvoip | e6211103f04f728200504c0756eff3561746e218 | [
"Unlicense"
] | null | null | null | controller/net/PacketReassembler.cpp | danog/libtgvoip | e6211103f04f728200504c0756eff3561746e218 | [
"Unlicense"
] | 1 | 2019-02-03T18:42:01.000Z | 2019-02-03T18:42:01.000Z | //
// Created by Grishka on 19.03.2018.
//
#include "PacketReassembler.h"
#include "tools/logging.h"
#include "VoIPController.h"
#include "video/VideoFEC.h"
#include <assert.h>
#include <sstream>
#define NUM_OLD_PACKETS 3
#define NUM_FEC_PACKETS 10
using namespace tgvoip;
using namespace tgvoip::video;
PacketReassembler::PacketReassembler()
{
}
PacketReassembler::~PacketReassembler()
{
}
void PacketReassembler::Reset()
{
}
void PacketReassembler::AddFragment(Buffer pkt, unsigned int fragmentIndex, unsigned int fragmentCount, uint32_t pts, uint8_t _fseq, bool keyframe, uint16_t rotation)
{
for (std::unique_ptr<Packet> &packet : packets)
{
if (packet->timestamp == pts)
{
if (fragmentCount != packet->partCount)
{
LOGE("Received fragment total count %u inconsistent with previous %u", fragmentCount, packet->partCount);
return;
}
if (fragmentIndex >= packet->partCount)
{
LOGE("Received fragment index %u is greater than total %u", fragmentIndex, fragmentCount);
return;
}
packet->AddFragment(std::move(pkt), fragmentIndex);
return;
}
}
uint32_t fseq = (lastFrameSeq & 0xFFFFFF00) | (uint32_t)_fseq;
if ((uint8_t)lastFrameSeq > _fseq)
fseq += 256;
//LOGV("fseq: %u", (unsigned int)fseq);
/*if(pts<maxTimestamp){
LOGW("Received fragment doesn't belong here (ts=%u < maxTs=%u)", pts, maxTimestamp);
return;
}*/
if (lastFrameSeq > 3 && fseq < lastFrameSeq - 3)
{
LOGW("Packet too late (fseq=%u, lastFseq=%u)", fseq, lastFrameSeq);
return;
}
if (fragmentIndex >= fragmentCount)
{
LOGE("Received fragment index %u is out of bounds %u", fragmentIndex, fragmentCount);
return;
}
if (fragmentCount > 255)
{
LOGE("Received fragment total count too big %u", fragmentCount);
return;
}
maxTimestamp = std::max(maxTimestamp, pts);
packets.push_back(std::make_unique<Packet>(fseq, pts, fragmentCount, 0, keyframe, rotation));
packets[packets.size() - 1]->AddFragment(std::move(pkt), fragmentIndex);
while (packets.size() > 3)
{
std::unique_ptr<Packet> &_old = packets[0];
if (_old->receivedPartCount == _old->partCount)
{
std::unique_ptr<Packet> old = std::move(packets[0]);
packets.erase(packets.begin());
Buffer buffer = old->Reassemble();
callback(std::move(buffer), old->seq, old->isKeyframe, old->rotation);
oldPackets.push_back(std::move(old));
while (oldPackets.size() > NUM_OLD_PACKETS)
oldPackets.erase(oldPackets.begin());
}
else
{
LOGW("Packet %u not reassembled (%u of %u)", packets[0]->seq, packets[0]->receivedPartCount, packets[0]->partCount);
if (packets[0]->partCount - packets[0]->receivedPartCount == 1 && !waitingForFEC)
{
bool found = false;
for (FecPacket &fec : fecPackets)
{
if (packets[0]->seq <= fec.seq && packets[0]->seq > fec.seq - fec.prevFrameCount)
{
LOGI("Found FEC packet: %u %u", fec.seq, fec.prevFrameCount);
found = true;
TryDecodeFEC(fec);
packets.erase(packets.begin());
break;
}
}
if (!found)
{
waitingForFEC = true;
break;
}
}
else
{
waitingForFEC = false;
LOGE("unrecoverable packet loss");
std::unique_ptr<Packet> old = std::move(packets[0]);
packets.erase(packets.begin());
oldPackets.push_back(std::move(old));
while (oldPackets.size() > NUM_OLD_PACKETS)
oldPackets.erase(oldPackets.begin());
}
}
}
lastFrameSeq = fseq;
}
void PacketReassembler::AddFEC(Buffer data, uint8_t _fseq, unsigned int frameCount, unsigned int fecScheme)
{
uint32_t fseq = (lastFrameSeq & 0xFFFFFF00) | (uint32_t)_fseq;
std::ostringstream _s;
for (unsigned int i = 0; i < frameCount; i++)
{
_s << (fseq - i);
_s << " ";
}
//LOGV("Received FEC packet: len %u, scheme %u, frames %s", (unsigned int)data.Length(), fecScheme, _s.str().c_str());
FecPacket fec{
fseq,
frameCount,
fecScheme,
std::move(data)};
if (waitingForFEC)
{
if (packets[0]->seq <= fec.seq && packets[0]->seq > fec.seq - fec.prevFrameCount)
{
LOGI("Found FEC packet: %u %u", fec.seq, fec.prevFrameCount);
TryDecodeFEC(fec);
packets.erase(packets.begin());
waitingForFEC = false;
}
}
fecPackets.push_back(std::move(fec));
while (fecPackets.size() > NUM_FEC_PACKETS)
fecPackets.erase(fecPackets.begin());
}
void PacketReassembler::SetCallback(std::function<void(Buffer packet, uint32_t pts, bool keyframe, uint16_t rotation)> callback)
{
this->callback = callback;
}
bool PacketReassembler::TryDecodeFEC(PacketReassembler::FecPacket &fec)
{
LOGI("Decoding FEC");
std::vector<Buffer> packetsForRecovery;
for (std::unique_ptr<Packet> &p : oldPackets)
{
if (p->seq <= fec.seq && p->seq > fec.seq - fec.prevFrameCount)
{
LOGD("Adding frame %u from old", p->seq);
for (uint32_t i = 0; i < p->partCount; i++)
{
packetsForRecovery.push_back(i < p->parts.size() ? Buffer::CopyOf(p->parts[i]) : Buffer());
}
}
}
for (std::unique_ptr<Packet> &p : packets)
{
if (p->seq <= fec.seq && p->seq > fec.seq - fec.prevFrameCount)
{
LOGD("Adding frame %u from pending", p->seq);
for (uint32_t i = 0; i < p->partCount; i++)
{
//LOGV("[%u] size %u", i, p.parts[i].Length());
packetsForRecovery.push_back(i < p->parts.size() ? Buffer::CopyOf(p->parts[i]) : Buffer());
}
}
}
if (fec.fecScheme == FEC_SCHEME_XOR)
{
Buffer recovered = ParityFEC::Decode(packetsForRecovery, fec.data);
LOGI("Recovered packet size %u", (unsigned int)recovered.Length());
if (!recovered.IsEmpty())
{
std::unique_ptr<Packet> &pkt = packets[0];
if (pkt->parts.size() < pkt->partCount)
{
pkt->parts.push_back(std::move(recovered));
}
else
{
for (Buffer &b : pkt->parts)
{
if (b.IsEmpty())
{
b = std::move(recovered);
break;
}
}
}
pkt->receivedPartCount++;
callback(pkt->Reassemble(), pkt->seq, pkt->isKeyframe, pkt->rotation);
}
}
return false;
}
#pragma mark - Packet
void PacketReassembler::Packet::AddFragment(Buffer pkt, uint32_t fragmentIndex)
{
//LOGV("Add fragment %u/%u to packet %u", fragmentIndex, partCount, timestamp);
if (parts.size() == fragmentIndex)
{
parts.push_back(std::move(pkt));
//LOGV("add1");
}
else if (parts.size() > fragmentIndex)
{
assert(parts[fragmentIndex].IsEmpty());
parts[fragmentIndex] = std::move(pkt);
//LOGV("add2");
}
else
{
while (parts.size() < fragmentIndex)
parts.push_back(Buffer());
parts.push_back(std::move(pkt));
//LOGV("add3");
}
receivedPartCount++;
//assert(parts.size()>=receivedPartCount);
if (parts.size() < receivedPartCount)
LOGW("Received %u parts but parts.size is %u", (unsigned int)receivedPartCount, (unsigned int)parts.size());
}
Buffer PacketReassembler::Packet::Reassemble()
{
assert(partCount == receivedPartCount);
assert(parts.size() == partCount);
if (partCount == 1)
{
return Buffer::CopyOf(parts[0]);
}
BufferOutputStream out(10240);
for (unsigned int i = 0; i < partCount; i++)
{
out.WriteBytes(parts[i]);
//parts[i]=Buffer();
}
return Buffer(std::move(out));
}
| 25.824818 | 166 | 0.657434 | [
"vector"
] |
04207f45fe19ec54b02e7ce643ef9108b1765584 | 2,678 | cpp | C++ | Linux/condor-remove/moc_Condor_Remove.cpp | BigWhiteCat/Qt-QML | 7d601721db535167ea257e8baffc1de83cc0aa15 | [
"MIT"
] | null | null | null | Linux/condor-remove/moc_Condor_Remove.cpp | BigWhiteCat/Qt-QML | 7d601721db535167ea257e8baffc1de83cc0aa15 | [
"MIT"
] | null | null | null | Linux/condor-remove/moc_Condor_Remove.cpp | BigWhiteCat/Qt-QML | 7d601721db535167ea257e8baffc1de83cc0aa15 | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'Condor_Remove.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "Condor_Remove.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'Condor_Remove.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.10.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_Condor_Remove_t {
QByteArrayData data[1];
char stringdata0[14];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Condor_Remove_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Condor_Remove_t qt_meta_stringdata_Condor_Remove = {
{
QT_MOC_LITERAL(0, 0, 13) // "Condor_Remove"
},
"Condor_Remove"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Condor_Remove[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void Condor_Remove::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject Condor_Remove::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_Condor_Remove.data,
qt_meta_data_Condor_Remove, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *Condor_Remove::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Condor_Remove::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_Condor_Remove.stringdata0))
return static_cast<void*>(this);
return QObject::qt_metacast(_clname);
}
int Condor_Remove::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 29.428571 | 96 | 0.658327 | [
"object"
] |
04235748db6125964043d9365fa959c6f1ab0e55 | 33,402 | cpp | C++ | src/gui/video_writer_ufmf.cpp | hhhHanqing/bias | ac409978ac0bfc6bc4cf8570bf7ce7509e81a219 | [
"Apache-2.0"
] | 5 | 2020-07-23T18:59:08.000Z | 2021-12-14T02:56:12.000Z | src/gui/video_writer_ufmf.cpp | hhhHanqing/bias | ac409978ac0bfc6bc4cf8570bf7ce7509e81a219 | [
"Apache-2.0"
] | 4 | 2020-08-30T13:55:22.000Z | 2022-03-24T21:14:15.000Z | src/gui/video_writer_ufmf.cpp | hhhHanqing/bias | ac409978ac0bfc6bc4cf8570bf7ce7509e81a219 | [
"Apache-2.0"
] | 3 | 2020-10-04T17:53:15.000Z | 2022-02-24T05:55:53.000Z | #include "video_writer_ufmf.hpp"
#include "basic_types.hpp"
#include "exception.hpp"
#include "lockable.hpp"
#include "background_data_ufmf.hpp"
#include "background_histogram_ufmf.hpp"
#include "background_median_ufmf.hpp"
#include <QThreadPool>
#include <QFileInfo>
#include <QDir>
#include <iostream>
namespace bias
{
// Static Constants
// ----------------------------------------------------------------------------------
const unsigned int VideoWriter_ufmf::FRAMES_TODO_MAX_QUEUE_SIZE = 250;
const unsigned int VideoWriter_ufmf::FRAMES_FINISHED_MAX_SET_SIZE = 250;
const unsigned int VideoWriter_ufmf::FRAMES_WAIT_MAX_QUEUE_SIZE = 50;
const unsigned int VideoWriter_ufmf::DEFAULT_FRAME_SKIP = 1;
const unsigned int VideoWriter_ufmf::DEFAULT_BACKGROUND_THRESHOLD = 40;
const unsigned int VideoWriter_ufmf::MIN_BACKGROUND_THRESHOLD = 1;
const unsigned int VideoWriter_ufmf::MAX_BACKGROUND_THRESHOLD = 255;
const unsigned int VideoWriter_ufmf::DEFAULT_BOX_LENGTH = 30;
const unsigned int VideoWriter_ufmf::MIN_BOX_LENGTH = 4;
const unsigned int VideoWriter_ufmf::MAX_BOX_LENGTH = 500;
const unsigned int VideoWriter_ufmf::DEFAULT_NUMBER_OF_COMPRESSORS = 15;
const unsigned int VideoWriter_ufmf::MIN_NUMBER_OF_COMPRESSORS = 1;
const unsigned int VideoWriter_ufmf::BASE_NUMBER_OF_THREADS = 4;
const bool VideoWriter_ufmf::DEFAULT_DILATE_STATE = true;
const unsigned int VideoWriter_ufmf::DEFAULT_DILATE_WINDOW_SIZE = 1;
const unsigned int VideoWriter_ufmf::MIN_DILATE_WINDOW_SIZE = 1;
const unsigned int VideoWriter_ufmf::MAX_DILATE_WINDOW_SIZE = 20;
const VideoWriterParams_ufmf VideoWriter_ufmf::DEFAULT_PARAMS =
VideoWriterParams_ufmf();
const QString VideoWriter_ufmf::DEFAULT_COLOR_CODING("MONO8");
const QString VideoWriter_ufmf::DUMMY_FILENAME("dummy.ufmf");
const QString VideoWriter_ufmf::UFMF_HEADER_STRING("ufmf");
const unsigned int VideoWriter_ufmf::UFMF_VERSION_NUMBER = 4;
const unsigned int VideoWriter_ufmf::KEYFRAME_CHUNK_ID = 0;
const unsigned int VideoWriter_ufmf::FRAME_CHUNK_ID = 1;
const unsigned int VideoWriter_ufmf::INDEX_DICT_CHUNK_ID = 2;
const char VideoWriter_ufmf::CHAR_FOR_DICT = 'd';
const char VideoWriter_ufmf::CHAR_FOR_ARRAY = 'a';
const char VideoWriter_ufmf::CHAR_FOR_DTYPE_FLOAT = 'f';
const char VideoWriter_ufmf::CHAR_FOR_DTYPE_UINT8 = 'B';
const char VideoWriter_ufmf::CHAR_FOR_DTYPE_UINT64 = 'q';
const char VideoWriter_ufmf::CHAR_FOR_DTYPE_DOUBLE = 'd';
// Methods
// ----------------------------------------------------------------------------------
VideoWriter_ufmf::VideoWriter_ufmf(QObject *parent)
: VideoWriter_ufmf(DEFAULT_PARAMS, DUMMY_FILENAME, 0, parent)
{}
VideoWriter_ufmf::VideoWriter_ufmf(
VideoWriterParams_ufmf params,
QString fileName,
unsigned int cameraNumber,
QObject *parent
)
: VideoWriter(fileName,cameraNumber,parent)
{
isFirst_ = true;
skipReported_ = false;
backgroundThreshold_ = params.backgroundThreshold;
medianUpdateCount_ = params.medianUpdateCount;
medianUpdateInterval_ = params.medianUpdateInterval;
boxLength_ = params.boxLength;
setFrameSkip(params.frameSkip);
numberOfCompressors_ = params.numberOfCompressors;
dilateState_ = params.dilateState;
dilateWindowSize_ = params.dilateWindowSize;
// ----------------------------------------------------------------------------
//std::cout << params.toString() << std::endl;
// -----------------------------------------------------------------------------
// Create thread pool for background modelling
threadPoolPtr_ = new QThreadPool(this);
unsigned int maxThreadCount = numberOfCompressors_ + BASE_NUMBER_OF_THREADS;
threadPoolPtr_ -> setMaxThreadCount(maxThreadCount);
// Create queue for images sent to background modeler
bgImageQueuePtr_ = std::make_shared<LockableQueue<StampedImage>>();
bgNewDataQueuePtr_ = std::make_shared<LockableQueue<BackgroundData_ufmf>>();
bgOldDataQueuePtr_ = std::make_shared<LockableQueue<BackgroundData_ufmf>>();
medianMatQueuePtr_ = std::make_shared<LockableQueue<cv::Mat>>();
// Create "to do" queue and "finished" set for frame compressors
framesToDoQueuePtr_ = std::make_shared<CompressedFrameQueue_ufmf>();
framesWaitQueuePtr_ = std::make_shared<CompressedFrameQueue_ufmf>();
framesFinishedSetPtr_ = std::make_shared<CompressedFrameSet_ufmf>();
framesSkippedIndexListPtr_ = std::make_shared<Lockable<std::list<unsigned long>>>();
isFixedSize_ = false;
colorCoding_ = QString(DEFAULT_COLOR_CODING);
indexLocation_ = 0;
nextFrameToWrite_ = 0;
numKeyFramesWritten_ = 0;
bgUpdateCount_ = 0;
bgModelFrameCount_ = 0;
bgModelTimeStamp_ = 0.0;
}
VideoWriter_ufmf::~VideoWriter_ufmf()
{
stopBackgroundModeling();
stopCompressors();
threadPoolPtr_ -> waitForDone();
finishWriting();
}
void VideoWriter_ufmf::addFrame(StampedImage stampedImg)
{
bool skipFrame = false;
bool haveNewMedianImage = false;
currentImage_ = stampedImg;
// On first call - setup output file, background modeling, start compressors, ...
if (isFirst_)
{
checkImageFormat(stampedImg);
// Set output file and write header
setupOutputFile(stampedImg);
writeHeader();
// Set initial bg median image - just use current image.
bgMedianImage_ = stampedImg.image;
bgMembershipImage_.create(stampedImg.image.rows, stampedImg.image.cols,CV_8UC1);
cv::add(bgMedianImage_, backgroundThreshold_, bgUpperBoundImage_);
cv::subtract(bgMedianImage_, backgroundThreshold_, bgLowerBoundImage_);
// Start background model and frame compressors
startBackgroundModeling();
startCompressors();
writeKeyFrame();
isFirst_ = false;
}
// Process frames or skip
if (frameCount_%frameSkip_==0)
{
// Add frame to background image queue if it is empty
bgImageQueuePtr_ -> acquireLock();
if (bgImageQueuePtr_ -> empty())
{
bgImageQueuePtr_ -> push(stampedImg);
bgImageQueuePtr_ -> signalNotEmpty();
}
bgImageQueuePtr_ -> releaseLock();
// Get median image if available
medianMatQueuePtr_ -> acquireLock();
if (!(medianMatQueuePtr_ -> empty()))
{
bgMedianImage_ = medianMatQueuePtr_ -> front();
medianMatQueuePtr_ -> pop();
haveNewMedianImage = true;
}
medianMatQueuePtr_ -> releaseLock();
// When new median image available re-calculate thresholds
if (haveNewMedianImage)
{
cv::add(bgMedianImage_, backgroundThreshold_, bgUpperBoundImage_);
cv::subtract(bgMedianImage_, backgroundThreshold_, bgLowerBoundImage_);
bgUpdateCount_++;
bgModelTimeStamp_ = currentImage_.timeStamp;
bgModelFrameCount_ = currentImage_.frameCount;
writeKeyFrame();
}
// Create compressed frame and set its data using the current frame
CompressedFrame_ufmf compressedFrame(boxLength_);
compressedFrame.dilateEnabled(dilateState_);
compressedFrame.setDilateWindowSize(dilateWindowSize_);
if (!(framesWaitQueuePtr_ -> empty()))
{
// Take pre-allocated compressed frame if available
compressedFrame = framesWaitQueuePtr_ -> front();
framesWaitQueuePtr_ -> pop();
}
compressedFrame.setData(
currentImage_,
bgLowerBoundImage_,
bgUpperBoundImage_,
bgUpdateCount_
);
framesToDoQueuePtr_ -> acquireLock();
unsigned int framesToDoQueueSize = framesToDoQueuePtr_ -> size();
if (framesToDoQueueSize < FRAMES_TODO_MAX_QUEUE_SIZE)
{
// Insert new (uncalculated) compressed frame into "to do" queue.
framesToDoQueuePtr_ -> push(compressedFrame);
framesToDoQueuePtr_ -> wakeOne();
}
else
{
skipFrame = true;
}
framesToDoQueuePtr_ -> releaseLock();
if (skipFrame)
{
// Queue is full - skip frame
framesSkippedIndexListPtr_ -> acquireLock();
framesSkippedIndexListPtr_ -> push_back(stampedImg.frameCount);
framesSkippedIndexListPtr_ -> releaseLock();
skipReported_ = true;
}
} // if (frameCount_%frameSkip_==0)
// Remove frames from compressed frames "finished" set and write to disk
//framesFinishedSetSize = clearFinishedFrames();
clearFinishedFrames();
frameCount_++;
// Cull framesWaitQueue if it starts to grow too large
unsigned int framesWaitQueueSize = framesWaitQueuePtr_ -> size();
if ( framesWaitQueueSize > FRAMES_WAIT_MAX_QUEUE_SIZE )
{
unsigned int numToCull = framesWaitQueueSize - FRAMES_WAIT_MAX_QUEUE_SIZE/2;
for (unsigned int i=0; i<numToCull; i++)
{
framesWaitQueuePtr_ -> pop();
}
}
// Report skipped frame
if ((skipFrame) && (!skipReported_))
{
std::cout << "warning: logging overflow - skipped frame -" << std::endl;
unsigned int errorId = ERROR_FRAMES_TODO_MAX_QUEUE_SIZE;
QString errorMsg("logger framesToDoQueue has exceeded the maximum allowed size");
emit imageLoggingError(errorId, errorMsg);
skipReported_ = true;
}
}
void VideoWriter_ufmf::finish()
{
while (clearFinishedFrames() > 0);
}
unsigned int VideoWriter_ufmf::clearFinishedFrames()
{
framesFinishedSetPtr_ -> acquireLock();
bool framesFinishedSetEmpty = framesFinishedSetPtr_ -> empty();
framesFinishedSetPtr_ -> releaseLock();
if (!framesFinishedSetEmpty)
{
bool writeDone = false;
while ( (!writeDone) && (!framesFinishedSetEmpty) )
{
// Handle skipped frames.
// --------------------------------------------------------------------------------
framesSkippedIndexListPtr_ -> acquireLock();
if (framesSkippedIndexListPtr_ -> size() > 0)
{
std::list<unsigned long>::iterator skippedIndexIt = framesSkippedIndexListPtr_ -> begin();
bool done = false;
while (!done)
{
if (*skippedIndexIt == nextFrameToWrite_)
{
nextFrameToWrite_ += frameSkip_;
}
else if (*skippedIndexIt < nextFrameToWrite_)
{
if (framesSkippedIndexListPtr_ -> size() > 1)
{
skippedIndexIt++;
}
else
{
done = true;
}
framesSkippedIndexListPtr_ -> pop_front();
}
else
{
done = true;
}
}
}
framesSkippedIndexListPtr_ -> releaseLock();
// Write next frame to file
// --------------------------------------------------------------------------------
framesFinishedSetPtr_ -> acquireLock();
CompressedFrameSet_ufmf::iterator frameIt = framesFinishedSetPtr_ -> begin();
CompressedFrame_ufmf compressedFrame = *frameIt;
if (compressedFrame.getFrameCount() == nextFrameToWrite_)
{
framesWaitQueuePtr_ -> push(compressedFrame);
framesFinishedSetPtr_ -> erase(frameIt);
nextFrameToWrite_ += frameSkip_;
writeCompressedFrame(compressedFrame);
}
else
{
writeDone = true;
}
framesFinishedSetEmpty = framesFinishedSetPtr_ -> empty();
framesFinishedSetPtr_ -> releaseLock();
} // while ( (!writeDone) && (!framesFinishedSetEmpty) )
} // if (!(framesFinishedSetPtr_
framesFinishedSetPtr_ -> acquireLock();
unsigned int framesFinishedSetSize = framesFinishedSetPtr_ -> size();
framesFinishedSetPtr_ -> releaseLock();
return framesFinishedSetSize;
}
void VideoWriter_ufmf::checkImageFormat(StampedImage stampedImg)
{
if (stampedImg.image.channels() != 1)
{
unsigned int errorId = ERROR_VIDEO_WRITER_INITIALIZE;
std::string errorMsg("video writer ufmf setup failed:\n\n");
errorMsg += "images must be single channel";
throw RuntimeError(errorId,errorMsg);
}
if (stampedImg.image.depth() != CV_8U)
{
unsigned int errorId = ERROR_VIDEO_WRITER_INITIALIZE;
std::string errorMsg("video writer ufmf setup failed:\n\n");
errorMsg += "image depth must be CV_8U";
throw RuntimeError(errorId,errorMsg);
}
}
void VideoWriter_ufmf::setupOutputFile(StampedImage stampedImg)
{
// Set error control state, set exceptions mask
file_.clear();
file_.exceptions(std::ifstream::failbit | std::ifstream::badbit);
// Get unique name for file and open for reading
QString incrFileName = getUniqueFileName();
try
{
file_.open(incrFileName.toStdString(), std::ios::binary | std::ios::out);
}
catch (std::ifstream::failure &exc)
{
unsigned int errorId = ERROR_VIDEO_WRITER_INITIALIZE;
std::string errorMsg("video writer unable to open file:\n\n");
errorMsg += exc.what();
throw RuntimeError(errorId, errorMsg);
}
if (!file_.is_open())
{
unsigned int errorId = ERROR_VIDEO_WRITER_INITIALIZE;
std::string errorMsg("video writer unable to open file:\n\n");
errorMsg += "no exception thrown";
throw RuntimeError(errorId, errorMsg);
}
setSize(stampedImg.image.size());
}
void VideoWriter_ufmf::writeHeader()
{
try
{
QByteArray headerStrArray = UFMF_HEADER_STRING.toLatin1();
unsigned int headerStrLen = UFMF_HEADER_STRING.size();
file_.write((char*) headerStrArray.data(), headerStrLen*sizeof(char));
uint32_t ufmf_version = uint32_t(UFMF_VERSION_NUMBER);
file_.write((char*) &ufmf_version, sizeof(uint32_t));
indexLocationPtr_ = file_.tellp();
uint64_t indexLocation_uint64 = uint64_t(indexLocation_);
file_.write((char*) &indexLocation_uint64, sizeof(uint64_t));
if (isFixedSize_)
{
uint16_t boxLength_uint16 = uint16_t(boxLength_);
file_.write((char*) &boxLength_uint16, sizeof(uint16_t));
file_.write((char*) &boxLength_uint16, sizeof(uint16_t));
}
else
{
uint16_t width = uint16_t(size_.width);
file_.write((char*) &width, sizeof(uint16_t));
uint16_t height = uint16_t(size_.height);
file_.write((char*) &height, sizeof(uint16_t));
}
uint8_t isFixedSize_uint8 = uint8_t(isFixedSize_);
file_.write((char*) &isFixedSize_uint8, sizeof(uint8_t));
uint8_t colorCodingLength = uint8_t(colorCoding_.size());
file_.write((char*) &colorCodingLength, sizeof(uint8_t));
QByteArray colorCodingArray = colorCoding_.toLatin1();
file_.write((char*) colorCodingArray.data(), colorCodingLength*sizeof(char));
}
catch (std::ifstream::failure &exc)
{
unsigned int errorId = ERROR_VIDEO_WRITER_INITIALIZE;
std::string errorMsg("video writer unable to write ufmf header:\n\n");
errorMsg += exc.what();
throw RuntimeError(errorId, errorMsg);
}
}
void VideoWriter_ufmf::finishWriting()
{
// Move to end of filed
file_.seekp(0, std::ios_base::end);
// Write index
// --------------------------------------------------------------------
// Write index chunk identifier and save index location
uint8_t chunkId = uint8_t(INDEX_DICT_CHUNK_ID);
file_.write((char*) &chunkId, sizeof(uint8_t));
indexLocation_ = file_.tellp();
// Write char for dict and number of keys
file_.write((char*) &CHAR_FOR_DICT, sizeof(char));
uint8_t numKeys = 2;
file_.write((char*) &numKeys, sizeof(uint8_t));
// Write index -> frame
// --------------------------------------------------------------------
// Write length of key and key for frame
const char frameString[] = "frame";
uint16_t frameStringLength = uint16_t(sizeof(frameString)-1);
file_.write((char*) &frameStringLength, sizeof(uint16_t));
file_.write((char*) frameString, frameStringLength*sizeof(char));
// Write char for dict and number of keys
file_.write((char*) &CHAR_FOR_DICT, sizeof(char));
numKeys = 2;
file_.write((char*) &numKeys, sizeof(uint8_t));
// Write index -> frame -> location
// --------------------------------------------------------------------
// Write length of key and key for location
const char locString[] = "loc";
uint16_t locStringLength = uint16_t(sizeof(locString) - 1);
file_.write((char*) &locStringLength, sizeof(uint16_t));
file_.write((char*) locString, locStringLength*sizeof(char));
// Write char for array and data type
file_.write((char*) &CHAR_FOR_ARRAY, sizeof(char));
file_.write((char*) &CHAR_FOR_DTYPE_UINT64, sizeof(char));
// Write number of bytes and frame positions
uint32_t numBytes = uint32_t(framePosList_.size()*sizeof(uint64_t));
file_.write((char*) &numBytes, sizeof(uint32_t));
for (
std::list<std::streampos>::iterator it=framePosList_.begin();
it!=framePosList_.end();
it++
)
{
uint64_t pos = *it;
file_.write((char*) &pos, sizeof(uint64_t));
}
// End write index -> frame -> location
// --------------------------------------------------------------------
// Write index -> frame -> timestamp
// --------------------------------------------------------------------
// Write key length and key for timestamp
const char timeStampString[] = "timestamp";
uint16_t timeStampStringLength = uint16_t(sizeof(timeStampString)-1);
file_.write((char*) &timeStampStringLength, sizeof(uint16_t));
file_.write((char*) timeStampString, timeStampStringLength*sizeof(char));
// Write char for array and data type
file_.write((char*) &CHAR_FOR_ARRAY, sizeof(char));
file_.write((char*) &CHAR_FOR_DTYPE_DOUBLE, sizeof(char));
// Write number of bytes and time stamps
numBytes = uint32_t(frameTimeStampList_.size()*sizeof(double));
file_.write((char*) &numBytes, sizeof(uint32_t));
for (
std::list<double>::iterator it=frameTimeStampList_.begin();
it!=frameTimeStampList_.end();
it++
)
{
double ts = *it;
file_.write((char*) &ts, sizeof(double));
}
// End write index -> frame -> timestamp
// --------------------------------------------------------------------
// End write index -> frame
// --------------------------------------------------------------------
// Write index -> keyframe
// --------------------------------------------------------------------
// Write key length and key for keyframe
const char keyFrameString[] = "keyframe";
uint16_t keyFrameStringLength = uint16_t(sizeof(keyFrameString)-1);
file_.write((char*) &keyFrameStringLength, sizeof(uint16_t));
file_.write((char*) keyFrameString, keyFrameStringLength*sizeof(char));
// Write char for dict and number of keys
file_.write((char*) &CHAR_FOR_DICT, sizeof(char));
numKeys = 1;
file_.write((char*) &numKeys, sizeof(uint8_t));
// Write index -> keyframe -> mean
// --------------------------------------------------------------------
// Write length of key and key for mean
const char meanString[] = "mean";
uint16_t meanStringLength = uint16_t(sizeof(meanString)-1);
file_.write((char*) &meanStringLength, sizeof(uint16_t));
file_.write((char*) meanString, meanStringLength*sizeof(char));
// Write char for dict and number of keys
file_.write((char*) &CHAR_FOR_DICT, sizeof(char));
numKeys = 2;
file_.write((char*) &numKeys, sizeof(uint8_t));
// Write index -> keyframe -> mean -> loc
// --------------------------------------------------------------------
// Write key length and key for location
file_.write((char*) &locStringLength, sizeof(uint16_t));
file_.write((char*) locString, locStringLength*sizeof(char));
// Write char for array and data type
file_.write((char*) &CHAR_FOR_ARRAY, sizeof(char));
file_.write((char*) &CHAR_FOR_DTYPE_UINT64, sizeof(char));
// Write number of bytes and keyframe positions
numBytes = uint32_t(bgKeyFramePosList_.size()*sizeof(uint64_t));
file_.write((char*) &numBytes, sizeof(uint32_t));
for (
std::list<std::streampos>::iterator it = bgKeyFramePosList_.begin();
it != bgKeyFramePosList_.end();
it++
)
{
uint64_t pos = *it;
file_.write((char*) &pos, sizeof(uint64_t));
}
// End write index -> keyframe -> mean -> loc
// --------------------------------------------------------------------
// Write index -> keyframe -> mean -> timestamp
// --------------------------------------------------------------------
// write key length and key for time stamp
file_.write((char*) &timeStampStringLength, sizeof(uint16_t));
file_.write((char*) timeStampString, timeStampStringLength*sizeof(char));
// Write char for array and data type
file_.write((char*) &CHAR_FOR_ARRAY, sizeof(char));
file_.write((char*) &CHAR_FOR_DTYPE_DOUBLE, sizeof(char));
// Write number of bytes and keyframe time stamps
numBytes = uint32_t(bgKeyFrameTimeStampList_.size()*sizeof(double));
file_.write((char*) &numBytes, sizeof(uint32_t));
for (
std::list<double>::iterator it = bgKeyFrameTimeStampList_.begin();
it != bgKeyFrameTimeStampList_.end();
it++
)
{
double ts = *it;
file_.write((char*) &ts, sizeof(double));
}
// End write index -> keyframe -> mean -> timestamp
// --------------------------------------------------------------------
// End write index -> keyframe -> mean
// --------------------------------------------------------------------
// End write index -> keyframe
// --------------------------------------------------------------------
// End index
// --------------------------------------------------------------------
// Write the index location
file_.seekp(indexLocationPtr_, std::ios_base::beg);
uint64_t indexLocation_uint64 = uint64_t(indexLocation_);
file_.write((char*) &indexLocation_uint64, sizeof(uint64_t));
// Close the file
file_.close();
}
void VideoWriter_ufmf::writeCompressedFrame(CompressedFrame_ufmf frame)
{
if (!frame.isReady()) { return; }
// Get position and time stamp for index
double timeStamp = frame.getTimeStamp();
std::streampos filePosBegin = file_.tellp();
framePosList_.push_back(filePosBegin);
frameTimeStampList_.push_back(timeStamp);
// Write keyframe chunk identifier
uint8_t chunkId = uint8_t(FRAME_CHUNK_ID);
file_.write((char*) &chunkId, sizeof(uint8_t));
// Write time stamp
file_.write((char*) &timeStamp, sizeof(double));
// Write number of connected components
uint32_t numConnectedComp = uint32_t(frame.getNumConnectedComp());
file_.write((char*) &numConnectedComp, sizeof(uint32_t));
// Write each box
std::shared_ptr<std::vector<uint16_t>> writeColBufPtr;
std::shared_ptr<std::vector<uint16_t>> writeRowBufPtr;
std::shared_ptr<std::vector<uint16_t>> writeWdtBufPtr;
std::shared_ptr<std::vector<uint16_t>> writeHgtBufPtr;
std::shared_ptr<std::vector<uint8_t>> imageDataPtr;
writeColBufPtr = frame.getWriteColBufPtr();
writeRowBufPtr = frame.getWriteRowBufPtr();
writeWdtBufPtr = frame.getWriteWdtBufPtr();
writeHgtBufPtr = frame.getWriteHgtBufPtr();
imageDataPtr = frame.getImageDataPtr();
unsigned int dataPos = 0;
for (unsigned int cc=0; cc<numConnectedComp; cc++)
{
uint16_t col = (*writeColBufPtr)[cc];
uint16_t row = (*writeRowBufPtr)[cc];
uint16_t wdt = (*writeWdtBufPtr)[cc];
uint16_t hgt = (*writeHgtBufPtr)[cc];
unsigned int boxArea = (*writeHgtBufPtr)[cc]*(*writeWdtBufPtr)[cc];
file_.write((char*) &col, sizeof(uint16_t));
file_.write((char*) &row, sizeof(uint16_t));
file_.write((char*) &wdt, sizeof(uint16_t));
file_.write((char*) &hgt, sizeof(uint16_t));
file_.write((char*) &(*imageDataPtr)[dataPos], boxArea*sizeof(uint8_t));
dataPos += boxArea;
}
// Calculate frame size
std::streampos filePosEnd = file_.tellp();
unsigned long frameSize = (unsigned long)(filePosEnd) - (unsigned long)(filePosBegin);
}
void VideoWriter_ufmf::writeKeyFrame()
{
// Get position and time stamp for index
bgKeyFramePosList_.push_back(file_.tellp());
bgKeyFrameTimeStampList_.push_back(bgModelTimeStamp_);
// Write keyframe chunk identifier
uint8_t chunkId = uint8_t(KEYFRAME_CHUNK_ID);
file_.write((char*) &chunkId, sizeof(uint8_t));
// Write keyframe type
const char keyFrameType[] = "mean";
uint8_t keyFrameTypeLength = sizeof(keyFrameType)-1;
file_.write((char*) &keyFrameTypeLength, sizeof(uint8_t));
file_.write((char*) keyFrameType, keyFrameTypeLength*sizeof(char));
// Discrepancy ... what about number of points/boxes
// Write char specifying data type
file_.write((char*) &CHAR_FOR_DTYPE_UINT8, sizeof(char));
// Write width and height
uint16_t width = uint16_t(bgMedianImage_.cols);
file_.write((char*) &width, sizeof(uint16_t));
uint16_t height = uint16_t(bgMedianImage_.rows);
file_.write((char*) &height, sizeof(uint16_t));
// Write timestamp
file_.write((char*) &bgModelTimeStamp_, sizeof(double));
// Write the frame data
unsigned int numPixel = bgMedianImage_.rows*bgMedianImage_.cols;
file_.write((char*) bgMedianImage_.data, numPixel*sizeof(char));
}
void VideoWriter_ufmf::startBackgroundModeling()
{
bgImageQueuePtr_ -> clear();
bgNewDataQueuePtr_ -> clear();
bgOldDataQueuePtr_ -> clear();
medianMatQueuePtr_ -> clear();
bgHistogramPtr_ = new BackgroundHistogram_ufmf(
bgImageQueuePtr_,
bgNewDataQueuePtr_,
bgOldDataQueuePtr_,
cameraNumber_
);
bgHistogramPtr_ -> setMedianUpdateCount(medianUpdateCount_);
bgHistogramPtr_ -> setMedianUpdateInterval(medianUpdateInterval_);
bgMedianPtr_ = new BackgroundMedian_ufmf(
bgNewDataQueuePtr_,
bgOldDataQueuePtr_,
medianMatQueuePtr_,
cameraNumber_
);
threadPoolPtr_ -> start(bgHistogramPtr_);
threadPoolPtr_ -> start(bgMedianPtr_);
}
void VideoWriter_ufmf::stopBackgroundModeling()
{
// Signal for background modeling threads to stop
if (!bgMedianPtr_.isNull())
{
bgMedianPtr_ -> acquireLock();
bgMedianPtr_ -> stop();
bgMedianPtr_ -> releaseLock();
bgNewDataQueuePtr_ -> acquireLock();
bgNewDataQueuePtr_ -> signalNotEmpty();
bgNewDataQueuePtr_ -> releaseLock();
}
if (!bgHistogramPtr_.isNull())
{
bgHistogramPtr_ -> acquireLock();
bgHistogramPtr_ -> stop();
bgHistogramPtr_ -> releaseLock();
bgImageQueuePtr_ -> acquireLock();
bgImageQueuePtr_ -> signalNotEmpty();
bgImageQueuePtr_ -> releaseLock();
}
}
void VideoWriter_ufmf::startCompressors()
{
framesToDoQueuePtr_ -> clear();
framesFinishedSetPtr_ -> clear();
// Create compressor threads and start on thread pool
compressorPtrVec_.resize(numberOfCompressors_);
for (unsigned int i=0; i<compressorPtrVec_.size(); i++)
{
compressorPtrVec_[i] = new Compressor_ufmf(
framesToDoQueuePtr_,
framesFinishedSetPtr_,
framesSkippedIndexListPtr_,
cameraNumber_
);
threadPoolPtr_ -> start(compressorPtrVec_[i]);
connect(
compressorPtrVec_[i],
SIGNAL(imageLoggingError(unsigned int, QString)),
this,
SLOT(onCompressorError(unsigned int, QString))
);
}
}
void VideoWriter_ufmf::stopCompressors()
{
// Send all compressor threads a stop signal
for (unsigned int i=0; i<compressorPtrVec_.size(); i++)
{
if (!(compressorPtrVec_[i].isNull()))
{
compressorPtrVec_[i] -> acquireLock();
compressorPtrVec_[i] -> stop();
compressorPtrVec_[i] -> releaseLock();
}
}
// Wait until all compressor threads are null
for (unsigned int i=0; i<compressorPtrVec_.size(); i++)
{
while (!(compressorPtrVec_[i].isNull()))
{
framesToDoQueuePtr_ -> acquireLock();
framesToDoQueuePtr_ -> wakeOne();
framesToDoQueuePtr_ -> releaseLock();
}
}
}
// Private slots
// ----------------------------------------------------------------------------------
void VideoWriter_ufmf::onCompressorError(unsigned int errorId, QString errorMsg)
{
emit imageLoggingError(errorId, errorMsg);
}
} // namespace bias
| 38.975496 | 111 | 0.545536 | [
"vector",
"model"
] |
04266ca3961ab38ed517fa071b0c368f8eac43da | 9,130 | cpp | C++ | src/shader.cpp | jondgoodwin/pegasus3d | b30cf4bcc707b4aca9c32c3fbd5aafc3798d7ec5 | [
"MIT-0",
"MIT"
] | 4 | 2018-01-01T08:57:08.000Z | 2021-12-01T14:36:58.000Z | src/shader.cpp | jondgoodwin/pegasus3d | b30cf4bcc707b4aca9c32c3fbd5aafc3798d7ec5 | [
"MIT-0",
"MIT"
] | null | null | null | src/shader.cpp | jondgoodwin/pegasus3d | b30cf4bcc707b4aca9c32c3fbd5aafc3798d7ec5 | [
"MIT-0",
"MIT"
] | null | null | null | /** Shader compilation and use
* @file
*
* This source file is part of the Pegasus3d browser.
* See Copyright Notice in pegasus3d.h
*/
#include <stdio.h>
#include <stdlib.h>
#include "pegasus3d.h"
#include "xyzmath.h"
/** Structure for holding a ready-to-use shader program.
We do this so that we can depend on a finalizer to delete
a program when it is no longer referenced. */
struct ShaderPgm {
GLuint program; //!< Handle for OpenGL shader program
};
/** Compile a shader program */
GLuint shader_compile(const char *shadersource, GLenum shadertype) {
int IsCompiled;
int maxLength;
char *InfoLog;
// This is the handle used to reference the shader
GLuint shader;
// Create an empty vertex shader handle
shader = glCreateShader(shadertype);
// Send the vertex shader source code to GL
// Note that the source code is NULL character terminated.
// GL will automatically detect that therefore the length info can be 0 in this case (the last parameter)
glShaderSource(shader, 1, (const GLchar**)&shadersource, 0);
// Compile the vertex shader and check for errors
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &IsCompiled);
if(IsCompiled == GL_FALSE)
{
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
InfoLog = (char *)malloc(maxLength);
glGetShaderInfoLog(shader, maxLength, &maxLength, InfoLog);
vmLog("Shader compilation failure: %s", InfoLog);
free(InfoLog);
return 0;
}
return shader;
}
/** Compile and bind shaders into a shader program */
Value shader_make(Value th, Value pgmv) {
int selfidx = 0;
GLuint vshader;
GLuint fshader;
int IsLinked;
int maxLength;
char *shaderProgramInfoLog;
Value vertex = pushProperty(th, selfidx, "vertex"); popValue(th);
vshader = shader_compile(toStr(vertex), GL_VERTEX_SHADER);
Value fragment = pushProperty(th, selfidx, "fragment"); popValue(th);
fshader = shader_compile(toStr(fragment), GL_FRAGMENT_SHADER);
if (vshader==0 || fshader==0)
return aNull;
// Link the shaders together to create a GL shader program
GLuint shaderprogram = glCreateProgram();
glAttachShader(shaderprogram, vshader);
glAttachShader(shaderprogram, fshader);
// Bind "attributes" in listed order.
Value inlist = pushProperty(th, selfidx, "attributes");
if (isArr(inlist)) {
for (AuintIdx i=0; i < getSize(inlist); i++) {
glBindAttribLocation(shaderprogram, i, toStr(arrGet(th, inlist, i)));
}
}
popValue(th);
// Link the program, then upload it to the GPU.
glLinkProgram(shaderprogram);
glDetachShader(shaderprogram, vshader);
glDetachShader(shaderprogram, fshader);
glDeleteShader(vshader);
glDeleteShader(fshader);
// Check for linkage errors, e.g.: a mismatch between the vertex and fragment shaders.
// Also possible: surpassed your GPU's abilities, too many ALU operations,
// too many texel fetch instructions or too many interpolators or dynamic loops.
glGetProgramiv(shaderprogram, GL_LINK_STATUS, (int *)&IsLinked);
if (IsLinked == GL_FALSE)
{
glGetProgramiv(shaderprogram, GL_INFO_LOG_LENGTH, &maxLength);
shaderProgramInfoLog = (char *)malloc(maxLength);
glGetProgramInfoLog(shaderprogram, maxLength, &maxLength, shaderProgramInfoLog);
vmLog("Shader program linkage error: %s", shaderProgramInfoLog);
free(shaderProgramInfoLog);
return aNull;
}
// Remember compiled program, then return as success
ShaderPgm* p = (ShaderPgm*) toHeader(pgmv);
p->program = shaderprogram;
return pgmv;
}
/** Close out a shader that is no longer referenced anywhere */
int shader_closepgm(Value shaderpgm) {
ShaderPgm *pgm = (ShaderPgm*) toHeader(shaderpgm);
glDeleteProgram(pgm->program);
return 1;
}
/** Create a new shader */
int shader_new(Value th) {
pushType(th, getLocal(th, 0), 16); // Create prototype of self (Shader)
return 1;
}
/** Render the shader, retrieving uniforms from context as parameter 1 */
int shader_render(Value th) {
int selfidx = 0;
int contextidx = 1;
int shapeidx = 2;
// Get compiled shader, if it exists
Value pgmv = pushProperty(th, selfidx, "_program");
if (pgmv==aNull) {
// If it does not exist, compile and bind it based on info
Value pgmtype = pushProperty(th, selfidx, "_compiledtype");
pgmv = strHasFinalizer(pushCData(th, pgmtype, ShaderValue, 0, sizeof(ShaderPgm))); // Is small enough to stick in header
if (aNull != (pgmv = shader_make(th, pgmv)))
popProperty(th, selfidx, "_program");
else
popValue(th);
}
/* Load the shader into the rendering pipeline */
if (pgmv != aNull) {
ShaderPgm *pgmdata = (ShaderPgm*) toHeader(pgmv);
glUseProgram(pgmdata->program);
// Calculate mvpmatrix = pmatrix * (mvmatrix = vmatrix * mmatrix)
Mat4 *mmatrix = (Mat4*) toHeader(pushProperty(th, shapeidx, "mmatrix")); popValue(th);
Mat4 *vmatrix = (Mat4*) toHeader(pushProperty(th, contextidx, "vmatrix")); popValue(th);
Mat4 *pmatrix = (Mat4*) toHeader(pushProperty(th, contextidx, "pmatrix")); popValue(th);
Mat4 mvpmatrix, mvmatrix;
mat4Mult(&mvmatrix, vmatrix, mmatrix);
mat4Mult(&mvpmatrix, pmatrix, &mvmatrix);
// Load all the shader's named "uniform" values from the shape or context
Value uniformlist = pushProperty(th, selfidx, "uniforms"); popValue(th);
if (isArr(uniformlist)) {
for (AuintIdx i=0; i < getSize(uniformlist); i++) {
Value uninamev = arrGet(th, uniformlist, i);
if (!isSym(uninamev)) continue;
// Is the uniform a matrix we just calculated?
const char *uninamestr = toStr(uninamev);
if (0==strcmp("mvpmatrix", uninamestr)) {
glUniformMatrix4fv(glGetUniformLocation(pgmdata->program, uninamestr), 1, GL_FALSE, (GLfloat *)&mvpmatrix);
continue;
}
else if (0==strcmp("mvmatrix", uninamestr)) {
glUniformMatrix4fv(glGetUniformLocation(pgmdata->program, uninamestr), 1, GL_FALSE, (GLfloat *)&mvmatrix);
continue;
}
else if (0==strcmp("mmatrix", uninamestr)) {
glUniformMatrix4fv(glGetUniformLocation(pgmdata->program, uninamestr), 1, GL_FALSE, (GLfloat *)mmatrix);
continue;
}
// Get and process a uniform value from the shape or render context
Value unival;
if (0==strcmp("cameraOrigin", uninamestr)) {
unival = pushProperty(th, contextidx, "origin"); popValue(th);
}
else {
unival = getProperty(th, getLocal(th, shapeidx), uninamev);
if (unival == aNull)
unival = getProperty(th, getLocal(th, contextidx), uninamev);
}
if (isFloat(unival))
glUniform1f(glGetUniformLocation(pgmdata->program, uninamestr), toAfloat(unival));
else if (isInt(unival))
glUniform1i(glGetUniformLocation(pgmdata->program, uninamestr), toAint(unival));
else if (isCData(unival)) {
switch(getCDataType(unival)) {
case Mat2Value: glUniformMatrix2fv(glGetUniformLocation(pgmdata->program, uninamestr), 1, GL_FALSE, (GLfloat *) toHeader(unival)); break;
case Mat3Value: glUniformMatrix3fv(glGetUniformLocation(pgmdata->program, uninamestr), 1, GL_FALSE, (GLfloat *) toHeader(unival)); break;
case Mat4Value:
glUniformMatrix4fv(glGetUniformLocation(pgmdata->program, uninamestr), 1, GL_FALSE, (GLfloat *) toHeader(unival)); break;
//case PegUint32: glUniform1iv(glGetUniformLocation(pgmdata->program, uninamestr), univalhdr->nStructs, (GLint *) toCData(unival)); break;
case FloatNbr: glUniform1fv(glGetUniformLocation(pgmdata->program, uninamestr), 1, (GLfloat *) toCData(unival)); break;
case Vec2Value: glUniform2fv(glGetUniformLocation(pgmdata->program, uninamestr), 1, (GLfloat *) toHeader(unival)); break;
case XyzValue: glUniform3fv(glGetUniformLocation(pgmdata->program, uninamestr), 1, (GLfloat *) toHeader(unival)); break;
case ColorValue: case QuatValue:
glUniform4fv(glGetUniformLocation(pgmdata->program, uninamestr), 1, (GLfloat *) toHeader(unival)); break;
default:
//const char *x = toStr(uninamev);
assert(false && "Unsupported uniform type!!!");
}
} else if (isType(unival)) {
pushSym(th, "name");
Value name = getProperty(th, unival, getFromTop(th, 0));
popValue(th);
// If it is a texture, render it to get its texture unit value
if (isEqStr(name, "Texture")) {
pushSym(th, "_Render");
pushValue(th, unival);
pushLocal(th, contextidx);
getCall(th, 2, 1);
glUniform1i(glGetUniformLocation(pgmdata->program, uninamestr), toAint(popValue(th)));
}
}
}
}
}
else
glUseProgram(0);
return 0;
}
/** Initialize shader type */
void shader_init(Value th) {
Value Shader = pushType(th, aNull, 16);
pushSym(th, "Shader");
popProperty(th, 0, "_name");
pushCMethod(th, shader_new);
popProperty(th, 0, "New");
pushCMethod(th, shader_render);
popProperty(th, 0, "_Render");
Value pgmmmixin = pushMixin(th, aNull, aNull, 4);
pushSym(th, "*Shader");
popProperty(th, 1, "_name");
pushCMethod(th, shader_closepgm);
popProperty(th, 1, "_finalizer");
popProperty(th, 0, "_compiledtype");
popGloVar(th, "Shader");
} | 37.418033 | 143 | 0.697152 | [
"render",
"shape"
] |
54b685ceb36ffb164286027b2ed7c3316934ce0a | 2,143 | hpp | C++ | solid/frame/aio/aioactor.hpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 26 | 2015-08-25T16:07:58.000Z | 2019-07-05T15:21:22.000Z | solid/frame/aio/aioactor.hpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 5 | 2016-10-15T22:55:15.000Z | 2017-09-19T12:41:10.000Z | solid/frame/aio/aioactor.hpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 5 | 2016-09-15T10:34:52.000Z | 2018-10-30T11:46:46.000Z | // solid/frame/aio/aioactor.hpp
//
// Copyright (c) 2014 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.
//
#pragma once
#include "solid/utility/event.hpp"
#include "solid/frame/actorbase.hpp"
#include "solid/frame/aio/aiocommon.hpp"
#include "solid/frame/aio/aioforwardcompletion.hpp"
#include "solid/frame/aio/aioreactor.hpp"
#include "solid/frame/aio/aioreactorcontext.hpp"
namespace solid {
namespace frame {
namespace aio {
class CompletionHandler;
class Actor;
struct ActorProxy {
Actor& actor() const
{
return ract_;
}
private:
friend class Actor;
ActorProxy(Actor& _ract)
: ract_(_ract)
{
}
ActorProxy(ActorProxy const& _rd)
: ract_(_rd.ract_)
{
}
ActorProxy& operator=(ActorProxy const& _rd);
private:
Actor& ract_;
};
class Actor : public ActorBase, ForwardCompletionHandler {
protected:
friend class CompletionHandler;
friend class Reactor;
Actor() = default;
ActorProxy proxy()
{
return ActorProxy(*this);
}
bool registerCompletionHandler(CompletionHandler& _rch);
void registerCompletionHandlers();
bool isRunning() const;
void postStop(ReactorContext& _rctx)
{
if (doPrepareStop(_rctx)) {
_rctx.reactor().postActorStop(_rctx);
}
}
template <class F>
void postStop(ReactorContext& _rctx, F&& _f, Event&& _uevent = Event())
{
if (doPrepareStop(_rctx)) {
_rctx.reactor().postActorStop(_rctx, std::forward<F>(_f), std::move(_uevent));
}
}
template <class F>
void post(ReactorContext& _rctx, F&& _f, Event&& _uevent = Event())
{
_rctx.reactor().post(_rctx, std::forward<F>(_f), std::move(_uevent));
}
private:
virtual void onEvent(ReactorContext& _rctx, Event&& _uevent);
bool doPrepareStop(ReactorContext& _rctx);
};
} //namespace aio
} //namespace frame
} //namespace solid
| 21.646465 | 90 | 0.65749 | [
"solid"
] |
54bbb51d3732d7b0d562079c6c8181c46379e792 | 1,181 | hpp | C++ | tests/models/models/role.hpp | MrAhmedSayedAli/TinyORM | f185e76cfa955475df9b807c3e7ecaa4c20989c0 | [
"MIT"
] | 4 | 2021-07-07T01:21:34.000Z | 2022-02-01T01:38:24.000Z | tests/models/models/role.hpp | MrAhmedSayedAli/TinyORM | f185e76cfa955475df9b807c3e7ecaa4c20989c0 | [
"MIT"
] | 2 | 2022-03-04T10:57:15.000Z | 2022-03-26T17:10:28.000Z | tests/models/models/role.hpp | MrAhmedSayedAli/TinyORM | f185e76cfa955475df9b807c3e7ecaa4c20989c0 | [
"MIT"
] | 2 | 2021-08-10T01:31:31.000Z | 2022-03-04T10:37:42.000Z | #pragma once
#ifndef MODELS_ROLE_HPP
#define MODELS_ROLE_HPP
#include "orm/tiny/model.hpp"
#include "models/roleuser.hpp"
#include "models/user.hpp"
namespace Models
{
using Orm::Constants::NAME;
using Orm::Tiny::Model;
using Orm::Tiny::Relations::BelongsToMany;
class User;
// NOLINTNEXTLINE(misc-no-recursion)
class Role final : public Model<Role, User, RoleUser>
{
friend Model;
using Model::Model;
public:
/*! Get users that belong to the role. */
std::unique_ptr<BelongsToMany<Role, User>>
users()
{
// Ownership of a unique_ptr()
auto relation = belongsToMany<User>();
relation->withPivot("active");
return relation;
}
private:
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations {
{"users", [](auto &v) { v(&Role::users); }},
};
/*! The attributes that are mass assignable. */
inline static const QStringList u_fillable { // NOLINT(cppcoreguidelines-interfaces-global-init)
NAME,
};
/*! Indicates whether the model should be timestamped. */
bool u_timestamps = false;
};
} // namespace Models
#endif // MODELS_ROLE_HPP
| 21.089286 | 100 | 0.660457 | [
"model"
] |
54c26aa604b7144429f02d1fe2c3e24e5fc8d511 | 3,619 | hpp | C++ | test/SurveySystemTest.hpp | CBcidco/MBES-lib | 6b7759554db48c62d6b350d315283eb3fe0fd009 | [
"MIT"
] | 13 | 2019-10-29T14:16:13.000Z | 2022-02-24T06:44:37.000Z | test/SurveySystemTest.hpp | CBcidco/MBES-lib | 6b7759554db48c62d6b350d315283eb3fe0fd009 | [
"MIT"
] | 62 | 2019-04-16T13:53:50.000Z | 2022-03-07T19:44:23.000Z | test/SurveySystemTest.hpp | CBcidco/MBES-lib | 6b7759554db48c62d6b350d315283eb3fe0fd009 | [
"MIT"
] | 18 | 2019-04-10T19:51:21.000Z | 2022-01-31T21:42:22.000Z | /*
* Copyright 2017 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés
*/
/*
* File: SurveySystemTest.cpp
* Author: glm,jordan
*
*/
#include <Eigen/Dense>
#include <Eigen/src/Core/Matrix.h>
#include "catch.hpp"
#include "../src/SurveySystem.hpp"
#include "../src/utils/Exception.hpp"
#include <cmath>
TEST_CASE("Reading metadata from original MSPAC") {
SurveySystem params;
REQUIRE(params.readFile("test/data/metadata/TestMetaData.txt"));
/*
MultibeamModel R2Sonic2022
AntPositionOffsetX 1.31
AntPositionOffsetY 1.45
AntPositionOffsetZ 4.32
MBEOffsetX 0.765
MBEOffsetY 0.685
MBEOffsetZ 1.359
MBEDraft 0.70
MBEOffset2X 0.364
MBEOffset2Y 0.687
MBEOffset2Z 1.093
PitchRollAccuracy 0.050
HeadingAccuracy 0.050
HeaveAccuracy 0.050
PositionAccuracy 0.010
PitchAlignment 1.64
RollAlignment 0.62
HeadingAlignment 1.88
*/
//Test draft
/*
MBEDraft 0.70
*/
double draft = 0.7;
double draftPrecision = 0.000000001;
REQUIRE(std::abs(params.getDraft() - draft) < draftPrecision);
//Test model name
/*
MultibeamModel R2Sonic2022
*/
std::string testModelName = "R2Sonic2022";
REQUIRE(params.getMBES_model().compare(testModelName) == 0);
//Test antenna position
/*
AntPositionOffsetX 1.31
AntPositionOffsetY 1.45
AntPositionOffsetZ 4.32
*/
double antennaPrecision = 0.000000001;
Eigen::Vector3d testAntennatPosition(1.31, 1.45, -4.32);
Eigen::Vector3d testAntenna = params.getAntennaPosition().array() - testAntennatPosition.array();
REQUIRE(testAntenna.cwiseAbs().maxCoeff() < antennaPrecision);
//Test echosounder transmitter position
/*
MBEOffsetX 0.765
MBEOffsetY 0.685
MBEOffsetZ 1.359
*/
double transmitterPrecision = 0.000000001;
Eigen::Vector3d testTransmitterPosition(0.765, 0.685, -1.359);
Eigen::Vector3d testTransmitter = params.getEchosounderTransmitterPosition().array() - testTransmitterPosition.array();
REQUIRE(testTransmitter.cwiseAbs().maxCoeff() < transmitterPrecision);
//Test echosounder transmitter position
/*
MBEOffset2X 0.364
MBEOffset2Y 0.687
MBEOffset2Z 1.093
*/
double receiverPrecision = 0.000000001;
Eigen::Vector3d testReceiverPosition;
testReceiverPosition << 0.364, 0.687, -1.093;
Eigen::Vector3d testReceiver = params.getEchosounderReceivererPosition().array() - testReceiverPosition.array();
REQUIRE(testReceiver.cwiseAbs().maxCoeff() < receiverPrecision);
//Test echosounder transmitter position
/*
PitchRollAccuracy 0.050
HeadingAccuracy 0.050
*/
double attitudeAccuracyPrecision = 0.000000001;
double testPitchRollAccuracy = 0.050*D2R;
Attitude* acc = params.getAttitudeAccuracy();
REQUIRE(abs(acc->getRoll()*D2R-testPitchRollAccuracy) < attitudeAccuracyPrecision);
REQUIRE(abs(acc->getPitch()*D2R-testPitchRollAccuracy) < attitudeAccuracyPrecision);
}
TEST_CASE("Reading non-existing file") {
SurveySystem params;
REQUIRE(!params.readFile("/non/existant/file"));
}
//TODO: test case with a few invalid values
| 31.469565 | 123 | 0.629179 | [
"model"
] |
54c28b729b7e69869111ac265aa3acb26d133bab | 28,669 | cpp | C++ | applications/plugins/Compliant/odesolver/CompliantImplicitSolver.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | applications/plugins/Compliant/odesolver/CompliantImplicitSolver.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | applications/plugins/Compliant/odesolver/CompliantImplicitSolver.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | #include "CompliantImplicitSolver.h"
#include <SofaEigen2Solver/EigenSparseMatrix.h>
#include <sofa/core/ObjectFactory.h>
#include "../assembly/AssemblyVisitor.h"
#include "../utils/scoped.h"
namespace sofa {
namespace component {
namespace odesolver {
SOFA_DECL_CLASS(CompliantImplicitSolver)
int CompliantImplicitSolverClass = core::RegisterObject("Newmark-beta implicit solver for constrained dynamics using assembly")
.add< CompliantImplicitSolver >()
.addAlias("AssembledSolver"); // deprecated, for backward compatibility only
using namespace sofa::defaulttype;
using namespace sofa::helper;
using namespace core::behavior;
CompliantImplicitSolver::CompliantImplicitSolver()
: stabilization(initData(&stabilization,
"stabilization",
"apply a stabilization pass on kinematic constraints requesting it")),
warm_start(initData(&warm_start,
true,
"warm_start",
"warm start iterative solvers: avoids biasing solution towards zero (and speeds-up resolution)")),
debug(initData(&debug,
false,
"debug",
"print debug stuff")),
constraint_forces(initData(&constraint_forces,
"constraint_forces",
"add constraint forces to mstate's 'force' vector at compliance levels at the end of the time step. (0->do nothing, 1->add to existing forces, 2->clear existing forces, 3-> clear existing forces and propagate constraint forces toward independent dofs) ")),
alpha( initData(&alpha,
SReal(1),
"implicitVelocity",
"Weight of the next forces in the average forces used to update the velocities. 1 is implicit, 0 is explicit.")),
beta( initData(&beta,
SReal(1),
"implicitPosition",
"Weight of the next velocities in the average velocities used to update the positions. 1 is implicit, 0 is explicit.")),
stabilization_damping(initData(&stabilization_damping,
SReal(1e-7),
"stabilization_damping",
"stabilization damping hint to relax infeasible problems"))
, formulation(initData(&formulation,
"formulation",
"solve dynamics on velocity (vel) or velocity variation (dv) or acceleration (acc)"))
, neglecting_compliance_forces_in_geometric_stiffness(initData(&neglecting_compliance_forces_in_geometric_stiffness,
true,
"neglecting_compliance_forces_in_geometric_stiffness",
"isn't the name clear enough?"))
{
storeDSol = false;
assemblyVisitor = NULL;
helper::OptionsGroup stabilizationOptions;
stabilizationOptions.setNbItems( NB_STABILIZATION );
stabilizationOptions.setItemName( NO_STABILIZATION, "no stabilization" );
stabilizationOptions.setItemName( PRE_STABILIZATION, "pre-stabilization" );
stabilizationOptions.setItemName( POST_STABILIZATION_RHS, "post-stabilization rhs" );
stabilizationOptions.setItemName( POST_STABILIZATION_ASSEMBLY, "post-stabilization assembly" );
stabilizationOptions.setSelectedItem( PRE_STABILIZATION );
stabilization.setValue( stabilizationOptions );
helper::OptionsGroup formulationOptions;
formulationOptions.setNbItems( NB_FORMULATION );
formulationOptions.setItemName( FORMULATION_VEL, "vel" );
formulationOptions.setItemName( FORMULATION_DV, "dv" );
formulationOptions.setItemName( FORMULATION_ACC, "acc" );
formulationOptions.setSelectedItem( FORMULATION_VEL );
formulation.setValue( formulationOptions );
helper::OptionsGroup constraint_forcesOptions;
constraint_forcesOptions.setNbItems( 4 );
constraint_forcesOptions.setItemName( 0, "no" );
constraint_forcesOptions.setItemName( 1, "add" );
constraint_forcesOptions.setItemName( 2, "clear" );
constraint_forcesOptions.setItemName( 3, "propagate" );
constraint_forcesOptions.setSelectedItem( 0 );
constraint_forces.setValue( constraint_forcesOptions );
}
void CompliantImplicitSolver::send(simulation::Visitor& vis, bool precomputedTraversalOrder) {
// scoped::timer step("visitor execution");
this->getContext()->executeVisitor( &vis, precomputedTraversalOrder );
}
void CompliantImplicitSolver::storeDynamicsSolution(bool b) { storeDSol = b; }
void CompliantImplicitSolver::integrate( SolverOperations& sop,
const core::MultiVecCoordId& posId,
const core::MultiVecDerivId& velId ) {
scoped::timer step("position integration");
const SReal& dt = sop.mparams().dt();
sop.vop.v_op( posId, posId, velId, beta.getValue() * dt );
}
void CompliantImplicitSolver::integrate( SolverOperations& sop,
const core::MultiVecCoordId& posId,
const core::MultiVecDerivId& velId,
const core::MultiVecDerivId& accId,
const SReal& accFactor ) {
scoped::timer step("position integration");
const SReal& dt = sop.mparams().dt();
core::behavior::BaseMechanicalState::VMultiOp multi;
multi.resize(2);
const SReal& beta = this->beta.getValue();
multi[0].first = velId;
multi[0].second.push_back( std::make_pair(velId, 1.0) );
multi[0].second.push_back( std::make_pair(accId, accFactor) );
multi[1].first = posId;
multi[1].second.push_back( std::make_pair(posId, 1.0) );
multi[1].second.push_back( std::make_pair(velId, dt*beta) );
sop.vop.v_multiop( multi );
}
CompliantImplicitSolver::~CompliantImplicitSolver() {
if( assemblyVisitor ) delete assemblyVisitor;
}
void CompliantImplicitSolver::reset() {
if( !lagrange.id().isNull() )
{
// warning, vop.v_clear would only clear independent dofs
simulation::MechanicalVOpVisitor clearVisitor(core::ExecParams::defaultInstance(), lagrange.id(), core::ConstMultiVecId::null(), core::ConstMultiVecId::null(), 1.0);
clearVisitor.only_mapped = true;
send( clearVisitor, false );
}
}
void CompliantImplicitSolver::cleanup() {
sofa::simulation::common::VectorOperations vop( core::ExecParams::defaultInstance(), this->getContext() );
vop.v_free( lagrange.id(), false, true );
vop.v_free( _ck.id(), false, true );
vop.v_free( _acc.id() );
}
void CompliantImplicitSolver::compute_forces(SolverOperations& sop,
core::behavior::MultiVecDeriv& f,
core::behavior::MultiVecDeriv* f_k)
{
scoped::timer step("compute_forces");
const SReal factor = ( (formulation.getValue().getSelectedId()==FORMULATION_ACC) ? 1.0 : sop.mparams().dt() );
{
scoped::timer substep("forces computation");
sop.mop.computeForce( f ); // f = fk
}
if( f_k )
{
scoped::timer substep("f_k = fk");
f_k->eq( f, factor );
}
if( sys.n && !neglecting_compliance_forces_in_geometric_stiffness.getValue() )
{
scoped::timer substep("f += fc");
// using lambdas computed at the previous time step as an approximation of the forces generated by compliances
// at the current configuration (due to non-linearities, after integration of the previous time-step,
// elastic forces are too large leading to locking)
// If no lambdas are known (e.g. first time-step, newly created constraint, contact w/o history...),
// 0 is used and the associated compliance won't contribute to geometric stiffness generation for this step,
// like regular constraints.
simulation::MechanicalAddComplianceForce lvis( &sop.mparams(), f, lagrange, factor ); // f += fc with fc = lambda / dt
send( lvis );
}
// computing mapping geometric stiffnesses based on child force stored in f
simulation::MechanicalComputeGeometricStiffness gsvis( &sop.mparams(), f );
send( gsvis );
}
void CompliantImplicitSolver::propagate(const core::MechanicalParams* params)
{
simulation::MechanicalPropagatePositionAndVelocityVisitor bob( params );
send( bob );
}
void CompliantImplicitSolver::filter_constraints( const core::MultiVecCoordId& posId) const {
// compliant dofs
for(unsigned i = 0, end = sys.compliant.size(); i < end; ++i) {
system_type::dofs_type* dofs = sys.compliant[i];
const system_type::constraint_type& constraint = sys.constraints[i];
if( !constraint.projector ) continue; // if bilateral nothing to filter
const unsigned dim = dofs->getSize(); // nb lines per constraint
const unsigned constraint_dim = dofs->getDerivDimension(); // nb lines per constraint
constraint.value->filterConstraints( const_cast<system_type::constraint_type*>(&constraint)->projector->mask, posId, dim, constraint_dim );
}
}
void CompliantImplicitSolver::clear_constraints() const {
// compliant dofs
for(unsigned i = 0, end = sys.compliant.size(); i < end; ++i) {
const system_type::constraint_type& constraint = sys.constraints[i];
if( !constraint.projector ) continue; // if bilateral nothing to filter
constraint.projector->mask = NULL;
constraint.value->clear();
}
}
void CompliantImplicitSolver::rhs_dynamics(SolverOperations& sop,
vec& res, const system_type& sys,
MultiVecDeriv& f_k,
core::MultiVecCoordId posId,
core::MultiVecDerivId velId ) const {
assert( res.size() == sys.size() );
SReal m_factor, b_factor, k_factor;
const SReal& h = sys.dt;
SReal alpha = this->alpha.getValue();
switch( formulation.getValue().getSelectedId() )
{
case FORMULATION_DV: // c_k = h.f_k + h²Kv + hDv
m_factor = 0.0;
b_factor = h;
k_factor = h*h*alpha;
break;
case FORMULATION_ACC: // c_k = f_k + hKv + Dv
m_factor = 0.0;
b_factor = 1.0;
k_factor = h*alpha;
break;
case FORMULATION_VEL: // c_k = h.f_k + Mv
default:
// M v_k
m_factor = 1;
// h (1-alpha) B v_k
b_factor = h * (1 - alpha);
// h^2 alpha (1 - beta ) K v_k
k_factor = h * h * alpha * (1 - beta.getValue());
break;
}
{
scoped::timer substep("c_k+=MBKv");
// note: K v_k factor only for stiffness dofs
sop.mop.addMBKv( f_k, m_factor, b_factor, k_factor );
}
unsigned off = 0;
// master dofs: fetch what has been computed during compute_forces
for(unsigned i = 0, end = sys.master.size(); i < end; ++i) {
system_type::dofs_type* dofs = sys.master[i];
unsigned dim = dofs->getMatrixSize();
dofs->copyToBuffer(&res(off), f_k.id().getId(dofs), dim);
off += dim;
}
// Applying the projection here (in flat vector representation) is great.
// In compute_forces (in multivec representation) it would require a visitor (more expensive).
res.head( sys.m ) = sys.P * res.head( sys.m );
vec res_constraint(sys.n); // todo remove this temporary
rhs_constraints_dynamics( res_constraint, sys, posId, velId );
res.tail(sys.n).noalias() = res_constraint;
}
void CompliantImplicitSolver::rhs_constraints_dynamics(vec& res, const system_type& sys,
core::MultiVecCoordId posId,
core::MultiVecDerivId velId ) const {
assert( res.size() == sys.n );
if( !sys.n ) return;
unsigned off = 0;
unsigned stabilization = this->stabilization.getValue().getSelectedId();
unsigned formulation = this->formulation.getValue().getSelectedId();
SReal alpha = this->alpha.getValue();
SReal beta = this->beta.getValue();
// compliant dofs
for(unsigned i = 0, end = sys.compliant.size(); i < end; ++i) {
system_type::dofs_type* dofs = sys.compliant[i];
const system_type::constraint_type& constraint = sys.constraints[i];
const unsigned dim = dofs->getSize(); // nb constraints
const unsigned constraint_dim = dofs->getDerivDimension(); // nb lines per constraint
const unsigned total_dim = dim*constraint_dim; // nb constraint lines
assert( constraint.value ); // at least a fallback must be added in filter_constraints
constraint.value->dynamics( &res(off), dim, constraint_dim, stabilization!=NO_STABILIZATION, posId, velId );
// adjust compliant value based on alpha/beta
switch( formulation )
{
case FORMULATION_VEL: // ( phi/a -(1-b)*J.v ) / b
{
if( alpha != 1 ) res.segment(off,total_dim) /= alpha;
if( beta != 1 )
{
// get constraint violation velocity
vec v_constraint( total_dim );
dofs->copyToBuffer( &v_constraint(0), velId.getId(dofs), total_dim );
res.segment(off,total_dim).noalias() -= (1 - beta) * v_constraint;
res.segment(off,total_dim) /= beta;
}
break;
}
case FORMULATION_DV: // ( phi/a -J.v ) / b
{
if( alpha != 1 ) res.segment(off,total_dim) /= alpha;
vec v_constraint( total_dim );
dofs->copyToBuffer( &v_constraint(0), velId.getId(dofs), total_dim );
res.segment(off,total_dim).noalias() -= v_constraint;
if( beta != 1 ) res.segment(off,total_dim) /= beta;
break;
}
case FORMULATION_ACC: // ( phi/a -J.v ) / bh
{
if( alpha != 1 ) res.segment(off,total_dim) /= alpha;
vec v_constraint( total_dim );
dofs->copyToBuffer( &v_constraint(0), velId.getId(dofs), total_dim );
res.segment(off,total_dim).noalias() -= v_constraint;
res.segment(off,total_dim) /= ( beta * sys.dt );
break;
}
}
off += total_dim;
}
assert( off == sys.n );
// // adjust compliant value based on alpha/beta
// if(alpha != 1 ) res.tail( sys.n ) /= alpha;
// if( beta != 1 ) {
// // TODO dofs->copyToBuffer(v_compliant, core::VecDerivId::vel(), dim); rather than sys.J * v, v_compliant is already mapped
// // TODO use v_compliant to implement constraint damping
// res.tail( sys.n ).noalias() -= (1 - beta) * (sys.J * v);
// res.tail( sys.n ) /= beta;
// }
}
void CompliantImplicitSolver::rhs_correction(vec& res, const system_type& sys,
core::MultiVecCoordId posId,
core::MultiVecDerivId velId) const {
assert( res.size() == sys.size() );
// master dofs
res.head( sys.m ).setZero();
unsigned off = sys.m;
// compliant dofs
for(unsigned i = 0, end = sys.compliant.size(); i < end; ++i) {
system_type::dofs_type* dofs = sys.compliant[i];
const system_type::constraint_type& constraint = sys.constraints[i];
const unsigned dim = dofs->getSize(); // nb constraints
const unsigned constraint_dim = dofs->getDerivDimension(); // nb lines per constraint
assert( constraint.value ); // at least a fallback must be added in filter_constraints
constraint.value->correction( &res(off), dim, constraint_dim, posId, velId );
off += dim * constraint_dim;
}
}
void CompliantImplicitSolver::get_state(vec& res, const system_type& sys, const core::MultiVecDerivId& multiVecId) const {
assert( res.size() == sys.size() );
unsigned off = 0;
for(unsigned i = 0, end = sys.master.size(); i < end; ++i) {
system_type::dofs_type* dofs = sys.master[i];
unsigned dim = dofs->getMatrixSize();
dofs->copyToBuffer(&res(off), multiVecId.getId(dofs), dim);
off += dim;
}
for(unsigned i = 0, end = sys.compliant.size(); i < end; ++i) {
system_type::dofs_type* dofs = sys.compliant[i];
unsigned dim = dofs->getMatrixSize();
dofs->copyToBuffer(&res(off), lagrange.id().getId( dofs ), dim);
off += dim;
}
assert( off == sys.size() );
}
void CompliantImplicitSolver::set_state_v(const system_type& sys, const vec& data, const core::MultiVecDerivId& velId) const {
assert( data.size() == sys.size() );
unsigned off = 0;
// TODO project v ?
for(unsigned i = 0, end = sys.master.size(); i < end; ++i) {
system_type::dofs_type* dofs = sys.master[i];
unsigned dim = dofs->getMatrixSize();
dofs->copyFromBuffer(velId.getId(dofs), &data(off), dim);
off += dim;
}
}
void CompliantImplicitSolver::set_state_lambda(const system_type& sys, const vec& data) const {
// we directly store lambda (and not constraint *force*)
unsigned off = 0;
for(unsigned i = 0, end = sys.compliant.size(); i < end; ++i) {
system_type::dofs_type* dofs = sys.compliant[i];
unsigned dim = dofs->getMatrixSize();
dofs->copyFromBuffer(lagrange.id().getId( dofs ), &data(off), dim);
off += dim;
}
}
void CompliantImplicitSolver::set_state(const system_type& sys, const vec& data, const core::MultiVecDerivId& velId) const {
set_state_v( sys, data, velId );
set_state_lambda( sys, data.tail(sys.n) );
}
void CompliantImplicitSolver::perform_assembly( const core::MechanicalParams *mparams, system_type& sys )
{
scoped::timer step("perform_assembly");
// max: il ya des smart ptr pour ca.
if( assemblyVisitor ) delete assemblyVisitor;
assemblyVisitor = new simulation::AssemblyVisitor(mparams);
// fetch nodes/data
{
scoped::timer step("assembly: fetch data");
send( *assemblyVisitor );
}
// assemble system
assemblyVisitor->assemble(sys);
}
void CompliantImplicitSolver::solve(const core::ExecParams* params,
SReal dt,
core::MultiVecCoordId posId,
core::MultiVecDerivId velId) {
static_cast<simulation::Node*>(getContext())->precomputeTraversalOrder( params );
assert(kkt);
bool useVelocity = (formulation.getValue().getSelectedId()==FORMULATION_VEL);
SolverOperations sop( params, this->getContext(), alpha.getValue(), beta.getValue(), dt, posId, velId, true );
MultiVecDeriv f( &sop.vop, core::VecDerivId::force() ); // total force (stiffness + compliance) (f_k term)
_ck.realloc( &sop.vop, false, true ); // the right part of the implicit system (c_k term)
if( !useVelocity ) _acc.realloc( &sop.vop );
{
scoped::timer step("lambdas alloc");
lagrange.realloc( &sop.vop, false, true );
// vop.print( lagrange,serr, "BEGIN lambda: ", "\n" );
}
// compute forces and implicit right part warning: must be
// call before assemblyVisitor since the mapping's geometric
// stiffness depends on its child force
compute_forces( sop, f, &_ck );
// assemble system
perform_assembly( &sop.mparams(), sys );
// debugging
if( debug.getValue() ) sys.debug();
if( f_printLog.getValue() )
{
sout << "dynamics size m: " <<sys.m<< sendl;
sout << "constraint size n: " <<sys.n<< sendl;
}
// look for violated and active constraints
// must be performed after assembly and before system factorization
filter_constraints( posId );
// system factor
{
scoped::timer step("system factor");
kkt->factor( sys );
}
// system solution / rhs
vec x(sys.size());
vec rhs(sys.size());
// ready to solve
{
unsigned stabilizationType = stabilization.getValue().getSelectedId();
scoped::timer step("system solve");
// constraint pre-stabilization
if( sys.n && stabilizationType==PRE_STABILIZATION )
{
// Note that stabilization is always solved in velocity
scoped::timer step("correction");
x = vec::Zero( sys.size() );
rhs_correction(rhs, sys, posId, velId);
kkt->correct(x, sys, rhs, stabilization_damping.getValue() );
if( debug.getValue() ) {
serr << "correction rhs:" << std::endl
<< rhs.transpose() << std::endl
<< "solution:" << std::endl
<< x.transpose() << sendl;
}
MultiVecDeriv v_stab( &sop.vop ); // a temporary multivec not to modify velocity
set_state_v( sys, x, v_stab.id() ); // set v (no need to set lambda)
integrate( sop, posId, v_stab.id() );
}
// actual dynamics
{
scoped::timer step("dynamics");
if( warm_start.getValue() ) get_state( x, sys, useVelocity ? velId : _acc.id() );
else x = vec::Zero( sys.size() );
rhs_dynamics( sop, rhs, sys, _ck, posId, velId );
kkt->solve(x, sys, rhs);
if( debug.getValue() ) {
sout << "dynamics rhs:" << std::endl
<< rhs.transpose() << std::endl
<< "solution:" << std::endl
<< x.transpose() << sendl;
}
if( storeDSol ) {
dynamics_rhs = rhs;
dynamics_solution = x;
}
switch( formulation.getValue().getSelectedId() )
{
case FORMULATION_VEL: // p+ = p- + h.v
set_state( sys, x, velId ); // set v and lambda
integrate( sop, posId, velId );
break;
case FORMULATION_DV: // v+ = v- + dv p+ = p- + h.v
set_state( sys, x, _acc.id() ); // set v and lambda
integrate( sop, posId, velId, _acc.id(), 1.0 );
break;
case FORMULATION_ACC: // v+ = v- + h.a p+ = p- + h.v
set_state( sys, x, _acc.id() ); // set v and lambda
integrate( sop, posId, velId, _acc.id(), dt );
break;
}
// TODO is this even needed at this point ? NO it is done by the animation loop
// propagate( &sop.mparams() );
}
// propagate lambdas if asked to (constraint forces must be propagated before post_stab)
unsigned constraint_f = constraint_forces.getValue().getSelectedId();
if( constraint_f && sys.n ) {
scoped::timer step("constraint_forces");
simulation::propagate_constraint_force_visitor prop( &sop.mparams(), core::VecId::force(), lagrange.id(), useVelocity ? 1.0/sys.dt : 1.0, constraint_f>1, constraint_f==3 );
send( prop );
}
// constraint post-stabilization
if( stabilizationType>=POST_STABILIZATION_RHS )
{
post_stabilization( sop, posId, velId, stabilizationType==POST_STABILIZATION_ASSEMBLY);
}
}
clear_constraints();
// vop.print( lagrange,serr, "END lambda: ", "\n" );
}
void CompliantImplicitSolver::init() {
// do want KKTSolver !
kkt = this->getContext()->get<kkt_type>(core::objectmodel::BaseContext::Local);
// TODO slightly less dramatic error, maybe ?
if( !kkt ) throw std::logic_error("CompliantImplicitSolver needs a KKTSolver");
}
void CompliantImplicitSolver::post_stabilization(SolverOperations& sop,
core::MultiVecCoordId posId, core::MultiVecDerivId velId,
bool fullAssembly, bool realloc )
{
if( !sys.n ) return;
if( realloc )
{
static_cast<simulation::Node*>(getContext())->precomputeTraversalOrder( &sop.mparams() ); // if the graph changed, the traversal order needs to be updated
_ck.realloc( &sop.vop, false, true ); // the right part of the implicit system (c_k term)
}
// Note that stabilization is always solved in velocity
scoped::timer step("correction");
// propagate dynamics position and velocity
propagate( &sop.mparams() );
// at this point collision detection should be run again
// for now, we keep the same contact points with the same normals (wrong)
// but the contact violation is updated
// dt must be small with collisions
MultiVecDeriv f( &sop.vop, core::VecDerivId::force() );
compute_forces( sop, f );
if( fullAssembly )
{
// assemble system
perform_assembly( &sop.mparams(), sys );
// look for violated and active constraints
// must be performed after assembly and before system factorization
filter_constraints( posId );
// system factor
{
scoped::timer step("correction system factor");
kkt->factor( sys );
}
}
else
{
filter_constraints( posId );
}
vec x = vec::Zero( sys.size() );
vec rhs( sys.size() );
rhs_correction(rhs, sys, posId, velId);
kkt->correct(x, sys, rhs, stabilization_damping.getValue() );
if( debug.getValue() ) {
sout << "correction rhs:" << std::endl
<< rhs.transpose() << std::endl
<< "solution:" << std::endl
<< x.transpose() << sendl;
}
MultiVecDeriv v_stab( &sop.vop ); // a temporary multivec not to modify velocity
set_state_v( sys, x, v_stab.id() ); // set v (no need to set lambda)
integrate( sop, posId, v_stab.id() );
propagate( &sop.mparams() );
}
void CompliantImplicitSolver::parse(core::objectmodel::BaseObjectDescription* arg)
{
Inherit1::parse(arg);
// to be backward compatible with previous data structure
const char* propagate_lambdasChar = arg->getAttribute("propagate_lambdas");
if( propagate_lambdasChar )
{
serr<<helper::logging::Message::Deprecated<<"parse: You are using a deprecated Data 'propagate_lambdas', please have a look to 'constraint_forces'"<<sendl;
Data<bool> data;
data.read( propagate_lambdasChar );
if( data.getValue() )
constraint_forces.beginWriteOnly()->setSelectedItem(3); constraint_forces.endEdit();
}
}
}
}
}
| 36.992258 | 293 | 0.562036 | [
"vector"
] |
54c3d46c69360b9b0b975d0fba1d1449501ad288 | 23,502 | cc | C++ | contrib/fluxbox/src/FocusControl.cc | xk2600/lightbox | 987d901366fe706de1a8bbd1efd49b87abff3e0b | [
"BSD-2-Clause"
] | null | null | null | contrib/fluxbox/src/FocusControl.cc | xk2600/lightbox | 987d901366fe706de1a8bbd1efd49b87abff3e0b | [
"BSD-2-Clause"
] | 2 | 2017-05-30T05:21:59.000Z | 2018-03-14T07:21:33.000Z | src/FocusControl.cc | antix-skidoo/fluxbox | b83ee923f4ab2ab51f3b8c14343bda0579e538c6 | [
"MIT"
] | null | null | null | // FocusControl.cc
// Copyright (c) 2006 Fluxbox Team (fluxgen at fluxbox dot org)
//
// 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 "FocusControl.hh"
#include "ClientPattern.hh"
#include "Screen.hh"
#include "Window.hh"
#include "WinClient.hh"
#include "Workspace.hh"
#include "fluxbox.hh"
#include "FbWinFrameTheme.hh"
#include "Debug.hh"
#include "FbTk/EventManager.hh"
#include <string>
#include <iostream>
#include <algorithm>
#ifdef HAVE_CSTRING
#include <cstring>
#else
#include <string.h>
#endif
using std::endl;
using std::string;
WinClient *FocusControl::s_focused_window = 0;
FluxboxWindow *FocusControl::s_focused_fbwindow = 0;
WinClient *FocusControl::s_expecting_focus = 0;
bool FocusControl::s_reverting = false;
namespace {
bool doSkipWindow(const Focusable &win, const ClientPattern *pat) {
const FluxboxWindow *fbwin = win.fbwindow();
if (!fbwin || fbwin->isFocusHidden() || fbwin->isModal())
return true; // skip if no fbwindow or if focushidden
if (pat && !pat->match(win))
return true; // skip if it doesn't match the pattern
return false; // else don't skip
}
} // end anonymous namespace
FocusControl::FocusControl(BScreen &screen):
m_screen(screen),
m_focus_model(screen.resourceManager(),
CLICKFOCUS,
screen.name()+".focusModel",
screen.altName()+".FocusModel"),
m_tab_focus_model(screen.resourceManager(),
CLICKTABFOCUS,
screen.name()+".tabFocusModel",
screen.altName()+".TabFocusModel"),
m_focus_new(screen.resourceManager(), true,
screen.name()+".focusNewWindows",
screen.altName()+".FocusNewWindows"),
#ifdef XINERAMA
m_focus_same_head(screen.resourceManager(), false,
screen.name()+".focusSameHead",
screen.altName()+".FocusSameHead"),
#endif // XINERAMA
m_focused_list(screen), m_creation_order_list(screen),
m_focused_win_list(screen), m_creation_order_win_list(screen),
m_cycling_list(0),
m_was_iconic(0),
m_cycling_last(0),
m_cycling_next(0),
m_ignore_mouse_x(-1), m_ignore_mouse_y(-1) {
m_cycling_window = m_focused_list.clientList().end();
}
void FocusControl::cycleFocus(const FocusableList &window_list,
const ClientPattern *pat, bool cycle_reverse) {
if (!m_cycling_list) {
if (m_screen.isCycling())
// only set this when we're waiting for modifiers
m_cycling_list = &window_list;
m_was_iconic = 0;
m_cycling_last = 0;
m_cycling_next = 0;
} else if (m_cycling_list != &window_list)
m_cycling_list = &window_list;
Focusables::const_iterator it_begin = window_list.clientList().begin();
Focusables::const_iterator it_end = window_list.clientList().end();
// too many things can go wrong with remembering this
m_cycling_window = it_end;
if (m_cycling_next)
m_cycling_window = find(it_begin, it_end, m_cycling_next);
if (m_cycling_window == it_end)
m_cycling_window = find(it_begin, it_end, s_focused_window);
if (m_cycling_window == it_end)
m_cycling_window = find(it_begin, it_end, s_focused_fbwindow);
Focusables::const_iterator it = m_cycling_window;
FluxboxWindow *fbwin = 0;
WinClient *last_client = 0;
WinClient *was_iconic = 0;
// find the next window in the list that works
while (true) {
if (cycle_reverse && it == it_begin)
it = it_end;
else if (!cycle_reverse && it == it_end)
it = it_begin;
else
cycle_reverse ? --it : ++it;
// give up [do nothing] if we reach the current focused again
if (it == m_cycling_window)
return;
if (it == it_end)
continue;
fbwin = (*it)->fbwindow();
if (!fbwin)
continue;
// keep track of the originally selected window in a group
last_client = &fbwin->winClient();
was_iconic = (fbwin->isIconic() ? last_client : 0);
// now we actually try to focus the window
if (!doSkipWindow(**it, pat) && (m_cycling_next = *it) && (*it)->focus())
break;
m_cycling_next = 0;
}
m_cycling_window = it;
// if we're still in the same fbwin, there's nothing else to do
if (m_cycling_last && m_cycling_last->fbwindow() == fbwin)
return;
// if we were already cycling, then restore the old state
if (m_cycling_last) {
// set back to originally selected window in that group
m_cycling_last->fbwindow()->setCurrentClient(*m_cycling_last, false);
if (m_was_iconic == m_cycling_last) {
s_reverting = true; // little hack
m_cycling_last->fbwindow()->iconify();
s_reverting = false;
}
}
if (!isCycling())
fbwin->raise();
m_cycling_last = last_client;
m_was_iconic = was_iconic;
}
void FocusControl::goToWindowNumber(const FocusableList &winlist, int num,
const ClientPattern *pat) {
Focusables list = winlist.clientList();
if (num < 0) {
list.reverse();
num = -num;
}
Focusable *win = 0;
Focusables::const_iterator it = list.begin(), it_end = list.end();
for (; num && it != it_end; ++it) {
if (!doSkipWindow(**it, pat) && (*it)->acceptsFocus()) {
--num;
win = *it;
}
}
if (win) {
win->focus();
if (win->fbwindow())
win->fbwindow()->raise();
}
}
void FocusControl::addFocusBack(WinClient &client) {
m_focused_list.pushBack(client);
m_creation_order_list.pushBack(client);
}
void FocusControl::addFocusFront(WinClient &client) {
m_focused_list.pushFront(client);
m_creation_order_list.pushBack(client);
}
void FocusControl::addFocusWinBack(Focusable &win) {
m_focused_win_list.pushBack(win);
m_creation_order_win_list.pushBack(win);
}
void FocusControl::addFocusWinFront(Focusable &win) {
m_focused_win_list.pushFront(win);
m_creation_order_win_list.pushBack(win);
}
// move all clients in given window to back of focused list
void FocusControl::setFocusBack(FluxboxWindow &fbwin) {
// do nothing if there are no windows open
// don't change focus order while cycling
if (m_focused_list.empty() || s_reverting)
return;
m_focused_win_list.moveToBack(fbwin);
// we need to move its clients to the back while preserving their order
Focusables list = m_focused_list.clientList();
Focusables::iterator it = list.begin(), it_end = list.end();
for (; it != it_end; ++it) {
if ((*it)->fbwindow() == &fbwin)
m_focused_list.moveToBack(**it);
}
}
void FocusControl::stopCyclingFocus() {
// nothing to do
if (m_cycling_list == 0)
return;
m_cycling_last = 0;
m_cycling_next = 0;
m_cycling_list = 0;
// put currently focused window to top
if (s_focused_window) {
// re-focus last window to give the client a chance to redistribute the
// focus internally (client-side only modality)
s_focused_window->focus();
if (s_focused_window)
setScreenFocusedWindow(*s_focused_window);
if (s_focused_fbwindow)
s_focused_fbwindow->raise();
} else
revertFocus(m_screen);
}
/**
* Used to find out which window was last focused on the given workspace
* If workspace is outside the ID range, then the absolute last focused window
* is given.
*/
Focusable *FocusControl::lastFocusedWindow(int workspace) {
if (m_screen.isShuttingdown()) return 0;
if (workspace < 0 || workspace >= (int) m_screen.numberOfWorkspaces())
return m_focused_list.clientList().front();
#ifdef XINERAMA
int cur_head = focusSameHead() ? m_screen.getCurrHead() : (-1);
if(cur_head != -1) {
FluxboxWindow *fbwindow = focusedFbWindow();
if(fbwindow && fbwindow->isMoving()) {
cur_head = -1;
}
}
#endif // XINERAMA
Focusables::iterator it = m_focused_list.clientList().begin();
Focusables::iterator it_end = m_focused_list.clientList().end();
for (; it != it_end; ++it) {
if ((*it)->fbwindow() && (*it)->acceptsFocus() &&
(*it)->fbwindow()->winClient().validateClient() &&
#ifdef XINERAMA
( (cur_head == -1) || ((*it)->fbwindow()->getOnHead() == cur_head) ) &&
#endif // XINERAMA
((((int)(*it)->fbwindow()->workspaceNumber()) == workspace ||
(*it)->fbwindow()->isStuck()) && !(*it)->fbwindow()->isIconic()))
return *it;
}
return 0;
}
/**
* Used to find out which window was last active in the given group
* If ignore_client is given, it excludes that client.
* Stuck, iconic etc don't matter within a group
*/
WinClient *FocusControl::lastFocusedWindow(FluxboxWindow &group, WinClient *ignore_client) {
if (m_focused_list.empty() || m_screen.isShuttingdown())
return 0;
Focusables::iterator it = m_focused_list.clientList().begin();
Focusables::iterator it_end = m_focused_list.clientList().end();
for (; it != it_end; ++it) {
if (((*it)->fbwindow() == &group) &&
(*it) != ignore_client)
return dynamic_cast<WinClient *>(*it);
}
return 0;
}
void FocusControl::setScreenFocusedWindow(WinClient &win_client) {
// raise newly focused window to the top of the focused list
// don't change the order if we're cycling or shutting down
if (!isCycling() && !m_screen.isShuttingdown() && !s_reverting) {
m_focused_list.moveToFront(win_client);
if (win_client.fbwindow())
m_focused_win_list.moveToFront(*win_client.fbwindow());
}
}
void FocusControl::setFocusModel(FocusModel model) {
m_focus_model = model;
}
void FocusControl::setTabFocusModel(TabFocusModel model) {
m_tab_focus_model = model;
}
void FocusControl::dirFocus(FluxboxWindow &win, FocusDir dir) {
// change focus to the window in direction dir from the given window
// we scan through the list looking for the window that is "closest"
// in the given direction
FluxboxWindow *foundwin = 0;
int weight = 999999, exposure = 0; // extreme values
int borderW = win.frame().window().borderWidth(),
top = win.y() + borderW,
bottom = win.y() + win.height() + borderW,
left = win.x() + borderW,
right = win.x() + win.width() + borderW;
Workspace::Windows &wins = m_screen.currentWorkspace()->windowList();
Workspace::Windows::iterator it = wins.begin();
for (; it != wins.end(); ++it) {
if ((*it) == &win
|| (*it)->isIconic()
|| (*it)->isFocusHidden()
|| !(*it)->acceptsFocus())
continue; // skip self
// we check things against an edge, and within the bounds (draw a picture)
int edge=0, upper=0, lower=0, oedge=0, oupper=0, olower=0;
int otop = (*it)->y() + borderW,
// 2 * border = border on each side
obottom = (*it)->y() + (*it)->height() + borderW,
oleft = (*it)->x() + borderW,
// 2 * border = border on each side
oright = (*it)->x() + (*it)->width() + borderW;
// check if they intersect
switch (dir) {
case FOCUSUP:
edge = obottom;
oedge = bottom;
upper = left;
oupper = oleft;
lower = right;
olower = oright;
break;
case FOCUSDOWN:
edge = top;
oedge = otop;
upper = left;
oupper = oleft;
lower = right;
olower = oright;
break;
case FOCUSLEFT:
edge = oright;
oedge = right;
upper = top;
oupper = otop;
lower = bottom;
olower = obottom;
break;
case FOCUSRIGHT:
edge = left;
oedge = oleft;
upper = top;
oupper = otop;
lower = bottom;
olower = obottom;
break;
}
if (oedge < edge)
continue; // not in the right direction
if (olower <= upper || oupper >= lower) {
// outside our horz bounds, get a heavy weight penalty
int myweight = 100000 + oedge - edge + abs(upper-oupper)+abs(lower-olower);
if (myweight < weight) {
foundwin = *it;
exposure = 0;
weight = myweight;
}
} else if ((oedge - edge) < weight) {
foundwin = *it;
weight = oedge - edge;
exposure = ((lower < olower)?lower:olower) - ((upper > oupper)?upper:oupper);
} else if (foundwin && oedge - edge == weight) {
int myexp = ((lower < olower)?lower:olower) - ((upper > oupper)?upper:oupper);
if (myexp > exposure) {
foundwin = *it;
// weight is same
exposure = myexp;
}
} // else not improvement
}
if (foundwin)
foundwin->focus();
}
void FocusControl::ignoreAtPointer(bool force)
{
int ignore_i, ignore_x, ignore_y;
unsigned int ignore_ui;
Window ignore_w;
XQueryPointer(m_screen.rootWindow().display(),
m_screen.rootWindow().window(), &ignore_w, &ignore_w,
&ignore_x, &ignore_y,
&ignore_i, &ignore_i, &ignore_ui);
this->ignoreAt(ignore_x, ignore_y, force);
}
void FocusControl::ignoreAt(int x, int y, bool force)
{
if (force || this->focusModel() == MOUSEFOCUS) {
m_ignore_mouse_x = x; m_ignore_mouse_y = y;
}
}
void FocusControl::ignoreCancel()
{
m_ignore_mouse_x = m_ignore_mouse_y = -1;
}
bool FocusControl::isIgnored(int x, int y)
{
return x == m_ignore_mouse_x && y == m_ignore_mouse_y;
}
void FocusControl::removeClient(WinClient &client) {
if (client.screen().isShuttingdown())
return;
if (isCycling() && m_cycling_window != m_cycling_list->clientList().end() &&
*m_cycling_window == &client) {
m_cycling_window = m_cycling_list->clientList().end();
stopCyclingFocus();
} else if (m_cycling_last == &client) {
m_cycling_last = 0;
} else if (m_cycling_next == &client) {
m_cycling_next = 0;
}
m_focused_list.remove(client);
m_creation_order_list.remove(client);
client.screen().clientListSig().emit(client.screen());
}
void FocusControl::removeWindow(Focusable &win) {
if (win.screen().isShuttingdown())
return;
if (isCycling() && m_cycling_window != m_cycling_list->clientList().end() &&
*m_cycling_window == &win) {
m_cycling_window = m_cycling_list->clientList().end();
stopCyclingFocus();
}
m_focused_win_list.remove(win);
m_creation_order_win_list.remove(win);
win.screen().clientListSig().emit(win.screen());
}
void FocusControl::shutdown() {
// restore windows backwards so they get put back correctly on restart
Focusables::reverse_iterator it = m_focused_list.clientList().rbegin();
for (; it != m_focused_list.clientList().rend(); ++it) {
WinClient *client = dynamic_cast<WinClient *>(*it);
if (client && client->fbwindow())
client->fbwindow()->restore(client, true);
}
}
/**
* This function is called whenever we aren't quite sure what
* focus is meant to be, it'll make things right ;-)
*/
void FocusControl::revertFocus(BScreen &screen) {
if (s_reverting || screen.isShuttingdown())
return;
Focusable *next_focus =
screen.focusControl().lastFocusedWindow(screen.currentWorkspaceID());
if (next_focus && next_focus->fbwindow() &&
next_focus->fbwindow()->isStuck())
FocusControl::s_reverting = true;
// if setting focus fails, or isn't possible, fallback correctly
if (!(next_focus && next_focus->focus())) {
setFocusedWindow(0); // so we don't get dangling m_focused_window pointer
// if there's a menu open, focus it
if (FbTk::Menu::shownMenu())
FbTk::Menu::shownMenu()->grabInputFocus();
else {
switch (screen.focusControl().focusModel()) {
case FocusControl::MOUSEFOCUS:
case FocusControl::STRICTMOUSEFOCUS:
XSetInputFocus(screen.rootWindow().display(),
PointerRoot, None, CurrentTime);
break;
case FocusControl::CLICKFOCUS:
screen.rootWindow().setInputFocus(RevertToPointerRoot,
CurrentTime);
break;
}
}
}
FocusControl::s_reverting = false;
}
/*
* Like revertFocus, but specifically related to this window (transients etc)
* if full_revert, we fallback to a full revertFocus if we can't find anything
* local to the client.
* If unfocus_frame is true, we won't focus anything in the same frame
* as the client.
*
* So, we first prefer to choose the last client in this window, and if no luck
* (or unfocus_frame), then we just use the normal revertFocus on the screen.
*
* assumption: client has focus
*/
void FocusControl::unfocusWindow(WinClient &client,
bool full_revert,
bool unfocus_frame) {
// go up the transient tree looking for a focusable window
FluxboxWindow *fbwin = client.fbwindow();
if (fbwin == 0)
return; // nothing more we can do
BScreen &screen = fbwin->screen();
if (client.isTransient() && client.transientFor()->focus())
return;
if (!unfocus_frame) {
WinClient *last_focus = screen.focusControl().lastFocusedWindow(*fbwin, &client);
if (last_focus && last_focus->focus())
return;
}
if (full_revert && s_focused_window == &client)
revertFocus(screen);
}
void FocusControl::setFocusedWindow(WinClient *client) {
if (client == s_focused_window &&
(!client || client->fbwindow() == s_focused_fbwindow))
return;
BScreen *screen = client ? &client->screen() : 0;
if (client && screen && screen->focusControl().isCycling()) {
Focusable *next = screen->focusControl().m_cycling_next;
WinClient *nextClient = dynamic_cast<WinClient*>(next);
FluxboxWindow *nextWindow = nextClient ? 0 : dynamic_cast<FluxboxWindow*>(next);
if (next && nextClient != client && nextWindow != client->fbwindow() &&
screen->focusControl().m_cycling_list->contains(*next)) {
// if we're currently cycling and the client tries to juggle around focus
// on FocusIn events to provide client-side modality - don't let him
next->focus();
if (nextClient)
setFocusedWindow(nextClient); // doesn't happen automatically while cycling, 1148
return;
}
}
if (client && client != expectingFocus() && s_focused_window &&
(!(screen && screen->focusControl().isCycling())) &&
((s_focused_fbwindow->focusProtection() & Focus::Lock) ||
(client && client->fbwindow() && (client->fbwindow()->focusProtection() & Focus::Deny)))) {
s_focused_window->focus();
return;
}
BScreen *old_screen =
FocusControl::focusedWindow() ?
&FocusControl::focusedWindow()->screen() : 0;
fbdbg<<"------------------"<<endl;
fbdbg<<"Setting Focused window = "<<client<<endl;
if (client != 0)
fbdbg<<"title: "<<client->title().logical()<<endl;
fbdbg<<"Current Focused window = "<<s_focused_window<<endl;
fbdbg<<"------------------"<<endl;
// Update the old focused client to non focus
if (s_focused_fbwindow &&
(!client || client->fbwindow() != s_focused_fbwindow))
s_focused_fbwindow->setFocusFlag(false);
if (client && client->fbwindow() && !client->fbwindow()->isIconic()) {
// screen should be ok
s_focused_fbwindow = client->fbwindow();
s_focused_window = client; // update focused window
s_expecting_focus = 0;
s_focused_fbwindow->setCurrentClient(*client,
false); // don't set inputfocus
s_focused_fbwindow->setFocusFlag(true); // set focus flag
} else {
s_focused_window = 0;
s_focused_fbwindow = 0;
}
// update AtomHandlers and/or other stuff...
if (screen)
screen->focusedWindowSig().emit(*screen, s_focused_fbwindow, s_focused_window);
if (old_screen && screen != old_screen)
old_screen->focusedWindowSig().emit(*old_screen, s_focused_fbwindow, s_focused_window);
}
////////////////////// FocusControl RESOURCES
namespace FbTk {
template<>
std::string FbTk::Resource<FocusControl::FocusModel>::getString() const {
switch (m_value) {
case FocusControl::MOUSEFOCUS:
return string("MouseFocus");
case FocusControl::STRICTMOUSEFOCUS:
return string("StrictMouseFocus");
case FocusControl::CLICKFOCUS:
return string("ClickFocus");
}
// default string
return string("ClickFocus");
}
template<>
void FbTk::Resource<FocusControl::FocusModel>::
setFromString(char const *strval) {
if (strcasecmp(strval, "MouseFocus") == 0)
m_value = FocusControl::MOUSEFOCUS;
else if (strcasecmp(strval, "StrictMouseFocus") == 0)
m_value = FocusControl::STRICTMOUSEFOCUS;
else if (strcasecmp(strval, "ClickToFocus") == 0)
m_value = FocusControl::CLICKFOCUS;
else
setDefaultValue();
}
template<>
std::string FbTk::Resource<FocusControl::TabFocusModel>::getString() const {
switch (m_value) {
case FocusControl::MOUSETABFOCUS:
return string("SloppyTabFocus");
case FocusControl::CLICKTABFOCUS:
return string("ClickToTabFocus");
}
// default string
return string("ClickToTabFocus");
}
template<>
void FbTk::Resource<FocusControl::TabFocusModel>::
setFromString(char const *strval) {
if (strcasecmp(strval, "SloppyTabFocus") == 0 )
m_value = FocusControl::MOUSETABFOCUS;
else if (strcasecmp(strval, "ClickToTabFocus") == 0)
m_value = FocusControl::CLICKTABFOCUS;
else
setDefaultValue();
}
} // end namespace FbTk
| 33.148096 | 99 | 0.617564 | [
"model"
] |
54cc5366a49a3c7588e4528dd7f2224b1fb14bf3 | 51,882 | cpp | C++ | src/miner.cpp | xoleozhao/BitCash | 988186531b3c17d73a396dfdbc9dadf1fb4e4212 | [
"MIT"
] | null | null | null | src/miner.cpp | xoleozhao/BitCash | 988186531b3c17d73a396dfdbc9dadf1fb4e4212 | [
"MIT"
] | null | null | null | src/miner.cpp | xoleozhao/BitCash | 988186531b3c17d73a396dfdbc9dadf1fb4e4212 | [
"MIT"
] | null | null | null | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <miner.h>
#include <amount.h>
#include <boost/algorithm/string.hpp>
#include <cctype>
#include <chain.h>
#include <chainparams.h>
#include <coins.h>
#include <consensus/consensus.h>
#include <consensus/tx_verify.h>
#include <consensus/merkle.h>
#include <consensus/validation.h>
#include "cuckoo/miner.h"
#include <hash.h>
#include <validation.h>
#include <net.h>
#include <policy/feerate.h>
#include <policy/policy.h>
#include <pow.h>
#include <primitives/transaction.h>
#include <script/standard.h>
#include <timedata.h>
#include <tuple>
#include <util.h>
#include <utility>
#include <utilmoneystr.h>
#include <validationinterface.h>
#include <wallet/wallet.h>
#include <algorithm>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <queue>
#include <utility>
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include "RSJparser.tcc"
#include <curl/curl.h>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
std::string getdocumentwithcurl(std::string url)
{
CURL *curl;
CURLcode res;
std::string readBuffer = "";
//std::cout << url << std::endl;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
/* if(res != CURLE_OK) {
std::cout << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
std::cout << readBuffer << std::endl;*/
/* always cleanup */
curl_easy_cleanup(curl);
return readBuffer;
}
}
// Unconfirmed transactions in the memory pool often depend on other
// transactions in the memory pool. When we select transactions from the
// pool, we select by highest fee rate of a transaction combined with all
// its ancestors.
bool gpuminingfailed = false;
bool trygpumining = true;
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockWeight = 0;
const int MAX_NONCE = 0xfffff;
CAmount minedcoins=0;
bool triedoneproofofwork = false;
bool AddPriceInformation(CBlockHeader *pblock);
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
int64_t nOldTime = pblock->nTime;
int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
if (nOldTime < nNewTime)
pblock->nTime = nNewTime;
// Updating time can change work required on testnet:
if (consensusParams.fPowAllowMinDifficultyBlocks)
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams).nBits;
if (pblock->nTime > consensusParams.STABLETIME &&
(!(pblock->nPriceInfo.priceTime == pblock->nTime || (pblock->nPriceInfo.priceTime > pblock->nTime && pblock->nPriceInfo.priceTime <= pblock->nTime + MAX_PRICETIME_DIFFERENCE / 3)
|| (pblock->nPriceInfo.priceTime < pblock->nTime && pblock->nPriceInfo.priceTime + MAX_PRICETIME_DIFFERENCE / 3 >= pblock->nTime)))) {
AddPriceInformation(pblock);
} else
if (pblock->nTime > consensusParams.STABLETIME &&
(!(pblock->nPriceInfo2.priceTime == pblock->nTime || (pblock->nPriceInfo2.priceTime > pblock->nTime && pblock->nPriceInfo2.priceTime <= pblock->nTime + MAX_PRICETIME_DIFFERENCE / 3)
|| (pblock->nPriceInfo2.priceTime < pblock->nTime && pblock->nPriceInfo2.priceTime + MAX_PRICETIME_DIFFERENCE / 3 >= pblock->nTime)))) {
AddPriceInformation(pblock);
} else
if (pblock->nTime > consensusParams.STABLETIME &&
(!(pblock->nPriceInfo3.priceTime == pblock->nTime || (pblock->nPriceInfo3.priceTime > pblock->nTime && pblock->nPriceInfo3.priceTime <= pblock->nTime + MAX_PRICETIME_DIFFERENCE / 3)
|| (pblock->nPriceInfo3.priceTime < pblock->nTime && pblock->nPriceInfo3.priceTime + MAX_PRICETIME_DIFFERENCE / 3 >= pblock->nTime)))) {
AddPriceInformation(pblock);
}
if (pblock->nTime > consensusParams.X16RTIME)
pblock->nVersion |= hashx16Ractive;
return nNewTime - nOldTime;
}
BlockAssembler::Options::Options() {
blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
}
BlockAssembler::BlockAssembler(const CChainParams& params, const Options& options) : chainparams(params)
{
blockMinFeeRate = options.blockMinFeeRate;
// Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(MAX_BLOCK_WEIGHT - 4000, options.nBlockMaxWeight));
}
static BlockAssembler::Options DefaultOptions(const CChainParams& params)
{
// Block resource limits
// If -blockmaxweight is not given, limit to DEFAULT_BLOCK_MAX_WEIGHT
BlockAssembler::Options options;
options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
if (gArgs.IsArgSet("-blockmintxfee")) {
CAmount n = 0;
ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n);
options.blockMinFeeRate = CFeeRate(n);
} else {
options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
}
return options;
}
BlockAssembler::BlockAssembler(const CChainParams& params) : BlockAssembler(params, DefaultOptions(params)) {}
void BlockAssembler::resetBlock()
{
inBlock.clear();
// Reserve space for coinbase tx
nBlockWeight = 4000;
nBlockSigOpsCost = 400;
fIncludeWitness = false;
// These counters do not include coinbase tx
nBlockTx = 0;
nFees = 0;
}
/** Converts the nValue to other currencies according to the price information of the block and the currency of the transaction outputs */
void BlockAssembler::ConvertCurrenciesForBlockTemplate()
{
int i;
int j;
CAmount pricerate = pblock->GetPriceinCurrency(0);//dollar->bitcash /
CAmount pricerate2 = pblock->GetPriceinCurrency(1);//bitcash->dollar *
for (i = 0;i < pblock->vtx.size(); i++) {
CMutableTransaction tx(*pblock->vtx[i]);
int inputcurrency = 0;//Currency of transaction inputs
//only one input currency is allowed for all inputs
for (j = 0;j < tx.vin.size(); j++) {
if (tx.vin[j].isnickname) continue;
CCoinsViewCache inputs(pcoinsTip.get());
const Coin& coin = inputs.AccessCoin(tx.vin[j].prevout);
if (coin.IsCoinBase()) {
inputcurrency = 0;
} else {
inputcurrency = coin.out.currency;
}
break;
}
for (j = 0;j < tx.vout.size(); j++) {
if (tx.vout[j].currency != inputcurrency) {
if (inputcurrency == 0 && tx.vout[j].currency == 1) {
//std::cout << "Input BitCash: " << FormatMoney(tx.vout[j].nValueBitCash) << std::endl;
//Convert BitCash into Dollars
tx.vout[j].nValue = (__int128_t)tx.vout[j].nValueBitCash * (__int128_t)pricerate2 / (__int128_t)COIN;
//std::cout << "Converted to Dollar: " << FormatMoney(tx.vout[j].nValue) << std::endl;
} else
if (inputcurrency == 1 && tx.vout[j].currency == 0) {
//std::cout << "Input Dollar: " << FormatMoney(tx.vout[j].nValueBitCash) << std::endl;
//Convert Dollars into BitCash
tx.vout[j].nValue = (__int128_t)tx.vout[j].nValueBitCash * (__int128_t)COIN / (__int128_t)pricerate;
//std::cout << "Converted to BitCash: " << FormatMoney(tx.vout[j].nValue) << std::endl;
}
} else tx.vout[j].nValue = tx.vout[j].nValueBitCash;
}
pblock->vtx[i] = MakeTransactionRef(std::move(tx));
}
}
/** Converts the nValue to other currencies according to the price information of the block and the currency of the transaction outputs */
void BlockAssembler::CalculateFeesForBlock()
{
int i;
int j;
CAmount pricerate = pblock->GetPriceinCurrency(0);
nFees = 0;
for (i = 1;i < pblock->vtx.size(); i++) {//start from transaction 1 not 0, because transaction 0 is the coinbase placeholder
CTransaction tx(*pblock->vtx[i]);
int currency = 0;//Currency of transaction inputs
CAmount nValueIn = 0;
for (j = 0;j < tx.vin.size(); j++) {
if (tx.vin[j].isnickname) continue;
CCoinsViewCache inputs(pcoinsTip.get());
const Coin& coin = inputs.AccessCoin(tx.vin[j].prevout);
if (coin.IsCoinBase()) {
currency = 0;
} else
currency = coin.out.currency;
nValueIn += coin.out.nValue;
}
CAmount value_out = tx.GetValueOut();
// Tally transaction fees
CAmount txfee_aux = nValueIn - value_out;
if (currency != 0) {
//convert fee into currency 0
if (currency == 1) {
txfee_aux = (__int128_t)txfee_aux * (__int128_t)COIN / (__int128_t)pblock->GetPriceinCurrency(0);
}
}
nFees += txfee_aux;
}
}
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlockWithScriptPubKey(const CScript& scriptPubKeyIn, bool fMineWitnessTx)
{
int64_t nTimeStart = GetTimeMicros();
resetBlock();
pblocktemplate.reset(new CBlockTemplate());
if(!pblocktemplate.get())
return nullptr;
pblock = &pblocktemplate->block; // pointer for convenience
// Add dummy coinbase tx as first transaction
pblock->vtx.emplace_back();
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
LOCK2(cs_main, mempool.cs);
AddPriceInformation(pblock);
CBlockIndex* pindexPrev = chainActive.Tip();
assert(pindexPrev != nullptr);
nHeight = pindexPrev->nHeight + 1;
pblock->nTime = GetAdjustedTime();
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
if (pblock->nTime > chainparams.GetConsensus().STABLETIME)
pblock->nVersion |= stabletimeactive;
if (pblock->nTime > chainparams.GetConsensus().X16RTIME)
pblock->nVersion |= hashx16Ractive;
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
// Decide whether to include witness transactions
// This is only needed in case the witness softfork activation is reverted
// (which would require a very deep reorganization) or when
// -promiscuousmempoolflags is used.
// TODO: replace this with a call to main to assess validity of a mempool
// transaction (which in most cases can be a no-op).
// fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx;
fIncludeWitness=true;//always include Witness transactions
int nPackagesSelected = 0;
int nDescendantsUpdated = 0;
addPackageTxs(nPackagesSelected, nDescendantsUpdated);
nLastBlockTx = nBlockTx;
nLastBlockWeight = nBlockWeight;
CalculateFeesForBlock();
// Create coinbase transaction.
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(2);
coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
coinbaseTx.vout[0].nValueBitCash = coinbaseTx.vout[0].nValue;
//Pay to the development fund....
coinbaseTx.vout[1].scriptPubKey = GetScriptForRawPubKey(CPubKey(ParseHex(Dev1scriptPubKey)));
coinbaseTx.vout[1].nValue = GetBlockSubsidyDevs(nHeight, chainparams.GetConsensus());
coinbaseTx.vout[1].nValueBitCash = coinbaseTx.vout[1].nValue;
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
pblocktemplate->vTxFees[0] = -nFees;
// LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d C nVersion %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost, coinbaseTx.nVersion);
auto pow = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
pblock->nBits = pow.nBits;
pblock->nNonce = 0;
pblock->nEdgeBits = pow.nEdgeBits;
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
ConvertCurrenciesForBlockTemplate();
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
CValidationState state;
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
}
return std::move(pblocktemplate);
}
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(interfaces::Wallet* iwallet,
CWallet* wallet,
bool useinterface, bool fMineWitnessTx, bool includeextranonce)
{
int64_t nTimeStart = GetTimeMicros();
resetBlock();
pblocktemplate.reset(new CBlockTemplate());
if(!pblocktemplate.get())
return nullptr;
pblock = &pblocktemplate->block; // pointer for convenience
// Add dummy coinbase tx as first transaction
pblock->vtx.emplace_back();
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
LOCK2(cs_main, mempool.cs);
AddPriceInformation(pblock);
CBlockIndex* pindexPrev = chainActive.Tip();
assert(pindexPrev != nullptr);
nHeight = pindexPrev->nHeight + 1;
pblock->nTime = GetAdjustedTime();
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
if (pblock->nTime > chainparams.GetConsensus().STABLETIME)
pblock->nVersion |= stabletimeactive;
if (pblock->nTime > chainparams.GetConsensus().X16RTIME)
pblock->nVersion |= hashx16Ractive;
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
// Decide whether to include witness transactions
// This is only needed in case the witness softfork activation is reverted
// (which would require a very deep reorganization) or when
// -promiscuousmempoolflags is used.
// TODO: replace this with a call to main to assess validity of a mempool
// transaction (which in most cases can be a no-op).
// fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx;
fIncludeWitness=true;//always include Witness transactions
int nPackagesSelected = 0;
int nDescendantsUpdated = 0;
addPackageTxs(nPackagesSelected, nDescendantsUpdated);
nLastBlockTx = nBlockTx;
nLastBlockWeight = nBlockWeight;
CalculateFeesForBlock();
// Create coinbase transaction.
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(2);
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
coinbaseTx.vout[0].nValueBitCash = coinbaseTx.vout[0].nValue;
if (useinterface){
iwallet->FillTxOutForTransaction(coinbaseTx.vout[0],iwallet->GetCurrentAddressPubKey(),"", 0, false, false, CPubKey(), coinbaseTx.nVersion >= 6);
} else
{
wallet->FillTxOutForTransaction(coinbaseTx.vout[0],wallet->GetCurrentAddressPubKey(),"", 0, false, false, CPubKey(), coinbaseTx.nVersion >= 6);
}
//Pay to the development fund....
coinbaseTx.vout[1].scriptPubKey = GetScriptForRawPubKey(CPubKey(ParseHex(Dev1scriptPubKey)));
coinbaseTx.vout[1].nValue = GetBlockSubsidyDevs(nHeight, chainparams.GetConsensus());
coinbaseTx.vout[1].nValueBitCash = coinbaseTx.vout[1].nValue;
if (includeextranonce) {
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << ParseHex("FFBBAAEE003344BBFFBBAAEE003344BB") << OP_0;
} else {
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
}
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
pblocktemplate->vTxFees[0] = -nFees;
// LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d C nVersion %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost, coinbaseTx.nVersion);
auto pow = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
pblock->nBits = pow.nBits;
pblock->nNonce = 0;
pblock->nEdgeBits = pow.nEdgeBits;
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
ConvertCurrenciesForBlockTemplate();
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
CValidationState state;
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
}
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
stream << pblock->vtx[0];
std::string str=HexStr(stream.begin(),stream.end());
std::size_t found = str.find("ffbbaaee003344bbffbbaaee003344bb");
std::string str1=str;
std::string str2="";
if (found!=std::string::npos) {
str1=str.substr(0,found+32-16);
str2=str.substr(found+32,str.size()-found+32);
}
pblocktemplate->coinb1=str1;
pblocktemplate->coinb2=str2;
pblocktemplate->blockheight=nHeight;
return std::move(pblocktemplate);
}
void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
{
for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
// Only test txs not already in the block
if (inBlock.count(*iit)) {
testSet.erase(iit++);
}
else {
iit++;
}
}
}
std::set<std::string> exchanges;
const int numexchangeinfos = 5;
std::string exchangeinfos[numexchangeinfos] = {
{"https://wallet.choosebitcash.com/pricesources.txt"},
{"https://webwallet.choosebitcash.com/priceinfo/pricesources.txt"},
{"https://cadkas.com/priceinfo/pricesources.txt"},
{"https://price.choosebitcash.com/priceinfo/pricesources.txt"},
{"https://price2.choosebitcash.com/priceinfo/pricesources.txt"}
};
const int numwebsites = 5;
std::string pricewebsites[numwebsites] = {
{"https://wallet.choosebitcash.com/getpriceinfo.php"},
{"https://webwallet.choosebitcash.com/priceinfo/getpriceinfo.php"},
{"https://cadkas.com/priceinfo/getpriceinfo.php"},
{"https://price.choosebitcash.com/priceinfo/getpriceinfo.php"},
{"https://price2.choosebitcash.com/priceinfo/getpriceinfo.php"}
};
CAmount pricecache = COIN;
CAmount pricecache2 = COIN;
bool haspriceinfo = false;
uint64_t pricetime = 0;
void GetExchangesListFromWebserver()
{
//we already know these exchanges
for (int i = 0; i < numwebsites; i++) {
exchanges.insert(pricewebsites[i]);
}
//std::cout << "count " << exchanges.size() << std::endl;
//download a list of possible other exchanges
for (int i = 0; i < numexchangeinfos; i++) {
std::string server = exchangeinfos[i];
try {
std::string priceinfo = getdocumentwithcurl(server);
//std::cout << "c.priceinfo " << c.priceinfo << std::endl;
std::istringstream stream(priceinfo);
std::string line;
while(std::getline(stream, line)) {
exchanges.insert(boost::algorithm::trim_copy(line));
}
}
catch (std::exception& e)
{
}
}
//std::cout << "count " << exchanges.size() << std::endl;
}
CAmount GetPriceInformationFromWebserver(std::string server, std::string &price, std::string &signature, CAmount &secondprice)
{
secondprice = 0;
try
{
std::string priceinfo = getdocumentwithcurl(server);
RSJresource json (priceinfo);
if (time(nullptr) < Params().GetConsensus().MASTERKEYDUMMY) {
price = json["priceinfo"].as<std::string>("");
signature = json["signature"].as<std::string>("");
} else
{
price = json["priceinfo2"].as<std::string>("");
signature = json["signature2"].as<std::string>("");
}
}
catch (std::exception& e)
{
return 0;
}
if (IsHex(price)) {
std::vector<unsigned char> txData(ParseHex(price));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
CPriceInfo nPriceInfo;
ssData >> nPriceInfo;
if (nPriceInfo.prices[0] > 0) {
if (nPriceInfo.priceCount > 1 && nPriceInfo.prices[1] > 0)
secondprice = nPriceInfo.prices[1];
return nPriceInfo.prices[0];
} else return 0;
} catch (const std::exception&) {
// Fall through.
return 0;
}
} else return 0;
return 0;
}
CAmount GetOnePriceInformation(std::string &price, std::string &signature, CAmount &secondprice)
{
CAmount res = 0;
int size = exchanges.size();
int count = 0;
while (res <= 0 && count < size*4) {
int i = rand() % size;
//get the i. element of exchanges
std::set<std::string>::iterator it = exchanges.begin();
std::advance(it, i);
std::string ex = *it;
res = GetPriceInformationFromWebserver(ex, price, signature, secondprice);
count++;
}
return res;
}
int GetPriceServerCount()
{
return exchanges.size();
}
std::string GetPriceServerName(int i)
{
std::string outstr = "";
if (i >= 0 && i < exchanges.size())
{
//get the i. element of exchanges
std::set<std::string>::iterator it = exchanges.begin();
std::advance(it, i);
outstr = *it;
} else outstr = "FAILED.";
return outstr;
}
std::string CheckPriceServer(int i)
{
std::string outstr = "";
std::string price;
std::string signature;
if (i >= 0 && i < exchanges.size())
{
//get the i. element of exchanges
std::set<std::string>::iterator it = exchanges.begin();
std::advance(it, i);
std::string ex = *it;
int64_t nTime1 = GetTimeMicros();
std::string price, signature;
CAmount secondprice;
GetPriceInformationFromWebserver(ex, price, signature, secondprice);
bool found = false;
CAmount price1, price2;
if (IsHex(price)) {
std::vector<unsigned char> txData(ParseHex(price));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
CPriceInfo nPriceInfo;
ssData >> nPriceInfo;
if (nPriceInfo.priceCount >= 2 && nPriceInfo.prices[0] > 0 && nPriceInfo.prices[1] > 0) {
price1 = nPriceInfo.prices[0];
price2 = nPriceInfo.prices[1];
found = true;
}
} catch (const std::exception&) {
// Fall through.
}
}
if (!found)
{
outstr += "FAILED ( " + std::to_string( ( GetTimeMicros()- nTime1 ) / 1000 ) + "ms ).";
} else
{
outstr += "SUCCESSFUL ( " + FormatMoney(price1) + "; " + FormatMoney(price2) + "; " + std::to_string( ( GetTimeMicros()- nTime1 ) / 1000 ) + "ms ).";
}
} else outstr = "FAILED.";
return outstr;
}
CAmount GetPriceInformation(std::string &price, std::string &signature, std::string &price2, std::string &signature2, std::string &price3, std::string &signature3)
{
CAmount res = 0;
int size = exchanges.size();
int count = 0;
int i1 = 0;
int i2 = 0;
while (res <= 0 && count < size*4) {
int i = rand() % size;
i1 = i;
//get the i. element of exchanges
std::set<std::string>::iterator it = exchanges.begin();
std::advance(it, i);
std::string ex = *it;
CAmount secondprice;
res = GetPriceInformationFromWebserver(ex, price, signature, secondprice);
count++;
}
count = 0;
res = 0;
while (res <= 0 && count < size*4) {
int i = 0;
do {
i = rand() % size;
} while (i == i1);
i2 = i;
//get the i. element of exchanges
std::set<std::string>::iterator it = exchanges.begin();
std::advance(it, i);
std::string ex = *it;
CAmount secondprice;
res = GetPriceInformationFromWebserver(ex, price2, signature2, secondprice);
count++;
}
count = 0;
res = 0;
while (res <= 0 && count < size*4) {
int i = 0;
do {
i = rand() % size;
} while (i == i1 || i == i2);
//get the i. element of exchanges
std::set<std::string>::iterator it = exchanges.begin();
std::advance(it, i);
std::string ex = *it;
CAmount secondprice;
res = GetPriceInformationFromWebserver(ex, price3, signature3, secondprice);
count++;
}
return res;
}
bool AddPriceInformation(CBlock *pblock)
{
std::string price="";
std::string signature="";
std::string price2="";
std::string signature2="";
std::string price3="";
std::string signature3="";
if (GetPriceInformation(price, signature, price2, signature2, price3, signature3) <= 0) {
return 0;
}
if (IsHex(price)) {
std::vector<unsigned char> txData(ParseHex(price));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> pblock->nPriceInfo;
} catch (const std::exception&) {
// Fall through.
return false;
}
} else return false;
pblock->priceSig = ParseHex(signature);
if (IsHex(price2)) {
std::vector<unsigned char> txData(ParseHex(price2));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> pblock->nPriceInfo2;
} catch (const std::exception&) {
// Fall through.
return false;
}
} else return false;
pblock->priceSig2 = ParseHex(signature2);
if (IsHex(price3)) {
std::vector<unsigned char> txData(ParseHex(price3));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> pblock->nPriceInfo3;
} catch (const std::exception&) {
// Fall through.
return false;
}
} else return false;
pblock->priceSig3 = ParseHex(signature3);
return true;
}
bool AddPriceInformation(CBlockHeader *pblock)
{
std::string price="";
std::string signature="";
std::string price2="";
std::string signature2="";
std::string price3="";
std::string signature3="";
if (GetPriceInformation(price, signature, price2, signature2, price3, signature3) <= 0) {
return 0;
}
if (IsHex(price)) {
std::vector<unsigned char> txData(ParseHex(price));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> pblock->nPriceInfo;
} catch (const std::exception&) {
// Fall through.
return false;
}
} else return false;
pblock->priceSig = ParseHex(signature);
if (IsHex(price2)) {
std::vector<unsigned char> txData(ParseHex(price2));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> pblock->nPriceInfo2;
} catch (const std::exception&) {
// Fall through.
return false;
}
} else return false;
pblock->priceSig2 = ParseHex(signature2);
if (IsHex(price3)) {
std::vector<unsigned char> txData(ParseHex(price3));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> pblock->nPriceInfo3;
} catch (const std::exception&) {
// Fall through.
return false;
}
} else return false;
pblock->priceSig3 = ParseHex(signature3);
return true;
}
CAmount GetCachedPriceInformation(uint64_t cachetime, CAmount &secondpricereturn)
{
std::string price, signature;
CAmount secondprice = 0;
if (!haspriceinfo || GetTimeMillis() > pricetime + cachetime) {
CAmount tempprice = GetOnePriceInformation(price, signature, secondprice);
if (tempprice != 0) {
pricecache = tempprice;
pricecache2 = secondprice;
pricetime = GetTimeMillis();
haspriceinfo = true;
}
}
secondpricereturn = pricecache2;
return pricecache;
}
bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
{
// TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
return false;
if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
return false;
return true;
}
// Perform transaction-level checks before adding to block:
// - transaction finality (locktime)
// - premature witness (in case segwit transactions are added to mempool before
// segwit activation)
bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
{
for (const CTxMemPool::txiter it : package) {
if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
return false;
if (!fIncludeWitness && it->GetTx().HasWitness())
return false;
}
return true;
}
void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
{
pblock->vtx.emplace_back(iter->GetSharedTx());
pblocktemplate->vTxFees.push_back(iter->GetFee());
pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
nBlockWeight += iter->GetTxWeight();
++nBlockTx;
nBlockSigOpsCost += iter->GetSigOpCost();
nFees += iter->GetFee();
inBlock.insert(iter);
bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
if (fPrintPriority) {
LogPrintf("fee %s txid %s\n",
CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
iter->GetTx().GetHash().ToString());
}
}
int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
indexed_modified_transaction_set &mapModifiedTx)
{
int nDescendantsUpdated = 0;
for (const CTxMemPool::txiter it : alreadyAdded) {
CTxMemPool::setEntries descendants;
mempool.CalculateDescendants(it, descendants);
// Insert all descendants (not yet in block) into the modified set
for (CTxMemPool::txiter desc : descendants) {
if (alreadyAdded.count(desc))
continue;
++nDescendantsUpdated;
modtxiter mit = mapModifiedTx.find(desc);
if (mit == mapModifiedTx.end()) {
CTxMemPoolModifiedEntry modEntry(desc);
modEntry.nSizeWithAncestors -= it->GetTxSize();
modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
mapModifiedTx.insert(modEntry);
} else {
mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
}
}
}
return nDescendantsUpdated;
}
// Skip entries in mapTx that are already in a block or are present
// in mapModifiedTx (which implies that the mapTx ancestor state is
// stale due to ancestor inclusion in the block)
// Also skip transactions that we've already failed to add. This can happen if
// we consider a transaction in mapModifiedTx and it fails: we can then
// potentially consider it again while walking mapTx. It's currently
// guaranteed to fail again, but as a belt-and-suspenders check we put it in
// failedTx and avoid re-evaluation, since the re-evaluation would be using
// cached size/sigops/fee values that are not actually correct.
bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
{
assert (it != mempool.mapTx.end());
return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
}
void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
{
// Sort package by ancestor count
// If a transaction A depends on transaction B, then A's ancestor count
// must be greater than B's. So this is sufficient to validly order the
// transactions for block inclusion.
sortedEntries.clear();
sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
}
// This transaction selection algorithm orders the mempool based
// on feerate of a transaction including all unconfirmed ancestors.
// Since we don't remove transactions from the mempool as we select them
// for block inclusion, we need an alternate method of updating the feerate
// of a transaction with its not-yet-selected ancestors as we go.
// This is accomplished by walking the in-mempool descendants of selected
// transactions and storing a temporary modified state in mapModifiedTxs.
// Each time through the loop, we compare the best transaction in
// mapModifiedTxs with the next transaction in the mempool to decide what
// transaction package to work on next.
void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated)
{
// mapModifiedTx will store sorted packages after they are modified
// because some of their txs are already in the block
indexed_modified_transaction_set mapModifiedTx;
// Keep track of entries that failed inclusion, to avoid duplicate work
CTxMemPool::setEntries failedTx;
// Start by adding all descendants of previously added txs to mapModifiedTx
// and modifying them for their already included ancestors
UpdatePackagesForAdded(inBlock, mapModifiedTx);
CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
CTxMemPool::txiter iter;
// Limit the number of attempts to add transactions to the block when it is
// close to full; this is just a simple heuristic to finish quickly if the
// mempool has a lot of entries.
const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
int64_t nConsecutiveFailed = 0;
while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
{
// First try to find a new transaction in mapTx to evaluate.
if (mi != mempool.mapTx.get<ancestor_score>().end() &&
SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
++mi;
continue;
}
// Now that mi is not stale, determine which transaction to evaluate:
// the next entry from mapTx, or the best from mapModifiedTx?
bool fUsingModified = false;
modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
if (mi == mempool.mapTx.get<ancestor_score>().end()) {
// We're out of entries in mapTx; use the entry from mapModifiedTx
iter = modit->iter;
fUsingModified = true;
} else {
// Try to compare the mapTx entry to the mapModifiedTx entry
iter = mempool.mapTx.project<0>(mi);
if (modit != mapModifiedTx.get<ancestor_score>().end() &&
CompareTxMemPoolEntryByAncestorFee()(*modit, CTxMemPoolModifiedEntry(iter))) {
// The best entry in mapModifiedTx has higher score
// than the one from mapTx.
// Switch which transaction (package) to consider
iter = modit->iter;
fUsingModified = true;
} else {
// Either no entry in mapModifiedTx, or it's worse than mapTx.
// Increment mi for the next loop iteration.
++mi;
}
}
// We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
// contain anything that is inBlock.
assert(!inBlock.count(iter));
uint64_t packageSize = iter->GetSizeWithAncestors();
CAmount packageFees = iter->GetModFeesWithAncestors();
int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
bool isnick = iter->IsNicknameTx();
if (fUsingModified) {
packageSize = modit->nSizeWithAncestors;
packageFees = modit->nModFeesWithAncestors;
packageSigOpsCost = modit->nSigOpCostWithAncestors;
isnick = modit->IsNicknameTx();
}
if (!isnick && packageFees < blockMinFeeRate.GetFee(packageSize)) {
// Everything else we might consider has a lower fee rate
return;
}
if (!TestPackage(packageSize, packageSigOpsCost)) {
if (fUsingModified) {
// Since we always look at the best entry in mapModifiedTx,
// we must erase failed entries so that we can consider the
// next best entry on the next loop iteration
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
++nConsecutiveFailed;
if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
nBlockMaxWeight - 4000) {
// Give up if we're close to full and haven't succeeded in a while
break;
}
continue;
}
CTxMemPool::setEntries ancestors;
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
onlyUnconfirmed(ancestors);
ancestors.insert(iter);
// Test if all tx's are Final
if (!TestPackageTransactions(ancestors)) {
if (fUsingModified) {
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
continue;
}
// This transaction will make it in; reset the failed counter.
nConsecutiveFailed = 0;
// Package can be added. Sort the entries in a valid order.
std::vector<CTxMemPool::txiter> sortedEntries;
SortForBlock(ancestors, sortedEntries);
for (size_t i=0; i<sortedEntries.size(); ++i) {
AddToBlock(sortedEntries[i]);
// Erase from the modified set, if present
mapModifiedTx.erase(sortedEntries[i]);
}
++nPackagesSelected;
// Update transactions that depend on each of these
nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
}
}
void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
CMutableTransaction txCoinbase(*pblock->vtx[0]);
txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
assert(txCoinbase.vin[0].scriptSig.size() <= 100);
pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
}
static bool ProcessBlockFound(const CBlock* pblock, const CChainParams& chainparams)
{
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
return error("BitCashMiner: generated block is stale");
}
// Inform about the new block
// GetMainSignals().BlockFound(pblock->GetHash());
// Process this block the same as if we had received it from another node
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
if (!ProcessNewBlock(chainparams, shared_pblock, true, nullptr, false))
return error("BitCashMiner: ProcessNewBlock, block not accepted");
return true;
}
struct MinerContext {
std::atomic<bool>& alive;
int pow_threads;
int threads_number;
int nonces_per_thread;
const CChainParams& chainparams;
interfaces::Wallet* iwallet;
CWallet* wallet;
bool useinterface;
ctpl::thread_pool* pool;
int gpuid;
bool selectgpucpu;
bool gpumining;
};
bool mineriswaitingforblockdownload = false;
void MinerWorker(int thread_id, MinerContext& ctx)
{
auto start_nonce = thread_id * ctx.nonces_per_thread;
unsigned int nExtraNonce = 0;
while (ctx.alive) {
if (ctx.chainparams.MiningRequiresPeers()) {
// Busy-wait for the network to come online so we don't waste
// time mining n an obsolete chain. In regtest mode we expect
// to fly solo.
if (!g_connman) {
throw std::runtime_error(
"Peer-to-peer functionality missing or disabled");
}
mineriswaitingforblockdownload = true;
do {
bool fvNodesEmpty =
g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0;
if (!fvNodesEmpty && !IsInitialBlockDownload())
break;
g_connman->ResetMiningStats();
MilliSleep(1000);
} while (ctx.alive);
mineriswaitingforblockdownload = false;
}
if(g_connman) {
g_connman->InitMiningStats();
}
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrev = chainActive.Tip();
std::unique_ptr<CBlockTemplate> pblocktemplate{
BlockAssembler(Params()).CreateNewBlock(ctx.iwallet,ctx.wallet,ctx.useinterface)};
if (!pblocktemplate.get()) {
LogPrintf(
"Error in BitCash Miner: Keypool ran out, please call "
"keypoolrefill before restarting the mining thread\n");
return;
}
CBlock* pblock = &pblocktemplate->block;
assert(pblock);
pblock->nNonce = start_nonce;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
/* LogPrintf(
"%d: Running BitCash Miner with %u transactions "
"in block (%u bytes)\n",
thread_id,
pblock->vtx.size(),
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));*/
//
// Search
//
int64_t nStart = GetTimeMillis();
int graphs_checked = 0;
int cycles_found = 0;
arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
uint256 hash;
std::set<uint32_t> cycle;
// Check if something found
graphs_checked++;
bool cycle_found = false;
unsigned int nMaxTries = 1000;
while (nMaxTries > 0 && ctx.alive) {
cycles_found++;
if (CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus()))
{
LogPrintf("%d: BitCash Miner:\n", thread_id);
LogPrintf(
"\n\n\nproof-of-work found within %8.3f seconds \n"
"\tblock hash: %s\n\tnonce: %d\n\ttarget: %s\n\n\n",
static_cast<double>(GetTimeMillis() - nStart) / 1e3,
pblock->GetHash().GetHex(),
pblock->nNonce,
hashTarget.GetHex());
if (ProcessBlockFound(pblock, ctx.chainparams)) minedcoins+=19350000000;
// In regression test mode, stop mining after a block is found.
if (ctx.chainparams.MineBlocksOnDemand())
throw boost::thread_interrupted();
break;
}
graphs_checked++;
++pblock->nNonce;
--nMaxTries;
if (pblock->nNonce % ctx.nonces_per_thread == 0) {
pblock->nNonce += ctx.nonces_per_thread * (ctx.threads_number - 1);
}
triedoneproofofwork = true;
if(cycle_found) {
cycles_found++;
}
if (ctx.alive && g_connman) {
g_connman->AddCheckedGraphs(graphs_checked);
graphs_checked=0;
g_connman->AddFoundCycles(cycles_found);
cycles_found=0;
}
// Check for stop or if block needs to be rebuilt
if (!ctx.alive) {
break;
}
// Regtest mode doesn't require peers
if ((!g_connman || g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0) &&
ctx.chainparams.MiningRequiresPeers()) {
break;
}
if (pblock->nNonce >= MAX_NONCE) {
break;
}
if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast &&
(GetTimeMillis() - nStart) / 1e3 > /*ctx.chainparams.MininBlockStaleTime()*/35) {
break;
}
if (pindexPrev != chainActive.Tip()) {
LogPrintf("%d: Active chain tip changed. Breaking block lookup\n", thread_id);
break;
}
// Update nTime every few seconds
if (UpdateTime(pblock, ctx.chainparams.GetConsensus(), pindexPrev) < 0) {
// Recreate the block if the clock has run backwards,
// so that we can use the correct time.
break;
}
if (ctx.chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) {
// Changing pblock->nTime can change work required on testnet:
hashTarget.SetCompact(pblock->nBits);
}
pblock->nNonce++;
if (pblock->nNonce % ctx.nonces_per_thread == 0) {
pblock->nNonce += ctx.nonces_per_thread * (ctx.threads_number - 1);
}
}
if (ctx.alive && g_connman) {
g_connman->AddCheckedGraphs(graphs_checked);
g_connman->AddFoundCycles(cycles_found);
}
}
LogPrintf("BitCash Miner pool #%d terminated\n", thread_id);
}
bool isgpumining= true;
void static BitCashMiner(
interfaces::Wallet* iwallet,
CWallet* wallet,
bool useinterface,
const CChainParams& chainparams,
int pow_threads,
int bucket_size,
int bucket_threads,
bool selectgpucpu,
int gpuid
)
{
// assert(coinbase_script);
RenameThread("bitcash-miner");
if (bucket_threads < 1) {
bucket_threads = 1;
}
if (bucket_size == 0) {
bucket_size = MAX_NONCE / bucket_threads;
}
ctpl::thread_pool pool(bucket_threads + bucket_threads * pow_threads);
std::atomic<bool> alive{true};
try {
LogPrintf("Running BitCash Miner with %d pow threads, %d nonces per bucket and %d buckets in parallel.\n", pow_threads, bucket_size, bucket_threads);
for (int t = 0; t < bucket_threads; t++) {
MinerContext ctx{
alive,
pow_threads,
bucket_threads,
bucket_size,
chainparams,
iwallet,
wallet,
useinterface,
&pool,
gpuid+t,
selectgpucpu,
isgpumining
};
pool.push(MinerWorker, ctx);
}
while (true) {
boost::this_thread::interruption_point();
}
} catch (const boost::thread_interrupted&) {
LogPrintf("BitCash Miner terminated\n");
alive = false;
pool.stop();
throw;
} catch (const std::runtime_error& e) {
LogPrintf("BitCash Miner runtime error: %s\n", e.what());
gArgs.ForceSetArg("-mine", 0);
pool.stop();
return;
}
}
void GenerateBitCash(interfaces::Wallet* iwallet, CWallet* wallet, bool useinterface, bool mine, int pow_threads, int bucket_size, int bucket_threads, const CChainParams& chainparams, int gpuid, bool selectgpucpu, bool gpumining)
{
static boost::thread* minerThread = nullptr;
triedoneproofofwork = false;
if (pow_threads < 0) {
if (trygpumining) {
//1 Thread for GPU mining
pow_threads = 1;
if (bucket_threads<=0) bucket_threads = 1;
} else {
pow_threads = std::thread::hardware_concurrency() / 2;
bucket_threads = 2;
}
}
if (minerThread != nullptr) {
minerThread->interrupt();
delete minerThread;
minerThread = nullptr;
}
if (pow_threads == 0 || bucket_threads == 0 || !mine) {
if(g_connman) {
g_connman->ResetMiningStats();
}
return;
}
gpuminingfailed = false;
isgpumining = gpumining;
minerThread = new boost::thread(
&BitCashMiner,
iwallet,
wallet,
useinterface,
chainparams,
pow_threads,
bucket_size,
bucket_threads, selectgpucpu, gpuid);
}
| 35.317903 | 229 | 0.625072 | [
"vector"
] |
54d1311e53b5608db9746f4bc0dfba4a3bfefec7 | 535 | cpp | C++ | 06_TessellateTeapot/TeapotPatch.cpp | techlabxe/vulkan_book_3 | 039e6de75f5513155f3dd86321eec4cb4f10bcb3 | [
"CC-BY-3.0"
] | 2 | 2020-05-13T13:00:03.000Z | 2021-04-13T02:47:10.000Z | 06_TessellateTeapot/TeapotPatch.cpp | techlabxe/vulkan_book_3 | 039e6de75f5513155f3dd86321eec4cb4f10bcb3 | [
"CC-BY-3.0"
] | null | null | null | 06_TessellateTeapot/TeapotPatch.cpp | techlabxe/vulkan_book_3 | 039e6de75f5513155f3dd86321eec4cb4f10bcb3 | [
"CC-BY-3.0"
] | 3 | 2020-05-13T13:00:07.000Z | 2022-03-12T18:35:56.000Z | #include "TeapotPatch.h"
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <Windows.h>
using namespace TeapotPatch;
#include "TeapotPatch2.inc"
std::vector<vec3> TeapotPatch::GetTeapotPatchPoints()
{
std::vector<vec3> controls(teapot_points, teapot_points + _countof(teapot_points));
return controls;
}
std::vector<unsigned int> TeapotPatch::GetTeapotPatchIndices()
{
std::vector<unsigned int> indices(teapot_patches, teapot_patches + _countof(teapot_patches));
return indices;
}
| 22.291667 | 96 | 0.734579 | [
"vector"
] |
54d42024fe960939d7ac261da01ec2c89a5143a3 | 14,179 | cpp | C++ | src/Synthesis/sat_swap_synth.cpp | paniash/tweedledum | fe997bea3413a02033d76b20034e3a24b840bffb | [
"MIT"
] | 76 | 2018-07-21T08:12:17.000Z | 2022-01-25T06:22:25.000Z | src/Synthesis/sat_swap_synth.cpp | paniash/tweedledum | fe997bea3413a02033d76b20034e3a24b840bffb | [
"MIT"
] | 44 | 2018-10-26T10:44:39.000Z | 2022-02-07T01:07:38.000Z | src/Synthesis/sat_swap_synth.cpp | paniash/tweedledum | fe997bea3413a02033d76b20034e3a24b840bffb | [
"MIT"
] | 23 | 2018-09-27T15:28:48.000Z | 2022-03-07T12:21:37.000Z | /*------------------------------------------------------------------------------
| Part of Tweedledum Project. This file is distributed under the MIT License.
| See accompanying file /LICENSE for details.
*-----------------------------------------------------------------------------*/
#include "tweedledum/Synthesis/sat_swap_synth.h"
#include "tweedledum/IR/Circuit.h"
#include "tweedledum/Operators/Standard/Swap.h"
#include "tweedledum/Target/Device.h"
#include "tweedledum/Utils/Hash.h"
#include <bill/sat/cardinality.hpp>
#include <bill/sat/solver.hpp>
#include <nlohmann/json.hpp>
#include <vector>
namespace tweedledum {
namespace {
template<typename Cnf>
class SatSwapper {
using map_type = std::vector<uint32_t>;
using Swap = std::pair<uint32_t, uint32_t>;
using LBool = bill::lbool_type;
using Lit = bill::lit_type;
using Var = bill::var_type;
public:
SatSwapper(Device const& graph, std::vector<uint32_t> const& init_cfg,
std::vector<uint32_t> const& final_cfg, Cnf& cnf_builder,
nlohmann::json const& config)
: device_(graph)
, init_cfg_(init_cfg)
, init_t2v_(init_cfg.size(), 0)
, final_cfg_(final_cfg)
, is_activation_() // TODO: better naming!
, num_moments_(0)
, offset_(num_vertices() * num_vertices() + num_edges())
, opt_num_swaps_(true)
, cnf_builder_(cnf_builder)
, vertice_edges_map_(num_vertices())
{
for (uint32_t i = 0; i < init_cfg_.size(); ++i) {
init_t2v_[init_cfg[i]] = i;
}
for (uint32_t i = 0; i < num_edges(); ++i) {
auto& [u, v] = device_.edge(i);
vertice_edges_map_[u].emplace_back(i);
vertice_edges_map_[v].emplace_back(i);
}
auto cfg = config.find("sat_swap_synth");
if (cfg != config.end()) {
if (cfg->contains("opt_goal")) {
opt_num_swaps_ = !(cfg->at("opt_goal") == "depth");
}
}
pre_process();
}
void encode()
{
initial_moment();
// Assume initial configuration
for (uint32_t i = 0; i < init_cfg_.size(); ++i) {
Lit lit(
token_vertice_var(0, init_cfg_[i], i), bill::positive_polarity);
cnf_builder_.add_clause(lit);
}
for (uint32_t i = 0; i < min_num_moments_; ++i) {
add_moment();
}
}
std::vector<Lit> encode_assumptions()
{
std::vector<Lit> assumptions;
// Assume initial configuration
// for (uint32_t i = 0; i < init_cfg_.size(); ++i) {
// sat::Var var = token_vertice_var(0, init_cfg_[i], i);
// assumptions.emplace_back(var, sat::positive_polarity);
// }
// Assume final configuration
for (uint32_t i = 0; i < final_cfg_.size(); ++i) {
Var var = token_vertice_var(num_moments_ - 1, final_cfg_[i], i);
assumptions.emplace_back(var, bill::positive_polarity);
}
return assumptions;
}
void encode_new_moment()
{
add_moment();
if (opt_num_swaps_) {
add_moment();
}
}
std::vector<Swap> decode(std::vector<LBool> const& model)
{
std::vector<Swap> swaps;
for (uint32_t moment = 0; moment < num_moments_ - 1; ++moment) {
for (uint32_t edge = 0; edge < num_edges(); ++edge) {
Var var = swap_var(moment, edge);
if (model.at(var) == LBool::true_) {
swaps.push_back(device_.edge(edge));
}
}
}
return swaps;
}
private:
uint32_t compute_inv(std::vector<uint32_t> const& permutation)
{
uint32_t inv = 0;
for (uint32_t i = 0; i < permutation.size() - 1; ++i) {
for (uint32_t j = i + 1; j < permutation.size(); ++j) {
if (permutation.at(i) > permutation.at(j)) {
inv = inv + 1;
}
}
}
return inv;
}
void pre_process()
{
uint32_t max_distance = 0;
uint32_t sum_distance = 0;
for (uint32_t k = 0; k < init_cfg_.size(); ++k) {
if (init_cfg_[k] != final_cfg_[k]) {
auto it =
std::find(final_cfg_.begin(), final_cfg_.end(), init_cfg_[k]);
uint32_t idx = std::distance(final_cfg_.begin(), it);
uint32_t dist = device_.distance(k, idx);
sum_distance += dist;
max_distance = std::max(max_distance, dist);
}
}
// When optimizing for swap number, each moment hold only one SWAP
if (opt_num_swaps_) {
// sgn = false (odd), true (even)
bool sgn_init = compute_inv(init_cfg_) & 1;
bool sgn_final = compute_inv(final_cfg_) & 1;
min_num_moments_ = std::ceil(sum_distance / 2.0);
// If the minimum number of moments is odd, but the sgn of
// the permutations is the same, we add one, as we know that the
// solution must have an even number of swaps.
//
// If the minimum number of moments is even, but the sgn of the
// permutations are different, then we also need to add one.
if (min_num_moments_ & 1) {
if (sgn_init == sgn_final) {
++min_num_moments_;
}
} else {
if (sgn_init != sgn_final) {
++min_num_moments_;
}
}
} else {
min_num_moments_ = max_distance;
}
}
uint32_t num_edges() const
{
return device_.num_edges();
}
uint32_t num_vertices() const
{
return device_.num_qubits();
}
Var token_vertice_var(uint32_t moment, uint32_t token, uint32_t vertice)
{
return moment * offset_ + token * num_vertices() + vertice;
}
Var swap_var(uint32_t moment, uint32_t edge)
{
return moment * offset_ + num_vertices() * num_vertices() + edge;
}
void create_token_vertice_variables()
{
// Create token <-> vertice variables
// Make sure that each token is assign to only one vertice
std::vector<Var> variables;
for (uint32_t token = 0; token < num_vertices(); ++token) {
for (uint32_t vertice = 0; vertice < num_vertices(); ++vertice) {
if (device_.distance(vertice, init_t2v_[token])
<= (num_moments_ + 1)) {
variables.emplace_back(cnf_builder_.add_variable());
is_activation_.emplace_back(0);
continue;
}
cnf_builder_.add_clause(
Lit(cnf_builder_.add_variable(), bill::negative_polarity));
is_activation_.emplace_back(1);
}
bill::at_least_one(variables, cnf_builder_);
bill::at_most_one_pairwise(variables, cnf_builder_);
variables.clear();
}
// Make sure that each vertice is assign at only one token
for (uint32_t vertice = 0; vertice < num_vertices(); ++vertice) {
for (uint32_t token = 0; token < num_vertices(); ++token) {
if (device_.distance(vertice, init_t2v_[token])
<= (num_moments_ + 1)) {
variables.emplace_back(
token_vertice_var(num_moments_, token, vertice));
}
}
bill::at_least_one(variables, cnf_builder_);
bill::at_most_one_pairwise(variables, cnf_builder_);
variables.clear();
}
}
void initial_moment()
{
create_token_vertice_variables();
++num_moments_;
}
void add_moment()
{
// Create swap variables
std::vector<Var> variables;
for (uint32_t i = 0; i < num_edges(); ++i) {
variables.emplace_back(cnf_builder_.add_variable());
is_activation_.emplace_back(0);
}
if (opt_num_swaps_) {
at_most_one_pairwise(variables, cnf_builder_);
if (num_moments_ > 1) {
symmetry_break(num_moments_ - 2, num_moments_ - 1);
}
}
variables.clear();
// Create the token <-> vertice variables for the new moment
create_token_vertice_variables();
// Create the swaps contraints
// *) Condition 1:
assert(is_activation_.size() == cnf_builder_.num_variables());
std::vector<Lit> clause;
for (uint32_t vertice = 0; vertice < num_vertices(); ++vertice) {
for (uint32_t token = 0; token < num_vertices(); ++token) {
Var prev_var =
token_vertice_var(num_moments_ - 1, token, vertice);
Var current_var =
token_vertice_var(num_moments_, token, vertice);
if (is_activation_[current_var]) {
continue;
}
for (uint32_t edge : vertice_edges_map_[vertice]) {
Var edge_var = swap_var(num_moments_ - 1, edge);
clause.clear();
clause.emplace_back(current_var, bill::negative_polarity);
clause.emplace_back(prev_var, bill::negative_polarity);
clause.emplace_back(edge_var, bill::negative_polarity);
cnf_builder_.add_clause(clause);
}
}
}
// *) Condition 2:
for (uint32_t vertice = 0; vertice < device_.num_qubits(); ++vertice) {
for (uint32_t token = 0; token < device_.num_qubits(); ++token) {
Var prev_var =
token_vertice_var(num_moments_ - 1, token, vertice);
Var current_var =
token_vertice_var(num_moments_, token, vertice);
std::vector<Var> edge_vars;
std::vector<Lit> edge_lits;
std::vector<Lit> token_lits;
for (uint32_t edge : vertice_edges_map_[vertice]) {
edge_vars.emplace_back(swap_var(num_moments_ - 1, edge));
edge_lits.emplace_back(
edge_vars.back(), bill::positive_polarity);
auto [u, v] = device_.edge(edge);
if (u != vertice) {
token_lits.emplace_back(
token_vertice_var(num_moments_ - 1, token, u),
bill::positive_polarity);
} else {
token_lits.emplace_back(
token_vertice_var(num_moments_ - 1, token, v),
bill::positive_polarity);
}
}
if (!opt_num_swaps_) {
at_most_one_pairwise(edge_vars, cnf_builder_);
}
if (is_activation_[current_var]) {
continue;
}
clause = edge_lits;
clause.emplace_back(current_var, bill::negative_polarity);
clause.emplace_back(prev_var, bill::positive_polarity);
assert(edge_lits.size() == token_lits.size());
for (uint32_t i = 0; i < (1u << edge_lits.size()); ++i) {
for (uint32_t j = i, k = 0; j; j >>= 1, ++k) {
if (j & 1) {
clause[k] = token_lits[k];
} else {
clause[k] = edge_lits[k];
}
}
cnf_builder_.add_clause(clause);
}
}
}
++num_moments_;
}
// I don't think this is complete
void symmetry_break(uint32_t prev_moment, uint32_t current_moment)
{
std::vector<Lit> clause;
for (uint32_t i = 0; i < device_.num_edges(); ++i) {
auto& [u_i, v_i] = device_.edge(i);
for (uint32_t j = i + 1; j < device_.num_edges(); ++j) {
auto& [u_j, v_j] = device_.edge(j);
if (u_i == u_j || u_i == v_j || v_i == u_j || v_i == v_j) {
continue;
}
clause.emplace_back(
swap_var(prev_moment, j), bill::negative_polarity);
clause.emplace_back(
swap_var(current_moment, j), bill::negative_polarity);
cnf_builder_.add_clause(clause);
clause.clear();
}
}
}
Device const& device_;
std::vector<uint32_t> init_cfg_; // vertice -> token
std::vector<uint32_t> init_t2v_; // vertice <- token
std::vector<uint32_t> final_cfg_; // vertice -> token
uint32_t min_num_moments_;
// Encoded problem
std::vector<uint8_t> is_activation_;
uint32_t num_moments_;
uint32_t offset_;
bool opt_num_swaps_;
Cnf& cnf_builder_;
// Auxiliary
// Maps which edeges as connected to a particular node.
std::vector<std::vector<uint32_t>> vertice_edges_map_;
};
} // namespace
Circuit sat_swap_synth(Device const& device,
std::vector<uint32_t> const& init_cfg, std::vector<uint32_t> const& final_cfg,
nlohmann::json const& config)
{
using Swap = std::pair<uint32_t, uint32_t>;
std::vector<Swap> swaps;
bill::solver solver;
SatSwapper encoder(device, init_cfg, final_cfg, solver, config);
encoder.encode();
do {
std::vector<bill::lit_type> assumptions = encoder.encode_assumptions();
solver.solve(assumptions);
bill::result result = solver.get_result();
if (result) {
swaps = encoder.decode(result.model());
break;
}
encoder.encode_new_moment();
} while (1);
Circuit circuit;
for (uint32_t i = 0u; i < device.num_qubits(); ++i) {
circuit.create_qubit();
}
for (auto [x, y] : swaps) {
circuit.apply_operator(Op::Swap(), {Qubit(x), Qubit(y)});
}
return circuit;
}
} // namespace tweedledum
| 35.896203 | 80 | 0.527259 | [
"vector",
"model"
] |
54d96cc07ac102befca559290d964e327a00c3d9 | 736 | cpp | C++ | cpp/011-020/Letter Combinations of a Phone Number.cpp | KaiyuWei/leetcode | fd61f5df60cfc7086f7e85774704bacacb4aaa5c | [
"MIT"
] | 150 | 2015-04-04T06:53:49.000Z | 2022-03-21T13:32:08.000Z | cpp/011-020/Letter Combinations of a Phone Number.cpp | yizhu1012/leetcode | d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7 | [
"MIT"
] | 1 | 2015-04-13T15:15:40.000Z | 2015-04-21T20:23:16.000Z | cpp/011-020/Letter Combinations of a Phone Number.cpp | yizhu1012/leetcode | d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7 | [
"MIT"
] | 64 | 2015-06-30T08:00:07.000Z | 2022-01-01T16:44:14.000Z | class Solution {
public:
vector<string> letterCombinations(string digits) {
string symbols[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> result;
if (digits.empty()) {
return result;
}
result.push_back("");
for (char ch : digits) {
int num = ch - '0';
vector<string> new_result;
for (const string& s : result) {
for (char symbol : symbols[num]) {
string tmp = s + symbol;
new_result.push_back(tmp);
}
}
result.swap(new_result);
}
return result;
}
};
| 26.285714 | 96 | 0.434783 | [
"vector"
] |
54e40e77524998395be2b4db2ca2d0894f8aa076 | 14,047 | cpp | C++ | master.cpp | umbax/HyGP_3_0 | 2cd156e3c3b1ab6a60aadfe4f774a9a8bb169589 | [
"Apache-2.0"
] | 3 | 2017-07-08T21:53:12.000Z | 2022-02-09T08:16:48.000Z | master.cpp | umbax/HyGP_3_0 | 2cd156e3c3b1ab6a60aadfe4f774a9a8bb169589 | [
"Apache-2.0"
] | null | null | null | master.cpp | umbax/HyGP_3_0 | 2cd156e3c3b1ab6a60aadfe4f774a9a8bb169589 | [
"Apache-2.0"
] | 1 | 2017-07-08T21:53:02.000Z | 2017-07-08T21:53:02.000Z | // Copyright 2016 Dr Umberto Armani
//
// 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 <iostream> // basic i/o commands: cout, cin, scientific, fixed, cerr
#include <iomanip> // manipulators (text format): setw
#include <string> // to manipulate strings (C++)
#include <cstring> // to manipulate strings (C) (strcpy, strcmp)
#include <cstdlib> // NULL, exit, EXIT_FAILURE
#include <cmath> // pow, sqrt
#include <algorithm> // max_element, min_element
#include <exception>
/// compatibility issues (Microsoft tempting to modify commands?):commented if under linux, uncommented under WINDOWS
//#define strdup _strdup
using namespace std;
// headers
#include "./genetic_code/classes/run_parameters.h"
#include "./genetic_code/classes/problem_definition.h"
#include "./genetic_code/read_input/read_file_new.h" // read test data not implemented yet in OpenMP version
#include "./genetic_code/input_checks/input_check.h"
#include "./genetic_code/classes/reporter.h"
#include "./genetic_code/classes/class_POPULATION.h"
// global variables - population purposes
//const double PI = 4.0*atan(1.0); // redefined in Val_type.h
//double MAX_VAL = 1.8e+19; // redefined in Val_type.h
//double MIN_VAL = 1.8e-19; // redefined in Val_type.h
// try! Simple way to make fdf_c able to detect the values of a few variables. Think about inserting fdf_c in class Population!!!
Population *Pop; // try! Simple way to make fdf_c able to get the values of the tree
int VERBOSE = 1; //set to 1 if you want to print on the screen all the comments! 0 for a "clean" and wordless execution...
// use: ./gp location/name_input location/name_output
int main (int argc, char *argv[])
{
// check the number of arguments
if (argc<3) {
cerr << "\nERROR!!! Too few arguments!!!" ;
cerr << "\nUSAGE: >> ./gp location/input_file existing_directory_output";
cerr << "\nExample: >> ./gp ./input/input_file.txt ./output\n";
exit(-1);
}
if (argc>4) {
cerr << "\nERROR!!! Too many arguments!!!" ;
cerr << "\nUSAGE: >> ./gp location/input_file location/test_data existing_directory_output";
cerr << "\nExample: >> ./gp ./input/input_file.txt ./input/test_data_file.txt ./output\n";
exit(-1);
}
string FILE_INPUT;
string FILE_TEST_DATA;
string DIR_OUTPUT;
FILE_TEST_DATA = "Not defined";
FILE_INPUT=argv[1];
if (argc == 3) {
DIR_OUTPUT=argv[2];
} else {
FILE_TEST_DATA=argv[2];
DIR_OUTPUT=argv[3];
}
cout << "\nNAME_INPUT = " << FILE_INPUT;
cout << "\nNAME_TEST_DATA = " << FILE_TEST_DATA;
cout << "\nNAME_OUTPUT = " << DIR_OUTPUT;
//presentation
printf("\n\n **************************** ");
printf("\n FIRST EXPERIMENTS IN GP ");
printf("\n ");
printf("\n by Umberto Armani ");
printf("\n **************************** ");
cout << "\n\nAvailable operations:";
cout << "\nBINARY: add , sub, mult, sdiv, spow";
cout << "\nUNARY: shift, neg, square, cube, exp, nxp, sin, cos, inv, abs, log, sinh, cosh, tanh, rectwave, hfreqsin";
cout << "\n(list updated 7/11/2020)";
cout << "\n\nATTENTION! If you use more than 15 unary operations or 7 binary operations";
cout << "\nincrease the size of u_func_list or b_func_list (see problem_definition.h)";
cout << "\n(FUTURE solution : use vectors to read primitives...)";
cout << endl;
//set the number of decimal figures.
cout.precision(5);
// other classes instantiations
Variable* Z; //to be included in ProblemDefinition...
RunParameters Mparam; // to distinguish it from parameters object in Population
ProblemDefinition Mprobl; // to distinguish it from problem object in Population
Reporter pop_reporter;
// read inputs
read_input_file(FILE_INPUT, &Mparam, &Mprobl); // also initialise parameters and problem objects
if (argc==4) read_test_data(FILE_TEST_DATA, &Mparam, &Mprobl);
// check for errors on the input parameter between parenthesis
input_check(&Mparam, &Mprobl);
// compute additional attributes or set up structures in Problem Definition (variables, for example)
// now all is done in read_input_file (but it's too messy there...)
Mprobl.compute_inputdata_stats();
// print to file input data statistics
const char* DIR_OUTPUT_c=DIR_OUTPUT.c_str(); //= new char [str.length()+1];
pop_reporter.inputdatastats2file(&Mprobl, DIR_OUTPUT_c);
//cin.get();
// show imported data (input parameters and input data)
Mparam.show(); // run hyperparameters
//Mprobl.show_all(); // input data matrix and other data
// to stop the execution
//cout << "Have a go?" << endl;
//cin.get();
// random value generator
if (Mparam.seed<0) {
// if seed = -1 use random seed (time)
time_t *tp = NULL; // seed the random value generator
srand((unsigned int) time (tp)); //to be used normally
Mparam.seed = time(tp); // attention! two runs that starts within 1 second have the same seed, so are identical!
cout << "\n\nSEED=-1 in input file: seed randomly generated = " << Mparam.seed << endl;
} else {
// if seed >0 use the value given in input file
srand(Mparam.seed);
cout << "\n\nused seed = " << Mparam.seed << endl;
}
// PARALLELISATION. FROM HERE ....
time_t start, finish;
double delta_t;
time(&start);
int elapsed_time;
//---------------------------------------------------------------------
// CREATE THE POPULATION (constructor called)
//---------------------------------------------------------------------
// initialise variables
Mprobl.initialise_variables(&Z, Mparam.max_n_periods);
//for (int k=0; k<Mprobl.get_n_var(); k++)
// cout << "\n v_list" << k << " = " << Mprobl.v_list[k];
// do you really need new? Maybe yes, for scope issues
Population *P = new Population(&Mparam, &Mprobl);
if (!P) {
cerr << "\nmain : Error creating population!!!\n";
exit(-1);
}
// pause execution
//cin.get(); // problem with int_rand in Population constructor
//as it's hard to pass Pop as a parameter to fdf_c__ through fortran functions, treat it as a global variable
Pop = P;
int n =Pop->parameters->nvar;
cout << "\nn= " << n;
// split the whole input dataset in k folds for cross validation
Mprobl.kfold_split(Mparam.crossvalidation); // test with 3 folds
///// INITIAL GENERATION (0) ///////////////////////////////////////
// trees before parameters insertion
printf ("\nInitialization of the population (generation 0)\n");
P->print_population_without_parameters(0);
/// split the data set in tuning set (data_tuning) and validation set (data_validation).
// See SPLIT and VALIDATING_LINES in input file
// this function will also allow to increase the number of fitness cases during the run...
// 23/5/2017 rewrite the split function to implement correctly the CROSSVALIDATION and the PRESS error calculation
// IMPORTANT! Check that the correct Sy is used in computing RMSE (note taken on 10/5/2014)
//P->split_data(&Mparam, &Mprobl, 0,1);
/////////// OTHER GENERATIONS ///////////////////////////////////////
int check_end = 0;
int last_gen=0;
for (int i=0; i<Mparam.G+1; i++) {
if (i) { //skip generation 0
// split the data for the current generation (this function will also allow to increase the number of fitness cases during the run...)
//P->split_data(i,G,split); // not used...
// GENETIC OPERATORS: sorting, reproduction, crossover, mutation, pruning
P->new_spawn(Mparam, Mparam.nfitcases,i);
}
// adjust aggregate fitness (F) weights
//if (i%2==0) P->adjust_Fweight(i);
// evaluate fitness function (in hybrid/memetic GP parameters are added and tuned first, then the evaluation is performed)
P->evaluate(i,Mparam.G);
// sort according to F (aggregate fitness F, not RMSE!) : VITAL! Both populations must be sorted, trees[] and complete_trees[]
P->sort(i,tree_comp_F);
// update the external archive made of the best individual - structure and complete tree (for PARAMETER INHERITANCE)
P->update_ext_archive();
// compute elapsed time
elapsed_time = (int)(P->compute_time(start, finish, &delta_t));
if (VERBOSE) {
// print elapsed time
cout << "\nElapsed time: " << elapsed_time << " sec"; //total seconds
// print out the best member - population WITHOUT parameters
P->print_population_without_parameters(i);
// print out the best member - population WITH parameters
P->print_population_with_parameters(i);
}
// compute statistical data relating to population (vital if data is shared through populations)
// IT's REALLY IMPORTANT that this function is executed after evaluate and sort,
// as evaluate uses statistical data referring to the previous generation
P->compute_statistics();
// evaluate termination condition
check_end=P->terminate(Mparam.threshold);
last_gen = i;
// PRINT TO FILE OPERATIONS (in case of crash, data is saved) -------------------------
cout << "\nPrint generation results to file...";
// write evolution statistical data to file "data_gp.txt"
pop_reporter.stats2file(&Mparam, P, DIR_OUTPUT, i, check_end);
// write target points (training set), best individual corresponding values and residuals to file "points_gp.txt"
pop_reporter.points2file(&Mparam, &Mprobl, P, DIR_OUTPUT, i, check_end, start, finish, delta_t, Mparam.seed);
// write best individual's expression as per aggregate value F (!!!) on training data set to "best_gp.txt"
pop_reporter.update_best2file_build(P, DIR_OUTPUT, i, check_end);
// write best-so-far individuals (elite or archive - first repr_tot individuals) on training data set to "latest_archive.txt"
pop_reporter.archive2file_build(P, DIR_OUTPUT, i, check_end);
// write no of tree evaluations at each generation to "n_tree_evaluations.txt"
pop_reporter.n_tree_eval2file(P, DIR_OUTPUT, i, check_end);
// write related to adaptive approach (eps_neutral, the constructive, destructive and neutral genetic operations rates, etc) to "adaptation_data.txt"
pop_reporter.adaptive_gen_ops_data2file(P, DIR_OUTPUT, i, check_end);
// write values of F (aggregate fitness) to file
pop_reporter.F_coefficients2file(P, DIR_OUTPUT, i, check_end);
cout << "OK";
// -------------------------------------------------------------------------------------
if (check_end)
break;
// update genetic operators rates (adaptive approach - can be turned on and off inside the function)
if (i) P->adapt_genetic_operators_rates();
}
// end evolution
//termination criterion (successful run) satisfied
if (check_end) {
cout << "Termination criterion satisfied (RMSE < " << Mparam.threshold << ")." << endl;
cout << "Possible solution: " << endl;
P->print_population_with_parameters(last_gen);
cout << "Check latest_archive.txt for solutions\n" << endl;
}
else {
P->print_population_with_parameters(last_gen);
}
// just for test
//P->get_tree_derivative_given_norm_vector(Mprobl, P->complete_trees[0]);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//---------------------------------------------------------------------
// END OPERATIONS
//---------------------------------------------------------------------
// write node statistics to file
pop_reporter.node_stats2file(&Mparam, P, DIR_OUTPUT);
// evaluate fitness (RMSE and R2) on test data set (only if test data has been provided)
if (argc==4) {
// show data_test
//cout << "problem->show_data_validation() : show current data_test :" << endl;
//P->problem->show_data_test();
// evaluate first repr_tot complete individuals on test data set provided by the user
P->evaluate_complete_trees_on_test_dataset(); // SET CORRECTLY Mprobl.data_test, n_test, Sy_test after implementing function to read test data set
// sort according to error (RMSE) - better not to use it to keep order and to recognise performance on building and test data sets...
//P->sort(last_gen,tree_comp_fitness); // non va: ordina in ordine decrescente e alcune volte pone a 0 RMSE e R2. Perché?
// find and print best individual on test data set as per RMSE (!!!!) to file "best_gp_TEST.txt"
pop_reporter.best2file_test(P, DIR_OUTPUT, last_gen);
// print archive evaluated on the test data set to file
pop_reporter.archive2file_test(P, DIR_OUTPUT, last_gen); // insert a function to order in rmse decreasing order, leaving however the name of the run
}
// free memory allocated to Population, as not used anymore (in the future declare statically P, as you will always need one population...)
delete P; // 4/10/21 stack smashing detected after calling ProblemDefinition destructor...
// PARALLELISATION ... TO HERE.
cout << "\n\n END" << endl;
return 0;
}
// DIFFERENT OPTIMISERS
//#include "./genetic code/SQP/MINL2.cpp" - only for optimizer translated in C++
//#include "./genetic code/SQP/TINL2_mod.cpp" - only for optimizer translated in C++
//for Andrey's method - TI0L2 and MI0L2 - IT WORKS PERFECTLY
#include "./genetic_code/SQP/MI0L2_c/fdf_c.cpp"
//for Umberto's method - TINL2 and MINL2 - WORKS?
//#include "./genetic code/SQP/fdfTINL2_c.cpp"
| 41.559172 | 152 | 0.654802 | [
"object"
] |
54e456ee3ac98d48067703cd29c0a5c531019778 | 632 | hpp | C++ | include/SimEngine/SmartThingSchedule.hpp | buzyaba/SimEngine | e5469f927154de43ea52ad74c0ca4a0af9a7b721 | [
"MIT"
] | 5 | 2019-10-21T11:38:56.000Z | 2020-05-30T04:50:50.000Z | include/SimEngine/SmartThingSchedule.hpp | buzyaba/SimEngine | e5469f927154de43ea52ad74c0ca4a0af9a7b721 | [
"MIT"
] | 2 | 2020-03-16T13:16:27.000Z | 2020-10-10T07:35:15.000Z | include/SimEngine/SmartThingSchedule.hpp | buzyaba/SimEngine | e5469f927154de43ea52ad74c0ca4a0af9a7b721 | [
"MIT"
] | 3 | 2019-10-10T15:10:57.000Z | 2020-02-14T13:11:50.000Z | #pragma once
#include <string>
#include <vector>
#include "SimEngine/SmartThing.h"
#include "../lib/pugixml/include/pugixml.hpp"
#include "SimEngine/common.h"
#include <stdexcept>
class TSmartThingSchedule {
public:
TSmartThingSchedule() = default;
TSmartThingSchedule(std::vector<TSmartThing*>& _things, std::string xmlName);
void UpdateThingsProperties(std::size_t time);
private:
void LoadXML(std::string xmlName);
std::int64_t GetTimePointIndex(size_t time);
std::vector<TSmartThing*> things;
std::vector<size_t> time_points;
std::vector<std::vector<std::vector<double>>> actuatorsValues;
bool created;
};
| 25.28 | 79 | 0.751582 | [
"vector"
] |
54e47a3e859b0c0437fcce1f4f6a84814927104b | 474 | cpp | C++ | examples/exporting/save/save_2.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | 2 | 2020-09-02T14:02:26.000Z | 2020-10-28T07:00:44.000Z | examples/exporting/save/save_2.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | null | null | null | examples/exporting/save/save_2.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | 2 | 2020-09-01T16:22:07.000Z | 2020-09-02T14:02:27.000Z | #include <matplot/matplot.h>
int main() {
using namespace matplot;
auto f = figure(true);
std::vector<double> x = {2, 4, 7, 2, 4, 5, 2, 5, 1, 4};
bar(x);
save("img/barchart_ps","postscript");
save("img/barchart_latex","epslatex");
/*
* Add to your latex document:
* \begin{figure}
* \input{Barchart_latex}
* \end{figure}
*/
save("img/barchart_gif","gif");
save("img/barchart_jpeg","jpeg");
return 0;
} | 19.75 | 59 | 0.561181 | [
"vector"
] |
54e723b2953bbfb9ae1c6bf3b3878868f0da48d5 | 3,951 | cpp | C++ | drl_fluid_film_python3/gym-film/gym_film/envs/simulation_solver/advect_in_time.cpp | vbelus/falling-liquid-film-drl | b2fe80ffecbb71afb0bef8ded0d47e823b283868 | [
"MIT"
] | 13 | 2019-12-03T11:54:39.000Z | 2022-02-03T17:44:19.000Z | drl_fluid_film_python3/gym-film/gym_film/envs/simulation_solver/advect_in_time.cpp | vbelus/falling-liquid-film-drl | b2fe80ffecbb71afb0bef8ded0d47e823b283868 | [
"MIT"
] | 4 | 2019-11-29T16:46:10.000Z | 2019-12-10T15:25:28.000Z | drl_fluid_film_python3/gym-film/gym_film/envs/simulation_solver/advect_in_time.cpp | vbelus/falling-liquid-film-drl | b2fe80ffecbb71afb0bef8ded0d47e823b283868 | [
"MIT"
] | 3 | 2019-12-04T12:39:09.000Z | 2022-02-25T03:17:00.000Z | #include <valarray>
#include "TVD3.h"
#include "advect_in_time.h"
#include <cassert>
#include "utils.h"
#include <vector>
#define MACRO_H_XX(i) ((h[i-1] + h[i+1] - 2.0 * h[i]) / dx / dx)
namespace ait
{
void advect_in_time(std::valarray<double> & h,
std::valarray<double> & q,
std::valarray<double> & noise,
unsigned int n_step,
double dx,
double dt,
double delta,
double & t,
int half_width_jet,
std::valarray<int> middle_jet,
std::valarray<double> jet_strength_old,
std::valarray<double> jet_strength_new,
int NUM) noexcept {
std::valarray<double> q_old (NUM);
std::valarray<double> h_old (NUM);
std::valarray<double> q2_h_x (NUM);
std::valarray<double> dh (NUM);
assert(h.size() == q.size());
assert(noise.size() == n_step);
double delta_5 = 5.0 * delta;
double q2_h_BC;
double crrt_dq;
double crrt_h_xxx;
double previous_h_xxx = 0;
unsigned int i_p_1;
double a[3] = {0.0, 0.25, 2.0/3.0};
double b[3] = {1.0, 0.25, 2.0/3.0};
double c[3] = {1.0, 0.75, 1.0/3.0};
double idx = 1.0/dx;
double normalisation_jet = 1.0 / static_cast<double>(half_width_jet) /
static_cast<double>(half_width_jet);
double jet_strength;
int index = 0;
double jet_value;
for (unsigned int i_time=0; i_time<n_step; i_time++)
{
h_old = h;
q_old = q;
for (unsigned int i_RK=0; i_RK<3; i_RK++)
{
// even those TVD3 stuff could be computed on-the-fly to avoid the need to
// store arrays for dh and q2_h_x
// This should be quite OK with the way TVD3 is written, manly need to rename
// local variables.
// gains to expect: loop through 4 arrays instead of 6, reduce memory consumption
// (no need for dh and q2_h_x).
nTVD3::TVD3(q, dh, NUM);
dh *= -idx;
dh[1] = -(q[1] - q[0])*idx;
q2_h_x = q*q/h;
q2_h_BC = (q2_h_x[1] - q2_h_x[0])*idx;
nTVD3::TVD3(q2_h_x, q2_h_x, NUM);
q2_h_x *= idx;
q2_h_x[1] = q2_h_BC;
crrt_h_xxx = (4.0 * MACRO_H_XX(1+1) - 3.0 * MACRO_H_XX(1)
- MACRO_H_XX(1+2))*0.5*idx;
for (int i=1; i < NUM-2; i++){
previous_h_xxx = crrt_h_xxx;
i_p_1 = i + 1;
if (i_p_1 == NUM-2){
//
}
else if (i_p_1 == NUM-3){
crrt_h_xxx = (MACRO_H_XX(NUM-2) - MACRO_H_XX(NUM-3))*idx;
}
else{
crrt_h_xxx = (4.0 * MACRO_H_XX(i_p_1+1)
- 3.0 * MACRO_H_XX(i_p_1) - MACRO_H_XX(i_p_1+2))*0.5*idx;
}
crrt_dq = (h[i] * (previous_h_xxx + 1.0)
- q[i] / h[i] / h[i]) / delta_5 - q2_h_x[i] * 1.2;
// Here we apply the control
for (unsigned int j=0; j < middle_jet.size(); j++)
{
jet_strength = (jet_strength_old[j] + (jet_strength_new[j] - jet_strength_old[j])*static_cast<double>(i_time) / static_cast<double>(n_step));
index = i - middle_jet[j];
if ((index > -half_width_jet) && (index < half_width_jet))
{
jet_value = (half_width_jet + index)
* (half_width_jet - index)
* jet_strength
* normalisation_jet;
crrt_dq += jet_value;
}
}
h[i] = a[i_RK]*h[i] + b[i_RK]*dh[i]*dt + c[i_RK]*h_old[i];
q[i] = a[i_RK]*q[i] + b[i_RK]*crrt_dq*dt + c[i_RK]*q_old[i];
}
// the BCs
h[0] = 1 + noise[i_time];
q[0] = 1;
h[NUM - 2] = h[NUM - 3];
h[NUM - 1] = h[NUM - 2];
q[NUM - 2] = q[NUM - 3];
q[NUM - 1] = q[NUM - 2];
}
t += dt;
}
}
} // namespace ait
| 27.823944 | 155 | 0.498861 | [
"vector"
] |
54e84776d0bd6e81a3aa266f2cf5a2574d8c3efc | 411 | cpp | C++ | Codeforces/Round-494-Div3/C.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-01-30T13:21:30.000Z | 2018-01-30T13:21:30.000Z | Codeforces/Round-494-Div3/C.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | null | null | null | Codeforces/Round-494-Div3/C.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-08-29T13:26:50.000Z | 2018-08-29T13:26:50.000Z | // Brute Force
// 2
// 08-01-2019
#include <bits/stdc++.h>
using namespace std;
int main () {
int n, k;
cin >> n >> k;
vector <int> arr(n + 1, 0);
for (int i = 1; i <= n; i++) cin >> arr[i], arr[i] += arr[i - 1];
double ans = 0;
for (int i = 1; i <= n; i++) for (int j = i + k - 1; j <= n; j++) ans = max(ans, 1.0 * (arr[j] - arr[i - 1]) / (j - i + 1));
printf("%.12f\n", ans);
return (0);
}
| 21.631579 | 126 | 0.457421 | [
"vector"
] |
54e9b59ae357cde7a30513949652bec9e74a48a7 | 60,015 | cpp | C++ | plugins/stereo/resnet18_1025x321_net.cpp | ddoron9/jetson-inference | a96e2e70f3c08dd8c9625dc8929809e9b5cff07c | [
"MIT"
] | 5,788 | 2016-08-22T09:09:46.000Z | 2022-03-31T17:05:54.000Z | plugins/stereo/resnet18_1025x321_net.cpp | barisulgen/jetson-inference | 4e6b7ff37935a9bc64271119f42cd25366ce8c79 | [
"MIT"
] | 1,339 | 2016-08-15T08:51:10.000Z | 2022-03-31T18:44:20.000Z | plugins/stereo/resnet18_1025x321_net.cpp | barisulgen/jetson-inference | 4e6b7ff37935a9bc64271119f42cd25366ce8c79 | [
"MIT"
] | 2,730 | 2016-08-23T11:04:26.000Z | 2022-03-30T14:06:08.000Z | // Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
// Full license terms provided in LICENSE.md file.
//-------------------------------------------------------------------
// !!! This file was automatically generated. Do not edit. !!!
//-------------------------------------------------------------------
#include <NvInfer.h>
#include <cassert>
#include <string>
#include <unordered_map>
#include "redtail_tensorrt_plugins.h"
namespace redtail { namespace tensorrt
{
using namespace nvinfer1;
using weight_map = std::unordered_map<std::string, Weights>;
INetworkDefinition* createResNet18_1025x321Network(IBuilder& builder, IPluginContainer& plugin_factory,
DimsCHW img_dims, const weight_map& weights, DataType data_type,
ILogger& log)
{
INetworkDefinition* network = builder.createNetwork();
assert(network != nullptr);
// Input tensor.
auto left = network->addInput("left", DataType::kFLOAT, img_dims);
assert(left != nullptr);
// Input tensor.
auto right = network->addInput("right", DataType::kFLOAT, img_dims);
assert(right != nullptr);
// Scaling op.
auto left_scale = network->addScale(*left, ScaleMode::kUNIFORM,
weights.at("left_scale_shift"), weights.at("left_scale_scale"), weights.at("left_scale_power"));
assert(left_scale != nullptr);
left_scale->setName("left_scale");
// Scaling op.
auto right_scale = network->addScale(*right, ScaleMode::kUNIFORM,
weights.at("right_scale_shift"), weights.at("right_scale_scale"), weights.at("right_scale_power"));
assert(right_scale != nullptr);
right_scale->setName("right_scale");
// left_conv1 convolution op.
auto left_conv1 = network->addConvolution(*left_scale->getOutput(0), 32, DimsHW {5, 5},
weights.at("left_conv1_k"), weights.at("left_conv1_b"));
assert(left_conv1 != nullptr);
left_conv1->setName("left_conv1");
left_conv1->setStride( DimsHW {2, 2});
left_conv1->setPadding(DimsHW {2, 2});
// left_conv1_act ELU activation op.
auto left_conv1_act = addElu(plugin_factory, *network, *left_conv1->getOutput(0), data_type, "left_conv1_act");
assert(left_conv1_act != nullptr);
left_conv1_act->setName("left_conv1_act");
// right_conv1 convolution op.
auto right_conv1 = network->addConvolution(*right_scale->getOutput(0), 32, DimsHW {5, 5},
weights.at("right_conv1_k"), weights.at("right_conv1_b"));
assert(right_conv1 != nullptr);
right_conv1->setName("right_conv1");
right_conv1->setStride( DimsHW {2, 2});
right_conv1->setPadding(DimsHW {2, 2});
// right_conv1_act ELU activation op.
auto right_conv1_act = addElu(plugin_factory, *network, *right_conv1->getOutput(0), data_type, "right_conv1_act");
assert(right_conv1_act != nullptr);
right_conv1_act->setName("right_conv1_act");
// left_resblock1_conv1 convolution op.
auto left_resblock1_conv1 = network->addConvolution(*left_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock1_conv1_k"), weights.at("left_resblock1_conv1_b"));
assert(left_resblock1_conv1 != nullptr);
left_resblock1_conv1->setName("left_resblock1_conv1");
left_resblock1_conv1->setStride( DimsHW {1, 1});
left_resblock1_conv1->setPadding(DimsHW {1, 1});
// left_resblock1_conv1_act ELU activation op.
auto left_resblock1_conv1_act = addElu(plugin_factory, *network, *left_resblock1_conv1->getOutput(0), data_type, "left_resblock1_conv1_act");
assert(left_resblock1_conv1_act != nullptr);
left_resblock1_conv1_act->setName("left_resblock1_conv1_act");
// left_resblock1_conv2 convolution op.
auto left_resblock1_conv2 = network->addConvolution(*left_resblock1_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock1_conv2_k"), weights.at("left_resblock1_conv2_b"));
assert(left_resblock1_conv2 != nullptr);
left_resblock1_conv2->setName("left_resblock1_conv2");
left_resblock1_conv2->setStride( DimsHW {1, 1});
left_resblock1_conv2->setPadding(DimsHW {1, 1});
// left_resblock1_conv2_add tensor add op.
auto left_resblock1_conv2_add = network->addElementWise(*(left_resblock1_conv2->getOutput(0)), *(left_conv1_act->getOutput(0)), ElementWiseOperation::kSUM);
assert(left_resblock1_conv2_add != nullptr);
left_resblock1_conv2_add->setName("left_resblock1_conv2_add");
// left_resblock1_conv2_add_act ELU activation op.
auto left_resblock1_conv2_add_act = addElu(plugin_factory, *network, *left_resblock1_conv2_add->getOutput(0), data_type, "left_resblock1_conv2_add_act");
assert(left_resblock1_conv2_add_act != nullptr);
left_resblock1_conv2_add_act->setName("left_resblock1_conv2_add_act");
// right_resblock1_conv1 convolution op.
auto right_resblock1_conv1 = network->addConvolution(*right_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock1_conv1_k"), weights.at("right_resblock1_conv1_b"));
assert(right_resblock1_conv1 != nullptr);
right_resblock1_conv1->setName("right_resblock1_conv1");
right_resblock1_conv1->setStride( DimsHW {1, 1});
right_resblock1_conv1->setPadding(DimsHW {1, 1});
// right_resblock1_conv1_act ELU activation op.
auto right_resblock1_conv1_act = addElu(plugin_factory, *network, *right_resblock1_conv1->getOutput(0), data_type, "right_resblock1_conv1_act");
assert(right_resblock1_conv1_act != nullptr);
right_resblock1_conv1_act->setName("right_resblock1_conv1_act");
// right_resblock1_conv2 convolution op.
auto right_resblock1_conv2 = network->addConvolution(*right_resblock1_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock1_conv2_k"), weights.at("right_resblock1_conv2_b"));
assert(right_resblock1_conv2 != nullptr);
right_resblock1_conv2->setName("right_resblock1_conv2");
right_resblock1_conv2->setStride( DimsHW {1, 1});
right_resblock1_conv2->setPadding(DimsHW {1, 1});
// right_resblock1_conv2_add tensor add op.
auto right_resblock1_conv2_add = network->addElementWise(*(right_resblock1_conv2->getOutput(0)), *(right_conv1_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(right_resblock1_conv2_add != nullptr);
right_resblock1_conv2_add->setName("right_resblock1_conv2_add");
// right_resblock1_conv2_add_act ELU activation op.
auto right_resblock1_conv2_add_act = addElu(plugin_factory, *network, *right_resblock1_conv2_add->getOutput(0), data_type, "right_resblock1_conv2_add_act");
assert(right_resblock1_conv2_add_act != nullptr);
right_resblock1_conv2_add_act->setName("right_resblock1_conv2_add_act");
// left_resblock2_conv1 convolution op.
auto left_resblock2_conv1 = network->addConvolution(*left_resblock1_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock2_conv1_k"), weights.at("left_resblock2_conv1_b"));
assert(left_resblock2_conv1 != nullptr);
left_resblock2_conv1->setName("left_resblock2_conv1");
left_resblock2_conv1->setStride( DimsHW {1, 1});
left_resblock2_conv1->setPadding(DimsHW {1, 1});
// left_resblock2_conv1_act ELU activation op.
auto left_resblock2_conv1_act = addElu(plugin_factory, *network, *left_resblock2_conv1->getOutput(0), data_type, "left_resblock2_conv1_act");
assert(left_resblock2_conv1_act != nullptr);
left_resblock2_conv1_act->setName("left_resblock2_conv1_act");
// left_resblock2_conv2 convolution op.
auto left_resblock2_conv2 = network->addConvolution(*left_resblock2_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock2_conv2_k"), weights.at("left_resblock2_conv2_b"));
assert(left_resblock2_conv2 != nullptr);
left_resblock2_conv2->setName("left_resblock2_conv2");
left_resblock2_conv2->setStride( DimsHW {1, 1});
left_resblock2_conv2->setPadding(DimsHW {1, 1});
// left_resblock2_conv2_add tensor add op.
auto left_resblock2_conv2_add = network->addElementWise(*(left_resblock2_conv2->getOutput(0)), *(left_resblock1_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(left_resblock2_conv2_add != nullptr);
left_resblock2_conv2_add->setName("left_resblock2_conv2_add");
// left_resblock2_conv2_add_act ELU activation op.
auto left_resblock2_conv2_add_act = addElu(plugin_factory, *network, *left_resblock2_conv2_add->getOutput(0), data_type, "left_resblock2_conv2_add_act");
assert(left_resblock2_conv2_add_act != nullptr);
left_resblock2_conv2_add_act->setName("left_resblock2_conv2_add_act");
// right_resblock2_conv1 convolution op.
auto right_resblock2_conv1 = network->addConvolution(*right_resblock1_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock2_conv1_k"), weights.at("right_resblock2_conv1_b"));
assert(right_resblock2_conv1 != nullptr);
right_resblock2_conv1->setName("right_resblock2_conv1");
right_resblock2_conv1->setStride( DimsHW {1, 1});
right_resblock2_conv1->setPadding(DimsHW {1, 1});
// right_resblock2_conv1_act ELU activation op.
auto right_resblock2_conv1_act = addElu(plugin_factory, *network, *right_resblock2_conv1->getOutput(0), data_type, "right_resblock2_conv1_act");
assert(right_resblock2_conv1_act != nullptr);
right_resblock2_conv1_act->setName("right_resblock2_conv1_act");
// right_resblock2_conv2 convolution op.
auto right_resblock2_conv2 = network->addConvolution(*right_resblock2_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock2_conv2_k"), weights.at("right_resblock2_conv2_b"));
assert(right_resblock2_conv2 != nullptr);
right_resblock2_conv2->setName("right_resblock2_conv2");
right_resblock2_conv2->setStride( DimsHW {1, 1});
right_resblock2_conv2->setPadding(DimsHW {1, 1});
// right_resblock2_conv2_add tensor add op.
auto right_resblock2_conv2_add = network->addElementWise(*(right_resblock2_conv2->getOutput(0)), *(right_resblock1_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(right_resblock2_conv2_add != nullptr);
right_resblock2_conv2_add->setName("right_resblock2_conv2_add");
// right_resblock2_conv2_add_act ELU activation op.
auto right_resblock2_conv2_add_act = addElu(plugin_factory, *network, *right_resblock2_conv2_add->getOutput(0), data_type, "right_resblock2_conv2_add_act");
assert(right_resblock2_conv2_add_act != nullptr);
right_resblock2_conv2_add_act->setName("right_resblock2_conv2_add_act");
// left_resblock3_conv1 convolution op.
auto left_resblock3_conv1 = network->addConvolution(*left_resblock2_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock3_conv1_k"), weights.at("left_resblock3_conv1_b"));
assert(left_resblock3_conv1 != nullptr);
left_resblock3_conv1->setName("left_resblock3_conv1");
left_resblock3_conv1->setStride( DimsHW {1, 1});
left_resblock3_conv1->setPadding(DimsHW {1, 1});
// left_resblock3_conv1_act ELU activation op.
auto left_resblock3_conv1_act = addElu(plugin_factory, *network, *left_resblock3_conv1->getOutput(0), data_type, "left_resblock3_conv1_act");
assert(left_resblock3_conv1_act != nullptr);
left_resblock3_conv1_act->setName("left_resblock3_conv1_act");
// left_resblock3_conv2 convolution op.
auto left_resblock3_conv2 = network->addConvolution(*left_resblock3_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock3_conv2_k"), weights.at("left_resblock3_conv2_b"));
assert(left_resblock3_conv2 != nullptr);
left_resblock3_conv2->setName("left_resblock3_conv2");
left_resblock3_conv2->setStride( DimsHW {1, 1});
left_resblock3_conv2->setPadding(DimsHW {1, 1});
// left_resblock3_conv2_add tensor add op.
auto left_resblock3_conv2_add = network->addElementWise(*(left_resblock3_conv2->getOutput(0)), *(left_resblock2_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(left_resblock3_conv2_add != nullptr);
left_resblock3_conv2_add->setName("left_resblock3_conv2_add");
// left_resblock3_conv2_add_act ELU activation op.
auto left_resblock3_conv2_add_act = addElu(plugin_factory, *network, *left_resblock3_conv2_add->getOutput(0), data_type, "left_resblock3_conv2_add_act");
assert(left_resblock3_conv2_add_act != nullptr);
left_resblock3_conv2_add_act->setName("left_resblock3_conv2_add_act");
// right_resblock3_conv1 convolution op.
auto right_resblock3_conv1 = network->addConvolution(*right_resblock2_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock3_conv1_k"), weights.at("right_resblock3_conv1_b"));
assert(right_resblock3_conv1 != nullptr);
right_resblock3_conv1->setName("right_resblock3_conv1");
right_resblock3_conv1->setStride( DimsHW {1, 1});
right_resblock3_conv1->setPadding(DimsHW {1, 1});
// right_resblock3_conv1_act ELU activation op.
auto right_resblock3_conv1_act = addElu(plugin_factory, *network, *right_resblock3_conv1->getOutput(0), data_type, "right_resblock3_conv1_act");
assert(right_resblock3_conv1_act != nullptr);
right_resblock3_conv1_act->setName("right_resblock3_conv1_act");
// right_resblock3_conv2 convolution op.
auto right_resblock3_conv2 = network->addConvolution(*right_resblock3_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock3_conv2_k"), weights.at("right_resblock3_conv2_b"));
assert(right_resblock3_conv2 != nullptr);
right_resblock3_conv2->setName("right_resblock3_conv2");
right_resblock3_conv2->setStride( DimsHW {1, 1});
right_resblock3_conv2->setPadding(DimsHW {1, 1});
// right_resblock3_conv2_add tensor add op.
auto right_resblock3_conv2_add = network->addElementWise(*(right_resblock3_conv2->getOutput(0)), *(right_resblock2_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(right_resblock3_conv2_add != nullptr);
right_resblock3_conv2_add->setName("right_resblock3_conv2_add");
// right_resblock3_conv2_add_act ELU activation op.
auto right_resblock3_conv2_add_act = addElu(plugin_factory, *network, *right_resblock3_conv2_add->getOutput(0), data_type, "right_resblock3_conv2_add_act");
assert(right_resblock3_conv2_add_act != nullptr);
right_resblock3_conv2_add_act->setName("right_resblock3_conv2_add_act");
// left_resblock4_conv1 convolution op.
auto left_resblock4_conv1 = network->addConvolution(*left_resblock3_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock4_conv1_k"), weights.at("left_resblock4_conv1_b"));
assert(left_resblock4_conv1 != nullptr);
left_resblock4_conv1->setName("left_resblock4_conv1");
left_resblock4_conv1->setStride( DimsHW {1, 1});
left_resblock4_conv1->setPadding(DimsHW {1, 1});
// left_resblock4_conv1_act ELU activation op.
auto left_resblock4_conv1_act = addElu(plugin_factory, *network, *left_resblock4_conv1->getOutput(0), data_type, "left_resblock4_conv1_act");
assert(left_resblock4_conv1_act != nullptr);
left_resblock4_conv1_act->setName("left_resblock4_conv1_act");
// left_resblock4_conv2 convolution op.
auto left_resblock4_conv2 = network->addConvolution(*left_resblock4_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock4_conv2_k"), weights.at("left_resblock4_conv2_b"));
assert(left_resblock4_conv2 != nullptr);
left_resblock4_conv2->setName("left_resblock4_conv2");
left_resblock4_conv2->setStride( DimsHW {1, 1});
left_resblock4_conv2->setPadding(DimsHW {1, 1});
// left_resblock4_conv2_add tensor add op.
auto left_resblock4_conv2_add = network->addElementWise(*(left_resblock4_conv2->getOutput(0)), *(left_resblock3_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(left_resblock4_conv2_add != nullptr);
left_resblock4_conv2_add->setName("left_resblock4_conv2_add");
// left_resblock4_conv2_add_act ELU activation op.
auto left_resblock4_conv2_add_act = addElu(plugin_factory, *network, *left_resblock4_conv2_add->getOutput(0), data_type, "left_resblock4_conv2_add_act");
assert(left_resblock4_conv2_add_act != nullptr);
left_resblock4_conv2_add_act->setName("left_resblock4_conv2_add_act");
// right_resblock4_conv1 convolution op.
auto right_resblock4_conv1 = network->addConvolution(*right_resblock3_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock4_conv1_k"), weights.at("right_resblock4_conv1_b"));
assert(right_resblock4_conv1 != nullptr);
right_resblock4_conv1->setName("right_resblock4_conv1");
right_resblock4_conv1->setStride( DimsHW {1, 1});
right_resblock4_conv1->setPadding(DimsHW {1, 1});
// right_resblock4_conv1_act ELU activation op.
auto right_resblock4_conv1_act = addElu(plugin_factory, *network, *right_resblock4_conv1->getOutput(0), data_type, "right_resblock4_conv1_act");
assert(right_resblock4_conv1_act != nullptr);
right_resblock4_conv1_act->setName("right_resblock4_conv1_act");
// right_resblock4_conv2 convolution op.
auto right_resblock4_conv2 = network->addConvolution(*right_resblock4_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock4_conv2_k"), weights.at("right_resblock4_conv2_b"));
assert(right_resblock4_conv2 != nullptr);
right_resblock4_conv2->setName("right_resblock4_conv2");
right_resblock4_conv2->setStride( DimsHW {1, 1});
right_resblock4_conv2->setPadding(DimsHW {1, 1});
// right_resblock4_conv2_add tensor add op.
auto right_resblock4_conv2_add = network->addElementWise(*(right_resblock4_conv2->getOutput(0)), *(right_resblock3_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(right_resblock4_conv2_add != nullptr);
right_resblock4_conv2_add->setName("right_resblock4_conv2_add");
// right_resblock4_conv2_add_act ELU activation op.
auto right_resblock4_conv2_add_act = addElu(plugin_factory, *network, *right_resblock4_conv2_add->getOutput(0), data_type, "right_resblock4_conv2_add_act");
assert(right_resblock4_conv2_add_act != nullptr);
right_resblock4_conv2_add_act->setName("right_resblock4_conv2_add_act");
// left_resblock5_conv1 convolution op.
auto left_resblock5_conv1 = network->addConvolution(*left_resblock4_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock5_conv1_k"), weights.at("left_resblock5_conv1_b"));
assert(left_resblock5_conv1 != nullptr);
left_resblock5_conv1->setName("left_resblock5_conv1");
left_resblock5_conv1->setStride( DimsHW {1, 1});
left_resblock5_conv1->setPadding(DimsHW {1, 1});
// left_resblock5_conv1_act ELU activation op.
auto left_resblock5_conv1_act = addElu(plugin_factory, *network, *left_resblock5_conv1->getOutput(0), data_type, "left_resblock5_conv1_act");
assert(left_resblock5_conv1_act != nullptr);
left_resblock5_conv1_act->setName("left_resblock5_conv1_act");
// left_resblock5_conv2 convolution op.
auto left_resblock5_conv2 = network->addConvolution(*left_resblock5_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock5_conv2_k"), weights.at("left_resblock5_conv2_b"));
assert(left_resblock5_conv2 != nullptr);
left_resblock5_conv2->setName("left_resblock5_conv2");
left_resblock5_conv2->setStride( DimsHW {1, 1});
left_resblock5_conv2->setPadding(DimsHW {1, 1});
// left_resblock5_conv2_add tensor add op.
auto left_resblock5_conv2_add = network->addElementWise(*(left_resblock5_conv2->getOutput(0)), *(left_resblock4_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(left_resblock5_conv2_add != nullptr);
left_resblock5_conv2_add->setName("left_resblock5_conv2_add");
// left_resblock5_conv2_add_act ELU activation op.
auto left_resblock5_conv2_add_act = addElu(plugin_factory, *network, *left_resblock5_conv2_add->getOutput(0), data_type, "left_resblock5_conv2_add_act");
assert(left_resblock5_conv2_add_act != nullptr);
left_resblock5_conv2_add_act->setName("left_resblock5_conv2_add_act");
// right_resblock5_conv1 convolution op.
auto right_resblock5_conv1 = network->addConvolution(*right_resblock4_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock5_conv1_k"), weights.at("right_resblock5_conv1_b"));
assert(right_resblock5_conv1 != nullptr);
right_resblock5_conv1->setName("right_resblock5_conv1");
right_resblock5_conv1->setStride( DimsHW {1, 1});
right_resblock5_conv1->setPadding(DimsHW {1, 1});
// right_resblock5_conv1_act ELU activation op.
auto right_resblock5_conv1_act = addElu(plugin_factory, *network, *right_resblock5_conv1->getOutput(0), data_type, "right_resblock5_conv1_act");
assert(right_resblock5_conv1_act != nullptr);
right_resblock5_conv1_act->setName("right_resblock5_conv1_act");
// right_resblock5_conv2 convolution op.
auto right_resblock5_conv2 = network->addConvolution(*right_resblock5_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock5_conv2_k"), weights.at("right_resblock5_conv2_b"));
assert(right_resblock5_conv2 != nullptr);
right_resblock5_conv2->setName("right_resblock5_conv2");
right_resblock5_conv2->setStride( DimsHW {1, 1});
right_resblock5_conv2->setPadding(DimsHW {1, 1});
// right_resblock5_conv2_add tensor add op.
auto right_resblock5_conv2_add = network->addElementWise(*(right_resblock5_conv2->getOutput(0)), *(right_resblock4_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(right_resblock5_conv2_add != nullptr);
right_resblock5_conv2_add->setName("right_resblock5_conv2_add");
// right_resblock5_conv2_add_act ELU activation op.
auto right_resblock5_conv2_add_act = addElu(plugin_factory, *network, *right_resblock5_conv2_add->getOutput(0), data_type, "right_resblock5_conv2_add_act");
assert(right_resblock5_conv2_add_act != nullptr);
right_resblock5_conv2_add_act->setName("right_resblock5_conv2_add_act");
// left_resblock6_conv1 convolution op.
auto left_resblock6_conv1 = network->addConvolution(*left_resblock5_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock6_conv1_k"), weights.at("left_resblock6_conv1_b"));
assert(left_resblock6_conv1 != nullptr);
left_resblock6_conv1->setName("left_resblock6_conv1");
left_resblock6_conv1->setStride( DimsHW {1, 1});
left_resblock6_conv1->setPadding(DimsHW {1, 1});
// left_resblock6_conv1_act ELU activation op.
auto left_resblock6_conv1_act = addElu(plugin_factory, *network, *left_resblock6_conv1->getOutput(0), data_type, "left_resblock6_conv1_act");
assert(left_resblock6_conv1_act != nullptr);
left_resblock6_conv1_act->setName("left_resblock6_conv1_act");
// left_resblock6_conv2 convolution op.
auto left_resblock6_conv2 = network->addConvolution(*left_resblock6_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock6_conv2_k"), weights.at("left_resblock6_conv2_b"));
assert(left_resblock6_conv2 != nullptr);
left_resblock6_conv2->setName("left_resblock6_conv2");
left_resblock6_conv2->setStride( DimsHW {1, 1});
left_resblock6_conv2->setPadding(DimsHW {1, 1});
// left_resblock6_conv2_add tensor add op.
auto left_resblock6_conv2_add = network->addElementWise(*(left_resblock6_conv2->getOutput(0)), *(left_resblock5_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(left_resblock6_conv2_add != nullptr);
left_resblock6_conv2_add->setName("left_resblock6_conv2_add");
// left_resblock6_conv2_add_act ELU activation op.
auto left_resblock6_conv2_add_act = addElu(plugin_factory, *network, *left_resblock6_conv2_add->getOutput(0), data_type, "left_resblock6_conv2_add_act");
assert(left_resblock6_conv2_add_act != nullptr);
left_resblock6_conv2_add_act->setName("left_resblock6_conv2_add_act");
// right_resblock6_conv1 convolution op.
auto right_resblock6_conv1 = network->addConvolution(*right_resblock5_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock6_conv1_k"), weights.at("right_resblock6_conv1_b"));
assert(right_resblock6_conv1 != nullptr);
right_resblock6_conv1->setName("right_resblock6_conv1");
right_resblock6_conv1->setStride( DimsHW {1, 1});
right_resblock6_conv1->setPadding(DimsHW {1, 1});
// right_resblock6_conv1_act ELU activation op.
auto right_resblock6_conv1_act = addElu(plugin_factory, *network, *right_resblock6_conv1->getOutput(0), data_type, "right_resblock6_conv1_act");
assert(right_resblock6_conv1_act != nullptr);
right_resblock6_conv1_act->setName("right_resblock6_conv1_act");
// right_resblock6_conv2 convolution op.
auto right_resblock6_conv2 = network->addConvolution(*right_resblock6_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock6_conv2_k"), weights.at("right_resblock6_conv2_b"));
assert(right_resblock6_conv2 != nullptr);
right_resblock6_conv2->setName("right_resblock6_conv2");
right_resblock6_conv2->setStride( DimsHW {1, 1});
right_resblock6_conv2->setPadding(DimsHW {1, 1});
// right_resblock6_conv2_add tensor add op.
auto right_resblock6_conv2_add = network->addElementWise(*(right_resblock6_conv2->getOutput(0)), *(right_resblock5_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(right_resblock6_conv2_add != nullptr);
right_resblock6_conv2_add->setName("right_resblock6_conv2_add");
// right_resblock6_conv2_add_act ELU activation op.
auto right_resblock6_conv2_add_act = addElu(plugin_factory, *network, *right_resblock6_conv2_add->getOutput(0), data_type, "right_resblock6_conv2_add_act");
assert(right_resblock6_conv2_add_act != nullptr);
right_resblock6_conv2_add_act->setName("right_resblock6_conv2_add_act");
// left_resblock7_conv1 convolution op.
auto left_resblock7_conv1 = network->addConvolution(*left_resblock6_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock7_conv1_k"), weights.at("left_resblock7_conv1_b"));
assert(left_resblock7_conv1 != nullptr);
left_resblock7_conv1->setName("left_resblock7_conv1");
left_resblock7_conv1->setStride( DimsHW {1, 1});
left_resblock7_conv1->setPadding(DimsHW {1, 1});
// left_resblock7_conv1_act ELU activation op.
auto left_resblock7_conv1_act = addElu(plugin_factory, *network, *left_resblock7_conv1->getOutput(0), data_type, "left_resblock7_conv1_act");
assert(left_resblock7_conv1_act != nullptr);
left_resblock7_conv1_act->setName("left_resblock7_conv1_act");
// left_resblock7_conv2 convolution op.
auto left_resblock7_conv2 = network->addConvolution(*left_resblock7_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock7_conv2_k"), weights.at("left_resblock7_conv2_b"));
assert(left_resblock7_conv2 != nullptr);
left_resblock7_conv2->setName("left_resblock7_conv2");
left_resblock7_conv2->setStride( DimsHW {1, 1});
left_resblock7_conv2->setPadding(DimsHW {1, 1});
// left_resblock7_conv2_add tensor add op.
auto left_resblock7_conv2_add = network->addElementWise(*(left_resblock7_conv2->getOutput(0)), *(left_resblock6_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(left_resblock7_conv2_add != nullptr);
left_resblock7_conv2_add->setName("left_resblock7_conv2_add");
// left_resblock7_conv2_add_act ELU activation op.
auto left_resblock7_conv2_add_act = addElu(plugin_factory, *network, *left_resblock7_conv2_add->getOutput(0), data_type, "left_resblock7_conv2_add_act");
assert(left_resblock7_conv2_add_act != nullptr);
left_resblock7_conv2_add_act->setName("left_resblock7_conv2_add_act");
// right_resblock7_conv1 convolution op.
auto right_resblock7_conv1 = network->addConvolution(*right_resblock6_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock7_conv1_k"), weights.at("right_resblock7_conv1_b"));
assert(right_resblock7_conv1 != nullptr);
right_resblock7_conv1->setName("right_resblock7_conv1");
right_resblock7_conv1->setStride( DimsHW {1, 1});
right_resblock7_conv1->setPadding(DimsHW {1, 1});
// right_resblock7_conv1_act ELU activation op.
auto right_resblock7_conv1_act = addElu(plugin_factory, *network, *right_resblock7_conv1->getOutput(0), data_type, "right_resblock7_conv1_act");
assert(right_resblock7_conv1_act != nullptr);
right_resblock7_conv1_act->setName("right_resblock7_conv1_act");
// right_resblock7_conv2 convolution op.
auto right_resblock7_conv2 = network->addConvolution(*right_resblock7_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock7_conv2_k"), weights.at("right_resblock7_conv2_b"));
assert(right_resblock7_conv2 != nullptr);
right_resblock7_conv2->setName("right_resblock7_conv2");
right_resblock7_conv2->setStride( DimsHW {1, 1});
right_resblock7_conv2->setPadding(DimsHW {1, 1});
// right_resblock7_conv2_add tensor add op.
auto right_resblock7_conv2_add = network->addElementWise(*(right_resblock7_conv2->getOutput(0)), *(right_resblock6_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(right_resblock7_conv2_add != nullptr);
right_resblock7_conv2_add->setName("right_resblock7_conv2_add");
// right_resblock7_conv2_add_act ELU activation op.
auto right_resblock7_conv2_add_act = addElu(plugin_factory, *network, *right_resblock7_conv2_add->getOutput(0), data_type, "right_resblock7_conv2_add_act");
assert(right_resblock7_conv2_add_act != nullptr);
right_resblock7_conv2_add_act->setName("right_resblock7_conv2_add_act");
// left_resblock8_conv1 convolution op.
auto left_resblock8_conv1 = network->addConvolution(*left_resblock7_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock8_conv1_k"), weights.at("left_resblock8_conv1_b"));
assert(left_resblock8_conv1 != nullptr);
left_resblock8_conv1->setName("left_resblock8_conv1");
left_resblock8_conv1->setStride( DimsHW {1, 1});
left_resblock8_conv1->setPadding(DimsHW {1, 1});
// left_resblock8_conv1_act ELU activation op.
auto left_resblock8_conv1_act = addElu(plugin_factory, *network, *left_resblock8_conv1->getOutput(0), data_type, "left_resblock8_conv1_act");
assert(left_resblock8_conv1_act != nullptr);
left_resblock8_conv1_act->setName("left_resblock8_conv1_act");
// left_resblock8_conv2 convolution op.
auto left_resblock8_conv2 = network->addConvolution(*left_resblock8_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_resblock8_conv2_k"), weights.at("left_resblock8_conv2_b"));
assert(left_resblock8_conv2 != nullptr);
left_resblock8_conv2->setName("left_resblock8_conv2");
left_resblock8_conv2->setStride( DimsHW {1, 1});
left_resblock8_conv2->setPadding(DimsHW {1, 1});
// left_resblock8_conv2_add tensor add op.
auto left_resblock8_conv2_add = network->addElementWise(*(left_resblock8_conv2->getOutput(0)), *(left_resblock7_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(left_resblock8_conv2_add != nullptr);
left_resblock8_conv2_add->setName("left_resblock8_conv2_add");
// left_resblock8_conv2_add_act ELU activation op.
auto left_resblock8_conv2_add_act = addElu(plugin_factory, *network, *left_resblock8_conv2_add->getOutput(0), data_type, "left_resblock8_conv2_add_act");
assert(left_resblock8_conv2_add_act != nullptr);
left_resblock8_conv2_add_act->setName("left_resblock8_conv2_add_act");
// right_resblock8_conv1 convolution op.
auto right_resblock8_conv1 = network->addConvolution(*right_resblock7_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock8_conv1_k"), weights.at("right_resblock8_conv1_b"));
assert(right_resblock8_conv1 != nullptr);
right_resblock8_conv1->setName("right_resblock8_conv1");
right_resblock8_conv1->setStride( DimsHW {1, 1});
right_resblock8_conv1->setPadding(DimsHW {1, 1});
// right_resblock8_conv1_act ELU activation op.
auto right_resblock8_conv1_act = addElu(plugin_factory, *network, *right_resblock8_conv1->getOutput(0), data_type, "right_resblock8_conv1_act");
assert(right_resblock8_conv1_act != nullptr);
right_resblock8_conv1_act->setName("right_resblock8_conv1_act");
// right_resblock8_conv2 convolution op.
auto right_resblock8_conv2 = network->addConvolution(*right_resblock8_conv1_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_resblock8_conv2_k"), weights.at("right_resblock8_conv2_b"));
assert(right_resblock8_conv2 != nullptr);
right_resblock8_conv2->setName("right_resblock8_conv2");
right_resblock8_conv2->setStride( DimsHW {1, 1});
right_resblock8_conv2->setPadding(DimsHW {1, 1});
// right_resblock8_conv2_add tensor add op.
auto right_resblock8_conv2_add = network->addElementWise(*(right_resblock8_conv2->getOutput(0)), *(right_resblock7_conv2_add_act->getOutput(0)),
ElementWiseOperation::kSUM);
assert(right_resblock8_conv2_add != nullptr);
right_resblock8_conv2_add->setName("right_resblock8_conv2_add");
// right_resblock8_conv2_add_act ELU activation op.
auto right_resblock8_conv2_add_act = addElu(plugin_factory, *network, *right_resblock8_conv2_add->getOutput(0), data_type, "right_resblock8_conv2_add_act");
assert(right_resblock8_conv2_add_act != nullptr);
right_resblock8_conv2_add_act->setName("right_resblock8_conv2_add_act");
// left_encoder2D_out convolution op.
auto left_encoder2D_out = network->addConvolution(*left_resblock8_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("left_encoder2D_out_k"), weights.at("left_encoder2D_out_b"));
assert(left_encoder2D_out != nullptr);
left_encoder2D_out->setName("left_encoder2D_out");
left_encoder2D_out->setStride( DimsHW {1, 1});
left_encoder2D_out->setPadding(DimsHW {1, 1});
// right_encoder2D_out convolution op.
auto right_encoder2D_out = network->addConvolution(*right_resblock8_conv2_add_act->getOutput(0), 32, DimsHW {3, 3},
weights.at("right_encoder2D_out_k"), weights.at("right_encoder2D_out_b"));
assert(right_encoder2D_out != nullptr);
right_encoder2D_out->setName("right_encoder2D_out");
right_encoder2D_out->setStride( DimsHW {1, 1});
right_encoder2D_out->setPadding(DimsHW {1, 1});
// cost_vol cost volume op.
auto cost_vol = addCostVolume(plugin_factory, *network, *left_encoder2D_out->getOutput(0), *right_encoder2D_out->getOutput(0),
CostVolumeType::kDefault, 68, data_type, "cost_vol");
assert(cost_vol != nullptr);
cost_vol->setName("cost_vol");
// conv3D_1a 3D convolution op.
auto conv3D_1a = addConv3D(plugin_factory, *network, *cost_vol->getOutput(0),
Conv3DType::kTensorFlow, {5, {32, 3, 64, 3, 3}},
Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_1a_k"), weights.at("conv3D_1a_b"),
"conv3D_1a");
assert(conv3D_1a != nullptr);
conv3D_1a->setName("conv3D_1a");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_1a_tran = addTransform(plugin_factory, *network, *conv3D_1a->getOutput(0), {1, 0, 2, 3}, "conv3D_1a_tran_transform");
assert(conv3D_1a_tran != nullptr);
conv3D_1a_tran->setName("conv3D_1a_tran");
// conv3D_1a_act ELU activation op.
auto conv3D_1a_act = addElu(plugin_factory, *network, *conv3D_1a_tran->getOutput(0), data_type, "conv3D_1a_act");
assert(conv3D_1a_act != nullptr);
conv3D_1a_act->setName("conv3D_1a_act");
// conv3D_1b 3D convolution op.
auto conv3D_1b = addConv3D(plugin_factory, *network, *conv3D_1a_act->getOutput(0),
Conv3DType::kTensorFlow, {5, {32, 3, 32, 3, 3}},
Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_1b_k"), weights.at("conv3D_1b_b"),
"conv3D_1b");
assert(conv3D_1b != nullptr);
conv3D_1b->setName("conv3D_1b");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_1b_tran = addTransform(plugin_factory, *network, *conv3D_1b->getOutput(0), {1, 0, 2, 3}, "conv3D_1b_tran_transform");
assert(conv3D_1b_tran != nullptr);
conv3D_1b_tran->setName("conv3D_1b_tran");
// conv3D_1b_act ELU activation op.
auto conv3D_1b_act = addElu(plugin_factory, *network, *conv3D_1b_tran->getOutput(0), data_type, "conv3D_1b_act");
assert(conv3D_1b_act != nullptr);
conv3D_1b_act->setName("conv3D_1b_act");
// conv3D_1ds_pad padding op.
auto conv3D_1ds_pad = addPad(plugin_factory, *network, *conv3D_1b_act->getOutput(0), {0, 0, 0, 0}, {1, 0, 0, 0}, "conv3D_1ds_pad");
assert(conv3D_1ds_pad != nullptr);
conv3D_1ds_pad->setName("conv3D_1ds_pad");
// conv3D_1ds 3D convolution op.
auto conv3D_1ds = addConv3D(plugin_factory, *network, *conv3D_1ds_pad->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 32, 3, 3}},
Dims{3, {2, 2, 2}}, Dims{3, {0, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_1ds_k"), weights.at("conv3D_1ds_b"),
"conv3D_1ds");
assert(conv3D_1ds != nullptr);
conv3D_1ds->setName("conv3D_1ds");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_1ds_tran = addTransform(plugin_factory, *network, *conv3D_1ds->getOutput(0), {1, 0, 2, 3}, "conv3D_1ds_tran_transform");
assert(conv3D_1ds_tran != nullptr);
conv3D_1ds_tran->setName("conv3D_1ds_tran");
// conv3D_1ds_act ELU activation op.
auto conv3D_1ds_act = addElu(plugin_factory, *network, *conv3D_1ds_tran->getOutput(0), data_type, "conv3D_1ds_act");
assert(conv3D_1ds_act != nullptr);
conv3D_1ds_act->setName("conv3D_1ds_act");
// conv3D_2a 3D convolution op.
auto conv3D_2a = addConv3D(plugin_factory, *network, *conv3D_1ds_act->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 64, 3, 3}},
Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_2a_k"), weights.at("conv3D_2a_b"),
"conv3D_2a");
assert(conv3D_2a != nullptr);
conv3D_2a->setName("conv3D_2a");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_2a_tran = addTransform(plugin_factory, *network, *conv3D_2a->getOutput(0), {1, 0, 2, 3}, "conv3D_2a_tran_transform");
assert(conv3D_2a_tran != nullptr);
conv3D_2a_tran->setName("conv3D_2a_tran");
// conv3D_2a_act ELU activation op.
auto conv3D_2a_act = addElu(plugin_factory, *network, *conv3D_2a_tran->getOutput(0), data_type, "conv3D_2a_act");
assert(conv3D_2a_act != nullptr);
conv3D_2a_act->setName("conv3D_2a_act");
// conv3D_2b 3D convolution op.
auto conv3D_2b = addConv3D(plugin_factory, *network, *conv3D_2a_act->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 64, 3, 3}},
Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_2b_k"), weights.at("conv3D_2b_b"),
"conv3D_2b");
assert(conv3D_2b != nullptr);
conv3D_2b->setName("conv3D_2b");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_2b_tran = addTransform(plugin_factory, *network, *conv3D_2b->getOutput(0), {1, 0, 2, 3}, "conv3D_2b_tran_transform");
assert(conv3D_2b_tran != nullptr);
conv3D_2b_tran->setName("conv3D_2b_tran");
// conv3D_2b_act ELU activation op.
auto conv3D_2b_act = addElu(plugin_factory, *network, *conv3D_2b_tran->getOutput(0), data_type, "conv3D_2b_act");
assert(conv3D_2b_act != nullptr);
conv3D_2b_act->setName("conv3D_2b_act");
// conv3D_2ds_pad padding op.
auto conv3D_2ds_pad = addPad(plugin_factory, *network, *conv3D_2b_act->getOutput(0), {0, 0, 0, 0}, {1, 0, 0, 0}, "conv3D_2ds_pad");
assert(conv3D_2ds_pad != nullptr);
conv3D_2ds_pad->setName("conv3D_2ds_pad");
// conv3D_2ds 3D convolution op.
auto conv3D_2ds = addConv3D(plugin_factory, *network, *conv3D_2ds_pad->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 64, 3, 3}},
Dims{3, {2, 2, 2}}, Dims{3, {0, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_2ds_k"), weights.at("conv3D_2ds_b"),
"conv3D_2ds");
assert(conv3D_2ds != nullptr);
conv3D_2ds->setName("conv3D_2ds");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_2ds_tran = addTransform(plugin_factory, *network, *conv3D_2ds->getOutput(0), {1, 0, 2, 3}, "conv3D_2ds_tran_transform");
assert(conv3D_2ds_tran != nullptr);
conv3D_2ds_tran->setName("conv3D_2ds_tran");
// conv3D_2ds_act ELU activation op.
auto conv3D_2ds_act = addElu(plugin_factory, *network, *conv3D_2ds_tran->getOutput(0), data_type, "conv3D_2ds_act");
assert(conv3D_2ds_act != nullptr);
conv3D_2ds_act->setName("conv3D_2ds_act");
// conv3D_3a 3D convolution op.
auto conv3D_3a = addConv3D(plugin_factory, *network, *conv3D_2ds_act->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 64, 3, 3}},
Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_3a_k"), weights.at("conv3D_3a_b"),
"conv3D_3a");
assert(conv3D_3a != nullptr);
conv3D_3a->setName("conv3D_3a");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_3a_tran = addTransform(plugin_factory, *network, *conv3D_3a->getOutput(0), {1, 0, 2, 3}, "conv3D_3a_tran_transform");
assert(conv3D_3a_tran != nullptr);
conv3D_3a_tran->setName("conv3D_3a_tran");
// conv3D_3a_act ELU activation op.
auto conv3D_3a_act = addElu(plugin_factory, *network, *conv3D_3a_tran->getOutput(0), data_type, "conv3D_3a_act");
assert(conv3D_3a_act != nullptr);
conv3D_3a_act->setName("conv3D_3a_act");
// conv3D_3b 3D convolution op.
auto conv3D_3b = addConv3D(plugin_factory, *network, *conv3D_3a_act->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 64, 3, 3}},
Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_3b_k"), weights.at("conv3D_3b_b"),
"conv3D_3b");
assert(conv3D_3b != nullptr);
conv3D_3b->setName("conv3D_3b");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_3b_tran = addTransform(plugin_factory, *network, *conv3D_3b->getOutput(0), {1, 0, 2, 3}, "conv3D_3b_tran_transform");
assert(conv3D_3b_tran != nullptr);
conv3D_3b_tran->setName("conv3D_3b_tran");
// conv3D_3b_act ELU activation op.
auto conv3D_3b_act = addElu(plugin_factory, *network, *conv3D_3b_tran->getOutput(0), data_type, "conv3D_3b_act");
assert(conv3D_3b_act != nullptr);
conv3D_3b_act->setName("conv3D_3b_act");
// conv3D_3ds_pad padding op.
auto conv3D_3ds_pad = addPad(plugin_factory, *network, *conv3D_3b_act->getOutput(0), {0, 0, 0, 0}, {1, 0, 0, 0}, "conv3D_3ds_pad");
assert(conv3D_3ds_pad != nullptr);
conv3D_3ds_pad->setName("conv3D_3ds_pad");
// conv3D_3ds 3D convolution op.
auto conv3D_3ds = addConv3D(plugin_factory, *network, *conv3D_3ds_pad->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 64, 3, 3}},
Dims{3, {2, 2, 2}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_3ds_k"), weights.at("conv3D_3ds_b"),
"conv3D_3ds");
assert(conv3D_3ds != nullptr);
conv3D_3ds->setName("conv3D_3ds");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_3ds_tran = addTransform(plugin_factory, *network, *conv3D_3ds->getOutput(0), {1, 0, 2, 3}, "conv3D_3ds_tran_transform");
assert(conv3D_3ds_tran != nullptr);
conv3D_3ds_tran->setName("conv3D_3ds_tran");
// conv3D_3ds_act ELU activation op.
auto conv3D_3ds_act = addElu(plugin_factory, *network, *conv3D_3ds_tran->getOutput(0), data_type, "conv3D_3ds_act");
assert(conv3D_3ds_act != nullptr);
conv3D_3ds_act->setName("conv3D_3ds_act");
// conv3D_4a 3D convolution op.
auto conv3D_4a = addConv3D(plugin_factory, *network, *conv3D_3ds_act->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 64, 3, 3}},
Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_4a_k"), weights.at("conv3D_4a_b"),
"conv3D_4a");
assert(conv3D_4a != nullptr);
conv3D_4a->setName("conv3D_4a");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_4a_tran = addTransform(plugin_factory, *network, *conv3D_4a->getOutput(0), {1, 0, 2, 3}, "conv3D_4a_tran_transform");
assert(conv3D_4a_tran != nullptr);
conv3D_4a_tran->setName("conv3D_4a_tran");
// conv3D_4a_act ELU activation op.
auto conv3D_4a_act = addElu(plugin_factory, *network, *conv3D_4a_tran->getOutput(0), data_type, "conv3D_4a_act");
assert(conv3D_4a_act != nullptr);
conv3D_4a_act->setName("conv3D_4a_act");
// conv3D_4b 3D convolution op.
auto conv3D_4b = addConv3D(plugin_factory, *network, *conv3D_4a_act->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 64, 3, 3}},
Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_4b_k"), weights.at("conv3D_4b_b"),
"conv3D_4b");
assert(conv3D_4b != nullptr);
conv3D_4b->setName("conv3D_4b");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_4b_tran = addTransform(plugin_factory, *network, *conv3D_4b->getOutput(0), {1, 0, 2, 3}, "conv3D_4b_tran_transform");
assert(conv3D_4b_tran != nullptr);
conv3D_4b_tran->setName("conv3D_4b_tran");
// conv3D_4b_act ELU activation op.
auto conv3D_4b_act = addElu(plugin_factory, *network, *conv3D_4b_tran->getOutput(0), data_type, "conv3D_4b_act");
assert(conv3D_4b_act != nullptr);
conv3D_4b_act->setName("conv3D_4b_act");
// conv3D_4ds_pad padding op.
auto conv3D_4ds_pad = addPad(plugin_factory, *network, *conv3D_4b_act->getOutput(0), {0, 0, 0, 0}, {1, 0, 0, 0}, "conv3D_4ds_pad");
assert(conv3D_4ds_pad != nullptr);
conv3D_4ds_pad->setName("conv3D_4ds_pad");
// conv3D_4ds 3D convolution op.
auto conv3D_4ds = addConv3D(plugin_factory, *network, *conv3D_4ds_pad->getOutput(0),
Conv3DType::kTensorFlow, {5, {128, 3, 64, 3, 3}},
Dims{3, {2, 2, 2}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_4ds_k"), weights.at("conv3D_4ds_b"),
"conv3D_4ds");
assert(conv3D_4ds != nullptr);
conv3D_4ds->setName("conv3D_4ds");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_4ds_tran = addTransform(plugin_factory, *network, *conv3D_4ds->getOutput(0), {1, 0, 2, 3}, "conv3D_4ds_tran_transform");
assert(conv3D_4ds_tran != nullptr);
conv3D_4ds_tran->setName("conv3D_4ds_tran");
// conv3D_4ds_act ELU activation op.
auto conv3D_4ds_act = addElu(plugin_factory, *network, *conv3D_4ds_tran->getOutput(0), data_type, "conv3D_4ds_act");
assert(conv3D_4ds_act != nullptr);
conv3D_4ds_act->setName("conv3D_4ds_act");
// conv3D_5a 3D convolution op.
auto conv3D_5a = addConv3D(plugin_factory, *network, *conv3D_4ds_act->getOutput(0),
Conv3DType::kTensorFlow, {5, {128, 3, 128, 3, 3}},
Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_5a_k"), weights.at("conv3D_5a_b"),
"conv3D_5a");
assert(conv3D_5a != nullptr);
conv3D_5a->setName("conv3D_5a");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto conv3D_5a_tran = addTransform(plugin_factory, *network, *conv3D_5a->getOutput(0), {1, 0, 2, 3}, "conv3D_5a_tran_transform");
assert(conv3D_5a_tran != nullptr);
conv3D_5a_tran->setName("conv3D_5a_tran");
// conv3D_5a_act ELU activation op.
auto conv3D_5a_act = addElu(plugin_factory, *network, *conv3D_5a_tran->getOutput(0), data_type, "conv3D_5a_act");
assert(conv3D_5a_act != nullptr);
conv3D_5a_act->setName("conv3D_5a_act");
// conv3D_5b 3D convolution op.
auto conv3D_5b = addConv3D(plugin_factory, *network, *conv3D_5a_act->getOutput(0),
Conv3DType::kTensorFlow, {5, {128, 3, 128, 3, 3}},
Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("conv3D_5b_k"), weights.at("conv3D_5b_b"),
"conv3D_5b");
assert(conv3D_5b != nullptr);
conv3D_5b->setName("conv3D_5b");
// conv3D_5b_act ELU activation op.
auto conv3D_5b_act = addElu(plugin_factory, *network, *conv3D_5b->getOutput(0), data_type, "conv3D_5b_act");
assert(conv3D_5b_act != nullptr);
conv3D_5b_act->setName("conv3D_5b_act");
// deconv3D_1 3D transposed convolution op.
Dims deconv3D_1_out_dims{4, {9, 64, 21, 65}};
auto deconv3D_1 = addConv3DTranspose(plugin_factory, *network, *conv3D_5b_act->getOutput(0),
Conv3DType::kTensorFlow, {5, {128, 3, 64, 3, 3}}, deconv3D_1_out_dims,
Dims{3, {2, 2, 2}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("deconv3D_1_k"), weights.at("deconv3D_1_b"),
"deconv3D_1");
assert(deconv3D_1 != nullptr);
deconv3D_1->setName("deconv3D_1");
// deconv3D_1_add_skip tensor add op.
auto deconv3D_1_add_skip = network->addElementWise(*(deconv3D_1->getOutput(0)), *(conv3D_4b_act->getOutput(0)), ElementWiseOperation::kSUM);
assert(deconv3D_1_add_skip != nullptr);
deconv3D_1_add_skip->setName("deconv3D_1_add_skip");
// deconv3D_1_act ELU activation op.
auto deconv3D_1_act = addElu(plugin_factory, *network, *deconv3D_1_add_skip->getOutput(0), data_type, "deconv3D_1_act");
assert(deconv3D_1_act != nullptr);
deconv3D_1_act->setName("deconv3D_1_act");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto deconv3D_1_transform = addTransform(plugin_factory, *network, *deconv3D_1_act->getOutput(0), {1, 0, 2, 3}, "deconv3D_1_transform_transform");
assert(deconv3D_1_transform != nullptr);
deconv3D_1_transform->setName("deconv3D_1_transform");
// deconv3D_2 3D transposed convolution op.
Dims deconv3D_2_out_dims{4, {17, 64, 41, 129}};
auto deconv3D_2 = addConv3DTranspose(plugin_factory, *network, *deconv3D_1_transform->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 64, 3, 3}}, deconv3D_2_out_dims,
Dims{3, {2, 2, 2}}, Dims{3, {1, 1, 1}}, Dims{3, {1, 1, 1}},
weights.at("deconv3D_2_k"), weights.at("deconv3D_2_b"),
"deconv3D_2");
assert(deconv3D_2 != nullptr);
deconv3D_2->setName("deconv3D_2");
// deconv3D_2_add_skip tensor add op.
auto deconv3D_2_add_skip = network->addElementWise(*(deconv3D_2->getOutput(0)), *(conv3D_3b_act->getOutput(0)), ElementWiseOperation::kSUM);
assert(deconv3D_2_add_skip != nullptr);
deconv3D_2_add_skip->setName("deconv3D_2_add_skip");
// deconv3D_2_act ELU activation op.
auto deconv3D_2_act = addElu(plugin_factory, *network, *deconv3D_2_add_skip->getOutput(0), data_type, "deconv3D_2_act");
assert(deconv3D_2_act != nullptr);
deconv3D_2_act->setName("deconv3D_2_act");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto deconv3D_2_transform = addTransform(plugin_factory, *network, *deconv3D_2_act->getOutput(0), {1, 0, 2, 3}, "deconv3D_2_transform_transform");
assert(deconv3D_2_transform != nullptr);
deconv3D_2_transform->setName("deconv3D_2_transform");
// deconv3D_3 3D transposed convolution op.
Dims deconv3D_3_out_dims{4, {35, 64, 81, 257}};
auto deconv3D_3 = addConv3DTranspose(plugin_factory, *network, *deconv3D_2_transform->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 64, 3, 3}}, deconv3D_3_out_dims,
Dims{3, {2, 2, 2}}, Dims{3, {0, 1, 1}}, Dims{3, {0, 1, 1}},
weights.at("deconv3D_3_k"), weights.at("deconv3D_3_b"),
"deconv3D_3");
assert(deconv3D_3 != nullptr);
deconv3D_3->setName("deconv3D_3");
// deconv3D_3 output slice op.
auto deconv3D_3_slice_layer = addSlice(plugin_factory, *network, *deconv3D_3->getOutput(0),
deconv3D_3_out_dims,
{4, {0, 0, 0, 0}},
{4, {deconv3D_3_out_dims.d[0] - 1, deconv3D_3_out_dims.d[1], deconv3D_3_out_dims.d[2], deconv3D_3_out_dims.d[3]}},
"deconv3D_3_slice");
assert(deconv3D_3_slice_layer != nullptr);
deconv3D_3_slice_layer->setName("deconv3D_3_slice_layer");
// deconv3D_3_add_skip tensor add op.
auto deconv3D_3_add_skip = network->addElementWise(*(deconv3D_3_slice_layer->getOutput(0)), *(conv3D_2b_act->getOutput(0)), ElementWiseOperation::kSUM);
assert(deconv3D_3_add_skip != nullptr);
deconv3D_3_add_skip->setName("deconv3D_3_add_skip");
// deconv3D_3_act ELU activation op.
auto deconv3D_3_act = addElu(plugin_factory, *network, *deconv3D_3_add_skip->getOutput(0), data_type, "deconv3D_3_act");
assert(deconv3D_3_act != nullptr);
deconv3D_3_act->setName("deconv3D_3_act");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto deconv3D_3_transform = addTransform(plugin_factory, *network, *deconv3D_3_act->getOutput(0), {1, 0, 2, 3}, "deconv3D_3_transform_transform");
assert(deconv3D_3_transform != nullptr);
deconv3D_3_transform->setName("deconv3D_3_transform");
// deconv3D_4 3D transposed convolution op.
Dims deconv3D_4_out_dims{4, {69, 32, 161, 513}};
auto deconv3D_4 = addConv3DTranspose(plugin_factory, *network, *deconv3D_3_transform->getOutput(0),
Conv3DType::kTensorFlow, {5, {64, 3, 32, 3, 3}}, deconv3D_4_out_dims,
Dims{3, {2, 2, 2}}, Dims{3, {0, 1, 1}}, Dims{3, {0, 1, 1}},
weights.at("deconv3D_4_k"), weights.at("deconv3D_4_b"),
"deconv3D_4");
assert(deconv3D_4 != nullptr);
deconv3D_4->setName("deconv3D_4");
// deconv3D_4 output slice op.
auto deconv3D_4_slice_layer = addSlice(plugin_factory, *network, *deconv3D_4->getOutput(0),
deconv3D_4_out_dims,
{4, {0, 0, 0, 0}},
{4, {deconv3D_4_out_dims.d[0] - 1, deconv3D_4_out_dims.d[1], deconv3D_4_out_dims.d[2], deconv3D_4_out_dims.d[3]}},
"deconv3D_4_slice");
assert(deconv3D_4_slice_layer != nullptr);
deconv3D_4_slice_layer->setName("deconv3D_4_slice_layer");
// deconv3D_4_add_skip tensor add op.
auto deconv3D_4_add_skip = network->addElementWise(*(deconv3D_4_slice_layer->getOutput(0)), *(conv3D_1b_act->getOutput(0)), ElementWiseOperation::kSUM);
assert(deconv3D_4_add_skip != nullptr);
deconv3D_4_add_skip->setName("deconv3D_4_add_skip");
// deconv3D_4_act ELU activation op.
auto deconv3D_4_act = addElu(plugin_factory, *network, *deconv3D_4_add_skip->getOutput(0), data_type, "deconv3D_4_act");
assert(deconv3D_4_act != nullptr);
deconv3D_4_act->setName("deconv3D_4_act");
// Transpose output: KDHW -> DKHW for conv3d and DKHW -> KDHW for conv3d_transpose
auto deconv3D_4_transform = addTransform(plugin_factory, *network, *deconv3D_4_act->getOutput(0), {1, 0, 2, 3}, "deconv3D_4_transform_transform");
assert(deconv3D_4_transform != nullptr);
deconv3D_4_transform->setName("deconv3D_4_transform");
// deconv3D_5 3D transposed convolution op.
Dims deconv3D_5_out_dims{4, {137, 1, 321, 1025}};
auto deconv3D_5 = addConv3DTranspose(plugin_factory, *network, *deconv3D_4_transform->getOutput(0),
Conv3DType::kTensorFlow, {5, {32, 3, 1, 3, 3}}, deconv3D_5_out_dims,
Dims{3, {2, 2, 2}}, Dims{3, {0, 1, 1}}, Dims{3, {0, 1, 1}},
weights.at("deconv3D_5_k"), weights.at("deconv3D_5_b"),
"deconv3D_5");
assert(deconv3D_5 != nullptr);
deconv3D_5->setName("deconv3D_5");
// deconv3D_5 output slice op.
auto deconv3D_5_slice_layer = addSlice(plugin_factory, *network, *deconv3D_5->getOutput(0),
deconv3D_5_out_dims,
{4, {0, 0, 0, 0}},
{4, {deconv3D_5_out_dims.d[0] - 1, deconv3D_5_out_dims.d[1], deconv3D_5_out_dims.d[2], deconv3D_5_out_dims.d[3]}},
"deconv3D_5_slice");
assert(deconv3D_5_slice_layer != nullptr);
deconv3D_5_slice_layer->setName("deconv3D_5_slice_layer");
// Softargmax.
auto disp = addSoftargmax(plugin_factory, *network, *deconv3D_5_slice_layer->getOutput(0), SoftargmaxType::kMin, data_type, "disp_softargmax");
assert(disp != nullptr);
disp->setName("disp");
auto disp_out = disp->getOutput(0);
disp_out->setName("disp");
network->markOutput(*disp_out);
return network;
}
} } // namespace
| 57.873674 | 160 | 0.694043 | [
"3d"
] |
54eae3b2d0f63acf3dd62f4e5e16ba588d0b9c63 | 1,157 | cpp | C++ | mine/17-letter_combination_of_a_phone_number.cpp | Junlin-Yin/myLeetCode | 8a33605d3d0de9faa82b5092a8e9f56b342c463f | [
"MIT"
] | null | null | null | mine/17-letter_combination_of_a_phone_number.cpp | Junlin-Yin/myLeetCode | 8a33605d3d0de9faa82b5092a8e9f56b342c463f | [
"MIT"
] | null | null | null | mine/17-letter_combination_of_a_phone_number.cpp | Junlin-Yin/myLeetCode | 8a33605d3d0de9faa82b5092a8e9f56b342c463f | [
"MIT"
] | null | null | null | class Solution {
public:
vector<string> recursiveBody(vector<string> prev, string digits){
if(digits.size() == 0) return prev;
char c = digits[0];
vector<char> c_digits;
switch(c){
case '2': c_digits = {'a', 'b', 'c'}; break;
case '3': c_digits = {'d', 'e', 'f'}; break;
case '4': c_digits = {'g', 'h', 'i'}; break;
case '5': c_digits = {'j', 'k', 'l'}; break;
case '6': c_digits = {'m', 'n', 'o'}; break;
case '7': c_digits = {'p', 'q', 'r', 's'}; break;
case '8': c_digits = {'t', 'u', 'v'}; break;
case '9': c_digits = {'w', 'x', 'y', 'z'};
}
vector<string> curr;
if(prev.size() == 0) prev = {""};
for(auto s: prev){
for(auto d: c_digits){
string ss = s;
ss.push_back(d);
curr.push_back(ss);
}
}
return recursiveBody(curr, digits.substr(1));
}
vector<string> letterCombinations(string digits) {
return recursiveBody(vector<string>(), digits);
}
}; | 36.15625 | 70 | 0.438202 | [
"vector"
] |
54f1b14524d2cccc20770776a896b2a5696d51f2 | 707 | hpp | C++ | input/raw/out_of_band.hpp | 5cript/debugger-interface | 61d6fd73275b2240f61f19a3978015d9bb0c1e3c | [
"MIT"
] | null | null | null | input/raw/out_of_band.hpp | 5cript/debugger-interface | 61d6fd73275b2240f61f19a3978015d9bb0c1e3c | [
"MIT"
] | null | null | null | input/raw/out_of_band.hpp | 5cript/debugger-interface | 61d6fd73275b2240f61f19a3978015d9bb0c1e3c | [
"MIT"
] | null | null | null | #pragma once
#include "result.hpp"
#include "../../adapt.hpp"
#include <boost/optional.hpp>
namespace DebuggerInterface::RawData
{
struct StreamRecord
{
char type;
std::string value;
bool wasSet;
};
struct OutOfBand
{
boost::optional <long long> token;
char type;
std::string asyncClass;
std::vector <Result> results;
StreamRecord streamRecord;
};
}
BOOST_FUSION_ADAPT_STRUCT
(
DebuggerInterface::RawData::StreamRecord,
type, value, wasSet
)
BOOST_FUSION_ADAPT_STRUCT
(
DebuggerInterface::RawData::OutOfBand,
token, type, asyncClass, results, streamRecord
)
| 18.128205 | 51 | 0.612447 | [
"vector"
] |
54f28722deb9ede394afe429e13c60275b2058c1 | 4,274 | hpp | C++ | 3rdparty/mml/mml/src/mml/window/unix/clipboard_impl.hpp | ValtoForks/EtherealEngine | ab769803dcd71a61c2805afd259959b62fcdc1ff | [
"BSD-2-Clause"
] | 791 | 2016-11-04T14:13:41.000Z | 2022-03-20T20:47:31.000Z | 3rdparty/mml/mml/src/mml/window/unix/clipboard_impl.hpp | ValtoForks/EtherealEngine | ab769803dcd71a61c2805afd259959b62fcdc1ff | [
"BSD-2-Clause"
] | 28 | 2016-12-01T05:59:30.000Z | 2021-03-20T09:49:26.000Z | 3rdparty/mml/mml/src/mml/window/unix/clipboard_impl.hpp | ValtoForks/EtherealEngine | ab769803dcd71a61c2805afd259959b62fcdc1ff | [
"BSD-2-Clause"
] | 151 | 2016-12-21T09:44:43.000Z | 2022-03-31T13:42:18.000Z | #ifndef MML_CLIPBOARD_IMPL_HPP
#define MML_CLIPBOARD_IMPL_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <X11/Xlib.h>
#include <deque>
#include <string>
namespace mml
{
namespace priv
{
////////////////////////////////////////////////////////////
/// \brief Give access to the system clipboard
///
////////////////////////////////////////////////////////////
class clipboard_impl
{
public:
////////////////////////////////////////////////////////////
/// \brief Get the content of the clipboard as string data
///
/// This function returns the content of the clipboard
/// as a string. If the clipboard does not contain string
/// it returns an empty string object.
///
/// \return Current content of the clipboard
///
////////////////////////////////////////////////////////////
static std::string get_string();
////////////////////////////////////////////////////////////
/// \brief Set the content of the clipboard as string data
///
/// This function sets the content of the clipboard as a
/// string.
///
/// \param text string object containing the data to be sent
/// to the clipboard
///
////////////////////////////////////////////////////////////
static void set_string(const std::string& text);
////////////////////////////////////////////////////////////
/// \brief Process pending events for the hidden clipboard window
///
/// This function has to be called as part of normal window
/// event processing in order for our application to respond
/// to selection requests from other applications.
///
////////////////////////////////////////////////////////////
static void process_events();
private:
////////////////////////////////////////////////////////////
/// \brief Constructor
///
////////////////////////////////////////////////////////////
clipboard_impl();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~clipboard_impl();
////////////////////////////////////////////////////////////
/// \brief Get singleton instance
///
/// \return Singleton instance
///
////////////////////////////////////////////////////////////
static clipboard_impl& get_instance();
////////////////////////////////////////////////////////////
/// \brief getString implementation
///
/// \return Current content of the clipboard
///
////////////////////////////////////////////////////////////
std::string get_string_impl();
////////////////////////////////////////////////////////////
/// \brief setString implementation
///
/// \param text sf::String object containing the data to be sent to the clipboard
///
////////////////////////////////////////////////////////////
void set_string_impl(const std::string& text);
////////////////////////////////////////////////////////////
/// \brief processEvents implementation
///
////////////////////////////////////////////////////////////
void process_events_impl();
////////////////////////////////////////////////////////////
/// \brief Process an incoming event from the window
///
/// \param windowEvent Event which has been received
///
////////////////////////////////////////////////////////////
void process_event(XEvent& windowEvent);
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
::Window m_window; ///< X identifier defining our window
::Display* m_display; ///< Pointer to the display
Atom m_clipboard; ///< X Atom identifying the CLIPBOARD selection
Atom m_targets; ///< X Atom identifying TARGETS
Atom m_text; ///< X Atom identifying TEXT
Atom m_utf8String; ///< X Atom identifying UTF8_STRING
Atom m_targetProperty; ///< X Atom identifying our destination window property
std::string m_clipboardContents; ///< Our clipboard contents
std::deque<XEvent> m_events; ///< Queue we use to store pending events for this window
bool m_requestResponded; ///< Holds whether our selection request has been responded to or not
};
} // namespace priv
} // namespace mml
#endif // MML_CLIPBOARD_IMPL_HPP
| 33.390625 | 97 | 0.441507 | [
"object"
] |
07098efaca677b8480ad29eab53d91ae451fb59c | 5,169 | cpp | C++ | src/AerialImage.cpp | matheusbg8/aracati2017 | bb00a847e02087f012c9094126120ea5f0a9324c | [
"MIT"
] | 1 | 2022-03-24T04:46:50.000Z | 2022-03-24T04:46:50.000Z | src/AerialImage.cpp | matheusbg8/aracati2017 | bb00a847e02087f012c9094126120ea5f0a9324c | [
"MIT"
] | null | null | null | src/AerialImage.cpp | matheusbg8/aracati2017 | bb00a847e02087f012c9094126120ea5f0a9324c | [
"MIT"
] | 1 | 2022-01-01T04:28:31.000Z | 2022-01-01T04:28:31.000Z | #include "AerialImage.h"
bool AerialImage::loadYaml(const path &file)
{
// if(!is_regular_file(file))
// return false;
//cout << "Load map config from " << file.string() << endl;
FileStorage fs;
fs.open(file.string(), FileStorage::READ | FileStorage::FORMAT_YAML);
if (!fs.isOpened())
{
cerr << "Failed to open " << file.string() << endl;
return false;
}
const FileNode &nP1 = fs["p1"],
&nP2 = fs["p2"];
int zone1,zone2;
Point2d p1((double(nP1["lat"])),double(nP1["long"])),
p2((double(nP2["lat"])),double(nP2["long"]));
UTMRef[0] = latLon2UTM(p1,&zone1);
imgRef[0].x = double(nP1["pix_x"]);
imgRef[0].y = double(nP1["pix_y"]);
UTMRef[1] = latLon2UTM(p2,&zone2);
imgRef[1].x = double(nP2["pix_x"]);
imgRef[1].y = double(nP2["pix_y"]);
//cout << UTMRef[0] << " zone " << zone1 << endl
// << imgRef[0] << endl << endl
// << UTMRef[1] << " zone " << zone2 << endl
// << imgRef[1] << endl << endl;
if(zone1 != zone2)
{
cout << "Warnig: Coords in different zone!!!!!" << endl;
return false;
}
Point2d diffImg = imgRef[1] - imgRef[0],
diffUTM = UTMRef[1] - UTMRef[0];
// Compute scale transform from UTM to pixel
// taking two reference points on both coordinate system
UTM2Img_.x = diffImg.x/diffUTM.x;
UTM2Img_.y = diffImg.y/diffUTM.y;
return true;
}
AerialImage::AerialImage()
{
}
void AerialImage::resizeToMaxCols(int maxCols)
{
double scale = double(maxCols)/mapImg.cols;
resize(mapImg,mapImg,Size(), scale,scale);
imgRef[0]*= scale;
imgRef[1]*= scale;
UTM2Img_*=scale;
}
/**
* @brief AerialImage::getRectThatFitsIntoImg
* Giving a rect and an image, return an adjusted rect
* that fits into the image. top,bottom, left and right
* are output parameters that tells how many pixels
* were missing on each direction. This information
* can be used for a padding strategy.
* If the gave rect is completely out of the image
* a empty rect is returned and -1 on the output
* parameters.
* @param r - Input - Initial rect.
* @param top - Outout - changes on top of the rect.
* @param bottom - Output - changes on bottom of the rect.
* @param left - Outoput - changes on left of the rect.
* @param right - Output - changens on right of the rect.
* @return new rect that fits into the aerial image. An empty rect
* is returned if it is not possible to fit the rect.
*/
Rect AerialImage::getTranslateRectToFit(const Rect &r, int &top, int &bottom, int &left, int &right) const
{
top = bottom = left = right = 0;
int minX = r.x, maxX = r.x + r.width,
minY = r.y, maxY = r.y + r.height;
if(maxX < 0 || minX > mapImg.cols ||
maxY < 0 || minY > mapImg.rows)
{
top=bottom=left=right=-1;
return Rect();
}
Rect fr(r);
if(minX < 0)
{
fr.width+=minX; // Increased
fr.x =0; // moved to right
left=-minX;
}
if(maxX > mapImg.cols)
{
fr.width = mapImg.cols - fr.x;
right = maxX - mapImg.cols;
}
if(minY < 0)
{
fr.height+=fr.y;
fr.y = 0;
top = -minY;
}
if(maxY > mapImg.rows)
{
fr.height = mapImg.rows - fr.y;
bottom = maxY - mapImg.rows;
}
return fr;
}
bool AerialImage::loadMap(const path &mapFile)
{
path yamlFile(mapFile),
imgFile(mapFile);
bool succes = false;
yamlFile.replace_extension(".yaml");
mapName = mapFile.stem().string();
if(!loadYaml(yamlFile))
return false;
imgFile.replace_extension(".jpg");
succes = is_regular(imgFile);
// Try png
if(!succes)
{
imgFile.replace_extension(".png");
succes = is_regular(imgFile);
}
// Try jpeg
if(!succes)
{
imgFile.replace_extension(".jpeg");
succes = is_regular(imgFile);
}
if(!succes)
return false;
mapImg = imread(imgFile.string());
if(mapImg.empty())
{
cerr << "Error: Could not open map img " << imgFile.string() <<endl;
return false;
}
return true;
}
bool AerialImage::isOnMap(const Point2f &p)
{
Point2i pImg = UTM2Img(p);
if(pImg.x < 0 || pImg.x >= mapImg.cols ||
pImg.y < 0 || pImg.y >= mapImg.rows)
return false;
return true;
}
bool AerialImage::isOnMapImg(const Point2f &pImg)
{
if(pImg.x < 0 || pImg.x >= mapImg.cols ||
pImg.y < 0 || pImg.y >= mapImg.rows)
return false;
return true;
}
Point2d AerialImage::UTM2Img(const Point2d &UTMp) const
{
return Point2d (imgRef[0].x + (UTMp.x - UTMRef[0].x)*UTM2Img_.x,
imgRef[0].y + (UTMp.y - UTMRef[0].y)*UTM2Img_.y);
}
Point2d AerialImage::Img2UTM(const Point2d &ImgP) const
{
// First convert img point to the origin (reference point 0)
// Second apply the scale, now it is in UTM units and out of the center
// Third translate to the UTM reference
return Point2d (UTMRef[0].x + (ImgP.x - imgRef[0].x)/UTM2Img_.x,
UTMRef[0].y + (ImgP.y - imgRef[0].y)/UTM2Img_.y);
}
Point2d AerialImage::UTM2ImgRatio() const
{
return UTM2Img_;
}
const Mat &AerialImage::getMapImg() const
{
return mapImg;
}
string AerialImage::name()
{
return mapName;
}
| 23.179372 | 106 | 0.609402 | [
"transform"
] |
071002e68c1bfb13e5680b67aec4c971e825ac30 | 25,166 | hpp | C++ | src/old_arrayview.hpp | dblalock/conv | 90ef25db56a1f8855b8aa4950acd3b57499700d5 | [
"Apache-2.0"
] | null | null | null | src/old_arrayview.hpp | dblalock/conv | 90ef25db56a1f8855b8aa4950acd3b57499700d5 | [
"Apache-2.0"
] | null | null | null | src/old_arrayview.hpp | dblalock/conv | 90ef25db56a1f8855b8aa4950acd3b57499700d5 | [
"Apache-2.0"
] | null | null | null | //
// array.hpp
// Arr
//
// Created by DB on 11/21/18.
// Copyright © 2018 D Blalock. All rights reserved.
//
#ifndef arrayview_h
#define arrayview_h
#include <array>
#include <assert.h>
//#include "bint.hpp"
#include "macros.hpp" // for SFINAE macros
namespace ar {
//#include "array_utils.hpp" // for debug
// /** elements of tensor are contiguous along this ax with stride of 1;
// * e.g., axis 1 in a row-major matrix
// */
// class ContiguousAx {
// static const bool is_contig = true;
// static const bool is_dense = true;
// static const bool is_strided = true;
// };
/** elements of tensor are not contiguous along this ax, but
* sub-arrays are; e.g., axis 0 in a row-major matrix
*
* Dense along ax0:
* x x x x
* x x x x
* x x x x
*
* Not dense along ax0, but still strided:
*
* x x x x
*
* x x x x
*
* x x x x
*
* Not strided (ie, with uniform stride) along ax0:
*
* x x x x
* x x x x
*
* x x x x
*
* Dense along ax0, but only strided along ax1:
*
* x x x x
* x x x x
* x x x x
*/
// template<int Used=true>
// class DenseAx {
// static const int is_used = Used;
// static const bool is_contig = false;
// static const bool is_dense = true;
// static const bool is_strided = true;
// };
// template<int Used=false> class StridedAx {
// static const int is_used = Used;
// static const bool is_contig = false;
// static const bool is_dense = false;
// static const bool is_strided = true;
// };
// // for stuff like where(); not sure how to support this
// template<int Used=false> class ChaosAx {
// static const int is_used = Used;
// static const bool is_contig = false;
// static const bool is_dense = false;
// static const bool is_strided = false;
// };
using DefaultIndexType = int32_t;
// =============================================================== Static Sizes
struct anySz {
static const int is_valid = false;
static const int min = 0;
static const int max = 0;
};
using NoBounds = anySz; // AnySz is shorter in errors, but less clear in code
template<int Value=-1> struct ConstSize {
static const int is_valid = Value > 0;
static const int min = Value;
static const int max = Value;
};
template<int StaticSize, typename = void>
struct getSizeBound { using type = NoBounds; };
template<int StaticSize>
struct getSizeBound<StaticSize, ENABLE_IF(StaticSize > 0)>
{
using type = ConstSize<StaticSize>;
};
// ================================================================ Axis
struct AxisAttr {
enum {
Unused = 0,
Used = 1 << 0,
Strided = 1 << 1,
Dense = 1 << 2,
Contiguous = 1 << 3,
// these are for convenience when defining axis attributes, since
// stronger contiguity traits imply less strong ones
StridedMask = Strided,
DenseMask = Strided | Dense,
ContiguousMask = Strided | Dense | Contiguous
};
};
template<int Attrs=AxisAttr::Unused, class SizeBounds=NoBounds>
struct Axis {
static const int attrs = Attrs;
static const int is_used = Attrs & AxisAttr::Used;
static const bool is_strided = Attrs & AxisAttr::Strided;
static const bool is_dense = Attrs & AxisAttr::Dense;
static const bool is_contig = Attrs & AxisAttr::Contiguous;
// static const int stride = StaticStride;
using size_bounds = SizeBounds;
};
template<bool Contiguous=false, bool Dense=true, bool Strided=true,
int Used=true, class SizeBounds=NoBounds>
// int Used=true, int StaticStride=0, class SizeBounds=NoBounds>
struct make_axis {
static const int attrs =
(Contiguous ? AxisAttr::Contiguous : 0) |
(Dense ? AxisAttr::Dense : 0) |
(Strided ? AxisAttr::Strided : 0) |
(Used ? AxisAttr::Used : 0);
using type = Axis<attrs, SizeBounds>;
};
// ------------------------------------------------ axis aliases
using AxisContig = Axis<AxisAttr::ContiguousMask | AxisAttr::Used>;
using AxisDense = Axis<AxisAttr::DenseMask | AxisAttr::Used>;
using AxisStrided = Axis<AxisAttr::StridedMask | AxisAttr::Used>;
using AxisUnused = Axis<AxisAttr::Unused>;
// ------------------------------------------------ axis manipulation
template<class AxisT, bool Contig> struct setAxisContiguous {
using type = typename make_axis<Contig, AxisT::is_dense, AxisT::is_strided,
AxisT::is_used, typename AxisT::SizeBounds>::type;
};
template<class AxisT, bool Dense> struct setAxisDense {
using type = typename make_axis<AxisT::is_contig, Dense, AxisT::is_strided,
AxisT::is_used, typename AxisT::SizeBounds>::type;
};
template<class AxisT, bool Strided> struct setAxisStrided {
using type = typename make_axis<AxisT::is_contig, AxisT::is_dense, Strided,
AxisT::is_used, typename AxisT::SizeBounds>::type;
};
template<class AxisT, int Used> struct setAxisUsed {
using type = typename make_axis<AxisT::is_contig, AxisT::is_dense,
AxisT::is_strided, Used, typename AxisT::SizeBounds>::type;
};
// template<class AxisT, int Stride> struct setAxisStaticStride {
// using type = Axis<AxisT::is_contig && (Stride == 1), AxisT::is_dense,
// AxisT::is_strided, AxisT::is_used, Stride, typename AxisT::SizeBounds>;
// };
template<class AxisT, class SizeBounds> struct setAxisSizeBounds {
static const int attrs = AxisT::attrs;
using type = Axis<attrs, SizeBounds>;
};
template<class AxisT, int StaticSize> struct setAxisStaticSize {
// using SizeBoundsT = ConstSize<StaticSize>;
using SizeBoundsT = typename getSizeBound<StaticSize>::type;
using type = typename setAxisSizeBounds<AxisT, SizeBoundsT>::type;
};
#define SET_AXIS_PROP(STRUCT_NAME, AXES_T, AX, VAL) \
typename STRUCT_NAME<GET_AXIS_T(AXES_T, AX), VAL>::type
#define SET_AXIS_CONTIGUOUS(AXES_T, AX, BOOL) \
SET_AXIS_PROP(setAxisContiguous, AXES_T, AX, BOOL)
#define SET_AXIS_DENSE(AXES_T, AX, BOOL) \
SET_AXIS_PROP(setAxisDense, AXES_T, AX, BOOL)
#define SET_AXIS_STRIDED(AXES_T, AX, BOOL) \
SET_AXIS_PROP(setAxisStrided, AXES_T, AX, BOOL)
#define SET_AXIS_USED(AXES_T, AX, BOOL) \
SET_AXIS_PROP(setAxisUsed, AXES_T, AX, BOOL)
// typename setAxisContiguous(GET_AXIS_T(AXES_T, AX), BOOL)::type
#define SET_AXIS_SIZE(AXES_T, AX, BOOL) \
SET_AXIS_PROP(setAxisStaticSize, AXES_T, AX, BOOL)
// ============================================================= Storage Order
struct StorageOrders {
// enum { Unspecified = -1, RowMajor = 0, ColMajor = 1, NCHW = 2};
enum { Unspecified = 0, RowMajor = 1, ColMajor = 2, NCHW = 3};
};
// template<int Order> struct StorageOrder { };
// template<> struct StorageOrder<StorageOrders::RowMajor> {
// static constexpr std::array<int, 4> order {3, 2, 1, 0};
// };
/** This is to get ND indices from cuda thread/block indices */
template<int Rank, int Order> struct idxs_from_flat_idx {};
template<int Order> struct idxs_from_flat_idx<1, Order> {
template<class ShapeT, class IdxT>
ShapeT operator()(const ShapeT& shape, IdxT idx) {
return idx;
}
};
template<> struct idxs_from_flat_idx<2, StorageOrders::RowMajor> {
template<class ShapeT, class IdxT>
ShapeT operator()(const ShapeT& shape, IdxT idx) {
return {idx / shape[1], idx % shape[1]};
}
};
template<> struct idxs_from_flat_idx<2, StorageOrders::ColMajor> {
template<class ShapeT, class IdxT>
ShapeT operator()(const ShapeT& shape, IdxT idx) {
return {idx % shape[0], idx / shape[0]};
}
};
template<> struct idxs_from_flat_idx<3, StorageOrders::RowMajor> {
template<class ShapeT, class IdxT>
ShapeT operator()(const ShapeT& shape, IdxT idx) {
auto rowidx = idx / (shape[1] * shape[2]);
auto flat_idx_into_row = idx % (shape[1] * shape[2]);
auto colidx = (flat_idx_into_row / shape[2]);
return {rowidx, colidx, idx % shape[2]};
}
};
template<> struct idxs_from_flat_idx<3, StorageOrders::ColMajor> {
template<class ShapeT, class IdxT>
ShapeT operator()(const ShapeT& shape, IdxT idx) {
auto chanidx = idx / (shape[0] * shape[1]);
auto flat_idx_into_channel = idx % (shape[0] * shape[1]);
auto colidx = flat_idx_into_channel / shape[0];
return {idx % shape[0], colidx, chanidx};
}
};
template<> struct idxs_from_flat_idx<4, StorageOrders::RowMajor> {
template<class ShapeT, class IdxT>
ShapeT operator()(const ShapeT& shape, IdxT idx) {
auto one_sample_sz = shape[1] * shape[2] * shape[3];
auto sampleidx = idx / one_sample_sz;
auto idx_into_sample = idx % one_sample_sz;
auto sample_idxs = idxs_from_flat_idx<3, StorageOrders::RowMajor>{}(
ShapeT{shape[1], shape[1], shape[3]}, idx_into_sample);
return {sampleidx, sample_idxs[0], sample_idxs[1], sample_idxs[2]};
}
};
template<> struct idxs_from_flat_idx<4, StorageOrders::ColMajor> {
// TODO impl this if needed
};
// template<> struct idxs_from_flat_idx<4, StorageOrders::NCHW> {
// template<class ShapeT, class IdxT>
// ShapeT operator()(const ShapeT& shape, IdxT idx) {
// auto one_sample_sz = shape[1] * shape[2] * shape[3];
// auto sample_idx = idx / one_sample_sz;
// auto idx_into_sample = idx % one_sample_sz;
// auto one_channel_sz = shape[1] * shape[2];
// auto chan_idx = idx_into_sample / one_channel_sz;
// auto idx_into_channel = idx_into_sample % one_channel_sz;
// auto one_row_sz = shape[2];
// auto row_idx = idx_into_channel / one_row_sz;
// auto col_idx = idx_into_channel % one_row_sz;
// return {sample_idx, row_idx, col_idx, chan_idx};
// }
// };
// compute Axes storage order based on axis characteristics
// ================================================================ Axes
// ------------------------------------------------ axis type
// TODO need some type information for whether the whole thing is one
// contiguous chunk of memory or not; this is the common case, but can only
// know that it is if it's never been sliced/selected from except as one
// contiguous slice along major axis; probably replace int Order here with
// int Attrs, where low bits are Order and higher bits for contiguous and
// potential other info (such as storage format (eg, rle compressed), or
// padding info); and maybe do nums mod 10 as indicators so options are
// legible in dbg msgs (eg, 457 = 4,5,7, instead of inscrutable bit combo)
template<class Ax0=AxisContig, class Ax1=AxisUnused,
class Ax2=AxisUnused, class Ax3=AxisUnused,
class Ax4=AxisUnused, int Order=StorageOrders::Unspecified>
struct Axes {
using AxisT0 = Ax0;
using AxisT1 = Ax1;
using AxisT2 = Ax2;
using AxisT3 = Ax3;
using AxisT4 = Ax4;
// static const int debug = false; // TODO rm
static const int order = Order;
static const int rank = Ax0::is_used + Ax1::is_used + Ax2::is_used +
Ax3::is_used + Ax4::is_used;
static const bool is_any_ax_contig =
Ax0::is_contig || Ax1::is_contig || Ax2::is_contig ||
Ax3::is_contig || Ax4::is_contig;
// XXX if rank 3 or more, one ax will be strided even if whole array is one
// contiguous chunk of memory
static const bool is_dense = (rank >= 1) &&
(Ax0::is_dense || !Ax0::is_used) &&
(Ax1::is_dense || !Ax1::is_used) &&
(Ax2::is_dense || !Ax2::is_used) &&
(Ax3::is_dense || !Ax3::is_used) &&
(Ax4::is_dense || !Ax4::is_used);
// static const int is_rowmajor = Ax0::is_contig
// is_dense -> one ax must be contiguous, or this makes no sense
static_assert(!is_dense || is_any_ax_contig,
"Somehow dense, but nothing contiguous!?");
};
// template<int Ax, class Axis> struct getAxis {};
// template<class Axis>
// ------------------------------------------------ aliases for common axes
using AxesDense1D =
Axes<AxisContig, AxisUnused, AxisUnused, AxisUnused, AxisUnused, StorageOrders::RowMajor>;
using AxesRowMajor2D =
Axes<AxisDense, AxisContig, AxisUnused, AxisUnused, AxisUnused, StorageOrders::RowMajor>;
using AxesRowMajor3D =
Axes<AxisDense, AxisDense, AxisContig, AxisUnused, AxisUnused, StorageOrders::RowMajor>;
using AxesRowMajor4D =
Axes<AxisDense, AxisDense, AxisDense, AxisContig, AxisUnused, StorageOrders::RowMajor>;
using AxesRowMajor5D =
Axes<AxisDense, AxisDense, AxisDense, AxisDense, AxisContig, StorageOrders::RowMajor>;
using AxesColMajor2D =
Axes<AxisContig, AxisDense, AxisUnused, AxisUnused, AxisUnused, StorageOrders::ColMajor>;
using AxesColMajor3D =
Axes<AxisContig, AxisDense, AxisDense, AxisUnused, AxisUnused, StorageOrders::ColMajor>;
using AxesColMajor4D =
Axes<AxisContig, AxisDense, AxisDense, AxisDense, AxisUnused, StorageOrders::ColMajor>;
using AxesColMajor5D =
Axes<AxisContig, AxisDense, AxisDense, AxisDense, AxisDense, StorageOrders::ColMajor>;
// using AxesNCHW =
// Axes<AxisDense, AxisDense, AxisContig, AxisDense, AxisUnused, StorageOrders::NCHW>;
// ------------------------------------------------ axes manipulation
template<int ax, class Axes> struct getAxis {};
template<class Axes> struct getAxis<0, Axes> { using type = typename Axes::AxisT0; };
template<class Axes> struct getAxis<1, Axes> { using type = typename Axes::AxisT1; };
template<class Axes> struct getAxis<2, Axes> { using type = typename Axes::AxisT2; };
template<class Axes> struct getAxis<3, Axes> { using type = typename Axes::AxisT3; };
template<class Axes> struct getAxis<4, Axes> { using type = typename Axes::AxisT4; };
#define GET_AXIS_T(AXES, INT) typename getAxis<INT, AXES>::type
// template<class AxesT, int StaticDim0=0, int StaticDim1=0, int StaticDim2=0, int StaticDim3=0>
template<class AxesT, int StaticDim0=0, int StaticDim1=0, int StaticDim2=0,
int StaticDim3=0, int StaticDim4=0>
struct setStaticSizes {
using AxisT0 = SET_AXIS_SIZE(AxesT, 0, StaticDim0);
using AxisT1 = SET_AXIS_SIZE(AxesT, 1, StaticDim1);
using AxisT2 = SET_AXIS_SIZE(AxesT, 2, StaticDim2);
using AxisT3 = SET_AXIS_SIZE(AxesT, 3, StaticDim3);
using AxisT4 = SET_AXIS_SIZE(AxesT, 4, StaticDim4);
static const int order = AxesT::order;
using type = Axes<AxisT0, AxisT1, AxisT2, AxisT3, AxisT4, order>;
};
template<int Rank, int Order> struct GetDefaultAxesType {};
template<> struct GetDefaultAxesType<1, StorageOrders::RowMajor> { using type = AxesDense1D; };
template<> struct GetDefaultAxesType<1, StorageOrders::ColMajor> { using type = AxesDense1D; };
template<> struct GetDefaultAxesType<2, StorageOrders::RowMajor> { using type = AxesRowMajor2D; };
template<> struct GetDefaultAxesType<2, StorageOrders::ColMajor> { using type = AxesColMajor2D; };
template<> struct GetDefaultAxesType<3, StorageOrders::RowMajor> { using type = AxesRowMajor3D; };
template<> struct GetDefaultAxesType<3, StorageOrders::ColMajor> { using type = AxesColMajor3D; };
template<> struct GetDefaultAxesType<4, StorageOrders::RowMajor> { using type = AxesRowMajor4D; };
template<> struct GetDefaultAxesType<4, StorageOrders::ColMajor> { using type = AxesColMajor4D; };
template<> struct GetDefaultAxesType<5, StorageOrders::RowMajor> { using type = AxesRowMajor5D; };
template<> struct GetDefaultAxesType<5, StorageOrders::ColMajor> { using type = AxesColMajor5D; };
// template<> struct GetDefaultAxesType<4, StorageOrders::NCHW> { using type = AxesNCHW; };
template<int Rank, int Order, int StaticDim0, int StaticDim1,
int StaticDim2, int StaticDim3, int StaticDim4>
struct GetAxesType {
using baseAxesType = typename GetDefaultAxesType<Rank, Order>::type;
// static_assert(baseAxesType::attrItDoesntHave, "type of GetAxesType: ");
using type = typename setStaticSizes<
baseAxesType, StaticDim0, StaticDim1, StaticDim2, StaticDim3, StaticDim4>::type;
};
// ------------------------------------------------ strides for various axes
template<class AxesT, class IdxT=DefaultIndexType>
std::array<IdxT, AxesT::rank> default_strides_for_shape(
std::array<IdxT, AxesT::rank> shape)
{
static const int rank = AxesT::rank;
static const int order = AxesT::order;
static_assert(rank >= 0, "Rank must be >= 0!");
static_assert(rank <= 5, "Rank must be <= 5!");
// TODO rm rank <= 2 after debug
static_assert(rank <= 2 || AxesT::is_dense, "Only dense axes can use default strides!");
static_assert(rank <= 2 || order != StorageOrders::Unspecified,
"Must specify storage order for rank 3 tensors and above!");
static_assert((order == StorageOrders::RowMajor ||
order == StorageOrders::ColMajor ||
order == StorageOrders::NCHW ||
order == StorageOrders::Unspecified),
"Only StorageOrders RowMajor, ColMajor, NCHW, "
"and Unspecified supported!");
static_assert(order != StorageOrders::NCHW || rank == 4,
"NCHW order only supported for rank 4 tensors!");
std::array<IdxT, AxesT::rank> strides{0};
if (rank == 1) {
// static_assert(AxisT0::is_contig,
// "1D array must be contiguous to use default strides!");
strides[0] = 1;
return strides;
}
if (rank == 2) {
if (AxesT::AxisT0::is_contig) { // colmajor
strides[0] = 1;
strides[1] = shape[0];
} else { // rowmajor
strides[0] = shape[1];
strides[1] = 1;
}
return strides;
}
switch(order) { // rank 3+ if we got to here
case StorageOrders::RowMajor:
strides[rank - 1] = 1;
for (int i = rank - 2; i >= 0; i--) {
strides[i] = shape[i + 1] * strides[i + 1];
}
break;
case StorageOrders::ColMajor:
strides[0] = 1;
for (int i = 1; i < rank; i++) {
strides[i] = shape[i - 1] * strides[i - 1];
}
break;
// case StorageOrders::NCHW:
// // conceptually, axes mean NHWC: #imgs, nrows, ncols, nchannels
// strides[0] = shape[1] * shape[2] * shape[3]; // sz of whole img
// strides[1] = shape[2]; // row stride = number of cols
// strides[2] = 1; // col stride = 1, like rowmajor
// strides[3] = shape[1] * shape[2]; // channel stride = nrows * ncols
// break;
default:
assert("Somehow got unrecognized storage order!");
break; // can't happen
}
return strides;
}
template<class AxesT, class ShapeT>
ShapeT clip_shape_to_static_bounds(const ShapeT& shape) {
static const int rank = AxesT::rank;
ShapeT ret(shape);
using bounds0 = GET_AXIS_T(AxesT, 0)::size_bounds;
using bounds1 = GET_AXIS_T(AxesT, 1)::size_bounds;
using bounds2 = GET_AXIS_T(AxesT, 2)::size_bounds;
using bounds3 = GET_AXIS_T(AxesT, 3)::size_bounds;
using bounds4 = GET_AXIS_T(AxesT, 4)::size_bounds;
if (rank >= 1 && bounds0::is_valid) {
ret[0] = MIN(MAX(bounds0::min, shape[0]), bounds0::max);
}
if (rank >= 2 && bounds1::is_valid) {
ret[1] = MIN(MAX(bounds1::min, shape[1]), bounds1::max);
}
if (rank >= 3 && bounds2::is_valid) {
ret[2] = MIN(MAX(bounds2::min, shape[2]), bounds2::max);
}
if (rank >= 4 && bounds3::is_valid) {
ret[3] = MIN(MAX(bounds3::min, shape[3]), bounds3::max);
}
if (rank >= 5 && bounds4::is_valid) {
ret[4] = MIN(MAX(bounds4::min, shape[4]), bounds3::max);
}
return ret;
}
template<class DataT, class AxesT=AxesDense1D, class IdxT=DefaultIndexType>
struct ArrayView {
static const int rank = AxesT::rank;
static const int order = AxesT::order;
using axes_t = AxesT;
using strides_t = std::array<IdxT, rank>;
using shape_t = std::array<IdxT, rank>;
using idxs_t = strides_t;
ArrayView(DataT *const data, const shape_t& shape):
_data(data),
_shape(clip_shape_to_static_bounds<AxesT>(shape)),
_strides(default_strides_for_shape<AxesT>(_shape))
{
// printf("I'm an ArrayView and I have rank %d!\n", rank);
};
// these two funcs are to make using CUDA thread/block indices easier
IdxT flatten_idxs(const idxs_t& idxs) {
IdxT idx = 0;
for (int i = 0; i < rank; i++) {
idx += idxs[i] * _strides[i];
}
return idx;
}
// // needs dense array; TODO allow arbitrary strides
// idxs_t unflatten_dense_idx(IdxT idx) {
// auto helper = idxs_from_flat_idx<rank, order>();
// return helper(_shape, idx);
// }
// template<class IntT=IdxT, REQ_RANGE_ENCOMPASSES(IdxT, IntT)>
// DataT& operator[](const std::array<IntT, NumIdxs>& idxs) {
template<class IntT=IdxT, REQ_RANGE_ENCOMPASSES(IdxT, IntT)>
DataT& operator[](const idxs_t& idxs) {
return _data[flatten_idxs(idxs)];
}
const shape_t& shape() const { return _shape; }
const shape_t& strides() const { return _strides; }
const IdxT size() const {
IdxT sz = 1;
for (int i = 0; i < rank; i++) {
sz *= _shape[i];
}
return sz;
}
void setValue(DataT val) {
static_assert(AxesT::is_dense,
"setValue() only implemented for dense arrayviews!");
if (AxesT::is_dense) {
// use memset if it will preserve correctness
if (sizeof(val) == 1) {
memset(_data, val, size());
// DataT converted = ((DataT)((unsigned char)val));
// if (converted == val) {
// memset(_data, val, sizeof(DataT)*size());
// }
} else {
for (IdxT i = 0; i < size(); i++) {
_data[i] = val;
}
}
}
}
void setZero() {
// setValue(0);
static_assert(AxesT::is_dense,
"setZero() only implemented for dense arrayviews!");
if (AxesT::is_dense) {
memset(_data, 0, sizeof(DataT)*size());
}
}
private:
DataT *const _data;
const shape_t _shape;
const strides_t _strides;
};
template<int Rank, int Order=StorageOrders::RowMajor,
int StaticDim0=0, int StaticDim1=0, int StaticDim2=0, int StaticDim3=0, int StaticDim4=0,
class IdxT=DefaultIndexType, class DataT=void>
struct GetArrayViewType {
using AxesT = typename GetAxesType<Rank, Order,
StaticDim0, StaticDim1, StaticDim2, StaticDim3, StaticDim4>::type;
// static_assert(AxesT::attrItDoesntHave, "type of GetAxesType: ");
using type = ArrayView<DataT, AxesT, IdxT>;
};
// ================================================================ wrappers
// wrappers to make views of different ranks
// TODO have a type for each dim so that you don't get errors about deducing
// conflicting types for IdxT
// -or just make these int64s and static_cast when constructing the ArrayView
// -also allow decoupling DataT from type of the pointer to allow int4, int2
template<int Order=StorageOrders::RowMajor,
int StaticDim0=0, int StaticDim1=0, int StaticDim2=0, int StaticDim3=0, int StaticDim4=0,
class IdxT=DefaultIndexType, class DataT=void>
static inline auto make_view(DataT* data, IdxT dim0, IdxT dim1, IdxT dim2,
IdxT dim3, IdxT dim4)
{
using ArrayViewT = typename GetArrayViewType<5, Order,
StaticDim0, StaticDim1, StaticDim2, StaticDim3, StaticDim4, IdxT, DataT>::type;
return ArrayViewT(data, {dim0, dim1, dim2, dim3, dim4});
}
template<int Order=StorageOrders::RowMajor,
int StaticDim0=0, int StaticDim1=0, int StaticDim2=0, int StaticDim3=0,
class IdxT=DefaultIndexType, class DataT=void>
static inline auto make_view(DataT* data, IdxT dim0, IdxT dim1,
IdxT dim2, IdxT dim3)
{
using ArrayViewT = typename GetArrayViewType<4, Order,
StaticDim0, StaticDim1, StaticDim2, StaticDim3, 0, IdxT, DataT>::type;
return ArrayViewT(data, {dim0, dim1, dim2, dim3});
}
template<int Order=StorageOrders::RowMajor,
int StaticDim0=0, int StaticDim1=0, int StaticDim2=0,
class IdxT=DefaultIndexType, class DataT=void>
static inline auto make_view(DataT* data, IdxT dim0, IdxT dim1, IdxT dim2)
{
using ArrayViewT = typename GetArrayViewType<3, Order,
StaticDim0, StaticDim1, StaticDim2, 0, 0, IdxT, DataT>::type;
return ArrayViewT(data, {dim0, dim1, dim2});
}
template<int Order=StorageOrders::RowMajor, int StaticDim0=0, int StaticDim1=0,
class IdxT=DefaultIndexType, class DataT=void>
static inline auto make_view(DataT* data, IdxT dim0, IdxT dim1)
{
using ArrayViewT = typename GetArrayViewType<2, Order,
StaticDim0, StaticDim1, 0, 0, 0, IdxT, DataT>::type;
return ArrayViewT(data, {dim0, dim1});
}
template<int Order=StorageOrders::RowMajor, int StaticDim0=0,
class IdxT=DefaultIndexType, class DataT=void>
static inline auto make_view(DataT* data, IdxT dim0)
{
using ArrayViewT = typename GetArrayViewType<1, Order,
StaticDim0, 0, 0, 0, 0, IdxT, DataT>::type;
return ArrayViewT(data, {dim0});
}
} // namespace ar
#endif /* array_h */
| 37.617339 | 98 | 0.642255 | [
"shape"
] |
071338842daa3a9fac3f08a9288ece62b63715a8 | 2,623 | cpp | C++ | Arduino/Wheelly/IMU.cpp | m-marini/wheelly | 80446e72c9e44f8f845cdcd96325ae4d9632e643 | [
"MIT"
] | null | null | null | Arduino/Wheelly/IMU.cpp | m-marini/wheelly | 80446e72c9e44f8f845cdcd96325ae4d9632e643 | [
"MIT"
] | 16 | 2022-02-13T16:16:13.000Z | 2022-03-27T18:27:09.000Z | Arduino/Wheelly/IMU.cpp | m-marini/wheelly | 80446e72c9e44f8f845cdcd96325ae4d9632e643 | [
"MIT"
] | null | null | null | #include "IMU.h"
#define G_VALUE 9.80665
#define ACC_SCALE (4.0 * G_VALUE / 32768.0)
#define GYRO_SCALE (1.0 / 32768.0)
#define WATCH_DOG_INTERVAL 100000ul
IMU::IMU(MPU6050& mpu) : _mpu {mpu} {
_watchDogInterval = WATCH_DOG_INTERVAL;
_devStatus = IMU_FAILURE_STATUS;
}
void IMU::begin() {
_devStatus = IMU_FAILURE_STATUS;
_mpu.initialize();
int rc;
if (!(rc = _mpu.testConnection())) {
Serial.println(F("!! Connection IMU failed."));
return;
}
_devStatus = _mpu.dmpInitialize();
if (_devStatus) {
Serial.print(F("!! DMP initialize failed: "));
Serial.print(_devStatus);
Serial.println();
}
}
/*
*/
void IMU::enableDMP() {
if (_devStatus == 0) {
// turn on the DMP, now that it's ready
_mpu.setDMPEnabled(true);
// get expected DMP packet size for later comparison
_packetSize = _mpu.dmpGetFIFOPacketSize();
}
}
/*
*/
void IMU::reset() {
if (_devStatus == 0) {
_mpu.resetFIFO();
_prevTime = micros();
kickAt(_prevTime + _watchDogInterval);
}
}
/*
*/
void IMU::polling(unsigned long clockMillis, unsigned long clockMicros) {
if (_devStatus == 0) {
if (_mpu.getFIFOCount() >= _packetSize) {
if (_readFifo(clockMillis, clockMicros) && _onData != NULL) {
_onData(_context);
}
} else if (clockMicros >= _watchDogTime && _onWatchDog != NULL) {
kickAt(clockMicros + _watchDogInterval);
_onWatchDog(_context);
}
}
}
boolean IMU::_readFifo(unsigned long clockMillis, unsigned long clockMicros) {
// read a packet from FIFO
uint8_t _fifoBuffer[64]; // FIFO storage buffer
_mpu.getFIFOBytes(_fifoBuffer, _packetSize);
_mpu.resetFIFO();
kickAt(clockMicros + _watchDogInterval);
_dt = (float)(clockMicros - _prevTime) * 1e-6;
if (_dt > 0 && _dt < 1.0) {
_lastTime = clockMillis;
_prevTime = clockMicros;
VectorFloat gravity; // [x, y, z] gravity vector
Quaternion _q; // [w, x, y, z] quaternion container
_mpu.dmpGetQuaternion(&_q, _fifoBuffer);
_mpu.dmpGetGravity(&gravity, &_q);
_mpu.dmpGetYawPitchRoll(_ypr, &_q, &gravity);
return true;
}
return false;
}
/*
*/
void IMU::calibrate(int steps) {
if (_devStatus == 0) {
_mpu.setXAccelOffset(0);
_mpu.setYAccelOffset(0);
_mpu.setZAccelOffset(0);
_mpu.setXGyroOffset(0);
_mpu.setYGyroOffset(0);
_mpu.setZGyroOffset(0);
// Calibration Time: generate offsets and calibrate our MPU6050
_mpu.CalibrateAccel(steps);
_mpu.CalibrateGyro(steps);
#ifdef DEBUG
_mpu.PrintActiveOffsets();
#endif
}
}
| 23.419643 | 78 | 0.642013 | [
"vector"
] |
071a23bcfb8f716d3b746814e94a9234e28289bc | 3,621 | cpp | C++ | aws-cpp-sdk-dms/source/model/ReplicationSubnetGroup.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-dms/source/model/ReplicationSubnetGroup.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-dms/source/model/ReplicationSubnetGroup.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/dms/model/ReplicationSubnetGroup.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace DatabaseMigrationService
{
namespace Model
{
ReplicationSubnetGroup::ReplicationSubnetGroup() :
m_replicationSubnetGroupIdentifierHasBeenSet(false),
m_replicationSubnetGroupDescriptionHasBeenSet(false),
m_vpcIdHasBeenSet(false),
m_subnetGroupStatusHasBeenSet(false),
m_subnetsHasBeenSet(false)
{
}
ReplicationSubnetGroup::ReplicationSubnetGroup(const JsonValue& jsonValue) :
m_replicationSubnetGroupIdentifierHasBeenSet(false),
m_replicationSubnetGroupDescriptionHasBeenSet(false),
m_vpcIdHasBeenSet(false),
m_subnetGroupStatusHasBeenSet(false),
m_subnetsHasBeenSet(false)
{
*this = jsonValue;
}
ReplicationSubnetGroup& ReplicationSubnetGroup::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("ReplicationSubnetGroupIdentifier"))
{
m_replicationSubnetGroupIdentifier = jsonValue.GetString("ReplicationSubnetGroupIdentifier");
m_replicationSubnetGroupIdentifierHasBeenSet = true;
}
if(jsonValue.ValueExists("ReplicationSubnetGroupDescription"))
{
m_replicationSubnetGroupDescription = jsonValue.GetString("ReplicationSubnetGroupDescription");
m_replicationSubnetGroupDescriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("VpcId"))
{
m_vpcId = jsonValue.GetString("VpcId");
m_vpcIdHasBeenSet = true;
}
if(jsonValue.ValueExists("SubnetGroupStatus"))
{
m_subnetGroupStatus = jsonValue.GetString("SubnetGroupStatus");
m_subnetGroupStatusHasBeenSet = true;
}
if(jsonValue.ValueExists("Subnets"))
{
Array<JsonValue> subnetsJsonList = jsonValue.GetArray("Subnets");
for(unsigned subnetsIndex = 0; subnetsIndex < subnetsJsonList.GetLength(); ++subnetsIndex)
{
m_subnets.push_back(subnetsJsonList[subnetsIndex].AsObject());
}
m_subnetsHasBeenSet = true;
}
return *this;
}
JsonValue ReplicationSubnetGroup::Jsonize() const
{
JsonValue payload;
if(m_replicationSubnetGroupIdentifierHasBeenSet)
{
payload.WithString("ReplicationSubnetGroupIdentifier", m_replicationSubnetGroupIdentifier);
}
if(m_replicationSubnetGroupDescriptionHasBeenSet)
{
payload.WithString("ReplicationSubnetGroupDescription", m_replicationSubnetGroupDescription);
}
if(m_vpcIdHasBeenSet)
{
payload.WithString("VpcId", m_vpcId);
}
if(m_subnetGroupStatusHasBeenSet)
{
payload.WithString("SubnetGroupStatus", m_subnetGroupStatus);
}
if(m_subnetsHasBeenSet)
{
Array<JsonValue> subnetsJsonList(m_subnets.size());
for(unsigned subnetsIndex = 0; subnetsIndex < subnetsJsonList.GetLength(); ++subnetsIndex)
{
subnetsJsonList[subnetsIndex].AsObject(m_subnets[subnetsIndex].Jsonize());
}
payload.WithArray("Subnets", std::move(subnetsJsonList));
}
return payload;
}
} // namespace Model
} // namespace DatabaseMigrationService
} // namespace Aws | 26.625 | 99 | 0.765811 | [
"model"
] |
071de3ef742c8f12c33fba9b10dd5361e7dc32f9 | 9,505 | cpp | C++ | src/utils/icp.cpp | h2ssh/Vulcan | cc46ec79fea43227d578bee39cb4129ad9bb1603 | [
"MIT"
] | 6 | 2020-03-29T09:37:01.000Z | 2022-01-20T08:56:31.000Z | src/utils/icp.cpp | h2ssh/Vulcan | cc46ec79fea43227d578bee39cb4129ad9bb1603 | [
"MIT"
] | 1 | 2021-03-05T08:00:50.000Z | 2021-03-05T08:00:50.000Z | src/utils/icp.cpp | h2ssh/Vulcan | cc46ec79fea43227d578bee39cb4129ad9bb1603 | [
"MIT"
] | 11 | 2019-05-13T00:04:38.000Z | 2022-01-20T08:56:38.000Z | /* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file icp.cpp
* \author Collin Johnson
*
* Definition of functions for doing ICP:
*
* - icp_2d
*/
#include <utils/icp.h>
#include <core/pose.h>
#include <core/vector.h>
#include <core/matrix.h>
#include <core/point.h>
#include <core/angle_functions.h>
#include <iostream>
#include <cassert>
// #define DEBUG_TRANSFORM
namespace vulcan
{
namespace utils
{
struct icp_pair_t
{
int index;
float distance;
};
void transform_points(const std::vector<Point<float>>& points,
const pose_t& transform,
std::vector<Point<float>>& transformed);
void match_points(const std::vector<Point<float>>& from,
const std::vector<Point<float>>& to,
float maxMatchDistance,
bool canMatchEndpoints,
std::vector<icp_pair_t>& matches);
icp_pair_t closest_point_index(const Point<float>& from,
const std::vector<Point<float>>& to,
float maxMatchDistance);
pose_t find_transform(const std::vector<Point<float>>& from,
const std::vector<Point<float>>& to,
const std::vector<icp_pair_t>& matches);
Point<float> mean_point(const std::vector<Point<float>>& points);
bool is_transform_converged(const pose_t& previous, const pose_t& current);
pose_t icp_2d(const std::vector<Point<float>>& from,
const std::vector<Point<float>>& to,
const pose_t& initial)
{
const int MAX_ITERATIONS = 500;
const float MAX_MATCH_DISTANCE = 0.5f;
// If either is empty, then can't calculate a transform!
if(from.empty() || to.empty())
{
return pose_t(0.0f, 0.0f, 0.0f);
}
std::vector<Point<float>> transformed(from.size());
std::vector<icp_pair_t> matchIndices(from.size());
pose_t previousTransform;
pose_t transformIncrement;
pose_t currentTransform = initial;
int numIterations = 0;
do
{
previousTransform = currentTransform;
transform_points(from, previousTransform, transformed);
match_points(transformed, to, MAX_MATCH_DISTANCE, true, matchIndices);
transformIncrement = find_transform(transformed, to, matchIndices);
currentTransform = pose_t(transformIncrement.x + currentTransform.x*std::cos(transformIncrement.theta) - currentTransform.y*std::sin(transformIncrement.theta),
transformIncrement.y + currentTransform.x*std::sin(transformIncrement.theta) + currentTransform.y*std::cos(transformIncrement.theta),
angle_sum(currentTransform.theta, transformIncrement.theta));
} while(!is_transform_converged(previousTransform, currentTransform) && (numIterations++ < MAX_ITERATIONS));
return currentTransform;
}
void transform_points(const std::vector<Point<float>>& points,
const pose_t& transform,
std::vector<Point<float>>& transformed)
{
Point<float> position = transform.toPoint();
transformed.resize(points.size());
for(std::size_t n = 0; n < points.size(); ++n)
{
transformed[n] = position + rotate(points[n], transform.theta);
}
}
void match_points(const std::vector<Point<float>>& from,
const std::vector<Point<float>>& to,
float maxMatchDistance,
bool canMatchEndpoints,
std::vector<icp_pair_t>& matches)
{
std::size_t start = canMatchEndpoints ? 0 : 1;
std::size_t end = canMatchEndpoints ? from.size() : from.size()-1;
matches.resize(from.size());
if(!canMatchEndpoints)
{
matches.front().index = -1;
matches.back().index = -1;
}
for(std::size_t n = start; n < end; ++n)
{
icp_pair_t match = closest_point_index(from[n], to, maxMatchDistance);
if(!canMatchEndpoints && (match.index == 0 || static_cast<std::size_t>(match.index+1) == to.size()))
{
match.index = -1;
}
matches[n] = match;
}
}
icp_pair_t closest_point_index(const Point<float>& from,
const std::vector<Point<float>>& to,
float maxMatchDistance)
{
float closestDistance = HUGE_VALF;
int closestIndex = -1;
for(std::size_t n = 0; n < to.size(); ++n)
{
float distance = distance_between_points(from, to[n]);
if((distance < closestDistance) && (distance < maxMatchDistance))
{
closestDistance = distance;
closestIndex = n;
}
}
if(closestIndex == -1)
{
closestDistance = -1.0;
}
return {closestIndex, closestDistance};
}
pose_t find_transform(const std::vector<Point<float>>& from,
const std::vector<Point<float>>& to,
const std::vector<icp_pair_t>& matches)
{
/*
* Finding the transform via ICP involves solving a least-squares estimation problem that minimizes the
* error between the from and to points. This problem can be solved in closed-form using the SVD. The
* calculation goes as follows:
*
* - f_bar, t_bar = mean values of points in from and to
* - f_rel, t_rel = a point with the mean subtracted out, i.e. from[n] - f_bar
* - H = sum(f_rel dot t_rel') -- 2x2 matrix
* - USV' = SVD(H)
* - R = VU', rotation matrix of transform
* - T = t_bar - R*f_bar, position offset of transform
*/
assert(from.size() == matches.size());
auto comparePairsOp = [](const icp_pair_t& lhs, const icp_pair_t& rhs) { return lhs.distance < rhs.distance; };
float maxDist = std::max_element(matches.begin(), matches.end(), comparePairsOp)->distance;
Point<float> fromBar;
Point<float> toBar;
int numValid = 0;
double sumWeight = 0.0;
for(std::size_t n = 0; n < matches.size(); ++n)
{
if(matches[n].index == -1)
{
continue;
}
double weight = (maxDist - matches[n].distance) / maxDist; //(matches[n].distance < 0.001) ? 1.0/0.001 : 1.0/matches[n].distance;
sumWeight += weight;
fromBar.x += from[n].x * weight;
fromBar.y += from[n].y * weight;
toBar.x += to[matches[n].index].x * weight;
toBar.y += to[matches[n].index].y * weight;
++numValid;
}
assert(numValid);
fromBar.x /= sumWeight;
fromBar.y /= sumWeight;
toBar.x /= sumWeight;
toBar.y /= sumWeight;
Point<float> fromRel;
Point<float> toRel;
Matrix h(2, 2);
h.zeros();
for(std::size_t n = 0; n < from.size(); ++n)
{
if(matches[n].index == -1)
{
continue;
}
double weight = 1.0;//(maxDist - matches[n].distance) / sumDist; //(matches[n].distance < 0.001) ? 1.0/0.001 : 1.0/matches[n].distance;
fromRel = from[n] - fromBar;
toRel = to[matches[n].index] - toBar;
h(0, 0) += fromRel.x * toRel.x * weight;
h(0, 1) += fromRel.x * toRel.y * weight;
h(1, 0) += fromRel.y * toRel.x * weight;
h(1, 1) += fromRel.y * toRel.y * weight;
}
Matrix u;
Matrix v;
Vector s;
arma::svd(u, s, v, h);
Matrix r = v * arma::trans(u);
if(arma::det(r) < 0)
{
Matrix fix(2, 2);
fix.zeros();
fix(0,0) = 1.0;
fix(1,1) = arma::det(u * arma::trans(v));
r = u * fix * arma::trans(v);
}
float rotation = std::atan2(-r(0,1), r(0,0));
Point<float> position = toBar - rotate(fromBar, rotation);
#ifdef DEBUG_TRANSFORM
std::cout<<"From:"<<fromBar<<" To:"<<toBar<<" Transform:"<<pose_t(position.x, position.y, rotation)<<'\n'
<<"Max:"<<maxDist<<' '<<" Sum:"<<sumDist<<' '<<" Rotated:"<<rotate(fromBar, rotation)<<" Other:"<<rotate(fromBar, -rotation)<<'\n';
#endif
return pose_t(position.x, position.y, rotation);
}
Point<float> mean_point(const std::vector<Point<float>>& points)
{
assert(!points.empty());
Point<float> meanPoint;
for(auto& point : points)
{
meanPoint += point;
}
return Point<float>(meanPoint.x/points.size(), meanPoint.y/points.size());
}
bool is_transform_converged(const pose_t& previous, const pose_t& current)
{
const float POSITION_TOLERANCE = 1e-5;
const float ORIENTATION_TOLERANCE = 1e-5;
return (std::abs(previous.x - current.x) < POSITION_TOLERANCE) &&
(std::abs(previous.y - current.y) < POSITION_TOLERANCE) &&
(std::abs(previous.theta - current.theta) < ORIENTATION_TOLERANCE);
}
} // namespace utils
} // namesapce vulcan
| 30.86039 | 174 | 0.570121 | [
"vector",
"transform"
] |
07296f7cbe6fb81847e22d536bb7372646db0dee | 1,564 | cpp | C++ | tests/lang/type_checker_array_tests.cpp | faouellet/Tostitos | a34776c2c81a1f6658aa098da0c9fda90110197e | [
"MIT"
] | 1 | 2016-01-29T01:07:15.000Z | 2016-01-29T01:07:15.000Z | tests/lang/type_checker_array_tests.cpp | faouellet/Tostitos | a34776c2c81a1f6658aa098da0c9fda90110197e | [
"MIT"
] | 20 | 2015-08-05T10:36:29.000Z | 2016-06-21T23:19:16.000Z | tests/lang/type_checker_array_tests.cpp | Alex-B09/Tostitos | a34776c2c81a1f6658aa098da0c9fda90110197e | [
"MIT"
] | 1 | 2021-07-14T02:45:43.000Z | 2021-07-14T02:45:43.000Z | #ifdef STAND_ALONE
# define BOOST_TEST_MODULE Main
#else
#ifndef _WIN32
# define BOOST_TEST_MODULE TypeCheckerArrayTests
#endif
#endif
#include <boost/test/unit_test.hpp>
#include "toslang_sema_fixture.h"
BOOST_FIXTURE_TEST_SUITE( SemaTestSuite, TosLangSemaFixture )
//////////////////// CORRECT USE CASES ////////////////////
BOOST_AUTO_TEST_CASE( ArrayInitTypeCheck )
{
size_t errorCount = GetTypeErrors("../asts/array/array_init_identifier.ast");
BOOST_REQUIRE_EQUAL(errorCount, 0);
}
//////////////////// ERROR USE CASES ////////////////////
BOOST_AUTO_TEST_CASE( BadScalarInitWithArrayTypeCheck )
{
size_t errorCount = GetTypeErrors("../asts/array/bad_scalar_init_with_array.ast");
BOOST_REQUIRE_EQUAL(errorCount, 1);
// Check if the correct error message got printed
std::vector<std::string> messages{ GetErrorMessages() };
BOOST_REQUIRE_EQUAL(messages.size(), 1);
BOOST_REQUIRE_EQUAL(messages[0], "TYPE ERROR: Trying to instantiate a scalar variable with an array expression at line 1, column 17");
}
BOOST_AUTO_TEST_CASE( BadArrayInitWithScalarTypeCheck )
{
size_t errorCount = GetTypeErrors("../asts/array/bad_array_init_with_scalar.ast");
BOOST_REQUIRE_EQUAL(errorCount, 1);
// Check if the correct error message got printed
std::vector<std::string> messages{ GetErrorMessages() };
BOOST_REQUIRE_EQUAL(messages.size(), 1);
BOOST_REQUIRE_EQUAL(messages[0], "TYPE ERROR: Trying to instantiate an array variable with a scalar value at line 1, column 22");
}
BOOST_AUTO_TEST_SUITE_END()
| 32.583333 | 138 | 0.727621 | [
"vector"
] |
0729a0776d5ecc690a4872a8cba47524ba703bdf | 3,459 | cc | C++ | ndash/src/mpd/adaptation_set.cc | google/ndash | 1465e2fb851ee17fd235280bdbbbf256e5af8044 | [
"Apache-2.0"
] | 41 | 2017-04-19T19:38:10.000Z | 2021-09-07T02:40:27.000Z | ndash/src/mpd/adaptation_set.cc | google/ndash | 1465e2fb851ee17fd235280bdbbbf256e5af8044 | [
"Apache-2.0"
] | 8 | 2017-04-21T16:40:09.000Z | 2019-12-09T19:48:40.000Z | ndash/src/mpd/adaptation_set.cc | google/ndash | 1465e2fb851ee17fd235280bdbbbf256e5af8044 | [
"Apache-2.0"
] | 19 | 2017-04-24T14:43:18.000Z | 2022-03-17T19:13:45.000Z | /*
* Copyright 2017 Google 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 "mpd/adaptation_set.h"
#include "base/logging.h"
namespace ndash {
namespace mpd {
AdaptationSet::AdaptationSet(
int32_t id,
AdaptationType type,
std::vector<std::unique_ptr<Representation>>* representations,
std::vector<std::unique_ptr<ContentProtection>>* content_protections,
std::unique_ptr<SegmentBase> segment_base,
std::vector<std::unique_ptr<DescriptorType>>* supplemental_properties,
std::vector<std::unique_ptr<DescriptorType>>* essential_properties)
: id_(id), type_(type), segment_base_(std::move(segment_base)) {
DCHECK(representations != nullptr);
representations_ = std::move(*representations);
if (content_protections != nullptr) {
content_protections_ = std::move(*content_protections);
}
if (supplemental_properties != nullptr) {
supplemental_properties_ = std::move(*supplemental_properties);
}
if (essential_properties != nullptr) {
essential_properties_ = std::move(*essential_properties);
}
}
AdaptationSet::~AdaptationSet() {}
bool AdaptationSet::HasContentProtection() const {
return !content_protections_.empty();
}
const std::vector<std::unique_ptr<Representation>>*
AdaptationSet::GetRepresentations() {
return &representations_;
}
bool AdaptationSet::HasRepresentations() const {
return !representations_.empty();
}
int32_t AdaptationSet::NumRepresentations() const {
return representations_.size();
}
const Representation* AdaptationSet::GetRepresentation(int32_t index) const {
DCHECK_GE(index, 0);
DCHECK_LT(index, representations_.size());
return representations_.at(index).get();
}
const std::vector<std::unique_ptr<ContentProtection>>*
AdaptationSet::GetContentProtections() {
return &content_protections_;
}
bool AdaptationSet::HasContentProtections() const {
return !content_protections_.empty();
}
int32_t AdaptationSet::NumContentProtections() const {
return content_protections_.size();
}
const ContentProtection* AdaptationSet::GetContentProtection(
int32_t index) const {
DCHECK_GE(index, 0);
DCHECK_LT(index, content_protections_.size());
return content_protections_.at(index).get();
}
int32_t AdaptationSet::GetId() const {
return id_;
}
AdaptationType AdaptationSet::GetType() const {
return type_;
}
SegmentBase* AdaptationSet::GetSegmentBase() const {
return segment_base_.get();
}
size_t AdaptationSet::GetSupplementalPropertyCount() const {
return supplemental_properties_.size();
}
const DescriptorType* AdaptationSet::GetSupplementalProperty(int index) const {
return supplemental_properties_.at(index).get();
}
size_t AdaptationSet::GetEssentialPropertyCount() const {
return essential_properties_.size();
}
const DescriptorType* AdaptationSet::GetEssentialProperty(int index) const {
return essential_properties_.at(index).get();
}
} // namespace mpd
} // namespace ndash
| 28.121951 | 79 | 0.756577 | [
"vector"
] |
0731443db4fbab858dea4428a783a2d2226adf5c | 1,508 | cpp | C++ | 6_adv_recursion/11_keypad_approach2.cpp | ShyamNandanKumar/coding-ninja2 | a43a21575342261e573f71f7d8eff0572f075a17 | [
"MIT"
] | 11 | 2021-01-02T10:07:17.000Z | 2022-03-16T00:18:06.000Z | 6_adv_recursion/11_keypad_approach2.cpp | meyash/cp_master | 316bf47db2a5b40891edd73cff834517993c3d2a | [
"MIT"
] | null | null | null | 6_adv_recursion/11_keypad_approach2.cpp | meyash/cp_master | 316bf47db2a5b40891edd73cff834517993c3d2a | [
"MIT"
] | 5 | 2021-05-19T11:17:18.000Z | 2021-09-16T06:23:31.000Z | // Given an integer n, using phone keypad find out and print all the possible strings that can be made using digits of input n.
// Note : The order of strings are not important. Just print different strings in new lines.
// Input Format :
// Integer n
// Output Format :
// All possible strings in different lines
// Constraints :
// 1 <= n <= 10^6
// Sample Input:
// 23
// Sample Output:
// ad
// ae
// af
// bd
// be
// bf
// cd
// ce
// cf
#include <bits/stdc++.h>
using namespace std;
void print_combinations(int num,string out,vector<vector<char>> keys){
// base case
if(num==0||num==1){
cout<<out<<endl;
return;
}
//get last number in num
int rem=num%10;
//print all combinations by using all chars from rem's key mappings
for(int i=0;i<keys[rem-2].size();i++){
print_combinations(num/10,keys[rem-2][i]+out,keys);
}
}
void printKeypad(int num){
/*
Given an integer number print all the possible combinations of the keypad. You do not need to return anything just print them.
*/
vector<vector<char>> keys;
keys.push_back({'a','b','c'}); //2nd key
keys.push_back({'d','e','f'}); //3rd key
keys.push_back({'g','h','i'}); //4th key
keys.push_back({'j','k','l'}); //5th key
keys.push_back({'m','n','o'}); //6th key
keys.push_back({'p','q','r','s'}); //7th key
keys.push_back({'t','u','v'}); //8th key
keys.push_back({'w','x','y','z'}); //9th key
string out;
print_combinations(num,out,keys);
}
| 27.418182 | 130 | 0.611406 | [
"vector"
] |
0735585b59b896dda14654c05773c4ac1b30436d | 3,164 | cpp | C++ | Source/src/ezcard/parameter/vcard_parameter_case_classes.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | 5 | 2019-10-30T06:10:10.000Z | 2020-04-25T16:52:06.000Z | Source/src/ezcard/parameter/vcard_parameter_case_classes.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | null | null | null | Source/src/ezcard/parameter/vcard_parameter_case_classes.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | 2 | 2019-11-27T23:47:54.000Z | 2020-01-13T16:36:03.000Z | //
// vcard_parameter_case_classes.cpp
// OpenPGP
//
// Created by Yanfeng Zhang on 1/10/17.
//
// The MIT License
//
// Copyright (c) 2019 Proton Technologies AG
//
// 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 "vcard_parameter_case_classes.hpp"
#include "calscale.hpp"
#include "encoding.hpp"
#include "email_type.hpp"
template class VCardParameterCaseClasses<Calscale>;
template class VCardParameterCaseClasses<Encoding>;
template class VCardParameterCaseClasses<EmailType>;
template <class T>
std::shared_ptr<T> VCardParameterCaseClasses<T>::create(const std::string& value, std::vector<VCardVersion::Ptr> support) {
return std::shared_ptr<T>(new T(value, support));
}
template <class T>
std::shared_ptr<T> VCardParameterCaseClasses<T>::create(const std::string& value, std::vector<VCardVersion::Ptr> support, bool preserveCase) {
return std::shared_ptr<T>(new T(value, support, preserveCase));
}
//public class VCardParameterCaseClasses<T extends VCardParameter> extends CaseClasses<T, String> {
// public VCardParameterCaseClasses(Class<T> clazz) {
// super(clazz);
// }
//
// @Override
// protected T create(String value) {
// //reflection: return new ClassName(value);
// try {
// //try (String) constructor
// Constructor<T> constructor = clazz.getDeclaredConstructor(String.class);
// constructor.setAccessible(true);
// return constructor.newInstance(value);
// } catch (Exception e) {
// try {
// //try (String, VCardVersion...) constructor
// Constructor<T> constructor = clazz.getDeclaredConstructor(String.class, VCardVersion[].class);
// constructor.setAccessible(true);
// return constructor.newInstance(value, new VCardVersion[] {});
// } catch (Exception e2) {
// throw new RuntimeException(e2);
// }
// }
// }
//
// @Override
// protected boolean matches(T object, String value) {
// return object.getValue().equalsIgnoreCase(value);
// }
//}
| 39.061728 | 142 | 0.687737 | [
"object",
"vector"
] |
07375b9b8e2ca5922f910cdce7c6346413644447 | 6,785 | cpp | C++ | libraries/plugins/transaction/transaction_plugin.cpp | Whitecoin-Owner/Whitecoin-core | a48c1c229b9a311b10654ac79335890ca57aec4a | [
"MIT"
] | 10 | 2020-09-26T12:00:03.000Z | 2021-07-27T06:41:40.000Z | libraries/plugins/transaction/transaction_plugin.cpp | r8d8/Whitecoin-core | ba4438a0e41babde272c67a3b2048b4247a7dc4e | [
"MIT"
] | 23 | 2020-05-31T13:08:03.000Z | 2021-12-08T09:07:30.000Z | libraries/plugins/transaction/transaction_plugin.cpp | r8d8/Whitecoin-core | ba4438a0e41babde272c67a3b2048b4247a7dc4e | [
"MIT"
] | 4 | 2019-12-05T15:32:08.000Z | 2021-09-21T17:53:41.000Z | /*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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 <graphene/transaction/transaction_plugin.hpp>
#include <graphene/app/impacted.hpp>
#include <graphene/chain/transaction_object.hpp>
#include <graphene/chain/config.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/evaluator.hpp>
#include <graphene/chain/transaction_evaluation_state.hpp>
#include <fc/smart_ref_impl.hpp>
#include <fc/thread/thread.hpp>
#include <iostream>
namespace graphene { namespace transaction {
namespace detail
{
class transaction_plugin_impl
{
public:
transaction_plugin_impl(transaction_plugin& _plugin);
virtual ~transaction_plugin_impl();
/** this method is called as a callback after a block is applied
* and will process/index all operations that were applied in the block.
*/
void update_transaction_record( const signed_block& b );
void erase_transaction_records(const vector<signed_transaction>& trxs);
graphene::chain::database& database()
{
return _self.database();
}
transaction_plugin& _self;
flat_set<address> _tracked_addresses;
bool _partial_operations = false;
/** add one history record, then check and remove the earliest history record */
void add_transaction_history( const signed_transaction& trx );
};
transaction_plugin_impl::transaction_plugin_impl(transaction_plugin& plugin):_self(plugin){}
transaction_plugin_impl::~transaction_plugin_impl(){}
void transaction_plugin_impl::erase_transaction_records(const vector<signed_transaction>& trxs)
{
const auto& db = database();
for (auto tx : trxs)
{
leveldb::WriteOptions write_options;
db.get_levelDB()->Delete(write_options, tx.id().str());
}
}
void transaction_plugin_impl::update_transaction_record( const signed_block& b )
{
graphene::chain::database& db = database();
for (auto trx : b.transactions) {
leveldb::WriteOptions write_options;
trx_object obj;
obj.trx = trx;
obj.trx_id = trx.id();
obj.block_num = b.block_num();
leveldb::Status sta = db.get_levelDB()->Put(write_options, obj.trx_id.str(), fc::json::to_string(obj));
if (!sta.ok())
{
elog("Put error: ${error}", ("error", (trx.id().str() + ":" + sta.ToString()).c_str()));
FC_ASSERT(false, "Put Data to transaction failed");
return;
}
add_transaction_history(trx);
}
}
void transaction_plugin_impl::add_transaction_history(const signed_transaction& trx)
{
graphene::chain::database& db = database();
if (_tracked_addresses.size() == 0)
return;
auto chain_id = db.get_chain_id();
auto signatures = trx.get_signature_keys(chain_id);
flat_set<address> addresses;
for (auto sig : signatures)
{
addresses.insert(address(sig));
}
auto res=db.get_contract_invoke_result(trx.id());
for (const auto& it : res)
{
for (const auto& deposit_it : it.deposit_to_address)
{
addresses.insert(deposit_it.first.first);
}
}
for (auto op : trx.operations)
{
if (op.which() == operation::tag<transfer_operation>::value)
{
auto op_transfer = op.get<transfer_operation>();
addresses.insert(op_transfer.from_addr);
addresses.insert(op_transfer.to_addr);
}
else if (op.which() == operation::tag<graphene::chain::crosschain_record_operation>::value)
{
auto op_record = op.get<graphene::chain::crosschain_record_operation>();
const auto& tunnel_idx = db.get_index_type<account_binding_index>().indices().get<by_binded_account>();
const auto tunnel_itr = tunnel_idx.find(boost::make_tuple(op_record.cross_chain_trx.from_account, op_record.cross_chain_trx.asset_symbol));
addresses.insert(tunnel_itr->owner);
}
auto id = operation_gurantee_id(op);
if (id.valid())
{
const auto& obj = db.get(*id);
addresses.insert(obj.owner_addr);
}
}
auto trx_op = db.fetch_trx(trx.id());
if (!trx_op.valid())
return;
for (auto addr : addresses)
{
auto iter = _tracked_addresses.find(addr);
if (iter == _tracked_addresses.end())
continue;
db.create<history_transaction_object>([&](history_transaction_object& obj) {
obj.addr = addr;
obj.trx_id = trx_op->trx_id;
obj.block_num = trx_op->block_num;
});
}
}
} // end namespace detail
transaction_plugin::transaction_plugin() :
my( new detail::transaction_plugin_impl(*this) )
{
}
transaction_plugin::~transaction_plugin()
{
}
std::string transaction_plugin::plugin_name()const
{
return "transaction_plugin";
}
void transaction_plugin::plugin_set_program_options(
boost::program_options::options_description& cli,
boost::program_options::options_description& cfg
)
{
cli.add_options()
("track-address", boost::program_options::value<std::vector<std::string>>()->composing()->multitoken(), "address to track history for (may specify multiple times)");
cfg.add(cli);
}
void transaction_plugin::plugin_initialize(const boost::program_options::variables_map& options)
{
database().applied_block.connect( [&]( const signed_block& b){ my->update_transaction_record(b); } );
database().removed_trxs.connect([&](vector<signed_transaction> b) {my->erase_transaction_records(b); });
database().add_index <primary_index<trx_index > >();
database().add_index <primary_index<history_transaction_index > >();
LOAD_VALUE_SET(options, "track-address", my->_tracked_addresses, graphene::chain::address);
}
void transaction_plugin::plugin_startup()
{
}
flat_set<address> transaction_plugin::tracked_address() const
{
return my->_tracked_addresses;
}
void transaction_plugin::add_tracked_address(vector<address> addrs)
{
for (auto addr : addrs)
my->_tracked_addresses.insert(addr);
}
} }
| 31.85446 | 174 | 0.728224 | [
"vector"
] |
07438b07e888c0071a66863a297fd650b2c3e17c | 25,682 | hpp | C++ | include/ripple/graph/node.hpp | robclu/ripple | 734dfa77e100a86b3c60589d41ca627e41d4a783 | [
"MIT"
] | 4 | 2021-04-25T16:38:12.000Z | 2021-12-23T08:32:15.000Z | include/ripple/graph/node.hpp | robclu/ripple | 734dfa77e100a86b3c60589d41ca627e41d4a783 | [
"MIT"
] | null | null | null | include/ripple/graph/node.hpp | robclu/ripple | 734dfa77e100a86b3c60589d41ca627e41d4a783 | [
"MIT"
] | null | null | null | /**=--- ripple/graph/node.hpp ------------------------------ -*- C++ -*- ---==**
*
* Ripple
*
* Copyright (c) 2019 - 2021 Rob Clucas.
*
* This file is distributed under the MIT License. See LICENSE for details.
*
*==-------------------------------------------------------------------------==*
*
* \file node.hpp
* \brief This file implements a Node class for a graph.
*
*==------------------------------------------------------------------------==*/
#ifndef RIPPLE_GRAPH_NODE_HPP
#define RIPPLE_GRAPH_NODE_HPP
#include <ripple/container/tuple.hpp>
#include <ripple/execution/execution_traits.hpp>
#include <ripple/functional/invocable.hpp>
#include <ripple/math/math.hpp>
#include <ripple/utility/forward.hpp>
#include <array>
#include <atomic>
#include <cassert>
#include <string>
#include <vector>
namespace ripple {
/** Forward declaration of the graph class. */
class Graph;
/** Defines the kinds of nodes. */
enum class NodeKind : uint8_t {
normal = 0, //!< Default kind of node.
split = 1, //!< Node in a split operation in a graph.
sync = 2 //!< Node kind to explicity create a sync point in a graph.
};
/*==--- [node executor] ----------------------------------------------------==*/
/**
* The NodeExecutor struct is a base class which enables a types which derive
* from it to be stored in a container for execution. Thiis interface defines
* an execute method which performs execution of the node work.
*/
struct NodeExecutor {
// clang-format off
/** Defaulted constructor. */
NodeExecutor() noexcept = default;
/** Virtual destructor to avoid incorrect deletion from derived class. */
virtual ~NodeExecutor() noexcept = default;
/** Copy constructor -- deleted. */
NodeExecutor(const NodeExecutor&) = delete;
/** Move constructor -- deleted. */
NodeExecutor(NodeExecutor&&) = delete;
/** Copy assignment -- deleted. */
auto operator=(const NodeExecutor&) = delete;
/** Move assignment -- deleted. */
auto operator=(NodeExecutor&&) = delete;
// clang-format on
/**
* The clone method enables copying/moving the executor, but makes the
* intention to do so explicit.
* \param storage A pointer to the storage to clone the executor into.
* \return A pointer to the cloned executor.
*/
virtual auto clone(void* storage) const noexcept -> NodeExecutor* = 0;
/**
* Executes the work assosciated with the executor.
*/
virtual auto execute() noexcept -> void = 0;
};
/*==--- [node executor impl] -----------------------------------------------==*/
/**
* The NodeExecutorImpl struct implements the NodeExecutor interface, storing
* a callable object which defines the work to be executed.
*
* \tparam Callable The type of the invocable to store.
* \tparam Args The type of the callable's arguments to store.
*/
template <typename Callable, typename... Args>
struct NodeExecutorImpl final : public NodeExecutor {
private:
// clang-format off
/** Defines an alias for the type of the invocable for the node. */
using InvocableType = Invocable<std::decay_t<Callable>>;
/** Defines the type of the argument contianer. */
using ArgContainer = Tuple<Args...>;
/** The number of arguments for the execution. */
static constexpr size_t num_args = sizeof...(Args);
// clang-format on
public:
/**
* Constructor to store the invocable and args for the executor.
* \param invocable The invocable object to store.
* \param args The arguments for the invocable.
* \tparam InvType The type of the invocable.
* \tparam ArgTypes The types of the arguments.
*/
template <typename InvType, typename... ArgTypes>
NodeExecutorImpl(InvType&& invocable, ArgTypes&&... args) noexcept
: invocable_{ripple_forward(invocable)}, args_{ripple_forward(args)...} {}
/** Destuctor -- defaulted. */
~NodeExecutorImpl() noexcept final = default;
/**
* Copy constructor which copies the other executor into this one.
* \param other The other executor to copy.
*/
NodeExecutorImpl(const NodeExecutorImpl& other) noexcept
: invocable_{other.invocable_}, args_{other.args_} {}
/**
* Move constructor which moves the other executor into this.
* \param other The other executor to copy.
*/
NodeExecutorImpl(NodeExecutorImpl&& other) noexcept
: invocable_{ripple_move(other._invocable)},
args_{ripple_move(other._args)} {}
/**
* Copy assignment to copy the other executor to this one.
* \param other The other executor to copy to this one.
* \return A reference to the new executor.
*/
auto operator=(const NodeExecutorImpl& other) noexcept -> NodeExecutorImpl& {
invocable_ = other.invocable_;
args_ = other.args_;
return *this;
}
/**
* Move assignment to move the other executor to this one.
* \param other The other executor to move to this one.
* \return A reference to the new executor.
*/
auto operator=(NodeExecutorImpl&& other) noexcept -> NodeExecutorImpl& {
if (&other != this) {
invocable_ = ripple_move(other.invocable_);
args_ = ripple_move(other.args_);
}
return *this;
}
/*==--- [interface impl] -------------------------------------------------==*/
/**
* Implementation of the execute method to run the executor.
*/
auto execute() noexcept -> void final {
execute_impl(std::make_index_sequence<num_args>());
}
/**
* Implementation of the clone method to copy this class into the provided
* storage.
* \param storage The storage to clone into.
* \return A pointer to the cloned executor.
*/
auto clone(void* storage) const noexcept -> NodeExecutorImpl* final {
new (storage) NodeExecutorImpl(*this);
return reinterpret_cast<NodeExecutorImpl*>(storage);
}
private:
InvocableType invocable_; //!< The object to be invoked.
ArgContainer args_; //!< Args for the invocable.
/**
* Implementation of execution of the invocable, expanding the args into it.
* \tparam I The indices for the arguments.
*/
template <size_t... I>
auto execute_impl(std::index_sequence<I...>) noexcept -> void {
invocable_(get<I>(args_)...);
}
};
/*==--- [node info] --------------------------------------------------------==*/
/**
* This class defines extra infromation for a node which may be useful for
* the construction of graphs, but which is not necessary for execution.
* We store it separately to reduce the memory footprint of the node so that
* on the fast path (node execution) this information does not result in a
* performance hit.
*/
struct NodeInfo {
// clang-format off
/** Defines the type used for the node name. */
using Name = std::string;
/// Defines the type used for the node id.
using IdType = uint64_t;
/// Defines the type of the friends container.
using Friends = std::vector<IdType>;
/// Default id of the node.
static constexpr IdType default_id = std::numeric_limits<IdType>::max();
/// Default name of the node.
static constexpr auto default_name = "";
// clang-format on
/**
* Creates an id for a node from the given indices, using hash combining.
* \param indices The indices to create an id from.
* \tparam Size The number of ids.
* \return The id of the node.
*/
template <size_t Size>
static auto
id_from_indices(const std::array<uint32_t, Size>& indices) -> uint64_t {
using namespace math;
static_assert(Size <= 3, "Node id only valid for up to 3 dimensions!");
return Size == 1 ? indices[0]
: Size == 2 ? hash_combine(indices[0], indices[1])
: Size == 3
? hash_combine(indices[2], hash_combine(indices[0], indices[1]))
: 0;
}
/**
* Creates a name for a node from the indices.
* \param indices The indices to create a name from.
* \tparam Size The number of ids.
* \return The name of the node.
*/
template <size_t Size>
static auto
name_from_indices(const std::array<uint32_t, Size>& indices) noexcept
-> Name {
Name name = Size == 0 ? "" : std::to_string(indices[0]);
for (auto i : range(Size - 1)) {
name += "_" + std::to_string(indices[i + 1]);
}
return name;
}
/*==--- [construction] ---------------------------------------------------==*/
/** Default constructor for node info. */
NodeInfo() = default;
/**
* Constructor to set the execution kind for the node.
* \param exec_kind_ The execution kind for the node.
*/
explicit NodeInfo(ExecutionKind exec_kind_) noexcept : exec{exec_kind_} {}
/**
* Constructor to set the kind and execution kind for the node.
* \param kind_ The kind of teh node.
* \param exec_kind_ The execution kind for the node.
*/
explicit NodeInfo(NodeKind kind_, ExecutionKind exec_kind_) noexcept
: kind{kind_}, exec{exec_kind_} {}
/**
* Constructor for node info which sets the name for the node.
* \param name_ The name of the node.
*/
NodeInfo(Name name_) noexcept : name{ripple_move(name_)} {}
/**
* Constructor to set the node name and id.
* \param name_ The name of the node.
* \param id_ The id of the node.
*/
NodeInfo(Name name_, IdType id_) noexcept
: name{ripple_move(name_)}, id{id_} {}
/**
* Constructor to set the node name , id, and kind.
* \param name_ The name of the node.
* \param id_ The id of the node.
* \param kind_ The kind of the node.
*/
NodeInfo(Name name_, IdType id_, NodeKind kind_) noexcept
: name{ripple_move(name_)}, id{id_}, kind{kind_} {}
/**
* Constructor to set the node name, id, kind, and execution target for the
* node.
* \param name_ The name of the node.
* \param id_ The id of the node.
* \param kind_ The kind of the node.
* \param exec_ The execution kind of the node.
*/
NodeInfo(Name name_, IdType id_, NodeKind kind_, ExecutionKind exec_) noexcept
: name{ripple_move(name_)}, id{id_}, kind{kind_}, exec{exec_} {}
/*==--- [deleted] --------------------------------------------------------==*/
// clang-format off
/** Copy constructor -- deleted. */
NodeInfo(const NodeInfo& other) = default;
/** Move constructor deleted. */
NodeInfo(NodeInfo&& other) = default;
/** Move assignment -- deleted. */
auto operator=(const NodeInfo&) = delete;
/** Copy assignment -- deleted. */
auto operator=(NodeInfo&&) = delete;
// clang-format on
/*==--- [members] --------------------------------------------------------==*/
Name name = default_name; //!< The name of the node.
Friends friends = {}; //!< Siblings for the node.
IdType id = default_id; //!< Id of the node.
NodeKind kind = NodeKind::normal; //!< The kind of the node.
ExecutionKind exec = ExecutionKind::gpu; //!< Execution kind of the node.
};
/*==--- [node impl] --------------------------------------------------------==*/
/**
* Implementation type of a node class, which defines an operation a graph
* which performs work.
*
* It should be given an alignment which is a multiple of the cache line size
* so that there is no false sharing of nodes when they are used across
* threads.
*
* There is a small amount of overhead in the nodes, but they are still cheap
* In order for the Node's work to be __any__ callable object, the abstract base
* class NodeExecutor pointer needs to be stores.
*
* This is not really a problem in terms of storage overhead since ndoes are
* cache line aligned, and the 8 bytes are usually only a fraction of the cache
* line size, but it does reduce the available storage for the callable for the
* executor's work and more importantly, the arguments for the callable. It is
* therefore only a problem if the callable has many arguments, or the
* arguments are large. If this is a problem, a compile time error will be
* generated, in which case the alignment of the Node can be increased by the
* cachline size.
*
* Executing the Node's work then requires invoking the stored callable
* through the base NodeExecutor class. Benchmarks have shown that the compiler
* is usually able to remove the virtual function indirection, and the
* performance is usually the same as a __non inlined__ function call. The
* major drawback therefore is the loss of the ability for the compiler to
* inline.
*
* However, the benchmarking also showed that the the cost is approximately
* 1.1ns for any body of work executed through the NodeExecutor vs 0.25ns for
* an inlined version. This cost is therfore pretty small, and worth the added
* flexibility of allowing nodes to have any signature.
*
* \note The benchmarks were also on *very* cheap nodes (with small workloads).
*
* The above limitations are also not significant, since the *correct* use of
* nodes in the graph is to perform *non trivial* workloads. Even a node with
* a ~30ns workload only incurrs a ~2.5% overhead compared to if the Node's
* work body was executed inline. Most work should be in the us to ms range
* anyway, making the overhead negligible.
*
* \tparam Alignment The aligment for the node.
* \tparam MinStorage The number of bytes of storage required for a node.
*/
template <size_t Alignment, size_t MinStorage = 72>
class alignas(Alignment) Node {
/** Allow the graph class access to the node for building the graph. */
friend Graph;
// clang-format off
/**
* We use a vector for the successors, because it's only 24 bytes and enfore
* some limits on the number of successors for a node. What we really need to
* ensure is that the successors are contiguous so that when they are modified
* or accessed by a node they are on the same cache line, which is what the
* vector gives us.
*/
using Successors = std::vector<Node*>;
/** Defines the value type of the counter. */
using CounterValue = uint32_t;
/** Defines the type of the unfinished counter. */
using Counter = std::atomic<CounterValue>;
/** Defines the type of the pointer to the node information. */
using NodeInfoPtr = NodeInfo*;
/** Defines the type of the node executor pointer. */
using NodeExecutorPtr = NodeExecutor*;
// clang-format off
/** Memory required for all node data. */
static constexpr size_t data_mem_size =
sizeof(Successors) +
sizeof(NodeExecutorPtr) +
sizeof(NodeInfoPtr) +
sizeof(CounterValue) +
sizeof(Counter);
/** Spare space on cache line. */
static constexpr size_t spare_mem = data_mem_size % Alignment;
/** Multiples of alignment required for the node. */
static constexpr size_t align_mult = (data_mem_size + MinStorage) / Alignment;
/** Defines the size of the storage buffer for the node. */
static constexpr size_t size = spare_mem + (align_mult * Alignment);
// clang-format on
/** Returns true if T is not a Node. */
template <typename T>
static constexpr bool is_not_node_v = !std::is_same_v<std::decay_t<T>, Node>;
/** Defines a valid type if T is not a node. */
template <typename T>
using non_node_enable_t = std::enable_if_t<is_not_node_v<T>, int>;
public:
/*==--- [construction] ---------------------------------------------------==*/
// clang-format off
/** Default constructor. */
Node() noexcept = default;
/** Default destructor. */
~Node() noexcept = default;
// clang-format on
/**
* Copy constructor which clones the executor and copies the rest of the node
* state.
*
* \note This will check against the executor being a nullptr in debug mode,
* in release there is not check and a null executor will likely cause
* a segfault.
*
* \note This could be expensive if the node has *a lot* of successors.
*
* \note This does not copy the node's information. Information for a node
* is unique and should be allocated and set after copying a noce.
*
* \param other The other node to copy into this node.
*/
Node(const Node& other) noexcept {
debug_assert_node_valid(other);
executor_ = other.executor_->clone(&storage_);
incoming_ = other.incoming_;
dependents_.store(
other.dependents_.load(std::memory_order_relaxed),
std::memory_order_relaxed);
for (size_t i = 0; i < other.successors_.size(); ++i) {
successors_[i] = other.successors_[i];
}
}
/**
* Move constructor which just calls the copy constructor for most of the node
* data, but moves the successors of the other node into this node.
* \param other The other task to move from.
*/
Node(Node&& other) noexcept
: executor_(other.executor_),
info_(other.info_),
incoming_(other.incoming_),
successors_(ripple_move(other.successors_)),
dependents_(other.dependents_.load(std::memory_order_relaxed)) {
other._executor = nullptr;
other._info = nullptr;
other._incoming = 0;
other._dependents.store(0, std::memory_order_relaxed);
}
/**
* Constructs the node, creating its executor by storing the callable and
* the callable's arguments in the additional storage for the node.
*
* \note This constructor is only enabled if F is not a Node.
*
* \note If the callable and its arguments will not fit into the node storage
* then this will fail at compile time and the size of the node will
* need to be increased.
*
*
* \param callable The callable object to store.
* \param args The arguments to store.
* \tparam F The type of the callable object.
* \tparam Args The type of the arguments for the callable.
*/
template <typename F, typename... Args, non_node_enable_t<F> = 0>
Node(F&& callable, Args&&... args) noexcept {
set_executor(ripple_forward(callable), ripple_forward(args)...);
}
/*==--- [operator overloads] ---------------------------------------------==*/
/**
* Copy assignment overload which clones the executor and copies the node
* state.
*
* \note This will check against the other node's executor being a nullptr in
* debug, but will likely cause a segfault in release.
*
* \note This does not copy the node information, which should be unique
* and therefore allocated and then set after copying the node.
*
* \param other The other node to copy.
* \return A reference to the new node.
*/
auto operator=(const Node& other) noexcept -> Node& {
if (this == &other) {
return *this;
}
debug_assert_valid_node(other);
executor_ = other.executor_->clone(&storage_);
incoming_ = other.incoming_;
dependents_.store(
other.dependents_.load(std::memory_order_relaxed),
std::memory_order_relaxed);
for (int i = 0; i < other.successors_.size(); ++i) {
successors_[i] = other.successors_[i];
}
return *this;
}
/**
* Move assignment overload which clones the executor, copies the other node
* state, moves the other node's successors, and invalidates the other node.
*
* \note This will check against the other node's executor being a nullptr in
* debug, in release it will likely cause a segfault.
*
* \param other The other node to move from.
* \return A reference to the new node.
*/
auto operator=(Node&& other) noexcept -> Node& {
if (this == &other) {
return *this;
}
debug_assert_node_valid(other);
executor_ = other.executor_;
info_ = other.info_;
incoming_ = other.incoming_;
successors_ = ripple_move(other.successors_);
dependents_.store(
other.dependents_.load(std::memory_order_relaxed),
std::memory_order_relaxed);
other.executor_ = nullptr;
other.info_ = nullptr;
other.incoming_ = 0;
other.dependents_.store(0, std::memory_order_relaxed);
return *this;
}
/*==--- [interface] ------ -----------------------------------------------==*/
/**
* Sets the executor of the node to use the given callable and its args.
*
* \note This will check that there is enough space in the node storage for
* the callable and its arguments. If there is not enough space, a
* compile time error is generated with the required additional number
* of bytes.
*
* \param callable The callable object to store.
* \param args The arguments to store.
* \tparam F The type of the callable object.
* \tparam Args The type of the arguments for the callable.
*/
template <typename F, typename... Args>
auto set_executor(F&& callable, Args&&... args) noexcept -> void {
using Executor = NodeExecutorImpl<F, Args...>;
if constexpr (size < sizeof(Executor)) {
static_assert(
Tuple<
Num<size - sizeof(Executor)>,
Num<size>,
Num<sizeof(Executor)>,
Num<sizeof(F)>,
Tuple<Args, Num<sizeof(Args)>>...>::too_large,
"Node storage is too small to allocate callable and its args!");
}
new (&storage_) Executor{ripple_forward(callable), ripple_forward(args)...};
executor_ = reinterpret_cast<Executor*>(&storage_);
}
/**
* Tries to run the node.
* \return true if the node has no dependencies and therefore executes,
* otherwise returns false.
*/
auto try_run() noexcept -> bool {
if (dependents_.load(std::memory_order_relaxed) != size_t{0}) {
return false;
}
/* Reset the node incase it needs to be run again, as well as to make sure
* that it can't be run again until all dependents have run;
*
* \note This is very improtant that this is reset *before* the executor
* executes. If not, it's possible that multiple threads could see
* this node as having no dependencies, and both run the node.
*/
dependents_.store(incoming_, std::memory_order_relaxed);
executor_->execute();
for (auto* successor : successors_) {
if (successor && successor->num_dependents() > 0) {
successor->dependents_.fetch_sub(1, std::memory_order_relaxed);
}
}
return true;
}
/**
* Add sthe given node as a successor for this node.
* \param node The node to add as a successor to this node.
*/
auto add_successor(Node& node) noexcept -> void {
for (auto* successor : successors_) {
if (successor == &node) {
return;
}
}
successors_.push_back(&node);
node.increment_num_dependents();
}
/**
* Adds the node with the given id as a friend of this node.
*
* \note A friend node is a node which can execute in parallel with another
* node, but which is used by the other node for the other node's
* operation, but is not modified by it.
*
* For example, if x is a friend of y, then y *uses* x for an
* operation, and x cannot be modified by any operations on it until
* *y* has performed its operation.
*
* \param friend_id The id of the friend to add.
*/
auto add_friend(typename NodeInfo::IdType friend_id) noexcept -> void {
info_->friends.emplace_back(friend_id);
}
/**
* Gets all friends for the node.
* \return A container of all friend node ids.
*/
auto friends() const noexcept -> typename NodeInfo::Friends& {
return info_->friends;
}
/** Increments the number of dependents for the node. */
auto increment_num_dependents() noexcept -> void {
dependents_.fetch_add(1, std::memory_order_relaxed);
incoming_ = dependents_.load(std::memory_order_relaxed);
}
/**
* Gets the name of the node.
* \return the name of the node.
*/
auto name() const noexcept -> typename NodeInfo::Name {
return info_ ? info_->name : NodeInfo::default_name;
}
/**
* Gets the id of the node.
* \return The id of the node.
*/
auto id() const noexcept -> typename NodeInfo::IdType {
return info_ ? info_->id : NodeInfo::default_id;
}
/**
* Gets the kind of the node.
* \return The kind of the node.
*/
auto kind() const noexcept -> NodeKind {
return info_ ? info_->kind : NodeKind::normal;
}
/**
* Gets the execution target for the node.
* \return The kind of the execution target for the node.
*/
auto execution_kind() const noexcept -> ExecutionKind {
return info_ ? info_->exec : default_execution_kind;
}
/**
* Gets the number of dependents for the node.
* \return The number of dependents for the node.
*/
auto num_dependents() const noexcept -> CounterValue {
return dependents_.load(std::memory_order_relaxed);
}
private:
/*==--- [members] --------------------------------------------------------==*/
Successors successors_ = {}; //!< Array of successors.
NodeExecutorPtr executor_ = nullptr; //!< The executor to run the node.
NodeInfoPtr info_ = nullptr; //!< Node's info.
CounterValue incoming_ = 0; //!< Incomming connections.
Counter dependents_ = 0; //!< Counter for dependents.
char storage_[size] = {}; //!< Additional storage.
/**
* Checks if the given node is valid.
*
* \note In release build this is disabled, while in debug builds
* this will terminate if the executor in node is a nullptr.
*
* \param node The node to check the validity of.
*/
auto debug_assert_node_valid(const Node& node) const noexcept -> void {
assert(node.executor_ != nullptr && "Node executor can't be a nullptr!");
}
};
} // namespace ripple
#endif // RIPPLE_GRAPH_NODE_HPP | 35.180822 | 80 | 0.641772 | [
"object",
"vector"
] |
0748d6902898ea9833998ad1a92c2d2d1e82b918 | 90,146 | hpp | C++ | core/unit_test/TestViewSubview.hpp | ORNL-CEES/kokkos | 70d113838b7dade09218a46c1e8aae44b6dbd321 | [
"BSD-3-Clause"
] | 1 | 2019-10-15T19:26:22.000Z | 2019-10-15T19:26:22.000Z | core/unit_test/TestViewSubview.hpp | ORNL-CEES/kokkos | 70d113838b7dade09218a46c1e8aae44b6dbd321 | [
"BSD-3-Clause"
] | 16 | 2019-04-15T20:52:05.000Z | 2020-01-24T05:13:25.000Z | core/unit_test/TestViewSubview.hpp | ORNL-CEES/kokkos | 70d113838b7dade09218a46c1e8aae44b6dbd321 | [
"BSD-3-Clause"
] | 1 | 2019-11-25T14:06:26.000Z | 2019-11-25T14:06:26.000Z | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef TESTVIEWSUBVIEW_HPP_
#define TESTVIEWSUBVIEW_HPP_
#include <gtest/gtest.h>
#include <Kokkos_Core.hpp>
#include <stdexcept>
#include <sstream>
#include <iostream>
#include <type_traits>
// TODO @refactoring move this to somewhere common
//------------------------------------------------------------------------------
template <class...>
struct _kokkos____________________static_test_failure_____;
template <class...>
struct static_predicate_message {};
//------------------------------------------------------------------------------
template <class, template <class...> class, class...>
struct static_assert_predicate_true_impl;
template <template <class...> class predicate, class... message, class... args>
struct static_assert_predicate_true_impl<
typename std::enable_if<predicate<args...>::type::value>::type, predicate,
static_predicate_message<message...>, args...> {
using type = int;
};
template <template <class...> class predicate, class... message, class... args>
struct static_assert_predicate_true_impl<
typename std::enable_if<!predicate<args...>::type::value>::type, predicate,
static_predicate_message<message...>, args...> {
using type = typename _kokkos____________________static_test_failure_____<
message...>::type;
};
template <template <class...> class predicate, class... args>
struct static_assert_predicate_true
: static_assert_predicate_true_impl<void, predicate,
static_predicate_message<>, args...> {};
template <template <class...> class predicate, class... message, class... args>
struct static_assert_predicate_true<
predicate, static_predicate_message<message...>, args...>
: static_assert_predicate_true_impl<
void, predicate, static_predicate_message<message...>, args...> {};
//------------------------------------------------------------------------------
// error "messages"
struct _kokkos__________types_should_be_the_same_____expected_type__ {};
struct _kokkos__________actual_type_was__ {};
template <class Expected, class Actual>
struct static_expect_same {
using type = typename static_assert_predicate_true<
std::is_same,
static_predicate_message<
_kokkos__________types_should_be_the_same_____expected_type__,
Expected, _kokkos__________actual_type_was__, Actual>,
Expected, Actual>::type;
};
//------------------------------------------------------------------------------
namespace TestViewSubview {
template <class Layout, class Space>
struct getView {
static Kokkos::View<double**, Layout, Space> get(int n, int m) {
return Kokkos::View<double**, Layout, Space>("G", n, m);
}
};
template <class Space>
struct getView<Kokkos::LayoutStride, Space> {
static Kokkos::View<double**, Kokkos::LayoutStride, Space> get(int n, int m) {
const int rank = 2;
const int order[] = {0, 1};
const unsigned dim[] = {unsigned(n), unsigned(m)};
Kokkos::LayoutStride stride =
Kokkos::LayoutStride::order_dimensions(rank, order, dim);
return Kokkos::View<double**, Kokkos::LayoutStride, Space>("G", stride);
}
};
template <class ViewType, class Space>
struct fill_1D {
typedef typename Space::execution_space execution_space;
typedef typename ViewType::size_type size_type;
ViewType a;
double val;
fill_1D(ViewType a_, double val_) : a(a_), val(val_) {}
KOKKOS_INLINE_FUNCTION
void operator()(const int i) const { a(i) = val; }
};
template <class ViewType, class Space>
struct fill_2D {
typedef typename Space::execution_space execution_space;
typedef typename ViewType::size_type size_type;
ViewType a;
double val;
fill_2D(ViewType a_, double val_) : a(a_), val(val_) {}
KOKKOS_INLINE_FUNCTION
void operator()(const int i) const {
for (int j = 0; j < static_cast<int>(a.extent(1)); j++) {
a(i, j) = val;
}
}
};
template <class Layout, class Space>
void test_auto_1d() {
typedef Kokkos::View<double**, Layout, Space> mv_type;
typedef typename mv_type::size_type size_type;
const double ZERO = 0.0;
const double ONE = 1.0;
const double TWO = 2.0;
const size_type numRows = 10;
const size_type numCols = 3;
mv_type X = getView<Layout, Space>::get(numRows, numCols);
typename mv_type::HostMirror X_h = Kokkos::create_mirror_view(X);
fill_2D<mv_type, Space> f1(X, ONE);
Kokkos::parallel_for(X.extent(0), f1);
Kokkos::fence();
Kokkos::deep_copy(X_h, X);
for (size_type j = 0; j < numCols; ++j) {
for (size_type i = 0; i < numRows; ++i) {
ASSERT_TRUE(X_h(i, j) == ONE);
}
}
fill_2D<mv_type, Space> f2(X, 0.0);
Kokkos::parallel_for(X.extent(0), f2);
Kokkos::fence();
Kokkos::deep_copy(X_h, X);
for (size_type j = 0; j < numCols; ++j) {
for (size_type i = 0; i < numRows; ++i) {
ASSERT_TRUE(X_h(i, j) == ZERO);
}
}
fill_2D<mv_type, Space> f3(X, TWO);
Kokkos::parallel_for(X.extent(0), f3);
Kokkos::fence();
Kokkos::deep_copy(X_h, X);
for (size_type j = 0; j < numCols; ++j) {
for (size_type i = 0; i < numRows; ++i) {
ASSERT_TRUE(X_h(i, j) == TWO);
}
}
for (size_type j = 0; j < numCols; ++j) {
auto X_j = Kokkos::subview(X, Kokkos::ALL, j);
fill_1D<decltype(X_j), Space> f4(X_j, ZERO);
Kokkos::parallel_for(X_j.extent(0), f4);
Kokkos::fence();
Kokkos::deep_copy(X_h, X);
for (size_type i = 0; i < numRows; ++i) {
ASSERT_TRUE(X_h(i, j) == ZERO);
}
for (size_type jj = 0; jj < numCols; ++jj) {
auto X_jj = Kokkos::subview(X, Kokkos::ALL, jj);
fill_1D<decltype(X_jj), Space> f5(X_jj, ONE);
Kokkos::parallel_for(X_jj.extent(0), f5);
Kokkos::fence();
Kokkos::deep_copy(X_h, X);
for (size_type i = 0; i < numRows; ++i) {
ASSERT_TRUE(X_h(i, jj) == ONE);
}
}
}
}
template <class LD, class LS, class Space>
void test_1d_strided_assignment_impl(bool a, bool b, bool c, bool d, int n,
int m) {
Kokkos::View<double**, LS, Space> l2d("l2d", n, m);
int col = n > 2 ? 2 : 0;
int row = m > 2 ? 2 : 0;
if (Kokkos::Impl::SpaceAccessibility<
Kokkos::HostSpace, typename Space::memory_space>::accessible) {
if (a) {
Kokkos::View<double*, LD, Space> l1da =
Kokkos::subview(l2d, Kokkos::ALL, row);
ASSERT_TRUE(&l1da(0) == &l2d(0, row));
if (n > 1) {
ASSERT_TRUE(&l1da(1) == &l2d(1, row));
}
}
if (b && n > 13) {
Kokkos::View<double*, LD, Space> l1db =
Kokkos::subview(l2d, std::pair<unsigned, unsigned>(2, 13), row);
ASSERT_TRUE(&l1db(0) == &l2d(2, row));
ASSERT_TRUE(&l1db(1) == &l2d(3, row));
}
if (c) {
Kokkos::View<double*, LD, Space> l1dc =
Kokkos::subview(l2d, col, Kokkos::ALL);
ASSERT_TRUE(&l1dc(0) == &l2d(col, 0));
if (m > 1) {
ASSERT_TRUE(&l1dc(1) == &l2d(col, 1));
}
}
if (d && m > 13) {
Kokkos::View<double*, LD, Space> l1dd =
Kokkos::subview(l2d, col, std::pair<unsigned, unsigned>(2, 13));
ASSERT_TRUE(&l1dd(0) == &l2d(col, 2));
ASSERT_TRUE(&l1dd(1) == &l2d(col, 3));
}
}
}
template <class Space>
void test_1d_strided_assignment() {
test_1d_strided_assignment_impl<Kokkos::LayoutStride, Kokkos::LayoutLeft,
Space>(true, true, true, true, 17, 3);
test_1d_strided_assignment_impl<Kokkos::LayoutStride, Kokkos::LayoutRight,
Space>(true, true, true, true, 17, 3);
test_1d_strided_assignment_impl<Kokkos::LayoutLeft, Kokkos::LayoutLeft,
Space>(true, true, false, false, 17, 3);
test_1d_strided_assignment_impl<Kokkos::LayoutRight, Kokkos::LayoutLeft,
Space>(true, true, false, false, 17, 3);
test_1d_strided_assignment_impl<Kokkos::LayoutLeft, Kokkos::LayoutRight,
Space>(false, false, true, true, 17, 3);
test_1d_strided_assignment_impl<Kokkos::LayoutRight, Kokkos::LayoutRight,
Space>(false, false, true, true, 17, 3);
test_1d_strided_assignment_impl<Kokkos::LayoutLeft, Kokkos::LayoutLeft,
Space>(true, true, false, false, 17, 1);
test_1d_strided_assignment_impl<Kokkos::LayoutLeft, Kokkos::LayoutLeft,
Space>(true, true, true, true, 1, 17);
test_1d_strided_assignment_impl<Kokkos::LayoutRight, Kokkos::LayoutLeft,
Space>(true, true, true, true, 1, 17);
test_1d_strided_assignment_impl<Kokkos::LayoutRight, Kokkos::LayoutLeft,
Space>(true, true, false, false, 17, 1);
test_1d_strided_assignment_impl<Kokkos::LayoutLeft, Kokkos::LayoutRight,
Space>(true, true, true, true, 17, 1);
test_1d_strided_assignment_impl<Kokkos::LayoutLeft, Kokkos::LayoutRight,
Space>(false, false, true, true, 1, 17);
test_1d_strided_assignment_impl<Kokkos::LayoutRight, Kokkos::LayoutRight,
Space>(false, false, true, true, 1, 17);
test_1d_strided_assignment_impl<Kokkos::LayoutRight, Kokkos::LayoutRight,
Space>(true, true, true, true, 17, 1);
}
template <class Space>
void test_left_0() {
typedef Kokkos::View<int[2][3][4][5][2][3][4][5], Kokkos::LayoutLeft, Space>
view_static_8_type;
if (Kokkos::Impl::SpaceAccessibility<
Kokkos::HostSpace, typename Space::memory_space>::accessible) {
view_static_8_type x_static_8("x_static_left_8");
ASSERT_TRUE(x_static_8.span_is_contiguous());
Kokkos::View<int, Kokkos::LayoutLeft, Space> x0 =
Kokkos::subview(x_static_8, 0, 0, 0, 0, 0, 0, 0, 0);
ASSERT_TRUE(x0.span_is_contiguous());
ASSERT_TRUE(&x0() == &x_static_8(0, 0, 0, 0, 0, 0, 0, 0));
Kokkos::View<int*, Kokkos::LayoutLeft, Space> x1 = Kokkos::subview(
x_static_8, Kokkos::pair<int, int>(0, 2), 1, 2, 3, 0, 1, 2, 3);
ASSERT_TRUE(x1.span_is_contiguous());
ASSERT_TRUE(&x1(0) == &x_static_8(0, 1, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&x1(1) == &x_static_8(1, 1, 2, 3, 0, 1, 2, 3));
Kokkos::View<int**, Kokkos::LayoutLeft, Space> x2 =
Kokkos::subview(x_static_8, Kokkos::pair<int, int>(0, 2), 1, 2, 3,
Kokkos::pair<int, int>(0, 2), 1, 2, 3);
ASSERT_TRUE(!x2.span_is_contiguous());
ASSERT_TRUE(&x2(0, 0) == &x_static_8(0, 1, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&x2(1, 0) == &x_static_8(1, 1, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&x2(0, 1) == &x_static_8(0, 1, 2, 3, 1, 1, 2, 3));
ASSERT_TRUE(&x2(1, 1) == &x_static_8(1, 1, 2, 3, 1, 1, 2, 3));
// Kokkos::View< int**, Kokkos::LayoutLeft, Space > error_2 =
Kokkos::View<int**, Kokkos::LayoutStride, Space> sx2 =
Kokkos::subview(x_static_8, 1, Kokkos::pair<int, int>(0, 2), 2, 3,
Kokkos::pair<int, int>(0, 2), 1, 2, 3);
ASSERT_TRUE(!sx2.span_is_contiguous());
ASSERT_TRUE(&sx2(0, 0) == &x_static_8(1, 0, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&sx2(1, 0) == &x_static_8(1, 1, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&sx2(0, 1) == &x_static_8(1, 0, 2, 3, 1, 1, 2, 3));
ASSERT_TRUE(&sx2(1, 1) == &x_static_8(1, 1, 2, 3, 1, 1, 2, 3));
Kokkos::View<int****, Kokkos::LayoutStride, Space> sx4 =
Kokkos::subview(x_static_8, 0, Kokkos::pair<int, int>(0, 2) /* of [3] */
,
1, Kokkos::pair<int, int>(1, 3) /* of [5] */
,
1, Kokkos::pair<int, int>(0, 2) /* of [3] */
,
2, Kokkos::pair<int, int>(2, 4) /* of [5] */
);
ASSERT_TRUE(!sx4.span_is_contiguous());
for (int i0 = 0; i0 < (int)sx4.extent(0); ++i0)
for (int i1 = 0; i1 < (int)sx4.extent(1); ++i1)
for (int i2 = 0; i2 < (int)sx4.extent(2); ++i2)
for (int i3 = 0; i3 < (int)sx4.extent(3); ++i3) {
ASSERT_TRUE(&sx4(i0, i1, i2, i3) == &x_static_8(0, 0 + i0, 1,
1 + i1, 1, 0 + i2,
2, 2 + i3));
}
}
}
template <class Space>
void test_left_1() {
typedef Kokkos::View<int*** * [2][3][4][5], Kokkos::LayoutLeft, Space>
view_type;
if (Kokkos::Impl::SpaceAccessibility<
Kokkos::HostSpace, typename Space::memory_space>::accessible) {
view_type x8("x_left_8", 2, 3, 4, 5);
ASSERT_TRUE(x8.span_is_contiguous());
Kokkos::View<int, Kokkos::LayoutLeft, Space> x0 =
Kokkos::subview(x8, 0, 0, 0, 0, 0, 0, 0, 0);
ASSERT_TRUE(x0.span_is_contiguous());
ASSERT_TRUE(&x0() == &x8(0, 0, 0, 0, 0, 0, 0, 0));
Kokkos::View<int*, Kokkos::LayoutLeft, Space> x1 =
Kokkos::subview(x8, Kokkos::pair<int, int>(0, 2), 1, 2, 3, 0, 1, 2, 3);
ASSERT_TRUE(x1.span_is_contiguous());
ASSERT_TRUE(&x1(0) == &x8(0, 1, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&x1(1) == &x8(1, 1, 2, 3, 0, 1, 2, 3));
Kokkos::View<int**, Kokkos::LayoutLeft, Space> x2 =
Kokkos::subview(x8, Kokkos::pair<int, int>(0, 2), 1, 2, 3,
Kokkos::pair<int, int>(0, 2), 1, 2, 3);
ASSERT_TRUE(!x2.span_is_contiguous());
ASSERT_TRUE(&x2(0, 0) == &x8(0, 1, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&x2(1, 0) == &x8(1, 1, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&x2(0, 1) == &x8(0, 1, 2, 3, 1, 1, 2, 3));
ASSERT_TRUE(&x2(1, 1) == &x8(1, 1, 2, 3, 1, 1, 2, 3));
// Kokkos::View< int**, Kokkos::LayoutLeft, Space > error_2 =
Kokkos::View<int**, Kokkos::LayoutStride, Space> sx2 =
Kokkos::subview(x8, 1, Kokkos::pair<int, int>(0, 2), 2, 3,
Kokkos::pair<int, int>(0, 2), 1, 2, 3);
ASSERT_TRUE(!sx2.span_is_contiguous());
ASSERT_TRUE(&sx2(0, 0) == &x8(1, 0, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&sx2(1, 0) == &x8(1, 1, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&sx2(0, 1) == &x8(1, 0, 2, 3, 1, 1, 2, 3));
ASSERT_TRUE(&sx2(1, 1) == &x8(1, 1, 2, 3, 1, 1, 2, 3));
Kokkos::View<int****, Kokkos::LayoutStride, Space> sx4 =
Kokkos::subview(x8, 0, Kokkos::pair<int, int>(0, 2) /* of [3] */
,
1, Kokkos::pair<int, int>(1, 3) /* of [5] */
,
1, Kokkos::pair<int, int>(0, 2) /* of [3] */
,
2, Kokkos::pair<int, int>(2, 4) /* of [5] */
);
ASSERT_TRUE(!sx4.span_is_contiguous());
for (int i0 = 0; i0 < (int)sx4.extent(0); ++i0)
for (int i1 = 0; i1 < (int)sx4.extent(1); ++i1)
for (int i2 = 0; i2 < (int)sx4.extent(2); ++i2)
for (int i3 = 0; i3 < (int)sx4.extent(3); ++i3) {
ASSERT_TRUE(&sx4(i0, i1, i2, i3) ==
&x8(0, 0 + i0, 1, 1 + i1, 1, 0 + i2, 2, 2 + i3));
}
}
}
template <class Space>
void test_left_2() {
typedef Kokkos::View<int****, Kokkos::LayoutLeft, Space> view_type;
if (Kokkos::Impl::SpaceAccessibility<
Kokkos::HostSpace, typename Space::memory_space>::accessible) {
view_type x4("x4", 2, 3, 4, 5);
ASSERT_TRUE(x4.span_is_contiguous());
Kokkos::View<int, Kokkos::LayoutLeft, Space> x0 =
Kokkos::subview(x4, 0, 0, 0, 0);
ASSERT_TRUE(x0.span_is_contiguous());
ASSERT_TRUE(&x0() == &x4(0, 0, 0, 0));
Kokkos::View<int*, Kokkos::LayoutLeft, Space> x1 =
Kokkos::subview(x4, Kokkos::pair<int, int>(0, 2), 1, 2, 3);
ASSERT_TRUE(x1.span_is_contiguous());
ASSERT_TRUE(&x1(0) == &x4(0, 1, 2, 3));
ASSERT_TRUE(&x1(1) == &x4(1, 1, 2, 3));
Kokkos::View<int**, Kokkos::LayoutLeft, Space> x2 = Kokkos::subview(
x4, Kokkos::pair<int, int>(0, 2), 1, Kokkos::pair<int, int>(1, 3), 2);
ASSERT_TRUE(!x2.span_is_contiguous());
ASSERT_TRUE(&x2(0, 0) == &x4(0, 1, 1, 2));
ASSERT_TRUE(&x2(1, 0) == &x4(1, 1, 1, 2));
ASSERT_TRUE(&x2(0, 1) == &x4(0, 1, 2, 2));
ASSERT_TRUE(&x2(1, 1) == &x4(1, 1, 2, 2));
// Kokkos::View< int**, Kokkos::LayoutLeft, Space > error_2 =
Kokkos::View<int**, Kokkos::LayoutStride, Space> sx2 = Kokkos::subview(
x4, 1, Kokkos::pair<int, int>(0, 2), 2, Kokkos::pair<int, int>(1, 4));
ASSERT_TRUE(!sx2.span_is_contiguous());
ASSERT_TRUE(&sx2(0, 0) == &x4(1, 0, 2, 1));
ASSERT_TRUE(&sx2(1, 0) == &x4(1, 1, 2, 1));
ASSERT_TRUE(&sx2(0, 1) == &x4(1, 0, 2, 2));
ASSERT_TRUE(&sx2(1, 1) == &x4(1, 1, 2, 2));
ASSERT_TRUE(&sx2(0, 2) == &x4(1, 0, 2, 3));
ASSERT_TRUE(&sx2(1, 2) == &x4(1, 1, 2, 3));
Kokkos::View<int****, Kokkos::LayoutStride, Space> sx4 =
Kokkos::subview(x4, Kokkos::pair<int, int>(1, 2) /* of [2] */
,
Kokkos::pair<int, int>(1, 3) /* of [3] */
,
Kokkos::pair<int, int>(0, 4) /* of [4] */
,
Kokkos::pair<int, int>(2, 4) /* of [5] */
);
ASSERT_TRUE(!sx4.span_is_contiguous());
for (int i0 = 0; i0 < (int)sx4.extent(0); ++i0)
for (int i1 = 0; i1 < (int)sx4.extent(1); ++i1)
for (int i2 = 0; i2 < (int)sx4.extent(2); ++i2)
for (int i3 = 0; i3 < (int)sx4.extent(3); ++i3) {
ASSERT_TRUE(&sx4(i0, i1, i2, i3) ==
&x4(1 + i0, 1 + i1, 0 + i2, 2 + i3));
}
}
}
template <class Space>
void test_left_3() {
typedef Kokkos::View<int**, Kokkos::LayoutLeft, Space> view_type;
if (Kokkos::Impl::SpaceAccessibility<
Kokkos::HostSpace, typename Space::memory_space>::accessible) {
view_type xm("x4", 10, 5);
ASSERT_TRUE(xm.span_is_contiguous());
Kokkos::View<int, Kokkos::LayoutLeft, Space> x0 = Kokkos::subview(xm, 5, 3);
ASSERT_TRUE(x0.span_is_contiguous());
ASSERT_TRUE(&x0() == &xm(5, 3));
Kokkos::View<int*, Kokkos::LayoutLeft, Space> x1 =
Kokkos::subview(xm, Kokkos::ALL, 3);
ASSERT_TRUE(x1.span_is_contiguous());
for (int i = 0; i < int(xm.extent(0)); ++i) {
ASSERT_TRUE(&x1(i) == &xm(i, 3));
}
Kokkos::View<int**, Kokkos::LayoutLeft, Space> x2 =
Kokkos::subview(xm, Kokkos::pair<int, int>(1, 9), Kokkos::ALL);
ASSERT_TRUE(!x2.span_is_contiguous());
for (int j = 0; j < int(x2.extent(1)); ++j)
for (int i = 0; i < int(x2.extent(0)); ++i) {
ASSERT_TRUE(&x2(i, j) == &xm(1 + i, j));
}
Kokkos::View<int**, Kokkos::LayoutLeft, Space> x2c =
Kokkos::subview(xm, Kokkos::ALL, std::pair<int, int>(2, 4));
ASSERT_TRUE(x2c.span_is_contiguous());
for (int j = 0; j < int(x2c.extent(1)); ++j)
for (int i = 0; i < int(x2c.extent(0)); ++i) {
ASSERT_TRUE(&x2c(i, j) == &xm(i, 2 + j));
}
Kokkos::View<int**, Kokkos::LayoutLeft, Space> x2_n1 =
Kokkos::subview(xm, std::pair<int, int>(1, 1), Kokkos::ALL);
ASSERT_TRUE(x2_n1.extent(0) == 0);
ASSERT_TRUE(x2_n1.extent(1) == xm.extent(1));
Kokkos::View<int**, Kokkos::LayoutLeft, Space> x2_n2 =
Kokkos::subview(xm, Kokkos::ALL, std::pair<int, int>(1, 1));
ASSERT_TRUE(x2_n2.extent(0) == xm.extent(0));
ASSERT_TRUE(x2_n2.extent(1) == 0);
}
}
//----------------------------------------------------------------------------
template <class Space>
void test_right_0() {
typedef Kokkos::View<int[2][3][4][5][2][3][4][5], Kokkos::LayoutRight, Space>
view_static_8_type;
if (Kokkos::Impl::SpaceAccessibility<
Kokkos::HostSpace, typename Space::memory_space>::accessible) {
view_static_8_type x_static_8("x_static_right_8");
Kokkos::View<int, Kokkos::LayoutRight, Space> x0 =
Kokkos::subview(x_static_8, 0, 0, 0, 0, 0, 0, 0, 0);
ASSERT_TRUE(&x0() == &x_static_8(0, 0, 0, 0, 0, 0, 0, 0));
Kokkos::View<int*, Kokkos::LayoutRight, Space> x1 = Kokkos::subview(
x_static_8, 0, 1, 2, 3, 0, 1, 2, Kokkos::pair<int, int>(1, 3));
ASSERT_TRUE(x1.extent(0) == 2);
ASSERT_TRUE(&x1(0) == &x_static_8(0, 1, 2, 3, 0, 1, 2, 1));
ASSERT_TRUE(&x1(1) == &x_static_8(0, 1, 2, 3, 0, 1, 2, 2));
Kokkos::View<int**, Kokkos::LayoutRight, Space> x2 =
Kokkos::subview(x_static_8, 0, 1, 2, Kokkos::pair<int, int>(1, 3), 0, 1,
2, Kokkos::pair<int, int>(1, 3));
ASSERT_TRUE(x2.extent(0) == 2);
ASSERT_TRUE(x2.extent(1) == 2);
ASSERT_TRUE(&x2(0, 0) == &x_static_8(0, 1, 2, 1, 0, 1, 2, 1));
ASSERT_TRUE(&x2(1, 0) == &x_static_8(0, 1, 2, 2, 0, 1, 2, 1));
ASSERT_TRUE(&x2(0, 1) == &x_static_8(0, 1, 2, 1, 0, 1, 2, 2));
ASSERT_TRUE(&x2(1, 1) == &x_static_8(0, 1, 2, 2, 0, 1, 2, 2));
// Kokkos::View< int**, Kokkos::LayoutRight, Space > error_2 =
Kokkos::View<int**, Kokkos::LayoutStride, Space> sx2 =
Kokkos::subview(x_static_8, 1, Kokkos::pair<int, int>(0, 2), 2, 3,
Kokkos::pair<int, int>(0, 2), 1, 2, 3);
ASSERT_TRUE(sx2.extent(0) == 2);
ASSERT_TRUE(sx2.extent(1) == 2);
ASSERT_TRUE(&sx2(0, 0) == &x_static_8(1, 0, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&sx2(1, 0) == &x_static_8(1, 1, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&sx2(0, 1) == &x_static_8(1, 0, 2, 3, 1, 1, 2, 3));
ASSERT_TRUE(&sx2(1, 1) == &x_static_8(1, 1, 2, 3, 1, 1, 2, 3));
Kokkos::View<int****, Kokkos::LayoutStride, Space> sx4 =
Kokkos::subview(x_static_8, 0, Kokkos::pair<int, int>(0, 2) /* of [3] */
,
1, Kokkos::pair<int, int>(1, 3) /* of [5] */
,
1, Kokkos::pair<int, int>(0, 2) /* of [3] */
,
2, Kokkos::pair<int, int>(2, 4) /* of [5] */
);
ASSERT_TRUE(sx4.extent(0) == 2);
ASSERT_TRUE(sx4.extent(1) == 2);
ASSERT_TRUE(sx4.extent(2) == 2);
ASSERT_TRUE(sx4.extent(3) == 2);
for (int i0 = 0; i0 < (int)sx4.extent(0); ++i0)
for (int i1 = 0; i1 < (int)sx4.extent(1); ++i1)
for (int i2 = 0; i2 < (int)sx4.extent(2); ++i2)
for (int i3 = 0; i3 < (int)sx4.extent(3); ++i3) {
ASSERT_TRUE(&sx4(i0, i1, i2, i3) == &x_static_8(0, 0 + i0, 1,
1 + i1, 1, 0 + i2,
2, 2 + i3));
}
}
}
template <class Space>
void test_right_1() {
typedef Kokkos::View<int*** * [2][3][4][5], Kokkos::LayoutRight, Space>
view_type;
if (Kokkos::Impl::SpaceAccessibility<
Kokkos::HostSpace, typename Space::memory_space>::accessible) {
view_type x8("x_right_8", 2, 3, 4, 5);
Kokkos::View<int, Kokkos::LayoutRight, Space> x0 =
Kokkos::subview(x8, 0, 0, 0, 0, 0, 0, 0, 0);
ASSERT_TRUE(&x0() == &x8(0, 0, 0, 0, 0, 0, 0, 0));
Kokkos::View<int*, Kokkos::LayoutRight, Space> x1 =
Kokkos::subview(x8, 0, 1, 2, 3, 0, 1, 2, Kokkos::pair<int, int>(1, 3));
ASSERT_TRUE(&x1(0) == &x8(0, 1, 2, 3, 0, 1, 2, 1));
ASSERT_TRUE(&x1(1) == &x8(0, 1, 2, 3, 0, 1, 2, 2));
Kokkos::View<int**, Kokkos::LayoutRight, Space> x2 =
Kokkos::subview(x8, 0, 1, 2, Kokkos::pair<int, int>(1, 3), 0, 1, 2,
Kokkos::pair<int, int>(1, 3));
ASSERT_TRUE(&x2(0, 0) == &x8(0, 1, 2, 1, 0, 1, 2, 1));
ASSERT_TRUE(&x2(1, 0) == &x8(0, 1, 2, 2, 0, 1, 2, 1));
ASSERT_TRUE(&x2(0, 1) == &x8(0, 1, 2, 1, 0, 1, 2, 2));
ASSERT_TRUE(&x2(1, 1) == &x8(0, 1, 2, 2, 0, 1, 2, 2));
// Kokkos::View< int**, Kokkos::LayoutRight, Space > error_2 =
Kokkos::View<int**, Kokkos::LayoutStride, Space> sx2 =
Kokkos::subview(x8, 1, Kokkos::pair<int, int>(0, 2), 2, 3,
Kokkos::pair<int, int>(0, 2), 1, 2, 3);
ASSERT_TRUE(&sx2(0, 0) == &x8(1, 0, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&sx2(1, 0) == &x8(1, 1, 2, 3, 0, 1, 2, 3));
ASSERT_TRUE(&sx2(0, 1) == &x8(1, 0, 2, 3, 1, 1, 2, 3));
ASSERT_TRUE(&sx2(1, 1) == &x8(1, 1, 2, 3, 1, 1, 2, 3));
Kokkos::View<int****, Kokkos::LayoutStride, Space> sx4 =
Kokkos::subview(x8, 0, Kokkos::pair<int, int>(0, 2) /* of [3] */
,
1, Kokkos::pair<int, int>(1, 3) /* of [5] */
,
1, Kokkos::pair<int, int>(0, 2) /* of [3] */
,
2, Kokkos::pair<int, int>(2, 4) /* of [5] */
);
for (int i0 = 0; i0 < (int)sx4.extent(0); ++i0)
for (int i1 = 0; i1 < (int)sx4.extent(1); ++i1)
for (int i2 = 0; i2 < (int)sx4.extent(2); ++i2)
for (int i3 = 0; i3 < (int)sx4.extent(3); ++i3) {
ASSERT_TRUE(&sx4(i0, i1, i2, i3) ==
&x8(0, 0 + i0, 1, 1 + i1, 1, 0 + i2, 2, 2 + i3));
}
}
}
template <class Space>
void test_right_3() {
typedef Kokkos::View<int**, Kokkos::LayoutRight, Space> view_type;
if (Kokkos::Impl::SpaceAccessibility<
Kokkos::HostSpace, typename Space::memory_space>::accessible) {
view_type xm("x4", 10, 5);
ASSERT_TRUE(xm.span_is_contiguous());
Kokkos::View<int, Kokkos::LayoutRight, Space> x0 =
Kokkos::subview(xm, 5, 3);
ASSERT_TRUE(x0.span_is_contiguous());
ASSERT_TRUE(&x0() == &xm(5, 3));
Kokkos::View<int*, Kokkos::LayoutRight, Space> x1 =
Kokkos::subview(xm, 3, Kokkos::ALL);
ASSERT_TRUE(x1.span_is_contiguous());
for (int i = 0; i < int(xm.extent(1)); ++i) {
ASSERT_TRUE(&x1(i) == &xm(3, i));
}
Kokkos::View<int**, Kokkos::LayoutRight, Space> x2c =
Kokkos::subview(xm, Kokkos::pair<int, int>(1, 9), Kokkos::ALL);
ASSERT_TRUE(x2c.span_is_contiguous());
for (int j = 0; j < int(x2c.extent(1)); ++j)
for (int i = 0; i < int(x2c.extent(0)); ++i) {
ASSERT_TRUE(&x2c(i, j) == &xm(1 + i, j));
}
Kokkos::View<int**, Kokkos::LayoutRight, Space> x2 =
Kokkos::subview(xm, Kokkos::ALL, std::pair<int, int>(2, 4));
ASSERT_TRUE(!x2.span_is_contiguous());
for (int j = 0; j < int(x2.extent(1)); ++j)
for (int i = 0; i < int(x2.extent(0)); ++i) {
ASSERT_TRUE(&x2(i, j) == &xm(i, 2 + j));
}
Kokkos::View<int**, Kokkos::LayoutRight, Space> x2_n1 =
Kokkos::subview(xm, std::pair<int, int>(1, 1), Kokkos::ALL);
ASSERT_TRUE(x2_n1.extent(0) == 0);
ASSERT_TRUE(x2_n1.extent(1) == xm.extent(1));
Kokkos::View<int**, Kokkos::LayoutRight, Space> x2_n2 =
Kokkos::subview(xm, Kokkos::ALL, std::pair<int, int>(1, 1));
ASSERT_TRUE(x2_n2.extent(0) == xm.extent(0));
ASSERT_TRUE(x2_n2.extent(1) == 0);
}
}
namespace Impl {
constexpr int N0 = 113;
constexpr int N1 = 11;
constexpr int N2 = 17;
constexpr int N3 = 5;
constexpr int N4 = 7;
template <class SubView, class View>
void test_Check1D(SubView a, View b, std::pair<int, int> range) {
int errors = 0;
for (int i = 0; i < range.second - range.first; i++) {
if (a(i) != b(i + range.first)) errors++;
}
if (errors > 0) {
std::cout << "Error Suviews test_Check1D: " << errors << std::endl;
}
ASSERT_TRUE(errors == 0);
}
template <class SubView, class View>
void test_Check1D2D(SubView a, View b, int i0, std::pair<int, int> range) {
int errors = 0;
for (int i1 = 0; i1 < range.second - range.first; i1++) {
if (a(i1) != b(i0, i1 + range.first)) errors++;
}
if (errors > 0) {
std::cout << "Error Suviews test_Check1D2D: " << errors << std::endl;
}
ASSERT_TRUE(errors == 0);
}
template <class SubView, class View>
void test_Check2D3D(SubView a, View b, int i0, std::pair<int, int> range1,
std::pair<int, int> range2) {
int errors = 0;
for (int i1 = 0; i1 < range1.second - range1.first; i1++) {
for (int i2 = 0; i2 < range2.second - range2.first; i2++) {
if (a(i1, i2) != b(i0, i1 + range1.first, i2 + range2.first)) errors++;
}
}
if (errors > 0) {
std::cout << "Error Suviews test_Check2D3D: " << errors << std::endl;
}
ASSERT_TRUE(errors == 0);
}
template <class SubView, class View>
void test_Check3D5D(SubView a, View b, int i0, int i1,
std::pair<int, int> range2, std::pair<int, int> range3,
std::pair<int, int> range4) {
int errors = 0;
for (int i2 = 0; i2 < range2.second - range2.first; i2++) {
for (int i3 = 0; i3 < range3.second - range3.first; i3++) {
for (int i4 = 0; i4 < range4.second - range4.first; i4++) {
if (a(i2, i3, i4) != b(i0, i1, i2 + range2.first, i3 + range3.first,
i4 + range4.first)) {
errors++;
}
}
}
}
if (errors > 0) {
std::cout << "Error Suviews test_Check3D5D: " << errors << std::endl;
}
ASSERT_TRUE(errors == 0);
}
template <class Space, class LayoutSub, class Layout, class LayoutOrg,
class MemTraits>
void test_1d_assign_impl() {
{ // Breaks.
Kokkos::View<int*, LayoutOrg, Space> a_org("A", N0);
Kokkos::View<int*, LayoutOrg, Space, MemTraits> a(a_org);
Kokkos::fence();
for (int i = 0; i < N0; i++) a_org(i) = i;
Kokkos::View<int[N0], Layout, Space, MemTraits> a1(a);
Kokkos::fence();
test_Check1D(a1, a, std::pair<int, int>(0, N0));
Kokkos::View<int[N0], LayoutSub, Space, MemTraits> a2(a1);
Kokkos::fence();
test_Check1D(a2, a, std::pair<int, int>(0, N0));
a1 = a;
test_Check1D(a1, a, std::pair<int, int>(0, N0));
// Runtime Fail expected.
// Kokkos::View< int[N1] > afail1( a );
// Compile Time Fail expected.
// Kokkos::View< int[N1] > afail2( a1 );
}
{ // Works.
Kokkos::View<int[N0], LayoutOrg, Space, MemTraits> a("A");
Kokkos::View<int*, Layout, Space, MemTraits> a1(a);
Kokkos::fence();
test_Check1D(a1, a, std::pair<int, int>(0, N0));
a1 = a;
Kokkos::fence();
test_Check1D(a1, a, std::pair<int, int>(0, N0));
}
}
template <class Space, class Type, class TypeSub, class LayoutSub, class Layout,
class LayoutOrg, class MemTraits>
void test_2d_subview_3d_impl_type() {
Kokkos::View<int***, LayoutOrg, Space> a_org("A", N0, N1, N2);
Kokkos::View<Type, Layout, Space, MemTraits> a(a_org);
for (int i0 = 0; i0 < N0; i0++)
for (int i1 = 0; i1 < N1; i1++)
for (int i2 = 0; i2 < N2; i2++) {
a_org(i0, i1, i2) = i0 * 1000000 + i1 * 1000 + i2;
}
Kokkos::View<TypeSub, LayoutSub, Space, MemTraits> a1;
a1 = Kokkos::subview(a, 3, Kokkos::ALL, Kokkos::ALL);
Kokkos::fence();
test_Check2D3D(a1, a, 3, std::pair<int, int>(0, N1),
std::pair<int, int>(0, N2));
Kokkos::View<TypeSub, LayoutSub, Space, MemTraits> a2(a, 3, Kokkos::ALL,
Kokkos::ALL);
Kokkos::fence();
test_Check2D3D(a2, a, 3, std::pair<int, int>(0, N1),
std::pair<int, int>(0, N2));
}
template <class Space, class LayoutSub, class Layout, class LayoutOrg,
class MemTraits>
void test_2d_subview_3d_impl_layout() {
test_2d_subview_3d_impl_type<Space, int[N0][N1][N2], int[N1][N2], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int[N0][N1][N2], int * [N2], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int[N0][N1][N2], int**, LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int * [N1][N2], int[N1][N2], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int * [N1][N2], int * [N2], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int * [N1][N2], int**, LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int* * [N2], int[N1][N2], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int* * [N2], int * [N2], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int* * [N2], int**, LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int***, int[N1][N2], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int***, int * [N2], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, int***, int**, LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int[N0][N1][N2], const int[N1][N2],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int[N0][N1][N2], const int * [N2],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int[N0][N1][N2], const int**,
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int * [N1][N2], const int[N1][N2],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int * [N1][N2], const int * [N2],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int * [N1][N2], const int**,
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int* * [N2], const int[N1][N2],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int* * [N2], const int * [N2],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int* * [N2], const int**, LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int***, const int[N1][N2],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int***, const int * [N2], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_2d_subview_3d_impl_type<Space, const int***, const int**, LayoutSub,
Layout, LayoutOrg, MemTraits>();
}
template <class Space, class Type, class TypeSub, class LayoutSub, class Layout,
class LayoutOrg, class MemTraits>
void test_3d_subview_5d_impl_type() {
Kokkos::View<int*****, LayoutOrg, Space> a_org("A", N0, N1, N2, N3, N4);
Kokkos::View<Type, Layout, Space, MemTraits> a(a_org);
for (int i0 = 0; i0 < N0; i0++)
for (int i1 = 0; i1 < N1; i1++)
for (int i2 = 0; i2 < N2; i2++)
for (int i3 = 0; i3 < N3; i3++)
for (int i4 = 0; i4 < N4; i4++) {
a_org(i0, i1, i2, i3, i4) =
i0 * 1000000 + i1 * 10000 + i2 * 100 + i3 * 10 + i4;
}
Kokkos::View<TypeSub, LayoutSub, Space, MemTraits> a1;
a1 = Kokkos::subview(a, 3, 5, Kokkos::ALL, Kokkos::ALL, Kokkos::ALL);
Kokkos::fence();
test_Check3D5D(a1, a, 3, 5, std::pair<int, int>(0, N2),
std::pair<int, int>(0, N3), std::pair<int, int>(0, N4));
Kokkos::View<TypeSub, LayoutSub, Space, MemTraits> a2(
a, 3, 5, Kokkos::ALL, Kokkos::ALL, Kokkos::ALL);
Kokkos::fence();
test_Check3D5D(a2, a, 3, 5, std::pair<int, int>(0, N2),
std::pair<int, int>(0, N3), std::pair<int, int>(0, N4));
}
template <class Space, class LayoutSub, class Layout, class LayoutOrg,
class MemTraits>
void test_3d_subview_5d_impl_layout() {
test_3d_subview_5d_impl_type<Space, int[N0][N1][N2][N3][N4], int[N2][N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int[N0][N1][N2][N3][N4], int * [N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int[N0][N1][N2][N3][N4], int* * [N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int[N0][N1][N2][N3][N4], int***,
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int * [N1][N2][N3][N4], int[N2][N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int * [N1][N2][N3][N4], int * [N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int * [N1][N2][N3][N4], int* * [N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int * [N1][N2][N3][N4], int***, LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int* * [N2][N3][N4], int[N2][N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int* * [N2][N3][N4], int * [N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int* * [N2][N3][N4], int* * [N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int* * [N2][N3][N4], int***, LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int** * [N3][N4], int[N2][N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int** * [N3][N4], int * [N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int** * [N3][N4], int* * [N4], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int** * [N3][N4], int***, LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int*** * [N4], int[N2][N3][N4], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int*** * [N4], int * [N3][N4], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int*** * [N4], int* * [N4], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int*** * [N4], int***, LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int*****, int[N2][N3][N4], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int*****, int * [N3][N4], LayoutSub,
Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int*****, int* * [N4], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, int*****, int***, LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int[N0][N1][N2][N3][N4],
const int[N2][N3][N4], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int[N0][N1][N2][N3][N4],
const int * [N3][N4], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int[N0][N1][N2][N3][N4],
const int* * [N4], LayoutSub, Layout, LayoutOrg,
MemTraits>();
test_3d_subview_5d_impl_type<Space, const int[N0][N1][N2][N3][N4],
const int***, LayoutSub, Layout, LayoutOrg,
MemTraits>();
test_3d_subview_5d_impl_type<Space, const int * [N1][N2][N3][N4],
const int[N2][N3][N4], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int * [N1][N2][N3][N4],
const int * [N3][N4], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int * [N1][N2][N3][N4],
const int* * [N4], LayoutSub, Layout, LayoutOrg,
MemTraits>();
test_3d_subview_5d_impl_type<Space, const int * [N1][N2][N3][N4],
const int***, LayoutSub, Layout, LayoutOrg,
MemTraits>();
test_3d_subview_5d_impl_type<Space, const int* * [N2][N3][N4],
const int[N2][N3][N4], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int* * [N2][N3][N4],
const int * [N3][N4], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int* * [N2][N3][N4],
const int* * [N4], LayoutSub, Layout, LayoutOrg,
MemTraits>();
test_3d_subview_5d_impl_type<Space, const int* * [N2][N3][N4], const int***,
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int** * [N3][N4],
const int[N2][N3][N4], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int** * [N3][N4],
const int * [N3][N4], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int** * [N3][N4], const int* * [N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int** * [N3][N4], const int***,
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int*** * [N4],
const int[N2][N3][N4], LayoutSub, Layout,
LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int*** * [N4], const int * [N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int*** * [N4], const int* * [N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int*** * [N4], const int***,
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int*****, const int[N2][N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int*****, const int * [N3][N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int*****, const int* * [N4],
LayoutSub, Layout, LayoutOrg, MemTraits>();
test_3d_subview_5d_impl_type<Space, const int*****, const int***, LayoutSub,
Layout, LayoutOrg, MemTraits>();
}
inline void test_subview_legal_args_right() {
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::pair<int, int>, int, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t, int, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::pair<int, int>, int, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t, int, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, int, Kokkos::pair<int, int>,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::pair<int, int>, int,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>, int,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>, int,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(1, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(1, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(1, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(1, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::pair<int, int> >::value));
}
inline void test_subview_legal_args_left() {
ASSERT_EQ(
1,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, int>::value));
ASSERT_EQ(
1,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, int>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, int>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, int>::value));
ASSERT_EQ(1, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int, int>::value));
ASSERT_EQ(1, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::pair<int, int>, int, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t, int, int>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, int, Kokkos::pair<int, int>,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::pair<int, int>, int,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::pair<int, int>, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t, int>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>, int,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>, int,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(
1,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value));
ASSERT_EQ(
1,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(1, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int> >::value));
ASSERT_EQ(1, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(
0,
(Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t,
Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::Impl::ALL_t>::value));
ASSERT_EQ(0, (Kokkos::Impl::SubviewLegalArgsCompileTime<
Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0,
Kokkos::pair<int, int>, Kokkos::pair<int, int>,
Kokkos::pair<int, int> >::value));
}
} // namespace Impl
template <class Space, class MemTraits = void>
void test_1d_assign() {
Impl::test_1d_assign_impl<Space, Kokkos::LayoutLeft, Kokkos::LayoutLeft,
Kokkos::LayoutLeft, MemTraits>();
// Impl::test_1d_assign_impl< Space, Kokkos::LayoutRight, Kokkos::LayoutLeft,
// Kokkos::LayoutLeft >();
Impl::test_1d_assign_impl<Space, Kokkos::LayoutStride, Kokkos::LayoutLeft,
Kokkos::LayoutLeft, MemTraits>();
// Impl::test_1d_assign_impl< Space, Kokkos::LayoutLeft, Kokkos::LayoutRight,
// Kokkos::LayoutLeft >();
Impl::test_1d_assign_impl<Space, Kokkos::LayoutRight, Kokkos::LayoutRight,
Kokkos::LayoutRight, MemTraits>();
Impl::test_1d_assign_impl<Space, Kokkos::LayoutStride, Kokkos::LayoutRight,
Kokkos::LayoutRight, MemTraits>();
// Impl::test_1d_assign_impl< Space, Kokkos::LayoutLeft, Kokkos::LayoutStride,
// Kokkos::LayoutLeft >(); Impl::test_1d_assign_impl< Space,
// Kokkos::LayoutRight, Kokkos::LayoutStride, Kokkos::LayoutLeft >();
Impl::test_1d_assign_impl<Space, Kokkos::LayoutStride, Kokkos::LayoutStride,
Kokkos::LayoutLeft, MemTraits>();
}
template <class Space, class MemTraits = void>
void test_2d_subview_3d() {
Impl::test_2d_subview_3d_impl_layout<Space, Kokkos::LayoutRight,
Kokkos::LayoutRight, Kokkos::LayoutRight,
MemTraits>();
Impl::test_2d_subview_3d_impl_layout<Space, Kokkos::LayoutStride,
Kokkos::LayoutRight, Kokkos::LayoutRight,
MemTraits>();
Impl::test_2d_subview_3d_impl_layout<Space, Kokkos::LayoutStride,
Kokkos::LayoutStride,
Kokkos::LayoutRight, MemTraits>();
Impl::test_2d_subview_3d_impl_layout<Space, Kokkos::LayoutStride,
Kokkos::LayoutLeft, Kokkos::LayoutLeft,
MemTraits>();
Impl::test_2d_subview_3d_impl_layout<Space, Kokkos::LayoutStride,
Kokkos::LayoutStride, Kokkos::LayoutLeft,
MemTraits>();
}
template <class Space, class MemTraits = void>
void test_3d_subview_5d_right() {
Impl::test_3d_subview_5d_impl_layout<Space, Kokkos::LayoutStride,
Kokkos::LayoutRight, Kokkos::LayoutRight,
MemTraits>();
Impl::test_3d_subview_5d_impl_layout<Space, Kokkos::LayoutStride,
Kokkos::LayoutStride,
Kokkos::LayoutRight, MemTraits>();
}
template <class Space, class MemTraits = void>
void test_3d_subview_5d_left() {
Impl::test_3d_subview_5d_impl_layout<Space, Kokkos::LayoutStride,
Kokkos::LayoutLeft, Kokkos::LayoutLeft,
MemTraits>();
Impl::test_3d_subview_5d_impl_layout<Space, Kokkos::LayoutStride,
Kokkos::LayoutStride, Kokkos::LayoutLeft,
MemTraits>();
}
namespace Impl {
template <class Layout, class Space>
struct FillView_3D {
Kokkos::View<int***, Layout, Space> a;
KOKKOS_INLINE_FUNCTION
void operator()(const int& ii) const {
const int i = std::is_same<Layout, Kokkos::LayoutLeft>::value
? ii % a.extent(0)
: ii / (a.extent(1) * a.extent(2));
const int j = std::is_same<Layout, Kokkos::LayoutLeft>::value
? (ii / a.extent(0)) % a.extent(1)
: (ii / a.extent(2)) % a.extent(1);
const int k = std::is_same<Layout, Kokkos::LayoutRight>::value
? ii / (a.extent(0) * a.extent(1))
: ii % a.extent(2);
a(i, j, k) = 1000000 * i + 1000 * j + k;
}
};
template <class Layout, class Space>
struct FillView_4D {
Kokkos::View<int****, Layout, Space> a;
KOKKOS_INLINE_FUNCTION
void operator()(const int& ii) const {
const int i = std::is_same<Layout, Kokkos::LayoutLeft>::value
? ii % a.extent(0)
: ii / (a.extent(1) * a.extent(2) * a.extent(3));
const int j = std::is_same<Layout, Kokkos::LayoutLeft>::value
? (ii / a.extent(0)) % a.extent(1)
: (ii / (a.extent(2) * a.extent(3)) % a.extent(1));
const int k = std::is_same<Layout, Kokkos::LayoutRight>::value
? (ii / (a.extent(0) * a.extent(1))) % a.extent(2)
: (ii / a.extent(3)) % a.extent(2);
const int l = std::is_same<Layout, Kokkos::LayoutRight>::value
? ii / (a.extent(0) * a.extent(1) * a.extent(2))
: ii % a.extent(3);
a(i, j, k, l) = 1000000 * i + 10000 * j + 100 * k + l;
}
};
template <class Layout, class Space, class MemTraits>
struct CheckSubviewCorrectness_3D_3D {
Kokkos::View<const int***, Layout, Space, MemTraits> a;
Kokkos::View<const int***, Layout, Space, MemTraits> b;
int offset_0, offset_2;
KOKKOS_INLINE_FUNCTION
void operator()(const int& ii) const {
const int i = std::is_same<Layout, Kokkos::LayoutLeft>::value
? ii % b.extent(0)
: ii / (b.extent(1) * b.extent(2));
const int j = std::is_same<Layout, Kokkos::LayoutLeft>::value
? (ii / b.extent(0)) % b.extent(1)
: (ii / b.extent(2)) % b.extent(1);
const int k = std::is_same<Layout, Kokkos::LayoutRight>::value
? ii / (b.extent(0) * b.extent(1))
: ii % b.extent(2);
if (a(i + offset_0, j, k + offset_2) != b(i, j, k)) {
Kokkos::abort(
"Error: check_subview_correctness 3D-3D (LayoutLeft -> LayoutLeft or "
"LayoutRight -> LayoutRight)");
}
}
};
template <class Layout, class Space, class MemTraits>
struct CheckSubviewCorrectness_3D_4D {
Kokkos::View<const int****, Layout, Space, MemTraits> a;
Kokkos::View<const int***, Layout, Space, MemTraits> b;
int offset_0, offset_2, index;
KOKKOS_INLINE_FUNCTION
void operator()(const int& ii) const {
const int i = std::is_same<Layout, Kokkos::LayoutLeft>::value
? ii % b.extent(0)
: ii / (b.extent(1) * b.extent(2));
const int j = std::is_same<Layout, Kokkos::LayoutLeft>::value
? (ii / b.extent(0)) % b.extent(1)
: (ii / b.extent(2)) % b.extent(1);
const int k = std::is_same<Layout, Kokkos::LayoutRight>::value
? ii / (b.extent(0) * b.extent(1))
: ii % b.extent(2);
int i0, i1, i2, i3;
if (std::is_same<Layout, Kokkos::LayoutLeft>::value) {
i0 = i + offset_0;
i1 = j;
i2 = k + offset_2;
i3 = index;
} else {
i0 = index;
i1 = i + offset_0;
i2 = j;
i3 = k + offset_2;
}
if (a(i0, i1, i2, i3) != b(i, j, k)) {
Kokkos::abort(
"Error: check_subview_correctness 3D-4D (LayoutLeft -> LayoutLeft or "
"LayoutRight -> LayoutRight)");
}
}
};
} // namespace Impl
template <class Space, class MemTraits = void>
void test_layoutleft_to_layoutleft() {
Impl::test_subview_legal_args_left();
{
Kokkos::View<int***, Kokkos::LayoutLeft, Space> a("A", 100, 4, 3);
Kokkos::View<int***, Kokkos::LayoutLeft, Space> b(
a, Kokkos::pair<int, int>(16, 32), Kokkos::ALL, Kokkos::ALL);
Impl::FillView_3D<Kokkos::LayoutLeft, Space> fill;
fill.a = a;
Kokkos::parallel_for(Kokkos::RangePolicy<typename Space::execution_space>(
0, a.extent(0) * a.extent(1) * a.extent(2)),
fill);
Impl::CheckSubviewCorrectness_3D_3D<Kokkos::LayoutLeft, Space, MemTraits>
check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 0;
Kokkos::parallel_for(Kokkos::RangePolicy<typename Space::execution_space>(
0, b.extent(0) * b.extent(1) * b.extent(2)),
check);
Kokkos::fence();
}
{
Kokkos::View<int***, Kokkos::LayoutLeft, Space> a("A", 100, 4, 5);
Kokkos::View<int***, Kokkos::LayoutLeft, Space> b(
a, Kokkos::pair<int, int>(16, 32), Kokkos::ALL,
Kokkos::pair<int, int>(1, 3));
Impl::FillView_3D<Kokkos::LayoutLeft, Space> fill;
fill.a = a;
Kokkos::parallel_for(Kokkos::RangePolicy<typename Space::execution_space>(
0, a.extent(0) * a.extent(1) * a.extent(2)),
fill);
Impl::CheckSubviewCorrectness_3D_3D<Kokkos::LayoutLeft, Space, MemTraits>
check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 1;
Kokkos::parallel_for(Kokkos::RangePolicy<typename Space::execution_space>(
0, b.extent(0) * b.extent(1) * b.extent(2)),
check);
Kokkos::fence();
}
{
Kokkos::View<int****, Kokkos::LayoutLeft, Space> a("A", 100, 4, 5, 3);
Kokkos::View<int***, Kokkos::LayoutLeft, Space> b(
a, Kokkos::pair<int, int>(16, 32), Kokkos::ALL,
Kokkos::pair<int, int>(1, 3), 1);
Impl::FillView_4D<Kokkos::LayoutLeft, Space> fill;
fill.a = a;
Kokkos::parallel_for(
Kokkos::RangePolicy<typename Space::execution_space>(
0, a.extent(0) * a.extent(1) * a.extent(2) * a.extent(3)),
fill);
Impl::CheckSubviewCorrectness_3D_4D<Kokkos::LayoutLeft, Space, MemTraits>
check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 1;
check.index = 1;
Kokkos::parallel_for(Kokkos::RangePolicy<typename Space::execution_space>(
0, b.extent(0) * b.extent(1) * b.extent(2)),
check);
Kokkos::fence();
}
}
template <class Space, class MemTraits = void>
void test_layoutright_to_layoutright() {
Impl::test_subview_legal_args_right();
{
Kokkos::View<int***, Kokkos::LayoutRight, Space> a("A", 100, 4, 3);
Kokkos::View<int***, Kokkos::LayoutRight, Space> b(
a, Kokkos::pair<int, int>(16, 32), Kokkos::ALL, Kokkos::ALL);
Impl::FillView_3D<Kokkos::LayoutRight, Space> fill;
fill.a = a;
Kokkos::parallel_for(Kokkos::RangePolicy<typename Space::execution_space>(
0, a.extent(0) * a.extent(1) * a.extent(2)),
fill);
Impl::CheckSubviewCorrectness_3D_3D<Kokkos::LayoutRight, Space, MemTraits>
check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 0;
Kokkos::parallel_for(Kokkos::RangePolicy<typename Space::execution_space>(
0, b.extent(0) * b.extent(1) * b.extent(2)),
check);
Kokkos::fence();
}
{
Kokkos::View<int****, Kokkos::LayoutRight, Space> a("A", 3, 4, 5, 100);
Kokkos::View<int***, Kokkos::LayoutRight, Space> b(
a, 1, Kokkos::pair<int, int>(1, 3), Kokkos::ALL, Kokkos::ALL);
Impl::FillView_4D<Kokkos::LayoutRight, Space> fill;
fill.a = a;
Kokkos::parallel_for(
Kokkos::RangePolicy<typename Space::execution_space>(
0, a.extent(0) * a.extent(1) * a.extent(2) * a.extent(3)),
fill);
Impl::CheckSubviewCorrectness_3D_4D<Kokkos::LayoutRight, Space, MemTraits>
check;
check.a = a;
check.b = b;
check.offset_0 = 1;
check.offset_2 = 0;
check.index = 1;
Kokkos::parallel_for(Kokkos::RangePolicy<typename Space::execution_space>(
0, b.extent(0) * b.extent(1) * b.extent(2)),
check);
Kokkos::fence();
}
}
//----------------------------------------------------------------------------
template <class Space>
struct TestUnmanagedSubviewReset {
Kokkos::View<int****, Space> a;
KOKKOS_INLINE_FUNCTION
void operator()(int) const noexcept {
auto sub_a = Kokkos::subview(a, 0, Kokkos::ALL, Kokkos::ALL, Kokkos::ALL);
for (int i = 0; i < int(a.extent(0)); ++i) {
sub_a.assign_data(&a(i, 0, 0, 0));
if (&sub_a(1, 1, 1) != &a(i, 1, 1, 1)) {
Kokkos::abort("TestUnmanagedSubviewReset");
}
}
}
TestUnmanagedSubviewReset() : a(Kokkos::view_alloc(), 20, 10, 5, 2) {}
};
template <class Space>
void test_unmanaged_subview_reset() {
Kokkos::parallel_for(
Kokkos::RangePolicy<typename Space::execution_space>(0, 1),
TestUnmanagedSubviewReset<Space>());
}
//----------------------------------------------------------------------------
template <class T>
struct get_view_type;
template <class T, class... Args>
struct get_view_type<Kokkos::View<T, Args...> > {
using type = T;
};
template <class T>
struct
___________________________________TYPE_DISPLAY________________________________________;
#define TYPE_DISPLAY(...) \
typename ___________________________________TYPE_DISPLAY________________________________________< \
__VA_ARGS__>::type notdefined;
template <class Space, class Layout>
struct TestSubviewStaticSizes {
Kokkos::View<int * [10][5][2], Layout, Space> a;
KOKKOS_INLINE_FUNCTION
int operator()() const noexcept {
/* Doesn't actually do anything; just static assertions */
auto sub_a = Kokkos::subview(a, 0, Kokkos::ALL, Kokkos::ALL, Kokkos::ALL);
typename static_expect_same<
/* expected */ int[10][5][2],
/* actual */ typename get_view_type<decltype(sub_a)>::type>::type
test_1 = 0;
auto sub_a_2 = Kokkos::subview(a, 0, 0, Kokkos::ALL, Kokkos::ALL);
typename static_expect_same<
/* expected */ int[5][2],
/* actual */ typename get_view_type<decltype(sub_a_2)>::type>::type
test_2 = 0;
auto sub_a_3 = Kokkos::subview(a, 0, 0, Kokkos::ALL, 0);
typename static_expect_same<
/* expected */ int[5],
/* actual */ typename get_view_type<decltype(sub_a_3)>::type>::type
test_3 = 0;
auto sub_a_4 = Kokkos::subview(a, Kokkos::ALL, 0, Kokkos::ALL, Kokkos::ALL);
typename static_expect_same<
/* expected */ int * [5][2],
/* actual */ typename get_view_type<decltype(sub_a_4)>::type>::type
test_4 = 0;
// TODO we'll need to update this test once we allow interleaving of static
// and dynamic
auto sub_a_5 = Kokkos::subview(a, Kokkos::ALL, 0, Kokkos::ALL,
Kokkos::make_pair(0, 1));
typename static_expect_same<
/* expected */ int***,
/* actual */ typename get_view_type<decltype(sub_a_5)>::type>::type
test_5 = 0;
auto sub_a_sub = Kokkos::subview(sub_a_5, 0, Kokkos::ALL, 0);
typename static_expect_same<
/* expected */ int*,
/* actual */ typename get_view_type<decltype(sub_a_sub)>::type>::type
test_sub = 0;
auto sub_a_7 = Kokkos::subview(a, Kokkos::ALL, 0, Kokkos::make_pair(0, 1),
Kokkos::ALL);
typename static_expect_same<
/* expected */ int* * [2],
/* actual */ typename get_view_type<decltype(sub_a_7)>::type>::type
test_7 = 0;
return test_1 + test_2 + test_3 + test_4 + test_5 + test_sub + test_7;
}
TestSubviewStaticSizes() : a(Kokkos::view_alloc(), 20) {}
};
template <class Space>
struct TestExtentsStaticTests {
using test1 = typename static_expect_same<
/* expected */
Kokkos::Experimental::Extents<Kokkos::Experimental::dynamic_extent,
Kokkos::Experimental::dynamic_extent, 1, 2,
3>,
/* actual */
typename Kokkos::Impl::ParseViewExtents<double* * [1][2][3]>::type>::type;
using test2 = typename static_expect_same<
/* expected */
Kokkos::Experimental::Extents<1, 2, 3>,
/* actual */
typename Kokkos::Impl::ParseViewExtents<double[1][2][3]>::type>::type;
using test3 = typename static_expect_same<
/* expected */
Kokkos::Experimental::Extents<3>,
/* actual */
typename Kokkos::Impl::ParseViewExtents<double[3]>::type>::type;
using test4 = typename static_expect_same<
/* expected */
Kokkos::Experimental::Extents<>,
/* actual */
typename Kokkos::Impl::ParseViewExtents<double>::type>::type;
};
} // namespace TestViewSubview
#endif
| 44.081174 | 101 | 0.55795 | [
"3d"
] |
074e5d1ab34453db5fa99b059acaf2d535b7b31f | 5,085 | hpp | C++ | include/GlobalNamespace/INetworkConfig.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/INetworkConfig.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/INetworkConfig.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: MasterServerEndPoint
class MasterServerEndPoint;
}
// Completed forward declares
// Begin il2cpp-utils forward declares
struct Il2CppString;
// Completed il2cpp-utils forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: INetworkConfig
// [TokenAttribute] Offset: FFFFFFFF
class INetworkConfig {
public:
// Creating value type constructor for type: INetworkConfig
INetworkConfig() noexcept {}
// public System.Int32 get_maxPartySize()
// Offset: 0xFFFFFFFF
int get_maxPartySize();
// public System.Int32 get_discoveryPort()
// Offset: 0xFFFFFFFF
int get_discoveryPort();
// public System.Int32 get_partyPort()
// Offset: 0xFFFFFFFF
int get_partyPort();
// public System.Int32 get_multiplayerPort()
// Offset: 0xFFFFFFFF
int get_multiplayerPort();
// public MasterServerEndPoint get_masterServerEndPoint()
// Offset: 0xFFFFFFFF
GlobalNamespace::MasterServerEndPoint* get_masterServerEndPoint();
// public System.String get_masterServerStatusUrl()
// Offset: 0xFFFFFFFF
::Il2CppString* get_masterServerStatusUrl();
}; // INetworkConfig
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::INetworkConfig*, "", "INetworkConfig");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::INetworkConfig::get_maxPartySize
// Il2CppName: get_maxPartySize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::INetworkConfig::*)()>(&GlobalNamespace::INetworkConfig::get_maxPartySize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::INetworkConfig*), "get_maxPartySize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::INetworkConfig::get_discoveryPort
// Il2CppName: get_discoveryPort
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::INetworkConfig::*)()>(&GlobalNamespace::INetworkConfig::get_discoveryPort)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::INetworkConfig*), "get_discoveryPort", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::INetworkConfig::get_partyPort
// Il2CppName: get_partyPort
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::INetworkConfig::*)()>(&GlobalNamespace::INetworkConfig::get_partyPort)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::INetworkConfig*), "get_partyPort", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::INetworkConfig::get_multiplayerPort
// Il2CppName: get_multiplayerPort
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::INetworkConfig::*)()>(&GlobalNamespace::INetworkConfig::get_multiplayerPort)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::INetworkConfig*), "get_multiplayerPort", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::INetworkConfig::get_masterServerEndPoint
// Il2CppName: get_masterServerEndPoint
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::MasterServerEndPoint* (GlobalNamespace::INetworkConfig::*)()>(&GlobalNamespace::INetworkConfig::get_masterServerEndPoint)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::INetworkConfig*), "get_masterServerEndPoint", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::INetworkConfig::get_masterServerStatusUrl
// Il2CppName: get_masterServerStatusUrl
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::INetworkConfig::*)()>(&GlobalNamespace::INetworkConfig::get_masterServerStatusUrl)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::INetworkConfig*), "get_masterServerStatusUrl", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 50.85 | 211 | 0.743559 | [
"vector"
] |
074ebb3bbb5fc9aec2c07f18407e1a4277cc8f05 | 8,747 | cpp | C++ | src/VirtualMachine.cpp | xilwen/servant-base-lib | 432c67cb90774b67b350cf1f9e642665ef8c4f4d | [
"MIT"
] | null | null | null | src/VirtualMachine.cpp | xilwen/servant-base-lib | 432c67cb90774b67b350cf1f9e642665ef8c4f4d | [
"MIT"
] | null | null | null | src/VirtualMachine.cpp | xilwen/servant-base-lib | 432c67cb90774b67b350cf1f9e642665ef8c4f4d | [
"MIT"
] | null | null | null | #include "VirtualMachine.hpp"
#include "VBoxWrapperClient.hpp"
#include "PackageManager.hpp"
#include "ProfileManager.hpp"
#include <json.hpp>
using json = nlohmann::json;
VirtualMachine::VirtualMachine()
{
}
VirtualMachine::~VirtualMachine()
{
}
void VirtualMachine::setUuid(std::wstring uuid)
{
this->uuid = uuid;
}
void VirtualMachine::setName(std::wstring name)
{
this->name = name;
}
std::wstring VirtualMachine::getUuid()
{
return uuid;
}
std::wstring VirtualMachine::getName()
{
return name;
}
std::wstring VirtualMachine::launch()
{
return VBoxWrapperClient::getInstance()->message()->machineMessage(uuid, L"control start");
}
std::wstring VirtualMachine::sendPowerOffSignal()
{
return VBoxWrapperClient::getInstance()->message()->machineMessage(uuid, L"control stop");
}
void VirtualMachine::rename(std::wstring newName)
{
VBoxWrapperClient::getInstance()->message()->machineMessage(uuid, L"set machineName " + newName);
}
VirtualMachineState VirtualMachine::getStatus()
{
auto result = VBoxWrapperClient::getInstance()->message()->machineMessage(uuid, L"get machineState");
if (result == L"PoweredOff")
{
return VirtualMachineState::PoweredOff;
}
if (result == L"Running")
{
return VirtualMachineState::Running;
}
if (result == L"Aborted")
{
return VirtualMachineState::Aborted;
}
if (result == L"Starting")
{
return VirtualMachineState::Starting;
}
if (result == L"Stopping")
{
return VirtualMachineState::Stopping;
} else
{
return VirtualMachineState::Unknown;
}
}
VirtualMachine *VirtualMachine::getVirtualMachine(const std::wstring &nameOrUuid)
{
std::vector<VirtualMachine> *machines = PackageManager::getInstance()->getMachines();
for (VirtualMachine x : *machines)
{
if (x.getName() == nameOrUuid || x.getUuid() == nameOrUuid)
{
return x.getInstance();
}
}
return nullptr;
}
VirtualMachine *VirtualMachine::getInstance()
{
return this;
}
std::string &VirtualMachine::getIconPath()
{
return iconPath;
}
void VirtualMachine::setIconPath(const std::string &iconPath)
{
VirtualMachine::iconPath = iconPath;
}
std::string &VirtualMachine::getType()
{
return type;
}
void VirtualMachine::setType(const std::string &type)
{
VirtualMachine::type = type;
}
unsigned int VirtualMachine::getPortNumber() const
{
return portNumber;
}
void VirtualMachine::setPortNumber(unsigned int portNumber)
{
VirtualMachine::portNumber = portNumber;
}
unsigned int VirtualMachine::getCustomPortNumber() const
{
return customPortNumber;
}
void VirtualMachine::setCustomPortNumber(unsigned int customPortNumber)
{
VirtualMachine::customPortNumber = customPortNumber;
}
const std::string &VirtualMachine::getManagementURL() const
{
return managementURL;
}
void VirtualMachine::setManagementURL(const std::string &managementURL)
{
VirtualMachine::managementURL = managementURL;
}
const std::string &VirtualMachine::getShareURL() const
{
return shareURL;
}
void VirtualMachine::setShareURL(const std::string &shareURL)
{
VirtualMachine::shareURL = shareURL;
}
const std::string &VirtualMachine::getShareAdditionURL() const
{
return shareAdditionURL;
}
void VirtualMachine::setShareAdditionURL(const std::string &shareAdditionURL)
{
VirtualMachine::shareAdditionURL = shareAdditionURL;
}
unsigned int VirtualMachine::getManagementPort() const
{
return managementPort;
}
void VirtualMachine::setManagementPort(unsigned int managementPort)
{
VirtualMachine::managementPort = managementPort;
}
const std::string &VirtualMachine::getProtocol() const
{
return protocol;
}
void VirtualMachine::setProtocol(const std::string &protocol)
{
VirtualMachine::protocol = protocol;
}
const std::string &VirtualMachine::getTipURL() const
{
return tipURL;
}
void VirtualMachine::setTipURL(const std::string &tipURL)
{
VirtualMachine::tipURL = tipURL;
}
bool VirtualMachine::isUseLocalIP() const
{
return useLocalIP;
}
void VirtualMachine::setUseLocalIP(bool useLocalIP)
{
VirtualMachine::useLocalIP = useLocalIP;
}
void VirtualMachine::setCPUAmount(int cpuAmount)
{
VBoxWrapperClient::getInstance()->message()->machineMessage(uuid, L"set cpuCount " + std::to_wstring(cpuAmount));
}
void VirtualMachine::setRAMAmount(int ramAmount)
{
VBoxWrapperClient::getInstance()->message()->machineMessage(uuid, L"set ramSize " + std::to_wstring(ramAmount));
}
void VirtualMachine::addPortForwardingRule(unsigned int guestPort, unsigned int hostPort)
{
VBoxWrapperClient::getInstance()->message()->machineMessage(uuid,
L"set addPortForwarding " + std::to_wstring(guestPort) +
L" " + std::to_wstring(hostPort));
}
void VirtualMachine::removePortForwardingRule(unsigned int guestPort)
{
VBoxWrapperClient::getInstance()->message()->machineMessage(uuid, L"set removePortForwarding " +
std::to_wstring(guestPort));
}
void VirtualMachine::saveUseLocalIP(bool useLocalIP)
{
json machineJson(ProfileManager::getInstance()->getMachinesJson());
for (auto it = machineJson.begin(); it != machineJson.end(); ++it)
{
if(it->find("machineUuid").value() == this->getUuidString())
{
if(it->find("useLocalIP") != it->end())
{
it->at("useLocalIP") = useLocalIP;
} else
{
it->emplace("useLocalIP", useLocalIP);
}
}
}
ProfileManager::getInstance()->writeMachinesJson(machineJson);
}
const std::string &VirtualMachine::getUuidString() const
{
return uuidString;
}
void VirtualMachine::setUuidString(const std::string &uuidString)
{
VirtualMachine::uuidString = uuidString;
}
void VirtualMachine::saveCustomPort(unsigned int customPort)
{
json machineJson(ProfileManager::getInstance()->getMachinesJson());
for (auto it = machineJson.begin(); it != machineJson.end(); ++it)
{
if(it->find("machineUuid").value() == this->getUuidString())
{
if(it->find("customPort") != it->end())
{
it->at("customPort") = customPort;
} else
{
it->emplace("customPort", customPort);
}
}
}
ProfileManager::getInstance()->writeMachinesJson(machineJson);
}
void VirtualMachine::enableWebmin()
{
addPortForwardingRule(10000, 10000);
json machineJson(ProfileManager::getInstance()->getMachinesJson());
for (auto it = machineJson.begin(); it != machineJson.end(); ++it)
{
if(it->find("machineUuid").value() == this->getUuidString())
{
if(it->find("webminLock") != it->end())
{
it->at("webminLock") = true;
} else
{
it->emplace("webminLock", true);
}
}
}
ProfileManager::getInstance()->writeMachinesJson(machineJson);
}
void VirtualMachine::disableWebmin()
{
removePortForwardingRule(10000);
json machineJson(ProfileManager::getInstance()->getMachinesJson());
for (auto it = machineJson.begin(); it != machineJson.end(); ++it)
{
if(it->find("machineUuid").value() == this->getUuidString())
{
if(it->find("webminLock") != it->end())
{
it->at("webminLock") = false;
} else
{
it->emplace("webminLock", false);
}
}
}
ProfileManager::getInstance()->writeMachinesJson(machineJson);
}
bool VirtualMachine::webminEnabled()
{
json machineJson(ProfileManager::getInstance()->getMachinesJson());
for (auto it = machineJson.begin(); it != machineJson.end(); ++it)
{
if(it->find("machineUuid").value() == this->getUuidString())
{
if(it->find("webminLock") != it->end())
{
if(it->find("webminLock").value() == true)
{
return true;
}
}
}
}
return false;
}
void VirtualMachine::exportMachine(std::wstring path)
{
VBoxWrapperClient::getInstance()->message()->machineMessage(uuid,
L"control output " + path);
}
unsigned int VirtualMachine::getSingletonPort() const
{
return singletonPort;
}
void VirtualMachine::setSingletonPort(unsigned int singletonPort)
{
VirtualMachine::singletonPort = singletonPort;
}
| 24.501401 | 120 | 0.63839 | [
"vector"
] |
07585c2f485014207a06cff043a97f823780e6ee | 2,179 | cc | C++ | algac/common/algorithm_test.cc | algac/algac | 09323a8bb27c8ac6a69bf7a076df1e93bf997b56 | [
"MIT"
] | 1 | 2019-01-23T23:01:31.000Z | 2019-01-23T23:01:31.000Z | algac/common/algorithm_test.cc | algac/algac | 09323a8bb27c8ac6a69bf7a076df1e93bf997b56 | [
"MIT"
] | null | null | null | algac/common/algorithm_test.cc | algac/algac | 09323a8bb27c8ac6a69bf7a076df1e93bf997b56 | [
"MIT"
] | null | null | null | // Copyright (C) 2019-2021, YU
#include "algac/common/algorithm.h"
#include <atomic>
#include <deque>
#include <functional> // function
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "algac/common/common.h"
#include "algac/test_utils/test_utils.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
namespace algac {
TEST(Algorithm, BSearch) {
InitGoogleTestLogging();
vector<int> vec{1, 2, 3, 4, 5, 6};
int off = BSearch<int>(vec, 4, 0, vec.size());
EXPECT_EQ(3, off);
LOG(INFO) << "BSearch element does not exists: "
<< BSearch<int>(vec, 9, 0, vec.size());
}
TEST(Algorithm, Sort) {
InitGoogleTestLogging();
int step = 0;
std::function<void(const vector<int>&)> PrintVector =
[&step](const vector<int>& v) {
string line;
for (const auto& e : v) {
// LOG(INFO) << "elem = " << e;
line += std::to_string(e);
line += " ";
}
LOG(INFO) << "Vector[" << (step++) << "] ( size = " << v.size()
<< " ): " << line;
};
vector<int> vec{32, 71, 12, 45, 26, 80, 53, 33}; // 32 71 12 45 26 80 53 33
EXPECT_EQ(32, vec[0]);
EXPECT_EQ(71, vec[1]);
EXPECT_EQ(12, vec[2]);
EXPECT_EQ(45, vec[3]);
EXPECT_EQ(26, vec[4]);
EXPECT_EQ(80, vec[5]);
EXPECT_EQ(53, vec[6]);
EXPECT_EQ(33, vec[7]);
PrintVector(vec);
// using default comparison (operator <):
sort(vec.begin(), vec.begin() + 4); // (12 32 45 71)26 80 53 33
EXPECT_EQ(12, vec[0]);
EXPECT_EQ(32, vec[1]);
EXPECT_EQ(45, vec[2]);
EXPECT_EQ(71, vec[3]);
EXPECT_EQ(26, vec[4]);
EXPECT_EQ(80, vec[5]);
EXPECT_EQ(53, vec[6]);
EXPECT_EQ(33, vec[7]);
PrintVector(vec);
// using function as comp
sort(vec.begin() + 5, vec.end(), [](int l, int r) -> bool {
return (l / 10 - l % 10) < (r / 10 - r % 10);
}); // 12 32 45 71 26 { 33 53 80 }
EXPECT_EQ(12, vec[0]);
EXPECT_EQ(32, vec[1]);
EXPECT_EQ(45, vec[2]);
EXPECT_EQ(71, vec[3]);
EXPECT_EQ(26, vec[4]);
EXPECT_EQ(33, vec[5]);
EXPECT_EQ(53, vec[6]);
EXPECT_EQ(80, vec[7]);
PrintVector(vec);
}
} // namespace algac
| 24.211111 | 78 | 0.576411 | [
"vector"
] |
075cc42e2fd72754a148d05033bad77c18c3b016 | 3,092 | cpp | C++ | Codeforces/Gym102823H.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 18 | 2019-01-01T13:16:59.000Z | 2022-02-28T04:51:50.000Z | Codeforces/Gym102823H.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | null | null | null | Codeforces/Gym102823H.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 5 | 2019-09-13T08:48:17.000Z | 2022-02-19T06:59:03.000Z | #include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define SZ(x) ((int)x.size())
#define lowbit(x) x&-x
#define pb push_back
#define ALL(x) (x).begin(),(x).end()
#define UNI(x) sort(ALL(x)),x.resize(unique(ALL(x))-x.begin())
#define GETPOS(c,x) (lower_bound(ALL(c),x)-c.begin())
#define LEN(x) strlen(x)
#define MS0(x) memset((x),0,sizeof((x)))
#define Rint register int
#define ls (u<<1)
#define rs (u<<1|1)
typedef unsigned int unit;
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> Vi;
typedef vector<ll> Vll;
typedef vector<pii> Vpii;
template<class T> void _R(T &x) { cin >> x; }
void _R(int &x) { scanf("%d", &x); }
void _R(ll &x) { scanf("%lld", &x); }
void _R(ull &x) { scanf("%llu", &x); }
void _R(double &x) { scanf("%lf", &x); }
void _R(char &x) { scanf(" %c", &x); }
void _R(char *x) { scanf("%s", x); }
void R() {}
template<class T, class... U> void R(T &head, U &... tail) { _R(head); R(tail...); }
template<class T> void _W(const T &x) { cout << x; }
void _W(const int &x) { printf("%d", x); }
void _W(const ll &x) { printf("%lld", x); }
void _W(const double &x) { printf("%.16f", x); }
void _W(const char &x) { putchar(x); }
void _W(const char *x) { printf("%s", x); }
template<class T,class U> void _W(const pair<T,U> &x) {_W(x.fi);putchar(' '); _W(x.se);}
template<class T> void _W(const vector<T> &x) { for (auto i = x.begin(); i != x.end(); _W(*i++)) if (i != x.cbegin()) putchar(' '); }
void W() {}
template<class T, class... U> void W(const T &head, const U &... tail) { _W(head); putchar(sizeof...(tail) ? ' ' : '\n'); W(tail...); }
const int MOD=1e9+7,mod=998244353;
ll qpow(ll a,ll b) {ll res=1;a%=MOD; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
const int MAXN=5e5+10,MAXM=2e6+10;
const int INF=INT_MAX,SINF=0x3f3f3f3f;
const ll llINF=LLONG_MAX;
const int inv2=(MOD+1)/2;
const int Lim=1<<20;
char s[MAXN],t[MAXN];
char ans[MAXN];
void solve()
{
R(s,t);
int n=LEN(s),cnt=n;
memset(ans,0,(n+5)*sizeof(char));
for(int i=0;i<n;i++)
if(s[i]==t[i])
{
cnt--;
ans[i]='a';
}
ans[n]=0;
int cnt1=0,cnt2=0;
Vi vec;
for(int i=0;i<n;i++)if(s[i]!=t[i])
vec.pb(i);
for(auto i:vec)
{
for(int j=0;j<3;j++)
{
if(s[i]!=j+'a'&&t[i]!=j+'a')
{
ans[i]=j+'a';
break;
}
}
}
Vi vec2;
for(auto i:vec)
{
if(cnt<=abs(cnt1-cnt2)+1)
{
vec2.pb(i);
continue;
}
cnt--;
if(ans[i]<s[i]&&ans[i]<t[i])continue;
if(ans[i]>s[i]&&t[i]>s[i])
{
ans[i]=s[i];
cnt1++;
}
if(ans[i]>t[i]&&s[i]>t[i])
{
ans[i]=t[i];
cnt2++;
}
}
int p=abs(cnt1-cnt2);
//W(cnt,p,ans);
for(auto i:vec2)
{
if(p<=0)break;
if(p==cnt)
{
if(cnt2>cnt1)ans[i]=s[i],p--;
else ans[i]=t[i],p--;
}
else
{
if(cnt2>cnt1)
{
if(ans[i]>s[i])ans[i]=s[i],p--;
}
else
{
if(ans[i]>t[i])ans[i]=t[i],p--;
}
}
cnt--;
}
}
int main()
{
int T;
scanf("%d",&T);
for(int kase=1;kase<=T;kase++)
{
solve();
printf("Case %d: %s\n",kase,ans);
}
return 0;
} | 22.405797 | 135 | 0.555304 | [
"vector"
] |
075f383443baf159a6b609ed5ef0cb097a3094d6 | 1,121 | cpp | C++ | Implementation/Migratory Birds.cpp | AbdallahHemdan/HackerRank_ProblemSolving_Solutions | 4c1684d706c0185cc71154c26b84ab0216f633e0 | [
"MIT"
] | 3 | 2020-01-03T11:39:26.000Z | 2021-03-12T21:44:09.000Z | Implementation/Migratory Birds.cpp | AbdallahHemdan/HackerRank_ProblemSolving_Solutions | 4c1684d706c0185cc71154c26b84ab0216f633e0 | [
"MIT"
] | null | null | null | Implementation/Migratory Birds.cpp | AbdallahHemdan/HackerRank_ProblemSolving_Solutions | 4c1684d706c0185cc71154c26b84ab0216f633e0 | [
"MIT"
] | 1 | 2019-10-21T19:31:24.000Z | 2019-10-21T19:31:24.000Z | #include <iostream>
#include <cmath>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <iomanip>
#include <assert.h>
#include <vector>
#include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <set>
#include <complex>
#include <list>
#include <climits>
#include <cctype>
#include <bitset>
#include <numeric>
#include<array>
#include<tuple>
#include <utility>
#include <functional>
#include <locale>
using namespace std ;
int main (){
int size ;
cin >> size ;
int arr[size] ;
for (int i=0 ;i< size ; i++)
cin >> arr[i] ;
sort(arr,arr+size) ;
int counter = 1 ;
int arrofcount[size] = {0} ;
int arr2[size] = {0} ;
for (int i=0 ;i<size ;i++)
if (arr[i]==arr[i+1])
counter++ ;
else{
arrofcount[i]= counter ;
counter = 1 ;
}
int save=0 ;
int max = arrofcount[0] ;
for (int i=1 ;i< size ; i++)
if (arrofcount[i]>max)
{
max=arrofcount[i] ;
save = i ;
}
cout << arr[save] << endl ;
}
| 16.984848 | 34 | 0.597681 | [
"vector"
] |
0760830b67a258938a03c3308d25ed923b7e9487 | 775 | cpp | C++ | modules/labraytracer/rayintersection.cpp | victorca25/inviwo | 34b6675f6b791a08e358d24aea4f75d5baadc6da | [
"BSD-2-Clause"
] | 4 | 2018-01-21T20:38:47.000Z | 2021-01-10T03:16:16.000Z | modules/labraytracer/rayintersection.cpp | victorca25/inviwo | 34b6675f6b791a08e358d24aea4f75d5baadc6da | [
"BSD-2-Clause"
] | null | null | null | modules/labraytracer/rayintersection.cpp | victorca25/inviwo | 34b6675f6b791a08e358d24aea4f75d5baadc6da | [
"BSD-2-Clause"
] | 19 | 2018-09-09T19:43:30.000Z | 2022-02-01T07:59:30.000Z | /*********************************************************************
* Author : Himangshu Saikia
* Init : Tuesday, October 17, 2017 - 10:41:28
*
* Project : KTH Inviwo Modules
*
* License : Follows the Inviwo BSD license model
*********************************************************************
*/
#include <labraytracer/rayintersection.h>
namespace inviwo {
RayIntersection::RayIntersection() {
}
RayIntersection::RayIntersection(const Ray& ray, std::shared_ptr<const Renderable> renderable,
const double lambda, const vec3& normal, const vec3& uvw) {
mRay = ray;
mRenderable = renderable;
mLambda = lambda;
mNormal = normal;
mUVW = uvw;
mPosition = ray.pointOnRay(mLambda);
}
} // namespace
| 26.724138 | 94 | 0.534194 | [
"model"
] |
79e3c0762649c60b3ddc34bc03453480823783e3 | 6,867 | cpp | C++ | test/WidomMoveTests.cpp | hsidky/LNTMC | 6f1cc81476718ef19f85fd596d0815a194705a50 | [
"MIT"
] | 10 | 2016-08-16T23:32:33.000Z | 2021-07-06T09:39:58.000Z | test/WidomMoveTests.cpp | hsidky/LNT-MC | 6f1cc81476718ef19f85fd596d0815a194705a50 | [
"MIT"
] | 33 | 2015-04-09T16:19:51.000Z | 2016-02-06T04:34:01.000Z | test/WidomMoveTests.cpp | hsidky/LNT-MC | 6f1cc81476718ef19f85fd596d0815a194705a50 | [
"MIT"
] | 8 | 2015-02-16T18:34:46.000Z | 2021-01-11T19:37:14.000Z | #include "../src/ForceFields/LennardJonesFF.h"
#include "../src/ForceFields/ForceFieldManager.h"
#include "../src/Simulation/StandardSimulation.h"
#include "../src/Moves/MoveManager.h"
#include "../src/Moves/TranslateMove.h"
#include "../src/Moves/InsertParticleMove.h"
#include "../src/Moves/DeleteParticleMove.h"
#include "../src/Moves/WidomInsertionMove.h"
#include "../src/Particles/Particle.h"
#include "../src/Worlds/World.h"
#include "../src/Worlds/WorldManager.h"
#include "TestAccumulator.h"
#include "json/json.h"
#include "gtest/gtest.h"
#include "../src/Observers/DLMFileObserver.h"
#include <fstream>
using namespace SAPHRON;
// Grand canonical simulation tests.
TEST(WidomInsertionMove, Default)
{
Particle s({0, 0, 0},{0,0,0}, "LJ");
World world(1, 1, 1, 5.0, 1.0);
world.SetTemperature(1.0);
// Pack the world.
world.PackWorld({&s}, {1.0}, 200, 0.4);
ASSERT_EQ(200, world.GetParticleCount());
ForceFieldManager ffm;
LennardJonesFF lj(1.0, 1.0, {2.5});
ffm.AddNonBondedForceField("LJ", "LJ", lj);
auto H1 = ffm.EvaluateEnergy(world);
WorldManager wm;
wm.AddWorld(&world);
WidomInsertionMove move({"LJ"}, wm);
ASSERT_EQ(200, world.GetParticleCount());
// Let's perform the move and see the change in chemical potential
for(int i = 0; i < 10000; ++i)
{
move.Perform(&wm, &ffm, MoveOverride::ForceReject);
ASSERT_EQ(200, world.GetParticleCount());
}
EXPECT_NE(world.GetChemicalPotential("LJ"), 0.0);
world.SetChemicalPotential("LJ", 0.0);
ASSERT_NEAR(world.GetChemicalPotential("LJ"), 0.0, 1E-10);
//Try Force accept
for(int i = 0; i < 10000; ++i)
{
move.Perform(&wm, &ffm, MoveOverride::ForceAccept);
ASSERT_EQ(200, world.GetParticleCount());
}
EXPECT_NE(world.GetChemicalPotential("LJ"), 0.0);
}
TEST(WidomInsertionMove, Multi_Species)
{
Particle s({0, 0, 0},{0,0,0}, "LJ");
Particle s2({1, 1, 1},{0,0,0}, "LJ2");
World world(1, 1, 1, 5.0, 1.0);
world.SetTemperature(1.0);
// Pack the world.
world.PackWorld({&s, &s2}, {0.5, 0.5}, 200, 0.4);
ASSERT_EQ(200, world.GetParticleCount());
ASSERT_EQ(2,world.GetComposition().size());
ForceFieldManager ffm;
LennardJonesFF lj(1.0, 1.0, {2.5, 2.5});
ffm.AddNonBondedForceField("LJ", "LJ", lj);
ffm.AddNonBondedForceField("LJ", "LJ2", lj);
ffm.AddNonBondedForceField("LJ2", "LJ2", lj);
auto H1 = ffm.EvaluateEnergy(world);
WorldManager wm;
wm.AddWorld(&world);
std::vector<std::string> plist = {"LJ","LJ2"};
WidomInsertionMove move(plist, wm);
ASSERT_EQ(200, world.GetParticleCount());
// Let's perform the move and see the change in chemical potential
for(int i = 0; i < 10000; ++i)
{
move.Perform(&wm, &ffm, MoveOverride::ForceReject);
ASSERT_EQ(200, world.GetParticleCount());
}
EXPECT_NE(world.GetChemicalPotential("LJ"), 0.0);
ASSERT_NEAR(world.GetChemicalPotential("LJ"), world.GetChemicalPotential("LJ2"), 1E-10);
world.SetChemicalPotential("LJ", 0.0);
world.SetChemicalPotential("LJ2", 0.0);
ASSERT_NEAR(world.GetChemicalPotential("LJ"), 0.0, 1E-10);
ASSERT_NEAR(world.GetChemicalPotential("LJ2"), 0.0, 1E-10);
//Try Force accept
for(int i = 0; i < 10000; ++i)
{
move.Perform(&wm, &ffm, MoveOverride::ForceAccept);
ASSERT_EQ(200, world.GetParticleCount());
}
EXPECT_NE(world.GetChemicalPotential("LJ"), 0.0);
ASSERT_NEAR(world.GetChemicalPotential("LJ"), world.GetChemicalPotential("LJ2"), 1E-10);
}
// Test values from Frenkel, Dean, and Smit,
// Understanding Molecular Simulation :
// From Algorithms to Applications. Amsterdam, NLD: Academic Press, 2001.
// density mu
// 0.2996415770609319, -0.9010989010989015
// 0.4028673835125448, -0.9010989010989015
// 0.4989247311827957, -0.5347985347985365
// 0.6007168458781361, 0.3443223443223431
TEST(WidomInsertionMove, LJFluid)
{
auto sigma = 1.;
auto eps = 1.;
auto rcut = 3.0*sigma;
auto N = 500;
// Prototype particle.
Particle lj({0, 0, 0}, {0, 0, 0}, "LJ");
// Initialze worlds for widom, set densities.
// World world(1, 1, 1, rcut + 1.0, 1.0);
// World world2(1, 1, 1, rcut + 1.0, 1.0);
// World world3(1, 1, 1, rcut + 1.0, 1.0);
// World world4(1, 1, 1, rcut + 1.0, 1.0);
World world5(1, 1, 1, rcut + 1.0, 1.0);
// world.PackWorld({&lj}, {1.0}, N, 0.300);
// world2.PackWorld({&lj}, {1.0}, N, 0.403);
// world3.PackWorld({&lj}, {1.0}, N, 0.499);
// world4.PackWorld({&lj}, {1.0}, N, 0.601);
world5.PackWorld({&lj}, {1.0}, N, 0.640);
// world.SetTemperature(T);
// world2.SetTemperature(T);
// world3.SetTemperature(T);
// world4.SetTemperature(T);
world5.SetTemperature(1.5);
// Initialize world manager.
WorldManager wm;
// wm.AddWorld(&world);
// wm.AddWorld(&world2);
// wm.AddWorld(&world3);
// wm.AddWorld(&world4);
wm.AddWorld(&world5);
// ASSERT_EQ(N, world.GetParticleCount());
// ASSERT_EQ(N, world2.GetParticleCount());
// ASSERT_EQ(N, world3.GetParticleCount());
// ASSERT_EQ(N, world4.GetParticleCount());
ASSERT_EQ(N, world5.GetParticleCount());
// Initialize LJ forcefield.
LennardJonesFF ff(eps, sigma, {rcut, rcut, rcut});
ForceFieldManager ffm;
ffm.AddNonBondedForceField("LJ", "LJ", ff);
// Initialize moves.
MoveManager mm;
TranslateMove move1(0.22);
mm.AddMove(&move1, 75);
MoveManager mm2;
mm2.AddMove(&move1, 1);
WidomInsertionMove move2({"LJ"}, wm);
mm2.AddMove(&move2, 100);
MoveManager mm3;
mm3.AddMove(&move1, 75);
InsertParticleMove move3({"LJ"}, wm, 500, false);
mm3.AddMove(&move3, 12);
DeleteParticleMove move4({"LJ"},false);
mm3.AddMove(&move4, 12);
// Initialize observer.
SimFlags flags;
flags.world_on();
flags.simulation_on();
TestAccumulator observer(flags, 1, 2000);
TestAccumulator observer2(flags, 1, 2000);
// Initialize ensemble.
StandardSimulation ensemble(&wm, &ffm, &mm);
StandardSimulation ensemble2(&wm, &ffm, &mm2);
StandardSimulation ensemble3(&wm, &ffm, &mm3);
ensemble2.AddObserver(&observer);
ensemble3.AddObserver(&observer2);
// Run
ensemble.Run(20000);
ensemble2.Run(20000);
auto mus = observer.GetAverageChemicalPotential();
// EXPECT_NEAR(mus[&world], -0.901, 1e-2);
// EXPECT_NEAR(mus[&world2], -0.901, 1e-2);
// EXPECT_NEAR(mus[&world3], -0.535, 1e-2);
// EXPECT_NEAR(mus[&world4], 0.3443, 1e-2);
EXPECT_NEAR(mus[&world5], -2.0 - 1.5*log(0.640), 1e-2);
// world.SetChemicalPotential("LJ", -0.901+2*log(0.3));
// world2.SetChemicalPotential("LJ", -0.901+2*log(0.403));
// world3.SetChemicalPotential("LJ", -0.535+2*log(0.499));
// world4.SetChemicalPotential("LJ", 0.344+2*log(0.601));
world5.SetChemicalPotential("LJ", -2.0);
world5.SetVolume(512.0, true);
ensemble3.Run(20000);
auto rhos = observer2.GetAverageDensities();
// EXPECT_NEAR(rhos[&world], 0.300, 1e-2);
// EXPECT_NEAR(rhos[&world2], 0.403, 1e-2);
// EXPECT_NEAR(rhos[&world3], 0.499, 1e-2);
// EXPECT_NEAR(rhos[&world4], 0.601, 1e-2);
EXPECT_NEAR(rhos[&world5], 0.64, 1e-2);
} | 28.143443 | 89 | 0.678608 | [
"vector"
] |
79ee4d338ded91356f9a2748b4833dee43525be2 | 2,546 | cpp | C++ | leetcode/947.most-stones-removed-with-same-row-or-column.cpp | upupming/algorithm | 44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1 | [
"MIT"
] | 107 | 2019-10-25T07:46:59.000Z | 2022-03-29T11:10:56.000Z | leetcode/947.most-stones-removed-with-same-row-or-column.cpp | upupming/algorithm | 44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1 | [
"MIT"
] | 1 | 2021-08-13T05:42:27.000Z | 2021-08-13T05:42:27.000Z | leetcode/947.most-stones-removed-with-same-row-or-column.cpp | upupming/algorithm | 44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1 | [
"MIT"
] | 18 | 2020-12-09T14:24:22.000Z | 2022-03-30T06:56:01.000Z | /*
* @lc app=leetcode id=947 lang=cpp
*
* [947] Most Stones Removed with Same Row or Column
*/
#include <bits/stdc++.h>
using namespace std;
// @lc code=start
class Solution {
public:
int removeStones(vector<vector<int>>& stones) {
map<int, map<int, bool>> m, m1;
map<int, map<int, int>> parent;
int rows = 0, cols = 0;
for (auto stone : stones) {
m[stone[0]][stone[1]] = true;
m1[stone[1]][stone[0]] = true;
parent[stone[0]][stone[1]] = -1;
}
int ans = 0;
for (auto mi : m) {
int i = mi.first;
for (auto mj : mi.second) {
int j = mj.first;
int curRoot = find(parent, i, j);
int xi = i, xj = j;
// cout << "curRoot: " << curRoot % 10000 << ", " << curRoot / 10000 << endl;
// Same row
for (auto point : mi.second) {
int xj = point.first;
if (!m[xi][xj] || !(xj > j)) continue;
int xRoot = find(parent, xi, xj);
// cout << "xRoot: " << xRoot % 10000 << ", " << xRoot / 10000 << endl;
if (curRoot != xRoot) {
parent[xRoot % 10000][xRoot / 10000] = curRoot;
// cout << "union for " << i << ", " << j << "; " << xi << ", " << xj << endl;
ans++;
// assert(find(parent, i, j) == find(parent, xi, xj));
}
}
// Same column
for (auto point : m1[j]) {
int xi = point.first;
if (!m[xi][xj] || !(xi > i)) continue;
int xRoot = find(parent, xi, xj);
// cout << "xRoot: " << xRoot % 10000 << ", " << xRoot / 10000 << endl;
if (curRoot != xRoot) {
parent[xRoot % 10000][xRoot / 10000] = curRoot;
// cout << "union for " << i << ", " << j << "; " << xi << ", " << xj << endl;
ans++;
// assert(find(parent, i, j) == find(parent, xi, xj));
}
}
}
}
return ans;
}
int find(map<int, map<int, int>>& parent, int i, int j) {
if (parent[i][j] == -1)
return i + j * 10000;
else
return find(parent, parent[i][j] % 10000, parent[i][j] / 10000);
}
};
// @lc code=end
| 34.405405 | 102 | 0.382561 | [
"vector"
] |
79f03988c533ea52a2c78bf36f491f8805aa1093 | 918 | hh | C++ | elements/flow/flowrouter.hh | MassimoGirondi/fastclick | 71b9a3392c2e847a22de3c354be1d9f61216cb5b | [
"BSD-3-Clause-Clear"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | elements/flow/flowrouter.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | elements/flow/flowrouter.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | #ifndef CLICK_FLOWROUTER_HH
#define CLICK_FLOWROUTER_HH
#include <click/string.hh>
#include <click/timer.hh>
#include "ctxmanager.hh"
#include <vector>
#include <click/flow/flowelement.hh>
CLICK_DECLS
class FlowRouter: public FlowSpaceElement<int> {
public:
FlowRouter() CLICK_COLD;
~FlowRouter() CLICK_COLD {};
const char *class_name() const { return "FlowRouter"; }
const char *port_count() const { return "1/-"; }
const char *processing() const { return PUSH; }
int configure(Vector<String> &, ErrorHandler *) CLICK_COLD;
int initialize(ErrorHandler *errh) CLICK_COLD;
void push_batch(int, int* flowdata, PacketBatch* batch) override;
FlowNode* get_table(int,Vector<FlowElement*>) override;
private :
typedef struct {
FlowNode* root;
int output;
} Rule;
Vector<Rule> rules;
FlowNode* _table;
bool _verbose;
};
CLICK_ENDDECLS
#endif
| 20.4 | 69 | 0.696078 | [
"vector"
] |
79f7b97bb40f8ac719f0e97c1dd94983fc7c22cd | 2,961 | cpp | C++ | Sources/XML/Resources/xml_resource_node.cpp | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | Sources/XML/Resources/xml_resource_node.cpp | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | Sources/XML/Resources/xml_resource_node.cpp | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | /*
** ClanLib SDK
** Copyright (c) 1997-2016 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#include "XML/precomp.h"
#include "API/XML/Resources/xml_resource_node.h"
#include "API/XML/Resources/xml_resource_document.h"
#include "API/XML/dom_element.h"
#include "API/Core/IOData/path_help.h"
#include "xml_resource_document_impl.h"
#include <memory>
#include <vector>
namespace clan
{
class XMLResourceDocument_Impl;
class XMLResourceNode_Impl
{
public:
std::weak_ptr<XMLResourceDocument_Impl> resource_document;
DomElement element;
};
XMLResourceNode::XMLResourceNode()
{
}
XMLResourceNode::XMLResourceNode(DomElement element, XMLResourceDocument &resource_document)
: impl(std::make_shared<XMLResourceNode_Impl>())
{
impl->element = element;
impl->resource_document = std::weak_ptr<XMLResourceDocument_Impl>(resource_document.impl);
}
XMLResourceNode::~XMLResourceNode()
{
}
bool XMLResourceNode::is_null() const
{
return !impl;
}
std::string XMLResourceNode::get_type() const
{
return impl->element.get_local_name();
}
std::string XMLResourceNode::get_name() const
{
return impl->element.get_attribute("name");
}
DomElement &XMLResourceNode::get_element()
{
return impl->element;
}
XMLResourceDocument XMLResourceNode::get_document()
{
return XMLResourceDocument(impl->resource_document);
}
FileSystem XMLResourceNode::get_file_system() const
{
return impl->resource_document.lock()->fs;
}
std::string XMLResourceNode::get_base_path() const
{
return impl->resource_document.lock()->base_path;
}
IODevice XMLResourceNode::open_file(const std::string &filename, File::OpenMode mode, unsigned int access, unsigned int share, unsigned int flags) const
{
return get_file_system().open_file(PathHelp::combine(get_base_path(), filename), mode, access, share, flags);
}
bool XMLResourceNode::operator ==(const XMLResourceNode &other) const
{
return impl == other.impl;
}
}
| 27.165138 | 153 | 0.745019 | [
"vector"
] |
79fdf8186d5705327edd604529e85c02b549f593 | 27,358 | hpp | C++ | packages/monte_carlo/estimator/native/src/MonteCarlo_TetMeshTrackLengthFluxEstimator_def.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/estimator/native/src/MonteCarlo_TetMeshTrackLengthFluxEstimator_def.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/estimator/native/src/MonteCarlo_TetMeshTrackLengthFluxEstimator_def.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_TetMeshTrackLengthFluxEstimator.cpp
//! \author Alex Robinson, Eli Moll
//! \brief Tet mesh flux estimator class declaration.
//!
//---------------------------------------------------------------------------//
// Moab Includes
#include <moab/Core.hpp>
#include <moab/BoundBox.hpp>
// FRENSIE Includes
#include "MonteCarlo_TetMeshTrackLengthFluxEstimator.hpp"
#include "MonteCarlo_SimulationGeneralProperties.hpp"
#include "Utility_Tuple.hpp"
#include "Utility_TetrahedronHelpers.hpp"
#include "Utility_MOABException.hpp"
#include "Utility_ContractException.hpp"
#include "Utility_ExceptionTestMacros.hpp"
namespace MonteCarlo{
// Initialize static member data
template<typename ContributionMultiplierPolicy>
const double
TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::s_tol = 1e-6;
// Constructor
template<typename ContributionMultiplierPolicy>
TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::TetMeshTrackLengthFluxEstimator(
const Estimator::idType id,
const double multiplier,
const std::string input_mesh_file_name,
const std::string output_mesh_file_name )
: StandardEntityEstimator<moab::EntityHandle>( id, multiplier ),
d_moab_interface( new moab::Core ),
d_tet_meshset(),
d_kd_tree( new moab::AdaptiveKDTree( d_moab_interface.getRawPtr() ) ),
d_kd_tree_root(),
d_tet_barycentric_transform_matrices(),
d_tet_reference_vertices(),
d_output_mesh_name( output_mesh_file_name )
{
// Create empty MOAB meshset
moab::EntityHandle d_tet_meshset;
moab::ErrorCode return_value = d_moab_interface->create_meshset(
moab::MESHSET_SET, d_tet_meshset);
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Populate MOAB meshset with data from input file
std::cout << "Loading tetrahedral mesh from file "
<< input_mesh_file_name << " ... ";
std::cout.flush();
return_value = d_moab_interface->load_file(
input_mesh_file_name.c_str(), &d_tet_meshset);
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Range (domain) of all tetrahedral elements
moab::Range all_tet_elements;
// Extract 3D elements from meshset
return_value = d_moab_interface->get_entities_by_dimension(
d_tet_meshset, 3, all_tet_elements);
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Clear the meshset
return_value = d_moab_interface->clear_meshset(&d_tet_meshset, 1);
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Reconstruct the meshset using only 3D entitites
return_value = d_moab_interface->add_entities(
d_tet_meshset, all_tet_elements);
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
unsigned int number_of_tets = all_tet_elements.size();
boost::unordered_map<moab::EntityHandle,double> entity_volumes;
for( moab::Range::const_iterator tet = all_tet_elements.begin();
tet != all_tet_elements.end();
++tet )
{
// Make sure the tet is valid
TEST_FOR_EXCEPTION( *tet == 0,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Extract the vertex data for the given tet
std::vector<moab::EntityHandle> vertex_handles;
moab::EntityHandle current_tet = *tet;
d_moab_interface->get_connectivity( ¤t_tet, 1, vertex_handles );
// Test that the vertex entity contains four points
TEST_FOR_EXCEPTION( vertex_handles.size() != 4,
Utility::MOABException,
"Error: tet found with incorrect number of vertices "
"(" << vertex_handles.size() << " != 4)" );
moab::CartVect vertices[4];
for( unsigned j = 0; j != vertex_handles.size(); ++j )
{
d_moab_interface->get_coords( &vertex_handles[j],
1,
vertices[j].array() );
}
// Calculate Barycentric Matrix
moab::Matrix3& barycentric_transform_matrix =
d_tet_barycentric_transform_matrices[*tet];
Utility::calculateBarycentricTransformMatrix(
vertices[0],
vertices[1],
vertices[2],
vertices[3],
barycentric_transform_matrix );
// Assign reference vertices (always fourth vertex)
d_tet_reference_vertices[*tet] = vertices[3];
// Calculate tet volumes
entity_volumes[*tet] = Utility::calculateTetrahedronVolume( vertices[0],
vertices[1],
vertices[2],
vertices[3]);
}
// Assign the entity volumes
this->assignEntities( entity_volumes );
int current_dimension;
// Get dimension of the input set
current_dimension =
d_moab_interface->dimension_from_handle(all_tet_elements[0]);
moab::Range surface_triangles;
// Determine the edges from the input set
return_value = d_moab_interface->get_adjacencies( all_tet_elements,
current_dimension - 1,
true,
surface_triangles,
moab::Interface::UNION );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
all_tet_elements.merge( surface_triangles );
const char settings[]="MESHSET_FLAGS=0x1;TAG_NAME=0";
moab::FileOptions fileopts(settings);
std::cout << "(constructed " << entity_volumes.size()
<< " tetrahedrons) done." << std::endl;
// Create the kd-tree
std::cout << "Constructing kd-tree for tetrahedral mesh from file "
<< input_mesh_file_name << " ... ";
std::cout.flush();
d_kd_tree->build_tree(all_tet_elements, &d_kd_tree_root, &fileopts);
std::cout << "done." << std::endl;
}
// Set the response functions
template<typename ContributionMultiplierPolicy>
void TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::setResponseFunctions(
const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_functions )
{
for( unsigned i = 0; i < response_functions.size(); ++i )
{
if( !response_functions[i]->isSpatiallyUniform() )
{
std::cerr << "Warning: tetrahedral mesh track length estimators can only "
<< "be used with spatially uniform response functions. Results from "
<< "tetrahdedral mesh track length estimator " << getId()
<< "will not be correct." << std::endl;
}
}
StandardEntityEstimator::setResponseFunctions( response_functions );
}
// Set the particle types that can contribute to the estimator
template<typename ContributionMultiplierPolicy>
void TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::setParticleTypes( const Teuchos::Array<ParticleType>& particle_types )
{
Estimator::setParticleTypes( particle_types );
}
// Add current history estimator contribution
template<typename ContributionMultiplierPolicy>
void TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::updateFromGlobalParticleSubtrackEndingEvent(
const ParticleState& particle,
const double start_point[3],
const double end_point[3] )
{
if( this->isParticleTypeAssigned( particle.getParticleType() ) )
{
// Calculate the track length
double track_length = sqrt(
(end_point[0]-start_point[0])*(end_point[0]-start_point[0]) +
(end_point[1]-start_point[1])*(end_point[1]-start_point[1]) +
(end_point[2]-start_point[2])*(end_point[2]-start_point[2]) );
std::vector<double> ray_tet_intersections;
std::vector<moab::EntityHandle> tet_surface_triangles;
moab::ErrorCode return_value =
d_kd_tree->ray_intersect_triangles( d_kd_tree_root,
s_tol,
particle.getDirection(),
start_point,
tet_surface_triangles,
ray_tet_intersections,
0,
track_length );
// Clear the moab surface triangle entity handles - not used
tet_surface_triangles.clear();
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
if( ray_tet_intersections.size() > 0 )
{
// Sort all intersections of the ray with the tets
std::sort( ray_tet_intersections.begin(),
ray_tet_intersections.end() );
// Calculate the tet intersection points and partial track lengths
std::vector<moab::CartVect> array_of_hit_points;
// Add the origin point
{
moab::CartVect start_point_cv( start_point[0],
start_point[1],
start_point[2] );
array_of_hit_points.push_back( start_point_cv );
}
for( unsigned i = 0; i < ray_tet_intersections.size(); ++i )
{
moab::CartVect hit_point;
hit_point[0] = particle.getXDirection() * ray_tet_intersections[i]
+ start_point[0];
hit_point[1] = particle.getYDirection() * ray_tet_intersections[i]
+ start_point[1];
hit_point[2] = particle.getZDirection() * ray_tet_intersections[i]
+ start_point[2];
array_of_hit_points.push_back( hit_point );
}
// Add the end point if it doesn't lie on an intersection point
if( track_length > ray_tet_intersections.back() )
{
moab::CartVect end_point_cv(end_point[0], end_point[1], end_point[2]);
array_of_hit_points.push_back( end_point_cv );
ray_tet_intersections.push_back( track_length );
}
// Compute and add the partial history contribution to appropriate tet
for( unsigned int i = 0; i < ray_tet_intersections.size(); ++i )
{
moab::CartVect tet_centroid = ( (array_of_hit_points[i+1] +
array_of_hit_points[i])/2.0 );
// Check that the centroid falls in the mesh - if the mesh
// is concave its possible that it falls outside
if( this->isPointInMesh( tet_centroid.array() ) )
{
moab::EntityHandle tet = whichTetIsPointIn( tet_centroid.array() );
// Make sure a tet was found (tolerance issues may prevent this)
if( tet == 0 )
continue;
double partial_track_length;
if( i != 0)
{
partial_track_length = ray_tet_intersections[i] -
ray_tet_intersections[i-1];
}
else
partial_track_length = ray_tet_intersections[i];
// Handle the special case where the first point is on a mesh surface
if( partial_track_length > 0.0 )
{
// Add partial history contribution
addPartialHistoryContribution( tet,
particle,
0,
partial_track_length );
}
}
}
}
// Account for the cases where there are no intersections
else
{
// case 1: track is entirely in one tet
if( this->isPointInMesh( start_point ) )
{
moab::EntityHandle tet = whichTetIsPointIn( start_point );
// Add partial history contribution if tet was found (tolerance
// issues may prevent this)
if( tet != 0 )
addPartialHistoryContribution( tet, particle, 0, track_length );
}
// case 2: track entirely misses mesh - do nothing
}
}
}
// Test if a point is in the mesh
template<typename ContributionMultiplierPolicy>
bool
TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::isPointInMesh(
const double point[3] )
{
bool point_in_mesh = false;
// Find the leaf that the point is in (if there is one)
moab::AdaptiveKDTreeIter kd_tree_iteration;
moab::ErrorCode return_value =
d_kd_tree->point_search( point, kd_tree_iteration );
// Check that the leaf actually contains the point (concave mesh)
if( return_value == moab::MB_SUCCESS && kd_tree_iteration.handle() != 0 )
{
moab::EntityHandle leaf_node = kd_tree_iteration.handle();
moab::Range tets_in_leaf;
return_value = d_moab_interface->get_entities_by_dimension( leaf_node,
3,
tets_in_leaf,
false );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Quickly check if the point is likely in one of the tets
for( moab::Range::const_iterator tet = tets_in_leaf.begin();
tet != tets_in_leaf.end();
++tet )
{
if( Utility::isPointInTet(
point,
d_tet_reference_vertices.find( *tet )->second,
d_tet_barycentric_transform_matrices.find( *tet )->second,
s_tol ) )
{
point_in_mesh = true;
break;
}
}
}
// The point is outside the mesh bounding box
else
point_in_mesh = false;
return point_in_mesh;
}
// Determine which tet a given point is in
/*! \details This function should only be called after testing if the point
* is in the mesh. If the point is in the mesh, it is still possible that
* this function will not be able to find the correct tet due to numerical
* precision. In that event the return value will be zero. It is therefore
* important to test that the return value from this function is not zero
* before using it.
*/
template<typename ContributionMultiplierPolicy>
moab::EntityHandle TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::whichTetIsPointIn(
const double point[3] )
{
// Make sure the point is in the mesh
testPrecondition( this->isPointInMesh( point ) );
// Find the kd-tree leaf that contains the point
moab::AdaptiveKDTreeIter kd_tree_iterator;
moab::ErrorCode return_value = d_kd_tree->point_search( point,
kd_tree_iterator );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
TEST_FOR_EXCEPTION( kd_tree_iterator.handle() == 0,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
moab::EntityHandle leaf = kd_tree_iterator.handle();
moab::Range tets_in_leaf;
return_value = d_moab_interface->get_entities_by_dimension( leaf,
3,
tets_in_leaf,
false );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// A tet must be found since a leaf was found - failure to find a tet
// indicates a tolerance issue usually
moab::EntityHandle tet_handle = 0;
for( moab::Range::const_iterator tet = tets_in_leaf.begin();
tet != tets_in_leaf.end();
++tet )
{
if( Utility::isPointInTet(
point,
d_tet_reference_vertices.find( *tet )->second,
d_tet_barycentric_transform_matrices.find( *tet )->second,
s_tol ) )
{
tet_handle = *tet;
break;
}
}
// Make sure the tet has been found
if( tet_handle == 0 && SimulationGeneralProperties::displayWarnings() )
{
#pragma omp critical( point_in_tet_warning_message )
{
std::cerr << "Warning: the tetrahedron containing point {"
<< point[0] << "," << point[1] << "," << point[2]
<< "} could not be found (" << tets_in_leaf.size()
<< " tets in leaf)!." << std::endl;
}
}
// Make sure the leaf is valid
testPostcondition( tets_in_leaf.size() > 0 );
return tet_handle;
}
// Get all tet elements
template<typename ContributionMultiplierPolicy>
const moab::Range TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::getAllTetElements() const
{
moab::Range all_tet_elements;
moab::ErrorCode return_value = d_moab_interface->get_entities_by_dimension(
d_tet_meshset, 3, all_tet_elements);
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
return all_tet_elements;
}
// Export the estimator data
template<typename ContributionMultiplierPolicy>
void TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::exportData(
EstimatorHDF5FileHandler& hdf5_file,
const bool process_data ) const
{
// Export data in FRENSIE formatting for data manipulation
StandardEntityEstimator<moab::EntityHandle>::exportData( hdf5_file,
process_data );
// Export data for visualization
if( process_data )
{
moab::Range all_tet_elements;
std::vector<moab::Tag> mean_tag( this->getNumberOfBins()*
this->getNumberOfResponseFunctions()+
this->getNumberOfResponseFunctions() ),
relative_error_tag( mean_tag.size() );
std::vector<moab::Tag> vov_tag( this->getNumberOfResponseFunctions() ),
fom_tag( vov_tag.size() );
moab::ErrorCode return_value = d_moab_interface->get_entities_by_dimension(
d_tet_meshset, 3, all_tet_elements);
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Process moments
for ( moab::Range::const_iterator tet = all_tet_elements.begin();
tet != all_tet_elements.end();
++tet )
{
const double tet_volume = this->getEntityNormConstant( *tet );
const Estimator::TwoEstimatorMomentsArray& tet_bin_data =
this->getEntityBinData( *tet );
std::string mean_tag_prefix = "mean: ";
std::string relative_error_tag_prefix = "relative_error: ";
std::string vov_tag_prefix = "vov: ";
std::string fom_tag_prefix = "fom: ";
for( unsigned i = 0; i < tet_bin_data.size(); ++i )
{
double mean, relative_error;
this->processMoments( tet_bin_data[i],
tet_volume,
mean,
relative_error );
std::string bin_name = this->getBinName( i );
std::string mean_tag_name = mean_tag_prefix + bin_name;
std::string relative_error_tag_name = relative_error_tag_prefix +
bin_name;
// Assign mean tag data
moab::ErrorCode return_value = d_moab_interface->tag_get_handle(
mean_tag_name.c_str(),
1,
moab::MB_TYPE_DOUBLE,
mean_tag[i],
moab::MB_TAG_DENSE|moab::MB_TAG_CREAT );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
return_value = d_moab_interface->tag_set_data( mean_tag[i],
&(*tet),
1,
&mean );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Assign error tag data
return_value = d_moab_interface->tag_get_handle(
relative_error_tag_name.c_str(),
1,
moab::MB_TYPE_DOUBLE,
relative_error_tag[i],
moab::MB_TAG_DENSE|moab::MB_TAG_CREAT );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
return_value = d_moab_interface->tag_set_data( relative_error_tag[i],
&(*tet),
1,
&relative_error );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
}
// Assign total bin data for each entity
std::string total_tag_prefix = "total_";
std::string total_mean_tag_name = total_tag_prefix + "mean";
std::string total_relative_error_tag_name = total_tag_prefix +
"relative_error";
std::string total_vov_tag_name = total_tag_prefix + "vov";
std::string total_fom_tag_name = total_tag_prefix + "fom";
const Estimator::FourEstimatorMomentsArray& total_tet_data =
this->getEntityTotalData( *tet );
for( unsigned i = 0; i != total_tet_data.size(); ++i )
{
double mean, relative_error, vov, fom;
this->processMoments( total_tet_data[i],
tet_volume,
mean,
relative_error,
vov,
fom);
unsigned tag_index = this->getNumberOfBins() + i;
// Assign total mean tag data
moab::ErrorCode return_value = d_moab_interface->tag_get_handle(
total_mean_tag_name.c_str(),
1,
moab::MB_TYPE_DOUBLE,
mean_tag[tag_index],
moab::MB_TAG_DENSE|moab::MB_TAG_CREAT );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
return_value = d_moab_interface->tag_set_data( mean_tag[tag_index],
&(*tet),
1,
&mean );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Assign total relative error tag data
return_value = d_moab_interface->tag_get_handle(
total_relative_error_tag_name.c_str(),
1,
moab::MB_TYPE_DOUBLE,
relative_error_tag[tag_index],
moab::MB_TAG_DENSE|moab::MB_TAG_CREAT );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
return_value = d_moab_interface->tag_set_data(
relative_error_tag[tag_index],
&(*tet),
1,
&relative_error );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Assign total vov tag data
return_value = d_moab_interface->tag_get_handle(
total_vov_tag_name.c_str(),
1,
moab::MB_TYPE_DOUBLE,
vov_tag[i],
moab::MB_TAG_DENSE|moab::MB_TAG_CREAT );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
return_value = d_moab_interface->tag_set_data( vov_tag[i],
&(*tet),
1,
&vov );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
// Assign total fom tag data
return_value = d_moab_interface->tag_get_handle(
total_fom_tag_name.c_str(),
1,
moab::MB_TYPE_DOUBLE,
fom_tag[i],
moab::MB_TAG_DENSE|moab::MB_TAG_CREAT );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
return_value = d_moab_interface->tag_set_data( fom_tag[i],
&(*tet),
1,
&fom );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
}
}
// Export the mesh
std::vector<moab::Tag> output_tags = mean_tag;
output_tags.insert( output_tags.end(),
relative_error_tag.begin(),
relative_error_tag.end() );
output_tags.insert( output_tags.end(),
vov_tag.begin(),
vov_tag.end() );
output_tags.insert( output_tags.end(),
fom_tag.begin(),
fom_tag.end() );
return_value = d_moab_interface->write_file( d_output_mesh_name.c_str(),
NULL,
NULL,
&d_tet_meshset,
1,
&(output_tags[0]),
output_tags.size() );
TEST_FOR_EXCEPTION( return_value != moab::MB_SUCCESS,
Utility::MOABException,
moab::ErrorCodeStr[return_value] );
}
}
// Print the estimator data
/*! \details Due to the large number of tets that are likely to be printed,
* printing of data to the screen will not be done.
*/
template<typename ContributionMultiplierPolicy>
void TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::print(
std::ostream& os ) const
{ /* ... */ }
// Assign bin boundaries to an estimator dimension
template<typename ContributionMultiplierPolicy>
void TetMeshTrackLengthFluxEstimator<ContributionMultiplierPolicy>::assignBinBoundaries(
const Teuchos::RCP<EstimatorDimensionDiscretization>& bin_boundaries )
{
if( bin_boundaries->getDimension() == COSINE_DIMENSION )
{
std::cerr << "Warning: " << bin_boundaries->getDimensionName()
<< " bins cannot be set for standard cell estimators. The bins "
<< "requested for tetrahdedral mesh flux estimator " << this->getId()
<< " will be ignored."
<< std::endl;
}
else if( bin_boundaries->getDimension() == TIME_DIMENSION )
{
std::cerr << "Warning: " << bin_boundaries->getDimensionName()
<< " bins cannot be set for standard cell estimators. The bins "
<< "requested for tetrahdedral mesh flux estimator " << this->getId()
<< " will be ignored."
<< std::endl;
}
else
{
StandardEntityEstimator<moab::EntityHandle>::assignBinBoundaries(
bin_boundaries );
}
}
} // end MonteCarlo namespace
//---------------------------------------------------------------------------//
// end MonteCarlo_TetMeshTrackLengthFluxEstimator.hpp
//---------------------------------------------------------------------------//
| 35.391979 | 138 | 0.606404 | [
"mesh",
"vector",
"3d"
] |
031d4b65510d2f584bf7c1372e6e645edd9581f2 | 7,352 | cpp | C++ | src/BThreadPack/BThreadPoolPrivate.cpp | zhangbolily/BThreadPack | 6565309d253039e1e7e45c702b84a488fc837a58 | [
"MIT"
] | 2 | 2019-03-30T03:39:00.000Z | 2021-09-08T13:02:30.000Z | src/BThreadPack/BThreadPoolPrivate.cpp | zhangbolily/BThreadPack | 6565309d253039e1e7e45c702b84a488fc837a58 | [
"MIT"
] | null | null | null | src/BThreadPack/BThreadPoolPrivate.cpp | zhangbolily/BThreadPack | 6565309d253039e1e7e45c702b84a488fc837a58 | [
"MIT"
] | 2 | 2019-12-23T22:08:53.000Z | 2021-09-08T10:55:21.000Z | /* MIT License
*
* Copyright (c) 2018 Ball Chang
*
* 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.
*/
/*
* @Author : Ball Chang
* @File : BThreadPoolPrivate.cpp
* @Date : 2019-03-27
*/
#include "BThreadPack/BThreadPool.h"
#include "BThreadPack/private/BThreadPoolPrivate.h"
#include "BThreadPack/private/BGroupTaskPrivate.h"
namespace BThreadPack {
BThreadPoolPrivate::BThreadPoolPrivate(BThreadPool* ptr)
: BAbstractThreadPoolPrivate(static_cast<BAbstractThreadPool*>(ptr)),
m_public_ptr(ptr) {
}
void BThreadPoolPrivate::Run(BThreadInfo &thread_info) {
thread_info.running();
BThreadPool* thread_pool_handle =
static_cast<BThreadPool*>(thread_info.threadPoolHandle());
if (thread_pool_handle == nullptr) {
thread_info.exit(BError);
return;
}
BGeneralTask* p_general_task = nullptr;
BGroupTask* p_group_task = nullptr;
while (1) {
// Get group task first
p_general_task = static_cast<BGeneralTask*>(
thread_pool_handle->m_private_ptr->getGroupTask(&p_group_task));
if (p_general_task == nullptr) {
p_group_task = nullptr;
p_general_task = static_cast<BGeneralTask*>(
thread_pool_handle->m_private_ptr->getTask());
}
if (p_general_task == nullptr) {
thread_pool_handle->m_private_ptr->wait();
// Check the thread pool status and flag to determine weather exit.
if (thread_pool_handle->status()
== BAbstractThreadPool::BThreadPoolStatus::ThreadPoolStop
|| thread_pool_handle->m_private_ptr->isRemove()) {
thread_info.exit(BSuccess);
return;
} else {
continue;
}
}
// Finished validate
// Set this thread namespace
if (p_general_task->name().empty()) {
BThreadPoolPrivate::setThreadName("BThreadPack");
} else {
BThreadPoolPrivate::setThreadName(p_general_task->name());
}
// Processing this task and recording time
if (p_group_task != nullptr) {
p_group_task->m_private_ptr->startExecutionTiming();
p_group_task->m_private_ptr->setStatus(
BGroupTask::BGroupTaskStatus::Executing);
}
p_general_task->m_private_ptr->setStatus(BGeneralTask::BTaskStatus::TaskExecuting);
p_general_task->m_private_ptr->startExecutionTiming();
int32 _retcode = p_general_task->execute();
p_general_task->m_private_ptr->stopExecutionTiming();
p_general_task->m_private_ptr->stopRealTiming();
// Stop processing
// All of group tasks have been finisehd, stop recording time.
if (p_group_task != nullptr) {
p_group_task->m_private_ptr->stopExecutionTiming();
p_group_task->m_private_ptr->stopRealTiming();
p_group_task->m_private_ptr->setStatus(
BGroupTask::BGroupTaskStatus::Finished);
p_group_task->m_private_ptr->finishedOneTask();
}
// Check if this task has been processed successfully
if (_retcode == BError) {
p_general_task->m_private_ptr->setStatus(BGeneralTask::BTaskStatus::TaskFailed);
} else {
p_general_task->m_private_ptr->setStatus(BGeneralTask::BTaskStatus::TaskFinished);
}
switch (thread_pool_handle->optimizePolicy()) {
case BThreadPool::PerformanceFirst:{
uint64 *_task_time = new uint64;
*_task_time = p_general_task->executionTime();
thread_pool_handle->sendMessage(
TaskTimeMessageNum, static_cast<void*>(_task_time));
break;
};
case BThreadPool::ProcessTimeFirst:{
uint64 *_task_time = new uint64;
*_task_time = p_general_task->executionTime();
thread_pool_handle->sendMessage(
TaskTimeMessageNum, static_cast<void*>(_task_time));
break;
};
default: break;
}
if (p_general_task->autoDelete()) {
delete p_general_task;
p_general_task = nullptr;
} else {
if (p_group_task != nullptr) {
p_group_task->m_private_ptr->pushFinishedTask(
static_cast<BAbstractTask*>(p_general_task));
} else {
thread_pool_handle->m_private_ptr->pushFinishedTask(
static_cast<BAbstractTask*>(p_general_task));
}
}
// Finished check
}
}
int32 BThreadPoolPrivate::normalOptimizer(
std::vector<BGeneralTask *> _task_vec) {
// TODO(Ball Chang): This function need to be reimplemented.
return BCore::ReturnCode::BSuccess;
}
int64 BThreadPoolPrivate::initializeThreadPool() {
return initializeThreadPool(m_public_ptr->capacity());
}
int64 BThreadPoolPrivate::initializeThreadPool(uint32 _thread_num) {
m_public_ptr->kill();
m_public_ptr->setStatus(BThreadPool::BThreadPoolStatus::ThreadPoolRunning);
BThreadInfo thread_info;
thread_info.setThreadPoolHandle(
static_cast<BAbstractThreadPool*>(m_public_ptr));
for (uint32 i = 0; i < _thread_num; ++i) {
// Construct a new thread and pass it to thread pool.
if (BAbstractThreadPoolPrivate::addThread(BThread())
== BThreadPoolFull) {
return BThreadPoolFull;
} else {
// You can add some actions like set affinity here before detach.
m_thread_vec_.back().start(BThreadPoolPrivate::Run, thread_info);
#ifdef _B_DEBUG_
B_PRINT_DEBUG("BThreadPoolPrivate::initializeThreadPool"
" - Added a new thread, id is "
<< m_thread_vec_.back().id())
#endif
m_thread_vec_.back().detach();
}
}
return BCore::ReturnCode::BSuccess;
}
void BThreadPoolPrivate::setThreadName(const char* _name) {
#ifdef WIN32
#else
prctl(PR_SET_NAME, _name);
#endif
}
void BThreadPoolPrivate::setThreadName(const std::string _name) {
BThreadPoolPrivate::setThreadName(_name.c_str());
}
} // namespace BThreadPack
| 36.039216 | 94 | 0.642274 | [
"vector"
] |
032584bb7f17b8611cac80841db4905b4eb87401 | 9,584 | cpp | C++ | test/cpp/unit/data/samplers/test_negative.cpp | ryansun117/marius | c6a81b2ea6b6b468baf5277cf6955f9543b66c82 | [
"Apache-2.0"
] | null | null | null | test/cpp/unit/data/samplers/test_negative.cpp | ryansun117/marius | c6a81b2ea6b6b468baf5277cf6955f9543b66c82 | [
"Apache-2.0"
] | null | null | null | test/cpp/unit/data/samplers/test_negative.cpp | ryansun117/marius | c6a81b2ea6b6b468baf5277cf6955f9543b66c82 | [
"Apache-2.0"
] | null | null | null | //
// Created by Jason Mohoney on 2/9/22.
//
#include <gtest/gtest.h>
#include <data/samplers/negative.h>
int num_nodes = 6;
torch::Tensor edges = torch::tensor({{0, 2},
{0, 4},
{1, 3},
{1, 5},
{4, 2},
{5, 2}}, torch::kInt64);
torch::Tensor typed_edges = torch::tensor({{0, 0, 2},
{0, 1, 4},
{1, 1, 3},
{1, 0, 5},
{4, 0, 2},
{5, 1, 2}}, torch::kInt64);
torch::Tensor batch_edges = torch::tensor({{1, 5}, {0, 2}, {4, 2}}, torch::kInt64);
torch::Tensor batch_typed_edges = torch::tensor({{1, 0, 5}, {0, 0, 2}, {4, 0, 2}}, torch::kInt64);
class CorruptNodeNegativeSamplerTest : public ::testing::Test {
protected:
shared_ptr<MariusGraph> graph;
shared_ptr<MariusGraph> typed_graph;
void SetUp() override {
torch::Tensor dst_sorted_edges = edges.index_select(0, edges.select(1, 1).argsort(0));
torch::Tensor dst_sorted_typed_edges = typed_edges.index_select(0, typed_edges.select(1, 2).argsort(0));
graph = std::make_shared<MariusGraph>(edges, dst_sorted_edges, num_nodes);
typed_graph = std::make_shared<MariusGraph>(typed_edges, dst_sorted_typed_edges, num_nodes);
graph->sortAllEdges(torch::tensor({{0, 3}}, torch::kInt64));
typed_graph->sortAllEdges(torch::tensor({{0, 1, 3}}, torch::kInt64));
}
};
void validate_sample(shared_ptr<CorruptNodeNegativeSampler> sampler, torch::Tensor sample, shared_ptr<MariusGraph> graph) {
// validate shape
ASSERT_EQ(sample.size(0), sampler->num_chunks_);
if (sampler->num_negatives_ != -1) {
ASSERT_EQ(sample.size(1), sampler->num_negatives_);
} else {
ASSERT_EQ(sample.size(1), graph->num_nodes_in_memory_);
}
// validate max and min ids
ASSERT_TRUE(sample.max().item<int64_t>() < graph->num_nodes_in_memory_);
ASSERT_TRUE(sample.min().item<int64_t>() >= 0);
}
void validate_filter_local(torch::Tensor filter, torch::Tensor sample, torch::Tensor edges_t, bool inverse) {
// check filtered edges are present in the graph
auto batch_accessor = edges_t.accessor<int64_t, 2>();
auto sample_accessor = sample.accessor<int64_t, 2>();
auto filter_accessor = filter.accessor<int64_t, 2>();
bool has_relations = false;
if (edges_t.size(1) == 3) {
has_relations = true;
}
int64_t num_chunks = sample.size(0);
int64_t num_edges = edges_t.size(0);
int64_t chunk_size = ceil((double) num_edges / num_chunks);
for (int i = 0; i < filter.size(0); i++) {
int64_t src;
int64_t rel;
int64_t dst;
bool found = false;
int64_t edge_id = filter_accessor[i][0];
int chunk_id = edge_id / chunk_size;
if (inverse) {
src = sample_accessor[chunk_id][filter_accessor[i][1]];
if (has_relations) {
rel = batch_accessor[edge_id][1];
dst = batch_accessor[edge_id][2];
} else {
dst = batch_accessor[edge_id][1];
}
} else {
src = batch_accessor[edge_id][0];
dst = sample_accessor[chunk_id][filter_accessor[i][1]];
if (has_relations) {
rel = batch_accessor[edge_id][1];
}
}
if (has_relations) {
for (int k = 0; k < edges_t.size(0); k++) {
if (batch_accessor[k][0] == src && batch_accessor[k][1] == rel && batch_accessor[k][2] == dst) {
found = true;
}
}
} else {
for (int k = 0; k < edges_t.size(0); k++) {
if (batch_accessor[k][0] == src && batch_accessor[k][1] == dst) {
found = true;
}
}
}
ASSERT_TRUE(found);
}
}
void validate_filter_global(torch::Tensor filter, torch::Tensor sample, shared_ptr<MariusGraph> graph, torch::Tensor edges_t, bool inverse) {
// check filtered edges are present in the graph
auto graph_accessor = graph->src_sorted_edges_.accessor<int64_t, 2>();
auto batch_accessor = edges_t.accessor<int64_t, 2>();
auto sample_accessor = sample.accessor<int64_t, 2>();
auto filter_accessor = filter.accessor<int64_t, 2>();
bool has_relations = false;
if (edges_t.size(1) == 3) {
has_relations = true;
}
int64_t num_chunks = sample.size(0);
int64_t num_edges = edges_t.size(0);
int64_t chunk_size = ceil((double) num_edges / num_chunks);
for (int i = 0; i < filter.size(0); i++) {
int64_t src;
int64_t rel;
int64_t dst;
bool found = false;
int64_t edge_id = filter_accessor[i][0];
int chunk_id = edge_id / chunk_size;
if (inverse) {
src = sample_accessor[chunk_id][filter_accessor[i][1]];
if (has_relations) {
rel = batch_accessor[edge_id][1];
dst = batch_accessor[edge_id][2];
} else {
dst = batch_accessor[edge_id][1];
}
} else {
src = batch_accessor[edge_id][0];
dst = sample_accessor[chunk_id][filter_accessor[i][1]];
if (has_relations) {
rel = batch_accessor[edge_id][1];
}
}
if (has_relations) {
for (int k = 0; k < graph->src_sorted_edges_.size(0); k++) {
if (graph_accessor[k][0] == src && graph_accessor[k][1] == rel && graph_accessor[k][2] == dst) {
found = true;
}
}
} else {
for (int k = 0; k < graph->src_sorted_edges_.size(0); k++) {
if (graph_accessor[k][0] == src && graph_accessor[k][1] == dst) {
found = true;
}
}
}
ASSERT_TRUE(found);
}
}
void test_unfiltered_corruption_sampler(shared_ptr<CorruptNodeNegativeSampler> sampler, shared_ptr<MariusGraph> graph, torch::Tensor edges_t) {
torch::Tensor sample;
torch::Tensor filter;
std::tie(sample, filter) = sampler->getNegatives(graph, edges_t, false);
validate_sample(sampler, sample, graph);
validate_filter_local(filter, sample, edges_t, false);
std::tie(sample, filter) = sampler->getNegatives(graph, edges_t, true);
validate_sample(sampler, sample, graph);
validate_filter_local(filter, sample, edges_t, true);
}
void test_filtered_corruption_sampler(shared_ptr<CorruptNodeNegativeSampler> sampler, shared_ptr<MariusGraph> graph, torch::Tensor edges_t) {
torch::Tensor sample;
torch::Tensor filter;
std::tie(sample, filter) = sampler->getNegatives(graph, edges_t, false);
validate_sample(sampler, sample, graph);
validate_filter_global(filter, sample, graph, edges_t, false);
std::tie(sample, filter) = sampler->getNegatives(graph, edges_t, true);
validate_sample(sampler, sample, graph);
validate_filter_global(filter, sample, graph, edges_t, true);
}
TEST_F(CorruptNodeNegativeSamplerTest, TestUniform) {
auto corrupt_uniform = std::make_shared<CorruptNodeNegativeSampler>(1, 5, 0.0, false);
test_unfiltered_corruption_sampler(corrupt_uniform, graph, batch_edges);
test_unfiltered_corruption_sampler(corrupt_uniform, typed_graph, batch_typed_edges);
}
TEST_F(CorruptNodeNegativeSamplerTest, TestUniformChunked) {
auto corrupt_uniform_chunked = std::make_shared<CorruptNodeNegativeSampler>(3, 5, 0.0, false);
test_unfiltered_corruption_sampler(corrupt_uniform_chunked, graph, batch_edges);
test_unfiltered_corruption_sampler(corrupt_uniform_chunked, typed_graph, batch_typed_edges);
}
TEST_F(CorruptNodeNegativeSamplerTest, TestMix) {
auto corrupt_mix = std::make_shared<CorruptNodeNegativeSampler>(1, 5, 0.5, false);
test_unfiltered_corruption_sampler(corrupt_mix, graph, batch_edges);
test_unfiltered_corruption_sampler(corrupt_mix, typed_graph, batch_typed_edges);
}
TEST_F(CorruptNodeNegativeSamplerTest, TestMixChunked) {
auto corrupt_mix_chunked = std::make_shared<CorruptNodeNegativeSampler>(3, 5, 0.5, false);
test_unfiltered_corruption_sampler(corrupt_mix_chunked, graph, batch_edges);
test_unfiltered_corruption_sampler(corrupt_mix_chunked, typed_graph, batch_typed_edges);
}
TEST_F(CorruptNodeNegativeSamplerTest, TestAllDegree) {
auto corrupt_all_degree = std::make_shared<CorruptNodeNegativeSampler>(1, 5, 1.0, false);
test_unfiltered_corruption_sampler(corrupt_all_degree, graph, batch_edges);
test_unfiltered_corruption_sampler(corrupt_all_degree, typed_graph, batch_typed_edges);
}
TEST_F(CorruptNodeNegativeSamplerTest, TestAllDegreeChunked) {
auto corrupt_all_degree_chunked = std::make_shared<CorruptNodeNegativeSampler>(3, 5, 1.0, false);
test_unfiltered_corruption_sampler(corrupt_all_degree_chunked, graph, batch_edges);
test_unfiltered_corruption_sampler(corrupt_all_degree_chunked, typed_graph, batch_typed_edges);
}
TEST_F(CorruptNodeNegativeSamplerTest, TestFilter) {
auto corrupt_filtered = std::make_shared<CorruptNodeNegativeSampler>(1, -1, 0.0, true);
test_filtered_corruption_sampler(corrupt_filtered, graph, batch_edges);
test_filtered_corruption_sampler(corrupt_filtered, typed_graph, batch_typed_edges);
} | 38.801619 | 143 | 0.626878 | [
"shape"
] |
03260b9a491ec395e56140757eb5c2bab228aa5f | 912 | cpp | C++ | CSES/ProblemSet/IntroductoryProblems/GrayCode_sol6_iterative_approach_and_pattern_O(N2^N)_time_O(2^N)_extra_space_80ms.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | CSES/ProblemSet/IntroductoryProblems/GrayCode_sol6_iterative_approach_and_pattern_O(N2^N)_time_O(2^N)_extra_space_80ms.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | CSES/ProblemSet/IntroductoryProblems/GrayCode_sol6_iterative_approach_and_pattern_O(N2^N)_time_O(2^N)_extra_space_80ms.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution{
public:
void generateGrayCode(int n, vector<int>& grayCode){
const int FULL_MASK = (1 << n) - 1;
grayCode.clear();
grayCode.resize(FULL_MASK + 1, 0);
for(int mask = 0; mask <= FULL_MASK; ++mask){
for(int bit = 0; bit < n; ++bit){
if((1 << bit) <= mask){
int blockIdx = 1 + (mask - (1 << bit)) / (1 << (bit + 1));
if(blockIdx & 1){
grayCode[mask] |= (1 << bit);
}
}
}
}
}
};
int main(){
int n;
cin >> n;
vector<int> grayCode;
Solution().generateGrayCode(n, grayCode);
for(int code: grayCode){
for(int bit = n - 1; bit >= 0; --bit){
cout << ((code >> bit) & 1);
}
cout << "\n";
}
return 0;
} | 24 | 78 | 0.419956 | [
"vector"
] |
032f49a5575423133596ee96094571817f446683 | 11,401 | cpp | C++ | pxr/usd/lib/sdf/abstractData.cpp | YuqiaoZhang/USD | bf3a21e6e049486441440ebf8c0387db2538d096 | [
"BSD-2-Clause"
] | 27 | 2017-10-17T02:44:43.000Z | 2021-06-10T08:23:54.000Z | pxr/usd/lib/sdf/abstractData.cpp | YuqiaoZhang/USD | bf3a21e6e049486441440ebf8c0387db2538d096 | [
"BSD-2-Clause"
] | 1 | 2020-07-07T22:39:42.000Z | 2020-07-07T22:39:42.000Z | pxr/usd/lib/sdf/abstractData.cpp | YuqiaoZhang/USD | bf3a21e6e049486441440ebf8c0387db2538d096 | [
"BSD-2-Clause"
] | 7 | 2018-07-11T19:03:59.000Z | 2022-03-24T07:57:06.000Z | //
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/usd/sdf/abstractData.h"
#include "pxr/base/trace/trace.h"
#include <iostream>
#include <vector>
#include <utility>
using std::vector;
using std::pair;
using std::make_pair;
PXR_NAMESPACE_OPEN_SCOPE
TF_DEFINE_PUBLIC_TOKENS(SdfDataTokens, SDF_DATA_TOKENS);
////////////////////////////////////////////////////////////
SdfAbstractData::~SdfAbstractData()
{
}
struct SdfAbstractData_IsEmptyChecker : public SdfAbstractDataSpecVisitor
{
SdfAbstractData_IsEmptyChecker() : isEmpty(true) { }
virtual bool VisitSpec(const SdfAbstractData &, const SdfPath &)
{
isEmpty = false;
return false;
}
virtual void Done(const SdfAbstractData&)
{
// Do nothing
}
bool isEmpty;
};
bool
SdfAbstractData::IsEmpty() const
{
SdfAbstractData_IsEmptyChecker checker;
VisitSpecs(&checker);
return checker.isEmpty;
}
struct SdfAbstractData_CopySpecs : public SdfAbstractDataSpecVisitor
{
SdfAbstractData_CopySpecs(SdfAbstractData* dest_) : dest(dest_) { }
virtual bool VisitSpec(
const SdfAbstractData& src, const SdfPath &path)
{
const std::vector<TfToken> keys = src.List(path);
dest->CreateSpec(path, src.GetSpecType(path));
TF_FOR_ALL(keyIt, keys) {
dest->Set(path, *keyIt, src.Get(path, *keyIt));
}
return true;
}
virtual void Done(const SdfAbstractData&)
{
// Do nothing
}
SdfAbstractData* dest;
};
void
SdfAbstractData::CopyFrom(const SdfAbstractDataConstPtr& source)
{
SdfAbstractData_CopySpecs copySpecsToThis(this);
source->VisitSpecs(©SpecsToThis);
}
// Visitor that checks whether all specs in the visited SdfAbstractData object
// exist in another SdfAbstractData object.
struct SdfAbstractData_CheckAllSpecsExist : public SdfAbstractDataSpecVisitor
{
SdfAbstractData_CheckAllSpecsExist(const SdfAbstractData& data)
: passed(true), _data(data) { }
virtual bool VisitSpec(
const SdfAbstractData&, const SdfPath &path)
{
if (!_data.HasSpec(path)) {
passed = false;
}
return passed;
}
virtual void Done(const SdfAbstractData&)
{
// Do nothing
}
bool passed;
private:
const SdfAbstractData& _data;
};
// Visitor that checks whether all specs in the visited SdfAbstractData object
// have the same fields and contents as another SdfAbstractData object.
struct SdfAbstractData_CheckAllSpecsMatch : public SdfAbstractDataSpecVisitor
{
SdfAbstractData_CheckAllSpecsMatch(const SdfAbstractData& rhs)
: passed(true), _rhs(rhs) { }
virtual bool VisitSpec(
const SdfAbstractData& lhs, const SdfPath &path)
{
return (passed = _AreSpecsAtPathEqual(lhs, _rhs, path));
}
virtual void Done(const SdfAbstractData&)
{
// Do nothing
}
bool passed;
private:
static bool _AreSpecsAtPathEqual(
const SdfAbstractData& lhs, const SdfAbstractData& rhs,
const SdfPath &path)
{
const TfTokenVector lhsFields = lhs.List(path);
const TfTokenVector rhsFields = rhs.List(path);
std::set<TfToken> lhsFieldSet( lhsFields.begin(), lhsFields.end() );
std::set<TfToken> rhsFieldSet( rhsFields.begin(), rhsFields.end() );
if (lhs.GetSpecType(path) != rhs.GetSpecType(path))
return false;
if (lhsFieldSet != rhsFieldSet)
return false;
TF_FOR_ALL(field, lhsFields) {
// Note: this comparison forces manufacturing of VtValues.
if (lhs.Get(path, *field) != rhs.Get(path, *field))
return false;
}
return true;
}
private:
const SdfAbstractData& _rhs;
};
bool
SdfAbstractData::Equals(const SdfAbstractDataRefPtr &rhs) const
{
TRACE_FUNCTION();
// Check that the set of specs matches.
SdfAbstractData_CheckAllSpecsExist
rhsHasAllSpecsInThis(*boost::get_pointer(rhs));
VisitSpecs(&rhsHasAllSpecsInThis);
if (!rhsHasAllSpecsInThis.passed)
return false;
SdfAbstractData_CheckAllSpecsExist thisHasAllSpecsInRhs(*this);
rhs->VisitSpecs(&thisHasAllSpecsInRhs);
if (!thisHasAllSpecsInRhs.passed)
return false;
// Check that every spec matches.
SdfAbstractData_CheckAllSpecsMatch
thisSpecsMatchRhsSpecs(*boost::get_pointer(rhs));
VisitSpecs(&thisSpecsMatchRhsSpecs);
return thisSpecsMatchRhsSpecs.passed;
}
// Visitor for collecting a sorted set of all paths in an SdfAbstractData.
struct SdfAbstractData_SortedPathCollector : public SdfAbstractDataSpecVisitor
{
virtual bool VisitSpec(
const SdfAbstractData& data, const SdfPath &path)
{
paths.insert(path);
return true;
}
virtual void Done(const SdfAbstractData&)
{
// Do nothing
}
SdfPathSet paths;
};
void
SdfAbstractData::WriteToStream(std::ostream& os) const
{
TRACE_FUNCTION();
// We sort keys and fields below to ensure a stable output ordering.
SdfAbstractData_SortedPathCollector collector;
VisitSpecs(&collector);
for (SdfPath const &path: collector.paths) {
const SdfSpecType specType = GetSpecType(path);
os << path << " " << TfEnum::GetDisplayName(specType) << '\n';
const TfTokenVector fields = List(path);
const std::set<TfToken> fieldSet(fields.begin(), fields.end());
for (TfToken const &fieldName: fieldSet) {
const VtValue value = Get(path, fieldName);
os << " "
<< fieldName << " "
<< value.GetTypeName() << " "
<< value << '\n';
}
}
}
void
SdfAbstractData::VisitSpecs(SdfAbstractDataSpecVisitor* visitor) const
{
if (TF_VERIFY(visitor)) {
_VisitSpecs(visitor);
visitor->Done(*this);
}
}
bool
SdfAbstractData::HasSpecAndField(
const SdfPath &path, const TfToken &fieldName,
SdfAbstractDataValue *value, SdfSpecType *specType) const
{
*specType = GetSpecType(path);
return *specType != SdfSpecTypeUnknown && Has(path, fieldName, value);
}
bool
SdfAbstractData::HasSpecAndField(
const SdfPath &path, const TfToken &fieldName,
VtValue *value, SdfSpecType *specType) const
{
*specType = GetSpecType(path);
return *specType != SdfSpecTypeUnknown && Has(path, fieldName, value);
}
std::type_info const &
SdfAbstractData::GetTypeid(const SdfPath &path, const TfToken &fieldName) const
{
return Get(path, fieldName).GetTypeid();
}
bool
SdfAbstractData::HasDictKey(const SdfPath &path,
const TfToken &fieldName,
const TfToken &keyPath,
SdfAbstractDataValue* value) const
{
VtValue tmp;
bool result = HasDictKey(path, fieldName, keyPath, value ? &tmp : NULL);
if (result && value) {
value->StoreValue(tmp);
}
return result;
}
bool
SdfAbstractData::HasDictKey(const SdfPath &path,
const TfToken &fieldName,
const TfToken &keyPath,
VtValue *value) const
{
// Attempt to look up field.
VtValue dictVal;
if (Has(path, fieldName, &dictVal) && dictVal.IsHolding<VtDictionary>()) {
// It's a dictionary -- attempt to find element at keyPath.
if (VtValue const *v =
dictVal.UncheckedGet<VtDictionary>().GetValueAtPath(keyPath)) {
if (value)
*value = *v;
return true;
}
}
return false;
}
VtValue
SdfAbstractData::GetDictValueByKey(const SdfPath &path,
const TfToken &fieldName,
const TfToken &keyPath) const
{
VtValue result;
HasDictKey(path, fieldName, keyPath, &result);
return result;
}
void
SdfAbstractData::SetDictValueByKey(const SdfPath &path,
const TfToken &fieldName,
const TfToken &keyPath,
const VtValue &value)
{
if (value.IsEmpty()) {
EraseDictValueByKey(path, fieldName, keyPath);
return;
}
VtValue dictVal = Get(path, fieldName);
// Swap out existing dictionary (if present).
VtDictionary dict;
dictVal.Swap(dict);
// Now modify dict.
dict.SetValueAtPath(keyPath, value);
// Swap it back into the VtValue, and set it.
dictVal.Swap(dict);
Set(path, fieldName, dictVal);
}
void
SdfAbstractData::SetDictValueByKey(const SdfPath &path,
const TfToken &fieldName,
const TfToken &keyPath,
const SdfAbstractDataConstValue& value)
{
VtValue vtval;
value.GetValue(&vtval);
SetDictValueByKey(path, fieldName, keyPath, vtval);
}
void
SdfAbstractData::EraseDictValueByKey(const SdfPath &path,
const TfToken &fieldName,
const TfToken &keyPath)
{
VtValue dictVal = Get(path, fieldName);
if (dictVal.IsHolding<VtDictionary>()) {
// Swap out existing dictionary (if present).
VtDictionary dict;
dictVal.Swap(dict);
// Now modify dict.
dict.EraseValueAtPath(keyPath);
// Swap it back into the VtValue, and set it.
if (dict.empty()) {
Erase(path, fieldName);
} else {
dictVal.Swap(dict);
Set(path, fieldName, dictVal);
}
}
}
std::vector<TfToken>
SdfAbstractData::ListDictKeys(const SdfPath &path,
const TfToken &fieldName,
const TfToken &keyPath) const
{
vector<TfToken> result;
VtValue dictVal = GetDictValueByKey(path, fieldName, keyPath);
if (dictVal.IsHolding<VtDictionary>()) {
VtDictionary const &dict = dictVal.UncheckedGet<VtDictionary>();
result.reserve(dict.size());
TF_FOR_ALL(i, dict)
result.push_back(TfToken(i->first));
}
return result;
}
////////////////////////////////////////////////////////////
SdfAbstractDataSpecVisitor::~SdfAbstractDataSpecVisitor()
{
}
PXR_NAMESPACE_CLOSE_SCOPE
| 27.875306 | 79 | 0.634944 | [
"object",
"vector"
] |
033eb69743bb47ee46cb8eae9a2448f27f812166 | 5,643 | cpp | C++ | src/lidar_measurement_model_likelihood.cpp | doctorwk007/mcl_3dl | 6eda33369a52d09c4f3927e36fd26f8f64fd2ece | [
"BSD-3-Clause"
] | null | null | null | src/lidar_measurement_model_likelihood.cpp | doctorwk007/mcl_3dl | 6eda33369a52d09c4f3927e36fd26f8f64fd2ece | [
"BSD-3-Clause"
] | 1 | 2019-10-23T06:36:32.000Z | 2019-10-23T06:36:32.000Z | src/lidar_measurement_model_likelihood.cpp | yuseidesu/mcl_3dl | 8ff95840b8a51fda367f0bb76e674d3b1b68197b | [
"BSD-3-Clause"
] | 1 | 2019-11-09T03:35:51.000Z | 2019-11-09T03:35:51.000Z | /*
* Copyright (c) 2018, the mcl_3dl authors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDEDNode BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <string>
#include <vector>
#include <ros/ros.h>
#include <pcl/point_types.h>
#include <pcl_ros/point_cloud.h>
#include <mcl_3dl/pf.h>
#include <mcl_3dl/point_cloud_random_sampler.h>
#include <mcl_3dl/point_types.h>
#include <mcl_3dl/vec3.h>
#include <mcl_3dl/lidar_measurement_models/lidar_measurement_model_likelihood.h>
namespace mcl_3dl
{
void LidarMeasurementModelLikelihood::loadConfig(
const ros::NodeHandle& nh,
const std::string& name)
{
ros::NodeHandle pnh(nh, name);
int num_points, num_points_global;
pnh.param("num_points", num_points, 96);
pnh.param("num_points_global", num_points_global, 8);
num_points_default_ = num_points_ = num_points;
num_points_global_ = num_points_global;
double clip_near, clip_far;
pnh.param("clip_near", clip_near, 0.5);
pnh.param("clip_far", clip_far, 10.0);
clip_near_sq_ = clip_near * clip_near;
clip_far_sq_ = clip_far * clip_far;
double clip_z_min, clip_z_max;
pnh.param("clip_z_min", clip_z_min, -2.0);
pnh.param("clip_z_max", clip_z_max, 2.0);
clip_z_min_ = clip_z_min;
clip_z_max_ = clip_z_max;
double match_weight;
pnh.param("match_weight", match_weight, 5.0);
match_weight_ = match_weight;
double match_dist_min, match_dist_flat;
pnh.param("match_dist_min", match_dist_min, 0.2);
pnh.param("match_dist_flat", match_dist_flat, 0.05);
match_dist_min_ = match_dist_min;
match_dist_flat_ = match_dist_flat;
}
void LidarMeasurementModelLikelihood::setGlobalLocalizationStatus(
const size_t num_particles,
const size_t current_num_particles)
{
if (current_num_particles <= num_particles)
{
num_points_ = num_points_default_;
return;
}
size_t num = num_points_default_ * num_particles / current_num_particles;
if (num < num_points_global_)
num = num_points_global_;
num_points_ = num;
}
typename pcl::PointCloud<LidarMeasurementModelBase::PointType>::Ptr
LidarMeasurementModelLikelihood::filter(
const typename pcl::PointCloud<LidarMeasurementModelBase::PointType>::ConstPtr& pc) const
{
const auto local_points_filter = [this](const LidarMeasurementModelBase::PointType& p)
{
if (p.x * p.x + p.y * p.y > clip_far_sq_)
return true;
if (p.x * p.x + p.y * p.y < clip_near_sq_)
return true;
if (p.z < clip_z_min_ || clip_z_max_ < p.z)
return true;
return false;
};
pcl::PointCloud<LidarMeasurementModelBase::PointType>::Ptr pc_filtered(
new pcl::PointCloud<LidarMeasurementModelBase::PointType>);
*pc_filtered = *pc;
pc_filtered->erase(
std::remove_if(pc_filtered->begin(), pc_filtered->end(), local_points_filter), pc_filtered->end());
pc_filtered->width = 1;
pc_filtered->height = pc_filtered->points.size();
return sampler_.sample<LidarMeasurementModelBase::PointType>(pc_filtered, num_points_);
}
LidarMeasurementResult LidarMeasurementModelLikelihood::measure(
typename ChunkedKdtree<LidarMeasurementModelBase::PointType>::Ptr& kdtree,
const typename pcl::PointCloud<LidarMeasurementModelBase::PointType>::ConstPtr& pc,
const std::vector<Vec3>& origins,
const State6DOF& s) const
{
if (!pc)
return LidarMeasurementResult(1, 0);
if (pc->size() == 0)
return LidarMeasurementResult(1, 0);
pcl::PointCloud<LidarMeasurementModelBase::PointType>::Ptr pc_particle(
new pcl::PointCloud<LidarMeasurementModelBase::PointType>);
std::vector<int> id(1);
std::vector<float> sqdist(1);
float score_like = 0;
*pc_particle = *pc;
s.transform(*pc_particle);
size_t num = 0;
for (auto& p : pc_particle->points)
{
if (kdtree->radiusSearch(p, match_dist_min_, id, sqdist, 1))
{
const float dist = match_dist_min_ - std::max(sqrtf(sqdist[0]), match_dist_flat_);
if (dist < 0.0)
continue;
score_like += dist * match_weight_;
num++;
}
}
const float match_ratio = static_cast<float>(num) / pc_particle->points.size();
return LidarMeasurementResult(score_like, match_ratio);
}
} // namespace mcl_3dl
| 35.490566 | 105 | 0.735247 | [
"vector",
"transform"
] |
03480ddb420c242dd5d4b3a0333c8b1b944f337e | 3,304 | inl | C++ | android/spatialiteandroidlibrary/src/main/jni/geos-3.2.2/source/headers/geos/geom/Coordinate.inl | fedort/react-native-spatial | f12fe12c567ecb6c088a2b0cb9468c2f28d4cbba | [
"MIT"
] | null | null | null | android/spatialiteandroidlibrary/src/main/jni/geos-3.2.2/source/headers/geos/geom/Coordinate.inl | fedort/react-native-spatial | f12fe12c567ecb6c088a2b0cb9468c2f28d4cbba | [
"MIT"
] | null | null | null | android/spatialiteandroidlibrary/src/main/jni/geos-3.2.2/source/headers/geos/geom/Coordinate.inl | fedort/react-native-spatial | f12fe12c567ecb6c088a2b0cb9468c2f28d4cbba | [
"MIT"
] | 1 | 2021-01-13T17:59:17.000Z | 2021-01-13T17:59:17.000Z | /**********************************************************************
* $Id: Coordinate.inl 2554 2009-06-06 21:14:51Z strk $
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2005-2006 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************/
#ifndef GEOS_GEOM_COORDINATE_INL
#define GEOS_GEOM_COORDINATE_INL
#include <geos/geom/Coordinate.h>
//#include <geos/geom/PrecisionModel.h> // we need it for makePrecise, possibly to be obsoleted
#include <geos/platform.h> // for DoubleNotANumber
#include <cassert>
#include <cmath>
namespace geos {
namespace geom { // geos::geom
INLINE void
Coordinate::setNull()
{
x=DoubleNotANumber;
y=DoubleNotANumber;
z=DoubleNotANumber;
}
INLINE Coordinate&
Coordinate::getNull()
{
return nullCoord;
}
INLINE bool
Coordinate::isNull() const
{
return (ISNAN(x) && ISNAN(y) && ISNAN(z));
}
INLINE
Coordinate::~Coordinate()
{
}
INLINE
Coordinate::Coordinate(double xNew, double yNew, double zNew)
:
x(xNew),
y(yNew),
z(zNew)
{}
#if 0
INLINE
Coordinate::Coordinate(const Coordinate& c)
:
x(c.x),
y(c.y),
z(c.z)
{
}
INLINE Coordinate&
Coordinate::operator=(const Coordinate &c)
{
if ( this == &c ) return *this;
x=c.x;
y=c.y;
z=c.z;
return *this;
}
#endif
INLINE bool
Coordinate::equals2D(const Coordinate& other) const
{
if (x != other.x) return false;
if (y != other.y) return false;
return true;
}
INLINE bool
Coordinate::equals(const Coordinate& other) const
{
return equals2D(other);
}
INLINE int
Coordinate::compareTo(const Coordinate& other) const
{
if (x < other.x) return -1;
if (x > other.x) return 1;
if (y < other.y) return -1;
if (y > other.y) return 1;
return 0;
}
INLINE bool
Coordinate::equals3D(const Coordinate& other) const
{
return (x == other.x) && ( y == other.y) &&
((z == other.z)||(ISNAN(z) && ISNAN(other.z)));
}
#if 0
INLINE void
Coordinate::makePrecise(const PrecisionModel *pm)
{
x = pm->makePrecise(x);
y = pm->makePrecise(y);
}
#endif
INLINE double
Coordinate::distance(const Coordinate& p) const
{
double dx = x - p.x;
double dy = y - p.y;
return std::sqrt(dx * dx + dy * dy);
}
INLINE int
Coordinate::hashCode() const
{
//Algorithm from Effective Java by Joshua Bloch [Jon Aquino]
int result = 17;
result = 37 * result + hashCode(x);
result = 37 * result + hashCode(y);
return result;
}
/*static*/
INLINE int
Coordinate::hashCode(double d)
{
int64 f = (int64)(d);
return (int)(f^(f>>32));
}
INLINE bool
CoordinateLessThen::operator()(const Coordinate* a, const Coordinate* b) const
{
if (a->compareTo(*b)<0) return true;
else return false;
}
INLINE bool
CoordinateLessThen::operator()(const Coordinate& a, const Coordinate& b) const
{
if (a.compareTo(b)<0) return true;
else return false;
}
INLINE bool
operator==(const Coordinate& a, const Coordinate& b)
{
return a.equals2D(b);
}
INLINE bool
operator!=(const Coordinate& a, const Coordinate& b)
{
return ! a.equals2D(b);
}
} // namespace geos::geom
} // namespace geos
#endif // GEOS_GEOM_COORDINATE_INL
| 18.355556 | 95 | 0.66132 | [
"geometry"
] |
034bf9077325a16d539fcae72364021f3a1f02ff | 863 | cpp | C++ | acwing/1128.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | null | null | null | acwing/1128.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | null | null | null | acwing/1128.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | 2 | 2020-01-01T13:49:08.000Z | 2021-03-06T06:54:26.000Z | #include <iostream>
#include <vector>
using namespace std;
const int INF = 1e5+3;
int n, m;
vector<vector<int>> g;
int dijstra() {
vector<int> dist(n+1, INF);
vector<bool> used(n+1, false);
dist[1] = 0;
for(int i=0; i<n; i++) {
int t = -1;
int cmp = INF;
for(int j=1; j<=n; j++) {
if(used[j]==false && dist[j]<cmp) {
t = j;
cmp = dist[j];
}
}
if(t==-1) return -1;
used[t] = true;
for(int j=1; j<=n; j++) {
if(used[j]==false && g[t][j]!=INF) {
dist[j] = min(dist[j], dist[t]+g[t][j]);
}
}
}
int res = 0;
for(int i=1; i<=n; i++) {
res = max(res, dist[i]);
}
return res;
}
int main(void) {
cin>>n>>m;
g.assign(n+1, vector<int>(n+1, INF));
for(int i=0; i<m; i++) {
int x, y, z;
cin>>x>>y>>z;
if(x!=y) {
g[x][y] = min(g[x][y], z);
g[y][x] = min(g[y][x], z);
}
}
cout<<dijstra()<<endl;
}
| 15.140351 | 44 | 0.479722 | [
"vector"
] |
035361dea276de26cce0f1bdc0e616c7e4a12ab8 | 62,796 | cc | C++ | media/gpu/vaapi/vaapi_video_encode_accelerator.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | media/gpu/vaapi/vaapi_video_encode_accelerator.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | media/gpu/vaapi/vaapi_video_encode_accelerator.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2014 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 "media/gpu/vaapi/vaapi_video_encode_accelerator.h"
#include <string.h>
#include <va/va.h>
#include <va/va_enc_h264.h>
#include <va/va_enc_vp8.h>
#include <algorithm>
#include <memory>
#include <type_traits>
#include <utility>
#include "base/bind.h"
#include "base/bits.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/numerics/safe_conversions.h"
#include "base/stl_util.h"
#include "base/task/post_task.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/format_utils.h"
#include "media/base/unaligned_shared_memory.h"
#include "media/base/video_bitrate_allocation.h"
#include "media/gpu/chromeos/platform_video_frame_utils.h"
#include "media/gpu/h264_dpb.h"
#include "media/gpu/macros.h"
#include "media/gpu/vaapi/h264_encoder.h"
#include "media/gpu/vaapi/vaapi_common.h"
#include "media/gpu/vaapi/vaapi_utils.h"
#include "media/gpu/vaapi/vp8_encoder.h"
#include "media/gpu/vaapi/vp9_encoder.h"
#include "media/gpu/vaapi/vp9_temporal_layers.h"
#include "media/gpu/vp8_reference_frame_vector.h"
#include "media/gpu/vp9_reference_frame_vector.h"
#define NOTIFY_ERROR(error, msg) \
do { \
SetState(kError); \
VLOGF(1) << msg; \
VLOGF(1) << "Calling NotifyError(" << error << ")"; \
NotifyError(error); \
} while (0)
namespace media {
namespace {
// Minimum number of frames in flight for pipeline depth, adjust to this number
// if encoder requests less.
constexpr size_t kMinNumFramesInFlight = 4;
void FillVAEncRateControlParams(
uint32_t bps,
uint32_t window_size,
uint32_t initial_qp,
uint32_t min_qp,
uint32_t max_qp,
uint32_t framerate,
uint32_t buffer_size,
VAEncMiscParameterRateControl& rate_control_param,
VAEncMiscParameterFrameRate& framerate_param,
VAEncMiscParameterHRD& hrd_param) {
memset(&rate_control_param, 0, sizeof(rate_control_param));
rate_control_param.bits_per_second = bps;
rate_control_param.window_size = window_size;
rate_control_param.initial_qp = initial_qp;
rate_control_param.min_qp = min_qp;
rate_control_param.max_qp = max_qp;
rate_control_param.rc_flags.bits.disable_frame_skip = true;
memset(&framerate_param, 0, sizeof(framerate_param));
framerate_param.framerate = framerate;
memset(&hrd_param, 0, sizeof(hrd_param));
hrd_param.buffer_size = buffer_size;
hrd_param.initial_buffer_fullness = buffer_size / 2;
}
// Calculate the size of the allocated buffer aligned to hardware/driver
// requirements.
gfx::Size GetInputFrameSize(VideoPixelFormat format,
const gfx::Size& visible_size) {
// Get a VideoFrameLayout of a graphic buffer with the same gfx::BufferUsage
// as camera stack.
base::Optional<VideoFrameLayout> layout = GetPlatformVideoFrameLayout(
/*gpu_memory_buffer_factory=*/nullptr, format, visible_size,
gfx::BufferUsage::VEA_READ_CAMERA_AND_CPU_READ_WRITE);
if (!layout || layout->planes().empty()) {
VLOGF(1) << "Failed to allocate VideoFrameLayout";
return gfx::Size();
}
int32_t stride = layout->planes()[0].stride;
size_t plane_size = layout->planes()[0].size;
if (stride == 0 || plane_size == 0) {
VLOGF(1) << "Unexpected stride=" << stride << ", plane_size=" << plane_size;
return gfx::Size();
}
return gfx::Size(stride, plane_size / stride);
}
} // namespace
// Encode job for one frame. Created when an input frame is awaiting and
// enough resources are available to proceed. Once the job is prepared and
// submitted to the hardware, it awaits on the |submitted_encode_jobs_| queue
// for an output bitstream buffer to become available. Once one is ready,
// the encoded bytes are downloaded to it, job resources are released
// and become available for reuse.
class VaapiEncodeJob : public AcceleratedVideoEncoder::EncodeJob {
public:
VaapiEncodeJob(scoped_refptr<VideoFrame> input_frame,
bool keyframe,
base::OnceClosure execute_cb,
scoped_refptr<VASurface> input_surface,
scoped_refptr<CodecPicture> picture,
std::unique_ptr<ScopedVABuffer> coded_buffer);
~VaapiEncodeJob() override = default;
VaapiEncodeJob* AsVaapiEncodeJob() override { return this; }
VABufferID coded_buffer_id() const { return coded_buffer_->id(); }
const scoped_refptr<VASurface> input_surface() const {
return input_surface_;
}
const scoped_refptr<CodecPicture> picture() const { return picture_; }
private:
// Input surface for video frame data or scaled data.
const scoped_refptr<VASurface> input_surface_;
const scoped_refptr<CodecPicture> picture_;
// Buffer that will contain the output bitstream data for this frame.
const std::unique_ptr<ScopedVABuffer> coded_buffer_;
DISALLOW_COPY_AND_ASSIGN(VaapiEncodeJob);
};
struct VaapiVideoEncodeAccelerator::InputFrameRef {
InputFrameRef(scoped_refptr<VideoFrame> frame, bool force_keyframe)
: frame(frame), force_keyframe(force_keyframe) {}
const scoped_refptr<VideoFrame> frame;
const bool force_keyframe;
};
struct VaapiVideoEncodeAccelerator::BitstreamBufferRef {
BitstreamBufferRef(int32_t id, BitstreamBuffer buffer)
: id(id),
shm(std::make_unique<UnalignedSharedMemory>(buffer.TakeRegion(),
buffer.size(),
false)),
offset(buffer.offset()) {}
const int32_t id;
const std::unique_ptr<UnalignedSharedMemory> shm;
const off_t offset;
};
VideoEncodeAccelerator::SupportedProfiles
VaapiVideoEncodeAccelerator::GetSupportedProfiles() {
if (IsConfiguredForTesting())
return supported_profiles_for_testing_;
return VaapiWrapper::GetSupportedEncodeProfiles();
}
class VaapiVideoEncodeAccelerator::H264Accelerator
: public H264Encoder::Accelerator {
public:
explicit H264Accelerator(VaapiVideoEncodeAccelerator* vea) : vea_(vea) {}
~H264Accelerator() override = default;
// H264Encoder::Accelerator implementation.
scoped_refptr<H264Picture> GetPicture(
AcceleratedVideoEncoder::EncodeJob* job) override;
bool SubmitPackedHeaders(
AcceleratedVideoEncoder::EncodeJob* job,
scoped_refptr<H264BitstreamBuffer> packed_sps,
scoped_refptr<H264BitstreamBuffer> packed_pps) override;
bool SubmitFrameParameters(
AcceleratedVideoEncoder::EncodeJob* job,
const H264Encoder::EncodeParams& encode_params,
const H264SPS& sps,
const H264PPS& pps,
scoped_refptr<H264Picture> pic,
const std::list<scoped_refptr<H264Picture>>& ref_pic_list0,
const std::list<scoped_refptr<H264Picture>>& ref_pic_list1) override;
private:
VaapiVideoEncodeAccelerator* const vea_;
};
class VaapiVideoEncodeAccelerator::VP8Accelerator
: public VP8Encoder::Accelerator {
public:
explicit VP8Accelerator(VaapiVideoEncodeAccelerator* vea) : vea_(vea) {}
~VP8Accelerator() override = default;
// VP8Encoder::Accelerator implementation.
scoped_refptr<VP8Picture> GetPicture(
AcceleratedVideoEncoder::EncodeJob* job) override;
bool SubmitFrameParameters(AcceleratedVideoEncoder::EncodeJob* job,
const VP8Encoder::EncodeParams& encode_params,
scoped_refptr<VP8Picture> pic,
const Vp8ReferenceFrameVector& ref_frames,
const std::array<bool, kNumVp8ReferenceBuffers>&
ref_frames_used) override;
private:
VaapiVideoEncodeAccelerator* const vea_;
};
class VaapiVideoEncodeAccelerator::VP9Accelerator
: public VP9Encoder::Accelerator {
public:
explicit VP9Accelerator(VaapiVideoEncodeAccelerator* vea) : vea_(vea) {}
~VP9Accelerator() override = default;
// VP9Encoder::Accelerator implementation.
scoped_refptr<VP9Picture> GetPicture(
AcceleratedVideoEncoder::EncodeJob* job) override;
bool SubmitFrameParameters(
AcceleratedVideoEncoder::EncodeJob* job,
const VP9Encoder::EncodeParams& encode_params,
scoped_refptr<VP9Picture> pic,
const Vp9ReferenceFrameVector& ref_frames,
const std::array<bool, kVp9NumRefsPerFrame>& ref_frames_used) override;
private:
VaapiVideoEncodeAccelerator* const vea_;
};
VaapiVideoEncodeAccelerator::VaapiVideoEncodeAccelerator()
: output_buffer_byte_size_(0),
state_(kUninitialized),
child_task_runner_(base::ThreadTaskRunnerHandle::Get()),
// TODO(akahuang): Change to use SequencedTaskRunner to see if the
// performance is affected.
encoder_task_runner_(base::ThreadPool::CreateSingleThreadTaskRunner(
{base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, base::MayBlock()},
base::SingleThreadTaskRunnerThreadMode::DEDICATED)) {
VLOGF(2);
DCHECK_CALLED_ON_VALID_SEQUENCE(child_sequence_checker_);
DETACH_FROM_SEQUENCE(encoder_sequence_checker_);
child_weak_this_ = child_weak_this_factory_.GetWeakPtr();
encoder_weak_this_ = encoder_weak_this_factory_.GetWeakPtr();
// The default value of VideoEncoderInfo of VaapiVideoEncodeAccelerator.
encoder_info_.implementation_name = "VaapiVideoEncodeAccelerator";
encoder_info_.has_trusted_rate_controller = true;
DCHECK(encoder_info_.is_hardware_accelerated);
DCHECK(encoder_info_.supports_native_handle);
DCHECK(!encoder_info_.supports_simulcast);
}
VaapiVideoEncodeAccelerator::~VaapiVideoEncodeAccelerator() {
VLOGF(2);
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
}
CodecPicture* VaapiVideoEncodeAccelerator::GetPictureFromJobForTesting(
VaapiEncodeJob* job) {
return job->picture().get();
}
bool VaapiVideoEncodeAccelerator::Initialize(const Config& config,
Client* client) {
DCHECK_CALLED_ON_VALID_SEQUENCE(child_sequence_checker_);
DCHECK_EQ(state_, kUninitialized);
VLOGF(2) << "Initializing VAVEA, " << config.AsHumanReadableString();
// VaapiVEA supports temporal layers for VP9 only, but we also allow VP8 to
// support VP8 simulcast.
if (config.HasSpatialLayer()) {
VLOGF(1) << "Spatial layer encoding is not yet supported";
return false;
}
client_ptr_factory_.reset(new base::WeakPtrFactory<Client>(client));
client_ = client_ptr_factory_->GetWeakPtr();
VideoCodec codec = VideoCodecProfileToVideoCodec(config.output_profile);
if (codec != kCodecH264 && codec != kCodecVP8 && codec != kCodecVP9) {
VLOGF(1) << "Unsupported profile: "
<< GetProfileName(config.output_profile);
return false;
}
switch (config.input_format) {
case PIXEL_FORMAT_I420:
case PIXEL_FORMAT_NV12:
break;
default:
VLOGF(1) << "Unsupported input format: " << config.input_format;
return false;
}
if (config.storage_type.value_or(Config::StorageType::kShmem) ==
Config::StorageType::kGpuMemoryBuffer) {
#if !defined(USE_OZONE)
VLOGF(1) << "Native mode is only available on OZONE platform.";
return false;
#else
if (config.input_format != PIXEL_FORMAT_NV12) {
// TODO(crbug.com/894381): Support other formats.
VLOGF(1) << "Unsupported format for native input mode: "
<< VideoPixelFormatToString(config.input_format);
return false;
}
native_input_mode_ = true;
#endif // USE_OZONE
}
const SupportedProfiles& profiles = GetSupportedProfiles();
auto profile = find_if(profiles.begin(), profiles.end(),
[output_profile = config.output_profile](
const SupportedProfile& profile) {
return profile.profile == output_profile;
});
if (profile == profiles.end()) {
VLOGF(1) << "Unsupported output profile "
<< GetProfileName(config.output_profile);
return false;
}
if (config.input_visible_size.width() > profile->max_resolution.width() ||
config.input_visible_size.height() > profile->max_resolution.height()) {
VLOGF(1) << "Input size too big: " << config.input_visible_size.ToString()
<< ", max supported size: " << profile->max_resolution.ToString();
return false;
}
DCHECK_EQ(IsConfiguredForTesting(), !!vaapi_wrapper_);
if (!IsConfiguredForTesting()) {
if (vaapi_wrapper_) {
VLOGF(1) << "Initialize() is called twice";
return false;
}
VaapiWrapper::CodecMode mode =
codec == kCodecVP9 ? VaapiWrapper::kEncodeConstantQuantizationParameter
: VaapiWrapper::kEncode;
vaapi_wrapper_ = VaapiWrapper::CreateForVideoCodec(
mode, config.output_profile, EncryptionScheme::kUnencrypted,
base::BindRepeating(&ReportVaapiErrorToUMA,
"Media.VaapiVideoEncodeAccelerator.VAAPIError"));
if (!vaapi_wrapper_) {
VLOGF(1) << "Failed initializing VAAPI for profile "
<< GetProfileName(config.output_profile);
return false;
}
}
// Finish remaining initialization on the encoder thread.
encoder_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&VaapiVideoEncodeAccelerator::InitializeTask,
encoder_weak_this_, config));
return true;
}
void VaapiVideoEncodeAccelerator::InitializeTask(const Config& config) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
DCHECK_EQ(state_, kUninitialized);
VLOGF(2);
output_codec_ = VideoCodecProfileToVideoCodec(config.output_profile);
AcceleratedVideoEncoder::Config ave_config{};
DCHECK_EQ(IsConfiguredForTesting(), !!encoder_);
switch (output_codec_) {
case kCodecH264:
if (!IsConfiguredForTesting()) {
encoder_ = std::make_unique<H264Encoder>(
std::make_unique<H264Accelerator>(this));
}
DCHECK_EQ(ave_config.bitrate_control,
AcceleratedVideoEncoder::BitrateControl::kConstantBitrate);
break;
case kCodecVP8:
if (!IsConfiguredForTesting()) {
encoder_ = std::make_unique<VP8Encoder>(
std::make_unique<VP8Accelerator>(this));
}
DCHECK_EQ(ave_config.bitrate_control,
AcceleratedVideoEncoder::BitrateControl::kConstantBitrate);
break;
case kCodecVP9:
if (!IsConfiguredForTesting()) {
encoder_ = std::make_unique<VP9Encoder>(
std::make_unique<VP9Accelerator>(this));
}
ave_config.bitrate_control = AcceleratedVideoEncoder::BitrateControl::
kConstantQuantizationParameter;
break;
default:
NOTREACHED() << "Unsupported codec type " << GetCodecName(output_codec_);
return;
}
if (!vaapi_wrapper_->GetVAEncMaxNumOfRefFrames(
config.output_profile, &ave_config.max_num_ref_frames)) {
NOTIFY_ERROR(kPlatformFailureError,
"Failed getting max number of reference frames"
"supported by the driver");
return;
}
DCHECK_GT(ave_config.max_num_ref_frames, 0u);
if (!encoder_->Initialize(config, ave_config)) {
NOTIFY_ERROR(kInvalidArgumentError, "Failed initializing encoder");
return;
}
output_buffer_byte_size_ = encoder_->GetBitstreamBufferSize();
va_surface_release_cb_ = BindToCurrentLoop(base::BindRepeating(
&VaapiVideoEncodeAccelerator::RecycleVASurfaceID, encoder_weak_this_));
vpp_va_surface_release_cb_ = BindToCurrentLoop(base::BindRepeating(
&VaapiVideoEncodeAccelerator::RecycleVPPVASurfaceID, encoder_weak_this_));
visible_rect_ = gfx::Rect(config.input_visible_size);
expected_input_coded_size_ = VideoFrame::DetermineAlignedSize(
config.input_format, config.input_visible_size);
DCHECK(
expected_input_coded_size_.width() <= encoder_->GetCodedSize().width() &&
expected_input_coded_size_.height() <= encoder_->GetCodedSize().height());
DCHECK_EQ(IsConfiguredForTesting(), !aligned_va_surface_size_.IsEmpty());
if (!IsConfiguredForTesting()) {
// The aligned VA surface size must be the same as a size of a native
// graphics buffer. Since the VA surface's format is NV12, we specify NV12
// to query the size of the native graphics buffer.
aligned_va_surface_size_ =
GetInputFrameSize(PIXEL_FORMAT_NV12, config.input_visible_size);
if (aligned_va_surface_size_.IsEmpty()) {
NOTIFY_ERROR(kPlatformFailureError, "Failed to get frame size");
return;
}
}
va_surfaces_per_video_frame_ =
native_input_mode_
?
// In native input mode, we do not need surfaces for input frames.
kNumSurfacesForOutputPicture
:
// In non-native mode, we need to create additional surfaces for input
// frames.
kNumSurfacesForOutputPicture + kNumSurfacesPerInputVideoFrame;
// The number of required buffers is the number of required reference frames
// + 1 for the current frame to be encoded.
const size_t max_ref_frames = encoder_->GetMaxNumOfRefFrames();
num_frames_in_flight_ = std::max(kMinNumFramesInFlight, max_ref_frames);
DVLOGF(1) << "Frames in flight: " << num_frames_in_flight_;
// The surface size for the reconstructed surface (and input surface in non
// native input mode) is the coded size.
if (!vaapi_wrapper_->CreateContextAndSurfaces(
kVaSurfaceFormat, encoder_->GetCodedSize(),
VaapiWrapper::SurfaceUsageHint::kVideoEncoder,
(num_frames_in_flight_ + 1) * va_surfaces_per_video_frame_,
&available_va_surface_ids_)) {
NOTIFY_ERROR(kPlatformFailureError, "Failed creating VASurfaces");
return;
}
child_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&Client::RequireBitstreamBuffers, client_,
num_frames_in_flight_, expected_input_coded_size_,
output_buffer_byte_size_));
if (config.HasTemporalLayer()) {
DCHECK(!config.spatial_layers.empty());
encoder_info_.fps_allocation[0] = VP9TemporalLayers::GetFpsAllocation(
config.spatial_layers[0].num_of_temporal_layers);
} else {
constexpr uint8_t kFullFramerate = 255;
encoder_info_.fps_allocation[0] = {kFullFramerate};
}
// Notify VideoEncoderInfo after initialization.
child_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&Client::NotifyEncoderInfoChange, client_, encoder_info_));
SetState(kEncoding);
}
void VaapiVideoEncodeAccelerator::RecycleVASurfaceID(
VASurfaceID va_surface_id) {
DVLOGF(4) << "va_surface_id: " << va_surface_id;
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
available_va_surface_ids_.push_back(va_surface_id);
EncodePendingInputs();
}
void VaapiVideoEncodeAccelerator::RecycleVPPVASurfaceID(
VASurfaceID va_surface_id) {
DVLOGF(4) << "va_surface_id: " << va_surface_id;
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
available_vpp_va_surface_ids_.push_back(va_surface_id);
EncodePendingInputs();
}
void VaapiVideoEncodeAccelerator::ExecuteEncode(VASurfaceID va_surface_id) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
if (!vaapi_wrapper_->ExecuteAndDestroyPendingBuffers(va_surface_id))
NOTIFY_ERROR(kPlatformFailureError, "Failed to execute encode");
}
void VaapiVideoEncodeAccelerator::UploadFrame(
scoped_refptr<VideoFrame> frame,
VASurfaceID va_surface_id,
const gfx::Size& va_surface_size) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
DVLOGF(4) << "frame is uploading: " << va_surface_id;
if (!vaapi_wrapper_->UploadVideoFrameToSurface(*frame, va_surface_id,
va_surface_size))
NOTIFY_ERROR(kPlatformFailureError, "Failed to upload frame");
}
void VaapiVideoEncodeAccelerator::SubmitBuffer(
VABufferType type,
scoped_refptr<base::RefCountedBytes> buffer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
if (!vaapi_wrapper_->SubmitBuffer(type, buffer->size(), buffer->front()))
NOTIFY_ERROR(kPlatformFailureError, "Failed submitting a buffer");
}
void VaapiVideoEncodeAccelerator::SubmitVAEncMiscParamBuffer(
VAEncMiscParameterType type,
scoped_refptr<base::RefCountedBytes> buffer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
const size_t temp_size = sizeof(VAEncMiscParameterBuffer) + buffer->size();
std::vector<uint8_t> temp(temp_size);
auto* const va_buffer =
reinterpret_cast<VAEncMiscParameterBuffer*>(temp.data());
va_buffer->type = type;
memcpy(va_buffer->data, buffer->front(), buffer->size());
if (!vaapi_wrapper_->SubmitBuffer(VAEncMiscParameterBufferType, temp_size,
temp.data())) {
NOTIFY_ERROR(kPlatformFailureError, "Failed submitting a buffer");
}
}
void VaapiVideoEncodeAccelerator::SubmitH264BitstreamBuffer(
scoped_refptr<H264BitstreamBuffer> buffer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
if (!vaapi_wrapper_->SubmitBuffer(VAEncPackedHeaderDataBufferType,
buffer->BytesInBuffer(), buffer->data())) {
NOTIFY_ERROR(kPlatformFailureError, "Failed submitting a bitstream buffer");
}
}
void VaapiVideoEncodeAccelerator::NotifyEncodedChunkSize(
VABufferID buffer_id,
VASurfaceID sync_surface_id) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
const uint64_t encoded_chunk_size =
vaapi_wrapper_->GetEncodedChunkSize(buffer_id, sync_surface_id);
if (encoded_chunk_size == 0)
NOTIFY_ERROR(kPlatformFailureError, "Failed getting an encoded chunksize");
DCHECK(encoder_);
encoder_->BitrateControlUpdate(encoded_chunk_size);
}
void VaapiVideoEncodeAccelerator::TryToReturnBitstreamBuffer() {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
if (state_ != kEncoding)
return;
while (!submitted_encode_jobs_.empty() &&
submitted_encode_jobs_.front() == nullptr) {
// A null job indicates a flush command.
submitted_encode_jobs_.pop();
DVLOGF(2) << "FlushDone";
DCHECK(flush_callback_);
child_task_runner_->PostTask(
FROM_HERE, base::BindOnce(std::move(flush_callback_), true));
}
if (submitted_encode_jobs_.empty() || available_bitstream_buffers_.empty())
return;
auto buffer = std::move(available_bitstream_buffers_.front());
available_bitstream_buffers_.pop();
auto encode_job = std::move(submitted_encode_jobs_.front());
submitted_encode_jobs_.pop();
ReturnBitstreamBuffer(std::move(encode_job), std::move(buffer));
}
void VaapiVideoEncodeAccelerator::ReturnBitstreamBuffer(
std::unique_ptr<VaapiEncodeJob> encode_job,
std::unique_ptr<BitstreamBufferRef> buffer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
const VABufferID coded_buffer_id = encode_job->coded_buffer_id();
uint8_t* target_data = static_cast<uint8_t*>(buffer->shm->memory());
size_t data_size = 0;
if (!vaapi_wrapper_->DownloadFromVABuffer(
coded_buffer_id, encode_job->input_surface()->id(), target_data,
buffer->shm->size(), &data_size)) {
NOTIFY_ERROR(kPlatformFailureError, "Failed downloading coded buffer");
return;
}
DVLOGF(4) << "Returning bitstream buffer "
<< (encode_job->IsKeyframeRequested() ? "(keyframe)" : "")
<< " id: " << buffer->id << " size: " << data_size;
auto metadata = encoder_->GetMetadata(encode_job.get(), data_size);
encode_job.reset();
child_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&Client::BitstreamBufferReady, client_,
buffer->id, std::move(metadata)));
}
void VaapiVideoEncodeAccelerator::Encode(scoped_refptr<VideoFrame> frame,
bool force_keyframe) {
DVLOGF(4) << "Frame timestamp: " << frame->timestamp().InMilliseconds()
<< " force_keyframe: " << force_keyframe;
DCHECK_CALLED_ON_VALID_SEQUENCE(child_sequence_checker_);
encoder_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&VaapiVideoEncodeAccelerator::EncodeTask,
encoder_weak_this_, std::move(frame), force_keyframe));
}
void VaapiVideoEncodeAccelerator::EncodeTask(scoped_refptr<VideoFrame> frame,
bool force_keyframe) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
DCHECK_NE(state_, kUninitialized);
input_queue_.push(
std::make_unique<InputFrameRef>(std::move(frame), force_keyframe));
EncodePendingInputs();
}
std::unique_ptr<VaapiEncodeJob> VaapiVideoEncodeAccelerator::CreateEncodeJob(
scoped_refptr<VideoFrame> frame,
bool force_keyframe) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
if (native_input_mode_ &&
frame->storage_type() != VideoFrame::STORAGE_DMABUFS &&
frame->storage_type() != VideoFrame::STORAGE_GPU_MEMORY_BUFFER) {
NOTIFY_ERROR(kPlatformFailureError,
"Unexpected storage: " << frame->storage_type());
return nullptr;
}
if (available_va_surface_ids_.size() < va_surfaces_per_video_frame_ ||
(vpp_vaapi_wrapper_ && available_vpp_va_surface_ids_.empty())) {
DVLOGF(4) << "Not enough surfaces available";
return nullptr;
}
auto coded_buffer = vaapi_wrapper_->CreateVABuffer(VAEncCodedBufferType,
output_buffer_byte_size_);
if (!coded_buffer) {
NOTIFY_ERROR(kPlatformFailureError, "Failed creating coded buffer");
return nullptr;
}
scoped_refptr<VASurface> input_surface;
if (native_input_mode_) {
if (frame->format() != PIXEL_FORMAT_NV12) {
NOTIFY_ERROR(kPlatformFailureError,
"Expected NV12, got: " << frame->format());
return nullptr;
}
DCHECK(frame);
scoped_refptr<gfx::NativePixmap> pixmap =
CreateNativePixmapDmaBuf(frame.get());
if (!pixmap) {
NOTIFY_ERROR(kPlatformFailureError,
"Failed to create NativePixmap from VideoFrame");
return nullptr;
}
input_surface = vaapi_wrapper_->CreateVASurfaceForPixmap(std::move(pixmap));
if (!input_surface) {
NOTIFY_ERROR(kPlatformFailureError, "Failed to create VASurface");
return nullptr;
}
} else {
if (expected_input_coded_size_ != frame->coded_size()) {
// In non-zero copy mode, the coded size of the incoming frame should be
// the same as the one we requested through
// Client::RequireBitstreamBuffers().
NOTIFY_ERROR(kPlatformFailureError,
"Expected frame coded size: "
<< expected_input_coded_size_.ToString()
<< ", but got: " << frame->coded_size().ToString());
return nullptr;
}
DCHECK_EQ(visible_rect_.origin(), gfx::Point(0, 0));
if (visible_rect_ != frame->visible_rect()) {
// In non-zero copy mode, the client is responsible for scaling and
// cropping.
NOTIFY_ERROR(kPlatformFailureError,
"Expected frame visible rectangle: "
<< visible_rect_.ToString()
<< ", but got: " << frame->visible_rect().ToString());
return nullptr;
}
input_surface = new VASurface(available_va_surface_ids_.back(),
encoder_->GetCodedSize(), kVaSurfaceFormat,
base::BindOnce(va_surface_release_cb_));
available_va_surface_ids_.pop_back();
}
if (visible_rect_ != frame->visible_rect()) {
DCHECK(native_input_mode_);
// Do cropping/scaling. Here the buffer size contained in |input_surface|
// is |frame->coded_size()|.
if (!vpp_vaapi_wrapper_) {
vpp_vaapi_wrapper_ = VaapiWrapper::Create(
VaapiWrapper::kVideoProcess, VAProfileNone,
EncryptionScheme::kUnencrypted,
base::BindRepeating(
&ReportVaapiErrorToUMA,
"Media.VaapiVideoEncodeAccelerator.Vpp.VAAPIError"));
if (!vpp_vaapi_wrapper_) {
NOTIFY_ERROR(kPlatformFailureError,
"Failed to initialize VppVaapiWrapper");
return nullptr;
}
// Allocate the same number of surfaces as reconstructed surfaces.
if (!vpp_vaapi_wrapper_->CreateContextAndSurfaces(
kVaSurfaceFormat, aligned_va_surface_size_,
VaapiWrapper::SurfaceUsageHint::kVideoProcessWrite,
num_frames_in_flight_ + 1, &available_vpp_va_surface_ids_)) {
NOTIFY_ERROR(kPlatformFailureError,
"Failed creating VASurfaces for scaling");
vpp_vaapi_wrapper_ = nullptr;
return nullptr;
};
}
scoped_refptr<VASurface> blit_surface = new VASurface(
available_vpp_va_surface_ids_.back(), aligned_va_surface_size_,
kVaSurfaceFormat, base::BindOnce(vpp_va_surface_release_cb_));
available_vpp_va_surface_ids_.pop_back();
// Crop/Scale the visible area of |frame->visible_rect()| ->
// |visible_rect_|.
if (!vpp_vaapi_wrapper_->BlitSurface(*input_surface, *blit_surface,
frame->visible_rect(),
visible_rect_)) {
NOTIFY_ERROR(
kPlatformFailureError,
"Failed BlitSurface on frame size: "
<< frame->coded_size().ToString()
<< " (visible rect: " << frame->visible_rect().ToString()
<< ") -> frame size: " << aligned_va_surface_size_.ToString()
<< " (visible rect: " << visible_rect_.ToString() << ")");
return nullptr;
}
// We can destroy the original |input_surface| because the buffer is already
// copied to blit_surface.
input_surface = std::move(blit_surface);
}
// Here, the surface size contained in |input_surface| is
// |aligned_va_surface_size_| regardless of scaling in zero-copy mode, and
// encoder_->GetCodedSize().
scoped_refptr<VASurface> reconstructed_surface =
new VASurface(available_va_surface_ids_.back(), encoder_->GetCodedSize(),
kVaSurfaceFormat, base::BindOnce(va_surface_release_cb_));
available_va_surface_ids_.pop_back();
scoped_refptr<CodecPicture> picture;
switch (output_codec_) {
case kCodecH264:
picture = new VaapiH264Picture(std::move(reconstructed_surface));
break;
case kCodecVP8:
picture = new VaapiVP8Picture(std::move(reconstructed_surface));
break;
case kCodecVP9:
picture = new VaapiVP9Picture(std::move(reconstructed_surface));
break;
default:
return nullptr;
}
auto job = std::make_unique<VaapiEncodeJob>(
frame, force_keyframe,
base::BindOnce(&VaapiVideoEncodeAccelerator::ExecuteEncode,
encoder_weak_this_, input_surface->id()),
input_surface, std::move(picture), std::move(coded_buffer));
if (!native_input_mode_) {
job->AddSetupCallback(base::BindOnce(
&VaapiVideoEncodeAccelerator::UploadFrame, encoder_weak_this_, frame,
input_surface->id(), input_surface->size()));
}
return job;
}
void VaapiVideoEncodeAccelerator::EncodePendingInputs() {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
DVLOGF(4);
while (state_ == kEncoding && !input_queue_.empty()) {
const std::unique_ptr<InputFrameRef>& input_frame = input_queue_.front();
// If this is a flush (null) frame, don't create/submit a new encode job for
// it, but forward a null job to the submitted_encode_jobs_ queue.
std::unique_ptr<VaapiEncodeJob> job;
TRACE_EVENT0("media,gpu", "VAVEA::FromCreateEncodeJobToReturn");
if (input_frame) {
job = CreateEncodeJob(input_frame->frame, input_frame->force_keyframe);
if (!job)
return;
}
input_queue_.pop();
if (job && !encoder_->PrepareEncodeJob(job.get())) {
NOTIFY_ERROR(kPlatformFailureError, "Failed preparing an encode job.");
return;
}
TRACE_EVENT0("media,gpu", "VAVEA::FromExecuteToReturn");
if (job) {
TRACE_EVENT0("media,gpu", "VAVEA::Execute");
job->Execute();
}
submitted_encode_jobs_.push(std::move(job));
TryToReturnBitstreamBuffer();
}
}
void VaapiVideoEncodeAccelerator::UseOutputBitstreamBuffer(
BitstreamBuffer buffer) {
DVLOGF(4) << "id: " << buffer.id();
DCHECK_CALLED_ON_VALID_SEQUENCE(child_sequence_checker_);
if (buffer.size() < output_buffer_byte_size_) {
NOTIFY_ERROR(kInvalidArgumentError, "Provided bitstream buffer too small");
return;
}
auto buffer_ref =
std::make_unique<BitstreamBufferRef>(buffer.id(), std::move(buffer));
encoder_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&VaapiVideoEncodeAccelerator::UseOutputBitstreamBufferTask,
encoder_weak_this_, std::move(buffer_ref)));
}
void VaapiVideoEncodeAccelerator::UseOutputBitstreamBufferTask(
std::unique_ptr<BitstreamBufferRef> buffer_ref) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
DCHECK_NE(state_, kUninitialized);
if (!buffer_ref->shm->MapAt(buffer_ref->offset, buffer_ref->shm->size())) {
NOTIFY_ERROR(kPlatformFailureError, "Failed mapping shared memory.");
return;
}
available_bitstream_buffers_.push(std::move(buffer_ref));
TryToReturnBitstreamBuffer();
}
void VaapiVideoEncodeAccelerator::RequestEncodingParametersChange(
uint32_t bitrate,
uint32_t framerate) {
DCHECK_CALLED_ON_VALID_SEQUENCE(child_sequence_checker_);
VideoBitrateAllocation allocation;
allocation.SetBitrate(0, 0, bitrate);
encoder_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&VaapiVideoEncodeAccelerator::RequestEncodingParametersChangeTask,
encoder_weak_this_, allocation, framerate));
}
void VaapiVideoEncodeAccelerator::RequestEncodingParametersChange(
const VideoBitrateAllocation& bitrate_allocation,
uint32_t framerate) {
DCHECK_CALLED_ON_VALID_SEQUENCE(child_sequence_checker_);
encoder_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&VaapiVideoEncodeAccelerator::RequestEncodingParametersChangeTask,
encoder_weak_this_, bitrate_allocation, framerate));
}
void VaapiVideoEncodeAccelerator::RequestEncodingParametersChangeTask(
VideoBitrateAllocation bitrate_allocation,
uint32_t framerate) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
DCHECK_NE(state_, kUninitialized);
if (!encoder_->UpdateRates(bitrate_allocation, framerate)) {
VLOGF(1) << "Failed to update rates to " << bitrate_allocation.GetSumBps()
<< " " << framerate;
}
}
void VaapiVideoEncodeAccelerator::Flush(FlushCallback flush_callback) {
DVLOGF(2);
DCHECK_CALLED_ON_VALID_SEQUENCE(child_sequence_checker_);
encoder_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&VaapiVideoEncodeAccelerator::FlushTask,
encoder_weak_this_, std::move(flush_callback)));
}
void VaapiVideoEncodeAccelerator::FlushTask(FlushCallback flush_callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
if (flush_callback_) {
NOTIFY_ERROR(kIllegalStateError, "There is a pending flush");
child_task_runner_->PostTask(
FROM_HERE, base::BindOnce(std::move(flush_callback), false));
return;
}
flush_callback_ = std::move(flush_callback);
// Insert an null job to indicate a flush command.
input_queue_.push(std::unique_ptr<InputFrameRef>(nullptr));
EncodePendingInputs();
}
bool VaapiVideoEncodeAccelerator::IsFlushSupported() {
return true;
}
void VaapiVideoEncodeAccelerator::Destroy() {
DVLOGF(2);
DCHECK_CALLED_ON_VALID_SEQUENCE(child_sequence_checker_);
child_weak_this_factory_.InvalidateWeakPtrs();
// We're destroying; cancel all callbacks.
client_ptr_factory_.reset();
encoder_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&VaapiVideoEncodeAccelerator::DestroyTask,
encoder_weak_this_));
}
void VaapiVideoEncodeAccelerator::DestroyTask() {
VLOGF(2);
DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_);
encoder_weak_this_factory_.InvalidateWeakPtrs();
if (flush_callback_) {
child_task_runner_->PostTask(
FROM_HERE, base::BindOnce(std::move(flush_callback_), false));
}
// Clean up members that are to be accessed on the encoder thread only.
if (vaapi_wrapper_)
vaapi_wrapper_->DestroyContextAndSurfaces(available_va_surface_ids_);
if (vpp_vaapi_wrapper_) {
vpp_vaapi_wrapper_->DestroyContextAndSurfaces(
available_vpp_va_surface_ids_);
}
available_va_buffer_ids_.clear();
while (!available_bitstream_buffers_.empty())
available_bitstream_buffers_.pop();
while (!input_queue_.empty())
input_queue_.pop();
// Note ScopedVABuffer in VaapiEncodeJob must be destroyed before
// |vaapi_wrapper_| is destroyed to ensure VADisplay is valid on the
// ScopedVABuffer's destruction.
DCHECK(vaapi_wrapper_ || submitted_encode_jobs_.empty());
while (!submitted_encode_jobs_.empty())
submitted_encode_jobs_.pop();
encoder_ = nullptr;
delete this;
}
void VaapiVideoEncodeAccelerator::SetState(State state) {
// Only touch state on encoder thread, unless it's not running.
if (!encoder_task_runner_->BelongsToCurrentThread()) {
encoder_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&VaapiVideoEncodeAccelerator::SetState,
encoder_weak_this_, state));
return;
}
VLOGF(2) << "setting state to: " << state;
state_ = state;
}
void VaapiVideoEncodeAccelerator::NotifyError(Error error) {
if (!child_task_runner_->BelongsToCurrentThread()) {
child_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&VaapiVideoEncodeAccelerator::NotifyError,
child_weak_this_, error));
return;
}
if (client_) {
client_->NotifyError(error);
client_ptr_factory_.reset();
}
}
VaapiEncodeJob::VaapiEncodeJob(scoped_refptr<VideoFrame> input_frame,
bool keyframe,
base::OnceClosure execute_cb,
scoped_refptr<VASurface> input_surface,
scoped_refptr<CodecPicture> picture,
std::unique_ptr<ScopedVABuffer> coded_buffer)
: EncodeJob(input_frame, keyframe, std::move(execute_cb)),
input_surface_(input_surface),
picture_(std::move(picture)),
coded_buffer_(std::move(coded_buffer)) {
DCHECK(input_surface_);
DCHECK(picture_);
DCHECK(coded_buffer_);
}
static void InitVAPictureH264(VAPictureH264* va_pic) {
*va_pic = {};
va_pic->picture_id = VA_INVALID_ID;
va_pic->flags = VA_PICTURE_H264_INVALID;
}
static scoped_refptr<base::RefCountedBytes> MakeRefCountedBytes(void* ptr,
size_t size) {
return base::MakeRefCounted<base::RefCountedBytes>(
reinterpret_cast<uint8_t*>(ptr), size);
}
bool VaapiVideoEncodeAccelerator::H264Accelerator::SubmitFrameParameters(
AcceleratedVideoEncoder::EncodeJob* job,
const H264Encoder::EncodeParams& encode_params,
const H264SPS& sps,
const H264PPS& pps,
scoped_refptr<H264Picture> pic,
const std::list<scoped_refptr<H264Picture>>& ref_pic_list0,
const std::list<scoped_refptr<H264Picture>>& ref_pic_list1) {
VAEncSequenceParameterBufferH264 seq_param = {};
#define SPS_TO_SP(a) seq_param.a = sps.a;
SPS_TO_SP(seq_parameter_set_id);
SPS_TO_SP(level_idc);
seq_param.intra_period = encode_params.i_period_frames;
seq_param.intra_idr_period = encode_params.idr_period_frames;
seq_param.ip_period = encode_params.ip_period_frames;
seq_param.bits_per_second = encode_params.bitrate_bps;
SPS_TO_SP(max_num_ref_frames);
base::Optional<gfx::Size> coded_size = sps.GetCodedSize();
if (!coded_size) {
DVLOGF(1) << "Invalid coded size";
return false;
}
constexpr int kH264MacroblockSizeInPixels = 16;
seq_param.picture_width_in_mbs =
coded_size->width() / kH264MacroblockSizeInPixels;
seq_param.picture_height_in_mbs =
coded_size->height() / kH264MacroblockSizeInPixels;
#define SPS_TO_SP_FS(a) seq_param.seq_fields.bits.a = sps.a;
SPS_TO_SP_FS(chroma_format_idc);
SPS_TO_SP_FS(frame_mbs_only_flag);
SPS_TO_SP_FS(log2_max_frame_num_minus4);
SPS_TO_SP_FS(pic_order_cnt_type);
SPS_TO_SP_FS(log2_max_pic_order_cnt_lsb_minus4);
#undef SPS_TO_SP_FS
SPS_TO_SP(bit_depth_luma_minus8);
SPS_TO_SP(bit_depth_chroma_minus8);
SPS_TO_SP(frame_cropping_flag);
if (sps.frame_cropping_flag) {
SPS_TO_SP(frame_crop_left_offset);
SPS_TO_SP(frame_crop_right_offset);
SPS_TO_SP(frame_crop_top_offset);
SPS_TO_SP(frame_crop_bottom_offset);
}
SPS_TO_SP(vui_parameters_present_flag);
#define SPS_TO_SP_VF(a) seq_param.vui_fields.bits.a = sps.a;
SPS_TO_SP_VF(timing_info_present_flag);
#undef SPS_TO_SP_VF
SPS_TO_SP(num_units_in_tick);
SPS_TO_SP(time_scale);
#undef SPS_TO_SP
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitBuffer,
base::Unretained(vea_), VAEncSequenceParameterBufferType,
MakeRefCountedBytes(&seq_param, sizeof(seq_param))));
VAEncPictureParameterBufferH264 pic_param = {};
auto va_surface_id = pic->AsVaapiH264Picture()->GetVASurfaceID();
pic_param.CurrPic.picture_id = va_surface_id;
pic_param.CurrPic.TopFieldOrderCnt = pic->top_field_order_cnt;
pic_param.CurrPic.BottomFieldOrderCnt = pic->bottom_field_order_cnt;
pic_param.CurrPic.flags = 0;
pic_param.coded_buf = job->AsVaapiEncodeJob()->coded_buffer_id();
pic_param.pic_parameter_set_id = pps.pic_parameter_set_id;
pic_param.seq_parameter_set_id = pps.seq_parameter_set_id;
pic_param.frame_num = pic->frame_num;
pic_param.pic_init_qp = pps.pic_init_qp_minus26 + 26;
pic_param.num_ref_idx_l0_active_minus1 =
pps.num_ref_idx_l0_default_active_minus1;
pic_param.pic_fields.bits.idr_pic_flag = pic->idr;
pic_param.pic_fields.bits.reference_pic_flag = pic->ref;
#define PPS_TO_PP_PF(a) pic_param.pic_fields.bits.a = pps.a;
PPS_TO_PP_PF(entropy_coding_mode_flag);
PPS_TO_PP_PF(transform_8x8_mode_flag);
PPS_TO_PP_PF(deblocking_filter_control_present_flag);
#undef PPS_TO_PP_PF
VAEncSliceParameterBufferH264 slice_param = {};
slice_param.num_macroblocks =
seq_param.picture_width_in_mbs * seq_param.picture_height_in_mbs;
slice_param.macroblock_info = VA_INVALID_ID;
slice_param.slice_type = pic->type;
slice_param.pic_parameter_set_id = pps.pic_parameter_set_id;
slice_param.idr_pic_id = pic->idr_pic_id;
slice_param.pic_order_cnt_lsb = pic->pic_order_cnt_lsb;
slice_param.num_ref_idx_active_override_flag = true;
for (size_t i = 0; i < base::size(pic_param.ReferenceFrames); ++i)
InitVAPictureH264(&pic_param.ReferenceFrames[i]);
for (size_t i = 0; i < base::size(slice_param.RefPicList0); ++i)
InitVAPictureH264(&slice_param.RefPicList0[i]);
for (size_t i = 0; i < base::size(slice_param.RefPicList1); ++i)
InitVAPictureH264(&slice_param.RefPicList1[i]);
VAPictureH264* ref_frames_entry = pic_param.ReferenceFrames;
VAPictureH264* ref_list_entry = slice_param.RefPicList0;
// Initialize the current entry on slice and picture reference lists to
// |ref_pic| and advance list pointers.
auto fill_ref_frame = [&ref_frames_entry,
&ref_list_entry](scoped_refptr<H264Picture> ref_pic) {
VAPictureH264 va_pic_h264;
InitVAPictureH264(&va_pic_h264);
va_pic_h264.picture_id = ref_pic->AsVaapiH264Picture()->GetVASurfaceID();
va_pic_h264.flags = 0;
*ref_frames_entry = va_pic_h264;
*ref_list_entry = va_pic_h264;
++ref_frames_entry;
++ref_list_entry;
};
// Fill slice_param.RefPicList{0,1} with pictures from ref_pic_list{0,1},
// respectively, and pic_param.ReferenceFrames with entries from both.
std::for_each(ref_pic_list0.begin(), ref_pic_list0.end(), fill_ref_frame);
ref_list_entry = slice_param.RefPicList1;
std::for_each(ref_pic_list1.begin(), ref_pic_list1.end(), fill_ref_frame);
VAEncMiscParameterRateControl rate_control_param;
VAEncMiscParameterFrameRate framerate_param;
VAEncMiscParameterHRD hrd_param;
FillVAEncRateControlParams(
encode_params.bitrate_bps,
base::strict_cast<uint32_t>(encode_params.cpb_window_size_ms),
base::strict_cast<uint32_t>(pic_param.pic_init_qp),
base::strict_cast<uint32_t>(encode_params.min_qp),
base::strict_cast<uint32_t>(encode_params.max_qp),
encode_params.framerate,
base::strict_cast<uint32_t>(encode_params.cpb_size_bits),
rate_control_param, framerate_param, hrd_param);
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitBuffer,
base::Unretained(vea_), VAEncPictureParameterBufferType,
MakeRefCountedBytes(&pic_param, sizeof(pic_param))));
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitBuffer,
base::Unretained(vea_), VAEncSliceParameterBufferType,
MakeRefCountedBytes(&slice_param, sizeof(slice_param))));
job->AddSetupCallback(base::BindOnce(
&VaapiVideoEncodeAccelerator::SubmitVAEncMiscParamBuffer,
base::Unretained(vea_), VAEncMiscParameterTypeRateControl,
MakeRefCountedBytes(&rate_control_param, sizeof(rate_control_param))));
job->AddSetupCallback(base::BindOnce(
&VaapiVideoEncodeAccelerator::SubmitVAEncMiscParamBuffer,
base::Unretained(vea_), VAEncMiscParameterTypeFrameRate,
MakeRefCountedBytes(&framerate_param, sizeof(framerate_param))));
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitVAEncMiscParamBuffer,
base::Unretained(vea_), VAEncMiscParameterTypeHRD,
MakeRefCountedBytes(&hrd_param, sizeof(hrd_param))));
return true;
}
scoped_refptr<H264Picture>
VaapiVideoEncodeAccelerator::H264Accelerator::GetPicture(
AcceleratedVideoEncoder::EncodeJob* job) {
return base::WrapRefCounted(
reinterpret_cast<H264Picture*>(job->AsVaapiEncodeJob()->picture().get()));
}
bool VaapiVideoEncodeAccelerator::H264Accelerator::SubmitPackedHeaders(
AcceleratedVideoEncoder::EncodeJob* job,
scoped_refptr<H264BitstreamBuffer> packed_sps,
scoped_refptr<H264BitstreamBuffer> packed_pps) {
// Submit SPS.
VAEncPackedHeaderParameterBuffer par_buffer = {};
par_buffer.type = VAEncPackedHeaderSequence;
par_buffer.bit_length = packed_sps->BytesInBuffer() * 8;
job->AddSetupCallback(base::BindOnce(
&VaapiVideoEncodeAccelerator::SubmitBuffer, base::Unretained(vea_),
VAEncPackedHeaderParameterBufferType,
MakeRefCountedBytes(&par_buffer, sizeof(par_buffer))));
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitH264BitstreamBuffer,
base::Unretained(vea_), packed_sps));
// Submit PPS.
par_buffer = {};
par_buffer.type = VAEncPackedHeaderPicture;
par_buffer.bit_length = packed_pps->BytesInBuffer() * 8;
job->AddSetupCallback(base::BindOnce(
&VaapiVideoEncodeAccelerator::SubmitBuffer, base::Unretained(vea_),
VAEncPackedHeaderParameterBufferType,
MakeRefCountedBytes(&par_buffer, sizeof(par_buffer))));
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitH264BitstreamBuffer,
base::Unretained(vea_), packed_pps));
return true;
}
scoped_refptr<VP8Picture>
VaapiVideoEncodeAccelerator::VP8Accelerator::GetPicture(
AcceleratedVideoEncoder::EncodeJob* job) {
return base::WrapRefCounted(
reinterpret_cast<VP8Picture*>(job->AsVaapiEncodeJob()->picture().get()));
}
bool VaapiVideoEncodeAccelerator::VP8Accelerator::SubmitFrameParameters(
AcceleratedVideoEncoder::EncodeJob* job,
const VP8Encoder::EncodeParams& encode_params,
scoped_refptr<VP8Picture> pic,
const Vp8ReferenceFrameVector& ref_frames,
const std::array<bool, kNumVp8ReferenceBuffers>& ref_frames_used) {
VAEncSequenceParameterBufferVP8 seq_param = {};
const auto& frame_header = pic->frame_hdr;
seq_param.frame_width = frame_header->width;
seq_param.frame_height = frame_header->height;
seq_param.frame_width_scale = frame_header->horizontal_scale;
seq_param.frame_height_scale = frame_header->vertical_scale;
seq_param.error_resilient = 1;
seq_param.bits_per_second = encode_params.bitrate_allocation.GetSumBps();
seq_param.intra_period = encode_params.kf_period_frames;
VAEncPictureParameterBufferVP8 pic_param = {};
pic_param.reconstructed_frame = pic->AsVaapiVP8Picture()->GetVASurfaceID();
DCHECK_NE(pic_param.reconstructed_frame, VA_INVALID_ID);
auto last_frame = ref_frames.GetFrame(Vp8RefType::VP8_FRAME_LAST);
pic_param.ref_last_frame =
last_frame ? last_frame->AsVaapiVP8Picture()->GetVASurfaceID()
: VA_INVALID_ID;
auto golden_frame = ref_frames.GetFrame(Vp8RefType::VP8_FRAME_GOLDEN);
pic_param.ref_gf_frame =
golden_frame ? golden_frame->AsVaapiVP8Picture()->GetVASurfaceID()
: VA_INVALID_ID;
auto alt_frame = ref_frames.GetFrame(Vp8RefType::VP8_FRAME_ALTREF);
pic_param.ref_arf_frame =
alt_frame ? alt_frame->AsVaapiVP8Picture()->GetVASurfaceID()
: VA_INVALID_ID;
pic_param.coded_buf = job->AsVaapiEncodeJob()->coded_buffer_id();
DCHECK_NE(pic_param.coded_buf, VA_INVALID_ID);
pic_param.ref_flags.bits.no_ref_last =
!ref_frames_used[Vp8RefType::VP8_FRAME_LAST];
pic_param.ref_flags.bits.no_ref_gf =
!ref_frames_used[Vp8RefType::VP8_FRAME_GOLDEN];
pic_param.ref_flags.bits.no_ref_arf =
!ref_frames_used[Vp8RefType::VP8_FRAME_ALTREF];
if (frame_header->IsKeyframe()) {
pic_param.ref_flags.bits.force_kf = true;
}
pic_param.pic_flags.bits.frame_type = frame_header->frame_type;
pic_param.pic_flags.bits.version = frame_header->version;
pic_param.pic_flags.bits.show_frame = frame_header->show_frame;
pic_param.pic_flags.bits.loop_filter_type = frame_header->loopfilter_hdr.type;
pic_param.pic_flags.bits.num_token_partitions =
frame_header->num_of_dct_partitions;
pic_param.pic_flags.bits.segmentation_enabled =
frame_header->segmentation_hdr.segmentation_enabled;
pic_param.pic_flags.bits.update_mb_segmentation_map =
frame_header->segmentation_hdr.update_mb_segmentation_map;
pic_param.pic_flags.bits.update_segment_feature_data =
frame_header->segmentation_hdr.update_segment_feature_data;
pic_param.pic_flags.bits.loop_filter_adj_enable =
frame_header->loopfilter_hdr.loop_filter_adj_enable;
pic_param.pic_flags.bits.refresh_entropy_probs =
frame_header->refresh_entropy_probs;
pic_param.pic_flags.bits.refresh_golden_frame =
frame_header->refresh_golden_frame;
pic_param.pic_flags.bits.refresh_alternate_frame =
frame_header->refresh_alternate_frame;
pic_param.pic_flags.bits.refresh_last = frame_header->refresh_last;
pic_param.pic_flags.bits.copy_buffer_to_golden =
frame_header->copy_buffer_to_golden;
pic_param.pic_flags.bits.copy_buffer_to_alternate =
frame_header->copy_buffer_to_alternate;
pic_param.pic_flags.bits.sign_bias_golden = frame_header->sign_bias_golden;
pic_param.pic_flags.bits.sign_bias_alternate =
frame_header->sign_bias_alternate;
pic_param.pic_flags.bits.mb_no_coeff_skip = frame_header->mb_no_skip_coeff;
if (frame_header->IsKeyframe())
pic_param.pic_flags.bits.forced_lf_adjustment = true;
static_assert(std::extent<decltype(pic_param.loop_filter_level)>() ==
std::extent<decltype(pic_param.ref_lf_delta)>() &&
std::extent<decltype(pic_param.ref_lf_delta)>() ==
std::extent<decltype(pic_param.mode_lf_delta)>() &&
std::extent<decltype(pic_param.ref_lf_delta)>() ==
std::extent<decltype(
frame_header->loopfilter_hdr.ref_frame_delta)>() &&
std::extent<decltype(pic_param.mode_lf_delta)>() ==
std::extent<decltype(
frame_header->loopfilter_hdr.mb_mode_delta)>(),
"Invalid loop filter array sizes");
for (size_t i = 0; i < base::size(pic_param.loop_filter_level); ++i) {
pic_param.loop_filter_level[i] = frame_header->loopfilter_hdr.level;
pic_param.ref_lf_delta[i] = frame_header->loopfilter_hdr.ref_frame_delta[i];
pic_param.mode_lf_delta[i] = frame_header->loopfilter_hdr.mb_mode_delta[i];
}
pic_param.sharpness_level = frame_header->loopfilter_hdr.sharpness_level;
pic_param.clamp_qindex_high = encode_params.max_qp;
pic_param.clamp_qindex_low = encode_params.min_qp;
VAQMatrixBufferVP8 qmatrix_buf = {};
for (size_t i = 0; i < base::size(qmatrix_buf.quantization_index); ++i)
qmatrix_buf.quantization_index[i] = frame_header->quantization_hdr.y_ac_qi;
qmatrix_buf.quantization_index_delta[0] =
frame_header->quantization_hdr.y_dc_delta;
qmatrix_buf.quantization_index_delta[1] =
frame_header->quantization_hdr.y2_dc_delta;
qmatrix_buf.quantization_index_delta[2] =
frame_header->quantization_hdr.y2_ac_delta;
qmatrix_buf.quantization_index_delta[3] =
frame_header->quantization_hdr.uv_dc_delta;
qmatrix_buf.quantization_index_delta[4] =
frame_header->quantization_hdr.uv_ac_delta;
VAEncMiscParameterRateControl rate_control_param;
VAEncMiscParameterFrameRate framerate_param;
VAEncMiscParameterHRD hrd_param;
FillVAEncRateControlParams(
base::checked_cast<uint32_t>(
encode_params.bitrate_allocation.GetSumBps()),
base::strict_cast<uint32_t>(encode_params.cpb_window_size_ms),
base::strict_cast<uint32_t>(encode_params.initial_qp),
base::strict_cast<uint32_t>(encode_params.min_qp),
base::strict_cast<uint32_t>(encode_params.max_qp),
encode_params.framerate,
base::strict_cast<uint32_t>(encode_params.cpb_size_bits),
rate_control_param, framerate_param, hrd_param);
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitBuffer,
base::Unretained(vea_), VAEncSequenceParameterBufferType,
MakeRefCountedBytes(&seq_param, sizeof(seq_param))));
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitBuffer,
base::Unretained(vea_), VAEncPictureParameterBufferType,
MakeRefCountedBytes(&pic_param, sizeof(pic_param))));
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitBuffer,
base::Unretained(vea_), VAQMatrixBufferType,
MakeRefCountedBytes(&qmatrix_buf, sizeof(qmatrix_buf))));
job->AddSetupCallback(base::BindOnce(
&VaapiVideoEncodeAccelerator::SubmitVAEncMiscParamBuffer,
base::Unretained(vea_), VAEncMiscParameterTypeRateControl,
MakeRefCountedBytes(&rate_control_param, sizeof(rate_control_param))));
job->AddSetupCallback(base::BindOnce(
&VaapiVideoEncodeAccelerator::SubmitVAEncMiscParamBuffer,
base::Unretained(vea_), VAEncMiscParameterTypeFrameRate,
MakeRefCountedBytes(&framerate_param, sizeof(framerate_param))));
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitVAEncMiscParamBuffer,
base::Unretained(vea_), VAEncMiscParameterTypeHRD,
MakeRefCountedBytes(&hrd_param, sizeof(hrd_param))));
return true;
}
scoped_refptr<VP9Picture>
VaapiVideoEncodeAccelerator::VP9Accelerator::GetPicture(
AcceleratedVideoEncoder::EncodeJob* job) {
return base::WrapRefCounted(
reinterpret_cast<VP9Picture*>(job->AsVaapiEncodeJob()->picture().get()));
}
bool VaapiVideoEncodeAccelerator::VP9Accelerator::SubmitFrameParameters(
AcceleratedVideoEncoder::EncodeJob* job,
const VP9Encoder::EncodeParams& encode_params,
scoped_refptr<VP9Picture> pic,
const Vp9ReferenceFrameVector& ref_frames,
const std::array<bool, kVp9NumRefsPerFrame>& ref_frames_used) {
VAEncSequenceParameterBufferVP9 seq_param = {};
const auto& frame_header = pic->frame_hdr;
// TODO(crbug.com/811912): Double check whether the
// max_frame_width or max_frame_height affects any of the memory
// allocation and tighten these values based on that.
constexpr gfx::Size kMaxFrameSize(4096, 4096);
seq_param.max_frame_width = kMaxFrameSize.height();
seq_param.max_frame_height = kMaxFrameSize.width();
seq_param.bits_per_second = encode_params.bitrate_allocation.GetSumBps();
seq_param.intra_period = encode_params.kf_period_frames;
VAEncPictureParameterBufferVP9 pic_param = {};
pic_param.frame_width_src = frame_header->frame_width;
pic_param.frame_height_src = frame_header->frame_height;
pic_param.frame_width_dst = frame_header->render_width;
pic_param.frame_height_dst = frame_header->render_height;
pic_param.reconstructed_frame = pic->AsVaapiVP9Picture()->GetVASurfaceID();
DCHECK_NE(pic_param.reconstructed_frame, VA_INVALID_ID);
for (size_t i = 0; i < kVp9NumRefFrames; i++) {
auto ref_pic = ref_frames.GetFrame(i);
pic_param.reference_frames[i] =
ref_pic ? ref_pic->AsVaapiVP9Picture()->GetVASurfaceID()
: VA_INVALID_ID;
}
pic_param.coded_buf = job->AsVaapiEncodeJob()->coded_buffer_id();
DCHECK_NE(pic_param.coded_buf, VA_INVALID_ID);
if (frame_header->IsKeyframe()) {
pic_param.ref_flags.bits.force_kf = true;
} else {
// Non-key frame mode, the frame has at least 1 reference frames.
size_t first_used_ref_frame = 3;
for (size_t i = 0; i < kVp9NumRefsPerFrame; i++) {
if (ref_frames_used[i]) {
first_used_ref_frame = std::min(first_used_ref_frame, i);
pic_param.ref_flags.bits.ref_frame_ctrl_l0 |= (1 << i);
}
}
CHECK_LT(first_used_ref_frame, 3u);
pic_param.ref_flags.bits.ref_last_idx =
ref_frames_used[0] ? frame_header->ref_frame_idx[0]
: frame_header->ref_frame_idx[first_used_ref_frame];
pic_param.ref_flags.bits.ref_gf_idx =
ref_frames_used[1] ? frame_header->ref_frame_idx[1]
: frame_header->ref_frame_idx[first_used_ref_frame];
pic_param.ref_flags.bits.ref_arf_idx =
ref_frames_used[2] ? frame_header->ref_frame_idx[2]
: frame_header->ref_frame_idx[first_used_ref_frame];
}
pic_param.pic_flags.bits.frame_type = frame_header->frame_type;
pic_param.pic_flags.bits.show_frame = frame_header->show_frame;
pic_param.pic_flags.bits.error_resilient_mode =
frame_header->error_resilient_mode;
pic_param.pic_flags.bits.intra_only = frame_header->intra_only;
pic_param.pic_flags.bits.allow_high_precision_mv =
frame_header->allow_high_precision_mv;
pic_param.pic_flags.bits.mcomp_filter_type =
frame_header->interpolation_filter;
pic_param.pic_flags.bits.frame_parallel_decoding_mode =
frame_header->frame_parallel_decoding_mode;
pic_param.pic_flags.bits.reset_frame_context =
frame_header->reset_frame_context;
pic_param.pic_flags.bits.refresh_frame_context =
frame_header->refresh_frame_context;
pic_param.pic_flags.bits.frame_context_idx = frame_header->frame_context_idx;
pic_param.refresh_frame_flags = frame_header->refresh_frame_flags;
pic_param.luma_ac_qindex = frame_header->quant_params.base_q_idx;
pic_param.luma_dc_qindex_delta = frame_header->quant_params.delta_q_y_dc;
pic_param.chroma_ac_qindex_delta = frame_header->quant_params.delta_q_uv_ac;
pic_param.chroma_dc_qindex_delta = frame_header->quant_params.delta_q_uv_dc;
pic_param.filter_level = frame_header->loop_filter.level;
pic_param.log2_tile_rows = frame_header->tile_rows_log2;
pic_param.log2_tile_columns = frame_header->tile_cols_log2;
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitBuffer,
base::Unretained(vea_), VAEncSequenceParameterBufferType,
MakeRefCountedBytes(&seq_param, sizeof(seq_param))));
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitBuffer,
base::Unretained(vea_), VAEncPictureParameterBufferType,
MakeRefCountedBytes(&pic_param, sizeof(pic_param))));
if (bitrate_control_ ==
AcceleratedVideoEncoder::BitrateControl::kConstantQuantizationParameter) {
job->AddPostExecuteCallback(base::BindOnce(
&VaapiVideoEncodeAccelerator::NotifyEncodedChunkSize,
base::Unretained(vea_), job->AsVaapiEncodeJob()->coded_buffer_id(),
job->AsVaapiEncodeJob()->input_surface()->id()));
return true;
}
VAEncMiscParameterRateControl rate_control_param;
VAEncMiscParameterFrameRate framerate_param;
VAEncMiscParameterHRD hrd_param;
FillVAEncRateControlParams(
base::checked_cast<uint32_t>(
encode_params.bitrate_allocation.GetSumBps()),
base::strict_cast<uint32_t>(encode_params.cpb_window_size_ms),
base::strict_cast<uint32_t>(encode_params.initial_qp),
base::strict_cast<uint32_t>(encode_params.min_qp),
base::strict_cast<uint32_t>(encode_params.max_qp),
encode_params.framerate,
base::strict_cast<uint32_t>(encode_params.cpb_size_bits),
rate_control_param, framerate_param, hrd_param);
job->AddSetupCallback(base::BindOnce(
&VaapiVideoEncodeAccelerator::SubmitVAEncMiscParamBuffer,
base::Unretained(vea_), VAEncMiscParameterTypeRateControl,
MakeRefCountedBytes(&rate_control_param, sizeof(rate_control_param))));
job->AddSetupCallback(base::BindOnce(
&VaapiVideoEncodeAccelerator::SubmitVAEncMiscParamBuffer,
base::Unretained(vea_), VAEncMiscParameterTypeFrameRate,
MakeRefCountedBytes(&framerate_param, sizeof(framerate_param))));
job->AddSetupCallback(
base::BindOnce(&VaapiVideoEncodeAccelerator::SubmitVAEncMiscParamBuffer,
base::Unretained(vea_), VAEncMiscParameterTypeHRD,
MakeRefCountedBytes(&hrd_param, sizeof(hrd_param))));
return true;
}
} // namespace media
| 39.052239 | 80 | 0.722259 | [
"vector"
] |
0355acd89f119a29105d1a580545fd980a757537 | 3,163 | cpp | C++ | examples/p1897.cpp | Chlorie/libunifex | 9869196338016939265964b82c7244915de6a12f | [
"Apache-2.0"
] | 1 | 2021-11-23T11:30:39.000Z | 2021-11-23T11:30:39.000Z | examples/p1897.cpp | Chlorie/libunifex | 9869196338016939265964b82c7244915de6a12f | [
"Apache-2.0"
] | null | null | null | examples/p1897.cpp | Chlorie/libunifex | 9869196338016939265964b82c7244915de6a12f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <unifex/just.hpp>
#include <unifex/let.hpp>
#include <unifex/transform.hpp>
#include <unifex/scheduler_concepts.hpp>
#include <unifex/sync_wait.hpp>
#include <unifex/timed_single_thread_context.hpp>
#include <unifex/indexed_for.hpp>
#include <unifex/when_all.hpp>
#include <chrono>
#include <iostream>
using namespace unifex;
using namespace std::chrono;
using namespace std::chrono_literals;
namespace execution {
class sequenced_policy {};
class parallel_policy{};
inline constexpr sequenced_policy seq{};
inline constexpr parallel_policy par{};
}
namespace ranges {
struct int_iterator {
using value_type = int;
using reference = value_type&;
using difference_type = size_t;
using pointer = value_type*;
using iterator_category = std::random_access_iterator_tag;
int operator[](size_t offset) const {
return base_ + static_cast<int>(offset);
}
int operator*() const {
return base_;
}
int_iterator operator++() {
++base_;
return *this;
}
int_iterator operator++(int) {
auto cur = *this;
++base_;
return cur;
}
bool operator!=(const int_iterator& rhs) const {
return base_ != rhs.base_;
}
int base_;
};
struct iota_view {
int size_;
using iterator = int_iterator;
int_iterator begin() {
return int_iterator{0};
}
int_iterator end() {
return int_iterator{size_};
}
size_t size() const {
return size_;
}
};
} // namespace ranges
int main() {
// use seq, which supports a forward range
auto result = sync_wait(indexed_for(
just(42),
execution::seq,
ranges::iota_view{10},
[](int idx, int& x) {
x = x + idx;
}));
std::cout << "all done " << *result << "\n";
// indexed_for example from P1897R2:
auto just_sender =
just(std::vector<int>{3, 4, 5}, 10);
// Use par which requires range to be random access
auto indexed_for_sender =
indexed_for(
std::move(just_sender),
execution::par,
ranges::iota_view{3},
[](int idx, std::vector<int>& vec, const int& i){
vec[idx] = vec[idx] + i + idx;
});
auto transform_sender = transform(
std::move(indexed_for_sender), [](std::vector<int> vec, int /*i*/){return vec;});
// Slight difference from p1897R2 because unifex's sync_wait returns an optional
// to account for cancellation
std::vector<int> vector_result =
*sync_wait(std::move(transform_sender));
std::cout << "vector result:\n";
for(auto v : vector_result) {
std::cout << "\t" << v << "\n";
}
return 0;
}
| 23.962121 | 85 | 0.672463 | [
"vector",
"transform"
] |
03583dbe6fcb1a4450fadb7c05dd27a593280539 | 4,447 | hpp | C++ | src/Engine/Renderer/RenderTechnique/ShaderConfiguration.hpp | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | src/Engine/Renderer/RenderTechnique/ShaderConfiguration.hpp | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | src/Engine/Renderer/RenderTechnique/ShaderConfiguration.hpp | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | #ifndef RADIUMENGINE_SHADERCONFIGURATION_HPP
#define RADIUMENGINE_SHADERCONFIGURATION_HPP
#include <Engine/RaEngine.hpp>
#include <set>
#include <string>
#include <array>
#include <list>
namespace Ra
{
namespace Engine
{
enum ShaderType : uint
{
ShaderType_VERTEX = 0,
ShaderType_FRAGMENT,
ShaderType_GEOMETRY,
ShaderType_TESS_CONTROL,
ShaderType_TESS_EVALUATION,
ShaderType_COMPUTE,
ShaderType_COUNT
};
/// A struct used to create shader programs later on.
/// A ShaderConfiguration should be added once to the ShaderConfigurationFactory,
/// then the factory must be used to retrieve the added shader configurations.
/// Typical use case :
/// /**************************** CREATION ****************************/
/// // Create the shader configuration once (see MainApplication::addBasicShaders for example)
/// ShaderConfiguration config("MyConfig");
/// // Add shader files to the config (note that the file extensions can be whatever you want)
/// config.addShader(ShaderType_VERTEX, "path/to/shader.vert.glsl");
/// config.addShader(ShaderType_FRAGMENT, "path/to/shader.frag.glsl");
/// // Same for other shader types. Vertex and fragment are required, other are optional
/// // Note that, for a compute shader, only the compute shader is needed.
///
/// // Add the configuration to the factory
/// ShaderConfigurationFactory::addConfiguration(config);
///
/// /**************************** USAGE ****************************/
/// // When you want to reuse created shader configurations, just set it using
/// auto config = ShaderConfigurationFactory::getConfiguration("MyConfig");
/// // You can then pass it to createRenderObject for example
/// createRenderObject(name, component, RenderObjectType::Fancy, mesh, config, material);
class RA_ENGINE_API ShaderConfiguration
{
friend class ShaderProgram;
public:
ShaderConfiguration() = default;
/// Initializes a shader configuration with a name
/// Warning: This does not query the corresponding configuration in the ShaderConfigurationFactory
/// The proper way to do this is by calling
/// ShaderConfigurationFactory::getConfiguration(name);
ShaderConfiguration(const std::string& name);
/// Initializes a configuration with a name, a vertex and a fragment shader
/// This does not add the configuration to the factory
/// ShaderConfigurationFactory::addConfiguration(config) must be called.
ShaderConfiguration(const std::string& name, const std::string& vertexShader, const std::string& fragmentShader);
// Add a shader given its type
void addShader(ShaderType type, const std::string& name);
/// Will be processed as a #define prop
/// The same shader files with different properties leads to different shader programs
void addProperty(const std::string& prop);
void addProperties(const std::list<std::string>& props );
void removeProperty(const std::string& prop);
/// Tell if a shader configuration has at least a vertex and a fragment shader, or a compute shader.
bool isComplete() const;
bool operator< (const ShaderConfiguration& other) const;
std::set<std::string> getProperties() const;
// get default shader configuration
static ShaderConfiguration getDefaultShaderConfig() { return m_defaultShaderConfig; }
public:
std::string m_name;
private:
std::array<std::string, ShaderType_COUNT> m_shaders;
std::set<std::string> m_properties;
static ShaderConfiguration m_defaultShaderConfig;
};
} // namespace Engine
} // namespace Ra
#endif // RADIUMENGINE_SHADERCONFIGURATION_HPP
| 45.377551 | 126 | 0.584664 | [
"mesh"
] |
035a9c6de30a15b1ecd3318621f37830b603c932 | 204,327 | cpp | C++ | DataProxy/test/DatabaseProxyTest.cpp | aol/DataProxyLibrary | b1a16e6abadcf3e1cd07448086e2375511a337e6 | [
"BSD-3-Clause"
] | null | null | null | DataProxy/test/DatabaseProxyTest.cpp | aol/DataProxyLibrary | b1a16e6abadcf3e1cd07448086e2375511a337e6 | [
"BSD-3-Clause"
] | null | null | null | DataProxy/test/DatabaseProxyTest.cpp | aol/DataProxyLibrary | b1a16e6abadcf3e1cd07448086e2375511a337e6 | [
"BSD-3-Clause"
] | null | null | null | // FILE NAME: $HeadURL: svn+ssh://svn.cm.aol.com/advertising/adlearn/gen1/trunk/lib/cpp/DataProxy/test/DatabaseProxyTest.cpp $
//
// REVISION: $Revision: 303696 $
//
// COPYRIGHT: (c) 2006 Advertising.com All Rights Reserved.
//
// LAST UPDATED: $Date: 2014-07-31 18:04:05 -0400 (Thu, 31 Jul 2014) $
// UPDATED BY: $Author: pnguyen7 $
#include "DPLCommon.hpp"
#include "DatabaseProxyTest.hpp"
#include "Database.hpp"
#include "FileUtilities.hpp"
#include "TempDirectory.hpp"
#include "ProxyUtilities.hpp"
#include "ProxyTestHelpers.hpp"
#include "AssertThrowWithMessage.hpp"
#include "AssertFileContents.hpp"
#include "AssertTableContents.hpp"
#include "OracleUnitTestDatabase.hpp"
#include "MySqlUnitTestDatabase.hpp"
#include "MockRequestForwarder.hpp"
#include "MockDataProxyClient.hpp"
#include "MockDatabaseConnectionManager.hpp"
#include <fstream>
#include <boost/regex.hpp>
CPPUNIT_TEST_SUITE_REGISTRATION( DatabaseProxyTest );
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( DatabaseProxyTest, "DatabaseProxyTest" );
namespace
{
const std::string MATCH_FILE_AND_LINE_NUMBER( ".+?:[0-9]+?: " );
std::string GetOracleTableDDL( const std::string i_rName )
{
std::stringstream result;
result << "CREATE TABLE " << i_rName << " ( "
<< "media_id NUMBER(*,0), "
<< "website_id NUMBER(*,0), "
<< "impressions NUMBER(*,0), "
<< "revenue NUMBER, "
<< "dummy NUMBER(*,0), "
<< "myConstant NUMBER(*,0), "
<< "CONSTRAINT cpk_" << i_rName << " PRIMARY KEY (media_id, website_id) )";
return result.str();
}
std::string GetMySqlTableDDL( const std::string i_rName )
{
std::stringstream result;
result << "CREATE TABLE " << i_rName << " ( "
<< "media_id INT, "
<< "website_id INT, "
<< "impressions INT, "
<< "revenue DOUBLE, "
<< "dummy INT, "
<< "myConstant INT, "
<< "PRIMARY KEY cpk_" << i_rName << " (media_id, website_id) ) ENGINE=innodb";
return result.str();
}
std::string GetElementsOracleDDL(const std::string i_Name)
{
std::stringstream result;
result << "CREATE TABLE " << i_Name << " ( "
<< "fake_element_id NUMBER(*,0), "
<< "fake_element_name VARCHAR(2000), "
<< "CONSTRAINT cpk_" << i_Name << " PRIMARY KEY (fake_element_id) )";
return result.str();
}
std::string GetElementsMySqlDDL(const std::string i_Name)
{
std::stringstream result;
result << "CREATE TABLE " << i_Name << " ( "
<< "fake_element_id INT, "
<< "fake_element_name VARCHAR(2000), "
<< "PRIMARY KEY cpk_" << i_Name << " (fake_element_id) ) ENGINE=innodb";
return result.str();
}
}
DatabaseProxyTest::DatabaseProxyTest()
: m_pTempDir()
{
}
DatabaseProxyTest::~DatabaseProxyTest()
{
}
void DatabaseProxyTest::setUp()
{
XMLPlatformUtils::Initialize();
m_pTempDir.reset( new TempDirectory() );
CPPUNIT_ASSERT_NO_THROW( m_pOracleDB.reset(new OracleUnitTestDatabase() ));
CPPUNIT_ASSERT_NO_THROW( m_pMySQLDB.reset( new MySqlUnitTestDatabase() ));
CPPUNIT_ASSERT_NO_THROW( m_pOracleObservationDB.reset(new Database( Database::DBCONN_OCI_ORACLE,
m_pOracleDB->GetServerName(),
m_pOracleDB->GetDBName(),
m_pOracleDB->GetUserName(),
m_pOracleDB->GetPassword(),
false,
m_pOracleDB->GetSchema() ) ));
CPPUNIT_ASSERT_NO_THROW( m_pMySQLObservationDB.reset( new Database( Database::DBCONN_ODBC_MYSQL,
m_pMySQLDB->GetServerName(),
m_pMySQLDB->GetDBName(),
m_pMySQLDB->GetUserName(),
m_pMySQLDB->GetPassword() ) ));
CPPUNIT_ASSERT_NO_THROW( m_pMySQLAccessoryDB.reset( new Database( Database::DBCONN_ODBC_MYSQL,
m_pMySQLDB->GetServerName(),
m_pMySQLDB->GetDBName(),
m_pMySQLDB->GetUserName(),
m_pMySQLDB->GetPassword() ) ));
}
void DatabaseProxyTest::tearDown()
{
//XMLPlatformUtils::Terminate();
m_pOracleObservationDB.reset();
m_pMySQLObservationDB.reset();
m_pOracleDB.reset();
m_pMySQLDB.reset();
m_pMySQLAccessoryDB.reset();
m_pTempDir.reset();
}
void DatabaseProxyTest::testConstructorExceptionWithNoReadOrWriteOrDeleteNode()
{
MockDataProxyClient client;
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< "</DataNode>";
MockDatabaseConnectionManager dbManager;
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Node not configured to handle Load or Store or Delete operations" );
}
void DatabaseProxyTest::testConstructorExceptionIllegalXml()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} order by ot_id\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Neither 'connection' nor 'connectionByTable' attributes were provided");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Read header = \"id,desc\" "
<< " connection = \"myOracleConnection\" "
<< " connectionByTable = \"myTable${campaign_id}\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} order by ot_id\" />"
<< "</DataNode>";
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Invalid to supply both 'connection' and 'connectionByTable' attributes");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Read header = \"id,desc\" "
<< " connection = \"myOracleConnection\" />"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
XMLUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "Unable to find attribute: 'query' in node: Read");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\""
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} order by ot_id\" />"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
XMLUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "Unable to find attribute: 'header' in node: Read");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write table = \"myTable\" "
<< " stagingTable = \"myStagingTable\" "
<< " workingDir = \"./\" >"
<< " <Columns><Column name=\"key1\" type=\"key\" /></Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Neither 'connection' nor 'connectionByTable' attributes were provided");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write table = \"myTable\" "
<< " connection = \"myOracleConnection\" "
<< " connectionByTable = \"myShard${campaign_id}\" "
<< " stagingTable = \"myStagingTable\" "
<< " workingDir = \"./\" >"
<< " <Columns><Column name=\"key1\" type=\"key\" /></Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Invalid to supply both 'connection' and 'connectionByTable' attributes");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " stagingTable = \"myStagingTable\" "
<< " workingDir = \"./\" >"
<< " <Columns><Column name=\"key1\" type=\"key\" /></Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
XMLUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "Unable to find attribute: 'table' in node: Write");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"myTable\" "
<< " stagingTable = \"myStagingTable\" >"
<< " <Columns><Column name=\"key1\" type=\"key\" /></Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
XMLUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "Unable to find attribute: 'workingDir' in node: Write");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"myTable\" "
<< " stagingTable = \"myStagingTable\" "
<< " workingDir = \"./\" >"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
XMLUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "Incorrect number of Columns child nodes specified in Write. There were 0 but there should be exactly 1");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"myTable\" "
<< " stagingTable = \"myTable\" "
<< " workingDir = \"./\" >"
<< " <Columns><Column name=\"key1\" type=\"key\" /></Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Attributes for table and stagingTable cannot have the same value: myTable");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connectionByTable = \"myTable${campaign}\""
<< " stagingTable = \"myTable${campaign}\" "
<< " workingDir = \"./\" >"
<< " <Columns><Column name=\"key1\" type=\"key\" /></Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Attributes for table and stagingTable cannot have the same value: myTable\\$\\{campaign\\}");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"myTable\" "
<< " stagingTable = \"myStagingTable\" "
<< " workingDir = \"/nonexistent\" >"
<< " <Columns><Column name=\"key1\" type=\"key\" /></Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
InvalidDirectoryException,
MATCH_FILE_AND_LINE_NUMBER + "/nonexistent does not exist or is not a valid directory\\." );
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"myTable\" "
<< " stagingTable = \"myStagingTable\" "
<< " garbage = \"true\" "
<< " workingDir = \"./\" >"
<< " <Columns><Column name=\"key1\" type=\"key\" /></Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
XMLUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "Found invalid attribute: garbage in node: Write" );
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"myTable\" "
<< " stagingTable = \"myStagingTable\" "
<< " onColumnParameterCollision = \"garbage\" "
<< " workingDir = \"./\" >"
<< " <Columns><Column name=\"key1\" type=\"key\" /></Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Write attribute: onColumnParameterCollision has invalid value: garbage. Valid values are 'fail', 'useColumn', 'useParameter'" );
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete "
<< " query = \"Delete from OracleTable where ot_id = ${idToMatch}\" />"
<< "</DataNode>";
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Neither 'connection' nor 'connectionByTable' attributes were provided");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete "
<< " connection = \"myOracleConnection\" "
<< " connectionByTable = \"myTable${campaign_id}\" "
<< " query = \"Delete from OracleTable where ot_id = ${idToMatch}\" />"
<< "</DataNode>";
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Invalid to supply both 'connection' and 'connectionByTable' attributes");
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete "
<< " connection = \"myOracleConnection\" />"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE(DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ),
XMLUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "Unable to find attribute: 'query' in node: Delete");
}
void DatabaseProxyTest::testOperationAttributeParsing()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\">" << std::endl
<< " <Read operation = \"ignore\""
<< " connection = \"myOracleConnection\" "
<< " header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = 1 order by ot_id\" >"
<< " </Read>"
<< " <Write connection = \"myOracleConnection\""
<< " operation = \"ignore\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " directLoad = \"true\" "
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" sourceName=\"MEDIA_ID\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" sourceName=\"MY_CONSTANT\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< " <Delete connection = \"myOracleConnection\" "
<< " operation = \"ignore\""
<< " query = \"Delete from OracleTable where ot_id = ${idToMatch} or ot_id = 1\" >"
<< " </Delete>"
<< "</DataNode>" << std::endl;
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_NO_THROW( DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
}
void DatabaseProxyTest::testOperationNotSupported()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"rows\" "
<< " query = \"Select count(*) from OracleTable\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
std::stringstream results;
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Store( parameters, results ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Proxy not configured to be able to perform Store operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Delete( parameters ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Proxy not configured to be able to perform Delete operations" );
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"myTable\" "
<< " stagingTable = \"myStagingTable\" "
<< " workingDir = \"./\" >"
<< " <Columns><Column name=\"key1\" type=\"key\" /></Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy2( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy2.Load( parameters, results ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Proxy not configured to be able to perform Load operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy2.Delete( parameters ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Proxy not configured to be able to perform Delete operations" );
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete "
<< " connection = \"myOracleConnection\" "
<< " query = \"Delete from OracleTable where ot_id = ${idToMatch}\" />"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy3( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy3.Load( parameters, results ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Proxy not configured to be able to perform Load operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy3.Store( parameters, results ),
DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Proxy not configured to be able to perform Store operations" );
}
void DatabaseProxyTest::testPing()
{
MockDataProxyClient client;
// case: oracle / read-enabled
{
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type=\"db\" >"
<< " <Read connection=\"myOracleConnection\" "
<< " header=\"whatever\" "
<< " query=\"whatever\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::READ ) );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::WRITE ), PingException, ".*:\\d+: Not configured to be able to handle Write operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::DELETE ), PingException, ".*:\\d+: Not configured to be able to handle Delete operations" );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
}
// case: oracle / write-enabled
{
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type=\"db\" >"
<< " <Write connection=\"myOracleConnection\" "
<< " table=\"whatever\" >"
<< " <Columns>"
<< " <Column name=\"whatever\" type=\"key\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::WRITE ) );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::READ ), PingException, ".*:\\d+: Not configured to be able to handle Read operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::DELETE ), PingException, ".*:\\d+: Not configured to be able to handle Delete operations" );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
}
// case: oracle / delete-enabled
{
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type=\"db\" >"
<< " <Delete connection=\"myOracleConnection\" "
<< " query=\"whatever\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::DELETE ) );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::READ ), PingException, ".*:\\d+: Not configured to be able to handle Read operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::WRITE ), PingException, ".*:\\d+: Not configured to be able to handle Write operations" );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
}
// case: oracle / multiple-enabled
{
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type=\"db\" >"
<< " <Read connection=\"myOracleConnection\" "
<< " header=\"whatever\" "
<< " query=\"whatever\" />"
<< " <Write connection=\"myOracleConnection\" "
<< " table=\"whatever\" >"
<< " <Columns>"
<< " <Column name=\"whatever\" type=\"key\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::READ ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::WRITE ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::READ | DPL::WRITE ) );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::READ | DPL::DELETE ), PingException, ".*:\\d+: Not configured to be able to handle Delete operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::WRITE | DPL::DELETE ), PingException, ".*:\\d+: Not configured to be able to handle Delete operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::READ | DPL::WRITE | DPL::DELETE ), PingException, ".*:\\d+: Not configured to be able to handle Delete operations" );
std::stringstream expected;
// 2 validates (done at config time)
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
// one GetConnection for null-checking on the write config
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
// total of 8 GetConnections (done at ping time)
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
}
// case: mysql / read-enabled
{
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySqlConnection", m_pMySQLDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type=\"db\" >"
<< " <Read connection=\"myMySqlConnection\" "
<< " header=\"whatever\" "
<< " query=\"whatever\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::READ ) );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::WRITE ), PingException, ".*:\\d+: Not configured to be able to handle Write operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::DELETE ), PingException, ".*:\\d+: Not configured to be able to handle Delete operations" );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
}
// case: mysql / write-enabled
{
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySqlConnection", m_pMySQLDB);
dbManager.InsertConnection("myMySqlConnection", m_pOracleDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type=\"db\" >"
<< " <Write connection=\"myMySqlConnection\" "
<< " table=\"whatever\" >"
<< " <Columns>"
<< " <Column name=\"whatever\" type=\"key\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::WRITE ) );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::READ ), PingException, ".*:\\d+: Not configured to be able to handle Read operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::DELETE ), PingException, ".*:\\d+: Not configured to be able to handle Delete operations" );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
}
// case: mysql / delete-enabled
{
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySqlConnection", m_pMySQLDB);
dbManager.InsertConnection("myMySqlConnection", m_pOracleDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type=\"db\" >"
<< " <Delete connection=\"myMySqlConnection\" "
<< " query=\"whatever\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::DELETE ) );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::READ ), PingException, ".*:\\d+: Not configured to be able to handle Read operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::WRITE ), PingException, ".*:\\d+: Not configured to be able to handle Write operations" );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
}
// case: mysql / multiple-enabled
{
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySqlConnection", m_pMySQLDB);
dbManager.InsertConnection("myMySqlConnection", m_pOracleDB);
std::stringstream xmlContents;
xmlContents << "<DataNode type=\"db\" >"
<< " <Read connection=\"myMySqlConnection\" "
<< " header=\"whatever\" "
<< " query=\"whatever\" />"
<< " <Write connection=\"myMySqlConnection\" "
<< " table=\"whatever\" >"
<< " <Columns>"
<< " <Column name=\"whatever\" type=\"key\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::READ ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::WRITE ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Ping( DPL::READ | DPL::WRITE ) );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::READ | DPL::DELETE ), PingException, ".*:\\d+: Not configured to be able to handle Delete operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::WRITE | DPL::DELETE ), PingException, ".*:\\d+: Not configured to be able to handle Delete operations" );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Ping( DPL::READ | DPL::WRITE | DPL::DELETE ), PingException, ".*:\\d+: Not configured to be able to handle Delete operations" );
std::stringstream expected;
// 2 validates (done at config time)
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
// one GetConnection done for write-side config
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
// total of 8 GetConnections (done at ping time)
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySqlConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
}
std::stringstream expected;
CPPUNIT_ASSERT_EQUAL( expected.str(), client.GetLog() );
client.ClearLog();
}
void DatabaseProxyTest::testOracleLoad()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = 1 order by ot_id\" >"
<< " </Read>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
std::stringstream results;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
CPPUNIT_ASSERT_NO_THROW( proxy.Load( parameters, results ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
expected.str("");
expected << "id,desc" << std::endl;
expected << "1,Alpha" << std::endl;
expected << "3,Charlie" << std::endl;
CPPUNIT_ASSERT_EQUAL( expected.str(), results.str() );
}
void DatabaseProxyTest::testMySQLLoad()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pMySQLDB, "Create Table MySQLTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO MySQLTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pMySQLDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myMySQLConnection\" "
<< " header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from MySQLTable where ot_id = ${idToMatch} or ot_id = 1 order by ot_id\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
dbManager.InsertConnection("myMySQLConnection", m_pMySQLDB);
std::stringstream results;
CPPUNIT_ASSERT_NO_THROW( proxy.Load( parameters, results ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myMySQLConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySQLConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
expected.str("");
expected << "id,desc" << std::endl;
expected << "1,Alpha" << std::endl;
expected << "3,Charlie" << std::endl;
CPPUNIT_ASSERT_EQUAL( expected.str(), results.str() );
}
void DatabaseProxyTest::testLoadExceptionMissingVariableNameDefinition()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = 1 order by ot_id\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
std::map< std::string, std::string > parameters;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream results;
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Load( parameters, results ),
ProxyUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "The following parameters are referenced, but are not specified in the parameters: idToMatch" );
}
void DatabaseProxyTest::testLoadWithExtraVariableNameDefinitions()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, NULL)");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = 1 order by ot_id\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
parameters["${An Unused Definition Should Not Throw An Exception}"] = "Unused";
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream results;
CPPUNIT_ASSERT_NO_THROW( proxy.Load( parameters, results ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
expected.str("");
expected << "id,desc" << std::endl;
expected << "1,Alpha" << std::endl;
expected << "3," << std::endl;
CPPUNIT_ASSERT_EQUAL( expected.str(), results.str() );
}
void DatabaseProxyTest::testLoadWithNoVariableNames()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = 1 order by ot_id\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream results;
CPPUNIT_ASSERT_NO_THROW( proxy.Load( parameters, results ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
expected.str("");
expected << "id,desc" << std::endl;
expected << "1,Alpha" << std::endl;
CPPUNIT_ASSERT_EQUAL( expected.str(), results.str() );
}
void DatabaseProxyTest::testLoadWithMultipleVariableNames()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = 1 order by ${orderBy}\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
//ordering by negative ot_id
parameters["orderBy"] = "-ot_id";
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream results;
CPPUNIT_ASSERT_NO_THROW( proxy.Load( parameters, results ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
expected.str("");
expected << "id,desc" << std::endl;
expected << "3,Charlie" << std::endl;
expected << "1,Alpha" << std::endl;
CPPUNIT_ASSERT_EQUAL( expected.str(), results.str() );
}
void DatabaseProxyTest::testLoadExceptionWithBadConnection()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = 1 order by ot_id\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream results;
CPPUNIT_ASSERT_NO_THROW( proxy.Load( parameters, results ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
expected.str("");
expected << "id,desc" << std::endl;
expected << "1,Alpha" << std::endl;
expected << "3,Charlie" << std::endl;
CPPUNIT_ASSERT_EQUAL( expected.str(), results.str() );
}
void DatabaseProxyTest::testLoadMaxStringParameter()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(500))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
//50 characters per line * 5. 250 characters is less than the default limit for string size(256).
values.push_back( "(1,'"
"000000000X000000000X000000000X000000000X000000000X"
"000000000X000000000X000000000X000000000X000000000X"
"000000000X000000000X000000000X000000000X000000000X"
"000000000X000000000X000000000X000000000X000000000X"
"000000000X000000000X000000000X000000000X000000000X"
"')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"id,desc\" "
<< " maxBindSize = \"300\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = 1 order by ot_id\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
std::stringstream results;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
CPPUNIT_ASSERT_NO_THROW( proxy.Load( parameters, results ));
std::stringstream expected;
expected.str("");
expected << "id,desc" << std::endl;
expected << "1,"
<< "000000000X000000000X000000000X000000000X000000000X"
<< "000000000X000000000X000000000X000000000X000000000X"
<< "000000000X000000000X000000000X000000000X000000000X"
<< "000000000X000000000X000000000X000000000X000000000X"
<< "000000000X000000000X000000000X000000000X000000000X"
<< std::endl;
expected << "3,Charlie" << std::endl;
CPPUNIT_ASSERT_EQUAL( expected.str(), results.str() );
}
void DatabaseProxyTest::testLoadSameVarNameReplacedTwice()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = ${idToMatch} - 2 order by ot_id\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
std::stringstream results;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
CPPUNIT_ASSERT_NO_THROW( proxy.Load( parameters, results ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
expected.str("");
expected << "id,desc" << std::endl;
expected << "1,Alpha" << std::endl;
expected << "3,Charlie" << std::endl;
CPPUNIT_ASSERT_EQUAL( expected.str(), results.str() );
}
void DatabaseProxyTest::testLoadExceptionEmptyVarName()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"id,desc\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = ${} - 2 order by ot_id\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
std::stringstream results;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Load( parameters, results ),
ProxyUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "Variable name referenced must be alphanumeric \\(enclosed within \"\\$\\{\" and \"\\}\"\\)\\."
" Instead it is: '\\$\\{\\}'");
}
void DatabaseProxyTest::testLoadCustomSeparators()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Read connection = \"myOracleConnection\" "
<< " header = \"id with spaces | desc\" "
<< " fieldSeparator = \" | \" "
<< " recordSeparator = \";;;\" "
<< " query = \"Select ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = 1 order by ot_id\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
std::stringstream results;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
CPPUNIT_ASSERT_NO_THROW( proxy.Load( parameters, results ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
expected.str("");
expected << "id with spaces | desc;;;";
expected << "1 | Alpha;;;";
expected << "3 | Charlie;;;";
CPPUNIT_ASSERT_EQUAL( expected.str(), results.str() );
}
void DatabaseProxyTest::testStoreException()
{
MockDataProxyClient client;
// create primary & staging tables
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
Database::Statement(*m_pOracleDB, GetOracleTableDDL("stg_kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myOracleConnection", m_pOracleDB );
// CASE 1: Ambiguous required column in incoming stream
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " directLoad = \"true\" "
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "media_id,media_id,website_id,ignore,impressions,revenue,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1" << std::endl
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "myConstant" ] = "24";
parameters[ "ignore" ] = "ignoreMe4";
parameters[ "ignore5" ] = "ignoreMe5";
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( pProxy->Store( parameters, data ), DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Column: media_id from incoming stream is ambiguous with another column of the same name" );
// CASE 2: Not all required columns accounted for
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " directLoad = \"true\" "
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.str("");
data << "media_id,ignore,ignore,ignore,impressions,ignore,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1" << std::endl
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
parameters.clear();
parameters[ "myConstant" ] = "24";
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( pProxy->Store( parameters, data ), DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Incoming data is insufficient, since the following required columns are still unaccounted for: revenue,website_id" );
}
void DatabaseProxyTest::testOracleStore()
{
MockDataProxyClient client;
// create primary & staging tables
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
Database::Statement(*m_pOracleDB, GetOracleTableDDL("stg_kna")).Execute();
// insert some dummy data into the staging table to be cleared
std::string prefix = "INSERT INTO stg_kna (media_id, website_id, impressions, revenue, dummy, myConstant) VALUES ";
Database::Statement( *m_pOracleDB, prefix + "(12, 13, -1, -2, -3, -4)" ).Execute();
CPPUNIT_ASSERT_NO_THROW( m_pOracleDB->Commit() );
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myOracleConnection", m_pOracleDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " directLoad = \"true\" "
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" sourceName=\"MEDIA_ID\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" sourceName=\"MY_CONSTANT\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "na\\?!*&()[]{}|,'\"me", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT( proxy.SupportsTransactions() );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "MEDIA_ID,ignore,website_id,ignore,impressions,revenue,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1\\,-9" << std::endl // the escaped comma should validate that CSVReader allows escapes
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "MY_CONSTANT" ] = "24";
parameters[ "ignore" ] = "ignoreMe4";
parameters[ "ignore5" ] = "ignoreMe5";
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, data ) );
std::stringstream expectedStaging;
expectedStaging << "12,13,14,15.5,,24" << std::endl
<< "22,23,24,25.5,,24" << std::endl
<< "32,33,34,35.5,,24" << std::endl
<< "42,43,44,45.5,,24" << std::endl
<< "52,53,54,55.5,,24" << std::endl
<< "62,63,64,65.5,,24" << std::endl;
//the sqlloader will have loaded the staging table at this point
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedStaging.str(), *m_pOracleObservationDB, "stg_kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// check table contents: nothing yet since it hasn't been committed
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
// check table contents
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// no cleanup was on, so files should still exist in temporary directory
std::vector< std::string > files;
FileUtilities::ListDirectory( m_pTempDir->GetDirectoryName(), files, false );
std::sort( files.begin(), files.end() );
CPPUNIT_ASSERT_EQUAL( size_t(3), files.size() );
CPPUNIT_ASSERT_MESSAGE( files[0], boost::regex_match( files[0], boost::regex("name\\.[0-9]+\\.[0-9]+\\.[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}\\.ctrl") ) );
CPPUNIT_ASSERT_MESSAGE( files[1], boost::regex_match( files[1], boost::regex("name\\.[0-9]+\\.[0-9]+\\.[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}\\.dat") ) );
CPPUNIT_ASSERT_MESSAGE( files[2], boost::regex_match( files[2], boost::regex("name\\.[0-9]+\\.[0-9]+\\.[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}\\.log") ) );
// truncate & do it again with noCleanUp off
Database::Statement( *m_pOracleDB, "TRUNCATE TABLE kna" ).Execute();
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " directLoad = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" sourceName=\"MEDIA_ID\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" sourceName=\"MY_CONSTANT\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy2( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.clear();
data.seekg( 0L, std::ios_base::beg );
CPPUNIT_ASSERT_NO_THROW( proxy2.Store( parameters, data ) );
// check table contents; empty since no commit yet
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
CPPUNIT_ASSERT_NO_THROW( proxy2.Commit() );
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// no cleanup was off (by default), so files should still exist in temporary directory
files.clear();
FileUtilities::ListDirectory( m_pTempDir->GetDirectoryName(), files, false );
CPPUNIT_ASSERT_EQUAL( size_t(0), files.size() );
}
void DatabaseProxyTest::testOracleStagingTableSpecifiedByParameter()
{
MockDataProxyClient client;
// create primary & staging tables
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
Database::Statement(*m_pOracleDB, GetOracleTableDDL("stg_kna")).Execute();
// insert some dummy data into the staging table to be cleared
std::string prefix = "INSERT INTO stg_kna (media_id, website_id, impressions, revenue, dummy, myConstant) VALUES ";
Database::Statement( *m_pOracleDB, prefix + "(12, 13, -1, -2, -3, -4)" ).Execute();
CPPUNIT_ASSERT_NO_THROW( m_pOracleDB->Commit() );
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myOracleConnection", m_pOracleDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_${stagingTableName}\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " directLoad = \"true\" "
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" sourceName=\"MEDIA_ID\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" sourceName=\"MY_CONSTANT\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "na\\?!*&()[]{}|,'\"me", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT( proxy.SupportsTransactions() );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "MEDIA_ID,ignore,website_id,ignore,impressions,revenue,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1\\,-9" << std::endl // the escaped comma should validate that CSVReader allows escapes
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "MY_CONSTANT" ] = "24";
parameters[ "ignore" ] = "ignoreMe4";
parameters[ "ignore5" ] = "ignoreMe5";
parameters[ "stagingTableName" ] = "kna";
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, data ) );
std::stringstream expectedStaging;
expectedStaging << "12,13,14,15.5,,24" << std::endl
<< "22,23,24,25.5,,24" << std::endl
<< "32,33,34,35.5,,24" << std::endl
<< "42,43,44,45.5,,24" << std::endl
<< "52,53,54,55.5,,24" << std::endl
<< "62,63,64,65.5,,24" << std::endl;
//the sqlloader will have loaded the staging table at this point
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedStaging.str(), *m_pOracleObservationDB, "stg_kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// check table contents: nothing yet since it hasn't been committed
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
// check table contents
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// no cleanup was on, so files should still exist in temporary directory
std::vector< std::string > files;
FileUtilities::ListDirectory( m_pTempDir->GetDirectoryName(), files, false );
std::sort( files.begin(), files.end() );
CPPUNIT_ASSERT_EQUAL( size_t(3), files.size() );
CPPUNIT_ASSERT_MESSAGE( files[0], boost::regex_match( files[0], boost::regex("name\\.[0-9]+\\.[0-9]+\\.[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}\\.ctrl") ) );
CPPUNIT_ASSERT_MESSAGE( files[1], boost::regex_match( files[1], boost::regex("name\\.[0-9]+\\.[0-9]+\\.[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}\\.dat") ) );
CPPUNIT_ASSERT_MESSAGE( files[2], boost::regex_match( files[2], boost::regex("name\\.[0-9]+\\.[0-9]+\\.[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}\\.log") ) );
// truncate & do it again with noCleanUp off
Database::Statement( *m_pOracleDB, "TRUNCATE TABLE kna" ).Execute();
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_${stagingTableName}\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " directLoad = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" sourceName=\"MEDIA_ID\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" sourceName=\"MY_CONSTANT\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy2( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.clear();
data.seekg( 0L, std::ios_base::beg );
CPPUNIT_ASSERT_NO_THROW( proxy2.Store( parameters, data ) );
// check table contents; empty since no commit yet
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
CPPUNIT_ASSERT_NO_THROW( proxy2.Commit() );
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// no cleanup was off (by default), so files should still exist in temporary directory
files.clear();
FileUtilities::ListDirectory( m_pTempDir->GetDirectoryName(), files, false );
CPPUNIT_ASSERT_EQUAL( size_t(0), files.size() );
}
void DatabaseProxyTest::testOracleStoreDifferentSchema()
{
MockDataProxyClient client;
// create primary & staging tables
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
Database::Statement(*m_pOracleDB, GetOracleTableDDL("stg_kna")).Execute();
// insert some dummy data into the staging table to be cleared
std::string prefix = "INSERT INTO stg_kna (media_id, website_id, impressions, revenue, dummy, myConstant) VALUES ";
Database::Statement( *m_pOracleDB, prefix + "(12, 13, -1, -2, -3, -4)" ).Execute();
CPPUNIT_ASSERT_NO_THROW( m_pOracleDB->Commit() );
MockDatabaseConnectionManager dbManager;
// create a db connection that is connected to username five0test, but attached to the unittestdb's SCHEMA
boost::shared_ptr< Database > pDifferentSchemaDB( new Database( Database::DBCONN_OCI_THREADSAFE_ORACLE, "", "ADLAPPD_AWS", "five0test", "DSLYCZZHA7", false, m_pOracleDB->GetSchema() ) );
CPPUNIT_ASSERT_NO_THROW( Database::Statement( *m_pOracleDB, "GRANT SELECT, INSERT, UPDATE ON stg_kna TO five0test" ).Execute() );
CPPUNIT_ASSERT_NO_THROW( Database::Statement( *m_pOracleDB, "GRANT INSERT, UPDATE ON kna TO five0test" ).Execute() );
CPPUNIT_ASSERT_NO_THROW( Database::Statement( *m_pOracleDB, "GRANT EXECUTE ON sp_truncate_table TO five0test" ).Execute() );
dbManager.InsertConnection( "myOracleConnection", pDifferentSchemaDB, "oracle" );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " directLoad = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" sourceName=\"MEDIA_ID\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" sourceName=\"MY_CONSTANT\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT( proxy.SupportsTransactions() );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "MEDIA_ID,ignore,website_id,ignore,impressions,revenue,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1\\,-9" << std::endl // the escaped comma should validate that CSVReader allows escapes
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "MY_CONSTANT" ] = "24";
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
// check table contents
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// no cleanup was off (by default), so files should still exist in temporary directory
std::vector< std::string > files;
FileUtilities::ListDirectory( m_pTempDir->GetDirectoryName(), files, false );
CPPUNIT_ASSERT_EQUAL( size_t(0), files.size() );
// truncate & do it again with the prefix already supplied
Database::Statement( *m_pOracleDB, "TRUNCATE TABLE kna" ).Execute();
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"" << pDifferentSchemaDB->GetSchema() << ".stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " directLoad = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" sourceName=\"MEDIA_ID\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" sourceName=\"MY_CONSTANT\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy2( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
data.clear();
data.seekg( 0L, std::ios_base::beg );
CPPUNIT_ASSERT_NO_THROW( proxy2.Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( proxy2.Commit() );
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// no cleanup was off (by default), so files should still exist in temporary directory
files.clear();
FileUtilities::ListDirectory( m_pTempDir->GetDirectoryName(), files, false );
CPPUNIT_ASSERT_EQUAL( size_t(0), files.size() );
}
void DatabaseProxyTest::testOracleStoreNoStaging()
{
MockDataProxyClient client;
// create primary table
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myOracleConnection", m_pOracleDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" sourceName=\"MEDIA_ID\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" sourceName=\"MY_CONSTANT\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT( proxy.SupportsTransactions() );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "MEDIA_ID,ignore,website_id,ignore,impressions,revenue,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1\\,-9" << std::endl // the escaped comma should validate that CSVReader allows escapes
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "MY_CONSTANT" ] = "24";
parameters[ "ignore" ] = "ignoreMe4";
parameters[ "ignore5" ] = "ignoreMe5";
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, data ) );
// check table contents: nothing yet since it hasn't been committed
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
// check table contents
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
}
void DatabaseProxyTest::testMySqlStore()
{
MockDataProxyClient client;
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
// insert some dummy data into the staging table to be cleared
std::string prefix = "INSERT INTO stg_kna (media_id, website_id, impressions, revenue, dummy, myConstant) VALUES ";
Database::Statement( *m_pMySQLDB, prefix + "(12, 13, -1, -2, -3, -4)" ).Execute();
CPPUNIT_ASSERT_NO_THROW( m_pMySQLDB->Commit() );
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myMySqlConnection", m_pMySQLDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" sourceName=\"WEBSITE_ID\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" sourceName=\"WHATEVER\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" sourceName=\"MY_CONSTANT\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT( proxy.SupportsTransactions() );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "media_id,ignore,WEBSITE_ID,ignore,impressions,revenue,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1" << std::endl
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "MY_CONSTANT" ] = "24";
parameters[ "ignore" ] = "ignoreMe4";
parameters[ "ignore5" ] = "ignoreMe5";
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, data ) );
// check table contents; it will be empty since we haven't committed yet
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// MySQL staging table is no longer used except to define the temporary table, which can't be observed in the observation db
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// no cleanup was on, so files should still exist in temporary directory
std::vector< std::string > files;
FileUtilities::ListDirectory( m_pTempDir->GetDirectoryName(), files, false );
std::sort( files.begin(), files.end() );
CPPUNIT_ASSERT_EQUAL( size_t(1), files.size() );
CPPUNIT_ASSERT_MESSAGE( files[0], boost::regex_match( files[0], boost::regex("name\\.[0-9]+\\.[0-9]+\\.[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}\\.dat") ) );
// truncate & do it again with noCleanUp off
CPPUNIT_ASSERT_NO_THROW( m_pMySQLObservationDB->Commit() );
CPPUNIT_ASSERT_NO_THROW( m_pMySQLAccessoryDB->Commit() );
Database::Statement( *m_pMySQLDB, "TRUNCATE TABLE kna" ).Execute();
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" sourceName=\"WEBSITE_ID\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" sourceName=\"WHATEVER\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" sourceName=\"MY_CONSTANT\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy2( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.clear();
data.seekg( 0L, std::ios_base::beg );
CPPUNIT_ASSERT_NO_THROW( proxy2.Store( parameters, data ) );
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
CPPUNIT_ASSERT_NO_THROW( proxy2.Commit() );
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// no cleanup was off (by default), so files should still exist in temporary directory
files.clear();
FileUtilities::ListDirectory( m_pTempDir->GetDirectoryName(), files, false );
CPPUNIT_ASSERT_EQUAL( size_t(0), files.size() );
}
void DatabaseProxyTest::testMySqlStagingTableSpecifiedByParameter()
{
MockDataProxyClient client;
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
// insert some dummy data into the staging table to be cleared
std::string prefix = "INSERT INTO stg_kna (media_id, website_id, impressions, revenue, dummy, myConstant) VALUES ";
Database::Statement( *m_pMySQLDB, prefix + "(12, 13, -1, -2, -3, -4)" ).Execute();
CPPUNIT_ASSERT_NO_THROW( m_pMySQLDB->Commit() );
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myMySqlConnection", m_pMySQLDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_${stagingTableName}\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" sourceName=\"WEBSITE_ID\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" sourceName=\"WHATEVER\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" sourceName=\"MY_CONSTANT\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT( proxy.SupportsTransactions() );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "media_id,ignore,WEBSITE_ID,ignore,impressions,revenue,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1" << std::endl
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "MY_CONSTANT" ] = "24";
parameters[ "ignore" ] = "ignoreMe4";
parameters[ "ignore5" ] = "ignoreMe5";
parameters[ "stagingTableName" ] = "kna";
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, data ) );
// check table contents; it will be empty since we haven't committed yet
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// MySQL staging table is no longer used except to define the temporary table, which can't be observed in the observation db
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// no cleanup was on, so files should still exist in temporary directory
std::vector< std::string > files;
FileUtilities::ListDirectory( m_pTempDir->GetDirectoryName(), files, false );
std::sort( files.begin(), files.end() );
CPPUNIT_ASSERT_EQUAL( size_t(1), files.size() );
CPPUNIT_ASSERT_MESSAGE( files[0], boost::regex_match( files[0], boost::regex("name\\.[0-9]+\\.[0-9]+\\.[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}\\.dat") ) );
// truncate & do it again with noCleanUp off
CPPUNIT_ASSERT_NO_THROW( m_pMySQLObservationDB->Commit() );
CPPUNIT_ASSERT_NO_THROW( m_pMySQLAccessoryDB->Commit() );
CPPUNIT_ASSERT_NO_THROW( m_pMySQLDB->Commit() );
Database::Statement( *m_pMySQLDB, "TRUNCATE TABLE kna" ).Execute();
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_${stagingTableName}\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" sourceName=\"WEBSITE_ID\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" sourceName=\"WHATEVER\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" sourceName=\"MY_CONSTANT\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy2( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.clear();
data.seekg( 0L, std::ios_base::beg );
CPPUNIT_ASSERT_NO_THROW( proxy2.Store( parameters, data ) );
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
CPPUNIT_ASSERT_NO_THROW( proxy2.Commit() );
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// no cleanup was off (by default), so files should still exist in temporary directory
files.clear();
FileUtilities::ListDirectory( m_pTempDir->GetDirectoryName(), files, false );
CPPUNIT_ASSERT_EQUAL( size_t(0), files.size() );
}
void DatabaseProxyTest::testMySqlStoreNoStaging()
{
MockDataProxyClient client;
// create primary table
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myMySqlConnection", m_pMySQLDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" sourceName=\"WEBSITE_ID\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" sourceName=\"WHATEVER\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" sourceName=\"MY_CONSTANT\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT( proxy.SupportsTransactions() );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "media_id,ignore,WEBSITE_ID,ignore,impressions,revenue,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1" << std::endl
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "MY_CONSTANT" ] = "24";
parameters[ "ignore" ] = "ignoreMe4";
parameters[ "ignore5" ] = "ignoreMe5";
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, data ) );
// check table contents; it will be empty since we haven't committed yet
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
CPPUNIT_ASSERT_NO_THROW( m_pMySQLObservationDB->Commit() );
CPPUNIT_ASSERT_NO_THROW( m_pMySQLAccessoryDB->Commit() );
CPPUNIT_ASSERT_NO_THROW( Database::Statement( *m_pMySQLDB, "TRUNCATE TABLE kna" ).Execute() );
expected.str("");
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// do the same w/ parameters only
parameters.clear();
data.clear();
data.str("");
parameters["media_id"] = "1";
parameters["WEBSITE_ID"] = "2";
parameters["impressions"] = "3";
parameters["revenue"] = "4";
parameters["MY_CONSTANT"] = "5";
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, data ) );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
expected.str("");
expected << "1,2,3,4,17,5" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
}
void DatabaseProxyTest::testStoreColumnParameterCollisionBehaviors()
{
MockDataProxyClient client;
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myMySqlConnection", m_pMySQLDB );
// CASE 0: default behavior (fail on collision)
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "media_id,website_id,impressions,revenue" << std::endl
<< "12,13,14,15.5" << std::endl
<< "22,23,24,25.5" << std::endl
<< "32,33,34,35.5" << std::endl
<< "42,43,44,45.5" << std::endl
<< "52,53,54,55.5" << std::endl
<< "62,63,64,65.5" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "myConstant" ] = "24";
parameters[ "website_id" ] = "-33";
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( pProxy->Store( parameters, data ), DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Parameter: website_id with value: -33 is ambiguous with a column from the input stream of the same name" );
std::stringstream expected;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// CASE 1: force failure on collision
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " onColumnParameterCollision = \"fail\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.clear();
data.seekg( 0L );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( pProxy->Store( parameters, data ), DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Parameter: website_id with value: -33 is ambiguous with a column from the input stream of the same name" );
expected.str("");
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// CASE 2: use column over parameter
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " onColumnParameterCollision = \"useColumn\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.clear();
data.seekg( 0L );
CPPUNIT_ASSERT_NO_THROW( pProxy->Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
expected.str("");
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// CASE 3: use parameter over column
CPPUNIT_ASSERT_NO_THROW( m_pMySQLObservationDB->Commit() );
CPPUNIT_ASSERT_NO_THROW( m_pMySQLAccessoryDB->Commit() );
Database::Statement( *m_pMySQLDB, "TRUNCATE TABLE kna" ).Execute();
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " onColumnParameterCollision = \"useParameter\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.clear();
data.seekg( 0L );
CPPUNIT_ASSERT_NO_THROW( pProxy->Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
expected.str("");
expected << "12,-33,14,15.5,17,24" << std::endl
<< "22,-33,24,25.5,17,24" << std::endl
<< "32,-33,34,35.5,17,24" << std::endl
<< "42,-33,44,45.5,17,24" << std::endl
<< "52,-33,54,55.5,17,24" << std::endl
<< "62,-33,64,65.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
}
void DatabaseProxyTest::testStoreColumnParameterCollisionBehaviorsNoStaging()
{
MockDataProxyClient client;
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myMySqlConnection", m_pMySQLDB );
// CASE 0: default behavior (fail on collision)
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "media_id,website_id,impressions,revenue" << std::endl
<< "12,13,14,15.5" << std::endl
<< "22,23,24,25.5" << std::endl
<< "32,33,34,35.5" << std::endl
<< "42,43,44,45.5" << std::endl
<< "52,53,54,55.5" << std::endl
<< "62,63,64,65.5" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "myConstant" ] = "24";
parameters[ "website_id" ] = "-33";
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( pProxy->Store( parameters, data ), DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Parameter: website_id with value: -33 is ambiguous with a column from the input stream of the same name" );
std::stringstream expected;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// CASE 1: force failure on collision
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.clear();
data.seekg( 0L );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( pProxy->Store( parameters, data ), DatabaseProxyException,
MATCH_FILE_AND_LINE_NUMBER + "Parameter: website_id with value: -33 is ambiguous with a column from the input stream of the same name" );
expected.str("");
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// CASE 2: use column over parameter
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " onColumnParameterCollision = \"useColumn\" "
<< " table = \"kna\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.clear();
data.seekg( 0L );
CPPUNIT_ASSERT_NO_THROW( pProxy->Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
expected.str("");
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
// CASE 3: use parameter over column
CPPUNIT_ASSERT_NO_THROW( m_pMySQLObservationDB->Commit() );
CPPUNIT_ASSERT_NO_THROW( m_pMySQLAccessoryDB->Commit() );
Database::Statement( *m_pMySQLDB, "TRUNCATE TABLE kna" ).Execute();
xmlContents.str("");
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " onColumnParameterCollision = \"useParameter\" "
<< " table = \"kna\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
data.clear();
data.seekg( 0L );
CPPUNIT_ASSERT_NO_THROW( pProxy->Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
expected.str("");
expected << "12,-33,14,15.5,17,24" << std::endl
<< "22,-33,24,25.5,17,24" << std::endl
<< "32,-33,34,35.5,17,24" << std::endl
<< "42,-33,44,45.5,17,24" << std::endl
<< "52,-33,54,55.5,17,24" << std::endl
<< "62,-33,64,65.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
}
void DatabaseProxyTest::testStoreParameterOnly()
{
MockDataProxyClient client;
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myMySqlConnection", m_pMySQLDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
std::map< std::string, std::string > parameters;
parameters[ "media_id" ] = "12";
parameters[ "website_id" ] = "13";
parameters[ "impressions" ] = "14";
parameters[ "revenue" ] = "15.5";
parameters[ "myConstant" ] = "24";
CPPUNIT_ASSERT_NO_THROW( pProxy->Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
}
void DatabaseProxyTest::testStoreParameterWithTableParameter()
{
MockDataProxyClient client;
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna_foo")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myMySqlConnection", m_pMySQLDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna_${instance}\" "
<< " dynamicStagingTable=\"true\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
std::map< std::string, std::string > parameters;
parameters[ "media_id" ] = "12";
parameters[ "website_id" ] = "13";
parameters[ "impressions" ] = "14";
parameters[ "revenue" ] = "15.5";
parameters[ "myConstant" ] = "24";
parameters[ "instance" ] = "foo";
CPPUNIT_ASSERT_NO_THROW( pProxy->Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna_foo", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
}
void DatabaseProxyTest::testStoreParameterOnlyNoStaging()
{
MockDataProxyClient client;
// create primary table
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myMySqlConnection", m_pMySQLDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
std::map< std::string, std::string > parameters;
parameters[ "media_id" ] = "12";
parameters[ "website_id" ] = "13";
parameters[ "impressions" ] = "14";
parameters[ "revenue" ] = "15.5";
parameters[ "myConstant" ] = "24";
CPPUNIT_ASSERT_NO_THROW( pProxy->Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
}
void DatabaseProxyTest::testMySqlStoreDynamicTables()
{
MockDataProxyClient client;
// create primary table only
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myMySqlConnection", m_pMySQLDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySqlConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " dynamicStagingTable = \"true\" "
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" sourceName=\"WEBSITE_ID\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" sourceName=\"WHATEVER\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" sourceName=\"MY_CONSTANT\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT( proxy.SupportsTransactions() );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "media_id,ignore,WEBSITE_ID,ignore,impressions,revenue,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1" << std::endl
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "MY_CONSTANT" ] = "24";
parameters[ "ignore" ] = "ignoreMe4";
parameters[ "ignore5" ] = "ignoreMe5";
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
}
void DatabaseProxyTest::testOracleStoreDynamicTables()
{
MockDataProxyClient client;
// create primary table only
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myOracleConnection", m_pOracleDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"stg_kna\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " maxTableNameLength = \"30\" "
<< " dynamicStagingTable = \"true\" "
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" sourceName=\"WEBSITE_ID\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" sourceName=\"WHATEVER\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" sourceName=\"MY_CONSTANT\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
CPPUNIT_ASSERT( proxy.SupportsTransactions() );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream data;
data << "media_id,ignore,WEBSITE_ID,ignore,impressions,revenue,ignore" << std::endl
<< "12,-1,13,-1,14,15.5,-1" << std::endl
<< "22,-2,23,-2,24,25.5,-2" << std::endl
<< "32,-3,33,-3,34,35.5,-3" << std::endl
<< "42,-4,43,-4,44,45.5,-4" << std::endl
<< "52,-5,53,-5,54,55.5,-5" << std::endl
<< "62,-6,63,-6,64,65.5,-6" << std::endl;
std::map< std::string, std::string > parameters;
parameters[ "MY_CONSTANT" ] = "24";
parameters[ "ignore" ] = "ignoreMe4";
parameters[ "ignore5" ] = "ignoreMe5";
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, data ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
std::stringstream expected;
expected << "12,13,14,15.5,17,24" << std::endl
<< "22,23,24,25.5,17,24" << std::endl
<< "32,33,34,35.5,17,24" << std::endl
<< "42,43,44,45.5,17,24" << std::endl
<< "52,53,54,55.5,17,24" << std::endl
<< "62,63,64,65.5,17,24" << std::endl;
// check table contents
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" )
}
void DatabaseProxyTest::testDynamicTableNameLength()
{
MockDataProxyClient client;
// create primary table only
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myOracleConnection", m_pOracleDB );
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"kna\" "
<< " stagingTable = \"kna_stg\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\""
<< " maxTableNameLength = \"3\" " // because kna_stg... will be truncated to just "kna", we'll get a collision!
<< " dynamicStagingTable = \"true\" "
<< " noCleanUp = \"true\" "
<< " insertOnly = \"true\" >"
<< " <Columns>"
<< " <Column name=\"media_id\" type=\"key\" />"
<< " <Column name=\"website_id\" type=\"key\" sourceName=\"WEBSITE_ID\" />"
<< " <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />"
<< " <Column name=\"dummy\" type=\"data\" ifNew=\"17\" sourceName=\"WHATEVER\" />"
<< " <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" sourceName=\"MY_CONSTANT\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ), DatabaseProxyException,
".*/.*:\\d+: Attributes for table and stagingTable will collide due to the fact that the maxTableNameLength attribute will truncate the staging table name" );
}
void DatabaseProxyTest::testOracleDelete()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
m_pOracleDB->Commit();
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete connection = \"myOracleConnection\" "
<< " query = \"Delete from OracleTable where ot_id = ${idToMatch} or ot_id = 1\" >"
<< " </Delete>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
CPPUNIT_ASSERT_NO_THROW( proxy.Delete( parameters ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
// check table contents: no changes yet since it hasn't been committed
expected.str("");
expected << "1,Alpha" << std::endl
<< "2,Bravo" << std::endl
<< "3,Charlie" << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "OracleTable", "ot_id,ot_desc", "ot_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
// Verify that the records were deleted.
expected.str("");
expected << "2,Bravo" << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "OracleTable", "ot_id,ot_desc", "ot_id" )
}
void DatabaseProxyTest::testMySQLDelete()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pMySQLDB, "Create Table MySQLTable(ot_id INT, ot_desc VARCHAR(64)) ENGINE=innodb").Execute();
std::string cmd( "INSERT INTO MySQLTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pMySQLDB, cmd+values[i] );
stmt.Execute();
}
m_pMySQLDB->Commit();
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete connection = \"myMySQLConnection\" "
<< " query = \"Delete from MySQLTable where ot_id = ${idToMatch} or ot_id = 1\" >"
<< " </Delete>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySQLConnection", m_pMySQLDB);
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
CPPUNIT_ASSERT_NO_THROW( proxy.Delete( parameters ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myMySQLConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myMySQLConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
// check table contents: no changes yet since it hasn't been committed
expected.str("");
expected << "1,Alpha" << std::endl
<< "2,Bravo" << std::endl
<< "3,Charlie" << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "MySQLTable", "ot_id,ot_desc", "ot_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
// Verify that the records were deleted.
expected.str("");
expected << "2,Bravo" << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "MySQLTable", "ot_id,ot_desc", "ot_id" )
}
void DatabaseProxyTest::testDeleteExceptionMissingVariableNameDefinition()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
m_pOracleDB->Commit();
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete connection = \"myOracleConnection\" "
<< " query = \"Delete from OracleTable where ot_id = ${idToMatch} or ot_id = 1\" >"
<< " </Delete>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
std::map< std::string, std::string > parameters;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Delete( parameters ),
ProxyUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "The following parameters are referenced, but are not specified in the parameters: idToMatch" );
}
void DatabaseProxyTest::testDeleteWithExtraVariableNameDefinitions()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, NULL)");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
m_pOracleDB->Commit();
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete connection = \"myOracleConnection\" "
<< " query = \"Delete from OracleTable where ot_id = ${idToMatch} or ot_id = 1\" >"
<< " </Delete>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
parameters["${An Unused Definition Should Not Throw An Exception}"] = "Unused";
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
std::stringstream results;
CPPUNIT_ASSERT_NO_THROW( proxy.Delete( parameters ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
// check table contents: no changes yet since it hasn't been committed
expected.str("");
expected << "1,Alpha" << std::endl
<< "2,Bravo" << std::endl
<< "3," << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "OracleTable", "ot_id,ot_desc", "ot_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
// Verify that the records were deleted.
expected.str("");
expected << "2,Bravo" << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "OracleTable", "ot_id,ot_desc", "ot_id" )
}
void DatabaseProxyTest::testDeleteWithNoVariableNames()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
m_pOracleDB->Commit();
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete connection = \"myOracleConnection\" "
<< " query = \"Delete from OracleTable where ot_id = 1\" >"
<< " </Delete>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["ignored"] = "3";
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
CPPUNIT_ASSERT_NO_THROW( proxy.Delete( parameters ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
// check table contents: no changes yet since it hasn't been committed
expected.str("");
expected << "1,Alpha" << std::endl
<< "2,Bravo" << std::endl
<< "3,Charlie" << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "OracleTable", "ot_id,ot_desc", "ot_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
// Verify that the appropriate record is deleted.
expected.str("");
expected << "2,Bravo" << std::endl
<< "3,Charlie" << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleDB, "OracleTable", "ot_id,ot_desc", "ot_id" )
}
void DatabaseProxyTest::testDeleteWithMultipleVariableNames()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
m_pOracleDB->Commit();
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete connection = \"myOracleConnection\" "
<< " query = \"Delete from OracleTable where ot_id < ${idToMatch1} and ot_id > ${idToMatch2}\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch1"] = "4";
// Only allow 2 records to be deleted
parameters["idToMatch2"] = "2";
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
CPPUNIT_ASSERT_NO_THROW( proxy.Delete( parameters ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
// check table contents: no changes yet since it hasn't been committed
expected.str("");
expected << "1,Alpha" << std::endl
<< "2,Bravo" << std::endl
<< "3,Charlie" << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "OracleTable", "ot_id,ot_desc", "ot_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
// Verify that the appropriate records are deleted
expected.str("");
expected << "1,Alpha" << std::endl
<< "2,Bravo" << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleDB, "OracleTable", "ot_id,ot_desc", "ot_id" )
}
void DatabaseProxyTest::testDeleteSameVarNameReplacedTwice()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
m_pOracleDB->Commit();
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete connection = \"myOracleConnection\" "
<< " query = \"Delete from OracleTable where ot_id < ${idToMatch} or ot_id = ${idToMatch}\" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
CPPUNIT_ASSERT_NO_THROW( proxy.Delete( parameters ) );
std::stringstream expected;
expected << "MockDatabaseConnectionManager::ValidateConnectionName" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
expected << "MockDatabaseConnectionManager::GetConnection" << std::endl
<< "ConnectionName: myOracleConnection" << std::endl
<< std::endl;
CPPUNIT_ASSERT_EQUAL(expected.str(), dbManager.GetLog());
// check table contents: no changes yet since it hasn't been committed
expected.str("");
expected << "1,Alpha" << std::endl
<< "2,Bravo" << std::endl
<< "3,Charlie" << std::endl
<< "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "OracleTable", "ot_id,ot_desc", "ot_id" )
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
// Verify that the appropriate records are deleted
expected.str("");
expected << "4,Delta" << std::endl
<< "5,Echo" << std::endl;
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "OracleTable", "ot_id,ot_desc", "ot_id" )
}
void DatabaseProxyTest::testDeleteExceptionEmptyVarName()
{
MockDataProxyClient client;
//Create a Database table and populate it
Database::Statement(*m_pOracleDB, "Create Table OracleTable(ot_id INT, ot_desc VARCHAR(64))").Execute();
std::string cmd( "INSERT INTO OracleTable (ot_id, ot_desc) VALUES ");
std::vector<std::string> values;
values.push_back( "(1, 'Alpha')");
values.push_back( "(2, 'Bravo')");
values.push_back( "(3, 'Charlie')");
values.push_back( "(4, 'Delta')");
values.push_back( "(5, 'Echo')");
for( size_t i = 0; i < values.size(); ++i )
{
Database::Statement stmt( *m_pOracleDB, cmd+values[i] );
stmt.Execute();
}
m_pOracleDB->Commit();
//Create a Database XML node
std::stringstream xmlContents;
xmlContents << "<DataNode type = \"db\" >"
<< " <Delete connection = \"myOracleConnection\" "
<< " query = \"Delete ot_id, ot_desc from OracleTable where ot_id = ${idToMatch} or ot_id = ${} \" />"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
MockDatabaseConnectionManager dbManager;
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
std::map< std::string, std::string > parameters;
parameters["idToMatch"] = "3";
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Delete( parameters ),
ProxyUtilitiesException,
MATCH_FILE_AND_LINE_NUMBER + "Variable name referenced must be alphanumeric \\(enclosed within \"\\$\\{\" and \"\\}\"\\)\\."
" Instead it is: '\\$\\{\\}'");
}
void DatabaseProxyTest::testOracleStoreWithPreStatement()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
// create primary & staging tables
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
Database::Statement(*m_pOracleDB, GetOracleTableDDL("stg_kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myOracleConnection\"\n"
" table=\"kna\"\n"
" stagingTable=\"stg_kna\"\n"
" workingDir=\"" + m_pTempDir->GetDirectoryName() + "\"\n"
" noCleanUp=\"true\"\n"
" pre-statement=\"insert into kna (media_id,website_id,impressions,revenue,dummy,myConstant) VALUES (1000,2000,3999,4999,5999,6999)\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the data to be stored
std::string data
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1001,2001,3001,4001,5001,6001\n" //should be inserted
"1000,2000,3000,4000,5000,6000\n" //should be ignored because the key exists and we are configured to only insert non-matched rows
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
std::map< std::string, std::string > parameters;
std::stringstream dataStream(data);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
std::string expectedAfterCommit
(
"1000,2000,3999,4999,5999,6999\n"
"1001,2001,3001,4001,5001,6001\n"
);
//the following verifies that:
//a. 'pre-statement' was executed
//b. the upload was executed
//c. 'pre-statement' was executed before the upload assuming that we correctly configured the data node to insert non-matched rows only
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedAfterCommit, *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
void DatabaseProxyTest::testOracleStoreWithPostStatement()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
// create primary & staging tables
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
Database::Statement(*m_pOracleDB, GetOracleTableDDL("stg_kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myOracleConnection\"\n"
" table=\"kna\"\n"
" stagingTable=\"stg_kna\"\n"
" workingDir=\"" + m_pTempDir->GetDirectoryName() + "\"\n"
" noCleanUp=\"true\"\n"
" post-statement=\"update kna set myConstant=42\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the data to be stored
std::string data
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1001,2001,3001,4001,5001,6001\n"
"1000,2000,3000,4000,5000,6000\n"
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
std::map< std::string, std::string > parameters;
std::stringstream dataStream(data);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
std::string expectedAfterCommit
(
"1000,2000,3000,4000,5000,42\n"
"1001,2001,3001,4001,5001,42\n"
);
//the following verifies that:
//a. 'post-statement' was executed
//b. the upload was executed
//c. 'post-statement' was executed after the upload
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedAfterCommit, *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
void DatabaseProxyTest::testOracleStoreWithBothPreStatementAndPostStatement()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
// create primary & staging tables
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
Database::Statement(*m_pOracleDB, GetOracleTableDDL("stg_kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myOracleConnection\"\n"
" table=\"kna\"\n"
" stagingTable=\"stg_kna\"\n"
" workingDir=\"" + m_pTempDir->GetDirectoryName() + "\"\n"
" noCleanUp=\"true\"\n"
" pre-statement=\"insert into kna (media_id,website_id,impressions,revenue,dummy,myConstant) VALUES (1000,2000,3999,4999,5999,${preConstant})\"\n"
" post-statement=\"update kna set myConstant=${postConstant}\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the data to be stored
std::string data
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1001,2001,3001,4001,5001,6001\n"
"1000,2000,3000,4000,5000,6000\n"
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
std::map< std::string, std::string > parameters;
parameters["preConstant"] = "6999";
parameters["postConstant"] = "42";
std::stringstream dataStream(data);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
std::string expectedAfterCommit
(
"1000,2000,3999,4999,5999,42\n"
"1001,2001,3001,4001,5001,42\n"
);
//the following verifies that:
//a. 'pre-statement' was executed
//b. 'post-statement' was executed
//c. the upload was executed
//d. the order was: 'pre-statement', upload, 'post-statement'
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedAfterCommit, *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
void DatabaseProxyTest::testOracleStoreWithBothPreStatementAndPostStatementNoData()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
// create primary & staging tables
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
Database::Statement(*m_pOracleDB, GetOracleTableDDL("stg_kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myOracleConnection\"\n"
" table=\"kna\"\n"
" stagingTable=\"stg_kna\"\n"
" workingDir=\"" + m_pTempDir->GetDirectoryName() + "\"\n"
" noCleanUp=\"true\"\n"
" pre-statement=\"insert into kna (media_id,website_id,impressions,revenue,dummy,myConstant) VALUES (1000,2000,3999,4999,5999,${preConstant})\"\n"
" post-statement=\"update kna set myConstant=${postConstant}\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the data to be stored
std::string data
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
std::map< std::string, std::string > parameters;
parameters["preConstant"] = "6999";
parameters["postConstant"] = "42";
std::stringstream dataStream(data);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
std::string expectedAfterCommit
(
"1000,2000,3999,4999,5999,42\n"
);
//the following verifies that:
//a. 'pre-statement' was executed
//b. 'post-statement' was executed
//c. the upload was a no-op
//d. the order was: 'pre-statement', 'post-statement'
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedAfterCommit, *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
void DatabaseProxyTest::testOracleStoreWithBothPreStatementAndPostStatementNoStaging()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
// create primary & staging tables
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myOracleConnection\"\n"
" table=\"kna\"\n"
" pre-statement=\"insert into kna (media_id,website_id,impressions,revenue,dummy,myConstant) VALUES (1000,2000,3999,4999,5999,${preConstant})\"\n"
" post-statement=\"update kna set myConstant=${postConstant}\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the data to be stored
std::string data
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1001,2001,3001,4001,5001,6001\n"
"1000,2000,3000,4000,5000,6000\n"
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
std::map< std::string, std::string > parameters;
parameters["preConstant"] = "6999";
parameters["postConstant"] = "42";
std::stringstream dataStream(data);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
std::string expectedAfterCommit
(
"1000,2000,3999,4999,5999,42\n"
"1001,2001,3001,4001,5001,42\n"
);
//the following verifies that:
//a. 'pre-statement' was executed
//b. 'post-statement' was executed
//c. the upload was executed
//d. the order was: 'pre-statement', upload, 'post-statement'
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedAfterCommit, *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
void DatabaseProxyTest::testMySqlStoreWithPreStatement()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySQLConnection", m_pMySQLDB);
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myMySQLConnection\"\n"
" table=\"kna\"\n"
" stagingTable=\"stg_kna\"\n"
" workingDir=\"" + m_pTempDir->GetDirectoryName() + "\"\n"
" noCleanUp=\"true\"\n"
" pre-statement=\"insert into kna (media_id,website_id,impressions,revenue,dummy,myConstant) VALUES (1000,2000,3999,4999,5999,6999)\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the data to be stored
std::string data
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1001,2001,3001,4001,5001,6001\n" //should be inserted
"1000,2000,3000,4000,5000,6000\n" //should be ignored because the key exists and we are configured to only insert non-matched rows
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
std::map< std::string, std::string > parameters;
std::stringstream dataStream(data);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
std::string expectedAfterCommit
(
"1000,2000,3999,4999,5999,6999\n"
"1001,2001,3001,4001,5001,6001\n"
);
//the following verifies that:
//a. 'pre-statement' was executed
//b. the upload was executed
//c. 'pre-statement' was executed before the upload assuming that we correctly configured the data node to insert non-matched rows only
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedAfterCommit, *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
void DatabaseProxyTest::testMySqlStoreWithPostStatement()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySQLConnection", m_pMySQLDB);
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myMySQLConnection\"\n"
" table=\"kna\"\n"
" stagingTable=\"stg_kna\"\n"
" workingDir=\"" + m_pTempDir->GetDirectoryName() + "\"\n"
" noCleanUp=\"true\"\n"
" post-statement=\"update kna set myConstant=42\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the data to be stored
std::string data
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1001,2001,3001,4001,5001,6001\n"
"1000,2000,3000,4000,5000,6000\n"
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
std::map< std::string, std::string > parameters;
std::stringstream dataStream(data);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
std::string expectedAfterCommit
(
"1000,2000,3000,4000,5000,42\n"
"1001,2001,3001,4001,5001,42\n"
);
//the following verifies that:
//a. 'post-statement' was executed
//b. the upload was executed
//c. 'post-statement' was executed after the upload
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedAfterCommit, *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
void DatabaseProxyTest::testMySqlStoreWithBothPreStatementAndPostStatement()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySQLConnection", m_pMySQLDB);
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myMySQLConnection\"\n"
" table=\"kna\"\n"
" stagingTable=\"stg_kna\"\n"
" workingDir=\"" + m_pTempDir->GetDirectoryName() + "\"\n"
" noCleanUp=\"true\"\n"
" pre-statement=\"insert into kna (media_id,website_id,impressions,revenue,dummy,myConstant) VALUES (1000,2000,3999,4999,5999,${preConstant})\"\n"
" post-statement=\"update kna set myConstant=${postConstant}\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the data to be stored
std::string data
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1001,2001,3001,4001,5001,6001\n"
"1000,2000,3000,4000,5000,6000\n"
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
std::map< std::string, std::string > parameters;
parameters["preConstant"] = "6999";
parameters["postConstant"] = "42";
std::stringstream dataStream(data);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
std::string expectedAfterCommit
(
"1000,2000,3999,4999,5999,42\n"
"1001,2001,3001,4001,5001,42\n"
);
//the following verifies that:
//a. 'pre-statement' was executed
//b. 'post-statement' was executed
//c. the upload was executed
//d. the order was: 'pre-statement', upload, 'post-statement'
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedAfterCommit, *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
void DatabaseProxyTest::testMySqlStoreWithBothPreStatementAndPostStatementNoData()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySQLConnection", m_pMySQLDB);
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myMySQLConnection\"\n"
" table=\"kna\"\n"
" stagingTable=\"stg_kna\"\n"
" workingDir=\"" + m_pTempDir->GetDirectoryName() + "\"\n"
" noCleanUp=\"true\"\n"
" pre-statement=\"insert into kna (media_id,website_id,impressions,revenue,dummy,myConstant) VALUES (1000,2000,3999,4999,5999,${preConstant})\"\n"
" post-statement=\"update kna set myConstant=${postConstant}\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the data to be stored
std::string data
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
std::map< std::string, std::string > parameters;
parameters["preConstant"] = "6999";
parameters["postConstant"] = "42";
std::stringstream dataStream(data);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
std::string expectedAfterCommit
(
"1000,2000,3999,4999,5999,42\n"
);
//the following verifies that:
//a. 'pre-statement' was executed
//b. 'post-statement' was executed
//c. the upload was a no-op
//d. the order was: 'pre-statement', 'post-statement'
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedAfterCommit, *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
void DatabaseProxyTest::testMySqlStoreWithBothPreStatementAndPostStatementNoStaging()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySQLConnection", m_pMySQLDB);
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myMySQLConnection\"\n"
" table=\"kna\"\n"
" pre-statement=\"insert into kna (media_id,website_id,impressions,revenue,dummy,myConstant) VALUES (1000,2000,3999,4999,5999,${preConstant})\"\n"
" post-statement=\"update kna set myConstant=${postConstant}\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the data to be stored
std::string data
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1001,2001,3001,4001,5001,6001\n"
"1000,2000,3000,4000,5000,6000\n"
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) );
std::map< std::string, std::string > parameters;
parameters["preConstant"] = "6999";
parameters["postConstant"] = "42";
std::stringstream dataStream(data);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
std::string expectedAfterCommit
(
"1000,2000,3999,4999,5999,42\n"
"1001,2001,3001,4001,5001,42\n"
);
//the following verifies that:
//a. 'pre-statement' was executed
//b. 'post-statement' was executed
//c. the upload was executed
//d. the order was: 'pre-statement', upload, 'post-statement'
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedAfterCommit, *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
//-verify the following
//a. if two stores are executed with the same data proxy without commit every being called then no data is stored to the primary table
void DatabaseProxyTest::testOracleMultipleStore()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myOracleConnection", m_pOracleDB);
// create primary & staging tables
Database::Statement(*m_pOracleDB, GetOracleTableDDL("kna")).Execute();
Database::Statement(*m_pOracleDB, GetOracleTableDDL("stg_kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myOracleConnection\"\n"
" table=\"kna\"\n"
" stagingTable=\"stg_kna\"\n"
" workingDir=\"" + m_pTempDir->GetDirectoryName() + "\"\n"
" noCleanUp=\"true\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the first store
std::string firstStoreData
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1000,2000,3000,4000,5000,6000\n"
"1001,2001,3001,4001,5001,6001\n"
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
CPPUNIT_ASSERT_NO_THROW(pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) ));
std::map< std::string, std::string > parameters;
std::stringstream dataStream(firstStoreData);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
//the second store
std::string secondStoreData
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1002,2002,3002,4002,5002,6002\n"
);
std::stringstream dataStreamTwo(secondStoreData);
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStreamTwo));
//we still have never called commit; no data should be stored
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
std::string expectedData
(
"1000,2000,3000,4000,5000,6000\n"
"1001,2001,3001,4001,5001,6001\n"
"1002,2002,3002,4002,5002,6002\n"
);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedData, *m_pOracleObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
//-verify the following
//a. if two stores are executed with the same mysql data proxy without commit every being called then no data is stored to the primary table
void DatabaseProxyTest::testMySqlMultipleStore()
{
MockDataProxyClient client;
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection("myMySQLConnection", m_pMySQLDB);
// create primary & staging tables
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("kna")).Execute();
Database::Statement(*m_pMySQLDB, GetMySqlTableDDL("stg_kna")).Execute();
//Create a Database XML node
std::string xmlContents
(
"<DataNode type = \"db\" >\n"
" <Write connection=\"myMySQLConnection\"\n"
" table=\"kna\"\n"
" stagingTable=\"stg_kna\"\n"
" workingDir=\"" + m_pTempDir->GetDirectoryName() + "\"\n"
" noCleanUp=\"true\">\n"
" <Columns>\n"
" <Column name=\"media_id\" type=\"key\" />\n"
" <Column name=\"website_id\" type=\"key\" />\n"
" <Column name=\"impressions\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"revenue\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"dummy\" type=\"data\" ifNew=\"%v\" />\n"
" <Column name=\"myConstant\" type=\"data\" ifNew=\"%v\" />\n"
" </Columns>\n"
" </Write>\n"
"</DataNode>\n"
);
//the first store
std::string firstStoreData
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1000,2000,3000,4000,5000,6000\n"
"1001,2001,3001,4001,5001,6001\n"
);
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents, "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
boost::scoped_ptr< DatabaseProxy > pProxy;
CPPUNIT_ASSERT_NO_THROW(pProxy.reset( new DatabaseProxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager ) ));
std::map< std::string, std::string > parameters;
std::stringstream dataStream(firstStoreData);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStream));
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT(!dataStream.bad());
//the second store
std::string secondStoreData
(
"media_id,website_id,impressions,revenue,dummy,myConstant\n"
"1002,2002,3002,4002,5002,6002\n"
);
std::stringstream dataStreamTwo(secondStoreData);
CPPUNIT_ASSERT_NO_THROW(pProxy->Store(parameters, dataStreamTwo));
//we still have never called commit; no data should be stored
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( std::string(""), *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
CPPUNIT_ASSERT_NO_THROW( pProxy->Commit() );
std::string expectedData
(
"1000,2000,3000,4000,5000,6000\n"
"1001,2001,3001,4001,5001,6001\n"
"1002,2002,3002,4002,5002,6002\n"
);
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expectedData, *m_pMySQLObservationDB, "kna", "media_id,website_id,impressions,revenue,dummy,myConstant", "media_id" );
}
void DatabaseProxyTest::testOracleStoreNoStagingWithMaxColumnLength()
{
MockDataProxyClient client;
// create primary table
Database::Statement(*m_pOracleDB, GetElementsOracleDDL("fake_elements")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myOracleConnection", m_pOracleDB );
std::stringstream xmlNoLengthAttribute;
xmlNoLengthAttribute << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"fake_elements\" >"
<< " <Columns>"
<< " <Column name=\"fake_element_id\" type=\"key\" />"
<< " <Column name=\"fake_element_name\" type=\"data\" ifNew=\"%v\"/>"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlNoLengthAttribute.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream header;
header << "fake_element_id,fake_element_name" << std::endl;
std::stringstream row_14CharacterName;
row_14CharacterName << "1,joelonsoftware" << std::endl;
std::stringstream storeInputCSV0;
storeInputCSV0 << header.str()
<< row_14CharacterName.str();
std::map< std::string, std::string > parameters;
//should succeed because the default bind size of 256 is larger than the 14 character element name
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, storeInputCSV0 ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
//check table contents
std::stringstream expected;
expected << row_14CharacterName.str();
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "fake_elements", "fake_element_id,fake_element_name", "fake_element_id" );
std::stringstream row_257CharacterName;
row_257CharacterName << "2,";
for (int i = 0; i < 257; i++)
{
row_257CharacterName << "g";
}
row_257CharacterName << std::endl;
std::stringstream storeInputCSV1;
storeInputCSV1 << header.str()
<< row_257CharacterName.str();
//now use a 257 character name: should fail because default bind size of 256 can not hold the 257 character element name
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Store( parameters, storeInputCSV1 ),
DBException,
".*?trailing null missing from STR bind value.*");
std::stringstream xmlLengthOf257;
xmlLengthOf257 << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"fake_elements\" >"
<< " <Columns>"
<< " <Column name=\"fake_element_id\" type=\"key\" />"
<< " <Column name=\"fake_element_name\" type=\"data\" ifNew=\"%v\" length=\"257\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlLengthOf257.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy1( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream storeInputCSV2;
storeInputCSV2 << header.str()
<< row_257CharacterName.str();
//now add a length attribute and set it to 257: should succeed because it can hold the 257 character element name
CPPUNIT_ASSERT_NO_THROW( proxy1.Store( parameters, storeInputCSV2 ) );
CPPUNIT_ASSERT_NO_THROW( proxy1.Commit() );
expected << row_257CharacterName.str();
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "fake_elements", "fake_element_id,fake_element_name", "fake_element_id" );
}
void DatabaseProxyTest::testOracleStoreWithStagingWithMaxColumnLength()
{
MockDataProxyClient client;
// create primary table
Database::Statement(*m_pOracleDB, GetElementsOracleDDL("fake_elements")).Execute();
// create stagint table
Database::Statement(*m_pOracleDB, GetElementsOracleDDL("stg_fake_elements")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myOracleConnection", m_pOracleDB );
std::stringstream xmlNoLengthAttribute;
xmlNoLengthAttribute << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"fake_elements\" "
<< " stagingTable = \"stg_fake_elements\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\" >"
<< " <Columns>"
<< " <Column name=\"fake_element_id\" type=\"key\" />"
<< " <Column name=\"fake_element_name\" type=\"data\" ifNew=\"%v\"/>"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlNoLengthAttribute.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream header;
header << "fake_element_id,fake_element_name" << std::endl;
std::stringstream row_14CharacterName;
row_14CharacterName << "1,joelonsoftware" << std::endl;
std::stringstream storeInputCSV0;
storeInputCSV0 << header.str()
<< row_14CharacterName.str();
std::map< std::string, std::string > parameters;
//should succeed because the default bind size of 256 is larger than the 14 character element name
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, storeInputCSV0 ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
//check table contents
std::stringstream expected;
expected << row_14CharacterName.str();
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "fake_elements", "fake_element_id,fake_element_name", "fake_element_id" );
std::stringstream row_257CharacterName;
row_257CharacterName << "2,";
for (int i = 0; i < 257; i++)
{
row_257CharacterName << "g";
}
row_257CharacterName << std::endl;
std::stringstream storeInputCSV1;
storeInputCSV1 << header.str()
<< row_257CharacterName.str();
//now use a 257 character name: should fail because default bind size of 256 can not hold the 257 character element name
CPPUNIT_ASSERT_THROW_WITH_MESSAGE( proxy.Store( parameters, storeInputCSV1 ),
DatabaseProxyException,
".*?SQLLoader failed!.*");
std::stringstream xmlLengthOf257;
xmlLengthOf257 << "<DataNode type = \"db\" >"
<< " <Write connection = \"myOracleConnection\""
<< " table = \"fake_elements\" "
<< " stagingTable = \"stg_fake_elements\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\" >"
<< " <Columns>"
<< " <Column name=\"fake_element_id\" type=\"key\" />"
<< " <Column name=\"fake_element_name\" type=\"data\" ifNew=\"%v\" length=\"257\" />"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
nodes.clear();
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlLengthOf257.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy1( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream storeInputCSV2;
storeInputCSV2 << header.str()
<< row_257CharacterName.str();
//now add a length attribute and set it to 257: should succeed because it can hold the 257 character element name
CPPUNIT_ASSERT_NO_THROW( proxy1.Store( parameters, storeInputCSV2 ) );
CPPUNIT_ASSERT_NO_THROW( proxy1.Commit() );
expected << row_257CharacterName.str();
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pOracleObservationDB, "fake_elements", "fake_element_id,fake_element_name", "fake_element_id" );
}
void DatabaseProxyTest::testMySQLStoreWithStagingWithMaxColumnLength()
{
MockDataProxyClient client;
// create primary table
Database::Statement(*m_pMySQLDB, GetElementsMySqlDDL("fake_elements")).Execute();
// create stagint table
Database::Statement(*m_pMySQLDB, GetElementsMySqlDDL("stg_fake_elements")).Execute();
MockDatabaseConnectionManager dbManager;
dbManager.InsertConnection( "myMySQLConnection", m_pMySQLDB );
std::stringstream xmlNoLengthAttribute;
xmlNoLengthAttribute << "<DataNode type = \"db\" >"
<< " <Write connection = \"myMySQLConnection\""
<< " table = \"fake_elements\" "
<< " stagingTable = \"stg_fake_elements\" "
<< " workingDir = \"" << m_pTempDir->GetDirectoryName() << "\" >"
<< " <Columns>"
<< " <Column name=\"fake_element_id\" type=\"key\" />"
<< " <Column name=\"fake_element_name\" type=\"data\" ifNew=\"%v\"/>"
<< " </Columns>"
<< " </Write>"
<< "</DataNode>";
std::vector<xercesc::DOMNode*> nodes;
ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlNoLengthAttribute.str(), "DataNode", nodes );
CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
DatabaseProxy proxy( "name", boost::shared_ptr< RequestForwarder >( new MockRequestForwarder( client ) ), *nodes[0], dbManager );
FileUtilities::ClearDirectory( m_pTempDir->GetDirectoryName() );
std::stringstream header;
header << "fake_element_id,fake_element_name" << std::endl;
std::stringstream row_14CharacterName;
row_14CharacterName << "1,joelonsoftware" << std::endl;
std::stringstream storeInputCSV0;
storeInputCSV0 << header.str()
<< row_14CharacterName.str();
std::map< std::string, std::string > parameters;
//should succeed because the default bind size of 256 is larger than the 14 character element name
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, storeInputCSV0 ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
//check table contents
std::stringstream expected;
expected << row_14CharacterName.str();
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "fake_elements", "fake_element_id,fake_element_name", "fake_element_id" );
std::stringstream field_257CharacterName;
for (int i = 0; i < 257; i++)
{
field_257CharacterName << "g";
}
std::stringstream row_257CharacterName;
row_257CharacterName << "2," << field_257CharacterName.str() << std::endl;
std::stringstream storeInputCSV1;
storeInputCSV1 << header.str()
<< row_257CharacterName.str();
//now use a 257 character name: should succeed because we use a 'load data infile' to load into the staging table and that doesn't require us to specify a buffer size.
CPPUNIT_ASSERT_NO_THROW( proxy.Store( parameters, storeInputCSV1 ) );
CPPUNIT_ASSERT_NO_THROW( proxy.Commit() );
expected << row_257CharacterName.str();
CPPUNIT_ASSERT_TABLE_ORDERED_CONTENTS( expected.str(), *m_pMySQLObservationDB, "fake_elements", "fake_element_id,fake_element_name", "fake_element_id" );
}
| 42.164053 | 189 | 0.669574 | [
"vector"
] |
035e1427bb1b2b31034272488c4a3c9c9469c45c | 876 | cpp | C++ | src/processor.cpp | encomp/CppND-System-Monitor | f16f0168f001c6e64257e44daac2ebb55f0c64f3 | [
"MIT"
] | null | null | null | src/processor.cpp | encomp/CppND-System-Monitor | f16f0168f001c6e64257e44daac2ebb55f0c64f3 | [
"MIT"
] | null | null | null | src/processor.cpp | encomp/CppND-System-Monitor | f16f0168f001c6e64257e44daac2ebb55f0c64f3 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include "processor.h"
using std::vector;
using std::string;
using std::stoi;
Processor::Processor(vector<string> cpu) {
init = false;
if (cpu.size() == 10) {
user = stoi(cpu[0]);
nice = stoi(cpu[1]);
system = stoi(cpu[2]);
idle = stoi(cpu[3]);
iowait = stoi(cpu[4]);
irq = stoi(cpu[5]);
softirq = stoi(cpu[6]);
steal = stoi(cpu[7]);
guest = stoi(cpu[8]);
guestNice = stoi(cpu[9]);
init = true;
}
}
// Return the aggregate CPU utilization
float Processor::Utilization() {
float Cpu = 0.0;
if (init) {
long Idle = idle + iowait;
long NonIdle = user + nice + system + irq + softirq + steal;
long Total = Idle + NonIdle;
Cpu = (Total - Idle) * 100 / Total;
Cpu /= 100;
}
return Cpu;
} | 23.675676 | 68 | 0.528539 | [
"vector"
] |
24ee714e84513ec025333ada5787169758ecfac7 | 19,923 | cpp | C++ | src/meshing/dual_contouring.cpp | aschier/MishMesh | 6128e33501935b57c80c7e0816aa1b2229907990 | [
"BSD-3-Clause"
] | 2 | 2019-08-15T11:10:35.000Z | 2022-01-27T02:30:47.000Z | src/meshing/dual_contouring.cpp | aschier/MishMesh | 6128e33501935b57c80c7e0816aa1b2229907990 | [
"BSD-3-Clause"
] | null | null | null | src/meshing/dual_contouring.cpp | aschier/MishMesh | 6128e33501935b57c80c7e0816aa1b2229907990 | [
"BSD-3-Clause"
] | 1 | 2021-05-26T13:25:28.000Z | 2021-05-26T13:25:28.000Z | #include "MishMesh/dual_contouring.h"
#include "vertexfit.hpp"
#include "grid.hpp"
#include <list>
namespace MishMesh {
namespace Meshing {
namespace DualContouring {
struct MeshProperties {
OpenMesh::VPropHandleT<std::vector<OpenMesh::Vec3d>> normals;
OpenMesh::VPropHandleT<std::vector<OpenMesh::Vec3d>> intersection_points;
OpenMesh::VPropHandleT<int> cube_idx;
};
/**
* An undirected edge
*/
struct Edge {
int idx1, idx2;
Edge(int idx1, int idx2) {
this->idx1 = std::min(idx1, idx2);
this->idx2 = std::max(idx1, idx2);
}
bool operator<(const Edge &other) const {
return idx1 < other.idx1 || (idx1 == other.idx1 && idx2 < other.idx2);
}
bool operator==(const Edge &other) const {
return idx1 != other.idx1 || idx2 != other.idx2;
}
};
/**
* A directed halfedge storing everything needed to build a halfedge mesh.
*/
struct HalfEdge {
int idx1, idx2;
OpenMesh::Vec3d normal;
OpenMesh::Vec3d intersection_point;
HalfEdge *opposite;
HalfEdge *next;
HalfEdge *prev;
MishMesh::PolyMesh::VertexHandle vh{};
bool visited = false;
bool boundary = false;
bool quad_edge = false;
};
/**
* Test if an edge between points with these values is intersected by isosurface algorithms.
* This function checks for three conditions to resolve ambiguities:
* - If at least one point is infinite, there is no intersection.
* - If value1*value2 < 0, there is an intersection.
* - If one value is 0 and the other value is smaller than 0, there is an intersection.
* @param value1 The value of the first point.
* @param value2 The value of the second point.
* @returns True, if there is an intersection.
*/
inline bool has_intersection(double value1, double value2) {
if(!std::isfinite(value1) || !std::isfinite(value2)) return false;
if(value1 * value2 < 0) return true;
if(value1 == 0 && value2 < 0) return true;
if(value1 < 0 && value2 == 0) return true;
return false;
}
/**
* Interpolate the point and normal along a grid edge from the coordinates and normals at the grid points.
* @param grid The grid.
* @param point_values The values at the grid points.
* @param point_normals The normals at the grid points..
* @param idx2 The index of the second grid point.
* @returns A interpolated point and the interpolated point normal.
*/
template<typename GridT>
std::pair<OpenMesh::Vec3d, OpenMesh::Vec3d> interpolate_point_and_normal(const GridT &grid, const std::vector<double> &point_values, const std::vector<OpenMesh::Vec3d> &point_normals, int idx1, int idx2) {
double value1 = point_values[idx1];
double value2 = point_values[idx2];
double alpha = -value2 / (value1 - value2);
assert(alpha >= 0 && alpha <= 1);
OpenMesh::Vec3d normal = (point_normals[idx1] * alpha + point_normals[idx2] * (1.0 - alpha)).normalized();
OpenMesh::Vec3d point = grid.point(idx1) * alpha + grid.point(idx2) * (1.0 - alpha);
return std::make_pair(point, normal);
}
/**
* Sample the distance function at the grid points.
<<<<<<< HEAD
* @param grid The grid.
* @param distance_function A function for calculating distances and normals.
>>>>>>> af85d32... Added a dual contouring implementation
*/
template<typename GridT>
std::pair<std::vector<double>, std::vector<OpenMesh::Vec3d>> compute_point_values_and_normals(const GridT &grid, ::MishMesh::Meshing::DistanceFunction distance_function, void *distance_function_data) {
const auto resolution = grid.resolution();
std::vector<double> point_values(resolution[0] * resolution[1] * resolution[2]);
std::vector<OpenMesh::Vec3d> point_normals(resolution[0] * resolution[1] * resolution[2]);
#pragma omp parallel for
for(int i = 0; i < resolution[0]; i++) {
for(int j = 0; j < resolution[1]; j++) {
for(int k = 0; k < resolution[2]; k++) {
OpenMesh::Vec3d p = grid.point(i, j, k);
int index = grid.point_idx(i, j, k);
std::tie(point_values[index], point_normals[index]) = distance_function(p, distance_function_data);
}
}
}
return make_pair(point_values, point_normals);
}
/**
* Create the halfedges belonging to one grid face, that are dual to the edges the face.
* @param[inout] halfedges The list with halfedges.
* @param[inout] gridedge_to_halfedges A map that assigns each grid edge the (four) halfedges that intersect
* the faces adjacent to the grid edge.
* @param grid The grid.
* @param point_values The distance function values at the grid points.
* @param point_normals The distance function normals at the grid points.
* @param i The step in x direction.
* @param j The step in y direction.
* @param k The step in z direction.
* @param faceDirection The direction of the processed face. Each cube (i,j,k) is used to process its LEFT/TOP/FAR faces.
*/
template<typename GridT>
void create_face_halfedges(std::list<HalfEdge> &halfedges, std::map<Edge, std::vector<HalfEdge *>> &gridedge_to_halfedges, const GridT &grid, const std::vector<double> &point_values, const std::vector<OpenMesh::Vec3d> &point_normals, int i, int j, int k, FaceDirection faceDirection) {
// Get the indices of the corners of the face
std::array<int, 4> idxs = grid.face_idxs(faceDirection, i, j, k);
HalfEdge *previous_halfedge = nullptr;
for(short l = 0; l < 4; l++) {
// The edge intersects the isosurface
if(has_intersection(point_values[idxs[l]], point_values[idxs[(l + 1) % 4]])) {
OpenMesh::Vec3d point;
OpenMesh::Vec3d normal;
std::tie(point, normal) = interpolate_point_and_normal(grid, point_values, point_normals, idxs[l], idxs[(l + 1) % 4]);
// Use an undirected primal cube edge to identify the quad around it.
Edge edge = Edge(idxs[l], idxs[(l + 1) % 4]);
// Create the halfedge between this cube and the left, top or far neighbor cube,
// which has its index shifted by -1 in the corresponding dimension.
int cube_idx1 = idxs[0];
int cube_idx2 = grid.point_idx(cube_idx1,
faceDirection == LEFT ? -1 : 0,
faceDirection == TOP ? -1 : 0,
faceDirection == FAR ? -1 : 0);
// Flip the halfedge depending on the direction (positive to negative) of the primal cube edge.
if(point_values[idxs[l]] > point_values[idxs[(l + 1) % 4]]) {
std::swap(cube_idx1, cube_idx2);
}
halfedges.push_back({cube_idx1, cube_idx2,
normal, point, previous_halfedge});
auto halfedge_ptr = &halfedges.back();
gridedge_to_halfedges[edge].push_back(halfedge_ptr);
// A grid face is intersected by four dual halfedges, that belong to the grid face and one of its edges
// and every second halfedge is connected to the previous one as its opposite edge.
// This gives correct connectivity for the three possible cases:
// 1) One different sign -> Create a wedge (e.g. crossing left and top edge)
// 2) Two different signs next to each other -> Create plane (e.g. crossing left and right edge)
// 3) Two different signs at opposite corners of the face -> Create two wedges
// (e.g. a wedge crossing left and top edges and a wedge crossing bottom and right edges)
//
// | |
// +--|---+ +------+ +--|---+
// __|__| | __|______|__ __|__| |
// | | | | | __|__
// | | | | | | |
// +------+ +------+ +---|--+
// |
// (1) (2) (3)
if(previous_halfedge != nullptr) {
assert(previous_halfedge->opposite == nullptr);
previous_halfedge->opposite = halfedge_ptr;
assert(halfedge_ptr->opposite == previous_halfedge);
// Unset previous_halfedge, so the next intersection creates a new halfedge
previous_halfedge = nullptr;
} else {
// Set previous_halfedge, so the next halfedge will be used as the opposite of this one.
previous_halfedge = halfedge_ptr;
}
}
}
}
/**
* Run create_face_halfedges for every face in the grid.
* @param[out] halfedges A list of halfedges.
* @param[out] gridedge_to_halfedge A map that contains for each grid edge a list of halfedges forming a face around the grid edge.
* @param grid The grid.
* @param point_values The distance values at the grid points.
* @param point_normals The normals at the grid points.
*/
template<typename GridT>
void create_halfedges(std::list<HalfEdge> &halfedges, std::map<Edge, std::vector<HalfEdge *>> &gridedge_to_halfedges, const GridT &grid, const std::vector<double> &point_values, const std::vector<OpenMesh::Vec3d> &point_normals) {
const auto resolution = grid.numCells();
for(int i = 0; i < resolution[0]; i++) {
for(int j = 0; j < resolution[1]; j++) {
for(int k = 0; k < resolution[2]; k++) {
for(short dim = 0; dim < 3; dim++) {
FaceDirection faceDirection = dim == 0 ? FaceDirection::LEFT : (dim == 1 ? FaceDirection::TOP : FaceDirection::FAR);
create_face_halfedges(halfedges, gridedge_to_halfedges, grid, point_values, point_normals, i, j, k, faceDirection);
}
}
}
}
}
/**
* Create quads in the halfedge structure using the information which halfedges belong to a dual face intersected by a grid edge.
* @param grid The grid.
* @param grid_edge_to_halfedges A map, that maps edges in the grid to the half edges that belong to the edge.
*/
template<typename GridT>
void assemble_quads(const GridT &grid, const std::map<Edge, std::vector<HalfEdge *>> &grid_edge_to_halfedges) {
for(auto &edge_quad_pair : grid_edge_to_halfedges) {
auto &quad_halfedges = edge_quad_pair.second;
if(quad_halfedges.size() != 4) {
// Remove invalid quads, that are generated at the boundary
// when a quad intersects cube faces that are outside of the bounding box
for(auto &he : quad_halfedges) {
he->quad_edge = false; // the edge does not belong to a quad
if(he->opposite != nullptr) {
// invalidate the opposite pointer of the opposite halfedge,
// so that a boundary edge will be generated for the remaining half edge
he->opposite->opposite = nullptr;
}
}
} else {
// assemble halfedges into a quad
for(auto &he1 : quad_halfedges) {
he1->quad_edge = true;
for(auto &he2 : quad_halfedges) {
if(he1->idx2 == he2->idx1) {
he1->next = he2;
he2->prev = he1;
}
}
}
}
}
}
/**
* Create the boundary halfedges for the mesh, by creating a boundary edge for each halfedge that does not have an opposite edge
* and create the opposite, next and prev pointers.
* @param[inout] boundary_halfedges A list storing the created boundary halfedges.
* @param[inout] halfedges A list storing the inner halfedges.
* The edges in the list will be changed with the correct adjacenct to the boundary half edges.
* @param grid The grid.
*/
template<typename GridT>
void create_boundary_halfedges(std::list<HalfEdge> &boundary_halfedges, std::list<HalfEdge> &halfedges, const GridT &grid) {
for(auto &he : halfedges) {
if(he.opposite == nullptr) {
boundary_halfedges.push_back({he.idx2, he.idx1, he.normal, he.intersection_point, &he});
he.opposite = &boundary_halfedges.back();
he.opposite->boundary = true;
}
}
// Generate the next pointers for boundary halfedges by circulating around the start vertex
// using the previous pointers of the inner halfedges.
for(auto &he : boundary_halfedges) {
HalfEdge *he2 = he.opposite;
while(!he2->boundary) {
he2 = he2->prev->opposite;
}
assert(he2->idx1 == he.idx2);
he.next = he2;
he2->prev = &he;
}
}
/**
* For each vertex, collect the intersection points of adjacent edges and the normals at these points in vertex properties,
* so they can be used later on for calculating vertex positions.
<<<<<<< HEAD
* @param mesh The mesh.
* @param meshProperties A struct with the handles of the needed mesh properties.
* @param grid The grid.
* @param halfedges a list storing the halfedges.
>>>>>>> af85d32... Added a dual contouring implementation
*/
template<typename GridT>
void collect_intersection_points_and_normals(MishMesh::PolyMesh &mesh, const MeshProperties &meshProperties, const GridT &grid, const std::list<HalfEdge> &halfedges) {
for(auto &he : halfedges) {
// Collect the interpolated normals and points from the edges to the vertex handle
auto he2 = &he;
// For each outgoing edge adjacent to the vertex that belongs to the halfedge he,
// insert the intersection point and normal into the corresponding lists.
do {
he2 = he2->opposite->next;
assert(he.vh.is_valid());
mesh.property(meshProperties.normals, he.vh).push_back(he2->normal);
mesh.property(meshProperties.intersection_points, he.vh).push_back(he2->intersection_point);
} while(he2 != &he);
}
}
/**
* Create vertices and faces from a halfedge data structure, by associating a new mesh vertex to each halfedge vertex, that does not
* have a vertex yet and creating faces for halfedge cycles.
* The vertices are initialized to lie on the center of the cuboid cells that contain them.
* @param mesh The mesh.
* @param meshProperties A struct with the handles of the needed mesh properties.
* @param grid The grid.
* @param halfedges a list storing the halfedges.
*/
template<typename GridT>
void create_vertices_and_faces(MishMesh::PolyMesh &mesh, const MeshProperties &meshProperties, const GridT &grid, std::list<HalfEdge> &halfedges) {
// We need to add all edges to the queue, because the input may have several disjunct connected components
for(auto &he : halfedges) {
if(!he.quad_edge) continue; // Ignore edges that are created at the boundary and do not belong to a full quad.
if(he.visited) continue; // Ignore halfedges that are already processed
if(he.boundary) continue; // Ignore boundary edges.
auto quad_he = &he; // Initialize the pointer to the current half edge.
std::array<MishMesh::PolyMesh::VertexHandle, 4> vhs;
for(short j = 0; j < 4; j++) {
// If there is no vertex associated with the edge, try to find one on edges that share the same vertex.
if(!quad_he->vh.is_valid()) {
assert(quad_he->opposite != nullptr);
assert(quad_he->opposite->next != nullptr);
auto he2 = quad_he;
do {
// next edge in the 1-ring around the common vertex.
assert(he2->opposite != nullptr);
assert(he2->opposite->next != nullptr);
he2 = he2->opposite->next;
if(he2->vh.is_valid()) {
quad_he->vh = he2->vh;
break;
}
} while(he2 != quad_he);
}
// When no vertex was found, create one
if(!quad_he->vh.is_valid()) {
OpenMesh::Vec3i idxs_ltf = grid.grid_idxs(quad_he->idx1);
OpenMesh::Vec3i idxs_rbn = idxs_ltf + OpenMesh::Vec3i{1, 1, 1};
assert(idxs_rbn[0] < grid.resolution(0) && idxs_rbn[1] < grid.resolution(1) && idxs_rbn[2] < grid.resolution(2));
auto p = grid.point(idxs_ltf) - grid.point(idxs_rbn);
quad_he->vh = mesh.add_vertex(p);
mesh.property(meshProperties.cube_idx, quad_he->vh) = quad_he->idx1;
}
vhs[j] = quad_he->vh;
quad_he->visited = true;
assert(quad_he->next != nullptr);
quad_he = quad_he->next;
}
assert(quad_he == &he);
mesh.add_face(vhs.data(), 4);
}
collect_intersection_points_and_normals(mesh, meshProperties, grid, halfedges);
}
/**
* Fit the created dual vertices to a position inside the grid cell.
* @param mesh The mesh.
* @param meshProperties A struct with the handles of the needed mesh properties.
* @param grid The grid.
* @param vertexFit The method for fitting the vertices.
*/
template<typename GridT>
void fit_vertices(MishMesh::PolyMesh &mesh, const MeshProperties &meshProperties, const GridT &grid, const VertexFit vertexFit) {
// Fit vertices to the position induced by the adjacent quads
for(auto vh : mesh.vertices()) {
auto idxs_ltf = grid.grid_idxs(mesh.property(meshProperties.cube_idx, vh));
auto idxs_rbn = idxs_ltf + OpenMesh::Vec3i(1, 1, 1);
MishMesh::BBox<OpenMesh::Vec3d, 3> vertex_bbox{grid.point(idxs_ltf), grid.point(idxs_rbn)};
assert(vertex_bbox.is_valid());
auto &points = mesh.property(meshProperties.intersection_points, vh);
if(vertexFit == VertexFit::Average) {
fit_vertex_average(mesh, vh, vertex_bbox, points);
}
#ifdef HAS_EIGEN
else if(vertexFit == VertexFit::SVD) {
auto &normals = mesh.property(meshProperties.normals, vh);
fit_vertex_svd(mesh, vh, vertex_bbox, points, normals, true, SVDCutoffType::ABSOLUTE, SVD_CUTOFF_FACTOR);
}
#endif
}
}
}
/**
* Create a quadrangulation of the isosurface of a signed distance function using the dual contouring algorithm.
* @param distance_function A function that calculates the distance and the normal of a grid point.
* @param distance_function_data An optional pointer to data used by the distance_function.
* @param mesh_bounding_box The bounding box of the mesh.
* @param resolution The number of grid cells in each dimension.
* @param vertexFit The method for fitting the vertices.
*/
MishMesh::PolyMesh dual_contouring(DistanceFunction distance_function, void *distance_function_data, MishMesh::BBox<OpenMesh::Vec3d, 3> mesh_bounding_box, OpenMesh::Vec3i resolution, VertexFit vertexFit) {
auto grid = RegularGrid(mesh_bounding_box, resolution + OpenMesh::Vec3i{1, 1, 1});
MishMesh::PolyMesh mesh;
DualContouring::MeshProperties meshProperties;
mesh.add_property(meshProperties.cube_idx);
mesh.add_property(meshProperties.intersection_points);
mesh.add_property(meshProperties.normals);
// Calculate the values and normals at the grid points
std::vector<double> point_values;
std::vector<OpenMesh::Vec3d> point_normals;
std::tie(point_values, point_normals) = DualContouring::compute_point_values_and_normals(grid, distance_function, distance_function_data);
// Create dual halfedges around edges that intersect the zero-contour
std::list<DualContouring::HalfEdge> halfedges;
std::map<DualContouring::Edge, std::vector<DualContouring::HalfEdge *>> gridedge_to_halfedges;
DualContouring::create_halfedges(halfedges, gridedge_to_halfedges, grid, point_values, point_normals);
// Assemble the halfedges to quads
DualContouring::assemble_quads(grid, gridedge_to_halfedges);
// Remove halfedges that do not belong to a quad
halfedges.remove_if([](const DualContouring::HalfEdge &he) { return !(he.quad_edge); });
// Create mesh boundary halfedges
std::list<DualContouring::HalfEdge> boundary_halfedges;
DualContouring::create_boundary_halfedges(boundary_halfedges, halfedges, grid);
for(auto &he : halfedges) {
assert(he.opposite != nullptr);
}
// Create the mesh vertices and faces using the halfedge structure
DualContouring::create_vertices_and_faces(mesh, meshProperties, grid, halfedges);
// Fit the vertices to their positions, either averaged or fit to a plane
DualContouring::fit_vertices(mesh, meshProperties, grid, vertexFit);
return mesh;
}
}
}
| 45.279545 | 288 | 0.66501 | [
"mesh",
"vector"
] |
24f3d92ed6184b75f3177e5e3b52b4b47af6cc17 | 3,222 | cpp | C++ | test/test_opcode.cpp | stfnwong/smips | f305d24e16632b0a4907607386fc9d98f3d389b5 | [
"MIT"
] | null | null | null | test/test_opcode.cpp | stfnwong/smips | f305d24e16632b0a4907607386fc9d98f3d389b5 | [
"MIT"
] | null | null | null | test/test_opcode.cpp | stfnwong/smips | f305d24e16632b0a4907607386fc9d98f3d389b5 | [
"MIT"
] | null | null | null | /* TEST_OPCODE
* Unit tests for opcode table
*
* Stefan Wong 2019
*/
#define CATCH_CONFIG_MAIN
#include "catch/catch.hpp"
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
// unit under test
#include "Opcode.hpp"
// sample instruction codes
typedef enum instr_code
{
LEX_NULL,
LEX_ADD, LEX_ADDU, LEX_ADDI, LEX_ADDIU,
LEX_AND, LEX_ANDI, LEX_DIV, LEX_DIVU,
} instr_code;
// sample opcodes
const Opcode test_instr_codes[] = {
Opcode(LEX_NULL, "\0"),
Opcode(LEX_ADD, "ADD"),
Opcode(LEX_ADDU, "ADDU"),
Opcode(LEX_ADDI, "ADDI"),
Opcode(LEX_ADDIU, "ADDIU"),
Opcode(LEX_AND, "AND"),
Opcode(LEX_ANDI, "ANDI"),
Opcode(LEX_DIV, "DIV"),
Opcode(LEX_DIVU, "DIVU"),
};
TEST_CASE("Test opcode structure init", "[classic]")
{
OpcodeTable test_table;
Opcode out_op;
// add some instructions to the table
for(const Opcode& code : test_instr_codes)
test_table.add(code);
REQUIRE(9 == test_table.size());
// Asking for an opcode past the last index should give a null op
out_op = test_table.getIdx(20);
REQUIRE(0 == out_op.instr);
REQUIRE("\0" == out_op.mnemonic);
// if we walk over these in order, they should exactly match
for(unsigned int idx = 0; idx < test_table.size(); ++idx)
{
out_op = test_table.getIdx(idx);
REQUIRE(test_instr_codes[idx].instr == out_op.instr);
REQUIRE(test_instr_codes[idx].mnemonic == out_op.mnemonic);
}
// now test init function (clears table)
test_table.init();
REQUIRE(0 == test_table.size());
}
TEST_CASE("Test OpcodeTable lookup by instr", "[classic]")
{
OpcodeTable test_table;
Opcode out_op;
// add some instructions to the table
for(const Opcode& code : test_instr_codes)
test_table.add(code);
REQUIRE(9 == test_table.size());
// If we ask for an Opcode by an instruction that we have not seen
// the result should be a null op
out_op = test_table.get(0xdeadbeef);
REQUIRE(0 == out_op.instr);
REQUIRE("\0" == out_op.mnemonic);
// Lookup each of the objects by instruction
for(unsigned int idx = 0; idx < test_table.size(); ++idx)
{
out_op = test_table.get(test_instr_codes[idx].instr);
REQUIRE(test_instr_codes[idx].instr == out_op.instr);
REQUIRE(test_instr_codes[idx].mnemonic == out_op.mnemonic);
}
}
TEST_CASE("Test OpcodeTable lookup by mnemonic", "[classic]")
{
OpcodeTable test_table;
Opcode out_op;
// add some instructions to the table
for(const Opcode& code : test_instr_codes)
test_table.add(code);
REQUIRE(9 == test_table.size());
// If we ask for an opcode by a mnemonic that we not seen
// before the result should be a null op
out_op = test_table.get("JUNK_OP");
REQUIRE(0 == out_op.instr);
REQUIRE("\0" == out_op.mnemonic);
// Lookup each of the objects by menmonic
for(unsigned int idx = 0; idx < test_table.size(); ++idx)
{
out_op = test_table.get(test_instr_codes[idx].mnemonic);
REQUIRE(test_instr_codes[idx].instr == out_op.instr);
REQUIRE(test_instr_codes[idx].mnemonic == out_op.mnemonic);
}
}
| 27.538462 | 70 | 0.6527 | [
"vector"
] |
24fb836aa42c286acab021f8b40bab8fb2993443 | 953 | cpp | C++ | 944-smallest-range-i/smallest-range-i.cpp | nagestx/MyLeetCode | ef2a98b48485a0cebc442bbbbdb2690ba51484e1 | [
"MIT"
] | 3 | 2018-12-15T14:07:12.000Z | 2020-07-19T23:18:09.000Z | 944-smallest-range-i/smallest-range-i.cpp | yangyangu/MyLeetCode | ef2a98b48485a0cebc442bbbbdb2690ba51484e1 | [
"MIT"
] | null | null | null | 944-smallest-range-i/smallest-range-i.cpp | yangyangu/MyLeetCode | ef2a98b48485a0cebc442bbbbdb2690ba51484e1 | [
"MIT"
] | null | null | null | // Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].
//
// After this process, we have some array B.
//
// Return the smallest possible difference between the maximum value of B and the minimum value of B.
//
//
//
//
//
//
//
// Example 1:
//
//
// Input: A = [1], K = 0
// Output: 0
// Explanation: B = [1]
//
//
//
// Example 2:
//
//
// Input: A = [0,10], K = 2
// Output: 6
// Explanation: B = [2,8]
//
//
//
// Example 3:
//
//
// Input: A = [1,3,6], K = 3
// Output: 0
// Explanation: B = [3,3,3] or B = [4,4,4]
//
//
//
//
// Note:
//
//
// 1 <= A.length <= 10000
// 0 <= A[i] <= 10000
// 0 <= K <= 10000
//
//
//
//
class Solution {
public:
int smallestRangeI(vector<int>& A, int K) {
sort(A.begin(),A.end());
int maxn = A[A.size() - 1];
int minx = A[0];
return maxn - minx <= 2* K ? 0 : maxn - minx - 2 * K;
}
};
| 15.370968 | 113 | 0.47744 | [
"vector"
] |
700224b94e827c4d59610568a84ee359e214f2de | 9,029 | cpp | C++ | source/palette.cpp | JROB774/tein-editor | f952a1c7ad1941f5a5266c232b1d50ab1a26f379 | [
"MIT"
] | 2 | 2018-09-02T11:30:27.000Z | 2020-07-21T15:53:05.000Z | source/palette.cpp | thatb0y/tein-editor | 4c49be9534e439154553a188df758fa956b20e49 | [
"MIT"
] | null | null | null | source/palette.cpp | thatb0y/tein-editor | 4c49be9534e439154553a188df758fa956b20e49 | [
"MIT"
] | null | null | null | GLOBAL constexpr const char* PALETTE_FILE = "textures/palette.png";
GLOBAL constexpr const char* TILESET_FILE = "data/tilesets.txt";
GLOBAL constexpr const char* APPEND_FILE = "data/tilesets.txt.append";
GLOBAL constexpr const char* MERGE_FILE = "data/tilesets.txt.merge";
GLOBAL constexpr const char* PATCH_FILE = "data/tilesets.txt.patch";
GLOBAL constexpr const char* GAME_GPAK = "game.gpak";
// The columns in the palette file to pull the colors from.
GLOBAL constexpr int PALETTE_MAIN_COLUMN = 5;
GLOBAL std::map<std::string, vec4> palette_main_lookup;
FILDEF void init_palette_lookup ()
{
LOG_DEBUG("Looking for palette information...");
constexpr const char* PATH_STEAM_X86 = ":/Program Files (x86)/Steam/steamapps/common/theendisnigh/";
constexpr const char* PATH_STEAM_X64 = ":/Program Files/Steam/steamapps/common/theendisnigh/";
constexpr const char* PATH_EPIC_X86 = ":/Program Files (x86)/Epic Games/theendisnigh/";
constexpr const char* PATH_EPIC_X64 = ":/Program Files)/Epic Games/theendisnigh/";
std::string drives = get_drive_names();
// In order of priority of where we want to search.
std::vector<std::string> paths;
paths.push_back(make_path_absolute(""));
for (auto& drive: drives)
{
std::string drive_letter(1, drive);
paths.push_back(drive_letter + PATH_STEAM_X86);
paths.push_back(drive_letter + PATH_STEAM_X64);
paths.push_back(drive_letter + PATH_EPIC_X86);
paths.push_back(drive_letter + PATH_EPIC_X64);
}
std::vector<u8> palette_data;
std::vector<u8> tileset_data;
std::vector<u8> append_data;
std::vector<u8> patch_data;
std::vector<u8> merge_data;
for (auto& path: paths)
{
LOG_DEBUG("Looking at: %s", path.c_str());
std::string palname(path + PALETTE_FILE);
if (palette_data.empty() && does_file_exist(palname))
{
LOG_DEBUG("Palette file found!");
palette_data = read_binary_file(palname);
}
std::string tname(path + TILESET_FILE);
if (tileset_data.empty() && does_file_exist(tname))
{
LOG_DEBUG("Tileset file found!");
tileset_data = read_binary_file(tname);
}
std::string aname(path + APPEND_FILE);
if (append_data.empty() && does_file_exist(aname))
{
LOG_DEBUG("Append file found!");
append_data = read_binary_file(aname);
}
std::string pname(path + PATCH_FILE);
if (patch_data.empty() && does_file_exist(pname))
{
LOG_DEBUG("Patch file found!");
patch_data = read_binary_file(pname);
}
std::string mname(path + MERGE_FILE);
if (merge_data.empty() && does_file_exist(mname))
{
LOG_DEBUG("Mege file found!");
merge_data = read_binary_file(mname);
}
// If any data does not exist then we will attempt to load from the GPAK.
if (palette_data.empty() || tileset_data.empty() || append_data.empty() || patch_data.empty() || merge_data.empty())
{
std::string file_name(path + "game.gpak");
std::vector<GPAK_Entry> entries;
if (does_file_exist(file_name))
{
LOG_DEBUG("GPAK file found!");
FILE* file = fopen(file_name.c_str(), "rb");
if (file)
{
defer { fclose(file); };
u32 entry_count;
fread(&entry_count, sizeof(u32), 1, file);
entries.resize(entry_count);
for (auto& e: entries)
{
fread(&e.name_length, sizeof(u16), 1, file);
e.name.resize(e.name_length);
fread(&e.name[0], sizeof(char), e.name_length, file);
fread(&e.file_size, sizeof(u32), 1, file);
}
std::vector<u8> file_buffer;
for (auto& e: entries)
{
file_buffer.resize(e.file_size);
fread(&file_buffer[0], sizeof(u8), e.file_size, file);
if (palette_data.empty() && e.name == PALETTE_FILE)
{
LOG_DEBUG("Palette file loaded from GPAK!");
palette_data = file_buffer;
}
if (tileset_data.empty() && e.name == TILESET_FILE)
{
LOG_DEBUG("Tileset file loaded from GPAK!");
tileset_data = file_buffer;
}
if (append_data.empty() && e.name == APPEND_FILE)
{
LOG_DEBUG("Append file loaded from GPAK!");
append_data = file_buffer;
}
if (patch_data.empty() && e.name == PATCH_FILE)
{
LOG_DEBUG("Patch file loaded from GPAK!");
patch_data = file_buffer;
}
if (merge_data.empty() && e.name == MERGE_FILE)
{
LOG_DEBUG("Merge file loaded from GPAK!");
merge_data = file_buffer;
}
}
}
}
}
// We can leave early because we have found all the files we are looking for so there's nothing else to search!
if (!palette_data.empty() && !tileset_data.empty() && !append_data.empty() && !patch_data.empty() && !merge_data.empty())
{
break;
}
}
// If they still aren't present then we can't load the palette.
if (palette_data.empty() || tileset_data.empty())
{
LOG_DEBUG("Could not find both a tileset or palette file!");
return;
}
constexpr int BPP = 4;
LOG_DEBUG("Loading palette data...");
int w, h, bpp;
u8* palette = stbi_load_from_memory(&palette_data[0], CAST(int, palette_data.size()), &w, &h, &bpp, BPP);
if (!palette)
{
LOG_ERROR(ERR_MIN, "Failed to load palette data for the map editor!");
return;
}
defer { stbi_image_free(palette); };
LOG_DEBUG("Loading tileset data...");
try
{
std::string tbuffer(tileset_data.begin(), tileset_data.end());
GonObject gon = GonObject::LoadFromBuffer(tbuffer);
// If there is extra tileset info then handle it.
if (!append_data.empty())
{
LOG_DEBUG("Appending tileset data...");
std::string buffer(append_data.begin(), append_data.end());
GonObject append = GonObject::LoadFromBuffer(buffer);
gon.Append(append);
}
if (!patch_data.empty())
{
LOG_DEBUG("Patching tileset data...");
std::string buffer(patch_data.begin(), patch_data.end());
GonObject patch = GonObject::LoadFromBuffer(buffer);
gon.PatchMerge(patch);
}
if (!merge_data.empty())
{
LOG_DEBUG("Merging tileset data...");
std::string buffer(merge_data.begin(), merge_data.end());
GonObject merge = GonObject::LoadFromBuffer(buffer);
gon.DeepMerge(merge);
}
for (auto it: gon.children_map)
{
std::string name = it.first;
if (gon.children_array[it.second].type == GonObject::FieldType::OBJECT &&
gon.children_array[it.second].Contains("palette"))
{
int palette_row = CAST(int, gon.children_array[it.second]["palette"].Number(0));
int pitch = w*BPP;
int index = (palette_row * pitch + (PALETTE_MAIN_COLUMN * BPP));
if (index+3 < (pitch*h)) // Make sure we aren't referencing out of the palette bounds.
{
float r = CAST(float, palette[index+0]) / 255;
float g = CAST(float, palette[index+1]) / 255;
float b = CAST(float, palette[index+2]) / 255;
float a = CAST(float, palette[index+3]) / 255;
palette_main_lookup.insert(std::pair<std::string, vec4>(name, vec4(r,g,b,a)));
}
}
}
}
catch (const char* msg)
{
LOG_ERROR(ERR_MIN, "Failed to load tileset data for the map editor!");
palette_main_lookup.clear();
}
}
FILDEF vec4 get_tileset_main_color (std::string tileset)
{
if (tileset != "..")
{
if (palette_main_lookup.find(tileset) != palette_main_lookup.end())
{
return palette_main_lookup[tileset];
}
return ((is_ui_light()) ? ui_color_ex_dark : ui_color_ex_dark);
}
return vec4(0,0,0,1);
}
| 38.751073 | 129 | 0.538709 | [
"object",
"vector"
] |
7002a37da2eaa245fb10d68de8c450b8c720e56a | 4,168 | cpp | C++ | hw03/playfair_encode.cpp | xuan-415/Cryptography | df4ca035cebeb49263a1aff8241fb232373d24ad | [
"MIT"
] | null | null | null | hw03/playfair_encode.cpp | xuan-415/Cryptography | df4ca035cebeb49263a1aff8241fb232373d24ad | [
"MIT"
] | null | null | null | hw03/playfair_encode.cpp | xuan-415/Cryptography | df4ca035cebeb49263a1aff8241fb232373d24ad | [
"MIT"
] | null | null | null | #include<vector>
#include<iostream>
#include<string>
#include<ctype.h>
using namespace std;
vector<vector<char>> table(5);
void trim(string &s){
int index = 0;
if( !s.empty())
{
while( (index = s.find(' ',index)) != string::npos)
{
s.erase(index,1);
}
}
}
void table_for_check(string key){
bool check_for_I = false;
string font = "ABCDEFGHIKLMNOPQRSTUVWXYZ";
for (int j = 0; j < key.size(); j++) {
for (int i = 0; i < key.size(); i++) {
if (i == j) continue;
if (key[j] == key[i]) key.erase(key.begin() + i);
}
}
for(int i = 0; i < key.size(); i++){
if(key[i] == 'I'){
check_for_I = true;
}
}
if(check_for_I) {
for(int i = 0; i < key.size(); i++){
if(key[i] == 'J'){
key.erase(key.begin() + i);
cout << key << endl;
}
}
}
else{
for(int i = 0; i < key.size(); i++){
if(key[i] == 'J'){
key[i] = 'I';
break;
}
}
}
for(int i = 0; i < key.size(); i++){
for(int j = 0; j < font.size(); j++){
if(font[j] == key[i]) font.erase(font.begin() + j);
}
}
key = key + font;
int j = 0;
for (int i = 0; i < key.size(); i++) {
table[j].push_back(key[i]);
if (i == 4) j = 1;
if (i == 9) j = 2;
if (i == 14) j = 3;
if (i == 19) j = 4;
}
}
string for_correct_text(string text){
for(int i = 0; i < text.size(); i++){
if(text[i] == 'J') text[i] = 'I';
}
for (int i = 0; i < text.size(); i += 2) {
if (text[i] == text[i + 1]) {
text.insert(i + 1, "X");
}
}
if((text.size() % 2) != 0){
text.push_back('X');
}
return text;
}
string check_position(char a, char b){
string ans;
vector<int> a_pos, b_pos;
for(int j = 0; j < 5; j++){
for(int i = 0; i < 5; i++){
if(table[j][i] == a) {
a_pos.push_back(i);
a_pos.push_back(j);
}
if(table[j][i] == b) {
b_pos.push_back(i);
b_pos.push_back(j);
}
}
}
// 同一個位置的問題 !!!
if(a == 'X' && b == 'X') {
a = table[a_pos[1]][a_pos[0] - 1];
b = table[b_pos[1]][b_pos[0] - 1];
}
else if(a_pos[0] == b_pos[0]){ //他們在同一行
if(a_pos[1] == 4){
a = table[0][a_pos[0]];
b = table[b_pos[1] + 1][b_pos[0]];
}
else if(b_pos[1] == 4){
b = table[0][b_pos[0]];
a = table[a_pos[1] + 1][a_pos[0]];
}
else {
a = table[a_pos[1] + 1][a_pos[0]];
b = table[b_pos[1] + 1][b_pos[0]];
}
}
else if(a_pos[1] == b_pos[1]){ //他們在同一列
if(a_pos[0] == 4){
a =table[a_pos[1]][0];
b = table[b_pos[1]][b_pos[0] + 1];
}
else if(b_pos[0] == 4){
b =table[b_pos[1]][0];
a = table[a_pos[1]][a_pos[0] + 1];
}
else{
a = table[a_pos[1]][a_pos[0] + 1];
b = table[b_pos[1]][b_pos[0] + 1];
}
}
else {
a = table[a_pos[1]][b_pos[0]];
b = table[b_pos[1]][a_pos[0]];
}
ans.push_back(a);
ans.push_back(b);
return ans;
}
int main(){
string key, text,ans;
cout << "key :";
getline(cin, key);
for(int i = 0; i < key.size(); i++){
key[i] = toupper(key[i]);
}
cout << "text :";
getline(cin, text);
for(int i = 0; i < text.size(); i++){
text[i] = toupper(text[i]);
}
trim(key);
trim(text);
table_for_check(key);
text = for_correct_text(text);
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
cout << table[i][j] << " ";
}
cout << endl;
}
for(int i = 0; i < text.size(); i += 2){
ans += check_position(text[i], text[i+1]);
}
cout << "answer :" << ans << endl;
system("pause");
} | 23.817143 | 63 | 0.395393 | [
"vector"
] |
7004e326a3ccf95a07b21276df3efe33be94bd2b | 5,809 | tcc | C++ | src/cpu/power/predictors/bloomfilter.tcc | JimmyZhang12/gem5 | 34a009b9f7f33667cc230ac7f7ebfb8705718c5d | [
"BSD-3-Clause"
] | null | null | null | src/cpu/power/predictors/bloomfilter.tcc | JimmyZhang12/gem5 | 34a009b9f7f33667cc230ac7f7ebfb8705718c5d | [
"BSD-3-Clause"
] | null | null | null | src/cpu/power/predictors/bloomfilter.tcc | JimmyZhang12/gem5 | 34a009b9f7f33667cc230ac7f7ebfb8705718c5d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020, University of Illinois
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andrew Smith
*/
/**
* Bloomfilter constructor, initializes the offset array and the table to
* false.
* @param n The number of hashes to perform on the input object
* @param size The size of the table
* @param seed The seed for srand() for generating the n hashes
* @return None
*/
template<class T>
Bloomfilter<T>::Bloomfilter(unsigned int n, unsigned int size, unsigned int seed) {
std::srand(seed);
offset.resize(n, 0);
table.resize(size, false);
for(size_t i = 0; i < offset.size(); i++) {
offset[i] = std::rand();
}
}
/**
* Bloomfilter find. Checks if the object is in the filter. Due to the
* nature of the bloom filter there is a chance of a false positive.
* @param obj Item to be hashed
* @return True if the item is in the table
*/
template<class T>
bool Bloomfilter<T>::find(const T obj) const {
if(table.size() == 0 || offset.size() == 0) {
return false;
}
bool retval = true;
int idx = 0;
for(size_t i = 0; i < offset.size(); i++) {
idx = h(offset[i], obj) % table.size();
retval &= table[idx];
}
return retval;
}
/**
* Bloomfilter insert. Adds the object to the filter.
* @param obj Item to be hashed
*/
template<class T>
void Bloomfilter<T>::insert(const T obj) {
if(table.size() == 0) {
return;
}
int idx = 0;
for(size_t i = 0; i < offset.size(); i++) {
idx = h(offset[i], obj) % table.size();
table[idx] = true;
}
}
/**
* resize, clears out the bloom filter and resets the seed, n hash ways and the
* size of the underlying table.
* @param n The number of hashes to perform on the input object
* @param size The size of the table
* @param seed The seed for srand() for generating the n hashes
* @return None
*/
template<class T>
void Bloomfilter<T>::resize(unsigned int n, unsigned int size, unsigned int seed) {
clear();
std::srand(seed);
offset.resize(n, 0);
table.resize(size, false);
for(size_t i = 0; i < offset.size(); i++) {
offset[i] = std::rand();
}
}
/**
* Reset the contents of the bloom filter, as it is not possible to erase a
* specific item.
*/
template<class T>
void Bloomfilter<T>::clear() {
std::replace(table.begin(), table.end(), true, false);
}
/**
* Bloomfilter hash function, hashes the object n ways with the std::hash
* function. Uses a different "offset" for hash.
* https://stackoverflow.com/a/7222201/916549
* https://www.boost.org/doc/libs/1_35_0/libs/functional/hash/examples/point.cpp
* @param val Item to be hashed
* @param offset Int prepended to the hash for the n-way hash
* @return Hashed value
*/
template<class T>
size_t Bloomfilter<T>::h(const int offset, const T& val) const {
size_t seed = 0;
std::hash<int> hash1;
std::hash<T> hash2;
seed ^= hash1(offset) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
seed ^= hash2(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
/**
* Hash function for std::vector<T>. Note that T must also have a hash
* function if it is not part of the Standard specializations for basic
* types. Combines the hashes of all the elements.
* https://stackoverflow.com/a/7222201/916549
* https://www.boost.org/doc/libs/1_35_0/libs/functional/hash/examples/point.cpp
* @param k Vector to be hashed
* @return Hashed value
*/
namespace std {
template <class T>
struct hash<vector<T>> {
size_t operator()(const std::vector<T>& k) const {
hash<T> h;
size_t seed = 0;
for(auto it = k.begin(); it != k.end(); it++) {
seed ^= h(*it) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
}
| 34.993976 | 83 | 0.696161 | [
"object",
"vector"
] |
7009ba7c097778b1a6dcfaf394a83a58fac7934a | 2,031 | cpp | C++ | PrinterContextNativeRuntimeComponent/PrinterPrintQueueEventHandlerHelper.cpp | Ganeshcoep/print-oem-samples | 0508c31e2881ee0d4379cd7ff830e0062e818a6c | [
"MIT"
] | 4 | 2020-03-25T20:39:20.000Z | 2021-04-20T16:11:17.000Z | PrinterContextNativeRuntimeComponent/PrinterPrintQueueEventHandlerHelper.cpp | Ganeshcoep/print-oem-samples | 0508c31e2881ee0d4379cd7ff830e0062e818a6c | [
"MIT"
] | 2 | 2019-06-13T23:13:13.000Z | 2020-07-30T18:01:03.000Z | PrinterContextNativeRuntimeComponent/PrinterPrintQueueEventHandlerHelper.cpp | Ganeshcoep/print-oem-samples | 0508c31e2881ee0d4379cd7ff830e0062e818a6c | [
"MIT"
] | 7 | 2019-06-13T23:15:42.000Z | 2020-08-05T14:57:37.000Z | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
* ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*
* This class represents a print queue event handler helper
* as described in https://msdn.microsoft.com/library/windows/hardware/dn265393
*/
#include "pch.h"
#include "PrinterQueueViewEventHelperEventArgs.h"
#include "PrinterPrintJobEventHandler.h"
#include "PrinterPrintQueueEventHandlerHelper.h"
// Namespaces
using namespace Windows::Foundation;
namespace PrinterContextNativeRuntimeComponent
{
namespace Printing
{
namespace PrinterExtension
{
PrinterPrintQueueEventHandlerHelper::PrinterPrintQueueEventHandlerHelper(int64 iPrintQueueView, Object^ notUsed)
{
IUnknown* pqview = (IUnknown*)(void*)iPrintQueueView;
if (pqview == NULL)
{
throw ref new InvalidArgumentException();
}
int hr = pqview->QueryInterface(__uuidof(IPrinterQueueView), (void**)view.GetAddressOf());
__abi_ThrowIfFailed(hr);
Windows::Foundation::TypedEventHandler<Object^, PrinterQueueViewEventHelperEventArgs^>^ p = ref new Windows::Foundation::TypedEventHandler<Object^, PrinterQueueViewEventHelperEventArgs^>(this, &PrinterPrintQueueEventHandlerHelper::_onChange);
handler = Make<PrinterPrintJobEventHandler>((int64)(void*)view.Get(), p);
}
PrinterPrintQueueEventHandlerHelper::~PrinterPrintQueueEventHandlerHelper()
{
view = nullptr;
handler = nullptr;
}
void PrinterPrintQueueEventHandlerHelper::_onChange(Object^ notUsed, PrinterQueueViewEventHelperEventArgs^ args)
{
OnChange(this, args);
}
}
}
}
| 37.611111 | 258 | 0.666667 | [
"object"
] |
7010bdc138e6fcfafc13c7eea52025b061c3eb38 | 510 | cpp | C++ | Cplus/AllDivisionsWiththeHighestScoreofaBinaryArray.cpp | Jum1023/leetcode | d8248aa84452cb1ea768d9b05ecd72a6746c0016 | [
"MIT"
] | 1 | 2018-01-22T12:06:28.000Z | 2018-01-22T12:06:28.000Z | Cplus/AllDivisionsWiththeHighestScoreofaBinaryArray.cpp | Jum1023/leetcode | d8248aa84452cb1ea768d9b05ecd72a6746c0016 | [
"MIT"
] | null | null | null | Cplus/AllDivisionsWiththeHighestScoreofaBinaryArray.cpp | Jum1023/leetcode | d8248aa84452cb1ea768d9b05ecd72a6746c0016 | [
"MIT"
] | null | null | null | #include <vector>
using namespace std;
class Solution
{
public:
vector<int> maxScoreIndices(vector<int> &nums)
{
int zero = 0, one = 0;
for (auto n : nums)
{
if (n == 1)
++one;
}
int sum = one, minsum = one;
vector<int> res = {0};
for (int i = 0; i < (int)nums.size(); ++i)
{
if (nums[i] == 0)
++zero;
else
--one;
if (sum == one + zero)
res.push_back(i + 1);
else if (sum < one + zero)
{
sum = one + zero;
res = {i + 1};
}
}
return res;
}
}; | 15.454545 | 47 | 0.498039 | [
"vector"
] |
701247d471be4cbe3c77e450c1543ec3eacd24eb | 24,314 | cpp | C++ | 3rdparty/etl/src/ETPatch.cpp | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | 3rdparty/etl/src/ETPatch.cpp | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | 3rdparty/etl/src/ETPatch.cpp | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | /********************************************************************************
EDITABLE TERRAIN LIBRARY v3 for Ogre
Copyright (c) 2008 Holger Frydrych <frydrych@oddbeat.de>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
********************************************************************************/
#include "ETPatch.h"
#include "ETIndexHandler.h"
#include <OgreHardwareBufferManager.h>
#include <OgreNode.h>
#include <OgreTagPoint.h>
#include <OgreEntity.h>
#include <OgreCamera.h>
#include <OgreSceneManager.h>
#include <OgreException.h>
#include <OgreMath.h>
#include <iostream>
using namespace Ogre;
using namespace std;
namespace ET
{
const unsigned short MAIN_BINDING = 0;
const unsigned short DELTA_BINDING = 1;
const unsigned int MORPH_CUSTOM_PARAM_ID = 77;
Patch::Patch(const String& name, TerrainDescription* description, bool autoDelete,
IndexHandler* indexHandler, unsigned int maxLOD, Real maxError, unsigned int vertexOptions,
Real lodMorphDistStart)
: MovableObject(name), mDescription(description), mAutoDelete(autoDelete), mIndexHandler(indexHandler),
mVertexOptions(vertexOptions), mMaxLOD(maxLOD), mMaxError(maxError), mCurLOD(0),
mLODMorphDistStart(lodMorphDistStart), mLightListDirty(true)
{
if (mDescription->getNumVerticesX() != mIndexHandler->getSizeX() ||
mDescription->getNumVerticesZ() != mIndexHandler->getSizeZ())
{
// sizes don't match
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Sizes of the terrain description and index handler don't match",
"ET::Patch::Patch");
}
// initialise LOD cache
unsigned int cacheStep = 1 << (mMaxLOD-1);
unsigned int cacheSizeX = (mDescription->getNumVerticesX()-1) / cacheStep;
unsigned int cacheSizeZ = (mDescription->getNumVerticesZ()-1) / cacheStep;
mLODCache.assign(mMaxLOD-1, RealArray2D(cacheSizeX, cacheSizeZ, 0));
memset(mNeighbours, 0, sizeof(mNeighbours));
mMaxLOD = min(mMaxLOD, mIndexHandler->getMaxLOD());
// disable LOD morphing if max LOD is 1
if (mMaxLOD <= 1)
{
mMaxLOD = 1;
mVertexOptions &= (~VO_LODMORPH);
}
mLODChangeMinDistSqr = vector<Real>(mMaxLOD);
mLastNextLOD = mMaxLOD+1;
// terrain should not cast shadows by default, too expensive
mCastShadows = false;
createVertexData();
// initial fill of the vertex buffer (=> update all vertices)
VertexList allVertices;
for (unsigned int i = 0; i < mDescription->getNumVertices(); ++i)
allVertices.insert(i);
updateVertexBuffer(allVertices);
// register as a listener to the TerrainDescription
mDescription->addListener(this);
}
Patch::~Patch()
{
// notify neighbours
for (int i = 0; i < 4; ++i)
{
if (mNeighbours[i])
mNeighbours[i]->mNeighbours[OPPOSITE_DIR[i]] = 0;
}
if (mDescription)
mDescription->removeListener(this);
delete mVertexData;
}
void Patch::createVertexData()
{
mVertexData = new VertexData;
mVertexData->vertexStart = 0;
mVertexData->vertexCount = mDescription->getNumVertices();
VertexDeclaration* decl = mVertexData->vertexDeclaration;
VertexBufferBinding* bind = mVertexData->vertexBufferBinding;
// first we need to declare the contents of our vertex buffer
size_t offset = 0;
decl->addElement(MAIN_BINDING, offset, VET_FLOAT3, VES_POSITION);
offset += VertexElement::getTypeSize(VET_FLOAT3);
if (mVertexOptions & VO_NORMALS)
{
// include vertex normals
decl->addElement(MAIN_BINDING, offset, VET_FLOAT3, VES_NORMAL);
offset += VertexElement::getTypeSize(VET_FLOAT3);
}
if (mVertexOptions & VO_TANGENTS)
{
// include vertex tangents
decl->addElement(MAIN_BINDING, offset, VET_FLOAT3, VES_TANGENT);
offset += VertexElement::getTypeSize(VET_FLOAT3);
}
if (mVertexOptions & VO_BINORMALS)
{
// include vertex binormals
decl->addElement(MAIN_BINDING, offset, VET_FLOAT3, VES_BINORMAL);
offset += VertexElement::getTypeSize(VET_FLOAT3);
}
// add primary texcoord set
decl->addElement(MAIN_BINDING, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0);
offset += VertexElement::getTypeSize(VET_FLOAT2);
if (mVertexOptions & VO_TEXCOORD1)
{
// include secondary texcoord set
decl->addElement(MAIN_BINDING, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 1);
offset += VertexElement::getTypeSize(VET_FLOAT2);
}
// create the primary vertex buffer
mMainBuffer = HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(MAIN_BINDING), mVertexData->vertexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
// bind the buffer
bind->setBinding(MAIN_BINDING, mMainBuffer);
// declare and create delta buffers, if requested
if (mVertexOptions & VO_LODMORPH)
{
decl->addElement(DELTA_BINDING, 0, VET_FLOAT1, VES_BLEND_WEIGHTS);
for (unsigned int i = 0; i < mMaxLOD-1; ++i)
{
HardwareVertexBufferSharedPtr buf = HardwareBufferManager::getSingleton().
createVertexBuffer(VertexElement::getTypeSize(VET_FLOAT1),
mDescription->getNumVertices(),
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
mDeltaBuffers.push_back(buf);
emptyBuffer(buf);
}
}
}
void Patch::updateVertexBuffer(const VertexList& dirtyVertices)
{
VertexDeclaration* decl = mVertexData->vertexDeclaration;
const VertexElement* positionElem = decl->findElementBySemantic(VES_POSITION);
const VertexElement* normalElem = 0, * tangentElem = 0, * binormalElem = 0;
const VertexElement* tex0Elem = decl->findElementBySemantic(VES_TEXTURE_COORDINATES, 0);
const VertexElement* tex1Elem = 0;
if (mVertexOptions & VO_NORMALS)
normalElem = decl->findElementBySemantic(VES_NORMAL);
if (mVertexOptions & VO_TANGENTS)
tangentElem = decl->findElementBySemantic(VES_TANGENT);
if (mVertexOptions & VO_BINORMALS)
binormalElem = decl->findElementBySemantic(VES_BINORMAL);
if (mVertexOptions & VO_TEXCOORD1)
tex1Elem = decl->findElementBySemantic(VES_TEXTURE_COORDINATES, 1);
// lock buffer
unsigned char* pBase = static_cast<unsigned char*>(mMainBuffer->lock(HardwareBuffer::HBL_NORMAL));
// iterate over all vertices to be updated
for (VertexList::const_iterator vert = dirtyVertices.begin(); vert != dirtyVertices.end(); ++vert)
{
unsigned int vertexIndex = *vert;
unsigned char* pCur = pBase + mMainBuffer->getVertexSize() * vertexIndex;
// update vertex position
float* pPosition;
positionElem->baseVertexPointerToElement(pCur, &pPosition);
Vector3 pos = mDescription->getVertexPosition(vertexIndex);
*pPosition++ = pos.x;
*pPosition++ = pos.y;
*pPosition = pos.z;
// update primary texcoord set
float* pTex0;
tex0Elem->baseVertexPointerToElement(pCur, &pTex0);
Vector2 tex0 = mDescription->getVertexTexcoord0(vertexIndex);
*pTex0++ = tex0.x;
*pTex0 = tex0.y;
if (mVertexOptions & VO_NORMALS)
{
// update vertex normal
float* pNormal;
normalElem->baseVertexPointerToElement(pCur, &pNormal);
Vector3 normal = mDescription->getVertexNormal(vertexIndex);
*pNormal++ = normal.x;
*pNormal++ = normal.y;
*pNormal = normal.z;
}
if (mVertexOptions & VO_TANGENTS)
{
// update vertex tangent
float* pTangent;
tangentElem->baseVertexPointerToElement(pCur, &pTangent);
Vector3 tangent = mDescription->getVertexTangent(vertexIndex);
*pTangent++ = tangent.x;
*pTangent++ = tangent.y;
*pTangent = tangent.z;
}
if (mVertexOptions & VO_BINORMALS)
{
// update vertex binormal
float* pBinormal;
binormalElem->baseVertexPointerToElement(pCur, &pBinormal);
Vector3 binormal = mDescription->getVertexBinormal(vertexIndex);
*pBinormal++ = binormal.x;
*pBinormal++ = binormal.y;
*pBinormal = binormal.z;
}
if (mVertexOptions & VO_TEXCOORD1)
{
// update secondary texcoord set
float* pTex1;
tex1Elem->baseVertexPointerToElement(pCur, &pTex1);
Vector2 tex1 = mDescription->getVertexTexcoord1(vertexIndex);
*pTex1++ = tex1.x;
*pTex1 = tex1.y;
}
}
// unlock the buffer
mMainBuffer->unlock();
// update the bounding box
updateBoundingBox();
// update the LOD distances
VertexList dirtyLODFrames;
unsigned int lodStep = 1 << (mMaxLOD-1);
unsigned int lodSizeX = mDescription->getNumVerticesX() / lodStep;
unsigned int lodSizeZ = mDescription->getNumVerticesZ() / lodStep;
for (VertexList::const_iterator it = dirtyVertices.begin(); it != dirtyVertices.end(); ++it)
{
unsigned int x, z;
mDescription->getVertexCoord(*it, x, z);
unsigned int lodX = x / lodStep, lodZ = z / lodStep;
unsigned int frameIndex = lodZ * lodSizeX + lodX;
if (lodX != lodSizeX && lodZ != lodSizeZ)
dirtyLODFrames.insert(frameIndex);
if (x % lodStep == 0 && x != 0 && lodZ != lodSizeZ)
dirtyLODFrames.insert(frameIndex-1);
if (z % lodStep == 0 && z != 0 && lodX != lodSizeX)
dirtyLODFrames.insert(frameIndex-lodSizeX);
}
updateLODChangeDistances(dirtyLODFrames);
}
void Patch::updateBoundingBox()
{
// iterate over all vertices of the TerrainDescription and find the extents
Vector3 minimum (1e30, 1e30, 1e30), maximum (-1e30, -1e30, -1e30);
unsigned int numVertices = mDescription->getNumVertices();
for (unsigned int i = 0; i < numVertices; ++i)
{
Vector3 pos = mDescription->getVertexPosition(i);
minimum.makeFloor(pos);
maximum.makeCeil(pos);
}
mBoundingBox.setExtents(minimum, maximum);
mCenter = mBoundingBox.getCenter();
mBoundingRadius = (mBoundingBox.getMaximum() - mCenter).length();
}
void Patch::updateLODChangeDistances(const VertexList& dirtyLODFrames)
{
// By switching to higher LOD levels, certain vertices are left out. We calculate
// the errors in terrain height which are introduced by that. From these errors
// we calculate the distance at which it's okay to switch to the higher LOD level.
// We also store the height differences in the delta buffers for geomorphing.
unsigned int patchSizeX = mDescription->getNumVerticesX();
unsigned int patchSizeZ = mDescription->getNumVerticesZ();
// lock delta buffers, if vertex morphing is enabled
vector<float*> pDeltas (mMaxLOD-1);
if (mVertexOptions & VO_LODMORPH)
{
for (unsigned int l = 0; l < mMaxLOD-1; ++l)
pDeltas[l] = static_cast<float*>( mDeltaBuffers[l]->lock(HardwareBuffer::HBL_NORMAL) );
}
// we are caching values in chunks of the size of the max LOD step
unsigned int cacheStep = 1 << (mMaxLOD-1);
unsigned int cacheSizeX = patchSizeX / cacheStep;
unsigned int cacheSizeZ = patchSizeZ / cacheStep;
vector<RealArray2D> cache (mMaxLOD-1, RealArray2D(cacheStep+1, cacheStep+1, 0));
// update all LOD frames which need updating, each frame is cacheStep x cacheStep
for (VertexList::const_iterator it = dirtyLODFrames.begin(); it != dirtyLODFrames.end(); ++it)
{
unsigned int cacheX = (*it % cacheSizeX) * cacheStep;
unsigned int cacheZ = (*it / cacheSizeX) * cacheStep;
unsigned int cacheEndX = cacheX + cacheStep, cacheEndZ = cacheZ + cacheStep;
for (unsigned int level = mMaxLOD-1; level >= 1; --level)
{
unsigned int levelStep = 1 << level;
unsigned int levelHalfStep = levelStep >> 1;
for (unsigned int levelX = cacheX; levelX < cacheEndX; levelX += levelStep)
{
for (unsigned int levelZ = cacheZ; levelZ < cacheEndZ; levelZ += levelStep)
{
unsigned int indexX = levelX - cacheX, indexZ = levelZ - cacheZ;
Real ul = mDescription->getVertexPosition(levelX, levelZ).y;
Real ur = mDescription->getVertexPosition(levelX+levelStep, levelZ).y;
Real ll = mDescription->getVertexPosition(levelX, levelZ+levelStep).y;
Real lr = mDescription->getVertexPosition(levelX+levelStep, levelZ+levelStep).y;
cache[level-1].at(indexX, indexZ) = 0;
cache[level-1].at(indexX+levelStep, indexZ) = 0;
cache[level-1].at(indexX, indexZ+levelStep) = 0;
cache[level-1].at(indexX+levelStep, indexZ+levelStep) = 0;
// calculate the height error for the intermediant vertices introduced from this level on
for (unsigned int l = level; l < mMaxLOD; ++l)
{
Real um = -mDescription->getVertexPosition(levelX+levelHalfStep, levelZ).y
+ (ul+ur)/2 - cache[l-1].at(indexX, indexZ)
- cache[l-1].at(indexX, indexZ+levelStep);
Real lm = -mDescription->getVertexPosition(levelX+levelHalfStep, levelZ+levelStep).y
+ (ll+lr)/2 - cache[l-1].at(indexX, indexZ+levelStep)
- cache[l-1].at(indexX+levelStep, indexZ+levelStep);
Real ml = -mDescription->getVertexPosition(levelX, levelZ+levelHalfStep).y
+ (ul+ll)/2 - cache[l-1].at(indexX, indexZ)
- cache[l-1].at(indexX+levelStep, indexZ);
Real mr = -mDescription->getVertexPosition(levelX+levelStep, levelZ+levelHalfStep).y
+ (ur+lr)/2 - cache[l-1].at(indexX+levelStep, indexZ)
- cache[l-1].at(indexX+levelStep, indexZ+levelStep);
Real mm = -mDescription->getVertexPosition(levelX+levelHalfStep, levelZ+levelHalfStep).y
+ (ll+ur)/2 - cache[l-1].at(indexX, indexZ+levelStep)
- cache[l-1].at(indexX+levelStep, indexZ);
cache[l-1].at(indexX+levelHalfStep, indexZ) = um/2;
cache[l-1].at(indexX+levelHalfStep, indexZ+levelStep) = lm/2;
cache[l-1].at(indexX, indexZ+levelHalfStep) = ml/2;
cache[l-1].at(indexX+levelStep, indexZ+levelHalfStep) = mr/2;
cache[l-1].at(indexX+levelHalfStep, indexZ+levelHalfStep) = mm/2;
// if vertex morphing is enabled, store values in delta buffers
if (l == level && (mVertexOptions & VO_LODMORPH))
{
if (!isBorderVertex(levelX+levelHalfStep, levelZ))
pDeltas[l-1][levelX+levelHalfStep + (levelZ)*patchSizeX] = um;
if (!isBorderVertex(levelX+levelHalfStep, levelZ+levelStep))
pDeltas[l-1][levelX+levelHalfStep + (levelZ+levelStep)*patchSizeX] = lm;
if (!isBorderVertex(levelX, levelZ+levelHalfStep))
pDeltas[l-1][levelX + (levelZ+levelHalfStep)*patchSizeX] = ml;
if (!isBorderVertex(levelX+levelStep, levelZ+levelHalfStep))
pDeltas[l-1][levelX+levelStep + (levelZ+levelHalfStep)*patchSizeX] = mr;
pDeltas[l-1][levelX+levelHalfStep + (levelZ+levelHalfStep)*patchSizeX] = mm;
}
}
}
}
// store into LOD cache
unsigned int lodCacheX = cacheX / cacheStep, lodCacheZ = cacheZ / cacheStep;
for (unsigned int l = 0; l < mMaxLOD-1; ++l)
{
Real maxAbs = 0;
for (RealArray2D::iterator it = cache[l].begin(); it != cache[l].end(); ++it)
{
if (Math::Abs(*it) > maxAbs)
maxAbs = Math::Abs(*it);
}
mLODCache[l].at(lodCacheX, lodCacheZ) = maxAbs * 2;
}
}
}
// unlock delta buffers, if vertex morphing is enabled
if (mVertexOptions & VO_LODMORPH)
{
for (unsigned int l = 0; l < mMaxLOD-1; ++l)
mDeltaBuffers[l]->unlock();
}
// C is a factor for the calculation of the min distance.
Real C = 0.5 / mMaxError;
// calculate new switch distances
mLODChangeMinDistSqr[0] = 0;
for (unsigned int l = 0; l < mMaxLOD-1; ++l)
{
Real maxError = *max_element(mLODCache[l].begin(), mLODCache[l].end());
Real switchDist = maxError*maxError*C*C;
mLODChangeMinDistSqr[l+1] = max(mLODChangeMinDistSqr[l], switchDist);
}
}
bool Patch::isBorderVertex(unsigned int x, unsigned int z)
{
return (x == 0 || z == 0 ||
x == mDescription->getNumVerticesX()-1 ||
z == mDescription->getNumVerticesZ()-1
);
}
void Patch::emptyBuffer(HardwareVertexBufferSharedPtr buf)
{
// fills the buffer with 0
void* pBuf = buf->lock(HardwareBuffer::HBL_DISCARD);
memset(pBuf, 0, mDescription->getNumVertices() * buf->getVertexSize());
buf->unlock();
}
void Patch::setNeighbour(int direction, Patch* neighbour)
{
int opposite = OPPOSITE_DIR[direction];
if (mNeighbours[direction] != 0)
{
// we are no longer neighbour to the previous patch
mNeighbours[direction]->mNeighbours[opposite] = 0;
}
if (neighbour)
{
// also adjust the neighbour settings of the neighbour
if (neighbour->mNeighbours[opposite] != 0)
neighbour->mNeighbours[opposite]->mNeighbours[direction] = 0;
neighbour->mNeighbours[opposite] = this;
}
mNeighbours[direction] = neighbour;
}
void Patch::notifyUpdated(const VertexList& dirtyVertices)
{
// update the vertex buffer
updateVertexBuffer(dirtyVertices);
}
void Patch::notifyDestroyed()
{
// set the TerrainDescription to 0 so that on destruction we don't try to unregister as a listener
mDescription = 0;
// should we automatically delete?
if (mAutoDelete)
delete this;
}
const String& Patch::getMovableType() const
{
static const String type = "EditableTerrainPatch";
return type;
}
const MaterialPtr& Patch::getMaterial() const
{
return mMaterial;
}
void Patch::setMaterial(const MaterialPtr& material)
{
mMaterial = material;
}
const AxisAlignedBox& Patch::getBoundingBox() const
{
return mBoundingBox;
}
Real Patch::getBoundingRadius() const
{
return mBoundingRadius;
}
void Patch::getWorldTransforms(Matrix4* m) const
{
*m = mParentNode->_getFullTransform();
}
const Quaternion& Patch::getWorldOrientation() const
{
return mParentNode->_getDerivedOrientation();
}
const Vector3& Patch::getWorldPosition() const
{
return mParentNode->_getDerivedPosition();
}
Real Patch::getSquaredViewDepth(const Camera* cam) const
{
return (mCenter - cam->getDerivedPosition()).squaredLength();
}
const LightList& Patch::getLights() const
{
if (mLightListDirty)
{
// query the scene manager of the parent node for lights affecting this renderable
SceneManager* sceneMgr = 0;
if (mParentIsTagPoint)
{
// get the parent entity and obtain its scene manager
sceneMgr = static_cast<const TagPoint*>(mParentNode)->getParentEntity()->_getManager();
}
else
{
// get the creator of the parent scene node
sceneMgr = static_cast<const SceneNode*>(mParentNode)->getCreator();
}
sceneMgr->_populateLightList(mCenter, mBoundingRadius, mLightList);
mLightListDirty = false;
}
return mLightList;
}
Ogre::uint32 Patch::getTypeFlags() const
{
return SceneManager::WORLD_GEOMETRY_TYPE_MASK;
}
void Patch::getRenderOperation(RenderOperation& op)
{
op.useIndexes = true;
op.operationType = RenderOperation::OT_TRIANGLE_LIST;
op.vertexData = mVertexData;
// determine LOD state of the neighbours
unsigned int northLOD = (mNeighbours[DIR_NORTH] ? mNeighbours[DIR_NORTH]->getCurrentLOD() : 0);
unsigned int eastLOD = (mNeighbours[DIR_EAST] ? mNeighbours[DIR_EAST]->getCurrentLOD() : 0);
unsigned int southLOD = (mNeighbours[DIR_SOUTH] ? mNeighbours[DIR_SOUTH]->getCurrentLOD() : 0);
unsigned int westLOD = (mNeighbours[DIR_WEST] ? mNeighbours[DIR_WEST]->getCurrentLOD() : 0);
op.indexData = mIndexHandler->getIndexData(mCurLOD, northLOD, eastLOD, southLOD, westLOD);
}
void Patch::_updateRenderQueue(RenderQueue* queue)
{
mLightListDirty = true;
queue->addRenderable(this, mRenderQueueID);
}
void Patch::_updateCustomGpuParameter(const GpuProgramParameters::AutoConstantEntry& constEntry,
GpuProgramParameters* params) const
{
if (constEntry.data == MORPH_CUSTOM_PARAM_ID)
params->_writeRawConstant(constEntry.physicalIndex, mLODMorphFactor);
else
Renderable::_updateCustomGpuParameter(constEntry, params);
}
void Patch::_notifyCurrentCamera(Camera* cam)
{
MovableObject::_notifyCurrentCamera(cam);
// we need to determine the level of detail to use for the tile and
// set up the correct delta buffer for LOD morphing
// get the distance from the camera to the patch
Vector3 camPos = cam->getDerivedPosition();
const AxisAlignedBox& aabb = getWorldBoundingBox(true);
Vector3 diff (0, 0, 0);
diff.makeFloor(camPos - aabb.getMinimum());
diff.makeCeil(camPos - aabb.getMaximum());
Real L = mCurCameraDistanceSqr = diff.squaredLength();
// determine LOD to use for this patch
mCurLOD = mMaxLOD - 1;
for (unsigned int i = 1; i < mMaxLOD; ++i)
{
if (mLODChangeMinDistSqr[i] > L)
{
mCurLOD = i - 1;
break;
}
}
// set up LOD morphing, if enabled
if (mVertexOptions & VO_LODMORPH)
{
// we need to find the next LOD after the current one, usually this is mCurLOD+1
// however, theoretically some LOD might have identical distances, so check anyway to be sure
unsigned int nextLevel = mCurLOD + 1;
for (unsigned int i = nextLevel; i < mMaxLOD; ++i)
{
if (mLODChangeMinDistSqr[i] > mLODChangeMinDistSqr[mCurLOD])
{
nextLevel = i;
break;
}
}
// determine the LOD morph factor by which to multiply the blendweights
if (nextLevel == mMaxLOD)
{
// there is no next level, so set the morph factor to 0
mLODMorphFactor = 0;
}
else
{
// get the distance range between the current and the next level
Real range = mLODChangeMinDistSqr[nextLevel] - mLODChangeMinDistSqr[mCurLOD];
Real percent = (L - mLODChangeMinDistSqr[mCurLOD]) / range;
// scale so that morphFactor == 0 for percent == mLODMorphDistStart and morphFactor == 1
// for percent == 1, clamp to 0 below
Real scale = 1.0 / (1.0 - mLODMorphDistStart);
mLODMorphFactor = max((percent - mLODMorphDistStart) * scale, Real(0));
}
// bind the correct delta buffer if changed
if (mLastNextLOD != nextLevel)
{
if (nextLevel != mMaxLOD)
{
mVertexData->vertexBufferBinding->setBinding(DELTA_BINDING, mDeltaBuffers[nextLevel-1]);
}
else
{
// bind a dummy, the morph factor is 0 anyway
mVertexData->vertexBufferBinding->setBinding(DELTA_BINDING, mDeltaBuffers[0]);
}
mLastNextLOD = nextLevel;
}
}
}
Technique* Patch::getTechnique() const
{
// based on the current distance to the camera, select the appropriate LOD technique from the material
unsigned short lodIndex = mMaterial->getLodIndexSquaredDepth(mCurCameraDistanceSqr);
return mMaterial->getBestTechnique(lodIndex);
}
}
| 36.289552 | 113 | 0.655178 | [
"vector"
] |
7015e5f27a70f86b5d95234471a68390f8595f13 | 19,758 | cc | C++ | chromeos/dbus/experimental_bluetooth_device_client.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/dbus/experimental_bluetooth_device_client.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/dbus/experimental_bluetooth_device_client.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:25:45.000Z | 2020-11-04T07:25:45.000Z | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/dbus/experimental_bluetooth_device_client.h"
#include <map>
#include <utility>
#include "base/bind.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "chromeos/dbus/bluetooth_property.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_manager.h"
#include "dbus/object_path.h"
#include "dbus/object_proxy.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
const char ExperimentalBluetoothDeviceClient::kNoResponseError[] =
"org.chromium.Error.NoResponse";
const char ExperimentalBluetoothDeviceClient::kUnknownDeviceError[] =
"org.chromium.Error.UnknownDevice";
ExperimentalBluetoothDeviceClient::Properties::Properties(
dbus::ObjectProxy* object_proxy,
const std::string& interface_name,
const PropertyChangedCallback& callback)
: dbus::PropertySet(object_proxy, interface_name, callback) {
RegisterProperty(bluetooth_device::kAddressProperty, &address);
RegisterProperty(bluetooth_device::kNameProperty, &name);
RegisterProperty(bluetooth_device::kIconProperty, &icon);
RegisterProperty(bluetooth_device::kClassProperty, &bluetooth_class);
RegisterProperty(bluetooth_device::kAppearanceProperty, &appearance);
RegisterProperty(bluetooth_device::kUUIDsProperty, &uuids);
RegisterProperty(bluetooth_device::kPairedProperty, &paired);
RegisterProperty(bluetooth_device::kConnectedProperty, &connected);
RegisterProperty(bluetooth_device::kTrustedProperty, &trusted);
RegisterProperty(bluetooth_device::kBlockedProperty, &blocked);
RegisterProperty(bluetooth_device::kAliasProperty, &alias);
RegisterProperty(bluetooth_device::kAdapterProperty, &adapter);
RegisterProperty(bluetooth_device::kLegacyPairingProperty, &legacy_pairing);
RegisterProperty(bluetooth_device::kModaliasProperty, &modalias);
RegisterProperty(bluetooth_device::kRSSIProperty, &rssi);
}
ExperimentalBluetoothDeviceClient::Properties::~Properties() {
}
// The ExperimentalBluetoothDeviceClient implementation used in production.
class ExperimentalBluetoothDeviceClientImpl
: public ExperimentalBluetoothDeviceClient,
public dbus::ObjectManager::Interface {
public:
explicit ExperimentalBluetoothDeviceClientImpl(dbus::Bus* bus)
: bus_(bus),
weak_ptr_factory_(this) {
object_manager_ = bus_->GetObjectManager(
bluetooth_manager::kBluetoothManagerServiceName,
dbus::ObjectPath(bluetooth_manager::kBluetoothManagerServicePath));
object_manager_->RegisterInterface(
bluetooth_device::kExperimentalBluetoothDeviceInterface, this);
}
virtual ~ExperimentalBluetoothDeviceClientImpl() {
object_manager_->UnregisterInterface(
bluetooth_device::kExperimentalBluetoothDeviceInterface);
}
// ExperimentalBluetoothDeviceClient override.
virtual void AddObserver(
ExperimentalBluetoothDeviceClient::Observer* observer) OVERRIDE {
DCHECK(observer);
observers_.AddObserver(observer);
}
// ExperimentalBluetoothDeviceClient override.
virtual void RemoveObserver(
ExperimentalBluetoothDeviceClient::Observer* observer) OVERRIDE {
DCHECK(observer);
observers_.RemoveObserver(observer);
}
// dbus::ObjectManager::Interface override.
virtual dbus::PropertySet* CreateProperties(
dbus::ObjectProxy* object_proxy,
const dbus::ObjectPath& object_path,
const std::string& interface_name) {
Properties* properties = new Properties(
object_proxy, interface_name,
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnPropertyChanged,
weak_ptr_factory_.GetWeakPtr(),
object_path));
return static_cast<dbus::PropertySet*>(properties);
}
// ExperimentalBluetoothDeviceClient override.
virtual std::vector<dbus::ObjectPath> GetDevicesForAdapter(
const dbus::ObjectPath& adapter_path) OVERRIDE {
std::vector<dbus::ObjectPath> object_paths, device_paths;
device_paths = object_manager_->GetObjectsWithInterface(
bluetooth_device::kExperimentalBluetoothDeviceInterface);
for (std::vector<dbus::ObjectPath>::iterator iter = device_paths.begin();
iter != device_paths.end(); ++iter) {
Properties* properties = GetProperties(*iter);
if (properties->adapter.value() == adapter_path)
object_paths.push_back(*iter);
}
return object_paths;
}
// ExperimentalBluetoothDeviceClient override.
virtual Properties* GetProperties(const dbus::ObjectPath& object_path)
OVERRIDE {
return static_cast<Properties*>(
object_manager_->GetProperties(
object_path,
bluetooth_device::kExperimentalBluetoothDeviceInterface));
}
// ExperimentalBluetoothDeviceClient override.
virtual void Connect(const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) OVERRIDE {
dbus::MethodCall method_call(
bluetooth_device::kExperimentalBluetoothDeviceInterface,
bluetooth_device::kConnect);
dbus::ObjectProxy* object_proxy =
object_manager_->GetObjectProxy(object_path);
if (!object_proxy) {
error_callback.Run(kUnknownDeviceError, "");
return;
}
// Connect may take an arbitrary length of time, so use no timeout.
object_proxy->CallMethodWithErrorCallback(
&method_call,
dbus::ObjectProxy::TIMEOUT_INFINITE,
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnSuccess,
weak_ptr_factory_.GetWeakPtr(), callback),
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnError,
weak_ptr_factory_.GetWeakPtr(), error_callback));
}
// ExperimentalBluetoothDeviceClient override.
virtual void Disconnect(const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) OVERRIDE {
dbus::MethodCall method_call(
bluetooth_device::kExperimentalBluetoothDeviceInterface,
bluetooth_device::kDisconnect);
dbus::ObjectProxy* object_proxy =
object_manager_->GetObjectProxy(object_path);
if (!object_proxy) {
error_callback.Run(kUnknownDeviceError, "");
return;
}
object_proxy->CallMethodWithErrorCallback(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnSuccess,
weak_ptr_factory_.GetWeakPtr(), callback),
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnError,
weak_ptr_factory_.GetWeakPtr(), error_callback));
}
// ExperimentalBluetoothDeviceClient override.
virtual void ConnectProfile(const dbus::ObjectPath& object_path,
const std::string& uuid,
const base::Closure& callback,
const ErrorCallback& error_callback) OVERRIDE {
dbus::MethodCall method_call(
bluetooth_device::kExperimentalBluetoothDeviceInterface,
bluetooth_device::kConnectProfile);
dbus::MessageWriter writer(&method_call);
writer.AppendString(uuid);
dbus::ObjectProxy* object_proxy =
object_manager_->GetObjectProxy(object_path);
if (!object_proxy) {
error_callback.Run(kUnknownDeviceError, "");
return;
}
// Connect may take an arbitrary length of time, so use no timeout.
object_proxy->CallMethodWithErrorCallback(
&method_call,
dbus::ObjectProxy::TIMEOUT_INFINITE,
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnSuccess,
weak_ptr_factory_.GetWeakPtr(), callback),
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnError,
weak_ptr_factory_.GetWeakPtr(), error_callback));
}
// ExperimentalBluetoothDeviceClient override.
virtual void DisconnectProfile(const dbus::ObjectPath& object_path,
const std::string& uuid,
const base::Closure& callback,
const ErrorCallback& error_callback)
OVERRIDE {
dbus::MethodCall method_call(
bluetooth_device::kExperimentalBluetoothDeviceInterface,
bluetooth_device::kDisconnectProfile);
dbus::MessageWriter writer(&method_call);
writer.AppendString(uuid);
dbus::ObjectProxy* object_proxy =
object_manager_->GetObjectProxy(object_path);
if (!object_proxy) {
error_callback.Run(kUnknownDeviceError, "");
return;
}
object_proxy->CallMethodWithErrorCallback(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnSuccess,
weak_ptr_factory_.GetWeakPtr(), callback),
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnError,
weak_ptr_factory_.GetWeakPtr(), error_callback));
}
// ExperimentalBluetoothDeviceClient override.
virtual void Pair(const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) OVERRIDE {
dbus::MethodCall method_call(
bluetooth_device::kExperimentalBluetoothDeviceInterface,
bluetooth_device::kPair);
dbus::ObjectProxy* object_proxy =
object_manager_->GetObjectProxy(object_path);
if (!object_proxy) {
error_callback.Run(kUnknownDeviceError, "");
return;
}
// Pairing may take an arbitrary length of time, so use no timeout.
object_proxy->CallMethodWithErrorCallback(
&method_call,
dbus::ObjectProxy::TIMEOUT_INFINITE,
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnSuccess,
weak_ptr_factory_.GetWeakPtr(), callback),
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnError,
weak_ptr_factory_.GetWeakPtr(), error_callback));
}
// ExperimentalBluetoothDeviceClient override.
virtual void CancelPairing(const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback)
OVERRIDE {
dbus::MethodCall method_call(
bluetooth_device::kExperimentalBluetoothDeviceInterface,
bluetooth_device::kCancelPairing);
dbus::ObjectProxy* object_proxy =
object_manager_->GetObjectProxy(object_path);
if (!object_proxy) {
error_callback.Run(kUnknownDeviceError, "");
return;
}
object_proxy->CallMethodWithErrorCallback(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnSuccess,
weak_ptr_factory_.GetWeakPtr(), callback),
base::Bind(&ExperimentalBluetoothDeviceClientImpl::OnError,
weak_ptr_factory_.GetWeakPtr(), error_callback));
}
private:
// Called by dbus::ObjectManager when an object with the device interface
// is created. Informs observers.
void ObjectAdded(const dbus::ObjectPath& object_path,
const std::string& interface_name) OVERRIDE {
FOR_EACH_OBSERVER(ExperimentalBluetoothDeviceClient::Observer, observers_,
DeviceAdded(object_path));
}
// Called by dbus::ObjectManager when an object with the device interface
// is removed. Informs observers.
void ObjectRemoved(const dbus::ObjectPath& object_path,
const std::string& interface_name) OVERRIDE {
FOR_EACH_OBSERVER(ExperimentalBluetoothDeviceClient::Observer, observers_,
DeviceRemoved(object_path));
}
// Called by BluetoothPropertySet when a property value is changed,
// either by result of a signal or response to a GetAll() or Get()
// call. Informs observers.
void OnPropertyChanged(const dbus::ObjectPath& object_path,
const std::string& property_name) {
FOR_EACH_OBSERVER(ExperimentalBluetoothDeviceClient::Observer, observers_,
DevicePropertyChanged(object_path, property_name));
}
// Called when a response for successful method call is received.
void OnSuccess(const base::Closure& callback,
dbus::Response* response) {
DCHECK(response);
callback.Run();
}
// Called when a response for a failed method call is received.
void OnError(const ErrorCallback& error_callback,
dbus::ErrorResponse* response) {
// Error response has optional error message argument.
std::string error_name;
std::string error_message;
if (response) {
dbus::MessageReader reader(response);
error_name = response->GetErrorName();
reader.PopString(&error_message);
} else {
error_name = kNoResponseError;
error_message = "";
}
error_callback.Run(error_name, error_message);
}
dbus::Bus* bus_;
dbus::ObjectManager* object_manager_;
// List of observers interested in event notifications from us.
ObserverList<ExperimentalBluetoothDeviceClient::Observer> observers_;
// Weak pointer factory for generating 'this' pointers that might live longer
// than we do.
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<ExperimentalBluetoothDeviceClientImpl> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ExperimentalBluetoothDeviceClientImpl);
};
// The ExperimentalBluetoothDeviceClient implementation used on Linux desktop,
// which does nothing.
class ExperimentalBluetoothDeviceClientStubImpl
: public ExperimentalBluetoothDeviceClient {
public:
struct Properties : public ExperimentalBluetoothDeviceClient::Properties {
explicit Properties(const PropertyChangedCallback& callback)
: ExperimentalBluetoothDeviceClient::Properties(
NULL,
bluetooth_device::kExperimentalBluetoothDeviceInterface,
callback) {
}
virtual ~Properties() {
}
virtual void Get(dbus::PropertyBase* property,
dbus::PropertySet::GetCallback callback) OVERRIDE {
VLOG(1) << "Get " << property->name();
callback.Run(false);
}
virtual void GetAll() OVERRIDE {
VLOG(1) << "GetAll";
}
virtual void Set(dbus::PropertyBase *property,
dbus::PropertySet::SetCallback callback) OVERRIDE {
VLOG(1) << "Set " << property->name();
callback.Run(false);
}
};
ExperimentalBluetoothDeviceClientStubImpl() {
dbus::ObjectPath dev0("/fake/hci0/dev0");
Properties* properties = new Properties(base::Bind(
&ExperimentalBluetoothDeviceClientStubImpl::OnPropertyChanged,
base::Unretained(this),
dev0));
properties->address.ReplaceValue("00:11:22:33:44:55");
properties->name.ReplaceValue("Fake Device");
properties->paired.ReplaceValue(true);
properties->trusted.ReplaceValue(true);
properties_map_[dev0] = properties;
}
virtual ~ExperimentalBluetoothDeviceClientStubImpl() {
// Clean up Properties structures
STLDeleteValues(&properties_map_);
}
// ExperimentalBluetoothDeviceClient override.
virtual void AddObserver(Observer* observer) OVERRIDE {
observers_.AddObserver(observer);
}
// ExperimentalBluetoothDeviceClient override.
virtual void RemoveObserver(Observer* observer) OVERRIDE {
observers_.RemoveObserver(observer);
}
virtual std::vector<dbus::ObjectPath> GetDevicesForAdapter(
const dbus::ObjectPath& adapter_path) OVERRIDE {
std::vector<dbus::ObjectPath> object_paths;
if (adapter_path.value() == "/fake/hci0")
object_paths.push_back(dbus::ObjectPath("/fake/hci0/dev0"));
return object_paths;
}
// ExperimentalBluetoothDeviceClient override.
virtual Properties* GetProperties(const dbus::ObjectPath& object_path)
OVERRIDE {
VLOG(1) << "GetProperties: " << object_path.value();
PropertiesMap::iterator iter = properties_map_.find(object_path);
if (iter != properties_map_.end())
return iter->second;
return NULL;
}
// ExperimentalBluetoothDeviceClient override.
virtual void Connect(const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) OVERRIDE {
VLOG(1) << "Connect: " << object_path.value();
error_callback.Run(kNoResponseError, "");
}
// ExperimentalBluetoothDeviceClient override.
virtual void Disconnect(const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) OVERRIDE {
VLOG(1) << "Disconnect: " << object_path.value();
error_callback.Run(kNoResponseError, "");
}
// ExperimentalBluetoothDeviceClient override.
virtual void ConnectProfile(const dbus::ObjectPath& object_path,
const std::string& uuid,
const base::Closure& callback,
const ErrorCallback& error_callback)
OVERRIDE {
VLOG(1) << "ConnectProfile: " << object_path.value() << " " << uuid;
error_callback.Run(kNoResponseError, "");
}
// ExperimentalBluetoothDeviceClient override.
virtual void DisconnectProfile(const dbus::ObjectPath& object_path,
const std::string& uuid,
const base::Closure& callback,
const ErrorCallback& error_callback)
OVERRIDE {
VLOG(1) << "DisconnectProfile: " << object_path.value() << " " << uuid;
error_callback.Run(kNoResponseError, "");
}
// ExperimentalBluetoothDeviceClient override.
virtual void Pair(const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) OVERRIDE {
VLOG(1) << "Pair: " << object_path.value();
error_callback.Run(kNoResponseError, "");
}
// ExperimentalBluetoothDeviceClient override.
virtual void CancelPairing(const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback)
OVERRIDE {
VLOG(1) << "CancelPairing: " << object_path.value();
error_callback.Run(kNoResponseError, "");
}
private:
void OnPropertyChanged(dbus::ObjectPath object_path,
const std::string& property_name) {
FOR_EACH_OBSERVER(ExperimentalBluetoothDeviceClient::Observer, observers_,
DevicePropertyChanged(object_path, property_name));
}
// List of observers interested in event notifications from us.
ObserverList<Observer> observers_;
// Static properties we typedef.
typedef std::map<const dbus::ObjectPath, Properties *> PropertiesMap;
PropertiesMap properties_map_;
};
ExperimentalBluetoothDeviceClient::ExperimentalBluetoothDeviceClient() {
}
ExperimentalBluetoothDeviceClient::~ExperimentalBluetoothDeviceClient() {
}
ExperimentalBluetoothDeviceClient* ExperimentalBluetoothDeviceClient::Create(
DBusClientImplementationType type,
dbus::Bus* bus) {
if (type == REAL_DBUS_CLIENT_IMPLEMENTATION)
return new ExperimentalBluetoothDeviceClientImpl(bus);
DCHECK_EQ(STUB_DBUS_CLIENT_IMPLEMENTATION, type);
return new ExperimentalBluetoothDeviceClientStubImpl();
}
} // namespace chromeos
| 38.665362 | 80 | 0.699767 | [
"object",
"vector"
] |
702ff7c530dfa928468455391ac45d0d3f93a7f5 | 13,277 | cpp | C++ | function-pointer-analysis/LLVMAssignment.cpp | kippesp/clang-llvm-tutorial | 92e5478fdebb9a11c60dc39e5a0556056346e957 | [
"WTFPL"
] | null | null | null | function-pointer-analysis/LLVMAssignment.cpp | kippesp/clang-llvm-tutorial | 92e5478fdebb9a11c60dc39e5a0556056346e957 | [
"WTFPL"
] | null | null | null | function-pointer-analysis/LLVMAssignment.cpp | kippesp/clang-llvm-tutorial | 92e5478fdebb9a11c60dc39e5a0556056346e957 | [
"WTFPL"
] | 1 | 2021-11-15T12:55:27.000Z | 2021-11-15T12:55:27.000Z | //===- Hello.cpp - Example code from "Writing an LLVM Pass" ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements two versions of the LLVM "Hello World" pass described
// in docs/WritingAnLLVMPass.html
//
//===----------------------------------------------------------------------===//
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/ToolOutputFile.h>
#include <llvm/Transforms/Scalar.h>
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include <iostream>
#include <set>
#include <string>
#include <vector>
using namespace llvm;
using namespace std;
// class function_data
// {
// public:
// llvm::StringRef fun_name;
// unsigned int numOfParams ;
// std::vector<llvm::Type::TypeID> params;
// };
///!TODO TO BE COMPLETED BY YOU FOR ASSIGNMENT 2
struct FuncPtrPass : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
FuncPtrPass() : FunctionPass(ID) {}
set<StringRef> call_list;
set<Value *> _call_list;
// type str match
StringRef getTypeString(Type *type) {
StringRef param_type = "";
switch (type->getTypeID()) {
case 0:
param_type = "void";
break;
case 1:
case 2:
param_type = "float";
break;
case 3:
case 4:
case 5:
case 6:
param_type = "double";
break;
case 7:
param_type = "label";
break;
case 10:
if (type->getIntegerBitWidth() == 8) {
param_type = "char";
} else {
param_type = "int";
}
break;
case 11:
param_type = "function";
break;
case 12:
param_type = "struct";
break;
case 13:
param_type = "array";
break;
case 14:
param_type = "pointer";
break;
default:
param_type = "default";
break;
}
return param_type;
}
// todo: arg num match
// process the function pointer that is passed by argument
void getArgFuncptr(Argument *argument) {
unsigned offset = argument->getArgNo();
// get its parent caller
Function *parent = argument->getParent();
for (User *U : parent->users()) {
if (CallInst *callInstCall = dyn_cast<CallInst>(U)) {
Value *v = callInstCall->getArgOperand(offset);
if (Function *func = dyn_cast<Function>(v)) {
// errs()<<func->getName ()<<"\n";
call_list.insert(func->getName());
_call_list.insert(v);
} else if (PHINode *phi_node = dyn_cast<PHINode>(v)) {
for (User *U : phi_node->users()) {
if (CallInst *callInstCall = dyn_cast<CallInst>(U)) {
Value *v = callInstCall->getArgOperand(offset);
if (Function *func = dyn_cast<Function>(v)) {
call_list.insert(func->getName());
_call_list.insert(v);
}
}
}
getPhiNode(phi_node);
} else if (LoadInst *loadInst = dyn_cast<LoadInst>(v)) {
getLoadInst(loadInst);
} else if (Argument *_argument = dyn_cast<Argument>(v)) {
getArgFuncptr(_argument);
}
} else if (PHINode *phi_node = dyn_cast<PHINode>(U)) {
for (User *U : phi_node->users()) {
if (CallInst *call_inst = dyn_cast<CallInst>(U)) {
Value *v = call_inst->getOperand(offset);
if (Function *func = dyn_cast<Function>(v)) {
call_list.insert(func->getName());
_call_list.insert(v);
}
}
}
}
}
}
void getCallInst(CallInst *call_inst) {
Function *func = call_inst->getCalledFunction();
// funcptr
if (func != NULL) {
for (inst_iterator inst_it = inst_begin(func), inst_ie = inst_end(func);
inst_it != inst_ie; ++inst_it) {
if (ReturnInst *ret = dyn_cast<ReturnInst>(&*inst_it)) {
Value *v = ret->getReturnValue();
if (Argument *argument = dyn_cast<Argument>(v)) {
getArgFuncptr(argument);
}
}
}
} else {
Value *funcptr = call_inst->getCalledValue();
if (PHINode *phi_node = dyn_cast<PHINode>(funcptr)) {
for (Value *Incoming : phi_node->incoming_values()) {
if (Function *func = dyn_cast<Function>(Incoming)) {
for (inst_iterator inst_it = inst_begin(func),
inst_ie = inst_end(func);
inst_it != inst_ie; ++inst_it) {
if (ReturnInst *ret = dyn_cast<ReturnInst>(&*inst_it)) {
Value *v = ret->getReturnValue();
if (Argument *argument = dyn_cast<Argument>(v)) {
getArgFuncptr(argument);
}
}
}
}
}
}
}
}
// process the function pointer
void getFunc(CallInst *callInst) {
Value *funcptr = callInst->getCalledValue();
// todo:corner case-bonus,load instruction
if (LoadInst *load_inst = dyn_cast<LoadInst>(funcptr)) {
getLoadInst(load_inst);
}
// the function pointer may be passed by the arg, get the use of the
// argument
else if (Argument *argument = dyn_cast<Argument>(funcptr)) {
getArgFuncptr(argument);
} else if (PHINode *phi_node = dyn_cast<PHINode>(funcptr)) {
getPhiNode(phi_node);
}
// the function pointer is a call intruction,recursively process
else if (CallInst *call_inst = dyn_cast<CallInst>(funcptr)) {
getCallInst(call_inst);
}
}
void getPhiNode(PHINode *phi_node) {
for (Value *Incoming : phi_node->incoming_values()) {
if (Function *func = dyn_cast<Function>(Incoming)) {
// errs()<<func->getName()<<"\n";
call_list.insert(func->getName());
_call_list.insert(Incoming);
}
// the phi node may contains null
else if (Constant *cons = dyn_cast<Constant>(Incoming)) {
if (ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(cons)) {
call_list.insert(StringRef("NULL"));
Function *func;
_call_list.insert(func);
}
} else if (phi_node = dyn_cast<PHINode>(Incoming)) {
getPhiNode(phi_node);
} else if (Argument *argument = dyn_cast<Argument>(Incoming)) {
getArgFuncptr(argument);
}
}
}
// corner case-bonus,load instruction
void getLoadInst(LoadInst *load_inst) {
Value *v = load_inst->getPointerOperand();
for (User *U : v->users()) {
if (StoreInst *st = dyn_cast<StoreInst>(U)) {
Value *value = st->getOperand(0);
if (Function *func = dyn_cast<Function>(value)) {
call_list.insert(func->getName());
_call_list.insert(value);
} else if (Argument *argument = dyn_cast<Argument>(value)) {
getArgFuncptr(argument);
} else if (load_inst = dyn_cast<LoadInst>(value)) {
getLoadInst(load_inst);
}
}
}
if (GetElementPtrInst *getElementPtrInst = dyn_cast<GetElementPtrInst>(v)) {
getGetElementPtrInst(getElementPtrInst);
}
}
void getGetElementPtrInst(GetElementPtrInst *getElementPtrInst) {
Value *v = getElementPtrInst->getOperand(0);
for (User *U : v->users()) {
if (GetElementPtrInst *gepi = dyn_cast<GetElementPtrInst>(U)) {
if (cmpGetElementPtrInst(getElementPtrInst, gepi) == true) {
for (User *UL : gepi->users()) {
if (StoreInst *storeInst = dyn_cast<StoreInst>(UL)) {
Value *vl = storeInst->getOperand(0);
if (Function *func = dyn_cast<Function>(vl)) {
call_list.insert(func->getName());
_call_list.insert(vl);
}
}
}
}
}
}
}
bool cmpGetElementPtrInst(GetElementPtrInst *gep_left,
GetElementPtrInst *gep_right) {
unsigned int ASL = gep_left->getPointerAddressSpace();
unsigned int ASR = gep_right->getPointerAddressSpace();
if (ASL != ASR) return false;
Type *ETL = gep_left->getSourceElementType();
Type *ETR = gep_right->getSourceElementType();
string bufferL;
raw_string_ostream osL(bufferL);
osL << *ETL;
string strETL = osL.str();
string bufferR;
raw_string_ostream osR(bufferR);
osR << *ETL;
string strETR = osR.str();
if (strETL != strETR) return false;
unsigned int NPL = gep_left->getNumOperands();
unsigned int NPR = gep_right->getNumOperands();
if (NPL != NPR) return false;
for (unsigned i = 0, e = gep_left->getNumOperands(); i != e; ++i) {
Value *vL = gep_left->getOperand(i);
Value *vR = gep_right->getOperand(i);
if (cmpValue(vL, vR) == false) return false;
}
return true;
}
bool cmpValue(Value *L, Value *R) {
string bufferL;
raw_string_ostream osL(bufferL);
osL << *L;
string strVL = osL.str();
string bufferR;
raw_string_ostream osR(bufferR);
osR << *R;
string strVR = osR.str();
if (strVL != strVR) return false;
return true;
}
// show the result
void display(unsigned line) {
errs() << line << " : ";
auto it = call_list.begin();
auto ie = call_list.end();
if (it != ie) {
errs() << *it;
++it;
}
for (; it != ie; ++it) {
errs() << ", " << *it;
}
errs() << "\n";
}
bool runOnFunction(Function &F) override {
bool updated = false;
// for each basic block in the function
Function::iterator bb_it = F.begin(), bb_ie = F.end();
for (; bb_it != bb_ie; ++bb_it) {
// for each intruction in the basic block
BasicBlock::iterator ii = bb_it->begin(), ie = bb_it->end();
for (; ii != ie; ++ii) {
Instruction *inst = dyn_cast<Instruction>(ii);
// only process the call instruction to get the possible function call
if (isa<CallInst>(ii)) {
CallInst *call = dyn_cast<CallInst>(inst);
// errs()<<*call<<"\n";
Function *func = call->getCalledFunction();
// FunctionType *type = call->getFunctionType();
// function pointer
if (func == NULL) {
// process the funcptr
getFunc(call);
display(call->getDebugLoc().getLine());
if (_call_list.size() == 1) {
call->setCalledFunction(*(_call_list.begin()));
// errs()<<*callInst<<" getCalledFunction Modified\n";
updated = true;
}
} // end of func==NULL
// debug call,e.g. llvm.dbg.value, ignore these info
else if (func->isIntrinsic()) {
continue;
}
// func is not null, so it is direct function call
else {
// output the call info directly
errs() << call->getDebugLoc().getLine() << " : " << func->getName()
<< "\n";
}
} // end of if()
} // end of for(ii)
} // end of outer loop
if (updated) return true;
return false;
}
};
char FuncPtrPass::ID = 0;
static RegisterPass<FuncPtrPass> X("funcptrpass",
"Print function call instruction");
static cl::opt<std::string> InputFilename(cl::Positional,
cl::desc("<filename>.bc"),
cl::init(""));
int main(int argc, char **argv) {
//LLVMContext &Context = getGlobalContext();
static LLVMContext Context;
SMDiagnostic Err;
// Parse the command line to read the Inputfilename
cl::ParseCommandLineOptions(
argc, argv, "FuncPtrPass \n My first LLVM too which does not do much.\n");
// Load the input module
std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
if (!M) {
Err.print(argv[0], errs());
return 1;
}
llvm::legacy::PassManager Passes;
/// Transform it to SSA
Passes.add(llvm::createPromoteMemoryToRegisterPass());
/// Your pass to print Function and Call Instructions
Passes.add(new FuncPtrPass());
bool updated = Passes.run(*M.get());
// write the changed call instruction to file
if (updated) {
// errs()<<"changed\n";
std::error_code EC;
std::unique_ptr<tool_output_file> Out(
new tool_output_file(InputFilename, EC, sys::fs::F_None));
WriteBitcodeToFile(M.get(), Out->os());
Out->keep();
}
}
| 30.592166 | 80 | 0.57287 | [
"vector",
"transform"
] |
7032932a22ff170788ee7d4e205571bfba359e63 | 2,489 | cpp | C++ | ext/libigl/external/cgal/src/CGAL_Project/examples/Point_set_processing_3/normals_example.cpp | liminchen/OptCuts | cb85b06ece3a6d1279863e26b5fd17a5abb0834d | [
"MIT"
] | 187 | 2019-01-23T04:07:11.000Z | 2022-03-27T03:44:58.000Z | ext/libigl/external/cgal/src/CGAL_Project/examples/Point_set_processing_3/normals_example.cpp | xiaoxie5002/OptCuts | 1f4168fc867f47face85fcfa3a572be98232786f | [
"MIT"
] | 8 | 2019-03-22T13:27:38.000Z | 2020-06-18T13:23:23.000Z | ext/libigl/external/cgal/src/CGAL_Project/examples/Point_set_processing_3/normals_example.cpp | xiaoxie5002/OptCuts | 1f4168fc867f47face85fcfa3a572be98232786f | [
"MIT"
] | 34 | 2019-02-13T01:11:12.000Z | 2022-02-28T03:29:40.000Z | #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/pca_estimate_normals.h>
#include <CGAL/mst_orient_normals.h>
#include <CGAL/property_map.h>
#include <CGAL/IO/read_xyz_points.h>
#include <utility> // defines std::pair
#include <list>
#include <fstream>
// Types
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef Kernel::Point_3 Point;
typedef Kernel::Vector_3 Vector;
// Point with normal vector stored in a std::pair.
typedef std::pair<Point, Vector> PointVectorPair;
// Concurrency
#ifdef CGAL_LINKED_WITH_TBB
typedef CGAL::Parallel_tag Concurrency_tag;
#else
typedef CGAL::Sequential_tag Concurrency_tag;
#endif
int main(int argc, char*argv[])
{
const char* fname = (argc>1)?argv[1]:"data/sphere_1k.xyz";
// Reads a .xyz point set file in points[].
std::list<PointVectorPair> points;
std::ifstream stream(fname);
if (!stream ||
!CGAL::read_xyz_points(stream,
std::back_inserter(points),
CGAL::First_of_pair_property_map<PointVectorPair>()))
{
std::cerr << "Error: cannot read file " << fname<< std::endl;
return EXIT_FAILURE;
}
// Estimates normals direction.
// Note: pca_estimate_normals() requires an iterator over points
// as well as property maps to access each point's position and normal.
const int nb_neighbors = 18; // K-nearest neighbors = 3 rings
CGAL::pca_estimate_normals<Concurrency_tag>(points.begin(), points.end(),
CGAL::First_of_pair_property_map<PointVectorPair>(),
CGAL::Second_of_pair_property_map<PointVectorPair>(),
nb_neighbors);
// Orients normals.
// Note: mst_orient_normals() requires an iterator over points
// as well as property maps to access each point's position and normal.
std::list<PointVectorPair>::iterator unoriented_points_begin =
CGAL::mst_orient_normals(points.begin(), points.end(),
CGAL::First_of_pair_property_map<PointVectorPair>(),
CGAL::Second_of_pair_property_map<PointVectorPair>(),
nb_neighbors);
// Optional: delete points with an unoriented normal
// if you plan to call a reconstruction algorithm that expects oriented normals.
points.erase(unoriented_points_begin, points.end());
return EXIT_SUCCESS;
}
| 37.712121 | 86 | 0.668943 | [
"vector"
] |
703803632a13be1bf0b65db2afe7edd95793fd3f | 10,741 | cpp | C++ | src/ql/ql_manager.cpp | li-plus/redbase-cpp | 38f9612b2cf4fbd792a2da13ca95295e789ba8aa | [
"MIT"
] | 18 | 2021-02-15T14:28:06.000Z | 2022-03-30T19:58:38.000Z | src/ql/ql_manager.cpp | li-plus/redbase-cpp | 38f9612b2cf4fbd792a2da13ca95295e789ba8aa | [
"MIT"
] | null | null | null | src/ql/ql_manager.cpp | li-plus/redbase-cpp | 38f9612b2cf4fbd792a2da13ca95295e789ba8aa | [
"MIT"
] | 5 | 2021-05-22T06:07:32.000Z | 2022-03-10T05:32:10.000Z | #include "ql_manager.h"
#include "ql_node.h"
#include "record_printer.h"
#include "sm/sm.h"
#include "ix/ix.h"
static TabCol check_column(const std::vector<ColMeta> &all_cols, TabCol target) {
if (target.tab_name.empty()) {
// Table name not specified, infer table name from column name
std::string tab_name;
for (auto &col: all_cols) {
if (col.name == target.col_name) {
if (!tab_name.empty()) {
throw AmbiguousColumnError(target.col_name);
}
tab_name = col.tab_name;
}
}
if (tab_name.empty()) { throw ColumnNotFoundError(target.col_name); }
target.tab_name = tab_name;
} else {
// Make sure target column exists
if (!(SmManager::db.is_table(target.tab_name) &&
SmManager::db.get_table(target.tab_name).is_col(target.col_name))) {
throw ColumnNotFoundError(target.tab_name + '.' + target.col_name);
}
}
return target;
}
static std::vector<ColMeta> get_all_cols(const std::vector<std::string> &tab_names) {
std::vector<ColMeta> all_cols;
for (auto &sel_tab_name: tab_names) {
const auto &sel_tab_cols = SmManager::db.get_table(sel_tab_name).cols;
all_cols.insert(all_cols.end(), sel_tab_cols.begin(), sel_tab_cols.end());
}
return all_cols;
}
static std::vector<Condition> check_where_clause(const std::vector<std::string> &tab_names,
const std::vector<Condition> &conds) {
auto all_cols = get_all_cols(tab_names);
// Get raw values in where clause
std::vector<Condition> res_conds = conds;
for (auto &cond: res_conds) {
// Infer table name from column name
cond.lhs_col = check_column(all_cols, cond.lhs_col);
if (!cond.is_rhs_val) {
cond.rhs_col = check_column(all_cols, cond.rhs_col);
}
TabMeta &lhs_tab = SmManager::db.get_table(cond.lhs_col.tab_name);
auto lhs_col = lhs_tab.get_col(cond.lhs_col.col_name);
ColType lhs_type = lhs_col->type;
ColType rhs_type;
if (cond.is_rhs_val) {
cond.rhs_val.init_raw(lhs_col->len);
rhs_type = cond.rhs_val.type;
} else {
TabMeta &rhs_tab = SmManager::db.get_table(cond.rhs_col.tab_name);
auto rhs_col = rhs_tab.get_col(cond.rhs_col.col_name);
rhs_type = rhs_col->type;
}
if (lhs_type != rhs_type) {
throw IncompatibleTypeError(coltype2str(lhs_type), coltype2str(rhs_type));
}
}
return res_conds;
}
void QlManager::insert_into(const std::string &tab_name, std::vector<Value> values) {
TabMeta tab = SmManager::db.get_table(tab_name);
if (values.size() != tab.cols.size()) {
throw InvalidValueCountError();
}
// Get record file handle
auto fh = SmManager::fhs.at(tab_name).get();
// Make record buffer
RmRecord rec(fh->hdr.record_size);
for (size_t i = 0; i < values.size(); i++) {
auto &col = tab.cols[i];
auto &val = values[i];
if (col.type != val.type) {
throw IncompatibleTypeError(coltype2str(col.type), coltype2str(val.type));
}
val.init_raw(col.len);
memcpy(rec.data + col.offset, val.raw->data, col.len);
}
// Insert into record file
Rid rid = fh->insert_record(rec.data);
// Insert into index
for (size_t i = 0; i < tab.cols.size(); i++) {
auto &col = tab.cols[i];
if (col.index) {
auto ih = SmManager::ihs.at(IxManager::get_index_name(tab_name, i)).get();
ih->insert_entry(rec.data + col.offset, rid);
}
}
}
void QlManager::delete_from(const std::string &tab_name, std::vector<Condition> conds) {
TabMeta &tab = SmManager::db.get_table(tab_name);
// Parse where clause
conds = check_where_clause({tab_name}, conds);
// Get all RID to delete
std::vector<Rid> rids;
QlNodeTable table_scan(tab_name, conds);
for (table_scan.begin(); !table_scan.is_end(); table_scan.next()) {
rids.push_back(table_scan.rid());
}
// Get record file
auto fh = SmManager::fhs.at(tab_name).get();
// Get all index files
std::vector<IxIndexHandle *> ihs(tab.cols.size(), nullptr);
for (size_t col_i = 0; col_i < tab.cols.size(); col_i++) {
if (tab.cols[col_i].index) {
ihs[col_i] = SmManager::ihs.at(IxManager::get_index_name(tab_name, col_i)).get();
}
}
// Delete each rid from record file and index file
for (auto &rid: rids) {
auto rec = fh->get_record(rid);
// Delete from index file
for (size_t col_i = 0; col_i < tab.cols.size(); col_i++) {
if (ihs[col_i] != nullptr) {
ihs[col_i]->delete_entry(rec->data + tab.cols[col_i].offset, rid);
}
}
// Delete from record file
fh->delete_record(rid);
}
}
void QlManager::update_set(const std::string &tab_name,
std::vector<SetClause> set_clauses,
std::vector<Condition> conds) {
TabMeta &tab = SmManager::db.get_table(tab_name);
// Parse where clause
conds = check_where_clause({tab_name}, conds);
// Get raw values in set clause
for (auto &set_clause: set_clauses) {
auto lhs_col = tab.get_col(set_clause.lhs.col_name);
if (lhs_col->type != set_clause.rhs.type) {
throw IncompatibleTypeError(coltype2str(lhs_col->type), coltype2str(set_clause.rhs.type));
}
set_clause.rhs.init_raw(lhs_col->len);
}
// Get all RID to update
std::vector<Rid> rids;
QlNodeTable table_scan(tab_name, conds);
for (table_scan.begin(); !table_scan.is_end(); table_scan.next()) {
rids.push_back(table_scan.rid());
}
// Get record file
auto fh = SmManager::fhs.at(tab_name).get();
// Get all necessary index files
std::vector<IxIndexHandle *> ihs(tab.cols.size(), nullptr);
for (auto &set_clause: set_clauses) {
auto lhs_col = tab.get_col(set_clause.lhs.col_name);
if (lhs_col->index) {
size_t lhs_col_idx = lhs_col - tab.cols.begin();
if (ihs[lhs_col_idx] == nullptr) {
ihs[lhs_col_idx] = SmManager::ihs.at(IxManager::get_index_name(tab_name, lhs_col_idx)).get();
}
}
}
// Update each rid from record file and index file
for (auto &rid: rids) {
auto rec = fh->get_record(rid);
// Remove old entry from index
for (size_t i = 0; i < tab.cols.size(); i++) {
if (ihs[i] != nullptr) {
ihs[i]->delete_entry(rec->data + tab.cols[i].offset, rid);
}
}
// Update record in record file
for (auto &set_clause: set_clauses) {
auto lhs_col = tab.get_col(set_clause.lhs.col_name);
memcpy(rec->data + lhs_col->offset, set_clause.rhs.raw->data, lhs_col->len);
}
fh->update_record(rid, rec->data);
// Insert new entry into index
for (size_t i = 0; i < tab.cols.size(); i++) {
if (ihs[i] != nullptr) {
ihs[i]->insert_entry(rec->data + tab.cols[i].offset, rid);
}
}
}
}
static std::vector<Condition> pop_conds(std::vector<Condition> &conds,
const std::vector<std::string> &tab_names) {
auto has_tab = [&](const std::string &tab_name) {
return std::find(tab_names.begin(), tab_names.end(), tab_name) != tab_names.end();
};
std::vector<Condition> solved_conds;
auto it = conds.begin();
while (it != conds.end()) {
if (has_tab(it->lhs_col.tab_name) && (it->is_rhs_val || has_tab(it->rhs_col.tab_name))) {
solved_conds.emplace_back(std::move(*it));
it = conds.erase(it);
} else {
it++;
}
}
return solved_conds;
}
void QlManager::select_from(std::vector<TabCol> sel_cols,
const std::vector<std::string> &tab_names,
std::vector<Condition> conds) {
// Parse selector
auto all_cols = get_all_cols(tab_names);
if (sel_cols.empty()) {
// select all columns
for (auto &col: all_cols) {
TabCol sel_col = {.tab_name = col.tab_name, .col_name = col.name};
sel_cols.push_back(sel_col);
}
} else {
// infer table name from column name
for (auto &sel_col: sel_cols) {
sel_col = check_column(all_cols, sel_col);
}
}
// Parse where clause
conds = check_where_clause(tab_names, conds);
// Scan table
std::vector<std::unique_ptr<QlNodeTable>> tab_nodes(tab_names.size());
for (size_t i = 0; i < tab_names.size(); i++) {
auto curr_conds = pop_conds(conds, {tab_names.begin(), tab_names.begin() + i + 1});
tab_nodes[i] = std::make_unique<QlNodeTable>(tab_names[i], curr_conds);
}
assert(conds.empty());
std::unique_ptr<QlNode> query_plan = std::move(tab_nodes.back());
for (size_t i = tab_names.size() - 2; i != (size_t) -1; i--) {
query_plan = std::make_unique<QlNodeJoin>(std::move(tab_nodes[i]), std::move(query_plan));
}
query_plan = std::make_unique<QlNodeProj>(std::move(query_plan), sel_cols);
// Column titles
std::vector<std::string> captions;
captions.reserve(sel_cols.size());
for (auto &sel_col: sel_cols) {
captions.push_back(sel_col.col_name);
}
// Print header
RecordPrinter rec_printer(sel_cols.size());
rec_printer.print_separator();
rec_printer.print_record(captions);
rec_printer.print_separator();
// Print records
size_t num_rec = 0;
for (query_plan->begin(); !query_plan->is_end(); query_plan->next()) {
auto rec = query_plan->rec();
std::vector<std::string> columns;
for (auto &col: query_plan->cols()) {
std::string col_str;
uint8_t *rec_buf = rec->data + col.offset;
if (col.type == TYPE_INT) {
col_str = std::to_string(*(int *) rec_buf);
} else if (col.type == TYPE_FLOAT) {
col_str = std::to_string(*(float *) rec_buf);
} else if (col.type == TYPE_STRING) {
col_str = std::string((char *) rec_buf, col.len);
col_str.resize(strlen(col_str.c_str()));
}
columns.push_back(col_str);
}
rec_printer.print_record(columns);
num_rec++;
}
// Print footer
rec_printer.print_separator();
// Print record count
RecordPrinter::print_record_count(num_rec);
}
| 38.916667 | 109 | 0.5884 | [
"vector"
] |
7044fc84391a6deb9e8e13f75878c964e7ebb276 | 23,234 | hpp | C++ | core/src/Cabana_Sort.hpp | suchyta1/Cabana | 126d67ce76645b90042197174fcc4cf494e6a56d | [
"Unlicense"
] | null | null | null | core/src/Cabana_Sort.hpp | suchyta1/Cabana | 126d67ce76645b90042197174fcc4cf494e6a56d | [
"Unlicense"
] | null | null | null | core/src/Cabana_Sort.hpp | suchyta1/Cabana | 126d67ce76645b90042197174fcc4cf494e6a56d | [
"Unlicense"
] | null | null | null | /****************************************************************************
* Copyright (c) 2018-2019 by the Cabana authors *
* All rights reserved. *
* *
* This file is part of the Cabana library. Cabana is distributed under a *
* BSD 3-clause license. For the licensing terms see the LICENSE file in *
* the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#ifndef CABANA_SORT_HPP
#define CABANA_SORT_HPP
#include <Cabana_AoSoA.hpp>
#include <Cabana_DeepCopy.hpp>
#include <Cabana_Slice.hpp>
#include <Kokkos_Core.hpp>
#include <Kokkos_Sort.hpp>
#include <type_traits>
namespace Cabana
{
//---------------------------------------------------------------------------//
/*!
\class BinningData
\brief Data describing the bin sizes and offsets resulting from a binning
operation.
*/
template <class DeviceType>
class BinningData
{
public:
using device_type = DeviceType;
using memory_space = typename device_type::memory_space;
using execution_space = typename device_type::execution_space;
using size_type = typename memory_space::size_type;
using CountView = Kokkos::View<const int *, device_type>;
using OffsetView = Kokkos::View<size_type *, device_type>;
BinningData()
: _nbin( 0 )
{
}
BinningData( const std::size_t begin, const std::size_t end,
CountView counts, OffsetView offsets,
OffsetView permute_vector )
: _begin( begin )
, _end( end )
, _nbin( counts.extent( 0 ) )
, _counts( counts )
, _offsets( offsets )
, _permute_vector( permute_vector )
{
}
/*!
\brief Get the number of bins.
\return The number of bins.
*/
KOKKOS_INLINE_FUNCTION
int numBin() const { return _nbin; }
/*!
\brief Given a bin get the number of tuples it contains.
\param bin_id The bin id.
\return The number of tuples in the bin.
*/
KOKKOS_INLINE_FUNCTION
int binSize( const size_type bin_id ) const { return _counts( bin_id ); }
/*!
\brief Given a bin get the tuple index at which it sorts.
\param bin_id The bin id.
\return The starting tuple index of the bin.
*/
KOKKOS_INLINE_FUNCTION
size_type binOffset( const size_type bin_id ) const
{
return _offsets( bin_id );
}
/*!
\brief Given a local tuple id in the binned layout, get the id of the
tuple in the old (unbinned) layout.
*/
KOKKOS_INLINE_FUNCTION
size_type permutation( const size_type tuple_id ) const
{
return _permute_vector( tuple_id );
}
/*!
\brief The beginning tuple index in the binning.
*/
KOKKOS_INLINE_FUNCTION
std::size_t rangeBegin() const { return _begin; }
/*!
\brief The ending tuple index in the binning.
*/
KOKKOS_INLINE_FUNCTION
std::size_t rangeEnd() const { return _end; }
private:
std::size_t _begin;
std::size_t _end;
int _nbin;
CountView _counts;
OffsetView _offsets;
OffsetView _permute_vector;
};
//---------------------------------------------------------------------------//
// Static type checker.
template <typename>
struct is_binning_data : public std::false_type
{
};
template <typename DeviceType>
struct is_binning_data<BinningData<DeviceType>> : public std::true_type
{
};
template <typename DeviceType>
struct is_binning_data<const BinningData<DeviceType>> : public std::true_type
{
};
namespace Impl
{
//---------------------------------------------------------------------------//
// Create a permutation vector over a range subset using a comparator over the
// given Kokkos View of keys.
template <class KeyViewType, class Comparator,
class DeviceType = typename KeyViewType::device_type>
BinningData<DeviceType>
kokkosBinSort( KeyViewType keys, Comparator comp, const bool sort_within_bins,
const std::size_t begin, const std::size_t end )
{
Kokkos::BinSort<KeyViewType, Comparator, DeviceType> bin_sort(
keys, begin, end, comp, sort_within_bins );
bin_sort.create_permute_vector();
return BinningData<DeviceType>( begin, end, bin_sort.get_bin_count(),
bin_sort.get_bin_offsets(),
bin_sort.get_permute_vector() );
}
//---------------------------------------------------------------------------//
// Given a set of keys, find the minimum and maximum over the given range.
template <class KeyViewType,
class DeviceType = typename KeyViewType::device_type>
Kokkos::MinMaxScalar<typename KeyViewType::non_const_value_type>
keyMinMax( KeyViewType keys, const std::size_t begin, const std::size_t end )
{
Kokkos::MinMaxScalar<typename KeyViewType::non_const_value_type> result;
Kokkos::MinMax<typename KeyViewType::non_const_value_type> reducer(
result );
Kokkos::parallel_reduce(
"Cabana::keyMinMax",
Kokkos::RangePolicy<typename DeviceType::execution_space>( begin, end ),
Kokkos::Impl::min_max_functor<KeyViewType>( keys ), reducer );
Kokkos::fence();
return result;
}
//---------------------------------------------------------------------------//
// Sort an AoSoA over a subset of its range using the given Kokkos View of
// keys.
template <class KeyViewType,
class DeviceType = typename KeyViewType::device_type>
BinningData<DeviceType>
kokkosBinSort1d( KeyViewType keys, const int nbin, const bool sort_within_bins,
const std::size_t begin, const std::size_t end )
{
// Find the minimum and maximum key values.
auto key_bounds =
Impl::keyMinMax<KeyViewType, DeviceType>( keys, begin, end );
// Create a sorting comparator.
Kokkos::BinOp1D<KeyViewType> comp( nbin, key_bounds.min_val,
key_bounds.max_val );
// BinSort
return kokkosBinSort<KeyViewType, decltype( comp ), DeviceType>(
keys, comp, sort_within_bins, begin, end );
}
//---------------------------------------------------------------------------//
// Copy the a 1D slice into a Kokkos view.
template <class SliceType, class DeviceType = typename SliceType::device_type>
Kokkos::View<typename SliceType::value_type *, typename SliceType::device_type>
copySliceToKeys( SliceType slice )
{
using KeyViewType =
Kokkos::View<typename SliceType::value_type *, DeviceType>;
KeyViewType keys( Kokkos::ViewAllocateWithoutInitializing( "slice_keys" ),
slice.size() );
Kokkos::RangePolicy<typename DeviceType::execution_space> exec_policy(
0, slice.size() );
auto copy_op = KOKKOS_LAMBDA( const std::size_t i )
{
keys( i ) = slice( i );
};
Kokkos::parallel_for( "Cabana::copySliceToKeys::copy_op", exec_policy,
copy_op );
Kokkos::fence();
return keys;
}
//---------------------------------------------------------------------------//
} // end namespace Impl
//---------------------------------------------------------------------------//
/*!
\brief Sort an AoSoA over a subset of its range using a general comparator
over the given Kokkos View of keys.
\tparam KeyViewType The Kokkos::View type for keys.
\tparam Comparator Kokkos::BinSort compatible comparator type.
\param keys The key values to use for sorting. A key value is needed for
every element of the AoSoA.
\param comp The comparator to use for sorting. Must be compatible with
Kokkos::BinSort.
\param begin The beginning index of the AoSoA range to sort.
\param end The end index of the AoSoA range to sort.
\return The permutation vector associated with the sorting.
*/
template <class KeyViewType, class Comparator,
class DeviceType = typename KeyViewType::device_type>
BinningData<DeviceType> sortByKeyWithComparator(
KeyViewType keys, Comparator comp, const std::size_t begin,
const std::size_t end,
typename std::enable_if<( Kokkos::is_view<KeyViewType>::value ), int>::type
* = 0 )
{
auto bin_data = Impl::kokkosBinSort<KeyViewType, DeviceType>(
keys, comp, true, begin, end );
return bin_data.permuteVector();
}
//---------------------------------------------------------------------------//
/*!
\brief Sort an entire AoSoA using a general comparator over the given
Kokkos View of keys.
\tparam KeyViewType The Kokkos::View type for keys.
\tparam Comparator Kokkos::BinSort compatible comparator type.
\param keys The key values to use for sorting. A key value is needed for
every element of the AoSoA.
\param comp The comparator to use for sorting. Must be compatible with
Kokkos::BinSort.
\return The permutation vector associated with the sorting.
*/
template <class KeyViewType, class Comparator,
class DeviceType = typename KeyViewType::device_type>
BinningData<DeviceType> sortByKeyWithComparator(
KeyViewType keys, Comparator comp,
typename std::enable_if<( Kokkos::is_view<KeyViewType>::value ), int>::type
* = 0 )
{
Impl::kokkosBinSort<KeyViewType, DeviceType>( keys, comp, true, 0,
keys.extent( 0 ) );
}
//---------------------------------------------------------------------------//
/*!
\brief Bin an AoSoA over a subset of its range using a general comparator
over the given Kokkos View of keys.
\tparam KeyViewType The Kokkos::View type for keys.
\tparam Comparator Kokkos::BinSort compatible comparator type.
\param keys The key values to use for binning. A key value is needed for
every element of the AoSoA.
\param comp The comparator to use for binning. Must be compatible with
Kokkos::BinSort.
\param begin The beginning index of the AoSoA range to bin.
\param end The end index of the AoSoA range to bin.
\return The binning data (e.g. bin sizes and offsets).
*/
template <class KeyViewType, class Comparator,
class DeviceType = typename KeyViewType::device_type>
BinningData<DeviceType> binByKeyWithComparator(
KeyViewType keys, Comparator comp, const std::size_t begin,
const std::size_t end,
typename std::enable_if<( Kokkos::is_view<KeyViewType>::value ), int>::type
* = 0 )
{
return Impl::kokkosBinSort<KeyViewType, DeviceType>( keys, comp, false,
begin, end );
}
//---------------------------------------------------------------------------//
/*!
\brief Bin an entire AoSoA using a general comparator over the given Kokkos
View of keys.
\tparam KeyViewType The Kokkos::View type for keys.
\tparam Comparator Kokkos::BinSort compatible comparator type.
\param keys The key values to use for binning. A key value is needed for
every element of the AoSoA.
\param comp The comparator to use for binning. Must be compatible with
Kokkos::BinSort.
\return The binning data (e.g. bin sizes and offsets).
*/
template <class KeyViewType, class Comparator,
class DeviceType = typename KeyViewType::device_type>
BinningData<DeviceType> binByKeyWithComparator(
KeyViewType keys, Comparator comp,
typename std::enable_if<( Kokkos::is_view<KeyViewType>::value ), int>::type
* = 0 )
{
return Impl::kokkosBinSort<KeyViewType, DeviceType>( keys, comp, false, 0,
keys.extent( 0 ) );
}
//---------------------------------------------------------------------------//
/*!
\brief Sort an AoSoA over a subset of its range based on the associated key
values.
\tparam KeyViewType The Kokkos::View type for keys.
\param keys The key values to use for sorting. A key value is needed for
every element of the AoSoA.
\param begin The beginning index of the AoSoA range to sort.
\param end The end index of the AoSoA range to sort.
\return The permutation vector associated with the sorting.
*/
template <class KeyViewType,
class DeviceType = typename KeyViewType::device_type>
BinningData<DeviceType>
sortByKey( KeyViewType keys, const std::size_t begin, const std::size_t end,
typename std::enable_if<( Kokkos::is_view<KeyViewType>::value ),
int>::type * = 0 )
{
int nbin = ( end - begin ) / 2;
return Impl::kokkosBinSort1d<KeyViewType, DeviceType>( keys, nbin, true,
begin, end );
}
//---------------------------------------------------------------------------//
/*!
\brief Sort an entire AoSoA based on the associated key values.
\tparam KeyViewType The Kokkos::View type for keys.
\param keys The key values to use for sorting. A key value is needed for
every element of the AoSoA.
\return The permutation vector associated with the sorting.
*/
template <class KeyViewType,
class DeviceType = typename KeyViewType::device_type>
BinningData<DeviceType>
sortByKey( KeyViewType keys,
typename std::enable_if<( Kokkos::is_view<KeyViewType>::value ),
int>::type * = 0 )
{
return sortByKey<KeyViewType, DeviceType>( keys, 0, keys.extent( 0 ) );
}
//---------------------------------------------------------------------------//
/*!
\brief Bin an AoSoA over a subset of its range based on the associated key
values and number of bins. The bins are evenly divided over the range of key
values.
\tparam KeyViewType The Kokkos::View type for keys.
\param keys The key values to use for binning. A key value is needed for
every element of the AoSoA.
\param nbin The number of bins to use for binning. The range of key values
will subdivided equally by the number of bins.
\param begin The beginning index of the AoSoA range to bin.
\param end The end index of the AoSoA range to bin.
\return The binning data (e.g. bin sizes and offsets).
*/
template <class KeyViewType,
class DeviceType = typename KeyViewType::device_type>
BinningData<DeviceType>
binByKey( KeyViewType keys, const int nbin, const std::size_t begin,
const std::size_t end,
typename std::enable_if<( Kokkos::is_view<KeyViewType>::value ),
int>::type * = 0 )
{
return Impl::kokkosBinSort1d<KeyViewType, DeviceType>( keys, nbin, false,
begin, end );
}
//---------------------------------------------------------------------------//
/*!
\brief Bin an entire AoSoA based on the associated key values and number of
bins. The bins are evenly divided over the range of key values.
\tparam KeyViewType The Kokkos::View type for keys.
\param keys The key values to use for binning. A key value is needed for
every element of the AoSoA.
\param nbin The number of bins to use for binning. The range of key values
will subdivided equally by the number of bins.
\return The binning data (e.g. bin sizes and offsets).
*/
template <class KeyViewType,
class DeviceType = typename KeyViewType::device_type>
BinningData<DeviceType>
binByKey( KeyViewType keys, const int nbin,
typename std::enable_if<( Kokkos::is_view<KeyViewType>::value ),
int>::type * = 0 )
{
return Impl::kokkosBinSort1d<KeyViewType, DeviceType>( keys, nbin, false, 0,
keys.extent( 0 ) );
}
//---------------------------------------------------------------------------//
/*!
\brief Sort an AoSoA over a subset of its range based on the associated
slice of keys.
\tparam SliceType Slice type for keys.
\param slice Slice of keys.
\param begin The beginning index of the AoSoA range to sort.
\param end The end index of the AoSoA range to sort.
\return The permutation vector associated with the sorting.
*/
template <class SliceType, class DeviceType = typename SliceType::device_type>
BinningData<DeviceType> sortByKey(
SliceType slice, const std::size_t begin, const std::size_t end,
typename std::enable_if<( is_slice<SliceType>::value ), int>::type * = 0 )
{
auto keys = Impl::copySliceToKeys<SliceType, DeviceType>( slice );
return sortByKey<decltype( keys ), DeviceType>( keys, begin, end );
}
//---------------------------------------------------------------------------//
/*!
\brief Sort an entire AoSoA based on the associated slice of keys.
\tparam SliceType Slice type for keys.
\param slice Slice of keys.
\return The permutation vector associated with the sorting.
*/
template <class SliceType, class DeviceType = typename SliceType::device_type>
BinningData<DeviceType> sortByKey(
SliceType slice,
typename std::enable_if<( is_slice<SliceType>::value ), int>::type * = 0 )
{
return sortByKey<SliceType, DeviceType>( slice, 0, slice.size() );
}
//---------------------------------------------------------------------------//
/*!
\brief Bin an AoSoA over a subset of its range based on the associated
slice of keys.
\tparam SliceType Slice type for keys
\param slice Slice of keys.
\param nbin The number of bins to use for binning. The range of key values
will subdivided equally by the number of bins.
\param begin The beginning index of the AoSoA range to bin.
\param end The end index of the AoSoA range to bin.
\return The binning data (e.g. bin sizes and offsets).
*/
template <class SliceType, class DeviceType = typename SliceType::device_type>
BinningData<DeviceType> binByKey(
SliceType slice, const int nbin, const std::size_t begin,
const std::size_t end,
typename std::enable_if<( is_slice<SliceType>::value ), int>::type * = 0 )
{
auto keys = Impl::copySliceToKeys<SliceType, DeviceType>( slice );
return binByKey<decltype( keys ), DeviceType>( keys, nbin, begin, end );
}
//---------------------------------------------------------------------------//
/*!
\brief Bin an entire AoSoA based on the associated slice of keys.
\tparam SliceType Slice type for keys.
\param slice Slice of keys.
\param nbin The number of bins to use for binning. The range of key values
will subdivided equally by the number of bins.
\return The binning data (e.g. bin sizes and offsets).
*/
template <class SliceType, class DeviceType = typename SliceType::device_type>
BinningData<DeviceType> binByKey(
SliceType slice, const int nbin,
typename std::enable_if<( is_slice<SliceType>::value ), int>::type * = 0 )
{
return binByKey<SliceType, DeviceType>( slice, nbin, 0, slice.size() );
}
//---------------------------------------------------------------------------//
/*!
\brief Given binning data permute an AoSoA.
\tparam BinningDataType The binning data type.
\tparam AoSoA_t The AoSoA type.
\param binning_data The binning data.
\param aosoa The AoSoA to permute.
*/
template <class BinningDataType, class AoSoA_t,
class DeviceType = typename BinningDataType::device_type>
void permute(
const BinningDataType &binning_data, AoSoA_t &aosoa,
typename std::enable_if<( is_binning_data<BinningDataType>::value &&
is_aosoa<AoSoA_t>::value ),
int>::type * = 0 )
{
auto begin = binning_data.rangeBegin();
auto end = binning_data.rangeEnd();
Kokkos::View<typename AoSoA_t::tuple_type *, DeviceType> scratch_tuples(
Kokkos::ViewAllocateWithoutInitializing( "scratch_tuples" ),
end - begin );
auto permute_to_scratch = KOKKOS_LAMBDA( const std::size_t i )
{
scratch_tuples( i - begin ) =
aosoa.getTuple( binning_data.permutation( i - begin ) );
};
Kokkos::parallel_for(
"Cabana::kokkosBinSort::permute_to_scratch",
Kokkos::RangePolicy<typename DeviceType::execution_space>( begin, end ),
permute_to_scratch );
Kokkos::fence();
auto copy_back = KOKKOS_LAMBDA( const std::size_t i )
{
aosoa.setTuple( i, scratch_tuples( i - begin ) );
};
Kokkos::parallel_for(
"Cabana::kokkosBinSort::copy_back",
Kokkos::RangePolicy<typename DeviceType::execution_space>( begin, end ),
copy_back );
Kokkos::fence();
}
//---------------------------------------------------------------------------//
/*!
\brief Given binning data permute a slice.
\tparam BinningDataType The binning data type.
\tparam SliceType The slice type.
\param binning_data The binning data.
\param slice The slice to permute.
*/
template <class BinningDataType, class SliceType,
class DeviceType = typename BinningDataType::device_type>
void permute(
const BinningDataType &binning_data, SliceType &slice,
typename std::enable_if<( is_binning_data<BinningDataType>::value &&
is_slice<SliceType>::value ),
int>::type * = 0 )
{
auto begin = binning_data.rangeBegin();
auto end = binning_data.rangeEnd();
// Get the number of components in the slice.
std::size_t num_comp = 1;
for ( std::size_t d = 2; d < slice.rank(); ++d )
num_comp *= slice.extent( d );
// Get the raw slice data.
auto slice_data = slice.data();
Kokkos::View<typename SliceType::value_type **, DeviceType> scratch_array(
Kokkos::ViewAllocateWithoutInitializing( "scratch_array" ), end - begin,
num_comp );
auto permute_to_scratch = KOKKOS_LAMBDA( const std::size_t i )
{
auto permute_i = binning_data.permutation( i - begin );
auto s = SliceType::index_type::s( permute_i );
auto a = SliceType::index_type::a( permute_i );
std::size_t slice_offset = s * slice.stride( 0 ) + a;
for ( std::size_t n = 0; n < num_comp; ++n )
scratch_array( i - begin, n ) =
slice_data[slice_offset + SliceType::vector_length * n];
};
Kokkos::parallel_for(
"Cabana::kokkosBinSort::permute_to_scratch",
Kokkos::RangePolicy<typename DeviceType::execution_space>( begin, end ),
permute_to_scratch );
Kokkos::fence();
auto copy_back = KOKKOS_LAMBDA( const std::size_t i )
{
auto s = SliceType::index_type::s( i );
auto a = SliceType::index_type::a( i );
std::size_t slice_offset = s * slice.stride( 0 ) + a;
for ( std::size_t n = 0; n < num_comp; ++n )
slice_data[slice_offset + SliceType::vector_length * n] =
scratch_array( i - begin, n );
};
Kokkos::parallel_for(
"Cabana::kokkosBinSort::copy_back",
Kokkos::RangePolicy<typename DeviceType::execution_space>( begin, end ),
copy_back );
Kokkos::fence();
}
//---------------------------------------------------------------------------//
} // end namespace Cabana
#endif // end CABANA_SORT_HPP
| 35.043741 | 80 | 0.608806 | [
"vector"
] |
704e8a425b9cc4e791d60d40b612c27ac3c201d2 | 7,138 | hh | C++ | CRVResponse/standalone/wls/include/G4CerenkovNew.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 1 | 2021-06-25T00:00:12.000Z | 2021-06-25T00:00:12.000Z | CRVResponse/standalone/wls/include/G4CerenkovNew.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 1 | 2019-11-22T14:45:51.000Z | 2019-11-22T14:50:03.000Z | CRVResponse/standalone/wls/include/G4CerenkovNew.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 3 | 2021-05-24T20:17:02.000Z | 2021-06-08T09:29:18.000Z | /*
Cerenkov process which doesn't assume that the the index of refraction increases with increasing energy.
In this more general case, the integrals, and cut-offs need to be treated differently.
*/
#ifndef G4Cerenkov_h
#define G4Cerenkov_h 1
/////////////
// Includes
/////////////
#include <CLHEP/Units/SystemOfUnits.h>
#include "globals.hh"
#include "templates.hh"
#include "Randomize.hh"
#include "G4ThreeVector.hh"
#include "G4ParticleMomentum.hh"
#include "G4Step.hh"
#include "G4VProcess.hh"
#include "G4OpticalPhoton.hh"
#include "G4DynamicParticle.hh"
#include "G4Material.hh"
#include "G4PhysicsTable.hh"
#include "G4MaterialPropertyVector.hh"
#include "G4MaterialPropertiesTable.hh"
#include "G4PhysicsOrderedFreeVector.hh"
#include <map>
// Class Description:
// Discrete Process -- Generation of Cerenkov Photons.
// Class inherits publicly from G4VDiscreteProcess.
// Class Description - End:
/////////////////////
// Class Definition
/////////////////////
class G4CerenkovNew : public G4VProcess
{
public:
////////////////////////////////
// Constructors and Destructor
////////////////////////////////
G4CerenkovNew(const G4String& processName = "CerenkovNew",
G4ProcessType type = fElectromagnetic);
~G4CerenkovNew();
G4CerenkovNew(const G4CerenkovNew &right);
private:
//////////////
// Operators
//////////////
G4CerenkovNew& operator=(const G4CerenkovNew &right);
public:
////////////
// Methods
////////////
static G4CerenkovNew* Instance() {return _fgInstance;}
G4bool IsApplicable(const G4ParticleDefinition& aParticleType);
// Returns true -> 'is applicable', for all charged particles
// except short-lived particles.
void BuildPhysicsTable(const G4ParticleDefinition& aParticleType);
// Build table at a right time
G4double GetMeanFreePath(const G4Track& aTrack,
G4double ,
G4ForceCondition* );
// Returns the discrete step limit and sets the 'StronglyForced'
// condition for the DoIt to be invoked at every step.
G4double PostStepGetPhysicalInteractionLength(const G4Track& aTrack,
G4double ,
G4ForceCondition* );
// Returns the discrete step limit and sets the 'StronglyForced'
// condition for the DoIt to be invoked at every step.
G4VParticleChange* PostStepDoIt(const G4Track& aTrack,
const G4Step& aStep);
// This is the method implementing the Cerenkov process.
// no operation in AtRestDoIt and AlongStepDoIt
virtual G4double AlongStepGetPhysicalInteractionLength(
const G4Track&,
G4double ,
G4double ,
G4double& ,
G4GPILSelection*
) { return -1.0; };
virtual G4double AtRestGetPhysicalInteractionLength(
const G4Track& ,
G4ForceCondition*
) { return -1.0; };
// no operation in AtRestDoIt and AlongStepDoIt
virtual G4VParticleChange* AtRestDoIt(
const G4Track& ,
const G4Step&
) {return 0;};
virtual G4VParticleChange* AlongStepDoIt(
const G4Track& ,
const G4Step&
) {return 0;};
void SetTrackSecondariesFirst(const G4bool state);
// If set, the primary particle tracking is interrupted and any
// produced Cerenkov photons are tracked next. When all have
// been tracked, the tracking of the primary resumes.
G4bool GetTrackSecondariesFirst() const;
// Returns the boolean flag for tracking secondaries first.
void SetMaxBetaChangePerStep(const G4double d);
// Set the maximum allowed change in beta = v/c in % (perCent)
// per step.
G4double GetMaxBetaChangePerStep() const;
// Returns the maximum allowed change in beta = v/c in % (perCent)
void SetMaxNumPhotonsPerStep(const G4int NumPhotons);
// Set the maximum number of Cerenkov photons allowed to be
// generated during a tracking step. This is an average ONLY;
// the actual number will vary around this average. If invoked,
// the maximum photon stack will roughly be of the size set.
// If not called, the step is not limited by the number of
// photons generated.
G4int GetMaxNumPhotonsPerStep() const;
// Returns the maximum number of Cerenkov photons allowed to be
// generated during a tracking step.
G4PhysicsTable* GetPhysicsTable() const;
// Returns the address of the physics table.
void DumpPhysicsTable() const;
// Prints the physics table.
G4double GetAverageNumberOfPhotons(const G4double charge,
const G4double beta,
const G4Material *aMaterial,
G4MaterialPropertyVector* Rindex) const;
private:
void BuildThePhysicsTable();
/////////////////////
// Helper Functions
/////////////////////
void GetMinMaxRindex(G4MaterialPropertyVector* Rindex, double &RImin, double &RImax) const;
void GetEnergyIntervals(G4MaterialPropertyVector* Rindex, double BetaInverse,
std::vector<std::pair<double,double> > &energyIntervals) const;
///////////////////////
// Class Data Members
///////////////////////
protected:
G4PhysicsTable* thePhysicsTable;
// A Physics Table can be either a cross-sections table or
// an energy table (or can be used for other specific
// purposes).
std::map<int,double> minRindex;
std::map<int,double> maxRindex;
private:
static G4CerenkovNew* _fgInstance;
G4bool fTrackSecondariesFirst;
G4double fMaxBetaChange;
G4int fMaxPhotons;
};
////////////////////
// Inline methods
////////////////////
inline
G4bool G4CerenkovNew::GetTrackSecondariesFirst() const
{
return fTrackSecondariesFirst;
}
inline
G4double G4CerenkovNew::GetMaxBetaChangePerStep() const
{
return fMaxBetaChange;
}
inline
G4int G4CerenkovNew::GetMaxNumPhotonsPerStep() const
{
return fMaxPhotons;
}
inline
void G4CerenkovNew::DumpPhysicsTable() const
{
G4int PhysicsTableSize = thePhysicsTable->entries();
G4PhysicsOrderedFreeVector *v;
for (G4int i = 0 ; i < PhysicsTableSize ; i++ )
{
v = (G4PhysicsOrderedFreeVector*)(*thePhysicsTable)[i];
v->DumpValues();
}
}
inline
G4PhysicsTable* G4CerenkovNew::GetPhysicsTable() const
{
return thePhysicsTable;
}
#endif /* G4CerenkovNew_h */
| 30.245763 | 104 | 0.592463 | [
"vector"
] |
7051f8e5d5b2a8523ff9afe19035bf051084faab | 9,485 | cc | C++ | src/DIF/RIB/RIBdListeners.cc | Miguel-A/RinaSim | 70ff28dc05e8250ca28c438290cf8c08f8a94a23 | [
"MIT"
] | 1 | 2016-02-24T19:31:04.000Z | 2016-02-24T19:31:04.000Z | src/DIF/RIB/RIBdListeners.cc | Miguel-A/RinaSim | 70ff28dc05e8250ca28c438290cf8c08f8a94a23 | [
"MIT"
] | null | null | null | src/DIF/RIB/RIBdListeners.cc | Miguel-A/RinaSim | 70ff28dc05e8250ca28c438290cf8c08f8a94a23 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2014-2016 Brno University of Technology, PRISTINE project
//
// 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 "RIBdListeners.h"
#include "IntRoutingUpdate.h"
RIBdListeners::RIBdListeners(RIBdBase* nribd) : ribd(nribd)
{
}
RIBdListeners::~RIBdListeners() {
ribd = NULL;
}
void LisRIBDRcvData::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "ReceiveData initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
CDAPMessage* cimsg = dynamic_cast<CDAPMessage*>(obj);
if (cimsg) {
ribd->receiveData(cimsg);
}
else
EV << "RIBdListener received unknown object!" << endl;
}
/*
void LisRIBDCreReq::receiveSignal(cComponent* src, simsignal_t id, cObject* obj) {
EV << "CreateRequest initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
Flow* flow = dynamic_cast<Flow*>(obj);
if (flow)
ribd->sendCreateRequestFlow(flow);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDAllReqFromFai::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "AllocationRequest{fromFAI} initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
Flow* flow = dynamic_cast<Flow*>(obj);
if (flow) {
//Check whether dstApp is local...
const APN dstApn = flow->getSrcApni().getApn();
if (ribd->getMyAddress().getApn() == dstApn) {
EV << "DST>" << dstApn << " MyAddr> " << ribd->getMyAddress().getApn() << endl;;
ribd->receiveAllocationRequestFromFai(flow);
}
}
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDCreResNega::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "CreateResponseFlowNegative initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
Flow* flow = dynamic_cast<Flow*>(obj);
if (flow)
ribd->sendCreateResponseNegative(flow);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDCreResPosi::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "CreateResponseFlowPositive initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
Flow* flow = dynamic_cast<Flow*>(obj);
if (flow)
ribd->sendCreateResponsePostive(flow);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDDelReq::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "DeleteRequest initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
Flow* flow = dynamic_cast<Flow*>(obj);
if (flow)
ribd->sendDeleteRequestFlow(flow);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDDelRes::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "DeleteResponse initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
Flow* flow = dynamic_cast<Flow*>(obj);
if (flow)
ribd->sendDeleteResponseFlow(flow);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDCreFloNega::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "CreateFlowNegative initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
Flow* flow = dynamic_cast<Flow*>(obj);
if (flow)
ribd->receiveCreateFlowNegativeFromRa(flow);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDCreFloPosi::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "CreateFlowPositive initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
Flow* flow = dynamic_cast<Flow*>(obj);
if (flow)
ribd->receiveCreateFlowPositiveFromRa(flow);
else
EV << "RIBdListener received unknown object!" << endl;
}
*/
void LisRIBDRoutingUpdate::receiveSignal(cComponent* src, simsignal_t id, cObject* obj)
{
EV << "LisRIBDRoutingUpdate initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
IntRoutingUpdate * info = dynamic_cast<IntRoutingUpdate *>(obj);
if (info)
{
ribd->receiveRoutingUpdateFromRouting(info);
}
else
{
EV << "ForwardingInfoUpdate listener received unknown object!" << endl;
}
}
void LisRIBDCongesNotif::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "LisRIBDCongesNotif initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
PDU* pdu = dynamic_cast<PDU*>(obj);
if (pdu)
ribd->sendCongestionNotification(pdu);
else
EV << "RIBdListener received unknown object!" << endl;
}
/*
void LisRIBDRcvCACE::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "ReceiveCACEData initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
CDAPMessage* cimsg = dynamic_cast<CDAPMessage*>(obj);
if (cimsg) {
ribd->receiveCACE(cimsg);
}
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDRcvEnrollCACE::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "Send CACE from Enrollment" << endl;
CDAPMessage* cimsg = dynamic_cast<CDAPMessage*>(obj);
if (cimsg) {
ribd->sendCACE(cimsg);
}
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDStaEnrolReq::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "StartEnrollmentRequest initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
EnrollmentObj* enroll = dynamic_cast<EnrollmentObj*>(obj);
if (enroll)
ribd->sendStartEnrollmentRequest(enroll);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDStaEnrolRes::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "StartEnrollmentResponse initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
EnrollmentObj* enroll = dynamic_cast<EnrollmentObj*>(obj);
if (enroll)
ribd->sendStartEnrollmentResponse(enroll);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDStoEnrolReq::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "StopEnrollmentRequest initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
EnrollmentObj* enroll = dynamic_cast<EnrollmentObj*>(obj);
if (enroll)
ribd->sendStopEnrollmentRequest(enroll);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDStoEnrolRes::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "StopEnrollmentResponse initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
EnrollmentObj* enroll = dynamic_cast<EnrollmentObj*>(obj);
if (enroll)
ribd->sendStopEnrollmentResponse(enroll);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDStaOperReq::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "StartOperationRequest initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
OperationObj* oper = dynamic_cast<OperationObj*>(obj);
if (oper)
ribd->sendStartOperationRequest(oper);
else
EV << "RIBdListener received unknown object!" << endl;
}
void LisRIBDStaOperRes::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj) {
EV << "StartOperationResponse initiated by " << src->getFullPath()
<< " and processed by " << ribd->getFullPath() << endl;
OperationObj* oper = dynamic_cast<OperationObj*>(obj);
if (oper)
ribd->sendStartOperationResponse(oper);
else
EV << "RIBdListener received unknown object!" << endl;
}
*/
| 35.524345 | 95 | 0.653769 | [
"object"
] |
7052c8484e6510ef88305d033e2d075320466765 | 2,363 | cpp | C++ | test/RangeQuery_test.cpp | Suraj-Yadav/PhysicsEngine2D | 557c47d6319e26f928dae6ae95ee5a0d7b7c82ae | [
"MIT"
] | 1 | 2019-05-01T02:05:47.000Z | 2019-05-01T02:05:47.000Z | test/RangeQuery_test.cpp | Suraj-Yadav/PhysicsEngine2D | 557c47d6319e26f928dae6ae95ee5a0d7b7c82ae | [
"MIT"
] | null | null | null | test/RangeQuery_test.cpp | Suraj-Yadav/PhysicsEngine2D | 557c47d6319e26f928dae6ae95ee5a0d7b7c82ae | [
"MIT"
] | null | null | null | #include <doctest.h>
#include <PhysicsEngine2D/KdTree.hpp>
#include <PhysicsEngine2D/RangeTree2D.hpp>
#include "TestUtil.hpp"
TYPE_TO_STRING(KdTree<int>);
TYPE_TO_STRING(RangeTree2D<int>);
TEST_CASE_TEMPLATE(
"Test RangeTree Range Query", Tree, KdTree<int>, RangeTree2D<int>) {
SUBCASE("Empty Input") {
std::vector<Vector2D> points(0);
std::vector<int> values(0);
Tree tree(points, values);
Range2D<dataType> range2D(-30, 30, -20, 20);
auto insidePointsGot = tree.rangeQuery(range2D);
std::sort(insidePointsGot.begin(), insidePointsGot.end());
CAPTURE(points);
CAPTURE(values);
CAPTURE(range2D);
CAPTURE(insidePointsGot);
REQUIRE_EQ(insidePointsGot.size(), 0);
}
SUBCASE("Fixed Input") {
std::vector<Vector2D> points = {
{0, 0}, {-20, -20}, {-20, 20}, {20, 20}, {20, -20}};
std::vector<int> values = {0, 1, 2, 3, 4};
Tree tree(points, values);
Range2D<dataType> range2D(-30, 10, -30, 10);
auto insidePointsGot = tree.rangeQuery(range2D);
std::sort(insidePointsGot.begin(), insidePointsGot.end());
CAPTURE(points);
CAPTURE(values);
CAPTURE(range2D);
CAPTURE(insidePointsGot.size());
CAPTURE(insidePointsGot);
REQUIRE_EQ(insidePointsGot.size(), 2);
REQUIRE_EQ(insidePointsGot[0], 0);
REQUIRE_EQ(insidePointsGot[1], 1);
}
SUBCASE("Random Inputs") {
const size_t length = 1000;
for (size_t i = 0; i < length; i++) {
auto points = getRandomPoints({-400, 400, -400, 400}, length);
auto values = getShuffledArrayOf1ToN(length);
Tree tree(points, values);
for (size_t i = 0; i < length; i++) {
auto range2D = getRandom2DRange(
{-400, 400, -400, 400}, {10, 400, 10, 400});
auto insidePointsGot = tree.rangeQuery(range2D);
std::vector<int> insidePointsActual;
for (size_t j = 0; j < length; j++) {
if (range2D.contains(points[j])) {
insidePointsActual.emplace_back(values[j]);
}
}
std::sort(insidePointsGot.begin(), insidePointsGot.end());
std::sort(insidePointsActual.begin(), insidePointsActual.end());
CAPTURE(points);
CAPTURE(values);
CAPTURE(range2D);
CAPTURE(insidePointsGot);
CAPTURE(insidePointsActual);
REQUIRE_EQ(insidePointsActual.size(), insidePointsGot.size());
for (size_t i = 0; i < insidePointsActual.size(); i++) {
REQUIRE_EQ(insidePointsActual[i], insidePointsGot[i]);
}
}
}
}
} | 29.911392 | 69 | 0.671181 | [
"vector"
] |
7054b404e4dfb30cffd46b1b82c22b5d427500b4 | 16,643 | cxx | C++ | Filters/AMR/Testing/Cxx/TestAMRGhostLayerStripping.cxx | txwhhny/vtk | 854d9aa87b944bc9079510515996406b98b86f7c | [
"BSD-3-Clause"
] | 1,755 | 2015-01-03T06:55:00.000Z | 2022-03-29T05:23:26.000Z | Filters/AMR/Testing/Cxx/TestAMRGhostLayerStripping.cxx | txwhhny/vtk | 854d9aa87b944bc9079510515996406b98b86f7c | [
"BSD-3-Clause"
] | 29 | 2015-04-23T20:58:30.000Z | 2022-03-02T16:16:42.000Z | Filters/AMR/Testing/Cxx/TestAMRGhostLayerStripping.cxx | txwhhny/vtk | 854d9aa87b944bc9079510515996406b98b86f7c | [
"BSD-3-Clause"
] | 1,044 | 2015-01-05T22:48:27.000Z | 2022-03-31T02:38:26.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: TestAMRGhostLayerStripping.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME TestAMRGhostLayerStripping.cxx -- Test for stripping ghost layers
//
// .SECTION Description
// A simple test for testing the functionality of stripping out ghost layers
// that partially cover lower resolution cells. The test constructs an AMR
// configuration using the vtkAMRGaussianPulseSource which has a known structure.
// Ghost layers are manually added to the hi-res grids and then stripped out.
// Tests cover also configurations with different refinement ratios and
// different numbers of ghost-layers.
// C/C++ includes
#include <cassert>
#include <cmath>
#include <iostream>
#include <sstream>
#include <vector>
// VTK includes
#include "vtkAMRGaussianPulseSource.h"
#include "vtkAMRInformation.h"
#include "vtkAMRUtilities.h"
#include "vtkCell.h"
#include "vtkCellData.h"
#include "vtkDoubleArray.h"
#include "vtkMathUtilities.h"
#include "vtkOverlappingAMR.h"
#include "vtkUniformGrid.h"
//#define DEBUG_ON
//------------------------------------------------------------------------------
// Debugging utilities. Must link vtkIOXML to work
#ifdef DEBUG_ON
#include "vtkXMLImageDataWriter.h"
void WriteUniformGrid(vtkUniformGrid* g, const std::string& prefix)
{
assert("pre: Uniform grid (g) is nullptr!" && (g != nullptr));
vtkXMLImageDataWriter* imgWriter = vtkXMLImageDataWriter::New();
std::ostringstream oss;
oss << prefix << "." << imgWriter->GetDefaultFileExtension();
imgWriter->SetFileName(oss.str().c_str());
imgWriter->SetInputData(g);
imgWriter->Write();
imgWriter->Delete();
}
//------------------------------------------------------------------------------
void WriteUnGhostedGrids(const int dimension, vtkOverlappingAMR* amr)
{
assert("pre: AMR dataset is nullptr!" && (amr != nullptr));
std::ostringstream oss;
oss.clear();
unsigned int levelIdx = 0;
for (; levelIdx < amr->GetNumberOfLevels(); ++levelIdx)
{
unsigned dataIdx = 0;
for (; dataIdx < amr->GetNumberOfDataSets(levelIdx); ++dataIdx)
{
vtkUniformGrid* grid = amr->GetDataSet(levelIdx, dataIdx);
if (grid != nullptr)
{
oss.str("");
oss << dimension << "D_UNGHOSTED_GRID_" << levelIdx << "_" << dataIdx;
WriteUniformGrid(grid, oss.str());
}
} // END for all data-sets
} // END for all levels
}
#endif
//------------------------------------------------------------------------------
double ComputePulse(const int dimension, double location[3], double pulseOrigin[3],
double pulseWidth[3], double pulseAmplitude)
{
double pulse = 0.0;
double r = 0.0;
for (int i = 0; i < dimension; ++i)
{
double d = location[i] - pulseOrigin[i];
double d2 = d * d;
double L2 = pulseWidth[i] * pulseWidth[i];
r += d2 / L2;
} // END for all dimensions
pulse = pulseAmplitude * std::exp(-r);
return (pulse);
}
//------------------------------------------------------------------------------
void ComputeCellCenter(vtkUniformGrid* grid, vtkIdType cellIdx, double centroid[3])
{
assert("pre: input grid instance is nullptr" && (grid != nullptr));
assert(
"pre: cell index is out-of-bounds!" && (cellIdx >= 0) && (cellIdx < grid->GetNumberOfCells()));
// We want to get all cells including blanked cells.
vtkCell* myCell = grid->vtkImageData::GetCell(cellIdx);
double pcenter[3];
std::vector<double> weights(myCell->GetNumberOfPoints());
int subId = myCell->GetParametricCenter(pcenter);
myCell->EvaluateLocation(subId, pcenter, centroid, weights.data());
}
//------------------------------------------------------------------------------
void GeneratePulseField(const int dimension, vtkUniformGrid* grid)
{
assert("pre: grid is nullptr!" && (grid != nullptr));
assert("pre: grid is empty!" && (grid->GetNumberOfCells() >= 1));
double pulseOrigin[3];
double pulseWidth[3];
double pulseAmplitude;
vtkAMRGaussianPulseSource* pulseSource = vtkAMRGaussianPulseSource::New();
pulseSource->GetPulseOrigin(pulseOrigin);
pulseSource->GetPulseWidth(pulseWidth);
pulseAmplitude = pulseSource->GetPulseAmplitude();
pulseSource->Delete();
vtkDoubleArray* centroidArray = vtkDoubleArray::New();
centroidArray->SetName("Centroid");
centroidArray->SetNumberOfComponents(3);
centroidArray->SetNumberOfTuples(grid->GetNumberOfCells());
vtkDoubleArray* pulseField = vtkDoubleArray::New();
pulseField->SetName("Gaussian-Pulse");
pulseField->SetNumberOfComponents(1);
pulseField->SetNumberOfTuples(grid->GetNumberOfCells());
double centroid[3];
vtkIdType cellIdx = 0;
for (; cellIdx < grid->GetNumberOfCells(); ++cellIdx)
{
ComputeCellCenter(grid, cellIdx, centroid);
centroidArray->SetComponent(cellIdx, 0, centroid[0]);
centroidArray->SetComponent(cellIdx, 1, centroid[1]);
centroidArray->SetComponent(cellIdx, 2, centroid[2]);
double pulse = ComputePulse(dimension, centroid, pulseOrigin, pulseWidth, pulseAmplitude);
pulseField->SetComponent(cellIdx, 0, pulse);
} // END for all cells
grid->GetCellData()->AddArray(centroidArray);
centroidArray->Delete();
grid->GetCellData()->AddArray(pulseField);
pulseField->Delete();
}
//------------------------------------------------------------------------------
vtkUniformGrid* GetGhostedGrid(
const int dimension, vtkUniformGrid* refGrid, int ghost[6], const int NG)
{
assert("pre: NG >= 1" && (NG >= 1));
// STEP 0: If the reference grid is nullptr just return
if (refGrid == nullptr)
{
return nullptr;
}
// STEP 1: Acquire reference grid origin,spacing, dims
int dims[3];
double origin[3];
double spacing[3];
refGrid->GetOrigin(origin);
refGrid->GetSpacing(spacing);
refGrid->GetDimensions(dims);
// STEP 2: Adjust origin and dimensions for ghost cells along each dimension
for (int i = 0; i < 3; ++i)
{
if (ghost[i * 2] == 1)
{
// Grow along min of dimension i
dims[i] += NG;
origin[i] -= NG * spacing[i];
}
if (ghost[i * 2 + 1] == 1)
{
// Grow along max of dimension i
dims[i] += NG;
}
} // END for all dimensions
// STEP 3: Construct ghosted grid
vtkUniformGrid* grid = vtkUniformGrid::New();
grid->Initialize();
grid->SetOrigin(origin);
grid->SetSpacing(spacing);
grid->SetDimensions(dims);
// STEP 4: Construct field data, i.e., Centroid and Gaussian-Pulse. The
// data is recomputed here, since we know how to compute it.
GeneratePulseField(dimension, grid);
return (grid);
}
//------------------------------------------------------------------------------
vtkOverlappingAMR* GetGhostedDataSet(const int dimension, const int NG, vtkOverlappingAMR* inputAMR)
{
vtkOverlappingAMR* ghostedAMR = vtkOverlappingAMR::New();
std::vector<int> blocksPerLevel(2);
blocksPerLevel[0] = 1;
blocksPerLevel[1] = 2;
ghostedAMR->Initialize(static_cast<int>(blocksPerLevel.size()), &blocksPerLevel[0]);
ghostedAMR->SetGridDescription(inputAMR->GetGridDescription());
ghostedAMR->SetOrigin(inputAMR->GetOrigin());
for (unsigned int i = 0; i < inputAMR->GetNumberOfLevels(); i++)
{
double spacing[3];
inputAMR->GetSpacing(i, spacing);
ghostedAMR->SetSpacing(i, spacing);
}
assert("pre: Expected number of levels is 2" && (ghostedAMR->GetNumberOfLevels() == 2));
// Copy the root grid
vtkUniformGrid* rootGrid = vtkUniformGrid::New();
rootGrid->DeepCopy(inputAMR->GetDataSet(0, 0));
vtkAMRBox box(rootGrid->GetOrigin(), rootGrid->GetDimensions(), rootGrid->GetSpacing(),
ghostedAMR->GetOrigin(), rootGrid->GetGridDescription());
ghostedAMR->SetAMRBox(0, 0, box);
ghostedAMR->SetDataSet(0, 0, rootGrid);
rootGrid->Delete();
// Knowing the AMR configuration returned by vtkAMRGaussingPulseSource
// we manually pad ghost-layers to the grids at level 1 (hi-res). How
// ghost layers are created is encoded to a ghost vector for each grid,
// {imin,imax,jmin,jmax,kmin,kmax}, where a value of "1" indicates that ghost
// cells are created in that direction or a "0" to indicate that ghost cells
// are not created in the given direction.
int ghost[2][6] = {
{ 0, 1, 0, 1, 0, 0 }, // ghost vector for grid (1,0) -- grow at imax,jmax
{ 1, 0, 1, 0, 0, 0 } // ghost vector for grid (1,1) -- grow at imin,jmin
};
for (int i = 0; i < 2; ++i)
{
vtkUniformGrid* grid = inputAMR->GetDataSet(1, i);
vtkUniformGrid* ghostedGrid = GetGhostedGrid(dimension, grid, ghost[i], NG);
box = vtkAMRBox(ghostedGrid->GetOrigin(), ghostedGrid->GetDimensions(),
ghostedGrid->GetSpacing(), ghostedAMR->GetOrigin(), ghostedGrid->GetGridDescription());
ghostedAMR->SetAMRBox(1, i, box);
ghostedAMR->SetDataSet(1, i, ghostedGrid);
#ifdef DEBUG_ON
std::ostringstream oss;
oss.clear();
oss.str("");
oss << dimension << "D_GHOSTED_GRID_1_" << i;
WriteUniformGrid(ghostedGrid, oss.str());
#endif
ghostedGrid->Delete();
} // END for all grids
return (ghostedAMR);
}
//------------------------------------------------------------------------------
vtkOverlappingAMR* GetAMRDataSet(const int dimension, const int refinementRatio)
{
vtkAMRGaussianPulseSource* amrGPSource = vtkAMRGaussianPulseSource::New();
amrGPSource->SetDimension(dimension);
amrGPSource->SetRefinementRatio(refinementRatio);
amrGPSource->Update();
vtkOverlappingAMR* myAMR = vtkOverlappingAMR::New();
myAMR->ShallowCopy(amrGPSource->GetOutput());
amrGPSource->Delete();
return (myAMR);
}
//------------------------------------------------------------------------------
bool CheckFields(vtkUniformGrid* grid)
{
// Since we know exactly what the fields are, i.e., gaussian-pulse and
// centroid, we manually check the grid for correctness.
assert("pre: grid is nullptr" && (grid != nullptr));
vtkCellData* CD = grid->GetCellData();
if (!CD->HasArray("Centroid") || !CD->HasArray("Gaussian-Pulse"))
{
return false;
}
vtkDoubleArray* centroidArray = vtkArrayDownCast<vtkDoubleArray>(CD->GetArray("Centroid"));
assert("pre: centroid arrays is nullptr!" && (centroidArray != nullptr));
if (centroidArray->GetNumberOfComponents() != 3)
{
return false;
}
double* centers = static_cast<double*>(centroidArray->GetVoidPointer(0));
vtkDoubleArray* pulseArray = vtkArrayDownCast<vtkDoubleArray>(CD->GetArray("Gaussian-Pulse"));
assert("pre: pulse array is nullptr!" && (pulseArray != nullptr));
if (pulseArray->GetNumberOfComponents() != 1)
{
return false;
}
double* pulses = static_cast<double*>(pulseArray->GetVoidPointer(0));
// Get default pulse parameters
double pulseOrigin[3];
double pulseWidth[3];
double pulseAmplitude;
vtkAMRGaussianPulseSource* pulseSource = vtkAMRGaussianPulseSource::New();
pulseSource->GetPulseOrigin(pulseOrigin);
pulseSource->GetPulseWidth(pulseWidth);
pulseAmplitude = pulseSource->GetPulseAmplitude();
pulseSource->Delete();
double centroid[3];
int dim = grid->GetDataDimension();
vtkIdType cellIdx = 0;
for (; cellIdx < grid->GetNumberOfCells(); ++cellIdx)
{
ComputeCellCenter(grid, cellIdx, centroid);
double val = ComputePulse(dim, centroid, pulseOrigin, pulseWidth, pulseAmplitude);
if (!vtkMathUtilities::FuzzyCompare(val, pulses[cellIdx], 1e-9))
{
std::cerr << "ERROR: pulse data mismatch!\n";
std::cerr << "expected=" << val << " computed=" << pulses[cellIdx];
std::cerr << std::endl;
return false;
}
if (!vtkMathUtilities::FuzzyCompare(centroid[0], centers[cellIdx * 3]) ||
!vtkMathUtilities::FuzzyCompare(centroid[1], centers[cellIdx * 3 + 1]) ||
!vtkMathUtilities::FuzzyCompare(centroid[2], centers[cellIdx * 3 + 2]))
{
std::cerr << "ERROR: centroid data mismatch!\n";
return false;
}
} // END for all cells
return true;
}
//------------------------------------------------------------------------------
bool AMRDataSetsAreEqual(vtkOverlappingAMR* computed, vtkOverlappingAMR* expected)
{
assert("pre: computed AMR dataset is nullptr" && (computed != nullptr));
assert("pre: expected AMR dataset is nullptr" && (expected != nullptr));
if (computed == expected)
{
return true;
}
if (computed->GetNumberOfLevels() != expected->GetNumberOfLevels())
{
return false;
}
if (!(*computed->GetAMRInfo() == *expected->GetAMRInfo()))
{
std::cerr << "ERROR: AMR data mismatch!\n";
return false;
}
unsigned int levelIdx = 0;
for (; levelIdx < computed->GetNumberOfLevels(); ++levelIdx)
{
if (computed->GetNumberOfDataSets(levelIdx) != expected->GetNumberOfDataSets(levelIdx))
{
return false;
}
unsigned int dataIdx = 0;
for (; dataIdx < computed->GetNumberOfDataSets(levelIdx); ++dataIdx)
{
vtkUniformGrid* computedGrid = computed->GetDataSet(levelIdx, dataIdx);
vtkUniformGrid* expectedGrid = expected->GetDataSet(levelIdx, dataIdx);
for (int i = 0; i < 3; ++i)
{
if (!vtkMathUtilities::FuzzyCompare(
computedGrid->GetOrigin()[i], expectedGrid->GetOrigin()[i]))
{
std::cerr << "ERROR: grid origin mismathc!\n";
return false;
}
} // END for all dimensions
if (!CheckFields(computedGrid))
{
std::cerr << "ERROR: grid fields were not as expected!\n";
return false;
}
} // END for all data
} // END for all levels
return true;
}
//------------------------------------------------------------------------------
int TestGhostStripping(const int dimension, const int refinementRatio, const int NG)
{
int rc = 0;
std::cout << "====\n";
std::cout << "Checking AMR data dim=" << dimension << " r=" << refinementRatio << " NG=" << NG
<< std::endl;
std::cout.flush();
// Get the non-ghosted dataset
vtkOverlappingAMR* amrData = GetAMRDataSet(dimension, refinementRatio);
assert("pre: amrData should not be nullptr!" && (amrData != nullptr));
if (vtkAMRUtilities::HasPartiallyOverlappingGhostCells(amrData))
{
++rc;
std::cerr << "ERROR: erroneously detected partially overlapping "
<< "ghost cells on non-ghosted grid!\n";
}
// Get the ghosted dataset
vtkOverlappingAMR* ghostedAMRData = GetGhostedDataSet(dimension, NG, amrData);
assert("pre: ghosted AMR data is nullptr!" && (ghostedAMRData != nullptr));
if (NG == refinementRatio)
{
// There are no partially overlapping ghost cells
if (vtkAMRUtilities::HasPartiallyOverlappingGhostCells(ghostedAMRData))
{
++rc;
std::cerr << "ERROR: detected partially overlapping "
<< "ghost cells when there shouldn't be any!\n";
}
}
else
{
if (!vtkAMRUtilities::HasPartiallyOverlappingGhostCells(ghostedAMRData))
{
++rc;
std::cerr << "ERROR: failed detection of partially overlapping "
<< "ghost cells!\n";
}
}
vtkOverlappingAMR* strippedAMRData = vtkOverlappingAMR::New();
vtkAMRUtilities::StripGhostLayers(ghostedAMRData, strippedAMRData);
#ifdef DEBUG_ON
WriteUnGhostedGrids(dimension, strippedAMRData);
#endif
// The strippedAMRData is expected to be exactly the same as the initial
// unghosted AMR dataset
if (!AMRDataSetsAreEqual(strippedAMRData, amrData))
{
++rc;
std::cerr << "ERROR: AMR data did not match expected data!\n";
}
amrData->Delete();
ghostedAMRData->Delete();
strippedAMRData->Delete();
return (rc);
}
//------------------------------------------------------------------------------
int TestAMRGhostLayerStripping(int vtkNotUsed(argc), char* vtkNotUsed(argv)[])
{
int rc = 0;
int DIM0 = 2;
int NDIM = 3;
int NumberOfRefinmentRatios = 3;
int rRatios[3] = { 2, 3, 4 };
for (int dim = DIM0; dim <= NDIM; ++dim)
{
for (int r = 0; r < NumberOfRefinmentRatios; ++r)
{
for (int ng = 1; ng <= rRatios[r] - 1; ++ng)
{
rc += TestGhostStripping(dim, rRatios[r], ng);
} // END for all ghost-layer tests
} // END for all refinementRatios to test
} // END for all dimensions to test
return rc;
}
| 33.153386 | 100 | 0.634501 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.