hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ca34c6e25ddb861899315dc3f74f68c115c9a741 | 32,625 | cc | C++ | Alignment/CocoaUtilities/src/ALIUtils.cc | gputtley/cmssw | c1ef8454804e4ebea8b65f59c4a952a6c94fde3b | [
"Apache-2.0"
] | 2 | 2020-01-21T11:23:39.000Z | 2020-01-21T11:23:42.000Z | Alignment/CocoaUtilities/src/ALIUtils.cc | gputtley/cmssw | c1ef8454804e4ebea8b65f59c4a952a6c94fde3b | [
"Apache-2.0"
] | 26 | 2018-10-30T12:47:58.000Z | 2022-03-29T08:39:00.000Z | Alignment/CocoaUtilities/src/ALIUtils.cc | p2l1pfp/cmssw | 9bda22bf33ecf18dd19a3af2b3a8cbdb1de556a9 | [
"Apache-2.0"
] | 3 | 2019-03-09T13:06:43.000Z | 2020-07-03T00:47:30.000Z | // COCOA class implementation file
//Id: ALIUtils.cc
//CAT: ALIUtils
//
// History: v1.0
// Pedro Arce
#include "Alignment/CocoaUtilities/interface/ALIUtils.h"
#include "Alignment/CocoaUtilities/interface/GlobalOptionMgr.h"
#include <cmath>
#include <cstdlib>
#include <iomanip>
ALIint ALIUtils::debug = -1;
ALIint ALIUtils::report = 1;
ALIdouble ALIUtils::_LengthValueDimensionFactor = 1.;
ALIdouble ALIUtils::_LengthSigmaDimensionFactor = 1.;
ALIdouble ALIUtils::_AngleValueDimensionFactor = 1.;
ALIdouble ALIUtils::_AngleSigmaDimensionFactor = 1.;
ALIdouble ALIUtils::_OutputLengthValueDimensionFactor = 1.;
ALIdouble ALIUtils::_OutputLengthSigmaDimensionFactor = 1.;
ALIdouble ALIUtils::_OutputAngleValueDimensionFactor = 1.;
ALIdouble ALIUtils::_OutputAngleSigmaDimensionFactor = 1.;
time_t ALIUtils::_time_now;
ALIdouble ALIUtils::deg = 0.017453293;
ALIbool ALIUtils::firstTime = false;
ALIdouble ALIUtils::maximum_deviation_derivative = 1.E-6;
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ CHECKS THAT EVERY CHARACTER IN A STRING IS NUMBER, ELSE GIVES AN ERROR
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
int ALIUtils::IsNumber(const ALIstring& str) {
int isnum = 1;
int numE = 0;
for (ALIuint ii = 0; ii < str.length(); ii++) {
if (!isdigit(str[ii]) && str[ii] != '.' && str[ii] != '-' && str[ii] != '+') {
//--- check for E(xponential)
if (str[ii] == 'E' || str[ii] == 'e') {
if (numE != 0 || ii == str.length() - 1) {
isnum = 0;
break;
}
numE++;
} else {
isnum = 0;
break;
}
}
}
return isnum;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Dump a Hep3DVector with the chosen precision
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::dump3v(const CLHEP::Hep3Vector& vec, const std::string& msg) {
// double phicyl = atan( vec.y()/vec.x() );
std::cout << msg << std::setprecision(8) << vec;
std::cout << std::endl;
// std::cout << " " << vec.theta()/deg << " " << vec.phi()/deg << " " << vec.perp() << " " << phicyl/deg << std::endl;
// setw(10);
// std::cout << msg << " x=" << std::setprecision(8) << vec.x() << " y=" << setprecision(8) <<vec.y() << " z=" << std::setprecision(8) << vec.z() << std::endl;
// std::setprecision(8);
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::dumprm(const CLHEP::HepRotation& rm, const std::string& msg, std::ostream& out) {
out << msg << " xx=" << rm.xx() << " xy=" << rm.xy() << " xz=" << rm.xz() << std::endl;
out << msg << " yx=" << rm.yx() << " yy=" << rm.yy() << " yz=" << rm.yz() << std::endl;
out << msg << " zx=" << rm.zx() << " zy=" << rm.zy() << " zz=" << rm.zz() << std::endl;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Set the dimension factor to convert input length values and errors to
//@@ the dimension of errors
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::SetLengthDimensionFactors() {
//---------------------------------------- if it doesn exist, GlobalOptions is 0
//---------- Calculate factors to convert to meters
GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance();
ALIint ad = ALIint(gomgr->getGlobalOption("length_value_dimension"));
_LengthValueDimensionFactor = CalculateLengthDimensionFactorFromInt(ad);
ad = ALIint(gomgr->GlobalOptions()[ALIstring("length_error_dimension")]);
_LengthSigmaDimensionFactor = CalculateLengthDimensionFactorFromInt(ad);
//---------- Change factor to convert to error dimensions
// _LengthValueDimensionFactor /= _LengthSigmaDimensionFactor;
//_LengthSigmaDimensionFactor = 1;
if (ALIUtils::debug >= 6)
std::cout << _LengthValueDimensionFactor << " Set Length DimensionFactors " << _LengthSigmaDimensionFactor
<< std::endl;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Set the dimension factor to convert input angle values and errors to
//@@ the dimension of errors
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::SetAngleDimensionFactors() {
//--------------------- if it doesn exist, GlobalOptions is 0
//---------- Calculate factors to convert to radians
GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance();
ALIint ad = ALIint(gomgr->GlobalOptions()[ALIstring("angle_value_dimension")]);
_AngleValueDimensionFactor = CalculateAngleDimensionFactorFromInt(ad);
ad = ALIint(gomgr->GlobalOptions()[ALIstring("angle_error_dimension")]);
_AngleSigmaDimensionFactor = CalculateAngleDimensionFactorFromInt(ad);
//---------- Change factor to convert to error dimensions
// _AngleValueDimensionFactor /= _AngleSigmaDimensionFactor;
//_AngleSigmaDimensionFactor = 1;
if (ALIUtils::debug >= 6)
std::cout << _AngleValueDimensionFactor << "Set Angle DimensionFactors" << _AngleSigmaDimensionFactor << std::endl;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Set the dimension factor to convert input length values and errors to
//@@ the dimension of errors
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::SetOutputLengthDimensionFactors() {
//---------------------------------------- if it doesn exist, GlobalOptions is 0
//---------- Calculate factors to convert to meters
GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance();
ALIint ad = ALIint(gomgr->GlobalOptions()[ALIstring("output_length_value_dimension")]);
if (ad == 0)
ad = ALIint(gomgr->GlobalOptions()[ALIstring("length_value_dimension")]);
_OutputLengthValueDimensionFactor = CalculateLengthDimensionFactorFromInt(ad);
ad = ALIint(gomgr->GlobalOptions()[ALIstring("output_length_error_dimension")]);
if (ad == 0)
ad = ALIint(gomgr->GlobalOptions()[ALIstring("length_error_dimension")]);
_OutputLengthSigmaDimensionFactor = CalculateLengthDimensionFactorFromInt(ad);
//---------- Change factor to convert to error dimensions
// _LengthValueDimensionFactor /= _LengthSigmaDimensionFactor;
//_LengthSigmaDimensionFactor = 1;
if (ALIUtils::debug >= 6)
std::cout << _OutputLengthValueDimensionFactor << "Output Length Dimension Factors"
<< _OutputLengthSigmaDimensionFactor << std::endl;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Set the dimension factor to convert input angle values and errors to
//@@ the dimension of errors
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::SetOutputAngleDimensionFactors() {
//--------------------- if it doesn exist, GlobalOptions is 0
//---------- Calculate factors to convert to radians
GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance();
ALIint ad = ALIint(gomgr->GlobalOptions()[ALIstring("output_angle_value_dimension")]);
if (ad == 0)
ad = ALIint(gomgr->GlobalOptions()[ALIstring("angle_value_dimension")]);
_OutputAngleValueDimensionFactor = CalculateAngleDimensionFactorFromInt(ad);
ad = ALIint(gomgr->GlobalOptions()[ALIstring("output_angle_error_dimension")]);
if (ad == 0)
ad = ALIint(gomgr->GlobalOptions()[ALIstring("angle_error_dimension")]);
_OutputAngleSigmaDimensionFactor = CalculateAngleDimensionFactorFromInt(ad);
//---------- Change factor to convert to error dimensions
// _AngleValueDimensionFactor /= _AngleSigmaDimensionFactor;
//_AngleSigmaDimensionFactor = 1;
if (ALIUtils::debug >= 9)
std::cout << _OutputAngleValueDimensionFactor << "Output Angle Dimension Factors"
<< _OutputAngleSigmaDimensionFactor << std::endl;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Calculate dimension factor to convert any length values and errors to meters
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ALIdouble ALIUtils::CalculateLengthDimensionFactorFromString(ALIstring dimstr) {
ALIdouble valsig = 1.;
ALIstring internalDim = "m";
if (internalDim == "m") {
if (dimstr == "m") {
valsig = 1.;
} else if (dimstr == "mm") {
valsig = 1.E-3;
} else if (dimstr == "mum") {
valsig = 1.E-6;
} else if (dimstr == "cm") {
valsig = 1.E-2;
} else {
std::cerr << "!!! UNKNOWN DIMENSION SCALING " << dimstr << std::endl
<< "VALUE MUST BE BETWEEN 0 AND 3 " << std::endl;
exit(1);
}
} else if (internalDim == "mm") {
if (dimstr == "m") {
valsig = 1.E3;
} else if (dimstr == "mm") {
valsig = 1.;
} else if (dimstr == "mum") {
valsig = 1.E-3;
} else if (dimstr == "cm") {
valsig = 1.E+1;
} else {
std::cerr << "!!! UNKNOWN DIMENSION SCALING: " << dimstr << std::endl
<< "VALUE MUST BE A LENGTH DIMENSION " << std::endl;
exit(1);
}
}
return valsig;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Calculate dimension factor to convert any angle values and errors to radians
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ALIdouble ALIUtils::CalculateAngleDimensionFactorFromString(ALIstring dimstr) {
ALIdouble valsig;
if (dimstr == "rad") {
valsig = 1.;
} else if (dimstr == "mrad") {
valsig = 1.E-3;
} else if (dimstr == "murad") {
valsig = 1.E-6;
} else if (dimstr == "deg") {
valsig = M_PI / 180.;
} else if (dimstr == "grad") {
valsig = M_PI / 200.;
} else {
std::cerr << "!!! UNKNOWN DIMENSION SCALING: " << dimstr << std::endl
<< "VALUE MUST BE AN ANGLE DIMENSION " << std::endl;
exit(1);
}
return valsig;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Calculate dimension factor to convert any length values and errors to meters
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ALIdouble ALIUtils::CalculateLengthDimensionFactorFromInt(ALIint ad) {
ALIdouble valsig;
switch (ad) {
case 0: //----- metres
valsig = CalculateLengthDimensionFactorFromString("m");
break;
case 1: //----- milimetres
valsig = CalculateLengthDimensionFactorFromString("mm");
break;
case 2: //----- micrometres
valsig = CalculateLengthDimensionFactorFromString("mum");
break;
case 3: //----- centimetres
valsig = CalculateLengthDimensionFactorFromString("cm");
break;
default:
std::cerr << "!!! UNKNOWN DIMENSION SCALING " << ad << std::endl << "VALUE MUST BE BETWEEN 0 AND 3 " << std::endl;
exit(1);
}
// use microradinas instead of radians
//- valsig *= 1000000.;
return valsig;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Calculate dimension factor to convert any angle values and errors to radians
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ALIdouble ALIUtils::CalculateAngleDimensionFactorFromInt(ALIint ad) {
ALIdouble valsig;
switch (ad) {
case 0: //----- radians
valsig = CalculateAngleDimensionFactorFromString("rad");
break;
case 1: //----- miliradians
valsig = CalculateAngleDimensionFactorFromString("mrad");
break;
case 2: //----- microradians
valsig = CalculateAngleDimensionFactorFromString("murad");
break;
case 3: //----- degrees
valsig = CalculateAngleDimensionFactorFromString("deg");
break;
case 4: //----- grads
valsig = CalculateAngleDimensionFactorFromString("grad");
break;
default:
std::cerr << "!!! UNKNOWN DIMENSION SCALING " << ad << std::endl << "VALUE MUST BE BETWEEN 0 AND 3 " << std::endl;
exit(1);
}
// use microradinas instead of radians
//- valsig *= 1000000.;
return valsig;
}
/*template<class T>
ALIuint FindItemInVector( const T* item, const std::vector<T*> std::vector )
{
}
*/
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void ALIUtils::dumpDimensions(std::ofstream& fout) {
fout << "DIMENSIONS: lengths = ";
ALIstring internalDim = "m";
if (_OutputLengthValueDimensionFactor == 1.) {
fout << "m";
} else if (_OutputLengthValueDimensionFactor == 1.E-3) {
fout << "mm";
} else if (_OutputLengthValueDimensionFactor == 1.E-6) {
fout << "mum";
} else if (_OutputLengthValueDimensionFactor == 1.E-2) {
fout << "cm";
} else {
std::cerr << " !! unknown OutputLengthValueDimensionFactor " << _OutputLengthValueDimensionFactor << std::endl;
exit(1);
}
fout << " +- ";
if (_OutputLengthSigmaDimensionFactor == 1.) {
fout << "m";
} else if (_OutputLengthSigmaDimensionFactor == 1.E-3) {
fout << "mm";
} else if (_OutputLengthSigmaDimensionFactor == 1.E-6) {
fout << "mum";
} else if (_OutputLengthSigmaDimensionFactor == 1.E-2) {
fout << "cm";
} else {
std::cerr << " !! unknown OutputLengthSigmaDimensionFactor " << _OutputLengthSigmaDimensionFactor << std::endl;
exit(1);
}
fout << " angles = ";
if (_OutputAngleValueDimensionFactor == 1.) {
fout << "rad";
} else if (_OutputAngleValueDimensionFactor == 1.E-3) {
fout << "mrad";
} else if (_OutputAngleValueDimensionFactor == 1.E-6) {
fout << "murad";
} else if (_OutputAngleValueDimensionFactor == M_PI / 180.) {
fout << "deg";
} else if (_OutputAngleValueDimensionFactor == M_PI / 200.) {
fout << "grad";
} else {
std::cerr << " !! unknown OutputAngleValueDimensionFactor " << _OutputAngleValueDimensionFactor << std::endl;
exit(1);
}
fout << " +- ";
if (_OutputAngleSigmaDimensionFactor == 1.) {
fout << "rad";
} else if (_OutputAngleSigmaDimensionFactor == 1.E-3) {
fout << "mrad";
} else if (_OutputAngleSigmaDimensionFactor == 1.E-6) {
fout << "murad";
} else if (_OutputAngleSigmaDimensionFactor == M_PI / 180.) {
fout << "deg";
} else if (_OutputAngleSigmaDimensionFactor == M_PI / 200.) {
fout << "grad";
} else {
std::cerr << " !! unknown OutputAngleSigmaDimensionFactor " << _OutputAngleSigmaDimensionFactor << std::endl;
exit(1);
}
fout << std::endl;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double ALIUtils::getFloat(const ALIstring& str) {
//----------- first check that it is a number
if (!IsNumber(str)) {
std::cerr << "!!!! EXITING: trying to get the float from a string that is not a number " << str << std::endl;
exit(1);
}
return atof(str.c_str());
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
int ALIUtils::getInt(const ALIstring& str) {
//----------- first check that it is an integer
if (!IsNumber(str)) {
//----- Check that it is a number
std::cerr << "!!!! EXITING: trying to get the integer from a string that is not a number " << str << std::endl;
exit(1);
} else {
//----- Check that it is not a float, no decimal or E-n
bool isFloat = false;
int ch = str.find('.');
ALIuint ii = 0;
if (ch != -1) {
for (ii = ch + 1; ii < str.size(); ii++) {
if (str[ii] != '0')
isFloat = true;
}
}
ch = str.find('E');
if (ch != -1)
ch = str.find('e');
if (ch != -1) {
if (str[ch + 1] == '-')
isFloat = true;
}
if (isFloat) {
std::cerr << "!!!! EXITING: trying to get the integer from a string that is a float: " << str << std::endl;
std::cerr << ii << " ii " << ch << std::endl;
exit(1);
}
}
return int(atof(str.c_str()));
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool ALIUtils::getBool(const ALIstring& str) {
bool val;
//t str = upper( str );
//----------- first check that it is a not number
if (str == "ON" || str == "TRUE") {
val = true;
} else if (str == "OFF" || str == "FALSE") {
val = false;
} else {
std::cerr << "!!!! EXITING: trying to get the float from a string that is not 'ON'/'OFF'/'TRUE'/'FALSE' " << str
<< std::endl;
exit(1);
}
return val;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ALIstring ALIUtils::subQuotes(const ALIstring& str) {
//---------- Take out leading and trailing '"'
if (str.find('"') != 0 || str.rfind('"') != str.length() - 1) {
std::cerr << "!!!EXITING trying to substract quotes from a word that has no quotes " << str << std::endl;
exit(1);
}
// str = str.strip(ALIstring::both, '\"');
//---------- Take out leading and trallling '"'
ALIstring strt = str.substr(1, str.size() - 2);
//- std::cout << " subquotes " << str << std::endl;
//---------- Look for leading spaces
while (strt[0] == ' ') {
strt = strt.substr(1, strt.size() - 1);
}
//---------- Look for trailing spaces
while (strt[strt.size() - 1] == ' ') {
strt = strt.substr(0, strt.size() - 1);
}
return strt;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void ALIUtils::dumpVS(const std::vector<ALIstring>& wl, const std::string& msg, std::ostream& outs) {
outs << msg << std::endl;
ALIuint siz = wl.size();
for (ALIuint ii = 0; ii < siz; ii++) {
outs << wl[ii] << " ";
/* ostream_iterator<ALIstring> os(outs," ");
copy(wl.begin(), wl.end(), os);*/
}
outs << std::endl;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ALIdouble ALIUtils::getDimensionValue(const ALIstring& dim, const ALIstring& dimType) {
ALIdouble value;
if (dimType == "Length") {
if (dim == "mm") {
value = 1.E-3;
} else if (dim == "cm") {
value = 1.E-2;
} else if (dim == "m") {
value = 1.;
} else if (dim == "mum") {
value = 1.E-6;
} else if (dim == "dm") {
value = 1.E-1;
} else if (dim == "nm") {
value = 1.E-9;
} else {
std::cerr << "!!!!FATAL ERROR: ALIUtils::GetDimensionValue. " << dim
<< " is a dimension not supported for dimension type " << dimType << std::endl;
abort();
}
} else if (dimType == "Angle") {
if (dim == "rad") {
value = 1.;
} else if (dim == "mrad") {
value = 1.E-3;
} else if (dim == "murad") {
value = 1.E-6;
} else if (dim == "deg") {
value = M_PI / 180.;
} else if (dim == "grad") {
value = M_PI / 200.;
} else {
std::cerr << "!!!!FATAL ERROR: ALIUtils::GetDimensionValue. " << dim
<< " is a dimension not supported for dimension type " << dimType << std::endl;
abort();
}
} else {
std::cerr << "!!!!FATAL ERROR: ALIUtils::GetDimensionValue. " << dimType << " is a dimension type not supported "
<< std::endl;
abort();
}
return value;
}
/*
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::ostream& operator << (std::ostream& os, const CLHEP::HepRotation& rm)
{
return os << " xx=" << rm.xx() << " xy=" << rm.xy() << " xz=" << rm.xz() << std::endl
<< " yx=" << rm.yx() << " yy=" << rm.yy() << " yz=" << rm.yz() << std::endl
<< " zx=" << rm.zx() << " zy=" << rm.zy() << " zz=" << rm.zz() << std::endl;
}
*/
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::string ALIUtils::changeName(const std::string& oldName, const std::string& subsstr1, const std::string& subsstr2) {
std::string newName = oldName;
int il = oldName.find(subsstr1);
// std::cout << " il " << il << " oldname " << oldName << " " << subsstr1 << std::endl;
while (il >= 0) {
newName = newName.substr(0, il) + subsstr2 + newName.substr(il + subsstr1.length(), newName.length());
// std::cout << " dnewName " << newName << " " << newName.substr( 0, il ) << " " << subsstr2 << " " << newName.substr( il+subsstr1.length(), newName.length() ) << std::endl;
il = oldName.find(subsstr1, il + 1);
}
return newName;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
std::vector<double> ALIUtils::getRotationAnglesFromMatrix(CLHEP::HepRotation& rmLocal,
double origAngleX,
double origAngleY,
double origAngleZ) {
double pii = acos(0.) * 2;
std::vector<double> newang(3);
double angleX = origAngleX;
double angleY = origAngleY;
double angleZ = origAngleZ;
if (ALIUtils::debug >= 4) {
std::cout << " angles as value entries: X= " << angleX << " Y= " << angleY << " Z " << angleZ << std::endl;
}
//- std::cout << name () << " vdbf " << angleX << " " << angleY << " " << angleZ << std::endl;
double rotzx = approxTo0(rmLocal.zx());
double rotzy = approxTo0(rmLocal.zy());
double rotzz = approxTo0(rmLocal.zz());
double rotyx = approxTo0(rmLocal.yx());
double rotxx = approxTo0(rmLocal.xx());
if (rotzy == 0. && rotzz == 0.) {
//check that entry is z angle
newang[0] = angleX;
//beware of aa <==> pii - aa
if (eq2ang(rmLocal.zx(), -1.)) {
double aa = asin(rmLocal.xy());
if (diff2pi(angleZ, -aa + newang[0]) < diff2pi(angleZ, -pii + aa + newang[0])) {
newang[2] = -aa + newang[0];
if (ALIUtils::debug >= 5)
std::cout << " newang[0] = -aa + newang[0] " << std::endl;
} else {
newang[2] = -pii + aa + newang[0];
if (ALIUtils::debug >= 5)
std::cout << " newang[0] = -pii + aa + newang[0] " << newang[0] << " " << aa << " " << newang[2] << std::endl;
}
} else {
double aa = asin(-rmLocal.xy());
if (diff2pi(angleZ, aa - newang[0]) < diff2pi(angleZ, pii - aa - newang[0])) {
newang[2] = aa - newang[0];
if (ALIUtils::debug >= 5)
std::cout << " newang[0] = aa - newang[2] " << std::endl;
} else {
newang[2] = pii - aa - newang[0];
if (ALIUtils::debug >= 5)
std::cout << " newang[0] = pii - aa - newang[2] " << newang[0] << " " << aa << " " << newang[2] << std::endl;
}
}
} else {
newang[0] = atan(rotzy / rotzz);
newang[2] = atan(rotyx / rotxx);
}
if (rotzx < -1.) {
//- std::cerr << " rotzx too small " << rotzx << " = " << rmLocal.zx() << " " << rotzx-rmLocal.zx() << std::endl;
rotzx = -1.;
} else if (rotzx > 1.) {
//- std::cerr << " rotzx too big " << rotzx << " = " << rmLocal.zx() << " " << rotzx-rmLocal.zx() << std::endl;
rotzx = 1.;
}
newang[1] = -asin(rotzx);
if (ALIUtils::debug >= 5)
std::cout << "First calculation of angles: " << std::endl
<< " newang[0] " << newang[0] << " " << rotzy << " " << rotzz << std::endl
<< " newang[1] " << newang[1] << " " << rotzx << std::endl
<< " newang[2] " << newang[2] << " " << rotyx << " " << rotxx << std::endl;
// newang[2] = acos( rmLocal.xx() / cos( newang[1] ) );
//----- CHECK if the angles are OK (there are several symmetries)
//--- Check if the predictions with the angles obtained match the values of the rotation matrix (they may differ for exampole by a sign or more in complicated formulas)
double rotnewxx = cos(newang[1]) * cos(newang[2]);
double rotnewzz = cos(newang[0]) * cos(newang[1]);
double rotnewxy = sin(newang[0]) * sin(newang[1]) * cos(newang[2]) - cos(newang[0]) * sin(newang[2]);
double rotnewxz = cos(newang[0]) * sin(newang[1]) * cos(newang[2]) + sin(newang[0]) * sin(newang[2]);
double rotnewyy = sin(newang[0]) * sin(newang[1]) * sin(newang[2]) + cos(newang[0]) * cos(newang[2]);
double rotnewyz = cos(newang[0]) * sin(newang[1]) * sin(newang[2]) - sin(newang[0]) * cos(newang[2]);
bool eqxx = eq2ang(rotnewxx, rmLocal.xx());
bool eqzz = eq2ang(rotnewzz, rmLocal.zz());
bool eqxy = eq2ang(rotnewxy, rmLocal.xy());
bool eqxz = eq2ang(rotnewxz, rmLocal.xz());
bool eqyy = eq2ang(rotnewyy, rmLocal.yy());
bool eqyz = eq2ang(rotnewyz, rmLocal.yz());
//--- Check if one of the tree angles should be changed
if (ALIUtils::debug >= 5) {
std::cout << " pred rm.xx " << rotnewxx << " =? " << rmLocal.xx() << " pred rm.zz " << rotnewzz << " =? "
<< rmLocal.zz() << std::endl;
std::cout << " eqxx " << eqxx << " eqzz " << eqzz << std::endl;
//- std::cout << " rotnewxx " << rotnewxx << " = " << rmLocal.xx() << " " << fabs( rotnewxx - rmLocal.xx() ) << " " <<(fabs( rotnewxx - rmLocal.xx() ) < 0.0001) << std::endl;
}
if (eqxx & !eqzz) {
newang[0] = pii + newang[0];
if (ALIUtils::debug >= 5)
std::cout << " change newang[0] " << newang[0] << std::endl;
} else if (!eqxx & !eqzz) {
newang[1] = pii - newang[1];
if (ALIUtils::debug >= 5)
std::cout << " change newang[1] " << newang[1] << std::endl;
} else if (!eqxx & eqzz) {
newang[2] = pii + newang[2];
if (ALIUtils::debug >= 5)
std::cout << " change newang[2] " << newang[2] << std::endl;
}
//--- Check if the 3 angles should be changed (previous check is invariant to the 3 changing)
if (ALIUtils::debug >= 5) {
std::cout << " pred rm.xy " << rotnewxy << " =? " << rmLocal.xy() << " pred rm.xz " << rotnewxz << " =? "
<< rmLocal.xz() << " pred rm.yy " << rotnewyy << " =? " << rmLocal.yy() << " pred rm.yz " << rotnewyz
<< " =? " << rmLocal.yz() << std::endl;
std::cout << " eqxy " << eqxy << " eqxz " << eqxz << " eqyy " << eqyy << " eqyz " << eqyz << std::endl;
}
if (!eqxy || !eqxz || !eqyy || !eqyz) {
// check also cases where one of the above 'eq' is OK because it is = 0
if (ALIUtils::debug >= 5)
std::cout << " change the 3 newang " << std::endl;
newang[0] = addPii(newang[0]);
newang[1] = pii - newang[1];
newang[2] = addPii(newang[2]);
double rotnewxy = -sin(newang[0]) * sin(newang[1]) * cos(newang[2]) - cos(newang[0]) * sin(newang[2]);
double rotnewxz = -cos(newang[0]) * sin(newang[1]) * cos(newang[2]) - sin(newang[0]) * sin(newang[2]);
if (ALIUtils::debug >= 5)
std::cout << " rotnewxy " << rotnewxy << " = " << rmLocal.xy() << " rotnewxz " << rotnewxz << " = "
<< rmLocal.xz() << std::endl;
}
if (diff2pi(angleX, newang[0]) + diff2pi(angleY, newang[1]) + diff2pi(angleZ, newang[2]) >
diff2pi(angleX, pii + newang[0]) + diff2pi(angleY, pii - newang[1]) + diff2pi(angleZ, pii + newang[2])) {
// check also cases where one of the above 'eq' is OK because it is = 0
if (ALIUtils::debug >= 5)
std::cout << " change the 3 newang " << std::endl;
newang[0] = addPii(newang[0]);
newang[1] = pii - newang[1];
newang[2] = addPii(newang[2]);
double rotnewxy = -sin(newang[0]) * sin(newang[1]) * cos(newang[2]) - cos(newang[0]) * sin(newang[2]);
double rotnewxz = -cos(newang[0]) * sin(newang[1]) * cos(newang[2]) - sin(newang[0]) * sin(newang[2]);
if (ALIUtils::debug >= 5)
std::cout << " rotnewxy " << rotnewxy << " = " << rmLocal.xy() << " rotnewxz " << rotnewxz << " = "
<< rmLocal.xz() << std::endl;
}
for (int ii = 0; ii < 3; ii++) {
newang[ii] = approxTo0(newang[ii]);
}
// double rotnewyx = cos( newang[1] ) * sin( newang[2] );
if (checkMatrixEquations(newang[0], newang[1], newang[2], &rmLocal) != 0) {
std::cerr << " wrong rotation matrix " << newang[0] << " " << newang[1] << " " << newang[2] << std::endl;
ALIUtils::dumprm(rmLocal, " matrix is ");
}
if (ALIUtils::debug >= 5) {
std::cout << "Final angles: newang[0] " << newang[0] << " newang[1] " << newang[1] << " newang[2] " << newang[2]
<< std::endl;
CLHEP::HepRotation rot;
rot.rotateX(newang[0]);
ALIUtils::dumprm(rot, " new rot after X ");
rot.rotateY(newang[1]);
ALIUtils::dumprm(rot, " new rot after Y ");
rot.rotateZ(newang[2]);
ALIUtils::dumprm(rot, " new rot ");
ALIUtils::dumprm(rmLocal, " rmLocal ");
//- ALIUtils::dumprm( theRmGlobOriginal, " theRmGlobOriginal " );
}
//- std::cout << " before return newang[0] " << newang[0] << " newang[1] " << newang[1] << " newang[2] " << newang[2] << std::endl;
return newang;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
double ALIUtils::diff2pi(double ang1, double ang2) {
double pii = acos(0.) * 2;
double diff = fabs(ang1 - ang2);
diff = diff - int(diff / 2. / pii) * 2 * pii;
return diff;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
bool ALIUtils::eq2ang(double ang1, double ang2) {
bool beq = true;
double pii = acos(0.) * 2;
double diff = diff2pi(ang1, ang2);
if (diff > 0.00001) {
if (fabs(diff - 2 * pii) > 0.00001) {
//- std::cout << " diff " << diff << " " << ang1 << " " << ang2 << std::endl;
beq = false;
}
} else {
beq = true;
}
return beq;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
double ALIUtils::approxTo0(double val) {
double precision = 1.e-9;
if (fabs(val) < precision)
val = 0;
return val;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
double ALIUtils::addPii(double val) {
if (val < M_PI) {
val += M_PI;
} else {
val -= M_PI;
}
return val;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
int ALIUtils::checkMatrixEquations(double angleX, double angleY, double angleZ, CLHEP::HepRotation* rot) {
//- std::cout << " cme " << angleX << " " << angleY << " " << angleZ << std::endl;
if (rot == nullptr) {
rot = new CLHEP::HepRotation();
rot->rotateX(angleX);
rot->rotateY(angleY);
rot->rotateZ(angleZ);
}
double sx = sin(angleX);
double cx = cos(angleX);
double sy = sin(angleY);
double cy = cos(angleY);
double sz = sin(angleZ);
double cz = cos(angleZ);
double rotxx = cy * cz;
double rotxy = sx * sy * cz - cx * sz;
double rotxz = cx * sy * cz + sx * sz;
double rotyx = cy * sz;
double rotyy = sx * sy * sz + cx * cz;
double rotyz = cx * sy * sz - sx * cz;
double rotzx = -sy;
double rotzy = sx * cy;
double rotzz = cx * cy;
int matrixElemBad = 0;
if (!eq2ang(rot->xx(), rotxx)) {
std::cerr << " EQUATION for xx() IS BAD " << rot->xx() << " <> " << rotxx << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->xy(), rotxy)) {
std::cerr << " EQUATION for xy() IS BAD " << rot->xy() << " <> " << rotxy << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->xz(), rotxz)) {
std::cerr << " EQUATION for xz() IS BAD " << rot->xz() << " <> " << rotxz << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->yx(), rotyx)) {
std::cerr << " EQUATION for yx() IS BAD " << rot->yx() << " <> " << rotyx << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->yy(), rotyy)) {
std::cerr << " EQUATION for yy() IS BAD " << rot->yy() << " <> " << rotyy << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->yz(), rotyz)) {
std::cerr << " EQUATION for yz() IS BAD " << rot->yz() << " <> " << rotyz << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->zx(), rotzx)) {
std::cerr << " EQUATION for zx() IS BAD " << rot->zx() << " <> " << rotzx << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->zy(), rotzy)) {
std::cerr << " EQUATION for zy() IS BAD " << rot->zy() << " <> " << rotzy << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->zz(), rotzz)) {
std::cerr << " EQUATION for zz() IS BAD " << rot->zz() << " <> " << rotzz << std::endl;
matrixElemBad++;
}
//- std::cout << " cme: matrixElemBad " << matrixElemBad << std::endl;
return matrixElemBad;
}
| 39.402174 | 182 | 0.511632 | gputtley |
ca35cd098258ace8c8383de3230cdfcaecfa1193 | 3,847 | hpp | C++ | stapl_release/stapl/containers/distribution/map_metadata.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/containers/distribution/map_metadata.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/containers/distribution/map_metadata.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_CONTAINERS_MAP_METADATA_HPP
#define STAPL_CONTAINERS_MAP_METADATA_HPP
#include <stapl/domains/iterator_domain.hpp>
#include <stapl/views/metadata/metadata_entry.hpp>
#include <stapl/views/metadata/container_fwd.hpp>
#include <stapl/containers/iterators/gid_of_fwd.hpp>
namespace stapl {
//////////////////////////////////////////////////////////////////////
/// @brief Class for computing the metadata of @ref map_distribution,
/// and all other associative distributions.
/// @tparam Distribution Type of the Distribution.
//////////////////////////////////////////////////////////////////////
template<typename Distribution>
class map_metadata
{
STAPL_IMPORT_TYPE(typename Distribution, index_type)
STAPL_IMPORT_TYPE(typename Distribution, base_container_type)
STAPL_IMPORT_TYPE(typename Distribution, container_manager_type)
typedef typename base_container_type::domain_type bc_domain_type;
typedef iterator_domain<
Distribution, typename bc_domain_type::field_selector
> domain_type;
public:
// public access required to allow the container's distribution class access.
typedef metadata_entry<domain_type, base_container_type*> dom_info_type;
private:
typedef metadata::growable_container<dom_info_type> metadata_type;
public:
typedef metadata_type metadata_cont_type;
typedef std::pair<bool, metadata_cont_type*> return_type;
//////////////////////////////////////////////////////////////////////
/// @brief Return the metadata of the specified container.
/// @see metadata_entry.
/// @param cont A pointer to the container.
///
/// Calls the operator on the distribution of the provided container.
///
/// @return a pair indicating if the metadata container is static and
/// balance distributed and a pointer to the metadata container.
//////////////////////////////////////////////////////////////////////
template <typename Container>
return_type operator()(Container* cont)
{
return operator()(&(cont->distribution()));
}
//////////////////////////////////////////////////////////////////////
/// @brief Return the metadata of the specified distribution.
/// @see metadata_entry.
/// @param dist A pointer to the distribution.
///
/// @return a pair indicating if the metadata container is static and
/// balance distributed and a pointer to the metadata container.
//////////////////////////////////////////////////////////////////////
return_type operator()(Distribution* dist)
{
metadata_cont_type* out_part = new metadata_type;
typedef typename container_manager_type::const_iterator citer_t;
citer_t cit = dist->container_manager().begin();
citer_t cit_end = dist->container_manager().end();
for ( ; cit != cit_end; ++cit)
{
base_container_type& bc = *cit;
if (!bc.domain().empty())
{
domain_type ndom(
bc.domain().first(), bc.domain().last(), *dist, bc.domain().size()
);
out_part->push_back_here(dom_info_type(
typename dom_info_type::cid_type(), ndom, &bc,
LQ_CERTAIN, get_affinity(),
dist->get_rmi_handle(), dist->get_location_id()
));
}
}
out_part->update();
return std::make_pair(false, out_part);
}
}; // class map_metadata
} // namespace stapl
#endif // STAPL_CONTAINERS_MAP_METADATA_HPP
| 34.657658 | 79 | 0.625422 | parasol-ppl |
ca360ecf778f3a531c706dd39105f1e5f08c6be8 | 20 | cpp | C++ | lib/threads/event.cpp | ashcharles/openset | 51dc29b9dffdb745a24e01a9e4d86c79d2ff20d6 | [
"MIT"
] | 18 | 2017-09-28T16:46:27.000Z | 2022-03-13T19:32:04.000Z | lib/threads/event.cpp | perple-io/openset | 201ee4a6247b6cce369885e05794e7dd3e8b8508 | [
"MIT"
] | 14 | 2017-10-05T13:40:48.000Z | 2019-10-18T15:44:44.000Z | lib/threads/event.cpp | perple-io/openset | 201ee4a6247b6cce369885e05794e7dd3e8b8508 | [
"MIT"
] | 4 | 2017-12-07T22:34:10.000Z | 2021-07-17T00:19:43.000Z | #include "event.h"
| 10 | 19 | 0.65 | ashcharles |
ca3655bb3d549aaa22baf73498a48a3fa13b99a9 | 2,233 | cpp | C++ | examples/tsp/src/tsp/tsp_instance.cpp | luishpmendes/ns-brkga | 61b3ec35ea4276359b1baa7c0f6c92087c4f8d3b | [
"MIT"
] | 11 | 2019-11-25T17:34:40.000Z | 2021-12-25T16:31:48.000Z | examples/tsp/src/tsp/tsp_instance.cpp | luishpmendes/ns-brkga | 61b3ec35ea4276359b1baa7c0f6c92087c4f8d3b | [
"MIT"
] | 3 | 2020-04-22T15:53:50.000Z | 2021-12-17T21:28:55.000Z | examples/tsp/src/tsp/tsp_instance.cpp | luishpmendes/ns-brkga | 61b3ec35ea4276359b1baa7c0f6c92087c4f8d3b | [
"MIT"
] | 7 | 2020-05-20T17:05:04.000Z | 2021-12-13T17:41:56.000Z | /******************************************************************************
* tsp_instance.cpp: Implementation for TSP_Instance class.
*
* (c) Copyright 2015-2019, Carlos Eduardo de Andrade.
* All Rights Reserved.
*
* Created on : Mar 05, 2019 by andrade
* Last update: Mar 05, 2019 by andrade
*
* This code is released under LICENSE.md.
*
* 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 "tsp/tsp_instance.hpp"
#include <fstream>
#include <stdexcept>
using namespace std;
//-----------------------------[ Constructor ]--------------------------------//
TSP_Instance::TSP_Instance(const std::string& filename):
num_nodes(0),
distances()
{
ifstream file(filename, ios::in);
if(!file)
throw runtime_error("Cannot open instance file");
file.exceptions(ifstream::failbit | ifstream::badbit);
try {
file >> num_nodes;
distances.resize((num_nodes * (num_nodes - 1)) / 2);
for(unsigned i = 0; i < distances.size(); ++i)
file >> distances[i];
}
catch(std::ifstream::failure& e) {
throw fstream::failure("Error reading the instance file");
}
}
//-------------------------------[ Distance ]---------------------------------//
double TSP_Instance::distance(unsigned i, unsigned j) const {
if(i > j)
swap(i, j);
return distances[(i * (num_nodes - 1)) - ((i - 1) * i / 2) + (j - i - 1)];
}
| 36.606557 | 80 | 0.596059 | luishpmendes |
ca37ed05ba42645e28e8b89162b3eca996b386f1 | 10,338 | hxx | C++ | Modules/Learning/Supervised/include/otbSharkRandomForestsMachineLearningModel.hxx | heralex/OTB | c52b504b64dc89c8fe9cac8af39b8067ca2c3a57 | [
"Apache-2.0"
] | 317 | 2015-01-19T08:40:58.000Z | 2022-03-17T11:55:48.000Z | Modules/Learning/Supervised/include/otbSharkRandomForestsMachineLearningModel.hxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 18 | 2015-07-29T14:13:45.000Z | 2021-03-29T12:36:24.000Z | Modules/Learning/Supervised/include/otbSharkRandomForestsMachineLearningModel.hxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 132 | 2015-02-21T23:57:25.000Z | 2022-03-25T16:03:16.000Z | /*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbSharkRandomForestsMachineLearningModel_hxx
#define otbSharkRandomForestsMachineLearningModel_hxx
#include <fstream>
#include "itkMacro.h"
#include "otbSharkRandomForestsMachineLearningModel.h"
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#pragma GCC diagnostic ignored "-Wignored-qualifiers"
#endif
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#include "otbSharkUtils.h"
#include <algorithm>
namespace otb
{
template <class TInputValue, class TOutputValue>
SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::SharkRandomForestsMachineLearningModel()
{
this->m_ConfidenceIndex = true;
this->m_ProbaIndex = true;
this->m_IsRegressionSupported = false;
this->m_IsDoPredictBatchMultiThreaded = true;
this->m_NormalizeClassLabels = true;
this->m_ComputeMargin = false;
}
/** Train the machine learning model */
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::Train()
{
#ifdef _OPENMP
omp_set_num_threads(itk::MultiThreader::GetGlobalDefaultNumberOfThreads());
#endif
std::vector<shark::RealVector> features;
std::vector<unsigned int> class_labels;
Shark::ListSampleToSharkVector(this->GetInputListSample(), features);
Shark::ListSampleToSharkVector(this->GetTargetListSample(), class_labels);
if (m_NormalizeClassLabels)
{
Shark::NormalizeLabelsAndGetDictionary(class_labels, m_ClassDictionary);
}
shark::ClassificationDataset TrainSamples = shark::createLabeledDataFromRange(features, class_labels);
// Set parameters
m_RFTrainer.setMTry(m_MTry);
m_RFTrainer.setNTrees(m_NumberOfTrees);
m_RFTrainer.setNodeSize(m_NodeSize);
// m_RFTrainer.setOOBratio(m_OobRatio);
m_RFTrainer.train(m_RFModel, TrainSamples);
}
template <class TInputValue, class TOutputValue>
typename SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::ConfidenceValueType
SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::ComputeConfidence(shark::RealVector& probas, bool computeMargin) const
{
assert(!probas.empty() && "probas vector is empty");
assert((!computeMargin || probas.size() > 1) && "probas size should be at least 2 if computeMargin is true");
ConfidenceValueType conf{0};
if (computeMargin)
{
std::nth_element(probas.begin(), probas.begin() + 1, probas.end(), std::greater<double>());
conf = static_cast<ConfidenceValueType>(probas[0] - probas[1]);
}
else
{
auto max_proba = *(std::max_element(probas.begin(), probas.end()));
conf = static_cast<ConfidenceValueType>(max_proba);
}
return conf;
}
template <class TInputValue, class TOutputValue>
typename SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::TargetSampleType
SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::DoPredict(const InputSampleType& value, ConfidenceValueType* quality,
ProbaSampleType* proba) const
{
shark::RealVector samples(value.Size());
for (size_t i = 0; i < value.Size(); i++)
{
samples.push_back(value[i]);
}
if (quality != nullptr || proba != nullptr)
{
shark::RealVector probas = m_RFModel.decisionFunction()(samples);
if (quality != nullptr)
{
(*quality) = ComputeConfidence(probas, m_ComputeMargin);
}
if (proba != nullptr)
{
for (size_t i = 0; i < probas.size(); i++)
{
// probas contain the N class probability indexed between 0 and N-1
(*proba)[i] = static_cast<unsigned int>(probas[i] * 1000);
}
}
}
unsigned int res{0};
m_RFModel.eval(samples, res);
TargetSampleType target;
if (m_NormalizeClassLabels)
{
target[0] = m_ClassDictionary[static_cast<TOutputValue>(res)];
}
else
{
target[0] = static_cast<TOutputValue>(res);
}
return target;
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::DoPredictBatch(const InputListSampleType* input, const unsigned int& startIndex,
const unsigned int& size, TargetListSampleType* targets,
ConfidenceListSampleType* quality, ProbaListSampleType* proba) const
{
assert(input != nullptr);
assert(targets != nullptr);
assert(input->Size() == targets->Size() && "Input sample list and target label list do not have the same size.");
assert(((quality == nullptr) || (quality->Size() == input->Size())) &&
"Quality samples list is not null and does not have the same size as input samples list");
assert(((proba == nullptr) || (input->Size() == proba->Size())) && "Proba sample list and target label list do not have the same size.");
if (startIndex + size > input->Size())
{
itkExceptionMacro(<< "requested range [" << startIndex << ", " << startIndex + size << "[ partially outside input sample list range.[0," << input->Size()
<< "[");
}
std::vector<shark::RealVector> features;
Shark::ListSampleRangeToSharkVector(input, features, startIndex, size);
shark::Data<shark::RealVector> inputSamples = shark::createDataFromRange(features);
#ifdef _OPENMP
omp_set_num_threads(itk::MultiThreader::GetGlobalDefaultNumberOfThreads());
#endif
if (proba != nullptr || quality != nullptr)
{
shark::Data<shark::RealVector> probas = m_RFModel.decisionFunction()(inputSamples);
if (proba != nullptr)
{
unsigned int id = startIndex;
for (shark::RealVector&& p : probas.elements())
{
ProbaSampleType prob{(unsigned int)p.size()};
for (size_t i = 0; i < p.size(); i++)
{
prob[i] = p[i] * 1000;
}
proba->SetMeasurementVector(id, prob);
++id;
}
}
if (quality != nullptr)
{
unsigned int id = startIndex;
for (shark::RealVector&& p : probas.elements())
{
ConfidenceSampleType confidence;
auto conf = ComputeConfidence(p, m_ComputeMargin);
confidence[0] = static_cast<ConfidenceValueType>(conf);
quality->SetMeasurementVector(id, confidence);
++id;
}
}
}
auto prediction = m_RFModel(inputSamples);
unsigned int id = startIndex;
for (const auto& p : prediction.elements())
{
TargetSampleType target;
if (m_NormalizeClassLabels)
{
target[0] = m_ClassDictionary[static_cast<TOutputValue>(p)];
}
else
{
target[0] = static_cast<TOutputValue>(p);
}
targets->SetMeasurementVector(id, target);
++id;
}
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::Save(const std::string& filename, const std::string& itkNotUsed(name))
{
std::ofstream ofs(filename);
if (!ofs)
{
itkExceptionMacro(<< "Error opening " << filename.c_str());
}
// Add comment with model file name
ofs << "#" << m_RFModel.name();
if (m_NormalizeClassLabels)
ofs << " with_dictionary";
ofs << std::endl;
if (m_NormalizeClassLabels)
{
ofs << m_ClassDictionary.size() << " ";
for (const auto& l : m_ClassDictionary)
{
ofs << l << " ";
}
ofs << std::endl;
}
shark::TextOutArchive oa(ofs);
m_RFModel.save(oa, 0);
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::Load(const std::string& filename, const std::string& itkNotUsed(name))
{
std::ifstream ifs(filename);
if (ifs.good())
{
// Check if the first line is a comment and verify the name of the model in this case.
std::string line;
getline(ifs, line);
if (line.at(0) == '#')
{
if (line.find(m_RFModel.name()) == std::string::npos)
itkExceptionMacro("The model file : " + filename + " cannot be read.");
if (line.find("with_dictionary") == std::string::npos)
{
m_NormalizeClassLabels = false;
}
}
else
{
// rewind if first line is not a comment
ifs.clear();
ifs.seekg(0, std::ios::beg);
}
if (m_NormalizeClassLabels)
{
size_t nbLabels{0};
ifs >> nbLabels;
m_ClassDictionary.resize(nbLabels);
for (size_t i = 0; i < nbLabels; ++i)
{
unsigned int label;
ifs >> label;
m_ClassDictionary[i] = label;
}
}
shark::TextInArchive ia(ifs);
m_RFModel.load(ia, 0);
}
}
template <class TInputValue, class TOutputValue>
bool SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::CanReadFile(const std::string& file)
{
try
{
this->Load(file);
m_RFModel.name();
}
catch (...)
{
return false;
}
return true;
}
template <class TInputValue, class TOutputValue>
bool SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::CanWriteFile(const std::string& itkNotUsed(file))
{
return true;
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::PrintSelf(std::ostream& os, itk::Indent indent) const
{
// Call superclass implementation
Superclass::PrintSelf(os, indent);
}
} // end namespace otb
#endif
| 32.30625 | 157 | 0.671697 | heralex |
ca3906359b23d981bcf6b446dc1fe368b6b4eada | 3,562 | cpp | C++ | Tools/Base64.cpp | xuyuanwang1993/p2p_work_on_kcp | 9f4081cdeee6550c3295215a123ecffd13128dac | [
"MIT"
] | 13 | 2019-09-19T01:04:00.000Z | 2022-02-24T08:26:25.000Z | Tools/Base64.cpp | xuyuanwang1993/p2p_work_on_kcp | 9f4081cdeee6550c3295215a123ecffd13128dac | [
"MIT"
] | 2 | 2019-10-16T12:57:29.000Z | 2019-11-08T12:07:43.000Z | Tools/Base64.cpp | xuyuanwang1993/p2p_work_on_kcp | 9f4081cdeee6550c3295215a123ecffd13128dac | [
"MIT"
] | 5 | 2019-10-16T12:45:20.000Z | 2022-01-19T15:03:36.000Z | #include "Base64.h"
#include <mutex>
#include <iostream>
using namespace std;
using namespace sensor_tool;
std::string sensor_tool::base64Encode(const std::string & origin_string)
{
static const char base64Char[] ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string ret("");
if(origin_string.empty()) return ret;
unsigned const numOrig24BitValues = origin_string.size()/3;
bool havePadding = origin_string.size() > numOrig24BitValues*3;//判断是否有余数
bool havePadding2 = origin_string.size() == numOrig24BitValues*3 + 2;//判断余数是否等于2
unsigned const numResultBytes = 4*(numOrig24BitValues + havePadding);//计算最终结果的size
ret.resize(numResultBytes);//确定返回字符串大小
unsigned i;
for (i = 0; i < numOrig24BitValues; ++i) {
ret[4*i+0] = base64Char[(origin_string[3*i]>>2)&0x3F];
ret[4*i+1] = base64Char[(((origin_string[3*i]&0x3)<<4) | (origin_string[3*i+1]>>4))&0x3F];
ret[4*i+2] = base64Char[((origin_string[3*i+1]<<2) | (origin_string[3*i+2]>>6))&0x3F];
ret[4*i+3] = base64Char[origin_string[3*i+2]&0x3F];
}
//处理不足3位的情况
//余1位需在后面补齐2个'='
//余2位需补齐一个'='
if (havePadding) {
ret[4*i+0] = base64Char[(origin_string[3*i]>>2)&0x3F];
if (havePadding2) {
ret[4*i+1] = base64Char[(((origin_string[3*i]&0x3)<<4) | (origin_string[3*i+1]>>4))&0x3F];
ret[4*i+2] = base64Char[(origin_string[3*i+1]<<2)&0x3F];
} else {
ret[4*i+1] = base64Char[((origin_string[3*i]&0x3)<<4)&0x3F];
ret[4*i+2] = '=';
}
ret[4*i+3] = '=';
}
return ret;
}
std::string sensor_tool::base64Decode(const std::string & origin_string)
{
static char base64DecodeTable[256];
static std::once_flag oc_init;
std::call_once(oc_init,[&](){
int i;//初始化映射表
for (i = 0; i < 256; ++i) base64DecodeTable[i] = (char)0x80;
for (i = 'A'; i <= 'Z'; ++i) base64DecodeTable[i] = 0 + (i - 'A');
for (i = 'a'; i <= 'z'; ++i) base64DecodeTable[i] = 26 + (i - 'a');
for (i = '0'; i <= '9'; ++i) base64DecodeTable[i] = 52 + (i - '0');
base64DecodeTable[(unsigned char)'+'] = 62;
base64DecodeTable[(unsigned char)'/'] = 63;
base64DecodeTable[(unsigned char)'='] = 0;
});
std::string ret("");
if(origin_string.empty()) return ret;
int k=0;
int paddingCount = 0;
int const jMax = origin_string.size() - 3;
ret.resize(3*origin_string.size()/4);
for(int j=0;j<jMax;j+=4)
{
char inTmp[4], outTmp[4];
for (int i = 0; i < 4; ++i) {
inTmp[i] = origin_string[i+j];
if (inTmp[i] == '=') ++paddingCount;
outTmp[i] = base64DecodeTable[(unsigned char)inTmp[i]];
if ((outTmp[i]&0x80) != 0) outTmp[i] = 0; // this happens only if there was an invalid character; pretend that it was 'A'
}
ret[k++]=(outTmp[0]<<2) | (outTmp[1]>>4);
ret[k++] = (outTmp[1]<<4) | (outTmp[2]>>2);
ret[k++] = (outTmp[2]<<6) | outTmp[3];
}
ret.assign(ret.c_str());//清除空白字符
return ret;
}
void Base64_test()
{
std::string qwer("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.");
std::string qaz=sensor_tool::base64Encode(qwer);
std::cout<<qaz<<std::endl;
std::cout<<qwer<<std::endl;
std::cout<<(int)(sensor_tool::base64Decode(qaz)==qwer)<<std::endl;
}
| 42.404762 | 294 | 0.603593 | xuyuanwang1993 |
ca3b9d371d21cdaedc67cb308df11838ca4cac95 | 4,649 | hpp | C++ | Externals/Boost/boost/numeric/odeint/iterator/impl/adaptive_time_iterator_controlled_impl.hpp | MINATILO/packing-generation | 4d4f5d037e0687b57178602b989431e82a5c8b96 | [
"MIT"
] | 79 | 2015-08-23T12:05:30.000Z | 2022-03-31T16:39:56.000Z | Externals/Boost/boost/numeric/odeint/iterator/impl/adaptive_time_iterator_controlled_impl.hpp | MINATILO/packing-generation | 4d4f5d037e0687b57178602b989431e82a5c8b96 | [
"MIT"
] | 31 | 2015-07-20T17:57:08.000Z | 2022-03-02T10:31:50.000Z | Externals/Boost/boost/numeric/odeint/iterator/impl/adaptive_time_iterator_controlled_impl.hpp | MINATILO/packing-generation | 4d4f5d037e0687b57178602b989431e82a5c8b96 | [
"MIT"
] | 36 | 2015-10-14T02:43:16.000Z | 2022-03-18T12:51:03.000Z | /*
[auto_generated]
boost/numeric/odeint/iterator/detail/adaptive_time_iterator_controlled_impl.hpp
[begin_description]
tba.
[end_description]
Copyright 2009-2012 Karsten Ahnert
Copyright 2009-2012 Mario Mulansky
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or
copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_ADAPTIVE_TIME_ITERATOR_CONTROLLED_IMPL_HPP_DEFINED
#define BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_ADAPTIVE_TIME_ITERATOR_CONTROLLED_IMPL_HPP_DEFINED
#include <boost/numeric/odeint/util/unit_helper.hpp>
#include <boost/numeric/odeint/stepper/controlled_step_result.hpp>
#include <boost/numeric/odeint/iterator/detail/ode_time_iterator_base.hpp>
namespace boost {
namespace numeric {
namespace odeint {
/*
* Specilization for controlled steppers
*/
/**
* \brief ODE Iterator with adaptive step size control. The value type of this iterator is a pair of state type and time type of the stepper.
*
* Implements an ODE iterator with adaptive step size control. Uses controlled steppers. adaptive_iterator is a model
* of single-pass iterator.
*
* The value type of this iterator is a pair of state type and time type of the stepper.
*
* \tparam Stepper The stepper type which should be used during the iteration.
* \tparam System The type of the system function (ODE) which should be solved.
*/
template< class Stepper , class System >
class adaptive_time_iterator< Stepper , System , controlled_stepper_tag > : public detail::ode_time_iterator_base
<
adaptive_time_iterator< Stepper , System , controlled_stepper_tag > ,
Stepper , System
>
{
private:
typedef Stepper stepper_type;
typedef System system_type;
typedef typename boost::numeric::odeint::unwrap_reference< stepper_type >::type unwrapped_stepper_type;
typedef typename unwrapped_stepper_type::state_type state_type;
typedef typename unwrapped_stepper_type::time_type time_type;
typedef typename unwrapped_stepper_type::value_type ode_value_type;
typedef detail::ode_time_iterator_base<
adaptive_time_iterator< Stepper , System , controlled_stepper_tag > ,
Stepper , System > base_type;
public:
/**
* \brief Constructs an adaptive_time_iterator. This constructor should be used to construct the begin iterator.
*
* \param stepper The stepper to use during the iteration.
* \param sys The system function (ODE) to solve.
* \param s The initial state. adaptive_time_iterator stores a reference of s and changes its value during the iteration.
* \param t The initial time.
* \param t_end The end time, at which the iteration should stop.
* \param dt The initial time step.
*/
adaptive_time_iterator( stepper_type stepper , system_type sys , state_type &s , time_type t , time_type t_end , time_type dt )
: base_type( stepper , sys , s , t , t_end , dt ) {}
/**
* \brief Constructs an adaptive_time_iterator. This constructor should be used to construct the end iterator.
*
* \param stepper The stepper to use during the iteration.
* \param sys The system function (ODE) to solve.
* \param s The initial state. adaptive_time_iterator stores a reference of s and changes its value during the iteration.
*/
adaptive_time_iterator( stepper_type stepper , system_type sys , state_type &s )
: base_type( stepper , sys , s ) {}
private:
friend class boost::iterator_core_access;
void increment()
{
unwrapped_stepper_type &stepper = this->m_stepper;
const size_t max_attempts = 1000;
size_t trials = 0;
controlled_step_result res = success;
do
{
res = stepper.try_step( this->m_system , *this->m_state , this->m_t , this->m_dt );
++trials;
}
while( ( res == fail ) && ( trials < max_attempts ) );
if( trials == max_attempts )
{
throw std::overflow_error( "Adaptive iterator : Maximal number of iterations reached. A step size could not be found." );
}
this->check_end();
}
};
} // namespace odeint
} // namespace numeric
} // namespace boost
#endif // BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_ADAPTIVE_TIME_ITERATOR_CONTROLLED_IMPL_HPP_DEFINED
| 38.106557 | 145 | 0.678856 | MINATILO |
ca3ea5838e7403cb98c2bf2326214e7d9c5990b2 | 666 | hpp | C++ | modules/scene_manager/include/rcl_interfaces/srv/get_parameters__struct.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2020-05-19T14:33:49.000Z | 2020-05-19T14:33:49.000Z | ros2_mod_ws/install/include/rcl_interfaces/srv/get_parameters__struct.hpp | mintforpeople/robobo-ros2-ios-port | 1a5650304bd41060925ebba41d6c861d5062bfae | [
"Apache-2.0"
] | 3 | 2019-11-14T12:20:06.000Z | 2020-08-07T13:51:10.000Z | modules/scene_manager/include/rcl_interfaces/srv/get_parameters__struct.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | // generated from rosidl_generator_cpp/resource/srv__struct.hpp.em
// generated code does not contain a copyright notice
#ifndef RCL_INTERFACES__SRV__GET_PARAMETERS__STRUCT_HPP_
#define RCL_INTERFACES__SRV__GET_PARAMETERS__STRUCT_HPP_
#include "rcl_interfaces/srv/get_parameters__request.hpp"
#include "rcl_interfaces/srv/get_parameters__response.hpp"
namespace rcl_interfaces
{
namespace srv
{
struct GetParameters
{
using Request = rcl_interfaces::srv::GetParameters_Request;
using Response = rcl_interfaces::srv::GetParameters_Response;
};
} // namespace srv
} // namespace rcl_interfaces
#endif // RCL_INTERFACES__SRV__GET_PARAMETERS__STRUCT_HPP_
| 24.666667 | 66 | 0.83033 | Omnirobotic |
ca41bb0c2d80b5b3c21572c535cc09784b7bfccc | 7,477 | cc | C++ | Geometry/HGCalCommonData/src/HGCalParameters.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | Geometry/HGCalCommonData/src/HGCalParameters.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | Geometry/HGCalCommonData/src/HGCalParameters.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "Geometry/HGCalCommonData/interface/HGCalParameters.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "Geometry/HGCalCommonData/interface/HGCalWaferIndex.h"
//#define EDM_ML_DEBUG
HGCalParameters::HGCalParameters(const std::string& nam) : name_(nam), nCells_(0), waferMaskMode_(0) {
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Construct HGCalParameters for " << name_;
#endif
}
HGCalParameters::~HGCalParameters() {}
void HGCalParameters::fillModule(const HGCalParameters::hgtrap& mytr, bool reco) {
if (reco) {
moduleLayR_.emplace_back(mytr.lay);
moduleBlR_.emplace_back(mytr.bl);
moduleTlR_.emplace_back(mytr.tl);
moduleHR_.emplace_back(mytr.h);
moduleDzR_.emplace_back(mytr.dz);
moduleAlphaR_.emplace_back(mytr.alpha);
moduleCellR_.emplace_back(mytr.cellSize);
} else {
moduleLayS_.emplace_back(mytr.lay);
moduleBlS_.emplace_back(mytr.bl);
moduleTlS_.emplace_back(mytr.tl);
moduleHS_.emplace_back(mytr.h);
moduleDzS_.emplace_back(mytr.dz);
moduleAlphaS_.emplace_back(mytr.alpha);
moduleCellS_.emplace_back(mytr.cellSize);
}
}
HGCalParameters::hgtrap HGCalParameters::getModule(unsigned int k, bool reco) const {
HGCalParameters::hgtrap mytr;
if (reco) {
if (k < moduleLayR_.size()) {
mytr.lay = moduleLayR_[k];
mytr.bl = moduleBlR_[k];
mytr.tl = moduleTlR_[k];
mytr.h = moduleHR_[k];
mytr.dz = moduleDzR_[k];
mytr.alpha = moduleAlphaR_[k];
mytr.cellSize = moduleCellR_[k];
} else {
mytr.lay = -1;
mytr.bl = mytr.tl = mytr.h = mytr.dz = mytr.alpha = mytr.cellSize = 0;
}
} else {
if (k < moduleLayS_.size()) {
mytr.lay = moduleLayS_[k];
mytr.bl = moduleBlS_[k];
mytr.tl = moduleTlS_[k];
mytr.h = moduleHS_[k];
mytr.dz = moduleDzS_[k];
mytr.alpha = moduleAlphaS_[k];
mytr.cellSize = moduleCellS_[k];
} else {
mytr.lay = -1;
mytr.bl = mytr.tl = mytr.h = mytr.dz = mytr.alpha = mytr.cellSize = 0;
}
}
return mytr;
}
void HGCalParameters::fillTrForm(const HGCalParameters::hgtrform& mytr) {
int zp = (mytr.zp == 1) ? 1 : 0;
uint32_t indx = ((zp & kMaskZside) << kShiftZside);
indx |= ((mytr.lay & kMaskLayer) << kShiftLayer);
indx |= ((mytr.sec & kMaskSector) << kShiftSector);
indx |= ((mytr.subsec & kMaskSubSec) << kShiftSubSec);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "ZP " << zp << ":" << kMaskZside << ":" << kShiftZside
<< ((zp & kMaskZside) << kShiftZside) << " Lay " << mytr.lay << ":" << kMaskLayer << ":"
<< kShiftLayer << ":" << ((mytr.lay & kMaskLayer) << kShiftLayer) << " Sector "
<< mytr.sec << ":" << kMaskSector << ":" << kShiftSector << ":"
<< ((mytr.sec & kMaskSector) << kShiftSector) << " SubSec " << mytr.subsec << ":"
<< kMaskSubSec << ":" << kShiftSubSec << ":"
<< ((mytr.subsec & kMaskSubSec) << kShiftSubSec) << " Index " << std::hex << indx
<< std::dec;
#endif
trformIndex_.emplace_back(indx);
trformTranX_.emplace_back(mytr.h3v.x());
trformTranY_.emplace_back(mytr.h3v.y());
trformTranZ_.emplace_back(mytr.h3v.z());
trformRotXX_.emplace_back((std::abs(mytr.hr.xx()) > tol) ? mytr.hr.xx() : 0);
trformRotYX_.emplace_back((std::abs(mytr.hr.yx()) > tol) ? mytr.hr.yx() : 0);
trformRotZX_.emplace_back((std::abs(mytr.hr.zx()) > tol) ? mytr.hr.zx() : 0);
trformRotXY_.emplace_back((std::abs(mytr.hr.xy()) > tol) ? mytr.hr.xy() : 0);
trformRotYY_.emplace_back((std::abs(mytr.hr.yy()) > tol) ? mytr.hr.yy() : 0);
trformRotZY_.emplace_back((std::abs(mytr.hr.zy()) > tol) ? mytr.hr.zy() : 0);
trformRotXZ_.emplace_back((std::abs(mytr.hr.xz()) > tol) ? mytr.hr.xz() : 0);
trformRotYZ_.emplace_back((std::abs(mytr.hr.yz()) > tol) ? mytr.hr.yz() : 0);
trformRotZZ_.emplace_back((std::abs(mytr.hr.zz()) > tol) ? mytr.hr.zz() : 0);
#ifdef EDM_ML_DEBUG
unsigned int k = trformIndex_.size() - 1;
edm::LogVerbatim("HGCalGeom") << "HGCalParameters[" << k << "] Index " << std::hex << trformIndex_[k] << std::dec
<< " (" << mytr.zp << ", " << mytr.lay << ", " << mytr.sec << ", " << mytr.subsec
<< ") Translation (" << trformTranX_[k] << ", " << trformTranY_[k] << ", "
<< trformTranZ_[k] << ") Rotation (" << trformRotXX_[k] << ", " << trformRotYX_[k]
<< ", " << trformRotZX_[k] << ", " << trformRotXY_[k] << ", " << trformRotYY_[k] << ", "
<< trformRotZY_[k] << ", " << trformRotXZ_[k] << ", " << trformRotYZ_[k] << ", "
<< trformRotZZ_[k];
#endif
}
HGCalParameters::hgtrform HGCalParameters::getTrForm(unsigned int k) const {
HGCalParameters::hgtrform mytr;
if (k < trformIndex_.size()) {
const auto& id = getID(k);
mytr.zp = id[0];
mytr.lay = id[1];
mytr.sec = id[2];
mytr.subsec = id[3];
mytr.h3v = CLHEP::Hep3Vector(trformTranX_[k], trformTranY_[k], trformTranZ_[k]);
const CLHEP::HepRep3x3 rotation(trformRotXX_[k],
trformRotXY_[k],
trformRotXZ_[k],
trformRotYX_[k],
trformRotYY_[k],
trformRotYZ_[k],
trformRotZX_[k],
trformRotZY_[k],
trformRotZZ_[k]);
mytr.hr = CLHEP::HepRotation(rotation);
} else {
mytr.zp = mytr.lay = mytr.sec = mytr.subsec = 0;
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "HGCalParameters[" << k << "] Index " << std::hex << trformIndex_[k] << std::dec
<< " (" << mytr.zp << ", " << mytr.lay << ", " << mytr.sec << ", " << mytr.subsec
<< ") Translation (" << mytr.h3v.x() << ", " << mytr.h3v.y() << ", " << mytr.h3v.z()
<< ") Rotation (" << mytr.hr.xx() << ", " << mytr.hr.yx() << ", " << mytr.hr.zx()
<< ", " << mytr.hr.xy() << ", " << mytr.hr.yy() << ", " << mytr.hr.zy() << ", "
<< mytr.hr.xz() << ", " << mytr.hr.yz() << ", " << mytr.hr.zz();
#endif
return mytr;
}
void HGCalParameters::addTrForm(const CLHEP::Hep3Vector& h3v) {
unsigned int k = trformTranX_.size();
if (k > 0) {
trformTranX_[k - 1] += h3v.x();
trformTranY_[k - 1] += h3v.y();
trformTranZ_[k - 1] += h3v.z();
}
}
void HGCalParameters::scaleTrForm(double scale) {
unsigned int k = trformTranX_.size();
if (k > 0) {
trformTranX_[k - 1] *= scale;
trformTranY_[k - 1] *= scale;
trformTranZ_[k - 1] *= scale;
}
}
std::array<int, 4> HGCalParameters::getID(unsigned int k) const {
int zp = ((trformIndex_[k] >> kShiftZside) & kMaskZside);
if (zp != 1)
zp = -1;
int lay = ((trformIndex_[k] >> kShiftLayer) & kMaskLayer);
int sec = ((trformIndex_[k] >> kShiftSector) & kMaskSector);
int subsec = ((trformIndex_[k] >> kShiftSubSec) & kMaskSubSec);
return std::array<int, 4>{{zp, lay, sec, subsec}};
}
#include "FWCore/Utilities/interface/typelookup.h"
TYPELOOKUP_DATA_REG(HGCalParameters);
| 43.47093 | 120 | 0.547813 | ckamtsikis |
ca4561089a60eae8772f3015894f365b5a63d25f | 3,044 | cpp | C++ | PhotoSynthViewer/src/DynamicLines.cpp | dddExperiments/PhotoSynthToolkit | 4f81577ca347c30c9c142bad2e6edc278e38a4ca | [
"Unlicense",
"MIT"
] | 17 | 2015-02-10T17:44:42.000Z | 2021-07-13T01:07:37.000Z | PhotoSynthViewer/src/DynamicLines.cpp | Acidburn0zzz/PhotoSynthToolkit | 4f81577ca347c30c9c142bad2e6edc278e38a4ca | [
"Unlicense",
"MIT"
] | null | null | null | PhotoSynthViewer/src/DynamicLines.cpp | Acidburn0zzz/PhotoSynthToolkit | 4f81577ca347c30c9c142bad2e6edc278e38a4ca | [
"Unlicense",
"MIT"
] | 11 | 2015-01-15T04:21:40.000Z | 2017-06-12T09:24:47.000Z | ////http://www.ogre3d.org/tikiwiki/DynamicLineDrawing
#include "DynamicLines.h"
#include <Ogre.h>
#include <cassert>
#include <cmath>
using namespace Ogre;
enum {
POSITION_BINDING,
TEXCOORD_BINDING
};
DynamicLines::DynamicLines(OperationType opType)
{
initialize(opType,false);
setMaterial("BaseWhiteNoLighting");
mDirty = true;
}
DynamicLines::~DynamicLines()
{
}
void DynamicLines::setOperationType(OperationType opType)
{
mRenderOp.operationType = opType;
}
RenderOperation::OperationType DynamicLines::getOperationType() const
{
return mRenderOp.operationType;
}
void DynamicLines::addPoint(const Vector3 &p)
{
mPoints.push_back(p);
mDirty = true;
}
void DynamicLines::addPoint(Real x, Real y, Real z)
{
mPoints.push_back(Vector3(x,y,z));
mDirty = true;
}
const Vector3& DynamicLines::getPoint(unsigned short index) const
{
assert(index < mPoints.size() && "Point index is out of bounds!!");
return mPoints[index];
}
unsigned short DynamicLines::getNumPoints(void) const
{
return (unsigned short)mPoints.size();
}
void DynamicLines::setPoint(unsigned short index, const Vector3 &value)
{
assert(index < mPoints.size() && "Point index is out of bounds!!");
mPoints[index] = value;
mDirty = true;
}
void DynamicLines::clear()
{
mPoints.clear();
mDirty = true;
}
void DynamicLines::update()
{
if (mDirty) fillHardwareBuffers();
}
void DynamicLines::createVertexDeclaration()
{
VertexDeclaration *decl = mRenderOp.vertexData->vertexDeclaration;
decl->addElement(POSITION_BINDING, 0, VET_FLOAT3, VES_POSITION);
}
void DynamicLines::fillHardwareBuffers()
{
int size = mPoints.size();
prepareHardwareBuffers(size,0);
if (!size) {
mBox.setExtents(Vector3::ZERO,Vector3::ZERO);
mDirty=false;
return;
}
Vector3 vaabMin = mPoints[0];
Vector3 vaabMax = mPoints[0];
HardwareVertexBufferSharedPtr vbuf =
mRenderOp.vertexData->vertexBufferBinding->getBuffer(0);
Real *prPos = static_cast<Real*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
{
for(int i = 0; i < size; i++)
{
*prPos++ = mPoints[i].x;
*prPos++ = mPoints[i].y;
*prPos++ = mPoints[i].z;
if(mPoints[i].x < vaabMin.x)
vaabMin.x = mPoints[i].x;
if(mPoints[i].y < vaabMin.y)
vaabMin.y = mPoints[i].y;
if(mPoints[i].z < vaabMin.z)
vaabMin.z = mPoints[i].z;
if(mPoints[i].x > vaabMax.x)
vaabMax.x = mPoints[i].x;
if(mPoints[i].y > vaabMax.y)
vaabMax.y = mPoints[i].y;
if(mPoints[i].z > vaabMax.z)
vaabMax.z = mPoints[i].z;
}
}
vbuf->unlock();
mBox.setExtents(vaabMin, vaabMax);
mDirty = false;
}
/*
void DynamicLines::getWorldTransforms(Matrix4 *xform) const
{
// return identity matrix to prevent parent transforms
*xform = Matrix4::IDENTITY;
}
*/
/*
const Quaternion &DynamicLines::getWorldOrientation(void) const
{
return Quaternion::IDENTITY;
}
const Vector3 &DynamicLines::getWorldPosition(void) const
{
return Vector3::ZERO;
}
*/ | 21.138889 | 76 | 0.676084 | dddExperiments |
ca47311ad3f0177055e82ffce67aab26f62f4ec4 | 11,578 | hpp | C++ | simcore/simulation/library/default_params.hpp | lamsoa729/simcore | daf7056cb0c17563ed0f6bdee343fa1f6cd59729 | [
"MIT"
] | null | null | null | simcore/simulation/library/default_params.hpp | lamsoa729/simcore | daf7056cb0c17563ed0f6bdee343fa1f6cd59729 | [
"MIT"
] | null | null | null | simcore/simulation/library/default_params.hpp | lamsoa729/simcore | daf7056cb0c17563ed0f6bdee343fa1f6cd59729 | [
"MIT"
] | null | null | null | YAML::Node default_config;
default_config["species"]["num"] = "0";
default_config["species"]["insertion_type"] = "random";
default_config["species"]["insert_file"] = "none";
default_config["species"]["overlap"] = "0";
default_config["species"]["draw_type"] = "orientation";
default_config["species"]["color"] = "0";
default_config["species"]["posit_flag"] = "0";
default_config["species"]["spec_flag"] = "0";
default_config["species"]["checkpoint_flag"] = "0";
default_config["species"]["n_posit"] = "100";
default_config["species"]["n_spec"] = "100";
default_config["species"]["n_checkpoint"] = "10000";
default_config["filament"]["diameter"] = "1";
default_config["filament"]["length"] = "-1";
default_config["filament"]["persistence_length"] = "400";
default_config["filament"]["max_length"] = "500";
default_config["filament"]["min_bond_length"] = "1.5";
default_config["filament"]["spiral_flag"] = "0";
default_config["filament"]["spiral_number_fail_condition"] = "0";
default_config["filament"]["driving_factor"] = "0";
default_config["filament"]["friction_ratio"] = "2";
default_config["filament"]["dynamic_instability_flag"] = "0";
default_config["filament"]["force_induced_catastrophe_flag"] = "0";
default_config["filament"]["optical_trap_flag"] = "0";
default_config["filament"]["optical_trap_spring"] = "20";
default_config["filament"]["optical_trap_fixed"] = "0";
default_config["filament"]["cilia_trap_flag"] = "0";
default_config["filament"]["fic_factor"] = "0.828";
default_config["filament"]["f_shrink_to_grow"] = "0.017";
default_config["filament"]["f_shrink_to_pause"] = "0.0";
default_config["filament"]["f_pause_to_grow"] = "0.0";
default_config["filament"]["f_pause_to_shrink"] = "0.0";
default_config["filament"]["f_grow_to_pause"] = "0.0";
default_config["filament"]["f_grow_to_shrink"] = "0.00554";
default_config["filament"]["metric_forces"] = "1";
default_config["filament"]["v_poly"] = "0.44";
default_config["filament"]["v_depoly"] = "0.793";
default_config["filament"]["theta_analysis"] = "0";
default_config["filament"]["lp_analysis"] = "0";
default_config["filament"]["global_order_analysis"] = "0";
default_config["filament"]["packing_fraction"] = "-1";
default_config["filament"]["perlen_ratio"] = "-1";
default_config["filament"]["n_bonds"] = "-1";
default_config["filament"]["driving_method"] = "0";
default_config["filament"]["n_equil"] = "0";
default_config["filament"]["orientation_corr_analysis"] = "0";
default_config["filament"]["orientation_corr_n_steps"] = "1000";
default_config["filament"]["crossing_analysis"] = "0";
default_config["filament"]["intrinsic_curvature"] = "0";
default_config["filament"]["flagella_flag"] = "0";
default_config["filament"]["flagella_freq"] = "1";
default_config["filament"]["flagella_period"] = "2";
default_config["filament"]["flagella_amplitude"] = "1";
default_config["filament"]["flocking_analysis"] = "0";
default_config["filament"]["polydispersity_flag"] = "0";
default_config["filament"]["polydispersity_factor"] = "0.03";
default_config["filament"]["polydispersity_warn_on_truncate"] = "0";
default_config["passive_filament"]["diameter"] = "1";
default_config["passive_filament"]["length"] = "-1";
default_config["passive_filament"]["persistence_length"] = "400";
default_config["passive_filament"]["max_length"] = "500";
default_config["passive_filament"]["min_length"] = "1";
default_config["passive_filament"]["max_bond_length"] = "5";
default_config["passive_filament"]["min_bond_length"] = "1.5";
default_config["passive_filament"]["driving_factor"] = "0";
default_config["passive_filament"]["friction_ratio"] = "2";
default_config["passive_filament"]["metric_forces"] = "1";
default_config["passive_filament"]["theta_analysis"] = "0";
default_config["passive_filament"]["lp_analysis"] = "0";
default_config["passive_filament"]["packing_fraction"] = "-1";
default_config["passive_filament"]["perlen_ratio"] = "-1";
default_config["passive_filament"]["n_bonds"] = "-1";
default_config["hard_rod"]["diameter"] = "1";
default_config["hard_rod"]["length"] = "40";
default_config["hard_rod"]["min_length"] = "3";
default_config["hard_rod"]["max_length"] = "300";
default_config["hard_rod"]["max_bond_length"] = "5";
default_config["hard_rod"]["driving_factor"] = "0";
default_config["br_bead"]["diameter"] = "1";
default_config["br_bead"]["driving_factor"] = "0";
default_config["br_bead"]["packing_fraction"] = "-1";
default_config["md_bead"]["diameter"] = "1";
default_config["md_bead"]["mass"] = "1";
default_config["md_bead"]["driving_factor"] = "0";
default_config["centrosome"]["diameter"] = "10";
default_config["centrosome"]["n_filaments_min"] = "0";
default_config["centrosome"]["n_filaments_max"] = "10";
default_config["centrosome"]["fixed_spacing"] = "0";
default_config["centrosome"]["alignment_potential"] = "0";
default_config["centrosome"]["k_spring"] = "1000";
default_config["centrosome"]["k_align"] = "0";
default_config["centrosome"]["spring_length"] = "0";
default_config["motor"]["diameter"] = "3";
default_config["motor"]["walker"] = "0";
default_config["motor"]["step_direction"] = "0";
default_config["motor"]["k_off"] = "2";
default_config["motor"]["k_on"] = "10";
default_config["motor"]["concentration"] = "0";
default_config["motor"]["velocity"] = "1";
default_config["motor"]["diffusion_flag"] = "1";
default_config["motor"]["k_spring"] = "1000";
default_config["motor"]["f_spring_max"] = "100";
default_config["bead_spring"]["diameter"] = "1";
default_config["bead_spring"]["length"] = "40";
default_config["bead_spring"]["persistence_length"] = "4000";
default_config["bead_spring"]["max_bond_length"] = "1";
default_config["bead_spring"]["bond_rest_length"] = "0.8";
default_config["bead_spring"]["bond_spring"] = "100";
default_config["bead_spring"]["driving_factor"] = "0";
default_config["bead_spring"]["lp_analysis"] = "0";
default_config["bead_spring"]["theta_analysis"] = "0";
default_config["bead_spring"]["packing_fraction"] = "-1";
default_config["spherocylinder"]["diameter"] = "1";
default_config["spherocylinder"]["length"] = "5";
default_config["spherocylinder"]["diffusion_analysis"] = "0";
default_config["spherocylinder"]["n_diffusion_samples"] = "1";
default_config["spherocylinder"]["midstep"] = "0";
default_config["spindle"]["diameter"] = "10";
default_config["spindle"]["length"] = "20";
default_config["spindle"]["n_filaments_bud"] = "1";
default_config["spindle"]["n_filaments_mother"] = "0";
default_config["spindle"]["alignment_potential"] = "0";
default_config["spindle"]["k_spring"] = "1000";
default_config["spindle"]["k_align"] = "0";
default_config["spindle"]["spring_length"] = "0";
default_config["spindle"]["spb_diameter"] = "5";
default_config["crosslink"]["concentration"] = "0";
default_config["crosslink"]["diameter"] = "1";
default_config["crosslink"]["walker"] = "0";
default_config["crosslink"]["velocity"] = "1";
default_config["crosslink"]["diffusion_flag"] = "0";
default_config["crosslink"]["k_on"] = "10";
default_config["crosslink"]["k_off"] = "2";
default_config["crosslink"]["k_on_d"] = "10";
default_config["crosslink"]["k_off_d"] = "2";
default_config["crosslink"]["force_dep_factor"] = "1";
default_config["crosslink"]["polar_affinity"] = "0";
default_config["crosslink"]["k_spring"] = "10";
default_config["crosslink"]["f_spring_max"] = "1000";
default_config["crosslink"]["f_stall"] = "100";
default_config["crosslink"]["force_dep_vel_flag"] = "1";
default_config["crosslink"]["k_align"] = "0";
default_config["crosslink"]["rest_length"] = "0";
default_config["crosslink"]["step_direction"] = "0";
default_config["crosslink"]["tether_draw_type"] = "orientation";
default_config["crosslink"]["tether_diameter"] = "0.5";
default_config["crosslink"]["tether_color"] = "3.1416";
default_config["crosslink"]["end_pausing"] = "0";
default_config["crosslink"]["r_capture"] = "5";
default_config["seed"] = "7859459105545";
default_config["n_runs"] = "1";
default_config["n_random"] = "1";
default_config["run_name"] = "sc";
default_config["n_dim"] = "3";
default_config["n_periodic"] = "0";
default_config["boundary"] = "0";
default_config["system_radius"] = "100";
default_config["n_steps"] = "1000000";
default_config["i_step"] = "0";
default_config["delta"] = "0.001";
default_config["cell_length"] = "10";
default_config["n_update_cells"] = "0";
default_config["graph_flag"] = "0";
default_config["n_graph"] = "1000";
default_config["graph_diameter"] = "0";
default_config["graph_background"] = "1";
default_config["draw_boundary"] = "1";
default_config["load_checkpoint"] = "0";
default_config["checkpoint_run_name"] = "sc";
default_config["n_load"] = "0";
default_config["print_complete"] = "0";
default_config["insertion_type"] = "species";
default_config["movie_flag"] = "0";
default_config["movie_directory"] = "frames";
default_config["time_analysis"] = "0";
default_config["bud_height"] = "680";
default_config["bud_radius"] = "300";
default_config["lj_epsilon"] = "1";
default_config["wca_eps"] = "1";
default_config["wca_sig"] = "1";
default_config["ss_a"] = "1";
default_config["ss_rs"] = "1.5";
default_config["ss_eps"] = "1";
default_config["f_cutoff"] = "2000";
default_config["max_overlap"] = "100000";
default_config["constant_pressure"] = "0";
default_config["constant_volume"] = "0";
default_config["target_pressure"] = "0";
default_config["target_radius"] = "100";
default_config["pressure_time"] = "100";
default_config["compressibility"] = "1";
default_config["stoch_flag"] = "1";
default_config["thermo_flag"] = "0";
default_config["n_thermo"] = "1000";
default_config["interaction_flag"] = "1";
default_config["species_insertion_failure_threshold"] = "10000";
default_config["species_insertion_reattempt_threshold"] = "10";
default_config["uniform_crystal"] = "0";
default_config["n_steps_equil"] = "0";
default_config["n_steps_target"] = "100000";
default_config["static_particle_number"] = "0";
default_config["checkpoint_from_spec"] = "0";
default_config["potential"] = "wca";
default_config["soft_potential_mag"] = "10";
default_config["soft_potential_mag_target"] = "-1";
default_config["like_like_interactions"] = "1";
default_config["auto_graph"] = "0";
default_config["local_order_analysis"] = "0";
default_config["local_order_width"] = "50";
default_config["local_order_bin_width"] = "0.5";
default_config["local_order_average"] = "1";
default_config["local_order_n_analysis"] = "100";
default_config["density_analysis"] = "0";
default_config["density_bin_width"] = "0.1";
default_config["density_com_only"] = "0";
default_config["polar_order_analysis"] = "0";
default_config["polar_order_n_bins"] = "100";
default_config["polar_order_contact_cutoff"] = "3";
default_config["polar_order_color"] = "0";
default_config["overlap_analysis"] = "0";
default_config["highlight_overlaps"] = "0";
default_config["reduced"] = "0";
default_config["reload_reduce_switch"] = "0";
default_config["flock_polar_min"] = "0.5";
default_config["flock_contact_min"] = "1.5";
default_config["highlight_flock"] = "0";
default_config["flock_color_ext"] = "1.57";
default_config["flock_color_int"] = "4.71";
default_config["in_out_flag"] = "0";
| 50.121212 | 70 | 0.687856 | lamsoa729 |
ca476e6a035c65f65acd00770f2efc24acfec253 | 10,417 | cpp | C++ | fileIO.cpp | CherryPill/tex_edit | 6a0287f892068a44e60bd67d60a4b4272bbc3c60 | [
"MIT"
] | null | null | null | fileIO.cpp | CherryPill/tex_edit | 6a0287f892068a44e60bd67d60a4b4272bbc3c60 | [
"MIT"
] | null | null | null | fileIO.cpp | CherryPill/tex_edit | 6a0287f892068a44e60bd67d60a4b4272bbc3c60 | [
"MIT"
] | null | null | null | #include <windows.h>
#include <tchar.h>
#include <commctrl.h>
#include <richedit.h>
#include <iostream>
#include <string>
#include <atlstr.h>
#include <cassert>
#include "appconst.h"
#include "toolbarControl.h"
#include "statusControl.h"
#include "mainWindowProc.h"
#include "menuids.h"
#include "mainPrefs.h"
#include "fileIO.h"
#include "globalVars.h"
#include "recentFiles.h"
#include "translations.h"
#include "service.h"
//converts menuindex to vector index and gets the filename from the string vector
WPARAM convertMenu2VecIndex(WPARAM menuIndex) {
//use throw catch here if menuIndex<22
WPARAM vecIndex = recentDocsList.size()-(menuIndex-IDM_REC_CLEAR);
//WPARAM vecIndex = (menuIndex - IDM_REC_CLEAR - 1);
return vecIndex;
}
std::string getRecentlyOpenedFileName(WPARAM index) {
return recentDocsList.at(index);
}
int detectFileType(std::string strPath) {
int startingPos = strPath.length()-4-1;
return strPath.find("rtf",startingPos)==-1?1:2;
}
int getActivatedFileMode(void) {
return OPENMODE; //1 - txt, 2 - rtf.
}
LPCTSTR getCurrentlyOpenedFileName(void) {
return (LPCTSTR)currentlyOpenedFile;
}
DWORD CALLBACK EditStreamCallbackIn(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, PLONG pcb) {
HANDLE hFile = (HANDLE)dwCookie;
if (ReadFile(hFile, lpBuff, cb, (DWORD *)pcb, NULL)) {
return 0;
}
return -1;
}
DWORD CALLBACK EditStreamCallbackOut(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, PLONG pcb) {
HANDLE hFile = (HANDLE)dwCookie;
if (WriteFile(hFile, lpBuff, cb, (DWORD *)pcb, NULL)) {
return 0;
}
return -1;
}
void openFileDiag(HWND mainWindow, int mode) { //0 - open, 1 - save as {
int fileTypeSaveOpen = 0;
OPENFILENAME fileName;
TCHAR szFile[MAX_PATH];
ZeroMemory(&fileName, sizeof(fileName));
fileName.lStructSize = sizeof(fileName);
fileName.lpstrFile = szFile;
fileName.lpstrFile[0] = '\0';
fileName.hwndOwner = mainWindow;
fileName.nMaxFile = sizeof(szFile);
fileName.lpstrFilter = _T("Text Files (*.txt)\0*.txt\0RTF files (*.rtf)\0*.rtf*\0");
//_T("Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0");
fileName.nFilterIndex = OPENMODE; //1 - .txt, 2 - .rtf
if (mode) {
fileName.Flags =
OFN_PATHMUSTEXIST
| OFN_OVERWRITEPROMPT
| OFN_EXPLORER
| OFN_HIDEREADONLY;
}
else {
fileName.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
}
if (mode) {
if (GetSaveFileName(&fileName)) {
fileTypeSaveOpen = fileName.nFilterIndex;
loadSaveFile(fileName.lpstrFile,mode,fileTypeSaveOpen);
_tcscpy(currentlyOpenedFile, szFile);
SetWindowText(hwnd, getCurrentlyOpenedFileName());
changeStatusControlMessage(2);
fileChanged = false;
fileLoaded = true;
disableFastSaveIcon();
}
//usr canceled out
else {
fileChanged = true;
}
}
else {
if (GetOpenFileName(&fileName)) {
fileTypeSaveOpen = fileName.nFilterIndex;
loadSaveFile(fileName.lpstrFile,mode,fileTypeSaveOpen);
_tcscpy(currentlyOpenedFile,szFile);
SetWindowText(hwnd, getCurrentlyOpenedFileName());
changeStatusControlMessage(1);
fileLoaded = true;
fileChanged = false;
//append
if (!recentDocsList.size()) {
recentDocsList_push(getCurrentlyOpenedFileName(), 0);
}
//insert before currAddRecent-1
else {
recentDocsList_push(getCurrentlyOpenedFileName(), 1);
}
}
}
}
//stream mode: 1 - write to file, 0 - write to editor
void loadSaveFile(LPTSTR filePath, int streamMode, int fileType) {
streamMode?FillFileFromRichEdit((LPCTSTR(filePath)),fileType):FillRichEditFromFile((LPCTSTR)filePath,fileType);
}
//1 - txt, 2 - rtf
void FillRichEditFromFile(LPCTSTR pszFile, int fileType) {
//settings.recentDocsList.push_back(pszFile);
WPARAM OPENFILETYPE;
assert(fileType>0);
if (fileType == 1) {
OPENMODE = 1;
OPENFILETYPE = SF_TEXT;
}
else if (fileType == 2) {
OPENMODE = 2;
OPENFILETYPE = SF_RTF;
}
BOOL fSuccess = FALSE;
HANDLE hFile = CreateFile(pszFile, GENERIC_READ,
FILE_SHARE_READ, 0, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, NULL);
//file exists
if (hFile != INVALID_HANDLE_VALUE) {
EDITSTREAM es = {0}; //main stream structure
es.pfnCallback = EditStreamCallbackIn;
es.dwCookie = (DWORD_PTR)hFile;
if (SendMessage(richEditControl, EM_STREAMIN, OPENFILETYPE, (LPARAM)&es) && es.dwError == 0) {
fSuccess = TRUE;
}
CloseHandle(hFile);
//TODO change to string CA2T/CT2A
std::wstring str = CW2W(pszFile);
//incrementRecentDocs(str); non-functional
//setting titlebar text to file path
//TODO resolve for settings file
if (settings.bShowCompleteFilePathInTitle) {
setWindowTitleToFile(pszFile, 1);
}
else {
setWindowTitleToFile(pszFile, 0);
}
//cutoff
//txt clause block toolbar formatting
if (!OPENMODE) {
disableFormattingOptions();
}
else {
enableFormattingOptions();
}
//save pszFile to global tracker
}
else {
//if file isn't found
MessageBox(hwnd, commDlgMsgError_EN[1], commDlgMsgErrorCaptions_EN[0], MB_ICONERROR | MB_OK);
if (askForDeletion())
{
recentDocsList_delete(pszFile);
}
//TODO: Prompt to delete from the recent list of files
}
}
void saveFile(void)
{
//stub
}
void FillFileFromRichEdit(LPCTSTR pszFile, int fileType) {
WPARAM SAVEFILETYPE;
assert(fileType);
if (fileType == 1) {
_tcscat((wchar_t*)pszFile,txtExt); //appending extension
SAVEFILETYPE = SF_TEXT;
}
else if (fileType == 2) {
_tcscat((wchar_t*)pszFile, rtfExt);
SAVEFILETYPE = SF_RTF;
}
BOOL fSuccess = FALSE;
HANDLE hFile = CreateFile(pszFile, GENERIC_WRITE,
0, 0, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
EDITSTREAM es = { 0 }; //main stream structure
es.pfnCallback = EditStreamCallbackOut;
es.dwCookie = (DWORD_PTR)hFile;
if (SendMessage(richEditControl, EM_STREAMOUT, (CP_UTF8 << 16) | SF_USECODEPAGE | SF_TEXT, (LPARAM)&es) && es.dwError == 0)
{
fSuccess = TRUE;
}
//cursor goes back to normal here
CloseHandle(hFile);
_tcscpy(currentlyOpenedFile, pszFile);
}
else {
MessageBox(hwnd, commDlgMsgError_EN[0], commDlgMsgErrorCaptions_EN[0], MB_OK | MB_ICONERROR);
}
}
void silentSaving(void) {
//silentSaving();
//initWaitCursor();
FillFileFromRichEdit(getCurrentlyOpenedFileName(), getActivatedFileMode()); //EXPLICIT CALL BE CAREFUL HERE
//resetCursor();
//MessageBox(hwnd, _T("Silently saved"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
changeStatusControlMessage(3);
SetWindowText(hwnd, getCurrentlyOpenedFileName());
fileChanged = false;
fileSaved = true;
disableFastSaveIcon();
}
void setWindowTitleToFile(LPCTSTR filePath, int mode)
{
TCHAR titleAppend[126];
LPCTSTR *file;
//complete
if (mode) {
_tcscpy(titleAppend, filePath);
_tcscat(titleAppend, _T(" - TexEdit"));
}
else {
file = cutoffFileName(filePath);
_tcscpy(titleAppend,(const wchar_t*)file);
}
SetWindowText(hwnd, titleAppend);
}
LPCTSTR *cutoffFileName(LPCTSTR fullPath) {
wchar_t fileNameExt[CHAR_MAX];
wchar_t drive[CHAR_MAX];
wchar_t dir[CHAR_MAX];
wchar_t fileName[CHAR_MAX];
wchar_t ext[CHAR_MAX];
_wsplitpath(fullPath,drive,dir,fileName,ext);
//LPCTSTR *res = (LPCTSTR*)_tcsrchr((const wchar_t*)fullPath,(wchar_t)'\\');
//assert(res);
//res = (LPCTSTR*)_tcstok((wchar_t*)res,(const wchar_t*)'\\');
_tcscpy(fileNameExt,fileName);
_tcscat(fileNameExt,ext);
return (LPCTSTR*)fileNameExt;
}
//save as
void initSavingAsSequence(void) {
openFileDiag(hwnd,1);
}
void initSilentSavingSequence(void) {
if (fileLoaded) {
if (fileChanged) {
silentSaving();
}
}
else {
if (fileChanged) {
openFileDiag(hwnd, 1);
}
else {
MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
}
}
}
//1 - txt, 2 - rtf
void fromRecent::initOpeningSequence(LPCTSTR filePath,int mode) {
if (fileLoaded) {
if (fileChanged) {
if (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL) == IDYES) {
silentSaving();
}
else{
FillRichEditFromFile(filePath, mode);
}
}
else {
FillRichEditFromFile(filePath, mode);
}
}
else {
if (fileChanged) {
switch (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL)) {
case IDYES: {
openFileDiag(hwnd, 1);
break;
}
case IDNO: {
FillRichEditFromFile(filePath, mode);
break;
}
case IDCANCEL: {
break;
}
}
}
else {
FillRichEditFromFile(filePath, mode);
//MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
}
}
}
void normal::initOpeningSequence(void) {
if (fileLoaded) {
if (fileChanged) {
if (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL) == IDYES) {
silentSaving();
}
else {
openFileDiag(hwnd,0);
}
}
else {
openFileDiag(hwnd,0);
}
}
else {
if (fileChanged) {
switch (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL)) {
case IDYES: {
openFileDiag(hwnd, 1);
break;
}
case IDNO: {
openFileDiag(hwnd, 0);
break;
}
case IDCANCEL: {
break;
}
}
}
else {
openFileDiag(hwnd,0);
//MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
}
}
}
//1 - txt, 2 - rtf
void initNewSequence(int mode) {
if (fileLoaded) {
if (fileChanged) {
if (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL) == IDYES) {
silentSaving();
}
else {
activateRespMode(mode);
}
}
else {
activateRespMode(mode);
}
}
else {
//bug with multiple new instances
if (fileChanged) {
switch (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL)) {
case IDYES: {
openFileDiag(hwnd, 1);
break;
}
case IDNO: {
activateRespMode(mode);
break;
}
case IDCANCEL: {
break;
}
}
}
else {
//MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
activateRespMode(mode);
}
}
}
void activateRespMode(int mode) {
if (mode == 2) {
activateNewRTFMode();
}
else if (mode == 1) {
activateNewTXTMode();
}
fileLoaded = false;
fileChanged = false;
} | 25.657635 | 131 | 0.690698 | CherryPill |
ca4a77a1b2da371aac972238280ae172be951a37 | 3,487 | cc | C++ | src/algorithms/OnlinePolicyGradient.cc | olethrosdc/beliefbox | 44c0c160732b875f294a3f6d7f27e8f4cdf9602c | [
"OLDAP-2.3"
] | 4 | 2015-12-02T23:16:44.000Z | 2018-01-07T10:54:36.000Z | src/algorithms/OnlinePolicyGradient.cc | olethrosdc/beliefbox | 44c0c160732b875f294a3f6d7f27e8f4cdf9602c | [
"OLDAP-2.3"
] | 2 | 2015-12-02T19:47:57.000Z | 2018-10-14T13:08:40.000Z | src/algorithms/OnlinePolicyGradient.cc | olethrosdc/beliefbox | 44c0c160732b875f294a3f6d7f27e8f4cdf9602c | [
"OLDAP-2.3"
] | 4 | 2018-01-14T14:23:18.000Z | 2018-10-29T12:46:41.000Z | #include "OnlinePolicyGradient.h"
PolicyGradientActorCritic::PolicyGradientActorCritic(int n_states_, int n_actions_, real gamma_, real step_size_) :
n_states(n_states_),
n_actions(n_actions_),
gamma(gamma_),
step_size(step_size_),
critic(n_states, n_actions, gamma, 0.0, step_size),
policy(n_states, n_actions),
params(n_states, n_actions),
Q(n_states, n_actions)
{
Reset();
}
real PolicyGradientActorCritic::Observe(real reward, const int& next_state, const int& next_action)
{
real d = 0;
if (state >= 0) {
d = GradientUpdate(state, action); // not sure how much difference it makes to update the next state-action pair instead
//printf("%d %d %d %d%f\n", state, action, d);
Q(state, action) += step_size * (reward + gamma * Q(next_state, next_action) - Q(state, action));
}
critic.Observe(reward, next_state, next_action);
UpdatePolicy();
state = next_state;
action = next_action;
return d;
}
int PolicyGradientActorCritic::Act(real reward, const int& next_state)
{
policy.Observe(reward, next_state);
int next_action = policy.SelectAction();
Observe(reward, next_state, next_action);
return next_action;
}
real PolicyGradientActorCritic::GradientUpdate(int s, int a)
{
//real U = critic.getValue(s);
//real U = critic.getValue(s);
real U = Q(s,a);
printf("s:%d, a:%d: Q_w:%f Q_S:%f\n", s, a, U, critic.getValue(s,a));
real delta = 0;
for (int j=0; j<n_actions; ++j) {
real p_a = policy.getActionProbability(s, j);
real d_sj = 0;
if (j==a) {
d_sj = (1.0 - p_a) * U;
} else {
d_sj = -p_a * U;
}
params(s,j) += step_size * d_sj;
delta += fabs(d_sj);
}
return delta;
}
void PolicyGradientActorCritic::UpdatePolicy()
{
for (int s=0; s<n_states; ++s) {
Vector eW = exp(params.getRow(s));
eW /= eW.Sum();
Vector* pS = policy.getActionProbabilitiesPtr(s);
(*pS) = eW;
}
}
// --- PGAC with features --- //
PolicyGradientActorCriticPhi::PolicyGradientActorCriticPhi(BasisSet<Vector, int>& basis_,
int n_states_,
int n_actions_,
real gamma_,
real step_size_) :
basis(basis_),
n_states(n_states_),
n_actions(n_actions_),
gamma(gamma_),
step_size(step_size_),
critic(n_states, n_actions, basis, gamma),
policy(n_states, n_actions, basis), // bug?
params(basis.size())
{
Reset();
}
real PolicyGradientActorCriticPhi::Observe(real reward, const Vector& next_state, const int& next_action)
{
basis.Observe(action, reward, next_state);
real d = 0;
if (valid_state) {
d = GradientUpdate(state, action);
}
critic.Observe(reward, next_state, next_action);
UpdatePolicy();
state = next_state;
action = next_action;
valid_state = true;
return d;
}
int PolicyGradientActorCriticPhi::Act(real reward, const Vector& next_state)
{
basis.Observe(action, reward, next_state);
//Vector features = basis.F();
int next_action = policy.SelectAction(next_state);
Observe(reward, next_state, next_action);
return next_action;
}
real PolicyGradientActorCriticPhi::GradientUpdate(const Vector& s, int a)
{
basis.Observe(s);
Vector phi = basis.F();
// copy the state-features into a larger state-action feature vector
Vector features(phi.Size()*n_actions);
int k = a * phi.Size();
for (int i=0; i<phi.Size(); ++i) {
features(k) = phi(i);
}
real U = critic.getValue(s);
Vector delta = policy.GradientUpdate(s, a, U);
policy.GradientUpdateForward(delta, step_size);
return U;
}
void PolicyGradientActorCriticPhi::UpdatePolicy()
{
}
| 25.82963 | 122 | 0.691999 | olethrosdc |
ca4bc3210a0c2809539eaa960265b4e58b30bac2 | 1,386 | cpp | C++ | shared/source/os_interface/windows/os_time_win.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 778 | 2017-09-29T20:02:43.000Z | 2022-03-31T15:35:28.000Z | shared/source/os_interface/windows/os_time_win.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 478 | 2018-01-26T16:06:45.000Z | 2022-03-30T10:19:10.000Z | shared/source/os_interface/windows/os_time_win.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 215 | 2018-01-30T08:39:32.000Z | 2022-03-29T11:08:51.000Z | /*
* Copyright (C) 2018-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/os_interface/windows/os_time_win.h"
#include "shared/source/os_interface/windows/device_time_wddm.h"
#include "shared/source/os_interface/windows/wddm/wddm.h"
#include <memory>
#undef WIN32_NO_STATUS
namespace NEO {
bool OSTimeWin::getCpuTime(uint64_t *timeStamp) {
uint64_t time;
this->QueryPerfomanceCounterFnc((LARGE_INTEGER *)&time);
*timeStamp = static_cast<uint64_t>((static_cast<double>(time) * NSEC_PER_SEC / frequency.QuadPart));
return true;
};
std::unique_ptr<OSTime> OSTimeWin::create(OSInterface *osInterface) {
return std::unique_ptr<OSTime>(new OSTimeWin(osInterface));
}
OSTimeWin::OSTimeWin(OSInterface *osInterface) {
this->osInterface = osInterface;
Wddm *wddm = osInterface ? osInterface->getDriverModel()->as<Wddm>() : nullptr;
this->deviceTime = std::make_unique<DeviceTimeWddm>(wddm);
QueryPerformanceFrequency(&frequency);
}
double OSTimeWin::getHostTimerResolution() const {
double retValue = 0;
if (frequency.QuadPart) {
retValue = 1e9 / frequency.QuadPart;
}
return retValue;
}
uint64_t OSTimeWin::getCpuRawTimestamp() {
LARGE_INTEGER cpuRawTimestamp = {};
this->QueryPerfomanceCounterFnc(&cpuRawTimestamp);
return cpuRawTimestamp.QuadPart;
}
} // namespace NEO
| 26.653846 | 104 | 0.731602 | troels |
ca4d642184c5ad7b58e45fc1fe56cc8a443739d8 | 8,778 | hpp | C++ | Source/AllProjects/GraphicUtils/CIDGraphDev/CIDGraphDev_ImgCacheItem.hpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 216 | 2019-03-09T06:41:28.000Z | 2022-02-25T16:27:19.000Z | Source/AllProjects/GraphicUtils/CIDGraphDev/CIDGraphDev_ImgCacheItem.hpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 9 | 2020-09-27T08:00:52.000Z | 2021-07-02T14:27:31.000Z | Source/AllProjects/GraphicUtils/CIDGraphDev/CIDGraphDev_ImgCacheItem.hpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 29 | 2019-03-09T10:12:24.000Z | 2021-03-03T22:25:29.000Z | //
// FILE NAME: CIDCtrls_ImgCacheItem.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 10/28/2005
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the header for the CIDCtrls_ImgCacheItem.cpp file, which implements
// a simple image cache item that various programs may want to use (after
// extending) to create an image cache.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TImgCacheItem
// PREFIX: ici
// ---------------------------------------------------------------------------
class CIDGRDEVEXP TImgCacheItem : public TObject
{
public :
// -------------------------------------------------------------------
// Public, static methods
// -------------------------------------------------------------------
static const TString& strImgName
(
const TImgCacheItem& iciSrc
);
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TImgCacheItem
(
const TString& strImgName
, const tCIDLib::TBoolean bThumb
);
TImgCacheItem
(
const TString& strImgName
, const tCIDLib::TBoolean bThumb
, const tCIDLib::TCard4 c4Size
, const TBitmap& bmpData
, const tCIDLib::TBoolean bDeepCopy
);
TImgCacheItem
(
const TImgCacheItem& I_NsClientBindSearch
);
~TImgCacheItem();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TImgCacheItem& operator=
(
const TImgCacheItem& iciSrc
);
// -------------------------------------------------------------------
// Public, virtual methods
// -------------------------------------------------------------------
virtual tCIDLib::TVoid Reset
(
const TString& strImgName
, const tCIDLib::TBoolean bThumb
);
virtual tCIDLib::TVoid Set
(
const tCIDLib::TBoolean bThumb
, const tCIDLib::TCard4 c4Size
, const TMemBuf& mbufData
, const tCIDLib::TCard4 c4SerialNum
, const TGraphDrawDev& gdevCompat
);
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bHasAlpha() const;
tCIDLib::TBoolean bStillGood
(
const TString& strExpiresStamp
) const;
tCIDLib::TBoolean bThumb() const;
tCIDLib::TBoolean bTransparent() const;
const TBitmap& bmpImage() const;
const TBitmap& bmpMask() const;
tCIDLib::TCard4 c4SerialNum() const;
tCIDLib::TCard4 c4Size() const;
tCIDLib::TCard4 c4TransClr() const;
tCIDLib::TVoid DropImage();
tCIDLib::TEncodedTime enctLastAccess() const;
tCIDLib::TEncodedTime enctLastCheck() const;
tCIDLib::TEncodedTime enctGoodTill() const;
const TString& strExpiresStamp() const;
const TString& strExpiresStamp
(
const TString& strToSet
);
const TString& strImageName() const;
const TString& strTagData() const;
const TString& strTagData
(
const TString& strToSet
);
tCIDLib::TVoid SetLastAccess();
tCIDLib::TVoid SetLastCheck();
tCIDLib::TVoid SetGoodTill
(
const tCIDLib::TCard4 c4Seconds
);
const TSize& szImage() const;
protected :
// -------------------------------------------------------------------
// Protected, non-virtual methods
// -------------------------------------------------------------------
TBitmap& bmpWriteable();
private :
// -------------------------------------------------------------------
// Private data members
//
// m_bThumb
// Indicatse if this is a thumbnail or the full size image.
//
// m_bTrans
// Indicates if this a color based transparency image. If so, then the
// mask images are needed for drawing.
//
// m_bmpImage
// m_bmpMask
// The image and the mask for the image if it is transparent.
//
// m_c4Size
// The size of the original raw image data, so we'll know how much is
// required if we have to send it.
//
// m_enctLastAccess
// Updated each time the image is accessed, and used to do a least recently
// used algorithm if our cache gets full.
//
// m_enctLastCheck
// The last time that the client code checked to see if the image
// is still up to date with any external source. This can be
// used to prevent repeated checks when the image is accessed
// multipled times quickly.
//
// m_enctGoodTill
// In some cases, it's known that an image will be valid for some length of
// time, in which case this can be set and used to avoid re-validating the
// cached image for that period. Defaults to zero, which means it will by
// default never be good.
//
// m_c4TransClr
// If color transparency based (m_bTrans is true), then this is the color that
// was used to create the masks.
//
// m_strExpiresStamp
// This is used to store an expiration stamp, generally for use with HTTP
// servers, which may provide such a stamp. If it provides a max-age that
// will be set via the SetGoodTill and will override this. If the good till
// is zero, then we try this guy.
//
// m_strImageName
// The original name of the image, whihc is whatever is meaningful
// to the user of this class.
//
// m_strTagData
// This is for the use of the application, to store some kind of tag info.
//
// m_szImage
// Get the size out up front, since we have to return it fairly often, and
// the bitmap itself returns it by value, so we can be more efficient.
// -------------------------------------------------------------------
tCIDLib::TBoolean m_bThumb;
tCIDLib::TBoolean m_bTrans;
TBitmap m_bmpImage;
TBitmap m_bmpMask;
tCIDLib::TCard4 m_c4Size;
tCIDLib::TCard4 m_c4TransClr;
tCIDLib::TEncodedTime m_enctLastAccess;
tCIDLib::TEncodedTime m_enctLastCheck;
tCIDLib::TEncodedTime m_enctGoodTill;
TString m_strExpiresStamp;
TString m_strImageName;
TString m_strTagData;
TSize m_szImage;
// -------------------------------------------------------------------
// Magic Macros
// -------------------------------------------------------------------
RTTIDefs(TImgCacheItem,TObject)
};
// ---------------------------------------------------------------------------
// Define a counter pointer to an image cache object. This is what normally would be
// handed out to callers when they want to use an image. This insures that the image
// will not be dropped from the cache as long as someone is holding it.
// ---------------------------------------------------------------------------
using TImgCacheItemPtr = TCntPtr<TImgCacheItem>;
inline const TString&
strExtractImgCacheItemPtrKey(const TImgCacheItemPtr& cptrSrc)
{
return cptrSrc->strImageName();
}
#pragma CIDLIB_POPPACK
| 33.632184 | 91 | 0.460355 | MarkStega |
ca4e4af46741270dc90b75dead61f1b5a9950d97 | 1,869 | hh | C++ | dev/g++/projects/embedded/libhal/hardwares/raspberry_pi/include/digital_out.hh | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/projects/embedded/libhal/hardwares/raspberry_pi/include/digital_out.hh | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/projects/embedded/libhal/hardwares/raspberry_pi/include/digital_out.hh | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | 1 | 2017-01-27T12:53:50.000Z | 2017-01-27T12:53:50.000Z | /*!
* \file digital_out.hpp
* \brief Header file for digital out gpio state.
* \author garciay.yann@gmail.com
* \copyright Copyright (c) 2015 ygarcia. All rights reserved
* \license This project is released under the MIT License
* \version 0.1
*/
#pragma once
#include "libhal.h"
/*!
* \class digital_out
* \brief digital output gpio state
* @see ::digital_write
*/
class digital_out {
protected:
/*! The gpio idenifier */
pin_name _gpio;
/*! The gpio state */
digital_state_t _state;
public:
/*!
* \brief Constructor
* State is set to low
* \param[in] The gpio to connect
*/
digital_out(const pin_name p_gpio_name) : _gpio(p_gpio_name), _state(digital_state_t::digital_state_low) { ::digital_write(_gpio, _state); };
/*!
* \brief Constructor
* \param[in] The gpio to connect
* \param[in] p_state The gpio state
*/
digital_out(const pin_name p_gpio_name, const digital_state_t p_state) : _gpio(p_gpio_name), _state(p_state) { ::digital_write(_gpio, _state); };
/*!
* \brief Destructor
* The gpio state is set to low before to destroy this class reference
*/
virtual ~digital_out() { ::digital_write(_gpio, digital_state_t::digital_state_low); };
/*!
* \brief Set the gpio state
* \param[in] The new gpio state
*/
inline void write(const digital_state_t p_state) { _state = p_state; ::digital_write(_gpio, _state); };
/*!
* \brief Indicates the gpio state
* \return The gpio state
* @see digital_state_t
*/
inline digital_state_t read() const { return _state; };
inline digital_out & operator = (const digital_state_t p_state) { write(p_state); return *this; };
inline digital_out & operator = (const digital_out & p_gpio) { write(p_gpio.read()); return *this; };
inline operator const digital_state_t() const { return read(); };
}; // End of class digital_out
| 31.15 | 147 | 0.686998 | YannGarcia |
ca4ecd2046f969b2cd2bca17a94de63611e72c21 | 629 | cpp | C++ | Advance/weakPointer.cpp | iarjunphp/CPP-Learning | 4946f861cb3f57da2b0beba07a206fafe261aaf4 | [
"MIT"
] | 77 | 2019-10-28T05:38:51.000Z | 2022-03-15T01:53:48.000Z | Advance/weakPointer.cpp | iarjunphp/CPP-Learning | 4946f861cb3f57da2b0beba07a206fafe261aaf4 | [
"MIT"
] | 3 | 2019-12-26T15:39:55.000Z | 2020-10-29T14:55:50.000Z | Advance/weakPointer.cpp | iarjunphp/CPP-Learning | 4946f861cb3f57da2b0beba07a206fafe261aaf4 | [
"MIT"
] | 24 | 2020-01-08T04:12:52.000Z | 2022-03-12T22:26:07.000Z | //Memory get free as scope ends and this pointers can have copy of them.
#include<iostream>
#include<memory>
using namespace std;
class User{
public:
User(){
cout<<"User Created\n";
}
~User(){
cout<<"User Destroyed\n";
}
void testFunc(){
cout<<"I am a test function\n";
}
};
int main(){
{
shared_ptr<User> tim = make_shared<User>();
weak_ptr<User> wtim = tim; // Created a weak pointer
shared_ptr<User> yo = wtim.lock(); // Using weak pointer back to shared
yo->testFunc();
}
cout<<"Outside scope\n";
return 0;
} | 18.5 | 80 | 0.562798 | iarjunphp |
ca4ee9f21cccb988fd077c31a422a7e49c029121 | 1,656 | cpp | C++ | Edgyne/ResourceShaderProgram.cpp | AWDaM/Edgyne | e2c9d01efc3dd50e41f7cc31c407baa44ea77560 | [
"MIT"
] | 1 | 2019-02-07T12:11:21.000Z | 2019-02-07T12:11:21.000Z | Edgyne/ResourceShaderProgram.cpp | MaxitoSama/Edgyne | e2c9d01efc3dd50e41f7cc31c407baa44ea77560 | [
"MIT"
] | null | null | null | Edgyne/ResourceShaderProgram.cpp | MaxitoSama/Edgyne | e2c9d01efc3dd50e41f7cc31c407baa44ea77560 | [
"MIT"
] | 1 | 2019-02-04T16:08:36.000Z | 2019-02-04T16:08:36.000Z | #include "ResourceShaderProgram.h"
#include "Application.h"
#include "ModuleShaders.h"
#include "JSONManager.h"
ResourceShaderProgram::ResourceShaderProgram() : Resource(RES_SHADER)
{
}
ResourceShaderProgram::ResourceShaderProgram(std::string& file) : Resource(RES_SHADER, file)
{
}
ResourceShaderProgram::~ResourceShaderProgram()
{
}
bool ResourceShaderProgram::CompileShaderProgram()
{
bool ret = false;
uint tmp_program_index = 0;
std::vector<uint> indexList;
for (std::vector<uint>::iterator it = shaderObjects.begin(); it != shaderObjects.end(); it++)
{
bool isVertex = false;
char* data = App->shaders->FindShaderObjectFromUID(*it, isVertex);
uint index = 0;
if (App->shaders->CompileShader(data, isVertex, &index))
indexList.push_back(index);
}
if(App->shaders->CreateShaderProgram(indexList, &program));
ret = true;
return ret;
}
void ResourceShaderProgram::AddNewObjectToProgram(uint uuid)
{
bool isVertex = false;
if (App->shaders->FindShaderObjectFromUID(uuid, isVertex))
{
shaderObjects.push_back(uuid);
JSON_File* hmm = App->JSON_manager->openWriteFile(("Library\\ShaderPrograms\\" + file).c_str());
JSON_Value* val = hmm->createValue();
for (std::vector<uint>::iterator item = shaderObjects.begin(); item != shaderObjects.end(); item++)
{
val->addUint("uid", (*item));
}
hmm->addValue("", val);
hmm->Write();
hmm->closeFile();
CompileShaderProgram();
}
}
bool ResourceShaderProgram::ContainsShader(uint uuid)
{
for (std::vector<uint>::iterator item = shaderObjects.begin(); item != shaderObjects.end(); item++)
{
if ((*item) == uuid)
{
return true;
}
}
return false;
}
| 22.684932 | 101 | 0.705314 | AWDaM |
ca50210d620fbafe1195d40dbe1befc2c9b9bc34 | 4,235 | cc | C++ | mojo/public/cpp/bindings/lib/buffer.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | mojo/public/cpp/bindings/lib/buffer.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | mojo/public/cpp/bindings/lib/buffer.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2017 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 "mojo/public/cpp/bindings/lib/buffer.h"
#include <cstring>
#include "base/check_op.h"
#include "base/notreached.h"
#include "base/numerics/safe_math.h"
#include "mojo/public/c/system/message_pipe.h"
#include "mojo/public/cpp/bindings/lib/bindings_internal.h"
namespace mojo {
namespace internal {
Buffer::Buffer() = default;
Buffer::Buffer(void* data, size_t size, size_t cursor)
: data_(data), size_(size), cursor_(cursor) {
DCHECK(IsAligned(data_));
}
Buffer::Buffer(MessageHandle message,
size_t message_payload_size,
void* data,
size_t size)
: message_(message),
message_payload_size_(message_payload_size),
data_(data),
size_(size),
cursor_(0) {
DCHECK(IsAligned(data_));
}
Buffer::Buffer(Buffer&& other) {
*this = std::move(other);
}
Buffer::~Buffer() = default;
Buffer& Buffer::operator=(Buffer&& other) {
message_ = other.message_;
message_payload_size_ = other.message_payload_size_;
data_ = other.data_;
size_ = other.size_;
cursor_ = other.cursor_;
other.Reset();
return *this;
}
size_t Buffer::Allocate(size_t num_bytes) {
const size_t aligned_num_bytes = Align(num_bytes);
const size_t new_cursor = cursor_ + aligned_num_bytes;
if (new_cursor < cursor_ || (new_cursor > size_ && !message_.is_valid())) {
// Either we've overflowed or exceeded a fixed capacity.
NOTREACHED();
return 0;
}
if (new_cursor > size_) {
// If we have an underlying message object we can extend its payload to
// obtain more storage capacity.
DCHECK_LE(message_payload_size_, new_cursor);
size_t additional_bytes = new_cursor - message_payload_size_;
DCHECK(base::IsValueInRangeForNumericType<uint32_t>(additional_bytes));
uint32_t new_size;
MojoResult rv = MojoAppendMessageData(
message_.value(), static_cast<uint32_t>(additional_bytes), nullptr, 0,
nullptr, &data_, &new_size);
DCHECK_EQ(MOJO_RESULT_OK, rv);
message_payload_size_ = new_cursor;
size_ = new_size;
}
DCHECK_LE(new_cursor, size_);
size_t block_start = cursor_;
cursor_ = new_cursor;
// Ensure that all the allocated space is zeroed to avoid uninitialized bits
// leaking into messages.
//
// TODO(rockot): We should consider only clearing the alignment padding. This
// means being careful about generated bindings zeroing padding explicitly,
// which itself gets particularly messy with e.g. packed bool bitfields.
memset(static_cast<uint8_t*>(data_) + block_start, 0, aligned_num_bytes);
return block_start;
}
bool Buffer::AttachHandles(std::vector<ScopedHandle>* handles) {
DCHECK(message_.is_valid());
uint32_t new_size = 0;
MojoResult rv = MojoAppendMessageData(
message_.value(), 0, reinterpret_cast<MojoHandle*>(handles->data()),
static_cast<uint32_t>(handles->size()), nullptr, &data_, &new_size);
if (rv != MOJO_RESULT_OK)
return false;
size_ = new_size;
for (auto& handle : *handles)
ignore_result(handle.release());
handles->clear();
return true;
}
void Buffer::Seal() {
if (!message_.is_valid())
return;
// Ensure that the backing message has the final accumulated payload size.
DCHECK_LE(message_payload_size_, cursor_);
size_t additional_bytes = cursor_ - message_payload_size_;
DCHECK(base::IsValueInRangeForNumericType<uint32_t>(additional_bytes));
MojoAppendMessageDataOptions options;
options.struct_size = sizeof(options);
options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
void* data;
uint32_t size;
MojoResult rv = MojoAppendMessageData(message_.value(),
static_cast<uint32_t>(additional_bytes),
nullptr, 0, &options, &data, &size);
DCHECK_EQ(MOJO_RESULT_OK, rv);
message_ = MessageHandle();
message_payload_size_ = cursor_;
data_ = data;
size_ = size;
}
void Buffer::Reset() {
message_ = MessageHandle();
data_ = nullptr;
size_ = 0;
cursor_ = 0;
}
} // namespace internal
} // namespace mojo
| 29.823944 | 80 | 0.701299 | Yannic |
ca50ce561027673aaa46a0e358f312825d6f635a | 281 | cc | C++ | writing-concepts/type_simple.cc | HappyCerberus/article-cpp20-concepts | 986934bc91727dd8874a318822b5497dfa734d01 | [
"MIT"
] | 3 | 2021-09-17T06:29:40.000Z | 2022-03-21T08:33:35.000Z | writing-concepts/type_simple.cc | HappyCerberus/article-cpp20-concepts | 986934bc91727dd8874a318822b5497dfa734d01 | [
"MIT"
] | null | null | null | writing-concepts/type_simple.cc | HappyCerberus/article-cpp20-concepts | 986934bc91727dd8874a318822b5497dfa734d01 | [
"MIT"
] | null | null | null | #include <concepts>
template <typename T>
concept type_test = requires {
typename T::ElementType; // ElementType member type must exist
};
void function(type_test auto x) {}
struct X { using ElementType = int; };
int main() {
function(X{}); // OK
function(1); // Fails
}
| 17.5625 | 66 | 0.676157 | HappyCerberus |
ca53b5af6362ccb1835d4e7855d0d6c78abc5a1d | 4,886 | cc | C++ | deadeye/src/deadeye.cc | strykeforce/steamworks | 00083c9378191aaeaab3a5c94c3c47738dcc1431 | [
"MIT"
] | null | null | null | deadeye/src/deadeye.cc | strykeforce/steamworks | 00083c9378191aaeaab3a5c94c3c47738dcc1431 | [
"MIT"
] | null | null | null | deadeye/src/deadeye.cc | strykeforce/steamworks | 00083c9378191aaeaab3a5c94c3c47738dcc1431 | [
"MIT"
] | null | null | null | #include "deadeye.h"
#include <chrono>
#include <thread>
using namespace deadeye;
namespace {
constexpr auto NTGT_SLEEP_MS = std::chrono::milliseconds(10);
}
Deadeye::Deadeye(std::shared_ptr<cpptoml::table> config)
: logger_(spdlog::get("deadeye")),
link_(config),
boiler_camera_(config),
gear_camera_(config) {
LoadConfigSettings(config);
link_.Start();
}
/**
* Main loop for camera frame aquistion and processing.
*/
void Deadeye::Run() {
while (true) {
int mode = link_.GetMode();
if (mode != current_mode_) {
logger_->info("switching mode to: {}", mode);
SwitchMode(mode);
current_mode_ = mode;
}
switch (mode) {
case Link::Mode::boiler:
ProcessBoilerTarget();
break;
case Link::Mode::gear:
ProcessGearTarget();
break;
case Link::Mode::idle:
std::this_thread::sleep_for(NTGT_SLEEP_MS);
continue;
}
}
}
/**
* Switch active mode.
*/
void Deadeye::SwitchMode(int mode) {
switch (mode) {
case Link::Mode::boiler:
logger_->info("Deadeye switching to boiler camera capture");
SPDLOG_TRACE(logger_, "start StopCapture");
if (!boiler_camera_.IsConnected()) {
SPDLOG_TRACE(logger_, "start Connect");
boiler_camera_.Connect();
}
SPDLOG_TRACE(logger_, "start StartCapture");
boiler_camera_.StartCapture();
SPDLOG_TRACE(logger_, "done configuring camera");
break;
case Link::Mode::gear:
logger_->info("Deadeye switching to gear camera capture");
boiler_camera_.StopCapture();
if (!gear_camera_.IsConnected()) {
gear_camera_.Connect();
}
break;
case Link::Mode::idle:
logger_->info("deadeye mode set to idle");
boiler_camera_.StopCapture();
break;
default:
logger_->info("EnableCamera called with unknown mode");
}
}
/**
* Called in boiler mode after frame acquired.
*/
void Deadeye::ProcessBoilerTarget() {
#ifdef LOG_FPS
static int framerate_count = 0;
if (framerate_count == 0) {
fps_.Start();
}
if (framerate_count++ > display_framerate_int_) {
fps_.Stop();
logger_->info("FPS = {}", fps_.FramesPerSecond());
framerate_count = 0;
}
fps_.Update();
#endif
int centerline_error; // vertical target separation
int azimuth_error;
bool success = boiler_camera_.ProcessFrame(azimuth_error, centerline_error);
#ifdef DISPLAY_FRAME
boiler_camera_.DisplayFrame();
#endif
#ifdef LOG_BOILER
static int boiler_count = 0;
if (boiler_count++ > display_boiler_int_) {
logger_->info("boiler acquired = {}, azimuth = {}, centerline = {}",
success, azimuth_error, centerline_error);
boiler_count = 0;
}
#endif
if (success) {
link_.SendBoilerSolution(azimuth_error, centerline_error);
return;
}
// logger_->warn("boiler targets not visible");
link_.SendNoTarget();
std::this_thread::sleep_for(NTGT_SLEEP_MS);
}
void Deadeye::ProcessGearTarget() {
#ifdef LOG_FPS
static int framerate_count = 0;
if (framerate_count == 0) {
fps_.Start();
}
if (framerate_count++ > display_framerate_int_) {
fps_.Stop();
logger_->info("FPS = {}", fps_.FramesPerSecond());
framerate_count = 0;
}
fps_.Update();
#endif
int azimuth_error;
int target_height;
bool success = gear_camera_.ProcessFrame(azimuth_error, target_height);
#ifdef DISPLAY_FRAME
gear_camera_.DisplayFrame();
#endif
#ifdef LOG_GEAR
static int gear_count = 0;
if (gear_count++ > display_gear_int_) {
logger_->info("gear acquired = {}, azimuth = {}, target height = {}",
success, azimuth_error, target_height);
gear_count = 0;
}
#endif
if (success) {
link_.SendGearSolution(azimuth_error, target_height);
return;
}
link_.SendNoTarget();
std::this_thread::sleep_for(NTGT_SLEEP_MS);
}
void Deadeye::LoadConfigSettings(
const std::shared_ptr<cpptoml::table> config_in) {
assert(config_in);
auto config = config_in->get_table("DEADEYE")->get_table("DEBUG");
#ifdef LOG_FPS
auto framerate_opt = config->get_as<int>("framerate");
if (framerate_opt) {
display_framerate_int_ = *framerate_opt;
}
logger_->warn("logging framerate every {} frames", display_framerate_int_);
#else
logger_->info("framerate logging disabled");
#endif
#ifdef LOG_BOILER
auto boiler_opt = config->get_as<int>("boiler");
if (boiler_opt) {
display_boiler_int_ = *boiler_opt;
}
logger_->warn("logging boiler solution every {} frames", display_boiler_int_);
#else
logger_->info("boiler solution logging disabled");
#endif
#ifdef LOG_GEAR
auto gear_opt = config->get_as<int>("gear");
if (gear_opt) {
display_gear_int_ = *gear_opt;
}
logger_->warn("logging gear solution every {} frames", display_gear_int_);
#else
logger_->info("gear solution logging disabled");
#endif
}
| 24.80203 | 80 | 0.667826 | strykeforce |
ca5881fba3802ac4ba98016c3240c8399cc9dd2e | 1,341 | cpp | C++ | clang/test/CodeGen/xray-attributes-noxray-supported.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 305 | 2019-09-14T17:16:05.000Z | 2022-03-31T15:05:20.000Z | clang/test/CodeGen/xray-attributes-noxray-supported.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 14 | 2020-02-03T23:39:51.000Z | 2021-07-20T16:24:25.000Z | clang/test/CodeGen/xray-attributes-noxray-supported.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 24 | 2019-10-03T11:22:11.000Z | 2022-01-25T09:59:30.000Z | // We want to ensure that the "never instrument" attributes show up even if we
// explicitly turn off XRay instrumentation.
//
/// -fno-xray-instrument is the default. It does not produce a CC1 option.
// RUN: %clang_cc1 %s -std=c++11 -x c++ -emit-llvm -o - \
// RUN: -triple x86_64-unknown-linux-gnu | FileCheck %s
// RUN: %clang_cc1 %s -std=c++11 -x c++ -emit-llvm -o - \
// RUN: -triple arm-unknown-linux-gnu -target-abi apcs-gnu | FileCheck %s
// RUN: %clang_cc1 %s -std=c++11 -x c++ -emit-llvm -o - \
// RUN: -triple mips-unknown-linux-gnu | FileCheck %s
// RUN: %clang_cc1 %s -std=c++11 -x c++ -emit-llvm -o - \
// RUN: -triple mipsel-unknown-linux-gnu | FileCheck %s
// RUN: %clang_cc1 %s -std=c++11 -x c++ -emit-llvm -o - \
// RUN: -triple mips64-unknown-linux-gnu | FileCheck %s
// RUN: %clang_cc1 %s -std=c++11 -x c++ -emit-llvm -o - \
// RUN: -triple mips64el-unknown-linux-gnu | FileCheck %s
// RUN: %clang_cc1 %s -std=c++11 -x c++ -emit-llvm -o - \
// RUN: -triple powerpc64le-unknown-linux-gnu | FileCheck %s
[[clang::xray_always_instrument]] void foo() {
// CHECK: define void @_Z3foov() #0
}
[[clang::xray_never_instrument]] void bar() {
// CHECK: define void @_Z3barv() #1
}
// CHECK-NOT: #0 = {{.*}}"function-instrument"="xray-always"
// CHECK: #1 = {{.*}}"function-instrument"="xray-never"
| 43.258065 | 78 | 0.62789 | medismailben |
3ed13b1c9bb29b80e0cba4dc9cd4c777bf9e4993 | 3,942 | cpp | C++ | CLRS/BinaryTree/VerticalOrderTraversalofaBinaryTree.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | CLRS/BinaryTree/VerticalOrderTraversalofaBinaryTree.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | CLRS/BinaryTree/VerticalOrderTraversalofaBinaryTree.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | /*
Given the root of a binary tree, calculate the vertical order traversal of the binary tree.
For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).
The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.
Return the vertical order traversal of the binary tree.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation:
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.
Example 2:
Input: root = [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
1 is at the top, so it comes first.
5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.
Example 3:
Input: root = [1,2,3,4,6,5,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
0 <= Node.val <= 1000
*/
// we use bfs to get the position (column, row, value) of each node and while traversing the nodes, we push the {row,value} to
// the vector associated with the corresponding column idx.
// To avoid using sorted map, we remember the min and max column ever encountered
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
unordered_map<int, vector<pair<int,int>> > m; // map column idx to (row,value) pairs
vector<vector<int>> res;
int min_col = INT_MAX, max_col = INT_MIN;
typedef struct {
TreeNode *node;
int row;
int column;
} NODE_POS;
queue<NODE_POS> q;
if ( !root )
return res;
q.push({root,0,0});
while (!q.empty() )
{
int n = q.size();
for ( int i = 0; i < n; i++ )
{
auto t = q.front();
q.pop();
m[t.column].push_back({t.row,t.node->val});
min_col = min(min_col,t.column);
max_col = max(max_col,t.column);
if ( t.node->left )
{
q.push({t.node->left,t.row+1,t.column-1});
}
if ( t.node->right )
{
q.push({t.node->right,t.row+1,t.column+1});
}
}
}
for ( int idx = min_col; idx <= max_col; idx++ )
{
if ( m.count(idx) )
{
sort(m[idx].begin(),m[idx].end());
vector<int> col_vals;
for ( auto t : m[idx] )
col_vals.push_back(t.second);
res.push_back(col_vals);
}
}
return res;
}
}; | 32.85 | 285 | 0.567732 | ComputerProgrammerStorager |
3ed2d85ac6c2faae68b56853b75323c487a384f8 | 8,578 | cpp | C++ | firmware-usbhost/common/http/test/HttpRequestParserTest.cpp | Zzzzipper/cppprojects | e9c9b62ca1e411320c24a3d168cab259fa2590d3 | [
"MIT"
] | null | null | null | firmware-usbhost/common/http/test/HttpRequestParserTest.cpp | Zzzzipper/cppprojects | e9c9b62ca1e411320c24a3d168cab259fa2590d3 | [
"MIT"
] | 1 | 2021-09-03T13:03:20.000Z | 2021-09-03T13:03:20.000Z | firmware-usbhost/common/http/test/HttpRequestParserTest.cpp | Zzzzipper/cppprojects | e9c9b62ca1e411320c24a3d168cab259fa2590d3 | [
"MIT"
] | null | null | null | #include "test/include/Test.h"
#include "http/HttpRequestParser.h"
#include "logger/include/Logger.h"
namespace Http {
class RequestParserTest : public TestSet {
public:
RequestParserTest();
bool testOK();
bool testBrokenHeader();
bool testCuttedData();
};
TEST_SET_REGISTER(Http::RequestParserTest);
RequestParserTest::RequestParserTest() {
TEST_CASE_REGISTER(RequestParserTest, testOK);
#if 0
TEST_CASE_REGISTER(RequestParserTest, testBrokenHeader);
TEST_CASE_REGISTER(RequestParserTest, testCuttedData);
#endif
}
/*
=== CreateAutomatModel =========================
POST /api/1.0/automat/Automat.php?action=CreateAutomatModel&_dc=1539090316532 HTTP/1.1
Host: devs.ephor.online
Connection: keep-alive
Content-Length: 24
Origin: https://devs.ephor.online
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
Content-Type: application/json
Accept: *//*
Referer: https://devs.ephor.online/client/index.html
Accept-Encoding: gzip, deflate, br
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Cookie: _ym_uid=1500301628417188656; PHPSESSID=au3fdendice73jro126183e38l
{"name":"1234","type":0}
*/
bool RequestParserTest::testOK() {
Http::RequestParser parser;
Request2 req;
StringBuilder serverName(64, 64);
StringBuilder serverPath(256, 256);
StringBuilder phpSessionId(64, 64);
StringBuilder reqData(1024, 1024);
req.serverName = &serverName;
req.serverPath = &serverPath;
req.phpSessionId = &phpSessionId;
req.data = &reqData;
parser.start(&req);
TEST_NUMBER_EQUAL(1024, parser.getBufSize());
TEST_NUMBER_EQUAL(0, parser.isComplete());
// TEST_NUMBER_EQUAL(Http::Response::Status_Unknown, req.statusCode);
const char *part1 =
"POST /api/1.0/automat/Automat.php?action=CreateAutomatModel&_dc=1539090316532 HTTP/1.1\r\n"
"Host: devs.ephor.online\r\n"
"Connection: keep-alive\r\n"
"Content-Le";
uint16_t part1Len = strlen(part1);
memcpy(parser.getBuf(), part1, part1Len);
parser.parseData(part1Len);
TEST_NUMBER_EQUAL(1014, parser.getBufSize());
TEST_NUMBER_EQUAL(0, parser.isComplete());
// TEST_NUMBER_EQUAL(Http::Response::Status_OK, req.statusCode);
const char *part2 =
"ngth: 24\r\n"
"Origin: https://devs.ephor.online\r\n"
"X-Requested-With: XMLHttpRequest\r\n"
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36\r\n"
"Content-Type: application/json\r\n"
"Accept: */*\r\n"
"Referer: https://devs.ephor.online/client/index.html\r\n"
"Accept-Encoding: gzip, deflate, br\r\n"
"Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7\r\n";
uint16_t part2Len = strlen(part2);
memcpy(parser.getBuf(), part2, part2Len);
parser.parseData(part2Len);
TEST_NUMBER_EQUAL(1024, parser.getBufSize());
TEST_NUMBER_EQUAL(0, parser.isComplete());
// TEST_NUMBER_EQUAL(Http::Response::Status_OK, req.statusCode);
const char *part3 =
"Cookie: _ym_uid=1500301628417188656; PHPSESSID=au3fdendice73jro126183e38l\r\n"
"\r\n"
"{\"name\":\"1234\",\"type\":0}";
uint16_t part3Len = strlen(part3);
memcpy(parser.getBuf(), part3, part3Len);
parser.parseData(part3Len);
TEST_NUMBER_EQUAL(1000, parser.getBufSize());
TEST_NUMBER_EQUAL(1, parser.isComplete());
TEST_NUMBER_EQUAL(Http::Request::Method_POST, req.method);
TEST_SUBSTR_EQUAL("devs.ephor.online", serverName.getString(), serverName.getLen());
TEST_NUMBER_EQUAL(80, req.serverPort);
TEST_SUBSTR_EQUAL("/api/1.0/automat/Automat.php?action=CreateAutomatModel&_dc=1539090316532", serverPath.getString(), serverPath.getLen());
TEST_NUMBER_EQUAL(24, req.contentLength);
TEST_NUMBER_EQUAL(0, req.rangeFrom);
TEST_NUMBER_EQUAL(0, req.rangeTo);
TEST_SUBSTR_EQUAL("au3fdendice73jro126183e38l", phpSessionId.getString(), phpSessionId.getLen());
TEST_SUBSTR_EQUAL("{\"name\":\"1234\",\"type\":0}", reqData.getString(), reqData.getLen());
return true;
}
#if 0
bool RequestParserTest::testBrokenHeader() {
Http::RequestParser parser;
Response resp;
StringBuilder phpSessionId(64, 64);
StringBuilder respData(1024, 1024);
resp.phpSessionId = &phpSessionId;
resp.data = &respData;
parser.start(&resp);
TEST_NUMBER_EQUAL(1024, parser.getBufSize());
TEST_NUMBER_EQUAL(0, parser.haveData());
TEST_NUMBER_EQUAL(0, parser.isComplete());
TEST_NUMBER_EQUAL(Http::Response::Status_Unknown, resp.statusCode);
const char *part1 =
"0123456789ABCDE\r\n"
"Server: nginx/1.9.5\r\n"
"Date: Sun, 24 Jan 2016 10:00:04 GMT\r\n"
"Content-Ty";
uint16_t part1Len = strlen(part1);
memcpy(parser.getBuf(), part1, part1Len);
parser.parseData(part1Len);
TEST_NUMBER_EQUAL(1014, parser.getBufSize());
TEST_NUMBER_EQUAL(0, parser.haveData());
TEST_NUMBER_EQUAL(0, parser.isComplete());
TEST_NUMBER_EQUAL(Http::Response::Status_ParserError, resp.statusCode);
const char *part2 =
"pe: text/html\r\n"
"Content-Length: 16\r\n"
"Content-Range: bytes 0-256/1024\r\n"
"Connection: keep-alive\r\n"
"Keep-Alive: timeout=30\r\n"
"X-Powered-By: PHP/5.5.31\r\n"
"Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n"
"Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n"
"Pragma: no-cache\r\n";
uint16_t part2Len = strlen(part2);
memcpy(parser.getBuf(), part2, part2Len);
parser.parseData(part2Len);
TEST_NUMBER_EQUAL(1014, parser.getBufSize());
TEST_NUMBER_EQUAL(0, parser.haveData());
TEST_NUMBER_EQUAL(0, parser.isComplete());
TEST_NUMBER_EQUAL(Http::Response::Status_ParserError, resp.statusCode);
const char *part3 =
"Set-Cookie: PHPSESSID=8a4bb025730a7f81fec32d9358c0e005; expires=Sun, 24-Jan-2016 12:00:04 GMT; Max-Age=7200; path=/\r\n"
"\r\n"
"{\"success\":true}";
uint16_t part3Len = strlen(part3);
memcpy(parser.getBuf(), part3, part3Len);
parser.parseData(part3Len);
TEST_NUMBER_EQUAL(1014, parser.getBufSize());
TEST_NUMBER_EQUAL(0, parser.haveData());
TEST_NUMBER_EQUAL(0, parser.isComplete());
TEST_NUMBER_EQUAL(Http::Response::Status_ParserError, resp.statusCode);
TEST_NUMBER_EQUAL(0, resp.contentLength);
TEST_NUMBER_EQUAL(0, resp.rangeFrom);
TEST_NUMBER_EQUAL(0, resp.rangeTo);
TEST_NUMBER_EQUAL(0, resp.rangeLength);
TEST_SUBSTR_EQUAL("", (const char*)phpSessionId.getData(), phpSessionId.getLen());
return true;
}
bool RequestParserTest::testCuttedData() {
Http::RequestParser parser;
Response resp;
StringBuilder phpSessionId(64, 64);
StringBuilder respData(1024, 1024);
resp.phpSessionId = &phpSessionId;
resp.data = &respData;
parser.start(&resp);
TEST_NUMBER_EQUAL(1024, parser.getBufSize());
TEST_NUMBER_EQUAL(0, parser.haveData());
TEST_NUMBER_EQUAL(0, parser.isComplete());
TEST_NUMBER_EQUAL(Http::Response::Status_Unknown, resp.statusCode);
const char *part1 =
"HTTP/1.1 200 OK\r\n"
"Server: nginx/1.9.5\r\n"
"Date: Sun, 24 Jan 2016 10:00:04 GMT\r\n"
"Content-Ty";
uint16_t part1Len = strlen(part1);
memcpy(parser.getBuf(), part1, part1Len);
parser.parseData(part1Len);
TEST_NUMBER_EQUAL(1014, parser.getBufSize());
TEST_NUMBER_EQUAL(0, parser.haveData());
TEST_NUMBER_EQUAL(0, parser.isComplete());
TEST_NUMBER_EQUAL(Http::Response::Status_OK, resp.statusCode);
const char *part2 =
"pe: text/html\r\n"
"Content-Length: 16\r\n"
"Content-Range: bytes 0-256/1024\r\n"
"Connection: keep-alive\r\n"
"Keep-Alive: timeout=30\r\n"
"X-Powered-By: PHP/5.5.31\r\n"
"Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n"
"Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n"
"Pragma: no-cache\r\n";
uint16_t part2Len = strlen(part2);
memcpy(parser.getBuf(), part2, part2Len);
parser.parseData(part2Len);
TEST_NUMBER_EQUAL(1024, parser.getBufSize());
TEST_NUMBER_EQUAL(0, parser.haveData());
TEST_NUMBER_EQUAL(0, parser.isComplete());
TEST_NUMBER_EQUAL(Http::Response::Status_OK, resp.statusCode);
const char *part3 =
"Set-Cookie: PHPSESSID=8a4bb025730a7f81fec32d9358c0e005; expires=Sun, 24-Jan-2016 12:00:04 GMT; Max-Age=7200; path=/\r\n"
"\r\n"
"{\"succe";
uint16_t part3Len = strlen(part3);
memcpy(parser.getBuf(), part3, part3Len);
parser.parseData(part3Len);
TEST_NUMBER_EQUAL(0, parser.haveData());
TEST_NUMBER_EQUAL(0, parser.isComplete());
TEST_NUMBER_EQUAL(Http::Response::Status_OK, resp.statusCode);
TEST_NUMBER_EQUAL(16, resp.contentLength);
TEST_NUMBER_EQUAL(0, resp.rangeFrom);
TEST_NUMBER_EQUAL(256, resp.rangeTo);
TEST_NUMBER_EQUAL(1024, resp.rangeLength);
TEST_SUBSTR_EQUAL("8a4bb025730a7f81fec32d9358c0e005", (const char*)phpSessionId.getData(), phpSessionId.getLen());
return true;
}
#endif
}
| 35.593361 | 140 | 0.74283 | Zzzzipper |
3ed2eb204e2073743d504a19a840d0dc62dbf63c | 2,715 | hpp | C++ | src/time/clocks.hpp | iamantony/CppNotes | 2707db6560ad80b0e5e286a04b2d46e5c0280b3f | [
"MIT"
] | 2 | 2020-07-31T14:13:56.000Z | 2021-02-03T09:51:43.000Z | src/time/clocks.hpp | iamantony/CppNotes | 2707db6560ad80b0e5e286a04b2d46e5c0280b3f | [
"MIT"
] | 28 | 2015-09-22T07:38:21.000Z | 2018-10-02T11:00:58.000Z | src/time/clocks.hpp | iamantony/CppNotes | 2707db6560ad80b0e5e286a04b2d46e5c0280b3f | [
"MIT"
] | 2 | 2018-10-11T14:10:50.000Z | 2021-02-27T08:53:50.000Z | #ifndef CLOCKS_HPP
#define CLOCKS_HPP
#include <chrono>
#include <iomanip>
#include <ratio>
#include <thread>
#include <iostream>
// http://www.modernescpp.com/index.php/the-three-clocks
using namespace std::chrono_literals;
namespace Time {
void GetCurrentTime() {
// Get time as time_point
auto systemNow = std::chrono::system_clock::now();
// Convert time_point into time_t
auto systemNowTime = std::chrono::system_clock::to_time_t(systemNow);
// Print current time using specified format
const char* timeFormat = "%d.%m.%Y %H:%M:%S";
std::cout << "Current time by system clock: " <<
std::put_time(std::localtime(&systemNowTime), timeFormat) <<
std::endl;
}
template <typename T>
void printRatio(){
std::cout << " precision: " << T::num << "/" << T::den << " second " <<
std::endl;
typedef typename std::ratio_multiply<T,std::kilo>::type MillSec;
typedef typename std::ratio_multiply<T,std::mega>::type MicroSec;
std::cout << std::fixed;
std::cout << " " <<
static_cast<double>(MillSec::num)/MillSec::den <<
" milliseconds " << std::endl;
std::cout << " " <<
static_cast<double>(MicroSec::num)/MicroSec::den <<
" microseconds " << std::endl;
}
void ClocksPeriod() {
std::cout << std::boolalpha << std::endl;
std::cout << "std::chrono::system_clock: " << std::endl;
std::cout << " is steady: " << std::chrono::system_clock::is_steady <<
std::endl;
printRatio<std::chrono::system_clock::period>();
std::cout << std::endl;
std::cout << "std::chrono::steady_clock: " << std::endl;
std::cout << " is steady: " << std::chrono::steady_clock::is_steady <<
std::endl;
printRatio<std::chrono::steady_clock::period>();
std::cout << std::endl;
std::cout << "std::chrono::high_resolution_clock: " << std::endl;
std::cout << " is steady: " <<
std::chrono::high_resolution_clock::is_steady << std::endl;
printRatio<std::chrono::high_resolution_clock::period>();
std::cout << std::endl;
}
void BenchmarkSomeOperation() {
auto someOperation = []() {
std::this_thread::sleep_for(1s);
};
auto start = std::chrono::high_resolution_clock::now();
someOperation();
auto stop = std::chrono::high_resolution_clock::now();
std::cout << "someOperation() took " <<
std::chrono::duration<double>(stop-start).count() <<
"ms" << std::endl;
}
void Start() {
GetCurrentTime();
ClocksPeriod();
BenchmarkSomeOperation();
}
}
#endif // CLOCKS_HPP
| 29.193548 | 77 | 0.586372 | iamantony |
3ed725ac4b32401f87bd86a1995073255f51c22c | 3,231 | cpp | C++ | robot_challenge/lib/Robot/Robot.cpp | matheusns/Oficina_RAS | 2bc685a920b1f2424b5d47f36f996019e836800e | [
"BSD-3-Clause"
] | null | null | null | robot_challenge/lib/Robot/Robot.cpp | matheusns/Oficina_RAS | 2bc685a920b1f2424b5d47f36f996019e836800e | [
"BSD-3-Clause"
] | null | null | null | robot_challenge/lib/Robot/Robot.cpp | matheusns/Oficina_RAS | 2bc685a920b1f2424b5d47f36f996019e836800e | [
"BSD-3-Clause"
] | null | null | null | #include <Robot.hpp>
namespace ras
{
Robot::Robot(PinName front_sensor_pin, PinName right_sensor_pin, PinName left_sensor_pin)
: serial_monitor_(USBTX, USBRX)
, right_motor_(NULL)
, left_motor_(NULL)
, front_sensor_(front_sensor_pin)
, left_sensor_(left_sensor_pin)
, right_sensor_(right_sensor_pin)
{
}
Robot::~Robot()
{
if (right_motor_ != NULL) delete right_motor_;
if (left_motor_ != NULL) delete left_motor_;
}
void Robot::setRightMotorPin(PinName inA, PinName pwm, PinName inB)
{
right_motor_ = new Motor();
right_motor_->setPinInA(inA);
right_motor_->setPinInB(inB);
right_motor_->setPinPwm(pwm);
}
void Robot::setLeftMotorPin(PinName inA, PinName pwm, PinName inB)
{
left_motor_ = new Motor();
left_motor_->setPinInA(inA);
left_motor_->setPinInB(inB);
left_motor_->setPinPwm(pwm);
}
void Robot::setSensorsLimiar(const float limiar)
{
this->limiar_ = limiar;
}
Direction Robot::move()
{
if (front_sensor_.read() > limiar_)
{
// serial_monitor_.printf("Front value %f !\n", front_sensor_.read());
moveFront();
return ras::FRONT;
}
else if (right_sensor_.read() > limiar_)
{
// serial_monitor_.printf("Right value %f !\n", right_sensor_.read());
moveRight();
return ras::RIGHT;
}
else if (left_sensor_.read() > limiar_)
{
// serial_monitor_.printf("Left value %f !\n", left_sensor_.read());
moveLeft();
return ras::LEFT;
}
else
{
moveBack();
return ras::BACK;
}
}
void Robot::moveFront()
{
if (right_motor_ != NULL && left_motor_ != NULL)
{
// serial_monitor_.printf("Moving to Front\n");
// serial_monitor_.printf("Left Forward - Right Forward\n");
right_motor_->accelerate( float(front_sensor_.read()) );
left_motor_->accelerate( float(front_sensor_.read()) );
right_motor_->moveForward();
left_motor_->moveForward();
}
}
void Robot::moveLeft()
{
if (right_motor_ != NULL && left_motor_ != NULL)
{
// serial_monitor_.printf("Moving to Left\n");
// serial_monitor_.printf("Left Stop - Right Forward\n");
right_motor_->accelerate( float(right_sensor_.read()) );
left_motor_->accelerate( float(right_sensor_.read()) );
right_motor_->moveForward();
left_motor_->stop();
}
}
void Robot::moveRight()
{
if (right_motor_ != NULL && left_motor_ != NULL)
{
// serial_monitor_.printf("Moving to Right\n");
// serial_monitor_.printf("Right Stop - Left Forward\n");
right_motor_->accelerate( float(left_sensor_.read()));
left_motor_->accelerate( float(left_sensor_.read()));
right_motor_->stop();
left_motor_->moveForward();
}
}
void Robot::moveBack()
{
if (right_motor_ != NULL && left_motor_ != NULL)
{
// serial_monitor_.printf("Moving to Back\n");
right_motor_->accelerate( float(left_sensor_.read())/2.0 );
left_motor_->accelerate( float(left_sensor_.read())/2.0 );
right_motor_->moveBack();
left_motor_->moveBack();
}
}
} | 24.853846 | 89 | 0.616837 | matheusns |
3ed9a6c408dc734a8c3d629d808faf7a0e5410e7 | 6,784 | hpp | C++ | include/cpp_mould/constexpr_driver.hpp | HeroicKatora/mould | d6f39f76f092197e950c4abf18af3a6bb4945fab | [
"BSD-3-Clause"
] | 3 | 2018-03-04T12:46:10.000Z | 2021-08-06T00:09:59.000Z | include/cpp_mould/constexpr_driver.hpp | HeroicKatora/mould | d6f39f76f092197e950c4abf18af3a6bb4945fab | [
"BSD-3-Clause"
] | null | null | null | include/cpp_mould/constexpr_driver.hpp | HeroicKatora/mould | d6f39f76f092197e950c4abf18af3a6bb4945fab | [
"BSD-3-Clause"
] | null | null | null | #ifndef CPP_MOULD_CONSTEXPR_DRIVER_HPP
#define CPP_MOULD_CONSTEXPR_DRIVER_HPP
#include <tuple>
#include "argument.hpp"
#include "engine.hpp"
#include "format.hpp"
#include "format_info.hpp"
namespace mould::internal::constexpr_driver {
/* Resolved expression representation */
template<size_t N>
struct ExpressionInformation {
int indices[N];
};
template<typename T>
struct TypedArgumentExpression {
int argument_index;
FormattingResult (*function)(const T&, Formatter);
FullOperation operation;
constexpr TypedArgumentExpression initialize(FullOperation operation) {
const auto info = TypedFormatterInformation<T>::get(operation);
return { argument_index, info.function, operation };
}
};
struct LiteralExpression {
size_t offset, length;
constexpr LiteralExpression initialize(FullOperation operation) {
return { operation.literal.offset, operation.literal.length };
}
};
template<typename T>
constexpr auto _expression_data()
-> ExpressionInformation<std::size(T::data.code)> {
ExpressionInformation<std::size(T::data.code)> result = {{}};
int* output_ptr = &result.indices[0];
FullOperationIterator iterator{T::data.code, T::data.immediates};
while(!iterator.code_buffer.empty()) {
auto op = *iterator;
if(op.operation.operation.type == OpCode::Insert) {
*output_ptr++ = op.formatting.index_value;
} else {
*output_ptr++ = -1;
}
}
return result;
}
template<typename T>
constexpr auto ExpressionData = _expression_data<T>();
/* Compile the useful data, retrieve the specific formatting functions */
template<int Index, typename ArgsTuple>
constexpr auto uninitialized_expression() {
if constexpr(Index < 0) {
return LiteralExpression { 0, 0 };
} else {
using type = typename std::tuple_element<Index, ArgsTuple>::type;
return TypedArgumentExpression<type> { Index, nullptr };
}
}
template<typename ... E>
struct CompiledFormatExpressions {
std::tuple<E...> expressions;
constexpr static CompiledFormatExpressions Compile(E ... expressions) {
return {
{ expressions ... }
};
}
template<size_t index>
using ExpressionType = typename std::tuple_element<index, std::tuple<E...>>::type;
};
template<typename T, typename ... E>
constexpr auto initialize(E ... expressions)
-> CompiledFormatExpressions<E...> {
FullOperationIterator iterator{T::data.code, T::data.immediates};
return CompiledFormatExpressions<E...>::Compile(expressions.initialize(*iterator) ...);
}
template<typename T, typename ArgsTuple, size_t ... indices>
constexpr auto build_expressions(std::index_sequence<indices...>) {
auto& data = ExpressionData<T>;
return initialize<T>(uninitialized_expression<data.indices[indices], ArgsTuple>() ...);
}
template<typename Format, typename ... Arguments>
constexpr auto CompiledExpressions = build_expressions<Format, std::tuple<Arguments...>>(
std::make_index_sequence<std::size(Format::data.code)>{});
/* Run the engine with arguments */
struct ExpressionContext {
Engine& engine;
Buffer<const char> format_buffer;
};
template<typename ExpT>
struct Eval;
template<>
struct Eval<LiteralExpression> {
template<typename Format, size_t index, typename ... Arguments>
static inline auto evaluate(
const ExpressionContext& context,
Arguments& ... args)
{
constexpr auto& expression = std::get<index>(CompiledExpressions<Format, Arguments...>.expressions);
context.engine.append(
context.format_buffer.begin() + expression.offset,
context.format_buffer.begin() + expression.offset + expression.length);
}
};
template<FormatArgument type, Immediate value, typename ... Arguments>
constexpr Immediate get_value(const Arguments& ... args) {
if constexpr(type == FormatArgument::Auto) {
return 0;
} else if constexpr(type == FormatArgument::Parameter) {
return std::get<value>(std::tie(args...));
} else {
return value;
}
}
template<typename T>
struct Eval<TypedArgumentExpression<T>> {
template<typename Format, size_t index, typename ... Arguments>
static inline auto evaluate(
const ExpressionContext& context,
Arguments& ... args)
{
constexpr auto& expression = std::get<index>(CompiledExpressions<Format, Arguments...>.expressions);
constexpr auto& formatting = expression.operation.formatting;
constexpr auto fn = expression.function;
#define CPP_MOULD_CONSTEXPR_EVAL_ASSERT(fkind) \
if constexpr(formatting.kind == FormatKind:: fkind) { \
static_assert(fn != nullptr, "Requested formatting (" #fkind ") not implemented"); \
}
CPP_MOULD_CONSTEXPR_EVAL_ASSERT(Auto)
CPP_MOULD_REPEAT_FOR_FORMAT_KINDS_MACRO(CPP_MOULD_CONSTEXPR_EVAL_ASSERT)
#undef CPP_MOULD_CONSTEXPR_EVAL_ASSERT
const auto& argument = std::get<ExpressionData<Format>.indices[index]>(std::tie(args...));
::mould::Format format {
// values
get_value<formatting.width, formatting.width_value>(args...),
get_value<formatting.precision, formatting.precision_value>(args...),
get_value<formatting.padding, formatting.padding_value>(args...),
// flags
formatting.width != FormatArgument::Auto,
formatting.precision != FormatArgument::Auto,
formatting.padding != FormatArgument::Auto,
formatting.alignment,
formatting.sign
};
fn(argument, ::mould::Formatter{context.engine, format});
}
};
struct Ignore {
template<typename ... I>
Ignore(I&& ...) {}
};
template<typename Format, typename ... Arguments, size_t ... Indices>
inline auto _eval(ExpressionContext context, std::index_sequence<Indices...>, Arguments& ... args) {
using Compiled = decltype(CompiledExpressions<Format, Arguments...>);
Ignore ignore{(Eval<typename Compiled::template ExpressionType<Indices>>::template evaluate<Format, Indices>(
context, args...), 0) ...};
}
template<typename Format, typename ... Arguments>
inline auto eval(Engine engine, Arguments ... args) {
ExpressionContext context {
engine,
Format::data.format_buffer()
};
return _eval<Format>(
context,
std::make_index_sequence<std::size(Format::data.code)>{},
args... );
}
}
namespace mould {
template<typename Format, typename ... Arguments>
void format_constexpr(
Format& format_string,
std::string& output,
Arguments&&... arguments)
{
using namespace internal::constexpr_driver;
internal::Engine engine{output};
eval<Format>(engine, arguments...);
}
}
#endif
| 32 | 113 | 0.684404 | HeroicKatora |
3edad376fe6ad405aeab29ef53b9fd59f1f1f3ca | 5,462 | cpp | C++ | src/xrGame/ui/UIInventoryUpgradeWnd_add.cpp | acidicMercury8/xray-1.5 | ae094d82b76a8ce916e196654c163894bbf00146 | [
"Linux-OpenIB"
] | 5 | 2021-10-30T09:36:07.000Z | 2021-12-30T08:14:32.000Z | src/xrGame/ui/UIInventoryUpgradeWnd_add.cpp | Samsuper12/ixray-1.5 | 8070f833f8216d4ead294a9f19b7cd123bb76ba3 | [
"Linux-OpenIB"
] | null | null | null | src/xrGame/ui/UIInventoryUpgradeWnd_add.cpp | Samsuper12/ixray-1.5 | 8070f833f8216d4ead294a9f19b7cd123bb76ba3 | [
"Linux-OpenIB"
] | 2 | 2020-08-04T17:23:16.000Z | 2020-10-16T16:53:38.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : UIInventoryUpgradeWnd_add.cpp
// Created : 08.11.2007
// Author : Evgeniy Sokolov
// Description : inventory upgrade UI window (additional) class implementation
////////////////////////////////////////////////////////////////////////////
#include "pch_script.h"
#include "object_broker.h"
#include "UIInventoryUpgradeWnd.h"
#include "xrUIXmlParser.h"
#include "UIXmlInit.h"
#include "../string_table.h"
void CUIInventoryUpgradeWnd::LoadCellsBacks( CUIXml& uiXml )
{
XML_NODE* stored_root = uiXml.GetLocalRoot();
int cnt = uiXml.GetNodesNum( "cell_states", 0, "state" );
XML_NODE* node = uiXml.NavigateToNode( "cell_states", 0 );
uiXml.SetLocalRoot( node );
for ( int i_st = 0; i_st < cnt; ++i_st )
{
uiXml.SetLocalRoot( uiXml.NavigateToNode( "state", i_st ) );
LPCSTR type = uiXml.Read( "type", 0, "" );
LPCSTR txr = uiXml.Read( "back_texture", 0, NULL );
u32 color = CUIXmlInit::GetColor( uiXml, "item_color", 0, 0 );
LoadCellStates( type, txr, color );
uiXml.SetLocalRoot( node );
}
uiXml.SetLocalRoot( stored_root );
// VERIFY2( VerirfyCells(), "Not all UI upgrade states are filled up !" );
}
void CUIInventoryUpgradeWnd::LoadCellStates( LPCSTR state_str, LPCSTR texture_name, u32 color )
{
VERIFY( state_str && xr_strcmp( state_str, "" ) );
// VERIFY( texture_name && xr_strcmp( texture_name, "" ) );
if ( texture_name && !xr_strcmp( texture_name, "" ) )
{
texture_name = NULL;
}
SetCellState( SelectCellState( state_str ), texture_name, color );
}
UIUpgrade::ViewState CUIInventoryUpgradeWnd::SelectCellState( LPCSTR state_str )
{
if ( !xr_strcmp( state_str, "enabled" ) ) { return UIUpgrade::STATE_ENABLED; }
if ( !xr_strcmp( state_str, "highlight" ) ) { return UIUpgrade::STATE_FOCUSED; }
if ( !xr_strcmp( state_str, "touched" ) ) { return UIUpgrade::STATE_TOUCHED; }
if ( !xr_strcmp( state_str, "selected" ) ) { return UIUpgrade::STATE_SELECTED; }
if ( !xr_strcmp( state_str, "unknown" ) ) { return UIUpgrade::STATE_UNKNOWN; }
if ( !xr_strcmp( state_str, "disabled_parent" ) ) { return UIUpgrade::STATE_DISABLED_PARENT; }
if ( !xr_strcmp( state_str, "disabled_group" ) ) { return UIUpgrade::STATE_DISABLED_GROUP; }
if ( !xr_strcmp( state_str, "disabled_money" ) ) { return UIUpgrade::STATE_DISABLED_PREC_MONEY; }
if ( !xr_strcmp( state_str, "disabled_quest" ) ) { return UIUpgrade::STATE_DISABLED_PREC_QUEST; }
VERIFY2( 0, make_string( "Such UI upgrade state (%s) does not exist !", state_str ) );
return UIUpgrade::STATE_UNKNOWN;
}
void CUIInventoryUpgradeWnd::SetCellState( UIUpgrade::ViewState state, LPCSTR texture_name, u32 color )
{
m_cell_textures[state] = texture_name;
// m_cell_colors[state] = color;
}
bool CUIInventoryUpgradeWnd::VerirfyCells()
{
for ( int i = 0; i < UIUpgrade::STATE_COUNT; ++i )
{
if ( !m_cell_textures[i]._get() ) return false;
}
return true;
}
void CUIInventoryUpgradeWnd::LoadSchemes( CUIXml& uiXml )
{
XML_NODE* tmpl_root = uiXml.NavigateToNode( "property", 0 );
Fvector2 pos_prop, size_prop;
pos_prop.x = uiXml.ReadAttribFlt( tmpl_root, "x" );
pos_prop.y = uiXml.ReadAttribFlt( tmpl_root, "y" );
size_prop.x = uiXml.ReadAttribFlt( tmpl_root, "width" );
size_prop.y = uiXml.ReadAttribFlt( tmpl_root, "height" );
XML_NODE* stored_root = uiXml.GetLocalRoot();
tmpl_root = uiXml.NavigateToNode( "templates", 0 );
uiXml.SetLocalRoot( tmpl_root );
Frect t_cell_border;
Frect t_cell_item;
t_cell_border.x1 = uiXml.ReadAttribFlt( "cell_border", 0, "x" );
t_cell_border.y1 = uiXml.ReadAttribFlt( "cell_border", 0, "y" );
t_cell_border.x2 = t_cell_border.x1 + uiXml.ReadAttribFlt( "cell_border", 0, "width" );
t_cell_border.y2 = t_cell_border.y1 + uiXml.ReadAttribFlt( "cell_border", 0, "height" );
t_cell_item.x1 = uiXml.ReadAttribFlt( "cell_item", 0, "x" );
t_cell_item.y1 = uiXml.ReadAttribFlt( "cell_item", 0, "y" );
t_cell_item.x2 = t_cell_item.x1 + uiXml.ReadAttribFlt( "cell_item", 0, "width" );
t_cell_item.y2 = t_cell_item.y1 + uiXml.ReadAttribFlt( "cell_item", 0, "height" );
int tmpl_count = uiXml.GetNodesNum( tmpl_root, "template" );
for ( int i_tmpl = 0; i_tmpl < tmpl_count; ++i_tmpl )
{
XML_NODE* tmpl_node = uiXml.NavigateToNode( "template", i_tmpl );
uiXml.SetLocalRoot( tmpl_node );
Scheme* scheme = xr_new<Scheme>();
scheme->cells.reserve( MAX_UI_UPGRADE_CELLS );
LPCSTR name = uiXml.ReadAttrib( tmpl_node, "name", "" );
VERIFY( name && xr_strcmp( name, "" ) );
scheme->name._set( name );
int clm_count = uiXml.GetNodesNum( tmpl_node, "column" );
for ( int i_clm = 0; i_clm < clm_count; ++i_clm )
{
XML_NODE* clm_node = uiXml.NavigateToNode( "column", i_clm );
uiXml.SetLocalRoot( clm_node );
int cell_cnt = uiXml.GetNodesNum( clm_node, "cell" );
for ( int i_cell = 0; i_cell < cell_cnt; ++i_cell )
{
UIUpgrade* item = xr_new<UIUpgrade>( this );
item->load_from_xml( uiXml, i_clm, i_cell, t_cell_border, t_cell_item );
item->init_property( pos_prop, size_prop );
scheme->cells.push_back( item );
}// for i_cell
uiXml.SetLocalRoot( tmpl_node );
}// for i_clm
m_schemes.push_back( scheme );
uiXml.SetLocalRoot( tmpl_root );
}// for i_tmpl
uiXml.SetLocalRoot( stored_root );
}
| 36.413333 | 104 | 0.660381 | acidicMercury8 |
3edde78bc6b80490d4c667d44febf217253f4a17 | 73,816 | cc | C++ | components/gcm_driver/gcm_client_impl_unittest.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | components/gcm_driver/gcm_client_impl_unittest.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | components/gcm_driver/gcm_client_impl_unittest.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.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 "components/gcm_driver/gcm_client_impl.h"
#include <stdint.h>
#include <initializer_list>
#include <memory>
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/time/clock.h"
#include "base/timer/timer.h"
#include "components/gcm_driver/features.h"
#include "google_apis/gcm/base/fake_encryptor.h"
#include "google_apis/gcm/base/mcs_message.h"
#include "google_apis/gcm/base/mcs_util.h"
#include "google_apis/gcm/engine/fake_connection_factory.h"
#include "google_apis/gcm/engine/fake_connection_handler.h"
#include "google_apis/gcm/engine/gservices_settings.h"
#include "google_apis/gcm/monitoring/gcm_stats_recorder.h"
#include "google_apis/gcm/protocol/android_checkin.pb.h"
#include "google_apis/gcm/protocol/checkin.pb.h"
#include "google_apis/gcm/protocol/mcs.pb.h"
#include "net/test/gtest_util.h"
#include "net/test/scoped_disable_exit_on_dfatal.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "services/network/test/test_network_connection_tracker.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/network/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest-spi.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/leveldatabase/leveldb_chrome.h"
namespace gcm {
namespace {
enum LastEvent {
NONE,
LOADING_COMPLETED,
REGISTRATION_COMPLETED,
UNREGISTRATION_COMPLETED,
MESSAGE_SEND_ERROR,
MESSAGE_SEND_ACK,
MESSAGE_RECEIVED,
MESSAGES_DELETED,
};
const char kChromeVersion[] = "45.0.0.1";
const uint64_t kDeviceAndroidId = 54321;
const uint64_t kDeviceSecurityToken = 12345;
const uint64_t kDeviceAndroidId2 = 11111;
const uint64_t kDeviceSecurityToken2 = 2222;
const int64_t kSettingsCheckinInterval = 16 * 60 * 60;
const char kProductCategoryForSubtypes[] = "com.chrome.macosx";
const char kExtensionAppId[] = "abcdefghijklmnopabcdefghijklmnop";
const char kRegistrationId[] = "reg_id";
const char kSubtypeAppId[] = "app_id";
const char kSender[] = "project_id";
const char kSender2[] = "project_id2";
const char kRegistrationResponsePrefix[] = "token=";
const char kUnregistrationResponsePrefix[] = "deleted=";
const char kRawData[] = "example raw data";
const char kInstanceID[] = "iid_1";
const char kScope[] = "GCM";
const char kDeleteTokenResponse[] = "token=foo";
const int kTestTokenInvalidationPeriod = 5;
const char kMessageId[] = "0:12345%5678";
const char kRegisterUrl[] = "https://android.clients.google.com/c2dm/register3";
// Helper for building arbitrary data messages.
MCSMessage BuildDownstreamMessage(
const std::string& project_id,
const std::string& category,
const std::string& subtype,
const std::map<std::string, std::string>& data,
const std::string& raw_data) {
mcs_proto::DataMessageStanza data_message;
data_message.set_from(project_id);
data_message.set_category(category);
for (auto iter = data.begin(); iter != data.end(); ++iter) {
mcs_proto::AppData* app_data = data_message.add_app_data();
app_data->set_key(iter->first);
app_data->set_value(iter->second);
}
if (!subtype.empty()) {
mcs_proto::AppData* app_data = data_message.add_app_data();
app_data->set_key("subtype");
app_data->set_value(subtype);
}
data_message.set_raw_data(raw_data);
data_message.set_persistent_id(kMessageId);
return MCSMessage(kDataMessageStanzaTag, data_message);
}
GCMClient::AccountTokenInfo MakeAccountToken(const std::string& email,
const std::string& token) {
GCMClient::AccountTokenInfo account_token;
account_token.email = email;
account_token.access_token = token;
return account_token;
}
std::map<std::string, std::string> MakeEmailToTokenMap(
const std::vector<GCMClient::AccountTokenInfo>& account_tokens) {
std::map<std::string, std::string> email_token_map;
for (auto iter = account_tokens.begin(); iter != account_tokens.end();
++iter) {
email_token_map[iter->email] = iter->access_token;
}
return email_token_map;
}
class FakeMCSClient : public MCSClient {
public:
FakeMCSClient(base::Clock* clock,
ConnectionFactory* connection_factory,
GCMStore* gcm_store,
scoped_refptr<base::SequencedTaskRunner> io_task_runner,
GCMStatsRecorder* recorder);
~FakeMCSClient() override;
void Login(uint64_t android_id, uint64_t security_token) override;
void SendMessage(const MCSMessage& message) override;
uint64_t last_android_id() const { return last_android_id_; }
uint64_t last_security_token() const { return last_security_token_; }
uint8_t last_message_tag() const { return last_message_tag_; }
const mcs_proto::DataMessageStanza& last_data_message_stanza() const {
return last_data_message_stanza_;
}
private:
uint64_t last_android_id_;
uint64_t last_security_token_;
uint8_t last_message_tag_;
mcs_proto::DataMessageStanza last_data_message_stanza_;
};
FakeMCSClient::FakeMCSClient(
base::Clock* clock,
ConnectionFactory* connection_factory,
GCMStore* gcm_store,
scoped_refptr<base::SequencedTaskRunner> io_task_runner,
GCMStatsRecorder* recorder)
: MCSClient("",
clock,
connection_factory,
gcm_store,
io_task_runner,
recorder),
last_android_id_(0u),
last_security_token_(0u),
last_message_tag_(kNumProtoTypes) {}
FakeMCSClient::~FakeMCSClient() {
}
void FakeMCSClient::Login(uint64_t android_id, uint64_t security_token) {
last_android_id_ = android_id;
last_security_token_ = security_token;
}
void FakeMCSClient::SendMessage(const MCSMessage& message) {
last_message_tag_ = message.tag();
if (last_message_tag_ == kDataMessageStanzaTag) {
last_data_message_stanza_.CopyFrom(
reinterpret_cast<const mcs_proto::DataMessageStanza&>(
message.GetProtobuf()));
}
}
class AutoAdvancingTestClock : public base::Clock {
public:
explicit AutoAdvancingTestClock(base::TimeDelta auto_increment_time_delta);
AutoAdvancingTestClock(const AutoAdvancingTestClock&) = delete;
AutoAdvancingTestClock& operator=(const AutoAdvancingTestClock&) = delete;
~AutoAdvancingTestClock() override;
base::Time Now() const override;
void Advance(base::TimeDelta delta);
int call_count() const { return call_count_; }
private:
mutable int call_count_;
base::TimeDelta auto_increment_time_delta_;
mutable base::Time now_;
};
AutoAdvancingTestClock::AutoAdvancingTestClock(
base::TimeDelta auto_increment_time_delta)
: call_count_(0), auto_increment_time_delta_(auto_increment_time_delta) {
}
AutoAdvancingTestClock::~AutoAdvancingTestClock() {
}
base::Time AutoAdvancingTestClock::Now() const {
call_count_++;
now_ += auto_increment_time_delta_;
return now_;
}
void AutoAdvancingTestClock::Advance(base::TimeDelta delta) {
now_ += delta;
}
class FakeGCMInternalsBuilder : public GCMInternalsBuilder {
public:
explicit FakeGCMInternalsBuilder(base::TimeDelta clock_step);
~FakeGCMInternalsBuilder() override;
base::Clock* GetClock() override;
std::unique_ptr<MCSClient> BuildMCSClient(
const std::string& version,
base::Clock* clock,
ConnectionFactory* connection_factory,
GCMStore* gcm_store,
scoped_refptr<base::SequencedTaskRunner> io_task_runner,
GCMStatsRecorder* recorder) override;
std::unique_ptr<ConnectionFactory> BuildConnectionFactory(
const std::vector<GURL>& endpoints,
const net::BackoffEntry::Policy& backoff_policy,
base::RepeatingCallback<void(
mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>)>
get_socket_factory_callback,
scoped_refptr<base::SequencedTaskRunner> io_task_runner,
GCMStatsRecorder* recorder,
network::NetworkConnectionTracker* network_connection_tracker) override;
private:
AutoAdvancingTestClock clock_;
};
FakeGCMInternalsBuilder::FakeGCMInternalsBuilder(base::TimeDelta clock_step)
: clock_(clock_step) {}
FakeGCMInternalsBuilder::~FakeGCMInternalsBuilder() {}
base::Clock* FakeGCMInternalsBuilder::GetClock() {
return &clock_;
}
std::unique_ptr<MCSClient> FakeGCMInternalsBuilder::BuildMCSClient(
const std::string& version,
base::Clock* clock,
ConnectionFactory* connection_factory,
GCMStore* gcm_store,
scoped_refptr<base::SequencedTaskRunner> io_task_runner,
GCMStatsRecorder* recorder) {
return base::WrapUnique<MCSClient>(new FakeMCSClient(
clock, connection_factory, gcm_store, io_task_runner, recorder));
}
std::unique_ptr<ConnectionFactory>
FakeGCMInternalsBuilder::BuildConnectionFactory(
const std::vector<GURL>& endpoints,
const net::BackoffEntry::Policy& backoff_policy,
base::RepeatingCallback<void(
mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>)>
get_socket_factory_callback,
scoped_refptr<base::SequencedTaskRunner> io_task_runner,
GCMStatsRecorder* recorder,
network::NetworkConnectionTracker* network_connection_tracker) {
return base::WrapUnique<ConnectionFactory>(new FakeConnectionFactory());
}
} // namespace
class GCMClientImplTest : public testing::Test,
public GCMClient::Delegate {
public:
GCMClientImplTest();
~GCMClientImplTest() override;
void SetUp() override;
void TearDown() override;
void SetFeatureParams(const base::Feature& feature,
const base::FieldTrialParams& params);
void InitializeInvalidationFieldTrial();
void BuildGCMClient(base::TimeDelta clock_step);
void InitializeGCMClient();
void StartGCMClient();
void Register(const std::string& app_id,
const std::vector<std::string>& senders);
void Unregister(const std::string& app_id);
void ReceiveMessageFromMCS(const MCSMessage& message);
void ReceiveOnMessageSentToMCS(
const std::string& app_id,
const std::string& message_id,
const MCSClient::MessageSendStatus status);
void FailCheckin(net::HttpStatusCode response_code);
void CompleteCheckin(uint64_t android_id,
uint64_t security_token,
const std::string& digest,
const std::map<std::string, std::string>& settings);
void CompleteCheckinImpl(uint64_t android_id,
uint64_t security_token,
const std::string& digest,
const std::map<std::string, std::string>& settings,
net::HttpStatusCode response_code);
void CompleteRegistration(const std::string& registration_id);
void CompleteUnregistration(const std::string& app_id);
bool ExistsRegistration(const std::string& app_id) const;
void AddRegistration(const std::string& app_id,
const std::vector<std::string>& sender_ids,
const std::string& registration_id);
// GCMClient::Delegate overrides (for verification).
void OnRegisterFinished(scoped_refptr<RegistrationInfo> registration_info,
const std::string& registration_id,
GCMClient::Result result) override;
void OnUnregisterFinished(scoped_refptr<RegistrationInfo> registration_info,
GCMClient::Result result) override;
void OnSendFinished(const std::string& app_id,
const std::string& message_id,
GCMClient::Result result) override {}
void OnMessageReceived(const std::string& registration_id,
const IncomingMessage& message) override;
void OnMessagesDeleted(const std::string& app_id) override;
void OnMessageSendError(
const std::string& app_id,
const gcm::GCMClient::SendErrorDetails& send_error_details) override;
void OnSendAcknowledged(const std::string& app_id,
const std::string& message_id) override;
void OnGCMReady(const std::vector<AccountMapping>& account_mappings,
const base::Time& last_token_fetch_time) override;
void OnActivityRecorded() override {}
void OnConnected(const net::IPEndPoint& ip_endpoint) override {}
void OnDisconnected() override {}
void OnStoreReset() override {}
GCMClientImpl* gcm_client() const { return gcm_client_.get(); }
GCMClientImpl::State gcm_client_state() const {
return gcm_client_->state_;
}
FakeMCSClient* mcs_client() const {
return static_cast<FakeMCSClient*>(gcm_client_->mcs_client_.get());
}
ConnectionFactory* connection_factory() const {
return gcm_client_->connection_factory_.get();
}
const GCMClientImpl::CheckinInfo& device_checkin_info() const {
return gcm_client_->device_checkin_info_;
}
void reset_last_event() {
last_event_ = NONE;
last_app_id_.clear();
last_registration_id_.clear();
last_message_id_.clear();
last_result_ = GCMClient::UNKNOWN_ERROR;
last_account_mappings_.clear();
last_token_fetch_time_ = base::Time();
}
LastEvent last_event() const { return last_event_; }
const std::string& last_app_id() const { return last_app_id_; }
const std::string& last_registration_id() const {
return last_registration_id_;
}
const std::string& last_message_id() const { return last_message_id_; }
GCMClient::Result last_result() const { return last_result_; }
const IncomingMessage& last_message() const { return last_message_; }
const GCMClient::SendErrorDetails& last_error_details() const {
return last_error_details_;
}
const base::Time& last_token_fetch_time() const {
return last_token_fetch_time_;
}
const std::vector<AccountMapping>& last_account_mappings() {
return last_account_mappings_;
}
const GServicesSettings& gservices_settings() const {
return gcm_client_->gservices_settings_;
}
const base::FilePath& temp_directory_path() const {
return temp_directory_.GetPath();
}
base::FilePath gcm_store_path() const {
// Pass an non-existent directory as store path to match the exact
// behavior in the production code. Currently GCMStoreImpl checks if
// the directory exist or not to determine the store existence.
return temp_directory_.GetPath().Append(FILE_PATH_LITERAL("GCM Store"));
}
int64_t CurrentTime();
// Tooling.
void PumpLoopUntilIdle();
bool CreateUniqueTempDir();
AutoAdvancingTestClock* clock() const {
return static_cast<AutoAdvancingTestClock*>(gcm_client_->clock_);
}
network::TestURLLoaderFactory* url_loader_factory() {
return &test_url_loader_factory_;
}
void FastForwardBy(const base::TimeDelta& duration) {
task_environment_.FastForwardBy(duration);
}
private:
base::test::TaskEnvironment task_environment_{
base::test::TaskEnvironment::TimeSource::MOCK_TIME};
// Must be declared first so that it is destroyed last. Injected to
// GCM client.
base::ScopedTempDir temp_directory_;
// Variables used for verification.
LastEvent last_event_;
std::string last_app_id_;
std::string last_registration_id_;
std::string last_message_id_;
GCMClient::Result last_result_;
IncomingMessage last_message_;
GCMClient::SendErrorDetails last_error_details_;
base::Time last_token_fetch_time_;
std::vector<AccountMapping> last_account_mappings_;
std::unique_ptr<GCMClientImpl> gcm_client_;
// Injected to GCM client.
network::TestURLLoaderFactory test_url_loader_factory_;
base::test::ScopedFeatureList scoped_feature_list_;
};
GCMClientImplTest::GCMClientImplTest()
: last_event_(NONE), last_result_(GCMClient::UNKNOWN_ERROR) {}
GCMClientImplTest::~GCMClientImplTest() {}
void GCMClientImplTest::SetUp() {
testing::Test::SetUp();
ASSERT_TRUE(CreateUniqueTempDir());
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
StartGCMClient();
InitializeInvalidationFieldTrial();
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken, std::string(),
std::map<std::string, std::string>()));
}
void GCMClientImplTest::TearDown() {
gcm_client_.reset();
PumpLoopUntilIdle();
testing::Test::TearDown();
}
void GCMClientImplTest::SetFeatureParams(const base::Feature& feature,
const base::FieldTrialParams& params) {
scoped_feature_list_.InitAndEnableFeatureWithParameters(feature, params);
base::FieldTrialParams actual_params;
EXPECT_TRUE(base::GetFieldTrialParamsByFeature(
features::kInvalidateTokenFeature, &actual_params));
EXPECT_EQ(params, actual_params);
}
void GCMClientImplTest::InitializeInvalidationFieldTrial() {
std::map<std::string, std::string> params;
params[features::kParamNameTokenInvalidationPeriodDays] =
std::to_string(kTestTokenInvalidationPeriod);
ASSERT_NO_FATAL_FAILURE(
SetFeatureParams(features::kInvalidateTokenFeature, std::move(params)));
}
void GCMClientImplTest::PumpLoopUntilIdle() {
task_environment_.RunUntilIdle();
}
bool GCMClientImplTest::CreateUniqueTempDir() {
return temp_directory_.CreateUniqueTempDir();
}
void GCMClientImplTest::BuildGCMClient(base::TimeDelta clock_step) {
gcm_client_ =
std::make_unique<GCMClientImpl>(base::WrapUnique<GCMInternalsBuilder>(
new FakeGCMInternalsBuilder(clock_step)));
}
void GCMClientImplTest::FailCheckin(net::HttpStatusCode response_code) {
std::map<std::string, std::string> settings;
CompleteCheckinImpl(0, 0, GServicesSettings::CalculateDigest(settings),
settings, response_code);
}
void GCMClientImplTest::CompleteCheckin(
uint64_t android_id,
uint64_t security_token,
const std::string& digest,
const std::map<std::string, std::string>& settings) {
CompleteCheckinImpl(android_id, security_token, digest, settings,
net::HTTP_OK);
}
void GCMClientImplTest::CompleteCheckinImpl(
uint64_t android_id,
uint64_t security_token,
const std::string& digest,
const std::map<std::string, std::string>& settings,
net::HttpStatusCode response_code) {
checkin_proto::AndroidCheckinResponse response;
response.set_stats_ok(true);
response.set_android_id(android_id);
response.set_security_token(security_token);
// For testing G-services settings.
if (!digest.empty()) {
response.set_digest(digest);
for (auto it = settings.begin(); it != settings.end(); ++it) {
checkin_proto::GservicesSetting* setting = response.add_setting();
setting->set_name(it->first);
setting->set_value(it->second);
}
response.set_settings_diff(false);
}
std::string response_string;
response.SerializeToString(&response_string);
EXPECT_TRUE(url_loader_factory()->SimulateResponseForPendingRequest(
gservices_settings().GetCheckinURL(),
network::URLLoaderCompletionStatus(net::OK),
network::CreateURLResponseHead(response_code), response_string));
// Give a chance for GCMStoreImpl::Backend to finish persisting data.
PumpLoopUntilIdle();
}
void GCMClientImplTest::CompleteRegistration(
const std::string& registration_id) {
std::string response(kRegistrationResponsePrefix);
response.append(registration_id);
EXPECT_TRUE(url_loader_factory()->SimulateResponseForPendingRequest(
GURL(kRegisterUrl), network::URLLoaderCompletionStatus(net::OK),
network::CreateURLResponseHead(net::HTTP_OK), response));
// Give a chance for GCMStoreImpl::Backend to finish persisting data.
PumpLoopUntilIdle();
}
void GCMClientImplTest::CompleteUnregistration(
const std::string& app_id) {
std::string response(kUnregistrationResponsePrefix);
response.append(app_id);
EXPECT_TRUE(url_loader_factory()->SimulateResponseForPendingRequest(
GURL(kRegisterUrl), network::URLLoaderCompletionStatus(net::OK),
network::CreateURLResponseHead(net::HTTP_OK), response));
// Give a chance for GCMStoreImpl::Backend to finish persisting data.
PumpLoopUntilIdle();
}
bool GCMClientImplTest::ExistsRegistration(const std::string& app_id) const {
return ExistsGCMRegistrationInMap(gcm_client_->registrations_, app_id);
}
void GCMClientImplTest::AddRegistration(
const std::string& app_id,
const std::vector<std::string>& sender_ids,
const std::string& registration_id) {
auto registration = base::MakeRefCounted<GCMRegistrationInfo>();
registration->app_id = app_id;
registration->sender_ids = sender_ids;
gcm_client_->registrations_.emplace(std::move(registration), registration_id);
}
void GCMClientImplTest::InitializeGCMClient() {
clock()->Advance(base::Milliseconds(1));
// Actual initialization.
GCMClient::ChromeBuildInfo chrome_build_info;
chrome_build_info.version = kChromeVersion;
chrome_build_info.product_category_for_subtypes = kProductCategoryForSubtypes;
gcm_client_->Initialize(
chrome_build_info, gcm_store_path(),
/*remove_account_mappings_with_email_key=*/true,
task_environment_.GetMainThreadTaskRunner(),
base::ThreadTaskRunnerHandle::Get(), base::DoNothing(),
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory_),
network::TestNetworkConnectionTracker::GetInstance(),
base::WrapUnique<Encryptor>(new FakeEncryptor), this);
}
void GCMClientImplTest::StartGCMClient() {
// Start loading and check-in.
gcm_client_->Start(GCMClient::IMMEDIATE_START);
PumpLoopUntilIdle();
}
void GCMClientImplTest::Register(const std::string& app_id,
const std::vector<std::string>& senders) {
auto gcm_info = base::MakeRefCounted<GCMRegistrationInfo>();
gcm_info->app_id = app_id;
gcm_info->sender_ids = senders;
gcm_client()->Register(std::move(gcm_info));
}
void GCMClientImplTest::Unregister(const std::string& app_id) {
auto gcm_info = base::MakeRefCounted<GCMRegistrationInfo>();
gcm_info->app_id = app_id;
gcm_client()->Unregister(std::move(gcm_info));
}
void GCMClientImplTest::ReceiveMessageFromMCS(const MCSMessage& message) {
gcm_client_->recorder_.RecordConnectionInitiated(std::string());
gcm_client_->recorder_.RecordConnectionSuccess();
gcm_client_->OnMessageReceivedFromMCS(message);
}
void GCMClientImplTest::ReceiveOnMessageSentToMCS(
const std::string& app_id,
const std::string& message_id,
const MCSClient::MessageSendStatus status) {
gcm_client_->OnMessageSentToMCS(0LL, app_id, message_id, status);
}
void GCMClientImplTest::OnGCMReady(
const std::vector<AccountMapping>& account_mappings,
const base::Time& last_token_fetch_time) {
last_event_ = LOADING_COMPLETED;
last_account_mappings_ = account_mappings;
last_token_fetch_time_ = last_token_fetch_time;
}
void GCMClientImplTest::OnMessageReceived(const std::string& registration_id,
const IncomingMessage& message) {
last_event_ = MESSAGE_RECEIVED;
last_app_id_ = registration_id;
last_message_ = message;
}
void GCMClientImplTest::OnRegisterFinished(
scoped_refptr<RegistrationInfo> registration_info,
const std::string& registration_id,
GCMClient::Result result) {
last_event_ = REGISTRATION_COMPLETED;
last_app_id_ = registration_info->app_id;
last_registration_id_ = registration_id;
last_result_ = result;
}
void GCMClientImplTest::OnUnregisterFinished(
scoped_refptr<RegistrationInfo> registration_info,
GCMClient::Result result) {
last_event_ = UNREGISTRATION_COMPLETED;
last_app_id_ = registration_info->app_id;
last_result_ = result;
}
void GCMClientImplTest::OnMessagesDeleted(const std::string& app_id) {
last_event_ = MESSAGES_DELETED;
last_app_id_ = app_id;
}
void GCMClientImplTest::OnMessageSendError(
const std::string& app_id,
const gcm::GCMClient::SendErrorDetails& send_error_details) {
last_event_ = MESSAGE_SEND_ERROR;
last_app_id_ = app_id;
last_error_details_ = send_error_details;
}
void GCMClientImplTest::OnSendAcknowledged(const std::string& app_id,
const std::string& message_id) {
last_event_ = MESSAGE_SEND_ACK;
last_app_id_ = app_id;
last_message_id_ = message_id;
}
int64_t GCMClientImplTest::CurrentTime() {
return clock()->Now().ToInternalValue() / base::Time::kMicrosecondsPerSecond;
}
TEST_F(GCMClientImplTest, LoadingCompleted) {
EXPECT_EQ(LOADING_COMPLETED, last_event());
EXPECT_EQ(kDeviceAndroidId, mcs_client()->last_android_id());
EXPECT_EQ(kDeviceSecurityToken, mcs_client()->last_security_token());
// Checking freshly loaded CheckinInfo.
EXPECT_EQ(kDeviceAndroidId, device_checkin_info().android_id);
EXPECT_EQ(kDeviceSecurityToken, device_checkin_info().secret);
EXPECT_TRUE(device_checkin_info().last_checkin_accounts.empty());
EXPECT_TRUE(device_checkin_info().accounts_set);
EXPECT_TRUE(device_checkin_info().account_tokens.empty());
}
TEST_F(GCMClientImplTest, LoadingBusted) {
// Close the GCM store.
gcm_client()->Stop();
PumpLoopUntilIdle();
// Mess up the store.
EXPECT_TRUE(leveldb_chrome::CorruptClosedDBForTesting(gcm_store_path()));
// Restart GCM client. The store should be reset and the loading should
// complete successfully.
reset_last_event();
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
StartGCMClient();
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId2, kDeviceSecurityToken2, std::string(),
std::map<std::string, std::string>()));
EXPECT_EQ(LOADING_COMPLETED, last_event());
EXPECT_EQ(kDeviceAndroidId2, mcs_client()->last_android_id());
EXPECT_EQ(kDeviceSecurityToken2, mcs_client()->last_security_token());
}
TEST_F(GCMClientImplTest, LoadingWithEmptyDirectory) {
// Close the GCM store.
gcm_client()->Stop();
PumpLoopUntilIdle();
// Make the store directory empty, to simulate a previous destroy store
// operation failing to delete the store directory.
ASSERT_TRUE(base::DeletePathRecursively(gcm_store_path()));
ASSERT_TRUE(base::CreateDirectory(gcm_store_path()));
base::HistogramTester histogram_tester;
// Restart GCM client. The store should be considered to not exist.
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
gcm_client()->Start(GCMClient::DELAYED_START);
PumpLoopUntilIdle();
histogram_tester.ExpectUniqueSample("GCM.LoadStatus",
13 /* STORE_DOES_NOT_EXIST */, 1);
// Since the store does not exist, the database should not have been opened.
histogram_tester.ExpectTotalCount("GCM.Database.Open", 0);
// Without a store, DELAYED_START loading should only reach INITIALIZED state.
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// The store directory should still exist (and be empty). If not, then the
// DELAYED_START load has probably reset the store, rather than leaving that
// to the next IMMEDIATE_START load as expected.
ASSERT_TRUE(base::DirectoryExists(gcm_store_path()));
ASSERT_FALSE(
base::PathExists(gcm_store_path().Append(FILE_PATH_LITERAL("CURRENT"))));
// IMMEDIATE_START loading should successfully create a new store despite the
// empty directory.
reset_last_event();
StartGCMClient();
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId2, kDeviceSecurityToken2, std::string(),
std::map<std::string, std::string>()));
EXPECT_EQ(LOADING_COMPLETED, last_event());
EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
EXPECT_EQ(kDeviceAndroidId2, mcs_client()->last_android_id());
EXPECT_EQ(kDeviceSecurityToken2, mcs_client()->last_security_token());
}
TEST_F(GCMClientImplTest, DestroyStoreWhenNotNeeded) {
// Close the GCM store.
gcm_client()->Stop();
PumpLoopUntilIdle();
// Restart GCM client. The store is loaded successfully.
reset_last_event();
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
gcm_client()->Start(GCMClient::DELAYED_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::LOADED, gcm_client_state());
EXPECT_TRUE(device_checkin_info().android_id);
EXPECT_TRUE(device_checkin_info().secret);
// Fast forward the clock to trigger the store destroying logic.
FastForwardBy(base::Milliseconds(300000));
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
EXPECT_FALSE(device_checkin_info().android_id);
EXPECT_FALSE(device_checkin_info().secret);
}
TEST_F(GCMClientImplTest, SerializeAndDeserialize) {
std::vector<std::string> senders{"sender"};
auto gcm_info = base::MakeRefCounted<GCMRegistrationInfo>();
gcm_info->app_id = kExtensionAppId;
gcm_info->sender_ids = senders;
gcm_info->last_validated = clock()->Now();
auto gcm_info_deserialized = base::MakeRefCounted<GCMRegistrationInfo>();
std::string gcm_registration_id_deserialized;
{
std::string serialized_key = gcm_info->GetSerializedKey();
std::string serialized_value =
gcm_info->GetSerializedValue(kRegistrationId);
ASSERT_TRUE(gcm_info_deserialized->Deserialize(
serialized_key, serialized_value, &gcm_registration_id_deserialized));
}
EXPECT_EQ(gcm_info->app_id, gcm_info_deserialized->app_id);
EXPECT_EQ(gcm_info->sender_ids, gcm_info_deserialized->sender_ids);
EXPECT_EQ(gcm_info->last_validated, gcm_info_deserialized->last_validated);
EXPECT_EQ(kRegistrationId, gcm_registration_id_deserialized);
auto instance_id_info = base::MakeRefCounted<InstanceIDTokenInfo>();
instance_id_info->app_id = kExtensionAppId;
instance_id_info->last_validated = clock()->Now();
instance_id_info->authorized_entity = "different_sender";
instance_id_info->scope = "scope";
auto instance_id_info_deserialized =
base::MakeRefCounted<InstanceIDTokenInfo>();
std::string instance_id_registration_id_deserialized;
{
std::string serialized_key = instance_id_info->GetSerializedKey();
std::string serialized_value =
instance_id_info->GetSerializedValue(kRegistrationId);
ASSERT_TRUE(instance_id_info_deserialized->Deserialize(
serialized_key, serialized_value,
&instance_id_registration_id_deserialized));
}
EXPECT_EQ(instance_id_info->app_id, instance_id_info_deserialized->app_id);
EXPECT_EQ(instance_id_info->last_validated,
instance_id_info_deserialized->last_validated);
EXPECT_EQ(instance_id_info->authorized_entity,
instance_id_info_deserialized->authorized_entity);
EXPECT_EQ(instance_id_info->scope, instance_id_info_deserialized->scope);
EXPECT_EQ(kRegistrationId, instance_id_registration_id_deserialized);
}
TEST_F(GCMClientImplTest, RegisterApp) {
EXPECT_FALSE(ExistsRegistration(kExtensionAppId));
std::vector<std::string> senders;
senders.push_back("sender");
Register(kExtensionAppId, senders);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("reg_id"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("reg_id", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
}
TEST_F(GCMClientImplTest, RegisterAppFromCache) {
EXPECT_FALSE(ExistsRegistration(kExtensionAppId));
std::vector<std::string> senders;
senders.push_back("sender");
Register(kExtensionAppId, senders);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("reg_id"));
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("reg_id", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
// Recreate GCMClient in order to load from the persistent store.
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
StartGCMClient();
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
}
TEST_F(GCMClientImplTest, RegisterPreviousSenderAgain) {
EXPECT_FALSE(ExistsRegistration(kExtensionAppId));
// Register a sender.
std::vector<std::string> senders;
senders.push_back("sender");
Register(kExtensionAppId, senders);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("reg_id"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("reg_id", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
reset_last_event();
// Register a different sender. Different registration ID from previous one
// should be returned.
std::vector<std::string> senders2;
senders2.push_back("sender2");
Register(kExtensionAppId, senders2);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("reg_id2"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("reg_id2", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
reset_last_event();
// Register the 1st sender again. Different registration ID from previous one
// should be returned.
std::vector<std::string> senders3;
senders3.push_back("sender");
Register(kExtensionAppId, senders3);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("reg_id"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("reg_id", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
}
TEST_F(GCMClientImplTest, DISABLED_RegisterAgainWhenTokenIsFresh) {
// Register a sender.
std::vector<std::string> senders;
senders.push_back("sender");
Register(kExtensionAppId, senders);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("reg_id"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("reg_id", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
reset_last_event();
// Advance time by (kTestTokenInvalidationPeriod)/2
clock()->Advance(base::Days(kTestTokenInvalidationPeriod / 2));
// Register the same sender again. The same registration ID as the
// previous one should be returned, and we should *not* send a
// registration request to the GCM server.
Register(kExtensionAppId, senders);
PumpLoopUntilIdle();
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("reg_id", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
}
TEST_F(GCMClientImplTest, RegisterAgainWhenTokenIsStale) {
// Register a sender.
std::vector<std::string> senders;
senders.push_back("sender");
Register(kExtensionAppId, senders);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("reg_id"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("reg_id", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
reset_last_event();
// Advance time by kTestTokenInvalidationPeriod
clock()->Advance(base::Days(kTestTokenInvalidationPeriod));
// Register the same sender again. Different registration ID from the
// previous one should be returned.
Register(kExtensionAppId, senders);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("reg_id2"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("reg_id2", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
}
TEST_F(GCMClientImplTest, UnregisterApp) {
EXPECT_FALSE(ExistsRegistration(kExtensionAppId));
std::vector<std::string> senders;
senders.push_back("sender");
Register(kExtensionAppId, senders);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("reg_id"));
EXPECT_TRUE(ExistsRegistration(kExtensionAppId));
Unregister(kExtensionAppId);
ASSERT_NO_FATAL_FAILURE(CompleteUnregistration(kExtensionAppId));
EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_FALSE(ExistsRegistration(kExtensionAppId));
}
// Tests that stopping the GCMClient also deletes pending registration requests.
// This is tested by checking that url fetcher contained in the request was
// deleted.
TEST_F(GCMClientImplTest, DeletePendingRequestsWhenStopping) {
std::vector<std::string> senders;
senders.push_back("sender");
Register(kExtensionAppId, senders);
gcm_client()->Stop();
PumpLoopUntilIdle();
EXPECT_EQ(0, url_loader_factory()->NumPending());
}
TEST_F(GCMClientImplTest, DispatchDownstreamMessage) {
// Register to receive messages from kSender and kSender2 only.
std::vector<std::string> senders;
senders.push_back(kSender);
senders.push_back(kSender2);
AddRegistration(kExtensionAppId, senders, "reg_id");
std::map<std::string, std::string> expected_data;
expected_data["message_type"] = "gcm";
expected_data["key"] = "value";
expected_data["key2"] = "value2";
// Message for kSender will be received.
MCSMessage message(BuildDownstreamMessage(
kSender, kExtensionAppId, std::string() /* subtype */, expected_data,
std::string() /* raw_data */));
EXPECT_TRUE(message.IsValid());
ReceiveMessageFromMCS(message);
expected_data.erase(expected_data.find("message_type"));
EXPECT_EQ(MESSAGE_RECEIVED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(expected_data.size(), last_message().data.size());
EXPECT_EQ(expected_data, last_message().data);
EXPECT_EQ(kSender, last_message().sender_id);
reset_last_event();
// Message for kSender2 will be received.
MCSMessage message2(BuildDownstreamMessage(
kSender2, kExtensionAppId, std::string() /* subtype */, expected_data,
std::string() /* raw_data */));
EXPECT_TRUE(message2.IsValid());
ReceiveMessageFromMCS(message2);
EXPECT_EQ(MESSAGE_RECEIVED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(expected_data.size(), last_message().data.size());
EXPECT_EQ(expected_data, last_message().data);
EXPECT_EQ(kSender2, last_message().sender_id);
}
TEST_F(GCMClientImplTest, DispatchDownstreamMessageRawData) {
std::vector<std::string> senders(1, kSender);
AddRegistration(kExtensionAppId, senders, "reg_id");
std::map<std::string, std::string> expected_data;
MCSMessage message(BuildDownstreamMessage(kSender, kExtensionAppId,
std::string() /* subtype */,
expected_data, kRawData));
EXPECT_TRUE(message.IsValid());
ReceiveMessageFromMCS(message);
EXPECT_EQ(MESSAGE_RECEIVED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(expected_data.size(), last_message().data.size());
EXPECT_EQ(kSender, last_message().sender_id);
EXPECT_EQ(kRawData, last_message().raw_data);
}
TEST_F(GCMClientImplTest, DISABLED_DispatchDownstreamMessageSendError) {
std::map<std::string, std::string> expected_data = {
{"message_type", "send_error"}, {"error_details", "some details"}};
MCSMessage message(BuildDownstreamMessage(
kSender, kExtensionAppId, std::string() /* subtype */, expected_data,
std::string() /* raw_data */));
EXPECT_TRUE(message.IsValid());
ReceiveMessageFromMCS(message);
EXPECT_EQ(MESSAGE_SEND_ERROR, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(kMessageId, last_error_details().message_id);
EXPECT_EQ(1UL, last_error_details().additional_data.size());
auto iter = last_error_details().additional_data.find("error_details");
EXPECT_TRUE(iter != last_error_details().additional_data.end());
EXPECT_EQ("some details", iter->second);
}
TEST_F(GCMClientImplTest, DispatchDownstreamMessgaesDeleted) {
std::map<std::string, std::string> expected_data;
expected_data["message_type"] = "deleted_messages";
MCSMessage message(BuildDownstreamMessage(
kSender, kExtensionAppId, std::string() /* subtype */, expected_data,
std::string() /* raw_data */));
EXPECT_TRUE(message.IsValid());
ReceiveMessageFromMCS(message);
EXPECT_EQ(MESSAGES_DELETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
}
TEST_F(GCMClientImplTest, SendMessage) {
OutgoingMessage message;
message.id = "007";
message.time_to_live = 500;
message.data["key"] = "value";
gcm_client()->Send(kExtensionAppId, kSender, message);
EXPECT_EQ(kDataMessageStanzaTag, mcs_client()->last_message_tag());
EXPECT_EQ(kExtensionAppId,
mcs_client()->last_data_message_stanza().category());
EXPECT_EQ(kSender, mcs_client()->last_data_message_stanza().to());
EXPECT_EQ(500, mcs_client()->last_data_message_stanza().ttl());
EXPECT_EQ(CurrentTime(), mcs_client()->last_data_message_stanza().sent());
EXPECT_EQ("007", mcs_client()->last_data_message_stanza().id());
EXPECT_EQ("gcm@chrome.com", mcs_client()->last_data_message_stanza().from());
EXPECT_EQ(kSender, mcs_client()->last_data_message_stanza().to());
EXPECT_EQ("key", mcs_client()->last_data_message_stanza().app_data(0).key());
EXPECT_EQ("value",
mcs_client()->last_data_message_stanza().app_data(0).value());
}
TEST_F(GCMClientImplTest, SendMessageAcknowledged) {
ReceiveOnMessageSentToMCS(kExtensionAppId, "007", MCSClient::SENT);
EXPECT_EQ(MESSAGE_SEND_ACK, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("007", last_message_id());
}
class GCMClientImplCheckinTest : public GCMClientImplTest {
public:
GCMClientImplCheckinTest();
~GCMClientImplCheckinTest() override;
void SetUp() override;
};
GCMClientImplCheckinTest::GCMClientImplCheckinTest() {
}
GCMClientImplCheckinTest::~GCMClientImplCheckinTest() {
}
void GCMClientImplCheckinTest::SetUp() {
testing::Test::SetUp();
// Creating unique temp directory that will be used by GCMStore shared between
// GCM Client and G-services settings.
ASSERT_TRUE(CreateUniqueTempDir());
// Time will be advancing one hour every time it is checked.
BuildGCMClient(base::Seconds(kSettingsCheckinInterval));
InitializeGCMClient();
StartGCMClient();
}
TEST_F(GCMClientImplCheckinTest, GServicesSettingsAfterInitialCheckin) {
std::map<std::string, std::string> settings;
settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval);
settings["checkin_url"] = "http://alternative.url/checkin";
settings["gcm_hostname"] = "alternative.gcm.host";
settings["gcm_secure_port"] = "7777";
settings["gcm_registration_url"] = "http://alternative.url/registration";
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
EXPECT_EQ(base::Seconds(kSettingsCheckinInterval),
gservices_settings().GetCheckinInterval());
EXPECT_EQ(GURL("http://alternative.url/checkin"),
gservices_settings().GetCheckinURL());
EXPECT_EQ(GURL("http://alternative.url/registration"),
gservices_settings().GetRegistrationURL());
EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
gservices_settings().GetMCSMainEndpoint());
EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
gservices_settings().GetMCSFallbackEndpoint());
}
// This test only checks that periodic checkin happens.
TEST_F(GCMClientImplCheckinTest, PeriodicCheckin) {
std::map<std::string, std::string> settings;
settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval);
settings["checkin_url"] = "http://alternative.url/checkin";
settings["gcm_hostname"] = "alternative.gcm.host";
settings["gcm_secure_port"] = "7777";
settings["gcm_registration_url"] = "http://alternative.url/registration";
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
EXPECT_EQ(2, clock()->call_count());
PumpLoopUntilIdle();
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
}
TEST_F(GCMClientImplCheckinTest, LoadGSettingsFromStore) {
std::map<std::string, std::string> settings;
settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval);
settings["checkin_url"] = "http://alternative.url/checkin";
settings["gcm_hostname"] = "alternative.gcm.host";
settings["gcm_secure_port"] = "7777";
settings["gcm_registration_url"] = "http://alternative.url/registration";
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
StartGCMClient();
EXPECT_EQ(base::Seconds(kSettingsCheckinInterval),
gservices_settings().GetCheckinInterval());
EXPECT_EQ(GURL("http://alternative.url/checkin"),
gservices_settings().GetCheckinURL());
EXPECT_EQ(GURL("http://alternative.url/registration"),
gservices_settings().GetRegistrationURL());
EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
gservices_settings().GetMCSMainEndpoint());
EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
gservices_settings().GetMCSFallbackEndpoint());
}
// This test only checks that periodic checkin happens.
TEST_F(GCMClientImplCheckinTest, CheckinWithAccounts) {
std::map<std::string, std::string> settings;
settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval);
settings["checkin_url"] = "http://alternative.url/checkin";
settings["gcm_hostname"] = "alternative.gcm.host";
settings["gcm_secure_port"] = "7777";
settings["gcm_registration_url"] = "http://alternative.url/registration";
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
std::vector<GCMClient::AccountTokenInfo> account_tokens;
account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
gcm_client()->SetAccountTokens(account_tokens);
EXPECT_TRUE(device_checkin_info().last_checkin_accounts.empty());
EXPECT_TRUE(device_checkin_info().accounts_set);
EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
device_checkin_info().account_tokens);
PumpLoopUntilIdle();
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
std::set<std::string> accounts;
accounts.insert("test_user1@gmail.com");
accounts.insert("test_user2@gmail.com");
EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
EXPECT_TRUE(device_checkin_info().accounts_set);
EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
device_checkin_info().account_tokens);
}
// This test only checks that periodic checkin happens.
TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountRemoved) {
std::map<std::string, std::string> settings;
settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval);
settings["checkin_url"] = "http://alternative.url/checkin";
settings["gcm_hostname"] = "alternative.gcm.host";
settings["gcm_secure_port"] = "7777";
settings["gcm_registration_url"] = "http://alternative.url/registration";
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
std::vector<GCMClient::AccountTokenInfo> account_tokens;
account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
gcm_client()->SetAccountTokens(account_tokens);
PumpLoopUntilIdle();
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
EXPECT_EQ(2UL, device_checkin_info().last_checkin_accounts.size());
EXPECT_TRUE(device_checkin_info().accounts_set);
EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
device_checkin_info().account_tokens);
account_tokens.erase(account_tokens.begin() + 1);
gcm_client()->SetAccountTokens(account_tokens);
PumpLoopUntilIdle();
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
std::set<std::string> accounts;
accounts.insert("test_user1@gmail.com");
EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
EXPECT_TRUE(device_checkin_info().accounts_set);
EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
device_checkin_info().account_tokens);
}
// This test only checks that periodic checkin happens.
TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountReplaced) {
std::map<std::string, std::string> settings;
settings["checkin_interval"] = base::NumberToString(kSettingsCheckinInterval);
settings["checkin_url"] = "http://alternative.url/checkin";
settings["gcm_hostname"] = "alternative.gcm.host";
settings["gcm_secure_port"] = "7777";
settings["gcm_registration_url"] = "http://alternative.url/registration";
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
std::vector<GCMClient::AccountTokenInfo> account_tokens;
account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
gcm_client()->SetAccountTokens(account_tokens);
PumpLoopUntilIdle();
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
std::set<std::string> accounts;
accounts.insert("test_user1@gmail.com");
EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
// This should trigger another checkin, because the list of accounts is
// different.
account_tokens.clear();
account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
gcm_client()->SetAccountTokens(account_tokens);
PumpLoopUntilIdle();
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken,
GServicesSettings::CalculateDigest(settings), settings));
accounts.clear();
accounts.insert("test_user2@gmail.com");
EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
EXPECT_TRUE(device_checkin_info().accounts_set);
EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
device_checkin_info().account_tokens);
}
TEST_F(GCMClientImplCheckinTest, ResetStoreWhenCheckinRejected) {
base::HistogramTester histogram_tester;
std::map<std::string, std::string> settings;
ASSERT_NO_FATAL_FAILURE(FailCheckin(net::HTTP_UNAUTHORIZED));
PumpLoopUntilIdle();
// Store should have been destroyed. Restart client and verify the initial
// checkin response is persisted.
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
StartGCMClient();
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId2, kDeviceSecurityToken2,
GServicesSettings::CalculateDigest(settings), settings));
EXPECT_EQ(LOADING_COMPLETED, last_event());
EXPECT_EQ(kDeviceAndroidId2, mcs_client()->last_android_id());
EXPECT_EQ(kDeviceSecurityToken2, mcs_client()->last_security_token());
}
class GCMClientImplStartAndStopTest : public GCMClientImplTest {
public:
GCMClientImplStartAndStopTest();
~GCMClientImplStartAndStopTest() override;
void SetUp() override;
void DefaultCompleteCheckin();
};
GCMClientImplStartAndStopTest::GCMClientImplStartAndStopTest() {
}
GCMClientImplStartAndStopTest::~GCMClientImplStartAndStopTest() {
}
void GCMClientImplStartAndStopTest::SetUp() {
testing::Test::SetUp();
ASSERT_TRUE(CreateUniqueTempDir());
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
}
void GCMClientImplStartAndStopTest::DefaultCompleteCheckin() {
ASSERT_NO_FATAL_FAILURE(
CompleteCheckin(kDeviceAndroidId, kDeviceSecurityToken, std::string(),
std::map<std::string, std::string>()));
PumpLoopUntilIdle();
}
TEST_F(GCMClientImplStartAndStopTest, DISABLED_StartStopAndRestart) {
// GCMClientImpl should be in INITIALIZED state at first.
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Delay start the GCM.
gcm_client()->Start(GCMClient::DELAYED_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Stop the GCM.
gcm_client()->Stop();
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Restart the GCM without delay.
gcm_client()->Start(GCMClient::IMMEDIATE_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
}
TEST_F(GCMClientImplStartAndStopTest, DelayedStartAndStopImmediately) {
// GCMClientImpl should be in INITIALIZED state at first.
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Delay start the GCM and then stop it immediately.
gcm_client()->Start(GCMClient::DELAYED_START);
gcm_client()->Stop();
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
}
TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndStopImmediately) {
// GCMClientImpl should be in INITIALIZED state at first.
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Start the GCM and then stop it immediately.
gcm_client()->Start(GCMClient::IMMEDIATE_START);
gcm_client()->Stop();
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
}
TEST_F(GCMClientImplStartAndStopTest, DelayedStartStopAndRestart) {
// GCMClientImpl should be in INITIALIZED state at first.
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Delay start the GCM and then stop and restart it immediately.
gcm_client()->Start(GCMClient::DELAYED_START);
gcm_client()->Stop();
gcm_client()->Start(GCMClient::DELAYED_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
}
TEST_F(GCMClientImplStartAndStopTest, ImmediateStartStopAndRestart) {
// GCMClientImpl should be in INITIALIZED state at first.
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Start the GCM and then stop and restart it immediately.
gcm_client()->Start(GCMClient::IMMEDIATE_START);
gcm_client()->Stop();
gcm_client()->Start(GCMClient::IMMEDIATE_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
}
TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndThenImmediateStart) {
// GCMClientImpl should be in INITIALIZED state at first.
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Start the GCM immediately and complete the checkin.
gcm_client()->Start(GCMClient::IMMEDIATE_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
ASSERT_NO_FATAL_FAILURE(DefaultCompleteCheckin());
EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
// Stop the GCM.
gcm_client()->Stop();
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Start the GCM immediately. GCMClientImpl should be in READY state.
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
gcm_client()->Start(GCMClient::IMMEDIATE_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
}
TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndThenDelayStart) {
// GCMClientImpl should be in INITIALIZED state at first.
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Start the GCM immediately and complete the checkin.
gcm_client()->Start(GCMClient::IMMEDIATE_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
ASSERT_NO_FATAL_FAILURE(DefaultCompleteCheckin());
EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
// Stop the GCM.
gcm_client()->Stop();
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Delay start the GCM. GCMClientImpl should be in LOADED state.
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
gcm_client()->Start(GCMClient::DELAYED_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::LOADED, gcm_client_state());
}
TEST_F(GCMClientImplStartAndStopTest, DISABLED_DelayedStartRace) {
// GCMClientImpl should be in INITIALIZED state at first.
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Delay start the GCM, then start it immediately while it's still loading.
gcm_client()->Start(GCMClient::DELAYED_START);
gcm_client()->Start(GCMClient::IMMEDIATE_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
ASSERT_NO_FATAL_FAILURE(DefaultCompleteCheckin());
EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
}
TEST_F(GCMClientImplStartAndStopTest, DelayedStart) {
// GCMClientImpl should be in INITIALIZED state at first.
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Delay start the GCM. The store will not be loaded and GCMClientImpl should
// still be in INITIALIZED state.
gcm_client()->Start(GCMClient::DELAYED_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Start the GCM immediately and complete the checkin.
gcm_client()->Start(GCMClient::IMMEDIATE_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
ASSERT_NO_FATAL_FAILURE(DefaultCompleteCheckin());
EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
// Registration.
std::vector<std::string> senders;
senders.push_back("sender");
Register(kExtensionAppId, senders);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("reg_id"));
EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
// Stop the GCM.
gcm_client()->Stop();
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
// Delay start the GCM. GCM is indeed started without delay because the
// registration record has been found.
BuildGCMClient(base::TimeDelta());
InitializeGCMClient();
gcm_client()->Start(GCMClient::DELAYED_START);
PumpLoopUntilIdle();
EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
}
// Test for known account mappings and last token fetching time being passed
// to OnGCMReady.
TEST_F(GCMClientImplStartAndStopTest, OnGCMReadyAccountsAndTokenFetchingTime) {
// Start the GCM and wait until it is ready.
gcm_client()->Start(GCMClient::IMMEDIATE_START);
PumpLoopUntilIdle();
ASSERT_NO_FATAL_FAILURE(DefaultCompleteCheckin());
base::Time expected_time = base::Time::Now();
gcm_client()->SetLastTokenFetchTime(expected_time);
AccountMapping expected_mapping;
expected_mapping.account_id = CoreAccountId("accId");
expected_mapping.email = "email@gmail.com";
expected_mapping.status = AccountMapping::MAPPED;
expected_mapping.status_change_timestamp = expected_time;
gcm_client()->UpdateAccountMapping(expected_mapping);
PumpLoopUntilIdle();
// Stop the GCM.
gcm_client()->Stop();
PumpLoopUntilIdle();
// Restart the GCM.
gcm_client()->Start(GCMClient::IMMEDIATE_START);
PumpLoopUntilIdle();
EXPECT_EQ(LOADING_COMPLETED, last_event());
EXPECT_EQ(expected_time, last_token_fetch_time());
ASSERT_EQ(1UL, last_account_mappings().size());
const AccountMapping& actual_mapping = last_account_mappings()[0];
EXPECT_EQ(expected_mapping.account_id, actual_mapping.account_id);
EXPECT_EQ(expected_mapping.email, actual_mapping.email);
EXPECT_EQ(expected_mapping.status, actual_mapping.status);
EXPECT_EQ(expected_mapping.status_change_timestamp,
actual_mapping.status_change_timestamp);
}
class GCMClientInstanceIDTest : public GCMClientImplTest {
public:
GCMClientInstanceIDTest();
~GCMClientInstanceIDTest() override;
void AddInstanceID(const std::string& app_id,
const std::string& instance_id);
void RemoveInstanceID(const std::string& app_id);
void GetToken(const std::string& app_id,
const std::string& authorized_entity,
const std::string& scope);
void DeleteToken(const std::string& app_id,
const std::string& authorized_entity,
const std::string& scope);
void CompleteDeleteToken();
bool ExistsToken(const std::string& app_id,
const std::string& authorized_entity,
const std::string& scope) const;
};
GCMClientInstanceIDTest::GCMClientInstanceIDTest() {
}
GCMClientInstanceIDTest::~GCMClientInstanceIDTest() {
}
void GCMClientInstanceIDTest::AddInstanceID(const std::string& app_id,
const std::string& instance_id) {
gcm_client()->AddInstanceIDData(app_id, instance_id, "123");
}
void GCMClientInstanceIDTest::RemoveInstanceID(const std::string& app_id) {
gcm_client()->RemoveInstanceIDData(app_id);
}
void GCMClientInstanceIDTest::GetToken(const std::string& app_id,
const std::string& authorized_entity,
const std::string& scope) {
auto instance_id_info = base::MakeRefCounted<InstanceIDTokenInfo>();
instance_id_info->app_id = app_id;
instance_id_info->authorized_entity = authorized_entity;
instance_id_info->scope = scope;
gcm_client()->Register(std::move(instance_id_info));
}
void GCMClientInstanceIDTest::DeleteToken(const std::string& app_id,
const std::string& authorized_entity,
const std::string& scope) {
auto instance_id_info = base::MakeRefCounted<InstanceIDTokenInfo>();
instance_id_info->app_id = app_id;
instance_id_info->authorized_entity = authorized_entity;
instance_id_info->scope = scope;
gcm_client()->Unregister(std::move(instance_id_info));
}
void GCMClientInstanceIDTest::CompleteDeleteToken() {
std::string response(kDeleteTokenResponse);
EXPECT_TRUE(url_loader_factory()->SimulateResponseForPendingRequest(
GURL(kRegisterUrl), network::URLLoaderCompletionStatus(net::OK),
network::CreateURLResponseHead(net::HTTP_OK), response));
// Give a chance for GCMStoreImpl::Backend to finish persisting data.
PumpLoopUntilIdle();
}
bool GCMClientInstanceIDTest::ExistsToken(const std::string& app_id,
const std::string& authorized_entity,
const std::string& scope) const {
auto instance_id_info = base::MakeRefCounted<InstanceIDTokenInfo>();
instance_id_info->app_id = app_id;
instance_id_info->authorized_entity = authorized_entity;
instance_id_info->scope = scope;
return gcm_client()->registrations_.count(std::move(instance_id_info)) > 0;
}
TEST_F(GCMClientInstanceIDTest, GetToken) {
AddInstanceID(kExtensionAppId, kInstanceID);
// Get a token.
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender, kScope));
GetToken(kExtensionAppId, kSender, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token1"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("token1", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsToken(kExtensionAppId, kSender, kScope));
// Get another token.
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender2, kScope));
GetToken(kExtensionAppId, kSender2, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token2"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("token2", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsToken(kExtensionAppId, kSender2, kScope));
// The 1st token still exists.
EXPECT_TRUE(ExistsToken(kExtensionAppId, kSender, kScope));
}
// Most tests in this file use kExtensionAppId which is special-cased by
// InstanceIDUsesSubtypeForAppId in gcm_client_impl.cc. This test uses
// kSubtypeAppId to cover the alternate case.
TEST_F(GCMClientInstanceIDTest, GetTokenWithSubtype) {
ASSERT_EQ(GCMClientImpl::READY, gcm_client_state());
AddInstanceID(kSubtypeAppId, kInstanceID);
EXPECT_FALSE(ExistsToken(kSubtypeAppId, kSender, kScope));
// Get a token.
GetToken(kSubtypeAppId, kSender, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token1"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kSubtypeAppId, last_app_id());
EXPECT_EQ("token1", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsToken(kSubtypeAppId, kSender, kScope));
// Delete the token.
DeleteToken(kSubtypeAppId, kSender, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteDeleteToken());
EXPECT_FALSE(ExistsToken(kSubtypeAppId, kSender, kScope));
}
TEST_F(GCMClientInstanceIDTest, DeleteInvalidToken) {
AddInstanceID(kExtensionAppId, kInstanceID);
// Delete an invalid token.
DeleteToken(kExtensionAppId, "Foo@#$", kScope);
PumpLoopUntilIdle();
EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(GCMClient::INVALID_PARAMETER, last_result());
reset_last_event();
// Delete a non-existing token.
DeleteToken(kExtensionAppId, kSender, kScope);
PumpLoopUntilIdle();
EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(GCMClient::INVALID_PARAMETER, last_result());
}
TEST_F(GCMClientInstanceIDTest, DeleteSingleToken) {
AddInstanceID(kExtensionAppId, kInstanceID);
// Get a token.
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender, kScope));
GetToken(kExtensionAppId, kSender, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token1"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("token1", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsToken(kExtensionAppId, kSender, kScope));
reset_last_event();
// Get another token.
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender2, kScope));
GetToken(kExtensionAppId, kSender2, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token2"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("token2", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsToken(kExtensionAppId, kSender2, kScope));
// The 1st token still exists.
EXPECT_TRUE(ExistsToken(kExtensionAppId, kSender, kScope));
reset_last_event();
// Delete the 2nd token.
DeleteToken(kExtensionAppId, kSender2, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteDeleteToken());
EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
// The 2nd token is gone while the 1st token still exists.
EXPECT_TRUE(ExistsToken(kExtensionAppId, kSender, kScope));
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender2, kScope));
reset_last_event();
// Delete the 1st token.
DeleteToken(kExtensionAppId, kSender, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteDeleteToken());
EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
// Both tokens are gone now.
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender, kScope));
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender, kScope));
reset_last_event();
// Trying to delete the token again will get an error.
DeleteToken(kExtensionAppId, kSender, kScope);
PumpLoopUntilIdle();
EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(GCMClient::INVALID_PARAMETER, last_result());
}
TEST_F(GCMClientInstanceIDTest, DISABLED_DeleteAllTokens) {
AddInstanceID(kExtensionAppId, kInstanceID);
// Get a token.
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender, kScope));
GetToken(kExtensionAppId, kSender, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token1"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("token1", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsToken(kExtensionAppId, kSender, kScope));
reset_last_event();
// Get another token.
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender2, kScope));
GetToken(kExtensionAppId, kSender2, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token2"));
EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ("token2", last_registration_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
EXPECT_TRUE(ExistsToken(kExtensionAppId, kSender2, kScope));
// The 1st token still exists.
EXPECT_TRUE(ExistsToken(kExtensionAppId, kSender, kScope));
reset_last_event();
// Delete all tokens.
DeleteToken(kExtensionAppId, "*", "*");
ASSERT_NO_FATAL_FAILURE(CompleteDeleteToken());
EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
// All tokens are gone now.
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender, kScope));
EXPECT_FALSE(ExistsToken(kExtensionAppId, kSender, kScope));
}
TEST_F(GCMClientInstanceIDTest, DeleteAllTokensBeforeGetAnyToken) {
AddInstanceID(kExtensionAppId, kInstanceID);
// Delete all tokens without getting a token first.
DeleteToken(kExtensionAppId, "*", "*");
// No need to call CompleteDeleteToken since unregistration request should
// not be triggered.
PumpLoopUntilIdle();
EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(GCMClient::SUCCESS, last_result());
}
TEST_F(GCMClientInstanceIDTest, DispatchDownstreamMessageWithoutSubtype) {
AddInstanceID(kExtensionAppId, kInstanceID);
GetToken(kExtensionAppId, kSender, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token1"));
std::map<std::string, std::string> expected_data;
MCSMessage message(BuildDownstreamMessage(
kSender, kExtensionAppId, std::string() /* subtype */, expected_data,
std::string() /* raw_data */));
EXPECT_TRUE(message.IsValid());
ReceiveMessageFromMCS(message);
EXPECT_EQ(MESSAGE_RECEIVED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(expected_data.size(), last_message().data.size());
EXPECT_EQ(expected_data, last_message().data);
EXPECT_EQ(kSender, last_message().sender_id);
}
TEST_F(GCMClientInstanceIDTest, DispatchDownstreamMessageWithSubtype) {
AddInstanceID(kSubtypeAppId, kInstanceID);
GetToken(kSubtypeAppId, kSender, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token1"));
std::map<std::string, std::string> expected_data;
MCSMessage message(BuildDownstreamMessage(
kSender, kProductCategoryForSubtypes, kSubtypeAppId /* subtype */,
expected_data, std::string() /* raw_data */));
EXPECT_TRUE(message.IsValid());
ReceiveMessageFromMCS(message);
EXPECT_EQ(MESSAGE_RECEIVED, last_event());
EXPECT_EQ(kSubtypeAppId, last_app_id());
EXPECT_EQ(expected_data.size(), last_message().data.size());
EXPECT_EQ(expected_data, last_message().data);
EXPECT_EQ(kSender, last_message().sender_id);
}
TEST_F(GCMClientInstanceIDTest, DispatchDownstreamMessageWithFakeSubtype) {
// Victim non-extension registration.
AddInstanceID(kSubtypeAppId, "iid_1");
GetToken(kSubtypeAppId, kSender, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token1"));
// Malicious extension registration.
AddInstanceID(kExtensionAppId, "iid_2");
GetToken(kExtensionAppId, kSender, kScope);
ASSERT_NO_FATAL_FAILURE(CompleteRegistration("token2"));
std::map<std::string, std::string> expected_data;
// Message for kExtensionAppId should be delivered to the extension rather
// than the victim app, despite the malicious subtype property attempting to
// impersonate victim app.
MCSMessage message(BuildDownstreamMessage(
kSender, kExtensionAppId /* category */, kSubtypeAppId /* subtype */,
expected_data, std::string() /* raw_data */));
EXPECT_TRUE(message.IsValid());
ReceiveMessageFromMCS(message);
EXPECT_EQ(MESSAGE_RECEIVED, last_event());
EXPECT_EQ(kExtensionAppId, last_app_id());
EXPECT_EQ(expected_data.size(), last_message().data.size());
EXPECT_EQ(expected_data, last_message().data);
EXPECT_EQ(kSender, last_message().sender_id);
}
} // namespace gcm
| 37.50813 | 80 | 0.75103 | Yannic |
3ee0a7010de3caa5b3fd80e905da793aa37deb72 | 791 | cpp | C++ | duomeiti/randomizeicontooleffect.cpp | xzchaoo/--- | 76d4893d88ee2cf8c294c70a474df840754e6de8 | [
"Apache-2.0"
] | 1 | 2019-02-24T08:36:32.000Z | 2019-02-24T08:36:32.000Z | duomeiti/randomizeicontooleffect.cpp | xzchaoo/--- | 76d4893d88ee2cf8c294c70a474df840754e6de8 | [
"Apache-2.0"
] | null | null | null | duomeiti/randomizeicontooleffect.cpp | xzchaoo/--- | 76d4893d88ee2cf8c294c70a474df840754e6de8 | [
"Apache-2.0"
] | null | null | null | #include "randomizeicontooleffect.h"
#include "iconmanager.h"
#include "gameicon.h"
#include <QList>
#include <QDebug>
#include "animationgroup.h"
#include "Animation.h"
#include "inversespiralfunction.h"
#include "spiralfunction.h"
#include "gameconfig.h"
RandomizeIconToolEffect::RandomizeIconToolEffect(QObject *parent) :
ToolEffect(parent){
}
//TODO
void RandomizeIconToolEffect::process(IconManager* iconManager){
m_musicPlayer->play (m_gc->gets("/toolmusic/path")+"/random.wav");
QList<GameIcon*>& list=*iconManager->gameIconList ();
int iconTypes=m_gc->iconTypes ();
for(int i=0;i<list.size ();++i){
if(list[i]==NULL||list[i]->isFreezing ())
continue;
list[i]->setIconType (qrand()%iconTypes);
}
m_toolEffectScore=m_gc->getInt ("/RandomizeIconToolEffect/score",0);
}
| 27.275862 | 69 | 0.738306 | xzchaoo |
3ee31db21021baef3203c2a4dae8b8462cc8ac1e | 8,239 | cpp | C++ | Code/UnitTests/FoundationTest/Logging/LogTest.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 703 | 2015-03-07T15:30:40.000Z | 2022-03-30T00:12:40.000Z | Code/UnitTests/FoundationTest/Logging/LogTest.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 233 | 2015-01-11T16:54:32.000Z | 2022-03-19T18:00:47.000Z | Code/UnitTests/FoundationTest/Logging/LogTest.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 101 | 2016-10-28T14:05:10.000Z | 2022-03-30T19:00:59.000Z | #include <FoundationTest/FoundationTestPCH.h>
#include <Foundation/Configuration/Startup.h>
#include <Foundation/IO/FileSystem/DataDirTypeFolder.h>
#include <Foundation/Logging/ConsoleWriter.h>
#include <Foundation/Logging/HTMLWriter.h>
#include <Foundation/Logging/Log.h>
#include <Foundation/Logging/VisualStudioWriter.h>
#include <Foundation/Threading/Thread.h>
#include <TestFramework/Utilities/TestLogInterface.h>
EZ_CREATE_SIMPLE_TEST_GROUP(Logging);
namespace
{
class LogTestLogInterface : public ezLogInterface
{
public:
virtual void HandleLogMessage(const ezLoggingEventData& le) override
{
switch (le.m_EventType)
{
case ezLogMsgType::Flush:
m_Result.Append("[Flush]\n");
return;
case ezLogMsgType::BeginGroup:
m_Result.Append(">", le.m_szTag, " ", le.m_szText, "\n");
break;
case ezLogMsgType::EndGroup:
m_Result.Append("<", le.m_szTag, " ", le.m_szText, "\n");
break;
case ezLogMsgType::ErrorMsg:
m_Result.Append("E:", le.m_szTag, " ", le.m_szText, "\n");
break;
case ezLogMsgType::SeriousWarningMsg:
m_Result.Append("SW:", le.m_szTag, " ", le.m_szText, "\n");
break;
case ezLogMsgType::WarningMsg:
m_Result.Append("W:", le.m_szTag, " ", le.m_szText, "\n");
break;
case ezLogMsgType::SuccessMsg:
m_Result.Append("S:", le.m_szTag, " ", le.m_szText, "\n");
break;
case ezLogMsgType::InfoMsg:
m_Result.Append("I:", le.m_szTag, " ", le.m_szText, "\n");
break;
case ezLogMsgType::DevMsg:
m_Result.Append("E:", le.m_szTag, " ", le.m_szText, "\n");
break;
case ezLogMsgType::DebugMsg:
m_Result.Append("D:", le.m_szTag, " ", le.m_szText, "\n");
break;
default:
EZ_REPORT_FAILURE("Invalid msg type");
break;
}
}
ezStringBuilder m_Result;
};
} // namespace
EZ_CREATE_SIMPLE_TEST(Logging, Log)
{
LogTestLogInterface log;
LogTestLogInterface log2;
ezLogSystemScope logScope(&log);
EZ_TEST_BLOCK(ezTestBlock::Enabled, "Output")
{
EZ_LOG_BLOCK("Verse 1", "Portal: Still Alive");
ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::All);
ezLog::Success("{0}", "This was a triumph.");
ezLog::Info("{0}", "I'm making a note here:");
ezLog::Error("{0}", "Huge Success");
ezLog::Info("{0}", "It's hard to overstate my satisfaction.");
ezLog::Dev("{0}", "Aperture Science. We do what we must, because we can,");
ezLog::Dev("{0}", "For the good of all of us, except the ones who are dead.");
ezLog::Flush();
ezLog::Flush(); // second flush should be ignored
{
EZ_LOG_BLOCK("Verse 2");
ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::DevMsg);
ezLog::Dev("But there's no sense crying over every mistake.");
ezLog::Debug("You just keep on trying 'till you run out of cake.");
ezLog::Info("And the science gets done, and you make a neat gun");
ezLog::Error("for the people who are still alive.");
}
{
EZ_LOG_BLOCK("Verse 3");
ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::InfoMsg);
ezLog::Info("I'm not even angry.");
ezLog::Debug("I'm being so sincere right now.");
ezLog::Dev("Even though you broke my heart and killed me.");
ezLog::Info("And tore me to pieces,");
ezLog::Dev("and threw every piece into a fire.");
ezLog::Info("As they burned it hurt because I was so happy for you.");
ezLog::Error("Now these points of data make a beautiful line");
ezLog::Dev("and we're off the beta, we're releasing on time.");
ezLog::Flush();
ezLog::Flush();
{
EZ_LOG_BLOCK("Verse 4");
ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::SuccessMsg);
ezLog::Info("So I'm glad I got burned,");
ezLog::Debug("think of all the things we learned");
ezLog::Debug("for the people who are still alive.");
{
ezLogSystemScope logScope2(&log2);
EZ_LOG_BLOCK("Interlude");
ezLog::Info("Well here we are again. It's always such a pleasure.");
ezLog::Error("Remember when you tried to kill me twice?");
}
{
EZ_LOG_BLOCK("Verse 5");
ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::WarningMsg);
ezLog::Debug("Go ahead and leave me.");
ezLog::Info("I think I prefer to stay inside.");
ezLog::Dev("Maybe you'll find someone else, to help you.");
ezLog::Dev("Maybe Black Mesa.");
ezLog::Info("That was a joke. Haha. Fat chance.");
ezLog::Warning("Anyway, this cake is great.");
ezLog::Success("It's so delicious and moist.");
ezLog::Dev("Look at me still talking when there's science to do.");
ezLog::Error("When I look up there it makes me glad I'm not you.");
ezLog::Info("I've experiments to run,");
ezLog::SeriousWarning("there is research to be done on the people who are still alive.");
}
}
}
}
{
EZ_LOG_BLOCK("Verse 6", "Last One");
ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::ErrorMsg);
ezLog::Dev("And believe me I am still alive.");
ezLog::Info("I'm doing science and I'm still alive.");
ezLog::Success("I feel fantastic and I'm still alive.");
ezLog::Warning("While you're dying I'll be still alive.");
ezLog::Error("And when you're dead I will be, still alive.");
ezLog::Debug("Still alive, still alive.");
}
/// \todo This test will fail if EZ_COMPILE_FOR_DEVELOPMENT is disabled.
/// We also currently don't test ezLog::Debug, because our build machines compile in release and then the text below would need to be
/// different.
const char* szResult = log.m_Result;
const char* szExpected = "\
>Portal: Still Alive Verse 1\n\
S: This was a triumph.\n\
I: I'm making a note here:\n\
E: Huge Success\n\
I: It's hard to overstate my satisfaction.\n\
E: Aperture Science. We do what we must, because we can,\n\
E: For the good of all of us, except the ones who are dead.\n\
[Flush]\n\
> Verse 2\n\
E: But there's no sense crying over every mistake.\n\
I: And the science gets done, and you make a neat gun\n\
E: for the people who are still alive.\n\
< Verse 2\n\
> Verse 3\n\
I: I'm not even angry.\n\
I: And tore me to pieces,\n\
I: As they burned it hurt because I was so happy for you.\n\
E: Now these points of data make a beautiful line\n\
[Flush]\n\
> Verse 4\n\
> Verse 5\n\
W: Anyway, this cake is great.\n\
E: When I look up there it makes me glad I'm not you.\n\
SW: there is research to be done on the people who are still alive.\n\
< Verse 5\n\
< Verse 4\n\
< Verse 3\n\
<Portal: Still Alive Verse 1\n\
>Last One Verse 6\n\
E: And when you're dead I will be, still alive.\n\
<Last One Verse 6\n\
";
EZ_TEST_STRING(szResult, szExpected);
const char* szResult2 = log2.m_Result;
const char* szExpected2 = "\
> Interlude\n\
I: Well here we are again. It's always such a pleasure.\n\
E: Remember when you tried to kill me twice?\n\
< Interlude\n\
";
EZ_TEST_STRING(szResult2, szExpected2);
}
EZ_CREATE_SIMPLE_TEST(Logging, GlobalTestLog)
{
ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::All);
{
ezTestLogInterface log;
ezTestLogSystemScope scope(&log, true);
log.ExpectMessage("managed to break", ezLogMsgType::ErrorMsg);
log.ExpectMessage("my heart", ezLogMsgType::WarningMsg);
log.ExpectMessage("see you", ezLogMsgType::WarningMsg, 10);
{
class LogThread : public ezThread
{
public:
virtual ezUInt32 Run() override
{
ezLog::Warning("I see you!");
ezLog::Debug("Test debug");
return 0;
}
};
LogThread thread[10];
for (ezUInt32 i = 0; i < 10; ++i)
{
thread[i].Start();
}
ezLog::Error("The only thing you managed to break so far");
ezLog::Warning("is my heart");
for (ezUInt32 i = 0; i < 10; ++i)
{
thread[i].Join();
}
}
}
}
| 32.058366 | 135 | 0.627139 | Tekh-ops |
3ee324fbbb8ecce844bee0fffb92c794157e69e4 | 2,021 | cpp | C++ | test/inf.cpp | aclex/floaxie | 81b34c37ce8304013c0d6b70aed12ef5960385af | [
"Apache-2.0"
] | 25 | 2016-02-11T16:56:48.000Z | 2022-02-01T10:27:57.000Z | test/inf.cpp | aclex/floaxie | 81b34c37ce8304013c0d6b70aed12ef5960385af | [
"Apache-2.0"
] | 2 | 2016-04-09T12:29:35.000Z | 2019-05-09T22:02:25.000Z | test/inf.cpp | aclex/floaxie | 81b34c37ce8304013c0d6b70aed12ef5960385af | [
"Apache-2.0"
] | 5 | 2016-08-10T18:11:59.000Z | 2021-04-10T16:41:50.000Z | #include <array>
#include <utility>
#include <iostream>
#include <cmath>
#include <cstdint>
#include "floaxie/atof.h"
#include "floaxie/print.h"
using namespace std;
using namespace floaxie;
namespace
{
const char* inf_str = "inf";
const char* inf_str_w = "0inf";
const char* pinf_str = "+inf";
const char* ninf_str = "-inf";
const char* uinf_str = "INf";
const char* puinf_str = "+InfINitY";
const char* muinf_str = "-inFIniTy";
const char* uinf_str_w = "infini";
}
int main(int, char**)
{
char* str_end;
const auto ret1 = atof<double>(inf_str, &str_end);
if (!std::isinf(ret1.value) || ret1.status != conversion_status::success || str_end - inf_str != 3)
{
return -1;
}
const auto ret1w = atof<double>(inf_str_w, &str_end);
if (std::isinf(ret1w.value) || ret1w.status != conversion_status::success || str_end - inf_str_w != 1)
{
return -10;
}
const auto ret2 = atof<double>(pinf_str, &str_end);
if (!std::isinf(ret2.value) || ret2.value < 0 || ret2.status != conversion_status::success || str_end - pinf_str != 4)
{
return -2;
}
const auto ret3 = atof<double>(ninf_str, &str_end);
if (!std::isinf(ret3.value) || ret3.value >= 0 || ret3.status != conversion_status::success || str_end - ninf_str != 4)
{
return -3;
}
const auto ret4 = atof<double>(uinf_str, &str_end);
if (!std::isinf(ret4.value) || ret4.status != conversion_status::success || str_end - uinf_str != 3)
{
return -4;
}
const auto ret5 = atof<double>(puinf_str, &str_end);
if (!std::isinf(ret5.value) || ret5.value < 0 || ret5.status != conversion_status::success || str_end - puinf_str != 9)
{
return -5;
}
const auto ret6 = atof<double>(muinf_str, &str_end);
if (!std::isinf(ret6.value) || ret6.value >= 0 || ret6.status != conversion_status::success || str_end - muinf_str != 9)
{
return -6;
}
const auto ret7w = atof<double>(uinf_str_w, &str_end);
if (!std::isinf(ret7w.value) || ret7w.status != conversion_status::success || str_end - uinf_str_w != 3)
{
return -11;
}
return 0;
}
| 25.910256 | 121 | 0.658585 | aclex |
3ee6414a3a9f9206ccc08bc7d69670c7e5fc156c | 48,845 | cc | C++ | Firestore/core/test/unit/local/leveldb_key_test.cc | liam-i/firebase-ios-sdk | 136e71f7aa438236421307a69c01789855515464 | [
"Apache-2.0"
] | 1 | 2022-03-26T00:08:22.000Z | 2022-03-26T00:08:22.000Z | Firestore/core/test/unit/local/leveldb_key_test.cc | AhmedShehata5/firebase-ios-sdk | b4dd98da69fca029123788e69e14d612ef44e0d1 | [
"Apache-2.0"
] | null | null | null | Firestore/core/test/unit/local/leveldb_key_test.cc | AhmedShehata5/firebase-ios-sdk | b4dd98da69fca029123788e69e14d612ef44e0d1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Google
*
* 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 "Firestore/core/src/local/leveldb_key.h"
#include <type_traits>
#include "Firestore/core/src/util/autoid.h"
#include "Firestore/core/src/util/string_util.h"
#include "Firestore/core/test/unit/testutil/testutil.h"
#include "absl/strings/match.h"
#include "gtest/gtest.h"
using firebase::firestore::model::BatchId;
using firebase::firestore::model::DocumentKey;
using firebase::firestore::model::ResourcePath;
using firebase::firestore::model::SnapshotVersion;
using firebase::firestore::model::TargetId;
namespace firebase {
namespace firestore {
namespace local {
namespace {
std::string RemoteDocKey(absl::string_view path_string) {
return LevelDbRemoteDocumentKey::Key(testutil::Key(path_string));
}
std::string RemoteDocKeyPrefix(absl::string_view path_string) {
return LevelDbRemoteDocumentKey::KeyPrefix(testutil::Resource(path_string));
}
std::string DocMutationKey(absl::string_view user_id,
absl::string_view key,
BatchId batch_id) {
return LevelDbDocumentMutationKey::Key(user_id, testutil::Key(key), batch_id);
}
std::string TargetDocKey(TargetId target_id, absl::string_view key) {
return LevelDbTargetDocumentKey::Key(target_id, testutil::Key(key));
}
std::string DocTargetKey(absl::string_view key, TargetId target_id) {
return LevelDbDocumentTargetKey::Key(testutil::Key(key), target_id);
}
std::string RemoteDocumentReadTimeKeyPrefix(absl::string_view collection_path,
int64_t version) {
return LevelDbRemoteDocumentReadTimeKey::KeyPrefix(
testutil::Resource(collection_path), testutil::Version(version));
}
std::string RemoteDocumentReadTimeKey(absl::string_view collection_path,
int64_t version,
absl::string_view document_id) {
return LevelDbRemoteDocumentReadTimeKey::Key(
testutil::Resource(collection_path), testutil::Version(version),
document_id);
}
} // namespace
/**
* Asserts that the description for given key is equal to the expected
* description.
*
* @param key A StringView of a textual key
* @param key A string that `Describe(key)` is expected to produce.
*/
#define AssertExpectedKeyDescription(expected_description, key) \
ASSERT_EQ((expected_description), DescribeKey(key))
TEST(LevelDbMutationKeyTest, Prefixing) {
auto table_key = LevelDbMutationKey::KeyPrefix();
auto empty_user_key = LevelDbMutationKey::KeyPrefix("");
auto foo_user_key = LevelDbMutationKey::KeyPrefix("foo");
auto foo2_key = LevelDbMutationKey::Key("foo", 2);
ASSERT_TRUE(absl::StartsWith(empty_user_key, table_key));
// This is critical: prefixes of the a value don't convert into prefixes of
// the key.
ASSERT_TRUE(absl::StartsWith(foo_user_key, table_key));
ASSERT_FALSE(absl::StartsWith(foo_user_key, empty_user_key));
// However whole segments in common are prefixes.
ASSERT_TRUE(absl::StartsWith(foo2_key, table_key));
ASSERT_TRUE(absl::StartsWith(foo2_key, foo_user_key));
}
TEST(LevelDbMutationKeyTest, EncodeDecodeCycle) {
LevelDbMutationKey key;
std::string user("foo");
std::vector<BatchId> batch_ids{0, 1, 100, INT_MAX - 1, INT_MAX};
for (auto batch_id : batch_ids) {
auto encoded = LevelDbMutationKey::Key(user, batch_id);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(user, key.user_id());
ASSERT_EQ(batch_id, key.batch_id());
}
}
TEST(LevelDbMutationKeyTest, Description) {
AssertExpectedKeyDescription("[mutation: incomplete key]",
LevelDbMutationKey::KeyPrefix());
AssertExpectedKeyDescription("[mutation: user_id=user1 incomplete key]",
LevelDbMutationKey::KeyPrefix("user1"));
auto key = LevelDbMutationKey::Key("user1", 42);
AssertExpectedKeyDescription("[mutation: user_id=user1 batch_id=42]", key);
AssertExpectedKeyDescription(
"[mutation: user_id=user1 batch_id=42 invalid "
"key=<hW11dGF0aW9uAAGNdXNlcjEAAYqqgCBleHRyYQ==>]",
key + " extra");
// Truncate the key so that it's missing its terminator.
key.resize(key.size() - 1);
AssertExpectedKeyDescription(
"[mutation: user_id=user1 batch_id=42 incomplete key]", key);
}
TEST(LevelDbDocumentMutationKeyTest, Prefixing) {
auto table_key = LevelDbDocumentMutationKey::KeyPrefix();
auto empty_user_key = LevelDbDocumentMutationKey::KeyPrefix("");
auto foo_user_key = LevelDbDocumentMutationKey::KeyPrefix("foo");
DocumentKey document_key = testutil::Key("foo/bar");
auto foo2_key = LevelDbDocumentMutationKey::Key("foo", document_key, 2);
ASSERT_TRUE(absl::StartsWith(empty_user_key, table_key));
// While we want a key with whole segments in common be considered a prefix
// it's vital that partial segments in common not be prefixes.
ASSERT_TRUE(absl::StartsWith(foo_user_key, table_key));
// Here even though "" is a prefix of "foo", that prefix is within a segment,
// so keys derived from those segments cannot be prefixes of each other.
ASSERT_FALSE(absl::StartsWith(foo_user_key, empty_user_key));
ASSERT_FALSE(absl::StartsWith(empty_user_key, foo_user_key));
// However whole segments in common are prefixes.
ASSERT_TRUE(absl::StartsWith(foo2_key, table_key));
ASSERT_TRUE(absl::StartsWith(foo2_key, foo_user_key));
}
TEST(LevelDbDocumentMutationKeyTest, EncodeDecodeCycle) {
LevelDbDocumentMutationKey key;
std::string user("foo");
std::vector<DocumentKey> document_keys{testutil::Key("a/b"),
testutil::Key("a/b/c/d")};
std::vector<BatchId> batch_ids{0, 1, 100, INT_MAX - 1, INT_MAX};
for (BatchId batch_id : batch_ids) {
for (auto&& document_key : document_keys) {
auto encoded =
LevelDbDocumentMutationKey::Key(user, document_key, batch_id);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(user, key.user_id());
ASSERT_EQ(document_key, key.document_key());
ASSERT_EQ(batch_id, key.batch_id());
}
}
}
TEST(LevelDbDocumentMutationKeyTest, Ordering) {
// Different user:
ASSERT_LT(DocMutationKey("1", "foo/bar", 0),
DocMutationKey("10", "foo/bar", 0));
ASSERT_LT(DocMutationKey("1", "foo/bar", 0),
DocMutationKey("2", "foo/bar", 0));
// Different paths:
ASSERT_LT(DocMutationKey("1", "foo/bar", 0),
DocMutationKey("1", "foo/baz", 0));
ASSERT_LT(DocMutationKey("1", "foo/bar", 0),
DocMutationKey("1", "foo/bar2", 0));
ASSERT_LT(DocMutationKey("1", "foo/bar", 0),
DocMutationKey("1", "foo/bar/suffix/key", 0));
ASSERT_LT(DocMutationKey("1", "foo/bar/suffix/key", 0),
DocMutationKey("1", "foo/bar2", 0));
// Different batch_id:
ASSERT_LT(DocMutationKey("1", "foo/bar", 0),
DocMutationKey("1", "foo/bar", 1));
}
TEST(LevelDbDocumentMutationKeyTest, Description) {
AssertExpectedKeyDescription("[document_mutation: incomplete key]",
LevelDbDocumentMutationKey::KeyPrefix());
AssertExpectedKeyDescription(
"[document_mutation: user_id=user1 incomplete key]",
LevelDbDocumentMutationKey::KeyPrefix("user1"));
auto key = LevelDbDocumentMutationKey::KeyPrefix(
"user1", testutil::Resource("foo/bar"));
AssertExpectedKeyDescription(
"[document_mutation: user_id=user1 path=foo/bar incomplete key]", key);
key = LevelDbDocumentMutationKey::Key("user1", testutil::Key("foo/bar"), 42);
AssertExpectedKeyDescription(
"[document_mutation: user_id=user1 path=foo/bar batch_id=42]", key);
}
TEST(LevelDbTargetGlobalKeyTest, EncodeDecodeCycle) {
LevelDbTargetGlobalKey key;
auto encoded = LevelDbTargetGlobalKey::Key();
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
}
TEST(LevelDbTargetGlobalKeyTest, Description) {
AssertExpectedKeyDescription("[target_global:]",
LevelDbTargetGlobalKey::Key());
}
TEST(LevelDbTargetKeyTest, EncodeDecodeCycle) {
LevelDbTargetKey key;
TargetId target_id = 42;
auto encoded = LevelDbTargetKey::Key(42);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(target_id, key.target_id());
}
TEST(LevelDbTargetKeyTest, Description) {
AssertExpectedKeyDescription("[target: target_id=42]",
LevelDbTargetKey::Key(42));
}
TEST(LevelDbQueryTargetKeyTest, EncodeDecodeCycle) {
LevelDbQueryTargetKey key;
std::string canonical_id("foo");
TargetId target_id = 42;
auto encoded = LevelDbQueryTargetKey::Key(canonical_id, 42);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(canonical_id, key.canonical_id());
ASSERT_EQ(target_id, key.target_id());
}
TEST(LevelDbQueryKeyTest, Description) {
AssertExpectedKeyDescription("[query_target: canonical_id=foo target_id=42]",
LevelDbQueryTargetKey::Key("foo", 42));
}
TEST(TargetDocumentKeyTest, EncodeDecodeCycle) {
LevelDbTargetDocumentKey key;
auto encoded = LevelDbTargetDocumentKey::Key(42, testutil::Key("foo/bar"));
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(42, key.target_id());
ASSERT_EQ(testutil::Key("foo/bar"), key.document_key());
}
TEST(TargetDocumentKeyTest, Ordering) {
// Different target_id:
ASSERT_LT(TargetDocKey(1, "foo/bar"), TargetDocKey(2, "foo/bar"));
ASSERT_LT(TargetDocKey(2, "foo/bar"), TargetDocKey(10, "foo/bar"));
ASSERT_LT(TargetDocKey(10, "foo/bar"), TargetDocKey(100, "foo/bar"));
ASSERT_LT(TargetDocKey(42, "foo/bar"), TargetDocKey(100, "foo/bar"));
// Different paths:
ASSERT_LT(TargetDocKey(1, "foo/bar"), TargetDocKey(1, "foo/baz"));
ASSERT_LT(TargetDocKey(1, "foo/bar"), TargetDocKey(1, "foo/bar2"));
ASSERT_LT(TargetDocKey(1, "foo/bar"), TargetDocKey(1, "foo/bar/suffix/key"));
ASSERT_LT(TargetDocKey(1, "foo/bar/suffix/key"), TargetDocKey(1, "foo/bar2"));
}
TEST(TargetDocumentKeyTest, Description) {
auto key = LevelDbTargetDocumentKey::Key(42, testutil::Key("foo/bar"));
ASSERT_EQ("[target_document: target_id=42 path=foo/bar]", DescribeKey(key));
}
TEST(DocumentTargetKeyTest, EncodeDecodeCycle) {
LevelDbDocumentTargetKey key;
auto encoded = LevelDbDocumentTargetKey::Key(testutil::Key("foo/bar"), 42);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(testutil::Key("foo/bar"), key.document_key());
ASSERT_EQ(42, key.target_id());
}
TEST(DocumentTargetKeyTest, Description) {
auto key = LevelDbDocumentTargetKey::Key(testutil::Key("foo/bar"), 42);
ASSERT_EQ("[document_target: path=foo/bar target_id=42]", DescribeKey(key));
}
TEST(DocumentTargetKeyTest, Ordering) {
// Different paths:
ASSERT_LT(DocTargetKey("foo/bar", 1), DocTargetKey("foo/baz", 1));
ASSERT_LT(DocTargetKey("foo/bar", 1), DocTargetKey("foo/bar2", 1));
ASSERT_LT(DocTargetKey("foo/bar", 1), DocTargetKey("foo/bar/suffix/key", 1));
ASSERT_LT(DocTargetKey("foo/bar/suffix/key", 1), DocTargetKey("foo/bar2", 1));
// Different target_id:
ASSERT_LT(DocTargetKey("foo/bar", 1), DocTargetKey("foo/bar", 2));
ASSERT_LT(DocTargetKey("foo/bar", 2), DocTargetKey("foo/bar", 10));
ASSERT_LT(DocTargetKey("foo/bar", 10), DocTargetKey("foo/bar", 100));
ASSERT_LT(DocTargetKey("foo/bar", 42), DocTargetKey("foo/bar", 100));
}
TEST(RemoteDocumentKeyTest, Prefixing) {
auto table_key = LevelDbRemoteDocumentKey::KeyPrefix();
ASSERT_TRUE(absl::StartsWith(RemoteDocKey("foo/bar"), table_key));
// This is critical: foo/bar2 should not contain foo/bar.
ASSERT_FALSE(
absl::StartsWith(RemoteDocKey("foo/bar2"), RemoteDocKey("foo/bar")));
// Prefixes must be encoded specially
ASSERT_FALSE(absl::StartsWith(RemoteDocKey("foo/bar/baz/quu"),
RemoteDocKey("foo/bar")));
ASSERT_TRUE(absl::StartsWith(RemoteDocKey("foo/bar/baz/quu"),
RemoteDocKeyPrefix("foo/bar")));
ASSERT_TRUE(absl::StartsWith(RemoteDocKeyPrefix("foo/bar/baz/quu"),
RemoteDocKeyPrefix("foo/bar")));
ASSERT_TRUE(absl::StartsWith(RemoteDocKeyPrefix("foo/bar/baz"),
RemoteDocKeyPrefix("foo/bar")));
ASSERT_TRUE(absl::StartsWith(RemoteDocKeyPrefix("foo/bar"),
RemoteDocKeyPrefix("foo")));
}
TEST(RemoteDocumentKeyTest, Ordering) {
ASSERT_LT(RemoteDocKey("foo/bar"), RemoteDocKey("foo/bar2"));
ASSERT_LT(RemoteDocKey("foo/bar"), RemoteDocKey("foo/bar/suffix/key"));
}
TEST(RemoteDocumentKeyTest, EncodeDecodeCycle) {
LevelDbRemoteDocumentKey key;
std::vector<std::string> paths{"foo/bar", "foo/bar2", "foo/bar/baz/quux"};
for (auto&& path : paths) {
auto encoded = RemoteDocKey(path);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(testutil::Key(path), key.document_key());
}
}
TEST(RemoteDocumentKeyTest, Description) {
AssertExpectedKeyDescription(
"[remote_document: path=foo/bar/baz/quux]",
LevelDbRemoteDocumentKey::Key(testutil::Key("foo/bar/baz/quux")));
}
TEST(RemoteDocumentReadTimeKeyTest, Ordering) {
// Different collection paths:
ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("bar", 1),
RemoteDocumentReadTimeKeyPrefix("baz", 1));
ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("bar", 1),
RemoteDocumentReadTimeKeyPrefix("foo/doc/bar", 1));
ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("foo/doc/bar", 1),
RemoteDocumentReadTimeKeyPrefix("foo/doc/baz", 1));
// Different read times:
ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("foo", 1),
RemoteDocumentReadTimeKeyPrefix("foo", 2));
ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("foo", 1),
RemoteDocumentReadTimeKeyPrefix("foo", 1000000));
ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("foo", 1000000),
RemoteDocumentReadTimeKeyPrefix("foo", 1000001));
// Different document ids:
ASSERT_LT(RemoteDocumentReadTimeKey("foo", 1, "a"),
RemoteDocumentReadTimeKey("foo", 1, "b"));
}
TEST(RemoteDocumentReadTimeKeyTest, EncodeDecodeCycle) {
LevelDbRemoteDocumentReadTimeKey key;
std::vector<std::string> collection_paths{"foo", "foo/doc/bar",
"foo/doc/bar/doc/baz"};
std::vector<int64_t> versions{1, 1000000, 1000001};
std::vector<std::string> document_ids{"docA", "docB"};
for (const auto& collection_path : collection_paths) {
for (auto version : versions) {
for (const auto& document_id : document_ids) {
auto encoded =
RemoteDocumentReadTimeKey(collection_path, version, document_id);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(testutil::Resource(collection_path), key.collection_path());
ASSERT_EQ(testutil::Version(version), key.read_time());
ASSERT_EQ(document_id, key.document_id());
}
}
}
}
TEST(RemoteDocumentReadTimeKeyTest, Description) {
AssertExpectedKeyDescription(
"[remote_document_read_time: path=coll "
"snapshot_version=Timestamp(seconds=1, nanoseconds=1000) "
"document_id=doc]",
RemoteDocumentReadTimeKey("coll", 1000001, "doc"));
}
TEST(BundleKeyTest, Prefixing) {
auto table_key = LevelDbBundleKey::KeyPrefix();
ASSERT_TRUE(absl::StartsWith(LevelDbBundleKey::Key("foo/bar"), table_key));
ASSERT_FALSE(absl::StartsWith(LevelDbBundleKey::Key("foo/bar2"),
LevelDbBundleKey::Key("foo/bar")));
}
TEST(BundleKeyTest, Ordering) {
ASSERT_LT(LevelDbBundleKey::Key("foo/bar"),
LevelDbBundleKey::Key("foo/bar2"));
ASSERT_LT(LevelDbBundleKey::Key("foo/bar"),
LevelDbBundleKey::Key("foo/bar/suffix/key"));
}
TEST(BundleKeyTest, EncodeDecodeCycle) {
LevelDbBundleKey key;
std::vector<std::string> ids{"foo", "bar", "foo-bar?baz!quux"};
for (auto&& id : ids) {
auto encoded = LevelDbBundleKey::Key(id);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(id, key.bundle_id());
}
}
TEST(BundleKeyTest, Description) {
AssertExpectedKeyDescription("[bundles: bundle_id=foo-bar?baz!quux]",
LevelDbBundleKey::Key("foo-bar?baz!quux"));
}
TEST(NamedQueryKeyTest, Prefixing) {
auto table_key = LevelDbNamedQueryKey::KeyPrefix();
ASSERT_TRUE(
absl::StartsWith(LevelDbNamedQueryKey::Key("foo-bar"), table_key));
ASSERT_FALSE(absl::StartsWith(LevelDbNamedQueryKey::Key("foo-bar2"),
LevelDbNamedQueryKey::Key("foo-bar")));
}
TEST(NamedQueryKeyTest, Ordering) {
ASSERT_LT(LevelDbNamedQueryKey::Key("foo/bar"),
LevelDbNamedQueryKey::Key("foo/bar2"));
ASSERT_LT(LevelDbNamedQueryKey::Key("foo/bar"),
LevelDbNamedQueryKey::Key("foo/bar/suffix/key"));
}
TEST(NamedQueryKeyTest, EncodeDecodeCycle) {
LevelDbNamedQueryKey key;
std::vector<std::string> names{"foo/bar", "foo/bar2", "foo-bar?baz!quux"};
for (auto&& name : names) {
auto encoded = LevelDbNamedQueryKey::Key(name);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(name, key.name());
}
}
TEST(NamedQueryKeyTest, Description) {
AssertExpectedKeyDescription("[named_queries: query_name=foo-bar?baz!quux]",
LevelDbNamedQueryKey::Key("foo-bar?baz!quux"));
}
TEST(IndexConfigurationKeyTest, Prefixing) {
auto table_key = LevelDbIndexConfigurationKey::KeyPrefix();
ASSERT_TRUE(
absl::StartsWith(LevelDbIndexConfigurationKey::Key(0, ""), table_key));
ASSERT_FALSE(absl::StartsWith(LevelDbIndexConfigurationKey::Key(1, ""),
LevelDbIndexConfigurationKey::Key(2, "")));
ASSERT_FALSE(absl::StartsWith(LevelDbIndexConfigurationKey::Key(1, "g"),
LevelDbIndexConfigurationKey::Key(1, "ag")));
}
TEST(IndexConfigurationKeyTest, Ordering) {
ASSERT_LT(LevelDbIndexConfigurationKey::Key(0, ""),
LevelDbIndexConfigurationKey::Key(1, ""));
ASSERT_EQ(LevelDbIndexConfigurationKey::Key(1, ""),
LevelDbIndexConfigurationKey::Key(1, ""));
ASSERT_LT(LevelDbIndexConfigurationKey::Key(0, "a"),
LevelDbIndexConfigurationKey::Key(0, "b"));
ASSERT_EQ(LevelDbIndexConfigurationKey::Key(1, "a"),
LevelDbIndexConfigurationKey::Key(1, "a"));
}
TEST(IndexConfigurationKeyTest, EncodeDecodeCycle) {
LevelDbIndexConfigurationKey key;
std::vector<std::string> groups = {
"",
"ab",
"12",
",867t-b",
"汉语; traditional Chinese: 漢語; pinyin: Hànyǔ[b]",
"اَلْعَرَبِيَّةُ, al-ʿarabiyyah "};
for (int32_t id = -5; id < 10; ++id) {
auto s = groups[(id + 5) % groups.size()];
auto encoded = LevelDbIndexConfigurationKey::Key(id, s);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(id, key.index_id());
ASSERT_EQ(s, key.collection_group());
}
}
TEST(IndexConfigurationKeyTest, Description) {
AssertExpectedKeyDescription(
"[index_configuration: index_id=8 collection_group=group]",
LevelDbIndexConfigurationKey::Key(8, "group"));
}
TEST(IndexStateKeyTest, Prefixing) {
auto table_key = LevelDbIndexStateKey::KeyPrefix();
ASSERT_TRUE(
absl::StartsWith(LevelDbIndexStateKey::Key("user_a", 0), table_key));
ASSERT_FALSE(absl::StartsWith(LevelDbIndexStateKey::Key("user_a", 0),
LevelDbIndexStateKey::Key("user_b", 0)));
ASSERT_FALSE(absl::StartsWith(LevelDbIndexStateKey::Key("user_a", 0),
LevelDbIndexStateKey::Key("user_a", 1)));
}
TEST(IndexStateKeyTest, Ordering) {
ASSERT_LT(LevelDbIndexStateKey::Key("foo/bar", 0),
LevelDbIndexStateKey::Key("foo/bar", 1));
ASSERT_LT(LevelDbIndexStateKey::Key("foo/bar", 0),
LevelDbIndexStateKey::Key("foo/bar1", 0));
}
TEST(IndexStateKeyTest, EncodeDecodeCycle) {
LevelDbIndexStateKey key;
std::vector<std::pair<std::string, int32_t>> ids{
{"foo/bar", 0}, {"foo/bar2", 1}, {"foo-bar?baz!quux", -1}};
for (auto&& id : ids) {
auto encoded = LevelDbIndexStateKey::Key(id.first, id.second);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(id.first, key.user_id());
ASSERT_EQ(id.second, key.index_id());
}
}
TEST(IndexStateKeyTest, Description) {
AssertExpectedKeyDescription(
"[index_state: user_id=foo-bar?baz!quux index_id=99]",
LevelDbIndexStateKey::Key("foo-bar?baz!quux", 99));
}
TEST(IndexEntryKeyTest, Prefixing) {
auto table_key = LevelDbIndexEntryKey::KeyPrefix();
ASSERT_TRUE(absl::StartsWith(
LevelDbIndexEntryKey::Key(0, "user_id", "array_value_encoded",
"directional_value_encoded", "document_id_99"),
table_key));
ASSERT_TRUE(
absl::StartsWith(LevelDbIndexEntryKey::Key(0, "user_id", "", "", ""),
LevelDbIndexEntryKey::KeyPrefix(0)));
ASSERT_FALSE(absl::StartsWith(LevelDbIndexEntryKey::Key(0, "", "", "", ""),
LevelDbIndexEntryKey::Key(1, "", "", "", "")));
}
TEST(IndexEntryKeyTest, Ordering) {
std::vector<std::string> entries = {
LevelDbIndexEntryKey::Key(-1, "", "", "", ""),
LevelDbIndexEntryKey::Key(0, "", "", "", ""),
LevelDbIndexEntryKey::Key(0, "u", "", "", ""),
LevelDbIndexEntryKey::Key(0, "v", "", "", ""),
LevelDbIndexEntryKey::Key(0, "v", "a", "", ""),
LevelDbIndexEntryKey::Key(0, "v", "b", "", ""),
LevelDbIndexEntryKey::Key(0, "v", "b", "d", ""),
LevelDbIndexEntryKey::Key(0, "v", "b", "e", ""),
LevelDbIndexEntryKey::Key(0, "v", "b", "e", "doc"),
LevelDbIndexEntryKey::Key(0, "v", "b", "e", "eoc"),
};
for (size_t i = 0; i < entries.size() - 1; ++i) {
auto& left = entries[i];
auto& right = entries[i + 1];
ASSERT_LT(left, right);
}
}
TEST(IndexEntryKeyTest, EncodeDecodeCycle) {
LevelDbIndexEntryKey key;
struct IndexEntry {
int32_t index_id;
std::string user_id;
std::string array_value;
std::string dir_value;
std::string document_name;
};
std::vector<IndexEntry> entries = {
{-1, "", "", "", ""},
{0, "foo", "bar", "baz", "did"},
{999, "u", "foo-bar?baz!quux", "", ""},
{-999, "u",
"اَلْعَرَبِيَّةُ, al-ʿarabiyyah [al ʕaraˈbijːa] (audio speaker iconlisten) or "
"عَرَبِيّ, ʿarabīy",
"汉语; traditional Chinese: 漢語; pinyin: Hànyǔ[b] or also 中文", "doc"},
};
for (auto&& entry : entries) {
auto encoded = LevelDbIndexEntryKey::Key(entry.index_id, entry.user_id,
entry.array_value, entry.dir_value,
entry.document_name);
bool ok = key.Decode(encoded);
ASSERT_TRUE(ok);
ASSERT_EQ(entry.index_id, key.index_id());
ASSERT_EQ(entry.user_id, key.user_id());
ASSERT_EQ(entry.array_value, key.array_value());
ASSERT_EQ(entry.dir_value, key.directional_value());
ASSERT_EQ(entry.document_name, key.document_key());
}
}
TEST(IndexEntryKeyTest, Description) {
AssertExpectedKeyDescription(
"[index_entries: index_id=1 user_id=user array_value=array "
"directional_value=directional document_id=foo-bar?baz!quux]",
LevelDbIndexEntryKey::Key(1, "user", "array", "directional",
"foo-bar?baz!quux"));
}
TEST(LevelDbDocumentOverlayKeyTest, Constructor) {
LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123);
EXPECT_EQ(key.user_id(), "test_user");
EXPECT_EQ(key.document_key(), testutil::Key("coll/doc"));
EXPECT_EQ(key.largest_batch_id(), 123);
}
TEST(LevelDbDocumentOverlayKeyTest, RvalueOverloadedGetters) {
LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123);
model::DocumentKey&& document_key = std::move(key).document_key();
EXPECT_EQ(document_key, testutil::Key("coll/doc"));
}
TEST(LevelDbDocumentOverlayKeyTest, Encode) {
LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123);
const std::string encoded_key = key.Encode();
LevelDbDocumentOverlayKey decoded_key;
ASSERT_TRUE(decoded_key.Decode(encoded_key));
EXPECT_EQ(decoded_key.user_id(), "test_user");
EXPECT_EQ(decoded_key.document_key(), testutil::Key("coll/doc"));
EXPECT_EQ(decoded_key.largest_batch_id(), 123);
}
TEST(LevelDbDocumentOverlayKeyTest, Prefixing) {
const std::string user1_key =
LevelDbDocumentOverlayKey::KeyPrefix("test_user1");
const std::string user2_key =
LevelDbDocumentOverlayKey::KeyPrefix("test_user2");
const std::string user1_doc1_key = LevelDbDocumentOverlayKey::KeyPrefix(
"test_user1", testutil::Key("coll/doc1"));
const std::string user2_doc2_key = LevelDbDocumentOverlayKey::KeyPrefix(
"test_user2", testutil::Key("coll/doc2"));
const std::string user1_doc2_key = LevelDbDocumentOverlayKey::KeyPrefix(
"test_user1", testutil::Key("coll/doc2"));
ASSERT_TRUE(absl::StartsWith(user1_doc1_key, user1_key));
ASSERT_TRUE(absl::StartsWith(user2_doc2_key, user2_key));
ASSERT_FALSE(absl::StartsWith(user1_key, user2_key));
ASSERT_FALSE(absl::StartsWith(user2_key, user1_key));
ASSERT_FALSE(absl::StartsWith(user1_doc1_key, user1_doc2_key));
ASSERT_FALSE(absl::StartsWith(user1_doc2_key, user1_doc1_key));
const std::string user1_doc1_batch_1_key = LevelDbDocumentOverlayKey::Key(
"test_user1", testutil::Key("coll/doc1"), 1);
const std::string user2_doc1_batch_1_key = LevelDbDocumentOverlayKey::Key(
"test_user2", testutil::Key("coll/doc1"), 1);
ASSERT_TRUE(absl::StartsWith(user1_doc1_batch_1_key, user1_key));
ASSERT_TRUE(absl::StartsWith(user2_doc1_batch_1_key, user2_key));
}
TEST(LevelDbDocumentOverlayKeyTest, Ordering) {
const std::string user1_doc1_batch_1_key = LevelDbDocumentOverlayKey::Key(
"test_user1", testutil::Key("coll/doc1"), 1);
const std::string user2_doc1_batch_1_key = LevelDbDocumentOverlayKey::Key(
"test_user2", testutil::Key("coll/doc1"), 1);
const std::string user1_doc2_batch_1_key = LevelDbDocumentOverlayKey::Key(
"test_user1", testutil::Key("coll/doc2"), 1);
const std::string user1_doc1_batch_2_key = LevelDbDocumentOverlayKey::Key(
"test_user1", testutil::Key("coll/doc1"), 2);
ASSERT_LT(user1_doc1_batch_1_key, user2_doc1_batch_1_key);
ASSERT_LT(user1_doc1_batch_1_key, user1_doc2_batch_1_key);
ASSERT_LT(user1_doc1_batch_1_key, user1_doc1_batch_2_key);
}
TEST(LevelDbDocumentOverlayKeyTest, EncodeDecodeCycle) {
const std::vector<std::string> user_ids{"test_user", "foo/bar2",
"foo-bar?baz!quux"};
const std::vector<std::string> document_keys{"col1/doc1",
"col2/doc2/col3/doc3"};
const std::vector<BatchId> batch_ids{1, 2, 3};
for (const std::string& user_id : user_ids) {
for (const std::string& document_key : document_keys) {
for (BatchId batch_id : batch_ids) {
SCOPED_TRACE(absl::StrCat("user_name=", user_id,
" document_key=", document_key,
" largest_batch_id=", batch_id));
const std::string encoded = LevelDbDocumentOverlayKey::Key(
user_id, testutil::Key(document_key), batch_id);
LevelDbDocumentOverlayKey key;
EXPECT_TRUE(key.Decode(encoded));
EXPECT_EQ(key.user_id(), user_id);
EXPECT_EQ(key.document_key(), testutil::Key(document_key));
EXPECT_EQ(key.largest_batch_id(), batch_id);
}
}
}
}
TEST(LevelDbDocumentOverlayKeyTest, Description) {
AssertExpectedKeyDescription(
"[document_overlays: user_id=foo-bar?baz!quux path=coll/doc "
"batch_id=123]",
LevelDbDocumentOverlayKey::Key("foo-bar?baz!quux",
testutil::Key("coll/doc"), 123));
}
TEST(LevelDbDocumentOverlayIndexKeyTest, TypeTraits) {
static_assert(
std::has_virtual_destructor<LevelDbDocumentOverlayIndexKey>::value,
"LevelDbDocumentOverlayIndexKey should have a virtual destructor");
}
TEST(LevelDbDocumentOverlayIndexKeyTest, ToLevelDbDocumentOverlayKey) {
LevelDbDocumentOverlayIndexKey index_key;
index_key.Reset("test_user", 123, testutil::Key("coll/doc1"));
LevelDbDocumentOverlayKey key = index_key.ToLevelDbDocumentOverlayKey();
EXPECT_EQ(key.user_id(), "test_user");
EXPECT_EQ(key.largest_batch_id(), 123);
EXPECT_EQ(key.document_key(), testutil::Key("coll/doc1"));
}
TEST(LevelDbDocumentOverlayIndexKeyTest, ToLevelDbDocumentOverlayKeyRvalue) {
LevelDbDocumentOverlayIndexKey index_key;
index_key.Reset("test_user", 123, testutil::Key("coll/doc1"));
LevelDbDocumentOverlayKey key =
std::move(index_key).ToLevelDbDocumentOverlayKey();
EXPECT_EQ(key.user_id(), "test_user");
EXPECT_EQ(key.largest_batch_id(), 123);
EXPECT_EQ(key.document_key(), testutil::Key("coll/doc1"));
}
TEST(LevelDbDocumentOverlayIndexKeyTest, Getters) {
LevelDbDocumentOverlayIndexKey key;
key.Reset("test_user", 123, testutil::Key("coll/doc1"));
EXPECT_EQ(key.user_id(), "test_user");
EXPECT_EQ(key.largest_batch_id(), 123);
EXPECT_EQ(key.document_key(), testutil::Key("coll/doc1"));
}
TEST(LevelDbDocumentOverlayLargestBatchIdIndexKeyTest, Prefixing) {
const std::string user1_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::KeyPrefix("test_user1");
const std::string user2_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::KeyPrefix("test_user2");
const std::string user1_batch1_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::KeyPrefix("test_user1", 1);
const std::string user2_batch2_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::KeyPrefix("test_user2", 2);
const std::string user1_batch2_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::KeyPrefix("test_user1", 2);
ASSERT_TRUE(absl::StartsWith(user1_batch1_key, user1_key));
ASSERT_TRUE(absl::StartsWith(user2_batch2_key, user2_key));
ASSERT_FALSE(absl::StartsWith(user1_key, user2_key));
ASSERT_FALSE(absl::StartsWith(user2_key, user1_key));
ASSERT_FALSE(absl::StartsWith(user1_batch1_key, user1_batch2_key));
ASSERT_FALSE(absl::StartsWith(user1_batch2_key, user1_batch1_key));
const std::string user1_batch1_doc1_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"test_user1", 1, testutil::Key("coll/doc1"));
const std::string user2_batch1_doc1_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"test_user2", 1, testutil::Key("coll/doc1"));
ASSERT_TRUE(absl::StartsWith(user1_batch1_doc1_key, user1_key));
ASSERT_FALSE(absl::StartsWith(user1_batch1_doc1_key, user2_key));
ASSERT_TRUE(absl::StartsWith(user2_batch1_doc1_key, user2_key));
ASSERT_FALSE(absl::StartsWith(user2_batch1_doc1_key, user1_key));
ASSERT_TRUE(absl::StartsWith(user1_batch1_doc1_key, user1_batch1_key));
ASSERT_FALSE(absl::StartsWith(user1_batch1_doc1_key, user1_batch2_key));
}
TEST(LevelDbDocumentOverlayLargestBatchIdIndexKeyTest, Ordering) {
const std::string user1_batch1_doc1_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"user1", 1, testutil::Key("coll/doc1"));
const std::string user2_batch1_doc1_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"user2", 1, testutil::Key("coll/doc1"));
const std::string user1_batch2_doc1_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"user1", 2, testutil::Key("coll/doc1"));
const std::string user2_batch2_doc1_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"user2", 2, testutil::Key("coll/doc1"));
const std::string user1_batch1_doc2_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"user1", 1, testutil::Key("coll/doc2"));
const std::string user2_batch1_doc2_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"user2", 1, testutil::Key("coll/doc2"));
const std::string user1_batch2_doc2_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"user1", 2, testutil::Key("coll/doc2"));
const std::string user2_batch2_doc2_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"user2", 2, testutil::Key("coll/doc2"));
ASSERT_LT(user1_batch1_doc1_key, user2_batch1_doc1_key);
ASSERT_LT(user1_batch1_doc1_key, user1_batch2_doc1_key);
ASSERT_LT(user1_batch1_doc1_key, user1_batch1_doc2_key);
ASSERT_LT(user2_batch1_doc1_key, user2_batch2_doc1_key);
ASSERT_LT(user2_batch1_doc1_key, user2_batch1_doc2_key);
ASSERT_LT(user2_batch2_doc1_key, user2_batch2_doc2_key);
}
TEST(LevelDbDocumentOverlayLargestBatchIdIndexKeyTest, EncodeDecodeCycle) {
const std::vector<std::string> user_ids{"test_user", "foo/bar2",
"foo-bar?baz!quux"};
const std::vector<BatchId> batch_ids{1, 2, 3};
const std::vector<DocumentKey> document_keys{testutil::Key("coll/doc1"),
testutil::Key("coll/doc2"),
testutil::Key("coll/doc3")};
for (const std::string& user_id : user_ids) {
for (BatchId batch_id : batch_ids) {
for (const DocumentKey& document_key : document_keys) {
SCOPED_TRACE(absl::StrCat("user_name=", user_id, " batch_id=", batch_id,
" path=", document_key.ToString()));
const std::string encoded =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(user_id, batch_id,
document_key);
LevelDbDocumentOverlayLargestBatchIdIndexKey key;
EXPECT_TRUE(key.Decode(encoded));
EXPECT_EQ(key.user_id(), user_id);
EXPECT_EQ(key.largest_batch_id(), batch_id);
EXPECT_EQ(key.document_key(), document_key);
}
}
}
}
TEST(LevelDbDocumentOverlayLargestBatchIdIndexKeyTest, Description) {
AssertExpectedKeyDescription(
"[document_overlays_largest_batch_id_index: user_id=foo-bar?baz!quux "
"batch_id=123 path=coll/docX]",
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(
"foo-bar?baz!quux", 123, testutil::Key("coll/docX")));
}
TEST(LevelDbDocumentOverlayLargestBatchIdIndexKeyTest,
FromLevelDbDocumentOverlayKey) {
LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123);
const std::string encoded_key =
LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(key);
LevelDbDocumentOverlayLargestBatchIdIndexKey decoded_key;
ASSERT_TRUE(decoded_key.Decode(encoded_key));
EXPECT_EQ(decoded_key.user_id(), "test_user");
EXPECT_EQ(decoded_key.largest_batch_id(), 123);
EXPECT_EQ(decoded_key.document_key(), testutil::Key("coll/doc"));
}
TEST(LevelDbDocumentOverlayCollectionIndexKeyTest, Prefixing) {
const std::string user1_key =
LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix("test_user1");
const std::string user2_key =
LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix("test_user2");
const std::string user1_coll1_key =
LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix(
"test_user1", ResourcePath{"coll1"});
const std::string user1_coll2_key =
LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix(
"test_user1", ResourcePath{"coll2"});
const std::string user2_coll1_key =
LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix(
"test_user2", ResourcePath{"coll1"});
const std::string user2_coll2_key =
LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix(
"test_user2", ResourcePath{"coll2"});
const std::string user1_coll1_batch1_key =
LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix(
"test_user1", ResourcePath{"coll1"}, 1);
const std::string user1_coll1_batch2_key =
LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix(
"test_user1", ResourcePath{"coll1"}, 2);
const std::string user2_coll2_batch2_key =
LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix(
"test_user2", ResourcePath{"coll2"}, 2);
ASSERT_TRUE(absl::StartsWith(user1_coll1_key, user1_key));
ASSERT_TRUE(absl::StartsWith(user1_coll2_key, user1_key));
ASSERT_TRUE(absl::StartsWith(user2_coll1_key, user2_key));
ASSERT_TRUE(absl::StartsWith(user2_coll2_key, user2_key));
ASSERT_TRUE(absl::StartsWith(user1_coll1_batch1_key, user1_coll1_key));
ASSERT_TRUE(absl::StartsWith(user1_coll1_batch2_key, user1_coll1_key));
ASSERT_FALSE(absl::StartsWith(user1_key, user2_key));
ASSERT_FALSE(absl::StartsWith(user2_key, user1_key));
ASSERT_FALSE(absl::StartsWith(user1_coll1_key, user1_coll2_key));
ASSERT_FALSE(absl::StartsWith(user1_coll2_key, user1_coll1_key));
ASSERT_FALSE(
absl::StartsWith(user1_coll1_batch1_key, user1_coll1_batch2_key));
ASSERT_FALSE(
absl::StartsWith(user1_coll1_batch2_key, user1_coll1_batch1_key));
const std::string user1_coll1_batch1_doc1_key =
LevelDbDocumentOverlayCollectionIndexKey::Key(
"test_user1", ResourcePath{"coll1"}, 1, "doc1");
const std::string user2_coll2_batch2_doc2_key =
LevelDbDocumentOverlayCollectionIndexKey::Key(
"test_user2", ResourcePath{"coll2"}, 2, "doc2");
ASSERT_TRUE(absl::StartsWith(user1_coll1_batch1_doc1_key, user1_key));
ASSERT_TRUE(absl::StartsWith(user2_coll2_batch2_doc2_key, user2_key));
ASSERT_TRUE(absl::StartsWith(user1_coll1_batch1_doc1_key, user1_coll1_key));
ASSERT_TRUE(absl::StartsWith(user2_coll2_batch2_doc2_key, user2_coll2_key));
ASSERT_TRUE(
absl::StartsWith(user1_coll1_batch1_doc1_key, user1_coll1_batch1_key));
ASSERT_TRUE(
absl::StartsWith(user2_coll2_batch2_doc2_key, user2_coll2_batch2_key));
}
TEST(LevelDbDocumentOverlayCollectionIndexKeyTest, Ordering) {
const std::string user1_coll1_batch1_doc1_key =
LevelDbDocumentOverlayCollectionIndexKey::Key(
"user1", ResourcePath{"coll1"}, 1, "doc1");
const std::string user2_coll1_batch1_doc1_key =
LevelDbDocumentOverlayCollectionIndexKey::Key(
"user2", ResourcePath{"coll1"}, 1, "doc1");
const std::string user2_coll2_batch1_doc1_key =
LevelDbDocumentOverlayCollectionIndexKey::Key(
"user2", ResourcePath{"coll2"}, 1, "doc1");
const std::string user2_coll2_batch2_doc1_key =
LevelDbDocumentOverlayCollectionIndexKey::Key(
"user2", ResourcePath{"coll2"}, 2, "doc1");
const std::string user2_coll2_batch2_doc2_key =
LevelDbDocumentOverlayCollectionIndexKey::Key(
"user2", ResourcePath{"coll2"}, 2, "doc2");
ASSERT_LT(user1_coll1_batch1_doc1_key, user2_coll1_batch1_doc1_key);
ASSERT_LT(user2_coll1_batch1_doc1_key, user2_coll2_batch1_doc1_key);
ASSERT_LT(user2_coll2_batch1_doc1_key, user2_coll2_batch2_doc1_key);
ASSERT_LT(user2_coll2_batch2_doc1_key, user2_coll2_batch2_doc2_key);
}
TEST(LevelDbDocumentOverlayCollectionIndexKeyTest, EncodeDecodeCycle) {
const std::vector<std::string> user_ids{"test_user", "foo/bar2",
"foo-bar?baz!quux"};
const std::vector<ResourcePath> collections{
ResourcePath{"coll1"}, ResourcePath{"coll2"},
ResourcePath{"coll3", "docX", "coll4"}};
const std::vector<BatchId> batch_ids{1, 2, 3};
const std::vector<std::string> document_ids{"doc1", "doc2", "doc3"};
for (const std::string& user_id : user_ids) {
for (const ResourcePath& collection : collections) {
for (const BatchId batch_id : batch_ids) {
for (const std::string& document_id : document_ids) {
SCOPED_TRACE(absl::StrCat("user_name=", user_id, " collection=",
collection.CanonicalString(),
" document_id=", document_id));
const std::string encoded =
LevelDbDocumentOverlayCollectionIndexKey::Key(
user_id, collection, batch_id, document_id);
LevelDbDocumentOverlayCollectionIndexKey key;
EXPECT_TRUE(key.Decode(encoded));
EXPECT_EQ(key.user_id(), user_id);
EXPECT_EQ(key.collection(), collection);
EXPECT_EQ(key.largest_batch_id(), batch_id);
EXPECT_EQ(key.document_key(),
DocumentKey(key.collection().Append(document_id)));
}
}
}
}
}
TEST(LevelDbDocumentOverlayCollectionIndexKeyTest, Description) {
AssertExpectedKeyDescription(
"[document_overlays_collection_index: user_id=foo-bar?baz!quux "
"path=coll1 batch_id=123 document_id=docX]",
LevelDbDocumentOverlayCollectionIndexKey::Key(
"foo-bar?baz!quux", ResourcePath{"coll1"}, 123, "docX"));
}
TEST(LevelDbDocumentOverlayCollectionIndexKeyTest,
FromLevelDbDocumentOverlayKey) {
LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123);
const std::string encoded_key =
LevelDbDocumentOverlayCollectionIndexKey::Key(key);
LevelDbDocumentOverlayCollectionIndexKey decoded_key;
ASSERT_TRUE(decoded_key.Decode(encoded_key));
EXPECT_EQ(decoded_key.user_id(), "test_user");
EXPECT_EQ(decoded_key.collection(), ResourcePath{"coll"});
EXPECT_EQ(decoded_key.largest_batch_id(), 123);
EXPECT_EQ(decoded_key.document_key(), testutil::Key("coll/doc"));
}
TEST(LevelDbDocumentOverlayCollectionGroupIndexKeyTest, Prefixing) {
const std::string user1_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user1");
const std::string user2_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user2");
const std::string user1_group1_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user1",
"group1");
const std::string user1_group2_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user1",
"group2");
const std::string user2_group2_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user2",
"group2");
const std::string user1_group1_batch1_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user1",
"group1", 1);
const std::string user1_group1_batch2_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user1",
"group1", 2);
const std::string user2_group2_batch2_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user2",
"group2", 2);
ASSERT_TRUE(absl::StartsWith(user1_group1_key, user1_key));
ASSERT_TRUE(absl::StartsWith(user1_group2_key, user1_key));
ASSERT_TRUE(absl::StartsWith(user2_group2_key, user2_key));
ASSERT_TRUE(absl::StartsWith(user1_group1_batch1_key, user1_group1_key));
ASSERT_TRUE(absl::StartsWith(user1_group1_batch2_key, user1_group1_key));
ASSERT_FALSE(absl::StartsWith(user1_key, user2_key));
ASSERT_FALSE(absl::StartsWith(user2_key, user1_key));
ASSERT_FALSE(absl::StartsWith(user1_group1_key, user1_group2_key));
ASSERT_FALSE(absl::StartsWith(user1_group2_key, user1_group1_key));
ASSERT_FALSE(
absl::StartsWith(user1_group1_batch1_key, user1_group1_batch2_key));
ASSERT_FALSE(
absl::StartsWith(user1_group1_batch2_key, user1_group1_batch1_key));
const std::string user1_group1_batch1_doc1_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::Key(
"test_user1", "group1", 1, testutil::Key("coll/doc1"));
const std::string user2_group2_batch2_doc2_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::Key(
"test_user2", "group2", 2, testutil::Key("coll/doc2"));
ASSERT_TRUE(absl::StartsWith(user1_group1_batch1_doc1_key, user1_key));
ASSERT_TRUE(absl::StartsWith(user2_group2_batch2_doc2_key, user2_key));
ASSERT_TRUE(absl::StartsWith(user1_group1_batch1_doc1_key, user1_group1_key));
ASSERT_TRUE(absl::StartsWith(user2_group2_batch2_doc2_key, user2_group2_key));
ASSERT_TRUE(
absl::StartsWith(user1_group1_batch1_doc1_key, user1_group1_batch1_key));
ASSERT_TRUE(
absl::StartsWith(user2_group2_batch2_doc2_key, user2_group2_batch2_key));
}
TEST(LevelDbDocumentOverlayCollectionGroupIndexKeyTest, Ordering) {
const std::string user1_group1_batch1_doc1_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::Key(
"user1", "group1", 1, testutil::Key("coll/doc1"));
const std::string user2_group1_batch1_doc1_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::Key(
"user2", "group1", 1, testutil::Key("coll/doc1"));
const std::string user2_group2_batch1_doc1_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::Key(
"user2", "group2", 1, testutil::Key("coll/doc1"));
const std::string user2_group2_batch2_doc1_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::Key(
"user2", "group2", 2, testutil::Key("coll/doc1"));
const std::string user2_group2_batch2_doc2_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::Key(
"user2", "group2", 2, testutil::Key("coll/doc2"));
ASSERT_LT(user1_group1_batch1_doc1_key, user2_group1_batch1_doc1_key);
ASSERT_LT(user2_group1_batch1_doc1_key, user2_group2_batch1_doc1_key);
ASSERT_LT(user2_group2_batch1_doc1_key, user2_group2_batch2_doc1_key);
ASSERT_LT(user2_group2_batch2_doc1_key, user2_group2_batch2_doc2_key);
}
TEST(LevelDbDocumentOverlayCollectionGroupIndexKeyTest, EncodeDecodeCycle) {
const std::vector<std::string> user_ids{"test_user", "foo/bar2",
"foo-bar?baz!quux"};
// NOTE: These collection groups do not actually match the document keys used;
// however, that's okay here in this unit test because the LevelDb key itself
// doesn't care if they match.
const std::vector<std::string> collection_groups{"group1", "group2"};
const std::vector<model::BatchId> batch_ids{1, 2, 3};
const std::vector<model::DocumentKey> document_keys{
testutil::Key("coll/doc1"), testutil::Key("coll/doc2"),
testutil::Key("coll/doc3")};
for (const std::string& user_id : user_ids) {
for (const std::string& collection_group : collection_groups) {
for (const model::BatchId batch_id : batch_ids) {
for (const model::DocumentKey& document_key : document_keys) {
SCOPED_TRACE(absl::StrCat("user_name=", user_id,
" collection_group=", collection_group,
" path=", document_key.ToString()));
const std::string encoded =
LevelDbDocumentOverlayCollectionGroupIndexKey::Key(
user_id, collection_group, batch_id, document_key);
LevelDbDocumentOverlayCollectionGroupIndexKey key;
EXPECT_TRUE(key.Decode(encoded));
EXPECT_EQ(key.user_id(), user_id);
EXPECT_EQ(key.collection_group(), collection_group);
EXPECT_EQ(key.largest_batch_id(), batch_id);
EXPECT_EQ(key.document_key(), document_key);
}
}
}
}
}
TEST(LevelDbDocumentOverlayCollectionGroupIndexKeyTest, Description) {
AssertExpectedKeyDescription(
"[document_overlays_collection_group_index: user_id=foo-bar?baz!quux "
"collection_group=group1 batch_id=123 path=coll/docX]",
LevelDbDocumentOverlayCollectionGroupIndexKey::Key(
"foo-bar?baz!quux", "group1", 123, testutil::Key("coll/docX")));
}
TEST(LevelDbDocumentOverlayCollectionGroupIndexKeyTest,
FromLevelDbDocumentOverlayKey) {
LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123);
const absl::optional<std::string> encoded_key =
LevelDbDocumentOverlayCollectionGroupIndexKey::Key(key);
ASSERT_TRUE(encoded_key.has_value());
LevelDbDocumentOverlayCollectionGroupIndexKey decoded_key;
ASSERT_TRUE(decoded_key.Decode(encoded_key.value()));
EXPECT_EQ(decoded_key.user_id(), "test_user");
EXPECT_EQ(decoded_key.collection_group(), "coll");
EXPECT_EQ(decoded_key.largest_batch_id(), 123);
EXPECT_EQ(decoded_key.document_key(), testutil::Key("coll/doc"));
}
#undef AssertExpectedKeyDescription
} // namespace local
} // namespace firestore
} // namespace firebase
| 41.324027 | 86 | 0.698352 | liam-i |
3ee7ff421e8863cd59a274ea5ea68232e8c96afd | 40,702 | cpp | C++ | export/windows/cpp/obj/src/openfl/_legacy/events/Event.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | export/windows/cpp/obj/src/openfl/_legacy/events/Event.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | export/windows/cpp/obj/src/openfl/_legacy/events/Event.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | // Generated by Haxe 3.3.0
#include <hxcpp.h>
#ifndef INCLUDED_Reflect
#include <Reflect.h>
#endif
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_openfl__legacy_events_Event
#include <openfl/_legacy/events/Event.h>
#endif
namespace openfl{
namespace _legacy{
namespace events{
void Event_obj::__construct(::String type,hx::Null< Bool > __o_bubbles,hx::Null< Bool > __o_cancelable){
Bool bubbles = __o_bubbles.Default(false);
Bool cancelable = __o_cancelable.Default(false);
HX_STACK_FRAME("openfl._legacy.events.Event","new",0xfb90e03b,"openfl._legacy.events.Event.new","openfl/_legacy/events/Event.hx",56,0xcca9b1d4)
HX_STACK_THIS(this)
HX_STACK_ARG(type,"type")
HX_STACK_ARG(bubbles,"bubbles")
HX_STACK_ARG(cancelable,"cancelable")
HXLINE( 58) this->_hx___type = type;
HXLINE( 59) this->_hx___bubbles = bubbles;
HXLINE( 60) this->_hx___cancelable = cancelable;
HXLINE( 61) this->_hx___isCancelled = false;
HXLINE( 62) this->_hx___isCancelledNow = false;
HXLINE( 63) this->_hx___target = null();
HXLINE( 64) this->_hx___currentTarget = null();
HXLINE( 65) this->_hx___eventPhase = (int)2;
}
Dynamic Event_obj::__CreateEmpty() { return new Event_obj; }
hx::ObjectPtr< Event_obj > Event_obj::__new(::String type,hx::Null< Bool > __o_bubbles,hx::Null< Bool > __o_cancelable)
{
hx::ObjectPtr< Event_obj > _hx_result = new Event_obj();
_hx_result->__construct(type,__o_bubbles,__o_cancelable);
return _hx_result;
}
Dynamic Event_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< Event_obj > _hx_result = new Event_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2]);
return _hx_result;
}
::openfl::_legacy::events::Event Event_obj::clone(){
HX_STACK_FRAME("openfl._legacy.events.Event","clone",0x58e80ff8,"openfl._legacy.events.Event.clone","openfl/_legacy/events/Event.hx",72,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 72) ::String _hx_tmp = this->get_type();
HXDLIN( 72) Bool _hx_tmp1 = this->get_bubbles();
HXDLIN( 72) Bool _hx_tmp2 = this->get_cancelable();
HXDLIN( 72) return ::openfl::_legacy::events::Event_obj::__new(_hx_tmp,_hx_tmp1,_hx_tmp2);
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,clone,return )
Bool Event_obj::isDefaultPrevented(){
HX_STACK_FRAME("openfl._legacy.events.Event","isDefaultPrevented",0x6e262ec5,"openfl._legacy.events.Event.isDefaultPrevented","openfl/_legacy/events/Event.hx",79,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 79) if (!(this->_hx___isCancelled)) {
HXLINE( 79) return this->_hx___isCancelledNow;
}
else {
HXLINE( 79) return true;
}
HXDLIN( 79) return false;
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,isDefaultPrevented,return )
void Event_obj::stopImmediatePropagation(){
HX_STACK_FRAME("openfl._legacy.events.Event","stopImmediatePropagation",0x3e5eefc2,"openfl._legacy.events.Event.stopImmediatePropagation","openfl/_legacy/events/Event.hx",86,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 86) Bool _hx_tmp = this->get_cancelable();
HXDLIN( 86) if (_hx_tmp) {
HXLINE( 88) this->_hx___isCancelled = true;
HXLINE( 89) this->_hx___isCancelledNow = true;
}
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,stopImmediatePropagation,(void))
void Event_obj::stopPropagation(){
HX_STACK_FRAME("openfl._legacy.events.Event","stopPropagation",0xf6346e45,"openfl._legacy.events.Event.stopPropagation","openfl/_legacy/events/Event.hx",98,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 98) Bool _hx_tmp = this->get_cancelable();
HXDLIN( 98) if (_hx_tmp) {
HXLINE( 100) this->_hx___isCancelled = true;
}
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,stopPropagation,(void))
::String Event_obj::toString(){
HX_STACK_FRAME("openfl._legacy.events.Event","toString",0x4aa366f1,"openfl._legacy.events.Event.toString","openfl/_legacy/events/Event.hx",109,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 109) ::String _hx_tmp = this->get_type();
HXDLIN( 109) ::String _hx_tmp1 = ((HX_("[Event type=",22,63,2e,48) + _hx_tmp) + HX_(" bubbles=",16,5f,ba,28));
HXDLIN( 109) Bool _hx_tmp2 = this->get_bubbles();
HXDLIN( 109) ::String _hx_tmp3 = ::Std_obj::string(_hx_tmp2);
HXDLIN( 109) ::String _hx_tmp4 = ((_hx_tmp1 + _hx_tmp3) + HX_(" cancelable=",89,25,e0,5d));
HXDLIN( 109) Bool _hx_tmp5 = this->get_cancelable();
HXDLIN( 109) ::String _hx_tmp6 = ::Std_obj::string(_hx_tmp5);
HXDLIN( 109) return ((_hx_tmp4 + _hx_tmp6) + HX_("]",5d,00,00,00));
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,toString,return )
::String Event_obj::_hx___formatToString(::String className,::Array< ::String > parameters){
HX_STACK_FRAME("openfl._legacy.events.Event","__formatToString",0x623f1968,"openfl._legacy.events.Event.__formatToString","openfl/_legacy/events/Event.hx",114,0xcca9b1d4)
HX_STACK_THIS(this)
HX_STACK_ARG(className,"className")
HX_STACK_ARG(parameters,"parameters")
HXLINE( 118) HX_VARI( ::String,output) = (HX_("[",5b,00,00,00) + className);
HXLINE( 119) HX_VARI( ::Dynamic,arg) = null();
HXLINE( 121) {
HXLINE( 121) HX_VARI( Int,_g) = (int)0;
HXDLIN( 121) while((_g < parameters->length)){
HXLINE( 121) HX_VARI( ::String,param) = parameters->__get(_g);
HXDLIN( 121) ++_g;
HXLINE( 123) arg = ::Reflect_obj::field(hx::ObjectPtr<OBJ_>(this),param);
HXLINE( 125) Bool _hx_tmp = ::Std_obj::is(arg,hx::ClassOf< ::String >());
HXDLIN( 125) if (_hx_tmp) {
HXLINE( 127) ::String _hx_tmp1 = ((HX_(" ",20,00,00,00) + param) + HX_("=\"",45,35,00,00));
HXDLIN( 127) ::String _hx_tmp2 = ::Std_obj::string(arg);
HXDLIN( 127) hx::AddEq(output,((_hx_tmp1 + _hx_tmp2) + HX_("\"",22,00,00,00)));
}
else {
HXLINE( 131) ::String _hx_tmp3 = ((HX_(" ",20,00,00,00) + param) + HX_("=",3d,00,00,00));
HXDLIN( 131) ::String _hx_tmp4 = ::Std_obj::string(arg);
HXDLIN( 131) hx::AddEq(output,(_hx_tmp3 + _hx_tmp4));
}
}
}
HXLINE( 137) hx::AddEq(output,HX_("]",5d,00,00,00));
HXLINE( 138) return output;
}
HX_DEFINE_DYNAMIC_FUNC2(Event_obj,_hx___formatToString,return )
Bool Event_obj::_hx___getIsCancelled(){
HX_STACK_FRAME("openfl._legacy.events.Event","__getIsCancelled",0x715efeb6,"openfl._legacy.events.Event.__getIsCancelled","openfl/_legacy/events/Event.hx",145,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 145) return this->_hx___isCancelled;
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,_hx___getIsCancelled,return )
Bool Event_obj::_hx___getIsCancelledNow(){
HX_STACK_FRAME("openfl._legacy.events.Event","__getIsCancelledNow",0x9a1c2800,"openfl._legacy.events.Event.__getIsCancelledNow","openfl/_legacy/events/Event.hx",152,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 152) return this->_hx___isCancelledNow;
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,_hx___getIsCancelledNow,return )
void Event_obj::_hx___setPhase(Int value){
HX_STACK_FRAME("openfl._legacy.events.Event","__setPhase",0xec9075de,"openfl._legacy.events.Event.__setPhase","openfl/_legacy/events/Event.hx",159,0xcca9b1d4)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HXLINE( 159) this->_hx___eventPhase = value;
}
HX_DEFINE_DYNAMIC_FUNC1(Event_obj,_hx___setPhase,(void))
Bool Event_obj::get_bubbles(){
HX_STACK_FRAME("openfl._legacy.events.Event","get_bubbles",0x8139fe59,"openfl._legacy.events.Event.get_bubbles","openfl/_legacy/events/Event.hx",171,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 171) return this->_hx___bubbles;
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_bubbles,return )
Bool Event_obj::get_cancelable(){
HX_STACK_FRAME("openfl._legacy.events.Event","get_cancelable",0xb4814062,"openfl._legacy.events.Event.get_cancelable","openfl/_legacy/events/Event.hx",172,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 172) return this->_hx___cancelable;
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_cancelable,return )
::Dynamic Event_obj::get_currentTarget(){
HX_STACK_FRAME("openfl._legacy.events.Event","get_currentTarget",0xee5478dc,"openfl._legacy.events.Event.get_currentTarget","openfl/_legacy/events/Event.hx",173,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 173) return this->_hx___currentTarget;
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_currentTarget,return )
::Dynamic Event_obj::set_currentTarget( ::Dynamic value){
HX_STACK_FRAME("openfl._legacy.events.Event","set_currentTarget",0x11c250e8,"openfl._legacy.events.Event.set_currentTarget","openfl/_legacy/events/Event.hx",174,0xcca9b1d4)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HXLINE( 174) return (this->_hx___currentTarget = value);
}
HX_DEFINE_DYNAMIC_FUNC1(Event_obj,set_currentTarget,return )
Int Event_obj::get_eventPhase(){
HX_STACK_FRAME("openfl._legacy.events.Event","get_eventPhase",0x2e4bd20f,"openfl._legacy.events.Event.get_eventPhase","openfl/_legacy/events/Event.hx",175,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 175) return this->_hx___eventPhase;
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_eventPhase,return )
::Dynamic Event_obj::get_target(){
HX_STACK_FRAME("openfl._legacy.events.Event","get_target",0xf0aed49f,"openfl._legacy.events.Event.get_target","openfl/_legacy/events/Event.hx",176,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 176) return this->_hx___target;
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_target,return )
::Dynamic Event_obj::set_target( ::Dynamic value){
HX_STACK_FRAME("openfl._legacy.events.Event","set_target",0xf42c7313,"openfl._legacy.events.Event.set_target","openfl/_legacy/events/Event.hx",177,0xcca9b1d4)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HXLINE( 177) return (this->_hx___target = value);
}
HX_DEFINE_DYNAMIC_FUNC1(Event_obj,set_target,return )
::String Event_obj::get_type(){
HX_STACK_FRAME("openfl._legacy.events.Event","get_type",0xdef84488,"openfl._legacy.events.Event.get_type","openfl/_legacy/events/Event.hx",178,0xcca9b1d4)
HX_STACK_THIS(this)
HXLINE( 178) return this->_hx___type;
}
HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_type,return )
::String Event_obj::ACTIVATE;
::String Event_obj::ADDED;
::String Event_obj::ADDED_TO_STAGE;
::String Event_obj::CANCEL;
::String Event_obj::CHANGE;
::String Event_obj::CLOSE;
::String Event_obj::COMPLETE;
::String Event_obj::CONNECT;
::String Event_obj::CONTEXT3D_CREATE;
::String Event_obj::DEACTIVATE;
::String Event_obj::ENTER_FRAME;
::String Event_obj::ID3;
::String Event_obj::INIT;
::String Event_obj::MOUSE_LEAVE;
::String Event_obj::OPEN;
::String Event_obj::REMOVED;
::String Event_obj::REMOVED_FROM_STAGE;
::String Event_obj::RENDER;
::String Event_obj::RESIZE;
::String Event_obj::SCROLL;
::String Event_obj::SELECT;
::String Event_obj::SOUND_COMPLETE;
::String Event_obj::TAB_CHILDREN_CHANGE;
::String Event_obj::TAB_ENABLED_CHANGE;
::String Event_obj::TAB_INDEX_CHANGE;
::String Event_obj::UNLOAD;
Event_obj::Event_obj()
{
}
void Event_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(Event);
HX_MARK_MEMBER_NAME(_hx___bubbles,"__bubbles");
HX_MARK_MEMBER_NAME(_hx___cancelable,"__cancelable");
HX_MARK_MEMBER_NAME(_hx___currentTarget,"__currentTarget");
HX_MARK_MEMBER_NAME(_hx___eventPhase,"__eventPhase");
HX_MARK_MEMBER_NAME(_hx___isCancelled,"__isCancelled");
HX_MARK_MEMBER_NAME(_hx___isCancelledNow,"__isCancelledNow");
HX_MARK_MEMBER_NAME(_hx___target,"__target");
HX_MARK_MEMBER_NAME(_hx___type,"__type");
HX_MARK_END_CLASS();
}
void Event_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(_hx___bubbles,"__bubbles");
HX_VISIT_MEMBER_NAME(_hx___cancelable,"__cancelable");
HX_VISIT_MEMBER_NAME(_hx___currentTarget,"__currentTarget");
HX_VISIT_MEMBER_NAME(_hx___eventPhase,"__eventPhase");
HX_VISIT_MEMBER_NAME(_hx___isCancelled,"__isCancelled");
HX_VISIT_MEMBER_NAME(_hx___isCancelledNow,"__isCancelledNow");
HX_VISIT_MEMBER_NAME(_hx___target,"__target");
HX_VISIT_MEMBER_NAME(_hx___type,"__type");
}
hx::Val Event_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"type") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_type()); }
break;
case 5:
if (HX_FIELD_EQ(inName,"clone") ) { return hx::Val( clone_dyn()); }
break;
case 6:
if (HX_FIELD_EQ(inName,"target") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_target()); }
if (HX_FIELD_EQ(inName,"__type") ) { return hx::Val( _hx___type); }
break;
case 7:
if (HX_FIELD_EQ(inName,"bubbles") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_bubbles()); }
break;
case 8:
if (HX_FIELD_EQ(inName,"__target") ) { return hx::Val( _hx___target); }
if (HX_FIELD_EQ(inName,"toString") ) { return hx::Val( toString_dyn()); }
if (HX_FIELD_EQ(inName,"get_type") ) { return hx::Val( get_type_dyn()); }
break;
case 9:
if (HX_FIELD_EQ(inName,"__bubbles") ) { return hx::Val( _hx___bubbles); }
break;
case 10:
if (HX_FIELD_EQ(inName,"cancelable") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_cancelable()); }
if (HX_FIELD_EQ(inName,"eventPhase") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_eventPhase()); }
if (HX_FIELD_EQ(inName,"__setPhase") ) { return hx::Val( _hx___setPhase_dyn()); }
if (HX_FIELD_EQ(inName,"get_target") ) { return hx::Val( get_target_dyn()); }
if (HX_FIELD_EQ(inName,"set_target") ) { return hx::Val( set_target_dyn()); }
break;
case 11:
if (HX_FIELD_EQ(inName,"get_bubbles") ) { return hx::Val( get_bubbles_dyn()); }
break;
case 12:
if (HX_FIELD_EQ(inName,"__cancelable") ) { return hx::Val( _hx___cancelable); }
if (HX_FIELD_EQ(inName,"__eventPhase") ) { return hx::Val( _hx___eventPhase); }
break;
case 13:
if (HX_FIELD_EQ(inName,"currentTarget") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_currentTarget()); }
if (HX_FIELD_EQ(inName,"__isCancelled") ) { return hx::Val( _hx___isCancelled); }
break;
case 14:
if (HX_FIELD_EQ(inName,"get_cancelable") ) { return hx::Val( get_cancelable_dyn()); }
if (HX_FIELD_EQ(inName,"get_eventPhase") ) { return hx::Val( get_eventPhase_dyn()); }
break;
case 15:
if (HX_FIELD_EQ(inName,"__currentTarget") ) { return hx::Val( _hx___currentTarget); }
if (HX_FIELD_EQ(inName,"stopPropagation") ) { return hx::Val( stopPropagation_dyn()); }
break;
case 16:
if (HX_FIELD_EQ(inName,"__isCancelledNow") ) { return hx::Val( _hx___isCancelledNow); }
if (HX_FIELD_EQ(inName,"__formatToString") ) { return hx::Val( _hx___formatToString_dyn()); }
if (HX_FIELD_EQ(inName,"__getIsCancelled") ) { return hx::Val( _hx___getIsCancelled_dyn()); }
break;
case 17:
if (HX_FIELD_EQ(inName,"get_currentTarget") ) { return hx::Val( get_currentTarget_dyn()); }
if (HX_FIELD_EQ(inName,"set_currentTarget") ) { return hx::Val( set_currentTarget_dyn()); }
break;
case 18:
if (HX_FIELD_EQ(inName,"isDefaultPrevented") ) { return hx::Val( isDefaultPrevented_dyn()); }
break;
case 19:
if (HX_FIELD_EQ(inName,"__getIsCancelledNow") ) { return hx::Val( _hx___getIsCancelledNow_dyn()); }
break;
case 24:
if (HX_FIELD_EQ(inName,"stopImmediatePropagation") ) { return hx::Val( stopImmediatePropagation_dyn()); }
}
return super::__Field(inName,inCallProp);
}
bool Event_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"ID3") ) { outValue = ID3; return true; }
break;
case 4:
if (HX_FIELD_EQ(inName,"INIT") ) { outValue = INIT; return true; }
if (HX_FIELD_EQ(inName,"OPEN") ) { outValue = OPEN; return true; }
break;
case 5:
if (HX_FIELD_EQ(inName,"ADDED") ) { outValue = ADDED; return true; }
if (HX_FIELD_EQ(inName,"CLOSE") ) { outValue = CLOSE; return true; }
break;
case 6:
if (HX_FIELD_EQ(inName,"CANCEL") ) { outValue = CANCEL; return true; }
if (HX_FIELD_EQ(inName,"CHANGE") ) { outValue = CHANGE; return true; }
if (HX_FIELD_EQ(inName,"RENDER") ) { outValue = RENDER; return true; }
if (HX_FIELD_EQ(inName,"RESIZE") ) { outValue = RESIZE; return true; }
if (HX_FIELD_EQ(inName,"SCROLL") ) { outValue = SCROLL; return true; }
if (HX_FIELD_EQ(inName,"SELECT") ) { outValue = SELECT; return true; }
if (HX_FIELD_EQ(inName,"UNLOAD") ) { outValue = UNLOAD; return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"CONNECT") ) { outValue = CONNECT; return true; }
if (HX_FIELD_EQ(inName,"REMOVED") ) { outValue = REMOVED; return true; }
break;
case 8:
if (HX_FIELD_EQ(inName,"ACTIVATE") ) { outValue = ACTIVATE; return true; }
if (HX_FIELD_EQ(inName,"COMPLETE") ) { outValue = COMPLETE; return true; }
break;
case 10:
if (HX_FIELD_EQ(inName,"DEACTIVATE") ) { outValue = DEACTIVATE; return true; }
break;
case 11:
if (HX_FIELD_EQ(inName,"ENTER_FRAME") ) { outValue = ENTER_FRAME; return true; }
if (HX_FIELD_EQ(inName,"MOUSE_LEAVE") ) { outValue = MOUSE_LEAVE; return true; }
break;
case 14:
if (HX_FIELD_EQ(inName,"ADDED_TO_STAGE") ) { outValue = ADDED_TO_STAGE; return true; }
if (HX_FIELD_EQ(inName,"SOUND_COMPLETE") ) { outValue = SOUND_COMPLETE; return true; }
break;
case 16:
if (HX_FIELD_EQ(inName,"CONTEXT3D_CREATE") ) { outValue = CONTEXT3D_CREATE; return true; }
if (HX_FIELD_EQ(inName,"TAB_INDEX_CHANGE") ) { outValue = TAB_INDEX_CHANGE; return true; }
break;
case 18:
if (HX_FIELD_EQ(inName,"REMOVED_FROM_STAGE") ) { outValue = REMOVED_FROM_STAGE; return true; }
if (HX_FIELD_EQ(inName,"TAB_ENABLED_CHANGE") ) { outValue = TAB_ENABLED_CHANGE; return true; }
break;
case 19:
if (HX_FIELD_EQ(inName,"TAB_CHILDREN_CHANGE") ) { outValue = TAB_CHILDREN_CHANGE; return true; }
}
return false;
}
hx::Val Event_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"target") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_target(inValue) ); }
if (HX_FIELD_EQ(inName,"__type") ) { _hx___type=inValue.Cast< ::String >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"__target") ) { _hx___target=inValue.Cast< ::Dynamic >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"__bubbles") ) { _hx___bubbles=inValue.Cast< Bool >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"__cancelable") ) { _hx___cancelable=inValue.Cast< Bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__eventPhase") ) { _hx___eventPhase=inValue.Cast< Int >(); return inValue; }
break;
case 13:
if (HX_FIELD_EQ(inName,"currentTarget") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_currentTarget(inValue) ); }
if (HX_FIELD_EQ(inName,"__isCancelled") ) { _hx___isCancelled=inValue.Cast< Bool >(); return inValue; }
break;
case 15:
if (HX_FIELD_EQ(inName,"__currentTarget") ) { _hx___currentTarget=inValue.Cast< ::Dynamic >(); return inValue; }
break;
case 16:
if (HX_FIELD_EQ(inName,"__isCancelledNow") ) { _hx___isCancelledNow=inValue.Cast< Bool >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
bool Event_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"ID3") ) { ID3=ioValue.Cast< ::String >(); return true; }
break;
case 4:
if (HX_FIELD_EQ(inName,"INIT") ) { INIT=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"OPEN") ) { OPEN=ioValue.Cast< ::String >(); return true; }
break;
case 5:
if (HX_FIELD_EQ(inName,"ADDED") ) { ADDED=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"CLOSE") ) { CLOSE=ioValue.Cast< ::String >(); return true; }
break;
case 6:
if (HX_FIELD_EQ(inName,"CANCEL") ) { CANCEL=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"CHANGE") ) { CHANGE=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"RENDER") ) { RENDER=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"RESIZE") ) { RESIZE=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"SCROLL") ) { SCROLL=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"SELECT") ) { SELECT=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"UNLOAD") ) { UNLOAD=ioValue.Cast< ::String >(); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"CONNECT") ) { CONNECT=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"REMOVED") ) { REMOVED=ioValue.Cast< ::String >(); return true; }
break;
case 8:
if (HX_FIELD_EQ(inName,"ACTIVATE") ) { ACTIVATE=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"COMPLETE") ) { COMPLETE=ioValue.Cast< ::String >(); return true; }
break;
case 10:
if (HX_FIELD_EQ(inName,"DEACTIVATE") ) { DEACTIVATE=ioValue.Cast< ::String >(); return true; }
break;
case 11:
if (HX_FIELD_EQ(inName,"ENTER_FRAME") ) { ENTER_FRAME=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"MOUSE_LEAVE") ) { MOUSE_LEAVE=ioValue.Cast< ::String >(); return true; }
break;
case 14:
if (HX_FIELD_EQ(inName,"ADDED_TO_STAGE") ) { ADDED_TO_STAGE=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"SOUND_COMPLETE") ) { SOUND_COMPLETE=ioValue.Cast< ::String >(); return true; }
break;
case 16:
if (HX_FIELD_EQ(inName,"CONTEXT3D_CREATE") ) { CONTEXT3D_CREATE=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"TAB_INDEX_CHANGE") ) { TAB_INDEX_CHANGE=ioValue.Cast< ::String >(); return true; }
break;
case 18:
if (HX_FIELD_EQ(inName,"REMOVED_FROM_STAGE") ) { REMOVED_FROM_STAGE=ioValue.Cast< ::String >(); return true; }
if (HX_FIELD_EQ(inName,"TAB_ENABLED_CHANGE") ) { TAB_ENABLED_CHANGE=ioValue.Cast< ::String >(); return true; }
break;
case 19:
if (HX_FIELD_EQ(inName,"TAB_CHILDREN_CHANGE") ) { TAB_CHILDREN_CHANGE=ioValue.Cast< ::String >(); return true; }
}
return false;
}
void Event_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("bubbles","\x67","\xbb","\x56","\x61"));
outFields->push(HX_HCSTRING("cancelable","\x14","\xa0","\x79","\xc4"));
outFields->push(HX_HCSTRING("currentTarget","\x6a","\x74","\x49","\x6a"));
outFields->push(HX_HCSTRING("eventPhase","\xc1","\x31","\x44","\x3e"));
outFields->push(HX_HCSTRING("target","\x51","\xf3","\xec","\x86"));
outFields->push(HX_HCSTRING("type","\xba","\xf2","\x08","\x4d"));
outFields->push(HX_HCSTRING("__bubbles","\x47","\x0c","\xa5","\xe2"));
outFields->push(HX_HCSTRING("__cancelable","\x34","\x1b","\x0d","\xfd"));
outFields->push(HX_HCSTRING("__currentTarget","\x4a","\xad","\xfb","\xf1"));
outFields->push(HX_HCSTRING("__eventPhase","\xe1","\xac","\xd7","\x76"));
outFields->push(HX_HCSTRING("__isCancelled","\x27","\x7e","\x2d","\x49"));
outFields->push(HX_HCSTRING("__isCancelledNow","\x2f","\x25","\xd8","\x53"));
outFields->push(HX_HCSTRING("__target","\x71","\x5e","\x1c","\x2f"));
outFields->push(HX_HCSTRING("__type","\xda","\x55","\x01","\xfc"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo Event_obj_sMemberStorageInfo[] = {
{hx::fsBool,(int)offsetof(Event_obj,_hx___bubbles),HX_HCSTRING("__bubbles","\x47","\x0c","\xa5","\xe2")},
{hx::fsBool,(int)offsetof(Event_obj,_hx___cancelable),HX_HCSTRING("__cancelable","\x34","\x1b","\x0d","\xfd")},
{hx::fsObject /*Dynamic*/ ,(int)offsetof(Event_obj,_hx___currentTarget),HX_HCSTRING("__currentTarget","\x4a","\xad","\xfb","\xf1")},
{hx::fsInt,(int)offsetof(Event_obj,_hx___eventPhase),HX_HCSTRING("__eventPhase","\xe1","\xac","\xd7","\x76")},
{hx::fsBool,(int)offsetof(Event_obj,_hx___isCancelled),HX_HCSTRING("__isCancelled","\x27","\x7e","\x2d","\x49")},
{hx::fsBool,(int)offsetof(Event_obj,_hx___isCancelledNow),HX_HCSTRING("__isCancelledNow","\x2f","\x25","\xd8","\x53")},
{hx::fsObject /*Dynamic*/ ,(int)offsetof(Event_obj,_hx___target),HX_HCSTRING("__target","\x71","\x5e","\x1c","\x2f")},
{hx::fsString,(int)offsetof(Event_obj,_hx___type),HX_HCSTRING("__type","\xda","\x55","\x01","\xfc")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo Event_obj_sStaticStorageInfo[] = {
{hx::fsString,(void *) &Event_obj::ACTIVATE,HX_HCSTRING("ACTIVATE","\xb3","\xab","\x31","\x3f")},
{hx::fsString,(void *) &Event_obj::ADDED,HX_HCSTRING("ADDED","\xa0","\x0c","\x32","\x9a")},
{hx::fsString,(void *) &Event_obj::ADDED_TO_STAGE,HX_HCSTRING("ADDED_TO_STAGE","\x59","\x58","\xdb","\x1a")},
{hx::fsString,(void *) &Event_obj::CANCEL,HX_HCSTRING("CANCEL","\x7a","\x99","\xb6","\x6a")},
{hx::fsString,(void *) &Event_obj::CHANGE,HX_HCSTRING("CHANGE","\x70","\x3d","\xf5","\x69")},
{hx::fsString,(void *) &Event_obj::CLOSE,HX_HCSTRING("CLOSE","\x98","\x4f","\x51","\xc6")},
{hx::fsString,(void *) &Event_obj::COMPLETE,HX_HCSTRING("COMPLETE","\xb9","\x90","\x4d","\xd9")},
{hx::fsString,(void *) &Event_obj::CONNECT,HX_HCSTRING("CONNECT","\xca","\x0f","\x54","\x95")},
{hx::fsString,(void *) &Event_obj::CONTEXT3D_CREATE,HX_HCSTRING("CONTEXT3D_CREATE","\x5b","\xc4","\x3d","\x41")},
{hx::fsString,(void *) &Event_obj::DEACTIVATE,HX_HCSTRING("DEACTIVATE","\x34","\xd0","\x0a","\x2e")},
{hx::fsString,(void *) &Event_obj::ENTER_FRAME,HX_HCSTRING("ENTER_FRAME","\x46","\xa6","\xab","\xc6")},
{hx::fsString,(void *) &Event_obj::ID3,HX_HCSTRING("ID3","\xf8","\x9f","\x37","\x00")},
{hx::fsString,(void *) &Event_obj::INIT,HX_HCSTRING("INIT","\x10","\x03","\x7c","\x30")},
{hx::fsString,(void *) &Event_obj::MOUSE_LEAVE,HX_HCSTRING("MOUSE_LEAVE","\xdd","\xd3","\xd5","\xd0")},
{hx::fsString,(void *) &Event_obj::OPEN,HX_HCSTRING("OPEN","\xca","\xcb","\x74","\x34")},
{hx::fsString,(void *) &Event_obj::REMOVED,HX_HCSTRING("REMOVED","\x80","\xf3","\xd3","\x72")},
{hx::fsString,(void *) &Event_obj::REMOVED_FROM_STAGE,HX_HCSTRING("REMOVED_FROM_STAGE","\x68","\xcc","\x72","\xdb")},
{hx::fsString,(void *) &Event_obj::RENDER,HX_HCSTRING("RENDER","\x56","\x17","\xac","\xb7")},
{hx::fsString,(void *) &Event_obj::RESIZE,HX_HCSTRING("RESIZE","\xf4","\x05","\xfe","\xba")},
{hx::fsString,(void *) &Event_obj::SCROLL,HX_HCSTRING("SCROLL","\x0d","\x84","\xe7","\xf9")},
{hx::fsString,(void *) &Event_obj::SELECT,HX_HCSTRING("SELECT","\xfc","\xc6","\xb5","\x1c")},
{hx::fsString,(void *) &Event_obj::SOUND_COMPLETE,HX_HCSTRING("SOUND_COMPLETE","\x89","\x35","\x98","\xf1")},
{hx::fsString,(void *) &Event_obj::TAB_CHILDREN_CHANGE,HX_HCSTRING("TAB_CHILDREN_CHANGE","\x66","\x8e","\x83","\x1c")},
{hx::fsString,(void *) &Event_obj::TAB_ENABLED_CHANGE,HX_HCSTRING("TAB_ENABLED_CHANGE","\xd8","\x4a","\xcd","\x8b")},
{hx::fsString,(void *) &Event_obj::TAB_INDEX_CHANGE,HX_HCSTRING("TAB_INDEX_CHANGE","\xe7","\xbd","\xc6","\xb6")},
{hx::fsString,(void *) &Event_obj::UNLOAD,HX_HCSTRING("UNLOAD","\xff","\x4c","\x0f","\x18")},
{ hx::fsUnknown, 0, null()}
};
#endif
static ::String Event_obj_sMemberFields[] = {
HX_HCSTRING("__bubbles","\x47","\x0c","\xa5","\xe2"),
HX_HCSTRING("__cancelable","\x34","\x1b","\x0d","\xfd"),
HX_HCSTRING("__currentTarget","\x4a","\xad","\xfb","\xf1"),
HX_HCSTRING("__eventPhase","\xe1","\xac","\xd7","\x76"),
HX_HCSTRING("__isCancelled","\x27","\x7e","\x2d","\x49"),
HX_HCSTRING("__isCancelledNow","\x2f","\x25","\xd8","\x53"),
HX_HCSTRING("__target","\x71","\x5e","\x1c","\x2f"),
HX_HCSTRING("__type","\xda","\x55","\x01","\xfc"),
HX_HCSTRING("clone","\x5d","\x13","\x63","\x48"),
HX_HCSTRING("isDefaultPrevented","\x40","\x30","\x27","\x04"),
HX_HCSTRING("stopImmediatePropagation","\x7d","\xbf","\x66","\x5b"),
HX_HCSTRING("stopPropagation","\xea","\x81","\x71","\xa0"),
HX_HCSTRING("toString","\xac","\xd0","\x6e","\x38"),
HX_HCSTRING("__formatToString","\x23","\x36","\x73","\xad"),
HX_HCSTRING("__getIsCancelled","\x71","\x1b","\x93","\xbc"),
HX_HCSTRING("__getIsCancelledNow","\x25","\x72","\xfc","\x44"),
HX_HCSTRING("__setPhase","\x59","\x04","\x56","\x73"),
HX_HCSTRING("get_bubbles","\x7e","\x1b","\x51","\xe7"),
HX_HCSTRING("get_cancelable","\x5d","\x28","\x6f","\x3a"),
HX_HCSTRING("get_currentTarget","\xc1","\x7f","\xb9","\x70"),
HX_HCSTRING("set_currentTarget","\xcd","\x57","\x27","\x94"),
HX_HCSTRING("get_eventPhase","\x0a","\xba","\x39","\xb4"),
HX_HCSTRING("get_target","\x1a","\x63","\x74","\x77"),
HX_HCSTRING("set_target","\x8e","\x01","\xf2","\x7a"),
HX_HCSTRING("get_type","\x43","\xae","\xc3","\xcc"),
::String(null()) };
static void Event_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(Event_obj::__mClass,"__mClass");
HX_MARK_MEMBER_NAME(Event_obj::ACTIVATE,"ACTIVATE");
HX_MARK_MEMBER_NAME(Event_obj::ADDED,"ADDED");
HX_MARK_MEMBER_NAME(Event_obj::ADDED_TO_STAGE,"ADDED_TO_STAGE");
HX_MARK_MEMBER_NAME(Event_obj::CANCEL,"CANCEL");
HX_MARK_MEMBER_NAME(Event_obj::CHANGE,"CHANGE");
HX_MARK_MEMBER_NAME(Event_obj::CLOSE,"CLOSE");
HX_MARK_MEMBER_NAME(Event_obj::COMPLETE,"COMPLETE");
HX_MARK_MEMBER_NAME(Event_obj::CONNECT,"CONNECT");
HX_MARK_MEMBER_NAME(Event_obj::CONTEXT3D_CREATE,"CONTEXT3D_CREATE");
HX_MARK_MEMBER_NAME(Event_obj::DEACTIVATE,"DEACTIVATE");
HX_MARK_MEMBER_NAME(Event_obj::ENTER_FRAME,"ENTER_FRAME");
HX_MARK_MEMBER_NAME(Event_obj::ID3,"ID3");
HX_MARK_MEMBER_NAME(Event_obj::INIT,"INIT");
HX_MARK_MEMBER_NAME(Event_obj::MOUSE_LEAVE,"MOUSE_LEAVE");
HX_MARK_MEMBER_NAME(Event_obj::OPEN,"OPEN");
HX_MARK_MEMBER_NAME(Event_obj::REMOVED,"REMOVED");
HX_MARK_MEMBER_NAME(Event_obj::REMOVED_FROM_STAGE,"REMOVED_FROM_STAGE");
HX_MARK_MEMBER_NAME(Event_obj::RENDER,"RENDER");
HX_MARK_MEMBER_NAME(Event_obj::RESIZE,"RESIZE");
HX_MARK_MEMBER_NAME(Event_obj::SCROLL,"SCROLL");
HX_MARK_MEMBER_NAME(Event_obj::SELECT,"SELECT");
HX_MARK_MEMBER_NAME(Event_obj::SOUND_COMPLETE,"SOUND_COMPLETE");
HX_MARK_MEMBER_NAME(Event_obj::TAB_CHILDREN_CHANGE,"TAB_CHILDREN_CHANGE");
HX_MARK_MEMBER_NAME(Event_obj::TAB_ENABLED_CHANGE,"TAB_ENABLED_CHANGE");
HX_MARK_MEMBER_NAME(Event_obj::TAB_INDEX_CHANGE,"TAB_INDEX_CHANGE");
HX_MARK_MEMBER_NAME(Event_obj::UNLOAD,"UNLOAD");
};
#ifdef HXCPP_VISIT_ALLOCS
static void Event_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(Event_obj::__mClass,"__mClass");
HX_VISIT_MEMBER_NAME(Event_obj::ACTIVATE,"ACTIVATE");
HX_VISIT_MEMBER_NAME(Event_obj::ADDED,"ADDED");
HX_VISIT_MEMBER_NAME(Event_obj::ADDED_TO_STAGE,"ADDED_TO_STAGE");
HX_VISIT_MEMBER_NAME(Event_obj::CANCEL,"CANCEL");
HX_VISIT_MEMBER_NAME(Event_obj::CHANGE,"CHANGE");
HX_VISIT_MEMBER_NAME(Event_obj::CLOSE,"CLOSE");
HX_VISIT_MEMBER_NAME(Event_obj::COMPLETE,"COMPLETE");
HX_VISIT_MEMBER_NAME(Event_obj::CONNECT,"CONNECT");
HX_VISIT_MEMBER_NAME(Event_obj::CONTEXT3D_CREATE,"CONTEXT3D_CREATE");
HX_VISIT_MEMBER_NAME(Event_obj::DEACTIVATE,"DEACTIVATE");
HX_VISIT_MEMBER_NAME(Event_obj::ENTER_FRAME,"ENTER_FRAME");
HX_VISIT_MEMBER_NAME(Event_obj::ID3,"ID3");
HX_VISIT_MEMBER_NAME(Event_obj::INIT,"INIT");
HX_VISIT_MEMBER_NAME(Event_obj::MOUSE_LEAVE,"MOUSE_LEAVE");
HX_VISIT_MEMBER_NAME(Event_obj::OPEN,"OPEN");
HX_VISIT_MEMBER_NAME(Event_obj::REMOVED,"REMOVED");
HX_VISIT_MEMBER_NAME(Event_obj::REMOVED_FROM_STAGE,"REMOVED_FROM_STAGE");
HX_VISIT_MEMBER_NAME(Event_obj::RENDER,"RENDER");
HX_VISIT_MEMBER_NAME(Event_obj::RESIZE,"RESIZE");
HX_VISIT_MEMBER_NAME(Event_obj::SCROLL,"SCROLL");
HX_VISIT_MEMBER_NAME(Event_obj::SELECT,"SELECT");
HX_VISIT_MEMBER_NAME(Event_obj::SOUND_COMPLETE,"SOUND_COMPLETE");
HX_VISIT_MEMBER_NAME(Event_obj::TAB_CHILDREN_CHANGE,"TAB_CHILDREN_CHANGE");
HX_VISIT_MEMBER_NAME(Event_obj::TAB_ENABLED_CHANGE,"TAB_ENABLED_CHANGE");
HX_VISIT_MEMBER_NAME(Event_obj::TAB_INDEX_CHANGE,"TAB_INDEX_CHANGE");
HX_VISIT_MEMBER_NAME(Event_obj::UNLOAD,"UNLOAD");
};
#endif
hx::Class Event_obj::__mClass;
static ::String Event_obj_sStaticFields[] = {
HX_HCSTRING("ACTIVATE","\xb3","\xab","\x31","\x3f"),
HX_HCSTRING("ADDED","\xa0","\x0c","\x32","\x9a"),
HX_HCSTRING("ADDED_TO_STAGE","\x59","\x58","\xdb","\x1a"),
HX_HCSTRING("CANCEL","\x7a","\x99","\xb6","\x6a"),
HX_HCSTRING("CHANGE","\x70","\x3d","\xf5","\x69"),
HX_HCSTRING("CLOSE","\x98","\x4f","\x51","\xc6"),
HX_HCSTRING("COMPLETE","\xb9","\x90","\x4d","\xd9"),
HX_HCSTRING("CONNECT","\xca","\x0f","\x54","\x95"),
HX_HCSTRING("CONTEXT3D_CREATE","\x5b","\xc4","\x3d","\x41"),
HX_HCSTRING("DEACTIVATE","\x34","\xd0","\x0a","\x2e"),
HX_HCSTRING("ENTER_FRAME","\x46","\xa6","\xab","\xc6"),
HX_HCSTRING("ID3","\xf8","\x9f","\x37","\x00"),
HX_HCSTRING("INIT","\x10","\x03","\x7c","\x30"),
HX_HCSTRING("MOUSE_LEAVE","\xdd","\xd3","\xd5","\xd0"),
HX_HCSTRING("OPEN","\xca","\xcb","\x74","\x34"),
HX_HCSTRING("REMOVED","\x80","\xf3","\xd3","\x72"),
HX_HCSTRING("REMOVED_FROM_STAGE","\x68","\xcc","\x72","\xdb"),
HX_HCSTRING("RENDER","\x56","\x17","\xac","\xb7"),
HX_HCSTRING("RESIZE","\xf4","\x05","\xfe","\xba"),
HX_HCSTRING("SCROLL","\x0d","\x84","\xe7","\xf9"),
HX_HCSTRING("SELECT","\xfc","\xc6","\xb5","\x1c"),
HX_HCSTRING("SOUND_COMPLETE","\x89","\x35","\x98","\xf1"),
HX_HCSTRING("TAB_CHILDREN_CHANGE","\x66","\x8e","\x83","\x1c"),
HX_HCSTRING("TAB_ENABLED_CHANGE","\xd8","\x4a","\xcd","\x8b"),
HX_HCSTRING("TAB_INDEX_CHANGE","\xe7","\xbd","\xc6","\xb6"),
HX_HCSTRING("UNLOAD","\xff","\x4c","\x0f","\x18"),
::String(null())
};
void Event_obj::__register()
{
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("openfl._legacy.events.Event","\xc9","\xa6","\x7f","\x71");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &Event_obj::__GetStatic;
__mClass->mSetStaticField = &Event_obj::__SetStatic;
__mClass->mMarkFunc = Event_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(Event_obj_sStaticFields);
__mClass->mMembers = hx::Class_obj::dupFunctions(Event_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< Event_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = Event_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = Event_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = Event_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void Event_obj::__boot()
{
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",12,0xcca9b1d4)
HXLINE( 12) ACTIVATE = HX_("activate",b3,1b,ac,e5);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",13,0xcca9b1d4)
HXLINE( 13) ADDED = HX_("added",c0,d4,43,1c);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",14,0xcca9b1d4)
HXLINE( 14) ADDED_TO_STAGE = HX_("addedToStage",63,22,55,0c);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",15,0xcca9b1d4)
HXLINE( 15) CANCEL = HX_("cancel",7a,ed,33,b8);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",16,0xcca9b1d4)
HXLINE( 16) CHANGE = HX_("change",70,91,72,b7);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",17,0xcca9b1d4)
HXLINE( 17) CLOSE = HX_("close",b8,17,63,48);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",18,0xcca9b1d4)
HXLINE( 18) COMPLETE = HX_("complete",b9,00,c8,7f);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",19,0xcca9b1d4)
HXLINE( 19) CONNECT = HX_("connect",ea,3b,80,15);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",20,0xcca9b1d4)
HXLINE( 20) CONTEXT3D_CREATE = HX_("context3DCreate",7c,bf,59,7b);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",21,0xcca9b1d4)
HXLINE( 21) DEACTIVATE = HX_("deactivate",34,5c,01,3c);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",22,0xcca9b1d4)
HXLINE( 22) ENTER_FRAME = HX_("enterFrame",f5,03,50,02);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",23,0xcca9b1d4)
HXLINE( 23) ID3 = HX_("id3",f8,03,50,00);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",24,0xcca9b1d4)
HXLINE( 24) INIT = HX_("init",10,3b,bb,45);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",25,0xcca9b1d4)
HXLINE( 25) MOUSE_LEAVE = HX_("mouseLeave",92,28,20,90);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",26,0xcca9b1d4)
HXLINE( 26) OPEN = HX_("open",ca,03,b4,49);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",27,0xcca9b1d4)
HXLINE( 27) REMOVED = HX_("removed",a0,1f,00,f3);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",28,0xcca9b1d4)
HXLINE( 28) REMOVED_FROM_STAGE = HX_("removedFromStage",34,21,76,ba);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",29,0xcca9b1d4)
HXLINE( 29) RENDER = HX_("render",56,6b,29,05);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",30,0xcca9b1d4)
HXLINE( 30) RESIZE = HX_("resize",f4,59,7b,08);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",31,0xcca9b1d4)
HXLINE( 31) SCROLL = HX_("scroll",0d,d8,64,47);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",32,0xcca9b1d4)
HXLINE( 32) SELECT = HX_("select",fc,1a,33,6a);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",33,0xcca9b1d4)
HXLINE( 33) SOUND_COMPLETE = HX_("soundComplete",a8,30,e6,1c);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",34,0xcca9b1d4)
HXLINE( 34) TAB_CHILDREN_CHANGE = HX_("tabChildrenChange",44,91,b5,de);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",35,0xcca9b1d4)
HXLINE( 35) TAB_ENABLED_CHANGE = HX_("tabEnabledChange",3c,45,98,72);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",36,0xcca9b1d4)
HXLINE( 36) TAB_INDEX_CHANGE = HX_("tabIndexChange",cd,1d,78,90);
}
{
HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",37,0xcca9b1d4)
HXLINE( 37) UNLOAD = HX_("unload",ff,a0,8c,65);
}
}
} // end namespace openfl
} // end namespace _legacy
} // end namespace events
| 46.676606 | 198 | 0.693307 | TinyPlanetStudios |
3ee93de6a90e8f8a1388e6d10a3f9edc9c7958be | 445 | hpp | C++ | backend/TaskGraphFrontEnd/markedBlock.hpp | Ridhii/SyncdSim | 4cd120e9f7d4db348d405db4608ef9c6f9499d01 | [
"BSD-3-Clause"
] | 50 | 2015-10-21T23:16:35.000Z | 2021-09-27T12:52:04.000Z | backend/TaskGraphFrontEnd/markedBlock.hpp | Ridhii/SyncdSim | 4cd120e9f7d4db348d405db4608ef9c6f9499d01 | [
"BSD-3-Clause"
] | 187 | 2015-01-08T22:24:54.000Z | 2020-04-17T17:23:50.000Z | backend/TaskGraphFrontEnd/markedBlock.hpp | Ridhii/SyncdSim | 4cd120e9f7d4db348d405db4608ef9c6f9499d01 | [
"BSD-3-Clause"
] | 25 | 2015-11-02T17:54:49.000Z | 2020-06-16T07:28:11.000Z | #ifndef MARKED_BLOCK_H
#define MARKED_BLOCK_H
#include "markedInstruction.hpp"
#include <vector>
class markedBlock
{
// markedCodeContainer basically does all the construction of this class by inserting instructions
friend class markedCodeContainer;
public:
typedef std::vector<markedInstruction>::iterator iterator;
iterator begin();
iterator end();
private:
std::vector<markedInstruction> instructions;
};
#endif
| 19.347826 | 102 | 0.761798 | Ridhii |
3eeaf0a59870042151db709f7b41cd350423bf55 | 23,911 | cpp | C++ | wdp_ahmm.cpp | travc/vt | 20ba6b7a313aebf2162eb877c38a5c818322bafe | [
"MIT"
] | 166 | 2015-01-14T23:14:05.000Z | 2022-03-31T14:15:56.000Z | wdp_ahmm.cpp | travc/vt | 20ba6b7a313aebf2162eb877c38a5c818322bafe | [
"MIT"
] | 108 | 2015-01-16T13:21:07.000Z | 2022-01-26T22:47:55.000Z | wdp_ahmm.cpp | travc/vt | 20ba6b7a313aebf2162eb877c38a5c818322bafe | [
"MIT"
] | 48 | 2015-01-16T23:35:18.000Z | 2022-03-01T12:14:53.000Z | /* The MIT License
Copyright (c) 2017 Adrian Tan <atks@umich.edu>
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 "wdp_ahmm.h"
#define MAXLEN 1024
#define MAX_MOTIF_LEN 20
#define MAXLEN_NBITS 10
#define S 0
#define M 1
#define D 2
#define I 3
#define E 4
#define N 5
#define NSTATES 6
/*for indexing single array*/
#define index(i,j) (((i)<<MAXLEN_NBITS)+(j))
/**
* Constructor.
*/
WDP_AHMM::WDP_AHMM(bool debug)
{
this->debug = debug;
initialize();
};
/**
* Constructor.
*/
WDP_AHMM::WDP_AHMM(LogTool *lt, bool debug)
{
this->debug = debug;
initialize();
};
/**
* Destructor.
*/
WDP_AHMM::~WDP_AHMM()
{
delete optimal_path;
for (size_t state=S; state<=E; ++state)
{
delete V[state];
delete U[state];
}
delete V;
delete U;
};
/**
* Initializes objects; helper function for constructor.
*/
void WDP_AHMM::initialize()
{
initialize_structures();
initialize_T();
initialize_UV();
};
/**
* Initializes objects for constructor.
*/
void WDP_AHMM::initialize_structures()
{
max_len = MAXLEN;
motif = NULL;
mlen = 0;
motif_discordance = new int32_t[MAXLEN];
optimal_path = new int32_t[MAXLEN<<2];
optimal_path_traced = false;
typedef int32_t (WDP_AHMM::*move) (int32_t t, int32_t j);
V = new float*[NSTATES];
U = new int32_t*[NSTATES];
// moves = new move*[NSTATES];
for (size_t state=S; state<=E; ++state)
{
V[state] = new float[MAX_MOTIF_LEN*MAXLEN];
U[state] = new int32_t[MAX_MOTIF_LEN*MAXLEN];
}
};
/**
* Initialize transition matrix based on parameters.
*/
void WDP_AHMM::initialize_T()
{
float delta = par.delta;
float epsilon = par.epsilon;
float tau = par.tau;
float eta = par.eta;
for (size_t i=S; i<=E; ++i)
{
for (size_t j=S; j<=E; ++j)
{
T[i][j] = -INFINITY;
}
}
T[S][M] = log10(((1-delta))/((1-eta)*(1-eta)));
T[M][M] = log10(((1-2*delta-tau))/((1-eta)*(1-eta)));
T[D][M] = log10(((1-epsilon-tau))/((1-eta)*(1-eta)));
T[I][M] = T[D][M];
T[S][D] = log10(delta/(1-eta));
T[M][D] = log10(delta/(1-eta));
T[D][D] = log10(epsilon/(1-eta));;
T[M][I] = T[M][D];
T[I][I] = T[D][D];
};
/**
* Initializes U and V.
*/
void WDP_AHMM::initialize_UV()
{
for (size_t i=0; i<MAXLEN; ++i)
{
for (size_t j=0; j<MAXLEN; ++j)
{
size_t c = index(i,j);
}
}
V[S][index(0,0)] = 0;
// U[S][index(0,0)] = START_TRACK;
V[M][index(0,0)] = -INFINITY;
};
/**
* Sets a model.
*/
void WDP_AHMM::set_model(const char* motif)
{
// if (motif) free(motif);
this->motif = strdup(motif);
// mlen = strlen(model[MOTIF]);
}
/**
* Sets delta.
*/
void WDP_AHMM::set_delta(float delta)
{
par.delta = delta;
}
/**
* Sets epsilon.
*/
void WDP_AHMM::set_epsilon(float epsilon)
{
par.epsilon = epsilon;
}
/**
* Sets tau.
*/
void WDP_AHMM::set_tau(float tau)
{
par.tau = tau;
}
/**
* Sets eta.
*/
void WDP_AHMM::set_eta(float eta)
{
par.eta = eta;
}
/**
* Sets mismatch penalty.
*/
void WDP_AHMM::set_mismatch_penalty(float mismatch_penalty)
{
par.mismatch_penalty = mismatch_penalty;
}
/**
* Sets debug.
*/
void WDP_AHMM::set_debug(bool debug)
{
this->debug = debug;
}
/**
* Get motif start position for model.
*/
int32_t WDP_AHMM::get_motif_model_spos1()
{
return 0;
};
/**
* Get motif end position for model.
*/
int32_t WDP_AHMM::get_motif_model_epos1()
{
return 0;
};
/**
* Get motif start position for read.
*/
int32_t WDP_AHMM::get_motif_read_spos1()
{
return 0;
};
/**
* Get motif end position for read.
*/
int32_t WDP_AHMM::get_motif_read_epos1()
{
return 0;
};
/**
* Get motif concordance.
*/
float WDP_AHMM::get_motif_concordance()
{
return motif_concordance;
};
/**
* Get exact motif count.
*/
uint32_t WDP_AHMM::get_exact_motif_count()
{
return exact_motif_count;
};
/**
* Get motif count.
*/
uint32_t WDP_AHMM::get_motif_count()
{
return motif_count;
};
/**
* Align read against model.
*/
void WDP_AHMM::align(const char* read, const char* qual)
{
clear_statistics();
optimal_path_traced = false;
this->read = read;
this->qual = qual;
rlen = strlen(read);
if (rlen>=MAXLEN)
{
fprintf(stderr, "[%s:%d %s] Sequence to be aligned is greater than %d currently supported, subsetting string to first 1023 characters: %d\n", __FILE__, __LINE__, __FUNCTION__, MAXLEN, rlen);
rlen = MAXLEN - 1;
}
// plen = rlen;
// float max = 0;
// char maxPath = 'X';
//
// size_t c,d,u,l;
//
// //alignment
// //take into consideration
// for (size_t i=1; i<=plen; ++i)
// {
// //break;
//
// for (size_t j=1; j<=rlen; ++j)
// {
// c = index(i,j);
// d = index(i-1,j-1);
// u = index(i-1,j);
// l = index(i,j-1);
//
// /////
// //M//
// /////
// //only need to update this i>rflen
// max_score = -INFINITY;
// max_track = NULL_TRACK;
// proc_comp(S, M, d, j-1, MATCH);
// proc_comp(M, M, d, j-1, MATCH);
// proc_comp(D, M, d, j-1, MATCH);
// proc_comp(I, M, d, j-1, MATCH);
// V[M][c] = max_score;
// U[M][c] = max_track;
// if (debug) std::cerr << "\tset M " << max_score << " - " << track2string(max_track) << "\n";
//
// /////
// //D//
// /////
// max_score = -INFINITY;
// max_track = NULL_TRACK;
// proc_comp(S, D, u, j, MODEL);
// proc_comp(M, D, u, j, MODEL);
// proc_comp(D, D, u, j, MODEL);
// V[D][c] = max_score;
// U[D][c] = max_track;
// if (debug) std::cerr << "\tset D " << max_score << " - " << track2string(max_track) << "\n";
//
// /////
// //I//
// /////
// max_score = -INFINITY;
// max_track = NULL_TRACK;
// proc_comp(S, I, l, j-1, READ);
// proc_comp(M, I, l, j-1, READ);
// proc_comp(I, I, l, j-1, READ);
// V[I][c] = max_score;
// U[I][c] = max_track;
// if (debug) std::cerr << "\tset I " << max_score << " - " << track2string(max_track) << "\n";
// }
// }
//
// if (debug)
// {
// std::cerr << "\n =V[S]=\n";
// print(V[S], plen+1, rlen+1);
// std::cerr << "\n =U[S]=\n";
// print_U(U[S], plen+1, rlen+1);
//
// std::cerr << "\n =V[M]=\n";
// print(V[M], plen+1, rlen+1);
// std::cerr << "\n =U[M]=\n";
// print_U(U[M], plen+1, rlen+1);
// std::cerr << "\n =V[D]=\n";
// print(V[D], plen+1, rlen+1);
// std::cerr << "\n =U[D]=\n";
// print_U(U[D], plen+1, rlen+1);
// std::cerr << "\n =V[I]=\n";
// print(V[I], plen+1, rlen+1);
// std::cerr << "\n =U[I]=\n";
// print_U(U[I], plen+1, rlen+1);
//
// std::cerr << "\n";
// std::cerr << "\n";
//
// print_T();
// }
//
// trace_path();
//
// exact_motif_count = motif_count;
// motif_concordance = 0;
// for (int32_t k=1; k<=motif_count; ++k)
// {
// if (motif_discordance[k])
// {
// --exact_motif_count;
// }
//
// if (mlen>=motif_discordance[k])
// {
// motif_concordance += (float)(mlen-motif_discordance[k]) / mlen;
// }
// }
// motif_concordance /= motif_count;
};
/**
* Trace path after alignment.
*/
void WDP_AHMM::trace_path()
{
// //search for a complete path in M
// size_t c;
// optimal_score = -INFINITY;
// optimal_track = NULL_TRACK;
// optimal_state = TBD;
// optimal_probe_len = 0;
// trf_score = 0;
// for (size_t i=lflen; i<=plen; ++i)
// {
// c = index(i,rlen);
//
// if (V[M][c]>=optimal_score)
// {
// optimal_score = V[M][c];
// optimal_track = U[M][c];
// optimal_state = M;
// optimal_probe_len = i;
// }
//
// if (V[D][c]>=optimal_score)
// {
// optimal_score = V[D][c];
// optimal_track = U[D][c];
// optimal_state = D;
// optimal_probe_len = i;
// }
// }
//
// //trace path
// optimal_path_ptr = optimal_path+(MAXLEN<<2)-1;
// int32_t i = optimal_probe_len, j = rlen;
// int32_t last_t = make_track(optimal_state, UNMODELED, 0, 0); //dummy end track for E
// optimal_path_len = 0;
// int32_t u;
// int32_t des_t, src_t = make_track(E, UNMODELED, 0, 0);
//
// do
// {
// u = track_get_u(last_t);
// last_t = U[u][index(i,j)];
// *optimal_path_ptr = track_set_u(last_t, u);
//
// des_t = *optimal_path_ptr;
// collect_statistics(src_t, des_t, j);
// if (debug) std::cerr << track2string(src_t) << " (" << i << "," << j << ") => " << track2string(des_t) << " : " << track2string(last_t) << "\n";
// src_t = des_t;
//
// if (u==M)
// {
// --i; --j;
// }
// else if (u==D)
// {
// --i;
// }
// else if (u==I || u==Z)
// {
// --j;
// }
//
// --optimal_path_ptr;
// ++optimal_path_len;
//
// } while (track_get_u(last_t)!=S);
//
// collect_statistics(src_t, last_t, j);
//
// ++optimal_path_ptr;
// optimal_path_traced = true;
};
/**
* Collect alignment summary statistics.
*/
void WDP_AHMM::collect_statistics(int32_t src_t, int32_t des_t, int32_t j)
{
// //std::cerr << "\t " << track2string(src_t) << " (" << j << ") => " << track2string(des_t) << "\n";
//
// int32_t src_u = track_get_u(src_t);
// int32_t des_u = track_get_u(des_t);
//
// if (src_u==E)
// {
// if (des_u==M || des_u==D || des_u==I)
// {
// rflank_start[MODEL] = NAN;
// rflank_start[READ] = NAN;
// rflank_end[MODEL] = INFINITY;
// rflank_end[READ] = INFINITY;
//
// motif_end[MODEL] = track_get_c(des_t);
// motif_count = track_get_c(des_t);
// last_motif_pos = track_get_p(des_t);
// motif_end[READ] = j;
//
// //initialize array for tracking inexact repeats
// for (int32_t k=1; k<=motif_count; ++k)
// {
// motif_discordance[k] = 0;
// }
//
// if (des_u==D || track_get_base(des_t)!=read[j-1])
// {
// ++motif_discordance[motif_count];
// }
// }
// }
//
// if (des_u==M)
// {
// if (track_get_base(des_t)!=read[j-1])
// {
// trf_score -= 7;
// ++motif_discordance[track_get_c(des_t)];
// }
// else
// {
// trf_score += 2;
// }
// }
//
// if (des_u==D || des_u==I)
// {
// trf_score -= 7;
// ++motif_discordance[track_get_c(des_t)];
// }
//
// frac_no_repeats = motif_count - (mlen-last_motif_pos)/((float)mlen);
};
/**
* Clear alignment statistics.
*/
void WDP_AHMM::clear_statistics()
{
// motif_start[MODEL] = NAN;
// motif_start[READ] = NAN;
// motif_end[MODEL] = NAN;
// motif_end[READ] = NAN;
// motif_count = NAN;
// exact_motif_count = NAN;
// motif_m = NAN;
// motif_xid = NAN;
// motif_concordance = NAN;
}
/**
* Update alignment statistics after collection.
*/
void WDP_AHMM::update_statistics()
{
motif_concordance = (float)motif_m/(motif_m+motif_xid);
}
/**
* Compute log10 emission odds based on equal error probability distribution.
*/
float WDP_AHMM::log10_emission_odds(char probe_base, char read_base, uint32_t pl, float mismatch_penalty)
{
// if (read_base=='N' || probe_base=='N')
// {
// return -INFINITY; //is this appropriate in this case?
// }
if (read_base!=probe_base)
{
return lt->pl2log10_varp(pl);
}
else //match
{
return -(lt->pl2log10_varp(pl)-mismatch_penalty);
}
};
/**
* Compute log10 emission odds based on equal error probability distribution.
*/
float WDP_AHMM::log10_emission_odds(char probe_base, char read_base, uint32_t pl)
{
// if (read_base=='N' || probe_base=='N')
// {
// return -INFINITY; //is this appropriate in this case?
// }
if (read_base!=probe_base)
{
return lt->pl2log10_varp(pl)-par.mismatch_penalty;
}
else //match
{
return -(lt->pl2log10_varp(pl));
}
};
/**
* Converts state to string representation.
*/
std::string WDP_AHMM::state2string(int32_t state)
{
// if (state==S)
// {
// return "S";
// }
// else if (state==M)
// {
// return "M";
// }
// else if (state==D)
// {
// return "D";
// }
// else if (state==I)
// {
// return "I";
// }
// else if (state==E)
// {
// return "E";
// }
// else if (state==N)
// {
// return "N";
// }
// else if (state==TBD)
// {
// return "*";
// }
// else
// {
// return "!";
// }
return "";
}
/**
* Converts state to cigar string representation.
*/
std::string WDP_AHMM::state2cigarstring(int32_t state)
{
if (state==S)
{
return "S";
}
else if (state==M)
{
return "M";
}
else if (state==D)
{
return "D";
}
else if (state==I)
{
return "I";
}
else if (state==E)
{
return "E";
}
else if (state==N)
{
return "N";
}
else
{
return "!";
}
}
/**
* Converts state to cigar string representation.
*/
std::string WDP_AHMM::track2cigarstring1(int32_t t, int32_t j)
{
// int32_t state = track_get_u(t);
//
// if (state==S)
// {
// return "S";
// }
// else if (state==M)
// {
// if (track_get_base(t)==read[j-1])
// {
// return "M";
// }
// else
// {
// return "*";
// }
// }
// else if (state==D)
// {
// return "D";
// }
// else if (state==I)
// {
// return "I";
// }
// else if (state==Z)
// {
// return "Z";
// }
// else if (state==E)
// {
// return "E";
// }
// else if (state==N)
// {
// return "N";
// }
// else if (state==TBD)
// {
// return "*";
// }
// else
// {
// return "!";
// }
return "";
}
/**
* Converts track to cigar string representation.
*/
std::string WDP_AHMM::track2cigarstring2(int32_t t)
{
// int32_t state = track_get_u(t);
//
// if (state==M)
// {
// return (track_get_c(t)%2==0?"+":"o");
// }
// else if (state==D)
// {
// return (track_get_c(t)%2==0?"+":"o");
// }
// else if (state==I)
// {
// return (track_get_c(t)%2==0?"+":"o");
// }
// else
// {
// return " ";
// }
return "";
}
/**
* Converts model component to string representation.
*/
std::string WDP_AHMM::component2string(int32_t component)
{
// if (component==MOTIF)
// {
// return "m";
// }
// else if (component==UNMODELED)
// {
// return "!";
// }
// else if (component==READ)
// {
// return "s";
// }
// else if (component==UNCERTAIN)
// {
// return "?";
// }
// else
// {
// return "!";
// }
return "";
}
/**
* Prints an alignment.
*/
void WDP_AHMM::print_alignment()
{
std::string pad = "\t";
print_alignment(pad);
};
/**
* Prints an alignment with padding.
*/
void WDP_AHMM::print_alignment(std::string& pad)
{
if (!optimal_path_traced)
{
std::cerr << "path not traced\n";
}
std::cerr << "=================================\n";
std::cerr << "WDP_AHMM\n";
std::cerr << "*********************************\n";
std::cerr << "repeat motif : " << motif << "\n";
std::cerr << "mlen : " << mlen << "\n";
// std::cerr << "plen : " << plen << "\n";
// std::cerr << "\n";
std::cerr << "read : " << read << "\n";
std::cerr << "rlen : " << rlen << "\n";
// std::cerr << "\n";
// std::cerr << "optimal score: " << optimal_score << "\n";
// std::cerr << "optimal state: " << state2string(optimal_state) << "\n";
// std::cerr << "optimal track: " << track2string(optimal_track) << "\n";
// std::cerr << "optimal probe len: " << optimal_probe_len << "\n";
// std::cerr << "optimal path length : " << optimal_path_len << "\n";
// std::cerr << "max j: " << rlen << "\n";
// std::cerr << "mismatch penalty: " << par.mismatch_penalty << "\n";
// std::cerr << "\n";
//
// std::cerr << "model: " << "(" << lflank_start[MODEL] << "~" << lflank_end[MODEL] << ") "
// << "[" << motif_start[MODEL] << "~" << motif_end[MODEL] << "]\n";
// std::cerr << "read : " << "(" << lflank_start[READ] << "~" << lflank_end[READ] << ") "
// << "[" << motif_start[READ] << "~" << motif_end[READ] << "]"
// << "[" << rflank_start[READ] << "~" << rflank_end[READ] << "]\n";
// std::cerr << "\n";
// std::cerr << "motif # : " << motif_count << " [" << motif_start[READ] << "," << motif_end[READ] << "]\n";
// std::cerr << "motif concordance : " << motif_concordance << "% (" << exact_motif_count << "/" << motif_count << ")\n";
// std::cerr << "last motif position : " << last_motif_pos << "\n";
// std::cerr << "motif discordance : ";
// for (int32_t k=1; k<=motif_count; ++k)
// {
// std::cerr << motif_discordance[k] << (k==motif_count?"\n":"|");
// }
// std::cerr << "fractional no. repeat units : " << frac_no_repeats << "\n";
// std::cerr << "repeat tract length : " << rlen << "\n";
// std::cerr << "TRF Score : " << trf_score << "\n";
//
// std::cerr << "\n";
//
// //print path
// int32_t* path;
// path = optimal_path_ptr;
// std::cerr << "Model: ";
// int32_t t = NULL_TRACK;
// int32_t j = 0;
// while (path<optimal_path+(MAXLEN<<2))
// {
// int32_t u = track_get_u(*path);
// if (u==M || u==D)
// {
// std::cerr << track_get_base(*path);
// }
// else
// {
// std::cerr << '-';
// }
// ++path;
// }
// std::cerr << " \n";
//
// std::cerr << " S";
// path = optimal_path_ptr;
// j=1;
// while (path<optimal_path+(MAXLEN<<2))
// {
// std::cerr << track2cigarstring1(*path,j);
// int32_t u = track_get_u(*path);
// if (u==M || u==I || u==Z)
// {
// ++j;
// }
// ++path;
// }
// std::cerr << "E\n";
//
// path = optimal_path_ptr;
// std::cerr << " ";
// while (path<optimal_path+(MAXLEN<<2))
// {
// std::cerr << track2cigarstring2(*path);
// ++path;
// }
// std::cerr << " \n";
//
// path = optimal_path_ptr;
// j=1;
// std::cerr << "Read: ";
// while (path<optimal_path+(MAXLEN<<2))
// {
// int32_t u = track_get_u(*path);
// if (u==M || u==I || u==Z)
// {
// std::cerr << read[j-1];
// ++j;
// }
// else
// {
// std::cerr << '-';
// }
// ++path;
// }
// std::cerr << " \n";
// std::cerr << "=================================\n";
};
/**
* Prints a float matrix.
*/
void WDP_AHMM::print(float *v, size_t plen, size_t rlen)
{
float val;
std::cerr << std::setprecision(1) << std::fixed;
for (size_t i=0; i<plen; ++i)
{
for (size_t j=0; j<rlen; ++j)
{
val = v[index(i,j)];
std::cerr << (val<0?" ":" ") << val;
}
std::cerr << "\n";
}
};
/**
* Prints a char matrix.
*/
void WDP_AHMM::print(int32_t *v, size_t plen, size_t rlen)
{
float val;
std::cerr << std::setprecision(1) << std::fixed << std::setw(6);
for (size_t i=0; i<plen; ++i)
{
for (size_t j=0; j<rlen; ++j)
{
val = v[index(i,j)];
std::cerr << (val<0?" ":" ") << val;
}
std::cerr << "\n";
}
};
/**
* Prints the transition matrix.
*/
void WDP_AHMM::print_T()
{
// std::cerr << "\t";
// for (size_t j=S; j<=Z; ++j)
// {
// std::cerr << std::setw(8) << std::setprecision(2) << std::fixed << state2string(j);
// }
// std::cerr << "\n";
//
// for (size_t i=S; i<=Z; ++i)
// {
// std::cerr << "\t";
// for (size_t j=S; j<=Z; ++j)
// {
// if (j)
// {
// std::cerr << std::setw(8) << std::setprecision(2) << std::fixed << T[i][j];
// }
// else
// {
// std::cerr << state2string(i) << std::setw(8) << std::setprecision(2) << std::fixed << T[i][j];
// }
// }
// std::cerr << "\n";
// }
// std::cerr << "\n";
};
/**
* Prints U.
*/
void WDP_AHMM::print_U(int32_t *U, size_t plen, size_t rlen)
{
// std::cerr << std::setprecision(1) << std::fixed;
// std::string state;
// for (size_t i=0; i<plen; ++i)
// {
// for (size_t j=0; j<rlen; ++j)
// {
// int32_t t = U[index(i,j)];
// state = state2string(track_get_u(t));
// std::cerr << (state.size()==1 ? " " : " ")
// << state << "|"
// << component2string(track_get_d(t)) << "|"
// << track_get_c(t) << "|"
// << track_get_p(t) << (j==rlen-1?"\n":" ");
// }
// }
};
/**
* Prints U and V.
*/
void WDP_AHMM::print_trace(int32_t state, size_t plen, size_t rlen)
{
// std::cerr << std::setprecision(1) << std::fixed;
// int32_t *u = U[state];
// float *v = V[state];
// std::string s;
// for (size_t i=0; i<plen; ++i)
// {
// for (size_t j=0; j<rlen; ++j)
// {
// int32_t t = u[index(i,j)];
// s = state2string(track_get_u(t));
// std::cerr << (s.size()==1 ? " " : " ")
// << s << "|"
// << component2string(track_get_d(t)) << "|"
// << track_get_c(t) << "|"
// << track_get_p(t) << "|"
// << v[index(i,j)];
// }
//
// std::cerr << "\n";
// }
};
/**
* Prints track.
*/
void WDP_AHMM::print_track(int32_t t)
{
// std::cerr << track2string(t) << "\n";
}
#undef MAXLEN
#undef MAX_MOTIF_LEN
#undef MAXLEN_NBITS
#undef S
#undef M
#undef I
#undef D
#undef E
#undef N
#undef NSTATES
#undef index
| 23.013474 | 198 | 0.478692 | travc |
3eed104191f94a839004720382a95ad1396c7f3e | 2,401 | hpp | C++ | src/px4/mavlink/common/mavlink_msg_fence_status.hpp | mfkiwl/GLMocap | 72de3cc11256d0d8567e86b8a2487ffc81fc984e | [
"MIT"
] | 10 | 2021-03-15T03:58:06.000Z | 2021-12-30T15:33:38.000Z | src/px4/mavlink/common/mavlink_msg_fence_status.hpp | mfkiwl/GLMocap | 72de3cc11256d0d8567e86b8a2487ffc81fc984e | [
"MIT"
] | 1 | 2021-07-08T10:26:06.000Z | 2021-07-08T10:31:11.000Z | src/px4/mavlink/common/mavlink_msg_fence_status.hpp | mfkiwl/GLMocap | 72de3cc11256d0d8567e86b8a2487ffc81fc984e | [
"MIT"
] | 8 | 2021-10-09T08:47:53.000Z | 2022-01-17T07:45:33.000Z | // MESSAGE FENCE_STATUS support class
#pragma once
namespace mavlink {
namespace common {
namespace msg {
/**
* @brief FENCE_STATUS message
*
* Status of geo-fencing. Sent in extended status stream when fencing enabled.
*/
struct FENCE_STATUS : mavlink::Message {
static constexpr msgid_t MSG_ID = 162;
static constexpr size_t LENGTH = 9;
static constexpr size_t MIN_LENGTH = 8;
static constexpr uint8_t CRC_EXTRA = 189;
static constexpr auto NAME = "FENCE_STATUS";
uint8_t breach_status; /*< Breach status (0 if currently inside fence, 1 if outside). */
uint16_t breach_count; /*< Number of fence breaches. */
uint8_t breach_type; /*< Last breach type. */
uint32_t breach_time; /*< [ms] Time (since boot) of last breach. */
uint8_t breach_mitigation; /*< Active action to prevent fence breach */
inline std::string get_name(void) const override
{
return NAME;
}
inline Info get_message_info(void) const override
{
return { MSG_ID, LENGTH, MIN_LENGTH, CRC_EXTRA };
}
inline std::string to_yaml(void) const override
{
std::stringstream ss;
ss << NAME << ":" << std::endl;
ss << " breach_status: " << +breach_status << std::endl;
ss << " breach_count: " << breach_count << std::endl;
ss << " breach_type: " << +breach_type << std::endl;
ss << " breach_time: " << breach_time << std::endl;
ss << " breach_mitigation: " << +breach_mitigation << std::endl;
return ss.str();
}
inline void serialize(mavlink::MsgMap &map) const override
{
map.reset(MSG_ID, LENGTH);
map << breach_time; // offset: 0
map << breach_count; // offset: 4
map << breach_status; // offset: 6
map << breach_type; // offset: 7
map << breach_mitigation; // offset: 8
}
inline void deserialize(mavlink::MsgMap &map) override
{
map >> breach_time; // offset: 0
map >> breach_count; // offset: 4
map >> breach_status; // offset: 6
map >> breach_type; // offset: 7
map >> breach_mitigation; // offset: 8
}
};
} // namespace msg
} // namespace common
} // namespace mavlink
| 31.181818 | 93 | 0.570179 | mfkiwl |
3eed5319602a0593c2248d72006ac9ed47bb19ce | 727 | cpp | C++ | NWNXLib/Utils.cpp | acaos/nwnxee-unified | 0e4c318ede64028c1825319f39c012e168e0482c | [
"MIT"
] | null | null | null | NWNXLib/Utils.cpp | acaos/nwnxee-unified | 0e4c318ede64028c1825319f39c012e168e0482c | [
"MIT"
] | null | null | null | NWNXLib/Utils.cpp | acaos/nwnxee-unified | 0e4c318ede64028c1825319f39c012e168e0482c | [
"MIT"
] | null | null | null | #include "Utils.hpp"
#include "API/Globals.hpp"
#include "API/CAppManager.hpp"
#include "API/CServerExoApp.hpp"
#include "API/CVirtualMachine.hpp"
#include <sstream>
namespace NWNXLib {
namespace Utils {
std::string ObjectIDToString(const API::Types::ObjectID id)
{
std::stringstream ss;
ss << std::hex << id;
return ss.str();
}
std::string GetCurrentScript()
{
auto *pVM = API::Globals::VirtualMachine();
return std::string(pVM->m_pVirtualMachineScript[pVM->m_nRecursionLevel].m_sScriptName.CStr());
}
void ExecuteScript(const std::string& script, API::Types::ObjectID oidOwner)
{
API::CExoString exoStr = script.c_str();
API::Globals::VirtualMachine()->RunScript(&exoStr, oidOwner, 1);
}
}
}
| 22.71875 | 98 | 0.709766 | acaos |
3eeec1b9f3a8d2ba9b4a84cd5a57277979d5b925 | 2,736 | cpp | C++ | modules/ide_old/src/DebugToolbar.cpp | DeepBlue14/rqt_ide | 853964dc429d61c9afb6f1fe827f2e3e83f92713 | [
"MIT"
] | null | null | null | modules/ide_old/src/DebugToolbar.cpp | DeepBlue14/rqt_ide | 853964dc429d61c9afb6f1fe827f2e3e83f92713 | [
"MIT"
] | null | null | null | modules/ide_old/src/DebugToolbar.cpp | DeepBlue14/rqt_ide | 853964dc429d61c9afb6f1fe827f2e3e83f92713 | [
"MIT"
] | null | null | null | #include "DebugToolbar.h"
DebugToolbar::DebugToolbar(QToolBar* parent) : QToolBar(parent)
{
actionPtrVecPtr = new QVector<QAction*>();
initActions();
}
void DebugToolbar::handleStartActPtrSlot()
{
cout << "@ DebugToolbar::handleStartActPtrSlot()" << endl;
}
void DebugToolbar::handleStopActPtrSlot()
{
cout << "@ DebugToolbar::handleStopActPtrSlot()" << endl;
}
void DebugToolbar::handlePauseActPtrSlot()
{
cout << "@ DebugToolbar::handlePauseActPtrSlot()" << endl;
}
void DebugToolbar::handleStepIntoActPtrSlot()
{
cout << "@ DebugToolbar::handleStepIntoActPtrSlot()" << endl;
}
void DebugToolbar::handleStepOverActPtrSlot()
{
cout << "@ DebugToolbar::handleStepOverActPtrSlot()" << endl;
}
void DebugToolbar::initActions()
{
startActPtr = new QAction(QIcon(RosEnv::imagesInstallLoc + "placeholder.jpg"), tr("&New File"), this);
startActPtr->setShortcut(QKeySequence::New);
startActPtr->setStatusTip("New File");
connect(startActPtr, SIGNAL(triggered() ), this, SLOT(handleStartActPtrSlot() ) );
actionPtrVecPtr->push_back(startActPtr);
stopActPtr = new QAction(QIcon(RosEnv::imagesInstallLoc + "placeholder.jpg"), tr("&New File"), this);
stopActPtr->setShortcut(QKeySequence::New);
stopActPtr->setStatusTip("New File");
connect(stopActPtr, SIGNAL(triggered() ), this, SLOT(handleStopActPtrSlot() ) );
actionPtrVecPtr->push_back(stopActPtr);
pauseActPtr = new QAction(QIcon(RosEnv::imagesInstallLoc + "placeholder.jpg"), tr("&New File"), this);
pauseActPtr->setShortcut(QKeySequence::New);
pauseActPtr->setStatusTip("New File");
connect(pauseActPtr, SIGNAL(triggered() ), this, SLOT(handlePauseActPtrSlot() ) );
actionPtrVecPtr->push_back(pauseActPtr);
stepIntoActPtr = new QAction(QIcon(RosEnv::imagesInstallLoc + "placeholder.jpg"), tr("&New File"), this);
stepIntoActPtr->setShortcut(QKeySequence::New);
stepIntoActPtr->setStatusTip("New File");
connect(stepIntoActPtr, SIGNAL(triggered() ), this, SLOT(handleStepIntoActPtrSlot() ) );
actionPtrVecPtr->push_back(stepIntoActPtr);
stepOverActPtr = new QAction(QIcon(RosEnv::imagesInstallLoc + "placeholder.jpg"), tr("&New File"), this);
stepOverActPtr->setShortcut(QKeySequence::New);
stepOverActPtr->setStatusTip("New File");
connect(stepOverActPtr, SIGNAL(triggered() ), this, SLOT(handleStepOverActPtrSlot() ) );
actionPtrVecPtr->push_back(stepOverActPtr);
}
QString* DebugToolbar::toString()
{
QString* tmp = new QString("***METHOD STUB***");
return tmp;
}
QVector<QAction*>* DebugToolbar::getActions()
{
return actionPtrVecPtr;
}
DebugToolbar::~DebugToolbar()
{
;
} | 28.206186 | 109 | 0.699561 | DeepBlue14 |
3eef74dc561c81851c0888212018507de5c6086c | 1,740 | cpp | C++ | foundation/plugins/undo/dmzPluginUndo.cpp | tongli/dmz | f2242027a17ea804259f9412b07d69f719a527c5 | [
"MIT"
] | 1 | 2016-05-08T22:02:35.000Z | 2016-05-08T22:02:35.000Z | foundation/plugins/undo/dmzPluginUndo.cpp | ashok/dmz | 2f8d4bced646f25abf2e98bdc0d378dafb4b32ed | [
"MIT"
] | null | null | null | foundation/plugins/undo/dmzPluginUndo.cpp | ashok/dmz | 2f8d4bced646f25abf2e98bdc0d378dafb4b32ed | [
"MIT"
] | null | null | null | #include "dmzPluginUndo.h"
#include <dmzRuntimeConfigToTypesBase.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
/*!
\class dmz::PluginUndo
\ingroup Foundation
\brief Performs and undo or redo when a message is received.
\details The default Message name to perform an undo is "Plugin_Undo_Message" and
the default Message to perform a redo is "Plugin_Redo_Message".
*/
//! \cond
dmz::PluginUndo::PluginUndo (const PluginInfo &Info, Config &local) :
Plugin (Info),
MessageObserver (Info),
_undo (Info),
_log (Info) {
_init (local);
}
dmz::PluginUndo::~PluginUndo () {
}
// Message Observer Interface
void
dmz::PluginUndo::receive_message (
const Message &Msg,
const UInt32 MessageSendHandle,
const Handle TargetObserverHandle,
const Data *InData,
Data *outData) {
_log.error << "Got message: " << Msg.get_name () << endl;
if (Msg == _undoMessage) { _undo.do_next (UndoTypeUndo); }
else if (Msg == _redoMessage) { _undo.do_next (UndoTypeRedo); }
}
void
dmz::PluginUndo::_init (Config &local) {
RuntimeContext *context (get_plugin_runtime_context ());
_undoMessage = config_create_message_type (
"undo.name",
local,
"Plugin_Undo_Message",
context);
_redoMessage = config_create_message_type (
"redo.name",
local,
"Plugin_Redo_Message",
context);
subscribe_to_message (_undoMessage);
subscribe_to_message (_redoMessage);
}
//! \endcond
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzPluginUndo (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::PluginUndo (Info, local);
}
};
| 20.714286 | 81 | 0.685057 | tongli |
3eef7732e01993ce21af170636cc3e74a05cd289 | 6,189 | cpp | C++ | test/test_pair.cpp | bastiankoe/compute | 57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f | [
"BSL-1.0"
] | 1 | 2015-03-18T01:14:13.000Z | 2015-03-18T01:14:13.000Z | test/test_pair.cpp | bastiankoe/compute | 57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f | [
"BSL-1.0"
] | null | null | null | test/test_pair.cpp | bastiankoe/compute | 57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f | [
"BSL-1.0"
] | null | null | null | //---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// 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
//
// See http://kylelutz.github.com/compute for more information.
//---------------------------------------------------------------------------//
#define BOOST_TEST_MODULE TestPair
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <boost/compute/algorithm/copy.hpp>
#include <boost/compute/algorithm/fill.hpp>
#include <boost/compute/algorithm/find.hpp>
#include <boost/compute/algorithm/transform.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/functional/get.hpp>
#include <boost/compute/functional/field.hpp>
#include <boost/compute/types/pair.hpp>
#include "quirks.hpp"
#include "check_macros.hpp"
#include "context_setup.hpp"
BOOST_AUTO_TEST_CASE(vector_pair_int_float)
{
boost::compute::vector<std::pair<int, float> > vector;
vector.push_back(std::make_pair(1, 1.1f));
vector.push_back(std::make_pair(2, 2.2f));
vector.push_back(std::make_pair(3, 3.3f));
BOOST_CHECK_EQUAL(vector.size(), size_t(3));
BOOST_CHECK(vector[0] == std::make_pair(1, 1.1f));
BOOST_CHECK(vector[1] == std::make_pair(2, 2.2f));
BOOST_CHECK(vector[2] == std::make_pair(3, 3.3f));
}
BOOST_AUTO_TEST_CASE(copy_pair_vector)
{
boost::compute::vector<std::pair<int, float> > input;
input.push_back(std::make_pair(1, 2.0f));
input.push_back(std::make_pair(3, 4.0f));
input.push_back(std::make_pair(5, 6.0f));
input.push_back(std::make_pair(7, 8.0f));
BOOST_CHECK_EQUAL(input.size(), size_t(4));
boost::compute::vector<std::pair<int, float> > output(4);
boost::compute::copy(input.begin(), input.end(), output.begin());
boost::compute::system::finish();
BOOST_CHECK(output[0] == std::make_pair(1, 2.0f));
BOOST_CHECK(output[1] == std::make_pair(3, 4.0f));
BOOST_CHECK(output[2] == std::make_pair(5, 6.0f));
BOOST_CHECK(output[3] == std::make_pair(7, 8.0f));
}
BOOST_AUTO_TEST_CASE(fill_pair_vector)
{
if(bug_in_struct_assignment(device)){
std::cerr << "skipping fill_pair_vector test" << std::endl;
return;
}
boost::compute::vector<std::pair<int, float> > vector(5);
boost::compute::fill(vector.begin(), vector.end(), std::make_pair(4, 2.0f));
boost::compute::system::finish();
BOOST_CHECK(vector[0] == std::make_pair(4, 2.0f));
BOOST_CHECK(vector[1] == std::make_pair(4, 2.0f));
BOOST_CHECK(vector[2] == std::make_pair(4, 2.0f));
BOOST_CHECK(vector[3] == std::make_pair(4, 2.0f));
BOOST_CHECK(vector[4] == std::make_pair(4, 2.0f));
}
BOOST_AUTO_TEST_CASE(fill_char_pair_vector)
{
if(bug_in_struct_assignment(device)){
std::cerr << "skipping fill_char_pair_vector test" << std::endl;
return;
}
std::pair<char, unsigned char> value('c', static_cast<unsigned char>(127));
boost::compute::vector<std::pair<char, unsigned char> > vector(5);
boost::compute::fill(vector.begin(), vector.end(), value);
boost::compute::system::finish();
BOOST_CHECK(vector[0] == value);
BOOST_CHECK(vector[1] == value);
BOOST_CHECK(vector[2] == value);
BOOST_CHECK(vector[3] == value);
BOOST_CHECK(vector[4] == value);
}
BOOST_AUTO_TEST_CASE(transform_pair_get)
{
boost::compute::vector<std::pair<int, float> > input;
input.push_back(std::make_pair(1, 2.0f));
input.push_back(std::make_pair(3, 4.0f));
input.push_back(std::make_pair(5, 6.0f));
input.push_back(std::make_pair(7, 8.0f));
boost::compute::vector<int> first_output(4);
boost::compute::transform(
input.begin(),
input.end(),
first_output.begin(),
::boost::compute::get<0>()
);
CHECK_RANGE_EQUAL(int, 4, first_output, (1, 3, 5, 7));
boost::compute::vector<float> second_output(4);
boost::compute::transform(
input.begin(),
input.end(),
second_output.begin(),
::boost::compute::get<1>()
);
CHECK_RANGE_EQUAL(float, 4, second_output, (2.0f, 4.0f, 6.0f, 8.0f));
}
BOOST_AUTO_TEST_CASE(transform_pair_field)
{
boost::compute::vector<std::pair<int, float> > input;
input.push_back(std::make_pair(1, 2.0f));
input.push_back(std::make_pair(3, 4.0f));
input.push_back(std::make_pair(5, 6.0f));
input.push_back(std::make_pair(7, 8.0f));
boost::compute::vector<int> first_output(4);
boost::compute::transform(
input.begin(),
input.end(),
first_output.begin(),
boost::compute::field<int>("first")
);
CHECK_RANGE_EQUAL(int, 4, first_output, (1, 3, 5, 7));
boost::compute::vector<float> second_output(4);
boost::compute::transform(
input.begin(),
input.end(),
second_output.begin(),
boost::compute::field<float>("second")
);
CHECK_RANGE_EQUAL(float, 4, second_output, (2.0f, 4.0f, 6.0f, 8.0f));
}
BOOST_AUTO_TEST_CASE(find_vector_pair)
{
boost::compute::vector<std::pair<int, float> > vector;
vector.push_back(std::make_pair(1, 1.1f));
vector.push_back(std::make_pair(2, 2.2f));
vector.push_back(std::make_pair(3, 3.3f));
BOOST_CHECK_EQUAL(vector.size(), size_t(3));
BOOST_CHECK(
boost::compute::find(
boost::compute::make_transform_iterator(
vector.begin(),
boost::compute::get<0>()
),
boost::compute::make_transform_iterator(
vector.end(),
boost::compute::get<0>()
),
int(2)
).base() == vector.begin() + 1
);
BOOST_CHECK(
boost::compute::find(
boost::compute::make_transform_iterator(
vector.begin(),
boost::compute::get<1>()
),
boost::compute::make_transform_iterator(
vector.end(),
boost::compute::get<1>()
),
float(3.3f)
).base() == vector.begin() + 2
);
}
BOOST_AUTO_TEST_SUITE_END()
| 33.274194 | 80 | 0.614639 | bastiankoe |
3ef28453b137e8199a40bf4fe6aee02681e56396 | 22,952 | hpp | C++ | nimbly-source/include/nimbly/core/flex.hpp | mousepawmedia/nimbly | 7ed7aeb0b494ff77031ff3208300fc57d34d1206 | [
"BSD-3-Clause"
] | 1 | 2022-02-26T18:14:33.000Z | 2022-02-26T18:14:33.000Z | nimbly-source/include/nimbly/core/flex.hpp | mousepawmedia/nimbly | 7ed7aeb0b494ff77031ff3208300fc57d34d1206 | [
"BSD-3-Clause"
] | null | null | null | nimbly-source/include/nimbly/core/flex.hpp | mousepawmedia/nimbly | 7ed7aeb0b494ff77031ff3208300fc57d34d1206 | [
"BSD-3-Clause"
] | null | null | null | /** Flex [Nimbly]
* Version: 2.0
*
* A dynamic contiguous data structure with a low dynamic allocation demand.
* FlexArray, FlexQueue, and FlexStack all rely on these.
*
* Author(s): Jason C. McDonald, Michael Parkman,
* Jonathan Theodore, Moshe Uminer
*/
/* LICENSE (BSD-3-Clause)
* Copyright (c) 2016-2021 MousePaw Media.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* CONTRIBUTING
* See https://www.mousepawmedia.com/developers for information
* on how to contribute to our projects.
*/
#ifndef NIMBLY_FLEX_HPP
#define NIMBLY_FLEX_HPP
#include <math.h>
#include <stdexcept>
#include <stdlib.h>
#include "iosqueak/channel.hpp"
template<typename type, bool raw_copy = false, bool factor_double = true>
class Flex
{
public:
/** Create a new flex, with the default starting size.
*/
Flex()
: internalArray(nullptr), internalArrayBound(nullptr), head(nullptr),
tail(nullptr), resizable(true), _elements(0), _capacity(0)
{
/* The call to resize() will sets the capacity to 8
* on initiation. */
// Allocate the structure with an initial size.
resize(8);
}
/** Create a new flex from another flex.
* Copies the contents of the source array.
* \param the source array
*/
Flex(const Flex<type>& cpy)
: internalArray(nullptr), internalArrayBound(nullptr), head(nullptr),
tail(nullptr), resizable(cpy.resizable), _elements(0), _capacity(0)
{
// Resize to the reserved size of the old array (handles _capacity)
resize(cpy._capacity);
// Copy elements over to the new memory (handles _elements)
copyForeignMemory(cpy);
}
/** Move the contents of a flex array.
* Moves (steals) the contents of the source array.
* \param the source array
*/
Flex(Flex<type>&& mov)
: internalArray(std::move(mov.internalArray)),
internalArrayBound(mov.internalArrayBound), head(mov.head),
tail(mov.tail), resizable(mov.resizable), _elements(mov._elements),
_capacity(mov._capacity)
{
// Prevent double-free when source object is destroyed.
mov.internalArray = nullptr;
}
/** Create a new flex with room for the specified number
* of elements.
* \param the number of elements the structure can hold.
*/
// cppcheck-suppress noExplicitConstructor
Flex(size_t numElements)
: internalArray(nullptr), head(nullptr), tail(nullptr), resizable(true),
_elements(0), _capacity(0)
{
// Never allow instantiating with a capacity less than 2.
if (numElements > 1) {
// Allocate the structure with the requested size.
resize(numElements);
} else {
resize(2);
}
}
/** Destructor. */
~Flex()
{
if (internalArray != nullptr) {
delete[] internalArray;
}
}
Flex<type>& operator=(const Flex<type>& rhs)
{
// Don't copy from self.
if (&rhs == this) {
return *(this);
}
// Free original array
if (this->internalArray != nullptr) {
delete[] this->internalArray;
}
this->internalArray = nullptr;
this->internalArrayBound = nullptr;
this->head = nullptr;
this->tail = nullptr;
// Redefine properties
this->resizable = rhs.resizable;
// Resize to the reserved size of the old array (handles _capacity)
resize(rhs._capacity);
// Copy elements over to the new memory (handles _elements)
copyForeignMemory(rhs);
return *(this);
}
Flex<type>& operator=(Flex&& rhs)
{
// Don't copy from self.
if (&rhs == this) {
return *(this);
}
// Free original array
if (this->internalArray != nullptr) {
delete[] this->internalArray;
}
// Directly steal the contents of the source array.
this->internalArray = std::move(rhs.internalArray);
this->internalArrayBound = rhs.internalArrayBound;
this->head = rhs.head;
this->tail = rhs.tail;
this->resizable = rhs.resizable;
this->_elements = rhs._elements;
this->_capacity = rhs._capacity;
// Prevent double-free when source object is destroyed.
rhs.internalArray = nullptr;
return *(this);
}
/** Access an element at a given index using the [] operator.
* For example, "internalArray[5]".
*/
type& operator[](size_t index) { return at(index); }
const type& operator[](size_t index) const { return at(index); }
/** Access an element at the given index.
* \param the index to access.
* \return the element at the given index.
*/
type& at(size_t index)
{
if (!validateIndex(index, false)) {
throw std::out_of_range("BaseFlexArray: Index out of range!");
}
return internalArray[toInternalIndex(index)];
}
const type& at(size_t index) const
{
if (!validateIndex(index, false)) {
throw std::out_of_range("BaseFlexArray: Index out of range!");
}
return internalArray[toInternalIndex(index)];
}
/** Clear all the elements in the array.
* \return true if successful, else false
*/
bool clear()
{
this->_elements = 0;
this->head = this->internalArray;
this->tail = this->internalArray;
return true;
}
/** Check if the data structure is empty.
* \return true if empty, else false
*/
bool isEmpty() const { return (_elements == 0); }
/** Check to see if the data structure is full.
* \return true is full, else false
*/
bool isFull() const { return (_capacity == _elements); }
/** Erase the elements in the specified range.
* \param the first index in the range to remove
* \param the last index in the range to remove
*/
bool erase(size_t first, size_t last = 0)
{
/* If no last index was specified, prepare to delete only
* the element 'first'. */
if (last == 0) {
last = first;
}
// If the range [first-last] is valid...
if (last >= first && last < this->_elements) {
size_t removeCount = (last + 1) - first;
//...and if we'll have leftovers after `last`
if (last < this->_elements - 1) {
// Shift the leftovers backwards into place.
memShift(last + 1, -removeCount);
}
// Recalculate the elements we have.
this->_elements -= removeCount;
return true;
} else {
// Throw non-fatal error.
channel << IOCat::error << "BaseFlexArray Erase: Invalid range ("
<< first << " - " << last << "). Took no action."
<< IOCtrl::endl;
return false;
}
}
/** Get the current number of elements in the structure.
* \return the number of elements
*/
size_t length() const { return _elements; }
/** Get the maximum number of elements the structure can hold
* without resizing.
* \return the maximum number of elements
*/
size_t capacity() const { return _capacity; }
/** Reserves room for the exact number of elements.
* \param the number of elements to reserve
* \return true if successful, else false
*/
bool reserve(size_t size) { return resize(size); }
bool shrink()
{
// Never allow shrinking smaller than 2.
if (this->_elements < 2) {
return resize(2, true);
}
// (implicit else)
return resize(this->_elements, true);
}
protected:
/// The pointer to the actual structure in memory.
type* internalArray;
/// The pointer to the end of the internal array.
type* internalArrayBound;
/// Pointer to the head element.
type* head;
/// Pointer to one past the tail element.
type* tail;
/// Whether the structure can be resized.
bool resizable;
/// The current number of elements in the structure.
size_t _elements;
/** The maximum number of elements (capacity) that can be contained
* in the structure without resizing. (1-based) */
size_t _capacity;
/** Directly access a value in the internal array.
* Does not check for bounds.
* \param the internal index to access
* \return the element at index
*/
type& rawAt(size_t index) { return internalArray[toInternalIndex(index)]; }
const type& rawAt(size_t index) const
{
return internalArray[toInternalIndex(index)];
}
/** Validate the given index is in range
* \param the index to validate
* \param whether to show an error message on failure, default false
* \return true if index is in range, else false
*/
inline bool validateIndex(size_t index, bool yell = false) const
{
/* If the index is greater than the number of elements
* in the array currently. */
if (index > this->_elements - 1) {
if (yell) {
// Throw a non-fatal error. Numbers are 0-based.
channel << IOCat::error << IOVrb::quiet << "Index " << index
<< " out of bounds [0 - " << this->_elements - 1 << "]."
<< IOCtrl::endl;
}
// Report failure.
return false;
}
// Otherwise, return true.
return true;
}
/** Convert an index to an internal index.
* \param the (external) index to access
* \return the (internal) index
*/
inline size_t toInternalIndex(size_t index) const
{
/* Get the internal index, by adding the external index
* to the head index, and then accounting for the
* circular buffer.
* Thanks to pydsigner and nisstyre in ##python-offtopic
* for suggesting the modulus.
*/
return (this->head - this->internalArray + index) % this->_capacity;
}
type& getFromHead() { return *(this->head); }
const type& getFromHead() const { return *(this->head); }
type& getFromTail()
{
if (this->tail == this->internalArray) {
// We have to get the element at the end of the internalArray.
return *(this->internalArray + (this->_capacity - 1));
}
return *(this->tail - 1);
}
const type& getFromTail() const
{
if (this->tail == this->internalArray) {
// We have to get the element at the end of the internalArray.
return *(this->internalArray + (this->_capacity - 1));
}
return *(this->tail - 1);
}
/** Efficiently insert a value at the head of the array.
* \param the value to insert
* \param whether to show an error message on failure, default false
* \return true if successful, else false
*/
bool insertAtHead(type&& value, bool yell = false)
{
// Check capacity and attempt a resize if necessary.
if (!checkSize(yell)) {
return false;
}
shiftHeadBack();
// Insert our value at the new head position.
*(this->head) = std::move(value);
// Increment the number of current elements in the array.
++this->_elements;
return true;
}
/** Efficiently insert a value at the tail of the array.
* \param the value to insert
* \param whether to show an error message on failure, default false
* return true if successful, else false
*/
bool insertAtTail(type&& value, bool yell = false)
{
// Check capacity and attempt a resize if necessary.
if (!checkSize(yell)) {
return false;
}
*(this->tail) = std::move(value);
shiftTailForward();
// Increment the number of current elements in the array
++this->_elements;
return true;
}
/** Insert a value at the given position in the array.
* Does NOT check index validity.
* \param the value to insert
* \param the index to insert the value at
* \param whether to show an error message on failure, default false
* \return true if successful, else false
*/
bool insertAtIndex(type&& value, size_t index, bool yell = false)
{
// Check capacity and attempt a resize if necessary.
if (!checkSize(yell)) {
return false;
}
// Shift the values to make room.
memShift(index, 1);
// Store the new value.
this->internalArray[toInternalIndex(index)] = std::move(value);
// Leave the head/tail shifting to memShift!
// Increment the number of current elements in the array.
++this->_elements;
return true;
}
/** Efficiently remove a value from the head.
* Does NOT check if the array is empty.
* \return true if successful, else false
*/
bool removeAtHead()
{
shiftHeadForward();
// Decrement the number of elements we're currently storing.
--this->_elements;
return true;
}
/** Efficiently remove a value from the tail.
* Does NOT check if the array is empty.
* \return true if successful, else false
*/
bool removeAtTail()
{
/* Move the tail position back, so the previous last value
* is now ignored.
*/
shiftTailBack();
// Decrement the number of elements we're currently storing.
--this->_elements;
return true;
}
/** Remove a value from the array.
* Does NOT check index validity.
* Does NOT check if the array is empty.
* \param the index to remove
* \return true if successful, else false
*/
bool removeAtIndex(size_t index)
{
/* Decrement the number of elements we're storing.
* If we have more than one element remaining...
*/
if (this->_elements-- > 1) {
/* Shift all the elements after the index left one position,
* overwriting the element we're removing.
*/
memShift(index, -1);
} else {
/* If we have only one element remaining, we should not
* memShift. Just ignore the element's existence.
*/
shiftTailBack();
}
return true;
}
/** Check if the array is full and attempt a resize if necessary.
* \param whether to show an error message on failure, default false
* \return true if resize successful or no resize necessary
*/
inline bool checkSize(bool yell = false)
{
// If we're full, attempt a resize.
if (this->_elements >= this->_capacity) {
// If we weren't able to resize, report failure.
if (!resize()) {
if (yell) {
channel << IOCat::error
<< "Data structure is full and cannot be resized."
<< IOCtrl::endl;
}
return false;
}
}
/* If no resize was necessary, or if resize was successful,
* report success.
*/
return true;
}
/** Copy elements from another Flex-based data structure
* \param the source data structure
*/
void copyForeignMemory(const Flex<type>& cpy)
{
for (size_t i = 0; i < cpy._elements; ++i) {
*(this->tail) = cpy.rawAt(i);
shiftTailForward();
}
this->_elements = cpy._elements;
}
/** Double the capacity of the structure.
* \param the number of elements to reserve space for
* \param whether we're allowed to non-destructively shrink.
* \return true if it was able to double capacity, else false.
*/
bool resize(size_t reserve = 0, bool allow_shrink = false)
{
// If we're not allowed to resize, report failure.
if (!resizable) {
return false;
}
size_t oldCapacity = this->_capacity;
if (reserve == 0) {
// check to see if maximum size is being approached
if (this->_capacity >= UINT32_MAX / 2) {
// set it to limit defined by UINT32_MAX
this->_capacity = UINT32_MAX;
// set it so that array can no longer be doubled in size
resizable = false;
}
// Increase the capacity.
/* Which option we use depends on whether we want to
* optimize for SPEED (2) or SPACE (1.5). */
if (factor_double) {
this->_capacity = this->_capacity * 2;
} else {
this->_capacity += this->_capacity / 2;
}
} else {
// If the reservation would destroy elements...
if (reserve < this->_elements) {
// Report error.
return false;
}
/* If the reservation would shrink the structure
* without permission... */
else if (!allow_shrink && reserve <= this->_capacity) {
// Report error.
return false;
}
this->_capacity = reserve;
}
/* Create the new structure with the new capacity.*/
type* tempArray = new type[this->_capacity];
// If there was an error allocating the new array...
if (tempArray == nullptr) {
// Report failure.
return false;
}
// If an old array exists...
if (this->internalArray != nullptr) {
/* Transfer all of the elements over.
* Since this is a circular buffer, we have to move things
* so it has room for expansion. The fastest way to do this
* is by storing the head element back at index 0.
* To do this, we'll move everything in two parts:
* (1) head to end of space, and (2) 0 to head-1.
*/
size_t headIndex = this->head - this->internalArray;
size_t step1 = oldCapacity - headIndex;
size_t step2 = headIndex;
if constexpr (raw_copy) {
memcpy(tempArray, this->head, sizeof(type) * step1);
memcpy(tempArray + step1,
this->internalArray,
sizeof(type) * step2);
} else {
size_t destIndex = 0;
for (size_t i = headIndex; i < headIndex + step1; ++i) {
tempArray[destIndex++] = std::move(this->internalArray[i]);
}
for (size_t i = 0; i < step2; ++i) {
tempArray[destIndex++] = std::move(this->internalArray[i]);
}
}
// Delete the old structure.
delete[] this->internalArray;
this->internalArray = nullptr;
}
// Store the new structure.
this->internalArray = tempArray;
this->internalArrayBound = this->internalArray + this->_capacity;
// Reset the head and tail
this->head = this->internalArray;
this->tail = this->internalArray + this->_elements;
// Report success.
return true;
}
/** Shift all elements from the given position the given direction
* and distance. This is intended for internal use only, and does
* not check for memory errors.
* \param the index to shift elements from
* \param the direction and distance to shift the elements in.
*/
void memShift(size_t fromIndex, int8_t direction)
{
/* Check if the index was valid given the number of elements
* we're actually storing. (We have to offset so we do our math
* in 1-indexing).
*/
if (fromIndex >= this->_elements) {
return;
}
// If the array is already empty, there's nothing to move.
if (isEmpty()) {
return;
}
// If we haven't yet had wraparound, move the tail section.
if (this->tail > this->head && this->tail < this->internalArrayBound) {
if constexpr (raw_copy) {
memmove(
// Move TO the given index.
this->head + fromIndex + direction,
// Move FROM the given index.
this->head + fromIndex,
// Total move size is the number of elements to be moved,
// times element size. The number of elements we move
// is calculated from the 1-based total number of elements.
sizeof(type) * (this->_elements - fromIndex));
} else {
size_t headIndex = this->head - this->internalArray;
size_t destIndex = headIndex + fromIndex + direction;
size_t srcIndex = headIndex + fromIndex;
size_t toMove = this->_elements - fromIndex;
// We must move elements last to first to prevent overwrite.
for (size_t i = toMove; i > 0; --i) {
/* toMove is converted to zero-index here, so the
* loop will break if toMove is 0 (undef behavior) */
// MOVE elements instead of copying
this->internalArray[destIndex + i - 1] =
std::move(this->internalArray[srcIndex + i - 1]);
}
}
shiftTail(direction);
}
// Else If we've already had wraparound, move the head section.
else if (this->tail < this->head) {
/* There is an ironic side-effect here that, if we are
* inserting at 0, we'll only move the head, and not
* actually shift anything! (Weird, but it works.)
*/
if constexpr (raw_copy) {
memmove(
// Move TO the given index.
// Must invert direction for this to work right.
this->head - direction,
// Move FROM the given index.
this->head,
sizeof(type) * fromIndex);
} else {
size_t headIndex = this->head - this->internalArray;
size_t destIndex = headIndex - direction;
size_t srcIndex = headIndex;
size_t toMove = fromIndex;
// We must move elements first-to-last to prevent overwrite.
for (size_t i = 0; i < toMove; ++i) {
// MOVE elements instead of copying
this->internalArray[destIndex + i] =
std::move(this->internalArray[srcIndex + i]);
}
}
shiftHead(-direction);
} else {
channel << "Flex: Impossible circular buffer arrangement."
<< IOCtrl::endl;
channel << "Internal Array: " << IOFormatPtr::address
<< this->internalArray << IOCtrl::endl;
channel << "Head: " << IOFormatPtr::address << this->head
<< IOCtrl::endl;
channel << "Tail: " << IOFormatPtr::address << this->tail
<< IOCtrl::endl;
channel << "Array Bound: " << IOFormatPtr::address
<< this->internalArrayBound << IOCtrl::endl;
channel << "Capacity: " << IOFormatPtr::address << this->_capacity
<< IOCtrl::endl;
channel << "Elements: " << IOFormatPtr::address << this->_elements
<< IOCtrl::endl;
throw std::runtime_error("Flex: Impossible situation. Aborting!");
}
}
inline void shiftHead(size_t direction)
{
size_t magnitude = direction;
if (direction > 0) {
for (size_t i = 0; i < magnitude; ++i) {
shiftHeadForward();
}
} else {
for (size_t i = 0; i < magnitude; ++i) {
shiftHeadBack();
}
}
}
inline void shiftHeadBack()
{
// Move the head back, accounting for wraparound.
if (this->head-- <= this->internalArray) {
this->head = this->internalArray + (this->_capacity - 1);
}
}
inline void shiftHeadForward()
{
// Move the head forward, accounting for wraparound.
if (++this->head - this->internalArray >= int(this->_capacity)) {
this->head = this->internalArray;
}
}
inline void shiftTail(size_t direction)
{
size_t magnitude = direction;
if (direction > 0) {
for (size_t i = 0; i < magnitude; ++i) {
shiftTailForward();
}
} else {
for (size_t i = 0; i < magnitude; ++i) {
shiftTailBack();
}
}
}
inline void shiftTailBack()
{
// Move the tail back, accounting for wraparound.
if (this->tail-- == this->internalArray) {
this->tail = this->internalArray + (this->_capacity - 1);
}
}
inline void shiftTailForward()
{
// Move the tail forward, accounting for wraparound.
if (++this->tail >= this->internalArrayBound) {
this->tail = this->internalArray;
}
}
};
#endif // NIMBLY_FLEX_HPP
| 27.956151 | 80 | 0.666478 | mousepawmedia |
3ef38bec6eeeebe0aefd37fded1e605824066763 | 9,648 | cc | C++ | mod/InitClusterBlock.cc | macndev/Stntuple | b5bb000edf015883eec32d87959cb7bd3ab88577 | [
"Apache-2.0"
] | null | null | null | mod/InitClusterBlock.cc | macndev/Stntuple | b5bb000edf015883eec32d87959cb7bd3ab88577 | [
"Apache-2.0"
] | null | null | null | mod/InitClusterBlock.cc | macndev/Stntuple | b5bb000edf015883eec32d87959cb7bd3ab88577 | [
"Apache-2.0"
] | 6 | 2019-11-21T15:27:27.000Z | 2022-02-28T20:57:13.000Z | //-----------------------------------------------------------------------------
// Apr 2013 P.Murat: initialization of the MU2E STNTUPLE cluster block
//
//-----------------------------------------------------------------------------
#include <cstdio>
#include "TROOT.h"
#include "TFolder.h"
#include "TLorentzVector.h"
#include <vector>
#include "Stntuple/obj/TStnDataBlock.hh"
#include "Stntuple/obj/TStnCluster.hh"
#include "Stntuple/obj/TStnClusterBlock.hh"
#include "art/Framework/Principal/Handle.h"
#include "art/Framework/Principal/Event.h"
#include "GeometryService/inc/GeometryService.hh"
#include "GeometryService/inc/GeomHandle.hh"
#include "CalorimeterGeom/inc/DiskCalorimeter.hh"
#include "RecoDataProducts/inc/KalRepPtrCollection.hh"
// #include "TrkReco/inc/TrkStrawHit.hh"
// #include "TrackCaloMatching/inc/TrkToCaloExtrapolCollection.hh"
#include "RecoDataProducts/inc/TrackClusterMatch.hh"
// #include "TrackCaloMatching/inc/TrkToCaloExtrapol.hh"
#include "MCDataProducts/inc/GenParticleCollection.hh"
#include "MCDataProducts/inc/SimParticleCollection.hh"
#include "MCDataProducts/inc/StepPointMCCollection.hh"
#include "RecoDataProducts/inc/StrawHitCollection.hh"
#include "RecoDataProducts/inc/CaloCrystalHitCollection.hh"
#include "RecoDataProducts/inc/CaloHitCollection.hh"
#include "RecoDataProducts/inc/CaloClusterCollection.hh"
//-----------------------------------------------------------------------------
// assume that the collection name is set, so we could grab it from the event
//-----------------------------------------------------------------------------
int StntupleInitMu2eClusterBlock(TStnDataBlock* Block, AbsEvent* Evt, int Mode) {
// const char* oname = {"MuratInitClusterBlock"};
// int station, ntrk;
// KalRep *krep;
// double h1_fltlen, hn_fltlen, entlen, fitmom_err;
// TStnTrack* track;
// const mu2e::StepPointMC* step;
mu2e::CaloClusterCollection* list_of_clusters;
const double kMinECrystal = 0.1; // count crystals above 100 KeV
static char calo_module_label[100], calo_description[100];
static char trcl_module_label[100], trcl_description[100];
TStnClusterBlock* cb = (TStnClusterBlock*) Block;
TStnCluster* cluster;
// static int first_entry(1);
cb->Clear();
//
// "makeCaloCluster" would be the process name, "AlgoCLOSESTSeededByENERGY" - the description,
//
cb->GetModuleLabel("mu2e::CaloClusterCollection",calo_module_label);
cb->GetDescription("mu2e::CaloClusterCollection",calo_description);
cb->GetModuleLabel("mu2e::TrackClusterMatchCollection",trcl_module_label);
cb->GetDescription("mu2e::TrackClusterMatchCollection",trcl_description );
art::Handle<mu2e::CaloClusterCollection> calo_cluster_handle;
if (calo_description[0] == 0) Evt->getByLabel(calo_module_label,calo_cluster_handle);
else Evt->getByLabel(calo_module_label,calo_description,calo_cluster_handle);
list_of_clusters = (mu2e::CaloClusterCollection*) &(*calo_cluster_handle);
std::vector<const mu2e::CaloCluster*> list_of_pcl;
const mu2e::CaloCluster *cl;
for (auto it = list_of_clusters->begin(); it != list_of_clusters->end(); it++) {
cl = &(*it);
list_of_pcl.push_back(cl);
}
//-----------------------------------------------------------------------------
// sort list of pointers such that the most energetic cluster goes the first
//-----------------------------------------------------------------------------
std::sort(list_of_pcl.begin(), list_of_pcl.end(),
[](const mu2e::CaloCluster*& lhs, const mu2e::CaloCluster*& rhs)
{ return lhs->energyDep() > rhs->energyDep(); } );
// art::Handle<mu2e::TrackClusterLink> trk_cal_map;
// if (trcl_module_label[0] != 0) {
// if (trcl_description[0] != 0) Evt->getByLabel(trcl_module_label,trcl_description,trk_cal_map);
// else Evt->getByLabel(trcl_module_label,trk_cal_map);
// }
art::ServiceHandle<mu2e::GeometryService> geom;
const mu2e::Calorimeter* cal(NULL);
if (geom->hasElement<mu2e::Calorimeter>() ) {
mu2e::GeomHandle<mu2e::Calorimeter> cc;
cal = cc.get();
}
// else if (geom->hasElement<mu2e::VaneCalorimeter>() ) {
// mu2e::GeomHandle<mu2e::VaneCalorimeter> vc;
// cal = vc.get();
// }
else if (geom->hasElement<mu2e::DiskCalorimeter>() ) {
mu2e::GeomHandle<mu2e::DiskCalorimeter> dc;
cal = dc.get();
}
//-----------------------------------------------------------------------------
// tracks are supposed to be already initialized
//-----------------------------------------------------------------------------
const mu2e::Crystal *cr;
const mu2e::CaloCrystalHit *hit;
const CLHEP::Hep3Vector *pos;
int id, ncl;
double sume, sume2, sumy, sumx, sumy2, sumx2, sumxy, qn;
double e, e1(-1.), e2, emean, e2mean;
ncl = list_of_clusters->size();
for (int i=0; i<ncl; i++) {
cluster = cb->NewCluster();
// cl = &list_of_clusters->at(i);
cl = list_of_pcl.at(i);
cluster->fCaloCluster = cl;
cluster->fDiskID = cl->diskId();
cluster->fEnergy = cl->energyDep();
cluster->fTime = cl->time();
const mu2e::CaloCluster::CaloCrystalHitPtrVector list_of_crystals = cluster->fCaloCluster->caloCrystalHitsPtrVector();
int nh = list_of_crystals.size();
//-----------------------------------------------------------------------------
// print individual crystals in local vane coordinate system
// Y and Z
//-----------------------------------------------------------------------------
qn = 0;
sume = 0;
sume2 = 0;
sumx = 0;
sumy = 0;
sumx2 = 0;
sumxy = 0;
sumy2 = 0;
e2 = 0;
for (int ih=0; ih<nh; ih++) {
hit = &(*list_of_crystals.at(ih));
e = hit->energyDep();
id = hit->id();
cr = &cal->crystal(id);
pos = &cr->localPosition();
if (e > kMinECrystal) {
qn += 1.;
sume += e;
sume2 += e*e;
sumx += e*pos->x();
sumy += e*pos->y();
sumx2 += e*pos->x()*pos->x();
sumxy += e*pos->x()*pos->y();
sumy2 += e*pos->y()*pos->y();
if (ih<2) {
e2 += e;
if (ih == 0) e1 = e;
}
}
}
emean = sume/(qn+1.e-12);
e2mean = sume2/(qn+1.e-12);
double xmean, ymean, x2mean, xymean, y2mean, sigxx, sigyy, sigxy, phi;
xmean = sumx /(sume+1.e-12);
ymean = sumy /(sume+1.e-12);
x2mean = sumx2/(sume+1.e-12);
y2mean = sumy2/(sume+1.e-12);
xymean = sumxy/(sume+1.e-12);
sigxx = x2mean-xmean*xmean;
sigxy = xymean-xmean*ymean;
sigyy = y2mean-ymean*ymean;
cluster->fX = cl->cog3Vector().x();
cluster->fY = cl->cog3Vector().y();
cluster->fZ = cl->cog3Vector().z();
cluster->fIx1 = -1.; // cl->cogRow();
cluster->fIx2 = -1.; // cl->cogColumn();
cluster->fNCrystals = nh;
cluster->fNCr1 = qn;
cluster->fYMean = ymean;
// reuse fZ to store X
cluster->fZMean = xmean;
cluster->fSigY = sqrt(y2mean-ymean*ymean);
cluster->fSigZ = sqrt(x2mean-xmean*xmean);
cluster->fSigR = sqrt(y2mean+x2mean-ymean*ymean-xmean*xmean);
//-----------------------------------------------------------------------------
// make sure that nothing goes into an overflow
//_____________________________________________________________________________
cluster->fFrE1 = e1/(sume+1.e-5);
cluster->fFrE2 = e2/(sume+1.e-5);
cluster->fSigE1 = sqrt(qn*(e2mean-emean*emean))/(sume+1.e-12);
cluster->fSigE2 = sqrt(qn*(e2mean-emean*emean))/(emean+1.e-12);
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
cluster->fSigXX = sigxx;
cluster->fSigXY = sigxy;
cluster->fSigYY = sigyy;
phi = 0.5*atan2(2*sigxy,sigxx-sigyy);
// if (sigxx < sigyy) {
// phi = phi + M_PI/2.;
// cluster->fSigXX = sigyy;
// cluster->fSigYY = sigxx;
// }
cluster->fNx = cos(phi);
cluster->fNy = sin(phi);
// unsigned int nm = (*trk_cal_map).size();
// for(size_t im=0; i<nm; im++) {
// // KalRepPtr const& trkPtr = fTrkCalMap->at(i).first->trk();
// // const KalRep * const &trk = *trkPtr;
// cl = &(*(*trk_cal_map).at(im).second);
// if (cl == cluster->fCaloCluster) {
// cluster->fClosestTrack = fTrackBlock->Track(im);
// break;
// }
// }
}
return 0;
}
//_____________________________________________________________________________
Int_t StntupleInitMu2eClusterBlockLinks(TStnDataBlock* Block, AbsEvent* AnEvent, int Mode)
{
// Mu2e version, do nothing
Int_t ev_number, rn_number;
ev_number = AnEvent->event();
rn_number = AnEvent->run();
if (! Block->Initialized(ev_number,rn_number)) return -1;
// do not do initialize links 2nd time
if (Block->LinksInitialized()) return 0;
TStnClusterBlock* header = (TStnClusterBlock*) Block;
// TStnEvent* ev = header->GetEvent();
//-----------------------------------------------------------------------------
// mark links as initialized
//-----------------------------------------------------------------------------
header->fLinksInitialized = 1;
return 0;
}
| 34.956522 | 122 | 0.547678 | macndev |
3ef515ce39f5ca04ed57a7e9356b156e4a48239b | 549 | hpp | C++ | LinearAlgebra/operation/scalar/scalar.hpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | LinearAlgebra/operation/scalar/scalar.hpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | LinearAlgebra/operation/scalar/scalar.hpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | #pragma once
#include "scalar.h"
namespace algebra::arithmetic {
template<typename T>
inline matrix<T>& operator*=(matrix<T>& m, T scalar) {
for (size_t i = 0U; i < m.columns(); ++i) {
for (size_t j = 0U; j < m.rows(); ++j) {
pixel id{i, j};
m[id] *= scalar;
}
}
return m;
}
template<typename T>
inline matrix<T> operator*(const matrix<T> &m, T scalar) {
matrix<T> result(m);
result *= scalar;
return result;
}
template<typename T>
inline matrix<T> operator*(T scalar, const matrix<T>& m) {
return m * scalar;
}
} | 18.931034 | 58 | 0.612022 | suiyili |
3ef86773cfcdb1640a64bf3f3dc494c886fcb919 | 116 | hxx | C++ | src/Providers/UNIXProviders/VLANService/UNIX_VLANService_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/VLANService/UNIX_VLANService_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/VLANService/UNIX_VLANService_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_AIX
#ifndef __UNIX_VLANSERVICE_PRIVATE_H
#define __UNIX_VLANSERVICE_PRIVATE_H
#endif
#endif
| 9.666667 | 36 | 0.836207 | brunolauze |
3efb1bfd766173e5d3984258eff284a4d1b3e91b | 289 | cpp | C++ | Chapter11/chapter11bt_05/main.cpp | markccchiang/Modern-Cpp-Programming-Cookbook | 42ba3c9ca1e0d897807f1c3baa5dddb0ee064f23 | [
"MIT"
] | null | null | null | Chapter11/chapter11bt_05/main.cpp | markccchiang/Modern-Cpp-Programming-Cookbook | 42ba3c9ca1e0d897807f1c3baa5dddb0ee064f23 | [
"MIT"
] | null | null | null | Chapter11/chapter11bt_05/main.cpp | markccchiang/Modern-Cpp-Programming-Cookbook | 42ba3c9ca1e0d897807f1c3baa5dddb0ee064f23 | [
"MIT"
] | null | null | null | #define BOOST_TEST_MODULE Controlling output
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE(test_case) {
BOOST_TEST(true);
}
BOOST_AUTO_TEST_SUITE(test_suite)
BOOST_AUTO_TEST_CASE(test_case) {
int a = 42;
BOOST_TEST(a == 0);
}
BOOST_AUTO_TEST_SUITE_END() | 19.266667 | 44 | 0.768166 | markccchiang |
3efb70530b7c62ff237b3511544c17fcfc3aad05 | 1,542 | cc | C++ | src/graph/op/kernel/binary_op_test.cc | ishine/deepx_core | a71fa4b5fec5cf5d83da04cbb9ee437d0c8b6e05 | [
"BSD-2-Clause"
] | 309 | 2021-03-24T03:00:19.000Z | 2022-03-31T16:17:46.000Z | src/graph/op/kernel/binary_op_test.cc | kiminh/deepx_core | 928d248ef26c9a5b48e34ff6a66761f94cd4be72 | [
"BSD-2-Clause"
] | 4 | 2021-03-30T01:46:32.000Z | 2021-04-06T12:22:18.000Z | src/graph/op/kernel/binary_op_test.cc | kiminh/deepx_core | 928d248ef26c9a5b48e34ff6a66761f94cd4be72 | [
"BSD-2-Clause"
] | 45 | 2021-03-29T06:12:17.000Z | 2022-03-04T05:19:46.000Z | // Copyright 2019 the deepx authors.
// Author: Yafei Zhang (kimmyzhang@tencent.com)
//
#include "../op_test.h"
namespace deepx_core {
class BinaryElementWiseBackwardTest : public testing::Test {};
TEST_F(BinaryElementWiseBackwardTest, Add) {
VariableNode X("X", Shape(2, 3), TENSOR_INITIALIZER_TYPE_RANDN, 0, 1);
VariableNode Y("Y", Shape(2, 3), TENSOR_INITIALIZER_TYPE_RANDN, 0, 1);
AddNode Z("Z", &X, &Y);
CheckOpBackward(&Z, 0);
}
TEST_F(BinaryElementWiseBackwardTest, Sub) {
VariableNode X("X", Shape(2, 3), TENSOR_INITIALIZER_TYPE_RANDN, 0, 1);
VariableNode Y("Y", Shape(2, 3), TENSOR_INITIALIZER_TYPE_RANDN, 0, 1);
SubNode Z("Z", &X, &Y);
CheckOpBackward(&Z, 0);
}
TEST_F(BinaryElementWiseBackwardTest, Mul) {
VariableNode X("X", Shape(2, 3), TENSOR_INITIALIZER_TYPE_RANDN, 0, 1);
VariableNode Y("Y", Shape(2, 3), TENSOR_INITIALIZER_TYPE_RANDN, 0, 1);
MulNode Z("Z", &X, &Y);
CheckOpBackward(&Z, 0);
}
TEST_F(BinaryElementWiseBackwardTest, Div) {
VariableNode X("X", Shape(2, 3), TENSOR_INITIALIZER_TYPE_RANDN, 0, 1);
VariableNode Y("Y", Shape(2, 3), TENSOR_INITIALIZER_TYPE_RAND, 1, 2);
DivNode Z("Z", &X, &Y);
CheckOpBackward(&Z, 0);
Y.set_initializer(TENSOR_INITIALIZER_TYPE_RAND, -2, -1);
CheckOpBackward(&Z, 0);
}
TEST_F(BinaryElementWiseBackwardTest, Pow) {
VariableNode X("X", Shape(2, 3), TENSOR_INITIALIZER_TYPE_RAND, 1, 2);
VariableNode Y("Y", Shape(2, 3), TENSOR_INITIALIZER_TYPE_RAND, 1, 2);
PowNode Z("Z", &X, &Y);
CheckOpBackward(&Z, 0);
}
} // namespace deepx_core
| 30.84 | 72 | 0.699092 | ishine |
3efc8eaed45e54f59a6dfe174cd9e6fd1f10d1bd | 1,915 | hpp | C++ | include/O2FS/OTwo.hpp | SirusDoma/O2FS | 3ffa2d5476b8ee883be145c275df5e7759c1e520 | [
"MIT"
] | 1 | 2022-02-16T12:36:32.000Z | 2022-02-16T12:36:32.000Z | include/O2FS/OTwo.hpp | SirusDoma/O2FS | 3ffa2d5476b8ee883be145c275df5e7759c1e520 | [
"MIT"
] | null | null | null | include/O2FS/OTwo.hpp | SirusDoma/O2FS | 3ffa2d5476b8ee883be145c275df5e7759c1e520 | [
"MIT"
] | null | null | null | #ifndef O2FS_OTWO_HPP
#define O2FS_OTWO_HPP
#include <windows.h>
#include <vector>
#include <unordered_map>
#include <string>
#include <O2FS/FileSystem.hpp>
namespace O2FS
{
class OTwo
{
private:
static std::vector<FileSystem*> systems;
static std::unordered_map<HANDLE, std::string> fileCaches;
// This enables modification for outer level assets (e.g OJN, OJM, OPI, OPA, OJNList.dat)
static BOOL WINAPI HookReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped);
static DWORD WINAPI HookGetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh);
// This enables file scanning modification (e.g *.ojn -> *.bms Scanning)
static HANDLE WINAPI HookFindFirstFile(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData);
static BOOL WINAPI HookFindNextFile(HANDLE hFindFile, LPWIN32_FIND_DATAA lpFindFileData);
// This allow cache to be invalidated
static BOOL WINAPI HookCloseHandle(HANDLE hObject);
public:
static bool Hooked();
static void Hook();
static void Unhook();
// Mount FileSystem hook to handle collection of files that being processed by game.
static bool Mount(FileSystem *fs);
static std::string GetFileName(HANDLE hFile);
// Real functions without detours
static BOOL WINAPI ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped);
static DWORD WINAPI GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh);
static HANDLE WINAPI FindFirstFile(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData);
static BOOL WINAPI FindNextFile(HANDLE hFindFile, LPWIN32_FIND_DATAA lpFindFileData);
static BOOL WINAPI CloseHandle(HANDLE hObject);
};
}
#endif //O2FS_OTWO_HPP
| 39.081633 | 157 | 0.721671 | SirusDoma |
3efe2e61948d859882ca8d18103796856df2e295 | 10,490 | cpp | C++ | src/solvers/solver_hardness.cpp | conp-solutions/cbmc | 648b8e304d5c5db43d01724024770780f5835952 | [
"BSD-4-Clause"
] | null | null | null | src/solvers/solver_hardness.cpp | conp-solutions/cbmc | 648b8e304d5c5db43d01724024770780f5835952 | [
"BSD-4-Clause"
] | null | null | null | src/solvers/solver_hardness.cpp | conp-solutions/cbmc | 648b8e304d5c5db43d01724024770780f5835952 | [
"BSD-4-Clause"
] | null | null | null | /*******************************************************************\
Module: measure and track the complexity of solver queries
Author: Diffblue Ltd.
\*******************************************************************/
#include "solver_hardness.h"
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <cstdint>
#include <util/format_expr.h>
#include <util/format_type.h>
#include <util/json_irep.h>
#include <util/json_stream.h>
#include <util/string2int.h>
solver_hardnesst::sat_hardnesst &solver_hardnesst::sat_hardnesst::
operator+=(const solver_hardnesst::sat_hardnesst &other)
{
clauses += other.clauses;
literals += other.literals;
variables.insert(other.variables.begin(), other.variables.end());
clause_set.insert(
clause_set.end(), other.clause_set.begin(), other.clause_set.end());
return *this;
}
bool solver_hardnesst::hardness_ssa_keyt::
operator==(const solver_hardnesst::hardness_ssa_keyt &other) const
{
if(ssa_expression != other.ssa_expression)
return false;
return pc->source_location.as_string() ==
other.pc->source_location.as_string();
}
bool solver_hardnesst::assertion_statst::empty() const
{
return pcs.empty();
}
void solver_hardnesst::register_ssa(
std::size_t ssa_index,
const exprt ssa_expression,
goto_programt::const_targett pc)
{
PRECONDITION(ssa_index < hardness_stats.size());
current_ssa_key.ssa_expression = expr2string(ssa_expression);
current_ssa_key.pc = pc;
auto pre_existing =
hardness_stats[ssa_index].insert({current_ssa_key, current_hardness});
if(!pre_existing.second)
{ // there already was an element with the same key
pre_existing.first->second += current_hardness;
}
if(hardness_stats[ssa_index].size() > max_ssa_set_size)
max_ssa_set_size = hardness_stats[ssa_index].size();
current_ssa_key = {};
current_hardness = {};
}
void solver_hardnesst::register_ssa_size(std::size_t size)
{
// do not shrink
if(size <= hardness_stats.size())
return;
hardness_stats.resize(size);
}
void solver_hardnesst::register_assertion_ssas(
const exprt ssa_expression,
const std::vector<goto_programt::const_targett> &pcs)
{
if(assertion_stats.empty())
return;
assertion_stats.sat_hardness = current_hardness;
assertion_stats.ssa_expression = expr2string(ssa_expression);
assertion_stats.pcs = pcs;
current_ssa_key = {};
current_hardness = {};
}
void solver_hardnesst::register_clause(
const bvt &bv,
const bvt &cnf,
const size_t cnf_clause_index,
bool register_cnf)
{
current_hardness.clauses++;
current_hardness.literals += bv.size();
for(const auto &literal : bv)
{
current_hardness.variables.insert(literal.var_no());
}
if(register_cnf)
{
#ifdef DEBUG
std::cout << cnf_clause_index << ": ";
for(const auto &literal : cnf)
std::cout << literal.dimacs() << " ";
std::cout << "0\n";
#endif
current_hardness.clause_set.push_back(cnf_clause_index);
}
}
void solver_hardnesst::set_outfile(const std::string &file_name)
{
outfile = file_name;
}
void solver_hardnesst::produce_report()
{
PRECONDITION(!outfile.empty());
// The SSA steps and indexed internally (by the position in the SSA equation)
// but if the `--paths` option is used, there are multiple equations, some
// sharing SSA steps. We only store the unique ones in a set but now we want
// to identify them by a single number. So we shift the SSA index to make room
// for the set index.
std::size_t ssa_set_bit_offset = 0;
const std::size_t one = 1;
while((one << ssa_set_bit_offset) < max_ssa_set_size)
++ssa_set_bit_offset;
std::ofstream out{outfile};
json_stream_arrayt json_stream_array{out};
for(std::size_t i = 0; i < hardness_stats.size(); i++)
{
const auto &ssa_step_hardness = hardness_stats[i];
if(ssa_step_hardness.empty())
continue;
std::size_t j = 0;
for(const auto &key_value_pair : ssa_step_hardness)
{
auto const &ssa = key_value_pair.first;
auto const &hardness = key_value_pair.second;
auto hardness_stats_json = json_objectt{};
hardness_stats_json["SSA_expr"] = json_stringt{ssa.ssa_expression};
hardness_stats_json["GOTO"] =
json_stringt{goto_instruction2string(ssa.pc)};
// It might be desirable to collect all SAT hardness statistics pertaining
// to a particular GOTO instruction, since there may be a number of SSA
// steps per GOTO instruction. The following JSON contains a unique
// identifier for each one.
hardness_stats_json["GOTO_ID"] =
json_numbert{std::to_string((i << ssa_set_bit_offset) + j)};
hardness_stats_json["Source"] = json(ssa.pc->source_location);
auto sat_hardness_json = json_objectt{};
sat_hardness_json["Clauses"] =
json_numbert{std::to_string(hardness.clauses)};
sat_hardness_json["Literals"] =
json_numbert{std::to_string(hardness.literals)};
sat_hardness_json["Variables"] =
json_numbert{std::to_string(hardness.variables.size())};
json_arrayt sat_hardness_clause_set_json;
for(auto const &clause : hardness.clause_set)
{
sat_hardness_clause_set_json.push_back(
json_numbert{std::to_string(clause)});
}
sat_hardness_json["ClauseSet"] = sat_hardness_clause_set_json;
hardness_stats_json["SAT_hardness"] = sat_hardness_json;
json_stream_array.push_back(hardness_stats_json);
++j;
}
}
if(!assertion_stats.empty())
{
auto assertion_stats_json = json_objectt{};
assertion_stats_json["SSA_expr"] =
json_stringt{assertion_stats.ssa_expression};
auto assertion_stats_pcs_json = json_arrayt{};
for(const auto &pc : assertion_stats.pcs)
{
auto assertion_stats_pc_json = json_objectt{};
assertion_stats_pc_json["GOTO"] =
json_stringt{goto_instruction2string(pc)};
assertion_stats_pc_json["Source"] = json(pc->source_location);
assertion_stats_pcs_json.push_back(assertion_stats_pc_json);
}
assertion_stats_json["Sources"] = assertion_stats_pcs_json;
auto assertion_hardness_json = json_objectt{};
assertion_hardness_json["Clauses"] =
json_numbert{std::to_string(assertion_stats.sat_hardness.clauses)};
assertion_hardness_json["Literals"] =
json_numbert{std::to_string(assertion_stats.sat_hardness.literals)};
assertion_hardness_json["Variables"] = json_numbert{
std::to_string(assertion_stats.sat_hardness.variables.size())};
json_arrayt assertion_sat_hardness_clause_set_json;
for(auto const &clause : assertion_stats.sat_hardness.clause_set)
{
assertion_sat_hardness_clause_set_json.push_back(
json_numbert{std::to_string(clause)});
}
assertion_hardness_json["ClauseSet"] =
assertion_sat_hardness_clause_set_json;
assertion_stats_json["SAT_hardness"] = assertion_hardness_json;
json_stream_array.push_back(assertion_stats_json);
}
}
std::string
solver_hardnesst::goto_instruction2string(goto_programt::const_targett pc)
{
std::stringstream out;
auto instruction = *pc;
if(!instruction.labels.empty())
{
out << " // Labels:";
for(const auto &label : instruction.labels)
out << " " << label;
}
if(instruction.is_target())
out << std::setw(6) << instruction.target_number << ": ";
switch(instruction.type)
{
case NO_INSTRUCTION_TYPE:
out << "NO INSTRUCTION TYPE SET";
break;
case GOTO:
case INCOMPLETE_GOTO:
if(!instruction.get_condition().is_true())
{
out << "IF " << format(instruction.get_condition()) << " THEN ";
}
out << "GOTO ";
if(instruction.is_incomplete_goto())
{
out << "(incomplete)";
}
else
{
for(auto gt_it = instruction.targets.begin();
gt_it != instruction.targets.end();
gt_it++)
{
if(gt_it != instruction.targets.begin())
out << ", ";
out << (*gt_it)->target_number;
}
}
break;
case RETURN:
case OTHER:
case DECL:
case DEAD:
case FUNCTION_CALL:
case ASSIGN:
out << format(instruction.get_code());
break;
case ASSUME:
case ASSERT:
if(instruction.is_assume())
out << "ASSUME ";
else
out << "ASSERT ";
out << format(instruction.get_condition());
break;
case SKIP:
out << "SKIP";
break;
case END_FUNCTION:
out << "END_FUNCTION";
break;
case LOCATION:
out << "LOCATION";
break;
case THROW:
out << "THROW";
{
const irept::subt &exception_list =
instruction.get_code().find(ID_exception_list).get_sub();
for(const auto &ex : exception_list)
out << " " << ex.id();
}
if(instruction.get_code().operands().size() == 1)
out << ": " << format(instruction.get_code().op0());
break;
case CATCH:
{
if(instruction.get_code().get_statement() == ID_exception_landingpad)
{
const auto &landingpad = to_code_landingpad(instruction.get_code());
out << "EXCEPTION LANDING PAD (" << format(landingpad.catch_expr().type())
<< ' ' << format(landingpad.catch_expr()) << ")";
}
else if(instruction.get_code().get_statement() == ID_push_catch)
{
out << "CATCH-PUSH ";
unsigned i = 0;
const irept::subt &exception_list =
instruction.get_code().find(ID_exception_list).get_sub();
DATA_INVARIANT(
instruction.targets.size() == exception_list.size(),
"unexpected discrepancy between sizes of instruction"
"targets and exception list");
for(auto gt_it = instruction.targets.begin();
gt_it != instruction.targets.end();
gt_it++, i++)
{
if(gt_it != instruction.targets.begin())
out << ", ";
out << exception_list[i].id() << "->" << (*gt_it)->target_number;
}
}
else if(instruction.get_code().get_statement() == ID_pop_catch)
{
out << "CATCH-POP";
}
else
{
UNREACHABLE;
}
break;
}
case ATOMIC_BEGIN:
out << "ATOMIC_BEGIN";
break;
case ATOMIC_END:
out << "ATOMIC_END";
break;
case START_THREAD:
out << "START THREAD " << instruction.get_target()->target_number;
break;
case END_THREAD:
out << "END THREAD";
break;
}
return out.str();
}
std::string solver_hardnesst::expr2string(const exprt expr)
{
std::stringstream ss;
ss << format(expr);
return ss.str();
}
| 27.105943 | 80 | 0.665396 | conp-solutions |
3efef6fe7d95344083ea3eb63e703ce45cad70f1 | 17,380 | cpp | C++ | cyclone/OpLogic.cpp | barryjburns/dgen | a6f61a594b996840110a6c4bc0347a9d8e4f81e7 | [
"BSD-3-Clause"
] | 33 | 2020-11-20T16:38:43.000Z | 2021-10-17T04:21:44.000Z | cyclone/OpLogic.cpp | barryjburns/dgen | a6f61a594b996840110a6c4bc0347a9d8e4f81e7 | [
"BSD-3-Clause"
] | 2 | 2020-11-21T00:32:37.000Z | 2020-11-23T17:38:26.000Z | cyclone/OpLogic.cpp | barryjburns/dgen | a6f61a594b996840110a6c4bc0347a9d8e4f81e7 | [
"BSD-3-Clause"
] | 2 | 2020-11-21T09:37:17.000Z | 2021-01-06T15:00:01.000Z |
// This file is part of the Cyclone 68000 Emulator
// Copyright (c) 2004,2011 FinalDave (emudave (at) gmail.com)
// Copyright (c) 2005-2011 Gražvydas "notaz" Ignotas (notasas (at) gmail.com)
// This code is licensed under the GNU General Public License version 2.0 and the MAME License.
// You can choose the license that has the most advantages for you.
// SVN repository can be found at http://code.google.com/p/cyclone68000/
#include "app.h"
// --------------------- Opcodes 0x0100+ ---------------------
// Emit a Btst (Register) opcode 0000nnn1 ttaaaaaa
int OpBtstReg(int op)
{
int use=0;
int type=0,sea=0,tea=0;
int size=0;
type=(op>>6)&3; // Btst/Bchg/Bclr/Bset
// Get source and target EA
sea=(op>>9)&7;
tea=op&0x003f;
if (tea<0x10) size=2; // For registers, 32-bits
if ((tea&0x38)==0x08) return 1; // movep
// See if we can do this opcode:
if (EaCanRead(tea,0)==0) return 1;
if (type>0)
{
if (EaCanWrite(tea)==0) return 1;
}
use=OpBase(op,size);
use&=~0x0e00; // Use same handler for all registers
if (op!=use) { OpUse(op,use); return 0; } // Use existing handler
OpStart(op,tea);
if(type==1||type==3) {
Cycles=8;
} else {
Cycles=type?8:4;
if(size>=2) Cycles+=2;
}
EaCalcReadNoSE(-1,11,sea,0,0x0e00);
EaCalcReadNoSE((type>0)?8:-1,0,tea,size,0x003f);
if (tea>=0x10)
ot(" and r11,r11,#7 ;@ mem - do mod 8\n"); // size always 0
else ot(" and r11,r11,#31 ;@ reg - do mod 32\n"); // size always 2
ot("\n");
ot(" mov r1,#1\n");
ot(" tst r0,r1,lsl r11 ;@ Do arithmetic\n");
ot(" bicne r10,r10,#0x40000000\n");
ot(" orreq r10,r10,#0x40000000 ;@ Get Z flag\n");
ot("\n");
if (type>0)
{
if (type==1) ot(" eor r1,r0,r1,lsl r11 ;@ Toggle bit\n");
if (type==2) ot(" bic r1,r0,r1,lsl r11 ;@ Clear bit\n");
if (type==3) ot(" orr r1,r0,r1,lsl r11 ;@ Set bit\n");
ot("\n");
EaWrite(8,1,tea,size,0x003f,0,0);
}
OpEnd(tea);
return 0;
}
// --------------------- Opcodes 0x0800+ ---------------------
// Emit a Btst/Bchg/Bclr/Bset (Immediate) opcode 00001000 ttaaaaaa nn
int OpBtstImm(int op)
{
int type=0,sea=0,tea=0;
int use=0;
int size=0;
type=(op>>6)&3;
// Get source and target EA
sea= 0x003c;
tea=op&0x003f;
if (tea<0x10) size=2; // For registers, 32-bits
// See if we can do this opcode:
if (EaCanRead(tea,0)==0||EaAn(tea)||tea==0x3c) return 1;
if (type>0)
{
if (EaCanWrite(tea)==0) return 1;
}
use=OpBase(op,size);
if (op!=use) { OpUse(op,use); return 0; } // Use existing handler
OpStart(op,sea,tea);
ot("\n");
EaCalcReadNoSE(-1,0,sea,0,0);
ot(" mov r11,#1\n");
ot(" bic r10,r10,#0x40000000 ;@ Blank Z flag\n");
if (tea>=0x10)
ot(" and r0,r0,#7 ;@ mem - do mod 8\n"); // size always 0
else ot(" and r0,r0,#0x1F ;@ reg - do mod 32\n"); // size always 2
ot(" mov r11,r11,lsl r0 ;@ Make bit mask\n");
ot("\n");
if(type==1||type==3) {
Cycles=12;
} else {
Cycles=type?12:8;
if(size>=2) Cycles+=2;
}
EaCalcReadNoSE((type>0)?8:-1,0,tea,size,0x003f);
ot(" tst r0,r11 ;@ Do arithmetic\n");
ot(" orreq r10,r10,#0x40000000 ;@ Get Z flag\n");
ot("\n");
if (type>0)
{
if (type==1) ot(" eor r1,r0,r11 ;@ Toggle bit\n");
if (type==2) ot(" bic r1,r0,r11 ;@ Clear bit\n");
if (type==3) ot(" orr r1,r0,r11 ;@ Set bit\n");
ot("\n");
EaWrite(8, 1,tea,size,0x003f,0,0);
#if CYCLONE_FOR_GENESIS && !MEMHANDLERS_CHANGE_CYCLES
// this is a bit hacky (device handlers might modify cycles)
if (tea==0x38||tea==0x39)
ot(" ldr r5,[r7,#0x5c] ;@ Load Cycles\n");
#endif
}
OpEnd(sea,tea);
return 0;
}
// --------------------- Opcodes 0x4000+ ---------------------
int OpNeg(int op)
{
// 01000tt0 xxeeeeee (tt=negx/clr/neg/not, xx=size, eeeeee=EA)
int type=0,size=0,ea=0,use=0;
type=(op>>9)&3;
ea =op&0x003f;
size=(op>>6)&3; if (size>=3) return 1;
// See if we can do this opcode:
if (EaCanRead (ea,size)==0||EaAn(ea)) return 1;
if (EaCanWrite(ea )==0) return 1;
use=OpBase(op,size);
if (op!=use) { OpUse(op,use); return 0; } // Use existing handler
OpStart(op,ea); Cycles=size<2?4:6;
if(ea >= 0x10) Cycles*=2;
EaCalc (11,0x003f,ea,size,0,0);
if (type!=1) EaRead (11,0,ea,size,0x003f,0,0); // Don't need to read for 'clr' (or do we, for a dummy read?)
if (type==1) ot("\n");
if (type==0)
{
ot(";@ Negx:\n");
GetXBit(1);
if(size!=2) ot(" mov r0,r0,asl #%i\n",size?16:24);
ot(" rscs r1,r0,#0 ;@ do arithmetic\n");
ot(" orr r3,r10,#0xb0000000 ;@ for old Z\n");
OpGetFlags(1,1,0);
if(size!=2) {
ot(" movs r1,r1,asr #%i\n",size?16:24);
ot(" orreq r10,r10,#0x40000000 ;@ possily missed Z\n");
}
ot(" andeq r10,r10,r3 ;@ fix Z\n");
ot("\n");
}
if (type==1)
{
ot(";@ Clear:\n");
ot(" mov r1,#0\n");
ot(" mov r10,#0x40000000 ;@ NZCV=0100\n");
ot("\n");
}
if (type==2)
{
ot(";@ Neg:\n");
if(size!=2) ot(" mov r0,r0,asl #%i\n",size?16:24);
ot(" rsbs r1,r0,#0\n");
OpGetFlags(1,1);
if(size!=2) ot(" mov r1,r1,asr #%i\n",size?16:24);
ot("\n");
}
if (type==3)
{
ot(";@ Not:\n");
if(size!=2) {
ot(" mov r0,r0,asl #%i\n",size?16:24);
ot(" mvn r1,r0,asr #%i\n",size?16:24);
}
else
ot(" mvn r1,r0\n");
ot(" adds r1,r1,#0 ;@ Defines NZ, clears CV\n");
OpGetFlags(0,0);
ot("\n");
}
if (type==1) eawrite_check_addrerr=1;
EaWrite(11, 1,ea,size,0x003f,0,0);
OpEnd(ea);
return 0;
}
// --------------------- Opcodes 0x4840+ ---------------------
// Swap, 01001000 01000nnn swap Dn
int OpSwap(int op)
{
int ea=0,use=0;
ea=op&7;
use=op&~0x0007; // Use same opcode for all An
if (op!=use) { OpUse(op,use); return 0; } // Use existing handler
OpStart(op); Cycles=4;
EaCalc (11,0x0007,ea,2,1);
EaRead (11, 0,ea,2,0x0007,1);
ot(" mov r1,r0,ror #16\n");
ot(" adds r1,r1,#0 ;@ Defines NZ, clears CV\n");
OpGetFlags(0,0);
EaWrite(11, 1,8,2,0x0007,1);
OpEnd();
return 0;
}
// --------------------- Opcodes 0x4a00+ ---------------------
// Emit a Tst opcode, 01001010 xxeeeeee
int OpTst(int op)
{
int sea=0;
int size=0,use=0;
sea=op&0x003f;
size=(op>>6)&3; if (size>=3) return 1;
// See if we can do this opcode:
if (EaCanWrite(sea)==0||EaAn(sea)) return 1;
use=OpBase(op,size);
if (op!=use) { OpUse(op,use); return 0; } // Use existing handler
OpStart(op,sea); Cycles=4;
EaCalc ( 0,0x003f,sea,size,1);
EaRead ( 0, 0,sea,size,0x003f,1);
ot(" adds r0,r0,#0 ;@ Defines NZ, clears CV\n");
ot(" mrs r10,cpsr ;@ r10=flags\n");
ot("\n");
OpEnd(sea);
return 0;
}
// --------------------- Opcodes 0x4880+ ---------------------
// Emit an Ext opcode, 01001000 1x000nnn
int OpExt(int op)
{
int ea=0;
int size=0,use=0;
int shift=0;
ea=op&0x0007;
size=(op>>6)&1;
shift=32-(8<<size);
use=OpBase(op,size);
if (op!=use) { OpUse(op,use); return 0; } // Use existing handler
OpStart(op); Cycles=4;
EaCalc (11,0x0007,ea,size+1,0,0);
EaRead (11, 0,ea,size+1,0x0007,0,0);
ot(" mov r0,r0,asl #%d\n",shift);
ot(" adds r0,r0,#0 ;@ Defines NZ, clears CV\n");
ot(" mrs r10,cpsr ;@ r10=flags\n");
ot(" mov r1,r0,asr #%d\n",shift);
ot("\n");
EaWrite(11, 1,ea,size+1,0x0007,0,0);
OpEnd();
return 0;
}
// --------------------- Opcodes 0x50c0+ ---------------------
// Emit a Set cc opcode, 0101cccc 11eeeeee
int OpSet(int op)
{
int cc=0,ea=0;
int size=0,use=0,changed_cycles=0;
static const char * const cond[16]=
{
"al","", "hi","ls","cc","cs","ne","eq",
"vc","vs","pl","mi","ge","lt","gt","le"
};
cc=(op>>8)&15;
ea=op&0x003f;
if ((ea&0x38)==0x08) return 1; // dbra, not scc
// See if we can do this opcode:
if (EaCanWrite(ea)==0) return 1;
use=OpBase(op,size);
if (op!=use) { OpUse(op,use); return 0; } // Use existing handler
changed_cycles=ea<8 && cc>=2;
OpStart(op,ea,0,changed_cycles); Cycles=8;
if (ea<8) Cycles=4;
if (cc)
ot(" mov r1,#0\n");
switch (cc)
{
case 0: // T
ot(" mvn r1,#0\n");
if (ea<8) Cycles+=2;
break;
case 1: // F
break;
case 2: // hi
ot(" tst r10,#0x60000000 ;@ hi: !C && !Z\n");
ot(" mvneq r1,r1\n");
if (ea<8) ot(" subeq r5,r5,#2 ;@ Extra cycles\n");
break;
case 3: // ls
ot(" tst r10,#0x60000000 ;@ ls: C || Z\n");
ot(" mvnne r1,r1\n");
if (ea<8) ot(" subne r5,r5,#2 ;@ Extra cycles\n");
break;
default:
ot(";@ Is the condition true?\n");
ot(" msr cpsr_flg,r10 ;@ ARM flags = 68000 flags\n");
ot(" mvn%s r1,r1\n",cond[cc]);
if (ea<8) ot(" sub%s r5,r5,#2 ;@ Extra cycles\n",cond[cc]);
break;
}
ot("\n");
eawrite_check_addrerr=1;
EaCalc (0,0x003f, ea,size,0,0);
EaWrite(0, 1, ea,size,0x003f,0,0);
opend_op_changes_cycles=changed_cycles;
OpEnd(ea,0);
return 0;
}
// Emit a Asr/Lsr/Roxr/Ror opcode
static int EmitAsr(int op,int type,int dir,int count,int size,int usereg)
{
char pct[8]=""; // count
int shift=32-(8<<size);
if (count>=1) sprintf(pct,"#%d",count); // Fixed count
if (usereg)
{
ot(";@ Use Dn for count:\n");
ot(" and r2,r8,#0x0e00\n");
ot(" ldr r2,[r7,r2,lsr #7]\n");
ot(" and r2,r2,#63\n");
ot("\n");
strcpy(pct,"r2");
}
else if (count<0)
{
ot(" mov r2,r8,lsr #9 ;@ Get 'n'\n");
ot(" and r2,r2,#7\n\n"); strcpy(pct,"r2");
}
// Take 2*n cycles:
if (count<0) ot(" sub r5,r5,r2,asl #1 ;@ Take 2*n cycles\n\n");
else Cycles+=count<<1;
if (type<2)
{
// Asr/Lsr
if (dir==0 && size<2)
{
ot(";@ For shift right, use loworder bits for the operation:\n");
ot(" mov r0,r0,%s #%d\n",type?"lsr":"asr",32-(8<<size));
ot("\n");
}
if (type==0 && dir) ot(" adds r3,r0,#0 ;@ save old value for V flag calculation, also clear V\n");
ot(";@ Shift register:\n");
if (type==0) ot(" movs r0,r0,%s %s\n",dir?"asl":"asr",pct);
if (type==1) ot(" movs r0,r0,%s %s\n",dir?"lsl":"lsr",pct);
OpGetFlags(0,0);
if (usereg) { // store X only if count is not 0
ot(" cmp %s,#0 ;@ shifting by 0?\n",pct);
ot(" biceq r10,r10,#0x20000000 ;@ if so, clear carry\n");
ot(" strne r10,[r7,#0x4c] ;@ else Save X bit\n");
} else {
// count will never be 0 if we use immediate
ot(" str r10,[r7,#0x4c] ;@ Save X bit\n");
}
ot("\n");
if (dir==0 && size<2)
{
ot(";@ restore after right shift:\n");
ot(" movs r0,r0,lsl #%d\n",32-(8<<size));
if (type)
ot(" orrmi r10,r10,#0x80000000 ;@ Potentially missed N flag\n");
ot("\n");
}
if (type==0 && dir) {
ot(";@ calculate V flag (set if sign bit changes at anytime):\n");
ot(" mov r1,#0x80000000\n");
ot(" ands r3,r3,r1,asr %s\n", pct);
ot(" cmpne r3,r1,asr %s\n", pct);
ot(" eoreq r1,r0,r3\n"); // above check doesn't catch (-1)<<(32+), so we need this
ot(" tsteq r1,#0x80000000\n");
ot(" orrne r10,r10,#0x10000000\n");
ot("\n");
}
}
// --------------------------------------
if (type==2)
{
int wide=8<<size;
// Roxr
if(count == 1)
{
if(dir==0) {
if(size!=2) {
ot(" orr r0,r0,r0,lsr #%i\n", size?16:24);
ot(" bic r0,r0,#0x%x\n", 1<<(32-wide));
}
GetXBit(0);
ot(" movs r0,r0,rrx\n");
OpGetFlags(0,1);
} else {
ot(" ldr r3,[r7,#0x4c]\n");
ot(" movs r0,r0,lsl #1\n");
OpGetFlags(0,1);
ot(" tst r3,#0x20000000\n");
ot(" orrne r0,r0,#0x%x\n", 1<<(32-wide));
ot(" bicne r10,r10,#0x40000000 ;@ clear Z in case it got there\n");
}
ot(" bic r10,r10,#0x10000000 ;@ make suve V is clear\n");
return 0;
}
if (usereg)
{
if (size==2)
{
ot(" subs r2,r2,#33\n");
ot(" addmis r2,r2,#33 ;@ Now r2=0-%d\n",wide);
}
else
{
ot(";@ Reduce r2 until <0:\n");
ot("Reduce_%.4x%s\n",op,ms?"":":");
ot(" subs r2,r2,#%d\n",wide+1);
ot(" bpl Reduce_%.4x\n",op);
ot(" adds r2,r2,#%d ;@ Now r2=0-%d\n",wide+1,wide);
}
ot(" beq norotx_%.4x\n",op);
ot("\n");
}
if (usereg||count < 0)
{
if (dir) ot(" rsb r2,r2,#%d ;@ Reverse direction\n",wide+1);
}
else
{
if (dir) ot(" mov r2,#%d ;@ Reversed\n",wide+1-count);
else ot(" mov r2,#%d\n",count);
}
if (shift) ot(" mov r0,r0,lsr #%d ;@ Shift down\n",shift);
ot("\n");
ot(";@ First get X bit (middle):\n");
ot(" ldr r3,[r7,#0x4c]\n");
ot(" rsb r1,r2,#%d\n",wide);
ot(" and r3,r3,#0x20000000\n");
ot(" mov r3,r3,lsr #29\n");
ot(" mov r3,r3,lsl r1\n");
ot(";@ Rotate bits:\n");
ot(" orr r3,r3,r0,lsr r2 ;@ Orr right part\n");
ot(" rsbs r2,r2,#%d ;@ should also clear ARM V\n",wide+1);
ot(" orrs r0,r3,r0,lsl r2 ;@ Orr left part, set flags\n");
ot("\n");
if (shift) ot(" movs r0,r0,lsl #%d ;@ Shift up and get correct NC flags\n",shift);
OpGetFlags(0,!usereg);
if (usereg) { // store X only if count is not 0
ot(" str r10,[r7,#0x4c] ;@ if not 0, Save X bit\n");
ot(" b nozerox%.4x\n",op);
ot("norotx_%.4x%s\n",op,ms?"":":");
ot(" ldr r2,[r7,#0x4c]\n");
ot(" adds r0,r0,#0 ;@ Defines NZ, clears CV\n");
OpGetFlags(0,0);
ot(" and r2,r2,#0x20000000\n");
ot(" orr r10,r10,r2 ;@ C = old_X\n");
ot("nozerox%.4x%s\n",op,ms?"":":");
}
ot("\n");
}
// --------------------------------------
if (type==3)
{
// Ror
if (size<2)
{
ot(";@ Mirror value in whole 32 bits:\n");
if (size<=0) ot(" orr r0,r0,r0,lsr #8\n");
if (size<=1) ot(" orr r0,r0,r0,lsr #16\n");
ot("\n");
}
ot(";@ Rotate register:\n");
if (!dir) ot(" adds r0,r0,#0 ;@ first clear V and C\n"); // ARM does not clear C if rot count is 0
if (count<0)
{
if (dir) ot(" rsb %s,%s,#32\n",pct,pct);
ot(" movs r0,r0,ror %s\n",pct);
}
else
{
int ror=count;
if (dir) ror=32-ror;
if (ror&31) ot(" movs r0,r0,ror #%d\n",ror);
}
OpGetFlags(0,0);
if (dir)
{
ot(" bic r10,r10,#0x30000000 ;@ clear CV\n");
ot(";@ Get carry bit from bit 0:\n");
if (usereg)
{
ot(" cmp %s,#32 ;@ rotating by 0?\n",pct);
ot(" tstne r0,#1 ;@ no, check bit 0\n");
}
else
ot(" tst r0,#1\n");
ot(" orrne r10,r10,#0x20000000\n");
}
ot("\n");
}
// --------------------------------------
return 0;
}
// Emit a Asr/Lsr/Roxr/Ror opcode - 1110cccd xxuttnnn
// (ccc=count, d=direction(r,l) xx=size extension, u=use reg for count, tt=type, nnn=register Dn)
int OpAsr(int op)
{
int ea=0,use=0;
int count=0,dir=0;
int size=0,usereg=0,type=0;
count =(op>>9)&7;
dir =(op>>8)&1;
size =(op>>6)&3;
if (size>=3) return 1; // use OpAsrEa()
usereg=(op>>5)&1;
type =(op>>3)&3;
if (usereg==0) count=((count-1)&7)+1; // because ccc=000 means 8
// Use the same opcode for target registers:
use=op&~0x0007;
// As long as count is not 8, use the same opcode for all shift counts:
if (usereg==0 && count!=8 && !(count==1&&type==2)) { use|=0x0e00; count=-1; }
if (usereg) { use&=~0x0e00; count=-1; } // Use same opcode for all Dn
if (op!=use) { OpUse(op,use); return 0; } // Use existing handler
OpStart(op,ea,0,count<0); Cycles=size<2?6:8;
EaCalc(11,0x0007, ea,size,1);
EaRead(11, 0, ea,size,0x0007,1);
EmitAsr(op,type,dir,count, size,usereg);
EaWrite(11, 0, ea,size,0x0007,1);
opend_op_changes_cycles = (count<0);
OpEnd(ea,0);
return 0;
}
// Asr/Lsr/Roxr/Ror etc EA - 11100ttd 11eeeeee
int OpAsrEa(int op)
{
int use=0,type=0,dir=0,ea=0,size=1;
type=(op>>9)&3;
dir =(op>>8)&1;
ea = op&0x3f;
if (ea<0x10) return 1;
// See if we can do this opcode:
if (EaCanRead(ea,0)==0) return 1;
if (EaCanWrite(ea)==0) return 1;
use=OpBase(op,size);
if (op!=use) { OpUse(op,use); return 0; } // Use existing handler
OpStart(op,ea); Cycles=6; // EmitAsr() will add 2
EaCalc (11,0x003f,ea,size,1);
EaRead (11, 0,ea,size,0x003f,1);
EmitAsr(op,type,dir,1,size,0);
EaWrite(11, 0,ea,size,0x003f,1);
OpEnd(ea);
return 0;
}
int OpTas(int op, int gen_special)
{
int ea=0;
int use=0;
ea=op&0x003f;
// See if we can do this opcode:
if (EaCanWrite(ea)==0 || EaAn(ea)) return 1;
use=OpBase(op,0);
if (op!=use) { OpUse(op,use); return 0; } // Use existing handler
if (!gen_special) OpStart(op,ea);
else
ot("Op%.4x_%s\n", op, ms?"":":");
Cycles=4;
if(ea>=8) Cycles+=10;
EaCalc (11,0x003f,ea,0,1);
EaRead (11, 1,ea,0,0x003f,1);
ot(" adds r1,r1,#0 ;@ Defines NZ, clears CV\n");
OpGetFlags(0,0);
ot("\n");
#if CYCLONE_FOR_GENESIS
// the original Sega hardware ignores write-back phase (to memory only)
if (ea < 0x10 || gen_special) {
#endif
ot(" orr r1,r1,#0x80000000 ;@ set bit7\n");
EaWrite(11, 1,ea,0,0x003f,1);
#if CYCLONE_FOR_GENESIS
}
#endif
OpEnd(ea);
#if (CYCLONE_FOR_GENESIS == 2)
if (!gen_special && ea >= 0x10) {
OpTas(op, 1);
}
#endif
return 0;
}
| 24.307692 | 110 | 0.524223 | barryjburns |
3eff299161e26886d8dd253733e933a05ea5c2b3 | 4,280 | cpp | C++ | stromx/runtime/test/PeriodicDelayTest.cpp | uboot/stromx | 5aff42008c576ca4aa9dbb1fdd238dac1d875ece | [
"Apache-2.0"
] | 11 | 2015-08-16T09:59:07.000Z | 2021-06-15T14:39:20.000Z | stromx/runtime/test/PeriodicDelayTest.cpp | uboot/stromx | 5aff42008c576ca4aa9dbb1fdd238dac1d875ece | [
"Apache-2.0"
] | null | null | null | stromx/runtime/test/PeriodicDelayTest.cpp | uboot/stromx | 5aff42008c576ca4aa9dbb1fdd238dac1d875ece | [
"Apache-2.0"
] | 8 | 2015-05-10T02:25:37.000Z | 2020-10-28T13:06:01.000Z | /*
* Copyright 2011 Matthias Fuchs
*
* 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 <boost/thread.hpp>
#include <cppunit/TestAssert.h>
#include "stromx/runtime/Exception.h"
#include "stromx/runtime/PeriodicDelay.h"
#include "stromx/runtime/OperatorTester.h"
#include "stromx/runtime/ReadAccess.h"
#include "stromx/runtime/test/PeriodicDelayTest.h"
CPPUNIT_TEST_SUITE_REGISTRATION (stromx::runtime::PeriodicDelayTest);
namespace stromx
{
using namespace runtime;
namespace runtime
{
void PeriodicDelayTest::setUp()
{
m_operator = new runtime::OperatorTester(new PeriodicDelay());
m_operator->initialize();
m_operator->activate();
m_data = DataContainer(new UInt32(4));
m_operator->setInputData(PeriodicDelay::INPUT, m_data);
}
void PeriodicDelayTest::testExecute()
{
m_operator->setParameter(PeriodicDelay::PERIOD, UInt32(1000));
{
DataContainer result = m_operator->getOutputData(PeriodicDelay::OUTPUT);
ReadAccess access(result);
access.get<UInt32>();
}
{
m_operator->clearOutputData(PeriodicDelay::OUTPUT);
m_operator->setInputData(PeriodicDelay::INPUT, m_data);
DataContainer result = m_operator->getOutputData(PeriodicDelay::OUTPUT);
}
{
m_operator->clearOutputData(PeriodicDelay::OUTPUT);
m_operator->setInputData(PeriodicDelay::INPUT, m_data);
DataContainer result = m_operator->getOutputData(PeriodicDelay::OUTPUT);
}
{
m_operator->clearOutputData(PeriodicDelay::OUTPUT);
m_operator->setInputData(PeriodicDelay::INPUT, m_data);
DataContainer result = m_operator->getOutputData(PeriodicDelay::OUTPUT);
}
m_operator->clearOutputData(PeriodicDelay::OUTPUT);
m_operator->setInputData(PeriodicDelay::INPUT, m_data);
boost::thread t1(boost::bind(&PeriodicDelayTest::getOutputDataInterrupted, this));
t1.interrupt();
t1.join();
}
void PeriodicDelayTest::testExecuteZeroPeriod()
{
m_operator->setParameter(PeriodicDelay::PERIOD, runtime::UInt32(0));
{
DataContainer result = m_operator->getOutputData(PeriodicDelay::OUTPUT);
ReadAccess access(result);
access.get<UInt32>();
}
{
m_operator->clearOutputData(PeriodicDelay::OUTPUT);
m_operator->setInputData(PeriodicDelay::INPUT, m_data);
DataContainer result = m_operator->getOutputData(PeriodicDelay::OUTPUT);
}
{
m_operator->clearOutputData(PeriodicDelay::OUTPUT);
m_operator->setInputData(PeriodicDelay::INPUT, m_data);
DataContainer result = m_operator->getOutputData(PeriodicDelay::OUTPUT);
}
{
m_operator->clearOutputData(PeriodicDelay::OUTPUT);
m_operator->setInputData(PeriodicDelay::INPUT, m_data);
DataContainer result = m_operator->getOutputData(PeriodicDelay::OUTPUT);
}
}
void PeriodicDelayTest::getOutputDataInterrupted()
{
CPPUNIT_ASSERT_THROW(m_operator->getOutputData(PeriodicDelay::OUTPUT), Interrupt);
}
void PeriodicDelayTest::tearDown()
{
delete m_operator;
}
}
}
| 36.581197 | 94 | 0.60257 | uboot |
3eff6b4397c0d23be0280e3862b369a0b74b8e81 | 359 | cpp | C++ | Hazelnut/src/HazelnutApp.cpp | njchensl/CHazel | 4ad8733a3c0056510725986f126e522b1e206826 | [
"Apache-2.0"
] | null | null | null | Hazelnut/src/HazelnutApp.cpp | njchensl/CHazel | 4ad8733a3c0056510725986f126e522b1e206826 | [
"Apache-2.0"
] | null | null | null | Hazelnut/src/HazelnutApp.cpp | njchensl/CHazel | 4ad8733a3c0056510725986f126e522b1e206826 | [
"Apache-2.0"
] | null | null | null | #include <Hazel.h>
#include <Hazel/Core/EntryPoint.h>
#include "EditorLayer.h"
extern "C" int g_UseCAPI = 0;
namespace Hazel {
class Hazelnut : public Application
{
public:
Hazelnut()
: Application("Hazelnut")
{
PushLayer(new EditorLayer());
}
~Hazelnut()
{
}
};
Application* CreateApplication()
{
return new Hazelnut();
}
}
| 11.966667 | 36 | 0.64624 | njchensl |
41008f837f3ebb1b17df989fb6d92a3f151d47b2 | 1,194 | hpp | C++ | vm/global_lock.hpp | rkh/rubinius | c4bcccbfba7656af4debc843953d7e29e3529ce7 | [
"BSD-3-Clause"
] | 2 | 2015-11-05T03:14:25.000Z | 2021-01-09T17:41:48.000Z | vm/global_lock.hpp | rkh/rubinius | c4bcccbfba7656af4debc843953d7e29e3529ce7 | [
"BSD-3-Clause"
] | null | null | null | vm/global_lock.hpp | rkh/rubinius | c4bcccbfba7656af4debc843953d7e29e3529ce7 | [
"BSD-3-Clause"
] | null | null | null | #ifndef RBX_GLOBAL_LOCK_HPP
#define RBX_GLOBAL_LOCK_HPP
#include "util/thread.hpp"
#include <sys/time.h>
#include <stdint.h>
namespace rubinius {
class VM;
class NativeMethodEnvironment;
class SharedState;
struct CallFrame;
class GlobalLock {
uint32_t locked_;
uint32_t serial_;
uint32_t request_drop_;
thread::Mutex mutex_;
thread::Condition condition_;
thread::Mutex handshake_mutex_;
thread::Condition handshake_condition_;
struct timeval timeout_;
public:
static bool debug_locking;
bool should_yield() {
return request_drop_ == 1;
}
void checkpoint(VM* state, CallFrame* call_frame) {
if(should_yield()) yield(state, call_frame);
}
GlobalLock();
void init();
void drop();
void take();
void yield(VM* vm, CallFrame* call_frame);
class LockGuard {
GlobalLock& lock_;
public:
LockGuard(GlobalLock& in_lock);
~LockGuard();
};
class UnlockGuard {
VM* vm_;
GlobalLock& lock_;
public:
UnlockGuard(VM* state, CallFrame* call_frame);
UnlockGuard(NativeMethodEnvironment* nme);
~UnlockGuard();
};
};
}
#endif
| 17.304348 | 55 | 0.653266 | rkh |
4100cefba20baefc4b89a79da8564fd1ee7e0813 | 7,407 | cpp | C++ | tests/AndroidCodecTest.cpp | travisleithead/skia | 2092340a0edc25e9082ce9717643d12d901c3971 | [
"BSD-3-Clause"
] | 6,304 | 2015-01-05T23:45:12.000Z | 2022-03-31T09:48:13.000Z | tests/AndroidCodecTest.cpp | travisleithead/skia | 2092340a0edc25e9082ce9717643d12d901c3971 | [
"BSD-3-Clause"
] | 67 | 2016-04-18T13:30:02.000Z | 2022-03-31T23:06:55.000Z | tests/AndroidCodecTest.cpp | travisleithead/skia | 2092340a0edc25e9082ce9717643d12d901c3971 | [
"BSD-3-Clause"
] | 1,231 | 2015-01-05T03:17:39.000Z | 2022-03-31T22:54:58.000Z | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/codec/SkAndroidCodec.h"
#include "include/codec/SkCodec.h"
#include "include/core/SkBitmap.h"
#include "include/core/SkColor.h"
#include "include/core/SkColorSpace.h"
#include "include/core/SkData.h"
#include "include/core/SkEncodedImageFormat.h"
#include "include/core/SkImageGenerator.h"
#include "include/core/SkImageInfo.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkTypes.h"
#include "include/third_party/skcms/skcms.h"
#include "src/codec/SkCodecImageGenerator.h"
#include "src/core/SkPixmapPriv.h"
#include "tests/Test.h"
#include "tools/Resources.h"
#include <string.h>
#include <initializer_list>
#include <memory>
#include <utility>
static SkISize times(const SkISize& size, float factor) {
return { (int) (size.width() * factor), (int) (size.height() * factor) };
}
static SkISize plus(const SkISize& size, int term) {
return { size.width() + term, size.height() + term };
}
static bool invalid(const SkISize& size) {
return size.width() < 1 || size.height() < 1;
}
DEF_TEST(AndroidCodec_computeSampleSize, r) {
if (GetResourcePath().isEmpty()) {
return;
}
for (const char* file : { "images/color_wheel.webp",
"images/ship.png",
"images/dog.jpg",
"images/color_wheel.gif",
"images/rle.bmp",
"images/google_chrome.ico",
"images/mandrill.wbmp",
#ifdef SK_CODEC_DECODES_RAW
"images/sample_1mp.dng",
#endif
}) {
auto data = GetResourceAsData(file);
if (!data) {
ERRORF(r, "Could not get %s", file);
continue;
}
auto codec = SkAndroidCodec::MakeFromCodec(SkCodec::MakeFromData(std::move(data)));
if (!codec) {
ERRORF(r, "Could not create codec for %s", file);
continue;
}
const auto dims = codec->getInfo().dimensions();
const SkISize downscales[] = {
plus(dims, -1),
times(dims, .15f),
times(dims, .6f),
{ (int32_t) (dims.width() * .25f), (int32_t) (dims.height() * .75f ) },
{ 1, 1 },
{ 1, 2 },
{ 2, 1 },
{ 0, -1 },
{ dims.width(), dims.height() - 1 },
};
for (SkISize size : downscales) {
const auto requested = size;
const int computedSampleSize = codec->computeSampleSize(&size);
REPORTER_ASSERT(r, size.width() >= 1 && size.height() >= 1);
if (codec->getEncodedFormat() == SkEncodedImageFormat::kWEBP) {
// WebP supports arbitrary down-scaling.
REPORTER_ASSERT(r, size == requested || invalid(requested));
} else if (computedSampleSize == 1) {
REPORTER_ASSERT(r, size == dims);
} else {
REPORTER_ASSERT(r, computedSampleSize > 1);
if (size.width() >= dims.width() || size.height() >= dims.height()) {
ERRORF(r, "File %s's computed sample size (%i) is bigger than"
" original? original: %i x %i\tsampled: %i x %i",
file, computedSampleSize, dims.width(), dims.height(),
size.width(), size.height());
}
REPORTER_ASSERT(r, size.width() >= requested.width() &&
size.height() >= requested.height());
REPORTER_ASSERT(r, size.width() < dims.width() &&
size.height() < dims.height());
}
}
const SkISize upscales[] = {
dims, plus(dims, 5), times(dims, 2),
};
for (SkISize size : upscales) {
const int computedSampleSize = codec->computeSampleSize(&size);
REPORTER_ASSERT(r, computedSampleSize == 1);
REPORTER_ASSERT(r, dims == size);
}
// This mimics how Android's ImageDecoder uses SkAndroidCodec. A client
// can choose their dimensions based on calling getSampledDimensions,
// but the ImageDecoder API takes an arbitrary size. It then uses
// computeSampleSize to determine the best dimensions and sampleSize.
// It should return the same dimensions. the sampleSize may be different
// due to integer division.
for (int sampleSize : { 1, 2, 3, 4, 8, 16, 32 }) {
const SkISize sampledDims = codec->getSampledDimensions(sampleSize);
SkISize size = sampledDims;
const int computedSampleSize = codec->computeSampleSize(&size);
if (sampledDims != size) {
ERRORF(r, "File '%s'->getSampledDimensions(%i) yields computed"
" sample size of %i\n\tsampledDimensions: %i x %i\t"
"computed dimensions: %i x %i",
file, sampleSize, computedSampleSize,
sampledDims.width(), sampledDims.height(),
size.width(), size.height());
}
}
}
}
DEF_TEST(AndroidCodec_wide, r) {
if (GetResourcePath().isEmpty()) {
return;
}
const char* path = "images/wide-gamut.png";
auto data = GetResourceAsData(path);
if (!data) {
ERRORF(r, "Missing file %s", path);
return;
}
auto codec = SkAndroidCodec::MakeFromCodec(SkCodec::MakeFromData(std::move(data)));
if (!codec) {
ERRORF(r, "Failed to create codec from %s", path);
return;
}
auto info = codec->getInfo();
auto cs = codec->computeOutputColorSpace(info.colorType(), nullptr);
if (!cs) {
ERRORF(r, "%s should have a color space", path);
return;
}
auto expected = SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kDisplayP3);
REPORTER_ASSERT(r, SkColorSpace::Equals(cs.get(), expected.get()));
}
DEF_TEST(AndroidCodec_P3, r) {
if (GetResourcePath().isEmpty()) {
return;
}
const char* path = "images/purple-displayprofile.png";
auto data = GetResourceAsData(path);
if (!data) {
ERRORF(r, "Missing file %s", path);
return;
}
auto codec = SkAndroidCodec::MakeFromCodec(SkCodec::MakeFromData(std::move(data)));
if (!codec) {
ERRORF(r, "Failed to create codec from %s", path);
return;
}
auto info = codec->getInfo();
auto cs = codec->computeOutputColorSpace(info.colorType(), nullptr);
if (!cs) {
ERRORF(r, "%s should have a color space", path);
return;
}
REPORTER_ASSERT(r, !cs->isSRGB());
REPORTER_ASSERT(r, cs->gammaCloseToSRGB());
skcms_Matrix3x3 matrix;
cs->toXYZD50(&matrix);
static constexpr skcms_Matrix3x3 kExpected = {{
{ 0.426254272f, 0.369018555f, 0.168914795f },
{ 0.226013184f, 0.685974121f, 0.0880126953f },
{ 0.0116729736f, 0.0950927734f, 0.71812439f },
}};
REPORTER_ASSERT(r, 0 == memcmp(&matrix, &kExpected, sizeof(skcms_Matrix3x3)));
}
| 36.131707 | 94 | 0.562171 | travisleithead |
4101a2e7fa7a6b45724634cbebacadd8a4b22a1f | 27,494 | cpp | C++ | media_driver/linux/common/codec/ddi/media_ddi_encode_jpeg.cpp | xhaihao/media-driver | fc044798bd07a21aacfdd6deeb5a9cb77ff34a54 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | media_driver/linux/common/codec/ddi/media_ddi_encode_jpeg.cpp | xhaihao/media-driver | fc044798bd07a21aacfdd6deeb5a9cb77ff34a54 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | media_driver/linux/common/codec/ddi/media_ddi_encode_jpeg.cpp | xhaihao/media-driver | fc044798bd07a21aacfdd6deeb5a9cb77ff34a54 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | /*
* Copyright (c) 2017-2018, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//!
//! \file media_ddi_encode_jpeg.cpp
//! \brief Defines class for DDI media jpeg encode.
//!
#include "media_libva_encoder.h"
#include "media_libva_util.h"
#include "media_ddi_encode_jpeg.h"
#include "media_ddi_encode_const.h"
#include "media_ddi_factory.h"
extern template class MediaDdiFactoryNoArg<DdiEncodeBase>;
static bool isEncodeJpegRegistered =
MediaDdiFactoryNoArg<DdiEncodeBase>::RegisterCodec<DdiEncodeJpeg>(ENCODE_ID_JPEG);
DdiEncodeJpeg::~DdiEncodeJpeg()
{
if (m_encodeCtx == nullptr)
{
return;
}
MOS_FreeMemory(m_encodeCtx->pPicParams);
m_encodeCtx->pPicParams = nullptr;
MOS_FreeMemory(m_encodeCtx->pEncodeStatusReport);
m_encodeCtx->pEncodeStatusReport = nullptr;
MOS_FreeMemory(m_huffmanTable);
m_huffmanTable = nullptr;
MOS_FreeMemory(m_encodeCtx->pQmatrixParams);
m_encodeCtx->pQmatrixParams = nullptr;
MOS_FreeMemory(m_encodeCtx->pSliceParams);
m_encodeCtx->pSliceParams = nullptr;
MOS_FreeMemory(m_encodeCtx->pbsBuffer);
m_encodeCtx->pbsBuffer = nullptr;
MOS_FreeMemory(m_appData);
m_appData = nullptr;
}
VAStatus DdiEncodeJpeg::ContextInitialize(CodechalSetting *codecHalSettings)
{
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx.", VA_STATUS_ERROR_INVALID_CONTEXT);
DDI_CHK_NULL(m_encodeCtx->pCpDdiInterface, "nullptr m_encodeCtx->pCpDdiInterface.", VA_STATUS_ERROR_INVALID_CONTEXT);
DDI_CHK_NULL(codecHalSettings, "nullptr codecHalSettings.", VA_STATUS_ERROR_INVALID_PARAMETER);
codecHalSettings->codecFunction = CODECHAL_FUNCTION_PAK;
codecHalSettings->width = m_encodeCtx->dwFrameWidth;
codecHalSettings->height = m_encodeCtx->dwFrameHeight;
codecHalSettings->mode = m_encodeCtx->wModeType;
codecHalSettings->standard = CODECHAL_JPEG;
VAStatus vaStatus = VA_STATUS_SUCCESS;
m_quantSupplied = false;
m_appDataSize = 0;
m_appDataTotalSize = 0;
m_appDataWholeHeader = false;
m_encodeCtx->pPicParams = (void *)MOS_AllocAndZeroMemory(sizeof(CodecEncodeJpegPictureParams));
DDI_CHK_NULL(m_encodeCtx->pPicParams, "nullptr m_encodeCtx->pPicParams.", VA_STATUS_ERROR_ALLOCATION_FAILED);
m_encodeCtx->pbsBuffer = (BSBuffer *)MOS_AllocAndZeroMemory(sizeof(BSBuffer));
DDI_CHK_NULL(m_encodeCtx->pbsBuffer, "nullptr m_encodeCtx->pbsBuffer.", VA_STATUS_ERROR_ALLOCATION_FAILED);
// Allocate Encode Status Report
m_encodeCtx->pEncodeStatusReport = (void *)MOS_AllocAndZeroMemory(CODECHAL_ENCODE_STATUS_NUM * sizeof(EncodeStatusReport));
DDI_CHK_NULL(m_encodeCtx->pEncodeStatusReport, "nullptr m_encodeCtx->pEncodeStatusReport.", VA_STATUS_ERROR_ALLOCATION_FAILED);
// for scan header from application
m_encodeCtx->pSliceParams = (void *)MOS_AllocAndZeroMemory(sizeof(CodecEncodeJpegScanHeader));
DDI_CHK_NULL(m_encodeCtx->pSliceParams, "nullptr m_encodeCtx->pSliceParams.", VA_STATUS_ERROR_ALLOCATION_FAILED);
// for Quant table
m_encodeCtx->pQmatrixParams = (void *)MOS_AllocAndZeroMemory(sizeof(CodecEncodeJpegQuantTable));
DDI_CHK_NULL(m_encodeCtx->pQmatrixParams, "nullptr m_encodeCtx->pQmatrixParams.", VA_STATUS_ERROR_ALLOCATION_FAILED);
// for pHuffmanTable
m_huffmanTable = (CodecEncodeJpegHuffmanDataArray *)MOS_AllocAndZeroMemory(sizeof(CodecEncodeJpegHuffmanDataArray));
DDI_CHK_NULL(m_huffmanTable, "nullptr m_huffmanTable.", VA_STATUS_ERROR_ALLOCATION_FAILED);
return vaStatus;
}
VAStatus DdiEncodeJpeg::RenderPicture(
VADriverContextP ctx,
VAContextID context,
VABufferID *buffers,
int32_t numBuffers)
{
VAStatus vaStatus = VA_STATUS_SUCCESS;
DDI_FUNCTION_ENTER();
DDI_CHK_NULL(ctx, "nullptr context", VA_STATUS_ERROR_INVALID_CONTEXT);
DDI_MEDIA_CONTEXT *mediaCtx = DdiMedia_GetMediaContext(ctx);
DDI_CHK_NULL(mediaCtx, "nullptr mediaCtx", VA_STATUS_ERROR_INVALID_CONTEXT);
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx", VA_STATUS_ERROR_INVALID_CONTEXT);
for (int32_t i = 0; i < numBuffers; i++)
{
DDI_MEDIA_BUFFER *buf = DdiMedia_GetBufferFromVABufferID(mediaCtx, buffers[i]);
DDI_CHK_NULL(buf, "Invalid buffer.", VA_STATUS_ERROR_INVALID_BUFFER);
if (buf->uiType == VAEncMacroblockDisableSkipMapBufferType)
{
DdiMedia_MediaBufferToMosResource(buf, &(m_encodeCtx->resPerMBSkipMapBuffer));
m_encodeCtx->bMbDisableSkipMapEnabled = true;
continue;
}
uint32_t dataSize = buf->iSize;
// can use internal function instead of DdiMedia_MapBuffer here?
void *data = nullptr;
DdiMedia_MapBuffer(ctx, buffers[i], &data);
DDI_CHK_NULL(data, "nullptr data.", VA_STATUS_ERROR_INVALID_BUFFER);
switch (buf->uiType)
{
case VAIQMatrixBufferType:
case VAQMatrixBufferType:
DDI_CHK_STATUS(Qmatrix(data), VA_STATUS_ERROR_INVALID_BUFFER);
break;
case VAEncPictureParameterBufferType:
DDI_CHK_STATUS(ParsePicParams(mediaCtx, data), VA_STATUS_ERROR_INVALID_BUFFER);
DDI_CHK_STATUS(
AddToStatusReportQueue((void *)m_encodeCtx->resBitstreamBuffer.bo),
VA_STATUS_ERROR_INVALID_BUFFER);
break;
case VAEncSliceParameterBufferType:
{
uint32_t numSlices = buf->uiNumElements;
DDI_CHK_STATUS(ParseSlcParams(mediaCtx, data, numSlices), VA_STATUS_ERROR_INVALID_BUFFER);
break;
}
case VAEncPackedHeaderParameterBufferType:
if ((*((int32_t *)data) == VAEncPackedHeaderRawData) || (*((int32_t *)data) == VA_ENC_PACKED_HEADER_MISC))
{
m_appDataSize = (((VAEncPackedHeaderParameterBuffer *)data)->bit_length + 7) >> 3;
}
else
{
vaStatus = VA_STATUS_ERROR_INVALID_BUFFER;
}
break;
case VAEncPackedHeaderDataBufferType:
{
uint8_t *tmpAppData = (uint8_t *)data;
//by default m_appDataWholeHeader is false, it means it only include headers between 0xFFE0 to 0xFFEF;
//follow JPEG spec definition of application segment definition
//if the packed header is start with 0xFFD8, a new SOI, it should include whole jpeg headers
if((tmpAppData[0] == 0xFF) && (tmpAppData[1] == 0xD8))
{
m_appDataWholeHeader = true;
}
if(m_appDataWholeHeader)
{
vaStatus = ParseAppData(data,m_appDataSize);
}
else
{
vaStatus = ParseAppData(data, buf->iSize);
}
m_appDataSize = 0;
}
break;
case VAHuffmanTableBufferType:
DDI_CHK_STATUS(ParseHuffmanParams(data), VA_STATUS_ERROR_INVALID_BUFFER);
break;
case VAEncQPBufferType:
DdiMedia_MediaBufferToMosResource(buf, &m_encodeCtx->resMBQpBuffer);
m_encodeCtx->bMBQpEnable = true;
break;
default:
DDI_ASSERTMESSAGE("not supported buffer type.");
break;
}
DdiMedia_UnmapBuffer(ctx, buffers[i]);
}
DDI_FUNCTION_EXIT(vaStatus);
return vaStatus;
}
// reset the parameters before each frame
VAStatus DdiEncodeJpeg::ResetAtFrameLevel()
{
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx", VA_STATUS_ERROR_INVALID_PARAMETER);
// Set the render target format
CodecEncodeJpegPictureParams *picParams = (CodecEncodeJpegPictureParams *)m_encodeCtx->pPicParams;
DDI_CHK_NULL(picParams, "nullptr picParams", VA_STATUS_ERROR_INVALID_PARAMETER);
picParams->m_inputSurfaceFormat = ConvertMediaFormatToInputSurfaceFormat(m_encodeCtx->RTtbl.pCurrentRT->format);
m_appDataSize = 0;
m_appDataTotalSize = 0;
m_appDataWholeHeader = false;
m_quantSupplied = false;
return VA_STATUS_SUCCESS;
}
VAStatus DdiEncodeJpeg::ParsePicParams(DDI_MEDIA_CONTEXT *mediaCtx, void *ptr)
{
DDI_CHK_NULL(mediaCtx, "nullptr mediaCtx", VA_STATUS_ERROR_INVALID_PARAMETER);
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx", VA_STATUS_ERROR_INVALID_PARAMETER);
DDI_CHK_NULL(ptr, "nullptr ptr", VA_STATUS_ERROR_INVALID_PARAMETER);
VAEncPictureParameterBufferJPEG *picParams = (VAEncPictureParameterBufferJPEG *)ptr;
CodecEncodeJpegPictureParams *jpegPicParams = (CodecEncodeJpegPictureParams *)m_encodeCtx->pPicParams;
DDI_CHK_NULL(jpegPicParams, "nullptr jpegPicParams", VA_STATUS_ERROR_INVALID_PARAMETER);
if (jpegPicParams->m_inputSurfaceFormat == DDI_ENCODE_JPEG_INPUTFORMAT_RESERVED)
{
return VA_STATUS_ERROR_INVALID_PARAMETER;
}
DDI_MEDIA_BUFFER *buf = DdiMedia_GetBufferFromVABufferID(mediaCtx, picParams->coded_buf);
DDI_CHK_NULL(buf, "nullptr buf", VA_STATUS_ERROR_INVALID_PARAMETER);
RemoveFromStatusReportQueue(buf);
DdiMedia_MediaBufferToMosResource(buf, &(m_encodeCtx->resBitstreamBuffer));
jpegPicParams->m_profile = picParams->pic_flags.bits.profile;
jpegPicParams->m_progressive = picParams->pic_flags.bits.progressive;
jpegPicParams->m_huffman = picParams->pic_flags.bits.huffman;
jpegPicParams->m_interleaved = picParams->pic_flags.bits.interleaved;
jpegPicParams->m_differential = picParams->pic_flags.bits.differential;
jpegPicParams->m_picWidth = picParams->picture_width;
jpegPicParams->m_picHeight = picParams->picture_height;
jpegPicParams->m_sampleBitDepth = picParams->sample_bit_depth;
jpegPicParams->m_numComponent = picParams->num_components;
jpegPicParams->m_quality = picParams->quality;
jpegPicParams->m_numScan = picParams->num_scan;
jpegPicParams->m_statusReportFeedbackNumber = 1;
for (int32_t i = 0; i < jpegNumComponent; i++)
{
jpegPicParams->m_componentID[i] = picParams->component_id[i];
jpegPicParams->m_quantTableSelector[i] = picParams->quantiser_table_selector[i];
}
return VA_STATUS_SUCCESS;
}
VAStatus DdiEncodeJpeg::ParseSlcParams(DDI_MEDIA_CONTEXT *mediaCtx, void *ptr, uint32_t numSlices)
{
DDI_UNUSED(mediaCtx);
if (numSlices != 1)
{
return VA_STATUS_ERROR_INVALID_PARAMETER;
}
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx", VA_STATUS_ERROR_INVALID_PARAMETER);
DDI_CHK_NULL(ptr, "nullptr ptr", VA_STATUS_ERROR_INVALID_PARAMETER);
DDI_CHK_NULL(m_huffmanTable, "nullptr m_huffmanTable", VA_STATUS_ERROR_INVALID_PARAMETER);
VAEncSliceParameterBufferJPEG *scanParams = (VAEncSliceParameterBufferJPEG *)ptr;
CodecEncodeJpegScanHeader *scanData = (CodecEncodeJpegScanHeader *)m_encodeCtx->pSliceParams;
DDI_CHK_NULL(scanData, "nullptr scanData", VA_STATUS_ERROR_INVALID_PARAMETER);
m_encodeCtx->dwNumSlices = numSlices;
// Only 1 scan is supported for JPEG
scanData->m_restartInterval = scanParams->restart_interval;
scanData->m_numComponent = scanParams->num_components;
for (int32_t componentCount = 0; componentCount < jpegNumComponent; componentCount++)
{
scanData->m_componentSelector[componentCount] = scanParams->components[componentCount].component_selector;
scanData->m_dcCodingTblSelector[componentCount] = scanParams->components[componentCount].dc_table_selector;
scanData->m_acCodingTblSelector[componentCount] = scanParams->components[componentCount].ac_table_selector;
// AC and DC table selectors always have the same value for android
m_huffmanTable->m_huffmanData[componentCount].m_tableID = scanData->m_dcCodingTblSelector[componentCount];
}
// Table ID for DC table for luma
m_huffmanTable->m_huffmanData[0].m_tableID = scanData->m_dcCodingTblSelector[0];
//Table ID for AC table for luma
m_huffmanTable->m_huffmanData[1].m_tableID = scanData->m_acCodingTblSelector[0];
// Table ID for DC table for chroma
m_huffmanTable->m_huffmanData[2].m_tableID = scanData->m_dcCodingTblSelector[1];
// Table ID for AC table for chroma
m_huffmanTable->m_huffmanData[3].m_tableID = scanData->m_dcCodingTblSelector[1];
return VA_STATUS_SUCCESS;
}
VAStatus DdiEncodeJpeg::Qmatrix(void *ptr)
{
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx", VA_STATUS_ERROR_INVALID_PARAMETER);
DDI_CHK_NULL(ptr, "nullptr ptr", VA_STATUS_ERROR_INVALID_PARAMETER);
VAQMatrixBufferJPEG *quantParams = (VAQMatrixBufferJPEG *)ptr;
CodecEncodeJpegQuantTable *quantMatrix = (CodecEncodeJpegQuantTable *)m_encodeCtx->pQmatrixParams;
DDI_CHK_NULL(quantMatrix, "nullptr quantMatrix", VA_STATUS_ERROR_INVALID_PARAMETER);
// Setting number of Quantization tables in Picture Params
CodecEncodeJpegPictureParams *picParams = (CodecEncodeJpegPictureParams *)m_encodeCtx->pPicParams;
DDI_CHK_NULL(picParams, "nullptr picParams", VA_STATUS_ERROR_INVALID_PARAMETER);
picParams->m_numQuantTable = 0;
if (quantParams->load_lum_quantiser_matrix == 1)
{
quantMatrix->m_quantTable[0].m_precision = 0; // only 8 bit precision is supported
quantMatrix->m_quantTable[0].m_tableID = 0; // tableID is 0 for luma
picParams->m_numQuantTable++;
for (int32_t i = 0; i < numQuantMatrix; i++)
{
quantMatrix->m_quantTable[0].m_qm[i] = quantParams->lum_quantiser_matrix[i] & 0xFF;
}
}
else // no luma quantization table present - invalid argument
{
// switch to default quantization table
m_quantSupplied = false;
return VA_STATUS_ERROR_INVALID_PARAMETER;
}
if (quantParams->load_chroma_quantiser_matrix == 1)
{
quantMatrix->m_quantTable[1].m_precision = 0; // only 8 bit precision is supported
quantMatrix->m_quantTable[1].m_tableID = 1; // table ID is 1 and 2 for U and V
picParams->m_numQuantTable++;
for (int32_t i = 0; i < numQuantMatrix; i++)
{
quantMatrix->m_quantTable[1].m_qm[i] = quantParams->chroma_quantiser_matrix[i] & 0xFF;
}
}
m_quantSupplied = true;
return VA_STATUS_SUCCESS;
}
VAStatus DdiEncodeJpeg::ParseHuffmanParams(void *ptr)
{
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx", VA_STATUS_ERROR_INVALID_PARAMETER);
DDI_CHK_NULL(ptr, "nullptr ptr", VA_STATUS_ERROR_INVALID_PARAMETER);
DDI_CHK_NULL(m_huffmanTable, "nullptr m_huffmanTable", VA_STATUS_ERROR_INVALID_PARAMETER);
VAHuffmanTableBufferJPEGBaseline *params = (VAHuffmanTableBufferJPEGBaseline *)ptr;
// Setting number of Huffman tables in Picture Params
CodecEncodeJpegPictureParams *picParams = (CodecEncodeJpegPictureParams *)m_encodeCtx->pPicParams;
DDI_CHK_NULL(picParams, "nullptr picParams", VA_STATUS_ERROR_INVALID_PARAMETER);
// For setting the tableIDs
CodecEncodeJpegScanHeader *scanData = (CodecEncodeJpegScanHeader *)m_encodeCtx->pSliceParams;
DDI_CHK_NULL(scanData, "nullptr scanData", VA_STATUS_ERROR_INVALID_PARAMETER);
picParams->m_numCodingTable = 0;
uint32_t numHuffBuffers = 0; // To check how many Huffman buffers the app sends
// Max number of huffman tables that can be sent by the app is 2
for (int32_t tblCount = 0; tblCount < maxNumHuffTables; tblCount++)
{
if (params->load_huffman_table[tblCount] != 0)
{
numHuffBuffers++;
// first copy DC table
m_huffmanTable->m_huffmanData[tblCount * 2].m_tableClass = 0;
m_huffmanTable->m_huffmanData[tblCount * 2].m_tableID = scanData->m_dcCodingTblSelector[tblCount];
for (int32_t i = 0; i < JPEG_NUM_HUFF_TABLE_DC_BITS; i++)
{
m_huffmanTable->m_huffmanData[tblCount * 2].m_bits[i] = params->huffman_table[tblCount].num_dc_codes[i] & 0xFF;
}
for (int32_t i = 0; i < JPEG_NUM_HUFF_TABLE_DC_HUFFVAL; i++)
{
m_huffmanTable->m_huffmanData[tblCount * 2].m_huffVal[i] = params->huffman_table[tblCount].dc_values[i] & 0xFF;
}
// Now copy AC table
m_huffmanTable->m_huffmanData[(tblCount * 2) + 1].m_tableClass = 1;
m_huffmanTable->m_huffmanData[(tblCount * 2) + 1].m_tableID = scanData->m_acCodingTblSelector[tblCount];
for (int32_t i = 0; i < JPEG_NUM_HUFF_TABLE_AC_BITS; i++)
{
m_huffmanTable->m_huffmanData[(tblCount * 2) + 1].m_bits[i] = params->huffman_table[tblCount].num_ac_codes[i] & 0xFF;
}
for (int32_t i = 0; i < JPEG_NUM_HUFF_TABLE_AC_HUFFVAL; i++)
{
m_huffmanTable->m_huffmanData[(tblCount * 2) + 1].m_huffVal[i] = params->huffman_table[tblCount].ac_values[i] & 0xFF;
}
}
}
if (numHuffBuffers > (JPEG_NUM_ENCODE_HUFF_BUFF / 2))
{
return VA_STATUS_ERROR_INVALID_PARAMETER;
}
// Multiplying with 2 because each table contains both AC and DC buffers
picParams->m_numCodingTable += numHuffBuffers * 2;
return VA_STATUS_SUCCESS;
};
VAStatus DdiEncodeJpeg::ParseAppData(void *ptr, int32_t size)
{
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx.", VA_STATUS_ERROR_INVALID_PARAMETER);
DDI_CHK_NULL(ptr, "nullptr ptr.", VA_STATUS_ERROR_INVALID_PARAMETER);
uint32_t prevAppDataSize = m_appDataTotalSize;
if (m_appData == nullptr)
{
m_appData = (void *)MOS_AllocAndZeroMemory(size);
if (!m_appData)
{
return VA_STATUS_ERROR_ALLOCATION_FAILED;
}
MOS_SecureMemcpy(m_appData, size, ptr, size);
}
else // app data had been sent before
{
void *tempAppData = (void *)MOS_AllocAndZeroMemory(size + (int32_t)prevAppDataSize);
if (nullptr == tempAppData)
{
return VA_STATUS_ERROR_ALLOCATION_FAILED;
}
// Copy over previous app data to a new location
MOS_SecureMemcpy(tempAppData, prevAppDataSize, (uint8_t *)m_appData, prevAppDataSize);
uint8_t *newAddress = (uint8_t *)tempAppData + prevAppDataSize;
// Add new app data buffer to the new location
MOS_SecureMemcpy(newAddress, size, (uint8_t *)ptr, size);
// Now free the previous location containing app data and overwrite with new app data buffer
MOS_FreeMemory(m_appData);
m_appData = tempAppData;
}
m_appDataTotalSize += size;
return VA_STATUS_SUCCESS;
}
VAStatus DdiEncodeJpeg::EncodeInCodecHal(uint32_t numSlices)
{
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx", VA_STATUS_ERROR_INVALID_CONTEXT);
DDI_CHK_NULL(m_encodeCtx->pCodecHal, "nullptr m_encodeCtx->pCodecHal", VA_STATUS_ERROR_INVALID_CONTEXT);
if (numSlices != 1)
{
return VA_STATUS_ERROR_INVALID_PARAMETER;
}
DDI_CODEC_RENDER_TARGET_TABLE *rtTbl = &(m_encodeCtx->RTtbl);
CodecEncodeJpegPictureParams *picParams = (CodecEncodeJpegPictureParams *)(m_encodeCtx->pPicParams);
CodecEncodeJpegScanHeader *scanData = (CodecEncodeJpegScanHeader *)m_encodeCtx->pSliceParams;
EncoderParams encodeParams;
MOS_ZeroMemory(&encodeParams, sizeof(EncoderParams));
encodeParams.ExecCodecFunction = CODECHAL_FUNCTION_PAK;
// Check if Qunt table was sent by application
// if it is not sent by application, driver will use default and scaled by quality setting
// if it is sent by application, and it also packed header with scaled qmatrix
// scal the qmatrix to change with quality setting
if (!m_quantSupplied)
{
DefaultQmatrix();
}
else if(m_appDataWholeHeader)
{
QualityScaleQmatrix();
}
// Raw Surface
MOS_SURFACE rawSurface;
MOS_ZeroMemory(&rawSurface, sizeof(MOS_SURFACE));
rawSurface.Format = (MOS_FORMAT)picParams->m_inputSurfaceFormat;
rawSurface.dwOffset = 0;
DdiMedia_MediaSurfaceToMosResource(rtTbl->pCurrentRT, &(rawSurface.OsResource));
// Recon Surface
MOS_SURFACE reconSurface;
MOS_ZeroMemory(&reconSurface, sizeof(MOS_SURFACE));
reconSurface.Format = Format_Invalid;
reconSurface.dwOffset = 0;
encodeParams.bJpegQuantMatrixSent = m_quantSupplied;
// Bitstream surface
MOS_RESOURCE bitstreamSurface;
MOS_ZeroMemory(&bitstreamSurface, sizeof(MOS_RESOURCE));
bitstreamSurface = m_encodeCtx->resBitstreamBuffer; // in render picture
bitstreamSurface.Format = Format_Buffer;
encodeParams.psRawSurface = &rawSurface;
encodeParams.psReconSurface = &reconSurface;
encodeParams.presBitstreamBuffer = &bitstreamSurface;
encodeParams.pPicParams = m_encodeCtx->pPicParams;
encodeParams.pSliceParams = m_encodeCtx->pSliceParams;
encodeParams.pApplicationData = m_appData;
// Slice level data
encodeParams.dwNumSlices = numSlices;
encodeParams.dwNumHuffBuffers = picParams->m_numCodingTable;
encodeParams.dwAppDataSize = m_appDataTotalSize;
encodeParams.fullHeaderInAppData = m_appDataWholeHeader;
encodeParams.pQuantizationTable = m_encodeCtx->pQmatrixParams;
encodeParams.pHuffmanTable = m_huffmanTable;
encodeParams.pBSBuffer = m_encodeCtx->pbsBuffer;
encodeParams.pSlcHeaderData = (void *)m_encodeCtx->pSliceHeaderData;
if (scanData->m_numComponent == 1) // Y8 input format
{
// Take the first table sent by the app
encodeParams.dwNumHuffBuffers = 2;
}
MOS_STATUS status = m_encodeCtx->pCodecHal->Execute(&encodeParams);
if (MOS_STATUS_SUCCESS != status)
{
return VA_STATUS_ERROR_ENCODING_ERROR;
}
return VA_STATUS_SUCCESS;
}
uint32_t DdiEncodeJpeg::ConvertMediaFormatToInputSurfaceFormat(DDI_MEDIA_FORMAT format)
{
switch (format)
{
case Media_Format_NV12:
return DDI_ENCODE_JPEG_INPUTFORMAT_NV12;
case Media_Format_422H:
case Media_Format_422V:
case Media_Format_UYVY:
return DDI_ENCODE_JPEG_INPUTFORMAT_UYVY;
case Media_Format_YUY2:
return DDI_ENCODE_JPEG_INPUTFORMAT_YUY2;
case Media_Format_400P:
return DDI_ENCODE_JPEG_INPUTFORMAT_Y8;
case Media_Format_X8R8G8B8:
case Media_Format_A8R8G8B8:
case Media_Format_X8B8G8R8:
case Media_Format_R8G8B8A8:
case Media_Format_A8B8G8R8:
case Media_Format_444P:
case Media_Format_AYUV:
return DDI_ENCODE_JPEG_INPUTFORMAT_RGB;
default:
return DDI_ENCODE_JPEG_INPUTFORMAT_RESERVED;
}
}
VAStatus DdiEncodeJpeg::DefaultQmatrix()
{
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx", VA_STATUS_ERROR_INVALID_PARAMETER);
CodecEncodeJpegQuantTable *quantMatrix = (CodecEncodeJpegQuantTable *)m_encodeCtx->pQmatrixParams;
DDI_CHK_NULL(quantMatrix, "nullptr quantMatrix", VA_STATUS_ERROR_INVALID_PARAMETER);
// To get Quality from Pic Params
CodecEncodeJpegPictureParams *picParams = (CodecEncodeJpegPictureParams *)m_encodeCtx->pPicParams;
DDI_CHK_NULL(picParams, "nullptr picParams", VA_STATUS_ERROR_INVALID_PARAMETER);
uint32_t quality = 0;
if (picParams->m_quality < 50)
{
quality = 5000 / picParams->m_quality;
}
else
{
quality = 200 - (picParams->m_quality * 2);
}
// 2 tables - one for luma and one for chroma
for (int32_t qMatrixCount = 0; qMatrixCount < maxNumQuantTableIndex; qMatrixCount++)
{
quantMatrix->m_quantTable[qMatrixCount].m_precision = 0;
quantMatrix->m_quantTable[qMatrixCount].m_tableID = qMatrixCount;
for (int32_t i = 0; i < numQuantMatrix; i++)
{
uint32_t quantValue = 0;
if (qMatrixCount == 0)
{
quantValue = (defaultLumaQuant[i] * quality + 50) / 100;
}
else
{
quantValue = (defaultChromaQuant[i] * quality + 50) / 100;
}
// Clamp the value to range between 1 and 255
if (quantValue < 1)
{
quantValue = 1;
}
else if (quantValue > 255)
{
quantValue = 255;
}
quantMatrix->m_quantTable[qMatrixCount].m_qm[i] = (uint16_t)quantValue;
}
}
return VA_STATUS_SUCCESS;
}
VAStatus DdiEncodeJpeg::QualityScaleQmatrix()
{
DDI_CHK_NULL(m_encodeCtx, "nullptr m_encodeCtx", VA_STATUS_ERROR_INVALID_PARAMETER);
CodecEncodeJpegQuantTable *quantMatrix = (CodecEncodeJpegQuantTable *)m_encodeCtx->pQmatrixParams;
DDI_CHK_NULL(quantMatrix, "nullptr quantMatrix", VA_STATUS_ERROR_INVALID_PARAMETER);
// To get Quality from Pic Params
CodecEncodeJpegPictureParams *picParams = (CodecEncodeJpegPictureParams *)m_encodeCtx->pPicParams;
DDI_CHK_NULL(picParams, "nullptr picParams", VA_STATUS_ERROR_INVALID_PARAMETER);
uint32_t quality = 0;
if (picParams->m_quality < 50)
{
quality = 5000 / picParams->m_quality;
}
else
{
quality = 200 - (picParams->m_quality * 2);
}
// 2 tables - one for luma and one for chroma
for (int32_t qMatrixCount = 0; qMatrixCount < picParams->m_numQuantTable; qMatrixCount++)
{
quantMatrix->m_quantTable[qMatrixCount].m_precision = 0;
quantMatrix->m_quantTable[qMatrixCount].m_tableID = qMatrixCount;
for (int32_t i = 0; i < numQuantMatrix; i++)
{
uint32_t quantValue = 0;
quantValue = ( ((uint32_t)(quantMatrix->m_quantTable[qMatrixCount].m_qm[i])) * quality + 50) / 100;
// Clamp the value to range between 1 and 255
if (quantValue < 1)
{
quantValue = 1;
}
else if (quantValue > 255)
{
quantValue = 255;
}
quantMatrix->m_quantTable[qMatrixCount].m_qm[i] = (uint16_t)quantValue;
}
}
return VA_STATUS_SUCCESS;
}
uint32_t DdiEncodeJpeg::getSliceParameterBufferSize()
{
return sizeof(VAEncSliceParameterBufferJPEG);
}
uint32_t DdiEncodeJpeg::getPictureParameterBufferSize()
{
return sizeof(VAEncPictureParameterBufferJPEG);
}
uint32_t DdiEncodeJpeg::getQMatrixBufferSize()
{
return sizeof(VAQMatrixBufferJPEG);
}
| 37.766484 | 133 | 0.699935 | xhaihao |
410342d5b369416c85e2e0921929180d37f9f554 | 639 | cpp | C++ | example/single_pro/MutexLock.cpp | jianxinzhou/Maple | 96a85a96c1e978325f87c7ebc745addf190dcb59 | [
"BSD-2-Clause"
] | 1 | 2021-01-20T09:44:50.000Z | 2021-01-20T09:44:50.000Z | example/Singleton/MutexLock.cpp | jianxinzhou/Maple | 96a85a96c1e978325f87c7ebc745addf190dcb59 | [
"BSD-2-Clause"
] | null | null | null | example/Singleton/MutexLock.cpp | jianxinzhou/Maple | 96a85a96c1e978325f87c7ebc745addf190dcb59 | [
"BSD-2-Clause"
] | 1 | 2021-01-20T09:45:17.000Z | 2021-01-20T09:45:17.000Z | #include "MutexLock.h"
#include <assert.h>
MutexLock::MutexLock()
:isLocking_(false)
{
TINY_CHECK(!pthread_mutex_init(&mutex_, NULL));
}
MutexLock::~MutexLock()
{
assert(isLocking());
TINY_CHECK(!pthread_mutex_destroy(&mutex_));
}
void MutexLock::lock()
{
TINY_CHECK(!pthread_mutex_lock(&mutex_));
isLocking_ = true;
}
void MutexLock::unlock()
{
isLocking_ = false;
TINY_CHECK(!pthread_mutex_unlock(&mutex_));
}
// end MutexLock
MutexLockGuard::MutexLockGuard(MutexLock &mutex)
:mutex_(mutex)
{
mutex_.lock();
}
MutexLockGuard::~MutexLockGuard()
{
mutex_.unlock();
}
// end MutexLockGuard
| 15.975 | 51 | 0.687011 | jianxinzhou |
41040e0510afd373c33c5d66ac284a473eb053e9 | 5,385 | cpp | C++ | Code/Engine/RendererCore/Pipeline/Implementation/Passes/SimpleRenderPass.cpp | JohannStudanski/ezEngine | bb9d7dc4ad1ba52c2725f0a8bd1b851d59dbf43c | [
"MIT"
] | 1 | 2021-06-23T14:44:02.000Z | 2021-06-23T14:44:02.000Z | Code/Engine/RendererCore/Pipeline/Implementation/Passes/SimpleRenderPass.cpp | aemeltsev/ezEngine | 98528c268dbf8cf37bb1f31e8664bd9651b7023f | [
"MIT"
] | null | null | null | Code/Engine/RendererCore/Pipeline/Implementation/Passes/SimpleRenderPass.cpp | aemeltsev/ezEngine | 98528c268dbf8cf37bb1f31e8664bd9651b7023f | [
"MIT"
] | null | null | null | #include <RendererCorePCH.h>
#include <RendererCore/Pipeline/Passes/SimpleRenderPass.h>
#include <RendererCore/Pipeline/View.h>
#include <RendererCore/RenderContext/RenderContext.h>
#include <RendererFoundation/Resources/RenderTargetView.h>
#include <RendererFoundation/Resources/Texture.h>
#include <RendererCore/Debug/DebugRenderer.h>
// clang-format off
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezSimpleRenderPass, 1, ezRTTIDefaultAllocator<ezSimpleRenderPass>)
{
EZ_BEGIN_PROPERTIES
{
EZ_MEMBER_PROPERTY("Color", m_PinColor),
EZ_MEMBER_PROPERTY("DepthStencil", m_PinDepthStencil)->AddAttributes(new ezColorAttribute(ezColor::LightCoral)),
EZ_MEMBER_PROPERTY("Message", m_sMessage),
}
EZ_END_PROPERTIES;
}
EZ_END_DYNAMIC_REFLECTED_TYPE;
// clang-format on
ezSimpleRenderPass::ezSimpleRenderPass(const char* szName)
: ezRenderPipelinePass(szName, true)
{
}
ezSimpleRenderPass::~ezSimpleRenderPass() {}
bool ezSimpleRenderPass::GetRenderTargetDescriptions(const ezView& view, const ezArrayPtr<ezGALTextureCreationDescription* const> inputs,
ezArrayPtr<ezGALTextureCreationDescription> outputs)
{
ezGALDevice* pDevice = ezGALDevice::GetDefaultDevice();
const ezGALRenderTargetSetup& setup = view.GetRenderTargetSetup();
// Color
if (inputs[m_PinColor.m_uiInputIndex])
{
outputs[m_PinColor.m_uiOutputIndex] = *inputs[m_PinColor.m_uiInputIndex];
}
else
{
// If no input is available, we use the render target setup instead.
const ezGALRenderTargetView* pTarget = pDevice->GetRenderTargetView(setup.GetRenderTarget(0));
if (pTarget)
{
const ezGALRenderTargetViewCreationDescription& desc = pTarget->GetDescription();
const ezGALTexture* pTexture = pDevice->GetTexture(desc.m_hTexture);
if (pTexture)
{
outputs[m_PinColor.m_uiOutputIndex] = pTexture->GetDescription();
outputs[m_PinColor.m_uiOutputIndex].m_bCreateRenderTarget = true;
outputs[m_PinColor.m_uiOutputIndex].m_bAllowShaderResourceView = true;
outputs[m_PinColor.m_uiOutputIndex].m_ResourceAccess.m_bReadBack = false;
outputs[m_PinColor.m_uiOutputIndex].m_ResourceAccess.m_bImmutable = true;
outputs[m_PinColor.m_uiOutputIndex].m_pExisitingNativeObject = nullptr;
}
}
}
// DepthStencil
if (inputs[m_PinDepthStencil.m_uiInputIndex])
{
outputs[m_PinDepthStencil.m_uiOutputIndex] = *inputs[m_PinDepthStencil.m_uiInputIndex];
}
else
{
// If no input is available, we use the render target setup instead.
const ezGALRenderTargetView* pTarget = pDevice->GetRenderTargetView(setup.GetDepthStencilTarget());
if (pTarget)
{
const ezGALRenderTargetViewCreationDescription& desc = pTarget->GetDescription();
const ezGALTexture* pTexture = pDevice->GetTexture(desc.m_hTexture);
if (pTexture)
{
outputs[m_PinDepthStencil.m_uiOutputIndex] = pTexture->GetDescription();
}
}
}
return true;
}
void ezSimpleRenderPass::Execute(const ezRenderViewContext& renderViewContext,
const ezArrayPtr<ezRenderPipelinePassConnection* const> inputs,
const ezArrayPtr<ezRenderPipelinePassConnection* const> outputs)
{
ezGALDevice* pDevice = ezGALDevice::GetDefaultDevice();
// Setup render target
ezGALRenderTargetSetup renderTargetSetup;
if (inputs[m_PinColor.m_uiInputIndex])
{
renderTargetSetup.SetRenderTarget(0, pDevice->GetDefaultRenderTargetView(inputs[m_PinColor.m_uiInputIndex]->m_TextureHandle));
}
if (inputs[m_PinDepthStencil.m_uiInputIndex])
{
renderTargetSetup.SetDepthStencilTarget(pDevice->GetDefaultRenderTargetView(inputs[m_PinDepthStencil.m_uiInputIndex]->m_TextureHandle));
}
renderViewContext.m_pRenderContext->SetViewportAndRenderTargetSetup(renderViewContext.m_pViewData->m_ViewPortRect, renderTargetSetup);
// Setup Permutation Vars
ezTempHashedString sRenderPass("RENDER_PASS_FORWARD");
if (renderViewContext.m_pViewData->m_ViewRenderMode != ezViewRenderMode::None)
{
sRenderPass = ezViewRenderMode::GetPermutationValue(renderViewContext.m_pViewData->m_ViewRenderMode);
}
renderViewContext.m_pRenderContext->SetShaderPermutationVariable("RENDER_PASS", sRenderPass);
// Execute render functions
RenderDataWithCategory(renderViewContext, ezDefaultRenderDataCategories::SimpleOpaque);
RenderDataWithCategory(renderViewContext, ezDefaultRenderDataCategories::SimpleTransparent);
if (!m_sMessage.IsEmpty())
{
ezDebugRenderer::Draw2DText(*renderViewContext.m_pViewDebugContext, m_sMessage, ezVec2I32(20, 20), ezColor::OrangeRed);
}
ezDebugRenderer::Render(renderViewContext);
renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PREPARE_DEPTH", "TRUE");
RenderDataWithCategory(renderViewContext, ezDefaultRenderDataCategories::SimpleForeground);
renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PREPARE_DEPTH", "FALSE");
RenderDataWithCategory(renderViewContext, ezDefaultRenderDataCategories::SimpleForeground);
RenderDataWithCategory(renderViewContext, ezDefaultRenderDataCategories::GUI);
}
void ezSimpleRenderPass::SetMessage(const char* szMessage)
{
m_sMessage = szMessage;
}
EZ_STATICLINK_FILE(RendererCore, RendererCore_Pipeline_Implementation_Passes_SimpleRenderPass);
| 37.137931 | 140 | 0.772702 | JohannStudanski |
4105557229a73cef6c8a27a3877d26ac36d4f6e1 | 3,436 | cpp | C++ | Dynamic Programming: Advanced Optimizations/Li Chao Tree.cpp | jishanshaikh4/code-library | ee6e08b66f25977050402864b8a338c43fa2c520 | [
"MIT"
] | null | null | null | Dynamic Programming: Advanced Optimizations/Li Chao Tree.cpp | jishanshaikh4/code-library | ee6e08b66f25977050402864b8a338c43fa2c520 | [
"MIT"
] | 16 | 2022-01-15T17:50:08.000Z | 2022-01-28T12:55:21.000Z | Dynamic Programming: Advanced Optimizations/Li Chao Tree.cpp | jishanshaikh4/programming-contests | ee6e08b66f25977050402864b8a338c43fa2c520 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll inf = 2e18;
struct Line {
ll m, c;
ll eval(ll x) { return m * x + c; }
};
struct node {
Line line;
node *left = nullptr;
node *right = nullptr;
node(Line line) : line(line) {}
void add_segment(Line nw, int l, int r, int L, int R) {
if (l > r || r < L || l > R)
return;
int m = (l + 1 == r ? l : (l + r) / 2);
if (l >= L and r <= R) {
bool lef = nw.eval(l) < line.eval(l);
bool mid = nw.eval(m) < line.eval(m);
if (mid)
swap(line, nw);
if (l == r)
return;
if (lef != mid) {
if (left == nullptr)
left = new node(nw);
else
left->add_segment(nw, l, m, L, R);
} else {
if (right == nullptr)
right = new node(nw);
else
right->add_segment(nw, m + 1, r, L, R);
}
return;
}
if (max(l, L) <= min(m, R)) {
if (left == nullptr)
left = new node({0, inf});
left->add_segment(nw, l, m, L, R);
}
if (max(m + 1, L) <= min(r, R)) {
if (right == nullptr)
right = new node({0, inf});
right->add_segment(nw, m + 1, r, L, R);
}
}
ll query_segment(ll x, int l, int r, int L, int R) {
if (l > r || r < L || l > R)
return inf;
int m = (l + 1 == r ? l : (l + r) / 2);
if (l >= L and r <= R) {
ll ans = line.eval(x);
if (l < r) {
if (x <= m && left != nullptr)
ans = min(ans, left->query_segment(x, l, m, L, R));
if (x > m && right != nullptr)
ans = min(ans, right->query_segment(x, m + 1, r, L, R));
}
return ans;
}
ll ans = inf;
if (max(l, L) <= min(m, R)) {
if (left == nullptr)
left = new node({0, inf});
ans = min(ans, left->query_segment(x, l, m, L, R));
}
if (max(m + 1, L) <= min(r, R)) {
if (right == nullptr)
right = new node({0, inf});
ans = min(ans, right->query_segment(x, m + 1, r, L, R));
}
return ans;
}
};
struct LiChaoTree {
int L, R;
node *root;
LiChaoTree()
: L(numeric_limits<int>::min() / 2), R(numeric_limits<int>::max() / 2),
root(nullptr) {}
LiChaoTree(int L, int R) : L(L), R(R) { root = new node({0, inf}); }
void add_line(Line line) { root->add_segment(line, L, R, L, R); }
// y = mx + b: x in [l, r]
void add_segment(Line line, int l, int r) {
root->add_segment(line, L, R, l, r);
}
ll query(ll x) { return root->query_segment(x, L, R, L, R); }
ll query_segment(ll x, int l, int r) {
return root->query_segment(x, l, r, L, R);
}
};
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
LiChaoTree t = LiChaoTree((int)-1e9, (int)1e9);
int n, q;
cin >> n >> q;
for (int i = 0; i < n; i++) {
ll l, r, a, b;
cin >> l >> r >> a >> b;
r--;
t.add_segment({a, b}, l, r);
}
while (q--) {
int ty;
cin >> ty;
if (ty == 0) {
ll l, r, a, b;
cin >> l >> r >> a >> b;
r--;
t.add_segment({a, b}, l, r);
} else {
ll x;
cin >> x;
ll ans = t.query(x);
if (ans >= inf)
cout << "INFINITY\n";
else
cout << ans << '\n';
}
}
return 0;
}
// https://judge.yosupo.jp/problem/segment_add_get_min
| 26.229008 | 78 | 0.444121 | jishanshaikh4 |
41058bcd789601cc21fba23c85befb11982bb2a0 | 5,590 | cpp | C++ | megasampler.cpp | chaosite/SMTSampler | 7c1ce353dbd9e6007451870203311520a41f5d76 | [
"BSD-3-Clause"
] | null | null | null | megasampler.cpp | chaosite/SMTSampler | 7c1ce353dbd9e6007451870203311520a41f5d76 | [
"BSD-3-Clause"
] | null | null | null | megasampler.cpp | chaosite/SMTSampler | 7c1ce353dbd9e6007451870203311520a41f5d76 | [
"BSD-3-Clause"
] | null | null | null | #include "megasampler.h"
#include <capnp/serialize.h>
#include <cinttypes>
#include <cstdint>
#include <iostream>
#include <random>
#include "pythonfuncs.h"
#include "strengthen.capnp.h"
MEGASampler::MEGASampler(std::string _input, std::string _output_dir,
int _max_samples, double _max_time,
int _max_epoch_samples, double _max_epoch_time,
int _strategy, bool _json, bool _blocking)
: Sampler(_input, _output_dir, _max_samples, _max_time, _max_epoch_samples,
_max_epoch_time, _strategy, _json, _blocking),
simpl_formula(c) {
initialize_solvers();
std::cout << "starting MEGA" << std::endl;
}
void MEGASampler::do_epoch(const z3::model& m) {
is_time_limit_reached();
struct buflen ret = call_strengthen(original_formula, m, debug);
const auto view = kj::arrayPtr(reinterpret_cast<const capnp::word*>(ret.buf),
ret.len / sizeof(capnp::word));
// Disable the security measure, we trust ourselves
const capnp::ReaderOptions options{UINT64_MAX, 64};
capnp::FlatArrayMessageReader message(view, options);
auto container = message.getRoot<StrengthenResult>();
auto res = container.getRes();
auto failureDescription = container.getFailuredecription();
if (!res) {
std::cout << "An error has occurred during epoch: "
<< failureDescription.cStr() << "\n";
failure_cause = failureDescription.cStr();
safe_exit(1);
}
for (auto varinterval : container.getIntervalmap()) {
std::string varname = varinterval.getVariable().cStr();
auto interval = varinterval.getInterval();
bool isLowMinf = interval.getIslowminf();
bool isHighInf = interval.getIshighinf();
auto low = isLowMinf ? "MINF" : std::to_string(interval.getLow());
auto high = isHighInf ? "INF" : std::to_string(interval.getHigh());
if (debug)
std::cout << varname << ": "
<< "[" << low << "," << high << "] ";
}
if (debug) std::cout << "\n";
if (use_blocking)
add_soft_constraint_from_intervals(container.getIntervalmap());
if (is_time_limit_reached("epoch")) return;
sample_intervals_in_rounds(container.getIntervalmap());
}
void MEGASampler::finish() {
json_output["method name"] = "megasampler";
Sampler::finish();
}
static inline uint64_t ilog2(const uint64_t x) {
if (0 == x) return 1; // undefined but useful for me here
return (63 - __builtin_clzll(x));
}
static inline int64_t safe_mul(const int64_t a, const int64_t b) {
int64_t ret;
if (!__builtin_mul_overflow(a, b, &ret)) return ret;
return ((a > 0) ^ (b > 0)) ? INT64_MIN : INT64_MAX;
}
void MEGASampler::sample_intervals_in_rounds(
const capnp::List<StrengthenResult::VarInterval>::Reader& intervalmap) {
uint64_t coeff = 1;
for (auto imap : intervalmap) {
const auto& i = imap.getInterval();
if (i.getIslowminf() || i.getIshighinf()) {
coeff += 32;
continue;
}
coeff = safe_mul(coeff, ilog2(1 + ilog2(1 + i.getHigh() - i.getLow())));
}
if (use_blocking) coeff = safe_mul(coeff, intervalmap.size());
const uint64_t MAX_ROUNDS = std::max(use_blocking ? 50UL : 10UL, coeff);
const unsigned int MAX_SAMPLES = 30;
const float MIN_RATE = 0.75;
uint64_t debug_samples = 0;
if (debug)
std::cout << "Sampling, coeff = " << coeff
<< ", MAX_ROUNDS = " << MAX_ROUNDS
<< ", MAX_SAMPLES = " << MAX_SAMPLES << "\n";
float rate = 1.0;
for (uint64_t round = 0; round < MAX_ROUNDS && rate > MIN_RATE; ++round) {
is_time_limit_reached();
unsigned int new_samples = 0;
unsigned int round_samples = 0;
for (; round_samples <= MAX_SAMPLES; ++round_samples) {
const std::string sample = get_random_sample_from_intervals(intervalmap);
++total_samples;
if (save_and_output_sample_if_unique(sample)) {
if (debug) ++debug_samples;
++new_samples;
}
}
rate = new_samples / round_samples;
}
if (debug)
std::cout << "Epoch unique samples: " << debug_samples
<< ", rate = " << rate << "\n";
}
std::string MEGASampler::get_random_sample_from_intervals(
const capnp::List<StrengthenResult::VarInterval>::Reader& intervalmap) {
std::string sample_string;
for (auto varinterval : intervalmap) {
std::string varname = varinterval.getVariable().cStr();
const auto& interval = varinterval.getInterval();
sample_string += varname;
sample_string += ":";
int64_t low = interval.getLow();
int64_t high = interval.getHigh();
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<int64_t> gen(low, high); // uniform, unbiased
int64_t randNum = gen(rng);
sample_string += std::to_string(randNum);
sample_string += ";";
}
return sample_string;
}
static inline z3::expr combine_expr(const z3::expr& base, const z3::expr& arg) {
if (base) return base && arg;
return arg;
}
void MEGASampler::add_soft_constraint_from_intervals(
const capnp::List<StrengthenResult::VarInterval>::Reader& intervals) {
z3::expr expr(c);
for (auto interval : intervals) {
const auto var = c.int_const(interval.getVariable().cStr());
if (!interval.getInterval().getIslowminf()) {
const auto low = c.int_val(interval.getInterval().getLow());
expr = combine_expr(expr, var >= low);
}
if (!interval.getInterval().getIshighinf()) {
const auto high = c.int_val(interval.getInterval().getHigh());
expr = combine_expr(expr, var <= high);
}
}
opt.add_soft(!expr, 1);
}
| 34.720497 | 80 | 0.655456 | chaosite |
4105fbd17cfab7cdce73c25ceacb9a7ea65e083f | 2,296 | cc | C++ | runtime/vm/type_testing_stubs_arm64.cc | annagrin/sdk | dfce72bbf9bf359ecd810964259978e24c55e237 | [
"BSD-3-Clause"
] | 2 | 2019-08-15T18:30:00.000Z | 2020-11-03T20:17:12.000Z | runtime/vm/type_testing_stubs_arm64.cc | annagrin/sdk | dfce72bbf9bf359ecd810964259978e24c55e237 | [
"BSD-3-Clause"
] | 1 | 2021-01-21T14:45:59.000Z | 2021-01-21T14:45:59.000Z | runtime/vm/type_testing_stubs_arm64.cc | annagrin/sdk | dfce72bbf9bf359ecd810964259978e24c55e237 | [
"BSD-3-Clause"
] | 3 | 2020-02-13T02:08:04.000Z | 2020-08-09T07:49:55.000Z | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/globals.h"
#if defined(TARGET_ARCH_ARM64) && !defined(DART_PRECOMPILED_RUNTIME)
#include "vm/type_testing_stubs.h"
#define __ assembler->
namespace dart {
void TypeTestingStubGenerator::BuildOptimizedTypeTestStub(
compiler::Assembler* assembler,
HierarchyInfo* hi,
const Type& type,
const Class& type_class) {
const Register kInstanceReg = R0;
const Register kClassIdReg = R9;
BuildOptimizedTypeTestStubFastCases(assembler, hi, type, type_class,
kInstanceReg, kClassIdReg);
__ ldr(CODE_REG,
compiler::Address(THR, Thread::slow_type_test_stub_offset()));
__ ldr(R9, compiler::FieldAddress(CODE_REG, Code::entry_point_offset()));
__ br(R9);
}
void TypeTestingStubGenerator::
BuildOptimizedSubclassRangeCheckWithTypeArguments(
compiler::Assembler* assembler,
HierarchyInfo* hi,
const Class& type_class,
const TypeArguments& tp,
const TypeArguments& ta) {
const Register kInstanceReg = R0;
const Register kInstanceTypeArguments = R7;
const Register kClassIdReg = R9;
BuildOptimizedSubclassRangeCheckWithTypeArguments(
assembler, hi, type_class, tp, ta, kClassIdReg, kInstanceReg,
kInstanceTypeArguments);
}
void TypeTestingStubGenerator::BuildOptimizedTypeArgumentValueCheck(
compiler::Assembler* assembler,
HierarchyInfo* hi,
const AbstractType& type_arg,
intptr_t type_param_value_offset_i,
compiler::Label* check_failed) {
const Register kInstantiatorTypeArgumentsReg = R1;
const Register kFunctionTypeArgumentsReg = R2;
const Register kInstanceTypeArguments = R7;
const Register kClassIdReg = R9;
const Register kOwnTypeArgumentValue = TMP;
BuildOptimizedTypeArgumentValueCheck(
assembler, hi, type_arg, type_param_value_offset_i, kClassIdReg,
kInstanceTypeArguments, kInstantiatorTypeArgumentsReg,
kFunctionTypeArgumentsReg, kOwnTypeArgumentValue, check_failed);
}
} // namespace dart
#endif // defined(TARGET_ARCH_ARM64) && !defined(DART_PRECOMPILED_RUNTIME)
| 32.8 | 77 | 0.747387 | annagrin |
410664eda0f1db6e1326af9ab80d94a59cbff8e5 | 10,885 | cpp | C++ | src/Interface.cpp | RicardoCoutinho/LAIG | 13933ce1dd05ff4d099ffb0864bb9034c52592e7 | [
"MIT"
] | null | null | null | src/Interface.cpp | RicardoCoutinho/LAIG | 13933ce1dd05ff4d099ffb0864bb9034c52592e7 | [
"MIT"
] | null | null | null | src/Interface.cpp | RicardoCoutinho/LAIG | 13933ce1dd05ff4d099ffb0864bb9034c52592e7 | [
"MIT"
] | null | null | null | #include "Interface.h"
#include "YAFScene.h"
#include "Application.h"
#include <GL/glui.h>
#define MOUSE_ROTATE_FACTOR 0
#define MOUSE_PAN_FACTOR 0
#define MOUSE_ZOOM_FACTOR 0
//#define MOUSE_ROTATE_FACTOR 0.5
//#define MOUSE_PAN_FACTOR 0.05
//#define MOUSE_ZOOM_FACTOR 0.5
#define CG_CGFcamera_AXIS_X 0
#define CG_CGFcamera_AXIS_Y 1
#define CG_CGFcamera_AXIS_Z 2
int Interface::modifiers=0;
Interface::Interface() {
gamemode = false;
}
Interface::~Interface() {
}
Interface * Interface::activeInterface=NULL;
void Interface::setScene(YAFScene* sc)
{
scene=sc;
}
float Interface::getDisplacementY()
{
return displacementY;
}
void Interface::init(int parent) {
//glui_window = GLUI_Master.create_glui_subwindow(parent, GLUI_SUBWINDOW_LEFT);
GLUI_Master.set_glutKeyboardFunc(Interface::preprocessKeyboard);
GLUI_Master.set_glutMouseFunc(Interface::preprocessMouse);
glutMotionFunc(Interface::preprocessMouseMoved);
glutPassiveMotionFunc(Interface::preprocessPassiveMouseMoved);
displacementX = 0;
displacementY = 0;
pressing_left=false;
pressing_right=false;
pressing_middle=false;
prev_X = 0;
prev_Y = 0;
}
void Interface::initGUI()
{
}
GLUI_Checkbox* Interface::addCheckbox(char* name, int* value, int id )
{
return glui_window->add_checkbox(name, value, id, Interface::preprocessGUI);
}
GLUI_Checkbox* Interface::addCheckboxToPanel(GLUI_Panel *p,char* name, int* value,int id )
{
return glui_window->add_checkbox_to_panel(p,name, value,id,Interface::preprocessGUI);
}
GLUI_Button* Interface::addButton(char* name,int id)
{
return glui_window->add_button(name, id, Interface::preprocessGUI);
}
GLUI_Button* Interface::addButtonToPanel(GLUI_Panel *p,char* name, int id )
{
return glui_window->add_button_to_panel(p,name, id, Interface::preprocessGUI);
}
void Interface::addColumn()
{
glui_window->add_column();
}
void Interface::addColumnToPanel(GLUI_Panel *p)
{
glui_window->add_column_to_panel(p);
}
GLUI_EditText* Interface::addEditText(char* name, char* var, int id )
{
return glui_window->add_edittext(name,GLUI_EDITTEXT_STRING, var,id,Interface::preprocessGUI);
}
GLUI_EditText* Interface::addEditText(char* name, int* var, int id )
{
return glui_window->add_edittext(name,GLUI_EDITTEXT_INT, var,id,Interface::preprocessGUI);
}
GLUI_EditText* Interface::addEditText(char* name, float* var, int id )
{
return glui_window->add_edittext(name,GLUI_EDITTEXT_FLOAT, var,id,Interface::preprocessGUI);
}
GLUI_EditText* Interface::addEditTextToPanel(GLUI_Panel *p,char* name, char* var, int id )
{
return glui_window->add_edittext_to_panel(p,name,GLUI_EDITTEXT_FLOAT, var,id,Interface::preprocessGUI);
}
GLUI_EditText* Interface::addEditTextToPanel(GLUI_Panel *p,char* name, int* var, int id )
{
return glui_window->add_edittext_to_panel(p,name,GLUI_EDITTEXT_FLOAT, var,id,Interface::preprocessGUI);
}
GLUI_EditText* Interface::addEditTextToPanel(GLUI_Panel *p,char* name, float* var, int id )
{
return glui_window->add_edittext_to_panel(p,name,GLUI_EDITTEXT_FLOAT, var,id,Interface::preprocessGUI);
}
GLUI_Listbox* Interface::addListbox(char* name, int* var, int id )
{
return glui_window->add_listbox(name,var,id,Interface::preprocessGUI);
}
GLUI_Listbox* Interface::addListboxToPanel(GLUI_Panel *p,char* name, int* var, int id)
{
return glui_window->add_listbox_to_panel(p,name,var,id,Interface::preprocessGUI);
}
GLUI_Panel* Interface::addPanel(char* name, int type )
{
return glui_window->add_panel(name,type);
}
GLUI_Panel* Interface::addPanelToPanel(GLUI_Panel *p,char* name, int type)
{
return glui_window->add_panel_to_panel(p,name,type);
}
GLUI_RadioButton* Interface::addRadioButtonToGroup(GLUI_RadioGroup * group, char * name)
{
return glui_window->add_radiobutton_to_group(group,name);
}
GLUI_RadioGroup* Interface::addRadioGroup(int *var, int id )
{
return glui_window->add_radiogroup(var,id,Interface::preprocessGUI);
}
GLUI_RadioGroup* Interface::addRadioGroupToPanel(GLUI_Panel *p,int *var, int id)
{
return glui_window->add_radiogroup_to_panel(p,var,id,Interface::preprocessGUI);
}
GLUI_Rollout* Interface::addRollout(char *name, int open, int type )
{
return glui_window->add_rollout(name,open,type);
}
GLUI_Rollout* Interface::addRolloutToPanel(GLUI_Panel* p,char *name, int open, int type )
{
return glui_window->add_rollout_to_panel(p,name,open,type);
}
void Interface::addSeparator()
{
return glui_window->add_separator();
}
void Interface::addSeparatorToPanel(GLUI_Panel *p)
{
return glui_window->add_separator_to_panel(p);
}
GLUI_Rotation* Interface::addRotation(char* name, float* var, int id)
{
return glui_window->add_rotation(name,var,id,Interface::preprocessGUI);
}
GLUI_Rotation* Interface::addRotationToPanel(GLUI_Panel *p,char* name, float* var, int id)
{
return glui_window->add_rotation_to_panel(p,name,var,id,Interface::preprocessGUI);
}
GLUI_Spinner* Interface::addSpinner(char* name, int type, int* var, int id)
{
return glui_window->add_spinner(name,type,var,id,Interface::preprocessGUI);
}
GLUI_Spinner* Interface::addSpinnerToPanel(GLUI_Panel* p,char* name, int type, int* var, int id )
{
return glui_window->add_spinner_to_panel(p,name,type,var,id,Interface::preprocessGUI);
}
GLUI_StaticText* Interface::addStaticText(char* name)
{
return glui_window->add_statictext(name);
}
GLUI_StaticText* Interface::addStaticTextToPanel(GLUI_Panel *p,char* name)
{
return glui_window->add_statictext_to_panel(p,name);
}
GLUI_Translation* Interface::addTranslationToPanel(GLUI_Panel* p,char* name, int type, float* var, int id)
{
return glui_window->add_translation_to_panel(p,name,type,var,id,Interface::preprocessGUI);
}
GLUI_Translation* Interface::addTranslation(char* name, int type, float* var, int id)
{
return glui_window->add_translation(name,type,var,id,Interface::preprocessGUI);
}
void Interface::preprocessKeyboard(unsigned char key, int x, int y)
{
modifiers=glutGetModifiers();
activeInterface->processKeyboard(key,x,y);
}
void Interface::preprocessMouse(int button, int state, int x, int y) {
modifiers=glutGetModifiers();
activeInterface->processMouse(button, state, x,y);
}
void Interface::preprocessMouseMoved(int x, int y) {
activeInterface->processMouseMoved(x,y);
}
void Interface::preprocessPassiveMouseMoved(int x, int y)
{
activeInterface->processPassiveMouseMoved(x,y);
}
void Interface::syncVars()
{
/****************************************************************/
/* This demonstrates GLUI::sync_live() */
/* We change the value of a variable that is 'live' to some */
/* control. We then call sync_live, and the control */
/* associated with that variable is automatically updated */
/* with the new value. This frees the programmer from having */
/* to always remember which variables are used by controls - */
/* simply change whatever variables are necessary, then sync */
/* the live ones all at once with a single call to sync_live */
/****************************************************************/
//glui_window->sync_live();
}
void Interface::preprocessGUI(GLUI_Control *ctrl)
{
activeInterface->processGUI(ctrl);
}
// Default handlers (to be overriden by sub-class)
void Interface::processKeyboard(unsigned char key, int x, int y)
{
switch (key) {
/*
case 'w':
//scene->cameras->getCamera(scene->camID)->setWalkMode();
break;
case 'e':
//scene->cameras->getCamera(scene->camID)->setExamineMode();
break;
*/
case 's':
Application::snapshot();
break;
case 48:
scene->appearances->getAppearance("floor")->setTexture(scene->textures->getTexture("board0"));
break;
case 49:
scene->appearances->getAppearance("floor")->setTexture(scene->textures->getTexture("board1"));
break;
case 50:
scene->appearances->getAppearance("floor")->setTexture(scene->textures->getTexture("board2"));
break;
case 'q':
if (!scene->board->menu) scene->camID = 30;
break;
case 'w':
if (!scene->board->menu) scene->camID = 31;
break;
case 'e':
if (!scene->board->menu) scene->camID = 32;
break;
case 'r':
if (!scene->board->menu) scene->camID = 33;
break;
case 'u':
if (scene->board->menu || scene->board->gameover!=0) return;
if ( scene->board->replay || (scene->board->placementsLeft[0]==12 && scene->board->placementsLeft[0]==12 )) ;
else
{
scene->board->undo();
}
break;
case 'i':
if (scene->board->menu || scene->board->gameover==0) return;
if (scene->board->gameover!=0 && scene->board->replay == 0)
{
scene->board->replay = true;
scene->board->reset();
scene->board->start_time = 0;
scene->board->actual_time = 0;
scene->board->actual_play = 0;
scene->board->itplay = scene->board->plays.begin();
scene->board->replayGame();
}
break;
case 27: // tecla de escape termina o programa
exit(0);
break;
}
}
void Interface::processMouse(int button, int state, int x, int y) {
prev_X = x;
prev_Y = y;
pressing_left = (button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN);
pressing_right = (button == GLUT_RIGHT_BUTTON) && (state == GLUT_DOWN);
pressing_middle = (button == GLUT_MIDDLE_BUTTON) && (state == GLUT_DOWN);
glutPostRedisplay();
}
void Interface::processMouseMoved(int x, int y) {
// pedido de refrescamento da janela
displacementX = x- prev_X;
displacementY = y- prev_Y;
if(pressing_left && modifiers==0)
{
scene->cameras->getCamera(scene->camID)->rotate(CG_CGFcamera_AXIS_X, displacementY*MOUSE_ROTATE_FACTOR);
scene->cameras->getCamera(scene->camID)->rotate(CG_CGFcamera_AXIS_Y, displacementX*MOUSE_ROTATE_FACTOR);
}
else if(pressing_right && modifiers==0)
{
scene->cameras->getCamera(scene->camID)->translate(CG_CGFcamera_AXIS_X, displacementX*MOUSE_PAN_FACTOR);
scene->cameras->getCamera(scene->camID)->translate(CG_CGFcamera_AXIS_Y, -displacementY*MOUSE_PAN_FACTOR);
}
else if(pressing_middle || (pressing_left && modifiers & GLUT_ACTIVE_CTRL))
{
scene->cameras->getCamera(scene->camID)->translate(CG_CGFcamera_AXIS_Z, displacementY*MOUSE_ZOOM_FACTOR);
}
prev_X = x;
prev_Y = y;
glutPostRedisplay();
}
void Interface::processPassiveMouseMoved(int x, int y) {
// pedido de refrescamento da janela
glutPostRedisplay();
}
void Interface::processGUI(GLUI_Control *ctrl)
{
}
| 28.054124 | 121 | 0.6904 | RicardoCoutinho |
41074d657bfbfbb8f1bbf9b0ea0abf63317c2c19 | 2,527 | cc | C++ | examples/octave/plot_b6.cc | yyk99/bzeditor | f4d3a24fbed2d7a3db82124e2c927288731f763b | [
"MIT"
] | null | null | null | examples/octave/plot_b6.cc | yyk99/bzeditor | f4d3a24fbed2d7a3db82124e2c927288731f763b | [
"MIT"
] | null | null | null | examples/octave/plot_b6.cc | yyk99/bzeditor | f4d3a24fbed2d7a3db82124e2c927288731f763b | [
"MIT"
] | null | null | null | //
//
//
#include "bezierMk2.h"
#include "Plotter.h"
#include <iostream>
#include <stdexcept>
std::ostream &operator<< (std::ostream &s, point2d_t const &p)
{
s << p.to_string();
return s;
}
void plot_b6_UT() /* unit test */
{
point2d_t p0 = point2d_t(10, 10);
point2d_t p1 = point2d_t(0, 20);
point2d_t p2 = point2d_t(30, 30);
point2d_t p3 = point2d_t(50, 20);
point2d_t p4 = point2d_t(40, 0);
point2d_t p5 = point2d_t(20, 0);
point2d_t p6 = p0;
{
std::vector<point2d_t> points = { p0, p1 };
auto r = bezierMk2(0, points);
if (r != p0)
throw std::logic_error("Expected p0");
}
{
std::vector<point2d_t> points = { p0, p1 };
auto r = bezierMk2(1, points);
if (r != p1)
throw std::logic_error("Expected p1");
}
{
{
std::vector<point2d_t> points = { p0, p1 };
double u = 0.5;
auto r = bezierMk2(0.5, points);
std::cout << "bz(" << u << ") = " << r << std::endl;
if (r != point2d_t(5, 15))
throw std::logic_error("Expected {5, 15}");
}
{
std::vector<point2d_t> points = { p0, p1, p2, p3, p4, p5, p6 };
double u = 0.5;
auto r = bezierMk2(0.5, points);
std::cout << "bz(" << u << ") = " << r << std::endl;
point2d_t expected = point2d_t(34.2187500000000, 15.4687500000000);
if (r != point2d_t(34.2187500000000, 15.4687500000000))
throw std::logic_error("Expected " + expected.to_string());
}
}
}
void plot_b6()
{
point2d_t p0 = point2d_t(10, 10);
point2d_t p1 = point2d_t(0, 20);
point2d_t p2 = point2d_t(30, 30);
point2d_t p3 = point2d_t(50, 20);
point2d_t p4 = point2d_t(40, 0);
point2d_t p5 = point2d_t(20, 0);
point2d_t p6 = p0;
std::vector<point2d_t> controls = { p0, p1, p2, p3, p4, p5, p6 };
std::cout << "X,Y" << std::endl;
const int N = 200;
std::vector<point2d_t> points(N+1);
for(int i = 0 ; i <= N ; ++i)
{
double u = 1.0 / N * i;
auto p = bezierMk2(u, controls);
std::cout << std::get<0>(p) << "," << std::get<1>(p) << std::endl;
points[i] = p;
}
Plotter plotter;
plotter.plot_image("plot_b6.png", controls, points);
}
int main()
{
try {
plot_b6();
} catch (std::exception ex) {
std::cerr << "Error: " << ex.what() << std::endl;
}
}
// end of file
| 23.839623 | 79 | 0.508508 | yyk99 |
410855a26d29cc1514ff01a021e1341a438e5cf2 | 4,456 | hpp | C++ | src/plugins/type/types.hpp | 0003088/libelektra-qt-gui-test | f127a7bd4daba1b70e1ea0ce13d8ff650beda5b6 | [
"BSD-3-Clause"
] | null | null | null | src/plugins/type/types.hpp | 0003088/libelektra-qt-gui-test | f127a7bd4daba1b70e1ea0ce13d8ff650beda5b6 | [
"BSD-3-Clause"
] | null | null | null | src/plugins/type/types.hpp | 0003088/libelektra-qt-gui-test | f127a7bd4daba1b70e1ea0ce13d8ff650beda5b6 | [
"BSD-3-Clause"
] | null | null | null | /**
* \file
*
* \brief Implementation of data types
*
* \copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#ifndef ELEKTRA_TYPES_HPP
#define ELEKTRA_TYPES_HPP
#include <set>
#include <map>
#include <string>
#include <sstream>
#include <locale>
#include <key.hpp>
#include <keyset.hpp>
#include <iostream>
namespace elektra {
using namespace kdb;
using namespace std;
class Type
{
public:
virtual bool check(Key k) = 0;
virtual ~Type();
};
class AnyType : public Type
{
public:
bool check(Key)
{
return true;
}
};
class EmptyType : public Type
{
public:
bool check(Key k)
{
return k.getString().empty();
}
};
class StringType : public Type
{
public:
bool check(Key k)
{
return !k.getString().empty();
}
};
template <typename T>
class TType : public Type
{
public:
bool check(Key k)
{
istringstream i (k.getString());
i.imbue (locale("C"));
T n;
i >> n;
if (i.bad()) return false;
if (i.fail()) return false;
if (!i.eof()) return false;
return true;
}
};
/**
* Reversible Type
* This checks even more pedantic, if the type is reversible
* to the same string.
* E.g. -1 might get to highest value (but this is not guaranteed)!
* */
template <typename T>
class RType : public Type
{
public:
bool check(Key k)
{
istringstream i (k.getString());
i.imbue (locale("C"));
T n;
i >> n;
if (i.bad()) return false;
if (i.fail()) return false;
if (!i.eof()) return false;
ostringstream o;
o << n;
if (o.str() != k.getString()) return false;
return true;
}
};
/**
* Reversible Type with min, max values
* This checks even more pedantic, if the type is reversible
* to the same string.
* E.g. -1 might get to highest value (but this is not guaranteed)!
* */
template <typename T>
class MType : public Type
{
public:
bool check(Key k)
{
istringstream i (k.getString());
i.imbue (locale("C"));
T n;
i >> n;
if (i.bad()) return false;
if (i.fail()) return false;
if (!i.eof()) return false;
ostringstream o;
o.imbue (locale("C"));
o << n;
if (o.fail()) return false;
if (o.str() != k.getString()) return false;
Key const min = k.getMeta<const Key>("check/type/min");
if (min)
{
istringstream i_min (min.getString());
i_min.imbue (locale("C"));
T n_min;
i_min >> n_min;
if (i_min.bad()) return false;
if (i_min.fail()) return false;
if (!i_min.eof()) return false;
if (n < n_min) return false;
}
Key const max = k.getMeta<const Key>("check/type/max");
if (max)
{
istringstream i_max (max.getString());
i_max.imbue (locale("C"));
T n_max;
i_max >> n_max;
if (i_max.bad()) return false;
if (i_max.fail()) return false;
if (!i_max.eof()) return false;
if (n > n_max) return false;
}
return true;
}
};
class FSType : public Type
{
std::set<std::string> choices;
public:
FSType()
{
choices.insert("auto");
choices.insert("swap");
choices.insert("adfs"); choices.insert("affs"); choices.insert("autofs"); choices.insert("cifs"); choices.insert("coda"); choices.insert("coherent"); choices.insert("cramfs"); choices.insert("debugfs"); choices.insert("devpts"); choices.insert("efs"); choices.insert("ext"); choices.insert("ext2"); choices.insert("ext3"); choices.insert("ext4"); choices.insert("hfs"); choices.insert("hfsplus"); choices.insert("hpfs"); choices.insert("iso9660"); choices.insert("jfs"); choices.insert("minix"); choices.insert("msdos"); choices.insert("ncpfs"); choices.insert("nfs"); choices.insert("nfs4"); choices.insert("ntfs"); choices.insert("proc"); choices.insert("qnx4"); choices.insert("ramfs"); choices.insert("reiserfs"); choices.insert("romfs"); choices.insert("smbfs"); choices.insert("sysv"); choices.insert("tmpfs"); choices.insert("udf"); choices.insert("ufs"); choices.insert("umsdos"); choices.insert("usbfs"); choices.insert("vfat"); choices.insert("xenix"); choices.insert("xfs"); choices.insert("xiafs");
}
bool check(Key k)
{
std::string label = k.getString();
size_t oldpos = 0;
size_t pos = label.find(',');;
while (pos != string::npos)
{
std::string type = label.substr (oldpos, pos - oldpos);
if (choices.find(type) == choices.end()) return false;
oldpos = pos+1;
pos = label.find(',', oldpos);
}
std::string lastType = label.substr (oldpos, string::npos);
if (choices.find(lastType) == choices.end()) return false;
return true;
}
};
} // end namespace elektra
#endif
| 22.28 | 1,015 | 0.644973 | 0003088 |
410859f88eac9a505febb206bd36593e0111d867 | 163 | cpp | C++ | tests/main.cpp | zivhoo/magic | 9f3c0d572c10e53d6580c1ffa80e1b69d07e91c0 | [
"Apache-2.0"
] | null | null | null | tests/main.cpp | zivhoo/magic | 9f3c0d572c10e53d6580c1ffa80e1b69d07e91c0 | [
"Apache-2.0"
] | null | null | null | tests/main.cpp | zivhoo/magic | 9f3c0d572c10e53d6580c1ffa80e1b69d07e91c0 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include "Magic.h"
using namespace std;
int main()
{
Magic::Magic magic;
magic.createRenderWindow("",500,400, false);
return 0;
} | 14.818182 | 48 | 0.662577 | zivhoo |
41086a8a27f4ab0f73ae58e7f2432b662d6149c5 | 128 | cpp | C++ | tensorflow-yolo-ios/dependencies/eigen/failtest/diagonal_nonconst_ctor_on_const_xpr.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 27 | 2017-06-07T19:07:32.000Z | 2020-10-15T10:09:12.000Z | tensorflow-yolo-ios/dependencies/eigen/failtest/diagonal_nonconst_ctor_on_const_xpr.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 3 | 2017-08-25T17:39:46.000Z | 2017-11-18T03:40:55.000Z | tensorflow-yolo-ios/dependencies/eigen/failtest/diagonal_nonconst_ctor_on_const_xpr.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 10 | 2017-06-16T18:04:45.000Z | 2018-07-05T17:33:01.000Z | version https://git-lfs.github.com/spec/v1
oid sha256:771e89a5fdad79addce7ae43103632797345b0f6f2ab6ffc1fd4a3eab37409b7
size 228
| 32 | 75 | 0.882813 | initialz |
4109e80caf272f9f2c669e50d4394c288134593a | 123 | hpp | C++ | source/appbase/widgets/node_editors/StatsSystem.hpp | clayne/CyberpunkSaveEditor | 2069ea833ced56f549776179c2147b27d32d650c | [
"MIT"
] | 276 | 2020-12-21T11:54:44.000Z | 2022-03-28T16:49:44.000Z | source/appbase/widgets/node_editors/StatsSystem.hpp | 13397729377/CyberpunkSaveEditor | 2069ea833ced56f549776179c2147b27d32d650c | [
"MIT"
] | 37 | 2020-12-21T18:25:12.000Z | 2022-03-31T23:51:33.000Z | source/appbase/widgets/node_editors/StatsSystem.hpp | 13397729377/CyberpunkSaveEditor | 2069ea833ced56f549776179c2147b27d32d650c | [
"MIT"
] | 36 | 2020-12-21T12:02:08.000Z | 2022-03-21T10:47:43.000Z | #pragma once
#include "inttypes.h"
#include "node_editor.hpp"
#include "redx/cpnames.hpp"
//#include "System.hpp"
| 15.375 | 28 | 0.682927 | clayne |
410c6ac7e00cccc01887426e16e6c35d47617caf | 11,902 | cpp | C++ | authentication/Engine.cpp | fmidev/smartmet-engine-authentication | 6e0521c8043bb0e239520f97c6b99e1dd459b517 | [
"MIT"
] | null | null | null | authentication/Engine.cpp | fmidev/smartmet-engine-authentication | 6e0521c8043bb0e239520f97c6b99e1dd459b517 | [
"MIT"
] | null | null | null | authentication/Engine.cpp | fmidev/smartmet-engine-authentication | 6e0521c8043bb0e239520f97c6b99e1dd459b517 | [
"MIT"
] | 1 | 2017-10-16T10:19:53.000Z | 2017-10-16T10:19:53.000Z | #include "Engine.h"
#include <macgyver/Exception.h>
#include <macgyver/PostgreSQLConnection.h>
#include <macgyver/StringConversion.h>
#include <spine/Reactor.h>
#include <stdexcept>
#include <utility>
//#include <pqxx/pqxx>
#include <stdexcept>
namespace SmartMet
{
namespace Engine
{
namespace Authentication
{
const std::string WILDCARD_IDENTIFIER = "*";
// Enum to signify access resolution status
enum class AccessStatus
{
WILDCARD_GRANT,
GRANT,
DENY,
UNKNOWN_APIKEY
};
// Token class
// Describes a singe authorization token, which has zero or more token values
class Token
{
public:
explicit Token(std::string name) : itsName(std::move(name)) {}
bool addValue(const std::string& value) const; // Constness here is hack, because std::set only
// has const_iterators
void deleteValue(const std::string& value);
bool hasValue(const std::string& value) const;
bool operator<(const Token& other) const;
bool operator==(const Token& other) const;
bool operator!=(const Token& other) const;
private:
std::string itsName;
mutable std::set<std::string> itsValues; // Hack, because std::set allows only const_iterators
};
bool Token::addValue(const std::string& value) const
{
return itsValues.insert(value).second;
}
void Token::deleteValue(const std::string& value)
{
itsValues.erase(value);
}
bool Token::hasValue(const std::string& value) const
{
return (itsValues.find(value) != itsValues.end());
}
bool Token::operator<(const Token& other) const
{
return itsName < other.itsName;
}
bool Token::operator==(const Token& other) const
{
return itsName == other.itsName;
}
bool Token::operator!=(const Token& other) const
{
return itsName != other.itsName;
}
// Type to signify that all token values are valid
struct WildCard
{
};
// Service class
// Tracks apikey-> token value relationships for a single service definition
// This object can be queried if a given apikey has access to a number of token values
class Service
{
public:
explicit Service(std::string name) : itsName(std::move(name)) {}
bool addToken(const std::string& apikey, const Token& token);
bool addTokenSet(const std::string& apikey, const std::set<Token>& tokens);
bool addWildCard(const std::string& apikey);
AccessStatus resolveAccess(const std::string& apikey,
const std::string& value,
bool explicitGrantOnly = false) const;
private:
std::string itsName;
std::set<std::string> itsWildCardApikeys;
// Apikey -> one or more token definitions
std::map<std::string, std::set<Token>> itsTokenApikeyMapping;
};
bool Service::addToken(const std::string& apikey, const Token& token)
{
try
{
auto it = itsTokenApikeyMapping.find(apikey);
if (it == itsTokenApikeyMapping.end())
{
// No such apikey yet
return itsTokenApikeyMapping.insert(std::make_pair(apikey, std::set<Token>{token})).second;
}
auto& tokenSet = it->second;
return tokenSet.insert(token).second;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
bool Service::addTokenSet(const std::string& apikey, const std::set<Token>& tokens)
{
try
{
return itsTokenApikeyMapping.insert(std::make_pair(apikey, tokens)).second;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
bool Service::addWildCard(const std::string& apikey)
{
try
{
return itsWildCardApikeys.insert(apikey).second;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
AccessStatus Service::resolveAccess(const std::string& apikey,
const std::string& value,
bool explicitGrantOnly) const
{
try
{
// First check if this apikey has "wildcard" definition, it means universal access
if (!explicitGrantOnly && (itsWildCardApikeys.find(apikey) != itsWildCardApikeys.end()))
return AccessStatus::WILDCARD_GRANT;
// Next check if value is found in token definitions for this apikey
auto it = itsTokenApikeyMapping.find(apikey);
if (it == itsTokenApikeyMapping.end())
{
// No such apikey defined for this service.
return explicitGrantOnly ? AccessStatus::DENY : AccessStatus::UNKNOWN_APIKEY;
}
const auto& tokens = it->second;
// See if value is defined in one of the token sets:
for (const auto& token : tokens)
{
if (token.hasValue(value))
return AccessStatus::GRANT;
}
return AccessStatus::DENY;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
Engine::Engine(const char* theConfigFile) : itsConfig(theConfigFile), itsActiveThreadCount(0) {}
bool Engine::authorize(const std::string& apikey,
const std::string& tokenvalue,
const std::string& service,
bool explicitGrantOnly) const
{
try
{
SmartMet::Spine::ReadLock lock(itsMutex);
auto it = itsServices.find(service);
if (it != itsServices.end())
{
AccessStatus value_status = it->second.resolveAccess(apikey, tokenvalue, explicitGrantOnly);
switch (value_status)
{
case AccessStatus::UNKNOWN_APIKEY:
// Unknown apikey for this aservice
// Default access policy is "allow", unknown apikey is let through
return itsConfig.defaultAccessAllow;
case AccessStatus::DENY:
return false;
case AccessStatus::GRANT:
case AccessStatus::WILDCARD_GRANT:
default: // Dummy case, for compiler
return true;
}
}
else // Unkown service, either there is a plugin programming error or no access tokens are
// defined for this service
return !explicitGrantOnly;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// Grant access if ALL token values are valid
bool Engine::authorize(const std::string& apikey,
const std::vector<std::string>& tokenvalues,
const std::string& service) const
{
try
{
SmartMet::Spine::ReadLock lock(itsMutex);
auto it = itsServices.find(service);
if (it == itsServices.end())
return true; // Unknown service, let through
for (const std::string& value : tokenvalues)
{
// Let through if all tokens are valid
AccessStatus value_status = it->second.resolveAccess(apikey, value);
switch (value_status)
{
case AccessStatus::UNKNOWN_APIKEY:
{
// Unknown apikey for this aservice
// Default access policy is "allow", unknown apikey is let through
return itsConfig.defaultAccessAllow;
}
case AccessStatus::DENY:
{
// Disallowed value encountered, deny access;
return false;
}
case AccessStatus::GRANT:
{
// Allowed value, continue to the next
continue;
}
case AccessStatus::WILDCARD_GRANT:
{
// This apikey has universal access, no reason to loop through all token values
return true;
}
}
}
// All tokens valid
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
void Engine::init()
{
try
{
rebuildMappings();
itsUpdateThread =
boost::movelib::make_unique<boost::thread>(boost::bind(&Engine::rebuildUpdateLoop, this));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Shutdown the engine
*/
// ----------------------------------------------------------------------
void Engine::shutdown()
{
try
{
std::cout << " -- Shutdown requested (authentication engine)\n";
while (itsActiveThreadCount > 0)
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
void Engine::rebuildUpdateLoop()
{
try
{
itsActiveThreadCount++;
while (!Spine::Reactor::isShuttingDown())
{
try
{
rebuildMappings();
}
catch (...)
{
Fmi::Exception exception(BCP, "Database exception!", nullptr);
exception.printError();
}
for (int i = 0; (!Spine::Reactor::isShuttingDown() && i < itsConfig.updateIntervalSeconds);
i++)
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
}
itsActiveThreadCount--;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
void Engine::rebuildMappings()
{
using namespace Fmi::Database;
try
{
PostgreSQLConnectionOptions opt;
opt.host = itsConfig.dBHost;
opt.port = itsConfig.port;
opt.database = itsConfig.database;
opt.username = itsConfig.user;
opt.password = itsConfig.password;
PostgreSQLConnection conn(opt);
std::string query;
pqxx::result res;
auto transaction = conn.transaction();
// Get token definitions
query =
"SELECT service,token,value from " + itsConfig.schema + "." + itsConfig.tokenTable + ";";
res = transaction->execute(query);
std::map<std::string, Service> newServices;
std::map<std::string, std::set<Token>> newTokens;
// Construct token objects
for (auto row : res)
{
std::string value;
std::string service;
std::string token;
// Indexing like so should be safe, database columns are 'not null'
row[0].to(service);
row[1].to(token);
row[2].to(value);
std::set<Token> tokens;
auto it = newTokens.insert(std::make_pair(service, tokens)).first;
Token thisToken(token);
auto tokenIt = it->second.insert(thisToken).first;
tokenIt->addValue(value);
}
// Construct Service objects
query =
"SELECT apikey,service,token from " + itsConfig.schema + "." + itsConfig.authTable + ";";
res = transaction->execute(query);
for (auto row : res)
{
std::string apikey;
std::string service;
std::string token;
// Indexing like so should be safe, database columns are 'not null'
row[0].to(apikey);
row[1].to(service);
row[2].to(token);
// Check errors here!
Service newService(service);
auto it = newServices.insert(std::make_pair(service, newService)).first;
// Check if token name is the wildcard definition
if (token == WILDCARD_IDENTIFIER)
{
it->second.addWildCard(apikey);
continue;
}
// Get defined tokens
auto tokenSetIt = newTokens.find(service);
if (tokenSetIt != newTokens.end())
{
auto tokenIt = tokenSetIt->second.find(
Token(token)); // Find the token object for this particular token name
if (tokenIt == tokenSetIt->second.end())
continue; // This is misconfiguration in the
// database
it->second.addToken(apikey, *tokenIt); // This could be a pointer type to save
// space
}
}
SmartMet::Spine::WriteLock lock(itsMutex);
std::swap(newServices, itsServices);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
Engine::~Engine() = default;
} // namespace Authentication
} // namespace Engine
} // namespace SmartMet
// DYNAMIC MODULE CREATION TOOLS
extern "C" void* engine_class_creator(const char* configfile, void* /* user_data */)
{
return new SmartMet::Engine::Authentication::Engine(configfile);
}
extern "C" const char* engine_name()
{
return "Authentication";
}
| 25.540773 | 98 | 0.621408 | fmidev |
410d513db2675d7401c3c061163a74764a2c3d46 | 3,338 | hxx | C++ | main/autodoc/source/parser_i/inc/s2_luidl/pe_singl.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/autodoc/source/parser_i/inc/s2_luidl/pe_singl.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/autodoc/source/parser_i/inc/s2_luidl/pe_singl.hxx | 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.
*
*************************************************************/
#ifndef LUIDL_PE_SINGL_HXX
#define LUIDL_PE_SINGL_HXX
// USED SERVICES
// BASE CLASSES
#include <s2_luidl/parsenv2.hxx>
#include <s2_luidl/pestate.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace idl
{
class Singleton;
class SglIfcSingleton;
}
}
namespace csi
{
namespace uidl
{
class PE_Type;
class PE_Singleton : public UnoIDL_PE,
public ParseEnvState
{
public:
PE_Singleton();
virtual ~PE_Singleton();
virtual void EstablishContacts(
UnoIDL_PE * io_pParentPE,
ary::Repository & io_rRepository,
TokenProcessing_Result &
o_rResult );
virtual void ProcessToken(
const Token & i_rToken );
virtual void Process_MetaType(
const TokMetaType & i_rToken );
virtual void Process_Identifier(
const TokIdentifier &
i_rToken );
virtual void Process_Punctuation(
const TokPunctuation &
i_rToken );
virtual void Process_Default();
private:
enum E_State
{
e_none = 0,
need_name,
need_curlbr_open,
e_std,
in_service,
need_finish,
in_base_interface,
e_STATES_MAX
};
#if 0
enum E_TokenType /// @ATTENTION Do not change existing values (except of tt_MAX) !!! Else array-indices will break.
{
tt_metatype = 0,
tt_identifier = 1,
tt_punctuation = 2,
tt_startoftype = 3,
tt_MAX
};
typedef void (PE_Singleton::*F_TOK)(const char *);
void On_need_singleton_MetaType(const char * i_sText);
void On_need_name_Identifer(const char * i_sText);
void On_need_curlbr_open_Punctuation(const char * i_sText);
void On_std_GotoService(const char * i_sText);
void On_std_Punctuation(const char * i_sText);
void On_need_finish_Punctuation(const char * i_sText);
void CallHandler(
const char * i_sTokenText,
E_TokenType i_eTokenType );
#endif // 0
void On_Default();
virtual void InitData();
virtual void TransferData();
virtual void ReceiveData();
virtual UnoIDL_PE & MyPE();
// DATA
// static F_TOK aDispatcher[e_STATES_MAX][tt_MAX];
E_State eState;
String sData_Name;
bool bIsPreDeclaration;
ary::idl::Singleton *
pCurSingleton;
ary::idl::SglIfcSingleton *
pCurSiSingleton;
Dyn<PE_Type> pPE_Type;
ary::idl::Type_id nCurParsed_Type;
};
} // namespace uidl
} // namespace csi
#endif
| 22.707483 | 117 | 0.665668 | Grosskopf |
410e034b8e52b95e97da7ea5935646dccc9ad59b | 18,764 | cc | C++ | src/poly/dma_dataflow.cc | xqdan/akg | e28501611d73d3957a1f3c58eeb6b028f2f2765d | [
"Apache-2.0"
] | null | null | null | src/poly/dma_dataflow.cc | xqdan/akg | e28501611d73d3957a1f3c58eeb6b028f2f2765d | [
"Apache-2.0"
] | null | null | null | src/poly/dma_dataflow.cc | xqdan/akg | e28501611d73d3957a1f3c58eeb6b028f2f2765d | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* 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 "poly/dma_dataflow.h"
#include "poly/poly_util.h"
namespace akg {
namespace ir {
namespace poly {
isl::id GpuDstId(GpuMemType type, isl::id tensor_id) {
std::string pos_fix = (type == GpuMemType::SHARED ? "_shared" : "_local");
return isl::id(tensor_id.ctx(), tensor_id.get_name() + pos_fix);
}
bool BufferDefInfo::CompareScheduleMarkNode(const isl::schedule_node_mark &mark1,
const isl::schedule_node_mark &mark2) {
return (mark1.get_id().get_name() == mark2.get_id().get_name());
}
std::shared_ptr<TensorFootprintCluster> BufferDefInfo::GetFootPrintCluster(const isl::schedule_node &mark_node) {
for (const auto &key : footprint_cluster_map) {
if (key.first.isa<isl::schedule_node_mark>() && mark_node.isa<isl::schedule_node_mark>() &&
CompareScheduleMarkNode(key.first.as<isl::schedule_node_mark>(), mark_node.as<isl::schedule_node_mark>())) {
isl::union_map umap1 = LocalSchedule(key.first);
isl::union_map umap2 = LocalSchedule(mark_node);
if (umap1.is_equal(umap2)) return key.second;
}
}
/************************
* This is for conv op im2col foorprint cluster
* The computation of this foorprint cluster is at realize_L1 mark node
* and add extension is at realize_L0 mark node
*************************/
if (footprint_cluster_map.size() == 1 && mark_node.isa<isl::schedule_node_mark>() &&
mark_node.as<isl::schedule_node_mark>().get_id().get_name() != "realize_UB") {
return footprints_cluster;
}
return nullptr;
}
std::shared_ptr<TensorFootprintCluster> BufferDefInfo::GetFootPrintClusterGPU(const isl::schedule_node &node) {
for (const auto &key : footprint_cluster_map) {
if (key.first.isa<isl::schedule_node_band>() && node.isa<isl::schedule_node_band>()) {
isl::union_map umap1 = LocalSchedule(key.first);
isl::union_map umap2 = LocalSchedule(node);
if (umap1.is_equal(umap2)) return key.second;
}
}
return nullptr;
}
std::vector<size_t> BufferDefInfo::TensorSize(const isl::schedule_node &mark_node) {
std::vector<size_t> res;
/********************************************
* some time the markNode is not the supported mark node in schedule tree
* batch_matmul case 2
********************************************/
if (sizes_map_.size() == 1) {
return sizes;
}
for (const auto &key : sizes_map_) {
if (key.first.isa<isl::schedule_node_mark>() && mark_node.isa<isl::schedule_node_mark>() &&
CompareScheduleMarkNode(key.first.as<isl::schedule_node_mark>(), mark_node.as<isl::schedule_node_mark>())) {
isl::union_map map1 = LocalSchedule(key.first);
isl::union_map map2 = LocalSchedule(mark_node);
if (map1.is_equal(map2)) return key.second;
}
}
return res;
}
isl::id BufferDefInfo::GetIndexDstId(const isl::ctx &ctx, const isl::id &id, const int index) {
CHECK_GE(index, 0);
if (index == 0) return id;
std::string id_name = id.get_name();
size_t pos = id_name.find("_local_");
std::string new_id_name = id_name;
if (pos != std::string::npos) {
std::stringstream ss;
ss << id_name.substr(0, pos) << "_promotion_" << index << id_name.substr(pos, id_name.size() - pos);
new_id_name = ss.str();
}
return isl::id(ctx, new_id_name);
}
std::vector<std::pair<isl::id, MemType>> BufferDefInfo::MakeDataStream(const isl::id new_dst_id) {
std::vector<std::pair<isl::id, MemType>> dataStream;
for (const auto &item : data_stream) {
if (item.first.get_name() == dst_tensor_id.get_name()) {
dataStream.emplace_back(std::make_pair(new_dst_id, item.second));
} else {
dataStream.push_back(item);
}
}
return dataStream;
}
std::vector<std::pair<isl::id, MemType>> BufferDefInfo::PartialDataStream(size_t start_idx) {
std::vector<std::pair<isl::id, MemType>> stream;
if (start_idx >= data_stream.size()) return stream;
for (size_t idx = start_idx; idx < data_stream.size(); ++idx) {
stream.push_back(data_stream[idx]);
}
return stream;
}
void BufferDefInfo::AddSize(const isl::schedule_node &node, const std::vector<size_t> &sizes) {
sizes_map_.emplace_back(std::make_pair(node, sizes));
}
isl::id BufferDefInfo::NextTensorDstId() {
isl::id result_id = dst_tensor_id;
if (data_stream.size() > static_cast<size_t>(DataStreamIndex::DS_SECOND)) {
result_id = data_stream[static_cast<size_t>(DataStreamIndex::DS_SECOND)].first;
}
return result_id;
}
bool BufferDefInfo::IsCubeCL1Write() {
const int l1WriteDFLen = static_cast<int>(DataStreamIndex::DS_THIRD);
if (data_stream.size() == l1WriteDFLen) {
if (data_stream[static_cast<size_t>(DataStreamIndex::DS_ZERO)].second == MemType::DDR &&
data_stream[static_cast<size_t>(DataStreamIndex::DS_FIRST)].second == MemType::UB_ &&
data_stream[static_cast<size_t>(DataStreamIndex::DS_SECOND)].second == MemType::L0C_)
return true;
}
return false;
}
bool BufferDefInfo::IsPreCubeL1Write() {
const int preCubeL1WriteDFLen = static_cast<int>(DataStreamIndex::DS_THIRD);
if (data_stream.size() == preCubeL1WriteDFLen) {
if (data_stream[static_cast<size_t>(DataStreamIndex::DS_ZERO)].second == MemType::DDR &&
data_stream[static_cast<size_t>(DataStreamIndex::DS_FIRST)].second == MemType::L1_ &&
data_stream[static_cast<size_t>(DataStreamIndex::DS_SECOND)].second == MemType::UBL1_)
return true;
}
return false;
}
bool BufferDefInfo::IsPreCubeTile2Write() {
const int preCubeTile2WriteDFLen = static_cast<int>(DataStreamIndex::DS_SECOND);
if (data_stream.size() == preCubeTile2WriteDFLen) {
if (data_stream[static_cast<size_t>(DataStreamIndex::DS_ZERO)].second == MemType::L1_ &&
data_stream[static_cast<size_t>(DataStreamIndex::DS_FIRST)].second == MemType::UBL1_)
return true;
}
return false;
}
bool BufferDefInfo::IsGemmDataL12L0() { return (SrcMemType() == MemType::L1_ && DstMemType() == MemType::L0A_); }
bool BufferDefInfo::IsGemmWeightL12L0() { return (SrcMemType() == MemType::L1_ && DstMemType() == MemType::L0B_); }
bool BufferDefInfo::IsIm2col() { return (SrcMemType() == MemType::L1_ && DstMemType() == MemType::L1_); }
MemType BufferDefInfo::SrcMemType() {
// tensor dataflow at least one data
CHECK_GE(data_stream.size(), 1);
return data_stream[0].second;
}
MemType BufferDefInfo::DstMemType() {
// tensor dataflow at least one data
CHECK_GE(data_stream.size(), 1);
if (data_stream.size() >= 2) return data_stream[1].second;
// the last tensor in dataflow, memType is DDR
return MemType::DDR;
}
void TensorDataFlow::Initial(const std::string &name, const DataFlowAttrs &attrs) {
mem_type_flow_.clear();
name_flow_.clear();
for (const auto &one_pair : attrs) {
mem_type_flow_.push_back(one_pair.first);
name_flow_.push_back(name + one_pair.second);
}
}
void StmtDataFlowInfo::AddReadTensor(const std::string &name, TENSOR_DATAFLOW_TYPE type) {
if (name == "") return;
if (reads_.find(name) == reads_.end()) {
TensorDataFlow dataflow;
CreateTensorDataFlow(type, name, dataflow);
reads_[name] = dataflow;
}
}
void StmtDataFlowInfo::AddWriteTensor(const std::string &name, TENSOR_DATAFLOW_TYPE type) {
if (name == "") return;
if (writes_.find(name) == writes_.end()) {
TensorDataFlow dataflow;
CreateTensorDataFlow(type, name, dataflow);
writes_[name] = dataflow;
}
}
void StmtDataFlowInfo::CreateTensorDataFlow(TENSOR_DATAFLOW_TYPE type, const std::string &name,
TensorDataFlow &dataflow) {
CHECK_NE(name, "");
switch (type) {
case TENSOR_DATAFLOW_TYPE::CUBE_CONV_A:
CubeConvA(name, dataflow);
break;
case TENSOR_DATAFLOW_TYPE::CUBE_CONV_B:
CubeConvB(name, dataflow);
break;
case TENSOR_DATAFLOW_TYPE::CUBE_CONV_C:
CubeConvC(name, dataflow);
break;
case TENSOR_DATAFLOW_TYPE::CUBE_GEMM_A:
CubeGEMMA(name, dataflow);
break;
case TENSOR_DATAFLOW_TYPE::CUBE_GEMM_B:
CubeGEMMB(name, dataflow);
break;
case TENSOR_DATAFLOW_TYPE::CUBE_GEMM_C:
CubeGEMMC(name, dataflow);
break;
case TENSOR_DATAFLOW_TYPE::VECTOR_UB:
VectorUB(name, dataflow);
break;
case TENSOR_DATAFLOW_TYPE::IM2COL_L1:
Im2colL1(name, dataflow);
break;
default:
CHECK(false) << "CreateTensorDataFlow type error!!! ";
}
}
void StmtDataFlowInfo::CubeConvA(const std::string &name, TensorDataFlow &dataflow) {
dataflow.Initial(name, Cube_Conv_A);
}
void StmtDataFlowInfo::CubeConvB(const std::string &name, TensorDataFlow &dataflow) {
dataflow.Initial(name, Cube_Conv_B);
}
void StmtDataFlowInfo::CubeConvC(const std::string &name, TensorDataFlow &dataflow) {
dataflow.Initial(name, Cube_Conv_C);
}
void StmtDataFlowInfo::CubeGEMMA(const std::string &name, TensorDataFlow &dataflow) {
std::size_t start1 = name.find("_fractal_L1");
if (start1 != std::string::npos) {
// spec gemm A
std::string head = name.substr(0, start1);
dataflow.Initial(head, Cube_Spec_Gemm_A);
return;
}
std::size_t start2 = name.find("_local_L1");
if (start2 != std::string::npos) {
// spec gemm A
std::string head = name.substr(0, start2);
dataflow.Initial(head, Cube_Spec_Gemm_A_);
return;
}
dataflow.Initial(name, Cube_Gemm_A);
return;
}
void StmtDataFlowInfo::CubeGEMMB(const std::string &name, TensorDataFlow &dataflow) {
std::size_t start1 = name.find("_local_L1");
if (start1 != std::string::npos) {
// spec gemm B
dataflow.Initial(name, Cube_Spec_Gemm_B);
return;
}
std::size_t start2 = name.find("_fractal_L1");
if (start2 != std::string::npos) {
// spec gemm B
dataflow.Initial(name, Cube_Spec_Gemm_B_);
return;
}
dataflow.Initial(name, Cube_Gemm_B);
return;
}
void StmtDataFlowInfo::CubeGEMMC(const std::string &name, TensorDataFlow &dataflow) {
std::size_t start = name.find("_local_UB");
if (start != std::string::npos) {
// spec gemm C
// this is only for conv fusion condition,
dataflow.Initial(name, Cube_Spec_Gemm_C);
} else {
dataflow.Initial(name, Cube_Gemm_C);
}
}
void StmtDataFlowInfo::VectorUB(const std::string &name, TensorDataFlow &dataflow) {
dataflow.Initial(name, Vector_UB);
}
void StmtDataFlowInfo::Im2colL1(const std::string &name, TensorDataFlow &dataflow) {
dataflow.Initial(name, Im2Col_L1);
}
void StmtDataFlowInfo::UpdateTensorMemType(MemType update_type) {
for (auto read = reads_.begin(); read != reads_.end(); ++read) {
for (uint64_t index = 0; index < read->second.mem_type_flow_.size(); ++index) {
if (read->second.mem_type_flow_[index] == MemType::UB_) {
read->second.mem_type_flow_[index] = update_type;
}
}
}
for (auto write = writes_.begin(); write != writes_.end(); ++write) {
for (uint64_t index = 0; index < write->second.mem_type_flow_.size(); ++index) {
if (write->second.mem_type_flow_[index] == MemType::UB_) {
write->second.mem_type_flow_[index] = update_type;
}
}
}
}
bool StmtDataFlowInfo::SameNameFlow(const std::vector<std::string> &left, const std::vector<std::string> &right) {
if (left.size() != right.size()) {
return false;
}
for (uint64_t index = 0; index < left.size(); ++index) {
if (left[index] != right[index]) return false;
}
return true;
}
bool StmtDataFlowInfo::SameMemFlow(const MemFlow &left, const MemFlow &right) const {
if (left.size() != right.size()) {
return false;
}
for (uint64_t index = 0; index < left.size(); ++index) {
if (left[index] != right[index]) return false;
}
return true;
}
template <typename T>
std::vector<T> StmtDataFlowInfo::MergedFlow(const std::vector<T> &left, const std::vector<T> &right) {
std::vector<T> result;
uint64_t left_idx = 0; // left array index
uint64_t rightIdx = 0; // right array index
while (left_idx < left.size() || rightIdx < right.size()) {
if (left_idx < left.size() && rightIdx < right.size() && left[left_idx] == right[rightIdx]) {
result.push_back(left[left_idx]);
left_idx++;
rightIdx++;
} else {
if (left_idx < left.size()) {
result.push_back(left[left_idx]);
left_idx++;
} else if (rightIdx < right.size()) {
result.push_back(right[rightIdx]);
rightIdx++;
}
}
}
return result;
}
void StmtDataFlowInfo::UpdateFlowInfo(std::map<std::string, std::vector<std::string>> &nameflow,
std::map<std::string, MemFlow> &memflow) {
for (const auto &read : reads_) {
if (nameflow.find(read.first) == nameflow.end()) {
nameflow[read.first] = read.second.name_flow_;
} else {
if (!SameNameFlow(nameflow[read.first], read.second.name_flow_)) {
// merge two name flow
nameflow[read.first] = MergedFlow(nameflow[read.first], read.second.name_flow_);
}
}
if (memflow.find(read.first) == memflow.end()) {
memflow[read.first] = read.second.mem_type_flow_;
} else {
if (!SameMemFlow(memflow[read.first], read.second.mem_type_flow_)) {
// merge two mem flow
memflow[read.first] = MergedFlow(memflow[read.first], read.second.mem_type_flow_);
}
}
CHECK_EQ(nameflow[read.first].size(), memflow[read.first].size());
}
CHECK_EQ(nameflow.size(), memflow.size());
for (const auto &write : writes_) {
if (nameflow.find(write.first) == nameflow.end()) {
nameflow[write.first] = write.second.name_flow_;
} else {
if (!SameNameFlow(nameflow[write.first], write.second.name_flow_)) {
// merge two name flow
nameflow[write.first] = MergedFlow(nameflow[write.first], write.second.name_flow_);
}
}
if (memflow.find(write.first) == memflow.end()) {
memflow[write.first] = write.second.mem_type_flow_;
} else {
if (!SameMemFlow(memflow[write.first], write.second.mem_type_flow_)) {
// merge two mem flow
memflow[write.first] = MergedFlow(memflow[write.first], write.second.mem_type_flow_);
}
}
CHECK_EQ(nameflow[write.first].size(), memflow[write.first].size());
}
CHECK_EQ(nameflow.size(), memflow.size());
}
void DMADataFlow::CreateStmtDataFlow(STMT_OP_TYPE op_type, const isl::id &stmt_id, const StmtOpInfo &stmt_op,
StmtIdHashMap &read_map, StmtIdHashMap &write_map) {
/**********************************
* stmt is classify three type
* 1.1 cube: conv
* 1.2 cube: gemm
* 2. vector
*********************************/
std::string state = stmt_id.get_name();
if (op_data_flow_.find(state) == op_data_flow_.end()) {
StmtDataFlowInfo stmtDataflow(stmt_id, stmt_op.isCube);
op_data_flow_[state] = stmtDataflow;
}
if (op_type == STMT_OP_TYPE::CUBE_CONV) {
// create memflow for A,B,C
op_data_flow_[state].AddReadTensor(stmt_op.A_, TENSOR_DATAFLOW_TYPE::CUBE_CONV_A);
op_data_flow_[state].AddReadTensor(stmt_op.B_, TENSOR_DATAFLOW_TYPE::CUBE_CONV_B);
op_data_flow_[state].AddWriteTensor(stmt_op.C_, TENSOR_DATAFLOW_TYPE::CUBE_CONV_C);
}
if (op_type == STMT_OP_TYPE::CUBE_GEMM) {
// create memflow for A,B,C
op_data_flow_[state].AddReadTensor(stmt_op.A_, TENSOR_DATAFLOW_TYPE::CUBE_GEMM_A);
op_data_flow_[state].AddReadTensor(stmt_op.B_, TENSOR_DATAFLOW_TYPE::CUBE_GEMM_B);
op_data_flow_[state].AddWriteTensor(stmt_op.C_, TENSOR_DATAFLOW_TYPE::CUBE_GEMM_C);
}
if (op_type == STMT_OP_TYPE::IM2COL_UB) {
// create memflow for A, B
if (read_map.find(stmt_id) != read_map.end()) {
for (const auto &id : read_map[stmt_id]) {
if (id.get_name() != "") {
op_data_flow_[state].AddReadTensor(id.get_name(), TENSOR_DATAFLOW_TYPE::IM2COL_L1);
}
}
}
// UB vector write tensors
if (write_map.find(stmt_id) != write_map.end()) {
for (const auto &id : write_map[stmt_id]) {
if (id.get_name() != "") {
op_data_flow_[state].AddWriteTensor(id.get_name(), TENSOR_DATAFLOW_TYPE::VECTOR_UB);
}
}
}
}
if (op_type == STMT_OP_TYPE::VECTOR) {
// UB vector read tensors
if (read_map.find(stmt_id) != read_map.end()) {
for (const auto &id : read_map[stmt_id]) {
if (id.get_name() != "") {
op_data_flow_[state].AddReadTensor(id.get_name(), TENSOR_DATAFLOW_TYPE::VECTOR_UB);
}
}
}
// UB vector write tensors
if (write_map.find(stmt_id) != write_map.end()) {
for (const auto &id : write_map[stmt_id]) {
if (id.get_name() != "") {
op_data_flow_[state].AddWriteTensor(id.get_name(), TENSOR_DATAFLOW_TYPE::VECTOR_UB);
}
}
}
}
}
void DMADataFlow::FusionAnalysis() {
bool has_cube = false;
bool cube_pre_fusion = has_cube;
bool cube_post_fusion = has_cube;
int state_num = 0;
// analysis has cube pre fusion and post fusion
for (const auto &state : op_data_flow_) {
if (has_cube && state_num > 0) cube_post_fusion = true;
if (state.second.is_cube_) {
has_cube = true;
if (state_num > 0) cube_pre_fusion = true;
}
state_num++;
}
if (!cube_pre_fusion && !cube_post_fusion) return;
bool start_pre_fusion = has_cube;
bool start_post_fusion = false;
for (auto state = op_data_flow_.begin(); state != op_data_flow_.end(); ++state) {
if (state->second.is_cube_) {
start_pre_fusion = false;
start_post_fusion = true;
}
if (cube_pre_fusion && start_pre_fusion) {
// To Do UB -> UBL1
state->second.UpdateTensorMemType(MemType::UBL1_);
}
if (cube_post_fusion && start_post_fusion) {
// update all memtype UB -> UBL0
state->second.UpdateTensorMemType(MemType::UBL0_);
}
}
}
void DMADataFlow::OpDataflowInfo(std::map<std::string, std::vector<std::string>> &nameflow,
std::map<std::string, MemFlow> &memflow) {
for (auto state : op_data_flow_) {
state.second.UpdateFlowInfo(nameflow, memflow);
}
CHECK_EQ(nameflow.size(), memflow.size());
}
} // namespace poly
} // namespace ir
} // namespace akg
| 34.556169 | 116 | 0.664517 | xqdan |
410f55abc58323c02fe5b24027567389f4811fb5 | 4,696 | hpp | C++ | Pods/Headers/Private/Realm/realm/impl/destroy_guard.hpp | Valpertui/mealtingpot-ios | 73368d4ec16fef55f3b8f30e45038955db6385df | [
"MIT"
] | 145 | 2015-07-22T06:04:49.000Z | 2021-12-08T13:37:04.000Z | Pods/Headers/Private/Realm/realm/impl/destroy_guard.hpp | Valpertui/mealtingpot-ios | 73368d4ec16fef55f3b8f30e45038955db6385df | [
"MIT"
] | 23 | 2016-01-14T06:52:56.000Z | 2017-02-13T22:11:42.000Z | Pods/Headers/Private/Realm/realm/impl/destroy_guard.hpp | Valpertui/mealtingpot-ios | 73368d4ec16fef55f3b8f30e45038955db6385df | [
"MIT"
] | 42 | 2015-07-24T02:59:31.000Z | 2019-07-23T08:51:59.000Z | /*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_IMPL_DESTROY_GUARD_HPP
#define REALM_IMPL_DESTROY_GUARD_HPP
#include <realm/util/features.h>
#include <realm/array.hpp>
namespace realm {
namespace _impl {
/// Calls `ptr->destroy()` if the guarded pointer (`ptr`) is not null
/// when the guard is destroyed. For arrays (`T` = `Array`) this means
/// that the array is destroyed in a shallow fashion. See
/// `DeepArrayDestroyGuard` for an alternative.
template<class T>
class DestroyGuard {
public:
DestroyGuard() noexcept;
DestroyGuard(T*) noexcept;
~DestroyGuard() noexcept;
void reset(T*) noexcept;
T* get() const noexcept;
T* release() noexcept;
private:
T* m_ptr;
};
using ShallowArrayDestroyGuard = DestroyGuard<Array>;
/// Calls `ptr->destroy_deep()` if the guarded Array pointer (`ptr`)
/// is not null when the guard is destroyed.
class DeepArrayDestroyGuard {
public:
DeepArrayDestroyGuard() noexcept;
DeepArrayDestroyGuard(Array*) noexcept;
~DeepArrayDestroyGuard() noexcept;
void reset(Array*) noexcept;
Array* get() const noexcept;
Array* release() noexcept;
private:
Array* m_ptr;
};
/// Calls `Array::destroy_deep(ref, alloc)` if the guarded 'ref'
/// (`ref`) is not zero when the guard is destroyed.
class DeepArrayRefDestroyGuard {
public:
DeepArrayRefDestroyGuard(Allocator&) noexcept;
DeepArrayRefDestroyGuard(ref_type, Allocator&) noexcept;
~DeepArrayRefDestroyGuard() noexcept;
void reset(ref_type) noexcept;
ref_type get() const noexcept;
ref_type release() noexcept;
private:
ref_type m_ref;
Allocator& m_alloc;
};
// Implementation:
// DestroyGuard<T>
template<class T>
inline DestroyGuard<T>::DestroyGuard() noexcept:
m_ptr(nullptr)
{
}
template<class T>
inline DestroyGuard<T>::DestroyGuard(T* ptr) noexcept:
m_ptr(ptr)
{
}
template<class T>
inline DestroyGuard<T>::~DestroyGuard() noexcept
{
if (m_ptr)
m_ptr->destroy();
}
template<class T>
inline void DestroyGuard<T>::reset(T* ptr) noexcept
{
if (m_ptr)
m_ptr->destroy();
m_ptr = ptr;
}
template<class T>
inline T* DestroyGuard<T>::get() const noexcept
{
return m_ptr;
}
template<class T>
inline T* DestroyGuard<T>::release() noexcept
{
T* ptr = m_ptr;
m_ptr = nullptr;
return ptr;
}
// DeepArrayDestroyGuard
inline DeepArrayDestroyGuard::DeepArrayDestroyGuard() noexcept:
m_ptr(nullptr)
{
}
inline DeepArrayDestroyGuard::DeepArrayDestroyGuard(Array* ptr) noexcept:
m_ptr(ptr)
{
}
inline DeepArrayDestroyGuard::~DeepArrayDestroyGuard() noexcept
{
if (m_ptr)
m_ptr->destroy_deep();
}
inline void DeepArrayDestroyGuard::reset(Array* ptr) noexcept
{
if (m_ptr)
m_ptr->destroy_deep();
m_ptr = ptr;
}
inline Array* DeepArrayDestroyGuard::get() const noexcept
{
return m_ptr;
}
inline Array* DeepArrayDestroyGuard::release() noexcept
{
Array* ptr = m_ptr;
m_ptr = nullptr;
return ptr;
}
// DeepArrayRefDestroyGuard
inline DeepArrayRefDestroyGuard::DeepArrayRefDestroyGuard(Allocator& alloc) noexcept:
m_ref(0),
m_alloc(alloc)
{
}
inline DeepArrayRefDestroyGuard::DeepArrayRefDestroyGuard(ref_type ref,
Allocator& alloc) noexcept:
m_ref(ref),
m_alloc(alloc)
{
}
inline DeepArrayRefDestroyGuard::~DeepArrayRefDestroyGuard() noexcept
{
if (m_ref)
Array::destroy_deep(m_ref, m_alloc);
}
inline void DeepArrayRefDestroyGuard::reset(ref_type ref) noexcept
{
if (m_ref)
Array::destroy_deep(m_ref, m_alloc);
m_ref = ref;
}
inline ref_type DeepArrayRefDestroyGuard::get() const noexcept
{
return m_ref;
}
inline ref_type DeepArrayRefDestroyGuard::release() noexcept
{
ref_type ref = m_ref;
m_ref = 0;
return ref;
}
} // namespace _impl
} // namespace realm
#endif // REALM_IMPL_DESTROY_GUARD_HPP
| 20.241379 | 85 | 0.67994 | Valpertui |
41107173169bb4c4685641b48e2c574656d298c0 | 3,668 | hpp | C++ | sprout/math/hypot.hpp | kevcadieux/Sprout | 6b5addba9face0a6403e66e7db2aa94d87387f61 | [
"BSL-1.0"
] | 691 | 2015-01-15T18:52:23.000Z | 2022-03-15T23:39:39.000Z | sprout/math/hypot.hpp | kevcadieux/Sprout | 6b5addba9face0a6403e66e7db2aa94d87387f61 | [
"BSL-1.0"
] | 22 | 2015-03-11T01:22:56.000Z | 2021-03-29T01:51:45.000Z | sprout/math/hypot.hpp | kevcadieux/Sprout | 6b5addba9face0a6403e66e7db2aa94d87387f61 | [
"BSL-1.0"
] | 57 | 2015-03-11T07:52:29.000Z | 2021-12-16T09:15:33.000Z | /*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_MATH_HYPOT_HPP
#define SPROUT_MATH_HYPOT_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/limits.hpp>
#include <sprout/math/detail/config.hpp>
#include <sprout/math/detail/float_compute.hpp>
#include <sprout/math/isnan.hpp>
#include <sprout/math/signbit.hpp>
#include <sprout/math/fabs.hpp>
#include <sprout/math/sqrt.hpp>
#include <sprout/type_traits/float_promote.hpp>
#include <sprout/type_traits/enabler_if.hpp>
namespace sprout {
namespace math {
namespace detail {
#if SPROUT_USE_BUILTIN_CMATH_FUNCTION
inline SPROUT_CONSTEXPR float
builtin_hypot(float x, float y) {
return __builtin_hypotf(x, y);
}
inline SPROUT_CONSTEXPR double
builtin_hypot(double x, double y) {
return __builtin_hypot(x, y);
}
inline SPROUT_CONSTEXPR long double
builtin_hypot(long double x, long double y) {
return __builtin_hypotl(x, y);
}
#endif
template<typename T>
inline SPROUT_CONSTEXPR T
hypot_impl_2(T t, T w) {
return t * sprout::math::sqrt(T(1) + w * w);
}
template<typename T>
inline SPROUT_CONSTEXPR T
hypot_impl_1(T x, T y) {
return x < y
? sprout::math::detail::hypot_impl_2(y, x / y)
: sprout::math::detail::hypot_impl_2(x, y / x)
;
}
template<typename T>
inline SPROUT_CONSTEXPR T
hypot_impl(T x, T y) {
return sprout::math::detail::hypot_impl_1(sprout::math::fabs(x), sprout::math::fabs(y));
}
} // namespace detail
//
// hypot
//
template<
typename FloatType,
typename sprout::enabler_if<std::is_floating_point<FloatType>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR FloatType
hypot(FloatType x, FloatType y) {
return y == sprout::numeric_limits<FloatType>::infinity() || y == -sprout::numeric_limits<FloatType>::infinity()
? sprout::numeric_limits<FloatType>::infinity()
: x == sprout::numeric_limits<FloatType>::infinity() || x == -sprout::numeric_limits<FloatType>::infinity()
? sprout::numeric_limits<FloatType>::infinity()
: sprout::math::isnan(y) ? y
: sprout::math::isnan(x) ? x
#if SPROUT_USE_BUILTIN_CMATH_FUNCTION
: sprout::math::detail::builtin_hypot(x, y)
#else
: y == 0 ? sprout::math::fabs(x)
: x == 0 ? sprout::math::fabs(y)
: static_cast<FloatType>(sprout::math::detail::hypot_impl(
static_cast<typename sprout::math::detail::float_compute<FloatType>::type>(x),
static_cast<typename sprout::math::detail::float_compute<FloatType>::type>(y)
))
#endif
;
}
template<
typename ArithmeticType1,
typename ArithmeticType2,
typename sprout::enabler_if<
std::is_arithmetic<ArithmeticType1>::value && std::is_arithmetic<ArithmeticType2>::value
>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR typename sprout::float_promote<ArithmeticType1, ArithmeticType2>::type
hypot(ArithmeticType1 x, ArithmeticType2 y) {
typedef typename sprout::float_promote<ArithmeticType1, ArithmeticType2>::type type;
return sprout::math::hypot(static_cast<type>(x), static_cast<type>(y));
}
} // namespace math
using sprout::math::hypot;
} // namespace sprout
#endif // #ifndef SPROUT_MATH_HYPOT_HPP
| 34.603774 | 116 | 0.658124 | kevcadieux |
4111dd3dc5cdb199aedbd4e64a8eb14472cf0fd0 | 352 | cpp | C++ | QtCases/main.cpp | TsyQi/MyAutomatic | 2afd3dcabba818051c7119fac7e6c099ff7954a7 | [
"Apache-2.0"
] | 4 | 2016-08-19T08:16:49.000Z | 2020-04-15T12:30:25.000Z | QtCases/main.cpp | TsyQi/Auto-control | d0dda0752d53d28f358346ee7ab217bf05118c96 | [
"Apache-2.0"
] | null | null | null | QtCases/main.cpp | TsyQi/Auto-control | d0dda0752d53d28f358346ee7ab217bf05118c96 | [
"Apache-2.0"
] | 3 | 2019-03-23T03:40:24.000Z | 2020-04-15T00:57:43.000Z | #include <QtPlugin>
#include <QtWidgets/qmessagebox.h>
#include "OpenGLWindow.h"
// Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
#ifdef _WIN32
extern "C" __declspec(dllexport)
#endif
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
OpenGLWindow w("flappy TRIANGLE");
a.setActiveWindow(&w);
w.show();
return a.exec();
}
| 20.705882 | 45 | 0.704545 | TsyQi |
4113ad6ad1fb5a9660bf88d48bf1f480d0d14dd6 | 8,658 | cc | C++ | flare/rpc/trackme.cc | flare-rpc/flare-cpp | c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950 | [
"Apache-2.0"
] | 3 | 2022-01-23T17:55:24.000Z | 2022-03-23T12:55:18.000Z | flare/rpc/trackme.cc | flare-rpc/flare-cpp | c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950 | [
"Apache-2.0"
] | null | null | null | flare/rpc/trackme.cc | flare-rpc/flare-cpp | c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950 | [
"Apache-2.0"
] | null | null | null | // 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.
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include "flare/base/fast_rand.h"
#include "flare/rpc/log.h"
#include "flare/rpc/channel.h"
#include "flare/rpc/trackme.pb.h"
#include "flare/rpc/policy/hasher.h"
#include "flare/base/scoped_file.h"
namespace flare::rpc {
DEFINE_string(trackme_server, "", "Where the TrackMe requests are sent to");
static const int32_t TRACKME_MIN_INTERVAL = 30;
static const int32_t TRACKME_MAX_INTERVAL = 600;
static int32_t s_trackme_interval = TRACKME_MIN_INTERVAL;
// Protecting global vars on trackme
static pthread_mutex_t s_trackme_mutex = PTHREAD_MUTEX_INITIALIZER;
// For contacting with trackme_server.
static Channel* s_trackme_chan = NULL;
// Any server address in this process.
static std::string* s_trackme_addr = NULL;
// Information of bugs.
// Notice that this structure may be a combination of all affected bugs.
// Namely `severity' is severity of the worst bug and `error_text' is
// combination of descriptions of all bugs. Check tools/trackme_server
// for impl. details.
struct BugInfo {
TrackMeSeverity severity;
std::string error_text;
bool operator==(const BugInfo& bug) const {
return severity == bug.severity && error_text == bug.error_text;
}
};
// If a bug was shown, its info was stored in this var as well so that we
// can avoid showing the same bug repeatly.
static BugInfo* g_bug_info = NULL;
// The timestamp(microseconds) that we sent TrackMeRequest.
static int64_t s_trackme_last_time = 0;
// version of RPC.
// Since the code for getting FLARE_RPC_REVISION often fails,
// FLARE_RPC_REVISION must be defined to string and be converted to number
// within our code.
// The code running before main() may see g_rpc_version=0, should be OK.
#if defined(FLARE_RPC_REVISION)
const int64_t g_rpc_version = atoll(FLARE_RPC_REVISION);
#else
const int64_t g_rpc_version = 0;
#endif
int ReadJPaasHostPort(int container_port) {
const uid_t uid = getuid();
struct passwd* pw = getpwuid(uid);
if (pw == NULL) {
RPC_VLOG << "Fail to get password file entry of uid=" << uid;
return -1;
}
char JPAAS_LOG_PATH[64];
snprintf(JPAAS_LOG_PATH, sizeof(JPAAS_LOG_PATH),
"%s/jpaas_run/logs/env.log", pw->pw_dir);
char* line = NULL;
size_t line_len = 0;
ssize_t nr = 0;
flare::base::scoped_file fp(fopen(JPAAS_LOG_PATH, "r"));
if (!fp) {
RPC_VLOG << "Fail to open `" << JPAAS_LOG_PATH << '\'';
return -1;
}
int host_port = -1;
char prefix[32];
const int prefix_len =
snprintf(prefix, sizeof(prefix), "JPAAS_HOST_PORT_%d=", container_port);
while ((nr = getline(&line, &line_len, fp.get())) != -1) {
if (line[nr - 1] == '\n') { // remove ending newline
--nr;
}
if (nr > prefix_len && memcmp(line, prefix, prefix_len) == 0) {
host_port = strtol(line + prefix_len, NULL, 10);
break;
}
}
free(line);
RPC_VLOG_IF(host_port < 0) << "No entry starting with `" << prefix << "' found";
return host_port;
}
// Called in server.cpp
void SetTrackMeAddress(flare::base::end_point pt) {
FLARE_SCOPED_LOCK(s_trackme_mutex);
if (s_trackme_addr == NULL) {
// JPAAS has NAT capabilities, read its log to figure out the open port
// accessible from outside.
const int jpaas_port = ReadJPaasHostPort(pt.port);
if (jpaas_port > 0) {
RPC_VLOG << "Use jpaas_host_port=" << jpaas_port
<< " instead of jpaas_container_port=" << pt.port;
pt.port = jpaas_port;
}
s_trackme_addr = new std::string(flare::base::endpoint2str(pt).c_str());
}
}
static void HandleTrackMeResponse(Controller* cntl, TrackMeResponse* res) {
if (cntl->Failed()) {
RPC_VLOG << "Fail to access " << FLAGS_trackme_server << ", " << cntl->ErrorText();
} else {
BugInfo cur_info;
cur_info.severity = res->severity();
cur_info.error_text = res->error_text();
bool already_reported = false;
{
FLARE_SCOPED_LOCK(s_trackme_mutex);
if (g_bug_info != NULL && *g_bug_info == cur_info) {
// we've shown the bug.
already_reported = true;
} else {
// save the bug.
if (g_bug_info == NULL) {
g_bug_info = new BugInfo(cur_info);
} else {
*g_bug_info = cur_info;
}
}
}
if (!already_reported) {
switch (res->severity()) {
case TrackMeOK:
break;
case TrackMeFatal:
LOG(ERROR) << "Your flare (r" << g_rpc_version
<< ") is affected by: " << res->error_text();
break;
case TrackMeWarning:
LOG(WARNING) << "Your flare (r" << g_rpc_version
<< ") is affected by: " << res->error_text();
break;
default:
LOG(WARNING) << "Unknown severity=" << res->severity();
break;
}
}
if (res->has_new_interval()) {
// We can't fully trust the result from trackme_server which may
// have bugs. Make sure the reporting interval is not too short or
// too long
int32_t new_interval = res->new_interval();
new_interval = std::max(new_interval, TRACKME_MIN_INTERVAL);
new_interval = std::min(new_interval, TRACKME_MAX_INTERVAL);
if (new_interval != s_trackme_interval) {
s_trackme_interval = new_interval;
RPC_VLOG << "Update s_trackme_interval to " << new_interval;
}
}
}
delete cntl;
delete res;
}
static void TrackMeNow(std::unique_lock<pthread_mutex_t>& mu) {
if (s_trackme_addr == NULL) {
return;
}
if (s_trackme_chan == NULL) {
Channel* chan = new (std::nothrow) Channel;
if (chan == NULL) {
LOG(FATAL) << "Fail to new trackme channel";
return;
}
ChannelOptions opt;
// keep #connections on server-side low
opt.connection_type = CONNECTION_TYPE_SHORT;
if (chan->Init(FLAGS_trackme_server.c_str(), "c_murmurhash", &opt) != 0) {
LOG(WARNING) << "Fail to connect to " << FLAGS_trackme_server;
delete chan;
return;
}
s_trackme_chan = chan;
}
mu.unlock();
TrackMeService_Stub stub(s_trackme_chan);
TrackMeRequest req;
req.set_rpc_version(g_rpc_version);
req.set_server_addr(*s_trackme_addr);
TrackMeResponse* res = new TrackMeResponse;
Controller* cntl = new Controller;
cntl->set_request_code(policy::MurmurHash32(s_trackme_addr->data(), s_trackme_addr->size()));
google::protobuf::Closure* done =
::flare::rpc::NewCallback(&HandleTrackMeResponse, cntl, res);
stub.TrackMe(cntl, &req, res, done);
}
// Called in global.cpp
// [Thread-safe] supposed to be called in low frequency.
void TrackMe() {
if (FLAGS_trackme_server.empty()) {
return;
}
int64_t now = flare::get_current_time_micros();
std::unique_lock<pthread_mutex_t> mu(s_trackme_mutex);
if (s_trackme_last_time == 0) {
// Delay the first ping randomly within s_trackme_interval. This
// protects trackme_server from ping storms.
s_trackme_last_time =
now + flare::base::fast_rand_less_than(s_trackme_interval) * 1000000L;
}
if (now > s_trackme_last_time + 1000000L * s_trackme_interval) {
s_trackme_last_time = now;
return TrackMeNow(mu);
}
}
} // namespace flare::rpc
| 36.378151 | 97 | 0.628205 | flare-rpc |
4115247034dedccdc7036b536c0539ca74cd831f | 1,624 | cpp | C++ | Kattis/Promotions/solution.cpp | caando/Competitive-Programming-Archive | 589781a23bda39aedf5fc437bf9b97c264fd3736 | [
"MIT"
] | 5 | 2021-09-09T09:16:29.000Z | 2022-01-08T11:28:12.000Z | Kattis/Promotions/solution.cpp | zjk2606/Competitive-Programming-Archive | 589781a23bda39aedf5fc437bf9b97c264fd3736 | [
"MIT"
] | 1 | 2021-09-09T09:16:26.000Z | 2021-09-11T04:00:36.000Z | Kattis/Promotions/solution.cpp | zjk2606/Competitive-Programming-Archive | 589781a23bda39aedf5fc437bf9b97c264fd3736 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using vi = vector<int>;
using vii = vector<pii>;
#define fi first
#define se second
#define sz(c) ((int)(c).size())
#define all(c) (c).begin(), (c).end()
#define forn(i,m, n) for (int i = m, nnnn = (n); i < nnnn; ++i)
#define pb push_back
#define mp make_pair
vector<int> child[5000], parent[5000];
bool counter[5000];
void getChild(int curr){
if (counter[curr] == true) return;
counter[curr] = true;
forn(i, 0, child[curr].size()){
getChild(child[curr][i]);
}
}
void getParent(int curr){
if (counter[curr] == true) return;
counter[curr] = true;
forn(i, 0, parent[curr].size()){
getParent(parent[curr][i]);
}
}
int main() {
int a, b, e, p;
cin >> a >> b >> e >> p;
int res1[e], res2[e];
forn(i, 0, e) {
res1[i] = 0;
res2[i] = 0;
}
forn(i, 0, p){
int fi, se;
cin >> fi >> se;
child[fi].pb(se);
parent[se].pb(fi);
}
forn(i, 0, e){
getChild(i);
forn(j, 0, e) {
if (counter[j] == true) {
res1[i]++;
counter[j] = false;
}
}
getParent(i);
forn(j, 0, e) {
if (counter[j] == true) {
res2[i]++;
counter[j] = false;
}
}
}
int A = 0, B = 0, C =0;
forn(i, 0, e) {
if (e - res1[i] < a) A++;
if (e - res1[i] < b) B++;
if (res2[i] - 1 >= b) C++;
}
cout << '\n';
cout << A << '\n' << B << '\n' << C;
} | 22.873239 | 64 | 0.446429 | caando |
4115695c125b91c599f09041bfb858e332a8b2a0 | 11,416 | cpp | C++ | SofaKernel/framework/sofa/helper/polygon_cube_intersection/polygon_cube_intersection.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | SofaKernel/framework/sofa/helper/polygon_cube_intersection/polygon_cube_intersection.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | SofaKernel/framework/sofa/helper/polygon_cube_intersection/polygon_cube_intersection.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
/*
* polygon_intersects_cube()
* by Don Hatch
* January 1994
*
* Algorithm:
* 1. If any edge intersects the cube, return true.
* Testing whether a line segment intersects the cube
* is equivalent to testing whether the origin is contained
* in the rhombic dodecahedron obtained by dragging
* a unit cube from (being centered at) one segment endpoint
* to the other.
* 2. If the polygon interior intersects the cube, return true.
* Since we know no vertex or edge intersects the cube,
* this amounts to testing whether any of the four cube diagonals
* intersects the interior of the polygon. (Same as voorhies's test).
* 3. Return false.
*/
#include "polygon_cube_intersection.h"
#include "vec.h"
namespace sofa
{
namespace helper
{
namespace polygon_cube_intersection
{
#define FOR(i,n) for ((i) = 0; (i) < (n); ++(i))
#define MAXDIM2(v) ((v)[0] > (v)[1] ? 0 : 1)
#define MAXDIM3(v) ((v)[0] > (v)[2] ? MAXDIM2(v) : MAXDIM2((v)+1)+1)
#define ABS(x) ((x)<0 ? -(x) : (x))
#define SQR(x) ((x)*(x))
#define SIGN_NONZERO(x) ((x) < 0 ? -1 : 1)
/* note a and b can be in the reverse order and it still works! */
#define IN_CLOSED_INTERVAL(a,x,b) (((x)-(a)) * ((x)-(b)) <= 0)
#define IN_OPEN_INTERVAL(a,x,b) (((x)-(a)) * ((x)-(b)) < 0)
#define seg_contains_point(a,b,x) (((b)>(x)) - ((a)>(x)))
/*
* Tells whether a given polygon with nonzero area
* contains a point which is assumed to lie in the plane of the polygon.
* Actually returns the multiplicity of containment.
* This will always be 1 or 0 for non-self-intersecting planar
* polygons with the normal in the standard direction
* (towards the eye when looking at the polygon so that it's CCW).
*/
extern int
polygon_contains_point_3d(int nverts, const float verts[/* nverts */][3],
const float polynormal[3],
float point[3])
{
float abspolynormal[3];
int zaxis, xaxis, yaxis, i, count;
/*
* Determine which axis to ignore
* (the one in which the polygon normal is largest)
*/
FOR(i,3)
abspolynormal[i] = ABS(polynormal[i]);
zaxis = MAXDIM3(abspolynormal);
if (polynormal[zaxis] < 0)
{
xaxis = (zaxis+2)%3;
yaxis = (zaxis+1)%3;
}
else
{
xaxis = (zaxis+1)%3;
yaxis = (zaxis+2)%3;
}
count = 0;
FOR(i,nverts)
{
const float* v = verts[i];
const float* w = verts[(i+1)%nverts];
if (const int xdirection = seg_contains_point(v[xaxis], w[xaxis], point[xaxis]))
{
if (seg_contains_point(v[yaxis], w[yaxis], point[yaxis]))
{
if (xdirection * (point[xaxis]-v[xaxis])*(w[yaxis]-v[yaxis]) <=
xdirection * (point[yaxis]-v[yaxis])*(w[xaxis]-v[xaxis]))
count += xdirection;
}
else
{
if (v[yaxis] <= point[yaxis])
count += xdirection;
}
}
}
return count;
}
/*
* A segment intersects the unit cube centered at the origin
* iff the origin is contained in the solid obtained
* by dragging a unit cube from one segment endpoint to the other.
* (This solid is a warped rhombic dodecahedron.)
* This amounts to 12 sidedness tests.
* Also, this test works even if one or both of the segment endpoints is
* inside the cube.
*/
extern int
segment_intersects_cube(const float v0[3], const float v1[3])
{
float edgevec[3];
VMV3(edgevec, v1, v0);
int i = 0;
int edgevec_signs[3];
FOR(i,3)
edgevec_signs[i] = SIGN_NONZERO(edgevec[i]);
/*
* Test the three cube faces on the v1-ward side of the cube--
* if v0 is outside any of their planes then there is no intersection.
* Also test the three cube faces on the v0-ward side of the cube--
* if v1 is outside any of their planes then there is no intersection.
*/
FOR(i,3)
{
if (v0[i] * edgevec_signs[i] > .5) return 0;
if (v1[i] * edgevec_signs[i] < -.5) return 0;
}
/*
* Okay, that's the six easy faces of the rhombic dodecahedron
* out of the way. Six more to go.
* The remaining six planes bound an infinite hexagonal prism
* joining the petrie polygons (skew hexagons) of the two cubes
* centered at the endpoints.
*/
FOR(i,3)
{
float rhomb_normal_dot_v0, rhomb_normal_dot_cubedge;
const int iplus1 = (i+1)%3;
const int iplus2 = (i+2)%3;
#ifdef THE_EASY_TO_UNDERSTAND_WAY
{
float rhomb_normal[3], cubedge_midpoint[3];
/*
* rhomb_normal = VXV3(edgevec, unit vector in direction i),
* being cavalier about which direction it's facing
*/
rhomb_normal[i] = 0;
rhomb_normal[iplus1] = edgevec[iplus2];
rhomb_normal[iplus2] = -edgevec[iplus1];
/*
* We now are describing a plane parallel to
* both segment and the cube edge in question.
* if |DOT3(rhomb_normal, an arbitrary point on the segment)| >
* |DOT3(rhomb_normal, an arbitrary point on the cube edge in question|
* then the origin is outside this pair of opposite faces.
* (This is equivalent to saying that the line
* containing the segment is "outside" (i.e. further away from the
* origin than) the line containing the cube edge.
*/
cubedge_midpoint[i] = 0;
cubedge_midpoint[iplus1] = edgevec_signs[iplus1]*.5;
cubedge_midpoint[iplus2] = -edgevec_signs[iplus2]*.5;
rhomb_normal_dot_v0 = DOT3(rhomb_normal, v0);
rhomb_normal_dot_cubedge = DOT3(rhomb_normal,cubedge_midpoint);
}
#else /* the efficient way */
rhomb_normal_dot_v0 = edgevec[iplus2] * v0[iplus1]
- edgevec[iplus1] * v0[iplus2];
rhomb_normal_dot_cubedge = .5f *
(edgevec[iplus2] * edgevec_signs[iplus1] +
edgevec[iplus1] * edgevec_signs[iplus2]);
#endif /* the efficient way */
if (SQR(rhomb_normal_dot_v0) > SQR(rhomb_normal_dot_cubedge))
return 0; /* origin is outside this pair of opposite planes */
}
return 1;
}
/*
* Tells whether a given polygon intersects the cube of edge length 1
* centered at the origin.
* Always returns 1 if a polygon edge intersects the cube;
* returns the multiplicity of containment otherwise.
* (See explanation of polygon_contains_point_3d() above).
*/
extern int
polygon_intersects_cube(int nverts, const float verts[/* nverts */][3],
const float polynormal[3],
int ,/* already_know_vertices_are_outside_cube unused*/
int already_know_edges_are_outside_cube)
{
int i, best_diagonal[3];
float p[3], t;
/*
* If any edge intersects the cube, return 1.
*/
if (!already_know_edges_are_outside_cube)
FOR(i,nverts)
if (segment_intersects_cube(verts[i], verts[(i+1)%nverts]))
return 1;
/*
* If the polygon normal is zero and none of its edges intersect the
* cube, then it doesn't intersect the cube
*/
if (ISZEROVEC3(polynormal))
return 0;
/*
* Now that we know that none of the polygon's edges intersects the cube,
* deciding whether the polygon intersects the cube amounts
* to testing whether any of the four cube diagonals intersects
* the interior of the polygon.
*
* Notice that we only need to consider the cube diagonal that comes
* closest to being perpendicular to the plane of the polygon.
* If the polygon intersects any of the cube diagonals,
* it will intersect that one.
*/
FOR(i,3)
best_diagonal[i] = SIGN_NONZERO(polynormal[i]);
/*
* Okay, we have the diagonal of interest.
* The plane containing the polygon is the set of all points p satisfying
* DOT3(polynormal, p) == DOT3(polynormal, verts[0])
* So find the point p on the cube diagonal of interest
* that satisfies this equation.
* The line containing the cube diagonal is described parametrically by
* t * best_diagonal
* so plug this into the previous equation and solve for t.
* DOT3(polynormal, t * best_diagonal) == DOT3(polynormal, verts[0])
* i.e.
* t = DOT3(polynormal, verts[0]) / DOT3(polynormal, best_diagonal)
*
* (Note that the denominator is guaranteed to be nonzero, since
* polynormal is nonzero and best_diagonal was chosen to have the largest
* magnitude dot-product with polynormal)
*/
t = DOT3(polynormal, verts[0])
/ DOT3(polynormal, best_diagonal);
if (!IN_CLOSED_INTERVAL(-.5, t, .5))
return 0; /* intersection point is not in cube */
SXV3(p, t, best_diagonal); /* p = t * best_diagonal */
return polygon_contains_point_3d(nverts, verts, polynormal, p);
}
extern float *
get_polygon_normal(float normal[3],
int nverts, const float verts[/* nverts */][3])
{
int i;
float tothis[3], toprev[3], cross[3];
/*
* Triangulate the polygon and sum up the nverts-2 triangle normals.
*/
ZEROVEC3(normal);
VMV3(toprev, verts[1], verts[0]); /* 3 subtracts */
for (i = 2; i <= nverts-1; ++i) /* n-2 times... */
{
VMV3(tothis, verts[i], verts[0]); /* 3 subtracts */
VXV3(cross, toprev, tothis); /* 3 subtracts, 6 multiplies */
VPV3(normal, normal, cross); /* 3 adds */
SET3(toprev, tothis);
}
return normal;
}
}
}
}
| 35.018405 | 88 | 0.577523 | sofa-framework |
4116916a2efa8e26373674c468980243f492b96a | 2,829 | hpp | C++ | engine/gems/sight/sop_transform.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 1 | 2020-04-14T13:55:16.000Z | 2020-04-14T13:55:16.000Z | engine/gems/sight/sop_transform.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 4 | 2020-09-25T22:34:29.000Z | 2022-02-09T23:45:12.000Z | engine/gems/sight/sop_transform.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 1 | 2020-07-02T11:51:17.000Z | 2020-07-02T11:51:17.000Z | /*
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#pragma once
#include <string>
#include <utility>
#include "engine/core/math/pose2.hpp"
#include "engine/core/math/pose3.hpp"
#include "engine/core/optional.hpp"
#include "engine/gems/geometry/pinhole.hpp"
#include "engine/gems/serialization/json.hpp"
#include "engine/gems/serialization/json_formatter.hpp"
namespace isaac {
namespace sight {
// Sight Operations Transformation:
// Contains the Pose2 or Pose3 transform as well as a scale factor
class SopTransform {
public:
// Default constructor
SopTransform() = default;
// Creates a SopTransform using the canvas pixel frame (allow you to draw directly at a given
// position on a canvas).
// Note: this only works for 2D and the Sop will not be rendered in 3D.
static SopTransform CanvasFrame() {
SopTransform t;
t.json_["t"] = "c";
return t;
}
// Creates a SopTransform using a reference frame
SopTransform(const std::string& reference_frame) {
json_["t"] = "f";
json_["f"] = reference_frame;
}
// Creates a SopTransform using a Pose2
template <typename K>
SopTransform(const Pose2<K>& pose) {
json_["t"] = "2d";
serialization::Set(json_["p"], pose);
}
// Creates a SopTransform using a Pose3
template <typename K>
SopTransform(const Pose3<K>& pose) {
json_["t"] = "3d";
serialization::Set(json_["p"], pose);
}
// Creates a transform with a Pose and a scale
template <typename Pose>
SopTransform(const Pose& pose, double scale) : SopTransform(pose) {
json_["s"] = scale;
}
// Creates a transform with a Pose and a pinhole projection
template <typename Pose, typename K>
SopTransform(const Pose& pose, const geometry::Pinhole<K>& pinhole) : SopTransform(pose) {
Json proj;
proj["c0"] = pinhole.center[0];
proj["c1"] = pinhole.center[1];
proj["f0"] = pinhole.focal[0];
proj["f1"] = pinhole.focal[1];
json_["proj"] = proj;
}
// Creates a transform with a Pose and a scale
template <typename Pose, typename K>
SopTransform(const Pose& pose, double scale, const geometry::Pinhole<K>& pinhole)
: SopTransform(pose, pinhole) {
json_["s"] = scale;
}
private:
friend const Json& ToJson(const SopTransform&);
friend Json ToJson(SopTransform&&);
Json json_;
};
// Returns the json of a SopTransform
const Json& ToJson(const SopTransform&);
Json ToJson(SopTransform&&);
} // namespace sight
} // namespace isaac
| 28.867347 | 95 | 0.707317 | stereoboy |
411a4f12928dd8dc223a4a428573a20bd1f5c46c | 5,562 | cpp | C++ | format/tables/TableFactory.cpp | eladraz/morph | e80b93af449471fb2ca9e256188f9a92f631fbc2 | [
"BSD-3-Clause"
] | 4 | 2017-01-24T09:32:23.000Z | 2021-08-20T03:29:54.000Z | format/tables/TableFactory.cpp | eladraz/morph | e80b93af449471fb2ca9e256188f9a92f631fbc2 | [
"BSD-3-Clause"
] | null | null | null | format/tables/TableFactory.cpp | eladraz/morph | e80b93af449471fb2ca9e256188f9a92f631fbc2 | [
"BSD-3-Clause"
] | 1 | 2021-08-20T03:29:55.000Z | 2021-08-20T03:29:55.000Z | /*
* Copyright (c) 2008-2016, Integrity Project Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 Integrity Project 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
*/
/*
* TableFactory.cpp
*
* Implementation file
*
* Author: Elad Raz <e@eladraz.com>
*/
#include "xStl/types.h"
#include "xStl/data/smartptr.h"
#include "xStl/data/datastream.h"
#include "xStl/stream/traceStream.h"
#include "format/EncodingUtils.h"
#include "format/tables/TablesID.h"
#include "format/tables/TableFactory.h"
#include "format/tables/ModuleTable.h"
#include "format/tables/TyperefTable.h"
#include "format/tables/TypedefTable.h"
#include "format/tables/FieldTable.h"
#include "format/tables/FieldRVATable.h"
#include "format/tables/MethodTable.h"
#include "format/tables/ParamTable.h"
#include "format/tables/MemberRefTable.h"
#include "format/tables/ConstantTable.h"
#include "format/tables/InterfaceImplTable.h"
#include "format/tables/CustomAttributeTable.h"
#include "format/tables/ClassLayoutTable.h"
#include "format/tables/DeclSecurityTable.h"
#include "format/tables/StandAloneSigTable.h"
#include "format/tables/PropertyMapTable.h"
#include "format/tables/PropertyTable.h"
#include "format/tables/MethodSemanticsTable.h"
#include "format/tables/MethodImplTable.h"
#include "format/tables/TypeSpecTable.h"
#include "format/tables/AssemblyTable.h"
#include "format/tables/AssemblyRefTable.h"
#include "format/tables/NestedClassTable.h"
#include "format/tables/GenericParamTable.h"
#include "format/tables/MethodSpecTable.h"
TablePtr TableFactory::readTable(MetadataStream& stream, uint id,
uint tablePosition)
{
mdToken newToken = EncodingUtils::buildToken(id, tablePosition + 1);
switch (id)
{
case TABLE_MODULE_TABLE: return TablePtr(new ModuleTable(stream, newToken));
case TABLE_TYPEREF_TABLE: return TablePtr(new TyperefTable(stream, newToken));
case TABLE_TYPEDEF_TABLE: return TablePtr(new TypedefTable(stream, newToken));
case TABLE_FIELD_TABLE: return TablePtr(new FieldTable(stream, newToken));
case TABLE_METHOD_TABLE: return TablePtr(new MethodTable(stream, newToken));
case TABLE_PARAM_TABLE: return TablePtr(new ParamTable(stream, newToken));
case TABLE_INTERFACEIMPL_TABLE: return TablePtr(new InterfaceImplTable(stream, newToken));
case TABLE_MEMBERREF_TABLE: return TablePtr(new MemberRefTable(stream, newToken));
case TABLE_CONSTANT_TABLE: return TablePtr(new ConstantTable(stream, newToken));
case TABLE_CUSTOMATTRIBUTE_TABLE: return TablePtr(new CustomAttributeTable(stream, newToken));
case TABLE_DECLSECURITY_TABLE: return TablePtr(new DeclSecurityTable(stream, newToken));
case TABLE_CLASSLAYOUT_TABLE: return TablePtr(new ClassLayoutTable(stream, newToken));
case TABLE_STANDALONGESIG_TABLE: return TablePtr(new StandAloneSigTable(stream, newToken));
case TABLE_PROPERTYMAP_TABLE: return TablePtr(new PropertyMapTable(stream, newToken));
case TABLE_PROPERTY_TABLE: return TablePtr(new PropertyTable(stream, newToken));
case TABLE_METHODSEMANTICS_TABLE: return TablePtr(new MethodSemanticsTable(stream, newToken));
case TABLE_METHODIMPL_TABLE: return TablePtr(new MethodImplTable(stream, newToken));
case TABLE_TYPESPEC_TABLE: return TablePtr(new TypeSpecTable(stream, newToken));
case TABLE_FIELDRVA_TABLE: return TablePtr(new FieldRVATable(stream, newToken));
case TABLE_ASSEMBLY_TABLE: return TablePtr(new AssemblyTable(stream, newToken));
case TABLE_ASSEMBLYREF_TABLE: return TablePtr(new AssemblyRefTable(stream, newToken));
case TABLE_NESTEDCLASS_TABLE: return TablePtr(new NestedClassTable(stream, newToken));
case TABLE_GENERICPARAM_TABLE: return TablePtr(new GenericParamTable(stream, newToken));
case TABLE_METHODSPEC_TABLE: return TablePtr(new MethodSpecTable(stream, newToken));
default:
// The table #id is not ready or unknown...
traceHigh("Cannot parse CLR file table: " << HEXDWORD(id) << endl);
CHECK_FAIL();
}
}
| 50.108108 | 98 | 0.759259 | eladraz |
411eddbb6ede14e3628bb7356455a8b6a0716873 | 2,038 | cpp | C++ | Classes/UI/Chooser.cpp | FrSanchez/snake | 4e2260d0784cd90ddf28a9f209b0d00da3cf66d0 | [
"MIT"
] | null | null | null | Classes/UI/Chooser.cpp | FrSanchez/snake | 4e2260d0784cd90ddf28a9f209b0d00da3cf66d0 | [
"MIT"
] | null | null | null | Classes/UI/Chooser.cpp | FrSanchez/snake | 4e2260d0784cd90ddf28a9f209b0d00da3cf66d0 | [
"MIT"
] | null | null | null | //
// Chooser.cpp
// cocos2d
//
// Created by Francisco Sanchez on 2/11/21.
//
#include "Chooser.h"
USING_NS_CC;
bool Chooser::init()
{
auto numLabel = Label::createWithTTF("1", "Arcade.ttf", 96);
numLabel->setTextColor(Color4B::WHITE);
numLabel->enableOutline(Color4B::GRAY, 5);
numLabel->setAlignment(TextHAlignment::CENTER, TextVAlignment::CENTER);
auto downNormal = Sprite::createWithSpriteFrameName("LeftNormal");
auto downSelected = Sprite::createWithSpriteFrameName("LeftSelected");
auto downItem = MenuItemSprite::create(downNormal, downSelected, CC_CALLBACK_1(Chooser::upDownCallback, this));
auto upNormal = Sprite::createWithSpriteFrameName("RightNormal");
auto upSelected = Sprite::createWithSpriteFrameName("RightSelected");
auto upItem = MenuItemSprite::create(upNormal, upSelected, CC_CALLBACK_1(Chooser::upDownCallback, this));
auto menuChoose = Menu::create(downItem, upItem, nullptr);
menuChoose->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
downItem->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
upItem->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
upItem->setTag(1);
downItem->setTag(-1);
addChild(menuChoose);
addChild(numLabel);
upItem->setUserData(numLabel);
downItem->setUserData(numLabel);
upItem->setPosition(Vec2(100,0));
downItem->setPosition(Vec2(-100,0));
menuChoose->setPosition(Vec2::ZERO);
numLabel->setPosition(Vec2::ZERO);
return true;
}
void Chooser::upDownCallback(cocos2d::Ref* pSender)
{
MenuItem *item = static_cast<MenuItem*>(pSender);
_value += item->getTag();
if (_value < _minValue)
{
_value = _maxValue;
}
if (_value > _maxValue)
{
_value = _minValue;
}
Label* numLabel = static_cast<Label*>(item->getUserData());
numLabel->setString(StringUtils::format("%d", _value));
if (_callback != nullptr) {
_callback(_value);
}
}
void Chooser::setMaxValue(int value)
{
_maxValue = value;
}
Chooser::~Chooser()
{
}
| 27.540541 | 115 | 0.682532 | FrSanchez |
4120345e8fc158ce29269b573dfdf0df69210872 | 2,372 | cc | C++ | chrome/browser/android/media/media_capture_devices_dispatcher_android.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/android/media/media_capture_devices_dispatcher_android.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/android/media/media_capture_devices_dispatcher_android.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "chrome/android/chrome_jni_headers/MediaCaptureDevicesDispatcherAndroid_jni.h"
#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/webrtc/media_stream_capture_indicator.h"
using base::android::JavaParamRef;
jboolean JNI_MediaCaptureDevicesDispatcherAndroid_IsCapturingAudio(
JNIEnv* env,
const JavaParamRef<jobject>& java_web_contents) {
content::WebContents* web_contents =
content::WebContents::FromJavaWebContents(java_web_contents);
scoped_refptr<MediaStreamCaptureIndicator> indicator =
MediaCaptureDevicesDispatcher::GetInstance()
->GetMediaStreamCaptureIndicator();
return indicator->IsCapturingAudio(web_contents);
}
jboolean JNI_MediaCaptureDevicesDispatcherAndroid_IsCapturingVideo(
JNIEnv* env,
const JavaParamRef<jobject>& java_web_contents) {
content::WebContents* web_contents =
content::WebContents::FromJavaWebContents(java_web_contents);
scoped_refptr<MediaStreamCaptureIndicator> indicator =
MediaCaptureDevicesDispatcher::GetInstance()
->GetMediaStreamCaptureIndicator();
return indicator->IsCapturingVideo(web_contents);
}
jboolean JNI_MediaCaptureDevicesDispatcherAndroid_IsCapturingScreen(
JNIEnv* env,
const JavaParamRef<jobject>& java_web_contents) {
content::WebContents* web_contents =
content::WebContents::FromJavaWebContents(java_web_contents);
scoped_refptr<MediaStreamCaptureIndicator> indicator =
MediaCaptureDevicesDispatcher::GetInstance()
->GetMediaStreamCaptureIndicator();
return indicator->IsCapturingWindow(web_contents) ||
indicator->IsCapturingDisplay(web_contents);
}
void JNI_MediaCaptureDevicesDispatcherAndroid_NotifyStopped(
JNIEnv* env,
const JavaParamRef<jobject>& java_web_contents) {
content::WebContents* web_contents =
content::WebContents::FromJavaWebContents(java_web_contents);
scoped_refptr<MediaStreamCaptureIndicator> indicator =
MediaCaptureDevicesDispatcher::GetInstance()
->GetMediaStreamCaptureIndicator();
indicator->NotifyStopped(web_contents);
}
| 41.614035 | 87 | 0.79511 | zealoussnow |
4124cc1897b4792aecf6be34bbf76782675087c5 | 1,293 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/AI/behavior/DriveToNodeTreeNodeDefinition.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/AI/behavior/DriveToNodeTreeNodeDefinition.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/AI/behavior/DriveToNodeTreeNodeDefinition.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/Scripting/Natives/Generated/AI/behavior/DriveTreeNodeDefinition.hpp>
namespace RED4ext
{
namespace AI { struct ArgumentMapping; }
namespace AI::behavior {
struct DriveToNodeTreeNodeDefinition : AI::behavior::DriveTreeNodeDefinition
{
static constexpr const char* NAME = "AIbehaviorDriveToNodeTreeNodeDefinition";
static constexpr const char* ALIAS = NAME;
Handle<AI::ArgumentMapping> useKinematic; // 40
Handle<AI::ArgumentMapping> needDriver; // 50
Handle<AI::ArgumentMapping> nodeRef; // 60
Handle<AI::ArgumentMapping> stopAtPathEnd; // 70
Handle<AI::ArgumentMapping> secureTimeOut; // 80
Handle<AI::ArgumentMapping> isPlayer; // 90
Handle<AI::ArgumentMapping> useTraffic; // A0
Handle<AI::ArgumentMapping> speedInTraffic; // B0
Handle<AI::ArgumentMapping> forceGreenLights; // C0
Handle<AI::ArgumentMapping> portals; // D0
Handle<AI::ArgumentMapping> trafficTryNeighborsForStart; // E0
Handle<AI::ArgumentMapping> trafficTryNeighborsForEnd; // F0
};
RED4EXT_ASSERT_SIZE(DriveToNodeTreeNodeDefinition, 0x100);
} // namespace AI::behavior
} // namespace RED4ext
| 35.916667 | 86 | 0.75406 | jackhumbert |
4126e3c9cf629bf24fe7a1e2e8086171a348c094 | 448 | cpp | C++ | examples/cpp.cpp | kurazu/pycon2015 | fd3878bfb961ccddb0bfd67e704c50355280d271 | [
"CC0-1.0"
] | null | null | null | examples/cpp.cpp | kurazu/pycon2015 | fd3878bfb961ccddb0bfd67e704c50355280d271 | [
"CC0-1.0"
] | null | null | null | examples/cpp.cpp | kurazu/pycon2015 | fd3878bfb961ccddb0bfd67e704c50355280d271 | [
"CC0-1.0"
] | null | null | null | #include <sstream>
#include <string>
static PyObject *
cpp_format(PyObject *self, PyObject * args)
{
const char * name;
unsigned age;
if (!PyArg_ParseTuple(args, "sI", &name, &age)) {
return NULL;
}
std::stringstream ss;
ss << name << " is " << age << " years old.";
std::string formatted = ss.str();
const char * formatted_cstring = formatted.c_str();
return PyUnicode_FromString(formatted_cstring);
}
| 24.888889 | 55 | 0.629464 | kurazu |
4126fda8853410e3bd8a844018220e275c206bf4 | 298 | cpp | C++ | C++ aleatorios/C/soma.cpp | higorslva/projetos-universidade | 92ed784025c85369f722f5d06c7a42fff7957f2e | [
"Apache-2.0"
] | null | null | null | C++ aleatorios/C/soma.cpp | higorslva/projetos-universidade | 92ed784025c85369f722f5d06c7a42fff7957f2e | [
"Apache-2.0"
] | null | null | null | C++ aleatorios/C/soma.cpp | higorslva/projetos-universidade | 92ed784025c85369f722f5d06c7a42fff7957f2e | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main ()
{
int nota;
std::cout << "Digite a nota: ";
std::cin >> nota;
if (nota>=7)
{
printf("Aluno aprovado");
}
else (nota<<7);
{
printf("Aluno reprovado");
}
return 0;
}
| 13.545455 | 36 | 0.456376 | higorslva |
412708460367666b68acce5feceecc6c10028631 | 10,611 | cpp | C++ | costmap_converter-master/src/costmap_converter_node.cpp | RuidongDavidLin/CUMTB_gazebo | a190c1dc17a587c789b5d856b3ee1b6de45e5503 | [
"MIT"
] | 1 | 2021-01-10T10:52:03.000Z | 2021-01-10T10:52:03.000Z | costmap_converter-master/src/costmap_converter_node.cpp | RuidongDavidLin/CUMTB_gazebo | a190c1dc17a587c789b5d856b3ee1b6de45e5503 | [
"MIT"
] | 1 | 2020-11-12T09:53:16.000Z | 2020-11-12T09:53:16.000Z | costmap_converter-master/src/costmap_converter_node.cpp | RuidongDavidLin/CUMTB_gazebo | a190c1dc17a587c789b5d856b3ee1b6de45e5503 | [
"MIT"
] | null | null | null | /*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2016,
* TU Dortmund - Institute of Control Theory and Systems Engineering.
* 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 institute 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.
*
* Author: Christoph Rösmann, Otniel Rinaldo
*********************************************************************/
#include <ros/ros.h>
#include <costmap_2d/costmap_2d.h>
#include <nav_msgs/OccupancyGrid.h>
#include <geometry_msgs/PolygonStamped.h>
#include <visualization_msgs/Marker.h>
#include <costmap_converter/costmap_converter_interface.h>
#include <pluginlib/class_loader.h>
class CostmapStandaloneConversion
{
public:
CostmapStandaloneConversion() : converter_loader_("costmap_converter", "costmap_converter::BaseCostmapToPolygons"), n_("~")
{
// load converter plugin from parameter server, otherwise set default
std::string converter_plugin = "costmap_converter::CostmapToPolygonsDBSMCCH";
n_.param("converter_plugin", converter_plugin, converter_plugin);
try
{
converter_ = converter_loader_.createInstance(converter_plugin);
}
catch(const pluginlib::PluginlibException& ex)
{
ROS_ERROR("The plugin failed to load for some reason. Error: %s", ex.what());
ros::shutdown();
}
ROS_INFO_STREAM("Standalone costmap converter:" << converter_plugin << " loaded.");
std::string costmap_topic = "/move_base/local_costmap/costmap";
n_.param("costmap_topic", costmap_topic, costmap_topic);
std::string costmap_update_topic = "/move_base/local_costmap/costmap_updates";
n_.param("costmap_update_topic", costmap_update_topic, costmap_update_topic);
std::string obstacles_topic = "costmap_obstacles";
n_.param("obstacles_topic", obstacles_topic, obstacles_topic);
std::string polygon_marker_topic = "costmap_polygon_markers";
n_.param("polygon_marker_topic", polygon_marker_topic, polygon_marker_topic);
costmap_sub_ = n_.subscribe(costmap_topic, 1, &CostmapStandaloneConversion::costmapCallback, this);
costmap_update_sub_ = n_.subscribe(costmap_update_topic, 1, &CostmapStandaloneConversion::costmapUpdateCallback, this);
obstacle_pub_ = n_.advertise<costmap_converter::ObstacleArrayMsg>(obstacles_topic, 1000);
marker_pub_ = n_.advertise<visualization_msgs::Marker>(polygon_marker_topic, 10);
occupied_min_value_ = 100;
n_.param("occupied_min_value", occupied_min_value_, occupied_min_value_);
std::string odom_topic = "/odom";
n_.param("odom_topic", odom_topic, odom_topic);
if (converter_)
{
converter_->setOdomTopic(odom_topic);
converter_->initialize(n_);
converter_->setCostmap2D(&map_);
//converter_->startWorker(ros::Rate(5), &map, true);
}
}
void costmapCallback(const nav_msgs::OccupancyGridConstPtr& msg)
{
ROS_INFO_ONCE("Got first costmap callback. This message will be printed once");
if (msg->info.width != map_.getSizeInCellsX() || msg->info.height != map_.getSizeInCellsY() || msg->info.resolution != map_.getResolution())
{
ROS_INFO("New map format, resizing and resetting map...");
map_.resizeMap(msg->info.width, msg->info.height, msg->info.resolution, msg->info.origin.position.x, msg->info.origin.position.y);
}
else
{
map_.updateOrigin(msg->info.origin.position.x, msg->info.origin.position.y);
}
for (std::size_t i=0; i < msg->data.size(); ++i)
{
unsigned int mx, my;
map_.indexToCells((unsigned int)i, mx, my);
map_.setCost(mx, my, msg->data[i] >= occupied_min_value_ ? 255 : 0 );
}
// convert
converter_->updateCostmap2D();
converter_->compute();
costmap_converter::ObstacleArrayConstPtr obstacles = converter_->getObstacles();
if (!obstacles)
return;
obstacle_pub_.publish(obstacles);
frame_id_ = msg->header.frame_id;
publishAsMarker(frame_id_, *obstacles, marker_pub_);
}
void costmapUpdateCallback(const map_msgs::OccupancyGridUpdateConstPtr& update)
{
unsigned int di = 0;
for (unsigned int y = 0; y < update->height ; ++y)
{
for (unsigned int x = 0; x < update->width ; ++x)
{
map_.setCost(x, y, update->data[di++] >= occupied_min_value_ ? 255 : 0 );
}
}
// convert
// TODO(roesmann): currently, the converter updates the complete costmap and not the part which is updated in this callback
converter_->updateCostmap2D();
converter_->compute();
costmap_converter::ObstacleArrayConstPtr obstacles = converter_->getObstacles();
if (!obstacles)
return;
obstacle_pub_.publish(obstacles);
publishAsMarker(frame_id_, *obstacles, marker_pub_);
}
void publishAsMarker(const std::string& frame_id, const std::vector<geometry_msgs::PolygonStamped>& polygonStamped, ros::Publisher& marker_pub)
{
visualization_msgs::Marker line_list;
line_list.header.frame_id = frame_id;
line_list.header.stamp = ros::Time::now();
line_list.ns = "Polygons";
line_list.action = visualization_msgs::Marker::ADD;
line_list.pose.orientation.w = 1.0;
line_list.id = 0;
line_list.type = visualization_msgs::Marker::LINE_LIST;
line_list.scale.x = 0.1;
line_list.color.g = 1.0;
line_list.color.a = 1.0;
for (std::size_t i=0; i<polygonStamped.size(); ++i)
{
for (int j=0; j< (int)polygonStamped[i].polygon.points.size()-1; ++j)
{
geometry_msgs::Point line_start;
line_start.x = polygonStamped[i].polygon.points[j].x;
line_start.y = polygonStamped[i].polygon.points[j].y;
line_list.points.push_back(line_start);
geometry_msgs::Point line_end;
line_end.x = polygonStamped[i].polygon.points[j+1].x;
line_end.y = polygonStamped[i].polygon.points[j+1].y;
line_list.points.push_back(line_end);
}
// close loop for current polygon
if (!polygonStamped[i].polygon.points.empty() && polygonStamped[i].polygon.points.size() != 2 )
{
geometry_msgs::Point line_start;
line_start.x = polygonStamped[i].polygon.points.back().x;
line_start.y = polygonStamped[i].polygon.points.back().y;
line_list.points.push_back(line_start);
if (line_list.points.size() % 2 != 0)
{
geometry_msgs::Point line_end;
line_end.x = polygonStamped[i].polygon.points.front().x;
line_end.y = polygonStamped[i].polygon.points.front().y;
line_list.points.push_back(line_end);
}
}
}
marker_pub.publish(line_list);
}
void publishAsMarker(const std::string& frame_id, const costmap_converter::ObstacleArrayMsg& obstacles, ros::Publisher& marker_pub)
{
visualization_msgs::Marker line_list;
line_list.header.frame_id = frame_id;
line_list.header.stamp = ros::Time::now();
line_list.ns = "Polygons";
line_list.action = visualization_msgs::Marker::ADD;
line_list.pose.orientation.w = 1.0;
line_list.id = 0;
line_list.type = visualization_msgs::Marker::LINE_LIST;
line_list.scale.x = 0.1;
line_list.color.g = 1.0;
line_list.color.a = 1.0;
for (const costmap_converter::ObstacleMsg& obstacle : obstacles.obstacles)
{
for (int j=0; j< (int)obstacle.polygon.points.size()-1; ++j)
{
geometry_msgs::Point line_start;
line_start.x = obstacle.polygon.points[j].x;
line_start.y = obstacle.polygon.points[j].y;
line_list.points.push_back(line_start);
geometry_msgs::Point line_end;
line_end.x = obstacle.polygon.points[j+1].x;
line_end.y = obstacle.polygon.points[j+1].y;
line_list.points.push_back(line_end);
}
// close loop for current polygon
if (!obstacle.polygon.points.empty() && obstacle.polygon.points.size() != 2 )
{
geometry_msgs::Point line_start;
line_start.x = obstacle.polygon.points.back().x;
line_start.y = obstacle.polygon.points.back().y;
line_list.points.push_back(line_start);
if (line_list.points.size() % 2 != 0)
{
geometry_msgs::Point line_end;
line_end.x = obstacle.polygon.points.front().x;
line_end.y = obstacle.polygon.points.front().y;
line_list.points.push_back(line_end);
}
}
}
marker_pub.publish(line_list);
}
private:
pluginlib::ClassLoader<costmap_converter::BaseCostmapToPolygons> converter_loader_;
boost::shared_ptr<costmap_converter::BaseCostmapToPolygons> converter_;
ros::NodeHandle n_;
ros::Subscriber costmap_sub_;
ros::Subscriber costmap_update_sub_;
ros::Publisher obstacle_pub_;
ros::Publisher marker_pub_;
std::string frame_id_;
int occupied_min_value_;
costmap_2d::Costmap2D map_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "costmap_converter");
CostmapStandaloneConversion convert_process;
ros::spin();
return 0;
}
| 35.727273 | 146 | 0.678447 | RuidongDavidLin |
4127f33642e8c6495190d922f05a0982b8e77e5c | 14,560 | cpp | C++ | fmod_alphabet_player.cpp | nbonaker/ticker | 4a9bab2916344914cbc96910c7eff4d9f0e10570 | [
"MIT"
] | null | null | null | fmod_alphabet_player.cpp | nbonaker/ticker | 4a9bab2916344914cbc96910c7eff4d9f0e10570 | [
"MIT"
] | 1 | 2018-11-06T09:30:23.000Z | 2018-11-06T09:30:23.000Z | fmod_alphabet_player.cpp | nbonaker/ticker | 4a9bab2916344914cbc96910c7eff4d9f0e10570 | [
"MIT"
] | 1 | 2019-01-23T14:46:11.000Z | 2019-01-23T14:46:11.000Z | #include "fmod_alphabet_player.h"
#include "fmod_errors.h"
#include <iostream>
#include <sstream>
//########################################### Initialisation/Release functions
AlphabetPlayer::AlphabetPlayer()
{
m_sound_files.reserve(MAX_ALPHABET);
m_stereo_pos.reserve(MAX_ALPHABET);
m_sound_times.reserve(MAX_ALPHABET);
m_p_system = NULL;
m_channels.resize(MAX_CHANNELS);
m_sound_idx.resize(MAX_CHANNELS);
m_left_input_on[0] = 1;
m_left_input_on[1] = 0;
m_right_input_on[0] = 0;
m_right_input_on[1] = 1;
m_input_off[0] = 0;
m_input_off[1] = 0;
m_cur_sound_index = -1;
m_cur_channel_index = -1;
m_instruct_sound = NULL;
m_config_dir_base = "config/channels";
m_alphabet_dir = "alphabet/";
setRootDir("./");
m_instruction_channel = NULL;
m_nticks = 2;
}
void AlphabetPlayer::initSoundSystem(void)
{
// NB: This function assumes all the pointers (ie. to system and
// sounds have been released).
// Create the sound system
releaseSounds();
m_result = FMOD::System_Create(&m_p_system);
fmodErrorCheck(m_result);
m_result = m_p_system->setOutput(FMOD_OUTPUTTYPE_ALSA);
fmodErrorCheck(m_result);
m_result = m_p_system->init(32, FMOD_INIT_NORMAL, 0);
fmodErrorCheck(m_result);
// Init all the sounds
m_sounds.resize(m_sound_files.size());
m_sound_times.resize(m_sound_files.size());
for (unsigned int n = 0; n < m_sound_files.size(); ++n)
{
m_sounds[n] = NULL;
m_sound_times[n] = -1;
}
// Init all indices
m_cur_sound_index = -1;
m_cur_channel_index = -1;
// Load the sounds
for (unsigned int n = 0; n < m_sound_files.size(); ++n)
{
m_result = m_p_system->createStream(m_sound_files[n].c_str(),
FMOD_SOFTWARE | FMOD_LOOP_OFF, 0,
&m_sounds[n]);
fmodErrorCheck(m_result);
}
}
void AlphabetPlayer::stop(void) { releaseSounds(); }
void AlphabetPlayer::restart(void) { initSoundSystem(); }
void AlphabetPlayer::releaseSounds(void)
{
if (m_instruct_sound != NULL)
{
m_result = m_instruct_sound->release();
fmodErrorCheck(m_result);
m_instruct_sound = NULL;
}
m_instruction_channel = NULL;
for (unsigned int n = 0; n < m_sounds.size(); ++n)
{
if (m_sounds[n] != NULL)
{
m_result = m_sounds[n]->release();
fmodErrorCheck(m_result);
m_sounds[n] = NULL;
m_sound_times[n] = -1;
}
}
for (int n = 0; n < MAX_CHANNELS; ++n)
{
if (m_channels[n] != NULL)
{
m_channels[n]->stop();
m_channels[n] = NULL;
m_sound_idx[n] = -1;
}
}
if (m_p_system != NULL)
{
m_result = m_p_system->close();
fmodErrorCheck(m_result);
m_result = m_p_system->release();
fmodErrorCheck(m_result);
m_p_system = NULL;
}
}
//######################################################### Error Checks
void AlphabetPlayer::fmodErrorCheck(FMOD_RESULT result)
{
if (result != FMOD_OK)
{
std::cerr << "FMOD error! (" << result << ") "
<< FMOD_ErrorString(result);
// exit(-1);
}
}
//############################################# File loading functions
template <class T>
bool AlphabetPlayer::fromString(T &t, const std::string &s,
std::ios_base &(*f)(std::ios_base &))
{
/*Examples:1. if(from_string<int>(i, std::string("ff"), std::hex)) ...
2. if(from_string<float>(f, std::string("123.456"), std::dec)) ...
*/
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
template <class T>
std::string AlphabetPlayer::toString(const T i_val)
{
std::stringstream out;
out << i_val;
return out.str();
}
template <class T>
bool AlphabetPlayer::readVal(std::ifstream &i_file, T &o_val)
{
std::string cur_string = "";
char cur_letter = '0';
bool assigned = false;
while (i_file.good())
{
cur_letter = (char)i_file.get();
if ((cur_letter == ' ') || (cur_letter == '\n'))
{
if (!assigned)
{
return false;
}
return fromString<T>(o_val, cur_string, std::dec);
}
cur_string += cur_letter;
assigned = true;
}
return assigned;
}
void AlphabetPlayer::loadAlphabetSequence(const int i_nchannels,
std::string &o_alphabet_sequence)
{
std::string nchannels = toString<int>(i_nchannels);
std::string config_file = m_config_dir + nchannels + "/alphabet.txt";
std::ifstream infile;
infile.open(config_file.c_str(), std::ios_base::in);
char cur_letter;
o_alphabet_sequence = "";
while (infile.good())
{
cur_letter = (char)infile.get();
if ((cur_letter == ' ') || (cur_letter == '\n'))
{
break;
}
o_alphabet_sequence += cur_letter;
}
infile.close();
}
void AlphabetPlayer::loadGroupStereoPos(const int i_nchannels,
std::vector<float> &o_pos)
{
std::string nchannels = toString<int>(i_nchannels);
std::string config_file = m_config_dir + nchannels + "/stereo_pos.txt";
std::ifstream infile;
infile.open(config_file.c_str(), std::ios_base::in);
o_pos.resize(i_nchannels);
for (int n = 0; n < i_nchannels; ++n)
{
if (!readVal<float>(infile, o_pos[n]))
{
std::cerr << "Can not read stereo position from " << config_file
<< " channel = " << n << std::endl;
infile.close();
// exit(-1);
return;
}
}
infile.close();
}
void AlphabetPlayer::loadLetterFiles(std::vector<float> &i_channel_pos,
std::string &i_alphabet_sequence)
{
unsigned int nchannels = i_channel_pos.size();
std::string sound_dir = m_sound_dir + toString<int>(nchannels) + "/";
m_sound_files.clear();
m_sound_times.clear();
m_stereo_pos.clear();
m_volume.resize(nchannels);
for (unsigned int n = 0; n < m_volume.size(); ++n)
{
m_volume[n].clear();
}
/* - Add the tick noise to the beginning of the first channel
- The actual stero location will be contained in m_stero_pos*/
for (unsigned int n = 0; n < m_nticks; ++n)
{
m_sound_files.push_back(sound_dir + "tick.ogg");
m_stereo_pos.push_back(0.0);
m_volume[0].push_back(1.0);
}
/* Add -1 as placeholders to channels 2-nchannels*/
for (unsigned int n = 1; n < nchannels; ++n)
{
for (unsigned int m = 0; m < m_nticks; ++m)
{
m_volume[n].push_back(-1.0);
}
}
// The rest of the letters
for (unsigned int n = 0, channel_cnt = 0; n < i_alphabet_sequence.length();
++n, ++channel_cnt)
{
while (channel_cnt >= nchannels)
channel_cnt -= nchannels;
if (i_alphabet_sequence[n] == '*')
{
m_volume[channel_cnt].push_back(-1.0);
continue;
}
m_sound_files.push_back(sound_dir + i_alphabet_sequence[n] + ".ogg");
m_stereo_pos.push_back(i_channel_pos[channel_cnt]);
m_volume[channel_cnt].push_back(1.0);
}
/*for (unsigned int c = 0; c < m_volume.size(); c++)
{
for (unsigned int l = 0; l < m_volume[c].size(); l++)
{
if (m_volume[c][l] < 0)
{
std::cout << 0;
}
else
{
std::cout << m_volume[c][l];
}
}
std::cout << std::endl;
}*/
}
//######################################### The main functions
void AlphabetPlayer::setTicks(unsigned int i_nticks) { m_nticks = i_nticks; }
void AlphabetPlayer::setChannels(int i_nchannels)
{
releaseSounds();
// Load the phase offset of channel (generates the stereo effect).
std::vector<float> group_stereo_pos;
loadGroupStereoPos(i_nchannels, group_stereo_pos);
// Load the sequence in which letters should be read.
std::string alphabet_sequence = "";
loadAlphabetSequence(i_nchannels, alphabet_sequence);
// Load the letter sound files and their final stereo positions.
loadLetterFiles(group_stereo_pos, alphabet_sequence);
// Setup the whole sound system.
initSoundSystem();
m_p_system->update();
}
void AlphabetPlayer::setRootDir(const std::string i_dir)
{
m_root_dir = i_dir;
m_sound_dir = i_dir + "voice_recordings/" + m_alphabet_dir + "channels";
m_config_dir = i_dir + m_config_dir_base;
m_instructions_dir = i_dir + "voice_recordings/commands/";
}
void AlphabetPlayer::setConfigDir(const std::string i_dir)
{
m_config_dir_base = i_dir;
setRootDir(m_root_dir);
}
void AlphabetPlayer::setAlphabetDir(const std::string i_dir)
{
m_alphabet_dir = i_dir;
setRootDir(m_root_dir);
}
int AlphabetPlayer::isReady(void)
{
bool is_playing = false;
for (unsigned int n = 0; n < m_channels.size(); ++n)
{
if (m_channels[n] == NULL)
continue;
m_channels[n]->isPlaying(&is_playing);
if (is_playing)
return 0;
}
if (m_instruction_channel == NULL)
{
return 1;
}
m_instruction_channel->isPlaying(&is_playing);
if (is_playing)
return 0;
return 1;
}
void AlphabetPlayer::playNext(void)
{
++m_cur_sound_index;
if (((unsigned int)m_cur_sound_index) >= m_sounds.size())
if (((unsigned int)m_cur_sound_index) >= m_sounds.size())
{
m_cur_sound_index = 0;
}
++m_cur_channel_index;
if (((unsigned int)m_cur_channel_index) >= m_channels.size())
{
m_cur_channel_index = 0;
}
m_sound_idx[m_cur_channel_index] = m_cur_sound_index;
m_result =
m_p_system->playSound(FMOD_CHANNEL_FREE, m_sounds[m_cur_sound_index],
false, &m_channels[m_cur_channel_index]);
fmodErrorCheck(m_result);
// Get the current channel and letter index
int channel = -1;
int letter_index = 0;
int cnt_sound = 0;
while (cnt_sound <= m_cur_sound_index)
{
if (++channel >= ((int)m_volume.size()))
{
channel = 0;
++letter_index;
}
if (m_volume[channel][letter_index] > 0.0)
++cnt_sound;
}
// std::cout << "sound index = " << m_cur_sound_index << " channel = " <<
// channel << " letter index = " << letter_index << " volume = "
// << m_volume[channel][letter_index] << " pan = " <<
// m_stereo_pos[m_cur_sound_index] << std::endl;
m_result = m_channels[m_cur_channel_index]->setVolume(
m_volume[channel][letter_index]);
fmodErrorCheck(m_result);
// FIXME: THIS LOOKS WEIRD BUT SOUNDS RIGHT, CHECK
m_result = m_channels[m_cur_channel_index]->setSpeakerLevels(
FMOD_SPEAKER_FRONT_LEFT, m_left_input_on, 3);
fmodErrorCheck(m_result);
m_result = m_channels[m_cur_channel_index]->setSpeakerLevels(
FMOD_SPEAKER_FRONT_LEFT, m_right_input_on, 3);
fmodErrorCheck(m_result);
m_result = m_channels[m_cur_channel_index]->setSpeakerLevels(
FMOD_SPEAKER_FRONT_LEFT, m_input_off, 3);
fmodErrorCheck(m_result);
m_result = m_channels[m_cur_channel_index]->setPan(
m_stereo_pos[m_cur_sound_index]);
m_p_system->update();
}
void AlphabetPlayer::setVolume(float i_volume, int i_nchannel)
{
if (i_nchannel >= ((int)m_channels.size()))
{
std::cerr << "Can not set volume of channel " << i_nchannel << ", only "
<< m_channels.size() - 1 << " allowed " << std::endl;
return;
}
unsigned int start_index = 0, nchannel = 0;
if (i_nchannel >= 0)
{
start_index = m_nticks;
nchannel = (unsigned int)i_nchannel;
}
for (unsigned int n = start_index; n < m_volume[nchannel].size(); ++n)
{
if (m_volume[nchannel][n] < 0.0)
continue;
m_volume[nchannel][n] = i_volume;
}
}
float AlphabetPlayer::getCurSoundLength(void)
{
if (m_cur_sound_index < 0)
return 0.0;
unsigned int sound_end;
m_result =
m_sounds[m_cur_sound_index]->getLength(&sound_end, FMOD_TIMEUNIT_MS);
return 0.001f * ((float)sound_end);
}
int AlphabetPlayer::getNChannelsPlaying(void)
{
if (m_cur_sound_index < 0)
return 0;
int n_channels_playing = 0;
m_result = m_p_system->getChannelsPlaying(&n_channels_playing);
fmodErrorCheck(m_result);
return n_channels_playing;
}
int AlphabetPlayer::getCurIndex(void) { return m_cur_sound_index; }
bool AlphabetPlayer::getIsCurChannelPlaying(void)
{
if (m_cur_sound_index < 0)
return false;
bool is_playing = false;
m_result = m_channels[m_cur_channel_index]->isPlaying(&is_playing);
return is_playing;
}
const std::vector<int> &AlphabetPlayer::getCurLetterTimes(void)
{
unsigned int letter_time = 0;
bool is_playing = false;
m_sound_times.assign(m_sound_times.size(), -1);
// If a sound is playing set it's corresponding letter time
for (unsigned int n = 0; n < m_channels.size(); ++n)
{
if (m_channels[n] == NULL)
continue;
m_channels[n]->isPlaying(&is_playing);
if (is_playing)
{
m_result =
m_channels[n]->getPosition(&letter_time, FMOD_TIMEUNIT_MS);
fmodErrorCheck(m_result);
m_sound_times[m_sound_idx[n]] = letter_time;
}
}
return m_sound_times;
}
bool AlphabetPlayer::getIsPlayingInstruction(void)
{
if (m_instruction_channel == NULL)
{
return false;
}
bool is_playing;
m_instruction_channel->isPlaying(&is_playing);
return (int)is_playing;
}
void AlphabetPlayer::playInstruction(std::string i_instruction_name,
std::string i_file_type)
{
std::string sound_file(m_instructions_dir + i_instruction_name +
i_file_type);
m_result = m_p_system->createSound(sound_file.c_str(),
FMOD_SOFTWARE | FMOD_LOOP_OFF, 0,
&m_instruct_sound);
fmodErrorCheck(m_result);
m_result = m_p_system->playSound(FMOD_CHANNEL_FREE, m_instruct_sound, false,
&m_instruction_channel);
fmodErrorCheck(m_result);
}
| 29.714286 | 80 | 0.593956 | nbonaker |
412c478823e481e9203655721ddd076708469c4b | 467 | cpp | C++ | Greedy Algorithms/activity_scheduling1.cpp | Reactor11/Data-Structures-Practice | 30d758aaece930e27585f9f7a2f904e74925516b | [
"MIT"
] | null | null | null | Greedy Algorithms/activity_scheduling1.cpp | Reactor11/Data-Structures-Practice | 30d758aaece930e27585f9f7a2f904e74925516b | [
"MIT"
] | null | null | null | Greedy Algorithms/activity_scheduling1.cpp | Reactor11/Data-Structures-Practice | 30d758aaece930e27585f9f7a2f904e74925516b | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int start[n],end[n];
for(int i=0;i<n;i++) cin>>start[i];
for(int i=0;i<n;i++) cin>>end[i];
int count=1,finish=end[0];
cout<<count<<" ";
for(int i=1;i<n;i++)
if(start[i] >= finish){
cout<<i+1<<" "; // gives activity number
count++;
finish = end[i];
}
cout<<endl;
cout<<"Number of activity : "<<count<<endl;
}
| 23.35 | 52 | 0.488223 | Reactor11 |
412de801b7bf18544d85cd0fe397097893e39055 | 32,216 | cc | C++ | Calibration/EcalCalibAlgos/src/PhiSymmetryCalibration_step2_SM.cc | malbouis/cmssw | 16173a30d3f0c9ecc5419c474bb4d272c58b65c8 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | Calibration/EcalCalibAlgos/src/PhiSymmetryCalibration_step2_SM.cc | gartung/cmssw | 3072dde3ce94dcd1791d778988198a44cde02162 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | Calibration/EcalCalibAlgos/src/PhiSymmetryCalibration_step2_SM.cc | gartung/cmssw | 3072dde3ce94dcd1791d778988198a44cde02162 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "Calibration/EcalCalibAlgos/src/PhiSymmetryCalibration_step2_SM.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "CondFormats/EcalObjects/interface/EcalIntercalibConstants.h"
#include "CondTools/Ecal/interface/EcalIntercalibConstantsXMLTranslator.h"
#include "CondFormats/DataRecord/interface/EcalIntercalibConstantsRcd.h"
#include "TH2F.h"
#include "TH1F.h"
#include "TFile.h"
#include <filesystem>
#include <fstream>
using namespace std;
PhiSymmetryCalibration_step2_SM::~PhiSymmetryCalibration_step2_SM() {}
PhiSymmetryCalibration_step2_SM::PhiSymmetryCalibration_step2_SM(const edm::ParameterSet& iConfig)
: channelStatusToken_(esConsumes()),
geometryToken_(esConsumes()),
firstpass_(true),
statusThreshold_(iConfig.getUntrackedParameter<int>("statusThreshold", 0)),
reiteration_(iConfig.getUntrackedParameter<bool>("reiteration", false)),
oldcalibfile_(iConfig.getUntrackedParameter<std::string>("oldcalibfile", "EcalIntercalibConstants.xml")),
have_initial_miscalib_(iConfig.getUntrackedParameter<bool>("haveInitialMiscalib", false)),
initialmiscalibfile_(iConfig.getUntrackedParameter<std::string>("initialmiscalibfile", "InitialMiscalib.xml")) {}
void PhiSymmetryCalibration_step2_SM::analyze(const edm::Event& ev, const edm::EventSetup& se) {
if (firstpass_) {
setUp(se);
firstpass_ = false;
}
}
void PhiSymmetryCalibration_step2_SM::setUp(const edm::EventSetup& se) {
const auto& chStatus = se.getData(channelStatusToken_);
const auto& geometry = se.getData(geometryToken_);
barrelCells = geometry.getValidDetIds(DetId::Ecal, EcalBarrel);
endcapCells = geometry.getValidDetIds(DetId::Ecal, EcalEndcap);
e_.setup(&geometry, &chStatus, statusThreshold_);
for (int sign = 0; sign < kSides; sign++) {
for (int ieta = 0; ieta < kBarlRings; ieta++) {
for (int iphi = 0; iphi < kBarlWedges; iphi++) {
int iphi_r = int(iphi / nscx);
if (!e_.goodCell_barl[ieta][iphi][sign]) {
nBads_barl_SM_[ieta][iphi_r][sign]++;
// std::cout << "N BAD CELL " << nBads_barl_SM_[ieta][iphi_r][sign] << endl;
}
}
}
}
/// if a miscalibration was applied, load it, if not put it to 1
if (have_initial_miscalib_) {
EcalCondHeader h;
namespace fs = std::filesystem;
fs::path p(initialmiscalibfile_.c_str());
if (!fs::exists(p))
edm::LogError("PhiSym") << "File not found: " << initialmiscalibfile_ << endl;
int ret = EcalIntercalibConstantsXMLTranslator::readXML(initialmiscalibfile_, h, miscalib_);
if (ret)
edm::LogError("PhiSym") << "Error reading XML files" << endl;
} else {
for (vector<DetId>::iterator it = barrelCells.begin(); it != barrelCells.end(); ++it) {
miscalib_[*it] = 1;
}
for (vector<DetId>::iterator it = endcapCells.begin(); it != endcapCells.end(); ++it) {
miscalib_[*it] = 1;
}
}
// if we are reiterating, read constants from previous iter
// if not put them to one
if (reiteration_) {
EcalCondHeader h;
namespace fs = std::filesystem;
fs::path p(oldcalibfile_.c_str());
if (!fs::exists(p))
edm::LogError("PhiSym") << "File not found: " << oldcalibfile_ << endl;
int ret = EcalIntercalibConstantsXMLTranslator::readXML(oldcalibfile_, h, oldCalibs_);
if (ret)
edm::LogError("PhiSym") << "Error reading XML files" << endl;
;
} else {
for (vector<DetId>::iterator it = barrelCells.begin(); it != barrelCells.end(); ++it)
oldCalibs_[*it] = 1;
for (vector<DetId>::iterator it = endcapCells.begin(); it != endcapCells.end(); ++it)
oldCalibs_[*it] = 1;
} // else
}
void PhiSymmetryCalibration_step2_SM::beginJob() {
for (int ieta = 0; ieta < kBarlRings; ieta++) {
for (int iphi = 0; iphi < kBarlWedges; iphi++) {
for (int sign = 0; sign < kSides; sign++) {
int iphi_r = int(iphi / nscx);
etsum_barl_[ieta][iphi][sign] = 0.;
nhits_barl_[ieta][iphi][sign] = 0;
esum_barl_[ieta][iphi][sign] = 0.;
etsum_barl_SM_[ieta][iphi_r][sign] = 0;
nBads_barl_SM_[ieta][iphi_r][sign] = 0;
epsilon_M_barl_SM_[ieta][iphi_r][sign] = 0;
}
}
etsumMean_barl_SM_[ieta] = 0.;
}
for (int ix = 0; ix < kEndcWedgesX; ix++) {
for (int iy = 0; iy < kEndcWedgesY; iy++) {
for (int sign = 0; sign < kSides; sign++) {
etsum_endc_[ix][iy][sign] = 0.;
nhits_endc_[ix][iy][sign] = 0;
esum_endc_[ix][iy][sign] = 0.;
}
}
}
readEtSums();
setupResidHistos();
}
void PhiSymmetryCalibration_step2_SM::endJob() {
if (firstpass_) {
edm::LogError("PhiSym") << "Must process at least one event-Exiting" << endl;
return;
}
// Here the real calculation of constants happens
// perform the area correction for endcap etsum
// NOT USED ANYMORE
/*
for (int ix=0; ix<kEndcWedgesX; ix++) {
for (int iy=0; iy<kEndcWedgesY; iy++) {
int ring = e_.endcapRing_[ix][iy];
if (ring!=-1) {
for (int sign=0; sign<kSides; sign++) {
etsum_endc_uncorr[ix][iy][sign] = etsum_endc_[ix][iy][sign];
etsum_endc_[ix][iy][sign]*=meanCellArea_[ring]/cellArea_[ix][iy];
}
}
}
}
*/
// ETsum histos, maps and other usefull histos (area,...)
// are filled and saved here
fillHistos();
// write ETsum mean for all rings
std::ofstream etsumMean_barl_out("etsumMean_barl.dat", ios::out);
for (int ieta = 0; ieta < kBarlRings; ieta++) {
etsumMean_barl_out << ieta << " " << etsumMean_barl_[ieta] << endl;
}
etsumMean_barl_out.close();
std::ofstream etsumMean_endc_out("etsumMean_endc.dat", ios::out);
for (int ring = 0; ring < kEndcEtaRings; ring++) {
etsumMean_endc_out << e_.cellPos_[ring][50].eta() << " " << etsumMean_endc_[ring] << endl;
}
etsumMean_endc_out.close();
// determine barrel calibration constants
for (int ieta = 0; ieta < kBarlRings; ieta++) {
for (int iphi = 0; iphi < kBarlWedges; iphi++) {
for (int sign = 0; sign < kSides; sign++) {
// sc
int iphi_r = int(iphi / nscx);
//if(nBads_barl_SM_[ieta][iphi_r][sign]>0){
// std::cout << "ETSUM" << etsum_barl_SM_[ieta][iphi_r][sign] << " " <<ieta << " " << iphi_r << " " << sign << " " << nBads_barl_SM_[ieta][iphi_r][sign]<< endl;
//}
float epsilon_T_SM = etsum_barl_SM_[ieta][iphi_r][sign] / etsumMean_barl_SM_[ieta] - 1.;
epsilon_M_barl_SM_[ieta][iphi_r][sign] = epsilon_T_SM / k_barl_[ieta];
if (e_.goodCell_barl[ieta][iphi][sign]) {
float etsum = etsum_barl_[ieta][iphi][sign];
float epsilon_T = (etsum / etsumMean_barl_[ieta]) - 1.;
rawconst_barl[ieta][iphi][sign] = epsilon_T + 1.;
epsilon_M_barl[ieta][iphi][sign] = epsilon_T / k_barl_[ieta];
} else {
rawconst_barl[ieta][iphi][sign] = 1.;
epsilon_M_barl[ieta][iphi][sign] = 0.;
} //if
} //sign
} //iphi
} //ieta
// determine endcap calibration constants
for (int ix = 0; ix < kEndcWedgesX; ix++) {
for (int iy = 0; iy < kEndcWedgesY; iy++) {
for (int sign = 0; sign < kSides; sign++) {
int ring = e_.endcapRing_[ix][iy];
if (ring != -1 && e_.goodCell_endc[ix][iy][sign]) {
float etsum = etsum_endc_[ix][iy][sign];
float epsilon_T = (etsum / etsumMean_endc_[ring]) - 1.;
rawconst_endc[ix][iy][sign] = epsilon_T + 1.;
epsilon_M_endc[ix][iy][sign] = epsilon_T / k_endc_[ring];
} else {
epsilon_M_endc[ix][iy][0] = 0.;
epsilon_M_endc[ix][iy][1] = 0.;
rawconst_endc[ix][iy][0] = 1.;
rawconst_endc[ix][iy][1] = 1.;
} //if
} //sign
} //iy
} //ix
// output sc calibration
std::fstream scfile("sccalibration.dat", std::ios::out);
for (int ieta = 0; ieta < kBarlRings; ++ieta) {
for (int iphi_r = 0; iphi_r < int(kBarlWedges / nscx); ++iphi_r) {
for (int sign = 0; sign < kSides; sign++) {
scfile << ieta << " " << iphi_r << " " << sign << " " << 1 / (1 + epsilon_M_barl_SM_[ieta][iphi_r][sign])
<< std::endl;
}
}
}
std::string newcalibfile("EcalIntercalibConstants_new.xml");
TFile ehistof("ehistos.root", "recreate");
TH1D ebhisto("eb", "eb", 100, 0., 2.);
std::vector<DetId>::const_iterator barrelIt = barrelCells.begin();
for (; barrelIt != barrelCells.end(); barrelIt++) {
EBDetId eb(*barrelIt);
int ieta = abs(eb.ieta()) - 1;
int iphi = eb.iphi() - 1;
int sign = eb.zside() > 0 ? 1 : 0;
/// this is the new constant, or better, the correction to be applied
/// to the old constant
newCalibs_[eb] = oldCalibs_[eb] / (1 + epsilon_M_barl[ieta][iphi][sign]);
if (e_.goodCell_barl[ieta][iphi][sign]) {
ebhisto.Fill(newCalibs_[eb]);
/// residual miscalibraition / expected precision
miscal_resid_barl_histos[ieta]->Fill(miscalib_[eb] * newCalibs_[eb]);
correl_barl_histos[ieta]->Fill(miscalib_[eb], newCalibs_[eb]);
}
} // barrelit
TH1D eehisto("ee", "ee", 100, 0., 2.);
std::vector<DetId>::const_iterator endcapIt = endcapCells.begin();
for (; endcapIt != endcapCells.end(); endcapIt++) {
EEDetId ee(*endcapIt);
int ix = ee.ix() - 1;
int iy = ee.iy() - 1;
int sign = ee.zside() > 0 ? 1 : 0;
newCalibs_[ee] = oldCalibs_[ee] / (1 + epsilon_M_endc[ix][iy][sign]);
if (e_.goodCell_endc[ix][iy][sign]) {
eehisto.Fill(newCalibs_[ee]);
miscal_resid_endc_histos[e_.endcapRing_[ix][iy]]->Fill(miscalib_[ee] * newCalibs_[ee]);
;
correl_endc_histos[e_.endcapRing_[ix][iy]]->Fill(miscalib_[ee], newCalibs_[ee]);
}
} //endcapit
// Write xml file
EcalCondHeader header;
header.method_ = "phi symmetry";
header.version_ = "0";
header.datasource_ = "testdata";
header.since_ = 1;
header.tag_ = "unknown";
header.date_ = "Mar 24 1973";
EcalIntercalibConstantsXMLTranslator::writeXML(newcalibfile, header, newCalibs_);
eehisto.Write();
ebhisto.Write();
ehistof.Close();
fillConstantsHistos();
outResidHistos();
}
void PhiSymmetryCalibration_step2_SM::fillConstantsHistos() {
TFile f("CalibHistos.root", "recreate");
TH2F barreletamap("barreletamap", "barreletamap", 171, -85, 86, 100, 0., 2.);
TH2F barreletamapraw("barreletamapraw", "barreletamapraw", 171, -85, 86, 100, 0., 2.);
TH2F barrelmapold("barrelmapold", "barrelmapold", 360, 1., 361., 171, -85., 86.);
TH2F barrelmapnew("barrelmapnew", "barrelmapnew", 360, 1., 361., 171, -85., 86.);
TH2F barrelmapratio("barrelmapratio", "barrelmapratio", 360, 1., 361., 171, -85., 86.);
TH1F rawconst_endc_h("rawconst_endc", "rawconst_endc", 100, 0., 2.);
TH1F const_endc_h("const_endc", "const_endc", 100, 0., 2.);
TH1F oldconst_endc_h("oldconst_endc", "oldconst_endc;oldCalib;", 200, 0, 2);
TH2F newvsraw_endc_h("newvsraw_endc", "newvsraw_endc;rawConst;newCalib", 200, 0, 2, 200, 0, 2);
TH2F endcapmapold_plus("endcapmapold_plus", "endcapmapold_plus", 100, 1., 101., 100, 1., 101.);
TH2F endcapmapnew_plus("endcapmapnew_plus", "endcapmapnew_plus", 100, 1., 101., 100, 1., 101.);
TH2F endcapmapratio_plus("endcapmapratio_plus", "endcapmapratio_plus", 100, 1., 101., 100, 1., 101.);
TH2F endcapmapold_minus("endcapmapold_minus", "endcapmapold_minus", 100, 1., 101., 100, 1., 101.);
TH2F endcapmapnew_minus("endcapmapnew_minus", "endcapmapnew_minus", 100, 1., 101., 100, 1., 101.);
TH2F endcapmapratio_minus("endcapmapratio_minus", "endcapmapratio_minus", 100, 1., 101., 100, 1., 101.);
for (int sign = 0; sign < kSides; sign++) {
int thesign = sign == 1 ? 1 : -1;
for (int ieta = 0; ieta < kBarlRings; ieta++) {
for (int iphi = 0; iphi < kBarlWedges; iphi++) {
if (e_.goodCell_barl[ieta][iphi][sign]) {
EBDetId eb(thesign * (ieta + 1), iphi + 1);
//int mod20= (iphi+1)%20;
//if (mod20==0 || mod20==1 ||mod20==2) continue; // exclude SM boundaries
barreletamap.Fill(ieta * thesign + thesign, newCalibs_[eb]);
barreletamapraw.Fill(ieta * thesign + thesign, rawconst_barl[ieta][iphi][sign]);
barrelmapold.Fill(iphi + 1, ieta * thesign + thesign, oldCalibs_[eb]);
barrelmapnew.Fill(iphi + 1, ieta * thesign + thesign, newCalibs_[eb]);
barrelmapratio.Fill(iphi + 1, ieta * thesign + thesign, newCalibs_[eb] / oldCalibs_[eb]);
} //if
} //iphi
} //ieta
for (int ix = 0; ix < kEndcWedgesX; ix++) {
for (int iy = 0; iy < kEndcWedgesY; iy++) {
if (e_.goodCell_endc[ix][iy][sign]) {
if (!EEDetId::validDetId(ix + 1, iy + 1, thesign))
continue;
EEDetId ee(ix + 1, iy + 1, thesign);
rawconst_endc_h.Fill(rawconst_endc[ix][iy][sign]);
const_endc_h.Fill(newCalibs_[ee]);
oldconst_endc_h.Fill(oldCalibs_[ee]);
newvsraw_endc_h.Fill(rawconst_endc[ix][iy][sign], newCalibs_[ee]);
if (sign == 1) {
endcapmapold_plus.Fill(ix + 1, iy + 1, oldCalibs_[ee]);
endcapmapnew_plus.Fill(ix + 1, iy + 1, newCalibs_[ee]);
endcapmapratio_plus.Fill(ix + 1, iy + 1, newCalibs_[ee] / oldCalibs_[ee]);
} else {
endcapmapold_minus.Fill(ix + 1, iy + 1, oldCalibs_[ee]);
endcapmapnew_minus.Fill(ix + 1, iy + 1, newCalibs_[ee]);
endcapmapratio_minus.Fill(ix + 1, iy + 1, newCalibs_[ee] / oldCalibs_[ee]);
}
} //if
} //iy
} //ix
} // sides
barreletamap.Write();
barreletamapraw.Write();
rawconst_endc_h.Write();
const_endc_h.Write();
oldconst_endc_h.Write();
newvsraw_endc_h.Write();
barrelmapold.Write();
barrelmapnew.Write();
barrelmapratio.Write();
endcapmapold_plus.Write();
endcapmapnew_plus.Write();
endcapmapratio_plus.Write();
endcapmapold_minus.Write();
endcapmapnew_minus.Write();
endcapmapratio_minus.Write();
f.Close();
}
//_____________________________________________________________________________
void PhiSymmetryCalibration_step2_SM::fillHistos() {
TFile f("PhiSymmetryCalibration.root", "recreate");
std::vector<TH1F*> etsum_barl_histos(kBarlRings);
std::vector<TH1F*> esum_barl_histos(kBarlRings);
// determine ranges of ET sums to get histo bounds and book histos (barrel)
for (int ieta = 0; ieta < kBarlRings; ieta++) {
float low = 999999.;
float high = 0.;
float low_e = 999999.;
float high_e = 0.;
for (int iphi = 0; iphi < kBarlWedges; iphi++) {
for (int sign = 0; sign < kSides; sign++) {
float etsum = etsum_barl_[ieta][iphi][sign];
if (etsum < low && etsum != 0.)
low = etsum;
if (etsum > high)
high = etsum;
float esum = esum_barl_[ieta][iphi][sign];
if (esum < low_e && esum != 0.)
low_e = esum;
if (esum > high_e)
high_e = esum;
}
}
ostringstream t;
t << "etsum_barl_" << ieta + 1;
etsum_barl_histos[ieta] = new TH1F(t.str().c_str(), "", 50, low - .2 * low, high + .1 * high);
t.str("");
t << "esum_barl_" << ieta + 1;
esum_barl_histos[ieta] = new TH1F(t.str().c_str(), "", 50, low_e - .2 * low_e, high_e + .1 * high_e);
t.str("");
// fill barrel ET sum histos
etsumMean_barl_[ieta] = 0.;
esumMean_barl_[ieta] = 0.;
for (int iphi = 0; iphi < kBarlWedges; iphi++) {
for (int sign = 0; sign < kSides; sign++) {
// mean for the SC
int iphi_r = int(iphi / nscx);
if (!(iphi % nscx)) {
// bad channel correction
etsum_barl_SM_[ieta][iphi_r][sign] =
etsum_barl_SM_[ieta][iphi_r][sign] * nscx / (nscx - nBads_barl_SM_[ieta][iphi_r][sign]);
// std::cout << "ETSUM M " << ieta << " " << iphi_r << " " <<
// sign << " " << etsum_barl_SM_[ieta][iphi_r][sign] << " " << nBads_barl_SM_[ieta][iphi_r][sign]<< endl;
etsumMean_barl_SM_[ieta] += etsum_barl_SM_[ieta][iphi_r][sign] / (2 * int(kBarlWedges / nscx));
}
if (e_.goodCell_barl[ieta][iphi][sign]) {
float etsum = etsum_barl_[ieta][iphi][sign];
float esum = esum_barl_[ieta][iphi][sign];
etsum_barl_histos[ieta]->Fill(etsum);
esum_barl_histos[ieta]->Fill(esum);
etsumMean_barl_[ieta] += etsum;
esumMean_barl_[ieta] += esum;
}
}
}
etsum_barl_histos[ieta]->Write();
esum_barl_histos[ieta]->Write();
etsumMean_barl_[ieta] /= (720. - e_.nBads_barl[ieta]);
esumMean_barl_[ieta] /= (720. - e_.nBads_barl[ieta]);
delete etsum_barl_histos[ieta];
delete esum_barl_histos[ieta]; //VS
}
std::vector<TH1F*> etsum_endc_histos(kEndcEtaRings);
std::vector<TH1F*> etsum_endc_uncorr_histos(kEndcEtaRings);
std::vector<TH1F*> esum_endc_histos(kEndcEtaRings);
std::vector<TH2F*> etsumvsarea_endc_histos(kEndcEtaRings);
std::vector<TH2F*> esumvsarea_endc_histos(kEndcEtaRings);
// determine ranges of ET sums to get histo bounds and book histos (endcap)
for (int ring = 0; ring < kEndcEtaRings; ring++) {
float low = FLT_MAX;
float low_uncorr = FLT_MAX;
float high = 0.;
float high_uncorr = 0;
float low_e = FLT_MAX;
float high_e = 0.;
float low_a = 1.;
float high_a = 0.;
for (int ix = 0; ix < kEndcWedgesX; ix++) {
for (int iy = 0; iy < kEndcWedgesY; iy++) {
if (e_.endcapRing_[ix][iy] == ring) {
for (int sign = 0; sign < kSides; sign++) {
float etsum = etsum_endc_[ix][iy][sign];
if (etsum < low && etsum != 0.)
low = etsum;
if (etsum > high)
high = etsum;
float etsum_uncorr = etsum_endc_uncorr[ix][iy][sign];
if (etsum_uncorr < low_uncorr && etsum_uncorr != 0.)
low_uncorr = etsum_uncorr;
if (etsum_uncorr > high_uncorr)
high_uncorr = etsum_uncorr;
float esum = esum_endc_[ix][iy][sign];
if (esum < low_e && esum != 0.)
low_e = esum;
if (esum > high_e)
high_e = esum;
float area = e_.cellArea_[ix][iy];
if (area < low_a)
low_a = area;
if (area > high_a)
high_a = area;
}
}
}
}
ostringstream t;
t << "etsum_endc_" << ring + 1;
etsum_endc_histos[ring] = new TH1F(t.str().c_str(), "", 50, low - .2 * low, high + .1 * high);
t.str("");
t << "etsum_endc_uncorr_" << ring + 1;
etsum_endc_uncorr_histos[ring] =
new TH1F(t.str().c_str(), "", 50, low_uncorr - .2 * low_uncorr, high_uncorr + .1 * high_uncorr);
t.str("");
t << "esum_endc_" << ring + 1;
esum_endc_histos[ring] = new TH1F(t.str().c_str(), "", 50, low_e - .2 * low_e, high_e + .1 * high_e);
t.str("");
t << "etsumvsarea_endc_" << ring + 1;
etsumvsarea_endc_histos[ring] =
new TH2F(t.str().c_str(), ";A_{#eta#phi};#Sigma E_{T}", 50, low_a, high_a, 50, low, high);
t.str("");
t << "esumvsarea_endc_" << ring + 1;
esumvsarea_endc_histos[ring] =
new TH2F(t.str().c_str(), ";A_{#eta#phi};#Sigma E", 50, low_a, high_a, 50, low_e, high_e);
t.str("");
// fill endcap ET sum histos
etsumMean_endc_[ring] = 0.;
esumMean_endc_[ring] = 0.;
for (int ix = 0; ix < kEndcWedgesX; ix++) {
for (int iy = 0; iy < kEndcWedgesY; iy++) {
if (e_.endcapRing_[ix][iy] == ring) {
for (int sign = 0; sign < kSides; sign++) {
if (e_.goodCell_endc[ix][iy][sign]) {
float etsum = etsum_endc_[ix][iy][sign];
float esum = esum_endc_[ix][iy][sign];
float etsum_uncorr = etsum_endc_uncorr[ix][iy][sign];
etsum_endc_histos[ring]->Fill(etsum);
etsum_endc_uncorr_histos[ring]->Fill(etsum_uncorr);
esum_endc_histos[ring]->Fill(esum);
float area = e_.cellArea_[ix][iy];
etsumvsarea_endc_histos[ring]->Fill(area, etsum);
esumvsarea_endc_histos[ring]->Fill(area, esum);
etsumMean_endc_[ring] += etsum;
esumMean_endc_[ring] += esum;
}
}
}
}
}
etsum_endc_histos[ring]->Write();
etsum_endc_uncorr_histos[ring]->Write();
esum_endc_histos[ring]->Write();
etsumMean_endc_[ring] /= (float(e_.nRing_[ring] * 2 - e_.nBads_endc[ring]));
esumMean_endc_[ring] /= (float(e_.nRing_[ring] * 2 - e_.nBads_endc[ring]));
etsumvsarea_endc_histos[ring]->Write();
esumvsarea_endc_histos[ring]->Write();
delete etsum_endc_histos[ring];
delete etsum_endc_uncorr_histos[ring];
delete esum_endc_histos[ring];
delete etsumvsarea_endc_histos[ring];
delete esumvsarea_endc_histos[ring];
} //ring
// Maps of etsum in EB and EE
TH2F barreletamap("barreletamap", "barreletamap", 171, -85, 86, 100, 0, 2);
TH2F barrelmap("barrelmap", "barrelmap - #frac{#Sigma E_{T}}{<#Sigma E_{T}>_{0}}", 360, 1, 360, 171, -85, 86);
TH2F barrelmap_e("barrelmape", "barrelmape - #frac{#Sigma E}{<#Sigma E>_{0}}", 360, 1, 360, 171, -85, 86);
TH2F barrelmap_divided("barrelmapdiv", "barrelmapdivided - #frac{#Sigma E_{T}}{hits}", 360, 1, 360, 171, -85, 86);
TH2F barrelmap_e_divided("barrelmapediv", "barrelmapedivided - #frac{#Sigma E}{hits}", 360, 1, 360, 171, -85, 86);
TH2F endcmap_plus_corr(
"endcapmapplus_corrected", "endcapmapplus - #frac{#Sigma E_{T}}{<#Sigma E_{T}>_{38}}", 100, 1, 101, 100, 1, 101);
TH2F endcmap_minus_corr(
"endcapmapminus_corrected", "endcapmapminus - #frac{#Sigma E_{T}}{<#Sigma E_{T}>_{38}}", 100, 1, 101, 100, 1, 101);
TH2F endcmap_plus_uncorr("endcapmapplus_uncorrected",
"endcapmapplus_uncor - #frac{#Sigma E_{T}}{<#Sigma E_{T}>_{38}}",
100,
1,
101,
100,
1,
101);
TH2F endcmap_minus_uncorr("endcapmapminus_uncorrected",
"endcapmapminus_uncor - #frac{#Sigma E_{T}}{<#Sigma E_{T}>_{38}}",
100,
1,
101,
100,
1,
101);
TH2F endcmap_e_plus("endcapmapeplus", "endcapmapeplus - #frac{#Sigma E}{<#Sigma E>_{38}}", 100, 1, 101, 100, 1, 101);
TH2F endcmap_e_minus(
"endcapmapeminus", "endcapmapeminus - #frac{#Sigma E}{<#Sigma E>_{38}}", 100, 1, 101, 100, 1, 101);
for (int sign = 0; sign < kSides; sign++) {
int thesign = sign == 1 ? 1 : -1;
for (int ieta = 0; ieta < kBarlRings; ieta++) {
for (int iphi = 0; iphi < kBarlWedges; iphi++) {
if (e_.goodCell_barl[ieta][iphi][sign]) {
barrelmap.Fill(iphi + 1, ieta * thesign + thesign, etsum_barl_[ieta][iphi][sign] / etsumMean_barl_[0]);
barrelmap_e.Fill(iphi + 1, ieta * thesign + thesign, esum_barl_[ieta][iphi][sign] / esumMean_barl_[0]); //VS
if (!nhits_barl_[ieta][iphi][sign])
nhits_barl_[ieta][iphi][sign] = 1;
barrelmap_divided.Fill(
iphi + 1, ieta * thesign + thesign, etsum_barl_[ieta][iphi][sign] / nhits_barl_[ieta][iphi][sign]);
barrelmap_e_divided.Fill(
iphi + 1, ieta * thesign + thesign, esum_barl_[ieta][iphi][sign] / nhits_barl_[ieta][iphi][sign]); //VS
//int mod20= (iphi+1)%20;
//if (mod20==0 || mod20==1 ||mod20==2) continue; // exclude SM boundaries
barreletamap.Fill(ieta * thesign + thesign, etsum_barl_[ieta][iphi][sign] / etsumMean_barl_[0]);
} //if
} //iphi
} //ieta
for (int ix = 0; ix < kEndcWedgesX; ix++) {
for (int iy = 0; iy < kEndcWedgesY; iy++) {
if (sign == 1) {
endcmap_plus_corr.Fill(ix + 1, iy + 1, etsum_endc_[ix][iy][sign] / etsumMean_endc_[38]);
endcmap_plus_uncorr.Fill(ix + 1, iy + 1, etsum_endc_uncorr[ix][iy][sign] / etsumMean_endc_[38]);
endcmap_e_plus.Fill(ix + 1, iy + 1, esum_endc_[ix][iy][sign] / esumMean_endc_[38]);
} else {
endcmap_minus_corr.Fill(ix + 1, iy + 1, etsum_endc_[ix][iy][sign] / etsumMean_endc_[38]);
endcmap_minus_uncorr.Fill(ix + 1, iy + 1, etsum_endc_uncorr[ix][iy][sign] / etsumMean_endc_[38]);
endcmap_e_minus.Fill(ix + 1, iy + 1, esum_endc_[ix][iy][sign] / esumMean_endc_[38]);
}
} //iy
} //ix
} //sign
barreletamap.Write();
barrelmap_divided.Write();
barrelmap.Write();
barrelmap_e_divided.Write();
barrelmap_e.Write();
endcmap_plus_corr.Write();
endcmap_minus_corr.Write();
endcmap_plus_uncorr.Write();
endcmap_minus_uncorr.Write();
endcmap_e_plus.Write();
endcmap_e_minus.Write();
vector<TH1F*> etavsphi_endc(kEndcEtaRings);
vector<TH1F*> areavsphi_endc(kEndcEtaRings);
vector<TH1F*> etsumvsphi_endcp_corr(kEndcEtaRings);
vector<TH1F*> etsumvsphi_endcm_corr(kEndcEtaRings);
vector<TH1F*> etsumvsphi_endcp_uncorr(kEndcEtaRings);
vector<TH1F*> etsumvsphi_endcm_uncorr(kEndcEtaRings);
vector<TH1F*> esumvsphi_endcp(kEndcEtaRings);
vector<TH1F*> esumvsphi_endcm(kEndcEtaRings);
std::vector<TH1F*> deltaeta_histos(kEndcEtaRings);
std::vector<TH1F*> deltaphi_histos(kEndcEtaRings);
for (int ring = 0; ring < kEndcEtaRings; ++ring) {
ostringstream t;
t << "etavsphi_endc_" << ring;
etavsphi_endc[ring] = new TH1F(t.str().c_str(), t.str().c_str(), e_.nRing_[ring], 0, e_.nRing_[ring]);
t.str("");
t << "areavsphi_endc_" << ring;
areavsphi_endc[ring] = new TH1F(t.str().c_str(), t.str().c_str(), e_.nRing_[ring], 0, e_.nRing_[ring]);
t.str("");
t << "etsumvsphi_endcp_corr_" << ring;
etsumvsphi_endcp_corr[ring] = new TH1F(t.str().c_str(), t.str().c_str(), e_.nRing_[ring], 0, e_.nRing_[ring]);
t.str("");
t << "etsumvsphi_endcm_corr_" << ring;
etsumvsphi_endcm_corr[ring] = new TH1F(t.str().c_str(), t.str().c_str(), e_.nRing_[ring], 0, e_.nRing_[ring]);
t.str("");
t << "etsumvsphi_endcp_uncorr_" << ring;
etsumvsphi_endcp_uncorr[ring] = new TH1F(t.str().c_str(), t.str().c_str(), e_.nRing_[ring], 0, e_.nRing_[ring]);
t.str("");
t << "etsumvsphi_endcm_uncorr_" << ring;
etsumvsphi_endcm_uncorr[ring] = new TH1F(t.str().c_str(), t.str().c_str(), e_.nRing_[ring], 0, e_.nRing_[ring]);
t.str("");
t << "esumvsphi_endcp_" << ring;
esumvsphi_endcp[ring] = new TH1F(t.str().c_str(), t.str().c_str(), e_.nRing_[ring], 0, e_.nRing_[ring]);
t.str("");
t << "esumvsphi_endcm_" << ring;
esumvsphi_endcm[ring] = new TH1F(t.str().c_str(), t.str().c_str(), e_.nRing_[ring], 0, e_.nRing_[ring]);
t.str("");
t << "deltaeta_" << ring;
deltaeta_histos[ring] = new TH1F(t.str().c_str(), "", 50, -.1, .1);
t.str("");
t << "deltaphi_" << ring;
deltaphi_histos[ring] = new TH1F(t.str().c_str(), "", 50, -.1, .1);
t.str("");
}
for (int ix = 0; ix < kEndcWedgesX; ix++) {
for (int iy = 0; iy < kEndcWedgesY; iy++) {
int ring = e_.endcapRing_[ix][iy];
if (ring != -1) {
int iphi_endc = -1;
for (int ip = 0; ip < e_.nRing_[ring]; ip++) {
if (e_.cellPhi_[ix][iy] == e_.phi_endc_[ip][ring])
iphi_endc = ip;
}
if (iphi_endc != -1) {
for (int sign = 0; sign < kSides; sign++) {
if (e_.goodCell_endc[ix][iy][sign]) {
if (sign == 1) {
etsumvsphi_endcp_corr[ring]->Fill(iphi_endc, etsum_endc_[ix][iy][sign]);
etsumvsphi_endcp_uncorr[ring]->Fill(iphi_endc, etsum_endc_uncorr[ix][iy][sign]);
esumvsphi_endcp[ring]->Fill(iphi_endc, esum_endc_[ix][iy][sign]);
} else {
etsumvsphi_endcm_corr[ring]->Fill(iphi_endc, etsum_endc_[ix][iy][sign]);
etsumvsphi_endcm_uncorr[ring]->Fill(iphi_endc, etsum_endc_uncorr[ix][iy][sign]);
esumvsphi_endcm[ring]->Fill(iphi_endc, esum_endc_[ix][iy][sign]);
}
} //if
} //sign
etavsphi_endc[ring]->Fill(iphi_endc, e_.cellPos_[ix][iy].eta());
areavsphi_endc[ring]->Fill(iphi_endc, e_.cellArea_[ix][iy]);
} //if iphi_endc
} //if ring
} //iy
} //ix
for (int ring = 0; ring < kEndcEtaRings; ++ring) {
etavsphi_endc[ring]->Write();
areavsphi_endc[ring]->Write();
etsumvsphi_endcp_corr[ring]->Write();
etsumvsphi_endcm_corr[ring]->Write();
etsumvsphi_endcp_uncorr[ring]->Write();
etsumvsphi_endcm_uncorr[ring]->Write();
esumvsphi_endcp[ring]->Write();
esumvsphi_endcm[ring]->Write();
deltaeta_histos[ring]->Write();
deltaphi_histos[ring]->Write();
delete etsumvsphi_endcp_corr[ring];
delete etsumvsphi_endcm_corr[ring];
delete etsumvsphi_endcp_uncorr[ring];
delete etsumvsphi_endcm_uncorr[ring];
delete etavsphi_endc[ring];
delete areavsphi_endc[ring];
delete esumvsphi_endcp[ring];
delete esumvsphi_endcm[ring];
delete deltaeta_histos[ring];
delete deltaphi_histos[ring];
}
f.Close();
}
void PhiSymmetryCalibration_step2_SM::readEtSums() {
//read in ET sums
int ieta, iphi, sign, ix, iy, dummy;
double etsum;
unsigned int nhits;
std::ifstream etsum_barl_in("etsum_barl.dat", ios::in);
while (etsum_barl_in >> dummy >> ieta >> iphi >> sign >> etsum >> nhits) {
etsum_barl_[ieta][iphi][sign] += etsum;
nhits_barl_[ieta][iphi][sign] += nhits;
// fill etsums for the SM calibration
int iphi_r = int(iphi / nscx);
etsum_barl_SM_[ieta][iphi_r][sign] += etsum;
// etsum*nscx/(nscx- nBads_barl_SM_[ieta][iphi_r][sign]);
// if(nBads_barl_SM_[ieta][iphi_r][sign]>0){
// std::cout << "ETSUM" << etsum_barl_SM_[ieta][iphi_r][sign] << " " << nscx << " " << nBads_barl_SM_[ieta][iphi_r][sign]<< endl;
// }
}
std::ifstream etsum_endc_in("etsum_endc.dat", ios::in);
while (etsum_endc_in >> dummy >> ix >> iy >> sign >> etsum >> nhits >> dummy) {
etsum_endc_[ix][iy][sign] += etsum;
nhits_endc_[ix][iy][sign] += nhits;
}
std::ifstream k_barl_in("k_barl.dat", ios::in);
for (int ieta = 0; ieta < kBarlRings; ieta++) {
k_barl_in >> dummy >> k_barl_[ieta];
}
std::ifstream k_endc_in("k_endc.dat", ios::in);
for (int ring = 0; ring < kEndcEtaRings; ring++) {
k_endc_in >> dummy >> k_endc_[ring];
}
}
void PhiSymmetryCalibration_step2_SM::setupResidHistos() {
miscal_resid_barl_histos.resize(kBarlRings);
correl_barl_histos.resize(kBarlRings);
for (int ieta = 0; ieta < kBarlRings; ieta++) {
ostringstream t1;
t1 << "mr_barl_" << ieta + 1;
miscal_resid_barl_histos[ieta] = new TH1F(t1.str().c_str(), "", 100, 0., 2.);
ostringstream t2;
t2 << "co_barl_" << ieta + 1;
correl_barl_histos[ieta] = new TH2F(t2.str().c_str(), "", 50, .5, 1.5, 50, .5, 1.5);
}
miscal_resid_endc_histos.resize(kEndcEtaRings);
correl_endc_histos.resize(kEndcEtaRings);
for (int ring = 0; ring < kEndcEtaRings; ring++) {
ostringstream t1;
t1 << "mr_endc_" << ring + 1;
miscal_resid_endc_histos[ring] = new TH1F(t1.str().c_str(), "", 100, 0., 2.);
ostringstream t2;
t2 << "co_endc_" << ring + 1;
correl_endc_histos[ring] = new TH2F(t2.str().c_str(), "", 50, .5, 1.5, 50, .5, 1.5);
}
}
void PhiSymmetryCalibration_step2_SM::outResidHistos() {
// output histograms of residual miscalibrations
TFile f("PhiSymmetryCalibration_miscal_resid.root", "recreate");
for (int ieta = 0; ieta < 85; ieta++) {
miscal_resid_barl_histos[ieta]->Write();
correl_barl_histos[ieta]->Write();
delete miscal_resid_barl_histos[ieta];
delete correl_barl_histos[ieta];
}
for (int ring = 0; ring < 39; ring++) {
miscal_resid_endc_histos[ring]->Write();
correl_endc_histos[ring]->Write();
delete miscal_resid_endc_histos[ring];
delete correl_endc_histos[ring];
}
f.Close();
}
| 37.287037 | 171 | 0.603861 | malbouis |
412fb0da32010ac304b12e1c9e108af3a73bd05f | 614 | cpp | C++ | src/core/p_render/render_graph/resources/RenderResource.cpp | jabronicus/P-Engine | 7786c2f97d19bd2913b706f6afe5087a392b1a3c | [
"MIT"
] | null | null | null | src/core/p_render/render_graph/resources/RenderResource.cpp | jabronicus/P-Engine | 7786c2f97d19bd2913b706f6afe5087a392b1a3c | [
"MIT"
] | null | null | null | src/core/p_render/render_graph/resources/RenderResource.cpp | jabronicus/P-Engine | 7786c2f97d19bd2913b706f6afe5087a392b1a3c | [
"MIT"
] | 1 | 2021-08-24T05:43:01.000Z | 2021-08-24T05:43:01.000Z | #include "../../../../../include/core/p_render/render_graph/resources/RenderResource.hpp"
RenderResource::RenderResource(RenderResource::Type type, unsigned int index, const std::string &name) : _type(type), _index(index), _name(name) {
}
void RenderResource::addWritePass(unsigned int index) {
_writePasses.insert(index);
}
void RenderResource::addReadPass(unsigned int index) {
_readPasses.insert(index);
}
std::unordered_set<unsigned int> &RenderResource::getWritePasses() {
return _writePasses;
}
std::unordered_set<unsigned int> &RenderResource::getReadPasses() {
return _readPasses;
}
| 26.695652 | 146 | 0.7443 | jabronicus |
41372fe5a4e67928b8a773b3b884581435962b33 | 593 | cpp | C++ | kernel/acpi.cpp | Ampferl/jonix | 75dc24187b96eb50f210b4362775c04b77844946 | [
"MIT"
] | 7 | 2021-03-23T16:45:41.000Z | 2022-01-04T16:26:56.000Z | kernel/acpi.cpp | Ampferl/jonix | 75dc24187b96eb50f210b4362775c04b77844946 | [
"MIT"
] | 5 | 2021-03-29T07:09:43.000Z | 2021-07-23T22:47:58.000Z | kernel/acpi.cpp | Ampferl/jonix | 75dc24187b96eb50f210b4362775c04b77844946 | [
"MIT"
] | 4 | 2021-06-25T17:25:45.000Z | 2021-07-23T13:05:25.000Z | #include "acpi.h"
namespace ACPI{
void* FindTable(SDTHeader* sdtHeader, char* signature){
int entries = (sdtHeader->Length - sizeof(ACPI::SDTHeader)) / 8;
for (int t = 0; t < entries; ++t) {
ACPI::SDTHeader* newSDTHeader = (ACPI::SDTHeader*)*(uint64_t*)((uint64_t)sdtHeader + sizeof(ACPI::SDTHeader) + (t * 8));
for (int i = 0; i < 4; ++i) {
if(newSDTHeader->Signature[i] != signature[i]){
break;
}
if(i==3)return newSDTHeader;
}
}
return 0;
}
}
| 29.65 | 132 | 0.495784 | Ampferl |
413d48a314dc18b7193703204631fa31c7cdc522 | 3,838 | cpp | C++ | Project2/Project2_Grose.cpp | bgrose/CSCE-240-Adv-Programming-Tech | c7bbd574ef09d2714c1459561fd68ee7bee52ff0 | [
"MIT"
] | 1 | 2020-12-29T03:59:53.000Z | 2020-12-29T03:59:53.000Z | Project2/Project2_Grose.cpp | bgrose/F20CSCE240 | c7bbd574ef09d2714c1459561fd68ee7bee52ff0 | [
"MIT"
] | null | null | null | Project2/Project2_Grose.cpp | bgrose/F20CSCE240 | c7bbd574ef09d2714c1459561fd68ee7bee52ff0 | [
"MIT"
] | null | null | null | /*
* @author Written By Bradley Grose
* @date Completed On 9/9/2020 at 8:01PM
* @summary This code must be able to take in 10 values and
* fill an array with those values. Then it will run using
* Bubble Sort in which it will sort it in increasing order.
* Then there is also a search function that searches for the
* index of a sent in value in the array. There is a print
* function that prints out each element with a space between.
* @input The user must input 10 individual integer values when prompted
* by the terminal
* @output The output will be the unsorted array, followed by the sorted
* array in increasing order. Then it will search for the value 1 and
* print out where it is found, if not, it will print out a not found message.
* Then it does the same thing for 99
* The format for array print out is a space between each element.
* @other I added a sort function using call by reference to do the swap for bubble sort
*/
#include <cstdlib>
#include <iostream>
using namespace std;
//Class Definition
void mySort(int arr[], int size);
int search(int arr[], int size, int element);
void readData(int arr[], int size);
void printData(int arr[], int size);
void swap(int *left, int *right);
//Main method provided by instructor
int main(int argc, char **argv) {
int data[10] = {0};
readData(data, 10);
printData(data, 10);
mySort(data, 10);
printData(data, 10);
int indexFound = -999;
indexFound = search(data, 10, 1);
if (indexFound != -1) {
cout << "The number 1 was found at index: " << indexFound << endl;
} else {
cout << "The number 1 was not found" << endl;
}
indexFound = search(data, 10, 99);
if (indexFound != -1) {
cout << "The number 99 was found at index: " << indexFound << endl;
} else {
cout << "The number 99 was not found" << endl;
}
return 0;
}
/* @summary Uses bubble sort to sort the array in increasing order
* @param int arr[] - Array of Values
* @param int size - Size of Array
* @return None
*/
void mySort(int arr[], int size) {
for (int i = 0; i < size - 1; i++)
for (int j = 0; j < size - 1; j++)
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}
/* @summary Searches for a given value in the array and returns the location
* @param int arr[] - Array of Values
* @param int size - Size of Array
* @param int element - Element to search for
* @return Index of Element or -1 if not found
*/
int search(int arr[], int size, int element) {
for (int i = 0; i < size - 1; i++) {
if (arr[i] == element) {
return i;
}
}
return -1;
}
/* @summary This will have the user input 10 values
* @param int arr[] - Array of Values
* @param int size - Size of Array
* @return None.
*/
void readData(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << "Enter Element " << i + 1 << " of " << size << "\t";
cin >> arr[i];
}
}
/* @summary Prints out the array with a space inbetween each value
* @param int arr[] - Array of Values
* @param int size - Size of Array
* @return None.
*/
void printData(int arr[], int size) {
cout << "\n";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << "\n";
}
/* @summary Swaps value for Bubble Sort
* @param int *low - Value from lower index
* @param int *high - Value from higher index
* @return None.
*/
void swap(int *low, int *high) {
int temp = *low;
*low = *high;
*high = temp;
}
| 29.984375 | 94 | 0.569046 | bgrose |
4140d8757a6bae49932641324d7467c1ec2dfab2 | 25,315 | cpp | C++ | inference-engine/tests/functional/inference_engine/ngraph_reader/broadcast_tests.cpp | anton-potapov/openvino | 84119afe9a8c965e0a0cd920fff53aee67b05108 | [
"Apache-2.0"
] | 2 | 2020-11-18T14:14:06.000Z | 2020-11-28T04:55:57.000Z | inference-engine/tests/functional/inference_engine/ngraph_reader/broadcast_tests.cpp | anton-potapov/openvino | 84119afe9a8c965e0a0cd920fff53aee67b05108 | [
"Apache-2.0"
] | 30 | 2020-11-13T11:44:07.000Z | 2022-02-21T13:03:16.000Z | inference-engine/tests/functional/inference_engine/ngraph_reader/broadcast_tests.cpp | anton-potapov/openvino | 84119afe9a8c965e0a0cd920fff53aee67b05108 | [
"Apache-2.0"
] | 3 | 2021-03-09T08:27:29.000Z | 2021-04-07T04:58:54.000Z | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <string>
#include "ngraph_reader_tests.hpp"
TEST_F(NGraphReaderTests, ConvertBroadcastToTiles1) {
std::string model = R"V0G0N(
<net name="Network" version="10">
<layers>
<layer id="14" name="data" type="Parameter" version="opset1">
<data element_type="f32" shape="112,1"/>
<output>
<port id="1" precision="FP32">
<dim>112</dim>
<dim>1</dim>
</port>
</output>
</layer>
<layer id="15" name="broadcast1_shape" type="Const" version="opset1">
<data offset="256" size="32"/>
<output>
<port id="1" precision="I64">
<dim>4</dim>
</port>
</output>
</layer>
<layer id="17" name="broadcast_1" type="Broadcast" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>112</dim>
<dim>1</dim>
</port>
<port id="1" precision="I64">
<dim>4</dim>
</port>
</input>
<output>
<port id="3" precision="FP32">
<dim>1</dim>
<dim>64</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</output>
</layer>
<layer id="6" name="output" type="Result" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>1</dim>
<dim>64</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</input>
</layer>
</layers>
<edges>
<edge from-layer="14" from-port="1" to-layer="17" to-port="0"/>
<edge from-layer="15" from-port="1" to-layer="17" to-port="1"/>
<edge from-layer="17" from-port="3" to-layer="6" to-port="0"/>
</edges>
</net>
)V0G0N";
std::string modelV5 = R"V0G0N(
<net name="Network" version="5" precision="FP32" batch="1">
<layers>
<layer id="0" name="data" precision="FP32" type="Input">
<output>
<port id="0">
<dim>112</dim>
<dim>1</dim>
</port>
</output>
</layer>
<layer id="1" name="Constant_107" precision="I64" type="Const">
<output>
<port id="0">
<dim>4</dim>
</port>
</output>
<blobs>
<custom offset="0" size="32"/>
</blobs>
</layer>
<layer id="2" name="DynReshape_108" precision="FP32" type="Reshape">
<data originalLayersNames="broadcast_1"/>
<input>
<port id="0">
<dim>112</dim>
<dim>1</dim>
</port>
<port id="1">
<dim>4</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>1</dim>
<dim>112</dim>
<dim>1</dim>
</port>
</output>
</layer>
<layer id="3" name="broadcast_1:" precision="FP32" type="Tile">
<data axis="3" tiles="112" originalLayersNames="broadcast_1"/>
<input>
<port id="0">
<dim>1</dim>
<dim>1</dim>
<dim>112</dim>
<dim>1</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>1</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</output>
</layer>
<layer id="4" name="broadcast_1" precision="FP32" type="Tile">
<data axis="1" tiles="64"/>
<input>
<port id="0">
<dim>1</dim>
<dim>1</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>64</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</output>
</layer>
</layers>
<edges>
<edge from-layer="0" from-port="0" to-layer="2" to-port="0"/>
<edge from-layer="1" from-port="0" to-layer="2" to-port="1"/>
<edge from-layer="2" from-port="3" to-layer="3" to-port="0"/>
<edge from-layer="3" from-port="3" to-layer="4" to-port="0"/>
</edges>
</net>
)V0G0N";
compareIRs(model, modelV5, 6422528, [](Blob::Ptr& weights) {
auto * broadcast1_shape = reinterpret_cast<int64_t *>(weights->buffer().as<int8_t*>() + 256);
broadcast1_shape[0] = 1;
broadcast1_shape[1] = 64;
broadcast1_shape[2] = 112;
broadcast1_shape[3] = 112;
});
}
TEST_F(NGraphReaderTests, ConvertBroadcastToTiles2) {
std::string model = R"V0G0N(
<net name="Network" version="10">
<layers>
<layer id="14" name="data" type="Parameter" version="opset1">
<data element_type="f32" shape="1"/>
<output>
<port id="1" precision="FP32">
<dim>1</dim>
</port>
</output>
</layer>
<layer id="15" name="broadcast1_shape" type="Const" version="opset1">
<data offset="256" size="32"/>
<output>
<port id="1" precision="I64">
<dim>4</dim>
</port>
</output>
</layer>
<layer id="17" name="broadcast_1" type="Broadcast" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>1</dim>
</port>
<port id="1" precision="I64">
<dim>4</dim>
</port>
<port id="2" precision="I64">
<dim>4</dim>
</port>
</input>
<output>
<port id="3" precision="FP32">
<dim>1</dim>
<dim>64</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</output>
</layer>
<layer id="6" name="output" type="Result" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>1</dim>
<dim>64</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</input>
</layer>
</layers>
<edges>
<edge from-layer="14" from-port="1" to-layer="17" to-port="0"/>
<edge from-layer="15" from-port="1" to-layer="17" to-port="1"/>
<edge from-layer="17" from-port="3" to-layer="6" to-port="0"/>
</edges>
</net>
)V0G0N";
std::string modelV5 = R"V0G0N(
<net name="Network" version="5" precision="FP32" batch="1">
<layers>
<layer id="0" name="data" precision="FP32" type="Input">
<output>
<port id="0">
<dim>1</dim>
</port>
</output>
</layer>
<layer id="1" name="Constant_107" precision="I64" type="Const">
<output>
<port id="0">
<dim>4</dim>
</port>
</output>
<blobs>
<custom offset="0" size="32"/>
</blobs>
</layer>
<layer id="2" name="DynReshape_108" precision="FP32" type="Reshape">
<data originalLayersNames="broadcast_1"/>
<input>
<port id="0">
<dim>1</dim>
</port>
<port id="1">
<dim>4</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>1</dim>
<dim>1</dim>
<dim>1</dim>
</port>
</output>
</layer>
<layer id="3" name="broadcast_1:" precision="FP32" type="Tile">
<data axis="3" tiles="112" originalLayersNames="broadcast_1"/>
<input>
<port id="0">
<dim>1</dim>
<dim>1</dim>
<dim>1</dim>
<dim>1</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>1</dim>
<dim>1</dim>
<dim>112</dim>
</port>
</output>
</layer>
<layer id="4" name="broadcast_1:_3" precision="FP32" type="Tile">
<data axis="2" tiles="112" originalLayersNames="broadcast_1"/>
<input>
<port id="0">
<dim>1</dim>
<dim>1</dim>
<dim>1</dim>
<dim>112</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>1</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</output>
</layer>
<layer id="5" name="broadcast_1" precision="FP32" type="Tile">
<data axis="1" tiles="64"/>
<input>
<port id="0">
<dim>1</dim>
<dim>1</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>64</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</output>
</layer>
</layers>
<edges>
<edge from-layer="0" from-port="0" to-layer="2" to-port="0"/>
<edge from-layer="1" from-port="0" to-layer="2" to-port="1"/>
<edge from-layer="2" from-port="3" to-layer="3" to-port="0"/>
<edge from-layer="3" from-port="3" to-layer="4" to-port="0"/>
<edge from-layer="4" from-port="3" to-layer="5" to-port="0"/>
</edges>
</net>
)V0G0N";
compareIRs(model, modelV5, 6422528, [](Blob::Ptr& weights) {
auto * broadcast1_shape = reinterpret_cast<int64_t *>(weights->buffer().as<int8_t*>() + 256);
broadcast1_shape[0] = 1;
broadcast1_shape[1] = 64;
broadcast1_shape[2] = 112;
broadcast1_shape[3] = 112;
});
}
TEST_F(NGraphReaderTests, ConvertBroadcastToTiles3) {
std::string model = R"V0G0N(
<net name="Network" version="10">
<layers>
<layer id="14" name="data" type="Parameter" version="opset1">
<data element_type="f32" shape="1,64,1,112"/>
<output>
<port id="1" precision="FP32">
<dim>1</dim>
<dim>64</dim>
<dim>1</dim>
<dim>112</dim>
</port>
</output>
</layer>
<layer id="15" name="broadcast1_shape" type="Const" version="opset1">
<data offset="256" size="32"/>
<output>
<port id="1" precision="I64">
<dim>4</dim>
</port>
</output>
</layer>
<layer id="17" name="broadcast_1" type="Broadcast" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>1</dim>
<dim>64</dim>
<dim>1</dim>
<dim>112</dim>
</port>
<port id="1" precision="I64">
<dim>4</dim>
</port>
<port id="2" precision="I64">
<dim>4</dim>
</port>
</input>
<output>
<port id="3" precision="FP32">
<dim>1</dim>
<dim>64</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</output>
</layer>
<layer id="6" name="output" type="Result" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>1</dim>
<dim>64</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</input>
</layer>
</layers>
<edges>
<edge from-layer="14" from-port="1" to-layer="17" to-port="0"/>
<edge from-layer="15" from-port="1" to-layer="17" to-port="1"/>
<edge from-layer="17" from-port="3" to-layer="6" to-port="0"/>
</edges>
</net>
)V0G0N";
std::string modelV5 = R"V0G0N(
<net name="Network" version="5" precision="FP32" batch="1">
<layers>
<layer id="0" name="data" precision="FP32" type="Input">
<output>
<port id="0">
<dim>1</dim>
<dim>64</dim>
<dim>1</dim>
<dim>112</dim>
</port>
</output>
</layer>
<layer id="3" name="broadcast_1" precision="FP32" type="Tile">
<data axis="2" tiles="112"/>
<input>
<port id="0">
<dim>1</dim>
<dim>64</dim>
<dim>1</dim>
<dim>112</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>64</dim>
<dim>112</dim>
<dim>112</dim>
</port>
</output>
</layer>
</layers>
<edges>
<edge from-layer="0" from-port="0" to-layer="3" to-port="0"/>
</edges>
</net>
)V0G0N";
compareIRs(model, modelV5, 6422528, [](Blob::Ptr& weights) {
auto * broadcast1_shape = reinterpret_cast<int64_t *>(weights->buffer().as<uint8_t *>() + 256);
broadcast1_shape[0] = 1;
broadcast1_shape[1] = 64;
broadcast1_shape[2] = 112;
broadcast1_shape[3] = 112;
});
}
TEST_F(NGraphReaderTests, ConvertBroadcastToTiles4) {
std::string model = R"V0G0N(
<net name="Network" version="10">
<layers>
<layer id="14" name="data" type="Parameter" version="opset1">
<data element_type="f32" shape="3,64"/>
<output>
<port id="1" precision="FP32">
<dim>3</dim>
<dim>64</dim>
</port>
</output>
</layer>
<layer id="15" name="broadcast1_shape" type="Const" version="opset1">
<data offset="256" size="32"/>
<output>
<port id="1" precision="I64">
<dim>4</dim>
</port>
</output>
</layer>
<layer id="16" name="broadcast1_axes" type="Const" version="opset1">
<data offset="288" size="16"/>
<output>
<port id="1" precision="I64">
<dim>2</dim>
</port>
</output>
</layer>
<layer id="17" name="broadcast_1" type="Broadcast" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>3</dim>
<dim>64</dim>
</port>
<port id="1" precision="I64">
<dim>4</dim>
</port>
<port id="2" precision="I64">
<dim>2</dim>
</port>
</input>
<output>
<port id="3" precision="FP32">
<dim>1</dim>
<dim>3</dim>
<dim>64</dim>
<dim>64</dim>
</port>
</output>
</layer>
<layer id="6" name="output" type="Result" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>1</dim>
<dim>3</dim>
<dim>64</dim>
<dim>64</dim>
</port>
</input>
</layer>
</layers>
<edges>
<edge from-layer="14" from-port="1" to-layer="17" to-port="0"/>
<edge from-layer="15" from-port="1" to-layer="17" to-port="1"/>
<edge from-layer="16" from-port="1" to-layer="17" to-port="2"/>
<edge from-layer="17" from-port="3" to-layer="6" to-port="0"/>
</edges>
</net>
)V0G0N";
std::string modelV5 = R"V0G0N(
<net name="Network" version="5" precision="FP32" batch="1">
<layers>
<layer id="0" name="data" precision="FP32" type="Input">
<output>
<port id="0">
<dim>3</dim>
<dim>64</dim>
</port>
</output>
</layer>
<layer id="1" name="Constant_107" precision="I64" type="Const">
<output>
<port id="0">
<dim>4</dim>
</port>
</output>
<blobs>
<custom offset="0" size="32"/>
</blobs>
</layer>
<layer id="2" name="DynReshape_108" precision="FP32" type="Reshape">
<data originalLayersNames="broadcast_1"/>
<input>
<port id="0">
<dim>3</dim>
<dim>64</dim>
</port>
<port id="1">
<dim>4</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>3</dim>
<dim>64</dim>
<dim>1</dim>
</port>
</output>
</layer>
<layer id="3" name="broadcast_1" precision="FP32" type="Tile">
<data axis="3" tiles="64"/>
<input>
<port id="0">
<dim>1</dim>
<dim>3</dim>
<dim>64</dim>
<dim>1</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>3</dim>
<dim>64</dim>
<dim>64</dim>
</port>
</output>
</layer>
</layers>
<edges>
<edge from-layer="0" from-port="0" to-layer="2" to-port="0"/>
<edge from-layer="1" from-port="0" to-layer="2" to-port="1"/>
<edge from-layer="2" from-port="3" to-layer="3" to-port="0"/>
</edges>
</net>
)V0G0N";
compareIRs(model, modelV5, 6422528, [](Blob::Ptr& weights) {
auto * broadcast1_shape = reinterpret_cast<int64_t *>(weights->buffer().as<int8_t*>() + 256);
broadcast1_shape[0] = 1;
broadcast1_shape[1] = 3;
broadcast1_shape[2] = 64;
broadcast1_shape[3] = 64;
broadcast1_shape[4] = 1;
broadcast1_shape[5] = 2;
});
}
TEST_F(NGraphReaderTests, DISABLED_ConvertBroadcastToTiles5) {
std::string model = R"V0G0N(
<net name="Network" version="10">
<layers>
<layer id="14" name="data" type="Parameter" version="opset1">
<output>
<port id="1" precision="FP32">
<dim>1</dim>
<dim>64</dim>
</port>
</output>
</layer>
<layer id="15" name="broadcast1_shape" type="Const" version="opset1">
<data offset="256" size="32"/>
<output>
<port id="1" precision="I64">
<dim>4</dim>
</port>
</output>
</layer>
<layer id="16" name="broadcast1_axes" type="Const" version="opset1">
<data offset="288" size="16"/>
<output>
<port id="1" precision="I64">
<dim>2</dim>
</port>
</output>
</layer>
<layer id="17" name="broadcast_1" type="Broadcast" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>1</dim>
<dim>64</dim>
</port>
<port id="1" precision="I64">
<dim>4</dim>
</port>
<port id="2" precision="I64">
<dim>2</dim>
</port>
</input>
<output>
<port id="3" precision="FP32">
<dim>1</dim>
<dim>3</dim>
<dim>64</dim>
<dim>64</dim>
</port>
</output>
</layer>
<layer id="6" name="output" type="Result" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>1</dim>
<dim>3</dim>
<dim>64</dim>
<dim>64</dim>
</port>
</input>
</layer>
</layers>
<edges>
<edge from-layer="14" from-port="1" to-layer="17" to-port="0"/>
<edge from-layer="15" from-port="1" to-layer="17" to-port="1"/>
<edge from-layer="16" from-port="1" to-layer="17" to-port="2"/>
<edge from-layer="17" from-port="3" to-layer="6" to-port="0"/>
</edges>
</net>
)V0G0N";
std::string modelV5 = R"V0G0N(
<net name="Network" version="5" precision="FP32" batch="1">
<layers>
<layer id="0" name="data" precision="FP32" type="Input">
<output>
<port id="0">
<dim>1</dim>
<dim>64</dim>
</port>
</output>
</layer>
<layer id="1" name="Constant_107" precision="I64" type="Const">
<output>
<port id="0">
<dim>4</dim>
</port>
</output>
<blobs>
<custom offset="0" size="32"/>
</blobs>
</layer>
<layer id="2" name="DynReshape_108" precision="FP32" type="Reshape">
<input>
<port id="0">
<dim>1</dim>
<dim>64</dim>
</port>
<port id="1">
<dim>4</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>1</dim>
<dim>64</dim>
<dim>1</dim>
</port>
</output>
</layer>
<layer id="3" name="broadcast_1" precision="FP32" type="Tile">
<data axis="3" tiles="64"/>
<input>
<port id="0">
<dim>1</dim>
<dim>1</dim>
<dim>64</dim>
<dim>1</dim>
</port>
</input>
<output>
<port id="1">
<dim>1</dim>
<dim>1</dim>
<dim>64</dim>
<dim>64</dim>
</port>
</output>
</layer>
<layer id="4" name="broadcast_2" precision="FP32" type="Tile">
<data axis="1" tiles="3"/>
<input>
<port id="0">
<dim>1</dim>
<dim>1</dim>
<dim>64</dim>
<dim>64</dim>
</port>
</input>
<output>
<port id="3">
<dim>1</dim>
<dim>3</dim>
<dim>64</dim>
<dim>64</dim>
</port>
</output>
</layer>
</layers>
<edges>
<edge from-layer="0" from-port="0" to-layer="2" to-port="0"/>
<edge from-layer="1" from-port="0" to-layer="2" to-port="1"/>
<edge from-layer="2" from-port="3" to-layer="3" to-port="0"/>
<edge from-layer="3" from-port="1" to-layer="4" to-port="0"/>
</edges>
</net>
)V0G0N";
compareIRs(model, modelV5, 6422528, [](Blob::Ptr& weights) {
auto * broadcast1_shape = reinterpret_cast<int64_t *>(weights->buffer().as<int8_t*>() + 256);
broadcast1_shape[0] = 1;
broadcast1_shape[1] = 3;
broadcast1_shape[2] = 64;
broadcast1_shape[3] = 64;
broadcast1_shape[4] = 1;
broadcast1_shape[5] = 2;
});
}
| 32.876623 | 111 | 0.389097 | anton-potapov |
41414d92ca07f20708af91887577b26290a9df36 | 1,161 | cpp | C++ | willow/src/popx/op/detachx.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | willow/src/popx/op/detachx.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | willow/src/popx/op/detachx.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2021 Graphcore Ltd. All rights reserved.
#include <popart/names.hpp>
#include <popart/op/detach.hpp>
#include <popart/popx/op/detachx.hpp>
#include <popart/popx/opxmanager.hpp>
namespace popart {
namespace popx {
DetachOpx::DetachOpx(popart::Op *op, popart::popx::Devicex *devicex)
: popart::popx::ElementWiseUnaryOpx(op, devicex) {
verifyOp<DetachOp>(op, Onnx::CustomOperators::Detach_1);
}
void DetachOpx::grow(snap::program::Sequence &prog) const {
auto input = getInTensor(DetachOp::getInIndex());
auto output = cloneNcopy(prog, input);
setOutTensor(DetachOp::getOutIndex(), output);
}
DetachInplaceOpx::DetachInplaceOpx(Op *op, Devicex *devicex)
: popart::popx::ElementWiseUnaryOpx(op, devicex) {
verifyOp<DetachInplaceOp>(op);
}
void DetachInplaceOpx::grow(snap::program::Sequence &) const {
setOutTensor(DetachOp::getOutIndex(), getInTensor(DetachOp::getInIndex()));
}
namespace {
OpxCreator<DetachOpx> detachOpxCreator(Onnx::CustomOperators::Detach_1);
OpxCreator<DetachInplaceOpx>
detachInplaceOpxCreator(Onnx::CustomOperators::DetachInplace);
} // namespace
} // namespace popx
} // namespace popart
| 28.317073 | 77 | 0.748493 | gglin001 |
4142a30226da6ff8ae62cb02e8f3d40acdfa51a7 | 2,736 | cpp | C++ | BallsToTheWall/src/ParticleSystem.cpp | JackiBackiBoy/BallsToTheWall | 9a18e3772e1ad2213e2282c59691818305088059 | [
"Apache-2.0"
] | null | null | null | BallsToTheWall/src/ParticleSystem.cpp | JackiBackiBoy/BallsToTheWall | 9a18e3772e1ad2213e2282c59691818305088059 | [
"Apache-2.0"
] | null | null | null | BallsToTheWall/src/ParticleSystem.cpp | JackiBackiBoy/BallsToTheWall | 9a18e3772e1ad2213e2282c59691818305088059 | [
"Apache-2.0"
] | null | null | null | #include "ParticleSystem.h"
#include "TimeTracker.h"
#include "Random.h"
#include "math\Math.h"
#include "SFML/System/Clock.hpp"
#include "Sandbox.h"
sf::Clock tempClock = sf::Clock();
ParticleSystem::ParticleSystem(const unsigned int& aParticleCount)
{
myParticles.resize(aParticleCount);
}
void ParticleSystem::OnUpdate()
{
for (auto& p : myParticles)
{
if (!p.Active) continue;
p.LifeRemaining -= TimeTracker::GetUnscaledDeltaTime();
if (p.LifeRemaining <= 0.0f)
{
p.Active = false;
continue;
}
p.Shape.move(p.Velocity * TimeTracker::GetUnscaledDeltaTime());
p.Shape.rotate(Math::ToDegrees(p.AngularVelocity * TimeTracker::GetUnscaledDeltaTime()));
}
}
void ParticleSystem::OnRender(sf::RenderWindow* aWindow)
{
for (auto& p : myParticles)
{
if (!p.Active) continue;
float tempLife = p.LifeRemaining / p.LifeTime;
if (Sandbox::GetPack() == "Fun")
{
p.ColorBegin = Math::ShiftRainbow(p.ColorBegin, TimeTracker::GetUnscaledDeltaTime() * 500);
}
p.Shape.setFillColor(Math::Lerp(p.ColorEnd, p.ColorBegin, tempLife));
p.Shape.setScale(Math::Lerp(p.SizeEnd, p.SizeBegin, tempLife));
aWindow->draw(p.Shape);
}
}
void ParticleSystem::Emit(const ParticleProps& someParticleProps)
{
Particle& tempP = myParticles[myParticleIndex];
tempP.Active = true;
tempP.Velocity = someParticleProps.Velocity;
tempP.Velocity.x += someParticleProps.VelocityVariation.x * (Random::Float() - 0.5f);
tempP.Velocity.y += someParticleProps.VelocityVariation.y * (Random::Float() - 0.5f);
tempP.AngularVelocity = someParticleProps.AngVel + someParticleProps.AngVelVariation * (Random::Float() - 0.5f);
tempP.ColorBegin = someParticleProps.ColorBegin;
tempP.ColorEnd = someParticleProps.ColorEnd;
tempP.LifeTime = someParticleProps.LifeTime;
tempP.LifeRemaining = someParticleProps.LifeTime;
tempP.SizeBegin = someParticleProps.SizeBegin + someParticleProps.SizeVariation * (Random::Float() - 0.5f);
tempP.SizeEnd = someParticleProps.SizeEnd;
if (someParticleProps.Shape.getPointCount() == 0)
{
tempP.Shape = sf::ConvexShape(someParticleProps.PointCount);
float tempAngleInc = Math::Pi * 2.f / tempP.Shape.getPointCount();
for (int i = 0; i < tempP.Shape.getPointCount(); i++)
{
tempP.Shape.setPoint(i, sf::Vector2f(cos(tempAngleInc * i), sin(tempAngleInc * i)));
}
}
else tempP.Shape = someParticleProps.Shape;
tempP.Shape.setPosition(someParticleProps.Position);
tempP.Shape.setRotation(Math::ToDegrees(someParticleProps.Rotation + someParticleProps.RotationVariation * (Random::Float() - 0.5f)));
if (myParticleIndex == 0)
{
myParticleIndex = myParticles.size() - 1;
}
else myParticleIndex--;
}
int ParticleSystem::GetSize()
{
return myParticles.size();
}
| 27.636364 | 135 | 0.729898 | JackiBackiBoy |
4144308d06f489eb002cbe3541de831492779f34 | 1,764 | hpp | C++ | src/standard/bits/DD_find_max.hpp | iDingDong/libDDCPP-old | 841260fecc84330ff3bfffba7263f5318f0b4655 | [
"BSD-3-Clause"
] | 1 | 2018-06-01T03:29:34.000Z | 2018-06-01T03:29:34.000Z | src/standard/bits/DD_find_max.hpp | iDingDong/libDDCPP-old | 841260fecc84330ff3bfffba7263f5318f0b4655 | [
"BSD-3-Clause"
] | null | null | null | src/standard/bits/DD_find_max.hpp | iDingDong/libDDCPP-old | 841260fecc84330ff3bfffba7263f5318f0b4655 | [
"BSD-3-Clause"
] | null | null | null | // DDCPP/standard/bits/DD_find_max.hpp
#ifndef DD_FIND_MAX_HPP_INCLUDED_
# define DD_FIND_MAX_HPP_INCLUDED_ 1
# include "DD_Iterator.hpp"
# include "DD_Range.hpp"
# include "DD_LessThan.hpp"
DD_DETAIL_BEGIN_
template <typename UndirectionalIteratorT_, typename BinaryPredicateT_>
UndirectionalIteratorT_ find_max(
UndirectionalIteratorT_ begin__,
UndirectionalIteratorT_ end__,
BinaryPredicateT_ less__
) DD_NOEXCEPT_AS(++begin__ != end__ && less__(*begin__, *begin__)) {
if (begin__ != end__) {
for (UndirectionalIteratorT_ current__(begin__); ++current__ != end__; ) {
if (less__(*begin__, *current__)) {
begin__ = current__;
}
}
}
return begin__;
}
template <typename UndirectionalIteratorT_>
inline UndirectionalIteratorT_ find_max(
UndirectionalIteratorT_ begin__,
UndirectionalIteratorT_ end__
) DD_NOEXCEPT_AS(static_cast<UndirectionalIteratorT_>(
::DD::detail_::find_max(begin__ DD_COMMA end__ DD_COMMA less_than)
)) {
return ::DD::detail_::find_max(begin__, end__, less_than);
}
template <typename UndirectionalRangeT_, typename BinaryPredicateT_>
inline DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT_) find_max(
UndirectionalRangeT_& range__,
BinaryPredicateT_ less__
) DD_NOEXCEPT_AS(::DD::detail_::find_max(DD_SPLIT_RANGE(range__) DD_COMMA less__)) {
return ::DD::detail_::find_max(DD_SPLIT_RANGE(range__), less__);
}
template <typename UndirectionalRangeT_>
inline DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT_) find_max(
UndirectionalRangeT_& range__
) DD_NOEXCEPT_AS(static_cast<DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT_)>(
::DD::detail_::find_max(range__, less_than)
)) {
return ::DD::detail_::find_max(range__, less_than);
}
DD_DETAIL_END_
DD_BEGIN_
using detail_::find_max;
DD_END_
#endif
| 24.164384 | 84 | 0.790249 | iDingDong |
4147724ab37e2fe0d5ebfd6bcf9419b5d43960d8 | 635 | cpp | C++ | hal/src/driver/nacl/epinput_ppapi.cpp | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | hal/src/driver/nacl/epinput_ppapi.cpp | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | hal/src/driver/nacl/epinput_ppapi.cpp | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | #include "driver.h"
#if EPINPUT_DRIVER == EPDRIVER_PPAPI
#include "input_internal.h"
// --------------------------------------------------------
// Author: Manu Evans, March 2015
void epInput_InitInternal()
{
}
// --------------------------------------------------------
// Author: Manu Evans, March 2015
void epInput_UpdateInternal()
{
InputState &input = gInputState[gCurrentInputState];
InputState &prev = gInputState[1 - gCurrentInputState];
// Temp hack to stop warnings
epUnused(input);
epUnused(prev);
// poll keyboard
//...
// poll mouse
//...
// poll gamepads
//...
}
#else
EPEMPTYFILE
#endif
| 16.282051 | 59 | 0.554331 | Euclideon |
414b8318271c43da7f97da01afe764898d637779 | 16,353 | cpp | C++ | Examples/PBD/PBDTissueStitch/PbdTissueStitchExample.cpp | Kitware/iMSTK | fa84907c77c524a45c126d836f15275d76648be6 | [
"Apache-2.0"
] | 15 | 2021-09-20T17:33:52.000Z | 2022-02-12T09:49:57.000Z | Examples/PBD/PBDTissueStitch/PbdTissueStitchExample.cpp | Kitware/iMSTK | fa84907c77c524a45c126d836f15275d76648be6 | [
"Apache-2.0"
] | null | null | null | Examples/PBD/PBDTissueStitch/PbdTissueStitchExample.cpp | Kitware/iMSTK | fa84907c77c524a45c126d836f15275d76648be6 | [
"Apache-2.0"
] | 3 | 2021-10-06T19:55:41.000Z | 2022-02-17T21:59:16.000Z | /*=========================================================================
Library: iMSTK
Copyright (c) Kitware, Inc. & Center for Modeling, Simulation,
& Imaging in Medicine, Rensselaer Polytechnic Institute.
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.txt
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 "imstkCamera.h"
#include "imstkCapsule.h"
#include "imstkDirectionalLight.h"
#include "imstkGeometryUtilities.h"
#include "imstkKeyboardDeviceClient.h"
#include "imstkKeyboardSceneControl.h"
#include "imstkLineMesh.h"
#include "imstkMouseSceneControl.h"
#include "imstkPbdModel.h"
#include "imstkPbdObject.h"
#include "imstkPbdObjectCollision.h"
#include "imstkPbdObjectStitching.h"
#include "imstkPointwiseMap.h"
#include "imstkRbdConstraint.h"
#include "imstkRenderMaterial.h"
#include "imstkRigidBodyModel2.h"
#include "imstkRigidObject2.h"
#include "imstkRigidObjectController.h"
#include "imstkScene.h"
#include "imstkSceneManager.h"
#include "imstkSimulationManager.h"
#include "imstkSurfaceMesh.h"
#include "imstkTetrahedralMesh.h"
#include "imstkVisualModel.h"
#include "imstkVTKViewer.h"
using namespace imstk;
// #define USE_THIN_TISSUE
#ifdef iMSTK_USE_OPENHAPTICS
#include "imstkHapticDeviceClient.h"
#include "imstkHapticDeviceManager.h"
#else
#include "imstkDummyClient.h"
#include "imstkMouseDeviceClient.h"
#endif
///
/// \brief Creates tetrahedral tissue object
/// \param name
/// \param physical dimension of tissue
/// \param dimensions of tetrahedral grid used for tissue
/// \param center of tissue block
///
static std::shared_ptr<PbdObject>
makeTetTissueObj(const std::string& name,
const Vec3d& size, const Vec3i& dim, const Vec3d& center)
{
auto tissueObj = std::make_shared<PbdObject>(name);
// Setup the Geometry
std::shared_ptr<TetrahedralMesh> tissueMesh = GeometryUtils::toTetGrid(center, size, dim);
std::shared_ptr<SurfaceMesh> surfMesh = tissueMesh->extractSurfaceMesh();
// Setup the Parameters
auto pbdParams = std::make_shared<PbdModelConfig>();
// Use FEMTet constraints (42k - 85k for tissue, but we want
// something much more stretchy to wrap)
pbdParams->m_femParams->m_YoungModulus = 1000.0;
pbdParams->m_femParams->m_PoissonRatio = 0.4; // 0.48 for tissue
pbdParams->enableFemConstraint(PbdFemConstraint::MaterialType::StVK);
/* pbdParams->enableConstraint(PbdModelConfig::ConstraintGenType::Volume, 0.01);
pbdParams->enableConstraint(PbdModelConfig::ConstraintGenType::Distance, 0.4);*/
pbdParams->m_doPartitioning = false;
pbdParams->m_uniformMassValue = 0.00001;
pbdParams->m_gravity = Vec3d(0.0, 0.0, 0.0);
pbdParams->m_dt = 0.001;
pbdParams->m_iterations = 5;
pbdParams->m_viscousDampingCoeff = 0.05;
// Fix the borders
for (int z = 0; z < dim[2]; z++)
{
for (int y = 0; y < dim[1]; y++)
{
for (int x = 0; x < dim[0]; x++)
{
if (x == 0)
{
pbdParams->m_fixedNodeIds.push_back(x + dim[0] * (y + dim[1] * z));
}
}
}
}
// Setup the Model
auto pbdModel = std::make_shared<PbdModel>();
pbdModel->setModelGeometry(tissueMesh);
pbdModel->configure(pbdParams);
// Setup the material
auto material = std::make_shared<RenderMaterial>();
material->setDisplayMode(RenderMaterial::DisplayMode::Wireframe);
material->setColor(Color(0.77, 0.53, 0.34));
material->setEdgeColor(Color(0.87, 0.63, 0.44));
material->setOpacity(0.5);
// Setup the Object
tissueObj->setVisualGeometry(surfMesh);
tissueObj->getVisualModel(0)->setRenderMaterial(material);
tissueObj->setPhysicsGeometry(tissueMesh);
tissueObj->setCollidingGeometry(surfMesh);
tissueObj->setPhysicsToCollidingMap(std::make_shared<PointwiseMap>(tissueMesh, surfMesh));
tissueObj->setDynamicalModel(pbdModel);
return tissueObj;
}
///
/// \brief Creates thin tissue object
///
static std::shared_ptr<PbdObject>
makeTriTissueObj(const std::string& name,
const Vec2d& size, const Vec2i& dim, const Vec3d& center)
{
auto tissueObj = std::make_shared<PbdObject>(name);
// Setup the Geometry
std::shared_ptr<SurfaceMesh> triMesh =
GeometryUtils::toTriangleGrid(center, size, dim,
Quatd::Identity(), 1.0);
// Setup the Parameters
auto pbdParams = std::make_shared<PbdModelConfig>();
pbdParams->enableConstraint(PbdModelConfig::ConstraintGenType::Distance, 0.1);
pbdParams->enableConstraint(PbdModelConfig::ConstraintGenType::Dihedral, 1e-6);
pbdParams->m_uniformMassValue = 0.00001;
pbdParams->m_gravity = Vec3d(0.0, 0.0, 0.0);
pbdParams->m_dt = 0.001;
pbdParams->m_iterations = 5;
pbdParams->m_viscousDampingCoeff = 0.025;
// Fix the borders
for (int y = 0; y < dim[1]; y++)
{
for (int x = 0; x < dim[0]; x++)
{
if (x == 0)
{
pbdParams->m_fixedNodeIds.push_back(x + dim[0] * y);
}
}
}
// Setup the Model
auto pbdModel = std::make_shared<PbdModel>();
pbdModel->setModelGeometry(triMesh);
pbdModel->configure(pbdParams);
// Setup the VisualModel
auto material = std::make_shared<RenderMaterial>();
material->setBackFaceCulling(false);
material->setDisplayMode(RenderMaterial::DisplayMode::WireframeSurface);
material->setColor(Color(0.77, 0.53, 0.34));
material->setEdgeColor(Color(0.87, 0.63, 0.44));
// Setup the Object
tissueObj->setVisualGeometry(triMesh);
tissueObj->getVisualModel(0)->setRenderMaterial(material);
tissueObj->setPhysicsGeometry(triMesh);
tissueObj->setCollidingGeometry(triMesh);
tissueObj->setDynamicalModel(pbdModel);
return tissueObj;
}
static std::shared_ptr<RigidObject2>
makeToolObj()
{
auto toolGeom = std::make_shared<LineMesh>();
auto verticesPtr = std::make_shared<VecDataArray<double, 3>>(2);
(*verticesPtr)[0] = Vec3d(0.0, -0.05, 0.0);
(*verticesPtr)[1] = Vec3d(0.0, 0.05, 0.0);
auto indicesPtr = std::make_shared<VecDataArray<int, 2>>(1);
(*indicesPtr)[0] = Vec2i(0, 1);
toolGeom->initialize(verticesPtr, indicesPtr);
auto toolObj = std::make_shared<RigidObject2>("ToolObj");
toolObj->setVisualGeometry(toolGeom);
toolObj->setCollidingGeometry(toolGeom);
toolObj->setPhysicsGeometry(toolGeom);
toolObj->getVisualModel(0)->getRenderMaterial()->setColor(Color(0.9, 0.9, 0.9));
toolObj->getVisualModel(0)->getRenderMaterial()->setShadingModel(RenderMaterial::ShadingModel::PBR);
toolObj->getVisualModel(0)->getRenderMaterial()->setRoughness(0.5);
toolObj->getVisualModel(0)->getRenderMaterial()->setMetalness(1.0);
toolObj->getVisualModel(0)->getRenderMaterial()->setIsDynamicMesh(false);
auto rbdModel = std::make_shared<RigidBodyModel2>();
rbdModel->getConfig()->m_gravity = Vec3d::Zero();
rbdModel->getConfig()->m_maxNumIterations = 5;
toolObj->setDynamicalModel(rbdModel);
toolObj->getRigidBody()->m_mass = 0.3;
toolObj->getRigidBody()->m_intertiaTensor = Mat3d::Identity() * 10000.0;
toolObj->getRigidBody()->m_initPos = Vec3d(0.0, 0.0, 0.0);
return toolObj;
}
///
/// \brief This example demonstrates stitching interaction with pbd tissues
///
int
main()
{
const double capsuleRadius = 0.02;
const double tissueLength = 0.15;
// Setup logger (write to file and stdout)
Logger::startLogger();
// Setup the scene
auto scene = std::make_shared<Scene>("PbdTissueStitch");
scene->getActiveCamera()->setPosition(0.0012, 0.0451, 0.1651);
scene->getActiveCamera()->setFocalPoint(0.0, 0.0, 0.0);
scene->getActiveCamera()->setViewUp(0.0, 0.96, -0.28);
// Setup a tet tissue
#ifdef USE_THIN_TISSUE
std::shared_ptr<PbdObject> tissueObj = makeTriTissueObj("Tissue",
Vec2d(tissueLength, 0.07), Vec2i(15, 5),
Vec3d(tissueLength * 0.5, -0.01 - capsuleRadius, 0.0));
#else
std::shared_ptr<PbdObject> tissueObj = makeTetTissueObj("Tissue",
Vec3d(tissueLength, 0.01, 0.07), Vec3i(15, 2, 5),
Vec3d(tissueLength * 0.5, -0.01 - capsuleRadius, 0.0));
#endif
scene->addSceneObject(tissueObj);
// Setup a capsule to wrap around
auto cdObj = std::make_shared<CollidingObject>("collisionObject");
auto capsuleGeom = std::make_shared<Capsule>();
capsuleGeom->setPosition(0.0, 0.0, 0.0);
capsuleGeom->setRadius(capsuleRadius);
capsuleGeom->setLength(0.08);
capsuleGeom->setOrientation(Quatd(Rotd(PI_2, Vec3d(1.0, 0.0, 0.0))));
cdObj->setVisualGeometry(capsuleGeom);
cdObj->getVisualModel(0)->getRenderMaterial()->setColor(
Color(246.0 / 255.0, 127.0 / 255.0, 123.0 / 255.0));
cdObj->setCollidingGeometry(capsuleGeom);
scene->addSceneObject(cdObj);
std::shared_ptr<RigidObject2> toolObj = makeToolObj();
scene->addSceneObject(toolObj);
// Setup CD with a cylinder CD object
auto collisionInteraction = std::make_shared<PbdObjectCollision>(tissueObj, cdObj, "SurfaceMeshToCapsuleCD");
collisionInteraction->setFriction(0.0);
scene->addInteraction(collisionInteraction);
auto stitching = std::make_shared<PbdObjectStitching>(tissueObj);
stitching->setStitchDistance(0.015);
scene->addInteraction(stitching);
// Lights
auto light1 = std::make_shared<DirectionalLight>();
light1->setFocalPoint(Vec3d(5.0, -8.0, -5.0));
light1->setIntensity(0.5);
scene->addLight("light1", light1);
auto light2 = std::make_shared<DirectionalLight>();
light2->setFocalPoint(Vec3d(-5.0, -8.0, -5.0));
light2->setIntensity(0.5);
scene->addLight("light2", light2);
// Run the simulation
{
// Setup a viewer to render
auto viewer = std::make_shared<VTKViewer>();
viewer->setActiveScene(scene);
viewer->setDebugAxesLength(0.001, 0.001, 0.001);
// Setup a scene manager to advance the scene
auto sceneManager = std::make_shared<SceneManager>();
sceneManager->setActiveScene(scene);
sceneManager->pause(); // Start simulation paused
auto driver = std::make_shared<SimulationManager>();
driver->addModule(viewer);
driver->addModule(sceneManager);
driver->setDesiredDt(0.001);
#ifdef iMSTK_USE_OPENHAPTICS
auto hapticManager = std::make_shared<HapticDeviceManager>();
hapticManager->setSleepDelay(0.1); // Delay for 1ms (haptics thread is limited to max 1000hz)
std::shared_ptr<HapticDeviceClient> deviceClient = hapticManager->makeDeviceClient();
driver->addModule(hapticManager);
#else
auto deviceClient = std::make_shared<DummyClient>();
connect<Event>(sceneManager, &SceneManager::postUpdate,
[&](Event*)
{
const Vec2d& pos = viewer->getMouseDevice()->getPos();
#ifdef USE_THIN_TISSUE
deviceClient->setPosition(Vec3d(40.0, 40.0, -(pos[1] * 100.0 - 50.0)));
deviceClient->setOrientation(Quatd(Rotd(-0.6, Vec3d(0.0, 0.0, 1.0))));
#else
deviceClient->setPosition(Vec3d(37.0, 0.0, -(pos[1] * 100.0 - 50.0)));
deviceClient->setOrientation(Quatd(Rotd(0.65, Vec3d(0.0, 0.0, 1.0))));
#endif
});
#endif
auto controller = std::make_shared<RigidObjectController>(toolObj, deviceClient);
controller->setTranslationScaling(0.001);
controller->setLinearKs(1000.0);
controller->setAngularKs(10000000.0);
controller->setUseCritDamping(true);
controller->setForceScaling(0.0045);
controller->setSmoothingKernelSize(15);
controller->setUseForceSmoothening(true);
scene->addController(controller);
#ifdef iMSTK_USE_OPENHAPTICS
connect<ButtonEvent>(deviceClient, &HapticDeviceClient::buttonStateChanged,
[&](ButtonEvent* e)
{
if (e->m_button == 0 && e->m_buttonState == BUTTON_PRESSED)
{
auto toolGeom = std::dynamic_pointer_cast<LineMesh>(toolObj->getCollidingGeometry());
const Vec3d& v1 = toolGeom->getVertexPosition(0);
const Vec3d& v2 = toolGeom->getVertexPosition(1);
stitching->beginStitch(v1, (v2 - v1).normalized());
}
});
#endif
double t = 0.0;
connect<KeyEvent>(viewer->getKeyboardDevice(), &KeyboardDeviceClient::keyPress,
[&](KeyEvent* e)
{
// Toggle gravity
if (e->m_key == 'g')
{
Vec3d& g = tissueObj->getPbdModel()->getConfig()->m_gravity;
g = Vec3d(0.0, -static_cast<double>(!(g.norm() > 0.0)), 0.0);
}
// Perform stitch
else if (e->m_key == 's')
{
auto toolGeom = std::dynamic_pointer_cast<LineMesh>(toolObj->getCollidingGeometry());
const Vec3d& v1 = toolGeom->getVertexPosition(0);
const Vec3d& v2 = toolGeom->getVertexPosition(1);
stitching->beginStitch(v1, (v2 - v1).normalized());
}
// Reset
else if (e->m_key == 'r')
{
t = 0.0;
}
});
// Record the intial positions
std::vector<Vec3d> initPositions;
auto pointMesh =
std::dynamic_pointer_cast<PointSet>(tissueObj->getPhysicsGeometry());
std::shared_ptr<VecDataArray<double, 3>> verticesPtr = pointMesh->getVertexPositions();
VecDataArray<double, 3>& vertices = *verticesPtr;
const std::vector<size_t> fixedNodes = tissueObj->getPbdModel()->getConfig()->m_fixedNodeIds;
for (size_t i = 0; i < fixedNodes.size(); i++)
{
initPositions.push_back(vertices[fixedNodes[i]]);
}
bool stopped = false;
// Script the movement of the tissues fixed points
connect<Event>(sceneManager, &SceneManager::postUpdate,
[&](Event*)
{
const double dt = sceneManager->getDt();
t += dt;
if (t < 10.5)
{
for (size_t i = 0; i < fixedNodes.size(); i++)
{
Vec3d initPos = initPositions[i];
Vec3d& pos = vertices[fixedNodes[i]];
const double r = (capsuleGeom->getPosition().head<2>() - initPos.head<2>()).norm();
pos = Vec3d(-sin(t) * r, -cos(t) * r, initPos[2]);
}
}
else
{
if (!stopped)
{
// Clear and reinit all constraints (new resting lengths)
stopped = true;
tissueObj->getPbdModel()->getConfig()->m_fixedNodeIds.clear();
tissueObj->initialize();
}
}
});
// Add mouse and keyboard controls to the viewer
{
auto mouseControl = std::make_shared<MouseSceneControl>(viewer->getMouseDevice());
mouseControl->setSceneManager(sceneManager);
viewer->addControl(mouseControl);
auto keyControl = std::make_shared<KeyboardSceneControl>(viewer->getKeyboardDevice());
keyControl->setSceneManager(sceneManager);
keyControl->setModuleDriver(driver);
viewer->addControl(keyControl);
}
driver->start();
}
return 0;
} | 37.766744 | 117 | 0.624778 | Kitware |
414b9092f3677eff4b31ef8fa98e0ed3a43067c0 | 4,710 | hpp | C++ | src/libraries/core/containers/Lists/Histogram/Histogram.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/containers/Lists/Histogram/Histogram.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/containers/Lists/Histogram/Histogram.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011-2015 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS 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.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::Histogram
Description
Calculates the counts per bin of a list.
\*---------------------------------------------------------------------------*/
#ifndef Histogram_H
#define Histogram_H
#include "labelList.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
/*---------------------------------------------------------------------------*\
Class Histogram Declaration
\*---------------------------------------------------------------------------*/
template<class List>
class Histogram
{
// Private data
//- Counts per bin
labelList counts_;
//- Number of <= lowest bin
label nLow_;
//- Number of > highest bin
label nHigh_;
// Private Member Functions
void count(const List& bins, const List& l);
//- Disallow default bitwise copy construct
Histogram(const Histogram&);
//- Disallow default bitwise assignment
void operator=(const Histogram&);
public:
// Constructors
//- Construct given bin values and input list
Histogram(const List& bins, const List& l);
//- Construct given min, max, number of bins and input list
Histogram
(
const typename List::const_reference min,
const typename List::const_reference max,
const label nBins,
const List& l
);
// Access
//- Return the counts per bin
inline const labelList& counts() const
{
return counts_;
}
//- Return the number of elements <= bins[0]
// (so inclusive lowest bin value)
inline label nLow() const
{
return nLow_;
}
//- Return the number of elements > bins[bins.size()-1]
// (so exclusive highest bin value)
inline label nHigh() const
{
return nHigh_;
}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "ListOps.hpp"
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
template<class List>
void CML::Histogram<List>::count(const List& bins, const List& l)
{
if (bins.size() < 2)
{
FatalErrorInFunction
<< "Should have at least two values in bins. Now:" << bins
<< exit(FatalError);
}
counts_.setSize(bins.size()-1);
counts_ = 0;
nLow_ = 0;
nHigh_ = 0;
forAll(l, i)
{
label index = findLower(bins, l[i]);
if (index == -1)
{
nLow_++;
}
else if (index == bins.size()-1)
{
nHigh_++;
}
else
{
counts_[index]++;
}
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class List>
CML::Histogram<List>::Histogram(const List& bins, const List& l)
{
count(bins, l);
}
template<class List>
CML::Histogram<List>::Histogram
(
const typename List::const_reference min,
const typename List::const_reference max,
const label nBins,
const List& l
)
{
List bins(nBins+1);
typename List::value_type span = (max-min) / nBins;
bins[0] = min;
for (label i = 1; i < nBins; i++)
{
bins[i] = bins[i-1] + span;
}
// Set max directly to avoid truncation errors.
bins[nBins] = max;
count(bins, l);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 23.432836 | 79 | 0.463482 | MrAwesomeRocks |
414e9cb32d6ebfc04a1754091e33b0c03f70c528 | 596 | hpp | C++ | wrapper/bindings/utility.hpp | Karanlos/gli-rs | 494a2dfec786824a5c3fcc5eb21c5d786076a48f | [
"MIT"
] | null | null | null | wrapper/bindings/utility.hpp | Karanlos/gli-rs | 494a2dfec786824a5c3fcc5eb21c5d786076a48f | [
"MIT"
] | null | null | null | wrapper/bindings/utility.hpp | Karanlos/gli-rs | 494a2dfec786824a5c3fcc5eb21c5d786076a48f | [
"MIT"
] | null | null | null |
#include <glm/gtc/epsilon.hpp>
extern "C" {
namespace bindings {
struct TexelType4F {
float content[4];
};
TexelType4F vec4ToTex4F(gli::vec4 raw) {
TexelType4F value;
value.content[0] = raw[0];
value.content[1] = raw[1];
value.content[2] = raw[2];
value.content[3] = raw[3];
return value;
}
}
}
namespace gli {
gli::vec4 tex4FToVec4(bindings::TexelType4F raw) {
return gli::vec4(raw.content[0], raw.content[1], raw.content[2], raw.content[3]);
}
}
| 19.866667 | 89 | 0.525168 | Karanlos |
4151c5492f764904c167f82d37088d71179cb616 | 9,871 | cpp | C++ | tests/tests/result_tests/when_any_tests.cpp | PazerOP/concurrencpp | fbc8c475d5a534c5d222d9b241ad9299f2413969 | [
"MIT"
] | 1 | 2020-10-29T21:43:36.000Z | 2020-10-29T21:43:36.000Z | tests/tests/result_tests/when_any_tests.cpp | PazerOP/concurrencpp | fbc8c475d5a534c5d222d9b241ad9299f2413969 | [
"MIT"
] | null | null | null | tests/tests/result_tests/when_any_tests.cpp | PazerOP/concurrencpp | fbc8c475d5a534c5d222d9b241ad9299f2413969 | [
"MIT"
] | null | null | null | #include "concurrencpp.h"
#include "../all_tests.h"
#include "../test_utils/test_ready_result.h"
#include "../test_utils/executor_shutdowner.h"
#include "../../tester/tester.h"
#include "../../helpers/assertions.h"
#include "../../helpers/random.h"
#include "../../helpers/object_observer.h"
namespace concurrencpp::tests {
template<class type>
void test_when_any_vector_empty_result();
template<class type>
void test_when_any_vector_empty_range();
template<class type>
result<void> test_when_any_vector_valid(std::shared_ptr<thread_executor> ex);
template<class type>
void test_when_any_vector_impl();
void test_when_any_vector();
void test_when_any_tuple_empty_result();
result<void> test_when_any_tuple_impl(std::shared_ptr<thread_executor> ex);
void test_when_any_tuple();
}
template <class type>
void concurrencpp::tests::test_when_any_vector_empty_result() {
const size_t task_count = 63;
std::vector<result_promise<type>> result_promises(task_count);
std::vector<result<type>> results;
for (auto& rp : result_promises) {
results.emplace_back(rp.get_result());
}
results.emplace_back();
assert_throws_with_error_message<errors::empty_result>(
[&] {
concurrencpp::when_any(results.begin(), results.end());
},
concurrencpp::details::consts::k_when_any_empty_result_error_msg);
const auto all_valid = std::all_of(
results.begin(),
results.begin() + task_count,
[](const auto& result) {
return static_cast<bool>(result);
});
assert_true(all_valid);
}
template <class type>
void concurrencpp::tests::test_when_any_vector_empty_range() {
std::vector<result<type>> empty_range;
assert_throws_with_error_message<std::invalid_argument>([&] {
when_any(empty_range.begin(), empty_range.end());
}, concurrencpp::details::consts::k_when_any_empty_range_error_msg);
}
template<class type>
concurrencpp::result<void>
concurrencpp::tests::test_when_any_vector_valid(std::shared_ptr<thread_executor> ex) {
const size_t task_count = 64;
auto values = result_factory<type>::get_many(task_count);
std::vector<result<type>> results;
random randomizer;
for (size_t i = 0; i < task_count; i++) {
const auto time_to_sleep = randomizer(10, 100);
results.emplace_back(ex->submit([i, time_to_sleep, &values]() -> type {
(void)values;
std::this_thread::sleep_for(std::chrono::milliseconds(time_to_sleep));
if (i % 4 == 0) {
throw costume_exception(i);
}
if constexpr (!std::is_same_v<void, type>) {
return values[i];
}
}));
}
auto any_done = co_await when_any(results.begin(), results.end());
auto& done_result = any_done.results[any_done.index];
const auto all_valid = std::all_of(
any_done.results.begin(),
any_done.results.end(),
[](const auto& result) {
return static_cast<bool>(result);
});
assert_true(all_valid);
if (any_done.index % 4 == 0) {
test_ready_result_costume_exception(std::move(done_result), any_done.index);
}
else {
if constexpr (std::is_same_v<void, type>) {
test_ready_result_result(std::move(done_result));
}
else {
test_ready_result_result(std::move(done_result), values[any_done.index]);
}
}
//the value vector is a local variable, tasks may outlive it. join them.
for (auto& result : any_done.results) {
if (!static_cast<bool>(result)) {
continue;
}
co_await result.resolve();
}
}
template <class type>
void concurrencpp::tests::test_when_any_vector_impl() {
test_when_any_vector_empty_result<type>();
test_when_any_vector_empty_range<type>();
{
auto thread_executor = std::make_shared<concurrencpp::thread_executor>();
executor_shutdowner es(thread_executor);
test_when_any_vector_valid<type>(thread_executor).get();
}
}
void concurrencpp::tests::test_when_any_vector() {
test_when_any_vector_impl<int>();
test_when_any_vector_impl<std::string>();
test_when_any_vector_impl<void>();
test_when_any_vector_impl<int&>();
test_when_any_vector_impl<std::string&>();
}
void concurrencpp::tests::test_when_any_tuple_empty_result() {
result_promise<int> rp_int;
auto int_res = rp_int.get_result();
result_promise<std::string> rp_s;
auto s_res = rp_s.get_result();
result_promise<void> rp_void;
auto void_res = rp_void.get_result();
result_promise<int&> rp_int_ref;
auto int_ref_res = rp_int_ref.get_result();
result<std::string&> s_ref_res;
assert_throws_with_error_message<errors::empty_result>(
[&] {
when_any(
std::move(int_res),
std::move(s_res),
std::move(void_res),
std::move(int_ref_res),
std::move(s_ref_res));
},
concurrencpp::details::consts::k_when_any_empty_result_error_msg);
//all pre-operation results are still valid
assert_true(static_cast<bool>(int_res));
assert_true(static_cast<bool>(s_res));
assert_true(static_cast<bool>(void_res));
assert_true(static_cast<bool>(int_res));
}
concurrencpp::result<void>
concurrencpp::tests::test_when_any_tuple_impl(std::shared_ptr<thread_executor> ex) {
std::atomic_size_t counter = 0;
random randomizer;
auto tts = randomizer(10,100);
auto int_res_val = ex->submit([&counter, tts] {
std::this_thread::sleep_for(std::chrono::milliseconds(tts));
counter.fetch_add(1, std::memory_order_relaxed);
return result_factory<int>::get();
});
tts = randomizer(10, 100);
auto int_res_ex = ex->submit([&counter, tts] {
std::this_thread::sleep_for(std::chrono::milliseconds(tts));
counter.fetch_add(1, std::memory_order_relaxed);
throw costume_exception(0);
return result_factory<int>::get();
});
tts = randomizer(10, 100);
auto s_res_val = ex->submit([&counter, tts]() -> std::string {
std::this_thread::sleep_for(std::chrono::milliseconds(tts));
counter.fetch_add(1, std::memory_order_relaxed);
return result_factory<std::string>::get();
});
tts = randomizer(10, 100);
auto s_res_ex = ex->submit([&counter, tts]() -> std::string {
std::this_thread::sleep_for(std::chrono::milliseconds(tts));
counter.fetch_add(1, std::memory_order_relaxed);
throw costume_exception(1);
return result_factory<std::string>::get();
});
tts = randomizer(10, 100);
auto void_res_val = ex->submit([&counter, tts] {
std::this_thread::sleep_for(std::chrono::milliseconds(tts));
counter.fetch_add(1, std::memory_order_relaxed);
});
tts = randomizer(10, 100);
auto void_res_ex = ex->submit([&counter, tts] {
std::this_thread::sleep_for(std::chrono::milliseconds(tts));
counter.fetch_add(1, std::memory_order_relaxed);
throw costume_exception(2);
});
tts = randomizer(10, 100);
auto int_ref_res_val = ex->submit([&counter, tts]() ->int& {
std::this_thread::sleep_for(std::chrono::milliseconds(tts));
counter.fetch_add(1, std::memory_order_relaxed);
return result_factory<int&>::get();
});
tts = randomizer(10, 100);
auto int_ref_res_ex = ex->submit([&counter, tts]() ->int& {
std::this_thread::sleep_for(std::chrono::milliseconds(tts));
counter.fetch_add(1, std::memory_order_relaxed);
throw costume_exception(3);
return result_factory<int&>::get();
});
tts = randomizer(10, 100);
auto s_ref_res_val = ex->submit([&counter, tts]() -> std::string& {
std::this_thread::sleep_for(std::chrono::milliseconds(tts));
counter.fetch_add(1, std::memory_order_relaxed);
return result_factory<std::string&>::get();
});
tts = randomizer(10, 100);
auto s_ref_res_ex = ex->submit([&counter, tts]() -> std::string& {
std::this_thread::sleep_for(std::chrono::milliseconds(tts));
counter.fetch_add(1, std::memory_order_relaxed);
throw costume_exception(4);
return result_factory<std::string&>::get();
});
auto any_done = co_await when_any(
std::move(int_res_val),
std::move(int_res_ex),
std::move(s_res_val),
std::move(s_res_ex),
std::move(void_res_val),
std::move(void_res_ex),
std::move(int_ref_res_val),
std::move(int_ref_res_ex),
std::move(s_ref_res_val),
std::move(s_ref_res_ex));
assert_bigger_equal(counter.load(std::memory_order_relaxed), size_t(1));
switch (any_done.index) {
case 0:
{
test_ready_result_result(std::move(std::get<0>(any_done.results)), result_factory<int>::get());
break;
}
case 1:
{
test_ready_result_costume_exception(std::move(std::get<1>(any_done.results)), 0);
break;
}
case 2:
{
test_ready_result_result(std::move(std::get<2>(any_done.results)), result_factory<std::string>::get());
break;
}
case 3:
{
test_ready_result_costume_exception(std::move(std::get<3>(any_done.results)), 1);
break;
}
case 4:
{
test_ready_result_result(std::move(std::get<4>(any_done.results)));
break;
}
case 5:
{
test_ready_result_costume_exception(std::move(std::get<5>(any_done.results)), 2);
break;
}
case 6:
{
test_ready_result_result(std::move(std::get<6>(any_done.results)), result_factory<int&>::get());
break;
}
case 7:
{
test_ready_result_costume_exception(std::move(std::get<7>(any_done.results)), 3);
break;
}
case 8:
{
test_ready_result_result(std::move(std::get<8>(any_done.results)), result_factory<std::string&>::get());
break;
}
case 9:
{
test_ready_result_costume_exception(std::move(std::get<9>(any_done.results)), 4);
break;
}
default:
{
assert_false(true);
}
}
auto wait = [](auto& result) {
if (static_cast<bool>(result)) {
result.wait();
}
};
std::apply([wait](auto&... results) {(wait(results), ...); }, any_done.results);
}
void concurrencpp::tests::test_when_any_tuple() {
test_when_any_tuple_empty_result();
{
auto thread_executor = std::make_shared<concurrencpp::thread_executor>();
executor_shutdowner es(thread_executor);
test_when_any_tuple_impl(thread_executor).get();
}
}
void concurrencpp::tests::test_when_any() {
tester test("when_any test");
test.add_step("when_any(begin, end)", test_when_any_vector);
test.add_step("when_any(result_types&& ... results)", test_when_any_tuple);
test.launch_test();
}
| 27.495822 | 107 | 0.714315 | PazerOP |
a9908aad6d1a2f554048be62d3b1c272c139c064 | 38,879 | cpp | C++ | src/runtime/ext/ext_ipc.ext_hhvm.cpp | burhan/hiphop-php | 6e02d7072a02fbaad1856878c2515e35f7e529f0 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2020-12-02T03:08:16.000Z | 2020-12-02T03:08:16.000Z | src/runtime/ext/ext_ipc.ext_hhvm.cpp | burhan/hiphop-php | 6e02d7072a02fbaad1856878c2515e35f7e529f0 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | src/runtime/ext/ext_ipc.ext_hhvm.cpp | burhan/hiphop-php | 6e02d7072a02fbaad1856878c2515e35f7e529f0 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <runtime/ext_hhvm/ext_hhvm.h>
#include <runtime/base/builtin_functions.h>
#include <runtime/base/array/array_init.h>
#include <runtime/ext/ext.h>
#include <runtime/vm/class.h>
#include <runtime/vm/runtime.h>
#include <exception>
namespace HPHP {
/*
long long HPHP::f_ftok(HPHP::String const&, HPHP::String const&)
_ZN4HPHP6f_ftokERKNS_6StringES2_
(return value) => rax
pathname => rdi
proj => rsi
*/
long long fh_ftok(Value* pathname, Value* proj) asm("_ZN4HPHP6f_ftokERKNS_6StringES2_");
TypedValue * fg1_ftok(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_ftok(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfInt64;
if (!IS_STRING_TYPE((args-1)->m_type)) {
tvCastToStringInPlace(args-1);
}
if (!IS_STRING_TYPE((args-0)->m_type)) {
tvCastToStringInPlace(args-0);
}
rv->m_data.num = (long long)fh_ftok((Value*)(args-0), (Value*)(args-1));
return rv;
}
TypedValue* fg_ftok(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
if (IS_STRING_TYPE((args-1)->m_type) && IS_STRING_TYPE((args-0)->m_type)) {
rv._count = 0;
rv.m_type = KindOfInt64;
rv.m_data.num = (long long)fh_ftok((Value*)(args-0), (Value*)(args-1));
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_ftok(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("ftok", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Variant HPHP::f_msg_get_queue(long long, long long)
_ZN4HPHP15f_msg_get_queueExx
(return value) => rax
_rv => rdi
key => rsi
perms => rdx
*/
TypedValue* fh_msg_get_queue(TypedValue* _rv, long long key, long long perms) asm("_ZN4HPHP15f_msg_get_queueExx");
TypedValue * fg1_msg_get_queue(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_msg_get_queue(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
switch (count) {
default: // count >= 2
if ((args-1)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-1);
}
case 1:
break;
}
if ((args-0)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-0);
}
fh_msg_get_queue((rv), (long long)(args[-0].m_data.num), (count > 1) ? (long long)(args[-1].m_data.num) : (long long)(0666));
if (rv->m_type == KindOfUninit) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_msg_get_queue(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count >= 1LL && count <= 2LL) {
if ((count <= 1 || (args-1)->m_type == KindOfInt64) && (args-0)->m_type == KindOfInt64) {
fh_msg_get_queue((&(rv)), (long long)(args[-0].m_data.num), (count > 1) ? (long long)(args[-1].m_data.num) : (long long)(0666));
if (rv.m_type == KindOfUninit) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_msg_get_queue(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("msg_get_queue", count, 1, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_msg_queue_exists(long long)
_ZN4HPHP18f_msg_queue_existsEx
(return value) => rax
key => rdi
*/
bool fh_msg_queue_exists(long long key) asm("_ZN4HPHP18f_msg_queue_existsEx");
TypedValue * fg1_msg_queue_exists(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_msg_queue_exists(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
tvCastToInt64InPlace(args-0);
rv->m_data.num = (fh_msg_queue_exists((long long)(args[-0].m_data.num))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_msg_queue_exists(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if ((args-0)->m_type == KindOfInt64) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_msg_queue_exists((long long)(args[-0].m_data.num))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_msg_queue_exists(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("msg_queue_exists", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_msg_send(HPHP::Object const&, long long, HPHP::Variant const&, bool, bool, HPHP::VRefParamValue const&)
_ZN4HPHP10f_msg_sendERKNS_6ObjectExRKNS_7VariantEbbRKNS_14VRefParamValueE
(return value) => rax
queue => rdi
msgtype => rsi
message => rdx
serialize => rcx
blocking => r8
errorcode => r9
*/
bool fh_msg_send(Value* queue, long long msgtype, TypedValue* message, bool serialize, bool blocking, TypedValue* errorcode) asm("_ZN4HPHP10f_msg_sendERKNS_6ObjectExRKNS_7VariantEbbRKNS_14VRefParamValueE");
TypedValue * fg1_msg_send(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_msg_send(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
switch (count) {
default: // count >= 6
case 5:
if ((args-4)->m_type != KindOfBoolean) {
tvCastToBooleanInPlace(args-4);
}
case 4:
if ((args-3)->m_type != KindOfBoolean) {
tvCastToBooleanInPlace(args-3);
}
case 3:
break;
}
if ((args-1)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-1);
}
if ((args-0)->m_type != KindOfObject) {
tvCastToObjectInPlace(args-0);
}
VRefParamValue defVal5 = null;
rv->m_data.num = (fh_msg_send((Value*)(args-0), (long long)(args[-1].m_data.num), (args-2), (count > 3) ? (bool)(args[-3].m_data.num) : (bool)(true), (count > 4) ? (bool)(args[-4].m_data.num) : (bool)(true), (count > 5) ? (args-5) : (TypedValue*)(&defVal5))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_msg_send(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count >= 3LL && count <= 6LL) {
if ((count <= 4 || (args-4)->m_type == KindOfBoolean) && (count <= 3 || (args-3)->m_type == KindOfBoolean) && (args-1)->m_type == KindOfInt64 && (args-0)->m_type == KindOfObject) {
rv._count = 0;
rv.m_type = KindOfBoolean;
VRefParamValue defVal5 = null;
rv.m_data.num = (fh_msg_send((Value*)(args-0), (long long)(args[-1].m_data.num), (args-2), (count > 3) ? (bool)(args[-3].m_data.num) : (bool)(true), (count > 4) ? (bool)(args[-4].m_data.num) : (bool)(true), (count > 5) ? (args-5) : (TypedValue*)(&defVal5))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 6);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_msg_send(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 6);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("msg_send", count, 3, 6, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 6);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_msg_receive(HPHP::Object const&, long long, HPHP::VRefParamValue const&, long long, HPHP::VRefParamValue const&, bool, long long, HPHP::VRefParamValue const&)
_ZN4HPHP13f_msg_receiveERKNS_6ObjectExRKNS_14VRefParamValueExS5_bxS5_
(return value) => rax
queue => rdi
desiredmsgtype => rsi
msgtype => rdx
maxsize => rcx
message => r8
unserialize => r9
flags => st0
errorcode => st8
*/
bool fh_msg_receive(Value* queue, long long desiredmsgtype, TypedValue* msgtype, long long maxsize, TypedValue* message, bool unserialize, long long flags, TypedValue* errorcode) asm("_ZN4HPHP13f_msg_receiveERKNS_6ObjectExRKNS_14VRefParamValueExS5_bxS5_");
TypedValue * fg1_msg_receive(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_msg_receive(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
switch (count) {
default: // count >= 8
case 7:
if ((args-6)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-6);
}
case 6:
if ((args-5)->m_type != KindOfBoolean) {
tvCastToBooleanInPlace(args-5);
}
case 5:
break;
}
if ((args-3)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-3);
}
if ((args-1)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-1);
}
if ((args-0)->m_type != KindOfObject) {
tvCastToObjectInPlace(args-0);
}
VRefParamValue defVal7 = null;
rv->m_data.num = (fh_msg_receive((Value*)(args-0), (long long)(args[-1].m_data.num), (args-2), (long long)(args[-3].m_data.num), (args-4), (count > 5) ? (bool)(args[-5].m_data.num) : (bool)(true), (count > 6) ? (long long)(args[-6].m_data.num) : (long long)(0), (count > 7) ? (args-7) : (TypedValue*)(&defVal7))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_msg_receive(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count >= 5LL && count <= 8LL) {
if ((count <= 6 || (args-6)->m_type == KindOfInt64) && (count <= 5 || (args-5)->m_type == KindOfBoolean) && (args-3)->m_type == KindOfInt64 && (args-1)->m_type == KindOfInt64 && (args-0)->m_type == KindOfObject) {
rv._count = 0;
rv.m_type = KindOfBoolean;
VRefParamValue defVal7 = null;
rv.m_data.num = (fh_msg_receive((Value*)(args-0), (long long)(args[-1].m_data.num), (args-2), (long long)(args[-3].m_data.num), (args-4), (count > 5) ? (bool)(args[-5].m_data.num) : (bool)(true), (count > 6) ? (long long)(args[-6].m_data.num) : (long long)(0), (count > 7) ? (args-7) : (TypedValue*)(&defVal7))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 8);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_msg_receive(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 8);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("msg_receive", count, 5, 8, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 8);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_msg_remove_queue(HPHP::Object const&)
_ZN4HPHP18f_msg_remove_queueERKNS_6ObjectE
(return value) => rax
queue => rdi
*/
bool fh_msg_remove_queue(Value* queue) asm("_ZN4HPHP18f_msg_remove_queueERKNS_6ObjectE");
TypedValue * fg1_msg_remove_queue(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_msg_remove_queue(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
tvCastToObjectInPlace(args-0);
rv->m_data.num = (fh_msg_remove_queue((Value*)(args-0))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_msg_remove_queue(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if ((args-0)->m_type == KindOfObject) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_msg_remove_queue((Value*)(args-0))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_msg_remove_queue(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("msg_remove_queue", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_msg_set_queue(HPHP::Object const&, HPHP::Array const&)
_ZN4HPHP15f_msg_set_queueERKNS_6ObjectERKNS_5ArrayE
(return value) => rax
queue => rdi
data => rsi
*/
bool fh_msg_set_queue(Value* queue, Value* data) asm("_ZN4HPHP15f_msg_set_queueERKNS_6ObjectERKNS_5ArrayE");
TypedValue * fg1_msg_set_queue(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_msg_set_queue(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
if ((args-1)->m_type != KindOfArray) {
tvCastToArrayInPlace(args-1);
}
if ((args-0)->m_type != KindOfObject) {
tvCastToObjectInPlace(args-0);
}
rv->m_data.num = (fh_msg_set_queue((Value*)(args-0), (Value*)(args-1))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_msg_set_queue(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
if ((args-1)->m_type == KindOfArray && (args-0)->m_type == KindOfObject) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_msg_set_queue((Value*)(args-0), (Value*)(args-1))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_msg_set_queue(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("msg_set_queue", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Array HPHP::f_msg_stat_queue(HPHP::Object const&)
_ZN4HPHP16f_msg_stat_queueERKNS_6ObjectE
(return value) => rax
_rv => rdi
queue => rsi
*/
Value* fh_msg_stat_queue(Value* _rv, Value* queue) asm("_ZN4HPHP16f_msg_stat_queueERKNS_6ObjectE");
TypedValue * fg1_msg_stat_queue(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_msg_stat_queue(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfArray;
tvCastToObjectInPlace(args-0);
fh_msg_stat_queue((Value*)(rv), (Value*)(args-0));
if (rv->m_data.num == 0LL) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_msg_stat_queue(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if ((args-0)->m_type == KindOfObject) {
rv._count = 0;
rv.m_type = KindOfArray;
fh_msg_stat_queue((Value*)(&(rv)), (Value*)(args-0));
if (rv.m_data.num == 0LL) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_msg_stat_queue(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("msg_stat_queue", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_sem_acquire(HPHP::Object const&)
_ZN4HPHP13f_sem_acquireERKNS_6ObjectE
(return value) => rax
sem_identifier => rdi
*/
bool fh_sem_acquire(Value* sem_identifier) asm("_ZN4HPHP13f_sem_acquireERKNS_6ObjectE");
TypedValue * fg1_sem_acquire(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_sem_acquire(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
tvCastToObjectInPlace(args-0);
rv->m_data.num = (fh_sem_acquire((Value*)(args-0))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_sem_acquire(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if ((args-0)->m_type == KindOfObject) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_sem_acquire((Value*)(args-0))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_sem_acquire(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("sem_acquire", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Variant HPHP::f_sem_get(long long, long long, long long, bool)
_ZN4HPHP9f_sem_getExxxb
(return value) => rax
_rv => rdi
key => rsi
max_acquire => rdx
perm => rcx
auto_release => r8
*/
TypedValue* fh_sem_get(TypedValue* _rv, long long key, long long max_acquire, long long perm, bool auto_release) asm("_ZN4HPHP9f_sem_getExxxb");
TypedValue * fg1_sem_get(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_sem_get(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
switch (count) {
default: // count >= 4
if ((args-3)->m_type != KindOfBoolean) {
tvCastToBooleanInPlace(args-3);
}
case 3:
if ((args-2)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-2);
}
case 2:
if ((args-1)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-1);
}
case 1:
break;
}
if ((args-0)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-0);
}
fh_sem_get((rv), (long long)(args[-0].m_data.num), (count > 1) ? (long long)(args[-1].m_data.num) : (long long)(1), (count > 2) ? (long long)(args[-2].m_data.num) : (long long)(0666), (count > 3) ? (bool)(args[-3].m_data.num) : (bool)(true));
if (rv->m_type == KindOfUninit) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_sem_get(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count >= 1LL && count <= 4LL) {
if ((count <= 3 || (args-3)->m_type == KindOfBoolean) && (count <= 2 || (args-2)->m_type == KindOfInt64) && (count <= 1 || (args-1)->m_type == KindOfInt64) && (args-0)->m_type == KindOfInt64) {
fh_sem_get((&(rv)), (long long)(args[-0].m_data.num), (count > 1) ? (long long)(args[-1].m_data.num) : (long long)(1), (count > 2) ? (long long)(args[-2].m_data.num) : (long long)(0666), (count > 3) ? (bool)(args[-3].m_data.num) : (bool)(true));
if (rv.m_type == KindOfUninit) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 4);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_sem_get(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 4);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("sem_get", count, 1, 4, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 4);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_sem_release(HPHP::Object const&)
_ZN4HPHP13f_sem_releaseERKNS_6ObjectE
(return value) => rax
sem_identifier => rdi
*/
bool fh_sem_release(Value* sem_identifier) asm("_ZN4HPHP13f_sem_releaseERKNS_6ObjectE");
TypedValue * fg1_sem_release(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_sem_release(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
tvCastToObjectInPlace(args-0);
rv->m_data.num = (fh_sem_release((Value*)(args-0))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_sem_release(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if ((args-0)->m_type == KindOfObject) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_sem_release((Value*)(args-0))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_sem_release(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("sem_release", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_sem_remove(HPHP::Object const&)
_ZN4HPHP12f_sem_removeERKNS_6ObjectE
(return value) => rax
sem_identifier => rdi
*/
bool fh_sem_remove(Value* sem_identifier) asm("_ZN4HPHP12f_sem_removeERKNS_6ObjectE");
TypedValue * fg1_sem_remove(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_sem_remove(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
tvCastToObjectInPlace(args-0);
rv->m_data.num = (fh_sem_remove((Value*)(args-0))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_sem_remove(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if ((args-0)->m_type == KindOfObject) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_sem_remove((Value*)(args-0))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_sem_remove(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("sem_remove", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Variant HPHP::f_shm_attach(long long, long long, long long)
_ZN4HPHP12f_shm_attachExxx
(return value) => rax
_rv => rdi
shm_key => rsi
shm_size => rdx
shm_flag => rcx
*/
TypedValue* fh_shm_attach(TypedValue* _rv, long long shm_key, long long shm_size, long long shm_flag) asm("_ZN4HPHP12f_shm_attachExxx");
TypedValue * fg1_shm_attach(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_shm_attach(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
switch (count) {
default: // count >= 3
if ((args-2)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-2);
}
case 2:
if ((args-1)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-1);
}
case 1:
break;
}
if ((args-0)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-0);
}
fh_shm_attach((rv), (long long)(args[-0].m_data.num), (count > 1) ? (long long)(args[-1].m_data.num) : (long long)(10000), (count > 2) ? (long long)(args[-2].m_data.num) : (long long)(0666));
if (rv->m_type == KindOfUninit) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_shm_attach(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count >= 1LL && count <= 3LL) {
if ((count <= 2 || (args-2)->m_type == KindOfInt64) && (count <= 1 || (args-1)->m_type == KindOfInt64) && (args-0)->m_type == KindOfInt64) {
fh_shm_attach((&(rv)), (long long)(args[-0].m_data.num), (count > 1) ? (long long)(args[-1].m_data.num) : (long long)(10000), (count > 2) ? (long long)(args[-2].m_data.num) : (long long)(0666));
if (rv.m_type == KindOfUninit) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_shm_attach(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("shm_attach", count, 1, 3, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_shm_detach(long long)
_ZN4HPHP12f_shm_detachEx
(return value) => rax
shm_identifier => rdi
*/
bool fh_shm_detach(long long shm_identifier) asm("_ZN4HPHP12f_shm_detachEx");
TypedValue * fg1_shm_detach(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_shm_detach(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
tvCastToInt64InPlace(args-0);
rv->m_data.num = (fh_shm_detach((long long)(args[-0].m_data.num))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_shm_detach(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if ((args-0)->m_type == KindOfInt64) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_shm_detach((long long)(args[-0].m_data.num))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_shm_detach(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("shm_detach", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_shm_remove(long long)
_ZN4HPHP12f_shm_removeEx
(return value) => rax
shm_identifier => rdi
*/
bool fh_shm_remove(long long shm_identifier) asm("_ZN4HPHP12f_shm_removeEx");
TypedValue * fg1_shm_remove(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_shm_remove(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
tvCastToInt64InPlace(args-0);
rv->m_data.num = (fh_shm_remove((long long)(args[-0].m_data.num))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_shm_remove(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if ((args-0)->m_type == KindOfInt64) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_shm_remove((long long)(args[-0].m_data.num))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_shm_remove(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("shm_remove", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Variant HPHP::f_shm_get_var(long long, long long)
_ZN4HPHP13f_shm_get_varExx
(return value) => rax
_rv => rdi
shm_identifier => rsi
variable_key => rdx
*/
TypedValue* fh_shm_get_var(TypedValue* _rv, long long shm_identifier, long long variable_key) asm("_ZN4HPHP13f_shm_get_varExx");
TypedValue * fg1_shm_get_var(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_shm_get_var(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if ((args-1)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-1);
}
if ((args-0)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-0);
}
fh_shm_get_var((rv), (long long)(args[-0].m_data.num), (long long)(args[-1].m_data.num));
if (rv->m_type == KindOfUninit) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_shm_get_var(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
if ((args-1)->m_type == KindOfInt64 && (args-0)->m_type == KindOfInt64) {
fh_shm_get_var((&(rv)), (long long)(args[-0].m_data.num), (long long)(args[-1].m_data.num));
if (rv.m_type == KindOfUninit) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_shm_get_var(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("shm_get_var", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_shm_has_var(long long, long long)
_ZN4HPHP13f_shm_has_varExx
(return value) => rax
shm_identifier => rdi
variable_key => rsi
*/
bool fh_shm_has_var(long long shm_identifier, long long variable_key) asm("_ZN4HPHP13f_shm_has_varExx");
TypedValue * fg1_shm_has_var(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_shm_has_var(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
if ((args-1)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-1);
}
if ((args-0)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-0);
}
rv->m_data.num = (fh_shm_has_var((long long)(args[-0].m_data.num), (long long)(args[-1].m_data.num))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_shm_has_var(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
if ((args-1)->m_type == KindOfInt64 && (args-0)->m_type == KindOfInt64) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_shm_has_var((long long)(args[-0].m_data.num), (long long)(args[-1].m_data.num))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_shm_has_var(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("shm_has_var", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_shm_put_var(long long, long long, HPHP::Variant const&)
_ZN4HPHP13f_shm_put_varExxRKNS_7VariantE
(return value) => rax
shm_identifier => rdi
variable_key => rsi
variable => rdx
*/
bool fh_shm_put_var(long long shm_identifier, long long variable_key, TypedValue* variable) asm("_ZN4HPHP13f_shm_put_varExxRKNS_7VariantE");
TypedValue * fg1_shm_put_var(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_shm_put_var(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
if ((args-1)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-1);
}
if ((args-0)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-0);
}
rv->m_data.num = (fh_shm_put_var((long long)(args[-0].m_data.num), (long long)(args[-1].m_data.num), (args-2))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_shm_put_var(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 3LL) {
if ((args-1)->m_type == KindOfInt64 && (args-0)->m_type == KindOfInt64) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_shm_put_var((long long)(args[-0].m_data.num), (long long)(args[-1].m_data.num), (args-2))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_shm_put_var(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("shm_put_var", count, 3, 3, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_shm_remove_var(long long, long long)
_ZN4HPHP16f_shm_remove_varExx
(return value) => rax
shm_identifier => rdi
variable_key => rsi
*/
bool fh_shm_remove_var(long long shm_identifier, long long variable_key) asm("_ZN4HPHP16f_shm_remove_varExx");
TypedValue * fg1_shm_remove_var(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) __attribute__((noinline,cold));
TypedValue * fg1_shm_remove_var(TypedValue* rv, HPHP::VM::ActRec* ar, long long count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
if ((args-1)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-1);
}
if ((args-0)->m_type != KindOfInt64) {
tvCastToInt64InPlace(args-0);
}
rv->m_data.num = (fh_shm_remove_var((long long)(args[-0].m_data.num), (long long)(args[-1].m_data.num))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_shm_remove_var(HPHP::VM::ActRec *ar) {
TypedValue rv;
long long count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
if ((args-1)->m_type == KindOfInt64 && (args-0)->m_type == KindOfInt64) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_shm_remove_var((long long)(args[-0].m_data.num), (long long)(args[-1].m_data.num))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_shm_remove_var(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("shm_remove_var", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
} // !HPHP
| 33.603284 | 332 | 0.629929 | burhan |
a9910a040a66f02b9a400c54c40bdaa89c9e0521 | 873 | hpp | C++ | builder/include/builder/CarBuilder.hpp | hwnBEAST/cpp_design_patterns | 42e04644a9c4ce8ff8bafefd37b2cee8d0628f45 | [
"MIT"
] | null | null | null | builder/include/builder/CarBuilder.hpp | hwnBEAST/cpp_design_patterns | 42e04644a9c4ce8ff8bafefd37b2cee8d0628f45 | [
"MIT"
] | null | null | null | builder/include/builder/CarBuilder.hpp | hwnBEAST/cpp_design_patterns | 42e04644a9c4ce8ff8bafefd37b2cee8d0628f45 | [
"MIT"
] | null | null | null | /**
* @file
*
* @brief
*
* @copyright Copyright (C) 2021. Full licence notice is in the LICENCE file.
*/
#pragma once
#include "builder/Car.hpp"
#include <cstdint>
#include <string>
namespace Builder
{
class CarBuilder
{
public:
/*--- Constructors ---*/
CarBuilder(const CarBuilder& other) = delete;
CarBuilder& operator=(const CarBuilder& other) = delete;
CarBuilder();
/*--- Methods ---*/
Builder::CarBuilder& color(Car::Color newColor);
Builder::CarBuilder& numberOfPassengers(std::uint8_t newNumberOfPassengers);
Builder::CarBuilder& ownerName(std::string newOwnerName);
Builder::CarBuilder& topSpeedKiloMperH(uint32_t newTopSpeed);
Builder::CarBuilder& manufacturerName(std::string newName);
Builder::CarBuilder& modelName(std::string newName);
Car build();
private:
Car car;
};
} // namespace Builder | 21.825 | 80 | 0.689576 | hwnBEAST |