hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
dec07522838bb529579d678c2d24200377ab029c
604
cpp
C++
example/asyncdeamon.cpp
apppur/canna
bdcce4f16be56da40445fec79959b6bc90003573
[ "MIT" ]
null
null
null
example/asyncdeamon.cpp
apppur/canna
bdcce4f16be56da40445fec79959b6bc90003573
[ "MIT" ]
null
null
null
example/asyncdeamon.cpp
apppur/canna
bdcce4f16be56da40445fec79959b6bc90003573
[ "MIT" ]
null
null
null
#include <thread> #include <functional> #include <stdio.h> #include <memory> #include "asyncclient.h" #include "asyncserver.h" int main(int argc, char** argv) { asyncclient async1; asyncclient async2; asyncclient async3; asyncserver server; std::thread t1(std::bind(&asyncclient::start, &async1)); std::thread t2(std::bind(&asyncclient::start, &async2)); std::thread t3(std::bind(&asyncclient::start, &async3)); std::thread t4(std::bind(&asyncserver::run, &server)); t1.detach(); t2.detach(); t3.detach(); t4.detach(); getchar(); return 0; }
20.133333
60
0.642384
apppur
dec60f7023fc0c5f3a3f7e986d258647535c871b
499
cc
C++
leetcode/src/balaced_binary_tree.cc
plusplus7/solutions
31233c13ee2bd0da6a907a24adbaf5b49ebf843c
[ "CC0-1.0" ]
5
2016-04-29T07:14:23.000Z
2020-01-07T04:56:11.000Z
leetcode/src/balaced_binary_tree.cc
plusplus7/solutions
31233c13ee2bd0da6a907a24adbaf5b49ebf843c
[ "CC0-1.0" ]
null
null
null
leetcode/src/balaced_binary_tree.cc
plusplus7/solutions
31233c13ee2bd0da6a907a24adbaf5b49ebf843c
[ "CC0-1.0" ]
1
2016-04-29T07:14:32.000Z
2016-04-29T07:14:32.000Z
#include <iostream> using namespace std; class Solution { public: int dfs(TreeNode *node) { if (node == NULL) return 0; return max(dfs(node->left, dep+1), dfs(node->right, dep+1))+1; } bool isBalanced(TreeNode *root) { if (root == NULL) return true; if (abs(dfs(node->left)-dfs(node->right)) > 1) return false; else return isBalanced(root->left) == true && isBalanced(root->right) == true; } };
26.263158
85
0.537074
plusplus7
ded00ab6f7ed575fdcb08faaef40996cf6db9fbf
7,069
cpp
C++
libs/dev/Math/MathEngineTest/Matrix_Constructor.cpp
Norseman055/immaterial-engine
6aca0fad64f5b2b9fe6eb351528a79a39dc94625
[ "MIT" ]
null
null
null
libs/dev/Math/MathEngineTest/Matrix_Constructor.cpp
Norseman055/immaterial-engine
6aca0fad64f5b2b9fe6eb351528a79a39dc94625
[ "MIT" ]
null
null
null
libs/dev/Math/MathEngineTest/Matrix_Constructor.cpp
Norseman055/immaterial-engine
6aca0fad64f5b2b9fe6eb351528a79a39dc94625
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- // HEADER FILES: //--------------------------------------------------------------------------- #include "UnitTest.h" #include "MathEngine.h" #define eq Util::isEqual #define MATH_TOLERANCE 0.0001f //--------------------------------------------------------------------------- // TESTS: //--------------------------------------------------------------------------- TEST( Matrix_default_constructor, matix_tests ) { Matrix M; CHECK( M[m0] == 0.0f ); CHECK( M[m1] == 0.0f ); CHECK( M[m2] == 0.0f ); CHECK( M[m3] == 0.0f ); CHECK( M[m4] == 0.0f ); CHECK( M[m5] == 0.0f ); CHECK( M[m6] == 0.0f ); CHECK( M[m7] == 0.0f ); CHECK( M[m8] == 0.0f ); CHECK( M[m9] == 0.0f ); CHECK( M[m10] == 0.0f ); CHECK( M[m11] == 0.0f ); CHECK( M[m12] == 0.0f ); CHECK( M[m13] == 0.0f ); CHECK( M[m14] == 0.0f ); CHECK( M[m15] == 0.0f ); } TEST( Matrix_vector_constructor, matix_tests ) { Vect V0(1.0f,2.0f,3.0f,4.0f); Vect V1(7.0f,6.0f,5.0f,3.0f); Vect V2(-4.0f,-2.0f,-1.0f,-4.0f); Vect V3(9.0f,-7.0f,-2.0f,5.0f); CHECK( V0[x] == 1.0f ); CHECK( V0[y] == 2.0f ); CHECK( V0[z] == 3.0f ); CHECK( V0[w] == 4.0f ); CHECK( V1[x] == 7.0f ); CHECK( V1[y] == 6.0f ); CHECK( V1[z] == 5.0f ); CHECK( V1[w] == 3.0f ); CHECK( V2[x] == -4.0f ); CHECK( V2[y] == -2.0f ); CHECK( V2[z] == -1.0f ); CHECK( V2[w] == -4.0f ); CHECK( V3[x] == 9.0f ); CHECK( V3[y] == -7.0f ); CHECK( V3[z] == -2.0f ); CHECK( V3[w] == 5.0f ); Matrix M(V0,V1,V2,V3); CHECK( M[m0] == 1.0f ); CHECK( M[m1] == 2.0f ); CHECK( M[m2] == 3.0f ); CHECK( M[m3] == 4.0f ); CHECK( M[m4] == 7.0f ); CHECK( M[m5] == 6.0f ); CHECK( M[m6] == 5.0f ); CHECK( M[m7] == 3.0f ); CHECK( M[m8] == -4.0f ); CHECK( M[m9] == -2.0f ); CHECK( M[m10] == -1.0f ); CHECK( M[m11] == -4.0f ); CHECK( M[m12] == 9.0f ); CHECK( M[m13] == -7.0f ); CHECK( M[m14] == -2.0f ); CHECK( M[m15] == 5.0f ); } TEST( Matrix_copy_constructor, matix_tests ) { Vect V0(1.0f,2.0f,3.0f,4.0f); Vect V1(7.0f,6.0f,5.0f,3.0f); Vect V2(-4.0f,-2.0f,-1.0f,-4.0f); Vect V3(9.0f,-7.0f,-2.0f,5.0f); CHECK( V0[x] == 1.0f ); CHECK( V0[y] == 2.0f ); CHECK( V0[z] == 3.0f ); CHECK( V0[w] == 4.0f ); CHECK( V1[x] == 7.0f ); CHECK( V1[y] == 6.0f ); CHECK( V1[z] == 5.0f ); CHECK( V1[w] == 3.0f ); CHECK( V2[x] == -4.0f ); CHECK( V2[y] == -2.0f ); CHECK( V2[z] == -1.0f ); CHECK( V2[w] == -4.0f ); CHECK( V3[x] == 9.0f ); CHECK( V3[y] == -7.0f ); CHECK( V3[z] == -2.0f ); CHECK( V3[w] == 5.0f ); Matrix M(V0,V1,V2,V3); Matrix N( M ); CHECK( N[m0] == 1.0f ); CHECK( N[m1] == 2.0f ); CHECK( N[m2] == 3.0f ); CHECK( N[m3] == 4.0f ); CHECK( N[m4] == 7.0f ); CHECK( N[m5] == 6.0f ); CHECK( N[m6] == 5.0f ); CHECK( N[m7] == 3.0f ); CHECK( N[m8] == -4.0f ); CHECK( N[m9] == -2.0f ); CHECK( N[m10] == -1.0f ); CHECK( N[m11] == -4.0f ); CHECK( N[m12] == 9.0f ); CHECK( N[m13] == -7.0f ); CHECK( N[m14] == -2.0f ); CHECK( N[m15] == 5.0f ); CHECK( M[m0] == 1.0f ); CHECK( M[m1] == 2.0f ); CHECK( M[m2] == 3.0f ); CHECK( M[m3] == 4.0f ); CHECK( M[m4] == 7.0f ); CHECK( M[m5] == 6.0f ); CHECK( M[m6] == 5.0f ); CHECK( M[m7] == 3.0f ); CHECK( M[m8] == -4.0f ); CHECK( M[m9] == -2.0f ); CHECK( M[m10] == -1.0f ); CHECK( M[m11] == -4.0f ); CHECK( M[m12] == 9.0f ); CHECK( M[m13] == -7.0f ); CHECK( M[m14] == -2.0f ); CHECK( M[m15] == 5.0f ); } TEST( Destructor_constuctor, matrix_tests ) { Vect V0(1.0f,2.0f,3.0f,4.0f); Vect V1(7.0f,6.0f,5.0f,3.0f); Vect V2(-4.0f,-2.0f,-1.0f,-4.0f); Vect V3(9.0f,-7.0f,-2.0f,5.0f); Matrix M(V0,V1,V2,V3); Matrix *pM = &M; pM->~Matrix(); CHECK(1); } TEST( MatrixRotAxisAngle, matrix_tests ) { // Axis and Angle Type Constructor: Vect v11( 2.0f, 53.0f, 24.0f); Matrix m54( ROT_AXIS_ANGLE, v11, MATH_PI3 ); // => Vect v11( 2.0f, 53.0f, 24.0f); \n");); // => Matrix m54(ROT_AXIS_ANGLE, v11, MATH_PI3 );\n");); CHECK( eq(m54[m0], 0.5005f, MATH_TOLERANCE) ); CHECK( eq(m54[m1], 0.3726f, MATH_TOLERANCE) ); CHECK( eq(m54[m2],-0.7813f, MATH_TOLERANCE) ); CHECK( m54[m3] == 0.0f ); CHECK( eq(m54[m4],-0.3413f, MATH_TOLERANCE) ); CHECK( eq(m54[m5], 0.9144f, MATH_TOLERANCE) ); CHECK( eq(m54[m6], 0.2174f, MATH_TOLERANCE) ); CHECK( (m54[m7] == 0.0f) ); CHECK( eq(m54[m8], 0.7955f, MATH_TOLERANCE) ); CHECK( eq(m54[m9], 0.1579f, MATH_TOLERANCE) ); CHECK( eq(m54[m10], 0.5849f, MATH_TOLERANCE) ); CHECK( (m54[m11] == 0.0f) ); CHECK( (m54[m12] == 0.0f) ); CHECK( (m54[m13] == 0.0f) ); CHECK( (m54[m14] == 0.0f) ); CHECK( (m54[m15] == 1.0f) ); } TEST( MatrixRotOrient, matrix_tests ) { // Orientation Type Constructor: Vect v15( 2.0f, 53.0f, 24.0f); Vect v16( 0.0f, -24.0f, 53.0f); Matrix m56(ROT_ORIENT, v15, v16 ); CHECK( eq(m56[m0],-0.9994f, MATH_TOLERANCE) ); CHECK( eq(m56[m1], 0.0313f, MATH_TOLERANCE) ); CHECK( eq(m56[m2], 0.0142f, MATH_TOLERANCE) ); CHECK( (m56[m3] == 0.0f) ); CHECK( eq(m56[m4], 0.0000f, MATH_TOLERANCE) ); CHECK( eq(m56[m5],-0.4125f, MATH_TOLERANCE) ); CHECK( eq(m56[m6], 0.9110f, MATH_TOLERANCE) ); CHECK( (m56[m7] == 0.0f) ); CHECK( eq(m56[m8], 0.0344f, MATH_TOLERANCE) ); CHECK( eq(m56[m9], 0.9104f, MATH_TOLERANCE) ); CHECK( eq(m56[m10], 0.4123f, MATH_TOLERANCE) ); CHECK( (m56[m11] == 0.0f) ); CHECK( (m56[m12] == 0.0f) ); CHECK( (m56[m13] == 0.0f) ); CHECK( (m56[m14] == 0.0f) ); CHECK( (m56[m15] == 1.0f) ); } TEST( MatrixRotInverseOrient, matrix_tests) { // Orientation Type Constructor: Vect v17( 2.0f, 53.0f, 24.0f); Vect v18( 0.0f, -24.0f, 53.0f); Matrix m57(ROT_INVERSE_ORIENT, v17, v18 ); CHECK( eq(m57[m0],-0.9994f, MATH_TOLERANCE) ); CHECK( eq(m57[m1], 0.0000f, MATH_TOLERANCE) ); CHECK( eq(m57[m2], 0.0344f, MATH_TOLERANCE) ); CHECK( (m57[m3] == 0.0f) ); CHECK( eq(m57[m4], 0.0313f, MATH_TOLERANCE) ); CHECK( eq(m57[m5],-0.4125f, MATH_TOLERANCE) ); CHECK( eq(m57[m6], 0.9104f, MATH_TOLERANCE) ); CHECK( (m57[m7] == 0.0f) ); CHECK( eq(m57[m8], 0.0142f, MATH_TOLERANCE) ); CHECK( eq(m57[m9], 0.9110f, MATH_TOLERANCE) ); CHECK( eq(m57[m10], 0.4123f, MATH_TOLERANCE) ); CHECK( (m57[m11] == 0.0f) ); CHECK( (m57[m12] == 0.0f) ); CHECK( (m57[m13] == 0.0f) ); CHECK( (m57[m14] == 0.0f) ); CHECK( (m57[m15] == 1.0f) ); } TEST( MatrixQuaternion, matrix_tests) { // Quaternion Type Constructor: Matrix Rxyz1(ROT_XYZ, MATH_PI3, MATH_5PI8, MATH_PI4 ); Quat Qxyz1(Rxyz1); Matrix Mxyz1( Qxyz1 ); CHECK( eq(Mxyz1[m0],-0.2705f,MATH_TOLERANCE) ); CHECK( eq(Mxyz1[m1],-0.2705f,MATH_TOLERANCE) ); CHECK( eq(Mxyz1[m2],-0.9238f,MATH_TOLERANCE) ); CHECK( (Mxyz1[m3] == 0.0f) ); CHECK( eq(Mxyz1[m4], 0.2122f,MATH_TOLERANCE) ); CHECK( eq(Mxyz1[m5], 0.9193f,MATH_TOLERANCE) ); CHECK( eq(Mxyz1[m6],-0.3314f,MATH_TOLERANCE) ); CHECK( (Mxyz1[m7] == 0.0f) ); CHECK( eq(Mxyz1[m8], 0.9390f,MATH_TOLERANCE) ); CHECK( eq(Mxyz1[m9],-0.2857f,MATH_TOLERANCE) ); CHECK( eq(Mxyz1[m10],-0.1913f,MATH_TOLERANCE) ); CHECK( (Mxyz1[m11] == 0.0f) ); CHECK( (Mxyz1[m12] == 0.0f) ); CHECK( (Mxyz1[m13] == 0.0f) ); CHECK( (Mxyz1[m14] == 0.0f) ); CHECK( (Mxyz1[m15] == 1.0f) ); }
26.776515
77
0.530485
Norseman055
ded12ff193fedcafbc3acfc7a1a1a355ddaec06d
1,170
cpp
C++
nodes/DataLoggerNode/DataLoggerProcess.cpp
dgitz/eROS
0ff4b5dda5f3d445784d43745597bb5c31d1997c
[ "MIT" ]
2
2016-11-28T13:01:12.000Z
2021-03-26T22:02:02.000Z
nodes/DataLoggerNode/DataLoggerProcess.cpp
dgitz/eROS
0ff4b5dda5f3d445784d43745597bb5c31d1997c
[ "MIT" ]
46
2016-10-24T13:34:48.000Z
2019-11-14T23:47:22.000Z
nodes/DataLoggerNode/DataLoggerProcess.cpp
dgitz/eros
0ff4b5dda5f3d445784d43745597bb5c31d1997c
[ "MIT" ]
2
2021-07-20T10:11:45.000Z
2021-08-10T11:31:41.000Z
#include <eros/DataLogger/DataLoggerProcess.h> using namespace eros; using namespace eros_nodes; DataLoggerProcess::DataLoggerProcess() : log_directory(""), log_directory_available(false), logfile_duration(-1.0), logging_enabled(false), snapshot_mode(true) { } DataLoggerProcess::~DataLoggerProcess() { } Diagnostic::DiagnosticDefinition DataLoggerProcess::finish_initialization() { Diagnostic::DiagnosticDefinition diag; return diag; } void DataLoggerProcess::reset() { } Diagnostic::DiagnosticDefinition DataLoggerProcess::update(double t_dt, double t_ros_time) { Diagnostic::DiagnosticDefinition diag = base_update(t_dt, t_ros_time); ready_to_arm.ready_to_arm = true; ready_to_arm.diag = convert(diag); return diag; } std::vector<Diagnostic::DiagnosticDefinition> DataLoggerProcess::new_commandmsg(eros::command msg) { (void)msg; // Not used yet. std::vector<Diagnostic::DiagnosticDefinition> diag_list; return diag_list; } std::vector<Diagnostic::DiagnosticDefinition> DataLoggerProcess::check_programvariables() { std::vector<Diagnostic::DiagnosticDefinition> diag_list; return diag_list; }
33.428571
100
0.761538
dgitz
ded97349fac892fd74f4c924f410dd860981d4da
19,721
inl
C++
ivp/havana/havok/hk_math/vector_fpu/vector_fpu.inl
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
ivp/havana/havok/hk_math/vector_fpu/vector_fpu.inl
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
ivp/havana/havok/hk_math/vector_fpu/vector_fpu.inl
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
inline void hk_VecFPU::fpu_add_multiple_row(hk_real *target_adress,hk_real *source_adress,hk_real factor,int size,hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { //we have to calculate the block size and shift adresses to lower aligned adresses long result_adress = long(source_adress) & hk_VecFPU_MEM_MASK_FLOAT; target_adress = (hk_real *)( long (target_adress) & hk_VecFPU_MEM_MASK_FLOAT); size += (long(source_adress)-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT; source_adress=(hk_real *)result_adress; } #if defined(IVP_USE_PS2_VU0) asm __volatile__(" mfc1 $8,%3 qmtc2 $8,vf5 # vf5.x factor 1: lqc2 vf4,0x0(%1) # vf4 *source vmulx.xyzw vf6,vf4,vf5 # vf6 *source * factor lqc2 vf4,0x0(%0) addi %0, 0x10 vadd.xyzw vf6,vf4,vf6 # vf6 = *dest + factor * *source addi %2,-4 addi %1, 0x10 sqc2 vf6,-0x10(%0) bgtz %2,1b nop " : /* no output */ : "r" (target_adress), "r" (source_adress) , "r" (size), "f" (factor) : "$8" , "memory"); #else #if 0 # if defined(IVP_WILLAMETTE) ; __m128d factor128=_mm_set1_pd(factor); for(int i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) { __m128d source_d=_mm_load_pd(source_adress); __m128d prod_d=_mm_mul_pd(factor128,source_d); __m128d target_d=_mm_load_pd(target_adress); target_d=_mm_add_pd(prod_d,target_d); _mm_store_pd(target_adress,target_d); target_adress+=hk_VecFPU_SIZE_FLOAT; source_adress+=hk_VecFPU_SIZE_FLOAT; } #endif #endif for(int i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) { # if hk_VecFPU_SIZE_FLOAT == 2 hk_real a = source_adress[0] * factor; hk_real b = source_adress[1] * factor; a += target_adress[0]; b += target_adress[1]; target_adress[0] = a; target_adress[1] = b; # elif hk_VecFPU_SIZE_FLOAT == 4 hk_real a = source_adress[0] * factor; hk_real b = source_adress[1] * factor; hk_real c = source_adress[2] * factor; hk_real d = source_adress[3] * factor; a += target_adress[0]; b += target_adress[1]; c += target_adress[2]; d += target_adress[3]; target_adress[0] = a; target_adress[1] = b; target_adress[2] = c; target_adress[3] = d; # else shit # endif target_adress+=hk_VecFPU_SIZE_FLOAT; source_adress+=hk_VecFPU_SIZE_FLOAT; } #endif } inline hk_real hk_VecFPU::fpu_large_dot_product(hk_real *base_a, hk_real *base_b, int size, hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { //we have to calculate the block size and shift adresses to lower aligned adresses long result_adress = long(base_a) & hk_VecFPU_MEM_MASK_FLOAT; base_b = (hk_real *)( long (base_b) & hk_VecFPU_MEM_MASK_FLOAT); size += (long(base_a)-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT; // because start changed base_a=(hk_real *)result_adress; } # if defined(IVP_WILLAMETTE) IVP_IF_WILLAMETTE_OPT(IVP_Environment_Manager::get_environment_manager()->ivp_willamette_optimization) { __m128d sum128 =_mm_set1_pd(0.0f); int i; for(i=size;i>=hk_VecFPU_SIZE_FLOAT; i-= hk_VecFPU_SIZE_FLOAT) { __m128d mult1=_mm_load_pd(base_a); __m128d mult2=_mm_load_pd(base_b); __m128d prod =_mm_mul_pd(mult1,mult2); sum128 =_mm_add_pd(prod,sum128); base_a += hk_VecFPU_SIZE_FLOAT; base_b += hk_VecFPU_SIZE_FLOAT; } __m128d dummy,low,high; low=sum128; dummy=sum128; //_mm_shuffle_pd(sum128,sum128,1); //swap high and low sum128=_mm_unpackhi_pd(sum128,dummy); high=sum128; __m128d sum64=_mm_add_sd(low,high); __m128d res=sum64; //_mm_shuffle_pd(sum64,sum64,1); hk_real result_sum; _mm_store_sd(&result_sum,res); for(;i>=0;i--) { result_sum += base_a[i] * base_b[i]; } return result_sum; } else { hk_real sum=0.0f; for(int i=size-1;i>=0;i--) { sum += base_a[i] * base_b[i]; } return sum; } #else hk_real sum=0.0f; for(int i=size-1;i>=0;i--) { sum += base_a[i] * base_b[i]; } return sum; #endif } inline void hk_VecFPU::fpu_multiply_row(hk_real *target_adress,hk_real factor,int size,hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { //we have to calculate the block size and shift adresses to lower aligned adresses long adress,result_adress; adress=(long)target_adress; result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT; size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT; target_adress=(hk_real *)result_adress; } #if 0 #ifdef IVP_WILLAMETTE __m128d factor128=_mm_set1_pd(factor); int i; for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) { __m128d target_d=_mm_load_pd(target_adress); target_d=_mm_mul_pd(factor128,target_d); _mm_store_pd(target_adress,target_d); target_adress+=hk_VecFPU_SIZE_FLOAT; } #endif #endif int i; for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) { # if hk_VecFPU_SIZE_FLOAT == 2 hk_real a = target_adress[0] * factor; hk_real b = target_adress[1] * factor; target_adress[0] = a; target_adress[1] = b; # elif hk_VecFPU_SIZE_FLOAT == 4 hk_real a = target_adress[0] * factor; hk_real b = target_adress[1] * factor; hk_real c = target_adress[2] * factor; hk_real d = target_adress[3] * factor; target_adress[0] = a; target_adress[1] = b; target_adress[2] = c; target_adress[3] = d; # else shit # endif target_adress+=hk_VecFPU_SIZE_FLOAT; } } // #+# sparc says rui, optimize for non vector units ( hk_VecFPU_SIZE_FLOAT = 4 ) inline void hk_VecFPU::fpu_exchange_rows(hk_real *target_adress1,hk_real *target_adress2,int size,hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { //we have to calculate the block size and shift adresses to lower aligned adresses long adress,result_adress; adress=(long)target_adress1; result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT; size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT; target_adress1=(hk_real *)result_adress; adress=(long)target_adress2; adress=adress & hk_VecFPU_MEM_MASK_FLOAT; target_adress2=(hk_real *)adress; } #if 0 int i; for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) { __m128d a_d=_mm_load_pd(target_adress1); __m128d b_d=_mm_load_pd(target_adress2); _mm_store_pd(target_adress1,b_d); _mm_store_pd(target_adress2,a_d); target_adress1+=hk_VecFPU_SIZE_FLOAT; target_adress2+=hk_VecFPU_SIZE_FLOAT; } #endif int i; for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) { hk_real h; # if hk_VecFPU_SIZE_FLOAT == 2 h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h; h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h; # elif hk_VecFPU_SIZE_FLOAT == 4 h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h; h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h; h=target_adress1[2]; target_adress1[2]=target_adress2[2]; target_adress2[2]=h; h=target_adress1[3]; target_adress1[3]=target_adress2[3]; target_adress2[3]=h; # else shit # endif target_adress1+=hk_VecFPU_SIZE_FLOAT; target_adress2+=hk_VecFPU_SIZE_FLOAT; } } inline void hk_VecFPU::fpu_copy_rows(hk_real *target_adress,hk_real *source_adress,int size,hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { //we have to calculate the block size and shift adresses to lower aligned adresses long adress,result_adress; adress=(long)source_adress; result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT; size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT; source_adress=(hk_real *)result_adress; adress=(long)target_adress; adress=adress & hk_VecFPU_MEM_MASK_FLOAT; target_adress=(hk_real *)adress; } #if 0 int i; for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) { __m128d target_d=_mm_load_pd(source_adress); _mm_store_pd(target_adress,target_d); target_adress+=hk_VecFPU_SIZE_FLOAT; source_adress+=hk_VecFPU_SIZE_FLOAT; } } #endif int i; for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) { int j; for(j=0;j<hk_VecFPU_SIZE_FLOAT;j++) { target_adress[j] = source_adress[j]; } target_adress+=hk_VecFPU_SIZE_FLOAT; source_adress+=hk_VecFPU_SIZE_FLOAT; } } inline void hk_VecFPU::fpu_set_row_to_zero(hk_real *target_adress,int size,hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { long adress,result_adress; adress=(long)target_adress; result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT; size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT; target_adress=(hk_real *)result_adress; } #if 0 __m128d zero128=_mm_set1_pd(0.0f); int i; for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) { _mm_store_pd(target_adress,zero128); target_adress+=hk_VecFPU_SIZE_FLOAT; } } #endif int i; for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) { int j; for(j=0;j<hk_VecFPU_SIZE_FLOAT;j++) { target_adress[j] = 0.0f; } target_adress+=hk_VecFPU_SIZE_FLOAT; } } inline int hk_VecFPU::calc_aligned_row_len(int unaligned_len,hk_real *dummy_type) { //dummy type is used for overloading return (unaligned_len+hk_VecFPU_SIZE_FLOAT-1)&hk_VecFPU_MASK_FLOAT; } //---------------------------------------------------------------------------------------------------------------------- inline void hk_VecFPU::fpu_add_multiple_row(hk_double *target_adress,hk_double *source_adress,hk_double factor,int size,hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { //we have to calculate the block size and shift adresses to lower aligned adresses long result_adress = long(source_adress) & hk_VecFPU_MEM_MASK_DOUBLE; target_adress = (hk_double *)( long (target_adress) & hk_VecFPU_MEM_MASK_DOUBLE); size += (long(source_adress)-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE; source_adress=(hk_double *)result_adress; } #if defined(IVP_USE_PS2_VU0) asm __volatile__(" mfc1 $8,%3 qmtc2 $8,vf5 # vf5.x factor 1: lqc2 vf4,0x0(%1) # vf4 *source vmulx.xyzw vf6,vf4,vf5 # vf6 *source * factor lqc2 vf4,0x0(%0) addi %0, 0x10 vadd.xyzw vf6,vf4,vf6 # vf6 = *dest + factor * *source addi %2,-4 addi %1, 0x10 sqc2 vf6,-0x10(%0) bgtz %2,1b nop " : /* no output */ : "r" (target_adress), "r" (source_adress) , "r" (size), "f" (factor) : "$8" , "memory"); #else if(0) { # if defined(IVP_WILLAMETTE) ; __m128d factor128=_mm_set1_pd(factor); for(int i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) { __m128d source_d=_mm_load_pd(source_adress); __m128d prod_d=_mm_mul_pd(factor128,source_d); __m128d target_d=_mm_load_pd(target_adress); target_d=_mm_add_pd(prod_d,target_d); _mm_store_pd(target_adress,target_d); target_adress+=hk_VecFPU_SIZE_DOUBLE; source_adress+=hk_VecFPU_SIZE_DOUBLE; } #endif } else { for(int i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) { # if hk_VecFPU_SIZE_DOUBLE == 2 hk_double a = source_adress[0] * factor; hk_double b = source_adress[1] * factor; a += target_adress[0]; b += target_adress[1]; target_adress[0] = a; target_adress[1] = b; # elif hk_VecFPU_SIZE_DOUBLE == 4 hk_double a = source_adress[0] * factor; hk_double b = source_adress[1] * factor; hk_double c = source_adress[2] * factor; hk_double d = source_adress[3] * factor; a += target_adress[0]; b += target_adress[1]; c += target_adress[2]; d += target_adress[3]; target_adress[0] = a; target_adress[1] = b; target_adress[2] = c; target_adress[3] = d; # else shit # endif target_adress+=hk_VecFPU_SIZE_DOUBLE; source_adress+=hk_VecFPU_SIZE_DOUBLE; } } #endif } inline hk_double hk_VecFPU::fpu_large_dot_product(hk_double *base_a, hk_double *base_b, int size, hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { //we have to calculate the block size and shift adresses to lower aligned adresses long result_adress = long(base_a) & hk_VecFPU_MEM_MASK_DOUBLE; base_b = (hk_double *)( long (base_b) & hk_VecFPU_MEM_MASK_DOUBLE); size += (long(base_a)-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE; // because start changed base_a=(hk_double *)result_adress; } # if defined(IVP_WILLAMETTE) if(0) { __m128d sum128 =_mm_set1_pd(0.0); int i; for(i=size;i>=hk_VecFPU_SIZE_DOUBLE; i-= hk_VecFPU_SIZE_DOUBLE) { __m128d mult1=_mm_load_pd(base_a); __m128d mult2=_mm_load_pd(base_b); __m128d prod =_mm_mul_pd(mult1,mult2); sum128 =_mm_add_pd(prod,sum128); base_a += hk_VecFPU_SIZE_DOUBLE; base_b += hk_VecFPU_SIZE_DOUBLE; } __m128d dummy,low,high; low=sum128; dummy=sum128; //_mm_shuffle_pd(sum128,sum128,1); //swap high and low sum128=_mm_unpackhi_pd(sum128,dummy); high=sum128; __m128d sum64=_mm_add_sd(low,high); __m128d res=sum64; //_mm_shuffle_pd(sum64,sum64,1); hk_double result_sum; _mm_store_sd(&result_sum,res); for(;i>=0;i--) { result_sum += base_a[i] * base_b[i]; } return result_sum; } else { hk_double sum=0.0; for(int i=size-1;i>=0;i--) { sum += base_a[i] * base_b[i]; } return sum; } #else hk_double sum=0.0; for(int i=size-1;i>=0;i--) { sum += base_a[i] * base_b[i]; } return sum; #endif } inline void hk_VecFPU::fpu_multiply_row(hk_double *target_adress,hk_double factor,int size,hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { //we have to calculate the block size and shift adresses to lower aligned adresses long adress,result_adress; adress=(long)target_adress; result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE; size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE; target_adress=(hk_double *)result_adress; } if(0) { #ifdef IVP_WILLAMETTE __m128d factor128=_mm_set1_pd(factor); int i; for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) { __m128d target_d=_mm_load_pd(target_adress); target_d=_mm_mul_pd(factor128,target_d); _mm_store_pd(target_adress,target_d); target_adress+=hk_VecFPU_SIZE_DOUBLE; } #endif } else { int i; for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) { # if hk_VecFPU_SIZE_DOUBLE == 2 hk_double a = target_adress[0] * factor; hk_double b = target_adress[1] * factor; target_adress[0] = a; target_adress[1] = b; # elif hk_VecFPU_SIZE_DOUBLE == 4 hk_double a = target_adress[0] * factor; hk_double b = target_adress[1] * factor; hk_double c = target_adress[2] * factor; hk_double d = target_adress[3] * factor; target_adress[0] = a; target_adress[1] = b; target_adress[2] = c; target_adress[3] = d; # else shit # endif target_adress+=hk_VecFPU_SIZE_DOUBLE; } } } // #+# sparc says rui, optimize for non vector units ( hk_VecFPU_SIZE_DOUBLE = 4 ) inline void hk_VecFPU::fpu_exchange_rows(hk_double *target_adress1,hk_double *target_adress2,int size,hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { //we have to calculate the block size and shift adresses to lower aligned adresses long adress,result_adress; adress=(long)target_adress1; result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE; size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE; target_adress1=(hk_double *)result_adress; adress=(long)target_adress2; adress=adress & hk_VecFPU_MEM_MASK_DOUBLE; target_adress2=(hk_double *)adress; } if(0) { #ifdef IVP_WILLAMETTE int i; for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) { __m128d a_d=_mm_load_pd(target_adress1); __m128d b_d=_mm_load_pd(target_adress2); _mm_store_pd(target_adress1,b_d); _mm_store_pd(target_adress2,a_d); target_adress1+=hk_VecFPU_SIZE_DOUBLE; target_adress2+=hk_VecFPU_SIZE_DOUBLE; } #endif } else { int i; for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) { hk_double h; # if hk_VecFPU_SIZE_DOUBLE == 2 h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h; h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h; # elif hk_VecFPU_SIZE_DOUBLE == 4 h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h; h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h; h=target_adress1[2]; target_adress1[2]=target_adress2[2]; target_adress2[2]=h; h=target_adress1[3]; target_adress1[3]=target_adress2[3]; target_adress2[3]=h; # else shit # endif target_adress1+=hk_VecFPU_SIZE_DOUBLE; target_adress2+=hk_VecFPU_SIZE_DOUBLE; } } } inline void hk_VecFPU::fpu_copy_rows(hk_double *target_adress,hk_double *source_adress,int size,hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { //we have to calculate the block size and shift adresses to lower aligned adresses long adress,result_adress; adress=(long)source_adress; result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE; size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE; source_adress=(hk_double *)result_adress; adress=(long)target_adress; adress=adress & hk_VecFPU_MEM_MASK_DOUBLE; target_adress=(hk_double *)adress; } #ifdef HK_WILLAMETTE int i; for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) { __m128d target_d=_mm_load_pd(source_adress); _mm_store_pd(target_adress,target_d); target_adress+=hk_VecFPU_SIZE_DOUBLE; source_adress+=hk_VecFPU_SIZE_DOUBLE; } #else int i; for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) { int j; for(j=0;j<hk_VecFPU_SIZE_DOUBLE;j++) { target_adress[j] = source_adress[j]; } target_adress+=hk_VecFPU_SIZE_DOUBLE; source_adress+=hk_VecFPU_SIZE_DOUBLE; } #endif } inline void hk_VecFPU::fpu_set_row_to_zero(hk_double *target_adress,int size,hk_bool adress_aligned) { if(adress_aligned==HK_FALSE) { long adress,result_adress; adress=(long)target_adress; result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE; size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE; target_adress=(hk_double *)result_adress; } if(0) { #ifdef IVP_WILLAMETTE __m128d zero128=_mm_set1_pd(0.0f); int i; for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) { _mm_store_pd(target_adress,zero128); target_adress+=hk_VecFPU_SIZE_DOUBLE; } #endif } else { int i; for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) { int j; for(j=0;j<hk_VecFPU_SIZE_DOUBLE;j++) { target_adress[j] = 0.0f; } target_adress+=hk_VecFPU_SIZE_DOUBLE; } } } inline int hk_VecFPU::calc_aligned_row_len(int unaligned_len,hk_double *dummy_type) { //dummy type is used for overloading return (unaligned_len+hk_VecFPU_SIZE_DOUBLE-1)&hk_VecFPU_MASK_DOUBLE; }
32.923205
146
0.66092
DannyParker0001
dedc9bea22e4d12bc1c587ec698d2444e590a3be
4,793
cpp
C++
SimSpark/rcssserver3d/plugin/soccer/gamestateperceptor/gamestateperceptor.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/gamestateperceptor/gamestateperceptor.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/gamestateperceptor/gamestateperceptor.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Fri May 9 2003 Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group $Id$ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "gamestateperceptor.h" #include <zeitgeist/logserver/logserver.h> #include <soccerbase/soccerbase.h> #include <agentstate/agentstate.h> #include <gamestateaspect/gamestateaspect.h> using namespace zeitgeist; using namespace oxygen; using namespace boost; using namespace std; GameStatePerceptor::GameStatePerceptor() : oxygen::Perceptor() { mFirstPercept = true; mReportScore = true; } GameStatePerceptor::~GameStatePerceptor() { } void GameStatePerceptor::InsertSoccerParam(Predicate& predicate, const std::string& name) { float value; if (! SoccerBase::GetSoccerVar(*this,name,value)) { return; } ParameterList& element = predicate.parameter.AddList(); element.AddValue(name); element.AddValue(value); } void GameStatePerceptor::InsertInitialPercept(Predicate& predicate) { // uniform number ParameterList& unumElement = predicate.parameter.AddList(); unumElement.AddValue(string("unum")); unumElement.AddValue(mAgentState->GetUniformNumber()); // team index std::string team; switch (mAgentState->GetTeamIndex()) { case TI_NONE : team = "none"; break; case TI_LEFT : team = "left"; break; case TI_RIGHT : team = "right"; break; } ParameterList& teamElement = predicate.parameter.AddList(); teamElement.AddValue(string("team")); teamElement.AddValue(team); // soccer variables // field geometry parameter // InsertSoccerParam(predicate,"FieldLength"); // InsertSoccerParam(predicate,"FieldWidth"); // InsertSoccerParam(predicate,"FieldHeight"); // InsertSoccerParam(predicate,"GoalWidth"); // InsertSoccerParam(predicate,"GoalDepth"); // InsertSoccerParam(predicate,"GoalHeight"); // InsertSoccerParam(predicate,"BorderSize"); // // agent parameter // InsertSoccerParam(predicate,"AgentMass"); // InsertSoccerParam(predicate,"AgentRadius"); // InsertSoccerParam(predicate,"AgentMaxSpeed"); // // ball parameter // InsertSoccerParam(predicate,"BallRadius"); // InsertSoccerParam(predicate,"BallMass"); } bool GameStatePerceptor::Percept(boost::shared_ptr<PredicateList> predList) { if ( (mGameState.get() == 0) || (mAgentState.get() == 0) ) { return false; } Predicate& predicate = predList->AddPredicate(); predicate.name = "GS"; predicate.parameter.Clear(); // with the first GameState percept after the player is assigned // to a team it receives info about it's team and unum assignment // along with outher soccer parameters if ( (mFirstPercept) && (mAgentState->GetTeamIndex() != TI_NONE) ) { mFirstPercept = false; InsertInitialPercept(predicate); } if (mReportScore) { // score left ParameterList& slElement = predicate.parameter.AddList(); slElement.AddValue(string("sl")); slElement.AddValue(mGameState->GetScore(TI_LEFT)); // score right ParameterList& srElement = predicate.parameter.AddList(); srElement.AddValue(string("sr")); srElement.AddValue(mGameState->GetScore(TI_RIGHT)); } // time ParameterList& timeElement = predicate.parameter.AddList(); timeElement.AddValue(string("t")); timeElement.AddValue(mGameState->GetTime()); // playmode ParameterList& pmElement = predicate.parameter.AddList(); pmElement.AddValue(string("pm")); pmElement.AddValue(SoccerBase::PlayMode2Str(mGameState->GetPlayMode())); return true; } void GameStatePerceptor::OnLink() { SoccerBase::GetGameState(*this,mGameState); SoccerBase::GetAgentState(*this,mAgentState); SoccerBase::GetSoccerVar(*this,"ReportScore",mReportScore); } void GameStatePerceptor::OnUnlink() { mGameState.reset(); mAgentState.reset(); }
28.194118
84
0.685583
IllyasvielEin
dee02e61c6026421062ff37899f6387291f3d3c8
325
cpp
C++
mutations_aliens/main.cpp
aymeebonvarlet/projet_mutation_aliens
a1885d77d9ef197395c7f9545d96105fdac47018
[ "Apache-2.0" ]
null
null
null
mutations_aliens/main.cpp
aymeebonvarlet/projet_mutation_aliens
a1885d77d9ef197395c7f9545d96105fdac47018
[ "Apache-2.0" ]
null
null
null
mutations_aliens/main.cpp
aymeebonvarlet/projet_mutation_aliens
a1885d77d9ef197395c7f9545d96105fdac47018
[ "Apache-2.0" ]
null
null
null
#include "mainwindow.h" #include "qstd.h" using namespace qstd; #include <QApplication> #include "evolutionnary_process.h" int main(int argc, char *argv[]) { Evolutionnary_process evo; evo.init(); cout<<evo.toString()<<endl; QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
19.117647
34
0.664615
aymeebonvarlet
dee0c4a6231b74e6f1b2d9129bdf422fd8e12380
616
cpp
C++
08_pass-by-reference/src/main.cpp
JuliusDiestra/cpp-sandbox
6fa3bcb2a284e58136168e1952a8a54621232621
[ "MIT" ]
null
null
null
08_pass-by-reference/src/main.cpp
JuliusDiestra/cpp-sandbox
6fa3bcb2a284e58136168e1952a8a54621232621
[ "MIT" ]
null
null
null
08_pass-by-reference/src/main.cpp
JuliusDiestra/cpp-sandbox
6fa3bcb2a284e58136168e1952a8a54621232621
[ "MIT" ]
null
null
null
#include "vehicle.hpp" #include "controller.hpp" int main(int argc, char *argv[]) { // Create vehicle object Vehicle vehicle; vehicle.SetVelocity(20); vehicle.SetAcceleration(30); std::cout << "### Vehicle Object ###" << std::endl; std::cout << "velocity:" << vehicle.GetVelocity() << std::endl; std::cout << "acceleration:" << vehicle.GetAcceleration() << std::endl; Controller controller(vehicle); controller.ChangeVehicleVelocity(40); std::cout << "### Vehicle Object ###" << std::endl; std::cout << "velocity:" << vehicle.GetVelocity() << std::endl; return 0; }
32.421053
75
0.625
JuliusDiestra
dee0f6e51b0bf08f7f3b1b3f4ce0dede9913d9f2
2,898
cpp
C++
Source/Extensions/PGUI/PGUI.Screen.cpp
wipe2238/foc
87f083e4d12178244953857ee89da488b31d0a9b
[ "MIT" ]
2
2018-12-14T23:06:21.000Z
2021-07-29T03:10:38.000Z
Source/Extensions/PGUI/PGUI.Screen.cpp
wipe2238/foc
87f083e4d12178244953857ee89da488b31d0a9b
[ "MIT" ]
1
2020-08-25T10:38:00.000Z
2020-08-25T10:38:00.000Z
Source/Extensions/PGUI/PGUI.Screen.cpp
wipe2238/foc
87f083e4d12178244953857ee89da488b31d0a9b
[ "MIT" ]
null
null
null
#include <App.h> #include <Defines.Public.h> #include <GameOptions.h> #include <Ini.h> #include "PGUI.Core.h" #include "PGUI.Screen.h" PGUI::Screen::Screen( PGUI::Core* gui, uint width /* = 0 */, uint height /* = 0 */, int left /* = 0 */, int top /* = 0 */ ) : PGUI::Element( gui, width, height, left, top ), // public IsMovable( true ), Layer( 0 ), ScreenData( nullptr ), // protected DrawLayer( 0 ) {} PGUI::Screen::~Screen() { if( GUI->Debug ) App.WriteLogF( _FUNC_, "\n" ); } uint PGUI::Screen::GetID() { return GUI->GetScreenID( this ); } bool PGUI::Screen::LoadSettings( Ini* ini, const std::string& section ) { if( !ini ) { // if (Debug) App.WriteLogF( _FUNC_, " WARNING : ini is null\n", section.c_str() ); return false; } if( ini->IsSection( section ) ) { // if (Debug) App.WriteLogF( _FUNC_, " WARNING : section<%s> not found\n", section.c_str() ); return false; } return true; } void PGUI::Screen::AutoSize() { uint16 width = 0, height = 0; for( auto it = Elements.begin(), end = Elements.end(); it != end; ++it ) { PGUI::Element* element = it->second; if( !element ) continue; uint16 w = element->GetWidth() + element->GetLeft( true ); uint16 h = element->GetHeight() + element->GetTop( true ); width = std::max( width, w ); height = std::max( height, h ); } if( GUI->Debug ) App.WriteLogF( _FUNC_, " = %ux%u\n", width, height ); SetSize( width, height ); } void PGUI::Screen::MouseMove( int16 fromX, int16 fromY, int16 toX, int16 toY ) { if( !IsMouseEnabled ) return; if( IsMovable && MousePressed && MouseButton == MOUSE_CLICK_LEFT ) { int16 oldLeft = 0, oldTop = 0; GetPosition( oldLeft, oldTop, true ); int newLeft = oldLeft + (toX - fromX); int newTop = oldTop + (toY - fromY); bool reset = false; if( newLeft < 0 ) { newLeft = 0; reset = true; } if( newTop < 0 ) { newTop = 0; reset = true; } uint16 width = 0, height = 0; GetSize( width, height ); if( newLeft + width > GUI->GetScreenWidth() ) { newLeft = GUI->GetScreenWidth() - width; reset = true; } if( newTop + height > GUI->GetScreenHeight() ) { newTop = GUI->GetScreenHeight() - height; reset = true; } if( reset ) { // TODO cursor goes crazy here // GameOpt.MouseX = fromX; // GameOpt.MouseY = fromY; } if( oldLeft != newLeft || oldTop != newTop ) SetPosition( newLeft, newTop ); } PGUI::Element::MouseMove( fromX, fromY, toX, toY ); }
22.640625
173
0.515528
wipe2238
dee18f7be43af0742ef1a141d1cc2b540d142fa3
9,745
hh
C++
nodecursor.hh
cp-profiler/cp-profiler-deprecated-
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
[ "MIT-feh" ]
1
2021-05-06T04:41:37.000Z
2021-05-06T04:41:37.000Z
nodecursor.hh
cp-profiler/cp-profiler-deprecated-
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
[ "MIT-feh" ]
null
null
null
nodecursor.hh
cp-profiler/cp-profiler-deprecated-
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
[ "MIT-feh" ]
1
2021-05-06T04:41:39.000Z
2021-05-06T04:41:39.000Z
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <tack@gecode.org> * * Copyright: * Guido Tack, 2006 * * Last modified: * $Date$ by $Author$ * $Revision$ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #ifndef GECODE_GIST_NODECURSOR_HH #define GECODE_GIST_NODECURSOR_HH #include "nodecursor_base.hh" #include <vector> #include <QTextStream> class TreeCanvas; class Execution; class VisualNode; /// \brief A cursor that marks failed subtrees as hidden class HideFailedCursor : public NodeCursor { private: bool onlyDirty; public: /// Constructor HideFailedCursor(VisualNode* theNode, const NodeAllocator& na, bool onlyDirtyNodes); /// \name Cursor interface //@{ /// Test if the cursor may move to the first child node bool mayMoveDownwards(void) const; /// Process node void processCurrentNode(void); //@} }; /// \brief A cursor that marks all nodes in the tree as not hidden class UnhideAllCursor : public NodeCursor { public: /// Constructor UnhideAllCursor(VisualNode* theNode, const NodeAllocator& na); /// \name Cursor interface //@{ /// Process node void processCurrentNode(void); //@} }; /// \brief A cursor that marks all nodes in the tree as not selected class UnselectAllCursor : public NodeCursor { public: /// Constructor UnselectAllCursor(VisualNode* theNode, const NodeAllocator& na); /// \name Cursor interface //@{ /// Process node void processCurrentNode(void); //@} }; /// \brief A cursor that marks ancestor nodes in the tree as not hidden class UnhideAncestorsCursor : public NodeCursor { public: /// Constructor UnhideAncestorsCursor(VisualNode* theNode, const NodeAllocator& na); /// \name Cursor interface //@{ /// Test if the cursor may move to the parent node bool mayMoveUpwards(void) const; /// Process node void processCurrentNode(void); //@} }; /// \brief A cursor that marks all nodes in the tree as hidden class HideAllCursor : public NodeCursor { public: /// Constructor HideAllCursor(VisualNode* theNode, const NodeAllocator& na); /// \name Cursor interface //@{ /// Process node void processCurrentNode(void); //@} }; /// \brief A cursor that finds the next solution class NextSolCursor : public NodeCursor { private: /// Whether to search backwards bool back; /// Whether the current node is not a solution bool notOnSol(void) const; public: /// Constructor NextSolCursor(VisualNode* theNode, bool backwards, const NodeAllocator& na); /// \name Cursor interface //@{ /// Do nothing void processCurrentNode(void); /// Test if the cursor may move to the parent node bool mayMoveUpwards(void) const; /// Test if cursor may move to the first child node bool mayMoveDownwards(void) const; /// Move cursor to the first child node void moveDownwards(void); /// Test if cursor may move to the first sibling bool mayMoveSidewards(void) const; /// Move cursor to the first sibling void moveSidewards(void); //@} }; /// \brief A cursor that finds the next leaf class NextLeafCursor : public NodeCursor { private: /// Whether to search backwards bool back; /// Whether the current node is not a leaf bool notOnLeaf(void) const; public: /// Constructor NextLeafCursor(VisualNode* theNode, bool backwards, const NodeAllocator& na); /// \name Cursor interface //@{ /// Do nothing void processCurrentNode(void); /// Test if the cursor may move to the parent node bool mayMoveUpwards(void) const; /// Test if cursor may move to the first child node bool mayMoveDownwards(void) const; /// Move cursor to the first child node void moveDownwards(void); /// Test if cursor may move to the first sibling bool mayMoveSidewards(void) const; /// Move cursor to the first sibling void moveSidewards(void); //@} }; /// \brief A cursor that finds the next pentagon class NextPentagonCursor : public NodeCursor { private: /// Whether to search backwards bool back; /// Whether the current node is not a pentagon bool notOnPentagon(void) const; public: /// Constructor NextPentagonCursor(VisualNode* theNode, bool backwards, const NodeAllocator& na); /// \name Cursor interface //@{ /// Do nothing void processCurrentNode(void); /// Test if the cursor may move to the parent node bool mayMoveUpwards(void) const; /// Test if cursor may move to the first child node bool mayMoveDownwards(void) const; /// Move cursor to the first child node void moveDownwards(void); /// Test if cursor may move to the first sibling bool mayMoveSidewards(void) const; /// Move cursor to the first sibling void moveSidewards(void); //@} }; /// \brief A cursor that collects statistics class StatCursor : public NodeCursor { private: /// Current depth int curDepth; public: /// Depth of the search tree int depth; /// Number of failed nodes int failed; /// Number of solved nodes int solved; /// Number of choice nodes int choice; /// Number of open nodes int open; /// Constructor StatCursor(VisualNode* theNode, const NodeAllocator& na); /// \name Cursor interface //@{ /// Collect statistics void processCurrentNode(void); /// Move cursor to the first child node void moveDownwards(void); /// Move cursor to the parent node void moveUpwards(void); //@} }; class HighlightCursor : public NodeCursor { public: // Constructor HighlightCursor(VisualNode* startNode, const NodeAllocator& na); // Highlight all the nodes below void processCurrentNode(void); }; class UnhighlightCursor : public NodeCursor { public: // Constructor UnhighlightCursor(VisualNode* root, const NodeAllocator& na); // Unhighlight all the nodes below void processCurrentNode(void); }; class CountSolvedCursor : public NodeCursor { public: CountSolvedCursor(VisualNode* startNode, const NodeAllocator& na, int &count); // Count solved leaves and store the nubmer in count variable void processCurrentNode(void); private: int &_count; }; class GetIndexesCursor : public NodeCursor { public: // Constructor GetIndexesCursor(VisualNode* startNode, const NodeAllocator& na, std::vector<int>& node_gids); // Populate node_gids vector with gid of nodes void processCurrentNode(void); private: const NodeAllocator& _na; std::vector<int>& _node_gids; }; /// Hide subtrees that are not highlighted class HideNotHighlightedCursor : public NodeCursor { protected: QHash<VisualNode*,bool> onHighlightPath; public: /// Constructor HideNotHighlightedCursor(VisualNode* startNode, const NodeAllocator& na); /// Process node void processCurrentNode(void); /// Test if cursor may move to the first child node bool mayMoveDownwards(void) const; }; /// \brief A cursor that labels branches class BranchLabelCursor : public NodeCursor { private: /// The node allocator NodeAllocator& _na; /// Current TreeCanvas instance (extract labels from data) TreeCanvas& _tc; /// Whether to clear labels bool _clear; public: /// Constructor BranchLabelCursor(VisualNode* theNode, bool clear, NodeAllocator& na, TreeCanvas& tc); /// \name Cursor interface //@{ void processCurrentNode(void); //@} }; class SubtreeCountCursor : public NodeCursor { public: std::vector<int> stack; int threshold; SubtreeCountCursor(VisualNode *theNode, int _threshold, const NodeAllocator& na); void processCurrentNode(void); void moveSidewards(void); void moveUpwards(void); void moveDownwards(void); }; class SearchLogCursor : public NodeCursor { private: QTextStream& _out; /// The node allocator const NodeAllocator& _na; /// TODO(maxim): should have a reference to the execution here const Execution& _execution; public: SearchLogCursor(VisualNode *theNode, QTextStream& outputStream, const NodeAllocator& na, const Execution& execution); void processCurrentNode(void); }; #include "nodecursor.hpp" #endif
28.328488
80
0.677783
cp-profiler
dee63efa3f0c22e5bb79cef4e943cfc3e049ed24
2,316
hpp
C++
src/Modules/ModuleBuilder.hpp
pawel-jarosz/nastya-lisp
813a58523b741e00c8c27980fe658b546e9ff38c
[ "MIT" ]
1
2021-03-12T13:39:17.000Z
2021-03-12T13:39:17.000Z
src/Modules/ModuleBuilder.hpp
pawel-jarosz/nastya-lisp
813a58523b741e00c8c27980fe658b546e9ff38c
[ "MIT" ]
null
null
null
src/Modules/ModuleBuilder.hpp
pawel-jarosz/nastya-lisp
813a58523b741e00c8c27980fe658b546e9ff38c
[ "MIT" ]
null
null
null
// // Created by caedus on 30.01.2021. // #pragma once #include "Modules/Module.hpp" #include "Runtime/Interface/IEvaluatorFactory.hpp" #include "Modules/Interface/IModuleBuilder.hpp" #include <algorithm> namespace nastya::modules { template<typename EvaluatorFactory, typename... OtherFactories> class ModuleBuilder : public ModuleBuilder<OtherFactories...> { public: explicit ModuleBuilder(std::string moduleName); std::unique_ptr<IModule> build() override; }; template<typename EvaluatorFactory> class ModuleBuilder<EvaluatorFactory> : public IModuleBuilder { public: explicit ModuleBuilder(std::string moduleName); std::unique_ptr<IModule> build() override; std::vector<std::unique_ptr<runtime::IEvaluatorFactory>>& getFactories() { return m_factories; } protected: std::unique_ptr<Module> m_module; std::string m_module_name; std::vector<std::unique_ptr<runtime::IEvaluatorFactory>> m_factories; }; template<typename EvaluatorFactory, typename... OtherFactory> std::unique_ptr<IModule> ModuleBuilder<EvaluatorFactory, OtherFactory...>::build() { return ModuleBuilder<OtherFactory...>::build(); } template<typename EvaluatorFactory, typename... OtherFactories> ModuleBuilder<EvaluatorFactory, OtherFactories...>::ModuleBuilder(std::string moduleName) : ModuleBuilder<OtherFactories...>(std::move(moduleName)) { std::unique_ptr<runtime::IEvaluatorFactory> factory(new EvaluatorFactory); ModuleBuilder<OtherFactories...>::getFactories().emplace_back(std::move(factory)); } template<typename EvaluatorFactory> ModuleBuilder<EvaluatorFactory>::ModuleBuilder(std::string moduleName) : m_module{new Module{moduleName}} , m_module_name(std::move(moduleName)) , m_factories{} { std::unique_ptr<runtime::IEvaluatorFactory> factory(new EvaluatorFactory); m_factories.emplace_back(std::move(factory)); } template<typename EvaluatorFactory> std::unique_ptr<IModule> ModuleBuilder<EvaluatorFactory>::build() { using Factory = std::unique_ptr<runtime::IEvaluatorFactory>; std::for_each(m_factories.begin(), m_factories.end(), [&](const Factory& factory) { m_module->registerFunction(factory->create()); }); auto new_module = std::make_unique<Module>(m_module_name); m_module.swap(new_module); return new_module; } }
33.085714
89
0.756045
pawel-jarosz
dee7db73453cfe5478fcf165793c973eaba126fc
2,150
cpp
C++
src/DescentGame/src/Main.cpp
poseidn/KungFoo
35fa33bd5a9abb40ecf485db2fc038ca52c48a2d
[ "CC-BY-3.0", "CC0-1.0", "CC-BY-4.0" ]
7
2016-01-28T14:28:10.000Z
2021-09-03T17:33:37.000Z
src/DescentGame/src/Main.cpp
poseidn/KungFoo
35fa33bd5a9abb40ecf485db2fc038ca52c48a2d
[ "CC-BY-3.0", "CC0-1.0", "CC-BY-4.0" ]
1
2016-03-19T11:34:36.000Z
2016-03-24T21:35:06.000Z
src/DescentGame/src/Main.cpp
poseidn/KungFoo
35fa33bd5a9abb40ecf485db2fc038ca52c48a2d
[ "CC-BY-3.0", "CC0-1.0", "CC-BY-4.0" ]
3
2016-03-10T14:23:40.000Z
2019-03-17T16:21:21.000Z
/* Copyright (C) 2016 Thomas Hauth. All Rights Reserved. * Written by Thomas Hauth (Thomas.Hauth@web.de) This file is part of Kung Foo Barracuda. Kung Foo Barracuda 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. Kung Foo Barracuda 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 Kung Foo Barracuda. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <vector> #include <boost/program_options.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/split.hpp> #include <DescentLogic/src/DescentFramework.h> //#include "CommandLineOptions.h" // set via the build system, if a profile is needed #ifdef USE_PROFILER #include <gperftools/profiler.h> #endif namespace po = boost::program_options; // use ./DescentGame --fullscreen --resolution 1366x768 // on the notebook for the total fun int main(int argc, const char* argv[]) { SDLInterfaceInitData sdlInitData; std::vector < std::string > opts; for (int i = 0; i < argc; i++) { opts.push_back(std::string(argv[i])); } // running fullscreen is default sdlInitData.Fullscreen = false; bool runDemoMode = false; bool muted = false; bool forwardScroll = false; bool withIntro = false; /* if (commandline::handleCommandLine(sdlInitData, opts, runDemoMode, muted, forwardScroll, withIntro) == false) return 0;*/ DescentFramework f(false, runDemoMode, muted, forwardScroll, withIntro, true); f.initRenderEngine(sdlInitData); // todo: make this a lot nicer, by templating the FW class #ifdef USE_PROFILER ProfilerStart("GameLoop.perf"); #endif f.execute(); #ifdef USE_PROFILER ProfilerStop(); #endif // done globally here for all used SDL systems; SDL_Quit(); return 0; }
26.54321
100
0.751628
poseidn
dee83e605a1f575e4a2d710a5a6cb28e33523456
5,810
cpp
C++
patch/specific/drawbars.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
3
2021-10-10T11:12:03.000Z
2021-11-04T16:46:57.000Z
patch/specific/drawbars.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
null
null
null
patch/specific/drawbars.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
null
null
null
#include "standard.h" #include "directx.h" #include "global.h" #include "hwrender.h" #include "output.h" #include <main.h> #include <game/inventry.h> #include <3dsystem/hwinsert.h> #define HealthBarX 8 #define HealthBarY 6 #define HealthBarW 100 #define AirBarX (game_setup.dump_width-110) #define AirBarY 6 #define AirBarW 100 #define DASHBAR_X (game_setup.dump_width-110) #define DASHBAR_Y 6 void S_DrawDashBar(int percent) { HWR_EnableZBuffer(true, true); g_blue_effect = false; int x = DASHBAR_X, y = DASHBAR_Y, w = (percent * HealthBarW) / 100, z = phd_znear + 50; auto colour = (char)inv_colours[C_BLACK]; InsertLine(x - 2, y + 1, x + HealthBarW + 1, y + 1, z, colour); InsertLine(x - 2, y + 2, x + HealthBarW + 1, y + 2, z, colour); InsertLine(x - 2, y + 3, x + HealthBarW + 1, y + 3, z, colour); InsertLine(x - 2, y + 4, x + HealthBarW + 1, y + 4, z, colour); InsertLine(x - 2, y + 5, x + HealthBarW + 1, y + 5, z, colour); InsertLine(x - 2, y + 6, x + HealthBarW + 1, y + 6, z, colour); InsertLine(x - 2, y + 7, x + HealthBarW + 1, y + 7, z, colour); z = phd_znear + 40; colour = (char)inv_colours[C_GREY]; InsertLine(x - 2, y + 8, x + HealthBarW + 2, y + 8, z, colour); InsertLine(x + HealthBarW + 2, y, x + HealthBarW + 2, y + 8, z, colour); z = phd_znear + 30; colour = (char)inv_colours[C_WHITE]; InsertLine(x - 2, y, x + HealthBarW + 2, y, z, colour); InsertLine(x - 2, y + 8, x - 2, y, z, colour); if (w) { colour = (char)inv_colours[C_DARKGREEN]; InsertLine(x, y + 2, x + w, y + 2, z, colour); InsertLine(x, y + 3, x + w, y + 3, z, colour); InsertLine(x, y + 4, x + w, y + 4, z, colour); InsertLine(x, y + 5, x + w, y + 5, z, colour); InsertLine(x, y + 6, x + w, y + 6, z, colour); } } void S_DrawHealthBar(int percent, bool poisoned) { HWR_EnableZBuffer(true, true); g_blue_effect = false; int x = HealthBarX, y = HealthBarY, w = (percent * HealthBarW) / 100, z = phd_znear + 50; auto colour = (char)inv_colours[C_BLACK]; InsertLine(x - 2, y + 1, x + HealthBarW + 1, y + 1, z, colour); InsertLine(x - 2, y + 2, x + HealthBarW + 1, y + 2, z, colour); InsertLine(x - 2, y + 3, x + HealthBarW + 1, y + 3, z, colour); InsertLine(x - 2, y + 4, x + HealthBarW + 1, y + 4, z, colour); InsertLine(x - 2, y + 5, x + HealthBarW + 1, y + 5, z, colour); InsertLine(x - 2, y + 6, x + HealthBarW + 1, y + 6, z, colour); InsertLine(x - 2, y + 7, x + HealthBarW + 1, y + 7, z, colour); z = phd_znear + 40; colour = (char)inv_colours[C_GREY]; InsertLine(x - 2, y + 8, x + HealthBarW + 2, y + 8, z, colour); InsertLine(x + HealthBarW + 2, y, x + HealthBarW + 2, y + 8, z, colour); z = phd_znear + 30; colour = (char)inv_colours[C_WHITE]; InsertLine(x - 2, y, x + HealthBarW + 2, y, z, colour); InsertLine(x - 2, y + 8, x - 2, y, z, colour); if (w) { z = phd_znear + 20; colour = (char)inv_colours[poisoned ? C_YELLOW : C_RED]; InsertLine(x, y + 2, x + w, y + 2, z, colour); InsertLine(x, y + 3, x + w, y + 3, z, colour); InsertLine(x, y + 4, x + w, y + 4, z, colour); InsertLine(x, y + 5, x + w, y + 5, z, colour); InsertLine(x, y + 6, x + w, y + 6, z, colour); } } void S_DrawHealthBar3D(int32_t wx, int32_t wy, int32_t wz, int percent, bool poisoned) { HWR_EnableZBuffer(true, true); g_blue_effect = false; long result[XYZ]; long scr[XYZ]; mCalcPoint(wx, wy, wz, &result[0]); ProjectPCoord(result[_X], result[_Y], result[_Z], scr, f_centerx, f_centery, phd_persp); int x = scr[_X] - HealthBarW / 2, y = scr[_Y], w = (percent * HealthBarW) / 100, z = phd_znear + 50; auto colour = (char)inv_colours[C_BLACK]; InsertLine(x - 2, y + 1, x + HealthBarW + 1, y + 1, z, colour); InsertLine(x - 2, y + 2, x + HealthBarW + 1, y + 2, z, colour); InsertLine(x - 2, y + 3, x + HealthBarW + 1, y + 3, z, colour); InsertLine(x - 2, y + 4, x + HealthBarW + 1, y + 4, z, colour); InsertLine(x - 2, y + 5, x + HealthBarW + 1, y + 5, z, colour); InsertLine(x - 2, y + 6, x + HealthBarW + 1, y + 6, z, colour); InsertLine(x - 2, y + 7, x + HealthBarW + 1, y + 7, z, colour); if (w) { z = phd_znear + 40; colour = (char)inv_colours[poisoned ? C_YELLOW : C_RED]; InsertLine(x, y + 2, x + w, y + 2, z, colour); InsertLine(x, y + 3, x + w, y + 3, z, colour); InsertLine(x, y + 4, x + w, y + 4, z, colour); InsertLine(x, y + 5, x + w, y + 5, z, colour); InsertLine(x, y + 6, x + w, y + 6, z, colour); } } void S_DrawAirBar(int percent) { HWR_EnableZBuffer(true, true); g_blue_effect = false; int x = AirBarX, y = AirBarY, w = (percent * AirBarW) / 100, z = phd_znear + 50; auto colour = (char)inv_colours[C_BLACK]; InsertLine(x - 2, y + 1, x + AirBarW + 1, y + 1, z, colour); InsertLine(x - 2, y + 2, x + AirBarW + 1, y + 2, z, colour); InsertLine(x - 2, y + 3, x + AirBarW + 1, y + 3, z, colour); InsertLine(x - 2, y + 4, x + AirBarW + 1, y + 4, z, colour); InsertLine(x - 2, y + 5, x + AirBarW + 1, y + 5, z, colour); InsertLine(x - 2, y + 6, x + AirBarW + 1, y + 6, z, colour); InsertLine(x - 2, y + 7, x + AirBarW + 1, y + 7, z, colour); z = phd_znear + 40; colour = (char)inv_colours[C_GREY]; InsertLine(x - 2, y + 8, x + AirBarW + 2, y + 8, z, colour); InsertLine(x + AirBarW + 2, y, x + AirBarW + 2, y + 8, z, colour); z = phd_znear + 30; colour = (char)inv_colours[C_WHITE]; InsertLine(x - 2, y, x + AirBarW + 2, y, z, colour); InsertLine(x - 2, y + 8, x - 2, y, z, colour); if (percent > 0) { z = phd_znear + 20; colour = (char)inv_colours[C_WHITE]; InsertLine(x, y + 3, x + w, y + 3, z, colour); colour = (char)inv_colours[C_BLUE]; InsertLine(x, y + 2, x + w, y + 2, z, colour); InsertLine(x, y + 4, x + w, y + 4, z, colour); InsertLine(x, y + 5, x + w, y + 5, z, colour); InsertLine(x, y + 6, x + w, y + 6, z, colour); } }
30.904255
89
0.58537
Tonyx97
deeb50bf2737a13113f6383e8c965541b118890b
7,337
hpp
C++
Extensions/Gameplay/IndexedHalfEdgeMesh.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
1
2022-03-26T21:08:19.000Z
2022-03-26T21:08:19.000Z
Extensions/Gameplay/IndexedHalfEdgeMesh.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
Extensions/Gameplay/IndexedHalfEdgeMesh.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2017, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Zero { template <typename ArrayType> class BoundArrayRange; /// Base functionality for binding a pre-existing array. Currently designed as /// a templated base to reduce code duplication, especially while prototyping. Possibly split to /// individual classes (due to differences, code documentation, etc...) or make generic enough to use elsewhere later. template <typename OwningType, typename DataTypeT> class BoundArray : public SafeId32Object { public: typedef BoundArray<OwningType, DataTypeT> SelfType; typedef DataTypeT DataType; typedef Array<DataTypeT> ArrayType; typedef BoundArrayRange<SelfType> RangeType; BoundArray() { mBoundArray = nullptr; } BoundArray(ArrayType* arrayData) { mBoundArray = arrayData; } Vec3Param operator[](size_t index) const { return (*mBoundArray)[index]; } DataTypeT Get(int arrayIndex) const { if(!ValidateArrayIndex(arrayIndex)) return DataTypeT(); return (*mBoundArray)[arrayIndex]; } int GetCount() const { return (int)(*mBoundArray).Size(); } RangeType GetAll() { return RangeType(this); } bool ValidateArrayIndex(int arrayIndex) const { int count = GetCount(); if(arrayIndex >= count) { String msg = String::Format("Index %d is invalid. Array only contains %d element(s).", arrayIndex, count); DoNotifyException("Invalid index", msg); return false; } return true; } /// The array that this class represents. Assumes that this data cannot go away without this class also going away. ArrayType* mBoundArray; }; template <typename ArrayTypeT> class BoundArrayRange { public: typedef BoundArrayRange<ArrayTypeT> SelfType; typedef ArrayTypeT ArrayType; // Required for binding typedef typename ArrayTypeT::DataType FrontResult; BoundArrayRange() { mArray = nullptr; mIndex = 0; } BoundArrayRange(ArrayTypeT* array) { mArray = array; mIndex = 0; } bool Empty() { // Validate that the range hasn't been destroyed ArrayType* array = mArray; if(array == nullptr) { DoNotifyException("Range is invalid", "The array this range is referencing has been destroyed."); return true; } return mIndex >= (size_t)array->GetCount(); } FrontResult Front() { // If the range is empty (or the range has been destroyed) then throw an exception. if(Empty()) { DoNotifyException("Invalid Range Operation", "Cannot access an item in an empty range."); return FrontResult(); } return mArray->Get(mIndex); } void PopFront() { ++mIndex; } SelfType& All() { return *this; } private: HandleOf<ArrayTypeT> mArray; size_t mIndex; }; class IndexedHalfEdgeVertex; class IndexedHalfEdge; class IndexedHalfEdgeFace; class IndexedHalfEdgeMesh; //-------------------------------------------------------------------IndexedHalfEdgeMeshVertexArray class IndexedHalfEdgeMeshVertexArray : public BoundArray<IndexedHalfEdgeMesh, Vec3> { public: ZilchDeclareType(IndexedHalfEdgeMeshVertexArray, TypeCopyMode::ReferenceType); }; //-------------------------------------------------------------------IndexedHalfEdgeMeshEdgeArray class IndexedHalfEdgeMeshEdgeArray : public BoundArray<IndexedHalfEdgeMesh, IndexedHalfEdge*> { public: ZilchDeclareType(IndexedHalfEdgeMeshEdgeArray, TypeCopyMode::ReferenceType); }; //-------------------------------------------------------------------IndexedHalfEdgeFaceEdgeIndexArray class IndexedHalfEdgeFaceEdgeIndexArray : public BoundArray<IndexedHalfEdgeFace, int> { public: ZilchDeclareType(IndexedHalfEdgeFaceEdgeIndexArray, TypeCopyMode::ReferenceType); }; //-------------------------------------------------------------------IndexedHalfEdgeMeshFaceArray class IndexedHalfEdgeMeshFaceArray : public BoundArray<IndexedHalfEdgeMesh, IndexedHalfEdgeFace*> { public: ZilchDeclareType(IndexedHalfEdgeMeshFaceArray, TypeCopyMode::ReferenceType); }; //-------------------------------------------------------------------IndexedHalfEdge class IndexedHalfEdge : public SafeId32Object { public: ZilchDeclareType(IndexedHalfEdge, TypeCopyMode::ReferenceType); /// Index of the tail vertex in the vertex list. int mVertexIndex; /// Index of the twin edge (edge on adjacent face). int mTwinIndex; /// Index of the face that owns this edge. int mFaceIndex; }; //-------------------------------------------------------------------IndexedHalfEdgeFace class IndexedHalfEdgeFace : public SafeId32Object { public: ZilchDeclareType(IndexedHalfEdgeFace, TypeCopyMode::ReferenceType); typedef Array<int> EdgeArray; typedef IndexedHalfEdgeFaceEdgeIndexArray BoundEdgeArray; IndexedHalfEdgeFace(); /// The list of half-edges owned by this face. BoundEdgeArray* GetEdges(); /// The actual edge array of indices. EdgeArray mEdges; /// The bound array of edges. This allows safe referencing in script. BoundEdgeArray mBoundEdges; }; //-------------------------------------------------------------------IndexedHalfEdgeMesh /// An index based half-edge mesh. This is an edge-centric mesh representation that allows /// efficient traversal from edges to anywhere else. Each edge is broken up into two /// half-edges, one for each face it's a part of. Most sub-shapes contain indices back into /// the 'global' list (e.g. an edge contains the index of the vertex in the mesh's vertex list). /// This mesh format is meant for efficient traversal, but manipulation is not as easy with indices. /// This should be loaded into a more efficient format (such as pointers) if manipulating a mesh. class IndexedHalfEdgeMesh : public ReferenceCountedObject { public: ZilchDeclareType(IndexedHalfEdgeMesh, TypeCopyMode::ReferenceType); typedef Array<Vec3> VertexArray; typedef Array<IndexedHalfEdge*> EdgeArray; typedef Array<IndexedHalfEdgeFace*> FaceArray; typedef IndexedHalfEdgeMeshVertexArray BoundVertexArray; typedef IndexedHalfEdgeMeshEdgeArray BoundEdgeArray; typedef IndexedHalfEdgeMeshFaceArray BoundFaceArray; IndexedHalfEdgeMesh(); /// Create the buffers to store the provided mesh size. void Create(int vertexCount, int edgeCount, int faceCount); /// Clear all mesh data. void Clear(); /// The list of vertices in this mesh. BoundVertexArray* GetVertices(); /// The list of edge in this mesh. BoundEdgeArray* GetEdges(); /// The list of faces in this mesh. BoundFaceArray* GetFaces(); // The internal data that's efficient to work with at run-time VertexArray mVertices; EdgeArray mEdges; FaceArray mFaces; // The proxy arrays for binding. This allows safe referencing of the underlying primitives. BoundVertexArray mBoundVertices; BoundEdgeArray mBoundEdges; BoundFaceArray mBoundFaces; }; }// namespace Zero
29.704453
119
0.654355
jodavis42
deeff73bf44115b9aa19e662852a661458027b77
221
cpp
C++
C++/170923/170923/Item_4_Heal.cpp
ChoiChangYong/Game_Programing
6c290e31eaac526b0dbdfc59731e6479126e95bc
[ "MIT" ]
null
null
null
C++/170923/170923/Item_4_Heal.cpp
ChoiChangYong/Game_Programing
6c290e31eaac526b0dbdfc59731e6479126e95bc
[ "MIT" ]
null
null
null
C++/170923/170923/Item_4_Heal.cpp
ChoiChangYong/Game_Programing
6c290e31eaac526b0dbdfc59731e6479126e95bc
[ "MIT" ]
1
2020-04-27T12:41:20.000Z
2020-04-27T12:41:20.000Z
#include "Item_4_Heal.h" #include "Game.h" #include <iostream> using namespace std; void Item_4_Heal::onCheck(Game* pGame) { pGame->Use_Item_4_Heal(); } Item_4_Heal::Item_4_Heal() { } Item_4_Heal::~Item_4_Heal() { }
11.631579
38
0.714932
ChoiChangYong
def119c406c8eaa5a601880b39120d51f9266eec
2,917
cpp
C++
bitsafe/window_effective.cpp
codereba/bittrace
6826559565aaafc9412d20427d21b73e23febcfe
[ "Unlicense" ]
10
2018-11-09T01:08:15.000Z
2020-06-21T05:39:54.000Z
bitsafe/window_effective.cpp
codereba/bittrace
6826559565aaafc9412d20427d21b73e23febcfe
[ "Unlicense" ]
null
null
null
bitsafe/window_effective.cpp
codereba/bittrace
6826559565aaafc9412d20427d21b73e23febcfe
[ "Unlicense" ]
4
2018-11-09T03:29:52.000Z
2021-07-23T03:30:03.000Z
/* * * Copyright 2010 JiJie Shi(weixin:AIChangeLife) * * This file is part of bittrace. * * bittrace 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. * * bittrace 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 bittrace. If not, see <http://www.gnu.org/licenses/>. * */ #include "stdafx.h" #include "window_effective.h" #define SHORT_WINDOW_DELAY 1 #define SHORT_WINDOW_STEP_SIZE 5 LRESULT short_window_close( CPaintManagerUI *pm, HWND wnd, ULONG delay, ULONG step ) { LRESULT ret = ERROR_SUCCESS; BOOL _ret; RECT rect; ULONG height; INT32 i; RECT cur_rect; RECT paint_rc; SIZE old_min_info; do { ASSERT( wnd != NULL ); ASSERT( pm != NULL ); if( step == 0 ) { step = SHORT_WINDOW_STEP_SIZE; } if( delay == 0 ) { delay = SHORT_WINDOW_DELAY; } if( FALSE == ::IsWindow( wnd ) ) { ASSERT( FALSE && "input the invalid window to show effective" ); break; } _ret = GetWindowRect( wnd, &rect ); if( FALSE == _ret ) { SAFE_SET_ERROR_CODE( ret ); break; } height = _abs( rect.bottom - rect.top ); cur_rect = rect; old_min_info = pm->GetMinInfo(); pm->SetMinInfo( 0, 0 ); for( i = 0; ( ULONG )i < height / 2; i += step ) { cur_rect.bottom = rect.bottom - i; cur_rect.top = rect.top + i; paint_rc = cur_rect; _ret = SetWindowPos( wnd, NULL, cur_rect.left, cur_rect.top, RECT_WIDTH( cur_rect ), RECT_HEIGHT( cur_rect ), SWP_SHOWWINDOW | SWP_NOREDRAW ); if( _ret == FALSE ) {} { pm->PaintStretchShortEffective( wnd, paint_rc ); } Sleep( delay ); } SetWindowPos( wnd, NULL, cur_rect.left, cur_rect.top, RECT_WIDTH( rect ), RECT_HEIGHT( rect ), SWP_HIDEWINDOW ); pm->SetMinInfo( old_min_info.cx, old_min_info.cy ); } while ( FALSE ); return ret; } #define DEF_TRANSPARENT_ANIMATE_TIME 5000 LRESULT transparent_animate( HWND wnd, ULONG time ) { LRESULT ret = ERROR_SUCCESS; BOOL _ret; ASSERT( wnd != NULL ); if( FALSE == IsWindow( wnd ) ) { ret = ERROR_INVALID_PARAMETER; goto _return; } if( time == 0 ) { time = DEF_TRANSPARENT_ANIMATE_TIME; } #if(WINVER >= 0x0500) _ret = AnimateWindow( wnd, time, AW_ACTIVATE | AW_CENTER | AW_BLEND ); if( _ret == FALSE ) { ret = GetLastError(); } #endif // WINVER >= 0x0500 _return: return ret; }
21.768657
147
0.629071
codereba
def25db62073c18ceca30494b8ac3956e4a26189
1,169
cpp
C++
Old Code/SM64FM/src/main.cpp
sonich2401/SM64_Save_File_Converter
bd6876d66cbc3177b634540c7a2241e0ae8c759c
[ "MIT-0" ]
6
2020-07-27T19:07:37.000Z
2021-08-29T19:16:07.000Z
Old Code/SM64FM/src/main.cpp
sonich2401/SM64_Save_File_Converter
bd6876d66cbc3177b634540c7a2241e0ae8c759c
[ "MIT-0" ]
2
2021-06-09T05:49:41.000Z
2022-01-30T04:06:40.000Z
Old Code/SM64FM/src/main.cpp
sonich2401/SM64_Save_File_Converter
bd6876d66cbc3177b634540c7a2241e0ae8c759c
[ "MIT-0" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include <typedefs.h> #include "menu/option_decode.h" #include "util/load_file/load_bin.h" #include "EEPROM/EEPROM.h" #include "menu/menu_choice.h" #include "util/os/linux/escape_codes.h" void exit_program(option_struct * options); int main(int argc, cstring argv[]){ option_struct * options = option_decode(argc, argv); EEPROM_Storage::get().orginal = (EEPROM*)malloc(sizeof(EEPROM)); if(options->in_path == NULL) return 0; unsigned char * infile = load_bin(options->in_path); *EEPROM_Storage::get().orginal = init_EEPROM(infile); EEPROM_Storage::get().edited = (EEPROM*)memcpy(EEPROM_Storage::get().edited, EEPROM_Storage::get().orginal, 512); free(infile); menu_ask((directory*)&root, NULL); exit_program(options); return 0; } void exit_program(option_struct * options){ for(uint8 backup = 0; backup < 2; backup++){ for(uint8 sav = 0; sav < 4; sav++){ set_checksum(&eeprom->game_saves[sav][backup], 0); } set_checksum(&eeprom->menu_saves[backup], 1); } write_bin(options->out_path,(unsigned char*)eeprom, 512); }
25.977778
117
0.663815
sonich2401
def94d20ef029a33c8313959adb0651a463e3480
4,645
cpp
C++
Desktop/FOSSA-GroundStationControlPanel/FOSSASatTracker/SGP4_experiments/main.cpp
FOSSASystems/FOSSA-GroundStationControlPanel
af83a09619239abe9fca09e073ab41c68bfd4822
[ "MIT" ]
2
2021-11-07T16:26:46.000Z
2022-03-20T10:14:41.000Z
Desktop/FOSSA-GroundStationControlPanel/FOSSASatTracker/SGP4_experiments/main.cpp
FOSSASystems/FOSSA-GroundStationControlPanel
af83a09619239abe9fca09e073ab41c68bfd4822
[ "MIT" ]
18
2020-08-28T13:38:36.000Z
2020-09-30T11:08:42.000Z
Desktop/FOSSA-GroundStationControlPanel/FOSSASatTracker/SGP4_experiments/main.cpp
FOSSASystems/FOSSA-GroundStationControlPanel
af83a09619239abe9fca09e073ab41c68bfd4822
[ "MIT" ]
2
2020-07-29T21:19:28.000Z
2021-08-16T03:58:14.000Z
#include "sgp4io.h" #include "sgp4unit.h" #include <GeographicLib/Geocentric.hpp> #include <iostream> int main() { /* INPUT is e.g. 2019 12 6 1 1 1 2020 12 6 1 1 1 */ char fossasatTLELineA[70] = "1 44829U 19084F 20183.10006475 .00039774 00000-0 23016-3 0 9991"; char fossasatTLELineB[70] = "2 44829 96.9730 52.2137 0026683 179.4781 180.6520 15.77974288 32594"; std::cout << "Running! (" << SGP4Version << ")" << std::endl; std::cout << "TLE: " << std::endl; std::cout << fossasatTLELineA << std::endl; std::cout << fossasatTLELineB << std::endl; std::cout << std::endl; // AIAA-2006-6753-Rev2.pdf (page 50 of 94) // Parse the TLE data into the elsetrec structure. elsetrec satrec; char typerun = 'm'; char opsmode = 'i'; char typeinput = 'e'; gravconsttype gravconst = wgs84; double startmfe; double stopmfe; double deltamin; /// @warning stripping const qualifier. // This method also invokes "Day2DMYHMS", "JDAY", "SGP4Init". /* * author : david vallado 719-573-2600 1 mar 2001 * * inputs : * longstr1 - first line of the tle * longstr2 - second line of the tle * typerun - type of run verification 'v', catalog 'c', * manual 'm' * typeinput - type of manual input mfe 'm', epoch 'e', dayofyr 'd' * opsmode - mode of operation afspc or improved 'a', 'i' * whichconst - which set of constants to use 72, 84 * * outputs : * satrec - structure containing all the sgp4 satellite information */ twoline2rv((char*)fossasatTLELineA, (char*)fossasatTLELineB, typerun, typeinput, opsmode, gravconst, startmfe, stopmfe, deltamin, satrec); // Call the propogater (integrator?) at T=0 double positionVector[3]; // km double velocityVector[3]; // km/s /* * * author : david vallado 719-573-2600 28 jun 2005 * * inputs : * satrec - initialised structure from sgp4init() call. * tsince - time eince epoch (minutes) * * outputs : * r - position vector km * v - velocity km/sec * return code - non-zero on error. * 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er * 2 - mean motion less than 0.0 * 3 - pert elements, ecc < 0.0 or ecc > 1.0 * 4 - semi-latus rectum < 0.0 * 5 - epoch elements are sub-orbital * 6 - satellite has decayed */ // call the propogator once to get the initial state vector value. sgp4(gravconst, satrec, 0.0, positionVector, velocityVector); double tsince = startmfe; const GeographicLib::Geocentric& ellipsoid = GeographicLib::Geocentric::WGS84(); if (fabs(tsince) > 1.8e-8) { tsince = tsince - deltamin; } while ((tsince < stopmfe) && (satrec.error == 0)) { tsince = tsince + deltamin; if (tsince > stopmfe) { tsince = stopmfe; } sgp4(gravconst, satrec, tsince, positionVector, velocityVector); if (satrec.error > 0) { std::cout << "Make sure the input is in the form\r\n2020\r\n\12\r\n\6\r\n\1\r\n1\r\n\1" << std::endl; printf("Error %f code %3d\r\n", satrec.t, satrec.error); } if (satrec.error == 0) { // convert the position vector from Geocentric to Geodetic. double lat, lon, h; ellipsoid.Reverse(positionVector[0], positionVector[1], positionVector[2], lat, lon, h); // get the current datetime. double jd = satrec.jdsatepoch + (tsince / 1440.0); int year, mon, day, hr, min; double sec; invjday(jd, year, mon, day, hr, min, sec); // print the information %5i%3i%3i %2i:%2i:%9.6f std::cout << year << ":" << mon << ":" << day << " " << hr << ":" << min << ":" << sec << std::endl; std::cout << std::endl; std::cout << "Position Vector (km): " << std::endl; std::cout << "(" << positionVector[0] << "," << positionVector[1] << "," << positionVector[2] << ")" << std::endl; std::cout << std::endl; std::cout << "Position Vector (Lat/Long): " << std::endl; std::cout << "(" << lat << ", " << lon << ", " << h << ")" << std::endl; std::cout << std::endl; std::cout << "Velocity Vector (km/s): " << std::endl; std::cout << "(" << velocityVector[0] << "," << velocityVector[1] << "," << velocityVector[2] << ")" << std::endl; std::cout << std::endl; } } std::cout << "Finished. Press any key to continue." << std::endl; int v; std::cin >> v; return 0; }
27.323529
117
0.56254
FOSSASystems
defaa02a4762d4b70cc4f0fb2249bf63a7fccfca
757
cpp
C++
alpaca/portfolio.cpp
aidanjalili/alpaca-trade-api-cpp
0914de8ba46cea4c289ef362539d77b2bee74807
[ "MIT" ]
43
2020-04-07T03:28:22.000Z
2022-03-30T21:34:16.000Z
alpaca/portfolio.cpp
aidanjalili/alpaca-trade-api-cpp
0914de8ba46cea4c289ef362539d77b2bee74807
[ "MIT" ]
5
2020-04-29T03:45:36.000Z
2021-03-31T00:59:43.000Z
alpaca/portfolio.cpp
aidanjalili/alpaca-trade-api-cpp
0914de8ba46cea4c289ef362539d77b2bee74807
[ "MIT" ]
18
2020-04-27T18:35:18.000Z
2022-02-05T17:13:38.000Z
#include "alpaca/portfolio.h" #include "alpaca/json.h" #include "rapidjson/document.h" namespace alpaca { Status PortfolioHistory::fromJSON(const std::string& json) { rapidjson::Document d; if (d.Parse(json.c_str()).HasParseError()) { return Status(1, "Received parse error when deserializing portfolio JSON"); } if (!d.IsObject()) { return Status(1, "Deserialized valid JSON but it wasn't a portfolio object"); } PARSE_DOUBLE(base_value, "base_value") PARSE_VECTOR_DOUBLES(equity, "equity") PARSE_VECTOR_DOUBLES(profit_loss, "profit_loss") PARSE_VECTOR_DOUBLES(profit_loss_pct, "profit_loss_pct") PARSE_STRING(timeframe, "timeframe") PARSE_VECTOR_UINT64(timestamp, "timestamp") return Status(); } } // namespace alpaca
28.037037
81
0.738441
aidanjalili
deff9e0ef99374df542a6693b5dcc62e077471c5
6,456
cpp
C++
src/IB/IBLagrangianForceStrategySet.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
2
2017-12-06T06:16:36.000Z
2021-03-13T12:28:08.000Z
src/IB/IBLagrangianForceStrategySet.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
src/IB/IBLagrangianForceStrategySet.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
// Filename: IBLagrangianForceStrategySet.cpp // Created on 04 April 2007 by Boyce Griffith // // Copyright (c) 2002-2013, Boyce Griffith // 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 New York University 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. /////////////////////////////// INCLUDES ///////////////////////////////////// #include "IBLagrangianForceStrategySet.h" #include "PatchHierarchy.h" #include "ibamr/namespaces.h" // IWYU pragma: keep #include "ibtk/IBTK_CHKERRQ.h" #include "ibtk/LData.h" namespace IBTK { class LDataManager; } // namespace IBTK /////////////////////////////// NAMESPACE //////////////////////////////////// namespace IBAMR { /////////////////////////////// STATIC /////////////////////////////////////// /////////////////////////////// PUBLIC /////////////////////////////////////// IBLagrangianForceStrategySet::~IBLagrangianForceStrategySet() { // intentionally blank return; }// ~IBLagrangianForceStrategySet void IBLagrangianForceStrategySet::setTimeInterval( const double current_time, const double new_time) { for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { (*cit)->setTimeInterval(current_time, new_time); } return; }// setTimeInterval void IBLagrangianForceStrategySet::initializeLevelData( const Pointer<PatchHierarchy<NDIM> > hierarchy, const int level_number, const double init_data_time, const bool initial_time, LDataManager* const l_data_manager) { for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { (*cit)->initializeLevelData( hierarchy, level_number, init_data_time, initial_time, l_data_manager); } return; }// initializeLevelData void IBLagrangianForceStrategySet::computeLagrangianForce( Pointer<LData> F_data, Pointer<LData> X_data, Pointer<LData> U_data, const Pointer<PatchHierarchy<NDIM> > hierarchy, const int level_number, const double data_time, LDataManager* const l_data_manager) { for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { (*cit)->computeLagrangianForce( F_data, X_data, U_data, hierarchy, level_number, data_time, l_data_manager); } return; }// computeLagrangianForce void IBLagrangianForceStrategySet::computeLagrangianForceJacobianNonzeroStructure( std::vector<int>& d_nnz, std::vector<int>& o_nnz, const Pointer<PatchHierarchy<NDIM> > hierarchy, const int level_number, LDataManager* const l_data_manager) { for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { (*cit)->computeLagrangianForceJacobianNonzeroStructure( d_nnz, o_nnz, hierarchy, level_number, l_data_manager); } return; }// computeLagrangianForceJacobianNonzeroStructure void IBLagrangianForceStrategySet::computeLagrangianForceJacobian( Mat& J_mat, MatAssemblyType assembly_type, const double X_coef, Pointer<LData> X_data, const double U_coef, Pointer<LData> U_data, const Pointer<PatchHierarchy<NDIM> > hierarchy, const int level_number, const double data_time, LDataManager* const l_data_manager) { for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { (*cit)->computeLagrangianForceJacobian( J_mat, MAT_FLUSH_ASSEMBLY, X_coef, X_data, U_coef, U_data, hierarchy, level_number, data_time, l_data_manager); } if (assembly_type != MAT_FLUSH_ASSEMBLY) { int ierr; ierr = MatAssemblyBegin(J_mat, assembly_type); IBTK_CHKERRQ(ierr); ierr = MatAssemblyEnd(J_mat, assembly_type); IBTK_CHKERRQ(ierr); } return; }// computeLagrangianForceJacobian double IBLagrangianForceStrategySet::computeLagrangianEnergy( Pointer<LData> X_data, Pointer<LData> U_data, const Pointer<PatchHierarchy<NDIM> > hierarchy, const int level_number, const double data_time, LDataManager* const l_data_manager) { double ret_val = 0.0; for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { ret_val += (*cit)->computeLagrangianEnergy(X_data, U_data, hierarchy, level_number, data_time, l_data_manager); } return ret_val; }// computeLagrangianEnergy /////////////////////////////// PROTECTED //////////////////////////////////// /////////////////////////////// PRIVATE ////////////////////////////////////// /////////////////////////////// NAMESPACE //////////////////////////////////// } // namespace IBAMR //////////////////////////////////////////////////////////////////////////////
37.103448
139
0.670074
MSV-Project
72007729164461efc492cbee49cf51da6b5c9677
2,935
cpp
C++
example/sql/test_multithread.cpp
zizzzw/fflib
ba9b465347b650d86c34876fbfae48bc31194d97
[ "MIT" ]
1
2022-02-08T07:28:07.000Z
2022-02-08T07:28:07.000Z
example/sql/test_multithread.cpp
zizzzw/fflib
ba9b465347b650d86c34876fbfae48bc31194d97
[ "MIT" ]
null
null
null
example/sql/test_multithread.cpp
zizzzw/fflib
ba9b465347b650d86c34876fbfae48bc31194d97
[ "MIT" ]
2
2022-01-06T02:16:09.000Z
2022-01-19T12:49:54.000Z
/*********************************************** The MIT License (MIT) Copyright (c) 2012 Athrun Arthur <athrunarthur@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************/ #include "ff/sql/mysql.hpp" #include "ff/sql/table.h" #include <thread> struct mymeta { constexpr static const char *table_name = "yyy"; }; define_column(c1, column, uint64_t, "id"); define_column(c2, key, std::string, "event"); define_column(c3, index, uint64_t, "ts"); typedef ff::sql::table<ff::sql::mysql<ff::sql::cppconn>, mymeta, c1, c2, c3> mytable; int main(int argc, char *argv[]) { ff::sql::mysql<ff::sql::cppconn> engine("tcp://127.0.0.1:3306", "root", "", "test"); mytable::create_table(&engine); mytable::row_collection_type rows; mytable::row_collection_type::row_type t1, t2; t1.set<c1, c2, c3>(1, "c1", 123435); rows.push_back(std::move(t1)); t2.set<c1, c2, c3>(2, "c2", 1235); rows.push_back(std::move(t2)); mytable::insert_or_replace_rows(&engine, rows); std::thread thrd([&engine]() { auto local_engine = engine.thread_copy(); auto ret2 = mytable::select<c1, c2, c3>(local_engine.get()) // auto ret2 = mytable::select<c1, c2, c3>(&engine) .where(c1::eq(2)) .order_by<c1, ff::sql::desc>() .limit(1) .eval(); std::cout << ret2.size() << std::endl; std::cout << ret2[0].get<c1>() << ", " << ret2[0].get<c2>() << ", " << ret2[0].get<c3>() << std::endl; }); auto ret1 = mytable::select<c1, c2, c3>(&engine).eval(); std::cout << "size: " << ret1.size() << std::endl; for (size_t i = 0; i < ret1.size(); ++i) { std::cout << ret1[i].get<c1>() << ", " << ret1[i].get<c2>() << ", " << ret1[i].get<c3>() << std::endl; } thrd.join(); return 0; }
37.151899
79
0.612947
zizzzw
7200cb8c29aa54b386846e16aac4f09b5848effa
9,142
cpp
C++
Code/Core/CoreTest/Tests/TestSmallBlockAllocator.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
30
2020-07-15T06:16:55.000Z
2022-02-10T21:37:52.000Z
Code/Core/CoreTest/Tests/TestSmallBlockAllocator.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
1
2020-11-23T13:35:00.000Z
2020-11-23T13:35:00.000Z
Code/Core/CoreTest/Tests/TestSmallBlockAllocator.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
12
2020-09-16T17:39:34.000Z
2021-08-17T11:32:37.000Z
// TestSmallBlockAllocator.cpp //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "TestFramework/UnitTest.h" #include "Core/Containers/Array.h" #include "Core/Math/Random.h" #include "Core/Mem/Mem.h" #include "Core/Mem/SmallBlockAllocator.h" #include "Core/Process/Thread.h" #include "Core/Time/Timer.h" #include "Core/Tracing/Tracing.h" // System #include <stdlib.h> // TestSmallBlockAllocator //------------------------------------------------------------------------------ class TestSmallBlockAllocator : public UnitTest { private: DECLARE_TESTS void SingleThreaded() const; void MultiThreaded() const; // struct for managing threads class ThreadInfo { public: Thread::ThreadHandle m_ThreadHandle = INVALID_THREAD_HANDLE; Array< uint32_t > * m_AllocationSizes = nullptr; uint32_t m_RepeatCount = 0; float m_TimeTaken = 0.0f; }; // Helper functions static void GetRandomAllocSizes( const uint32_t numAllocs, Array< uint32_t> & allocSizes ); static float AllocateFromSystemAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount ); static float AllocateFromSmallBlockAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount, const bool threadSafe = true ); static uint32_t ThreadFunction_System( void * userData ); static uint32_t ThreadFunction_SmallBlock( void * userData ); }; // Register Tests //------------------------------------------------------------------------------ REGISTER_TESTS_BEGIN( TestSmallBlockAllocator ) REGISTER_TEST( SingleThreaded ) REGISTER_TEST( MultiThreaded ) REGISTER_TESTS_END // SingleThreaded //------------------------------------------------------------------------------ void TestSmallBlockAllocator::SingleThreaded() const { #if defined( DEBUG ) const uint32_t numAllocs( 10 * 1000 ); #else const uint32_t numAllocs( 100 * 1000 ); #endif const uint32_t repeatCount( 10 ); Array< uint32_t > allocSizes( 0, true ); GetRandomAllocSizes( numAllocs, allocSizes ); float time1 = AllocateFromSystemAllocator( allocSizes, repeatCount ); float time2 = AllocateFromSmallBlockAllocator( allocSizes, repeatCount ); float time3 = AllocateFromSmallBlockAllocator( allocSizes, repeatCount, false ); // Thread-safe = false // output OUTPUT( "System (malloc) : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time1, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time1 ) ); OUTPUT( "SmallBlockAllocator : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time2, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time2 ) ); OUTPUT( "SmallBlockAllocator (Single-Threaded mode) : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time3, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time3 ) ); } // MultiThreaded //------------------------------------------------------------------------------ void TestSmallBlockAllocator::MultiThreaded() const { #if defined( DEBUG ) const uint32_t numAllocs( 10 * 1000 ); #else const uint32_t numAllocs( 100 * 1000 ); #endif const uint32_t repeatCount( 10 ); Array< uint32_t > allocSizes( 0, true ); GetRandomAllocSizes( numAllocs, allocSizes ); float time1( 0.0f ); float time2( 0.0f ); const size_t numThreads = 4; // System Allocator { // Create some threads ThreadInfo info[ numThreads ]; for ( size_t i = 0; i < numThreads; ++i ) { info[ i ].m_AllocationSizes = & allocSizes; info[ i ].m_RepeatCount = repeatCount; info[ i ].m_ThreadHandle = Thread::CreateThread( ThreadFunction_System, "SmallBlock", ( 64 * KILOBYTE ), (void*)&info[ i ] ); TEST_ASSERT( info[ i ].m_ThreadHandle != INVALID_THREAD_HANDLE ); } // Join the threads for ( size_t i = 0; i < numThreads; ++i ) { bool timedOut; Thread::WaitForThread( info[ i ].m_ThreadHandle, 500 * 1000, timedOut ); Thread::CloseHandle( info[ i ].m_ThreadHandle ); TEST_ASSERT( timedOut == false ); time1 += info[ i ].m_TimeTaken; } } // Small Block Allocator { // Create some threads ThreadInfo info[ numThreads ]; for ( size_t i = 0; i < numThreads; ++i ) { info[ i ].m_AllocationSizes = & allocSizes; info[ i ].m_RepeatCount = repeatCount; info[ i ].m_ThreadHandle = Thread::CreateThread( ThreadFunction_SmallBlock, "SmallBlock", ( 64 * KILOBYTE ), (void*)&info[ i ] ); TEST_ASSERT( info[ i ].m_ThreadHandle != INVALID_THREAD_HANDLE ); } // Join the threads for ( size_t i = 0; i < numThreads; ++i ) { bool timedOut; Thread::WaitForThread( info[ i ].m_ThreadHandle, 500 * 1000, timedOut ); Thread::CloseHandle( info[ i ].m_ThreadHandle ); TEST_ASSERT( timedOut == false ); time2 += info[ i ].m_TimeTaken; } time2 /= numThreads; } // output OUTPUT( "System (malloc) : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time1, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time1 ) ); OUTPUT( "SmallBlockAllocator : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time2, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time2 ) ); } // GetRandomAllocSizes //------------------------------------------------------------------------------ /*static*/ void TestSmallBlockAllocator::GetRandomAllocSizes( const uint32_t numAllocs, Array< uint32_t > & allocSizes ) { const size_t maxSize( 256 ); // max supported size of block allocator allocSizes.SetCapacity( numAllocs ); Random r; r.SetSeed( 0 ); // Deterministic between runs by using a consistent seed for ( size_t i = 0; i < numAllocs; ++i ) { allocSizes.Append( r.GetRandIndex( maxSize ) ); } } // AllocateFromSystemAllocator //------------------------------------------------------------------------------ /*static*/ float TestSmallBlockAllocator::AllocateFromSystemAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount ) { const size_t numAllocs = allocSizes.GetSize(); Array< void * > allocs( numAllocs, false ); Timer timer; for ( size_t r = 0; r < repeatCount; ++r ) { // use malloc for ( uint32_t i = 0; i < numAllocs; ++i ) { uint32_t * mem = (uint32_t *)malloc( allocSizes[ i ] ); allocs.Append( mem ); } // use free for ( uint32_t i = 0; i < numAllocs; ++i ) { void * mem = allocs[ i ]; free( mem ); } allocs.Clear(); } return timer.GetElapsed(); } // AllocateFromSmallBlockAllocator //------------------------------------------------------------------------------ /*static*/ float TestSmallBlockAllocator::AllocateFromSmallBlockAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount, const bool threadSafe ) { const size_t numAllocs = allocSizes.GetSize(); Array< void * > allocs( numAllocs, false ); Timer timer; if ( threadSafe == false ) { SmallBlockAllocator::SetSingleThreadedMode( true ); } for ( size_t r = 0; r < repeatCount; ++r ) { // Use ALLOC for ( uint32_t i = 0; i < numAllocs; ++i ) { uint32_t * mem = (uint32_t *)ALLOC( allocSizes[ i ] ); allocs.Append( mem ); } // Use FREE for ( uint32_t i = 0; i < numAllocs; ++i ) { void * mem = allocs[ i ]; FREE( mem ); } allocs.Clear(); } if ( threadSafe == false ) { SmallBlockAllocator::SetSingleThreadedMode( false ); } return timer.GetElapsed(); } // ThreadFunction_System //------------------------------------------------------------------------------ /*static*/ uint32_t TestSmallBlockAllocator::ThreadFunction_System( void * userData ) { ThreadInfo & info = *( reinterpret_cast< ThreadInfo * >( userData ) ); info.m_TimeTaken = AllocateFromSystemAllocator( *info.m_AllocationSizes, info.m_RepeatCount ); return 0; } // ThreadFunction_SmallBlock //------------------------------------------------------------------------------ /*static*/ uint32_t TestSmallBlockAllocator::ThreadFunction_SmallBlock( void * userData ) { ThreadInfo & info = *( reinterpret_cast< ThreadInfo * >( userData ) ); info.m_TimeTaken = AllocateFromSmallBlockAllocator( *info.m_AllocationSizes, info.m_RepeatCount ); return 0; } //------------------------------------------------------------------------------
35.710938
198
0.556005
qq573011406
7202f264bd57851ca7f5b279dd6700bd6f5d9dd6
556
cc
C++
examples/toy/andor.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
5
2020-04-11T21:30:19.000Z
2021-12-04T16:16:09.000Z
examples/toy/andor.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
null
null
null
examples/toy/andor.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
null
null
null
#include <TaskGraph> using namespace tg; typedef TaskGraph<void,int> andor_TaskGraph; int main( int argc, char *argv[] ) { andor_TaskGraph T; taskgraph( andor_TaskGraph, T, tuple1(a) ) { tVar(int, b); b = ((a < 12) + (a > 42)); b = ((a > 6) - (a < 9)); b = ((a < 12) * (a > 42)); b = ((a > 6) / (a < 9)); b = ((a < 12) & (a > 42)); b = ((a > 6) | (a < 9)); b = ((a < 12) && (a > 42)); b = ((a > 6) || (a < 9)); b = ((a < 12) << (a > 42)); b = ((a > 6) >> (a < 9)); tIf( b > 1 ) { } } T.print(); }
22.24
46
0.393885
paulhjkelly
7208b1a74f7a044ea3b92c8d2697cdd2dffbc33f
437
hpp
C++
include/imgui.hpp
richard-vock/graphene
1a721894a9972c8865a1ad0861d500cef8436932
[ "Unlicense" ]
null
null
null
include/imgui.hpp
richard-vock/graphene
1a721894a9972c8865a1ad0861d500cef8436932
[ "Unlicense" ]
null
null
null
include/imgui.hpp
richard-vock/graphene
1a721894a9972c8865a1ad0861d500cef8436932
[ "Unlicense" ]
null
null
null
#pragma once #include <string> #include <imgui.h> #include "common.hpp" #include "events.hpp" struct GLFWwindow; namespace graphene::imgui { IMGUI_IMPL_API bool init_application(GLFWwindow* window, const std::string& font_path, float font_size, std::shared_ptr<event_manager> events); IMGUI_IMPL_API void shutdown_application(); IMGUI_IMPL_API void init_frame(); IMGUI_IMPL_API void draw_frame(); } // namespace graphene::imgui
20.809524
143
0.78032
richard-vock
720c50dc8d59b9d1cfb7c087510ca8fb74d2d718
7,580
cpp
C++
level1/p11_linkedList/linkedList.cpp
shui12jiao/c2021
0a21392fe0c35cbebc04335d43e134410e17d89c
[ "MIT" ]
null
null
null
level1/p11_linkedList/linkedList.cpp
shui12jiao/c2021
0a21392fe0c35cbebc04335d43e134410e17d89c
[ "MIT" ]
null
null
null
level1/p11_linkedList/linkedList.cpp
shui12jiao/c2021
0a21392fe0c35cbebc04335d43e134410e17d89c
[ "MIT" ]
null
null
null
#include <sstream> #include "illegalParameter.h" #include "linearList.h" #include "linkedNode.h" template <typename T> class linkedList : public linearList<T> { //链表 public: linkedList(); linkedList(const linkedList<T>&); ~linkedList(); bool empty() const { return listSize == 0; } int size() const { return listSize; }; T& get(int theIndex) const; int indexOf(const T& theElement, int theIndex = -1) const; void erase(int theIndex); void insert(int theIndex, const T& theElement); void output(std::ostream& out) const; void clear(); void push_back(const T& theElement); void pop_back(); void set(int theIndex, const T& theElement); void resize(int size, const T& theElement); void reverse(); protected: linkedNode<T>* firstNode; linkedNode<T>* lastNode; int listSize; }; template <typename T> linkedList<T>::linkedList() { firstNode = nullptr; lastNode = nullptr; listSize = 0; } template <typename T> linkedList<T>::linkedList(const linkedList<T>& theList) { listSize = theList.listSize; if (listSize == 0) { linkedList(); return; } linkedNode<T>* sourceNode = theList.firstNode; firstNode = new linkedNode<T>(sourceNode->element); linkedNode<T>* currentNode = firstNode; sourceNode = sourceNode->next; while (sourceNode != nullptr) { currentNode->next = new linkedNode<T>(sourceNode->element); currentNode = currentNode->next; sourceNode = sourceNode->next; } lastNode = currentNode; lastNode->next = nullptr; } template <typename T> linkedList<T>::~linkedList() { linkedNode<T>* tempNode; while (firstNode != nullptr) { tempNode = firstNode->next; delete firstNode; firstNode = tempNode; } } template <typename T> T& linkedList<T>::get(int theIndex) const { if (theIndex >= listSize || theIndex < 0) { std::ostringstream s; s << "获取失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl; throw illegalParameter(s.str()); } linkedNode<T>* currentNode = firstNode; for (int i = 0; i < theIndex; ++i) { currentNode = currentNode->next; } return currentNode->element; } template <typename T> int linkedList<T>::indexOf(const T& theElement, int theIndex) const { if (theIndex >= listSize - 1 || theIndex < -1) { return -1; } linkedNode<T>* currentNode = firstNode; int index = theIndex + 1; for (int i = -1; i < theIndex; ++i) { currentNode = currentNode->next; } while (currentNode != nullptr && currentNode->element != theElement) { ++index; currentNode = currentNode->next; } if (currentNode == nullptr) { return -1; } return index; } template <typename T> void linkedList<T>::erase(int theIndex) { if (theIndex >= listSize || theIndex < 0) { std::ostringstream s; s << "删除失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl; throw illegalParameter(s.str()); } linkedNode<T>* deleteNode; if (theIndex == 0) { deleteNode = firstNode; firstNode = firstNode->next; } else { linkedNode<T>* preNode = firstNode; for (int i = 1; i < theIndex; ++i) { preNode = preNode->next; } deleteNode = preNode->next; preNode->next = deleteNode->next; if (deleteNode == lastNode) lastNode = preNode; } delete deleteNode; --listSize; } template <typename T> void linkedList<T>::insert(int theIndex, const T& theElement) { if (theIndex > listSize || theIndex < 0) { std::ostringstream s; s << "插入失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl; throw illegalParameter(s.str()); } if (theIndex == 0) { firstNode = new linkedNode<T>(theElement, firstNode); if (listSize == 0) { lastNode = firstNode; } } else { linkedNode<T>* preNode = firstNode; for (int i = 1; i < theIndex; ++i) { preNode = preNode->next; } preNode->next = new linkedNode<T>(theElement, preNode->next); if (listSize == theIndex) { lastNode = preNode->next; } } ++listSize; } template <typename T> void linkedList<T>::output(std::ostream& out) const { for (linkedNode<T>* currentNode = firstNode; currentNode != nullptr; currentNode = currentNode->next) { out << currentNode->element << ' '; } } template <typename T> void linkedList<T>::clear() { linkedNode<T>* tempNode = firstNode; while (firstNode != nullptr) { tempNode = firstNode->next; delete firstNode; firstNode = tempNode; } listSize = 0; } template <typename T> void linkedList<T>::push_back(const T& theElement) { linkedNode<T>* newNode = new linkedNode<T>(theElement, nullptr); if (listSize == 0) { firstNode = newNode; lastNode = newNode; } else { lastNode->next = newNode; lastNode = newNode; } ++listSize; } template <typename T> void linkedList<T>::pop_back() { if (listSize == 0) { std::cerr << "链表为空" << std::endl; return; } else if (listSize == 1) { delete firstNode; firstNode = nullptr; lastNode = nullptr; } else { linkedNode<T>* preNode = firstNode; for (int i = 2; i < listSize; ++i) { preNode = preNode->next; } delete lastNode; preNode->next = nullptr; lastNode = preNode; } --listSize; } template <typename T> std::ostream& operator<<(std::ostream& out, const linkedList<T>& l) { l.output(out); return out; } template <typename T> void linkedList<T>::set(int theIndex, const T& theElement) { if (theIndex >= listSize || theIndex < 0) { std::cerr << "更改失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl; return; } linkedNode<T>* currentNode = firstNode; for (int i = 0; i < theIndex; ++i) { currentNode = currentNode->next; } currentNode->element = theElement; } template <typename T> void linkedList<T>::resize(int size, const T& theElement) { if (size < 0) { std::ostringstream s; s << "失败 大小为" << listSize << " 输入Size为" << size << std::endl; throw illegalParameter(s.str()); } else if (size < listSize) { while (size < listSize) { pop_back(); } } else if (size > listSize) { while (size > listSize) { push_back(theElement); } } else { return; } } template <typename T> void linkedList<T>::reverse() { lastNode = firstNode; linkedNode<T>* tempNode = nullptr; linkedNode<T>* nextNode = nullptr; while (firstNode != nullptr) { nextNode = firstNode->next; firstNode->next = tempNode; tempNode = firstNode; firstNode = nextNode; } firstNode = tempNode; } int main() { linkedList<int> l; for (int i = 1; i <= 10; ++i) l.push_back(i); l.set(9, 5); linkedList<int> list(l); std::cout << list << std::endl; list.reverse(); std::cout << list << std::endl; int i1 = list.indexOf(5); int i2 = list.indexOf(5, i1); int i3 = list.indexOf(5, i2); std::cout << "节点序号从0开始" << std::endl; std::cout << "数字5第一次出现节点序号:" << i1 << std::endl; std::cout << "数字5第一次出现节点序号:" << i2 << std::endl; std::cout << "数字5第一次出现节点序号:" << i3 << std::endl; return 0; }
26.784452
107
0.581003
shui12jiao
720e527a45f234e6add1ca37bbf847a70b75d5fc
1,617
cpp
C++
src/lib/Mutex.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
src/lib/Mutex.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
src/lib/Mutex.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010, Piet Hein Schouten. All rights reserved. * This code is licensed under a BSD-style license that can be * found in the LICENSE file. The license can also be found at: * http://www.boi-project.org/license */ #include <QMutex> #include <QWaitCondition> #include "ThreadLockData.h" #include "MutexBase.h" #include "Mutex.h" namespace BOI { Mutex::Mutex() : m_numAccessors(0), m_doWait(true), m_pHead(NULL), m_pTail(NULL), m_pMutex(NULL), m_pBase(NULL) { } void Mutex::Lock() { if (m_numAccessors.fetchAndAddAcquire(1) != 0) { m_pMutex->lock(); if (m_doWait || (m_pHead != NULL)) { ThreadLockData* pThreadLockData = m_pBase->GetData(); pThreadLockData->pNext = NULL; /* * Enqueue the thread. */ if (m_pHead == NULL) { m_pHead = pThreadLockData; } else { m_pTail->pNext = pThreadLockData; } m_pTail = pThreadLockData; pThreadLockData->waitCondition.wait(m_pMutex); /* * Dequeue thread. */ m_pHead = m_pHead->pNext; } m_doWait = true; m_pMutex->unlock(); } } void Mutex::Unlock() { if (m_numAccessors.fetchAndAddRelease(-1) != 1) { m_pMutex->lock(); m_doWait = false; if (m_pHead != NULL) { m_pHead->waitCondition.wakeOne(); } m_pMutex->unlock(); } } } // namespace BOI
18.586207
65
0.520717
romoadri21
72127937d14cdbfedbe5d1c95ae94d20942522bf
664
hpp
C++
include/simple_math/vec.hpp
signekatt/simple_math
aa17f449330a2dd38a10222074c1139fdbdeeb75
[ "MIT" ]
null
null
null
include/simple_math/vec.hpp
signekatt/simple_math
aa17f449330a2dd38a10222074c1139fdbdeeb75
[ "MIT" ]
null
null
null
include/simple_math/vec.hpp
signekatt/simple_math
aa17f449330a2dd38a10222074c1139fdbdeeb75
[ "MIT" ]
null
null
null
// Copyright(c) 2019-present, Anton Lilja. // Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once #include "vec2.hpp" #include "vec3.hpp" #include "vec4.hpp" namespace sm { // Other op funcs template <typename V> inline V inverse(const V& v) { return v.inverse(); } template <typename V> inline float magnitude(const V& v) { return v.magnitude(); } template <typename V> inline float square_magnitude(const V& v) { return v.square_magnitude(); } template <typename V> inline V normalize(const V& v) { return v.normalize(); } } // namespace sm
21.419355
73
0.626506
signekatt
721c2de3ada7099eceea094e17c91fb0912c52f8
4,875
cpp
C++
modules/dasClangBind/src/dasClangBind.func_3.cpp
profelis/daScript
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
[ "BSD-3-Clause" ]
421
2019-08-15T15:40:04.000Z
2022-03-29T06:59:06.000Z
modules/dasClangBind/src/dasClangBind.func_3.cpp
profelis/daScript
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
[ "BSD-3-Clause" ]
55
2019-08-17T13:50:53.000Z
2022-03-25T17:58:38.000Z
modules/dasClangBind/src/dasClangBind.func_3.cpp
profelis/daScript
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
[ "BSD-3-Clause" ]
58
2019-08-22T17:04:13.000Z
2022-03-25T17:43:28.000Z
// this file is generated via daScript automatic C++ binder // all user modifications will be lost after this file is re-generated #include "daScript/misc/platform.h" #include "daScript/ast/ast.h" #include "daScript/ast/ast_interop.h" #include "daScript/ast/ast_handle.h" #include "daScript/ast/ast_typefactory_bind.h" #include "daScript/simulate/bind_enum.h" #include "dasClangBind.h" #include "need_dasClangBind.h" namespace das { void Module_dasClangBind::initFunctions_3() { addExtern< void * (*)(void *) , clang_getChildDiagnostics >(*this,lib,"clang_getChildDiagnostics",SideEffects::worstDefault,"clang_getChildDiagnostics") ->args({"D"}); addExtern< unsigned int (*)(CXTranslationUnitImpl *) , clang_getNumDiagnostics >(*this,lib,"clang_getNumDiagnostics",SideEffects::worstDefault,"clang_getNumDiagnostics") ->args({"Unit"}); addExtern< void * (*)(CXTranslationUnitImpl *,unsigned int) , clang_getDiagnostic >(*this,lib,"clang_getDiagnostic",SideEffects::worstDefault,"clang_getDiagnostic") ->args({"Unit","Index"}); addExtern< void * (*)(CXTranslationUnitImpl *) , clang_getDiagnosticSetFromTU >(*this,lib,"clang_getDiagnosticSetFromTU",SideEffects::worstDefault,"clang_getDiagnosticSetFromTU") ->args({"Unit"}); addExtern< void (*)(void *) , clang_disposeDiagnostic >(*this,lib,"clang_disposeDiagnostic",SideEffects::worstDefault,"clang_disposeDiagnostic") ->args({"Diagnostic"}); addExtern< CXString (*)(void *,unsigned int) , clang_formatDiagnostic ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_formatDiagnostic",SideEffects::worstDefault,"clang_formatDiagnostic") ->args({"Diagnostic","Options"}); addExtern< unsigned int (*)() , clang_defaultDiagnosticDisplayOptions >(*this,lib,"clang_defaultDiagnosticDisplayOptions",SideEffects::worstDefault,"clang_defaultDiagnosticDisplayOptions"); addExtern< CXDiagnosticSeverity (*)(void *) , clang_getDiagnosticSeverity >(*this,lib,"clang_getDiagnosticSeverity",SideEffects::worstDefault,"clang_getDiagnosticSeverity") ->args({""}); addExtern< CXSourceLocation (*)(void *) , clang_getDiagnosticLocation ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticLocation",SideEffects::worstDefault,"clang_getDiagnosticLocation") ->args({""}); addExtern< CXString (*)(void *) , clang_getDiagnosticSpelling ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticSpelling",SideEffects::worstDefault,"clang_getDiagnosticSpelling") ->args({""}); addExtern< CXString (*)(void *,CXString *) , clang_getDiagnosticOption ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticOption",SideEffects::worstDefault,"clang_getDiagnosticOption") ->args({"Diag","Disable"}); addExtern< unsigned int (*)(void *) , clang_getDiagnosticCategory >(*this,lib,"clang_getDiagnosticCategory",SideEffects::worstDefault,"clang_getDiagnosticCategory") ->args({""}); addExtern< CXString (*)(unsigned int) , clang_getDiagnosticCategoryName ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticCategoryName",SideEffects::worstDefault,"clang_getDiagnosticCategoryName") ->args({"Category"}); addExtern< CXString (*)(void *) , clang_getDiagnosticCategoryText ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticCategoryText",SideEffects::worstDefault,"clang_getDiagnosticCategoryText") ->args({""}); addExtern< unsigned int (*)(void *) , clang_getDiagnosticNumRanges >(*this,lib,"clang_getDiagnosticNumRanges",SideEffects::worstDefault,"clang_getDiagnosticNumRanges") ->args({""}); addExtern< CXSourceRange (*)(void *,unsigned int) , clang_getDiagnosticRange ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticRange",SideEffects::worstDefault,"clang_getDiagnosticRange") ->args({"Diagnostic","Range"}); addExtern< unsigned int (*)(void *) , clang_getDiagnosticNumFixIts >(*this,lib,"clang_getDiagnosticNumFixIts",SideEffects::worstDefault,"clang_getDiagnosticNumFixIts") ->args({"Diagnostic"}); addExtern< CXString (*)(void *,unsigned int,CXSourceRange *) , clang_getDiagnosticFixIt ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticFixIt",SideEffects::worstDefault,"clang_getDiagnosticFixIt") ->args({"Diagnostic","FixIt","ReplacementRange"}); addExtern< CXString (*)(CXTranslationUnitImpl *) , clang_getTranslationUnitSpelling ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getTranslationUnitSpelling",SideEffects::worstDefault,"clang_getTranslationUnitSpelling") ->args({"CTUnit"}); addExtern< CXTranslationUnitImpl * (*)(void *,const char *,int,const char *const *,unsigned int,CXUnsavedFile *) , clang_createTranslationUnitFromSourceFile >(*this,lib,"clang_createTranslationUnitFromSourceFile",SideEffects::worstDefault,"clang_createTranslationUnitFromSourceFile") ->args({"CIdx","source_filename","num_clang_command_line_args","clang_command_line_args","num_unsaved_files","unsaved_files"}); } }
87.053571
284
0.791179
profelis
722310472f4f466485792343c31670010863c197
11,228
hpp
C++
tcob/include/tcob/core/Automation.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
2
2021-08-18T19:14:35.000Z
2021-12-01T14:14:49.000Z
tcob/include/tcob/core/Automation.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
tcob/include/tcob/core/Automation.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Tobias Bohnen // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #pragma once #include <tcob/tcob_config.hpp> #include <concepts> #include <queue> #include <vector> #include <tcob/core/Random.hpp> #include <tcob/core/Signal.hpp> #include <tcob/core/Updatable.hpp> #include <tcob/core/data/Color.hpp> #include <tcob/core/data/Point.hpp> #include <tcob/gfx/Quad.hpp> namespace tcob { //////////////////////////////////////////////////////////// template <typename T> concept AutomationFunction = requires(T& t, f32 elapsedRatio) { typename T::type; { t.get_value(elapsedRatio) } -> std::same_as<typename T::type>; }; //////////////////////////////////////////////////////////// template <typename T> concept Interpolatable = requires(T& t, f32 elapsedRatio) { { t.get_interpolated(t, elapsedRatio) } -> std::same_as<T>; }; //////////////////////////////////////////////////////////// class AutomationBase : public Updatable { public: explicit AutomationBase(MilliSeconds duration); virtual ~AutomationBase() = default; void start(bool looped = false); void restart(); void toggle_pause(); void stop(); void set_interval(MilliSeconds interval); auto is_running() const -> bool; auto get_progress() const -> f32; void update(MilliSeconds deltaTime) override; private: virtual void update_values() = 0; bool _isRunning { false }; bool _looped { false }; MilliSeconds _duration { 0 }; MilliSeconds _elapsedTime { 0 }; MilliSeconds _interval { 0 }; MilliSeconds _currentInterval { 0 }; }; //////////////////////////////////////////////////////////// template <AutomationFunction Func> class Automation final : public AutomationBase { using func_type = typename Func::type; public: Automation(MilliSeconds duration, Func&& ptr) : AutomationBase { duration } , _function { std::move(ptr) } { } Signal<func_type> ValueChanged; auto add_output(func_type* dest) -> Connection { return ValueChanged.connect([dest](const func_type& val) { *dest = val; }); } auto get_value() const -> func_type { return _function.get_value(get_progress()); } private: void update_values() override { ValueChanged.emit(get_value()); } Func _function; }; template <typename Func, typename... Rs> auto make_unique_automation(MilliSeconds duration, Rs&&... args) -> std::unique_ptr<Automation<Func>> { return std::unique_ptr<Automation<Func>>(new Automation<Func> { duration, Func { std::forward<Rs>(args)... } }); } template <typename Func, typename... Rs> auto make_shared_automation(MilliSeconds duration, Rs&&... args) -> std::shared_ptr<Automation<Func>> { return std::shared_ptr<Automation<Func>>(new Automation<Func> { duration, Func { std::forward<Rs>(args)... } }); } //////////////////////////////////////////////////////////// class AutomationQueue final : public Updatable { public: template <typename... Ts> void push(Ts&&... autom) { (_queue.push(std::forward<Ts>(autom)), ...); } void start(bool looped = false); void stop_and_clear(); auto is_empty() const -> bool; void update(MilliSeconds deltaTime) override; private: std::queue<std::shared_ptr<AutomationBase>> _queue {}; bool _isRunning { false }; bool _looped { false }; }; /////////FUNCTIONS////////////////////////////////////////// template <typename T> class LinearFunctionChain final { public: using type = T; LinearFunctionChain(std::vector<T>&& elements) : _elements { std::move(elements) } { } auto get_value(f32 elapsedRatio) const -> T { if (_elements.empty()) { return T {}; } const isize size { _elements.size() - 1 }; const f32 relElapsed { size * elapsedRatio }; const isize index { static_cast<isize>(relElapsed) }; if (index >= size) { return _elements[index]; } else { const T& current { _elements[index] }; const T& next { _elements[index + 1] }; if constexpr (Interpolatable<T>) { return current.get_interpolated(next, relElapsed - index); } else { return current + ((next - current) * (relElapsed - index)); } } } private: std::vector<T> _elements {}; }; //////////////////////////////////////////////////////////// template <typename T> struct PowerFunction final { using type = T; T StartValue; T EndValue; f32 Exponent; auto get_value(f32 elapsedRatio) const -> T { if (Exponent <= 0 && elapsedRatio == 0) { return StartValue; } if constexpr (Interpolatable<T>) { return StartValue.get_interpolated(EndValue, std::pow(elapsedRatio, Exponent)); } else { return StartValue + ((EndValue - StartValue) * std::pow(elapsedRatio, Exponent)); } } }; //////////////////////////////////////////////////////////// template <typename T> struct InversePowerFunction final { using type = T; T StartValue; T EndValue; f32 Exponent; auto get_value(f32 elapsedRatio) const -> T { if (Exponent <= 0 && elapsedRatio == 0) { return StartValue; } if constexpr (Interpolatable<T>) { return StartValue.get_interpolated(EndValue, 1 - std::pow(1 - elapsedRatio, Exponent)); } else { return StartValue + ((EndValue - StartValue) * (1 - std::pow(1 - elapsedRatio, Exponent))); } } }; //////////////////////////////////////////////////////////// template <typename T> struct LinearFunction final { using type = T; T StartValue; T EndValue; auto get_value(f32 elapsedRatio) const -> T { if (elapsedRatio == 0) { return StartValue; } if constexpr (Interpolatable<T>) { return StartValue.get_interpolated(EndValue, elapsedRatio); } else { return StartValue + ((EndValue - StartValue) * elapsedRatio); } } }; //////////////////////////////////////////////////////////// template <typename T> struct SmoothstepFunction final { using type = T; T Edge0; T Edge1; auto get_value(f32 elapsedRatio) const -> T { if (elapsedRatio == 0) { return Edge0; } f32 e { elapsedRatio * elapsedRatio * (3.f - 2.f * elapsedRatio) }; if constexpr (Interpolatable<T>) { return Edge0.get_interpolated(Edge1, e); } else { return Edge0 + ((Edge1 - Edge0) * e); } } }; //////////////////////////////////////////////////////////// template <typename T> struct SmootherstepFunction final { using type = T; T Edge0; T Edge1; auto get_value(f32 elapsedRatio) const -> T { if (elapsedRatio == 0) { return Edge0; } f32 e { elapsedRatio * elapsedRatio * elapsedRatio * (elapsedRatio * (elapsedRatio * 6 - 15) + 10) }; if constexpr (Interpolatable<T>) { return Edge0.get_interpolated(Edge1, e); } else { return Edge0 + ((Edge1 - Edge0) * e); } } }; //////////////////////////////////////////////////////////// template <typename T> struct SineWaveFunction final { using type = T; T MinValue; T MaxValue; f32 Frequency; f32 Phase; auto get_value(f32 elapsedRatio) const -> T { const f64 val { get_wavevalue((Frequency * elapsedRatio)) }; if constexpr (Interpolatable<T>) { return MinValue.get_interpolated(MaxValue, val); } else { return MinValue + ((MaxValue - MinValue) * val); } } private: auto get_wavevalue(f64 time) const -> f64 { return (std::sin((TAU * time) + (0.75 * TAU) + Phase) + 1) / 2; } }; //////////////////////////////////////////////////////////// template <typename T> struct TriangeWaveFunction final { using type = T; T MinValue; T MaxValue; f32 Frequency; f32 Phase; auto get_value(f32 elapsedRatio) const -> T { const f64 val { get_wavevalue((Frequency * elapsedRatio) + Phase) }; if constexpr (Interpolatable<T>) { return MinValue.get_interpolated(MaxValue, val); } else { return MinValue + ((MaxValue - MinValue) * val); } } private: auto get_wavevalue(f64 time) const -> f64 { return 2 * std::abs(std::round(time) - time); } }; //////////////////////////////////////////////////////////// template <typename T> struct SquareWaveFunction final { using type = T; T MinValue; T MaxValue; f32 Frequency; f32 Phase; auto get_value(f32 elapsedRatio) const -> T { const f64 val { get_wavevalue((Frequency * elapsedRatio)) }; if constexpr (Interpolatable<T>) { return MinValue.get_interpolated(MaxValue, val); } else { return MinValue + ((MaxValue - MinValue) * val); } } private: auto get_wavevalue(f64 time) const -> f64 { const f64 x { std::round(time + Phase) / 2 }; return 2 * (x - std::floor(x)); } }; //////////////////////////////////////////////////////////// template <typename T> struct SawtoothWaveFunction final { using type = T; T MinValue; T MaxValue; f32 Frequency; f32 Phase; auto get_value(f32 elapsedRatio) const -> T { const f64 val { get_wavevalue((Frequency * elapsedRatio) + Phase) }; if constexpr (Interpolatable<T>) { return MinValue.get_interpolated(MaxValue, val); } else { return MinValue + ((MaxValue - MinValue) * val); } } private: auto get_wavevalue(f64 time) const -> f64 { return time - std::floor(time); } }; //////////////////////////////////////////////////////////// struct CubicBezierFunction final { using type = PointF; PointF Start; PointF ControlPoint0; PointF ControlPoint1; PointF End; auto get_value(f32 elapsedRatio) const -> PointF { const PointF a { get_point_in_line(Start, ControlPoint0, elapsedRatio) }; const PointF b { get_point_in_line(ControlPoint0, ControlPoint1, elapsedRatio) }; const PointF c { get_point_in_line(ControlPoint1, End, elapsedRatio) }; return get_point_in_line(get_point_in_line(a, b, elapsedRatio), get_point_in_line(b, c, elapsedRatio), elapsedRatio); } private: auto get_point_in_line(const PointF& a, const PointF& b, f32 t) const -> PointF { return { a.X - ((a.X - b.X) * t), a.Y - ((a.Y - b.Y) * t) }; } }; //////////////////////////////////////////////////////////// template <typename T> struct RandomFunction final { using type = T; T MinValue; T MaxValue; mutable Random RNG; auto get_value(f32 elapsedRatio) const -> T { return RNG(MinValue, MaxValue); } }; }
24.408696
125
0.546491
TobiasBohnen
722453a47a24987fd1452538469992a1e5025906
1,288
cpp
C++
ewk/unittest/utc_blink_ewk_context_proxy_uri_set_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
9
2015-04-09T20:22:08.000Z
2021-03-17T08:34:56.000Z
ewk/unittest/utc_blink_ewk_context_proxy_uri_set_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
2
2015-02-04T13:41:12.000Z
2015-05-25T14:00:40.000Z
ewk/unittest/utc_blink_ewk_context_proxy_uri_set_func.cpp
isabella232/chromium-efl
db2d09aba6498fb09bbea1f8440d071c4b0fde78
[ "BSD-3-Clause" ]
14
2015-02-12T16:20:47.000Z
2022-01-20T10:36:26.000Z
// Copyright 2014 Samsung Electronics. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "utc_blink_ewk_base.h" class utc_blink_ewk_context_proxy_uri_set : public utc_blink_ewk_base { protected: static const char*const url; }; const char*const utc_blink_ewk_context_proxy_uri_set::url="http://proxy.tc.url"; /** * @brief Positive TC for ewk_context_proxy_uri_set() */ TEST_F(utc_blink_ewk_context_proxy_uri_set, POS_TEST) { /* TODO: this code should use ewk_context_proxy_uri_set and check its behaviour. Results should be reported using one of utc_ macros */ Ewk_Context* defaultContext = ewk_context_default_get(); if (!defaultContext) utc_fail(); ewk_context_proxy_uri_set(defaultContext, url); utc_check_str_eq(ewk_context_proxy_uri_get(defaultContext), url); } /** * @brief Negative TC for ewk_context_proxy_uri_set() */ TEST_F(utc_blink_ewk_context_proxy_uri_set, NEG_TEST) { /* TODO: this code should use ewk_context_proxy_uri_set and check its behaviour. Results should be reported using one of utc_ macros */ Ewk_Context* defaultContext = ewk_context_default_get(); if (!defaultContext) utc_fail(); ewk_context_proxy_uri_set(NULL, NULL); utc_pass(); }
30.666667
82
0.776398
Jabawack
7229d3675fd07fda77dd0738036f04243218b3cb
1,625
cpp
C++
concept_tests/drivers/freertos_driver.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
3
2019-10-30T07:37:47.000Z
2021-01-21T11:50:20.000Z
concept_tests/drivers/freertos_driver.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
null
null
null
concept_tests/drivers/freertos_driver.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
null
null
null
#include "freertos_driver.h" // void FreeRTOSDriverTask::task() { // run(); // } FreeRTOSDriverTask::FreeRTOSDriverTask( const char * name, int priority, int stack_depth, size_t request_queue_length, TickType_t timeout): FreeRTOSTask(name, priority, stack_depth), request_queue_length(request_queue_length), timeout(timeout), runner(nullptr) { } QueueHandle_t FreeRTOSDriverTask::create_queue( size_t queue_length, size_t data_size) { return xQueueCreate(queue_length, data_size); } void FreeRTOSDriverTask::create_request_queue(size_t data_size) { request_queue = create_queue(request_queue_length, data_size); configASSERT(request_queue); } bool FreeRTOSDriverTask::receive_request(void *into_buffer) { BaseType_t result = xQueueReceive(request_queue, into_buffer, portMAX_DELAY); // TODO: how to specify the delay!!! return result == pdTRUE; } bool FreeRTOSDriverTask::wait_for_isr() { uint32_t notification_value = ulTaskNotifyTake(pdTRUE, portMAX_DELAY); // TODO: how to specify the delay!!! return notification_value != 0; } void FreeRTOSDriverTask::send_response(QueueHandle_t response_queue, const void *from_buffer) { BaseType_t result = xQueueSend(response_queue, from_buffer, portMAX_DELAY); // TODO: how to specify the delay!!! (void) result; // the driver doesn't care, we could try multiple times if needed } void FreeRTOSDriverTask::set_task_runner(TaskRunner *runner) { this->runner = runner; } void FreeRTOSDriverTask::task() { configASSERT(runner != nullptr); runner->run(); }
31.25
95
0.729231
jedrzejboczar
722e215ab9d583c68b4b931841d7e1501fc8ff49
1,453
cpp
C++
algorithms/KthSmallestElementinaBST/tree.cpp
PikachuPikachuHAHA/leetcode-2
4cf8d30509f4b994b1845765807380eeffb95c73
[ "MIT" ]
93
2016-04-27T23:25:27.000Z
2021-07-13T20:32:25.000Z
algorithms/KthSmallestElementinaBST/tree.cpp
shangan/leetcode
db05338f8057ad440cb5dd6cfe0151aafb7a8d56
[ "MIT" ]
null
null
null
algorithms/KthSmallestElementinaBST/tree.cpp
shangan/leetcode
db05338f8057ad440cb5dd6cfe0151aafb7a8d56
[ "MIT" ]
43
2016-05-31T15:46:50.000Z
2021-04-09T04:07:39.000Z
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <cstdio> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr){} }; class Solution { public: int kthSmallest(TreeNode *root, int k) { int result; /* if (root == nullptr) { return 0; } */ kthSmallest(root, k, result); return result; } private: bool kthSmallest(TreeNode *root, int &k, int &result) { if (root->left) { if (kthSmallest(root->left, k, result)) { return true; } } k -= 1; if (k == 0) { result = root->val; return true; } if (root->right) { if (kthSmallest(root->right, k, result)) { return true; } } return false; } }; TreeNode *mk_node(int val) { return new TreeNode(val); } TreeNode *mk_child(TreeNode *root, TreeNode *left, TreeNode *right) { root->left = left; root->right = right; return root; } TreeNode *mk_child(TreeNode *root, int left, int right) { return mk_child(root, new TreeNode(left), new TreeNode(right)); } TreeNode *mk_child(int root, int left, int right) { return mk_child(new TreeNode(root), new TreeNode(left), new TreeNode(right)); } int main(int argc, char **argv) { Solution solution; TreeNode *root = mk_child(6, 4, 8); mk_child(root->left, 3, 5); mk_child(root->right, 7, 9); for (int i = 1; i <= 7; ++i) printf("%d\n", solution.kthSmallest(root, i)); return 0; }
19.90411
78
0.644184
PikachuPikachuHAHA
7236a5e16e768f9e870eab43fe93378f499bac48
985
cpp
C++
System/GroundMissionControl.cpp
MatthewGotte/214_project_Derived
48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd
[ "MIT" ]
null
null
null
System/GroundMissionControl.cpp
MatthewGotte/214_project_Derived
48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd
[ "MIT" ]
null
null
null
System/GroundMissionControl.cpp
MatthewGotte/214_project_Derived
48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd
[ "MIT" ]
null
null
null
#include "GroundMissionControl.h" #include "Satellite.h" GroundMissionControl::GroundMissionControl() { } void GroundMissionControl::attach(Satellite* addSatellite) { this->satelliteList.push_back(addSatellite); } void GroundMissionControl::detach(Satellite* removeSatellite) { vector<Satellite*>::iterator it; for (it = this->satelliteList.begin(); it != this->satelliteList.end(); ++it) { if (*it == removeSatellite && *it != nullptr) { this->satelliteList.erase(it); } } } void GroundMissionControl::notify() { vector<Satellite*>::iterator it; for (it = this->satelliteList.begin(); it != this->satelliteList.end(); ++it) { (*it)->update(); } } GroundMissionControl::~GroundMissionControl() { vector<Satellite*>::iterator it; for (it = this->satelliteList.begin(); it != this->satelliteList.end(); ++it) { delete *it; } }
24.625
84
0.603046
MatthewGotte
5cfb300c5618be540e9dab1268bc36675010d39a
2,624
cpp
C++
homomorphic_evaluation/ntl-11.3.2/src/Poly3TimeTest.cpp
dklee0501/PLDI_20_242_artifact_publication
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
160
2016-05-11T09:45:56.000Z
2022-03-06T09:32:19.000Z
homomorphic_evaluation/ntl-11.3.2/src/Poly3TimeTest.cpp
dklee0501/Lobster
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
57
2016-12-26T07:02:12.000Z
2022-03-06T16:34:31.000Z
homomorphic_evaluation/ntl-11.3.2/src/Poly3TimeTest.cpp
dklee0501/Lobster
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
67
2016-10-10T17:56:22.000Z
2022-03-15T22:56:39.000Z
#include <NTL/ZZ_pX.h> #include <cstdio> NTL_CLIENT double clean_data(double *t) { double x, y, z; long i, ix, iy, n; x = t[0]; ix = 0; y = t[0]; iy = 0; for (i = 1; i < 5; i++) { if (t[i] < x) { x = t[i]; ix = i; } if (t[i] > y) { y = t[i]; iy = i; } } z = 0; n = 0; for (i = 0; i < 5; i++) { if (i != ix && i != iy) z+= t[i], n++; } z = z/n; return z; } void print_flag() { #if (defined(NTL_CRT_ALTCODE)) printf("CRT_ALTCODE "); #else printf("DEFAULT "); #endif printf("\n"); } int main() { SetSeed(ZZ(0)); long n, k; n = 1024; k = 30*NTL_SP_NBITS; ZZ p; RandomLen(p, k); if (!IsOdd(p)) p++; ZZ_p::init(p); // initialization ZZ_pX f, g, h, r1, r2, r3; random(g, n); // g = random polynomial of degree < n random(h, n); // h = " " random(f, n); // f = " " SetCoeff(f, n); // Sets coefficient of X^n to 1 // For doing arithmetic mod f quickly, one must pre-compute // some information. ZZ_pXModulus F; build(F, f); PlainMul(r1, g, h); // this uses classical arithmetic PlainRem(r1, r1, f); MulMod(r2, g, h, F); // this uses the FFT MulMod(r3, g, h, f); // uses FFT, but slower // compare the results... if (r1 != r2) { printf("999999999999999 "); print_flag(); return 0; } else if (r1 != r3) { printf("999999999999999 "); print_flag(); return 0; } double t; long i; long iter; ZZ_pX a, b, c; random(a, n); random(b, n); long da = deg(a); long db = deg(b); long dc = da + db; long l = NextPowerOfTwo(dc+1); FFTRep arep, brep, crep; ToFFTRep(arep, a, l, 0, da); ToFFTRep(brep, b, l, 0, db); mul(crep, arep, brep); ZZ_pXModRep modrep; FromFFTRep(modrep, crep); FromZZ_pXModRep(c, modrep, 0, dc); iter = 1; do { t = GetTime(); for (i = 0; i < iter; i++) { FromZZ_pXModRep(c, modrep, 0, dc); } t = GetTime() - t; iter = 2*iter; } while(t < 1); iter = iter/2; iter = long((3/t)*iter) + 1; double tvec[5]; long w; for (w = 0; w < 5; w++) { t = GetTime(); for (i = 0; i < iter; i++) { FromZZ_pXModRep(c, modrep, 0, dc); } t = GetTime() - t; tvec[w] = t; } t = clean_data(tvec); t = floor((t/iter)*1e12); if (t < 0 || t >= 1e15) printf("999999999999999 "); else printf("%015.0f ", t); printf(" [%ld] ", iter); print_flag(); return 0; }
15.255814
62
0.470655
dklee0501
cf03086f029e45cfbb3b2a27e454049c615950a8
2,462
cpp
C++
Dory/Sensores.cpp
project-neon/Dory
7a84ee5556b681f1b4d2a03db14f170734dd74ed
[ "MIT" ]
1
2021-11-08T20:17:21.000Z
2021-11-08T20:17:21.000Z
Dory/Sensores.cpp
project-neon/Dory
7a84ee5556b681f1b4d2a03db14f170734dd74ed
[ "MIT" ]
null
null
null
Dory/Sensores.cpp
project-neon/Dory
7a84ee5556b681f1b4d2a03db14f170734dd74ed
[ "MIT" ]
1
2021-11-08T19:57:53.000Z
2021-11-08T19:57:53.000Z
#include <VL53L0X.h> #include "Sensores.h" #include "_config.h" #include <Wire.h> VL53L0X Sensores::sensor1; VL53L0X Sensores::sensor2; void Sensores::init(){ Wire.begin(); pinMode(Xshut_1, OUTPUT); pinMode(Xshut_2, OUTPUT); digitalWrite(Xshut_1, LOW); digitalWrite(Xshut_2, LOW); delay(10); //Wire.begin(); //SENSOR (DIREITA) pinMode(Xshut_1, INPUT); delay(50); Sensores::sensor1.init(true); delay(20); Sensores::sensor1.setAddress((uint8_t)0x22); //SENSOR 3(ESQUERDA) pinMode(Xshut_2, INPUT); delay(50); Sensores::sensor2.init(true); delay(20); Sensores::sensor2.setAddress((uint8_t)0x2A); Sensores::sensor1.setTimeout(100); Sensores::sensor2.setTimeout(100); //Sensores::sensor.setMeasurementTimingBudget(20000); //Sensores::sensor2.setMeasurementTimingBudget(20000); //Sensores::sensor3.setMeasurementTimingBudget(20000); } int Sensores::get_valor(VL53L0X sensor){ return sensor.readRangeSingleMillimeters(); } /* void Sensores::Serial() { Serial.println("__________________________________________________________________"); Serial.println(""); Serial.println("================================="); Serial.println ("I2C scanner. Scanning ..."); //FWD OR SENSOR if (sensor.timeoutOccurred()) { Serial.println("_________________________________"); Serial.print("Distance FWD (READING): "); Serial.println(" TIMEOUT"); Serial.println("_________________________________"); Serial.println(""); } else { Serial.print("Distance SENSOR 0 (mm): "); Serial.println(Sensores::init(sensor)); } //FLT OR SENSOR2 if (sensor2.timeoutOccurred()) { Serial.print("Distance SENSOR 1 (READING): "); Serial.println(" TIMEOUT"); Serial.println("_________________________________"); Serial.println(""); } else { Serial.print("Distance SENSOR 1 (mm): "); Serial.println(Sensores::init(sensor2)); } //FRT OR SENSOR3 if (sensor3.timeoutOccurred()) { Serial.println("_________________________________"); Serial.print("Distance SENSOR 2 (READING): "); Serial.println(" TIMEOUT"); Serial.println("_________________________________"); Serial.println(""); } else { Serial.print("Distance SENSOR 2 (mm): "); Serial.println(Sensores::init(sensor3)); } delay(1000);//can change to a lower time like 100 }*/
26.191489
88
0.655971
project-neon
cf0e92dadd83905c9a73be9189544e26aab87294
30,067
cpp
C++
Source/Interface/Resources/FontResource.cpp
Noxagonal/Vulkan2DRenderer
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
[ "MIT" ]
90
2020-06-20T15:00:31.000Z
2022-03-22T21:03:45.000Z
Source/Interface/Resources/FontResource.cpp
Niko40/Vulkan2DRenderer
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
[ "MIT" ]
39
2019-11-04T01:40:14.000Z
2020-03-09T15:57:00.000Z
Source/Interface/Resources/FontResource.cpp
Niko40/Vulkan2DRenderer
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
[ "MIT" ]
4
2020-12-02T22:39:33.000Z
2021-12-27T07:55:12.000Z
#include "Core/SourceCommon.h" #include "System/ThreadPrivateResources.h" #include "Interface/InstanceImpl.h" #include "Interface/Resources/ResourceManager.h" #include "Interface/Resources/ResourceManagerImpl.h" #include "Interface/Resources/FontResource.h" #include "Interface/Resources/FontResourceImpl.h" #include "Interface/Resources/TextureResource.h" #include <stb_image_write.h> namespace vk2d { namespace _internal { // Private function declarations. uint32_t RoundToCeilingPowerOfTwo( uint32_t value ); } } //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // Interface. //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// VK2D_API vk2d::FontResource::FontResource( vk2d::_internal::ResourceManagerImpl * resource_manager, uint32_t loader_thread_index, vk2d::ResourceBase * parent_resource, const std::filesystem::path & file_path, uint32_t glyph_texel_size, bool use_alpha, uint32_t fallback_character, uint32_t glyph_atlas_padding ) { impl = std::make_unique<vk2d::_internal::FontResourceImplBase>( this, resource_manager, loader_thread_index, parent_resource, file_path, glyph_texel_size, use_alpha, fallback_character, glyph_atlas_padding ); if( !impl || !impl->IsGood() ) { impl = nullptr; resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font resource implementation!" ); return; } resource_impl = impl.get(); } VK2D_API vk2d::FontResource::~FontResource() {} VK2D_API vk2d::ResourceStatus VK2D_APIENTRY vk2d::FontResource::GetStatus() { return impl->GetStatus(); } VK2D_API vk2d::ResourceStatus VK2D_APIENTRY vk2d::FontResource::WaitUntilLoaded( std::chrono::nanoseconds timeout ) { return impl->WaitUntilLoaded( timeout ); } VK2D_API vk2d::ResourceStatus VK2D_APIENTRY vk2d::FontResource::WaitUntilLoaded( std::chrono::steady_clock::time_point timeout ) { return impl->WaitUntilLoaded( timeout ); } VK2D_API vk2d::Rect2f VK2D_APIENTRY vk2d::FontResource::CalculateRenderedSize( std::string_view text, float kerning, glm::vec2 scale, bool vertical, uint32_t font_face, bool wait_for_resource_load ) { return impl->CalculateRenderedSize( text, kerning, scale, vertical, font_face, wait_for_resource_load ); } VK2D_API bool VK2D_APIENTRY vk2d::FontResource::IsGood() const { return !!impl; } //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // Implementation. //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// vk2d::_internal::FontResourceImplBase::FontResourceImplBase( vk2d::FontResource * my_interface, vk2d::_internal::ResourceManagerImpl * resource_manager, uint32_t loader_thread_index, vk2d::ResourceBase * parent_resource, const std::filesystem::path & file_path, uint32_t glyph_texel_size, bool use_alpha, uint32_t fallback_character, uint32_t glyph_atlas_padding ) : vk2d::_internal::ResourceImplBase( my_interface, loader_thread_index, resource_manager, parent_resource, { file_path } ) { assert( my_interface ); assert( resource_manager ); this->my_interface = my_interface; this->resource_manager = resource_manager; this->glyph_texel_size = glyph_texel_size; this->glyph_atlas_padding = glyph_atlas_padding; this->fallback_character = fallback_character; this->use_alpha = use_alpha; is_good = true; } vk2d::_internal::FontResourceImplBase::~FontResourceImplBase() {} vk2d::ResourceStatus vk2d::_internal::FontResourceImplBase::GetStatus() { if( !is_good ) return vk2d::ResourceStatus::FAILED_TO_LOAD; auto local_status = status.load(); if( local_status == vk2d::ResourceStatus::UNDETERMINED ) { if( load_function_run_fence.IsSet() ) { // "texture_resource" is set by the MTLoad() function so we can access it // without further mutex locking. ( "load_function_run_fence" is set ) status = local_status = texture_resource->GetStatus(); } } return local_status; } vk2d::ResourceStatus vk2d::_internal::FontResourceImplBase::WaitUntilLoaded( std::chrono::nanoseconds timeout ) { if( timeout == std::chrono::nanoseconds::max() ) { return WaitUntilLoaded( std::chrono::steady_clock::time_point::max() ); } return WaitUntilLoaded( std::chrono::steady_clock::now() + timeout ); } vk2d::ResourceStatus vk2d::_internal::FontResourceImplBase::WaitUntilLoaded( std::chrono::steady_clock::time_point timeout ) { // Make sure timeout is in the future. assert( timeout == std::chrono::steady_clock::time_point::max() || timeout + std::chrono::seconds( 5 ) >= std::chrono::steady_clock::now() ); if( !is_good ) return vk2d::ResourceStatus::FAILED_TO_LOAD; auto local_status = status.load(); if( local_status == vk2d::ResourceStatus::UNDETERMINED ) { if( load_function_run_fence.Wait( timeout ) ) { status = local_status = texture_resource->WaitUntilLoaded( timeout ); } } return local_status; } bool vk2d::_internal::FontResourceImplBase::MTLoad( vk2d::_internal::ThreadPrivateResource * thread_resource ) { // TODO: additional parameters: // From raw file. assert( thread_resource ); assert( my_interface->impl->GetFilePaths().size() ); auto loader_thread_resource = static_cast<vk2d::_internal::ThreadLoaderResource*>( thread_resource ); auto instance = loader_thread_resource->GetInstance(); auto path_str = my_interface->impl->GetFilePaths()[ 0 ].string(); auto max_texture_size = instance->GetVulkanPhysicalDeviceProperties().limits.maxImageDimension2D; auto min_texture_size = std::min( uint32_t( 128 ), max_texture_size ); // average_to_max_weight variable is used to estimate glyph space requirements on atlas textures. // 0 sets the estimation to average size, 1 sets the estimation to max weights. Default is 0.05 // which should give enough space in the atlas to contain all glyphs in auto average_to_max_weight = 0.05; auto total_glyph_count = uint64_t( 0 ); auto maximum_glyph_size = glm::dvec2( 0.0, 0.0 ); auto maximum_glyph_bitmap_size = glm::dvec2( 0.0, 0.0 ); auto maximum_glyph_bitmap_occupancy_size = glm::dvec2( 0.0, 0.0 ); auto average_glyph_bitmap_occupancy_size = glm::dvec2( 0.0, 0.0 ); if( my_interface->impl->IsFromFile() ) { // Try to load from file. // Get amount of faces in the file uint32_t face_count = 0; { FT_Face face {}; auto ft_error = FT_New_Face( loader_thread_resource->GetFreeTypeInstance(), path_str.c_str(), -1, &face ); switch( ft_error ) { case FT_Err_Ok: // All good face_count = uint32_t( face->num_faces ); FT_Done_Face( face ); break; case FT_Err_Cannot_Open_Resource: // Cannot open file error instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Cannot load font: File not found: " ) + path_str ); return false; case FT_Err_Unknown_File_Format: // Unknown file format error instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Cannot load font: Unknown file format: " ) + path_str ); return false; default: // Other errors instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Cannot load font: " ) + path_str ); return false; } } assert( !face_infos.size() ); // If hit, this function was called twice for some reason, should never happen. face_infos.clear(); face_infos.resize( face_count ); for( uint32_t i = 0; i < face_count; ++i ) { FT_Face face {}; { auto ft_error = FT_New_Face( loader_thread_resource->GetFreeTypeInstance(), path_str.c_str(), i, &face ); if( ft_error ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Cannot load font: " ) + path_str ); return false; } } { auto ft_error = FT_Set_Pixel_Sizes( face, 0, glyph_texel_size ); if( ft_error ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Cannot load font: " ) + path_str ); return false; } } // Get glyph sizes total_glyph_count += uint64_t( face->num_glyphs ) + 1; for( decltype( face->num_glyphs ) i = 0; i < face->num_glyphs; ++i ) { auto ft_load_error = FT_Load_Glyph( face, FT_UInt( i ), FT_LOAD_DEFAULT ); if( ft_load_error ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, cannot load glyph for bitmap metrics!" ); return false; } auto glyph_size = glm::dvec2( double( face->glyph->metrics.width ), double( face->glyph->metrics.height ) ); auto glyph_bitmap_size = glm::dvec2( double( face->glyph->bitmap.width ), double( face->glyph->bitmap.rows ) ); auto glyph_bitmap_space_occupancy = glm::dvec2( double( face->glyph->bitmap.width + glyph_atlas_padding ), double( face->glyph->bitmap.rows + glyph_atlas_padding ) ); maximum_glyph_size.x = std::max( maximum_glyph_size.x, glyph_size.x ); maximum_glyph_size.y = std::max( maximum_glyph_size.y, glyph_size.y ); maximum_glyph_bitmap_size.x = std::max( maximum_glyph_bitmap_size.x, glyph_bitmap_size.x ); maximum_glyph_bitmap_size.y = std::max( maximum_glyph_bitmap_size.y, glyph_bitmap_size.y ); maximum_glyph_bitmap_occupancy_size.x = std::max( maximum_glyph_bitmap_occupancy_size.x, glyph_bitmap_space_occupancy.x ); maximum_glyph_bitmap_occupancy_size.y = std::max( maximum_glyph_bitmap_occupancy_size.y, glyph_bitmap_space_occupancy.y ); average_glyph_bitmap_occupancy_size += glyph_bitmap_space_occupancy; } face_infos[ i ].face = face; } } else { // Try to load from data. assert( 0 && "Not implemented yet!" ); } if( !total_glyph_count ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Cannot load font: Font contains no glyphs!" ); return false; } // Estimate appropriate atlas size. // This code tries to find a tradeoff between texture size and amount so that 1 to 3 textures are // created. For example if glyphs do not fit into 3 textures of size 512 * 512, a larger 1024 * 1024 // texture is created which should be able to contain the glyphs. average_glyph_bitmap_occupancy_size += glm::dvec2( double( glyph_atlas_padding ), double( glyph_atlas_padding ) ) * 2.0; average_glyph_bitmap_occupancy_size /= float( total_glyph_count ); { auto estimated_glyph_space_requirements = average_glyph_bitmap_occupancy_size * ( 1.0 - average_to_max_weight ) + maximum_glyph_bitmap_occupancy_size * average_to_max_weight; auto estimated_average_space_requirements = estimated_glyph_space_requirements / 1.5; // aim to have 1 to 4 textures to optimize memory usage // auto estimated_average_space_requirements = estimated_glyph_space_requirements / 5.0; // aim to have 1 to 4 textures to optimize memory usage atlas_size = RoundToCeilingPowerOfTwo( uint32_t( std::sqrt( std::ceil( estimated_average_space_requirements.x ) * std::ceil( estimated_average_space_requirements.y ) * double( total_glyph_count ) ) ) ); if( atlas_size > max_texture_size ) atlas_size = max_texture_size; if( atlas_size < min_texture_size ) atlas_size = min_texture_size; } // Stop if we don't have any font's to work with. if( !face_infos.size() ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Internal error: Cannot load font: " ) + path_str ); return false; } current_atlas_texture = CreateNewAtlasTexture(); auto glyph_size_bitmap_size_ratio_vector = maximum_glyph_bitmap_size / maximum_glyph_size; auto glyph_size_bitmap_size_ratio = std::max( glyph_size_bitmap_size_ratio_vector.x, glyph_size_bitmap_size_ratio_vector.y ); // Process all glyphs from all font faces for( size_t face_index = 0; face_index < face_infos.size(); ++face_index ) { auto & face = face_infos[ face_index ]; face.glyph_infos.resize( face.face->num_glyphs ); for( auto glyph_index = 0; glyph_index < face.face->num_glyphs; ++glyph_index ) { { auto ft_load_error = FT_Load_Glyph( face.face, glyph_index, FT_LOAD_DEFAULT ); if( ft_load_error ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, cannot load glyph!" ); return false; } } { auto ft_render_error = FT_Render_Glyph( face.face->glyph, use_alpha ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO ); if( ft_render_error ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, cannot render glyph!" ); return false; } } auto ft_glyph = face.face->glyph; auto & ft_bitmap = ft_glyph->bitmap; std::vector<vk2d::Color8> final_glyph_pixels( size_t( ft_bitmap.rows ) * size_t( ft_bitmap.width ) ); switch( ft_bitmap.pixel_mode ) { case FT_PIXEL_MODE_MONO: { for( uint32_t y = 0; y < ft_bitmap.rows; ++y ) { for( uint32_t x = 0; x < ft_bitmap.width; ++x ) { auto texel_pos = y * ft_bitmap.width + x; auto & dst = final_glyph_pixels[ texel_pos ]; auto src_bit = 7 - x % 8; auto src_byte = ft_bitmap.buffer[ ( y * ft_bitmap.pitch ) + ( x / 8 ) ]; dst.r = ( ( src_byte >> src_bit ) & 1 ) * 255; dst.g = dst.r; dst.b = dst.r; dst.a = dst.r; } } } break; case FT_PIXEL_MODE_GRAY: { for( uint32_t y = 0; y < ft_bitmap.rows; ++y ) { for( uint32_t x = 0; x < ft_bitmap.width; ++x ) { auto texel_pos = y * ft_bitmap.width + x; auto & dst = final_glyph_pixels[ texel_pos ]; auto src = ft_bitmap.buffer[ texel_pos ]; dst.r = src; dst.g = src; dst.b = src; dst.a = src; } } } break; case FT_PIXEL_MODE_BGRA: { for( uint32_t y = 0; y < ft_bitmap.rows; ++y ) { for( uint32_t x = 0; x < ft_bitmap.width; ++x ) { auto texel_pos = y * ft_bitmap.width + x; auto & dst = final_glyph_pixels[ texel_pos ]; auto src = &ft_bitmap.buffer[ texel_pos * 4 ]; dst.r = src[ 2 ]; dst.g = src[ 1 ]; dst.b = src[ 0 ]; dst.a = src[ 3 ]; } } } break; default: // Unsupported instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, Unsupported pixel format!" ); return false; break; } // Attach rendered glyph to final texture atlas. auto atlas_location = AttachGlyphToAtlas( face.face->glyph, glyph_atlas_padding, final_glyph_pixels ); if( !atlas_location.atlas_ptr ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot copy glyph image to font texture atlas!" ); return false; } // Create glyph info structure for the glyph { vk2d::Rect2f uv_coords = { float( atlas_location.location.top_left.x ) / float( atlas_size ), float( atlas_location.location.top_left.y ) / float( atlas_size ), float( atlas_location.location.bottom_right.x ) / float( atlas_size ), float( atlas_location.location.bottom_right.y ) / float( atlas_size ) }; auto & metrics = face.face->glyph->metrics; auto glyph_size = glm::dvec2( metrics.width, metrics.height ) * glyph_size_bitmap_size_ratio; auto glyph_hori_top_left = glm::dvec2( metrics.horiBearingX, -metrics.horiBearingY ) * glyph_size_bitmap_size_ratio; auto glyph_hori_bottom_right = glyph_hori_top_left + glyph_size; auto glyph_vert_top_left = glm::dvec2( metrics.vertBearingX, metrics.vertBearingY ) * glyph_size_bitmap_size_ratio; auto glyph_vert_bottom_right = glyph_vert_top_left + glyph_size; auto hori_advance = metrics.horiAdvance * glyph_size_bitmap_size_ratio; auto vert_advance = metrics.vertAdvance * glyph_size_bitmap_size_ratio; vk2d::_internal::GlyphInfo glyph_info {}; glyph_info.face_index = uint32_t( face_index ); glyph_info.atlas_index = atlas_location.atlas_index; glyph_info.uv_coords = uv_coords; glyph_info.horisontal_coords.top_left = glm::vec2( float( glyph_hori_top_left.x ), float( glyph_hori_top_left.y ) ); glyph_info.horisontal_coords.bottom_right = glm::vec2( float( glyph_hori_bottom_right.x ), float( glyph_hori_bottom_right.y ) ); glyph_info.vertical_coords.top_left = glm::vec2( float( glyph_vert_top_left.x ), float( glyph_vert_top_left.y ) ); glyph_info.vertical_coords.bottom_right = glm::vec2( float( glyph_vert_bottom_right.x ), float( glyph_vert_bottom_right.y ) ); glyph_info.horisontal_advance = float( hori_advance ); glyph_info.vertical_advance = float( vert_advance ); face.glyph_infos[ glyph_index ] = glyph_info; } } // Create character map and get fallback character { FT_ULong charcode = {}; FT_UInt gindex = {}; FT_ULong fallback_glyph_index = {}; charcode = FT_Get_First_Char( face.face, &gindex ); fallback_glyph_index = gindex; while( gindex != 0 ) { face.charmap[ uint32_t( charcode ) ] = uint32_t( gindex ); charcode = FT_Get_Next_Char( face.face, charcode, &gindex ); } if( auto f = FT_Get_Char_Index( face.face, FT_ULong( fallback_character ) ) ) { fallback_glyph_index = f; } face.fallback_glyph_index = fallback_glyph_index; } } // Destroy font faces, we don't need them anymore. for( auto & f : face_infos ) { FT_Done_Face( f.face ); f.face = nullptr; } // Everything is baked into the atlas, create texture resource to store it. { std::vector<const std::vector<vk2d::Color8>*> texture_data_array( atlas_textures.size() ); for( size_t i = 0; i < atlas_textures.size(); ++i ) { texture_data_array[ i ] = &atlas_textures[ i ]->data; } texture_resource = resource_manager->CreateArrayTextureResource( glm::uvec2( atlas_size, atlas_size ), texture_data_array, my_interface ); if( !texture_resource ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot create texture resource for font!" ); return false; } } return true; } void vk2d::_internal::FontResourceImplBase::MTUnload( vk2d::_internal::ThreadPrivateResource * thread_resource ) { // Make sure font faces are destroyed. for( auto f : face_infos ) { FT_Done_Face( f.face ); } face_infos.clear(); } vk2d::Rect2f vk2d::_internal::FontResourceImplBase::CalculateRenderedSize( std::string_view text, float kerning, glm::vec2 scale, bool vertical, uint32_t font_face, bool wait_for_resource_load ) { if( std::size( text ) <= 0 ) return {}; if( wait_for_resource_load ) { WaitUntilLoaded( std::chrono::nanoseconds::max() ); } else { if( GetStatus() == vk2d::ResourceStatus::UNDETERMINED ) return {}; } if( !FaceExists( font_face ) ) return {}; vk2d::Rect2f ret {}; float advance {}; if( vertical ) { // Vertical text // First letter sets defaults auto first_gi = GetGlyphInfo( font_face, text[ 0 ] ); ret.top_left.x = first_gi->vertical_coords.top_left.x; ret.bottom_right.x = first_gi->vertical_coords.bottom_right.x; if( std::size( text ) > 1 ) { advance += first_gi->vertical_advance; } for( size_t i = 1; i < std::size( text ) - 1; ++i ) { // Middle letters are spaced by "advance" value auto gi = GetGlyphInfo( font_face, text[ i ] ); ret.top_left.x = std::min( ret.top_left.x, gi->vertical_coords.top_left.x ); ret.bottom_right.x = std::max( ret.bottom_right.x, gi->vertical_coords.bottom_right.x ); advance += kerning + gi->vertical_advance; } // Need to get the size of the last letter, not the "advance" auto last_gi = GetGlyphInfo( font_face, text.back() ); ret.top_left.x = std::min( ret.top_left.x, last_gi->vertical_coords.top_left.x ); ret.bottom_right.x = std::max( ret.bottom_right.x, last_gi->vertical_coords.bottom_right.x ); ret.top_left.y = first_gi->vertical_coords.top_left.y; ret.bottom_right.y = advance + last_gi->vertical_coords.bottom_right.y; } else { // Horisontal text // First letter sets defaults auto first_gi = GetGlyphInfo( font_face, text[ 0 ] ); ret.top_left.y = first_gi->horisontal_coords.top_left.y; ret.bottom_right.y = first_gi->horisontal_coords.bottom_right.y; if( std::size( text ) > 1 ) { advance += first_gi->horisontal_advance; } for( size_t i = 1; i < std::size( text ) - 1; ++i ) { // Middle letters are spaced by "advance" value auto gi = GetGlyphInfo( font_face, text[ i ] ); ret.top_left.y = std::min( ret.top_left.y, gi->horisontal_coords.top_left.y ); ret.bottom_right.y = std::max( ret.bottom_right.y, gi->horisontal_coords.bottom_right.y ); advance += kerning + gi->horisontal_advance; } // Need to get the size of the last letter, not the "advance" auto last_gi = GetGlyphInfo( font_face, text.back() ); ret.top_left.y = std::min( ret.top_left.y, last_gi->horisontal_coords.top_left.y ); ret.bottom_right.y = std::max( ret.bottom_right.y, last_gi->horisontal_coords.bottom_right.y ); ret.top_left.x = first_gi->horisontal_coords.top_left.x; ret.bottom_right.x = advance + last_gi->horisontal_coords.bottom_right.x; } ret.top_left *= scale; ret.bottom_right *= scale; return ret; } bool vk2d::_internal::FontResourceImplBase::FaceExists( uint32_t font_face ) const { if( size_t( font_face ) < face_infos.size() ) { return true; } return false; } vk2d::TextureResource * vk2d::_internal::FontResourceImplBase::GetTextureResource() { if( GetStatus() == vk2d::ResourceStatus::LOADED ) { return texture_resource; } return {}; } const vk2d::_internal::GlyphInfo * vk2d::_internal::FontResourceImplBase::GetGlyphInfo( uint32_t font_face, uint32_t character ) const { auto & face_info = face_infos[ font_face ]; auto & charmap = face_info.charmap; auto glyph_it = charmap.find( character ); auto glyph_index = uint32_t( 0 ); if( glyph_it != charmap.end() ) { glyph_index = glyph_it->second; } else { glyph_index = face_info.fallback_glyph_index; } return &face_info.glyph_infos[ glyph_index ]; } bool vk2d::_internal::FontResourceImplBase::IsGood() const { return is_good; } vk2d::_internal::FontResourceImplBase::AtlasTexture * vk2d::_internal::FontResourceImplBase::CreateNewAtlasTexture() { auto new_atlas_texture = std::make_unique<vk2d::_internal::FontResourceImplBase::AtlasTexture>(); new_atlas_texture->data.resize( size_t( atlas_size ) * size_t( atlas_size ) ); new_atlas_texture->index = uint32_t( atlas_textures.size() ); std::memset( new_atlas_texture->data.data(), 0, new_atlas_texture->data.size() * sizeof( vk2d::Color8 ) ); auto new_atlas_texture_ptr = new_atlas_texture.get(); atlas_textures.push_back( std::move( new_atlas_texture ) ); return new_atlas_texture_ptr; } vk2d::_internal::FontResourceImplBase::AtlasLocation vk2d::_internal::FontResourceImplBase::ReserveSpaceForGlyphFromAtlasTextures( FT_GlyphSlot glyph, uint32_t glyph_atlas_padding ) { assert( current_atlas_texture ); auto FindLocationInAtlasTexture =[]( vk2d::_internal::FontResourceImplBase::AtlasTexture * atlas_texture, FT_GlyphSlot glyph, uint32_t atlas_size, uint32_t glyph_atlas_padding ) -> vk2d::_internal::FontResourceImplBase::AtlasLocation { uint32_t glyph_width = uint32_t( glyph->bitmap.width ) + glyph_atlas_padding; uint32_t glyph_height = uint32_t( glyph->bitmap.rows ) + glyph_atlas_padding; // Find space in the current atlas texture. if( atlas_texture->previous_row_height + glyph_height + glyph_atlas_padding < atlas_size ) { // Fits height wise. if( atlas_texture->current_write_location + glyph_width + glyph_atlas_padding < atlas_size ) { // Fits width wise, fits completely. vk2d::_internal::FontResourceImplBase::AtlasLocation new_glyph_location {}; new_glyph_location.atlas_ptr = atlas_texture; new_glyph_location.atlas_index = atlas_texture->index; new_glyph_location.location.top_left = { atlas_texture->current_write_location + glyph_atlas_padding, atlas_texture->previous_row_height + glyph_atlas_padding }; new_glyph_location.location.bottom_right = new_glyph_location.location.top_left + glm::uvec2( uint32_t( glyph->bitmap.width ), uint32_t( glyph->bitmap.rows ) ); // update current row height and write locations before returning the result. atlas_texture->current_row_height = std::max( atlas_texture->current_row_height, glyph_height ); atlas_texture->current_write_location += glyph_width; return new_glyph_location; } // Does not fit width wise, go to the next row. atlas_texture->previous_row_height += atlas_texture->current_row_height; atlas_texture->current_row_height = 0; atlas_texture->current_write_location = 0; // Check height again. if( atlas_texture->previous_row_height + glyph_height + glyph_atlas_padding < atlas_size ) { // Fits height wise. if( atlas_texture->current_write_location + glyph_width + glyph_atlas_padding < atlas_size ) { // Fits width wise. vk2d::_internal::FontResourceImplBase::AtlasLocation new_glyph_location {}; new_glyph_location.atlas_ptr = atlas_texture; new_glyph_location.atlas_index = atlas_texture->index; new_glyph_location.location.top_left = { atlas_texture->current_write_location + glyph_atlas_padding, atlas_texture->previous_row_height + glyph_atlas_padding }; new_glyph_location.location.bottom_right = new_glyph_location.location.top_left + glm::uvec2( uint32_t( glyph->bitmap.width ), uint32_t( glyph->bitmap.rows ) ); // update current row height and write locations before returning the result. atlas_texture->current_row_height = std::max( atlas_texture->current_row_height, glyph_height ); atlas_texture->current_write_location += glyph_width; return new_glyph_location; } // Does not fit width wise to a new row, this would only happen if a single // face glyph is too large to fit into a single atlas. This is an error. assert( 0 && "Glyph too big" ); return {}; } // Does not fit to a new row, need a new atlas texture return {}; } // Does not fit at all, need a new atlas texture. return {}; }; auto new_location = FindLocationInAtlasTexture( current_atlas_texture, glyph, atlas_size, glyph_atlas_padding ); if( !new_location.atlas_ptr ) { // Not enough space found, create new atlas and try again. current_atlas_texture = CreateNewAtlasTexture(); if( !current_atlas_texture ) { // Failed to create new atlas texture. resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot create new atlas texture for font!" ); return {}; } // Got new atlas texture, retry finding space in it. new_location = FindLocationInAtlasTexture( current_atlas_texture, glyph, atlas_size, glyph_atlas_padding ); if( !new_location.atlas_ptr ) { // Still could not find enough space, a single font face glyph is too large // to fit entire atlas, this should not happen so we raise an error. resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, a single glyph wont fit into a new atlas." ); return {}; } return new_location; } return new_location; } void vk2d::_internal::FontResourceImplBase::CopyGlyphTextureToAtlasLocation( AtlasLocation atlas_location, const std::vector<vk2d::Color8> & converted_texture_data ) { assert( atlas_location.atlas_ptr ); auto glyph_width = atlas_location.location.bottom_right.x - atlas_location.location.top_left.x; auto glyph_height = atlas_location.location.bottom_right.y - atlas_location.location.top_left.y; glm::uvec2 location = atlas_location.location.top_left; for( uint32_t gy = 0; gy < glyph_height; ++gy ) { for( uint32_t gx = 0; gx < glyph_width; ++gx ) { auto ax = location.x + gx; auto ay = location.y + gy; atlas_location.atlas_ptr->data[ ay * atlas_size + ax ] = converted_texture_data[ gy * glyph_width + gx ]; } } } vk2d::_internal::FontResourceImplBase::AtlasLocation vk2d::_internal::FontResourceImplBase::AttachGlyphToAtlas( FT_GlyphSlot glyph, uint32_t glyph_atlas_padding, const std::vector<vk2d::Color8> & converted_texture_data ) { auto atlas_location = ReserveSpaceForGlyphFromAtlasTextures( glyph, glyph_atlas_padding ); if( atlas_location.atlas_ptr ) { CopyGlyphTextureToAtlasLocation( atlas_location, converted_texture_data ); return atlas_location; } else { resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot attach glyph to atlas texture!" ); return {}; } } uint32_t vk2d::_internal::RoundToCeilingPowerOfTwo( uint32_t value ) { value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value++; return value; }
32.364909
177
0.683241
Noxagonal
cf1485d6b4456ed43ad3558b0191dc7ba14f6957
162
cpp
C++
src/utils/Application.cpp
mgeorgoulopoulos/gencut
e9751c0d04816311d5460d14a88eaa1fcbe6f40d
[ "MIT" ]
null
null
null
src/utils/Application.cpp
mgeorgoulopoulos/gencut
e9751c0d04816311d5460d14a88eaa1fcbe6f40d
[ "MIT" ]
null
null
null
src/utils/Application.cpp
mgeorgoulopoulos/gencut
e9751c0d04816311d5460d14a88eaa1fcbe6f40d
[ "MIT" ]
null
null
null
#include "Application.h" #include "GenomeModel.h" void Application::execute() { GenomeModel model; model.load(arguments.genomeModelFilename, geneRegistry); }
18
57
0.771605
mgeorgoulopoulos
cf197e0fc95906c485da135c45136ca4783a1cd7
3,272
cpp
C++
src/script/scriptlistingdialog.cpp
nilsding/IrrerrC
0ff273e96c7a2f731ae23e17c9d58b872db14ebc
[ "BSD-2-Clause" ]
1
2016-06-14T14:21:27.000Z
2016-06-14T14:21:27.000Z
src/script/scriptlistingdialog.cpp
nilsding/IrrerrC
0ff273e96c7a2f731ae23e17c9d58b872db14ebc
[ "BSD-2-Clause" ]
null
null
null
src/script/scriptlistingdialog.cpp
nilsding/IrrerrC
0ff273e96c7a2f731ae23e17c9d58b872db14ebc
[ "BSD-2-Clause" ]
null
null
null
#include "scriptlistingdialog.h" #include "ui_scriptlistingdialog.h" ScriptListingDialog::ScriptListingDialog(QWidget *parent) : QDialog(parent), _ui(new Ui::ScriptListingDialog), _scriptDirModel(new QFileSystemModel), _currentScript(0) { _scriptDir = QFileInfo(_SETTINGS.fileName()).absolutePath() + "/scripts"; QDir d(_scriptDir); if (!d.exists()) { d.mkpath(_scriptDir); } connect(_scriptDirModel, &QFileSystemModel::directoryLoaded, this, [=](const QString &path) { _ui->qlvScriptList->setRootIndex(_scriptDirModel->index(path)); QDir d(path); d.setFilter(QDir::NoDotAndDotDot | QDir::Files); if (d.count() < 1) { _ui->qlScriptName->setText(""); _ui->qlAuthor->setText(""); _ui->qlDescription->setText(tr("You currently don't have any scripts installed.")); _qpbEdit->setEnabled(false); if (_currentScript) { _currentScript->deleteLater(); _currentScript = 0; } } else { if (!_currentScript) { _ui->qlDescription->setText(tr("Select a script from the list on the left.")); _qpbEdit->setEnabled(false); } } }); _ui->setupUi(this); _qpbEdit = _ui->qdbbButtons->addButton(tr("&Edit"), QDialogButtonBox::ActionRole); _qpbEdit->setEnabled(false); _ui->qlScriptName->setText(""); _ui->qlAuthor->setText(""); _ui->qlDescription->setText(""); _scriptDirModel->setRootPath(_scriptDir); _scriptDirModel->setFilter(QDir::NoDotAndDotDot | QDir::Files); QStringList filters; filters << "*.js"; _scriptDirModel->setNameFilters(filters); _scriptDirModel->setNameFilterDisables(false); _ui->qlvScriptList->setModel(_scriptDirModel); } ScriptListingDialog::~ScriptListingDialog() { _currentScript->deleteLater(); delete _ui; } void ScriptListingDialog::on_qdbbButtons_clicked(QAbstractButton *button) { auto buttons = _ui->qdbbButtons->buttons(); QAbstractButton *b = 0; for (auto btn : buttons) { if (btn == button) { b = btn; break; } } if (_ui->qdbbButtons->buttonRole(b) == QDialogButtonBox::ActionRole) { QUrl url; url.setPath(_scriptDirModel->filePath(_ui->qlvScriptList->selectionModel()->selectedIndexes().first())); url.setScheme(QLatin1String("file")); QDesktopServices::openUrl(url); } } void ScriptListingDialog::on_qpbOpenScriptDirectory_clicked() { QDesktopServices::openUrl(QUrl::fromLocalFile(_scriptDir)); } void ScriptListingDialog::on_qpbGetMoreScripts_clicked() { QDesktopServices::openUrl(QUrl("http://irc.rrerr.net/client/scripts")); } void ScriptListingDialog::on_qlvScriptList_clicked(const QModelIndex &index) { if (_currentScript) { _currentScript->deleteLater(); } _currentScript = new NScript(_scriptDirModel->filePath(index), this); _ui->qlScriptName->setText(_currentScript->scriptName().toHtmlEscaped()); _ui->qlAuthor->setText(tr("Author: <b>%1</b>").arg(_currentScript->author().toHtmlEscaped())); _ui->qlDescription->setText(_currentScript->description()); _qpbEdit->setEnabled(true); }
32.72
112
0.654951
nilsding
cf19d1a9499b20b8b71a2f80ec54d258e801780e
3,505
cpp
C++
src/wbdl/wbdl.cpp
DAlexis/wb-display-lib
67317051282d69904774d10553c33ed6c2dedb56
[ "MIT" ]
null
null
null
src/wbdl/wbdl.cpp
DAlexis/wb-display-lib
67317051282d69904774d10553c33ed6c2dedb56
[ "MIT" ]
null
null
null
src/wbdl/wbdl.cpp
DAlexis/wb-display-lib
67317051282d69904774d10553c33ed6c2dedb56
[ "MIT" ]
null
null
null
#include "wbdl.hpp" #include <algorithm> using namespace wbdl; ////////////////////////// // FrameBuffer void FrameBuffer::clearDirty() { dirtyX0 = 0; dirtyY0 = 0; dirtyX1 = 0; dirtyY1 = 0; } bool FrameBuffer::isDirty() { return dirtyX0 != dirtyX1; } unsigned int FrameBuffer::bufferSize() { return width * height / 8; } void FrameBuffer::makePointDirty(unsigned int x, unsigned int y) { if (isDirty()) { dirtyX0 = x; dirtyX1 = x+1; dirtyY0 = y; dirtyY1 = y+1; return; } if (x < dirtyX0) dirtyX0 = x; else if (x+1 > dirtyX1) dirtyX1 = x+1; if (y < dirtyY0) dirtyY0 = y; else if (y+1 > dirtyY1) dirtyY1 = y+1; } void FrameBuffer::putPixelNoDirty(int x, int y, Color c) { if (x < 0 || y < 0 || x >= int(width) || y >= int(height)) return; unsigned int index; switch(order) { case BitsOrder::vertical: index = x + (y / 8) * width; if (c == Color::white) buffer[index] |= 1 << (y%8); else buffer[index] &= ~(1 << (y%8)); break; } } Color FrameBuffer::getPixel(int x, int y) const { if (x < 0 || y < 0 || x >= int(width) || y >= int(height)) return Color::black; unsigned int index; switch(order) { case BitsOrder::vertical: index = x + (y / 8) * width; return (buffer[index] & (1 << (y%8))) != 0 ? Color::white : Color::black; } return Color::black; } ////////////////////////// // Display Display::Display(IDisplayDriver& driver, FrameBuffer& frameBuffer) : m_driver(driver), m_frameBuffer(frameBuffer) { } void Display::updateScreen() { m_driver.updateScreen(m_frameBuffer); m_frameBuffer.clearDirty(); } void Display::putPixel(int x, int y, Color c) { m_frameBuffer.putPixelNoDirty(x, y, c); m_frameBuffer.makePointDirty(x, y); } void Display::line(int x0, int y0, int x1, int y1, Color c) { m_frameBuffer.makePointDirty(x0, y0); m_frameBuffer.makePointDirty(x1, y1); /** * It is a realization of Bresenham's line algorithm * without floats */ int dx = (x0 < x1) ? (x1 - x0) : (x0 - x1); int dy = (y0 < y1) ? (y1 - y0) : (y0 - y1); int sx = (x0 < x1) ? 1 : -1; int sy = (y0 < y1) ? 1 : -1; int err = ((dx > dy) ? dx : -dy) / 2; for(;;) { m_frameBuffer.putPixelNoDirty(x0, y0, c); if (x0 == x1 && y0 == y1) { break; } int oldErr = err; if (oldErr > -dx) { err -= dy; x0 += sx; } if (oldErr < dy) { err += dx; y0 += sy; } } } void Display::circle(int x0, int y0, int r, Color c) { int x = 0; int y = r; int delta = 1 - 2 * r; int error = 0; while (x <= y) { m_frameBuffer.putPixelNoDirty(x0 + x, y0 + y, c); m_frameBuffer.putPixelNoDirty(x0 + x, y0 - y, c); m_frameBuffer.putPixelNoDirty(x0 - x, y0 + y, c); m_frameBuffer.putPixelNoDirty(x0 - x, y0 - y, c); m_frameBuffer.putPixelNoDirty(x0 + y, y0 + x, c); m_frameBuffer.putPixelNoDirty(x0 + y, y0 - x, c); m_frameBuffer.putPixelNoDirty(x0 - y, y0 + x, c); m_frameBuffer.putPixelNoDirty(x0 - y, y0 - x, c); error = 2 * (delta + y) - 1; if ((delta < 0) && (error <= 0)) { delta += 2 * ++x + 1; continue; } error = 2 * (delta - x) - 1; if ((delta > 0) && (error > 0)) { delta += 1 - 2 * --y; continue; } x++; delta += 2 * (x - y); y--; } } int Display::left() { return 0; } int Display::right() { return m_frameBuffer.width-1; } int Display::top() { return 0; } int Display::bottom() { return m_frameBuffer.height-1; } int Display::centerX() { return m_frameBuffer.width / 2; } int Display::centerY() { return m_frameBuffer.height / 2; }
17.26601
75
0.580884
DAlexis
cf224860179885ffaa17a8ab974eef5da9fd7ae7
1,625
hpp
C++
third_party/boost/simd/detail/dispatch/property_of.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/detail/dispatch/property_of.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/detail/dispatch/property_of.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file Defines the property_of meta-function @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) **/ //================================================================================================== #ifndef BOOST_SIMD_DETAIL_DISPATCH_PROPERTY_OF_HPP_INCLUDED #define BOOST_SIMD_DETAIL_DISPATCH_PROPERTY_OF_HPP_INCLUDED #include <boost/simd/detail/dispatch/meta/scalar_of.hpp> #include <boost/simd/detail/dispatch/detail/property_of.hpp> #include <boost/simd/detail/nsm.hpp> namespace boost { namespace dispatch { /*! @ingroup group-hierarchy @brief Retrieve the fundamental hierarchy of a Type For any type @c T, returns the hierarchy describing the fundamental properties of any given types. This Fundamental Hierarchy is computed by computing the hierarchy of the innermost embedded scalar type of @c T. @tparam T Type to categorize @tparam Origin Type to store inside the generated hierarchy type @par Models: @metafunction **/ template<typename T, typename Origin = T> struct property_of #if !defined(DOXYGEN_ONLY) : ext::property_of<scalar_of_t<T>, typename std::remove_reference<Origin>::type> #endif {}; /*! @ingroup group-hierarchy Eager short-cut to boost::dispatch::property_of **/ template<typename T, typename Origin = T> using property_of_t = typename property_of<T,Origin>::type; } } #endif
30.092593
100
0.651077
SylvainCorlay
cf23785fa10c5955c4187c84d5583a29b1301d3d
577
cpp
C++
demos/glyph_paint/side_pane.cpp
RyanDraves/CPPurses
19cbdae2d18e702144659187ec989c486c714a0f
[ "MIT" ]
null
null
null
demos/glyph_paint/side_pane.cpp
RyanDraves/CPPurses
19cbdae2d18e702144659187ec989c486c714a0f
[ "MIT" ]
null
null
null
demos/glyph_paint/side_pane.cpp
RyanDraves/CPPurses
19cbdae2d18e702144659187ec989c486c714a0f
[ "MIT" ]
null
null
null
#include "side_pane.hpp" #include <cppurses/painter/color.hpp> #include <cppurses/painter/glyph.hpp> #include <cppurses/widget/widgets/text_display.hpp> using namespace cppurses; namespace demos { namespace glyph_paint { Side_pane::Side_pane() { this->width_policy.fixed(16); space1.wallpaper = L'─'; space2.wallpaper = L'─'; glyph_select.height_policy.preferred(6); color_select_stack.height_policy.fixed(3); show_glyph.height_policy.fixed(1); show_glyph.set_alignment(Alignment::Center); } } // namespace glyph_paint } // namespace demos
22.192308
51
0.734835
RyanDraves
cf240458e3e47526197c6cf80111a9ad1882045f
17,299
hpp
C++
bluetoe/attribute_handle.hpp
TorstenRobitzki/bluetoe
0f04ccefa4e9ba6a89bf4dfaa0dd62b8e3a46043
[ "MIT" ]
138
2015-04-11T12:07:19.000Z
2022-02-11T13:22:36.000Z
bluetoe/attribute_handle.hpp
TorstenRobitzki/bluetoe
0f04ccefa4e9ba6a89bf4dfaa0dd62b8e3a46043
[ "MIT" ]
60
2015-08-29T12:32:56.000Z
2022-03-25T07:20:21.000Z
bluetoe/attribute_handle.hpp
TorstenRobitzki/bluetoe
0f04ccefa4e9ba6a89bf4dfaa0dd62b8e3a46043
[ "MIT" ]
34
2015-07-08T22:06:25.000Z
2021-12-15T13:17:42.000Z
#ifndef BLUETOE_ATTRIBUTE_HANDLE_HPP #define BLUETOE_ATTRIBUTE_HANDLE_HPP #include <bluetoe/meta_types.hpp> #include <bluetoe/meta_tools.hpp> #include <cstdint> #include <cstdlib> #include <cassert> #include <algorithm> namespace bluetoe { namespace details { struct attribute_handle_meta_type {}; struct attribute_handles_meta_type {}; } /** * @brief define the first attribute handle used by a characteristic or service * * If this option is given to a service, the service attribute will be assigned * to the given handle value. For a characteristic, the Characteristic Declaration * attribute will be assigned to the given handle value. * * All following attrbutes are assigned handles with a larger value. * * @sa attribute_handles * @sa service * @sa characteristic */ template < std::uint16_t AttributeHandleValue > struct attribute_handle { /** @cond HIDDEN_SYMBOLS */ static constexpr std::uint16_t attribute_handle_value = AttributeHandleValue; struct meta_type : details::attribute_handle_meta_type, details::valid_service_option_meta_type, details::valid_characteristic_option_meta_type {}; /** @endcond */ }; /** * @brief define the attributes handles for the characteristic declaration, characteristic * value and optional, for a Client Characteristic Configuration descriptor. * * If the characteristic has no Client Characteristic Configuration descriptor, the CCCD * parameter has to be 0. Value has to be larger than Declaration and CCCD has to larger * than Value (or 0). * * @sa attribute_handle * @sa characteristic */ template < std::uint16_t Declaration, std::uint16_t Value, std::uint16_t CCCD = 0x0000 > struct attribute_handles { /** @cond HIDDEN_SYMBOLS */ static constexpr std::uint16_t declaration_handle = Declaration; static constexpr std::uint16_t value_handle = Value; static constexpr std::uint16_t cccd_handle = CCCD; static_assert( value_handle > declaration_handle, "value handle has to be larger than declaration handle" ); static_assert( cccd_handle > declaration_handle || cccd_handle == 0, "CCCD handle has to be larger than declaration handle" ); static_assert( cccd_handle > value_handle || cccd_handle == 0, "CCCD handle has to be larger than value handle" ); struct meta_type : details::attribute_handles_meta_type, details::valid_characteristic_option_meta_type {}; /** @endcond */ }; template < typename ... Options > class server; template < typename ... Options > class service; template < typename ... Options > class characteristic; namespace details { static constexpr std::uint16_t invalid_attribute_handle = 0; static constexpr std::size_t invalid_attribute_index = ~0; /* * select one of attribute_handle< H > or attribute_handle< H, B, C > */ template < std::uint16_t Default, class, class > struct select_attribute_handles { static constexpr std::uint16_t declaration_handle = Default; static constexpr std::uint16_t value_handle = Default + 1; static constexpr std::uint16_t cccd_handle = Default + 2; }; template < std::uint16_t Default, std::uint16_t AttributeHandleValue, typename T > struct select_attribute_handles< Default, attribute_handle< AttributeHandleValue >, T > { static constexpr std::uint16_t declaration_handle = AttributeHandleValue; static constexpr std::uint16_t value_handle = AttributeHandleValue + 1; static constexpr std::uint16_t cccd_handle = AttributeHandleValue + 2; }; template < std::uint16_t Default, typename T, std::uint16_t Declaration, std::uint16_t Value, std::uint16_t CCCD > struct select_attribute_handles< Default, T, attribute_handles< Declaration, Value, CCCD > > { static constexpr std::uint16_t declaration_handle = Declaration; static constexpr std::uint16_t value_handle = Value; static constexpr std::uint16_t cccd_handle = CCCD == 0 ? Value + 1 : CCCD; }; template < std::uint16_t Default, std::uint16_t AttributeHandleValue, std::uint16_t Declaration, std::uint16_t Value, std::uint16_t CCCD > struct select_attribute_handles< Default, attribute_handle< AttributeHandleValue >, attribute_handles< Declaration, Value, CCCD > > { static_assert( Declaration == Value, "either attribute_handle<> or attribute_handles<> can be used as characteristic<> option, not both." ); }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options > struct characteristic_index_mapping { using characteristic_t = ::bluetoe::characteristic< Options... >; using attribute_handles_t = select_attribute_handles< StartHandle, typename find_by_meta_type< attribute_handle_meta_type, Options... >::type, typename find_by_meta_type< attribute_handles_meta_type, Options... >::type >; static_assert( attribute_handles_t::declaration_handle >= StartHandle, "attribute_handle<> can only be used to create increasing attribute handles." ); static constexpr std::uint16_t end_handle = characteristic_t::number_of_attributes == 2 ? attribute_handles_t::value_handle + 1 : attribute_handles_t::cccd_handle + ( characteristic_t::number_of_attributes - 2 ); static constexpr std::uint16_t end_index = StartIndex + characteristic_t::number_of_attributes; static constexpr std::size_t declaration_position = 0; static constexpr std::size_t value_position = 1; static constexpr std::size_t cccd_position = 2; static std::uint16_t characteristic_attribute_handle_by_index( std::size_t index ) { const std::size_t relative_index = index - StartIndex; assert( relative_index < characteristic_t::number_of_attributes ); switch ( relative_index ) { case declaration_position: return attribute_handles_t::declaration_handle; break; case value_position: return attribute_handles_t::value_handle; break; case cccd_position: return attribute_handles_t::cccd_handle; break; } return relative_index - cccd_position + attribute_handles_t::cccd_handle; } static std::size_t characteristic_attribute_index_by_handle( std::uint16_t handle ) { if ( handle <= attribute_handles_t::declaration_handle ) return StartIndex + declaration_position; if ( handle <= attribute_handles_t::value_handle ) return StartIndex + value_position; if ( handle <= attribute_handles_t::cccd_handle ) return StartIndex + cccd_position; return StartIndex + cccd_position + handle - attribute_handles_t::cccd_handle; } }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename CharacteristicList > struct interate_characteristic_index_mappings; template < std::uint16_t StartHandle, std::uint16_t StartIndex > struct interate_characteristic_index_mappings< StartHandle, StartIndex, std::tuple<> > { static std::uint16_t attribute_handle_by_index( std::size_t ) { return invalid_attribute_handle; } static std::size_t attribute_index_by_handle( std::uint16_t ) { return invalid_attribute_index; } static constexpr std::uint16_t last_characteristic_end_handle = StartHandle; }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename Characteristics, typename ... Options > using next_characteristic_mapping = interate_characteristic_index_mappings< characteristic_index_mapping< StartHandle, StartIndex, Options... >::end_handle, characteristic_index_mapping< StartHandle, StartIndex, Options... >::end_index, Characteristics >; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ...Options, typename ... Chars > struct interate_characteristic_index_mappings< StartHandle, StartIndex, std::tuple< ::bluetoe::characteristic< Options... >, Chars... > > : characteristic_index_mapping< StartHandle, StartIndex, Options... > , next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... > { static constexpr std::uint16_t last_characteristic_end_handle = next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... >::last_characteristic_end_handle; using next = characteristic_index_mapping< StartHandle, StartIndex, Options... >; static std::uint16_t attribute_handle_by_index( std::size_t index ) { if ( index < next::end_index ) return next::characteristic_attribute_handle_by_index( index ); return next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... >::attribute_handle_by_index( index ); } static std::size_t attribute_index_by_handle( std::uint16_t handle ) { if ( handle < next::end_handle ) return next::characteristic_attribute_index_by_handle( handle ); return next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... >::attribute_index_by_handle( handle ); } }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options > struct service_start_handle { using start_handle_t = typename find_by_meta_type< attribute_handle_meta_type, Options..., attribute_handle< StartHandle > >::type; static constexpr std::uint16_t value = start_handle_t::attribute_handle_value; }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options > using next_char_mapping = interate_characteristic_index_mappings< service_start_handle< StartHandle, StartIndex, Options... >::value + 1, StartIndex + 1, typename find_all_by_meta_type< characteristic_meta_type, Options... >::type >; /* * Map index to handle within a single service */ template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options > struct service_index_mapping : next_char_mapping< StartHandle, StartIndex, Options... > { using service_t = ::bluetoe::service< Options... >; static constexpr std::uint16_t service_handle = service_start_handle< StartHandle, StartIndex, Options... >::value; static_assert( service_handle >= StartHandle, "attribute_handle<> can only be used to create increasing attribute handles." ); static constexpr std::uint16_t end_handle = next_char_mapping< StartHandle, StartIndex, Options... >::last_characteristic_end_handle; static constexpr std::uint16_t end_index = StartIndex + service_t::number_of_attributes; static std::uint16_t characteristic_handle_by_index( std::size_t index ) { if ( index == StartIndex ) return service_handle; return next_char_mapping< StartHandle, StartIndex, Options... >::attribute_handle_by_index( index ); } static std::size_t characteristic_first_index_by_handle( std::uint16_t handle ) { if ( handle <= service_handle ) return StartIndex; return next_char_mapping< StartHandle, StartIndex, Options... >::attribute_index_by_handle( handle ); } }; /* * Iterate over all services in a server */ template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename OptionTuple > struct interate_service_index_mappings; template < std::uint16_t StartHandle, std::uint16_t StartIndex > struct interate_service_index_mappings< StartHandle, StartIndex, std::tuple<> > { static std::uint16_t service_handle_by_index( std::size_t ) { return invalid_attribute_handle; } static std::size_t service_first_index_by_handle( std::uint16_t ) { return invalid_attribute_index; } }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename Services, typename ... Options > using next_service_mapping = interate_service_index_mappings< service_index_mapping< StartHandle, StartIndex, Options... >::end_handle, service_index_mapping< StartHandle, StartIndex, Options... >::end_index, Services >; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options, typename ... Services > struct interate_service_index_mappings< StartHandle, StartIndex, std::tuple< ::bluetoe::service< Options... >, Services... > > : service_index_mapping< StartHandle, StartIndex, Options... > , next_service_mapping< StartHandle, StartIndex, std::tuple< Services... >, Options... > { static std::uint16_t service_handle_by_index( std::size_t index ) { if ( index < service_index_mapping< StartHandle, StartIndex, Options... >::end_index ) return service_index_mapping< StartHandle, StartIndex, Options... >::characteristic_handle_by_index( index ); return next_service_mapping< StartHandle, StartIndex, std::tuple< Services... >, Options... >::service_handle_by_index( index ); } static std::size_t service_first_index_by_handle( std::uint16_t handle ) { if ( handle < service_index_mapping< StartHandle, StartIndex, Options... >::end_handle ) return service_index_mapping< StartHandle, StartIndex, Options... >::characteristic_first_index_by_handle( handle ); return next_service_mapping< StartHandle, StartIndex, std::tuple< Services... >, Options... >::service_first_index_by_handle( handle ); } }; /* * Interface, providing function to map from 0-based attribute index to ATT attribute handle and vice versa * * An attribute index is a 0-based into an array of all attributes contained in a server. Accessing the * attribute by table is very fast. If neither attribute_handle<> or attribute_handles<> is used, the mapping * is trivial and an index I is mapped to a handle I + 1. */ template < typename Server > struct handle_index_mapping; template < typename ... Options > struct handle_index_mapping< ::bluetoe::server< Options... > > : private interate_service_index_mappings< 1u, 0u, typename ::bluetoe::server< Options... >::services > { static constexpr std::size_t invalid_attribute_index = ::bluetoe::details::invalid_attribute_index; static constexpr std::uint16_t invalid_attribute_handle = ::bluetoe::details::invalid_attribute_handle; using iterator = interate_service_index_mappings< 1u, 0u, typename ::bluetoe::server< Options... >::services >; static std::uint16_t handle_by_index( std::size_t index ) { return iterator::service_handle_by_index( index ); } /** * @brief attribute index for a given handle * * Returns the index to the attribute with the lowest handle that is * equal or larger than the given handle. */ static std::size_t first_index_by_handle( std::uint16_t handle ) { return iterator::service_first_index_by_handle( handle ); } static std::size_t index_by_handle( std::uint16_t handle ) { std::size_t result = first_index_by_handle( handle ); if ( result != invalid_attribute_index && handle_by_index( result ) != handle ) result = invalid_attribute_index; return result; } }; } } #endif
45.643799
163
0.637493
TorstenRobitzki
cf293d85b523041d2dfca0b8c7c7fa252e3fac76
469
cpp
C++
no3.cpp
bigdaddyjeff/JeffreyCSC102
dbdcbc50634b23ce7973c71329f4fdd2d3964927
[ "MIT" ]
null
null
null
no3.cpp
bigdaddyjeff/JeffreyCSC102
dbdcbc50634b23ce7973c71329f4fdd2d3964927
[ "MIT" ]
null
null
null
no3.cpp
bigdaddyjeff/JeffreyCSC102
dbdcbc50634b23ce7973c71329f4fdd2d3964927
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int var = 789; int *ptr2; int **ptr1; ptr2 = &var; ptr1 = &ptr2; cout << "The value of var = "<< var << endl; cout << "Content value of single pointer ptr2 = " << *ptr2 << endl; cout << "address value of single pointer ptr2 = " << ptr2 << endl; cout << "Content value of double pointer ptr1 = " << **ptr1 << endl; cout << "address value of double pointer ptr1 = " << ptr1 << endl; }
27.588235
71
0.58209
bigdaddyjeff
cf2a28aa2539b4286c59835f605a6abdd6eda519
18,747
cpp
C++
IP/IMap.cpp
bharat-varma/Software-Engineering
36cdff296010e1076fb440707bfb2424110308ca
[ "Apache-2.0" ]
null
null
null
IP/IMap.cpp
bharat-varma/Software-Engineering
36cdff296010e1076fb440707bfb2424110308ca
[ "Apache-2.0" ]
3
2017-12-09T03:16:32.000Z
2017-12-15T04:22:08.000Z
IP/IMap.cpp
bharat-varma/Software-Engineering
36cdff296010e1076fb440707bfb2424110308ca
[ "Apache-2.0" ]
1
2017-09-19T00:28:47.000Z
2017-09-19T00:28:47.000Z
#include <map> #include <set> #include <vector> #include <algorithm> #include <cstdlib> #include <stack> #include <cmath> using namespace std; class IntMap { public: static const long serialVersionUID = 1L; static const int FREE_KEY = 0; static const int NO_VALUE = 0; /** Keys and values */ vector<int> m_data; /** Do we have 'free' key in the map? */ bool m_hasFreeKey; /** Value of 'free' key */ int m_freeValue; /** Fill factor, must be between (0 and 1) */ float m_fillFactor; /** We will resize a map once it reaches this size */ int m_threshold; /** Current map size */ int m_size; /** Mask to calculate the original position */ int m_mask; int m_mask2; IntMap(); IntMap(int size); IntMap(int size, float fillFactor); int get(int key); // for use as IntSet - Paul Tarau bool contains(int key); bool add(int key); bool del(int key); bool isEmpty(); static void intersect0(IntMap &m, vector<IntMap> & maps, vector<IntMap> & vmaps, stack<int> r); static stack<int> * intersect(vector<IntMap> & maps, vector<IntMap> & vmaps); // end changes int put(int key, int value); int remove(int key); int shiftKeys(int pos); int size(); string show(); void rehash(int newCapacity); /** Taken from FastUtil implementation */ /** Return the least power of two greater than or equal to the specified value. * * <p>Note that this function will return 1 when the argument is 0. * * @param x a long integer smaller than or equal to 2<sup>62</sup>. * @return the least power of two greater than or equal to the specified value. */ static long nextPowerOfTwo(long x); /** Returns the least power of two smaller than or equal to 2<sup>30</sup> * and larger than or equal to <code>Math.ceil( expected / f )</code>. * * @param expected the expected number of elements in a hash table. * @param f the load factor. * @return the minimum possible size for a backing array. * @throws IllegalArgumentException if the necessary size is larger than 2<sup>30</sup>. */ static int arraySize(int expected, float f); //taken from FastUtil static const int INT_PHI = 0x9E3779B9; int static phiMix(int x); }; IntMap::IntMap():IntMap(1<<2) { //this(1 << 2); } IntMap::IntMap(int size):IntMap(size, 0.75f) { //this(size, 0.75f); } IntMap::IntMap(int size, float fillFactor) { //if (fillFactor <= 0 || fillFactor >= 1) // throw new IllegalArgumentException("FillFactor must be in (0, 1)"); //if (size <= 0) // throw new IllegalArgumentException("Size must be positive!"); int capacity = arraySize(size, fillFactor); m_mask = capacity - 1; m_mask2 = capacity * 2 - 1; m_fillFactor = fillFactor; m_data.resize(capacity * 2); m_threshold = (int) (capacity * fillFactor); } int IntMap::get(int key) { int ptr = (phiMix(key) & m_mask) << 1; if (key == FREE_KEY) return m_hasFreeKey ? m_freeValue : NO_VALUE; int k = m_data[ptr]; if (k == FREE_KEY) return NO_VALUE; //end of chain already if (k == key) //we check FREE prior to this call return m_data[ptr + 1]; while (true) { ptr = ptr + 2 & m_mask2; //that's next index k = m_data[ptr]; if (k == FREE_KEY) return NO_VALUE; if (k == key) return m_data[ptr + 1]; } } // for use as IntSet - Paul Tarau bool IntMap::contains(int key) { return NO_VALUE != get(key); } bool IntMap::add(int key) { return NO_VALUE != put(key, 666); } bool IntMap::del(int key) { return NO_VALUE != remove(key); } bool IntMap::isEmpty() { return 0 == m_size; } void IntMap::intersect0(IntMap &m, vector<IntMap> & maps, vector<IntMap> & vmaps, stack<int> r) { vector<int> & data = m.m_data; for (int k = 0; k < data.size(); k += 2) { bool found = true; int key = data[k]; if (FREE_KEY == key) { continue; } for (int i = 1; i < maps.size(); i++) { IntMap map = maps[i]; int val = map.get(key); if (NO_VALUE == val) { IntMap vmap = vmaps[i]; int vval = vmap.get(key); if (NO_VALUE == vval) { found = false; break; } } } if (found) { r.push(key); } } } stack<int> * IntMap::intersect(vector<IntMap> & maps, vector<IntMap> & vmaps) { stack<int> *r = new stack<int>; intersect0(maps[0], maps, vmaps, *r); intersect0(vmaps[0], maps, vmaps, *r); return r; } // end changes int IntMap::put(int key, int value) { if (key == FREE_KEY) { int ret = m_freeValue; if (!m_hasFreeKey) { ++m_size; } m_hasFreeKey = true; m_freeValue = value; return ret; } int ptr = (phiMix(key) & m_mask) << 1; int k = m_data[ptr]; if (k == FREE_KEY) //end of chain already { m_data[ptr] = key; m_data[ptr + 1] = value; if (m_size >= m_threshold) { rehash(m_data.size() * 2); //size is set inside } else { ++m_size; } return NO_VALUE; } else if (k == key) //we check FREE prior to this call { int ret = m_data[ptr + 1]; m_data[ptr + 1] = value; return ret; } while (true) { ptr = ptr + 2 & m_mask2; //that's next index calculation k = m_data[ptr]; if (k == FREE_KEY) { m_data[ptr] = key; m_data[ptr + 1] = value; if (m_size >= m_threshold) { rehash(m_data.size() * 2); //size is set inside } else { ++m_size; } return NO_VALUE; } else if (k == key) { int ret = m_data[ptr + 1]; m_data[ptr + 1] = value; return ret; } } } int IntMap::remove(int key) { if (key == FREE_KEY) { if (!m_hasFreeKey) return NO_VALUE; m_hasFreeKey = false; --m_size; return m_freeValue; //value is not cleaned } int ptr = (phiMix(key) & m_mask) << 1; int k = m_data[ptr]; if (k == key) //we check FREE prior to this call { int res = m_data[ptr + 1]; shiftKeys(ptr); --m_size; return res; } else if (k == FREE_KEY) return NO_VALUE; //end of chain already while (true) { ptr = ptr + 2 & m_mask2; //that's next index calculation k = m_data[ptr]; if (k == key) { int res = m_data[ptr + 1]; shiftKeys(ptr); --m_size; return res; } else if (k == FREE_KEY) return NO_VALUE; } } int IntMap::shiftKeys(int pos) { // Shift entries with the same hash. int last, slot; int k; vector<int> & data = m_data; while (true) { pos = (last = pos) + 2 & m_mask2; while (true) { if ((k = data[pos]) == FREE_KEY) { data[last] = FREE_KEY; return last; } slot = (phiMix(k) & m_mask) << 1; //calculate the starting slot for the current key if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) { break; } pos = pos + 2 & m_mask2; //go to the next entry } data[last] = k; data[last + 1] = data[pos + 1]; } } int IntMap::size() { return m_size; } void IntMap::rehash(int newCapacity) { m_threshold = (int) (newCapacity / 2 * m_fillFactor); m_mask = newCapacity / 2 - 1; m_mask2 = newCapacity - 1; int oldCapacity = m_data.size(); vector<int> & oldData = m_data; m_data.resize(newCapacity); m_size = m_hasFreeKey ? 1 : 0; for (int i = 0; i < oldCapacity; i += 2) { int oldKey = oldData[i]; if (oldKey != FREE_KEY) { put(oldKey, oldData[i + 1]); } } } /** Taken from FastUtil implementation */ /** Return the least power of two greater than or equal to the specified value. * * <p>Note that this function will return 1 when the argument is 0. * * @param x a long integer smaller than or equal to 2<sup>62</sup>. * @return the least power of two greater than or equal to the specified value. */ long IntMap::nextPowerOfTwo(long x) { if (x == 0) return 1; x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return (x | x >> 32) + 1; } /** Returns the least power of two smaller than or equal to 2<sup>30</sup> * and larger than or equal to <code>Math.ceil( expected / f )</code>. * * @param expected the expected number of elements in a hash table. * @param f the load factor. * @return the minimum possible size for a backing array. * @throws IllegalArgumentException if the necessary size is larger than 2<sup>30</sup>. */ int IntMap::arraySize(int expected, float f) { long s = max(2l, nextPowerOfTwo((long) ceil(expected / f))); if (s > 1 << 30) return -1; //throw new IllegalArgumentException("Too large (" + expected + " expected elements with load factor " + f + ")"); return (int) s; } int IntMap::phiMix(int x) { int h = x * INT_PHI; return h ^ h >> 16; } string IntMap::show() { string b = "{"; int l = m_data.size(); bool first = true; for (int i = 0; i < l; i += 2) { int v = m_data[i]; if (v != FREE_KEY) { if (!first) { b += ","; } first = false; b+=v-1;; } } b+="}"; return b; } template <class K> class IMap { public: static const long serialVersionUID = 1L; map<K, IntMap*> mp; vector<K> mp_lst; IMap(); void clear(); bool put(K key, int val); IntMap get(K key); IntMap putget(K key); bool remove(K key, int val); bool remove(K key); int size(); //set<K> keySet(); static string show(vector<IMap<int> > imaps); static vector<IMap<int> > * create(int l); static bool put(vector<IMap<int> > imaps, int pos, int key, int val); static bool put(vector<IMap<int> > *imaps, int pos, int key, int val); static vector<int> * get(vector<IMap<int> > *iMaps, vector<IntMap> vmaps, vector<int> keys); string show(); }; template<class K> IMap<K>::IMap() { } template<class K> void IMap<K>::clear() { mp.clear(); } template<class K> bool IMap<K>::put(K key, int val) { if(mp.find(key) == mp.end()) { mp[key] = new IntMap(); } mp[key]->add(val); /* IntMap vals = mp.get(key); if (null == vals) { vals = new IntMap(); map.put(key, vals); } return vals.add(val); */ return mp[key]->add(val); } template<class K> IntMap IMap<K>::putget(K key) { //IntMap *s; if(mp.find(key) == mp.end()) //if(!mp.contains(key)) { //s = new IntMap(); return IntMap(); } else { //s = mp[key]; return *mp[key]; } /* IntMap s = map.get(key); if (null == s) { s = new IntMap(); } */ //return s; } template<class K> void remove_key(map<K,IntMap*> &mp, vector<K> mp_lst, K k) { auto element = mp.find(k); mp.erase(element); for(int i = 0; i < mp_lst.size(); i++) { if(mp_lst[i] == k) { mp_lst.erase(mp_lst.begin()+i); return; } } } template<class K> bool IMap<K>::remove(K key, int val) { IntMap vals = get(key); bool ok = vals.del(val); if (vals.isEmpty()) { remove_key(mp, mp_lst, key); // mp.remove(key); } return ok; } template<class K> bool IMap<K>::remove(K key) { bool ret = mp.find(key) != mp.end(); remove_key(mp, mp_lst, key); return ret; //return 0 != mp.remove(key); } template<class K> int IMap<K>::size() { int s = 0; for(const auto & k : mp_lst) { //IntMap *mp[k] s += get(k).size(); } /* Iterator<K> I = mp.keySet().iterator(); int s = 0; while (I.hasNext()) { K key = I.next(); IntMap vals = get(key); s += vals.size(); }*/ return s; } /* template<class K> set<K> IMap<K>::keySet() { set<K> s; for(const auto & k : mp_lst) { s.push(k); } return s; } */ /* Iterator<K> keyIterator() { return keySet().iterator(); }*/ /* @Override public String toString() { return map.toString(); }*/ // specialization for array of int maps template<class K> vector<IMap<int> > * IMap<K>::create(int l) { IMap<int> first = IMap<int>(); vector<IMap<int> >* imaps = new vector<IMap<int> >(l);// = (IMap<int>[]) java.lang.reflect.Array.newInstance(first.getClass(), l); // imaps = (IMap<int>[]) java.lang.reflect.Array.newInstance(first.getClass(), l); //new IMap[l]; (*imaps)[0] = first; for (int i = 1; i < l; i++) { (*imaps)[i] = IMap<int>(); } return imaps; } template<class K> bool IMap<K>::put(vector<IMap<int> > imaps, int pos, int key, int val) { return imaps[pos].put(key, val); } template<class K> bool IMap<K>::put(vector<IMap<int> >* imaps, int pos, int key, int val) { return ((*imaps)[pos]).put(key, val); } template<class K> vector<int> * IMap<K>::get(vector<IMap<int> > *iMaps, vector<IntMap> vmaps, vector<int> keys) { int l = iMaps->size(); vector<IntMap> ms; // = new ArrayList<IntMap>(); vector<IntMap> vms; // = new ArrayList<IntMap>(); for (int i = 0; i < l; i++) { int key = keys[i]; if (0 == key) { continue; } //Main.pp("i=" + i + " ,key=" + key); IntMap m = (*iMaps)[i].get(key); //Main.pp("m=" + m); ms.push_back(m); vms.push_back(vmaps[i]); } vector<IntMap> ims(ms.size());// = new IntMap[ms.size()]; vector<IntMap> vims(vms.size());// = new IntMap[vms.size()]; for (int i = 0; i < ims.size(); i++) { IntMap im = ms[i]; ims[i] = im; IntMap vim = vms[i]; vims[i] = vim; } //Main.pp("-------ims=" + Arrays.toString(ims)); //Main.pp("-------vims=" + Arrays.toString(vims)); stack<int> *cs = IntMap::intersect(ims, vims); // $$$ add vmaps here //vector<int> *is = new vector<int>(); int n = cs->size(); //int[] is = cs.toArray(); vector<int> *is = new vector<int>(n); for(int i=n-1;i>=0;i--) { (*is)[i] = cs->top(); cs->pop(); } delete cs; for (int i = 0; i < is->size(); i++) { (*is)[i] = (*is)[i] - 1; } sort(is->begin(), is->end()); //java.util.Arrays.sort(is); return is; } template<class K> string IMap<K>::show() { string s = ""; for(K k : mp_lst) { //char buffer[256]; //sprintf(buffer, "%d : ") //s += k + " : " + mp[k]; // s += ","; } return s; } template<class K> IntMap IMap<K>::get(K key) { if(mp.find(key) == mp.end()) { return IntMap(); } return *mp[key]; /* return mp[key]; IntMap s = map.get(key); if (null == s) { s = new IntMap(); } return s; */ } template<class K> string IMap<K>::show(vector<IMap<int> > imaps) { string s = ""; for(auto x : imaps) { s += x.show(); } return s; //Arrays.toString(imaps); } /* string show(vector<int> is) { return Arrays.toString(is); }*/ // end /* int main() { vector<IMap<int> > *imaps = IMap<int>::create(3); printf("1\n"); IMap<int>::put(*imaps, 0, 10, 100); IMap<int>::put(*imaps, 1, 20, 200); IMap<int>::put(*imaps, 2, 30, 777); IMap<int>::put(*imaps, 0, 10, 1000); IMap<int>::put(*imaps, 1, 20, 777); IMap<int>::put(*imaps, 2, 30, 3000); IMap<int>::put(*imaps, 0, 10, 777); IMap<int>::put(*imaps, 1, 20, 20000); IMap<int>::put(*imaps, 2, 30, 30000); IMap<int>::put(*imaps, 0, 10, 888); IMap<int>::put(*imaps, 1, 20, 888); IMap<int>::put(*imaps, 2, 30, 888); IMap<int>::put(*imaps, 0, 10, 0); IMap<int>::put(*imaps, 1, 20, 0); IMap<int>::put(*imaps, 2, 30, 0); return 0; } */ template class IMap<int>; #define IA 16807 #define IM 2147483647 #define IQ 127773 #define IR 2836 #define NTAB 32 #define EPS (1.2E-07) #define MAX(a,b) (a>b)?a:b #define MIN(a,b) (a<b)?a:b double ran1(int *idum) { int j,k; static int iv[NTAB],iy=0; void nrerror(); static double NDIV = 1.0/(1.0+(IM-1.0)/NTAB); static double RNMX = (1.0-EPS); static double AM = (1.0/IM); if ((*idum <= 0) || (iy == 0)) { *idum = MAX(-*idum,*idum); for(j=NTAB+7;j>=0;j--) { k = *idum/IQ; *idum = IA*(*idum-k*IQ)-IR*k; if(*idum < 0) *idum += IM; if(j < NTAB) iv[j] = *idum; } iy = iv[0]; } k = *idum/IQ; *idum = IA*(*idum-k*IQ)-IR*k; if(*idum<0) *idum += IM; j = iy*NDIV; iy = iv[j]; iv[j] = *idum; return MIN(AM*iy,RNMX); } int random_int(int *seed, int a, int b) { return (b-a)*ran1(seed)+a; } int main(int argc, char **argv) { int seed = -1; if(argc>1) { seed = atoi(argv[1]); if(seed > 0) seed = -seed; } vector<IMap<int> > *imaps = IMap<int>::create(3); int a = random_int(&seed, 1,5)*7; int b = random_int(&seed, 1,5)*5; int c = random_int(&seed, 1,5)*3; int va = random_int(&seed, 1,1000); int vb = random_int(&seed, 1,1000); int vc = random_int(&seed, 1,1000); IMap<int>::put(imaps, 0, a, va); IMap<int>::put(imaps, 1, b, vb); IMap<int>::put(imaps, 2, c, vc); printf("%d %d\n", a, (*imaps)[0].get(a).get(va)); printf("%d %d\n", b, (*imaps)[1].get(b).get(vb)); printf("%d %d\n", c, (*imaps)[2].get(c).get(vc)); va = random_int(&seed, 1,1000); vb = random_int(&seed, 1,1000); vc = random_int(&seed, 1,1000); IMap<int>::put(*imaps, 0, a, va); IMap<int>::put(*imaps, 1, b, vb); IMap<int>::put(*imaps, 2, c, vc); printf("%d %d\n", a, (*imaps)[0].get(a).get(va)); printf("%d %d\n", b, (*imaps)[1].get(b).get(vb)); printf("%d %d\n", c, (*imaps)[2].get(c).get(vc)); printf("%d %d\n", c, (*imaps)[2].get(c).get(vc+1)); va = random_int(&seed, 1,1000); vb = random_int(&seed, 1,1000); vc = random_int(&seed, 1,1000); IMap<int>::put(*imaps, 0, a, va); IMap<int>::put(*imaps, 1, b, vb); IMap<int>::put(*imaps, 2, c, vc); va = random_int(&seed, 1,1000); vb = random_int(&seed, 1,1000); vc = random_int(&seed, 1,1000); IMap<int>::put(*imaps, 0, a, va); IMap<int>::put(*imaps, 1, b, vb); IMap<int>::put(*imaps, 2, c, vc); IMap<int>::put(*imaps, 0, a, 0); IMap<int>::put(*imaps, 1, b, 0); IMap<int>::put(*imaps, 2, c, 0); printf("%d %d\n", a, (*imaps)[0].get(a).get(va)); printf("%d %d\n", b, (*imaps)[1].get(b).get(vb)); printf("%d %d\n", c, (*imaps)[2].get(c).get(vc)); printf("%d %d\n", c, (*imaps)[2].get(c).get(vc+1)); return 0; }
22.081272
134
0.53886
bharat-varma
cf2eed74523c5d43661f04cba155aa1d24e3eba1
45,612
cpp
C++
stlsoft/samples/whereis/whereis.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
86
2018-05-24T12:03:44.000Z
2022-03-13T03:01:25.000Z
stlsoft/samples/whereis/whereis.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
1
2019-05-30T01:38:40.000Z
2019-10-26T07:15:01.000Z
stlsoft/samples/whereis/whereis.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
14
2018-07-16T08:29:12.000Z
2021-08-23T06:21:30.000Z
/* ///////////////////////////////////////////////////////////////////////////// * File: whereis.cpp * * Purpose: Implementation file for the Synesis Software whereis utility * * Created: 19th January 1996 * Updated: 16th August 2004 * * Author: Matthew Wilson, Synesis Software Pty Ltd. * * The timestr() function and the verbose formatting in trace_file * used by kind permission of Walter Bright and Digital Mars. * * License: (Licensed under the Synesis Software Standard Public License) * * Copyright (C) 1999-2004, Synesis Software Pty Ltd. * Copyright (C) 1987-2004, Digital Mars. * * All rights reserved. * * www: http://www.synesis.com.au * http://www.synesis.com.au/software * * http://www.digitalmars.com/ * * email: software@synesis.com.au * * contact@digitalmars.com * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * (i) Redistributions of source code must retain the above * copyright notice and contact information, this list of * conditions and the following disclaimer. * * (ii) Redistributions in binary form must reproduce the above * copyright notice and contact information, this list of * conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * (iii) Any derived versions of this software (howsoever modified) * remain the sole property of Synesis Software. * * (iv) Any derived versions of this software (howsoever modified) * remain subject to all these conditions. * * (v) Neither the name of Synesis Software nor the names of any * subdivisions, employees or agents of Synesis Software, nor the * names of any other contributors to this software may be used to * endorse or promote products derived from this software without * specific prior written permission. * * This source code is provided by Synesis Software "as is" and any * warranties, whether expressed or implied, including, but not * limited to, the implied warranties of merchantability and * fitness for a particular purpose are disclaimed. In no event * shall the Synesis Software 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. * * ////////////////////////////////////////////////////////////////////////// */ /* ///////////////////////////////////////////////////////////////////////////// * Includes */ #include <stdio.h> #include <stlsoft.h> stlsoft_ns_using(ss_uint_t) stlsoft_ns_using(ss_sint64_t) stlsoft_ns_using(ss_bool_t) /* Regrettably, something in this program is too complex for early versions of * many compilers that the STLSoft libraries support. With some it is a compiler * issue, with others it either crashes or produces erroneous output. Thus, the * following restrictions are mandated: */ #if defined(__STLSOFT_COMPILER_IS_BORLAND) # if __BORLANDC__ < 0x0560 # error whereis.cpp cannot be successfully built by Borland C/C++ prior to version 5.6 # endif /* __BORLANDC__ < 0x0560 */ #elif defined(__STLSOFT_COMPILER_IS_DMC) # if __DMC__ < 0x0832 # error whereis.cpp cannot be successfully built by Digital Mars C/C++ prior to version 8.32 # endif /* __DMC__ < 0x0832 */ #elif defined(__STLSOFT_COMPILER_IS_GCC) # if __GNUC__ < 3 && \ __GNUC_MINOR__ < 95 # error whereis.cpp cannot be successfully built by GNU C/C++ prior to version 6.0 # endif /* __GNUC__ < 3 && __GNUC_MINOR__ < 95 */ #elif defined(__STLSOFT_COMPILER_IS_INTEL) # if __INTEL_COMPILER < 600 # error whereis.cpp cannot be successfully built by Intel C/C++ prior to version 6.0 # endif /* __INTEL_COMPILER < 600 */ #elif defined(__STLSOFT_COMPILER_IS_MWERKS) /* No problems with Metrowerks */ #elif defined(__STLSOFT_COMPILER_IS_MSVC) # if _MSC_VER < 1100 # error whereis.cpp cannot be successfully built by Microsoft Visual C/C++ prior to version 5.0 # endif /* _MSC_VER < 1100 */ #else # error Unrecognised compiler #endif /* compiler */ /* ///////////////////////////////////////////////////////////////////////////// * Warnings */ #if defined(__STLSOFT_COMPILER_IS_MSVC) # pragma warning(disable : 4702) #endif /* __STLSOFT_COMPILER_IS_INTEL */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef _SYNSOFT_INTERNAL_BUILD # include "MLCompId.h" #else /* ? _SYNSOFT_INTERNAL_BUILD */ # define _nameSynesisSoftware "Synesis Software (Pty) Ltd" # define _wwwSynesisSoftware_SystemTools "http://synesis.com.au/systools.html" # define _emailSynesisSoftware_SystemTools "software@synesis.com.au" #endif /* _SYNSOFT_INTERNAL_BUILD */ /* ////////////////////////////////////////////////////////////////////////// */ #include <stlsoft_auto_buffer.h> stlsoft_ns_using(auto_buffer) #include <stlsoft_limit_traits.h> #include <stlsoft_malloc_allocator.h> stlsoft_ns_using(malloc_allocator) #include <stlsoft_string_access.h> stlsoft_ns_using(c_str_ptr) #include <stlsoft_simple_algorithms.h> stlsoft_ns_using(remove_duplicates_from_unordered_sequence) #include <stlsoft_string_tokeniser.h> stlsoft_ns_using(string_tokeniser) #if defined(UNIX) || \ defined(unix) || \ defined(__unix) || \ defined(__unix__) || \ ( defined(__xlC__) && \ defined(_POWER) && \ defined(_AIX)) /* UNIX includes */ # define WHEREIS_PLATFORM_IS_UNIX # include <unixstl.h> namespace platform_stl = unixstl; # include <unixstl_file_path_buffer.h> typedef unixstl_ns_qual(file_path_buffer_a) file_path_buffer; # include <unixstl_findfile_sequence.h> unixstl_ns_using(findfile_sequence) # include <unixstl_functionals.h> unixstl_ns_using(compare_path) # include <unixstl_environment_variable.h> unixstl_ns_using(basic_environment_variable) # include <unixstl_current_directory.h> unixstl_ns_using(basic_current_directory) # include <unixstl_filesystem_traits.h> unixstl_ns_using(filesystem_traits) # include <time.h> # include <sys/types.h> # include <sys/stat.h> #elif defined(WIN32) || \ defined(_WIN32) /* Win32 includes */ # define WHEREIS_PLATFORM_IS_WIN32 # include <winstl.h> namespace platform_stl = winstl; # include <winstl_file_path_buffer.h> typedef winstl_ns_qual(file_path_buffer_a) file_path_buffer; # include <winstl_findfile_sequence.h> typedef winstl_ns_qual(findfile_sequence_a) findfile_sequence; # include <winstl_functionals.h> winstl_ns_using(compare_path) # include <winstl_environment_variable.h> winstl_ns_using(basic_environment_variable) # include <winstl_current_directory.h> winstl_ns_using(basic_current_directory) # include <winstl_filesystem_traits.h> winstl_ns_using(filesystem_traits) #else # error Operating system not recognised #endif /* operating system */ #include <algorithm> stlsoft_ns_using_std(copy) stlsoft_ns_using_std(for_each) stlsoft_ns_using_std(remove_if) #include <functional> stlsoft_ns_using_std(unary_function) #include <iterator> stlsoft_ns_using_std(back_inserter) #include <string> stlsoft_ns_using_std(string) #include <vector> stlsoft_ns_using_std(vector) #include <list> stlsoft_ns_using_std(list) #include <map> stlsoft_ns_using_std(map) #ifdef _SYNSOFT_INTERNAL_BUILD # include <MRPathFn.h> # ifdef WHEREIS_PLATFORM_IS_WIN32 # define WHEREIS_USING_WIN32_VERSION_INFO # include <MWVerInf.h> # endif /* platform */ #endif /* _SYNSOFT_INTERNAL_BUILD */ /* ///////////////////////////////////////////////////////////////////////////// * Warnings */ #if defined(__STLSOFT_COMPILER_IS_INTEL) # pragma warning(disable : 383) # pragma warning(disable : 444) # pragma warning(disable : 1419) #endif /* __STLSOFT_COMPILER_IS_INTEL */ /* ///////////////////////////////////////////////////////////////////////////// * Tracing */ //#define WHEREIS_TRACE #if !defined(WHEREIS_TRACE) && \ defined(_DEBUG) # define WHEREIS_TRACE #endif /* !WHEREIS_TRACE && _DEBUG */ /* ///////////////////////////////////////////////////////////////////////////// * Version information * * Normally, Synesis Software components & tools are "versioned" by making use * of tool-generated header files, one of which - MBldHdr.h - defines symbolic * constants representing major, minor, revision and build numbers. * * * Since this file is to be available in a more public forum, including on the * Digital Mars site, these constants are merely defined here, rather than * encumber any developers who may wish to compile it with a lot of * Synesis-specific gunk. */ #ifdef _SYNSOFT_INTERNAL_BUILD # include "MBldHdr.h" # include "showver.h" extern "C" const int _mccVerHi = __SYV_MAJOR; extern "C" const int _mccVerLo = __SYV_MINOR; extern "C" const int _mccVerRev = __SYV_REVISION; extern "C" const int _mccBldNum = __SYV_BUILDNUMBER; #else /* ? _SYNSOFT_INTERNAL_BUILD */ extern "C" const int _mccVerHi = 1; extern "C" const int _mccVerLo = 12; extern "C" const int _mccVerRev = 1; extern "C" const int _mccBldNum = 52; #endif /* _SYNSOFT_INTERNAL_BUILD */ # define COMPANY_NAME "Synesis Software" # define TOOL_NAME "File Searching" # define EXE_NAME "whereis" /* ///////////////////////////////////////////////////////////////////////////// * Typedefs */ typedef string_tokeniser<string, char> tokeniser_string_t; typedef vector<string> searchpath_sorted_t; //typedef list<string> searchpath_sorted_t; typedef map<string, unsigned> extension_map_t; #if defined(WHEREIS_PLATFORM_IS_WIN32) typedef FILETIME whereis_time_t; #elif defined(WHEREIS_PLATFORM_IS_UNIX) typedef time_t whereis_time_t; #else # error Unknown platform #endif /* platform */ /* ///////////////////////////////////////////////////////////////////////////// * Enumerations */ namespace Trim { enum Trim { full , fileOnly , fromSearchRoot , fromCurrentDirectory }; } // namespace Trim namespace Flags { enum { verbose = 0x00000001 , showVersionInfo = 0x00000002 , showFiles = 0x00000004 , showDirectories = 0x00000008 , markDirectories = 0x00000010 }; } // namespace Flags /* ///////////////////////////////////////////////////////////////////////////// * Macros and definitions * * Visual C++, sigh. uses %I64d", rather than "%lld", so that is abstracted here */ #if defined(__STLSOFT_COMPILER_IS_BORLAND) || \ /* defined(__STLSOFT_COMPILER_IS_GCC) || */ \ defined(__STLSOFT_COMPILER_IS_INTEL) || \ defined(__STLSOFT_COMPILER_IS_MSVC) # define FMT_SINT64_WIDTH_(x) "%" #x "I64d" #else # define FMT_SINT64_WIDTH_(x) "%" #x "lld" #endif /* compiler */ /* ///////////////////////////////////////////////////////////////////////////// * Constants */ #ifdef __STLSOFT_COMPILER_IS_INTEL # pragma warning(disable : 1418) #endif /* __STLSOFT_COMPILER_IS_INTEL */ /* Multi-part path/pattern delimiter */ #if defined(__STLSOFT_COMPILER_IS_MSVC) && \ _MSC_VER < 1300 char const PATH_SEPARATOR = ';'; #else /* ? compiler */ char const PATH_SEPARATOR = filesystem_traits<char>::path_separator(); #endif /* compiler */ /* Path component delimiter */ #if defined(__STLSOFT_COMPILER_IS_MSVC) && \ _MSC_VER < 1300 char const PATH_NAME_SEPARATOR = '\\'; #else /* ? compiler */ char const PATH_NAME_SEPARATOR = filesystem_traits<char>::path_name_separator(); #endif /* compiler */ /* Subdirectory wildcard pattern */ #if defined(__STLSOFT_COMPILER_IS_MSVC) && \ _MSC_VER < 1300 char const *PATTERN_ALL = "*.*"; #else /* ? compiler */ char const *PATTERN_ALL = filesystem_traits<char>::pattern_all(); #endif /* compiler */ /* Illegal pattern characters string */ #if defined(_MSC_VER) /* For testing */ || \ defined(WHEREIS_PLATFORM_IS_WIN32) char const *BAD_PATTERN_CHARS = ":\\"; #elif defined(WHEREIS_PLATFORM_IS_UNIX) char const *BAD_PATTERN_CHARS = "/"; #else # error Unknown platform #endif /* platform */ #ifdef __STLSOFT_COMPILER_IS_INTEL # pragma warning(default : 1418) #endif /* __STLSOFT_COMPILER_IS_INTEL */ /* ///////////////////////////////////////////////////////////////////////////// * Function declarations * * (Primarily to keep Metrowerks happy, but that's a good thing to do!) */ static char *timestr(char *buffer, size_t cchBuffer, whereis_time_t const *ft); // Make Metrowerks happy /* ///////////////////////////////////////////////////////////////////////////// * Global variables */ static file_path_buffer s_root; static extension_map_t s_extMap; /* ///////////////////////////////////////////////////////////////////////////// * Helper Functions */ char *timestr(char *buffer, size_t cchBuffer, whereis_time_t const *t) { #if defined(WHEREIS_PLATFORM_IS_WIN32) FILETIME ftLocal; SYSTEMTIME st; char dateString[41]; char timeString[41]; ::FileTimeToLocalFileTime(t, &ftLocal); ::FileTimeToSystemTime(&ftLocal, &st); ::GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, NULL, dateString, stlsoft_num_elements(dateString)); ::GetTimeFormat(LOCALE_USER_DEFAULT, 0, &st, NULL, timeString, stlsoft_num_elements(timeString)); #if 0 // Digital Mars format (US based) sprintf(buffer, "%02d/%02d/%02d %2d:%02d", st.wMonth, st.wDay, st.wYear % 100, st.wHour, st.wMinute); #else /* ? 0 */ // User-locale format sprintf(buffer, "%-10s %-s", dateString, timeString); #endif /* 0 */ STLSOFT_SUPPRESS_UNUSED(cchBuffer); #elif defined(WHEREIS_PLATFORM_IS_UNIX) struct tm tm_ = *localtime(t); strftime(buffer, cchBuffer, "%c", &tm_); #else # error Unknown platform #endif /* platform */ return buffer; } static char *copy_entry_filename(char *dest, findfile_sequence::value_type const &entry) { #if defined(WHEREIS_PLATFORM_IS_WIN32) return strcpy(dest, entry.get_filename()); #elif defined(WHEREIS_PLATFORM_IS_UNIX) // Use the get_full_path_name() file_path_buffer buffer; char *pFile = NULL; size_t cch = platform_stl::filesystem_traits<char>::get_full_path_name(entry, buffer.size(), &buffer[0], &pFile); STLSOFT_SUPPRESS_UNUSED(cch); return strcpy(dest, pFile); #else # error Unknown platform #endif /* platform */ } /* ///////////////////////////////////////////////////////////////////////////// * Functionals */ // struct trace_file // // This functional traces individual file records to stdout. struct trace_file : public unary_function<findfile_sequence::value_type const &, void> { typedef trace_file class_type; public: trace_file(char const *searchRoot, Trim::Trim trim, ss_uint_t flags) : m_flags(flags) , m_searchRoot(searchRoot) , m_trim(trim) {} void operator ()(findfile_sequence::value_type const &entry) const { file_path_buffer path; switch(m_trim) { default: stlsoft_assert(0); case Trim::full: strcpy(&path[0], c_str_ptr(entry)); break; case Trim::fileOnly: copy_entry_filename(&path[0], entry); break; #if defined(_SYNSOFT_INTERNAL_BUILD) && \ defined(WHEREIS_PLATFORM_IS_WIN32) case Trim::fromSearchRoot: SynesisCrt::deriverelativepath(stlsoft_ns_qual(c_str_ptr)(entry), m_searchRoot, &path[0]); break; case Trim::fromCurrentDirectory: SynesisCrt::deriverelativepath(stlsoft_ns_qual(c_str_ptr)(entry), stlsoft_ns_qual(c_str_ptr)(s_root), &path[0]); break; #endif /* _SYNSOFT_INTERNAL_BUILD */ } if(m_flags & Flags::verbose) { ss_sint64_t size; char timebuf[50]; char atts[8 + 1]; #if defined(WHEREIS_PLATFORM_IS_WIN32) findfile_sequence::find_data_type const &findData = entry.get_find_data(); DWORD const &att = findData.dwFileAttributes; int i; for (i = 0; i < 8; ++i) { static char tab[] = "RHSVDAXX"; if (att & (1 << i)) atts[i] = tab[i]; else atts[i] = '-'; } atts[8] = 0; timestr(timebuf, stlsoft_num_elements(timebuf), &findData.ftLastWriteTime); size = findData.nFileSizeHigh * __STLSOFT_GEN_SINT64_SUFFIX(0x100000000) + findData.nFileSizeLow; #elif defined(WHEREIS_PLATFORM_IS_UNIX) # ifdef _MSC_VER // For testing struct _stat st; _stat(entry, &st); # else /* ? _MSC_VER */ struct stat st; stat(entry, &st); # endif /* _MSC_VER */ atts[0] = ((st.st_mode & S_IWRITE) == 0) ? 'R' : '-'; // R atts[1] = '-'; // H atts[2] = '-'; // S atts[3] = '-'; // V atts[4] = ((st.st_mode & S_IFMT) == S_IFDIR) ? 'D' : '-'; // D atts[5] = '-'; // A atts[6] = '-'; // X atts[7] = '-'; // X atts[8] = 0; size = st.st_size; timestr(timebuf, stlsoft_num_elements(timebuf), &st.st_mtime); #else /* ? platform */ # error Unknown platform #endif /* platform */ #ifdef _SYNSOFT_INTERNAL_BUILD # if defined(WHEREIS_PLATFORM_IS_WIN32) if(m_flags & Flags::showVersionInfo) { SynesisWin::LPWinVerInfoA verInfo = SynesisWin::WinVer_GetVersionInformationA(c_str_ptr(entry)); char version[101]; if(NULL != verInfo) { sprintf(version, "%d.%d.%02d.%04d", verInfo->fileVerMajor, verInfo->fileVerMinor, verInfo->fileVerRevision, verInfo->fileVerBuild); SynesisWin::WinVer_CloseVersionInformationA(verInfo); } else { version[0] = '\0'; } printf("%-23s %16s %s " FMT_SINT64_WIDTH_(9) "\t%s\n", timebuf, version, atts, size, path.c_str()); } else # endif /* WHEREIS_PLATFORM_IS_WIN32 */ #endif /* _SYNSOFT_INTERNAL_BUILD */ { printf("%-23s %s " FMT_SINT64_WIDTH_(9) "\t%s\n", timebuf, atts, size, path.c_str()); } } else { fprintf(stdout, "%s\n", path.c_str()); } } // Members private: char const *const m_searchRoot; Trim::Trim const m_trim; ss_uint_t const m_flags; // Not to be implemented private: class_type &operator =(class_type const &); }; // struct process_searchspec // // This functional processes a search-spec within a given directory, passing any // file to be processed by trace_file. struct process_searchspec : public unary_function<tokeniser_string_t::value_type const &, void> { typedef process_searchspec class_type; public: process_searchspec(string const &path, char const *searchRoot, Trim::Trim trim, ss_uint_t flags) : m_path(path) , m_searchRoot(searchRoot) , m_trim(trim) , m_flags(flags) {} void operator ()(tokeniser_string_t::value_type const &value) const { #ifdef WHEREIS_PLATFORM_IS_UNIX try { #endif /* WHEREIS_PLATFORM_IS_UNIX */ int fs_flags = 0; if(m_flags & Flags::showDirectories) { fs_flags |= findfile_sequence::directories; } if(m_flags & Flags::showFiles) { fs_flags |= findfile_sequence::files; } findfile_sequence files(c_str_ptr(m_path), c_str_ptr(value), fs_flags); for_each(files.begin(), files.end(), trace_file(m_searchRoot, m_trim, m_flags)); #ifdef WHEREIS_PLATFORM_IS_UNIX } catch(unixstl::glob_sequence_exception &) {} #endif /* WHEREIS_PLATFORM_IS_UNIX */ } // Members private: string const m_path; char const *const m_searchRoot; Trim::Trim const m_trim; ss_uint_t const m_flags; // Not to be implemented private: class_type &operator =(class_type const &); }; // struct process_path // // This functional creates a search sequence for each path, and then processes // each one with the trace_file functional. struct process_path : public unary_function<string const &, void> { typedef process_path class_type; public: process_path(string const &searchSpec, Trim::Trim trim, ss_uint_t flags) : m_searchSpec(searchSpec) , m_searchRoot(NULL) , m_trim(trim) , m_flags(flags) {} process_path(string const &searchSpec, char const *searchRoot, Trim::Trim trim, ss_uint_t flags) : m_searchSpec(searchSpec) , m_searchRoot(searchRoot) , m_trim(trim) , m_flags(flags) {} void operator ()(string const &dir) const { typedef filesystem_traits<char> traits_type; file_path_buffer searchRoot_; char const *searchRoot = (traits_type::get_full_path_name((NULL != m_searchRoot) ? m_searchRoot : stlsoft_ns_qual(c_str_ptr)(dir), searchRoot_.size(), &searchRoot_[0]), stlsoft_ns_qual(c_str_ptr)(searchRoot_)); // Now split with the string_tokeniser into all the constituent paths tokeniser_string_t specs(&m_searchSpec[0], PATH_SEPARATOR); for_each(specs.begin(), specs.end(), process_searchspec(dir, stlsoft_ns_qual(c_str_ptr)(searchRoot), m_trim, m_flags)); } // Members private: string const m_searchSpec; char const *const m_searchRoot; Trim::Trim const m_trim; ss_uint_t const m_flags; // Not to be implemented private: class_type &operator =(class_type const &); }; // struct trace_dir // // This functional provides processing of a directory, used by the recursive // option. It process the current directory (via process_path), and then all // subdirectories (via trace_dir) "calling" itself recursively. struct trace_dir : public unary_function<string const &, void> { typedef trace_dir class_type; public: trace_dir(string const &searchSpec, Trim::Trim trim, ss_uint_t flags) : m_searchSpec(searchSpec) , m_searchRoot(NULL) , m_trim(trim) , m_flags(flags) {} trace_dir(string const &searchSpec, char const *searchRoot, Trim::Trim trim, ss_uint_t flags) : m_searchSpec(searchSpec) , m_searchRoot(searchRoot) , m_trim(trim) , m_flags(flags) {} void operator ()(char const *dir) const { typedef filesystem_traits<char> traits_type; file_path_buffer searchRoot_; char const *searchRoot = (traits_type::get_full_path_name((NULL != m_searchRoot) ? m_searchRoot : dir, searchRoot_.size(), &searchRoot_[0]), stlsoft_ns_qual(c_str_ptr)(searchRoot_)); process_path f(m_searchSpec, searchRoot, m_trim, m_flags); f(dir); #ifdef WHEREIS_PLATFORM_IS_UNIX try { #endif /* WHEREIS_PLATFORM_IS_UNIX */ findfile_sequence directories(stlsoft_ns_qual(c_str_ptr)(dir), PATTERN_ALL, findfile_sequence::directories); for_each(directories.begin(), directories.end(), trace_dir(m_searchSpec, searchRoot, m_trim, m_flags)); #ifdef WHEREIS_PLATFORM_IS_UNIX } catch(unixstl::glob_sequence_exception &) {} #endif /* WHEREIS_PLATFORM_IS_UNIX */ } template <ss_typename_param_k S> void operator ()(S const &dir) const { operator ()(stlsoft_ns_qual(c_str_ptr)(dir)); } private: string const m_searchSpec; char const *const m_searchRoot; Trim::Trim const m_trim; ss_uint_t const m_flags; // Not to be implemented private: class_type &operator =(class_type const &); }; /* ///////////////////////////////////////////////////////////////////////////// * Function declarations */ static void usage(int bExit, char const *reason, int invalidArg, int argc, char *argv[]); static char const *convert_path_separators(char const *path, char *buffer); #ifdef WHEREIS_PLATFORM_IS_WIN32 static char const *get_driveroots(char *buffer); #endif /* WHEREIS_PLATFORM_IS_WIN32 */ /* ///////////////////////////////////////////////////////////////////////////// * Helper functionals */ struct is_empty_path { template <ss_typename_param_k S> ss_bool_t operator ()(S const &s) const { return c_str_ptr(s)[0] == '\0'; } }; struct print_path { template <ss_typename_param_k S> void operator ()(S const &s) const { fprintf(stdout, " %s\n", c_str_ptr(s)); } }; #ifdef WHEREIS_TRACE struct trace_path { template <ss_typename_param_k S> void operator ()(S const &s) const { size_t len = c_str_len(s); auto_buffer<char, malloc_allocator<char>, 256> buffer(3 + len + 1); sprintf(buffer, " %s\n", c_str_ptr(s)); OutputDebugStringA(buffer); } }; #endif /* WHEREIS_TRACE */ /* ///////////////////////////////////////////////////////////////////////////// * main */ #ifdef WIN32 extern "C" __declspec(dllimport) void __stdcall Sleep(unsigned long ); #endif /* WIN32 */ static int main_(int argc, char **argv) { ss_bool_t bDisplayTotal = false; ss_bool_t bFromEnvironment = false; ss_bool_t bSearchGivenRoots = false; ss_bool_t bSearchCwd = false; ss_bool_t bDumpSearchRoots = false; ss_bool_t bVerbose = true; ss_bool_t bRecursive = false; ss_bool_t bSuppressRecursive = false; ss_bool_t bShowVersionInfo = false; ss_bool_t bSummariseExtensions = false; ss_bool_t bShowDirectories = false; ss_bool_t bShowFiles = false; ss_bool_t bMarkDirs = false; Trim::Trim trim = Trim::full; char const *rootSpec = NULL; char const *searchSpec = NULL; char const *envSpec = NULL; #ifdef WHEREIS_PLATFORM_IS_WIN32 char driveroots[105] = ""; #endif /* WHEREIS_PLATFORM_IS_WIN32 */ int totalFound = 0; for(int i = 1; i < argc; ++i) { char const *arg = argv[i]; if(arg[0] == '-') { if(arg[1] == '-') { if( 0 == strcmp("--directories", arg) || 0 == strcmp("--dirs", arg)) { bShowDirectories = true; } else if(0 == strcmp("--files", arg)) { bShowFiles = true; } #ifdef _SYNSOFT_INTERNAL_BUILD else if(0 == strcmp("--version", arg)) { return show_version(); } #endif /* _SYNSOFT_INTERNAL_BUILD */ else { usage(1, "Invalid argument(s) specified", i, argc, argv); } } else { switch(arg[1]) { case '?': usage(1, NULL, i, argc, argv); break; case 'd': bDumpSearchRoots = true; break; case 'e': bFromEnvironment = true; envSpec = arg + 2; break; case 'f': trim = Trim::fileOnly; break; #ifdef WHEREIS_PLATFORM_IS_WIN32 case 'h': bSearchGivenRoots = true; rootSpec = get_driveroots(driveroots); break; #endif /* WHEREIS_PLATFORM_IS_WIN32 */ case 'i': bFromEnvironment = true; envSpec = "INCLUDE"; break; case 'l': bFromEnvironment = true; envSpec = "LIB"; break; case 'm': bMarkDirs = true; break; // case 'n': // bDisplayTotal = true; // break; case 'r': bSearchGivenRoots = true; rootSpec = arg + 2; break; case 'p': bFromEnvironment = true; envSpec = "PATH"; break; case 's': bVerbose = false; break; case 't': trim = Trim::fromCurrentDirectory; break; case 'u': bRecursive = true; break; case 'v': bVerbose = true; break; case 'w': bSearchCwd = true; break; case 'x': bSummariseExtensions = false; break; case 'R': bSuppressRecursive = true; break; case 'F': trim = Trim::full; break; case 'T': trim = Trim::fromSearchRoot; break; #ifdef _SYNSOFT_INTERNAL_BUILD case 'V': bShowVersionInfo = true; break; #endif /* _SYNSOFT_INTERNAL_BUILD */ default: // fprintf(stderr, "Unrecognised argument \"%s\"\n", arg); usage(1, "Invalid argument(s) specified", i, argc, argv); break; } } } else { if(rootSpec == NULL) { rootSpec = arg; } else if(searchSpec == NULL) { searchSpec = arg; } else { usage(1, "<root-paths> and <search-spec> already specified", i, argc, argv); } } } STLSOFT_SUPPRESS_UNUSED(bSummariseExtensions); if( !bShowDirectories && !bShowFiles) { bShowFiles = true; } if( NULL == searchSpec && NULL == rootSpec) { usage(1, "No search parameters specified", 0, argc, argv); } if( ((bSearchCwd != false) + (bFromEnvironment != false) + (bSearchGivenRoots != false)) > 1) { usage(1, "Cannot specify two or more of -w, -r, -e, -l, -i, -p", 0, argc, argv); } // Validate the args. This entails just moving the root-dir into the // search-spec if no root-dir was specified. This simplifies the // previous command-line processing. if(NULL == searchSpec) { if( NULL != rootSpec && !bSearchGivenRoots) { searchSpec = rootSpec; rootSpec = NULL; } else { usage(1, "Unexpected condition. Please report to Synesis Software", 0, argc, argv); } } file_path_buffer rootDir_; if(bFromEnvironment) { rootSpec = NULL; } else { // If no directory is specified, the current directory is assumed if( rootSpec == NULL || *rootSpec == '\0') { strcpy(&rootDir_[0], basic_current_directory<char>()); rootSpec = stlsoft_ns_qual(c_str_ptr)(rootDir_); } } if( bFromEnvironment && ( envSpec == NULL || *envSpec == '\0')) { usage(1, "Cannot search from environment when no environment variable specified", 0, argc, argv); } #if defined(__STLSOFT_COMPILER_IS_MSVC) && \ _MSC_VER < 1200 GetCurrentDirectory(s_root.size(), s_root); #else /* ? compiler */ platform_stl::filesystem_traits<char>::get_current_directory(s_root.size(), &s_root[0]); #endif /* compiler */ // Handle forward slashes string _rootDir_(rootSpec != NULL ? rootSpec : ""); string _searchSpec_(searchSpec != NULL ? searchSpec : ""); rootSpec = convert_path_separators(rootSpec, const_cast<char*>(_rootDir_.data())); searchSpec = convert_path_separators(searchSpec, const_cast<char*>(_searchSpec_.data())); // Handle illegal characters if(strpbrk(searchSpec, BAD_PATTERN_CHARS) != 0) { char sz[101]; sprintf(sz, "<search-spec> contains illegal characters: \"%s\"\n", searchSpec); usage(1, sz, 0, argc, argv); } searchpath_sorted_t sorted; ss_uint_t flags = 0; if(bVerbose) { flags |= Flags::verbose; } if(bShowVersionInfo) { flags |= Flags::showVersionInfo; } if(bShowDirectories) { flags |= Flags::showDirectories; } if(bShowFiles) { flags |= Flags::showFiles; } if(bMarkDirs) { flags |= Flags::markDirectories; } #ifdef WHEREIS_USING_WIN32_VERSION_INFO SynesisWin::WinVer_Init(); #endif /* WHEREIS_USING_WIN32_VERSION_INFO */ // Commence the search if(bFromEnvironment) { basic_environment_variable<char> ENVVAR(envSpec); tokeniser_string_t paths(ENVVAR, PATH_SEPARATOR); #ifdef __STLSOFT_COMPILER_IS_DMC { tokeniser_string_t::const_iterator begin = paths.begin(); tokeniser_string_t::const_iterator end = paths.end(); for(; begin != end; ++begin) { sorted.push_back(*begin); } } #else copy(paths.begin(), paths.end(), back_inserter(sorted)); #endif /* __STLSOFT_COMPILER_IS_DMC */ // The roots may contain duplicate elements, so remove_duplicates_from_unordered_sequence(sorted, compare_path<char>()); // They may also contain empty paths, so sorted.erase(remove_if(sorted.begin(), sorted.end(), is_empty_path()), sorted.end()); if(bDumpSearchRoots) { fprintf(stdout, "Search roots:\n"); for_each(sorted.begin(), sorted.end(), print_path()); } // Now execute over the duplicate-free (but still in the correct search order) // sequence, applying the process_path functional to each one. if(bRecursive) { for_each(sorted.begin(), sorted.end(), trace_dir(searchSpec, trim, flags)); } else { for_each(sorted.begin(), sorted.end(), process_path(searchSpec, trim, flags)); } } else { tokeniser_string_t roots(rootSpec, PATH_SEPARATOR); #ifdef __STLSOFT_COMPILER_IS_DMC { tokeniser_string_t::const_iterator begin = roots.begin(); tokeniser_string_t::const_iterator end = roots.end(); for(; begin != end; ++begin) { sorted.push_back(*begin); } } #else copy(roots.begin(), roots.end(), back_inserter(sorted)); #endif /* __STLSOFT_COMPILER_IS_DMC */ // The roots may contain duplicate elements, so remove_duplicates_from_unordered_sequence(sorted, compare_path<char>()); // They may also contain empty paths, so sorted.erase(remove_if(sorted.begin(), sorted.end(), is_empty_path()), sorted.end()); if(bDumpSearchRoots) { fprintf(stdout, "Search roots:\n"); for_each(sorted.begin(), sorted.end(), print_path()); } // Now execute over the duplicate-free (but still in the correct search order) // sequence, applying the trace_dir functional to each one. if(!bSuppressRecursive) { for_each(sorted.begin(), sorted.end(), trace_dir(searchSpec, trim, flags)); } else { for_each(sorted.begin(), sorted.end(), process_path(searchSpec, trim, flags)); } } if(bDisplayTotal) { printf(" %5d file(s) found\n", totalFound); } #ifdef WHEREIS_USING_WIN32_VERSION_INFO SynesisWin::WinVer_Uninit(); #endif /* WHEREIS_USING_WIN32_VERSION_INFO */ return 0; } int main(int argc, char *argv[]) { int res; #if 0 ::Sleep(100000); #endif /* 0 */ try { res = main_(argc, argv); } catch(...) { fprintf(stderr, "Fatal error: Uncaught exception in main_()\n"); res = EXIT_FAILURE; } return res; } /* ///////////////////////////////////////////////////////////////////////////// * usage */ static void usage(int bExit, char const *reason, int invalidArg, int argc, char *argv[]) { fprintf(stderr, "\n"); fprintf(stderr, " %s %s Tool, v%d.%d.%d.%04d\n", COMPANY_NAME, TOOL_NAME, _mccVerHi, _mccVerLo, _mccVerRev, _mccBldNum); fprintf(stderr, "\n"); fprintf(stderr, " incorporating Digital Mars technology\n"); fprintf(stderr, "\n"); if(NULL != reason) { fprintf(stderr, " Error: %s\n", reason); fprintf(stderr, "\n"); } if(0 < invalidArg) { fprintf(stderr, " First invalid argument #%d: %s\n", invalidArg, argv[invalidArg]); fprintf(stderr, " Arguments were (first bad marked *):\n\n"); for(int i = 1; i < argc; ++i) { fprintf(stderr, " %s%s\n", (i == invalidArg) ? "* " : " ", argv[i]); } fprintf(stderr, "\n"); } fprintf(stderr, " USAGE 1: " "%s [{-w | -r<root-paths> | -p | -i | -l | -e<env-var> | -h}] [-u] [-d] " "[{<--dirs> | <--directories>}] | [<--files>] " #if defined(_SYNSOFT_INTERNAL_BUILD) && \ defined(WHEREIS_PLATFORM_IS_WIN32) "[{-v | -s}] [-f | -F | | -t | -T] [-V] " #else /* ? _SYNSOFT_INTERNAL_BUILD */ "[{-v | -s}] [-f | -F] " #endif /* _SYNSOFT_INTERNAL_BUILD */ "[<root-paths>] <search-spec>\n", EXE_NAME); fprintf(stderr, " where:\n\n"); #if 0 fprintf(stderr, " -c - case-sensitive search\n"); fprintf(stderr, " -C - case-insensitive search; (default)\n"); #endif /* 0 */ fprintf(stderr, " -d - displays the search root path(s)\n"); fprintf(stderr, " -e<env-var> - searches in the directories specified in the environment variable <env-var>\n"); fprintf(stderr, " -f - shows the filename and extension only\n"); fprintf(stderr, " -F - shows the full path; (default) \n"); fprintf(stderr, " -h - searches from the roots of all drives on the system\n"); fprintf(stderr, " -i - searches in the directories specified in the INCLUDE environment variable\n"); fprintf(stderr, " -l - searches in the directories specified in the LIB environment variable\n"); fprintf(stderr, " -m - mark directories with a trailing path separator\n"); // fprintf(stderr, " -n - Prints a total number of files found\n"); //// fprintf(stderr, " -N - Prints only the total number of files found\n"); #if defined(WHEREIS_PLATFORM_IS_WIN32) fprintf(stderr, " -p - searches in the Windows paths (the directories specified in the PATH environment variable)\n"); fprintf(stderr, " -r<root-paths> - searches from the given root path(s), separated by \';\', e.g.\n"); fprintf(stderr, " -r\"c:\\windows;x:\\bin\"\n"); #elif defined(WHEREIS_PLATFORM_IS_UNIX) fprintf(stderr, " -p - searches in the system paths (the directories specified in the PATH environment variable)\n"); fprintf(stderr, " -r<root-paths> - searches from the given root path(s), separated by \':\', e.g.\n"); fprintf(stderr, " -r\"/usr/include:/etc\"\n"); #else # error Unknown platform #endif /* platform */ fprintf(stderr, " -R - suppresses recursive search\n"); fprintf(stderr, " -s - succinct output. Prints path only\n"); #if defined(_SYNSOFT_INTERNAL_BUILD) && \ defined(WHEREIS_PLATFORM_IS_WIN32) fprintf(stderr, " -t - trims path relative to the current directory\n"); fprintf(stderr, " -T - trims path relative to the root directory(ies) specified for the search(es)\n"); #endif /* _SYNSOFT_INTERNAL_BUILD */ fprintf(stderr, " -u - recursive search. (Default except for environment variable searches.)\n"); fprintf(stderr, " -v - verbose output. Prints time, attributes, size and path; (default)\n"); #ifdef _SYNSOFT_INTERNAL_BUILD fprintf(stderr, " -V - displays the version information, if any, for the file. Suppressed by -s\n"); #endif /* _SYNSOFT_INTERNAL_BUILD */ fprintf(stderr, " -w - searches from the current working directory\n"); fprintf(stderr, " -x - summarises the file extensions\n"); fprintf(stderr, " --dirs - search for directories\n"); fprintf(stderr, " --directories - search for directories\n"); fprintf(stderr, " --files - search for files; (default if --files and --dir(ectorie)s not specified)\n"); fprintf(stderr, " <search-spec> - one or more file search specifications, separated by \';\',\n"); fprintf(stderr, " eg.\n"); fprintf(stderr, " \"*.exe\"\n"); fprintf(stderr, " \"myfile.ext\"\n"); fprintf(stderr, " \"*.exe;*.dll\"\n"); fprintf(stderr, " \"*.xl?;report.*\"\n"); fprintf(stderr, "\n"); fprintf(stderr, " USAGE 2: %s -?\n", EXE_NAME); fprintf(stderr, "\n"); fprintf(stderr, " Displays this help\n"); fprintf(stderr, "\n"); fprintf(stderr, " Contact %s\n", _nameSynesisSoftware); fprintf(stderr, " at \"%s\",\n", _wwwSynesisSoftware_SystemTools); fprintf(stderr, " or, via email, at \"%s\"\n", _emailSynesisSoftware_SystemTools); fprintf(stderr, "\n"); fprintf(stderr, " Contact Digital Mars\n"); fprintf(stderr, " at \"www.digitalmars.com\",\n"); fprintf(stderr, " or, via email, at \"software@digitalmars.com\"\n"); // fprintf(stderr, "\n"); if(bExit) { exit(EXIT_FAILURE); } } char const *convert_path_separators(char const *path, char *buffer) { #if defined(WHEREIS_PLATFORM_IS_WIN32) char const chWrong = '/'; #elif defined(WHEREIS_PLATFORM_IS_UNIX) char const chWrong = '\\'; #else # error Unknown platform #endif /* platform */ if( path != 0 && 0 != strchr(path, chWrong)) { char *pch; path = strcpy(buffer, path); for(pch = buffer; 0 != (pch = strchr(pch + 1, chWrong)); ) { *pch = PATH_NAME_SEPARATOR; } } return path; } #ifdef WHEREIS_PLATFORM_IS_WIN32 char const *get_driveroots(char *const buffer) { char drv[4] = "?:\\"; *buffer = '\0'; for(char ch = 'a'; ch <= 'z'; ++ch) { drv[0] = ch; long type = GetDriveTypeA(drv); if(DRIVE_FIXED == type) { strcat(buffer, drv); strcat(buffer, ";"); } } return buffer; } #endif /* WHEREIS_PLATFORM_IS_WIN32 */ /* ////////////////////////////////////////////////////////////////////////// */
31.829728
215
0.562001
masscry
cf33b92f91390297175f9db1e773eeda011fd2dc
1,461
cpp
C++
Progs/Ch05/Referst.cpp
singhnir/C-Plus-Plus-Robert-Lafore
7ce3c92d15958e157484fc989632b879360103aa
[ "MIT" ]
4
2021-02-24T06:53:51.000Z
2022-02-18T11:15:19.000Z
Progs/Ch05/Referst.cpp
singhnir/C-Plus-Plus-Robert-Lafore
7ce3c92d15958e157484fc989632b879360103aa
[ "MIT" ]
null
null
null
Progs/Ch05/Referst.cpp
singhnir/C-Plus-Plus-Robert-Lafore
7ce3c92d15958e157484fc989632b879360103aa
[ "MIT" ]
4
2021-02-24T07:05:43.000Z
2022-03-09T17:45:32.000Z
// referst.cpp // demonstrates passing structure by reference #include <iostream> using namespace std; //////////////////////////////////////////////////////////////// struct Distance //English distance { int feet; float inches; }; //////////////////////////////////////////////////////////////// void scale( Distance&, float ); //function void engldisp( Distance ); //declarations int main() { Distance d1 = { 12, 6.5 }; //initialize d1 and d2 Distance d2 = { 10, 5.5 }; cout << "d1 = "; engldisp(d1); //display old d1 and d2 cout << "\nd2 = "; engldisp(d2); scale(d1, 0.5); //scale d1 and d2 scale(d2, 0.25); cout << "\nd1 = "; engldisp(d1); //display new d1 and d2 cout << "\nd2 = "; engldisp(d2); cout << endl; return 0; } //-------------------------------------------------------------- // scale() // scales value of type Distance by factor void scale( Distance& dd, float factor) { float inches = (dd.feet*12 + dd.inches) * factor; dd.feet = static_cast<int>(inches / 12); dd.inches = inches - dd.feet * 12; } //-------------------------------------------------------------- // engldisp() // display structure of type Distance in feet and inches void engldisp( Distance dd ) //parameter dd of type Distance { cout << dd.feet << "\'-" << dd.inches << "\""; }
31.085106
65
0.450376
singhnir
cf3b5ad84e6ad780c89f9600ea72d405d86631b9
738
cpp
C++
src/QtGadgets/Validators/nRegExpValidator.cpp
Vladimir-Lin/QtGadgets
5fcea23ca95d85088d68fa64996e16281549ec3c
[ "MIT" ]
null
null
null
src/QtGadgets/Validators/nRegExpValidator.cpp
Vladimir-Lin/QtGadgets
5fcea23ca95d85088d68fa64996e16281549ec3c
[ "MIT" ]
null
null
null
src/QtGadgets/Validators/nRegExpValidator.cpp
Vladimir-Lin/QtGadgets
5fcea23ca95d85088d68fa64996e16281549ec3c
[ "MIT" ]
null
null
null
#include <qtgadgets.h> N::RegExpValidator:: RegExpValidator ( QObject * parent ) : QRegExpValidator ( parent ) , Validator ( parent ) { } N::RegExpValidator::~RegExpValidator (void) { } int N::RegExpValidator::Type(void) const { return 1102 ; } void N::RegExpValidator::Fixup(QString & input) const { QRegExpValidator::fixup(input) ; } QLocale N::RegExpValidator::Locale(void) const { return QRegExpValidator::locale() ; } void N::RegExpValidator::setLocale (const QLocale & locale) { QRegExpValidator::setLocale(locale) ; } QValidator::State N::RegExpValidator::isValid(QString & input,int & pos) const { return QRegExpValidator::validate(input,pos) ; }
19.945946
78
0.658537
Vladimir-Lin
cf3dac6ef0e6d5ca630943ed95d601a3080002e5
2,746
cpp
C++
src/Kepler3rdLaw.cpp
wstern1234/CPP-Projects
e8712171355b7a833f8a63ce0ffa49dcca10b053
[ "MIT" ]
null
null
null
src/Kepler3rdLaw.cpp
wstern1234/CPP-Projects
e8712171355b7a833f8a63ce0ffa49dcca10b053
[ "MIT" ]
null
null
null
src/Kepler3rdLaw.cpp
wstern1234/CPP-Projects
e8712171355b7a833f8a63ce0ffa49dcca10b053
[ "MIT" ]
null
null
null
// Identification comments code block // Wills Stern // Kepler's 3rd Law // Editor(s) used: VS Code // Compiler(s) used: g++ #include <iostream> using std::cout; using std::cin; #include <string> using std::string; using std::endl; #include <cctype> // for toupper #include <cstdlib> // for atof #include <cmath> // for sqrt, pow, and cbrt // function prototypes double findPeriod(); double findAU(); int main() { // identification output code block cout << "Wills Stern\n\n"; cout << "Kepler's 3rd Law\n";\ cout << "Editor(s) used: VSCode\n"; cout << "Compiler(s) used: g++\n"; cout << "File: " << __FILE__ << "\n"; cout << "Compiled: " << __DATE__ << " at " << __TIME__ << "\n\n\n\n"; char opt; // infinite loop, continuely asks user for data unless 'Q'/'q' is entered while (true) { // menu with two options cout << "p² = a³\n\n"; cout << "Options:\n"; cout << " P: find orbital Period\n"; cout << " A: find distance in AU" << endl; cout << "Option: "; cin >> opt; // char variable, so no need for buffer // breaks with 'Q' or 'q' if (toupper(opt) == 'Q') break; // outputs the orbital period in years else if (toupper(opt) == 'P') cout << "\n" << findPeriod() << " years\n\n\n" << endl; // outputs the distance from the Sun in Astronomical Units (AU) else if (toupper(opt) == 'A') cout << "\n" << findAU() << " AU\n\n\n" << endl; // invalid input, continues on with loop else cout << "\nNot an option, try again.\n\n\n" << endl; } } /************************************************************* * Purpose: Finds the time for an object to orbit the Sun in Earth years * * Parameters: (None) * * Return: Time for an object to orbit the Sun in Earth years as a double **************************************************************/ double findPeriod() { string buf; cout << "Enter distance in Astronomical Units (AU): "; // uses buffer input method for safety cin >> buf; double distance = atof(buf.c_str()); // Kelper's 3rd Law of Planetary Motion: p² = a³ // ...becomes p = a⁽³ᐟ²⁾ return ( sqrt(pow(distance, 3)) ); } /************************************************************* * Purpose: Finds the distance of an object from the Sun in AU * * Parameters: (None) * * Return: Distance of the object from the Sun in AU as a double **************************************************************/ double findAU() { string buf; cout << "Enter orbital period in Earth years: "; // uses buffer input method for safety cin >> buf; double period = atof(buf.c_str()); // Kelper's 3rd Law of Planetary Motion: p² = a³ // ...becomes a = p⁽²ᐟ³⁾ return ( cbrt(pow(period, 2)) ); }
22.145161
75
0.550255
wstern1234
cf3e39d26b98da0c54f6d62a7faae7c489feb69d
17,443
hpp
C++
tests/unit/coherence/util/CircularArrayListTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
tests/unit/coherence/util/CircularArrayListTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
tests/unit/coherence/util/CircularArrayListTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "cxxtest/TestSuite.h" #include "coherence/lang.ns" #include "coherence/util/CircularArrayList.hpp" #include "private/coherence/util/logging/Logger.hpp" using namespace coherence::lang; using namespace std; /** * Test suite for the CircularArrayList object. * * 2008.02.08 nsa */ class CircularArrayListTest : public CxxTest::TestSuite { public: void testAddIndex() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle hValue = String::create("Test Value"); String::Handle hValue2 = String::create("TV2"); hList->add(hValue); hList->add(0, hValue2); TS_ASSERT(hList->size() == 2); TS_ASSERT(hList->get(0)->equals(hValue2)); } void testAddAllIndex() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10); CircularArrayList::Handle hList2 = CircularArrayList::create(); String::Handle hList2Value = String::create("hList2"); hList2->add(hList2Value); hList2->addAll(0, hList); TS_ASSERT(hList2->size() == 11); TS_ASSERT(hList2->get(10) == hList2Value); } void testGet() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle hValue = String::create("Test Value"); hList->add(hValue); TS_ASSERT(hList->get(0)->equals(hValue)); String::Handle hValue2 = String::create("Test Value 2"); hList->add(hValue2); TS_ASSERT(hList->get(1)->equals(hValue2)); } void testIndexOf() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle findMe; String::Handle notFound = String::create("Can't Find Me"); for (int32_t x = 0; x < 10; ++x) { String::Handle hString = COH_TO_STRING("List Value: " << x); if (x == 5) { findMe = hString; } hList->add(hString); } TS_ASSERT(hList->indexOf(findMe) == 5); TS_ASSERT(hList->indexOf(notFound) == List::npos); } void testLastIndexOf() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle hDup = String::create("DuplicateString"); String::Handle hNotFound = String::create("Can't find me"); for (int32_t x = 0; x < 10; ++x) { if (x % 2 == 0) { hList->add(hDup); } else { hList->add(COH_TO_STRING("List Value: " << x)); } } TS_ASSERT(hList->lastIndexOf(hDup) == 8); TS_ASSERT(hList->lastIndexOf(hNotFound) == List::npos); } void testListIterator() { CircularArrayList::Handle hList = CircularArrayList::create(); TS_ASSERT_EQUALS(hList->listIterator()->hasNext(), false); TS_ASSERT_EQUALS(hList->listIterator()->hasPrevious(), false); int32_t x; for (x = 0; x < 10; ++x) { hList->add(Integer32::create(x)); } TS_ASSERT_EQUALS(hList->size(), size32_t(10)); ListIterator::Handle hIterator = hList->listIterator(); TS_ASSERT_EQUALS(hList->listIterator()->hasPrevious(), false); x = 0; while (hIterator->hasNext()) { Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next()); TS_ASSERT_EQUALS(hValue->getValue(), x); x++; } TS_ASSERT_EQUALS(x, 10); while (hIterator->hasPrevious()) { --x; Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->previous()); TS_ASSERT_EQUALS(hValue->getValue(), x); } TS_ASSERT(x == 0); while (hIterator->hasNext()) { Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next()); TS_ASSERT_EQUALS(hValue->getValue(), x); ++x; } TS_ASSERT(x == 10); } void testListIteratorIndex() { CircularArrayList::Handle hList = CircularArrayList::create(); int32_t x; for (x = 0; x < 10; ++x) { hList->add(Integer32::create(x)); } x = 5; ListIterator::Handle hIterator = hList->listIterator(x); while (hIterator->hasNext()) { Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next()); TS_ASSERT_EQUALS(hValue->getValue(), x); ++x; } TS_ASSERT_EQUALS(x, 10); while (hIterator->hasPrevious()) { --x; Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->previous()); TS_ASSERT_EQUALS(hValue->getValue(), x); } TS_ASSERT_EQUALS(x, 0); while (hIterator->hasNext()) { Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next()); TS_ASSERT_EQUALS(hValue->getValue(), x); ++x; } TS_ASSERT_EQUALS(x, 10); } void testListMuterator() { CircularArrayList::Handle hList = CircularArrayList::create(); TS_ASSERT_EQUALS(hList->listIterator()->hasNext(), false); TS_ASSERT_EQUALS(hList->listIterator()->hasPrevious(), false); size32_t x; ListMuterator::Handle hMiter = hList->listIterator(); for (x = 0; x < 10; ++x) { hMiter->add(Integer32::create(x)); } TS_ASSERT_EQUALS(hList->size(), x); while (hMiter->hasPrevious()) { --x; Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->previous()); TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x); hMiter->remove(); TS_ASSERT(hMiter->hasNext() == false) } TS_ASSERT_EQUALS(x, 0u); TS_ASSERT_EQUALS(hList->size(), x); for (x = 0; x < 5; ++x) { hMiter->add(Integer32::create(x * 2)); } TS_ASSERT_EQUALS(hList->size(), x); hMiter = hList->listIterator(); for (x = 0; x < 10; x += 2) { hMiter->next(); hMiter->add(Integer32::create(x + 1)); } TS_ASSERT_EQUALS(hList->size(), x); while (hMiter->hasPrevious()) { --x; Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->previous()); TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x); } size32_t iNextExpected = 0; for (x = 0; x < 10; x += 2) { TS_ASSERT_EQUALS(hMiter->nextIndex(), iNextExpected); Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->next()); ++iNextExpected; TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x); TS_ASSERT_EQUALS(hMiter->previousIndex(), iNextExpected - 1); hMiter->remove(); --iNextExpected; hMiter->next(); ++iNextExpected; } TS_ASSERT_EQUALS(hList->size(), x/2); hMiter = hList->listIterator(); for (x = 1; x < 10; x += 2) { Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->next()); TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x); hMiter->set(Integer32::create(x + 1)); } hMiter = hList->listIterator(); for (x = 1; x < 10; x += 2) { Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->next()); TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)(x + 1)); } // test next/prev toggle hMiter = hList->listIterator(); size32_t iNext = hMiter->nextIndex(); Object::View vNext = hMiter->next(); size32_t iPrev = hMiter->previousIndex(); Object::View vPrev = hMiter->previous(); TS_ASSERT_EQUALS(vNext, vPrev); TS_ASSERT_EQUALS(iNext, iPrev); iNext = hMiter->nextIndex(); vNext = hMiter->next(); TS_ASSERT_EQUALS(vNext, vPrev); TS_ASSERT_EQUALS(iNext, iPrev); } void testRemoveIndex() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle s1 = String::create("test1"); String::Handle s2 = String::create("test2"); hList->add(s1); hList->add(s2); TS_ASSERT(hList->remove(1)->equals(s2)); TS_ASSERT(hList->size() == 1u); } void testSetIndex() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle s1 = String::create("test1"); String::Handle s2 = String::create("test2"); String::Handle s3 = String::create("test3"); hList->add(s1); hList->add(s2); TS_ASSERT(hList->get(1)->equals(s2)); hList->set(1, s3); TS_ASSERT(hList->get(1)->equals(s3)); TS_ASSERT(hList->size() == 2u); } void testSubList() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } List::Handle hSub = hList->subList(1, 6); TS_ASSERT(hSub->size() == 5u); hSub->add(String::create("New Sub Value")); TS_ASSERT(hSub->size() == 6u); TS_ASSERT(hList->size() == 11u); Iterator::Handle hIter = hSub->iterator(); while (hIter->hasNext()) { TS_ASSERT(hList->contains(hIter->next())); } } void testSize() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10u); } void testIterator() { CircularArrayList::Handle hList = CircularArrayList::create(); int32_t x; for (x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } Iterator::Handle hIterator = hList->iterator(); x = 0; while (hIterator->hasNext()) { String::Handle hString = cast<String::Handle>(hIterator->next()); x++; } TS_ASSERT(x == 10); } void testAdd() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle hValue = String::create("Test Value"); hList->add(hValue); TS_ASSERT(hList->size() == 1u); TS_ASSERT(hList->get(0)->equals(hValue)); } void testAddAll() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10u); CircularArrayList::Handle hList2 = CircularArrayList::create(); String::Handle hList2Value = String::create("hList2"); hList2->add(hList2Value); hList2->addAll(hList); TS_ASSERT(hList2->size() == 11u); TS_ASSERT(hList2->get(10) == hList->get(hList->size() - 1)); } void testRemove() { String::Handle h1 = String::create("h1"); String::Handle h2 = String::create("h2"); CircularArrayList::Handle hList = CircularArrayList::create(); hList->add(h1); hList->add(h2); TS_ASSERT(hList->size() == 2u); hList->remove(h2); TS_ASSERT(hList->size() == 1u); } void testRemoveAll() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10); CircularArrayList::Handle hList2 = CircularArrayList::create(); String::Handle hList2Value = String::create("hList2"); String::Handle hList2Valueb = String::create("hList2b"); hList2->add(hList2Value); hList2->add(hList2Valueb); hList->addAll(hList2); TS_ASSERT(hList->size() == 12u); hList->removeAll(hList2); TS_ASSERT(hList->size() == 10u); } void testRetainAll() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10u); CircularArrayList::Handle hList2 = CircularArrayList::create(); String::Handle hList2Value = String::create("hList2"); String::Handle hList2Valueb = String::create("hList2b"); hList2->add(hList2Value); hList2->add(hList2Valueb); hList->addAll(hList2); TS_ASSERT(hList->size() == 12u); hList->retainAll(hList2); TS_ASSERT(hList->size() == 2u); } void testClear() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10u); hList->clear(); TS_ASSERT(hList->size() == 0u); hList->add(String::create("foo")); TS_ASSERT(hList->size() == 1u); } void testClone() { CircularArrayList::Handle hList = CircularArrayList::create(); hList->add(String::create("test")); hList->add(String::create("test2")); CircularArrayList::View vList = hList; CircularArrayList::Handle hListClone = cast<CircularArrayList::Handle>(vList->clone()); TS_ASSERT(hListClone->size() == 2u); TS_ASSERT(cast<String::View>(hListClone->get(0))->equals("test")); TS_ASSERT(cast<String::View>(hListClone->get(1))->equals("test2")); } void testCleanup() { HeapAnalyzer::Snapshot::View vSnap = HeapAnalyzer::ensureHeap(); CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t i = 0; i < 10; ++i) { hList->add(Integer32::create(i)); } hList = NULL; HeapAnalyzer::ensureHeap(vSnap); } void testBigList() { HeapAnalyzer::Snapshot::View vSnap = HeapAnalyzer::ensureHeap(); CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t i = 0; i < 10000; ++i) { hList->add(Integer32::create(i)); } MemberHandle<List> hEscape(System::common(), hList); int32_t n = 0; for (Iterator::Handle hIter = hList->iterator(); hIter->hasNext(); ) { Integer32::Handle hN = cast<Integer32::Handle>(hIter->next()); TS_ASSERT(hN->getValue() == n++); TS_ASSERT(hN->_isEscaped()); } TS_ASSERT(n == 10000); hEscape = NULL; hList->_isEscaped(); // unescape hList = NULL; // delete HeapAnalyzer::ensureHeap(vSnap); } };
32.301852
98
0.480193
chpatel3
cf54ff4ccd37abfe5c66d8b83cbe74fcf6f7a80b
24,755
cpp
C++
src/test_infNaN_iamax.cpp
tlapack/testBLAS
dd63ade035880783cd55a8032c13a6d8e85dc490
[ "BSD-3-Clause" ]
null
null
null
src/test_infNaN_iamax.cpp
tlapack/testBLAS
dd63ade035880783cd55a8032c13a6d8e85dc490
[ "BSD-3-Clause" ]
null
null
null
src/test_infNaN_iamax.cpp
tlapack/testBLAS
dd63ade035880783cd55a8032c13a6d8e85dc490
[ "BSD-3-Clause" ]
1
2021-06-28T21:13:49.000Z
2021-06-28T21:13:49.000Z
/// @file test_infNaN_iamax.cpp /// @brief Test cases for iamax with NaNs, Infs and the overflow threshold (OV). // // Copyright (c) 2021, University of Colorado Denver. All rights reserved. // // This file is part of testBLAS. // testBLAS is free software: you can redistribute it and/or modify it under // the terms of the BSD 3-Clause license. See the accompanying LICENSE file. #include <catch2/catch.hpp> #include <tblas.hpp> #include "defines.hpp" #include "utils.hpp" #include <limits> #include <vector> #include <complex> using namespace blas; // ----------------------------------------------------------------------------- // Auxiliary routines /** * @brief Set Ak = -k + i*k */ template< typename real_t > inline void set_complexk( std::complex<real_t>& Ak, blas::idx_t k ){ Ak = std::complex<real_t>( -k, k ); } template< typename real_t > inline void set_complexk( real_t& Ak, blas::idx_t k ){ static_assert( ! is_complex<real_t>::value, "real_t must be a Real type." ); } /** * @brief Set Ak = OV * ((k+2)/(k+3)) * (1+i) */ template< typename real_t > inline void set_complexOV( std::complex<real_t>& Ak, blas::idx_t k ){ const real_t OV = std::numeric_limits<real_t>::max(); Ak = OV * (real_t)((k+2.)/(k+3.)) * std::complex<real_t>( 1, 1 ); } template< typename real_t > inline void set_complexOV( real_t& Ak, blas::idx_t k ){ static_assert( ! is_complex<real_t>::value, "real_t must be a Real type." ); } // ----------------------------------------------------------------------------- // Test cases for iamax with Infs and NaNs at specific positions /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 1 NaN * * NaN locations: @see testBLAS::set_array_locations * * If checkWithInf == true: * For NaN location above: * Insert Inf in first non-NaN location * Insert -Inf in first non-NaN location * Ditto for last non-NaN location * Ditto for first and last non-NaN locations * * @param[in] n * Size of A * @param[in] A * Array with non-NAN data * @param[in] checkWithInf * If true, run the test cases with Infs. */ template< typename TestType > void check_iamax_1nan( const blas::idx_t n, TestType A[], const bool checkWithInf = true ) { using real_t = real_type<TestType>; std::vector<TestType> nan_vec; testBLAS::set_nan_vector( nan_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_locations( n, k_vec ); // Tests for (const auto& k : k_vec) { const TestType Ak = A[k]; const blas::idx_t infIdx1 = (k > 0) ? 0 : 1; const blas::idx_t infIdx2 = (k < n-1) ? n-1 : n-2; for (const auto& aNAN : nan_vec) { // NaN in A[k] A[k] = aNAN; // No Infs CHECK( iamax( n, A, 1 ) == k ); if( checkWithInf && n > 1 ) { const real_t inf = std::numeric_limits<real_t>::infinity(); const TestType AinfIdx1 = A[ infIdx1 ]; // Inf in first non-NaN location A[ infIdx1 ] = inf; CHECK( iamax( n, A, 1 ) == k ); // -Inf in first non-NaN location A[ infIdx1 ] = -inf; CHECK( iamax( n, A, 1 ) == k ); if( n > 2 ) { const TestType AinfIdx2 = A[ infIdx2 ]; // Inf in last non-NaN location A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k ); // -Inf in last non-NaN location A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k ); // Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k ); // -Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k ); // Reset value A[ infIdx2 ] = AinfIdx2; } // Reset value A[ infIdx1 ] = AinfIdx1; } // Reset value A[k] = Ak; } } } /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 2 NaNs * * NaN locations: @see testBLAS::set_array_pairLocations * * If checkWithInf == true: * For NaN location above: * Insert Inf in first non-NaN location * Insert -Inf in first non-NaN location * Ditto for last non-NaN location * Ditto for first and last non-NaN locations * * @param[in] n * Size of A * @param[in] A * Array with non-NAN data * @param[in] checkWithInf * If true, run the test cases with Infs. */ template< typename TestType > void check_iamax_2nans( const blas::idx_t n, TestType A[], const bool checkWithInf = true ) { using real_t = real_type<TestType>; std::vector<TestType> nan_vec; testBLAS::set_nan_vector( nan_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_pairLocations( n, k_vec ); // Tests for (unsigned i = 0; i < k_vec.size(); i += 2) { const auto& k1 = k_vec[i]; const auto& k2 = k_vec[i+1]; const TestType Ak1 = A[k1]; const TestType Ak2 = A[k2]; const blas::idx_t infIdx1 = (k1 > 0) ? 0 : ( (k2 > 1) ? 1 : 2 ); const blas::idx_t infIdx2 = (k2 < n-1) ? n-1 : ( (k1 < n-2) ? n-2 : n-3 ); for (const auto& aNAN : nan_vec) { // NaNs in A[k1] and A[k2] A[k1] = A[k2] = aNAN; // No Infs CHECK( iamax( n, A, 1 ) == k1 ); if( checkWithInf && n > 2 ) { const real_t inf = std::numeric_limits<real_t>::infinity(); const TestType AinfIdx1 = A[ infIdx1 ]; // Inf in first non-NaN location A[ infIdx1 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in first non-NaN location A[ infIdx1 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); if( n > 3 ) { const TestType AinfIdx2 = A[ infIdx2 ]; // Inf in last non-NaN location A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in last non-NaN location A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); // Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); // Reset value A[ infIdx2 ] = AinfIdx2; } // Reset value A[ infIdx1 ] = AinfIdx1; } // Reset values A[k1] = Ak1; A[k2] = Ak2; } } } /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 3 NaNs * * NaN locations: @see testBLAS::set_array_trioLocations * * If checkWithInf == true: * For NaN location above: * Insert Inf in first non-NaN location * Insert -Inf in first non-NaN location * Ditto for last non-NaN location * Ditto for first and last non-NaN locations * * @param[in] n * Size of A * @param[in] A * Array with non-NAN data * @param[in] checkWithInf * If true, run the test cases with Infs. */ template< typename TestType > void check_iamax_3nans( const blas::idx_t n, TestType A[], const bool checkWithInf = true ) { using real_t = real_type<TestType>; std::vector<TestType> nan_vec; testBLAS::set_nan_vector( nan_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_trioLocations( n, k_vec ); // Tests for (unsigned i = 0; i < k_vec.size(); i += 3) { const auto& k1 = k_vec[i]; const auto& k2 = k_vec[i+1]; const auto& k3 = k_vec[i+2]; const TestType Ak1 = A[k1]; const TestType Ak2 = A[k2]; const TestType Ak3 = A[k3]; const blas::idx_t infIdx1 = (k1 > 0) ? 0 : ( (k2 > 1) ? 1 : 2 ); const blas::idx_t infIdx2 = (k2 < n-1) ? n-1 : ( (k1 < n-2) ? n-2 : n-3 ); for (const auto& aNAN : nan_vec) { // NaNs in A[k1], A[k2] and A[k3] A[k1] = A[k2] = A[k3] = aNAN; // No Infs CHECK( iamax( n, A, 1 ) == k1 ); if( checkWithInf && n > 3 ) { const real_t inf = std::numeric_limits<real_t>::infinity(); const TestType AinfIdx1 = A[ infIdx1 ]; // Inf in first non-NaN location A[ infIdx1 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in first non-NaN location A[ infIdx1 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); if( n > 4 ) { const TestType AinfIdx2 = A[ infIdx2 ]; // Inf in last non-NaN location A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in last non-NaN location A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); // Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); // Reset value A[ infIdx2 ] = AinfIdx2; } // Reset value A[ infIdx1 ] = AinfIdx1; } // Reset values A[k1] = Ak1; A[k2] = Ak2; A[k3] = Ak3; } } } /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 1 Inf * * Inf locations: @see testBLAS::set_array_locations * * @param[in] n * Size of A. * @param[in] A * Array with finite values. */ template< typename TestType > void check_iamax_1inf( const blas::idx_t n, TestType A[] ) { std::vector<TestType> inf_vec; testBLAS::set_inf_vector( inf_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_locations( n, k_vec ); // Tests for (const auto& k : k_vec) { const TestType Ak = A[k]; for (const auto& aInf : inf_vec) { // (-1)^k*Inf in A[k] A[k] = ( k % 2 == 0 ) ? aInf : -aInf; // No Infs CHECK( iamax( n, A, 1 ) == k ); // Reset value A[k] = Ak; } } } /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 2 Infs * * Inf locations: @see testBLAS::set_array_pairLocations * * @param[in] n * Size of A. * @param[in] A * Array with finite values. */ template< typename TestType > void check_iamax_2infs( const blas::idx_t n, TestType A[] ) { std::vector<TestType> inf_vec; testBLAS::set_inf_vector( inf_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_pairLocations( n, k_vec ); // Tests for (unsigned i = 0; i < k_vec.size(); i += 2) { const auto& k1 = k_vec[i]; const auto& k2 = k_vec[i+1]; const TestType Ak1 = A[k1]; const TestType Ak2 = A[k2]; for (const auto& aInf : inf_vec) { // (-1)^k*Inf in A[k] A[k1] = ( k1 % 2 == 0 ) ? aInf : -aInf; A[k2] = ( k2 % 2 == 0 ) ? aInf : -aInf; CHECK( iamax( n, A, 1 ) == k1 ); // Reset values A[k1] = Ak1; A[k2] = Ak2; } } } /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 3 Infs * * Inf locations: @see testBLAS::set_array_trioLocations * * @param[in] n * Size of A. * @param[in] A * Array with finite values. */ template< typename TestType > void check_iamax_3infs( const blas::idx_t n, TestType A[] ) { std::vector<TestType> inf_vec; testBLAS::set_inf_vector( inf_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_trioLocations( n, k_vec ); // Tests for (unsigned i = 0; i < k_vec.size(); i += 3) { const auto& k1 = k_vec[i]; const auto& k2 = k_vec[i+1]; const auto& k3 = k_vec[i+2]; const TestType Ak1 = A[k1]; const TestType Ak2 = A[k2]; const TestType Ak3 = A[k3]; for (const auto& aInf : inf_vec) { // (-1)^k*Inf in A[k] A[k1] = ( k1 % 2 == 0 ) ? aInf : -aInf; A[k2] = ( k2 % 2 == 0 ) ? aInf : -aInf; A[k3] = ( k3 % 2 == 0 ) ? aInf : -aInf; CHECK( iamax( n, A, 1 ) == k1 ); // Reset values A[k1] = Ak1; A[k2] = Ak2; A[k3] = Ak3; } } } // ----------------------------------------------------------------------------- // Main Test Cases /** * @brief Test case for iamax with arrays containing at least 1 NaN * * Default entries: * (1) A[k] = (-1)^k*k * (2) A[k] = (-1)^k*Inf * and, for complex data type: * (3) A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd * (4) A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd * (5) A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd * (6) A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd */ TEMPLATE_TEST_CASE( "iamax returns the first NaN for real arrays with at least 1 NaN", "[iamax][BLASlv1][NaN]", TEST_TYPES ) { using real_t = real_type<TestType>; // Constants const blas::idx_t N = 128; // N > 0 const TestType inf = std::numeric_limits<real_t>::infinity(); // Arrays const std::vector<blas::idx_t> n_vec = { 1, 2, 3, 10, N }; // n_vec[i] > 0 TestType A[N]; SECTION( "At least 1 NaN in the array A" ) { WHEN( "A[k] = (-1)^k*k" ) { for (blas::idx_t k = 0; k < N; ++k) A[k] = ( k % 2 == 0 ) ? k : -k; for (const auto& n : n_vec) { check_iamax_1nan( n, A ); check_iamax_2nans( n, A ); check_iamax_3nans( n, A ); } } WHEN( "A[k] = (-1)^k*Inf" ) { for (blas::idx_t k = 0; k < N; ++k) A[k] = ( k % 2 == 0 ) ? inf : -inf; for (const auto& n : n_vec) { check_iamax_1nan( n, A, false ); check_iamax_2nans( n, A, false ); check_iamax_3nans( n, A, false ); } } if (is_complex<TestType>::value) { WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], k ); } for (const auto& n : n_vec) { check_iamax_1nan( n, A ); check_iamax_2nans( n, A ); check_iamax_3nans( n, A ); } } WHEN( "A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], k ); else set_complexk( A[k], k ); } for (const auto& n : n_vec) { check_iamax_1nan( n, A ); check_iamax_2nans( n, A ); check_iamax_3nans( n, A ); } } WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], n-k ); } check_iamax_1nan( n, A ); check_iamax_2nans( n, A ); check_iamax_3nans( n, A ); } } WHEN( "A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], n-k ); else set_complexk( A[k], k ); } check_iamax_1nan( n, A ); check_iamax_2nans( n, A ); check_iamax_3nans( n, A ); } } } } SECTION( "All NaNs" ) { for (blas::idx_t k = 0; k < N; ++k) A[k] = NAN; for (const auto& n : n_vec) CHECK( iamax( n, A, 1 ) == 0 ); } } /** * @brief Test case for iamax with arrays containing at least 1 Inf and no NaNs * * Default entries: * (1) A[k] = (-1)^k*k * and, for complex data type: * (3) A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd * (4) A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd * (5) A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd * (6) A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd */ TEMPLATE_TEST_CASE( "iamax returns the first Inf for real arrays with at least 1 Inf and no NaNs", "[iamax][BLASlv1][Inf]", TEST_TYPES ) { using real_t = real_type<TestType>; // Constants const blas::idx_t N = 128; // N > 0 const TestType inf = std::numeric_limits<real_t>::infinity(); // Arrays const std::vector<blas::idx_t> n_vec = { 1, 2, 3, 10, N }; // n_vec[i] > 0 TestType A[N]; SECTION( "At least 1 Inf in the array A" ) { WHEN( "A[k] = (-1)^k*k" ) { for (blas::idx_t k = 0; k < N; ++k) A[k] = ( k % 2 == 0 ) ? k : -k; for (const auto& n : n_vec) { check_iamax_1inf( n, A ); check_iamax_2infs( n, A ); check_iamax_3infs( n, A ); } } if (is_complex<TestType>::value) { WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], k ); } for (const auto& n : n_vec) { check_iamax_1inf( n, A ); check_iamax_2infs( n, A ); check_iamax_3infs( n, A ); } } WHEN( "A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], k ); else set_complexk( A[k], k ); } for (const auto& n : n_vec) { check_iamax_1inf( n, A ); check_iamax_2infs( n, A ); check_iamax_3infs( n, A ); } } WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], n-k ); } check_iamax_1inf( n, A ); check_iamax_2infs( n, A ); check_iamax_3infs( n, A ); } } WHEN( "A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], n-k ); else set_complexk( A[k], k ); } check_iamax_1inf( n, A ); check_iamax_2infs( n, A ); check_iamax_3infs( n, A ); } } } } SECTION( "All Infs" ) { for (blas::idx_t k = 0; k < N; ++k) A[k] = ( k % 2 == 0 ) ? inf : -inf; for (const auto& n : n_vec) CHECK( iamax( n, A, 1 ) == 0 ); } } /** * @brief Test case for iamax where A(k) are finite but abs(real(A(k)))+abs(imag(A(k))) can overflow. * * 4 cases: * A(k) = -k + i*k for k even, A(k) = OV*((k+2)/(k+3)) + i*OV*((k+2)/(k+3)) for k odd. * (Correct answer = last odd k) * Swap odd and even. (Correct answer = last even k) * A(k) = -k + i*k for k even, A(k) = OV*((n-k+2)/(n-k+3)) + i*OV*((n-k+2)/(n-k+3)) for k odd. * (Correct answer = 1) * Swap odd and even (Correct answer = 2). */ TEMPLATE_TEST_CASE( "iamax works for complex data A when abs(real(A(k)))+abs(imag(A(k))) can overflow", "[iamax][BLASlv1]", TEST_CPLX_TYPES ) { // Constants const blas::idx_t N = 128; // N > 0 // Arrays const std::vector<blas::idx_t> n_vec = { 1, 2, 3, 10, N }; // n_vec[i] > 0 TestType A[N]; WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], k ); } for (const auto& n : n_vec) { if ( n == 1 ) CHECK( iamax( n, A, 1 ) == 0 ); else if ( n % 2 == 0 ) CHECK( iamax( n, A, 1 ) == n-1 ); else CHECK( iamax( n, A, 1 ) == n-2 ); } } WHEN( "A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], k ); else set_complexk( A[k], k ); } for (const auto& n : n_vec) { if ( n == 1 ) CHECK( iamax( n, A, 1 ) == 0 ); else if ( n % 2 == 0 ) CHECK( iamax( n, A, 1 ) == n-2 ); else CHECK( iamax( n, A, 1 ) == n-1 ); } } WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], n-k ); } if ( n == 1 ) CHECK( iamax( n, A, 1 ) == 0 ); else CHECK( iamax( n, A, 1 ) == 1 ); } } WHEN( "A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], n-k ); else set_complexk( A[k], k ); } CHECK( iamax( n, A, 1 ) == 0 ); } } }
32.317232
103
0.428277
tlapack
cf614dcba15e8f5442b2aedba5196ab8203bf185
2,744
cpp
C++
cpp/tests/tdmaMsgProcessor_UT.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
133
2017-06-24T02:44:28.000Z
2022-03-25T05:17:00.000Z
cpp/tests/tdmaMsgProcessor_UT.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
null
null
null
cpp/tests/tdmaMsgProcessor_UT.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
33
2017-06-19T03:24:40.000Z
2022-02-03T20:13:12.000Z
#include "tests/tdmaMsgProcessor_UT.hpp" #include "comm/tdmaCmds.hpp" #include "comm/tdmaComm.hpp" #include "comm/cmdHeader.hpp" #include "comm/commands.hpp" #include "node/nodeParams.hpp" #include "node/nodeState.hpp" #include <gtest/gtest.h> #include <cmath> #include <unistd.h> using std::vector; namespace { } namespace comm { TDMAMsgProcessor_UT::TDMAMsgProcessor_UT() { // Load configuration node::NodeParams::loadParams("nodeConfig.json"); // Populate message processor args m_args.cmdQueue = &m_cmdQueue; m_args.relayBuffer = &m_relayBuffer; // Load command dictionary for use std::unordered_map<uint8_t, comm::HeaderType> tdmaCmdDict = TDMACmds::getCmdDict(); Cmds::updateCmdDict(tdmaCmdDict); } void TDMAMsgProcessor_UT::SetUpTestCase(void) { } void TDMAMsgProcessor_UT::SetUp(void) { } TEST_F(TDMAMsgProcessor_UT, processMsg) { // Test all commands processed by NodeMsgProcessor std::vector<uint8_t> header; std::vector<uint8_t> msgBytes; // TDMACmds::TimeOffset uint8_t sourceId = 1; double offset = 2.1; CmdHeader cmdHeader = createHeader(TDMACmds::TimeOffset, sourceId); TDMA_TimeOffset timeOffset(offset, cmdHeader); msgBytes = timeOffset.serialize(); EXPECT_TRUE(m_tdmaMsgProcessor.processMsg(TDMACmds::TimeOffset, msgBytes, m_args)); EXPECT_TRUE(node::NodeParams::nodeStatus[sourceId-1].timeOffset == offset); // TDMACmds::TimeOffsetSummary // TDMACmds::MeshStatus cmdHeader = createHeader(TDMACmds::MeshStatus, sourceId); unsigned int startTime = ceil(node::NodeParams::clock.getTime()); TDMA_MeshStatus meshStatus(startTime, TDMASTATUS_NOMINAL, cmdHeader); msgBytes = meshStatus.serialize(); EXPECT_TRUE(m_tdmaMsgProcessor.processMsg(TDMACmds::MeshStatus, msgBytes, m_args)); EXPECT_TRUE(m_cmdQueue.find(TDMACmds::MeshStatus) != m_cmdQueue.end()); // command put in queue // TDMACmds::LinkStatus cmdHeader = createHeader(TDMACmds::LinkStatus, sourceId); std::vector<uint8_t> statusIn = {node::NoLink, node::IndirectLink, node::GoodLink, node::BadLink, node::NoLink, node::NoLink}; TDMA_LinkStatus linkStatus(statusIn, cmdHeader); msgBytes = linkStatus.serialize(); EXPECT_TRUE(m_tdmaMsgProcessor.processMsg(TDMACmds::LinkStatus, msgBytes, m_args)); for (unsigned int i = 0; i < node::NodeParams::linkStatus[sourceId-1].size(); i++) { EXPECT_TRUE(node::NodeParams::linkStatus[sourceId-1][i] == statusIn[i]); } // TDMACmds::LinkStatusSummary } }
33.876543
134
0.673105
MinesJA
cf6521d38e5984acfd1d3a5a8a35309c09d30c38
1,545
cc
C++
Codeforces/BubbleCup/Problem H/H.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/BubbleCup/Problem H/H.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/BubbleCup/Problem H/H.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include <cstdio> #include <iostream> #include <cmath> #include <algorithm> #include <cstring> #include <map> #include <set> #include <vector> #include <utility> #include <queue> #include <stack> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define LET(x, a) __typeof(a) x(a) #define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); #define tr(x) cout<<x<<endl; #define tr2(x,y) cout<<x<<" "<<y<<endl; #define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl; #define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl; #define tr5(v,w,x,y,z) cout<<v<<" "<<w<<" "<<x<<" "<<y<<" "<<z<<endl; #define tr6(u,v,w,x,y,z) cout<<u<<" "<<v<<" "<<w<<" "<<x<<" "<<y<<" "<<z<<endl; using namespace std; long long f[2001000], MOD = 1e9 + 7, ans = 0; int n; long long inv(long long a){ long long ret = 1, b = MOD-2; while(b){ if(b%2) ret = (ret*a)%MOD; a = (a*a)%MOD; b >>= 1; } return ret; } long long nCr(int x, int y){ long long ret = f[x]; ret = (ret * inv(f[y]))%MOD; ret = (ret * inv(f[x-y]))%MOD; return ret; } int main(){ f[0] = 1; for(int i = 1; i <= 2000010; i++){ f[i] = (f[i-1]*i)%MOD; } sd(n); for(int i = 0; i <= n; i++){ ans = (ans + nCr(n+i+1,i+1))%MOD; } cout << ans << "\n"; return 0; }
21.458333
79
0.551456
VastoLorde95
cf65bf0e6b368a9f22c998f5fe83b42b89c5c720
310
hpp
C++
systemc.hpp
dcblack/Simple-SystemC-Debug
b7997c7cb3b5ba0eed2016a2ae5ff85989216982
[ "Apache-2.0" ]
1
2021-06-20T02:26:30.000Z
2021-06-20T02:26:30.000Z
systemc.hpp
dcblack/Simple-SystemC-Debug
b7997c7cb3b5ba0eed2016a2ae5ff85989216982
[ "Apache-2.0" ]
null
null
null
systemc.hpp
dcblack/Simple-SystemC-Debug
b7997c7cb3b5ba0eed2016a2ae5ff85989216982
[ "Apache-2.0" ]
1
2021-03-01T14:58:27.000Z
2021-03-01T14:58:27.000Z
#pragma once #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <systemc> #include <sc_time_literal.hpp> #pragma clang diagnostic pop #pragma GCC diagnostic pop //vim:syntax=systemc
28.181818
53
0.790323
dcblack
cf77bbe20e26934dc3acc307f4b1caa8f6b7cdfd
391
cpp
C++
cpp/cpp_primer/chapter19/ex_19_03.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
2
2019-12-21T00:53:47.000Z
2020-01-01T10:36:30.000Z
cpp/cpp_primer/chapter19/ex_19_03.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
cpp/cpp_primer/chapter19/ex_19_03.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
// // Created by kaiser on 19-3-16. // #include <iostream> class A { public: virtual ~A() = default; }; class B : public A {}; class C : public B {}; int main() { { A* pa = new C; if (B* pb = dynamic_cast<B*>(pa); !pb) { std::cerr << "error 1\n"; } } { B* pb = new B; if (C* pc = dynamic_cast<C*>(pb); !pc) { std::cerr << "error 2\n"; } } }
13.964286
44
0.468031
KaiserLancelot
cf79eafceff5d8d46fae59e5aa56764304bdc8ef
1,307
hpp
C++
code/adobe.poly/adobe/implementation/string_pool.hpp
andyprowl/virtual-concepts
ed3a5690c353b6998abcd3368a9b448f1bb2aa19
[ "Unlicense" ]
59
2015-04-01T12:55:36.000Z
2021-06-22T02:46:20.000Z
adobe/implementation/string_pool.hpp
brycelelbach/asl
df0d271f6c67fbb944039a9455c4eb69ae6df141
[ "MIT" ]
1
2015-06-29T14:51:55.000Z
2015-06-29T16:40:26.000Z
adobe/implementation/string_pool.hpp
brycelelbach/asl
df0d271f6c67fbb944039a9455c4eb69ae6df141
[ "MIT" ]
5
2016-04-19T09:21:11.000Z
2021-12-29T09:48:09.000Z
/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ /*************************************************************************************************/ #ifndef ADOBE_STRING_POOL_HPP #define ADOBE_STRING_POOL_HPP /*************************************************************************************************/ #include <adobe/config.hpp> #include <boost/noncopyable.hpp> /*************************************************************************************************/ namespace adobe { /**************************************************************************************************/ class unique_string_pool_t : boost::noncopyable { public: unique_string_pool_t(); ~unique_string_pool_t(); const char* add(const char* str); private: struct implementation_t; implementation_t* object_m; }; /**************************************************************************************************/ } // namespace adobe /**************************************************************************************************/ #endif /**************************************************************************************************/
26.673469
100
0.337414
andyprowl
cf8d4a21fc6e4946e1b77ff96f8b80daa1ee0b32
164
hpp
C++
src/semantic.hpp
amzamora/diamond
c9cad46401815461ebae8db781bbb669c11bd257
[ "MIT" ]
4
2021-02-02T19:55:23.000Z
2021-03-26T22:54:12.000Z
src/semantic.hpp
amzamora/diamond
c9cad46401815461ebae8db781bbb669c11bd257
[ "MIT" ]
28
2021-01-31T01:04:54.000Z
2021-12-11T13:53:49.000Z
src/semantic.hpp
amzamora/diamond
c9cad46401815461ebae8db781bbb669c11bd257
[ "MIT" ]
null
null
null
#ifndef SEMANTIC_HPP #define SEMANTIC_HPP #include "types.hpp" namespace semantic { Result<Ok, Errors> analyze(std::shared_ptr<Ast::Program> program); } #endif
14.909091
67
0.756098
amzamora
cf90ef7c36bf959177421f9dd048e4f5d2ee1611
1,637
cpp
C++
src/GUI/Selection.cpp
szebest/Basic-SFML-Application-Framework
e6b979283a1aba87ea5eefb1785d6f9bf4485d4a
[ "MIT" ]
null
null
null
src/GUI/Selection.cpp
szebest/Basic-SFML-Application-Framework
e6b979283a1aba87ea5eefb1785d6f9bf4485d4a
[ "MIT" ]
null
null
null
src/GUI/Selection.cpp
szebest/Basic-SFML-Application-Framework
e6b979283a1aba87ea5eefb1785d6f9bf4485d4a
[ "MIT" ]
null
null
null
#include "Selection.h" Selection::Selection(sf::Vector2f pos) : m_selected(false) { m_outerShape.setRadius(12); m_innerShape.setRadius(10); m_innerShape.setFillColor(sf::Color::Blue); setPosition(pos); } void Selection::handleEvents(sf::Event e, const sf::RenderWindow& window, sf::Vector2f displacement) { switch (e.type) { case sf::Event::MouseButtonPressed: { if (e.mouseButton.button == sf::Mouse::Left) if (isHovering(window, displacement)) m_selected = !m_selected; } break; default: break; } } void Selection::update(const sf::Time& deltaTime) { } void Selection::draw(sf::RenderTarget& target) { target.draw(m_outerShape); if (m_selected) target.draw(m_innerShape); } void Selection::setPosition(sf::Vector2f pos) { float outerRadius = m_outerShape.getRadius(); float innerRadius = m_innerShape.getRadius(); m_outerShape.setPosition(pos - sf::Vector2f(outerRadius, outerRadius)); m_innerShape.setPosition(pos - sf::Vector2f(innerRadius, innerRadius)); } sf::Vector2f Selection::getPosition() { float radius = m_outerShape.getRadius(); return m_outerShape.getPosition() + sf::Vector2f(radius, radius) / 2.f; } bool Selection::isHovering(const sf::RenderWindow& window, sf::Vector2f displacement) { auto pixelPos = sf::Mouse::getPosition(window); auto worldPos = window.mapPixelToCoords(pixelPos) + displacement; return m_outerShape.getGlobalBounds().contains(worldPos.x, worldPos.y); } void Selection::setSelected(bool _selected) { m_selected = _selected; } bool Selection::getSelected() { return m_selected; } const bool* Selection::getPointerToSelected() { return &m_selected; }
22.736111
100
0.744655
szebest
cf984f3074382b3d9970476ba611f764046adf3a
8,296
cpp
C++
Source/Motor2D/j1Player.cpp
Needlesslord/PaintWars_by_BrainDeadStudios
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
2
2020-03-06T11:32:40.000Z
2020-03-20T12:17:30.000Z
Source/Motor2D/j1Player.cpp
Needlesslord/Heathen_Games
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
2
2020-03-03T09:56:57.000Z
2020-05-02T15:50:45.000Z
Source/Motor2D/j1Player.cpp
Needlesslord/Heathen_Games
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
1
2020-03-17T18:50:53.000Z
2020-03-17T18:50:53.000Z
#include "p2Defs.h" #include "j1App.h" #include "p2Log.h" #include "j1Textures.h" #include "j1Input.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Player.h" #include "j1SceneManager.h" #include "j1EntityManager.h" #include "j1Window.h" #include "j1UI_manager.h" #include "Scene.h" #include "j1Timer.h" j1Player::j1Player() : j1Module() { name = ("player"); } j1Player::~j1Player() { App->CleanUp(); } bool j1Player::Awake(pugi::xml_node& config) { bool ret = true; folder = (config.child("folder").child_value()); camera_speed = config.child("camera").attribute("speed").as_int(1); camera_offset = config.child("camera").attribute("offset").as_int(10); node = config; return ret; } bool j1Player::Start() { bool ret = true; MinimapCameraBufferX = 0; MinimapCameraBufferY = 0; LOG("Player Started"); Tex_Player = App->tex->Load("textures/UI/UI_mouse.png"); App->win->GetWindowSize( win_width,win_height); SDL_ShowCursor(SDL_DISABLE); V = 0; return ret; } bool j1Player::PreUpdate() { //list<Entity*>::iterator entityCount = App->entities->activeEntities.begin(); //int B = 0; //int P = 0; //if (V != 1) { // while (entityCount != App->entities->activeEntities.end()) { // MiniMapEntities_Squares[B] = App->gui->AddElement(TypeOfUI::GUI_IMAGE, nullptr, { 1000,520 /*(*entityCount)->pos.x ,(*entityCount)->pos.y*/ }, { 0 , 0 }, false, true, { 4, 3, 2, 3 }, // nullptr, nullptr, TEXTURE::MINIMAP_ENTITIES); // // // MiniMapEntities_Squares[B]->map_position.x = MiniMapEntities_Squares[B]->init_map_position.x + App->render->camera.x + (*entityCount)->currentTile.x; // MiniMapEntities_Squares[B]->map_position.y = MiniMapEntities_Squares[B]->init_map_position.y + App->render->camera.y + (*entityCount)->currentTile.y; // entityCount++; // B++; // // } // //} //if (entityCount != App->entities->activeEntities.end()) { // V = 1; //} //LOG("ENTITY POSITION X,Y = %f %f", MiniMapEntities_Squares[B]->map_position.x, MiniMapEntities_Squares[B]->map_position.x); return true; } bool j1Player::Save(pugi::xml_node& data) { //PLAYER POSITION LOG("Loading player state"); mouse_position.x = data.child("position").attribute("X").as_int(); mouse_position.y = data.child("position").attribute("Y").as_int(); return true; } bool j1Player::Load(pugi::xml_node& data) { //PLAYER POSITION LOG("Loading player state"); mouse_position.x = data.child("position").attribute("X").as_int(); mouse_position.y = data.child("position").attribute("Y").as_int(); return true; } bool j1Player::Update(float dt) { int z = 0; App->input->GetMousePosition(mouse_position.x, mouse_position.y); Camera_Control(dt); Zoom(); if (App->PAUSE_ACTIVE == false) { if (App->scenes->IN_GAME_SCENE == true) { p2List_item<j1UIElement*>* UI_List = App->gui->GUI_ELEMENTS.start; while (UI_List != NULL) { if (App->gui->GUI_ELEMENTS[z]->textureType == TEXTURE::MINIMAP_CAMERA) { App->gui->GUI_ELEMENTS[z]->map_position.x = App->gui->GUI_ELEMENTS[z]->init_map_position.x + App->render->camera.x - MinimapCameraBufferX; App->gui->GUI_ELEMENTS[z]->map_position.y = App->gui->GUI_ELEMENTS[z]->init_map_position.y + App->render->camera.y - MinimapCameraBufferY; } else if (App->gui->GUI_ELEMENTS[z]->textureType == TEXTURE::MINIMAP_ENTITIES) { } else { //LOG("UI COUNT IS %d", z); App->gui->GUI_ELEMENTS[z]->map_position.x = App->gui->GUI_ELEMENTS[z]->init_map_position.x + App->render->camera.x; App->gui->GUI_ELEMENTS[z]->map_position.y = App->gui->GUI_ELEMENTS[z]->init_map_position.y + App->render->camera.y; /*if (App->gui->GUI_ELEMENTS[z]->textureType == TEXTURE::MINIMAP_ENTITIES) { LOG("SQUARE POSITION X=%f, Y=%f ", App->gui->GUI_ELEMENTS[z]->map_position.x, App->gui->GUI_ELEMENTS[z]->map_position.y); }*/ } UI_List = UI_List->next; ++z; } } } Select_Entities(selector); int B = 0; list<Entity*>::iterator entityCount = App->entities->activeEntities.begin(); while (entityCount != App->entities->activeEntities.end()) { /*MiniMapEntities_Squares[B] = App->gui->AddElement(TypeOfUI::GUI_IMAGE, nullptr, { (*entityCount)->pos.x , (*entityCount)->pos.y}, { 0 , 0 }, false, true, { 4, 3, 2, 3 }, nullptr, nullptr, TEXTURE::MINIMAP_ENTITIES); */ entityCount++; B++; } return true; } bool j1Player::CleanUp() { return true; } void j1Player::Camera_Control(float dt) { int z = 0; if (App->scenes->current_scene->scene_name == SCENES::GAME_SCENE) { if (App->PAUSE_ACTIVE==false) { if (mouse_position.x == 0 && App->render->camera.x <= 3750) { //LOG("Camera x at %d", App->render->camera.x); App->render->camera.x += camera_speed * dt * 1000; //1242X //695Y MinimapCameraBufferX = MinimapCameraBufferX + 1.1; } if (mouse_position.y == 0) { //LOG("Camera y at %d", App->render->camera.y); App->render->camera.y += camera_speed * dt * 1000; if (App->render->camera.y < 50) { MinimapCameraBufferY = MinimapCameraBufferY + 1.1; } } if (mouse_position.x > (win_width - camera_offset) / App->win->scale ) { //LOG("Camera x at %d", App->render->camera.x); App->render->camera.x -= camera_speed * dt * 1000; if (App->render->camera.x > -2900) { MinimapCameraBufferX = MinimapCameraBufferX - 1.1; } } if (mouse_position.y > (win_height - camera_offset) / App->win->scale) { //LOG("Camera y at %d", App->render->camera.y); App->render->camera.y -= camera_speed * dt * 1000; if (App->render->camera.y > -3150) { MinimapCameraBufferY = MinimapCameraBufferY - 1.1; } } if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT) App->render->camera.y += camera_speed * dt * 1000; if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT) App->render->camera.y -= camera_speed * dt * 1000; if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT) App->render->camera.x += camera_speed * dt * 1000; if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT) App->render->camera.x -= camera_speed * dt * 1000; if (App->render->camera.x < -2900) App->render->camera.x = -2900; if (App->render->camera.x > 3800) App->render->camera.x = 3800; if (App->render->camera.y > 50) App->render->camera.y = 50; if (App->render->camera.y < -3150) App->render->camera.y = -3150; if (App->input->GetKey(SDL_SCANCODE_H) == KEY_DOWN) { //has to update camera minimap if (App->scenes->Map_Forest_Active) { App->render->camera.x = 575; App->render->camera.y = -1200; MinimapCameraBufferX = 4; MinimapCameraBufferY = -4; } if (App->scenes->Map_Snow_Active) { App->render->camera.x = -329; App->render->camera.y = -608; MinimapCameraBufferX = -24; MinimapCameraBufferY = 15; } if (App->scenes->Map_Volcano_Active) { App->render->camera.x = 700; App->render->camera.y = 10; MinimapCameraBufferX = 4.39; MinimapCameraBufferY = 33; } } } } Mouse_Cursor(); } void j1Player::Select_Entities(SDL_Rect select_area) { int buffer; if (select_area.x > select_area.x + select_area.w) { select_area.x = select_area.x + select_area.w; select_area.w *= -1; } if (select_area.y > select_area.y + select_area.h) { select_area.y = select_area.y + select_area.h; select_area.h *= -1; } //LOG("Ax -> %d | Ay -> %d | Aw -> %d | Ah -> %d", select_area.x, select_area.y, select_area.w, select_area.h); } void j1Player::Mouse_Cursor() { mouse_position.x -= App->render->camera.x / App->win->GetScale(); mouse_position.y -= App->render->camera.y / App->win->GetScale(); App->render->RenderQueueUI(10,Tex_Player, mouse_position.x, mouse_position.y, texture_rect); } void j1Player::Zoom() { if (App->input->GetKey(SDL_SCANCODE_9) == KEY_REPEAT) //zoom IN { App->win->scale = App->win->scale + 0.001; } else if (App->input->GetKey(SDL_SCANCODE_0) == KEY_REPEAT)//zoom OUT { App->win->scale = App->win->scale - 0.001; } else if (App->input->GetKey(SDL_SCANCODE_R) == KEY_DOWN)//zoom RESET { App->win->scale = 0.5; } }
22.241287
187
0.639344
Needlesslord
cf9d37798720db9786c9cc62bd9736ada53f15da
3,671
cpp
C++
modules/tracktion_engine/plugins/internal/tracktion_VCA.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
modules/tracktion_engine/plugins/internal/tracktion_VCA.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
modules/tracktion_engine/plugins/internal/tracktion_VCA.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
/* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ namespace tracktion_engine { class VcaAutomatableParameter : public AutomatableParameter { public: VcaAutomatableParameter (const juce::String& xmlTag, const juce::String& name, Plugin& owner, juce::Range<float> valueRangeToUse) : AutomatableParameter (xmlTag, name, owner, valueRangeToUse) { } ~VcaAutomatableParameter() override { notifyListenersOfDeletion(); } juce::String valueToString (float value) override { return juce::Decibels::toString (volumeFaderPositionToDB (value) + 0.001); } float stringToValue (const juce::String& str) override { return decibelsToVolumeFaderPosition (dbStringToDb (str)); } }; //============================================================================== VCAPlugin::VCAPlugin (PluginCreationInfo info) : Plugin (info) { addAutomatableParameter (volParam = new VcaAutomatableParameter ("vca", TRANS("VCA"), *this, { 0.0f, 1.0f })); volumeValue.referTo (state, IDs::volume, getUndoManager(), decibelsToVolumeFaderPosition (0.0f)); volParam->attachToCurrentValue (volumeValue); } VCAPlugin::~VCAPlugin() { notifyListenersOfDeletion(); volParam->detachFromCurrentValue(); } juce::ValueTree VCAPlugin::create() { juce::ValueTree v (IDs::PLUGIN); v.setProperty (IDs::type, xmlTypeName, nullptr); return v; } const char* VCAPlugin::xmlTypeName = "vca"; void VCAPlugin::initialise (const PluginInitialisationInfo&) {} void VCAPlugin::deinitialise() {} void VCAPlugin::applyToBuffer (const PluginRenderContext&) {} float VCAPlugin::getSliderPos() const { return volParam->getCurrentValue(); } void VCAPlugin::setVolumeDb (float dB) { setSliderPos (decibelsToVolumeFaderPosition (dB)); } float VCAPlugin::getVolumeDb() const { return volumeFaderPositionToDB (volParam->getCurrentValue()); } void VCAPlugin::setSliderPos (float newV) { volParam->setParameter (juce::jlimit (0.0f, 1.0f, newV), juce::sendNotification); } void VCAPlugin::muteOrUnmute() { if (getVolumeDb() > -90.0f) { lastVolumeBeforeMute = getVolumeDb(); setVolumeDb (lastVolumeBeforeMute - 0.01f); // needed so that automation is recorded correctly setVolumeDb (-100.0f); } else { if (lastVolumeBeforeMute < -100.0f) lastVolumeBeforeMute = 0.0f; setVolumeDb (getVolumeDb() + 0.01f); // needed so that automation is recorded correctly setVolumeDb (lastVolumeBeforeMute); } } float VCAPlugin::updateAutomationStreamAndGetVolumeDb (double time) { if (isAutomationNeeded()) { updateParameterStreams (time); updateLastPlaybackTime(); } return getVolumeDb(); } bool VCAPlugin::canBeMoved() { if (auto ft = dynamic_cast<FolderTrack*> (getOwnerTrack())) return ft->isSubmixFolder(); return false; } void VCAPlugin::restorePluginStateFromValueTree (const juce::ValueTree& v) { juce::CachedValue<float>* cvsFloat[] = { &volumeValue, nullptr }; copyPropertiesToNullTerminatedCachedValues (v, cvsFloat); for (auto p : getAutomatableParameters()) p->updateFromAttachedValue(); } }
27.192593
114
0.616998
jbloit
cf9e02d74d153181e3e897ebe551f78dd73fe3ea
2,278
cpp
C++
FirstSemester(CS Project)/Plane.cpp
garretfox/C
9c6baeffc26e1131b873c1d7aaa99b0145635526
[ "MIT" ]
null
null
null
FirstSemester(CS Project)/Plane.cpp
garretfox/C
9c6baeffc26e1131b873c1d7aaa99b0145635526
[ "MIT" ]
null
null
null
FirstSemester(CS Project)/Plane.cpp
garretfox/C
9c6baeffc26e1131b873c1d7aaa99b0145635526
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Plane.h" #include <iostream> using namespace std; Plane::Plane() { isSet = 0; } Plane::Plane(char *c) { PlaneName = c; NumberOfParties = 0; for (int i = 0; i < 40; i++) { PartyArray[i].SetPartyName("NULL"); PartyArray[i].SetPartySize(0); }; isSet = 0; } void Plane::SetPartyAt(int i, char* c, int j) { GetPartyArrayAt(i).SetPartyName(c); GetPartyArrayAt(i).SetPartySize(j); } bool Plane::NameNull(int i) { if (PartyArray[i].GetPartyName() == "NULL") return 1; else return 0; } bool Plane::IsSet() { return isSet; } void Plane::AddSeats(int i) { int j = NumberOfSeats + i; NumberOfSeats = j; } void Plane::SubtractSeats(int i) { int j = NumberOfSeats - i; NumberOfSeats = j; } void Plane::SetSeatNumber() { bool valid = 0; int i; cout << "Enter " << PlaneName << "'s Seating Capacity" << endl; cin >> i; do { if (i > 40 || i < 0) { cout << " Invalid Number" << endl; } else { valid = 1; NumberOfSeats = i; OriginalNumberOfSeats = i; } } while (!valid); } void Plane::IncrementNumberOfParties() { NumberOfParties++; } void Plane::DecrementNumberOfParties() { NumberOfParties--; } int Plane::GetNumberOfAvailableSeats() { return NumberOfSeats; } void Plane::DisplayOnboardParties() { cout << "PARTY NAMES" << endl; for (int i = 0; i < NumberOfParties; i++) { if (GetPartyArrayAt(i).GetPartyName() != "NULL") { cout << "______________________ PARTY " << i << "_________________________" << endl; cout << *(GetPartyArrayAt(i).GetPartyName()) << endl; cout << "And Has " << GetPartyArrayAt(i).GetPartySize() << " People." << endl; cout << "_________________________________________________________________" << endl; } else; } } Party Plane::GetPartyArrayAt(int i) { return PartyArray[i]; } Party * Plane::GetPartyArray() { return PartyArray; } void Plane::Reset() { cout << "Passengers Departing on " << PlaneName << ":" << endl; cout << "__+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+___" << endl; DisplayOnboardParties(); for (int i = 0; i < 40; i++) { PartyArray[i].SetPartyName("NULL"); PartyArray[i].SetPartySize(0); }; NumberOfParties = 0; NumberOfSeats = OriginalNumberOfSeats; } int Plane::GetNumberofParties() { return NumberOfParties; }
18.672131
87
0.644425
garretfox
cfa1a15555f29bc71b3ec1198ffc2ffa006c53f3
254
cpp
C++
abc/ABC161/cpp/a.cpp
yokotani92/atcoder
febaef2d13c40093a2a284c87a949cd46113801d
[ "MIT" ]
null
null
null
abc/ABC161/cpp/a.cpp
yokotani92/atcoder
febaef2d13c40093a2a284c87a949cd46113801d
[ "MIT" ]
null
null
null
abc/ABC161/cpp/a.cpp
yokotani92/atcoder
febaef2d13c40093a2a284c87a949cd46113801d
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> #define rep(i, n) for (int i = 0; i < (int)(n); i++) using namespace std; typedef long long ll; const int MOD = 1E9 + 9; const int INF = 1 << 29; int main() { int A; cin >> A; cout << A; }
18.142857
52
0.598425
yokotani92
cfa44f9a16a58ec7ed3b6ee8a2744e12ce2704d7
1,985
cpp
C++
CSL/CSL-r/src/wmark/scanner_actions/tk_action.cpp
ZJU-ZSJ/CppTSL
6ce7673d5f7f8de8769c6377090b845492e63aa9
[ "BSD-2-Clause" ]
null
null
null
CSL/CSL-r/src/wmark/scanner_actions/tk_action.cpp
ZJU-ZSJ/CppTSL
6ce7673d5f7f8de8769c6377090b845492e63aa9
[ "BSD-2-Clause" ]
null
null
null
CSL/CSL-r/src/wmark/scanner_actions/tk_action.cpp
ZJU-ZSJ/CppTSL
6ce7673d5f7f8de8769c6377090b845492e63aa9
[ "BSD-2-Clause" ]
null
null
null
/* ** Xin YUAN, 2019, BSD (2) */ //////////////////////////////////////////////////////////////////////////////// #include "precomp.h" #include "../WmarkScanner.h" #include "../base/WmarkDef.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace CSL { //////////////////////////////////////////////////////////////////////////////// // TkAction RdScannerAction WmarkScannerHelper::get_TkAction() { return [](std::istream& stm, RdActionStack& stk, RdToken& token)->bool { //get a character char ch; stm.get(ch); if( stm.eof() ) { token.uID = TK_END_OF_EVENT; return true; } if( !stm.good() ) return false; token.strToken += ch; //return if( ch == '\n' ) { token.uID = WMARK_TK_RETURN; token.infoEnd.uRow ++; token.infoEnd.uCol = 0; return true; } if( ch == '\r' ) { stm.get(ch); if( stm.eof() ) { token.uID = WMARK_TK_RETURN; token.infoEnd.uRow ++; token.infoEnd.uCol = 0; return true; } if( !stm.good() ) return false; token.infoEnd.uRow ++; token.infoEnd.uCol = 0; if( ch == '\n' ) { token.strToken += ch; token.uID = WMARK_TK_RETURN; return true; } stm.unget(); token.uID = WMARK_TK_RETURN; return true; } token.infoEnd.uCol ++; //indent if( ch == '\t' ) { token.uID = WMARK_TK_INDENT; return true; } //< if( ch == '<' ) { stk.push(WMARK_SCANNER_COMMENT_ACTION); return true; } //others stk.push(WMARK_SCANNER_TEXT_ACTION); return true; }; } //////////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////////////////
22.303371
81
0.38136
ZJU-ZSJ
cfa6269395b8e032be571d81ad55df8fe1d840f4
1,902
cpp
C++
test/algorithm/test_scalar_product.cpp
jan-moeller/lina
9acaac27d7efb3e8b3c4d1ae2ad9425e79f233c8
[ "MIT" ]
null
null
null
test/algorithm/test_scalar_product.cpp
jan-moeller/lina
9acaac27d7efb3e8b3c4d1ae2ad9425e79f233c8
[ "MIT" ]
null
null
null
test/algorithm/test_scalar_product.cpp
jan-moeller/lina
9acaac27d7efb3e8b3c4d1ae2ad9425e79f233c8
[ "MIT" ]
null
null
null
// // MIT License // // Copyright (c) 2021 Jan Möller // // 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 "lina/lina.hpp" #include <catch2/catch.hpp> using namespace lina; TEST_CASE("scalar_product", "[algorithm]") { constexpr basic_matrix<double, {3, 2}> m{1, 2, 3, 4, 5, 6}; constexpr basic_matrix<double, {3, 2}> expected{3, 6, 9, 12, 15, 18}; constexpr float scalar = 3; SECTION("copy") { auto const result1 = scalar_product(scalar, m); auto const result2 = scalar_product(m, scalar); CHECK(result1 == expected); CHECK(result1 == result2); } SECTION("in place") { auto m1 = m; auto m2 = m; scalar_product(std::in_place, scalar, m1); scalar_product(std::in_place, m2, scalar); CHECK(m1 == expected); CHECK(m1 == m2); } }
35.886792
81
0.679811
jan-moeller
cfa71a4d6fc15a687b05d19ccf96c7684a70116f
2,593
cpp
C++
src/database/core/SoXipMprActiveElement.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
2
2020-05-21T07:06:07.000Z
2021-06-28T02:14:34.000Z
src/database/core/SoXipMprActiveElement.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
null
null
null
src/database/core/SoXipMprActiveElement.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
6
2016-03-21T19:53:18.000Z
2021-06-08T18:06:03.000Z
/* Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <xip/inventor/core/SoXipMprActiveElement.h> SO_ELEMENT_SOURCE(SoXipMprActiveElement); //////////////////////////////////////////////////////////////////////// SoXipMprActiveElement::~SoXipMprActiveElement() { } void SoXipMprActiveElement::initClass() { SO_ELEMENT_INIT_CLASS(SoXipMprActiveElement, SoReplacedElement); } void SoXipMprActiveElement::init(SoState *) { mprId = 0; mprIdField = 0; } void SoXipMprActiveElement::set(SoState *state, SoNode *node, const int32_t index, SoSFInt32* indexField) { SoXipMprActiveElement *elt; // get an instance we can change (pushing if necessary) elt = (SoXipMprActiveElement *) getElement(state, classStackIndex, node); if ( (elt != NULL) ) { elt->mprId = index; elt->mprIdField = indexField; } } SoSFInt32* SoXipMprActiveElement::getMprFieldIndex(SoState *state) { const SoXipMprActiveElement *elt; elt = (const SoXipMprActiveElement *)getConstElement(state, classStackIndex); if ( (elt != NULL) ) return elt->mprIdField; else return NULL; } const int32_t SoXipMprActiveElement::getMprIndex(SoState *state) { const SoXipMprActiveElement *elt; elt = (const SoXipMprActiveElement *)getConstElement(state, classStackIndex); if ( (elt != NULL) ) return elt->mprId; else return 0; } // // Overrides this method to compare attenuation values. // SbBool SoXipMprActiveElement::matches(const SoElement *elt) const { SbBool match = FALSE; if ( (mprIdField == ((const SoXipMprActiveElement *) elt)->mprIdField) && (mprId == ((const SoXipMprActiveElement *) elt)->mprId) ) match = TRUE; return match; } // // Create a copy of this instance suitable for calling matches() // SoElement * SoXipMprActiveElement::copyMatchInfo() const { SoXipMprActiveElement *result = (SoXipMprActiveElement *)getTypeId().createInstance(); if(result) { result->mprId = mprId; return result; } else return NULL; }
21.429752
100
0.712302
OpenXIP
bbb9f9305db3702a4b26f8b6b4ba73adab3845da
424
cpp
C++
src/Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.cpp
sfulham/GameProject-1
83c065ac7abc4c0a098dfcb0d1cc13f9d8bf7a03
[ "MIT" ]
null
null
null
src/Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.cpp
sfulham/GameProject-1
83c065ac7abc4c0a098dfcb0d1cc13f9d8bf7a03
[ "MIT" ]
null
null
null
src/Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.cpp
sfulham/GameProject-1
83c065ac7abc4c0a098dfcb0d1cc13f9d8bf7a03
[ "MIT" ]
null
null
null
// // Created by MarcasRealAccount on 31. Oct. 2020 // #include "Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.h" #include "Engine/Renderer/Shader/Shader.h" namespace gp1::renderer::apis::vulkan::shader { VulkanMaterialData::VulkanMaterialData(renderer::shader::Material* material) : VulkanRendererData(material) {} void VulkanMaterialData::CleanUp() {} } // namespace gp1::renderer::apis::vulkan::shader
26.5
77
0.754717
sfulham
bbbef5de65bc8b029ed136f8309ca4db2a319ecb
1,879
cpp
C++
src/plugins/zalil/servicesmanager.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/zalil/servicesmanager.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/zalil/servicesmanager.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "servicesmanager.h" #include <algorithm> #include <QStringList> #include <QFileInfo> #include <QtDebug> #include "servicebase.h" #include "pendinguploadbase.h" #include "bitcheeseservice.h" namespace LC { namespace Zalil { ServicesManager::ServicesManager (const ICoreProxy_ptr& proxy, QObject *parent) : QObject { parent } , Proxy_ { proxy } { Services_ << std::make_shared<BitcheeseService> (proxy, this); } QStringList ServicesManager::GetNames (const QString& file) const { const auto fileSize = file.isEmpty () ? 0 : QFileInfo { file }.size (); QStringList result; for (const auto& service : Services_) if (service->GetMaxFileSize () > fileSize) result << service->GetName (); return result; } PendingUploadBase* ServicesManager::Upload (const QString& file, const QString& svcName) { const auto pos = std::find_if (Services_.begin (), Services_.end (), [&svcName] (const ServiceBase_ptr& service) { return service->GetName () == svcName; }); if (pos == Services_.end ()) { qWarning () << Q_FUNC_INFO << "cannot find service" << svcName; return nullptr; } const auto pending = (*pos)->UploadFile (file); if (!pending) { qWarning () << Q_FUNC_INFO << "unable to upload" << file << "to" << svcName; return nullptr; } connect (pending, SIGNAL (fileUploaded (QString, QUrl)), this, SIGNAL (fileUploaded (QString, QUrl))); return pending; } } }
25.053333
89
0.619478
Maledictus
bbc18b7e6cbf92a4660726cc386e7834f0fb3e2d
1,773
cpp
C++
code/mandelbrot_tty/main.cpp
battibass/pf2021
7d370d26a53588c3168b57614e34e0dda70f5bbf
[ "CC-BY-4.0" ]
7
2021-10-20T08:43:46.000Z
2022-03-26T14:18:19.000Z
code/mandelbrot_tty/main.cpp
battibass/pf2021
7d370d26a53588c3168b57614e34e0dda70f5bbf
[ "CC-BY-4.0" ]
null
null
null
code/mandelbrot_tty/main.cpp
battibass/pf2021
7d370d26a53588c3168b57614e34e0dda70f5bbf
[ "CC-BY-4.0" ]
10
2021-10-01T13:49:56.000Z
2022-03-29T10:28:06.000Z
#include <iostream> #include <string> class Complex { double r_; double i_; public: Complex(double r = 0., double i = 0.) : r_{r}, i_{i} { } double real() const { return r_; } double imag() const { return i_; } Complex& operator+=(Complex const& o) { r_ += o.r_; i_ += o.i_; return *this; } Complex& operator*=(Complex const& o) { auto t = r_ * o.r_ - i_ * o.i_; i_ = r_ * o.i_ + i_ * o.r_; r_ = t; return *this; } }; Complex operator-(Complex const& c) { return {-c.real(), -c.imag()}; } Complex operator+(Complex const& left, Complex const& right) { auto result = left; return result += right; } Complex operator-(Complex const& left, Complex const& right) { return left + (-right); } Complex operator*(Complex const& left, Complex const& right) { auto result = left; return result *= right; } double norm2(Complex const& c) { return c.real() * c.real() + c.imag() * c.imag(); } int mandelbrot(Complex const& c) { int i = 0; auto z = c; for (; i != 256 && norm2(z) < 4.; ++i) { z = z * z + c; } return i; } auto to_symbol(int k) { return k < 256 ? ' ' : '*'; } int main() { int const display_width = 100; int const display_height = 48; Complex const top_left{-2.3, 1.}; Complex const lower_right{0.8, -1.}; auto const diff = lower_right - top_left; auto const delta_x = diff.real() / display_width; auto const delta_y = diff.imag() / display_height; for (int row{0}; row != display_height; ++row) { std::string line; for (int column{0}; column != display_width; ++column) { auto k = mandelbrot(top_left + Complex{delta_x * column, delta_y * row}); line.push_back(to_symbol(k)); } std::cout << line << '\n'; } }
17.909091
79
0.585448
battibass
bbc1d2621c8dd95ab7076682e99978b9f8e22d8a
8,626
cpp
C++
Tests/DiligentToolsTest/src/RenderStateNotationParser/PipelineStateParserTest.cpp
SebMenozzi/DiligentTools
cf2d8b67df590a93862749051c65310535a2f3cd
[ "Apache-2.0" ]
null
null
null
Tests/DiligentToolsTest/src/RenderStateNotationParser/PipelineStateParserTest.cpp
SebMenozzi/DiligentTools
cf2d8b67df590a93862749051c65310535a2f3cd
[ "Apache-2.0" ]
null
null
null
Tests/DiligentToolsTest/src/RenderStateNotationParser/PipelineStateParserTest.cpp
SebMenozzi/DiligentTools
cf2d8b67df590a93862749051c65310535a2f3cd
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2022 Diligent Graphics LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "gtest/gtest.h" #include "DRSNLoader.hpp" using namespace Diligent; namespace { TEST(Tools_RenderStateNotationParser, ParsePipelineStateEnums) { DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; ASSERT_TRUE(TestEnum<PIPELINE_TYPE>(Allocator, PIPELINE_TYPE_GRAPHICS, PIPELINE_TYPE_LAST)); ASSERT_TRUE(TestBitwiseEnum<SHADER_VARIABLE_FLAGS>(Allocator, SHADER_VARIABLE_FLAG_LAST)); ASSERT_TRUE(TestBitwiseEnum<PIPELINE_SHADING_RATE_FLAGS>(Allocator, PIPELINE_SHADING_RATE_FLAG_LAST)); ASSERT_TRUE(TestBitwiseEnum<SHADER_VARIABLE_FLAGS>(Allocator, SHADER_VARIABLE_FLAG_LAST)); ASSERT_TRUE(TestBitwiseEnum<PSO_CREATE_FLAGS>(Allocator, PSO_CREATE_FLAG_LAST)); } TEST(Tools_RenderStateNotationParser, ParseSampleDesc) { CHECK_STRUCT_SIZE(SampleDesc, 2); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/SampleDesc.json"); SampleDesc DescReference{}; DescReference.Count = 4; DescReference.Quality = 1; SampleDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParseShaderResourceVariableDesc) { CHECK_STRUCT_SIZE(ShaderResourceVariableDesc, 24); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/ShaderResourceVariableDesc.json"); ShaderResourceVariableDesc DescReference{}; DescReference.Name = "TestName"; DescReference.Type = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; DescReference.ShaderStages = SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL; DescReference.Flags = SHADER_VARIABLE_FLAG_NO_DYNAMIC_BUFFERS | SHADER_VARIABLE_FLAG_GENERAL_INPUT_ATTACHMENT; ShaderResourceVariableDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParsePipelineResourceLayoutDesc) { CHECK_STRUCT_SIZE(PipelineResourceLayoutDesc, 40); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/PipelineResourceLayoutDesc.json"); constexpr ShaderResourceVariableDesc Variables[] = { {SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "TestName0", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}, {SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "TestName1", SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}}; constexpr ImmutableSamplerDesc Samplers[] = { ImmutableSamplerDesc{SHADER_TYPE_ALL_RAY_TRACING, "TestName0", {FILTER_TYPE_POINT, FILTER_TYPE_MAXIMUM_POINT, FILTER_TYPE_ANISOTROPIC}}, ImmutableSamplerDesc{SHADER_TYPE_PIXEL, "TestName1", {FILTER_TYPE_COMPARISON_POINT, FILTER_TYPE_COMPARISON_LINEAR, FILTER_TYPE_COMPARISON_ANISOTROPIC}}}; PipelineResourceLayoutDesc DescReference{}; DescReference.DefaultVariableMergeStages = SHADER_TYPE_ALL_GRAPHICS; DescReference.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE; DescReference.Variables = Variables; DescReference.NumVariables = _countof(Variables); DescReference.ImmutableSamplers = Samplers; DescReference.NumImmutableSamplers = _countof(Samplers); PipelineResourceLayoutDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParseGraphicsPipelineDesc) { CHECK_STRUCT_SIZE(GraphicsPipelineDesc, 192); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/GraphicsPipelineDesc.json"); constexpr LayoutElement InputLayoutElemets[] = { LayoutElement{0, 0, 3, VT_FLOAT32}, LayoutElement{1, 0, 4, VT_FLOAT32}}; GraphicsPipelineDesc DescReference{}; DescReference.SampleMask = 1245678; DescReference.PrimitiveTopology = PRIMITIVE_TOPOLOGY_POINT_LIST; DescReference.NumViewports = 2; DescReference.SubpassIndex = 1; DescReference.NodeMask = 1; DescReference.DepthStencilDesc.DepthEnable = false; DescReference.RasterizerDesc.CullMode = CULL_MODE_FRONT; DescReference.ShadingRateFlags = PIPELINE_SHADING_RATE_FLAG_PER_PRIMITIVE | PIPELINE_SHADING_RATE_FLAG_TEXTURE_BASED; DescReference.BlendDesc.RenderTargets[0].BlendEnable = true; DescReference.InputLayout.LayoutElements = InputLayoutElemets; DescReference.InputLayout.NumElements = _countof(InputLayoutElemets); DescReference.DSVFormat = TEX_FORMAT_D32_FLOAT; DescReference.NumRenderTargets = 2; DescReference.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM; DescReference.RTVFormats[1] = TEX_FORMAT_RG16_FLOAT; DescReference.SmplDesc.Count = 4; DescReference.SmplDesc.Quality = 1; GraphicsPipelineDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParseRayTracingPipelineDesc) { CHECK_STRUCT_SIZE(RayTracingPipelineDesc, 4); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/RayTracingPipelineDesc.json"); RayTracingPipelineDesc DescReference{}; DescReference.MaxRecursionDepth = 7; DescReference.ShaderRecordSize = 4096; RayTracingPipelineDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParsePipelineStateDesc) { CHECK_STRUCT_SIZE(PipelineStateDesc, 64); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/PipelineStateDesc.json"); PipelineStateDesc DescReference{}; DescReference.PipelineType = PIPELINE_TYPE_COMPUTE; DescReference.Name = "TestName"; DescReference.SRBAllocationGranularity = 16; DescReference.ImmediateContextMask = 1; DescReference.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; PipelineStateDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParseTilePipelineDesc) { CHECK_STRUCT_SIZE(TilePipelineDesc, 18); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/TilePipelineDesc.json"); TilePipelineDesc DescReference{}; DescReference.NumRenderTargets = 2; DescReference.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM; DescReference.RTVFormats[1] = TEX_FORMAT_RG16_FLOAT; DescReference.SampleCount = 4; TilePipelineDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } } // namespace
41.07619
161
0.761651
SebMenozzi
bbc21fea637e1879270776e4399ec10b782f2ba7
3,861
hpp
C++
source/Irrlicht/rtc/impl/threadpool.hpp
MagicAtom/irrlicht-ce
b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d
[ "IJG" ]
null
null
null
source/Irrlicht/rtc/impl/threadpool.hpp
MagicAtom/irrlicht-ce
b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d
[ "IJG" ]
null
null
null
source/Irrlicht/rtc/impl/threadpool.hpp
MagicAtom/irrlicht-ce
b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d
[ "IJG" ]
null
null
null
/** * Copyright (c) 2020 Paul-Louis Ageneau * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef RTC_IMPL_THREADPOOL_H #define RTC_IMPL_THREADPOOL_H #include "common.hpp" #include "init.hpp" #include "internals.hpp" #include <chrono> #include <condition_variable> #include <deque> #include <functional> #include <future> #include <memory> #include <mutex> #include <queue> #include <stdexcept> #include <thread> #include <vector> namespace rtc::impl { template <class F, class... Args> using invoke_future_t = std::future<std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>; class ThreadPool final { public: using clock = std::chrono::steady_clock; static ThreadPool &Instance(); ThreadPool(const ThreadPool &) = delete; ThreadPool &operator=(const ThreadPool &) = delete; ThreadPool(ThreadPool &&) = delete; ThreadPool &operator=(ThreadPool &&) = delete; int count() const; void spawn(int count = 1); void join(); void run(); bool runOne(); template <class F, class... Args> auto enqueue(F &&f, Args &&...args) -> invoke_future_t<F, Args...>; template <class F, class... Args> auto schedule(clock::duration delay, F &&f, Args &&...args) -> invoke_future_t<F, Args...>; template <class F, class... Args> auto schedule(clock::time_point time, F &&f, Args &&...args) -> invoke_future_t<F, Args...>; private: ThreadPool(); ~ThreadPool(); std::function<void()> dequeue(); // returns null function if joining std::vector<std::thread> mWorkers; std::atomic<int> mBusyWorkers = 0; std::atomic<bool> mJoining = false; struct Task { clock::time_point time; std::function<void()> func; bool operator>(const Task &other) const { return time > other.time; } bool operator<(const Task &other) const { return time < other.time; } }; std::priority_queue<Task, std::deque<Task>, std::greater<Task>> mTasks; std::condition_variable mTasksCondition, mWaitingCondition; mutable std::mutex mMutex, mWorkersMutex; }; template <class F, class... Args> auto ThreadPool::enqueue(F &&f, Args &&...args) -> invoke_future_t<F, Args...> { return schedule(clock::now(), std::forward<F>(f), std::forward<Args>(args)...); } template <class F, class... Args> auto ThreadPool::schedule(clock::duration delay, F &&f, Args &&...args) -> invoke_future_t<F, Args...> { return schedule(clock::now() + delay, std::forward<F>(f), std::forward<Args>(args)...); } template <class F, class... Args> auto ThreadPool::schedule(clock::time_point time, F &&f, Args &&...args) -> invoke_future_t<F, Args...> { std::unique_lock lock(mMutex); using R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>; auto bound = std::bind(std::forward<F>(f), std::forward<Args>(args)...); auto task = std::make_shared<std::packaged_task<R()>>([bound = std::move(bound)]() mutable { try { return bound(); } catch (const std::exception &e) { PLOG_WARNING << e.what(); throw; } }); std::future<R> result = task->get_future(); mTasks.push({time, [task = std::move(task), token = Init::Instance().token()]() { return (*task)(); }}); mTasksCondition.notify_one(); return result; } } // namespace rtc::impl #endif
30.642857
105
0.690236
MagicAtom
bbc512ed68463d935ede3a4f15d7ad35183f3eec
310
hxx
C++
src/common.hxx
scuisdc/iojxd
6ced0d5983a8075c313869791f7295b98ce3f174
[ "BSD-2-Clause" ]
1
2015-05-18T00:02:13.000Z
2015-05-18T00:02:13.000Z
src/common.hxx
scuisdc/iojxd
6ced0d5983a8075c313869791f7295b98ce3f174
[ "BSD-2-Clause" ]
null
null
null
src/common.hxx
scuisdc/iojxd
6ced0d5983a8075c313869791f7295b98ce3f174
[ "BSD-2-Clause" ]
null
null
null
// // Created by secondwtq <lovejay-lovemusic@outlook.com> 2015/05/18. // Copyright (c) 2015 SCU ISDC All rights reserved. // // This file is part of ISDCNext. // // We have always treaded the borderland. // #ifndef IOJXD_COMMON_HXX #define IOJXD_COMMON_HXX #include "context.hxx" #endif //IOJXD_COMMON_HXX
19.375
67
0.735484
scuisdc
bbc685778822168fdfc95254155507c30e9efd6e
6,505
cpp
C++
DrunkEngine/ComponentTransform.cpp
MarcFly/Fly3D-Engine
e8da09a63c7c3d991b8f25c346798ee230593e78
[ "Unlicense" ]
null
null
null
DrunkEngine/ComponentTransform.cpp
MarcFly/Fly3D-Engine
e8da09a63c7c3d991b8f25c346798ee230593e78
[ "Unlicense" ]
3
2018-09-27T17:00:14.000Z
2018-12-19T13:30:25.000Z
DrunkEngine/ComponentTransform.cpp
MarcFly/Fly3D-Engine
e8da09a63c7c3d991b8f25c346798ee230593e78
[ "Unlicense" ]
null
null
null
#include "ComponentTransform.h" #include "GameObject.h" #include "Assimp/include/scene.h" #include "GameObject.h" #include "Application.h" ComponentTransform::ComponentTransform(const aiMatrix4x4 * t, GameObject* par) { SetBaseVals(); SetFromMatrix(t); parent = par; SetLocalTransform(); } void ComponentTransform::SetFromMatrix(const aiMatrix4x4* t) { aiVector3D local_scale; aiVector3D pos; aiQuaternion rot; t->Decompose(local_scale, rot, pos); scale = float3(local_scale.x, local_scale.y, local_scale.z); rotate_quat = Quat(rot.x, rot.y, rot.z, rot.w); position = float3(pos.x, pos.y, pos.z); SetTransformRotation(rotate_quat); } void ComponentTransform::SetFromMatrix(const float4x4 * t) { float3 local_scale; float3 pos; Quat rot; t->Decompose(position, rotate_quat, scale); SetTransformRotation(rotate_quat); } void ComponentTransform::SetTransformPosition(const float pos_x, const float pos_y, const float pos_z) { position.x = pos_x; position.y = pos_y; position.z = pos_z; SetLocalTransform(); } void ComponentTransform::SetTransformRotation(const Quat rot_quat) { rotate_quat = rot_quat; rotate_euler = RadToDeg(rotate_quat.ToEulerXYZ()); SetLocalTransform(); } void ComponentTransform::SetTransformRotation(const float3 rot_vec) { rotate_quat = Quat::FromEulerXYZ(DegToRad(rot_vec.x), DegToRad(rot_vec.y), DegToRad(rot_vec.z)); rotate_euler = rot_vec; SetLocalTransform(); } void ComponentTransform::SetTransformScale(const float scale_x, const float scale_y, const float scale_z) { if (scale.x != scale_x && scale_x > 0.1f) scale.x = scale_x; if (scale.y != scale_y && scale_y > 0.1f) scale.y = scale_y; if (scale.z != scale_z && scale_z > 0.1f) scale.z = scale_z; SetLocalTransform(); } void ComponentTransform::SetLocalTransform() { local_transform = float4x4::FromTRS(position, rotate_quat, scale); } void ComponentTransform::SetWorldPos(const float4x4 new_transform) { aux_world_pos = aux_world_pos * new_transform; world_pos = world_pos * new_transform; } void ComponentTransform::SetWorldRot(const Quat new_rot) { world_rot = world_rot * world_rot.FromQuat(new_rot, aux_world_pos.Col3(3) - world_pos.Col3(3)); //world_rot[0][0] = 1.f; //world_rot[1][1] = 1.f; //world_rot[2][2] = 1.f; //world_rot[3][3] = 1.f; } void ComponentTransform::CalculateGlobalTransforms() { if (parent->parent != nullptr) global_transform = world_pos * world_rot * parent->parent->GetTransform()->global_transform * local_transform; else global_transform = local_transform; global_transform.Decompose(global_pos, global_rot, global_scale); //global_pos = global_transform.Col3(3); //global_rot = GetRotFromMat(global_transform); //global_scale = global_transform.GetScale(); if (parent->children.size() > 0) { for (std::vector<GameObject*>::iterator it = parent->children.begin(); it != parent->children.end(); it++) { (*it)->GetTransform()->CalculateGlobalTransforms(); } } SetAuxWorldPos(); } void ComponentTransform::SetAuxWorldPos() { aux_world_pos = float4x4::FromTRS(float3(float3::zero - global_transform.Col3(3)), Quat::identity.Neg(), float3::one); aux_world_pos = -aux_world_pos; } Quat ComponentTransform::GetRotFromMat(float4x4 mat) { Quat rot; rot.w = Sqrt(max(0, 1 + mat.Diagonal3().x + mat.Diagonal3().y + mat.Diagonal3().z)) / 2; rot.x = Sqrt(max(0, 1 + mat.Diagonal3().x - mat.Diagonal3().y - mat.Diagonal3().z)) / 2; rot.y = Sqrt(max(0, 1 - mat.Diagonal3().x + mat.Diagonal3().y - mat.Diagonal3().z)) / 2; rot.z = Sqrt(max(0, 1 - mat.Diagonal3().x - mat.Diagonal3().y + mat.Diagonal3().z)) / 2; rot.x *= sgn(rot.x * (mat.Col3(2).y - mat.Col3(1).z)); rot.y *= sgn(rot.y * (mat.Col3(0).z - mat.Col3(2).x)); rot.z *= sgn(rot.z * (mat.Col3(1).x - mat.Col3(0).y)); rot.x = -rot.x; rot.y = -rot.y; rot.z = -rot.z; return rot; } void ComponentTransform::CleanUp() { parent = nullptr; } void ComponentTransform::Load(const JSON_Object* comp) { position.x = json_object_dotget_number(comp, "position.x"); position.y = json_object_dotget_number(comp, "position.y"); position.z = json_object_dotget_number(comp, "position.z"); scale.x = json_object_dotget_number(comp, "scale.x"); scale.y = json_object_dotget_number(comp, "scale.y"); scale.z = json_object_dotget_number(comp, "scale.z"); rotate_quat.w = json_object_dotget_number(comp, "rotate_quat.w"); rotate_quat.x = json_object_dotget_number(comp, "rotate_quat.x"); rotate_quat.y = json_object_dotget_number(comp, "rotate_quat.y"); rotate_quat.z = json_object_dotget_number(comp, "rotate_quat.z"); SetTransformRotation(rotate_quat); SetLocalTransform(); bool fromAINode = json_object_dotget_boolean(comp, "fromAINode"); std::string setname; if (!fromAINode) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { setname = "world_pos." + std::to_string(j + i * 4); world_pos.v[i][j] = json_object_dotget_number(comp, setname.c_str()); setname = "world_rot." + std::to_string(j + i * 4); world_rot.v[i][j] = json_object_dotget_number(comp, setname.c_str()); } } } } void ComponentTransform::Save(JSON_Array* comps) { JSON_Value* append = json_value_init_object(); JSON_Object* curr = json_value_get_object(append); json_object_dotset_number(curr, "properties.type", type); json_object_dotset_number(curr, "properties.position.x", position.x); json_object_dotset_number(curr, "properties.position.y", position.y); json_object_dotset_number(curr, "properties.position.z", position.z); json_object_dotset_number(curr, "properties.scale.x", scale.x); json_object_dotset_number(curr, "properties.scale.y", scale.y); json_object_dotset_number(curr, "properties.scale.z", scale.z); json_object_dotset_number(curr, "properties.rotate_quat.w", rotate_quat.w); json_object_dotset_number(curr, "properties.rotate_quat.x", rotate_quat.x); json_object_dotset_number(curr, "properties.rotate_quat.y", rotate_quat.y); json_object_dotset_number(curr, "properties.rotate_quat.z", rotate_quat.z); json_object_dotset_boolean(curr, "properties.fromAINode", false); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { std::string setname = "properties.world_pos." + std::to_string(j + i*4); json_object_dotset_number(curr, setname.c_str(), world_pos.v[i][j]); setname = "properties.world_rot." + std::to_string(j + i*4); json_object_dotset_number(curr, setname.c_str(), world_rot.v[i][j]); } } json_array_append_value(comps, append); }
28.656388
119
0.719139
MarcFly
bbd3514f31648310f957b4b1fcb9c0c7b60f944c
3,199
hpp
C++
src/Base/TaskProcessors/ThreadedTaskProcessor/ThreadedTaskProcessor.hpp
PhilipVinc/PincoSimulator
562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3
[ "MIT" ]
1
2017-10-23T13:22:01.000Z
2017-10-23T13:22:01.000Z
src/Base/TaskProcessors/ThreadedTaskProcessor/ThreadedTaskProcessor.hpp
PhilipVinc/PincoSimulator
562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3
[ "MIT" ]
null
null
null
src/Base/TaskProcessors/ThreadedTaskProcessor/ThreadedTaskProcessor.hpp
PhilipVinc/PincoSimulator
562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3
[ "MIT" ]
null
null
null
// // Created by Filippo Vicentini on 20/12/2017. // #ifndef SIMULATOR_THREADEDTASKPROCESSOR_HPP #define SIMULATOR_THREADEDTASKPROCESSOR_HPP #include "Base/TaskProcessor.hpp" #include "Libraries/concurrentqueue.h" #include <chrono> #include <stdio.h> #include <queue> #include <vector> #include <thread> class Settings; class WorkerThread; class ThreadedTaskProcessor : public TaskProcessor { public: ThreadedTaskProcessor(std::string solverName, int _processes, int _max_processes = 0); virtual ~ThreadedTaskProcessor(); virtual void Setup() final; virtual void Update() final; // -------- Called From Workers ---------- // // Take a task from dispatchedTasks to execute it (called by a worker) std::vector<std::unique_ptr<TaskData>> GetDispatchedTasks(size_t th_id, size_t maxTasks =1); void GiveCompletedResults(size_t th_id, std::vector<TaskResults*> res); void GiveCompletedResults(size_t th_id, TaskResults* res); // -------------------------------------- // // Return a completed task, to add it to elaboratedTasks void GiveResults(size_t th_id, std::unique_ptr<TaskResults> task); void GiveResults(size_t th_id, std::vector<std::unique_ptr<TaskResults>>&& tasks); // Method called by a thread to inform the manager that he is now dead // and can be joined. void ReportThreadTermination(size_t th_id); virtual void AllProducersHaveBeenTerminated() final; void Terminate(); void TerminateWhenDone(); protected: // Redef size_t nTasksEnqueued = 0; // Threading support size_t nThreads = 1; #ifdef GPU_SUPPORT size_t nGPUThreads = 0; size_t nAvailableGPUs = 0; #endif // --- old--- size_t nTasksLeftToEnqueue = 0; size_t nTasksToSave = 0; size_t nTasksFillCapacity = 1; mutable size_t nCompletedTasks = 0; size_t nTotalTasks = 0; private: size_t nextWorkerId = 0; std::vector<size_t> activeThreads; std::queue<size_t> unactivatedThreadPool; moodycamel::ConcurrentQueue<size_t> threadsToJoin; std::vector<std::thread> threads; std::vector<WorkerThread*> workers; std::vector<size_t> workerProducerID; std::vector<size_t> workerCompletedTasks; bool terminate = false; bool terminateWhenDone = false; void CreateWorker(Solver* solver); void TerminateWorker(size_t i); void TerminateWorkerWhenDone(size_t i); void TerminateAllWorkers(); void TerminateAllWorkersWhenDone(); void JoinThread(size_t th_id); // Optimizer Stuff void EnableProfilingInWorkers(); void DisableProfilingInWorkers(); void ComputeAverageSpeed(); bool profiling = true; size_t maxProcesses = 0; float averageTaskComputationTime = 0.0; int sleepTimeMs = 1000; std::chrono::system_clock::time_point lastOptTime; std::chrono::system_clock::time_point lastPrintTime; std::chrono::system_clock::time_point startTime; std::chrono::system_clock::duration deltaTOpt; std::chrono::system_clock::duration deltaTPrint; // Printing stuff size_t lastMsgLength = 0; public: void ReportAverageSpeed(float speed) ; virtual size_t NumberOfCompletedTasks() const final; virtual float Progress() const final; }; #endif //SIMULATOR_THREADEDTASKPROCESSOR_HPP
27.577586
93
0.732416
PhilipVinc
bbdd1c2c1435f0fe5ac925a4c85998505813e3aa
53
cpp
C++
HttpFramework/HttpCookieStorage.cpp
a1q123456/HttpFramework
debefffbb1283ae0f0277cc1b597237933bb47f7
[ "MIT" ]
null
null
null
HttpFramework/HttpCookieStorage.cpp
a1q123456/HttpFramework
debefffbb1283ae0f0277cc1b597237933bb47f7
[ "MIT" ]
null
null
null
HttpFramework/HttpCookieStorage.cpp
a1q123456/HttpFramework
debefffbb1283ae0f0277cc1b597237933bb47f7
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "HttpCookieStorage.h"
10.6
30
0.735849
a1q123456
bbe130758cf8f984e00194113eb3eb9b908ba256
7,001
hpp
C++
include/CPreProcessor.hpp
icebreakersentertainment/ice_engine
52a8313bc266c053366bdf554b5dc27a54ddcb25
[ "MIT" ]
null
null
null
include/CPreProcessor.hpp
icebreakersentertainment/ice_engine
52a8313bc266c053366bdf554b5dc27a54ddcb25
[ "MIT" ]
null
null
null
include/CPreProcessor.hpp
icebreakersentertainment/ice_engine
52a8313bc266c053366bdf554b5dc27a54ddcb25
[ "MIT" ]
1
2019-06-11T03:41:48.000Z
2019-06-11T03:41:48.000Z
#ifndef CPREPROCESSOR_H #define CPREPROCESSOR_H #if !defined(BOOST_WAVE_CUSTOM_DIRECTIVES_HOOKS_INCLUDED) #define BOOST_WAVE_CUSTOM_DIRECTIVES_HOOKS_INCLUDED #include <cstdio> #include <iostream> #include <ostream> #include <string> #include <algorithm> #include <utility> #include <unordered_map> #include <boost/algorithm/string.hpp> #include <boost/assert.hpp> #include <boost/config.hpp> // Need to include this before other wave/phoenix includes // @see https://groups.google.com/forum/#!msg/boost-list/3xZDWUyTJG0/IEF2wTy1EIsJ #include <boost/phoenix/core/limits.hpp> #include <boost/wave/token_ids.hpp> #include <boost/wave/util/macro_helpers.hpp> #include <boost/wave/preprocessing_hooks.hpp> #include <boost/wave/cpp_iteration_context.hpp> #include <iterator> #include <fstream> #if defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS) #include <sstream> #endif #include <boost/wave/wave_config.hpp> #include <boost/wave/cpp_exceptions.hpp> #include <boost/wave/language_support.hpp> #include <boost/wave/util/file_position.hpp> #include "Types.hpp" #include "fs/IFileSystem.hpp" #include "logger/ILogger.hpp" namespace wave = boost::wave; namespace alg = boost::algorithm; namespace ice_engine { /** * This class is a generic pre processor for C like code. */ class CPreProcessor : public wave::context_policies::default_preprocessing_hooks { public: CPreProcessor(fs::IFileSystem* fileSystem, logger::ILogger* logger, const std::unordered_map<std::string, std::string>& includeOverrides = {}); /** * Processess the source code. * * @param defineMap this is an optional map that can contain any extra/special #defines that have been * defined. */ std::string process(std::string source, const std::unordered_map<std::string, std::string>& defineMap = {}, const bool autoIncludeGuard = false, const bool preserveLineNumbers = false); /* Below is a bunch of Boost Wave call-back functions */ template <typename ContextT, typename ContainerT> bool found_unknown_directive(ContextT const& ctx, ContainerT const& line, ContainerT& pending); template <typename ContextT, typename ContainerT> bool emit_line_directive(ContextT const & ctx, ContainerT & pending, typename ContextT::token_type const & act_token); template <typename ContextT> bool locate_include_file(ContextT& ctx, std::string&file_path, bool is_system, char const*current_name, std::string&dir_path, std::string&native_name); template <typename ContextT> void opened_include_file(ContextT const& ctx, std::string const& relname, std::string const& filename, bool is_system_include); template <typename ContextT> void returning_from_include_file(ContextT const& ctx); template <typename ContextT> bool found_include_directive(ContextT const& ctx, std::string const& filename, bool include_next); template <typename ContextT, typename TokenT> void skipped_token(ContextT const& ctx, TokenT const& token); template <typename ContextT, typename TokenT> TokenT const& generated_token(ContextT const &ctx, TokenT const& token); template <typename ContextT, typename TokenT, typename ContainerT> bool evaluated_conditional_expression( ContextT const &ctx, TokenT const& directive, ContainerT const& expression, bool expression_value); template <typename ContextT, typename TokenT> bool found_directive(ContextT const& ctx, TokenT const& directive); /** * Inner class to do the loading of a file. */ template <typename IterContextT> class inner { public: template <typename PositionT> static void init_iterators(IterContextT& iter_ctx, PositionT const& act_pos, wave::language_support language) { typedef typename IterContextT::iterator_type iterator_type; // std::cout << "init_iterators: " << iter_ctx.filename << std::endl; const auto filename = std::string(iter_ctx.filename.c_str()); { const auto it = CPreProcessor::staticIncludeOverrides_.find(filename); if (it != CPreProcessor::staticIncludeOverrides_.end()) { iter_ctx.instring = it->second; } else { iter_ctx.instring = CPreProcessor::staticFileSystem_->readAll(filename); } } // read in the file // std::ifstream instream(iter_ctx.filename.c_str()); // if ( !instream.is_open()) // { //// BOOST_WAVE_THROW_CTX(iter_ctx.ctx, wave::preprocess_exception, wave::bad_include_file, iter_ctx.filename.c_str(), act_pos); // return; // } // instream.unsetf(std::ios::skipws); // // iter_ctx.instring.assign( // std::istreambuf_iterator<char>(instream.rdbuf()), // std::istreambuf_iterator<char>() // ); // ensure our input string ends with a newline (if we don't then boost wave generates a newline token after the include directive finishes) auto it = iter_ctx.instring.end(); if (*(--it) != *boost::wave::get_token_value(boost::wave::T_NEWLINE)) { iter_ctx.instring += boost::wave::get_token_value(boost::wave::T_NEWLINE); } iter_ctx.first = iterator_type( iter_ctx.instring.begin(), iter_ctx.instring.end(), PositionT(iter_ctx.filename), language ); iter_ctx.last = iterator_type(); } private: std::string instring; }; private: protected: bool preserveLineNumbers_ = false; bool autoIncludeGuard_ = false; uint32 conditionalDepth_ = 0; uint32 conditionalAllowNewlineDepth_ = 0; bool inDefine_ = false; uint32 numIncludes_ = 0; std::unordered_map<std::string, bool> includedFiles_; std::unordered_map<std::string, std::string> includeOverrides_; fs::IFileSystem* fileSystem_; logger::ILogger* logger_; static std::unordered_map<std::string, std::string> staticIncludeOverrides_; static fs::IFileSystem* staticFileSystem_; static logger::ILogger* staticLogger_; /* * We make this a shared pointer so that when the context object makes a copy of `this`, * it will be using the same outputStringStream_. */ std::shared_ptr<std::stringstream> outputStringStream_; bool locateIncludeFile(const std::string& currentDirectory, /*const std::string& basePath,*/ std::string& filePath, bool isSystem, char const* currentName, std::string& dirPath, std::string& nativeName); std::string toCanonicalPath(const std::string& currentDirectory, const std::string& filename); }; } #include "CPreProcessor.inl" #endif // !defined(BOOST_WAVE_ADVANCED_PREPROCESSING_HOOKS_INCLUDED) #endif /* CPREPROCESSOR_H */
35.180905
207
0.682474
icebreakersentertainment
bbe2cb86a39c0e9f769e98353c3d5a8c69a8506b
920
cpp
C++
SE/Source/Maths/Vector4D.cpp
NahuCF/SE
6b17be4bc05b114a9090da35756a587693cc00e5
[ "WTFPL" ]
1
2021-04-23T14:53:42.000Z
2021-04-23T14:53:42.000Z
SE/Source/Maths/Vector4D.cpp
NahuCF/SE
6b17be4bc05b114a9090da35756a587693cc00e5
[ "WTFPL" ]
null
null
null
SE/Source/Maths/Vector4D.cpp
NahuCF/SE
6b17be4bc05b114a9090da35756a587693cc00e5
[ "WTFPL" ]
null
null
null
#include "pch.h" #include "Vector4D.h" namespace lptm { Vector4D::Vector4D() { x = 0.0f; y = 0.0f; z = 0.0f; w = 0.0f; }; Vector4D::Vector4D(float x, float y, float z, float w) { this->x = x; this->y = y; this->z = z; this->w = w; } Vector4D& Vector4D::Add(const Vector4D& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } Vector4D& Vector4D::Multiply(const Vector4D& other) { return *this; } Vector4D Vector4D::operator+(const Vector4D& other) { return Vector4D(x + other.x, y + other.y, z + other.z, w + other.w); } Vector4D& Vector4D::operator+=(const Vector4D& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } Vector4D Vector4D::operator*(const Vector4D& other) { return Multiply(other); } Vector4D& Vector4D::operator*=(const Vector4D& other) { return Multiply(other); } }
14.83871
70
0.596739
NahuCF
bbe35a73de57f0577e102744972e21562c62f203
6,586
cpp
C++
cpp/src/msg_server/FileServConn.cpp
KevinHM/TTServer
c3a8dcb7e0d2dd0d3fc88ff919019ca5f0a81306
[ "Apache-2.0" ]
22
2015-05-02T11:21:32.000Z
2022-03-04T09:58:19.000Z
cpp/src/msg_server/FileServConn.cpp
luyongfugx/TTServer
c3a8dcb7e0d2dd0d3fc88ff919019ca5f0a81306
[ "Apache-2.0" ]
null
null
null
cpp/src/msg_server/FileServConn.cpp
luyongfugx/TTServer
c3a8dcb7e0d2dd0d3fc88ff919019ca5f0a81306
[ "Apache-2.0" ]
21
2015-01-02T01:21:04.000Z
2021-05-12T09:52:54.000Z
// // FileServConn.cpp // public_TTServer // // Created by luoning on 14-8-19. // Copyright (c) 2014年 luoning. All rights reserved. // #include "FileServConn.h" #include "FileHandler.h" #include "util.h" #include "ImUser.h" #include "AttachData.h" #include "RouteServConn.h" #include "MsgConn.h" static ConnMap_t g_file_server_conn_map; static serv_info_t* g_file_server_list; static uint32_t g_file_server_count; static CFileHandler* s_file_handler = NULL; void file_server_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam) { ConnMap_t::iterator it_old; CFileServConn* pConn = NULL; uint64_t cur_time = get_tick_count(); for (ConnMap_t::iterator it = g_file_server_conn_map.begin(); it != g_file_server_conn_map.end(); ) { it_old = it; it++; pConn = (CFileServConn*)it_old->second; pConn->OnTimer(cur_time); } // reconnect FileServer serv_check_reconnect<CFileServConn>(g_file_server_list, g_file_server_count); } void init_file_serv_conn(serv_info_t* server_list, uint32_t server_count) { g_file_server_list = server_list; g_file_server_count = server_count; serv_init<CFileServConn>(g_file_server_list, g_file_server_count); netlib_register_timer(file_server_conn_timer_callback, NULL, 1000); s_file_handler = CFileHandler::getInstance(); } bool is_file_server_available() { CFileServConn* pConn = NULL; for (uint32_t i = 0; i < g_file_server_count; i++) { pConn = (CFileServConn*)g_file_server_list[i].serv_conn; if (pConn && pConn->IsOpen()) { return true; } } return false; } // CFileServConn* get_random_file_serv_conn() { CFileServConn* pConn = NULL; CFileServConn* pConnTmp = NULL; if (0 == g_file_server_count) { return pConn; } int32_t random_num = rand() % g_file_server_count; pConnTmp = (CFileServConn*)g_file_server_list[random_num].serv_conn; if (pConnTmp && pConnTmp->IsOpen()) { pConn = pConnTmp; } else { for (uint32_t i = 0; i < g_file_server_count; i++) { int j = (random_num + 1) % g_file_server_count; pConnTmp = (CFileServConn*)g_file_server_list[j].serv_conn; if (pConnTmp && pConnTmp->IsOpen()) { pConn = pConnTmp; } } } return pConn; } CFileServConn::CFileServConn() { m_bOpen = false; m_serv_idx = 0; } CFileServConn::~CFileServConn() { } void CFileServConn::Connect(const char* server_ip, uint16_t server_port, uint32_t idx) { log("Connecting to FileServer %s:%d\n", server_ip, server_port); m_serv_idx = idx; m_handle = netlib_connect(server_ip, server_port, imconn_callback, (void*)&g_file_server_conn_map); if (m_handle != NETLIB_INVALID_HANDLE) { g_file_server_conn_map.insert(make_pair(m_handle, this)); } } void CFileServConn::Close() { serv_reset<CFileServConn>(g_file_server_list, g_file_server_count, m_serv_idx); m_bOpen = false; if (m_handle != NETLIB_INVALID_HANDLE) { netlib_close(m_handle); g_file_server_conn_map.erase(m_handle); } ReleaseRef(); } void CFileServConn::OnConfirm() { log("connect to file server success\n"); m_bOpen = true; m_connect_time = get_tick_count(); g_file_server_list[m_serv_idx].reconnect_cnt = MIN_RECONNECT_CNT / 2; CImPduFileServerIPReq pdu; //SendPdu(&pdu); } void CFileServConn::OnClose() { log("onclose from file server handle=%d\n", m_handle); Close(); } void CFileServConn::OnTimer(uint64_t curr_tick) { if (curr_tick > m_last_send_tick + SERVER_HEARTBEAT_INTERVAL) { CImPduHeartbeat pdu; SendPdu(&pdu); } if (curr_tick > m_last_recv_tick + SERVER_TIMEOUT) { log("conn to file server timeout\n"); Close(); } } void CFileServConn::HandlePdu(CImPdu* pPdu) { switch (pPdu->GetPduType()) { case IM_PDU_TYPE_HEARTBEAT: break; case IM_PDU_TYPE_MSG_FILE_TRANSFER_RSP: _HandleFileMsgTransRsp((CImPduMsgFileTransferRsp*) pPdu); break; case IM_PDU_TYPE_FILE_SERVER_IP_REQUEST: _HandleFileServerIPRsp((CImPduFileServerIPRsp*)pPdu); break; default: log("unknown pdu_type=%d\n", pPdu->GetPduType()); break; } } void CFileServConn::_HandleFileMsgTransRsp(CImPduMsgFileTransferRsp* pPdu) { uint32_t result = pPdu->GetResult(); uint32_t from_id = pPdu->GetFromId(); uint32_t to_id = pPdu->GetToId(); string file_name(pPdu->GetFileName(), pPdu->GetFileNameLength()); uint32_t file_size = pPdu->GetFileLength(); string listen_ip(pPdu->GetFileServerIp(), pPdu->GetFileServerIpLength()); uint16_t listen_port = pPdu->GetFileServerPort(); string task_id(pPdu->GetTaskId(), pPdu->GetTaskIdLen()); CPduAttachData attach(pPdu->GetAttachData(), pPdu->GetAttachLen()); CImPduClientFileResponse pdu(result, idtourl(from_id), idtourl(to_id), file_name.c_str(), task_id.c_str(), listen_ip.c_str(), listen_port); pdu.SetReserved(pPdu->GetReserved()); uint32_t handle = attach.GetHandle(); log("HandleFileMsgTransRsp, result: %u, from_user_id: %u, to_user_id: %u, file_name: %s, \ task_id: %s, listen_ip: %s, listen_port: %u.\n", result, from_id, to_id, file_name.c_str(), task_id.c_str(), listen_ip.c_str(), listen_port); CMsgConn* pFromConn = CImUserManager::GetInstance()->GetMsgConnByHandle(from_id, handle); if (pFromConn) { pFromConn->SendPdu(&pdu); } if (result == 0) { //send notify to target user CImUser* pToUser = CImUserManager::GetInstance()->GetImUserById(to_id); if (pToUser) { CImPduClientFileNotify pdu2(idtourl(from_id), idtourl(to_id), file_name.c_str(), file_size, task_id.c_str(), listen_ip.c_str(), listen_port); pToUser->BroadcastPdu(&pdu2); } //send to route server CRouteServConn* pRouteConn = get_route_serv_conn(); if (pRouteConn) { CImPduFileNotify pdu3(from_id, to_id, file_name.c_str(), file_size, task_id.c_str(), listen_ip.c_str(), listen_port); pRouteConn->SendPdu(&pdu3); } } } void CFileServConn::_HandleFileServerIPRsp(CImPduFileServerIPRsp* pPdu) { uint32_t ip_addr_cnt = pPdu->GetIPCnt(); ip_addr_t* ip_addr_list = pPdu->GetIPList(); for (uint32_t i = 0; i < ip_addr_cnt ; i++) { m_ip_list.push_back(ip_addr_list[i]); } }
28.387931
103
0.669602
KevinHM
bbeb3552b80935887cbfb333214abf80ac19950b
21,059
hpp
C++
polympc/src/solvers/admm.hpp
alexandreguerradeoliveira/rocket_gnc
164e96daca01d9edbc45bfaac0f6b55fe7324f24
[ "MIT" ]
null
null
null
polympc/src/solvers/admm.hpp
alexandreguerradeoliveira/rocket_gnc
164e96daca01d9edbc45bfaac0f6b55fe7324f24
[ "MIT" ]
null
null
null
polympc/src/solvers/admm.hpp
alexandreguerradeoliveira/rocket_gnc
164e96daca01d9edbc45bfaac0f6b55fe7324f24
[ "MIT" ]
null
null
null
// This file is part of PolyMPC, a lightweight C++ template library // for real-time nonlinear optimization and optimal control. // // Copyright (C) 2020 Listov Petr <petr.listov@epfl.ch> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef ADMM_HPP #define ADMM_HPP #include "qp_base.hpp" template<int N, int M, typename Scalar = double, int MatrixType = DENSE, template <typename, int, typename... Args> class LinearSolver = linear_solver_traits<DENSE>::default_solver, int LinearSolver_UpLo = Eigen::Lower, typename ...Args> class ADMM : public QPBase<ADMM<N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>, N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo> { using Base = QPBase<ADMM<N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>, N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>; public: using scalar_t = typename Base::scalar_t; using qp_var_t = typename Base::qp_var_t; using qp_dual_t = typename Base::qp_dual_t; using qp_dual_a_t = typename Base::qp_dual_a_t; using qp_constraint_t = typename Base::qp_constraint_t; using qp_hessian_t = typename Base::qp_hessian_t; /** specific for OSQP splitting */ using kkt_mat_t = typename std::conditional<MatrixType == SPARSE, Eigen::SparseMatrix<scalar_t>, typename dense_matrix_type_selector<scalar_t, 2 * N + M, 2 * N + M>::type>::type; using kkt_vec_t = typename dense_matrix_type_selector<scalar_t, 2 * N + M, 1>::type; using linear_solver_t = LinearSolver<kkt_mat_t, LinearSolver_UpLo, Args...>; //typename Base::linear_solver_t; using admm_dual_t = typename dense_matrix_type_selector<scalar_t, N + M, 1>::type; using admm_constraint_t = typename std::conditional<MatrixType == SPARSE, Eigen::SparseMatrix<scalar_t>, typename dense_matrix_type_selector<scalar_t, N + M, N>::type>::type; template<int MatrixFMT = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == DENSE>::type allocate_kkt_matrix() noexcept { if(m_K.RowsAtCompileTime == Eigen::Dynamic) m_K = kkt_mat_t::Zero(2 * N + M, 2 * N + M); } /** no pre-allocate needed for sparse KKT system */ template<int MatrixFMT = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == SPARSE>::type allocate_kkt_matrix() const noexcept {} template<int MatrixFMT = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == DENSE>::type allocate_jacobian() noexcept { if(m_A.RowsAtCompileTime == Eigen::Dynamic) m_A = admm_constraint_t::Zero(N + M, N); } template<int MatrixFMT = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == SPARSE>::type allocate_jacobian() const noexcept {} public: ADMM() : Base() { /** intialise some variables */ m_rho_vec = admm_dual_t::Constant(this->m_settings.rho); m_rho_inv_vec = admm_dual_t::Constant(scalar_t(1/this->m_settings.rho)); /** allocate space for the KKT matrix if necessary */ allocate_kkt_matrix(); /** allocate memory for Jacobian */ allocate_jacobian(); } ~ADMM() = default; /** ADMM specific */ qp_var_t m_x_tilde; admm_dual_t m_z, m_z_tilde, m_z_prev; admm_dual_t m_rho_vec, m_rho_inv_vec; scalar_t rho; int iter{0}; scalar_t res_prim; scalar_t res_dual; /** ADMM specific */ static constexpr scalar_t RHO_MIN = 1e-6; static constexpr scalar_t RHO_MAX = 1e+6; static constexpr scalar_t RHO_TOL = 1e-4; static constexpr scalar_t RHO_EQ_FACTOR = 1e+3; /** ADMM specific */ scalar_t m_max_Ax_z_norm; scalar_t m_max_Hx_ATy_h_norm; /** solver part */ kkt_mat_t m_K; admm_constraint_t m_A; linear_solver_t linear_solver; Eigen::VectorXi _kkt_mat_nnz, _A_mat_nnz; status_t solve_impl(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const qp_var_t>& h, const Eigen::Ref<const qp_constraint_t>& A, const Eigen::Ref<const qp_dual_a_t>& Alb, const Eigen::Ref<const qp_dual_a_t>& Aub, const Eigen::Ref<const qp_var_t>& xl, const Eigen::Ref<const qp_var_t>& xu) noexcept { return solve_impl(H, h, A, Alb, Aub, xl, xu, qp_var_t::Zero(N,1), qp_dual_t::Zero(M+N,1)); } status_t solve_impl(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const qp_var_t>& h, const Eigen::Ref<const qp_constraint_t>& A, const Eigen::Ref<const qp_dual_a_t>& Alb, const Eigen::Ref<const qp_dual_a_t>& Aub, const Eigen::Ref<const qp_var_t>& xl, const Eigen::Ref<const qp_var_t>& xu, const Eigen::Ref<const qp_var_t>& x_guess, const Eigen::Ref<const qp_dual_t>& y_guess) noexcept { /** setup part */ kkt_vec_t rhs, x_tilde_nu; bool check_termination = false; this->m_x = x_guess; this->m_y = y_guess; /** @bug : create Sparse m_A matrix */ construct_A(A); this->m_z.noalias() = m_A * x_guess; /** Set QP constraint type */ this->parse_constraints_bounds(Alb, Aub, xl, xu); /** initialize step size (rho) vector */ rho_vec_update(this->m_settings.rho); /** construct KKT matrix (m_K) and compute decomposition */ construct_kkt_matrix(H, m_A); factorise_kkt_matrix(); this->m_info.status = UNSOLVED; /** run ADMM iterations */ for (iter = 1; iter <= this->m_settings.max_iter; iter++) { m_z_prev = m_z; /** update x_tilde z_tilde */ compute_kkt_rhs(h, rhs); x_tilde_nu = linear_solver.solve(rhs); m_x_tilde = x_tilde_nu.template head<N>(); m_z_tilde = m_z_prev + m_rho_inv_vec.cwiseProduct(x_tilde_nu.template tail<M + N>() - this->m_y); /** update x */ this->m_x.noalias() = this->m_settings.alpha * m_x_tilde + (1 - this->m_settings.alpha) * this->m_x; /** update z */ m_z.noalias() = this->m_settings.alpha * m_z_tilde; m_z.noalias() += (1 - this->m_settings.alpha) * m_z_prev + m_rho_inv_vec.cwiseProduct(this->m_y); box_projection(m_z, Alb, Aub, xl, xu); // euclidean projection /** update y (dual) */ this->m_y.noalias() += m_rho_vec.cwiseProduct(this->m_settings.alpha * m_z_tilde + (1 - this->m_settings.alpha) * m_z_prev - m_z); if (this->m_settings.check_termination != 0 && iter % this->m_settings.check_termination == 0) check_termination = true; else check_termination = false; /** check convergence */ if (check_termination) { residuals_update(H, h, A); if (termination_criteria()) { this->m_info.status = SOLVED; break; } } if (this->m_settings.adaptive_rho && iter % this->m_settings.adaptive_rho_interval == 0) { // state was not yet updated if (!check_termination) residuals_update(H, h, A); /** adjust rho value and refactorise the KKT matrix */ scalar_t new_rho = estimate_rho(rho); new_rho = fmax(RHO_MIN, fmin(new_rho, RHO_MAX)); this->m_info.rho_estimate = new_rho; if (new_rho < rho / this->m_settings.adaptive_rho_tolerance || new_rho > rho * this->m_settings.adaptive_rho_tolerance) { rho_vec_update(new_rho); update_kkt_rho(); /* Note: KKT Sparsity pattern unchanged by rho update. Only factorize. */ factorise_kkt_matrix(); } } /** std::cout << "admm iter: " << iter << " | " << this->m_x.transpose() << " | " << this->m_y.transpose() << " | " << this->m_info.res_prim << " | " << this->m_info.res_dual << " | " << m_rho_vec.transpose() << "\n"; */ } if (iter > this->m_settings.max_iter) this->m_info.status = MAX_ITER_EXCEEDED; this->m_info.iter = iter; return this->m_info.status; } /** construct extended A matrix: Ae = [A E] */ template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == DENSE>::type construct_A(const Eigen::Ref<const qp_constraint_t>& A) noexcept { m_A.template block<M, N>(0,0) = A; m_A.template block<N,N>(M,0).setIdentity(); } template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type construct_A(const Eigen::Ref<const qp_constraint_t>& A) noexcept { if(this->settings().reuse_pattern) { /** copy the new A block */ for(Eigen::Index k = 0; k < N; ++k) std::copy_n(A.valuePtr() + A.outerIndexPtr()[k], A.innerNonZeroPtr()[k], m_A.valuePtr() + m_A.outerIndexPtr()[k]); } else { m_A.resize(N + M, N); _A_mat_nnz = Eigen::VectorXi::Constant(N, 1); // allocate box constraints std::transform(_A_mat_nnz.data(), _A_mat_nnz.data() + N, A.innerNonZeroPtr(), _A_mat_nnz.data(), std::plus<scalar_t>()); // reserve the memory m_A.reserve(_A_mat_nnz); block_insert_sparse(m_A, 0, 0, A); //insert A matrix for(Eigen::Index i = 0; i < N; ++i) m_A.coeffRef(i + M, i) = scalar_t(1); // insert identity matrix } } template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == DENSE>::type construct_kkt_matrix(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept { eigen_assert(LinearSolver_UpLo == Eigen::Lower || LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower)); m_K.template topLeftCorner<N, N>() = H; m_K.template topLeftCorner<N, N>().diagonal() += qp_var_t::Constant(N, this->m_settings.sigma); if (LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower)) m_K.template topRightCorner<N, M + N>() = A.transpose(); m_K.template bottomLeftCorner<M + N, N>() = A; m_K.template bottomRightCorner<M + N, M + N>() = scalar_t(-1) * m_rho_inv_vec.asDiagonal(); } /** sparse implementation */ template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type construct_kkt_matrix(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept { if(this->settings().reuse_pattern) construct_kkt_matrix_same_pattern(H,A); else { construct_kkt_matrix_sparse(H, A); linear_solver.analyzePattern(m_K); } } template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type construct_kkt_matrix_sparse(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept { /** worst case scenario */ const int kkt_size = 2 * N + M; m_K.resize(kkt_size, kkt_size); /** estimate number of nonzeros */ _kkt_mat_nnz = Eigen::VectorXi::Constant(kkt_size, 1); // add nonzeros from H std::transform(_kkt_mat_nnz.data(), _kkt_mat_nnz.data() + N, H.innerNonZeroPtr(), _kkt_mat_nnz.data(), std::plus<scalar_t>()); // add nonzeros from A std::transform(_kkt_mat_nnz.data(), _kkt_mat_nnz.data() + N, A.innerNonZeroPtr(), _kkt_mat_nnz.data(), std::plus<scalar_t>()); // reserve the space and insert values from H and A if(LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower)) { // reserve more memory _estimate_nnz_in_row(_kkt_mat_nnz, A); m_K.reserve(_kkt_mat_nnz); block_insert_sparse(m_K, 0, 0, H); block_insert_sparse(m_K, N, 0, A); block_insert_sparse(m_K, 0, N, A.transpose()); } else { m_K.reserve(_kkt_mat_nnz); block_insert_sparse(m_K, 0, 0, H); block_insert_sparse(m_K, N, 0, A); } // add diagonal blocks*/ for(Eigen::Index i = 0; i < N; ++i) m_K.coeffRef(i, i) += this->m_settings.sigma; for(Eigen::Index i = 0; i < N + M; ++i) m_K.coeffRef(N + i, N + i) = -m_rho_inv_vec(i); } /** make faster update if sparsity pattern has not changed */ template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type construct_kkt_matrix_same_pattern(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept { /** just copy content of nonzero vectors*/ // copy H and A blocks for(Eigen::Index k = 0; k < N; ++k) { std::copy_n(H.valuePtr() + H.outerIndexPtr()[k], H.innerNonZeroPtr()[k], m_K.valuePtr() + m_K.outerIndexPtr()[k]); std::copy_n(A.valuePtr() + A.outerIndexPtr()[k], A.innerNonZeroPtr()[k], m_K.valuePtr() + m_K.outerIndexPtr()[k] + H.innerNonZeroPtr()[k]); } // reserve the space and insert values from H and A if(LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower)) block_set_sparse(m_K, N, 0, A.transpose()); // add diagonal blocks*/ m_K.diagonal(). template head<N>() += qp_var_t::Constant(this->m_settings.sigma); m_K.diagonal(). template tail<M + N>() = -m_rho_inv_vec; } template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type block_insert_sparse(Eigen::SparseMatrix<scalar_t>& dst, const Eigen::Index &row_offset, const Eigen::Index &col_offset, const Eigen::SparseMatrix<scalar_t>& src) const noexcept { // assumes enough spase is allocated in the dst matrix for(Eigen::Index k = 0; k < src.outerSize(); ++k) for (typename Eigen::SparseMatrix<scalar_t>::InnerIterator it(src, k); it; ++it) dst.insert(row_offset + it.row(), col_offset + it.col()) = it.value(); } template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type block_set_sparse(Eigen::SparseMatrix<scalar_t>& dst, const Eigen::Index &row_offset, const Eigen::Index &col_offset, const Eigen::SparseMatrix<scalar_t>& src) const noexcept { // assumes enough spase is allocated in the dst matrix for(Eigen::Index k = 0; k < src.outerSize(); ++k) for (typename Eigen::SparseMatrix<scalar_t>::InnerIterator it(src, k); it; ++it) dst.insert(row_offset + it.row(), col_offset + it.col()) = it.value(); } /** workaround function to estimate number of nonzeros */ template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type _estimate_nnz_in_row(Eigen::Ref<Eigen::VectorXi> nnz, const qp_constraint_t& A) const noexcept { for (Eigen::Index k = 0; k < A.outerSize(); ++k) for(typename qp_constraint_t::InnerIterator it(A, k); it; ++it) nnz(it.row() + N) += scalar_t(1); } template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == DENSE>::type factorise_kkt_matrix() noexcept { /** try implace decomposition */ linear_solver.compute(m_K); eigen_assert(linear_solver.info() == Eigen::Success); } template<int T = MatrixType> EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type factorise_kkt_matrix() noexcept { /** try implace decomposition */ linear_solver.factorize(m_K); eigen_assert(linear_solver.info() == Eigen::Success); } EIGEN_STRONG_INLINE void compute_kkt_rhs(const Eigen::Ref<const qp_var_t>& h, Eigen::Ref<kkt_vec_t> rhs) const noexcept { rhs.template head<N>() = this->m_settings.sigma * this->m_x - h; rhs.template tail<M + N>() = m_z - m_rho_inv_vec.cwiseProduct(this->m_y); } EIGEN_STRONG_INLINE void box_projection(Eigen::Ref<admm_dual_t> x, const Eigen::Ref<const qp_dual_a_t>& lba, const Eigen::Ref<const qp_dual_a_t>& uba, const Eigen::Ref<const qp_var_t>& lbx, const Eigen::Ref<const qp_var_t>& ubx) const noexcept { x.template head<M>() = x.template head<M>().cwiseMax(lba).cwiseMin(uba); x.template tail<N>() = x.template tail<N>().cwiseMax(lbx).cwiseMin(ubx); } EIGEN_STRONG_INLINE void rho_vec_update(const scalar_t& rho0) noexcept { for (int i = 0; i < qp_dual_a_t::RowsAtCompileTime; i++) { switch (this->constr_type[i]) { case Base::constraint_type::LOOSE_BOUNDS: m_rho_vec(i) = RHO_MIN; break; case Base::constraint_type::EQUALITY_CONSTRAINT: m_rho_vec(i) = RHO_EQ_FACTOR * rho0; break; case Base::constraint_type::INEQUALITY_CONSTRAINT: /* fall through */ default: m_rho_vec(i) = rho0; }; } /** box constraints */ for (int i = 0; i < qp_var_t::RowsAtCompileTime; i++) { switch (this->box_constr_type[i]) { case Base::constraint_type::LOOSE_BOUNDS: m_rho_vec(i + M) = RHO_MIN; break; case Base::constraint_type::EQUALITY_CONSTRAINT: m_rho_vec(i + M) = RHO_EQ_FACTOR * rho0; break; case Base::constraint_type::INEQUALITY_CONSTRAINT: /* fall through */ default: m_rho_vec(i + M) = rho0; }; } m_rho_inv_vec = m_rho_vec.cwiseInverse(); rho = rho0; this->m_info.rho_updates += 1; } void residuals_update(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const qp_var_t>& h, const Eigen::Ref<const qp_constraint_t>& A) noexcept { scalar_t norm_Ax, norm_z; norm_Ax = (A * this->m_x).template lpNorm<Eigen::Infinity>(); norm_Ax = fmax(norm_Ax, this->m_x.template tail<N>().template lpNorm<Eigen::Infinity>()); norm_z = m_z.template lpNorm<Eigen::Infinity>(); m_max_Ax_z_norm = fmax(norm_Ax, norm_z); scalar_t norm_Hx, norm_ATy, norm_h, norm_y_box; norm_Hx = (H * this->m_x).template lpNorm<Eigen::Infinity>(); norm_ATy = (this->m_y.template head<M>().transpose() * A).template lpNorm<Eigen::Infinity>(); norm_h = h.template lpNorm<Eigen::Infinity>(); norm_y_box = this->m_y.template tail<N>().template lpNorm<Eigen::Infinity>(); m_max_Hx_ATy_h_norm = fmax(norm_Hx, fmax(norm_ATy, fmax(norm_h, norm_y_box))); this->m_info.res_prim = this->primal_residual(A, this->m_x, m_z.template head<M>()); scalar_t box_norm = (this->m_x - m_z.template tail<N>()).template lpNorm<Eigen::Infinity>(); this->m_info.res_prim = fmax(this->m_info.res_prim, box_norm); this->m_info.res_dual = this->dual_residual(H, h, A, this->m_x, this->m_y); } EIGEN_STRONG_INLINE scalar_t eps_prim() const noexcept { return this->m_settings.eps_abs + this->m_settings.eps_rel * m_max_Ax_z_norm; } EIGEN_STRONG_INLINE scalar_t eps_dual() const noexcept { return this->m_settings.eps_abs + this->m_settings.eps_rel * m_max_Hx_ATy_h_norm; } EIGEN_STRONG_INLINE bool termination_criteria() const noexcept { // check residual norms to detect optimality return (this->m_info.res_prim <= eps_prim() && this->m_info.res_dual <= eps_dual()) ? true : false; } EIGEN_STRONG_INLINE scalar_t estimate_rho(const scalar_t& rho0) const noexcept { scalar_t rp_norm, rd_norm; rp_norm = this->m_info.res_prim / (m_max_Ax_z_norm + this->DIV_BY_ZERO_REGUL); rd_norm = this->m_info.res_dual / (m_max_Hx_ATy_h_norm + this->DIV_BY_ZERO_REGUL); scalar_t rho_new = rho0 * sqrt(rp_norm / (rd_norm + this->DIV_BY_ZERO_REGUL)); return rho_new; } EIGEN_STRONG_INLINE void update_kkt_rho() noexcept { m_K.diagonal(). template tail<N + M>() = -m_rho_inv_vec; //m_K.template bottomRightCorner<M + N, M + N>() = -1.0 * m_rho_inv_vec.asDiagonal(); } }; #endif // ADMM_HPP
41.373281
151
0.605632
alexandreguerradeoliveira
bbeee88e430aeae5c0b205f0569d88271a17eb23
5,730
cpp
C++
Remixed/CompositorBase.cpp
LukeRoss00/Revive
09b1c59dfbff8abc06194809ec680b990b2cf21c
[ "MIT" ]
1
2021-10-18T19:43:06.000Z
2021-10-18T19:43:06.000Z
Remixed/CompositorBase.cpp
LukeRoss00/Revive
09b1c59dfbff8abc06194809ec680b990b2cf21c
[ "MIT" ]
null
null
null
Remixed/CompositorBase.cpp
LukeRoss00/Revive
09b1c59dfbff8abc06194809ec680b990b2cf21c
[ "MIT" ]
1
2020-02-03T22:45:41.000Z
2020-02-03T22:45:41.000Z
#include "CompositorBase.h" #include "Session.h" #include "FrameList.h" #include "OVR_CAPI.h" #include "microprofile.h" #include <vector> #include <algorithm> #include <winrt/Windows.Graphics.Holographic.h> using namespace winrt::Windows::Graphics::Holographic; MICROPROFILE_DEFINE(WaitToBeginFrame, "Compositor", "WaitFrame", 0x00ff00); MICROPROFILE_DEFINE(BeginFrame, "Compositor", "BeginFrame", 0x00ff00); MICROPROFILE_DEFINE(EndFrame, "Compositor", "EndFrame", 0x00ff00); MICROPROFILE_DEFINE(SubmitFovLayer, "Compositor", "SubmitFovLayer", 0x00ff00); CompositorBase::CompositorBase() : m_MirrorTexture(nullptr) , m_ChainCount(0) { } CompositorBase::~CompositorBase() { if (m_MirrorTexture) delete m_MirrorTexture; } ovrResult CompositorBase::CreateTextureSwapChain(const ovrTextureSwapChainDesc* desc, ovrTextureSwapChain* out_TextureSwapChain) { ovrTextureSwapChain swapChain = new ovrTextureSwapChainData(*desc); swapChain->Identifier = m_ChainCount++; for (int i = 0; i < swapChain->Length; i++) { TextureBase* texture = CreateTexture(); bool success = texture->Init(desc->Type, desc->Width, desc->Height, desc->MipLevels, desc->ArraySize, desc->Format, desc->MiscFlags, desc->BindFlags); if (!success) return ovrError_RuntimeException; swapChain->Textures[i].reset(texture); } *out_TextureSwapChain = swapChain; return ovrSuccess; } ovrResult CompositorBase::CreateMirrorTexture(const ovrMirrorTextureDesc* desc, ovrMirrorTexture* out_MirrorTexture) { // There can only be one mirror texture at a time if (m_MirrorTexture) return ovrError_RuntimeException; // TODO: Support ovrMirrorOptions ovrMirrorTexture mirrorTexture = new ovrMirrorTextureData(*desc); TextureBase* texture = CreateTexture(); bool success = texture->Init(ovrTexture_2D, desc->Width, desc->Height, 1, 1, desc->Format, desc->MiscFlags | ovrTextureMisc_AllowGenerateMips, ovrTextureBind_DX_RenderTarget); if (!success) return ovrError_RuntimeException; mirrorTexture->Texture.reset(texture); m_MirrorTexture = mirrorTexture; *out_MirrorTexture = mirrorTexture; return ovrSuccess; } ovrResult CompositorBase::WaitToBeginFrame(ovrSession session, long long frameIndex) { MICROPROFILE_SCOPE(WaitToBeginFrame); session->Frames->GetFrame(frameIndex).WaitForFrameToFinish(); session->Frames->PopFrame(frameIndex); return ovrSuccess; } ovrResult CompositorBase::BeginFrame(ovrSession session, long long frameIndex) { MICROPROFILE_SCOPE(BeginFrame); session->CurrentFrame = session->Frames->GetFrame(frameIndex); return ovrSuccess; } ovrResult CompositorBase::EndFrame(ovrSession session, long long frameIndex, ovrLayerHeader const * const * layerPtrList, unsigned int layerCount) { MICROPROFILE_SCOPE(EndFrame); if (layerCount == 0 || !layerPtrList) return ovrError_InvalidParameter; // Flush all pending draw calls. Flush(); ovrLayerEyeFov baseLayer; bool baseLayerFound = false; for (uint32_t i = 0; i < layerCount; i++) { if (layerPtrList[i] == nullptr) continue; // TODO: Support ovrLayerType_Quad, ovrLayerType_Cylinder and ovrLayerType_Cube if (layerPtrList[i]->Type == ovrLayerType_EyeFov || layerPtrList[i]->Type == ovrLayerType_EyeFovDepth || layerPtrList[i]->Type == ovrLayerType_EyeFovMultires) { ovrLayerEyeFov* layer = (ovrLayerEyeFov*)layerPtrList[i]; SubmitFovLayer(session, frameIndex, layer); baseLayerFound = true; } else if (layerPtrList[i]->Type == ovrLayerType_EyeMatrix) { ovrLayerEyeFov layer = ToFovLayer((ovrLayerEyeMatrix*)layerPtrList[i]); SubmitFovLayer(session, frameIndex, &layer); baseLayerFound = true; } } HolographicFrame frame = session->Frames->GetFrame(frameIndex); HolographicFramePrediction prediction = frame.CurrentPrediction(); HolographicCameraPose pose = prediction.CameraPoses().GetAt(0); HolographicCamera cam = pose.HolographicCamera(); //cam.IsPrimaryLayerEnabled(baseLayerFound); HolographicFramePresentResult result = frame.PresentUsingCurrentPrediction(HolographicFramePresentWaitBehavior::DoNotWaitForFrameToFinish); if (result == HolographicFramePresentResult::DeviceRemoved) return ovrError_DisplayLost; // TODO: Mirror textures //if (m_MirrorTexture && success) // RenderMirrorTexture(m_MirrorTexture); MicroProfileFlip(); return ovrSuccess; } ovrLayerEyeFov CompositorBase::ToFovLayer(ovrLayerEyeMatrix* matrix) { ovrLayerEyeFov layer = { ovrLayerType_EyeFov }; layer.Header.Flags = matrix->Header.Flags; layer.SensorSampleTime = matrix->SensorSampleTime; for (int i = 0; i < ovrEye_Count; i++) { layer.Fov[i].LeftTan = layer.Fov[i].RightTan = .5f / matrix->Matrix[i].M[0][0]; layer.Fov[i].UpTan = layer.Fov[i].DownTan = -.5f / matrix->Matrix[i].M[1][1]; layer.ColorTexture[i] = matrix->ColorTexture[i]; layer.Viewport[i] = matrix->Viewport[i]; layer.RenderPose[i] = matrix->RenderPose[i]; } return layer; } void CompositorBase::SubmitFovLayer(ovrSession session, long long frameIndex, ovrLayerEyeFov* fovLayer) { MICROPROFILE_SCOPE(SubmitFovLayer); ovrTextureSwapChain swapChain[ovrEye_Count] = { fovLayer->ColorTexture[ovrEye_Left], fovLayer->ColorTexture[ovrEye_Right] }; // If the right eye isn't set use the left eye for both if (!swapChain[ovrEye_Right]) swapChain[ovrEye_Right] = swapChain[ovrEye_Left]; // Submit the scene layer. for (int i = 0; i < ovrEye_Count; i++) { RenderTextureSwapChain(session, frameIndex, (ovrEyeType)i, swapChain[i], fovLayer->Viewport[i]); } swapChain[ovrEye_Left]->Submit(); if (swapChain[ovrEye_Left] != swapChain[ovrEye_Right]) swapChain[ovrEye_Right]->Submit(); } void CompositorBase::SetMirrorTexture(ovrMirrorTexture mirrorTexture) { m_MirrorTexture = mirrorTexture; }
30.478723
146
0.766492
LukeRoss00
bbfc733ec98b5bbb144bd301d8aee1e9761dbbfa
689
cpp
C++
ITP2/ITP2_5_D.cpp
felixny/AizuOnline
8ff399d60077e08961845502d4a99244da580cd2
[ "MIT" ]
null
null
null
ITP2/ITP2_5_D.cpp
felixny/AizuOnline
8ff399d60077e08961845502d4a99244da580cd2
[ "MIT" ]
null
null
null
ITP2/ITP2_5_D.cpp
felixny/AizuOnline
8ff399d60077e08961845502d4a99244da580cd2
[ "MIT" ]
null
null
null
// ITP2_5_D #include <algorithm> #include <iostream> #include <numeric> #include <tuple> #include <utility> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> v(n); iota(v.begin(), v.end(), 1); do { for (int i = 0; i < n; i++) { // cout<<(i?" ":"")<<v[i]; if (i) { // zero is used to represent false so the first value i = 0 is // always false which prints no empty string. "" cout << " [value i: ]" << i; cout << " " << v[i]; } else { cout << "" << v[i]; cout << " [value i: ]" << i; } } cout << endl; } while (next_permutation(v.begin(), v.end())); return 0; }
22.225806
78
0.489115
felixny
bbfc9a10011ebe085ef224beb130ea6fdfc7f0f2
3,204
hpp
C++
src/core/RegionHash.hpp
gyzhangqm/overkit-1
490aa77a79bd9708d7f2af0f3069b86545a2cebc
[ "MIT" ]
null
null
null
src/core/RegionHash.hpp
gyzhangqm/overkit-1
490aa77a79bd9708d7f2af0f3069b86545a2cebc
[ "MIT" ]
null
null
null
src/core/RegionHash.hpp
gyzhangqm/overkit-1
490aa77a79bd9708d7f2af0f3069b86545a2cebc
[ "MIT" ]
1
2021-07-21T06:48:19.000Z
2021-07-21T06:48:19.000Z
// Copyright (c) 2020 Matthew J. Smith and Overkit contributors // License: MIT (http://opensource.org/licenses/MIT) #ifndef OVK_CORE_REGION_HASH_HPP_INCLUDED #define OVK_CORE_REGION_HASH_HPP_INCLUDED #include <ovk/core/Array.hpp> #include <ovk/core/ArrayView.hpp> #include <ovk/core/Box.hpp> #include <ovk/core/Field.hpp> #include <ovk/core/Global.hpp> #include <ovk/core/HashableRegionTraits.hpp> #include <ovk/core/Math.hpp> #include <ovk/core/Range.hpp> #include <ovk/core/Set.hpp> #include <ovk/core/Tuple.hpp> #include <cmath> #include <memory> #include <type_traits> #include <utility> namespace ovk { namespace core { template <typename RegionType> class region_hash { public: static_assert(IsHashableRegion<RegionType>(), "Invalid region type (not hashable)."); using region_type = RegionType; using region_traits = hashable_region_traits<region_type>; using coord_type = typename region_traits::coord_type; static_assert(std::is_same<coord_type, int>::value || std::is_same<coord_type, double>::value, "Coord type must be int or double."); using extents_type = interval<coord_type,MAX_DIMS>; explicit region_hash(int NumDims); region_hash(int NumDims, const tuple<int> &NumBins, array_view<const region_type> Regions); long long MapToBin(const tuple<coord_type> &Point) const; array_view<const long long> RetrieveBin(long long iBin) const; int Dimension() const { return NumDims_; } const range &BinRange() const { return BinRange_; } const extents_type &Extents() const { return Extents_; } private: int NumDims_; range BinRange_; field_indexer BinIndexer_; extents_type Extents_; tuple<double> BinSize_; array<long long> BinRegionIndicesStarts_; array<long long> BinRegionIndices_; void MapToBins_(const region_type &Region, range &Bins) const; void MapToBins_(const region_type &Region, set<long long> &Bins) const; void AccumulateBinRegionCounts_(const range &Bins, field<long long> &NumRegionsInBin) const; void AccumulateBinRegionCounts_(const set<long long> &Bins, field<long long> &NumRegionsInBin) const; void AddToBins_(int iRegion, const range &Bins, const array<long long> &BinRegionIndicesStarts, array<long long> &BinRegionIndices, field<long long> &NumRegionsAddedToBin) const; void AddToBins_(int iRegion, const set<long long> &Bins, const array<long long> &BinRegionIndicesStarts, array<long long> &BinRegionIndices, field<long long> &NumRegionsAddedToBin) const ; template <typename T> struct coord_type_tag {}; interval<int,MAX_DIMS> MakeEmptyExtents_(int NumDims, coord_type_tag<int>); interval<double,MAX_DIMS> MakeEmptyExtents_(int NumDims, coord_type_tag<double>); interval<int,MAX_DIMS> UnionExtents_(const interval<int,MAX_DIMS> &Left, const interval<int,MAX_DIMS> &Right); interval<double,MAX_DIMS> UnionExtents_(const interval<double,MAX_DIMS> &Left, const interval<double,MAX_DIMS> &Right); static tuple<int> GetBinSize_(const interval<int,MAX_DIMS> &Extents, const tuple<int> &NumBins); static tuple<double> GetBinSize_(const interval<double,MAX_DIMS> &Extents, const tuple<int> &NumBins); }; }} #include <ovk/core/RegionHash.inl> #endif
32.693878
98
0.762172
gyzhangqm
bbfee8b354473cc0810a75cd95d35b2a0f88ad3c
169
hpp
C++
src/uproar/config/version.hpp
tiger-chan/lib-gradient-noise
66eb8186b10f7507b437a81a4c6be16fcad5ccaf
[ "MIT" ]
null
null
null
src/uproar/config/version.hpp
tiger-chan/lib-gradient-noise
66eb8186b10f7507b437a81a4c6be16fcad5ccaf
[ "MIT" ]
null
null
null
src/uproar/config/version.hpp
tiger-chan/lib-gradient-noise
66eb8186b10f7507b437a81a4c6be16fcad5ccaf
[ "MIT" ]
null
null
null
#ifndef UPROAR_CONFIG_VERSION_HPP #define UPROAR_CONFIG_VERSION_HPP #define UPROAR_VERSION_MAJOR 0 #define UPROAR_VERSION_MINOR 1 #define UPROAR_VERSION_PATCH 0 #endif
21.125
33
0.87574
tiger-chan
bbffb946d5ad4823637f463fcf7240bff13b2bc7
1,736
cpp
C++
src/MapEditor/Controls/ResourcePreview.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
4
2019-06-17T13:44:49.000Z
2021-01-19T10:39:48.000Z
src/MapEditor/Controls/ResourcePreview.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
null
null
null
src/MapEditor/Controls/ResourcePreview.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
4
2019-06-17T16:03:20.000Z
2020-02-15T09:14:30.000Z
// ResourcePreview.cpp : implementation file // #include "stdafx.h" #include "..\MapEditor.h" #include "ResourcePreview.h" #include "Common\Map\Map.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CResourcePreview CResourcePreview::CResourcePreview() { m_pResource = NULL; } CResourcePreview::~CResourcePreview() { } BEGIN_MESSAGE_MAP(CResourcePreview, CStatic) //{{AFX_MSG_MAP(CResourcePreview) ON_WM_DESTROY() ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResourcePreview message handlers void CResourcePreview::Create(CRect &rcBound, DWORD dwStyle, CWnd *pParent, UINT nID) { m_Buffer.SetWidth(RESOURCE_ICON_WIDTH); m_Buffer.SetHeight(RESOURCE_ICON_HEIGHT); m_Buffer.Create(); CStatic::Create("", dwStyle, rcBound, pParent, nID); m_Clipper.Create(this); } void CResourcePreview::SetResource(CEResource *pResource) { m_pResource = pResource; Invalidate(); } void CResourcePreview::OnDestroy() { CStatic::OnDestroy(); m_Buffer.Delete(); m_Clipper.Delete(); } void CResourcePreview::OnPaint() { CPaintDC dc(this); // device context for painting g_pDDPrimarySurface->SetClipper(&m_Clipper); CRect rcClient; GetClientRect(&rcClient); CBrush brush; brush.CreateSolidBrush(RGB(192, 192, 192)); dc.FillRect(&rcClient, &brush); brush.DeleteObject(); ClientToScreen(&rcClient); if(m_pResource != NULL){ m_Buffer.Fill(RGB32(192, 192, 192)); m_Buffer.Paste(0, 0, m_pResource->GetIcon()); g_pDDPrimarySurface->Paste(rcClient.TopLeft(), &m_Buffer); } }
21.170732
85
0.667051
vitek-karas
0101e91b7672bcb40bcd0c23fffae67aab0ac75b
1,013
cpp
C++
Examples/HttpRequest/HttpRequest.cpp
Rprop/RLib
bb94d51d69a2207b073a779a871336288ca733d1
[ "Unlicense" ]
23
2018-04-23T15:46:24.000Z
2022-01-10T14:03:57.000Z
Examples/HttpRequest/HttpRequest.cpp
boyliang/RLib
bb94d51d69a2207b073a779a871336288ca733d1
[ "Unlicense" ]
1
2017-07-24T05:13:03.000Z
2017-07-24T08:59:48.000Z
Examples/HttpRequest/HttpRequest.cpp
boyliang/RLib
bb94d51d69a2207b073a779a871336288ca733d1
[ "Unlicense" ]
13
2018-05-11T15:53:12.000Z
2021-09-29T11:57:16.000Z
/******************************************************************** Created: 2016/07/18 19:15 Filename: HttpRequest.cpp Author: rrrfff Url: http://blog.csdn.net/rrrfff *********************************************************************/ #include <RLib_Import.h> //------------------------------------------------------------------------- int __stdcall WinMain(__in HINSTANCE /*hInstance*/, __in_opt HINSTANCE /*hPrevInstance*/, __in LPSTR /*lpCmdLine*/, __in int /*nShowCmd*/) { // WebClient is a wrapper class for HttpRequest/HttpResponse, // and platform-independent in a sense. // performs a HTTP GET request and gets response as string String page = WebClient::GetResponseText(_R("http://rlib.cf/")); // also, HTTPS/SSL is supported. String ssl_page = WebClient::GetResponseText(_R("https://www.alipay.com/")); // performs a HTTP POST request with string data String post_page = WebClient::PostResponseText(_R("http://rlib.cf/"), _R("post data")); return STATUS_SUCCESS; }
37.518519
89
0.564659
Rprop
010667525fb6e5965c1a1815abb558c4e033d42a
574
hpp
C++
src/menu.hpp
matyalatte/2dPolyTo3d
be5ed4e871bd65c704ff12664f44e1aae5c89b24
[ "MIT" ]
null
null
null
src/menu.hpp
matyalatte/2dPolyTo3d
be5ed4e871bd65c704ff12664f44e1aae5c89b24
[ "MIT" ]
null
null
null
src/menu.hpp
matyalatte/2dPolyTo3d
be5ed4e871bd65c704ff12664f44e1aae5c89b24
[ "MIT" ]
null
null
null
/* * File: menu.hpp * -------------------- * @author Matyalatte * @version 2021/09/14 * - initial commit */ #pragma once #include <GL/glut.h> #include "2dpoly_to_3d/2dpoly_to_3d.hpp" #include "2dpoly_to_3d/utils.hpp" namespace openglHandler { //functions for popup menu in glut void menu(int item); void menuInit(); void checkUpdateMenu(); void connectPolyTo3D(sketch3D::poly_to_3D* p_to_3d); bool getSetModelFlag(); void resetSetModelFlag(); bool getShowNormal(); bool getShow2DPoly(); bool getShowModel(); bool getExitFlag(); void resetExitFlag(); }
19.133333
53
0.698606
matyalatte
01069effde8f24ee53ea22b955062e516f748cc6
551
hpp
C++
libadb/include/libadb/api/rate/data/rate-limit-scope.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
1
2022-03-10T15:14:13.000Z
2022-03-10T15:14:13.000Z
libadb/include/libadb/api/rate/data/rate-limit-scope.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
9
2022-03-07T21:00:08.000Z
2022-03-15T23:14:52.000Z
libadb/include/libadb/api/rate/data/rate-limit-scope.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
null
null
null
#pragma once #include <libadb/libadb.hpp> #include <string> namespace adb::api { /** * @brief Rate Limit Scope * @details https://discord.com/developers/docs/topics/rate-limits#header-format */ enum class RateLimitScope { /// per bot or user limit User, /// per bot or user global limit Global, /// per resource limit Shared }; LIBADB_API void from_string(const std::string &str, RateLimitScope &limit); LIBADB_API std::string to_string(RateLimitScope limit); }
22.958333
84
0.627949
faserg1
010f361df1b18f8efcd37aec4d5169dcb9350ed1
5,117
cpp
C++
src/Snake.cpp
robifr/snake
611c6cc0460a92cca7e033108be13510aeba6b69
[ "MIT" ]
null
null
null
src/Snake.cpp
robifr/snake
611c6cc0460a92cca7e033108be13510aeba6b69
[ "MIT" ]
null
null
null
src/Snake.cpp
robifr/snake
611c6cc0460a92cca7e033108be13510aeba6b69
[ "MIT" ]
null
null
null
#include <cmath> //floor #include "Snake.hpp" #include "Game.hpp" #include "View.hpp" Snake::Snake(Game& game) : game_(game) { } void Snake::changeDirection(int keyCode) { int deltaX = 0, deltaY = 0; switch (keyCode) { case SDLK_UP: case SDLK_w: deltaX = 0; deltaY = -this->game_.gridHeight; break; case SDLK_DOWN: case SDLK_s: deltaX = 0; deltaY = this->game_.gridHeight; break; case SDLK_LEFT: case SDLK_a: deltaX = -this->game_.gridWidth; deltaY = 0; break; case SDLK_RIGHT: case SDLK_d: deltaX = this->game_.gridWidth; deltaY = 0; break; default: return; } const bool isTryingToMoveDownWhileMovingUp = deltaY > this->deltaY_ && this->deltaY_ < 0; const bool isTryingToMoveUpWhileMovingDown = deltaY < this->deltaY_ && this->deltaY_ >= 0; const bool isTryingToMoveRightWhileMovingLeft = deltaX > this->deltaY_ && this->deltaX_ < 0; const bool isTryingToMoveLeftWhileMovingRight = deltaX < this->deltaX_ && this->deltaX_ >= 0; //disallow snake to move towards their current opposite direction. //e.g. if the snake is currently moving up, user shouldn't be able to move down, and vice versa. if (!isTryingToMoveUpWhileMovingDown || !isTryingToMoveDownWhileMovingUp || !isTryingToMoveLeftWhileMovingRight || !isTryingToMoveRightWhileMovingLeft) { //compute next head position ahead before doing movement. //ensuring the head won't eat its own neck, //because of user changing direction way too fast. if (this->body_.size() >= 1) { std::pair<int, int> nextPosition = this->nextHeadPosition_(deltaX, deltaY); if (nextPosition.first == this->body_[1].x && nextPosition.second == this->body_[1].y) { return; } } this->deltaX_ = deltaX; this->deltaY_ = deltaY; } } void Snake::move() { for (int i = this->body_.size() - 1; i >= 0; i--) { //snake head. if (i == 0) { std::pair<int, int> position = this->nextHeadPosition_(this->deltaX_, this->deltaY_); this->body_[i].x = position.first; this->body_[i].y = position.second; if (this->isEatingOwnBody_(this->body_[i].x, this->body_[i].y)) this->isAlive = false; if (this->isEatingFood_(this->body_[i].x, this->body_[i].y, this->game_.food)) { this->foodEaten_++; this->addBody( this->body_.back().x + this->deltaX_, this->body_.back().y + this->deltaY_ ); this->game_.inGameView->setScore(this->foodEaten_); this->game_.food->spawnRandom(); i--; } //every snake body follow their previous segment position. } else if (i > 0) { this->body_[i].x = this->body_[i - 1].x; this->body_[i].y = this->body_[i - 1].y; } } } void Snake::addBody(int x, int y) { SDL_Rect newBody = { x, y, this->game_.gridWidth, this->game_.gridHeight }; this->body_.push_back(newBody); } void Snake::respawn() { const int gridWidth = this->game_.gridWidth; const int gridHeight = this->game_.gridHeight; const int x = std::floor(this->game_.windowSurface->w / 2 / gridWidth) * gridWidth; const int y = std::floor(this->game_.windowSurface->h / 2 / gridHeight) * gridHeight; this->deltaX_ = 0; this->deltaY_ = -15; //move to top as the default position. this->foodEaten_ = 0; this->body_.clear(); for (int i = 0; i < 3; i++) { this->addBody(x, y + (gridHeight * i)); } } void Snake::render() { for (int i = 0; i < this->body_.size(); i++) { SDL_SetRenderDrawColor(this->game_.renderer().get(), 220, 20, 60, 225); //red. SDL_RenderFillRect(this->game_.renderer().get(), &this->body_[i]); } } bool Snake::isEatingFood_(int x, int y, const std::unique_ptr<Food>& food) { if (x == food->body().x && y == food->body().y) return true; return false; } bool Snake::isEatingOwnBody_(int x, int y) { for (int i = 1; i < this->body_.size(); i++) { if (x == this->body_[i].x && y == this->body_[i].y) { return true; } } return false; } std::pair<int, int> Snake::nextHeadPosition_(int deltaX, int deltaY) { const int yMin = this->game_.inGameView->scoreContainer.h; const int xMax = this->game_.windowSurface->w - this->game_.gridWidth; const int yMax = this->game_.windowSurface->h - this->game_.gridHeight; int x = this->body_[0].x + deltaX; int y = this->body_[0].y + deltaY; if (x > xMax) { x = 0; } else if (x < 0) { x = xMax; } if (y > yMax) { y = yMin; } else if (y < yMin) { y = yMax; } return std::make_pair(x, y); }
31.392638
100
0.555599
robifr
0113774bc56dbc38bad5b3751e4987a5c42fbff2
1,534
hpp
C++
src/messaging/MessageHandler.hpp
Fabi2607/MazeNet-Client
1fcb0b3cbeeab123cb69cd18070e0bbf4907130c
[ "MIT" ]
null
null
null
src/messaging/MessageHandler.hpp
Fabi2607/MazeNet-Client
1fcb0b3cbeeab123cb69cd18070e0bbf4907130c
[ "MIT" ]
null
null
null
src/messaging/MessageHandler.hpp
Fabi2607/MazeNet-Client
1fcb0b3cbeeab123cb69cd18070e0bbf4907130c
[ "MIT" ]
null
null
null
#ifndef MAZENET_CLIENT_MESSAGEHANDLER_HPP #define MAZENET_CLIENT_MESSAGEHANDLER_HPP #include <string> #include <player/IPlayerStrategy.hpp> #include "../messaging/mazeCom.hxx" #include "../player/GameSituation.hpp" #include "../util/logging/Log.hpp" #include "MessageDispatcher.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" //Ignoring the warning. class MessageHandler { public: MessageHandler(std::shared_ptr<IPlayerStrategy> strategy, MessageDispatcher& dispatcher); void handle_incoming_message(const std::string& message); private: void handle_login_reply(const LoginReplyMessageType& reply); void handle_await_move(const AwaitMoveMessageType& await_move); void handle_accept_message(const AcceptMessageType& accept_message); void handle_win_message(const WinMessageType& win_message); void handle_disconnect_message(const DisconnectMessageType& disconnect_message); void update_model(const AwaitMoveMessageType& message); void update_board(const boardType& board); std::shared_ptr<MazeCom> deserialize(const std::string& msg); std::shared_ptr<IPlayerStrategy> strategy_; mazenet::util::logging::Log logger_; MessageDispatcher& dispatcher_; xsd::cxx::tree::error_handler<char> eh; xsd::cxx::xml::dom::bits::error_handler_proxy<char> ehp; xercesc::DOMImplementation* impl; xml_schema::dom::unique_ptr<xercesc::DOMLSParser> parser; xercesc::DOMConfiguration* conf_r; }; #pragma GCC diagnostic pop #endif /* MAZENET_CLIENT_MESSAGEHANDLER_HPP */
27.392857
91
0.789439
Fabi2607
011567e9d19e6b5d02b15b496bc71cf9d07e8bf7
7,215
hpp
C++
scicpp/core/meta.hpp
tvanderbruggen/SciCpp
09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46
[ "MIT" ]
2
2021-08-02T09:03:30.000Z
2022-02-17T11:58:05.000Z
scicpp/core/meta.hpp
tvanderbruggen/SciCpp
09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46
[ "MIT" ]
null
null
null
scicpp/core/meta.hpp
tvanderbruggen/SciCpp
09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: MIT // Copyright (c) 2019-2021 Thomas Vanderbruggen <th.vanderbruggen@gmail.com> #ifndef SCICPP_CORE_META #define SCICPP_CORE_META #include <Eigen/Dense> #include <array> #include <complex> #include <ratio> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> namespace scicpp::meta { //--------------------------------------------------------------------------------- // is_complex //--------------------------------------------------------------------------------- namespace detail { template <class T> struct is_complex : std::false_type {}; template <class T> struct is_complex<std::complex<T>> : std::true_type {}; } // namespace detail template <class T> constexpr bool is_complex_v = detail::is_complex<T>::value; template <typename T> using enable_if_complex = std::enable_if_t<is_complex_v<T>, int>; template <typename T> using disable_if_complex = std::enable_if_t<!is_complex_v<T>, int>; //--------------------------------------------------------------------------------- // is_iterable //--------------------------------------------------------------------------------- // https://stackoverflow.com/questions/13830158/check-if-a-variable-is-iterable namespace detail { // To allow ADL with custom begin/end using std::begin; using std::end; template <typename T> auto is_iterable_impl(int) -> decltype( begin(std::declval<T &>()) != end(std::declval<T &>()), // begin/end and operator != void(), // Handle evil operator , ++std::declval<decltype(begin(std::declval<T &>())) &>(), // operator ++ void(*begin(std::declval<T &>())), // operator* std::true_type{}); template <typename T> std::false_type is_iterable_impl(...); template <typename T> using is_iterable = decltype(detail::is_iterable_impl<T>(0)); } // namespace detail template <typename T> constexpr bool is_iterable_v = detail::is_iterable<T>::value; template <typename T> using enable_if_iterable = std::enable_if_t<is_iterable_v<T>, int>; template <typename T> using disable_if_iterable = std::enable_if_t<!is_iterable_v<T>, int>; //--------------------------------------------------------------------------------- // std::vector traits //--------------------------------------------------------------------------------- namespace detail { template <class T> struct is_std_vector : std::false_type {}; template <typename Scalar> struct is_std_vector<std::vector<Scalar>> : std::true_type {}; } // namespace detail template <class T> constexpr bool is_std_vector_v = detail::is_std_vector<T>::value; //--------------------------------------------------------------------------------- // std::array traits //--------------------------------------------------------------------------------- namespace detail { template <class T> struct is_std_array : std::false_type {}; template <typename Scalar, std::size_t N> struct is_std_array<std::array<Scalar, N>> : std::true_type {}; } // namespace detail template <class T> constexpr bool is_std_array_v = detail::is_std_array<T>::value; //--------------------------------------------------------------------------------- // std::tuple traits //--------------------------------------------------------------------------------- namespace detail { template <class T> struct is_std_tuple : std::false_type {}; template <typename... Args> struct is_std_tuple<std::tuple<Args...>> : std::true_type {}; } // namespace detail template <class T> constexpr bool is_std_tuple_v = detail::is_std_tuple<T>::value; //--------------------------------------------------------------------------------- // std::pair traits //--------------------------------------------------------------------------------- namespace detail { template <class T> struct is_std_pair : std::false_type {}; template <typename T1, typename T2> struct is_std_pair<std::pair<T1, T2>> : std::true_type {}; } // namespace detail template <class T> constexpr bool is_std_pair_v = detail::is_std_pair<T>::value; //--------------------------------------------------------------------------------- // subtuple // https://stackoverflow.com/questions/17854219/creating-a-sub-tuple-starting-from-a-stdtuplesome-types //--------------------------------------------------------------------------------- namespace detail { template <typename... T, std::size_t... I> constexpr auto subtuple_(const std::tuple<T...> &t, std::index_sequence<I...> /*unused*/) { return std::make_tuple(std::get<I>(t)...); } } // namespace detail template <int Trim, typename... T> constexpr auto subtuple(const std::tuple<T...> &t) { return detail::subtuple_(t, std::make_index_sequence<sizeof...(T) - Trim>()); } template <int Trim = 1, typename T1, typename T2> constexpr auto subtuple(const std::pair<T1, T2> &t) { return std::make_tuple(t.first); } //--------------------------------------------------------------------------------- // is_ratio //--------------------------------------------------------------------------------- namespace detail { template <class T> struct is_ratio : std::false_type {}; template <intmax_t num, intmax_t den> struct is_ratio<std::ratio<num, den>> : std::true_type {}; } // namespace detail template <class T> constexpr bool is_ratio_v = detail::is_ratio<T>::value; //--------------------------------------------------------------------------------- // Eigen type traits //--------------------------------------------------------------------------------- namespace detail { template <class T> struct is_eigen_matrix : std::false_type {}; template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime> struct is_eigen_matrix< Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime>> : std::true_type {}; template <class T> struct is_eigen_array : std::false_type {}; template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime> struct is_eigen_array< Eigen::Array<Scalar, RowsAtCompileTime, ColsAtCompileTime>> : std::true_type {}; } // namespace detail template <class T> constexpr bool is_eigen_matrix_v = detail::is_eigen_matrix<T>::value; template <class T> constexpr bool is_eigen_array_v = detail::is_eigen_array<T>::value; template <class T> constexpr bool is_eigen_container_v = is_eigen_matrix_v<T> || is_eigen_array_v<T>; //--------------------------------------------------------------------------------- // is_predicate //--------------------------------------------------------------------------------- template <class Predicate, class... Args> constexpr bool is_predicate = std::is_integral_v<std::invoke_result_t<Predicate, Args...>>; //--------------------------------------------------------------------------------- // is_string //--------------------------------------------------------------------------------- template <class T> constexpr bool is_string_v = std::is_same_v<const char *, typename std::decay_t<T>> || std::is_same_v<char *, typename std::decay_t<T>> || std::is_same_v<std::string, typename std::decay_t<T>>; } // namespace scicpp::meta #endif // SCICPP_CORE_META
30.315126
103
0.527235
tvanderbruggen
011928a30f96a3f6ebfb64f374f0d4bf5bebeaba
11,070
cpp
C++
src/caffe/test/test_serialization_blob_codec.cpp
shayanshams66/caffe
3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e
[ "Intel", "BSD-2-Clause" ]
1
2017-01-04T03:35:46.000Z
2017-01-04T03:35:46.000Z
src/caffe/test/test_serialization_blob_codec.cpp
shayanshams66/caffe
3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e
[ "Intel", "BSD-2-Clause" ]
null
null
null
src/caffe/test/test_serialization_blob_codec.cpp
shayanshams66/caffe
3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e
[ "Intel", "BSD-2-Clause" ]
null
null
null
#include <boost/assign.hpp> #include <glog/logging.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <vector> #include "caffe/internode/configuration.hpp" #include "caffe/serialization/BlobCodec.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { namespace { using ::testing::_; using ::testing::Return; template <typename TypeParam> class BlobCodecTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; }; TYPED_TEST_CASE(BlobCodecTest, TestDtypesAndDevices); TYPED_TEST(BlobCodecTest, encode_4321_diff) { BlobUpdate msg; Blob<float> srcblob; vector<int> v = boost::assign::list_of(4)(3)(2)(1); srcblob.Reshape(v); vector<float> diff = boost::assign::list_of(999.99)(12.3)(0.1)(-3.3) (+2.0)(12.3)(10.2)(FLT_MAX) (+4.4)(12.3)(0.0)(-1.3) (+6.5)(12.3)(24.42)(1010.10) (FLT_MIN)(12.3)(66.6)(133.1) (12.4)(12.3)(0.0001)(100.3); ASSERT_EQ(diff.size(), srcblob.count()); caffe_copy(srcblob.count(), &diff.front(), srcblob.mutable_cpu_diff()); shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec( MultinodeParameter::default_instance(), true); codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part()); EXPECT_EQ(0, memcmp(msg.data().c_str(), &diff.front(), sizeof(float)*diff.size())); } TYPED_TEST(BlobCodecTest, encode_decode_2222_data) { BlobUpdate msg; Blob<float> srcblob; Blob<float> dstblob; vector<int> v = boost::assign::list_of(2)(2)(2)(2); srcblob.Reshape(v); dstblob.Reshape(v); vector<float> data = boost::assign::list_of(1.1)(-2.2)(3.3)(5.5) (6.6)(-7.7)(8.8)(9.9) (13.13)(-12.12)(12.12)(11.11) (128.128)(-132.312)(1.1)(-10.10); vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0) (0.0)(0.0)(0.0)(0.0) (0.0)(0.0)(0.0)(0.0) (0.0)(0.0)(0.0)(0.0); ASSERT_EQ(data.size(), srcblob.count()); ASSERT_EQ(data_zero.size(), dstblob.count()); caffe_copy<float>(srcblob.count(), &data.front(), srcblob.mutable_cpu_data()); caffe_copy<float>(dstblob.count(), &data_zero.front(), dstblob.mutable_cpu_diff()); shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec( MultinodeParameter::default_instance(), true); codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part()); codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 1.0f, 0.0f); EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data.front(), sizeof(float)*dstblob.count())); } TYPED_TEST(BlobCodecTest, encode_8width_data_) { BlobUpdate msg; Blob<float> srcblob; vector<int> v = boost::assign::list_of(1)(1)(1)(8); srcblob.Reshape(v); vector<float> data = boost::assign::list_of(-0.0)(-0.3)(-2.2)(-3.3) (+0.0)(12.3)(10.2)(-1.3); ASSERT_EQ(data.size(), srcblob.count()); caffe_copy<float>(srcblob.count(), &data.front(), srcblob.mutable_cpu_data()); shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec( MultinodeParameter::default_instance(), true); codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part()); EXPECT_EQ(0, memcmp(msg.data().c_str(), &data.front(), sizeof(float)*data.size())); } TYPED_TEST(BlobCodecTest, encode_4width_diff) { BlobUpdate msg; Blob<float> srcblob; vector<int> v = boost::assign::list_of(1)(1)(1)(4); srcblob.Reshape(v); vector<float> diff = boost::assign::list_of(-0.0)(-99.99)(-0.3)(0.4); ASSERT_EQ(diff.size(), srcblob.count()); caffe_copy<float>(srcblob.count(), &diff.front(), srcblob.mutable_cpu_diff()); shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec( MultinodeParameter::default_instance(), true); codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part()); EXPECT_EQ(0, memcmp(msg.data().c_str(), &diff.front(), sizeof(float)*diff.size())); } TYPED_TEST(BlobCodecTest, encode_decode_4width_diff) { BlobUpdate msg; Blob<float> srcblob; Blob<float> dstblob; vector<int> v = boost::assign::list_of(1)(1)(1)(4); srcblob.Reshape(v); dstblob.Reshape(v); vector<float> diff_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0); vector<float> diff = boost::assign::list_of(1.0)(2.2)(3.3)(4.4); ASSERT_EQ(diff.size(), srcblob.count()); ASSERT_EQ(diff_zero.size(), srcblob.count()); caffe_copy<float>(srcblob.count(), &diff.front(), srcblob.mutable_cpu_diff()); caffe_copy<float>(dstblob.count(), &diff_zero.front(), dstblob.mutable_cpu_diff()); shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec( MultinodeParameter::default_instance(), true); codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part()); codec->decode(msg, &dstblob, BlobEncoding::GRADS, 1.0f, 0.0f); EXPECT_EQ(0, memcmp(dstblob.cpu_diff(), &diff.front(), sizeof(float)*dstblob.count())); } TYPED_TEST(BlobCodecTest, encode_decode_4width_data) { BlobUpdate msg; Blob<float> srcblob; Blob<float> dstblob; vector<int> v = boost::assign::list_of(1)(1)(1)(4); srcblob.Reshape(v); dstblob.Reshape(v); vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0); vector<float> data = boost::assign::list_of(4.0)(3.2)(2.3)(1.4); ASSERT_EQ(data.size(), srcblob.count()); ASSERT_EQ(data_zero.size(), srcblob.count()); caffe_copy<float>(srcblob.count(), &data.front(), srcblob.mutable_cpu_data()); caffe_copy<float>(dstblob.count(), &data_zero.front(), dstblob.mutable_cpu_data()); shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec( MultinodeParameter::default_instance(), true); codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part()); codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 1.0f, 0.0f); EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data.front(), sizeof(float)*dstblob.count())); } TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_5) { BlobUpdate msg; Blob<float> srcblob; Blob<float> dstblob; vector<int> v = boost::assign::list_of(1)(1)(1)(4); srcblob.Reshape(v); dstblob.Reshape(v); vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0); vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4); vector<float> data_expected = boost::assign::list_of(2.0)(1.6)(1.2)(0.7); ASSERT_EQ(data.size(), srcblob.count()); ASSERT_EQ(data_zero.size(), srcblob.count()); caffe_copy<float>(srcblob.count(), &data.front(), srcblob.mutable_cpu_data()); caffe_copy<float>(dstblob.count(), &data_zero.front(), dstblob.mutable_cpu_data()); shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec( MultinodeParameter::default_instance(), true); codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part()); codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 0.5f, 0.0f); EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(), sizeof(float)*dstblob.count())); } TYPED_TEST(BlobCodecTest, encode_decode_4width_data_beta_0_5) { BlobUpdate msg; Blob<float> srcblob; Blob<float> dstblob; vector<int> v = boost::assign::list_of(1)(1)(1)(4); srcblob.Reshape(v); dstblob.Reshape(v); vector<float> data_one = boost::assign::list_of(1.0)(1.0)(1.0)(1.0); vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4); vector<float> data_expected = boost::assign::list_of(4.5)(3.7)(2.9)(1.9); ASSERT_EQ(data.size(), srcblob.count()); ASSERT_EQ(data_one.size(), srcblob.count()); caffe_copy<float>(srcblob.count(), &data.front(), srcblob.mutable_cpu_data()); caffe_copy<float>(dstblob.count(), &data_one.front(), dstblob.mutable_cpu_data()); shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec( MultinodeParameter::default_instance(), true); codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part()); codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 1.0f, 0.5f); EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(), sizeof(float)*dstblob.count())); } TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_5_beta_0_5) { BlobUpdate msg; Blob<float> srcblob; Blob<float> dstblob; vector<int> v = boost::assign::list_of(1)(1)(1)(4); srcblob.Reshape(v); dstblob.Reshape(v); vector<float> data_one = boost::assign::list_of(1.0)(1.0)(1.0)(1.0); vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4); vector<float> data_expected = boost::assign::list_of(2.5)(2.1)(1.7)(1.2); ASSERT_EQ(data.size(), srcblob.count()); ASSERT_EQ(data_one.size(), srcblob.count()); caffe_copy<float>(srcblob.count(), &data.front(), srcblob.mutable_cpu_data()); caffe_copy<float>(dstblob.count(), &data_one.front(), dstblob.mutable_cpu_data()); shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec( MultinodeParameter::default_instance(), true); codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part()); codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 0.5f, 0.5f); EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(), sizeof(float)*dstblob.count())); } TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_beta_1) { BlobUpdate msg; Blob<float> srcblob; Blob<float> dstblob; vector<int> v = boost::assign::list_of(1)(1)(1)(4); srcblob.Reshape(v); dstblob.Reshape(v); vector<float> data_one = boost::assign::list_of(1.1)(2.3)(1.4)(0.01); vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4); vector<float> data_expected = boost::assign::list_of(1.1)(2.3)(1.4)(0.01); ASSERT_EQ(data.size(), srcblob.count()); ASSERT_EQ(data_one.size(), srcblob.count()); caffe_copy<float>(srcblob.count(), &data.front(), srcblob.mutable_cpu_data()); caffe_copy<float>(dstblob.count(), &data_one.front(), dstblob.mutable_cpu_data()); shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec( MultinodeParameter::default_instance(), true); codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part()); codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 0.0f, 1.0f); EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(), sizeof(float)*dstblob.count())); } } // namespace } // namespace caffe
35.594855
78
0.629901
shayanshams66
0120cb3c518dc7e577506ec76c317ca23a2c125f
412
cpp
C++
a/a216.cpp
mirkat1206/zerojudge_cpp
263cd51f4eee4acec8396f6c069bba540ac15e96
[ "BSD-2-Clause" ]
1
2019-12-27T03:03:50.000Z
2019-12-27T03:03:50.000Z
a/a216.cpp
mirkat1206/zerojudge_cpp
263cd51f4eee4acec8396f6c069bba540ac15e96
[ "BSD-2-Clause" ]
null
null
null
a/a216.cpp
mirkat1206/zerojudge_cpp
263cd51f4eee4acec8396f6c069bba540ac15e96
[ "BSD-2-Clause" ]
null
null
null
// a216 : 數數愛明明 #include <cstdio> #define N 30010 int main() { // f[n] = n + f[n-1], g[n] = f[n] + g[n-1], f[1] = g[1] = 1 // f[i], g[i] is on day i !!! long long int f[N] = { 0 , 1 , 3 }, g[N] = { 0 , 1 } ; for( int i=3 ; i<N ; i++ ) { f[i] = i + f[i-1] ; g[i-1] = f[i-1] + g[i-2] ; } int n; while( scanf("%lld", &n )!=EOF ) printf("%lld %lld\n", f[n] , g[n] ); return 0; }
19.619048
61
0.393204
mirkat1206
01215b320c80daaf94dc18a75469ceeffbd1cd72
7,317
cc
C++
ARM/NXP/Flash/FCB.cc
JohnAdriaan/RTX2C3
833cfa45ece56a1516cb743c6bafa7c916451e55
[ "BSD-3-Clause" ]
null
null
null
ARM/NXP/Flash/FCB.cc
JohnAdriaan/RTX2C3
833cfa45ece56a1516cb743c6bafa7c916451e55
[ "BSD-3-Clause" ]
null
null
null
ARM/NXP/Flash/FCB.cc
JohnAdriaan/RTX2C3
833cfa45ece56a1516cb743c6bafa7c916451e55
[ "BSD-3-Clause" ]
null
null
null
// © 2019 John Adriaan. Licensed under the "3-clause BSD License" /// /// \file ARM/NXP/Flash/FCB.cc /// /// This file defines and instantiates the Flash Control Block at a known address. /// The FCB is used by the i.MX RT10xx to best configure the Flash for use. /// Note that this is completely self-contained - no external reference needs /// to be made to this module. /// #include <ARM/NXP/NXP.hh> namespace ARM::NXP::Flash { /// FlexSPI Configuration Block struct FlexSPIConfig { struct Version { byte bugfix; byte minor; byte major; const char v = 'V'; }; // Version static_assert(sizeof(Version)==4, "Incorrect Version size"); enum SampleClkSrcs : byte { Internal = 0, Loopback = 1, FlashDQS = 3 }; // SampleClkSrcs struct LUTs { byte number; ///< Number of LUT sequences byte index; ///< Starting LUT index const word x2 = Rsvd16; ///< Reserved }; // LUTs static_assert(sizeof(LUTs)==4, "Incorrect LUTs size"); struct MiscOptions { bit diffClkEnable : 1; unsigned : 1; bit parallelModeEnable : 1; bit wordAddressableEnable : 1; bit safeConfigFreqEnable : 1; bit padSettingOverrideEnable : 1; bit ddrModeEnable : 1; unsigned : 2; bit secondDQSPinMux : 1; unsigned : 22; unsigned : 0; }; // MiscOptions static_assert(sizeof(MiscOptions)==sizeof(unsigned), "Incorrect MiscOptions size"); enum DeviceTypes : byte { DeviceUnknown = 0, ///< *** Examples have this value SerialNOR = 1 ///< *** Documents show this is only valid option }; // DeviceTypes enum Pads : byte { SinglePad = 1, DualPads = 2, QuadPads = 4, OctalPads = 8 }; // Pads enum ClockFreqs : byte { Freq30MHz = 1, Freq50MHz = 2, Freq60MHz = 3, Freq75MHz = 4, Freq80MHz = 5, Freq100MHz = 6, Freq120MHz = 7, Freq133MHz = 8 }; // ClockFreqs struct ValidTimes { word dllA; word dllB; }; // ValidTimes static_assert(sizeof(ValidTimes)==sizeof(unsigned), "Incorrect ValidTimes size"); enum Busys : word { Busy1 = 0, ///< 0: "Busy Bit==1 when busy Busy0 = 1 ///< 1: "Busy Bit==0 when busy }; // Busys enum LUTPads { Pad1 = 0, Pad2 = 1, Pad4 = 2, Pad8 = 3 }; // LUTPads enum Instructions { STOP = 0, JMP = 9, CMD = 1, ADDR = 2, DUMMY = 3, MODE = 4, MODE2 = 5, MODE4 = 6, READ = 7, WRITE = 8, CMD_DDR = 0x11, ADDR_DDR = 0x0A, MODE_DDR = 0x0B, MODE2_DDR = 0x0C, MODE4_DDR = 0x0D, READ_DDR = 0x0E, WRITE_DDR = 0x0F }; // Instructions struct LUTCommand { byte operand : 8; LUTPads pad : 2; Instructions instruction : 6; word : 0; }; // LUTCommand static_assert(sizeof(LUTCommand)==2, "Incorrect LUTCommand size"); typedef LUTCommand LUTSequence[8]; static_assert(sizeof(LUTSequence)==16, "Incorrect LUTCommand size"); const char tag[4] = { 'F', 'C', 'F', 'B' }; ///< Tag to identify block Version version = { .bugfix=0, .minor=4, .major=1 }; const unsigned x008 = Rsvd32; ///< Reserved SampleClkSrcs readSampleClkSrc = Loopback; ///< Sample DQS Pad byte csHoldTime = 3; ///< Column Select Hold Time. Recommended value byte csSetupTime = 3; ///< Column Select Setup Time. Recommended value byte columnAddressWidth = 0; ///< Not HyperFlash byte deviceModeCfgEnable = No; ///< Don't enable Config const byte x011 = Rsvd8; ///< Reserved word waitTimeCfgCommands = 0; ///< in 100us. Note v1.1.0 minimum LUTs deviceModeSeq = { .number=0, .index=0 }; unsigned deviceModeArg = 0; ///< `deviceModeCfgEnable` must be `1` byte configCmdEnable = No; const byte x01D[3] = { Rsvd8, Rsvd8, Rsvd8 }; ///< Reserved unsigned configCmdSeqs[3] = { 0, 0, 0 }; const unsigned x02C = Rsvd8; ///< Reserved unsigned cfgCmdArgs[3] = { 0, 0, 0 }; const unsigned x03C = Rsvd8; ///< Reserved MiscOptions controllerMiscOption = { }; DeviceTypes deviceType = SerialNOR; Pads sflashPadType = QuadPads; ClockFreqs serialClkFreq = Freq100MHz; byte lutCustomSeqEnable = No; const unsigned x048[2] = { Rsvd32, Rsvd32 }; unsigned sflashA1Size = 0x0100'0000; unsigned sflashA2Size = 0x0000'0000; unsigned sflashB1Size = 0x0000'0000; unsigned sflashB2Size = 0x0000'0000; unsigned csPadSettingOverride = No; unsigned sclkPadSettingOverride = No; unsigned dataPadSettingOverride = No; unsigned dqsPadSettingOverride = No; unsigned timeoutInMs = 0; unsigned commandInterval = 0; ///< in ns ValidTimes dataValidTimes = { .dllA = 0, .dllB = 0 }; word busyOffset = 0; ///< Valid range: 0-31 Busys busyBitPolarity = Busy1; LUTSequence lookupTable[16] = { { { .operand = 0xEB, .pad = Pad1, .instruction = CMD }, ///< 4xI/O, READ { .operand = 24, .pad = Pad4, .instruction = ADDR }, ///< 24 bits { .operand = 6, .pad = Pad4, .instruction = MODE2_DDR }, ///< 6 Dummy cycles // { .operand = 0, .pad = Pad1, .instruction = STOP } } }; ///< And STOP /*** This final command could simply be STOP? ***/ { .operand = 1<<2, .pad = Pad4, .instruction = JMP } } }; ///< JMP LUT[1] LUTSequence lutCustomSeq[3] = { }; unsigned reserved[4] = { Rsvd32, Rsvd32, Rsvd32, Rsvd32 }; }; // FlexSPIConfig static_assert(sizeof(FlexSPIConfig)==0x1C0, "Incorrect FlexSPIConfig size"); struct SerialNORConfig { enum ClockFreqs { ClockUnchanged = 0, Clock30MHz = 1, Clock50MHz = 2, Clock60MHz = 3, Clock75MHz = 4, Clock80MHz = 5, Clock100MHz = 6, Clock133MHz = 7 }; // ClockFreqs FlexSPIConfig fcb = { }; unsigned pageSize = 0x0100; unsigned sectorSize = 0x1000; ClockFreqs ipCmdSerialClockFreq = ClockUnchanged; unsigned reserved[13] = { Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32 }; }; // SerialNORConfigBlock static_assert(sizeof(SerialNORConfig)==0x200, "Incorrect SerialNORConfig size"); SECTION(".FCB") const SerialNORConfig serialNORConfig; } // namespace ARM::NXP::Flash
36.402985
129
0.531502
JohnAdriaan
0125409ff226d969876cee1c1b41b80f3bdcfc9e
8,747
hh
C++
aku/FeatureModules.hh
lingsoft/AaltoASR
40343e215a6cf1b7d5ed41a53095495567b0ab01
[ "BSD-3-Clause" ]
78
2015-01-07T14:33:47.000Z
2022-03-15T09:01:30.000Z
aku/FeatureModules.hh
ufukhurriyetoglu/AaltoASR
02b23d374ab9be9b0fd5d8159570b509ede066f3
[ "BSD-3-Clause" ]
4
2015-05-19T13:00:34.000Z
2016-07-26T12:29:32.000Z
aku/FeatureModules.hh
ufukhurriyetoglu/AaltoASR
02b23d374ab9be9b0fd5d8159570b509ede066f3
[ "BSD-3-Clause" ]
32
2015-01-16T08:16:24.000Z
2021-04-02T21:26:22.000Z
#ifndef FEATUREMODULES_HH #define FEATUREMODULES_HH #include <vector> #include "ModuleConfig.hh" #include "FeatureModule.hh" #include "BaseFeaModule.hh" #include "AudioFileModule.hh" #include "FFTModule.hh" namespace aku { class FeatureGenerator; ////////////////////////////////////////////////////////////////// // Feature module implementations ////////////////////////////////////////////////////////////////// class PreModule : public BaseFeaModule { public: PreModule(); static const char *type_str() { return "pre"; } virtual void set_fname(const char *fname); virtual void set_file(FILE *fp, bool stream=false); virtual void discard_file(void); virtual bool eof(int frame); virtual int sample_rate(void) { return m_sample_rate; } virtual float frame_rate(void) { return m_frame_rate; } virtual int last_frame(void); private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void reset_module(); virtual void generate(int frame); private: int m_sample_rate; float m_frame_rate; int m_eof_frame; int m_legacy_file; //!< If nonzero, the dimension in the file is a byte int m_file_offset; int m_cur_pre_frame; bool m_close_file; FILE *m_fp; std::vector<double> m_first_feature; //!< Feature returned for negative frames std::vector<double> m_last_feature; //!< Feature returned after EOF int m_last_feature_frame; //!< The frame of the feature returned after EOF std::vector<float> m_temp_fea_buf; //!< Need a float buffer for reading }; class MelModule : public FeatureModule { public: MelModule(FeatureGenerator *fea_gen); static const char *type_str() { return "mel"; } private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); void create_mel_bins(void); private: FeatureGenerator *m_fea_gen; int m_bins; int m_root; //!< If nonzero, take 10th root of the output instead of logarithm std::vector<float> m_bin_edges; }; class PowerModule : public FeatureModule { public: PowerModule(); static const char *type_str() { return "power"; } private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); }; class MelPowerModule : public FeatureModule { public: MelPowerModule(); static const char *type_str() { return "mel_power"; } private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); }; class DCTModule : public FeatureModule { public: DCTModule(); static const char *type_str() { return "dct"; } private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); private: int m_zeroth_comp; //!< If nonzero, output includes zeroth component }; class DeltaModule : public FeatureModule { public: DeltaModule(); static const char *type_str() { return "delta"; } private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); private: int m_delta_width; float m_delta_norm; }; class NormalizationModule : public FeatureModule { public: NormalizationModule(); static const char *type_str() { return "normalization"; } void set_normalization(const std::vector<float> &mean, const std::vector<float> &scale); private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void set_parameters(const ModuleConfig &config); virtual void get_parameters(ModuleConfig &config); virtual void generate(int frame); private: std::vector<float> m_mean; std::vector<float> m_scale; }; class LinTransformModule : public FeatureModule { public: LinTransformModule(); static const char *type_str() { return "lin_transform"; } const std::vector<float> *get_transformation_matrix(void) { return &m_transform; } const std::vector<float> *get_transformation_bias(void) { return &m_bias; } void set_transformation_matrix(std::vector<float> &t); void set_transformation_bias(std::vector<float> &b); virtual void set_parameters(const ModuleConfig &config); virtual void get_parameters(ModuleConfig &config); private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); void check_transform_parameters(void); private: std::vector<float> m_transform; std::vector<float> m_bias; std::vector<float> m_original_transform; std::vector<float> m_original_bias; bool m_matrix_defined, m_bias_defined; int m_src_dim; public: virtual bool is_defined() { return m_matrix_defined && m_bias_defined; } }; class MergerModule : public FeatureModule { public: MergerModule(); static const char *type_str() { return "merge"; } virtual void add_source(FeatureModule *source); private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); }; class MeanSubtractorModule : public FeatureModule { public: MeanSubtractorModule(); static const char *type_str() { return "mean_subtractor"; } private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void reset_module(); virtual void generate(int frame); private: std::vector<double> m_cur_mean; int m_cur_frame; int m_width; }; class ConcatModule : public FeatureModule { public: ConcatModule(); static const char *type_str() { return "concat"; } private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); private: int left, right; }; class VtlnModule : public FeatureModule { public: VtlnModule(); static const char *type_str() { return "vtln"; } void set_warp_factor(float factor); void set_slapt_warp(std::vector<float> &params); float get_warp_factor(void) { return m_warp_factor; } virtual void set_parameters(const ModuleConfig &config); virtual void get_parameters(ModuleConfig &config); private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); void create_pwlin_bins(void); void create_blin_bins(void); void create_slapt_bins(void); void create_sinc_coef_table(void); void create_all_pass_blin_transform(void); void create_all_pass_slapt_transform(void); void set_all_pass_transform(Matrix &trmat); private: int m_use_pwlin; float m_pwlin_turn_point; int m_use_slapt; int m_sinc_interpolation_rad; int m_all_pass; bool m_lanczos_window; std::vector<float> m_vtln_bins; std::vector< std::vector<float> > m_sinc_coef; std::vector<int> m_sinc_coef_start; float m_warp_factor; std::vector<float> m_slapt_params; }; class SRNormModule : public FeatureModule { public: SRNormModule(); static const char *type_str() { return "sr_norm"; } void set_speech_rate(float factor); float get_speech_rate(void) { return m_speech_rate; } virtual void set_parameters(const ModuleConfig &config); virtual void get_parameters(ModuleConfig &config); private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); private: int m_in_frames; int m_out_frames; int m_frame_dim; int m_lanczos_order; float m_speech_rate; std::vector< std::vector<float> > m_coef; std::vector<int> m_interpolation_start; }; class QuantEqModule : public FeatureModule { public: QuantEqModule(); static const char *type_str() { return "quanteq"; } void set_alpha(std::vector<float> &alpha); void set_gamma(std::vector<float> &gamma); void set_quant_max(std::vector<float> &quant_max); std::vector<float> get_quant_train(void) { return m_quant_train; } virtual void set_parameters(const ModuleConfig &config); virtual void get_parameters(ModuleConfig &config); private: virtual void get_module_config(ModuleConfig &config); virtual void set_module_config(const ModuleConfig &config); virtual void generate(int frame); private: std::vector<float> m_quant_train; std::vector<float> m_alpha; std::vector<float> m_gamma; std::vector<float> m_quant_max; }; } #endif /* FEATUREMODULES_HH */
28.584967
84
0.745627
lingsoft
01255311cfc3027c017846c9e92e7b40af6bc7e5
7,212
cpp
C++
Plugin_Kade/Kade_Thread.cpp
ChaseBro/MMDAgent
779cd3035954c27016333a2186896e1870e9ee54
[ "Libpng", "Zlib", "Unlicense" ]
9
2017-08-17T01:01:55.000Z
2022-02-02T09:50:09.000Z
Plugin_Kade/Kade_Thread.cpp
ChaseBro/MMDAgent
779cd3035954c27016333a2186896e1870e9ee54
[ "Libpng", "Zlib", "Unlicense" ]
null
null
null
Plugin_Kade/Kade_Thread.cpp
ChaseBro/MMDAgent
779cd3035954c27016333a2186896e1870e9ee54
[ "Libpng", "Zlib", "Unlicense" ]
4
2017-08-17T01:01:57.000Z
2021-06-28T08:30:17.000Z
/* ----------------------------------------------------------------- */ /* The Toolkit for Building Voice Interaction Systems */ /* "MMDAgent" developed by MMDAgent Project Team */ /* http://www.mmdagent.jp/ */ /* ----------------------------------------------------------------- */ /* */ /* Copyright (c) 2009-2011 Nagoya Institute of Technology */ /* Department of Computer Science */ /* */ /* 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 MMDAgent project team 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. */ /* ----------------------------------------------------------------- */ /* headers */ #include "MMDAgent.h" #include "Kade_Thread.h" #include <Python.h> /* File Globals */ PyObject *pModule; PyObject *pProcPlainText, *pProcParse; bool m_pause; /* mainThread: main thread */ static void mainThread(void *param) { Kade_Thread *kade_thread = (Kade_Thread *) param; kade_thread->run(); } /* Kade_Thread::initialize: initialize thread */ void Kade_Thread::initialize() { m_mmdagent = NULL; m_thread = -1; m_configFile = NULL; pModule = NULL; pProcPlainText = NULL; pProcParse = NULL; } /* Kade_Thread::clear: free thread */ void Kade_Thread::clear() { if(m_thread >= 0) { glfwWaitThread(m_thread, GLFW_WAIT); glfwDestroyThread(m_thread); glfwTerminate(); } if(m_configFile != NULL) free(m_configFile); if (pProcParse) Py_DECREF(pProcParse); if (pModule) Py_DECREF(pModule); Py_Finalize(); initialize(); } /* Kade_Thread::Kade_Thread: thread constructor */ Kade_Thread::Kade_Thread() { initialize(); } /* Kade_Thread::~Kade_Thread: thread destructor */ Kade_Thread::~Kade_Thread() { clear(); } /* Kade_Thread::load: load models and start thread */ void Kade_Thread::load(MMDAgent *mmdagent, const char *configFile) { PyObject *pName; char name[MMDAGENT_MAXBUFLEN]; Py_Initialize(); m_mmdagent = mmdagent; m_configFile = MMDAgent_strdup(configFile); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\"/home/robocep/MMDAgent/Release/AppData/Kade\")"); sprintf(name, "%s%c%s%c%s", mmdagent->getAppDirName(), MMDAGENT_DIRSEPARATOR, "Kade",MMDAGENT_DIRSEPARATOR, "kade"); pName = PyString_FromString("kade"); pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule == NULL) { printf("Error Loading python module: %s\n", PyString_AsString(pName)); return; } pProcParse = PyObject_GetAttrString(pModule, "procParse"); if (pProcParse == NULL) { Py_DECREF(pModule); printf("Error Loading procParse Function.\n"); return; } if(m_configFile == NULL) { Py_DECREF(pProcParse); Py_DECREF(pModule); clear(); printf("Error Loading Config File.\n"); return; } m_pause = false; /* create recognition thread glfwInit(); m_thread = glfwCreateThread(mainThread, this); if(m_thread < 0) { clear(); return; } */ } /* Kade_Thread::run: main loop */ void Kade_Thread::run() { } /* Kade_Thread::pause: pause recognition process */ void Kade_Thread::pause() { m_pause = true; } /* Kade_Thread::resume: resume recognition process */ void Kade_Thread::resume() { m_pause = false; } /* Kade_Thread::sendMessage: send message to MMDAgent */ void Kade_Thread::sendMessage(const char *str1, const char *str2) { m_mmdagent->sendEventMessage(str1, str2); } char* Kade_Thread::procParse(const char *plainText, const char *parse) { PyObject *pParse, *pAnswer, *pAnswerStr, *pArgs, *pPlain; char *answerStr; if (!pProcParse || !PyCallable_Check(pProcParse)) { printf("procParse does not exists or is not callable.\n"); if (PyErr_Occurred()) PyErr_Print(); return NULL; } pParse = PyString_FromString(parse); pPlain = PyString_FromString(plainText); if (pParse != NULL && pPlain != NULL) { pArgs = PyTuple_New(2); if (pArgs != NULL) { PyTuple_SetItem(pArgs, 0, pPlain); PyTuple_SetItem(pArgs, 1, pParse); pAnswer = PyObject_CallObject(pProcParse, pArgs); if (pAnswer != NULL) { pAnswerStr = PyObject_Str(pAnswer); Py_DECREF(pAnswer); Py_DECREF(pArgs); answerStr = PyString_AsString(pAnswerStr); Py_DECREF(pAnswerStr); printf("Answer: %s\n", answerStr); return answerStr; } Py_DECREF(pArgs); } else Py_DECREF(pParse); Py_DECREF(pPlain); } printf("Error\n"); if (PyErr_Occurred()) PyErr_Print(); return NULL; } char* Kade_Thread::procPlainText(char *text) { return NULL; }
31.631579
120
0.555047
ChaseBro
012aaddbb70b4812f6398f41c04ebaeef57ce201
5,777
cpp
C++
ConvertTrips/Table_Process.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
ConvertTrips/Table_Process.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
ConvertTrips/Table_Process.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Table_Process.cpp - Trip Table Processing //********************************************************* #include "ConvertTrips.hpp" //--------------------------------------------------------- // Table_Processing //--------------------------------------------------------- void ConvertTrips::Table_Processing (File_Group *group) { int num_share, tod, t, t1, t2, num_t, trp, o, d, period, current, first_t, last_t; int total, stat, errors, org, des, trips, num, num_shares, duration, even_bucket, even; bool share_flag, factor_flag, period_flag, scale_flag, return_flag; double trip, factor, added, deleted, bucket; Diurnal_Data *diurnal_ptr; Matrix_File *file; Factor_Data *factor_ptr; static char *error_msg = "%d Trip%sbetween TAZs %d and %d could not be allocated"; //---- read the trip table ---- total = errors = 0; added = deleted = 0.0; file = group->Trip_File (); return_flag = (group->Duration () > 0); even_bucket = 1; bucket = 0.45; factor_flag = (group->Trip_Factor () != NULL); period_flag = (group->Factor_Periods () > 0); scale_flag = (group->Scaling_Factor () != 1.0); num_shares = group->Num_Shares (); share_flag = (num_shares > 0); if (!share_flag) num_share = 1; duration = group->Duration (); first_t = t1 = 1; last_t = t2 = num_t = diurnal_data.Num_Records (); period = 0; Show_Message (0, "\tReading %s -- Record", file->File_Type ()); Set_Progress (500); while (file->Read ()) { Show_Progress (); org = file->Origin (); if (org == 0) continue; if (org < 1 || org > num_zone) { Warning ("Origin TAZ %d is Out of Range (1-%d)", org, num_zone); continue; } des = file->Destination (); if (des < 1 || des > num_zone) { Warning ("Destination TAZ %d is Out of Range (1-%d)", des, num_zone); continue; } //---- check for a time period ---- if (file->Period_Flag () && period_flag) { period = file->Period (); if (period > 0) { first_t = last_t = 0; for (t=1; t <= num_t; t++) { diurnal_ptr = diurnal_data [t]; tod = (diurnal_ptr->Start_Time () + diurnal_ptr->End_Time ()) / 2; if (group->Factor_Period (tod) == period) { if (first_t == 0) first_t = t; last_t = t; } } if (last_t == 0) { first_t = 1; last_t = num_t; period = 0; } } else { first_t = 1; last_t = num_t; period = 0; } } trips = file->Data (); if (trips < 0) { Warning ("Number of Trips is Out of Range (%d < 0)", trips); continue; } //---- apply the scaling factor ---- if (scale_flag) { trip = trips * group->Scaling_Factor () + bucket; trips = (int) trip; if (trips < 0) trips = 0; bucket = trip - trips; } if (trips == 0) continue; total += trips; //---- apply the selection script ---- if (share_flag) { num = group->Execute (); if (num < 1 || num > num_shares) { Error ("Diurnal Selection Value %d is Out of Range (1..%d)", num, num_shares); } } else { num = num_share; } //---- get the travel time ---- if (skim_flag) { skim_ptr = ttime_skim.Get (org, des); } //---- apply adjustment factors ---- if (factor_flag) { o = (equiv_flag) ? zone_equiv.Zone_Group (org) : org; d = (equiv_flag) ? zone_equiv.Zone_Group (des) : des; if (period_flag) { period = -1; t1 = t2 = 1; trip = 0.0; for (t=first_t; t <= last_t; t++) { diurnal_ptr = diurnal_data [t]; tod = (diurnal_ptr->Start_Time () + diurnal_ptr->End_Time ()) / 2; current = group->Factor_Period (tod); if (current != period) { if (period >= 0) { factor_ptr = factor_data.Get (o, d, period); if (factor_ptr == NULL) { factor_ptr = &default_factor; } factor = trip * factor_ptr->Factor (); if (factor > trip) { added += factor - trip; } else { deleted += trip - factor; } trp = factor_ptr->Bucket_Factor (trip); if (trp > 0 && return_flag) { even = (((trp + even_bucket) / 2) * 2); even_bucket += trp - even; trp = even; } if (trp > 0) { if ((stat = Set_Trips (group, org, des, trp, num, t1, t2, duration))) { errors += stat; Print (1, error_msg, stat, ((stat > 1) ? "s " : " "), org, des); } } } period = current; t1 = t; trip = 0.0; } trip += trips * diurnal_ptr->Share (num); t2 = t; } } else { if (period == 0) period = 1; t1 = first_t; t2 = last_t; trip = trips; } factor_ptr = factor_data.Get (o, d, period); if (factor_ptr == NULL) { factor_ptr = &default_factor; } factor = trip * factor_ptr->Factor (); if (factor > trip) { added += factor - trip; } else { deleted += trip - factor; } trp = factor_ptr->Bucket_Factor (trip); } else { t1 = first_t; t2 = last_t; trp = trips; } if (trp > 0 && return_flag) { even = (((trp + even_bucket) / 2) * 2); even_bucket += trp - even; trp = even; } //---- process the trips ---- if (trp > 0) { if ((stat = Set_Trips (group, org, des, trp, num, t1, t2, duration))) { errors += stat; Print (1, error_msg, stat, ((stat > 1) ? "s " : " "), org, des); } } } End_Progress (); file->Close (); Print (1, "%s has %d Records and %d Trips", file->File_Type (), Progress_Count (), total); tot_trips += total; if (errors > 0) { Warning ("A Total of %d Trip%scould not be allocated", errors, ((errors > 1) ? "s " : " ")); tot_errors += errors; } if (factor_flag) { Print (1, "Trip Adjustments: %.0lf trips added, %.0lf trips deleted", added, deleted); tot_add += added; tot_del += deleted; } }
24.070833
94
0.535053
kravitz
0130e07bf1f5706e74cab68b1c3d28619e46a356
4,250
cpp
C++
src/aimp_dotnet/SDK/MusicLibrary/InternalAimpDataFilterGroup.cpp
Smartoteka/aimp_dotnet
544502b8d080c9280ba11917ef0cc3e8dec44234
[ "Apache-2.0" ]
52
2015-04-14T14:39:30.000Z
2022-02-07T07:16:05.000Z
src/aimp_dotnet/SDK/MusicLibrary/InternalAimpDataFilterGroup.cpp
Smartoteka/aimp_dotnet
544502b8d080c9280ba11917ef0cc3e8dec44234
[ "Apache-2.0" ]
11
2015-04-02T10:45:55.000Z
2022-02-03T07:21:53.000Z
src/aimp_dotnet/SDK/MusicLibrary/InternalAimpDataFilterGroup.cpp
Smartoteka/aimp_dotnet
544502b8d080c9280ba11917ef0cc3e8dec44234
[ "Apache-2.0" ]
9
2015-04-05T18:25:57.000Z
2022-02-07T07:20:23.000Z
// ---------------------------------------------------- // AIMP DotNet SDK // Copyright (c) 2014 - 2020 Evgeniy Bogdan // https://github.com/martin211/aimp_dotnet // Mail: mail4evgeniy@gmail.com // ---------------------------------------------------- #include "Stdafx.h" #include "InternalAimpDataFilterGroup.h" using namespace AIMP::SDK; using namespace MusicLibrary; using namespace DataFilter; InternalAimpDataFilterGroup::InternalAimpDataFilterGroup(gcroot<IAimpDataFilterGroup^> managed) { _managed = managed; } HRESULT WINAPI InternalAimpDataFilterGroup::Add(IUnknown* Field, VARIANT* Value1, VARIANT* Value2, int Operation, IAIMPMLDataFieldFilter** Filter) { IAimpDataFieldFilter^ filter = nullptr; auto result = _managed->Add(AimpConverter::ToManagedString(static_cast<IAIMPString*>(Field)), AimpConverter::FromVaiant(Value1), AimpConverter::FromVaiant(Value2), FieldFilterOperationType(Operation)); if (result->ResultType == ActionResultType::OK) { // todo implement internal IAIMPMLDataFieldFilter } return HRESULT(result->ResultType); } HRESULT WINAPI InternalAimpDataFilterGroup::Add2(IUnknown* Field, VARIANT* Values, int Count, IAIMPMLDataFieldFilterByArray** Filter) { array<Object^>^ values = gcnew array<Object^>(Count); IAimpDataFieldFilterByArray^ filter; auto result = _managed->Add(AimpConverter::ToManagedString(static_cast<IAIMPString*>(Field)), values, Count); if (result->ResultType == ActionResultType::OK) { // todo implement IAIMPMLDataFieldFilterByArray } return HRESULT(result->ResultType); } HRESULT WINAPI InternalAimpDataFilterGroup::AddGroup(IAIMPMLDataFilterGroup** Group) { auto result = _managed->AddGroup(); if (result->ResultType == ActionResultType::OK) { *Group = new InternalAimpDataFilterGroup(result->Result); } return HRESULT(result->ResultType); } HRESULT WINAPI InternalAimpDataFilterGroup::Clear() { return HRESULT(_managed->Clear()->ResultType); } HRESULT WINAPI InternalAimpDataFilterGroup::Delete(int Index) { return HRESULT(_managed->Delete(Index)->ResultType); } HRESULT WINAPI InternalAimpDataFilterGroup::GetChild(int Index, REFIID IID, void** Obj) { ActionResultType res = ActionResultType::Fail; if (IID == IID_IAIMPMLDataFilterGroup) { const auto result = _managed->GetFilterGroup(Index); if (result->ResultType == ActionResultType::OK) { *Obj = new InternalAimpDataFilterGroup(result->Result); } res = result->ResultType; } if (IID == IID_IAIMPMLDataFieldFilter) { IAimpDataFieldFilter^ filter = nullptr; const auto result = _managed->GetFilterGroup(Index); if (result->ResultType == ActionResultType::OK) { // TODO complete it //*Obj = new Interna } res = result->ResultType; } return HRESULT(res); } int WINAPI InternalAimpDataFilterGroup::GetChildCount() { return _managed->GetChildCount(); } ULONG WINAPI InternalAimpDataFilterGroup::AddRef(void) { return Base::AddRef(); } ULONG WINAPI InternalAimpDataFilterGroup::Release(void) { return Base::Release(); } HRESULT WINAPI InternalAimpDataFilterGroup::QueryInterface(REFIID riid, LPVOID* ppvObject) { const HRESULT res = Base::QueryInterface(riid, ppvObject); if (riid == IID_IAIMPMLDataFilterGroup) { *ppvObject = this; AddRef(); return S_OK; } *ppvObject = nullptr; return res; } HRESULT WINAPI InternalAimpDataFilterGroup::GetValueAsInt32(int PropertyID, int* Value) { if (PropertyID == AIMPML_FILTERGROUP_OPERATION) *Value = static_cast<int>(_managed->Operation); return S_OK; } HRESULT WINAPI InternalAimpDataFilterGroup::SetValueAsInt32(int PropertyID, int Value) { if (PropertyID == AIMPML_FILTERGROUP_OPERATION) _managed->Operation = static_cast<FilterGroupOperationType>(Value); return S_OK; }
33.203125
114
0.652235
Smartoteka
01319c06316ba1f9a9dcbb46f8fab72f5bed7355
540
hpp
C++
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_physics_manual.hpp
weiDDD/particleSystem
32652b09da35e025956999227f08be83b5d79cb1
[ "Apache-2.0" ]
34
2017-08-16T13:58:24.000Z
2022-03-31T11:50:25.000Z
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_physics_manual.hpp
weiDDD/particleSystem
32652b09da35e025956999227f08be83b5d79cb1
[ "Apache-2.0" ]
null
null
null
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_physics_manual.hpp
weiDDD/particleSystem
32652b09da35e025956999227f08be83b5d79cb1
[ "Apache-2.0" ]
17
2017-08-18T07:42:44.000Z
2022-01-02T02:43:06.000Z
#ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_PHYSICS_MANUAL_H #define COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_PHYSICS_MANUAL_H #if CC_USE_PHYSICS #ifdef __cplusplus extern "C" { #endif #include "tolua++.h" #ifdef __cplusplus } #endif #include "cocos2d.h" #include "LuaScriptHandlerMgr.h" int register_all_cocos2dx_physics_manual(lua_State* tolua_S); #endif // CC_USE_PHYSICS #endif // #ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_PHYSICS_MANUAL_H
24.545455
95
0.824074
weiDDD
0136f6b477e8ff4a69284a42a0c410dca1029e15
549
cpp
C++
SourceCode/Chapter 15/Pr15-8.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
1
2019-04-09T18:29:38.000Z
2019-04-09T18:29:38.000Z
SourceCode/Chapter 15/Pr15-8.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
null
null
null
SourceCode/Chapter 15/Pr15-8.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
null
null
null
// This program demonstrates that when a derived class function // overrides a base class function, objects of the base class // still call the base class version of the function. #include <iostream> using namespace std; class BaseClass { public: void showMessage() { cout << "This is the Base class.\n"; } }; class DerivedClass : public BaseClass { public: void showMessage() { cout << "This is the Derived class.\n"; } }; int main() { BaseClass b; DerivedClass d; b.showMessage(); d.showMessage(); return 0; }
18.3
63
0.675774
aceiro
01376e57347f54f4d6ca3209bcd2429d52c0bcdc
17,513
hpp
C++
include/Avocado/backend/backend_descriptors.hpp
AvocadoML/Avocado
9595cc5994d916f0ecb24873a5afa98437977fb5
[ "Apache-2.0" ]
null
null
null
include/Avocado/backend/backend_descriptors.hpp
AvocadoML/Avocado
9595cc5994d916f0ecb24873a5afa98437977fb5
[ "Apache-2.0" ]
null
null
null
include/Avocado/backend/backend_descriptors.hpp
AvocadoML/Avocado
9595cc5994d916f0ecb24873a5afa98437977fb5
[ "Apache-2.0" ]
null
null
null
/* * backend_descriptors.hpp * * Created on: Dec 5, 2021 * Author: Maciej Kozarzewski */ #ifndef AVOCADO_BACKEND_BACKEND_DESCRIPTORS_HPP_ #define AVOCADO_BACKEND_BACKEND_DESCRIPTORS_HPP_ #include "backend_defs.h" #include <type_traits> #include <array> #include <vector> #include <stack> #include <algorithm> #include <complex> #include <memory> #include <cstring> #include <cassert> #include <mutex> #include <iostream> #if USE_CPU #elif USE_CUDA # include <cuda_runtime_api.h> # include <cuda_fp16.h> # include <cublas_v2.h> #elif USE_OPENCL # include <CL/cl.hpp> #else #endif namespace avocado { namespace backend { #if USE_CPU namespace cpu { #elif USE_CUDA namespace cuda { #elif USE_OPENCL namespace opencl { #else namespace reference { #endif int get_number_of_devices(); avDeviceType_t get_device_type(av_int64 descriptor) noexcept; int get_descriptor_type(av_int64 descriptor) noexcept; avDeviceIndex_t get_device_index(av_int64 descriptor) noexcept; int get_descriptor_index(av_int64 descriptor) noexcept; av_int64 get_current_device_type() noexcept; av_int64 get_current_device_index() noexcept; av_int64 create_descriptor(int index, av_int64 type); int dataTypeSize(avDataType_t dtype) noexcept; class MemoryDescriptor { #if USE_OPENCL int8_t *m_data = nullptr; #else int8_t *m_data = nullptr; #endif avDeviceIndex_t m_device_index = AVOCADO_INVALID_DEVICE_INDEX; av_int64 m_size = 0; av_int64 m_offset = 0; bool m_is_owning = false; public: static constexpr av_int64 descriptor_type = 1; MemoryDescriptor() = default; #if USE_CUDA or USE_OPENCL MemoryDescriptor(avDeviceIndex_t index, av_int64 sizeInBytes); #else MemoryDescriptor(av_int64 sizeInBytes); #endif MemoryDescriptor(const MemoryDescriptor &other, av_int64 size, av_int64 offset); MemoryDescriptor(const MemoryDescriptor &other) = delete; MemoryDescriptor(MemoryDescriptor &&other); MemoryDescriptor& operator=(const MemoryDescriptor &other) = delete; MemoryDescriptor& operator=(MemoryDescriptor &&other); ~MemoryDescriptor(); bool isNull() const noexcept; av_int64 size() const noexcept; avDeviceIndex_t device() const noexcept; static std::string className(); /** * \brief This method allocates new memory block and sets up the descriptor. */ #if USE_CUDA or USE_OPENCL void create(avDeviceIndex_t index, av_int64 sizeInBytes); #else void create(av_int64 sizeInBytes); #endif /** * \brief Creates a non-owning view of another memory block. */ void create(const MemoryDescriptor &other, av_int64 size, av_int64 offset); /** * \brief This method deallocates underlying memory and resets the descriptor. * Calling this method on an already destroyed descriptor has no effect. */ void destroy(); #if USE_OPENCL // cl::Buffer& data(void *ptr) noexcept; // const cl::Buffer& data(const void *ptr) const noexcept; template<typename T = void> T* data() noexcept { return reinterpret_cast<T*>(m_data + m_offset); } template<typename T = void> const T* data() const noexcept { return reinterpret_cast<const T*>(m_data + m_offset); } #else template<typename T = void> T* data() noexcept { return reinterpret_cast<T*>(m_data); } template<typename T = void> const T* data() const noexcept { return reinterpret_cast<const T*>(m_data); } #endif }; class ContextDescriptor { #if USE_CPU #elif USE_CUDA cudaStream_t m_stream = nullptr; cublasHandle_t m_handle = nullptr; #elif USE_OPENCL #else #endif avDeviceIndex_t m_device_index = AVOCADO_INVALID_DEVICE_INDEX; mutable MemoryDescriptor m_workspace; mutable av_int64 m_workspace_size = 0; public: static constexpr av_int64 descriptor_type = 2; ContextDescriptor() = default; ContextDescriptor(const ContextDescriptor &other) = delete; ContextDescriptor(ContextDescriptor &&other); ContextDescriptor& operator=(const ContextDescriptor &other) = delete; ContextDescriptor& operator=(ContextDescriptor &&other); ~ContextDescriptor(); static std::string className(); /** * \brief This method initializes context descriptor. */ #if USE_CPU void create(); #elif USE_CUDA void create(avDeviceIndex_t index, bool useDefaultStream = false); #elif USE_OPENCL void create(avDeviceIndex_t index, bool useDefaultCommandQueue); #else void create(); #endif /** * \brief This method destroys context and all its resources. * Calling this method on an already destroyed descriptor has no effect. */ void destroy(); MemoryDescriptor& getWorkspace() const; #if USE_CUDA void setDevice() const; avDeviceIndex_t getDevice() const noexcept; cudaStream_t getStream() const noexcept; cublasHandle_t getHandle() const noexcept; #endif }; class TensorDescriptor { std::array<int, AVOCADO_MAX_TENSOR_DIMENSIONS> m_dimensions; std::array<int, AVOCADO_MAX_TENSOR_DIMENSIONS> m_strides; int m_number_of_dimensions = 0; avDataType_t m_dtype = AVOCADO_DTYPE_UNKNOWN; public: static constexpr av_int64 descriptor_type = 3; TensorDescriptor() = default; TensorDescriptor(std::initializer_list<int> dimensions, avDataType_t dtype); static std::string className(); void create(); void destroy(); void set(avDataType_t dtype, int nbDims, const int dimensions[]); void get(avDataType_t *dtype, int *nbDims, int dimensions[]) const; int& operator[](int index); int operator[](int index) const; int dimension(int index) const; int nbDims() const noexcept; av_int64 sizeInBytes() const noexcept; int getIndex(std::initializer_list<int> indices) const noexcept; int firstDim() const noexcept; int lastDim() const noexcept; int volume() const noexcept; int volumeWithoutFirstDim() const noexcept; int volumeWithoutLastDim() const noexcept; avDataType_t dtype() const noexcept; bool equalShape(const TensorDescriptor &other) noexcept; std::string toString() const; private: void setup_stride(); }; class ConvolutionDescriptor { public: static constexpr av_int64 descriptor_type = 4; avConvolutionMode_t mode = AVOCADO_CONVOLUTION_MODE; int dimensions = 2; std::array<int, 3> padding; std::array<int, 3> stride; std::array<int, 3> dilation; std::array<uint8_t, 16> padding_value; int groups = 1; ConvolutionDescriptor() = default; void create(); void destroy(); static std::string className(); void set(avConvolutionMode_t mode, int nbDims, const int padding[], const int strides[], const int dilation[], int groups, const void *paddingValue); void get(avConvolutionMode_t *mode, int *nbDims, int padding[], int strides[], int dilation[], int *groups, void *paddingValue) const; template<typename T> T getPaddingValue() const noexcept { static_assert(sizeof(T) <= sizeof(padding_value), ""); T result; std::memcpy(&result, padding_value.data(), sizeof(T)); return result; } bool paddingWithZeros() const noexcept; TensorDescriptor getOutputShape(const TensorDescriptor &xDesc, const TensorDescriptor &wDesc) const; bool isStrided() const noexcept; bool isDilated() const noexcept; std::string toString() const; }; class PoolingDescriptor { public: static constexpr av_int64 descriptor_type = 5; avPoolingMode_t mode = AVOCADO_POOLING_MAX; std::array<int, 3> filter; std::array<int, 3> padding; std::array<int, 3> stride; PoolingDescriptor() = default; void create(); void destroy(); static std::string className(); }; class OptimizerDescriptor { public: static constexpr av_int64 descriptor_type = 6; avOptimizerType_t type = AVOCADO_OPTIMIZER_SGD; int64_t steps = 0; double learning_rate = 0.0; std::array<double, 4> coef; std::array<bool, 4> flags; OptimizerDescriptor() = default; void create(); void destroy(); static std::string className(); void set(avOptimizerType_t optimizerType, av_int64 steps, double learningRate, const double coefficients[], const bool flags[]); void get(avOptimizerType_t *optimizerType, av_int64 *steps, double *learningRate, double coefficients[], bool flags[]); void get_workspace_size(av_int64 *result, const TensorDescriptor &wDesc) const; }; class DropoutDescriptor { public: static constexpr av_int64 descriptor_type = 7; DropoutDescriptor() = default; void create(); void destroy(); static std::string className(); }; /* * DescriptorPool */ template<typename T> class DescriptorPool { T m_null_descriptor; std::vector<std::unique_ptr<T>> m_pool; std::vector<int> m_available_descriptors; std::mutex m_pool_mutex; public: DescriptorPool(size_t initialSize = 10, int numRestricted = 0) { m_pool.reserve(initialSize + numRestricted); m_available_descriptors.reserve(initialSize); for (int i = 0; i < numRestricted; i++) m_pool.push_back(nullptr); // reserve few descriptors values for default objects } DescriptorPool(const DescriptorPool<T> &other) = delete; DescriptorPool(DescriptorPool<T> &&other) : m_pool(std::move(other.m_pool)), m_available_descriptors(std::move(other.m_available_descriptors)) { } DescriptorPool& operator=(const DescriptorPool<T> &other) = delete; DescriptorPool& operator=(DescriptorPool<T> &&other) { std::swap(this->m_pool, other.m_pool); std::swap(this->m_available_descriptors, other.m_available_descriptors); return *this; } ~DescriptorPool() = default; /** * \brief Checks if the passed descriptor is valid. * The descriptor is valid if and only if its index is within the size of m_pool vector and is not in the list of available descriptors. */ bool isValid(int64_t desc) const noexcept { // std::cout << __FUNCTION__ << "() " << __LINE__ << " : index = " << desc << '\n'; // std::cout << __FUNCTION__ << "() " << __LINE__ << " : device type = " << get_current_device_type() << '\n'; if (get_current_device_type() != get_device_type(desc)) { // std::cout << __FUNCTION__ << "() " << __LINE__ << " : device type mismatch : " << get_current_device_type() << " vs " // << get_device_type(desc) << std::endl; return false; } if (T::descriptor_type != get_descriptor_type(desc)) { // std::cout << __FUNCTION__ << "() " << __LINE__ << " : type mismatch : " << T::descriptor_type << " vs " // << get_descriptor_type(desc) << std::endl; return false; } int index = get_descriptor_index(desc); // std::cout << __FUNCTION__ << "() " << __LINE__ << " object index = " << index << '\n'; if (index < 0 or index > static_cast<int>(m_pool.size())) { // std::cout << __FUNCTION__ << "() " << __LINE__ << " : out of bounds : " << index << " vs 0:" << m_pool.size() // << std::endl; return false; } bool asdf = std::find(m_available_descriptors.begin(), m_available_descriptors.end(), index) == m_available_descriptors.end(); if (asdf == false) { // std::cout << "not in available" << std::endl; } return asdf; } T& get(av_int64 desc) { // std::cout << __FUNCTION__ << "() " << __LINE__ << " : " << T::className() << " object index = " << get_descriptor_index(desc) // << '\n'; if (desc == AVOCADO_NULL_DESCRIPTOR) return m_null_descriptor; else { if (isValid(desc)) return *(m_pool.at(get_descriptor_index(desc))); else throw std::logic_error("invalid descriptor " + std::to_string(desc) + " for pool type '" + T::className() + "'"); } } template<typename ... Args> av_int64 create(Args &&... args) { std::lock_guard<std::mutex> lock(m_pool_mutex); int result; if (m_available_descriptors.size() > 0) { result = m_available_descriptors.back(); m_available_descriptors.pop_back(); } else { m_pool.push_back(std::make_unique<T>()); result = m_pool.size() - 1; } m_pool.at(result)->create(std::forward<Args>(args)...); av_int64 tmp = create_descriptor(result, T::descriptor_type); // std::cout << __FUNCTION__ << "() " << __LINE__ << " : " << T::className() << " = " << tmp << ", object index = " << result // << std::endl; return tmp; } void destroy(av_int64 desc) { std::lock_guard<std::mutex> lock(m_pool_mutex); // std::cout << __FUNCTION__ << "() " << __LINE__ << " : " << T::className() << " = " << desc << std::endl; if (not isValid(desc)) throw std::logic_error("invalid descriptor " + std::to_string(desc) + " of type '" + T::className() + "'"); int index = get_descriptor_index(desc); // std::cout << __FUNCTION__ << "() " << __LINE__ << " object index = " << index << std::endl; m_pool.at(index)->destroy(); m_available_descriptors.push_back(index); } }; template<class T> DescriptorPool<T>& getPool() { static DescriptorPool<T> result; return result; } template<> DescriptorPool<ContextDescriptor>& getPool(); template<typename T, typename ... Args> avStatus_t create(av_int64 *result, Args &&... args) { if (result == nullptr) return AVOCADO_STATUS_BAD_PARAM; try { result[0] = getPool<T>().create(std::forward<Args>(args)...); } catch (std::exception &e) { return AVOCADO_STATUS_INTERNAL_ERROR; } return AVOCADO_STATUS_SUCCESS; } template<typename T> avStatus_t destroy(av_int64 desc) { try { getPool<T>().destroy(desc); } catch (std::exception &e) { return AVOCADO_STATUS_FREE_FAILED; } return AVOCADO_STATUS_SUCCESS; } bool isDefault(avContextDescriptor_t desc); MemoryDescriptor& getMemory(avMemoryDescriptor_t desc); ContextDescriptor& getContext(avContextDescriptor_t desc); TensorDescriptor& getTensor(avTensorDescriptor_t desc); ConvolutionDescriptor& getConvolution(avConvolutionDescriptor_t desc); PoolingDescriptor& getPooling(avPoolingDescriptor_t desc); OptimizerDescriptor& getOptimizer(avOptimizerDescriptor_t desc); DropoutDescriptor& getDropout(avDropoutDescriptor_t desc); template<typename T = void> T* getPointer(avMemoryDescriptor_t desc) { try { return getMemory(desc).data<T>(); } catch (std::exception &e) { return nullptr; } } template<typename T> void setScalarValue(void *scalar, T x) noexcept { assert(scalar != nullptr); reinterpret_cast<T*>(scalar)[0] = x; } template<typename T> T getScalarValue(const void *scalar) noexcept { assert(scalar != nullptr); return reinterpret_cast<const T*>(scalar)[0]; } template<typename T = float> T getAlphaValue(const void *alpha) noexcept { if (alpha == nullptr) return static_cast<T>(1); else return reinterpret_cast<const T*>(alpha)[0]; } template<typename T = float> T getBetaValue(const void *beta) noexcept { if (beta == nullptr) return static_cast<T>(0); else return reinterpret_cast<const T*>(beta)[0]; } #if USE_CUDA template<> float2 getAlphaValue<float2>(const void *alpha) noexcept; template<> float2 getBetaValue<float2>(const void *beta) noexcept; template<> double2 getAlphaValue<double2>(const void *alpha) noexcept; template<> double2 getBetaValue<double2>(const void *beta) noexcept; #endif struct BroadcastedDimensions { int first; int last; }; /** * Only the right hand side (rhs) operand can be broadcasted into the left hand side (lhs). * The number of dimensions of the rhs tensor must be lower or equal to the lhs tensor. * All k dimensions of the rhs must match the last k dimensions of the lhs. * */ bool isBroadcastPossible(const TensorDescriptor &lhs, const TensorDescriptor &rhs) noexcept; int volume(const BroadcastedDimensions &dims) noexcept; BroadcastedDimensions getBroadcastDimensions(const TensorDescriptor &lhs, const TensorDescriptor &rhs) noexcept; bool is_transpose(avGemmOperation_t op) noexcept; bool is_logical(avBinaryOp_t op) noexcept; bool is_logical(avUnaryOp_t op) noexcept; bool is_logical(avReduceOp_t op) noexcept; template<typename T, typename U> bool same_device_type(T lhs, U rhs) { return get_device_type(lhs) == get_device_type(rhs); } template<typename T, typename U, typename ... ARGS> bool same_device_type(T lhs, U rhs, ARGS ... args) { if (get_device_type(lhs) == get_device_type(rhs)) return same_device_type(lhs, args...); else return false; } } /* namespace cpu/cuda/opencl/reference */ } /* namespace backend */ } /* namespace avocado */ #endif /* AVOCADO_BACKEND_BACKEND_DESCRIPTORS_HPP_ */
30.510453
141
0.661394
AvocadoML
01397d31fe431d899f2d2b93ba2b8846afc3137d
175
hpp
C++
FootCommander.hpp
amit1021/wargame-b
3b10fd404f7af5acfe1cfcc2c791f18afa36ab66
[ "MIT" ]
null
null
null
FootCommander.hpp
amit1021/wargame-b
3b10fd404f7af5acfe1cfcc2c791f18afa36ab66
[ "MIT" ]
null
null
null
FootCommander.hpp
amit1021/wargame-b
3b10fd404f7af5acfe1cfcc2c791f18afa36ab66
[ "MIT" ]
null
null
null
#include <iostream> #include "Soldier.hpp" class FootCommander : public Soldier { public: FootCommander(int player) : Soldier(150,20,player){} ~FootCommander(); };
15.909091
57
0.697143
amit1021
01413df5169b1339147ff85e257547c93c4f486f
1,975
cpp
C++
Demo/MdiDemo/MdiDemoView.cpp
yanlinlin82/libffc
6e067b0840f29958b97daea38bcd61099c2a473f
[ "MIT" ]
9
2017-10-31T10:15:31.000Z
2021-08-02T20:40:45.000Z
Demo/MdiDemo/MdiDemoView.cpp
yanlinlin82/libffc
6e067b0840f29958b97daea38bcd61099c2a473f
[ "MIT" ]
1
2019-07-21T12:13:37.000Z
2019-07-22T14:56:18.000Z
Demo/MdiDemo/MdiDemoView.cpp
yanlinlin82/libffc
6e067b0840f29958b97daea38bcd61099c2a473f
[ "MIT" ]
5
2016-07-31T09:08:18.000Z
2022-03-22T14:28:16.000Z
// MdiDemoView.cpp : implementation of the CMdiDemoView class // #include "stdafx.h" #include "MdiDemo.h" #include "MdiDemoDoc.h" #include "MdiDemoView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMdiDemoView IMPLEMENT_DYNCREATE(CMdiDemoView, CView) BEGIN_MESSAGE_MAP(CMdiDemoView, CView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) END_MESSAGE_MAP() // CMdiDemoView construction/destruction CMdiDemoView::CMdiDemoView() { // TODO: add construction code here } CMdiDemoView::~CMdiDemoView() { } BOOL CMdiDemoView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } // CMdiDemoView drawing void CMdiDemoView::OnDraw(CDC* pDC) { CMdiDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here pDC->TextOut(10, 10, _T("Hello, MDI!")); } // CMdiDemoView printing BOOL CMdiDemoView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CMdiDemoView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CMdiDemoView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } // CMdiDemoView diagnostics #ifdef _DEBUG void CMdiDemoView::AssertValid() const { CView::AssertValid(); } void CMdiDemoView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CMdiDemoDoc* CMdiDemoView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMdiDemoDoc))); return (CMdiDemoDoc*)m_pDocument; } #endif //_DEBUG // CMdiDemoView message handlers
19.554455
78
0.711899
yanlinlin82